Files
tiny-worlds/web/view-play.mjs
T
mute eebc1993dd the night rounds: the GM-input rework and the reasoning-effort knob -- the workbench renders no faces: the composer overlay and the transcript share colour-only tokens (.narration dim, .emph accent), source verbatim, asterisks tinted and kept on screen, so the input's caret can never drift (the old overlay's real bold/italic shifted advance widths -- keeping every character preserved count, not width; the scrollbar-gutter match killed the second drift source); the story view carries its OWN renderer (view-story storyBody/storySpans) -- the book keeps real bold/italic with the asterisks spent, narration italic via #story-scoped CSS, one rule for the tool and typography for the deliverable, deliberately separate; the composer is turn-shaped: rows=6 floor, field-sizing: content grows it with the turn (the thing the GM remembered Firefox doing -- it was never in use), max-height 50vh caps with internal scroll, the footer moved under the transcript's column only so the input's width is the pane's; the transcript's stick-to-bottom was DEAD CODE all along (#transcript has no height or overflow -- main is the scroller, the scrollTop assignments were no-ops in every browser): stickBottom scrolls main and re-asserts next frame (Firefox's scroll anchoring can reclaim a same-tick scroll around a content wipe), main carries overflow-anchor: none; the prose pane drops its machinery by ruling: the status/agenda chips and the retired delta tags strip (the panes carry the derived state), the reminder card never renders (it is the same every turn -- the raw tab keeps every copy), and the status/agenda note receipts (the old delta applies and the whole-list sets alike) skip the prose walk while the raw keeps them; the model dropdown collapsed to one plain list of ids sorted, ceilings riding along (the family grouping left the user guessing what a family name means, and the curator's tier labels only made sense inside their groups); and the reasoning-effort round: the battery probes the ladder (probeEfforts -- each of none/minimal/low/medium/high/xhigh/max measured for mean thinking, two samples, efforts recorded per model, effortDefault the argmax mean over minimal..max, 'none' never a candidate -- it is the off switch; null when the model shows no thinking), the knob is first-class and the GM's alone (GM, 2026-11-16: hidden from the model, not her call -- never in the mind verb, never in the <model> display block, and renderView's via-derived block filters it too, both surfaces; it rides the via record for the raw surfaces), its unset state SENDS the measured max-mean default (the one knob with an honestly nameable default -- the registry measured it; layers run override > deployment > registry per-model, explicit null clears to nothing), the first non-numeric knob (RoleParams carries the string, the /model route validates against the ladder, the knob row a select whose unset label names what rides and rebuilds on model-select change); the GLM ladder verified live by hand before the build (low suppresses to a third of baseline, max elevates about double, the whole ladder accepted on both families without 400s, and reasoning_effort 'none' doubles as a standardized thinking-off switch); the model dropdown, the composer, and the knob UX browser-proven with zero console errors (the pass caught the unreachable-helpers bug: code after a factory's return never runs, a hoisted function referencing the uninitialized const throws silently mid-fill and stale rows render); smoke ALL PASS with the effort battery (the canned mock ladders, the default riding a bare turn's via, the override riding the next turn, the bogus-level 400, the null clear, no reasoning_effort in any <model> block) + restart + reminder + repo checks green, typecheck green on both programs; ROADMAP gains the distant extension point (n-choice inference composed by a turn-editor agent) and the operator's queue moved there from QUESTIONS by the GM; HANDOFF prepared as the handoff (the typing-round bullet trimmed into the rounds list, the server line now truthful -- the debug server runs, the registry bullet carries the six-knob state and the pending-effort refine)
2026-11-16 23:52:58 +00:00

536 lines
21 KiB
JavaScript

// web/view-play.mjs -- the play surface: the transcript, her two
// blocks (the status pane and the agenda pane -- one widget, two
// instances), the GM notepad, housekeeping (close session, the
// dry-run replay), fork, and the input line.
/** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').TableResponse} TableResponse */
/** @typedef {import('./shapes.mjs').CarryoverResponse} CarryoverResponse */
/** @typedef {import('./shapes.mjs').NotesResponse} NotesResponse */
/** @typedef {import('./shapes.mjs').HousekeepingLogResponse} HousekeepingLogResponse */
/** @typedef {import('../server/shapes.mjs').JobState} JobState */
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
import { banner, hideBanner, renderMeter, setBusy, setSessionInfo } from './chrome.mjs';
import { navigate, render, runGone } from './router.mjs';
import { logEvent } from './log.mjs';
import { armedButton, modelList, modelsBox, paneEditor } from './widgets.mjs';
import { renderRaw, renderTranscript, viaLine } from './transcript.mjs';
// the table's two faces: the curated projection (the table) and the
// raw audit log. Sticky across the re-renders a turn triggers;
// switching runs resets to the table.
/** @type {?string} */ let rawRun = null;
let rawOpen = false;
// her two blocks, split along the seam: how she is (the status) vs
// what she means to do (the agenda). Both render compact, mirroring
// the wire formats the model cites. The edit button stages a block
// edit -- it rides the next GM turn as the override (the composition
// overwrites her newest blocks; the panes then show the composed
// truth the scan derives).
const statusPane = paneEditor({
section: 'status-pane',
body: 'status',
empty: 'a blank sheet',
placeholder: 'one description per line -- empty clears the status',
rows: 5,
format: (items) => items.join(', '), // compact, mirroring the <status> wire format
toText: (items) => items.join('\n'),
fromText: (text) => text
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+/, '').split(','))
.map((x) => x.trim()).filter(Boolean),
});
const agendaPane = paneEditor({
section: 'agenda-pane',
body: 'agenda',
empty: 'a clear head',
placeholder: 'one item per line, top first -- empty clears the agenda',
rows: 4,
// the pane renders bullets; the block grammar is the bullet list
// invariants teaches
format: (items) => items.map((d) => `- ${d}`).join('\n'),
toText: (items) => items.join('\n'),
fromText: (text) => text
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
.map((x) => x.trim()).filter(Boolean),
});
const models = modelsBox('models-pane', { title: 'models' });
export function leave() {
saveNotes();
stopPoll();
/** @type {HTMLDialogElement} */ ($('ask-modal')).close();
}
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters play with a run id
if (rawRun !== id) { rawRun = id; rawOpen = false; } // a new run starts at the table
statusPane.reset();
agendaPane.reset();
$('conflict').hidden = true;
await saveNotes(); // flush the pad for the previous run before switching
state.runId = id;
notesDirty = false;
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = '';
$('notes-state').textContent = '';
await refreshPlay(id, seq);
}
/** @param {string} id @param {number} seq @returns {Promise<void>} */
async function refreshPlay(id, seq) {
/** @type {RunDetail} */ let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
if (e.status === 404) return runGone(id, location.pathname);
// the table is the owner's: everyone else reads the story
if (e.status === 403) return navigate(`/runs/${id}/story`);
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
if (seq !== state.seq) return;
if (detail.draft) return navigate(`/runs/${id}/setup`); // the owner's draft opens the editor
setSessionInfo(detail.phase === 'live'
? `${detail.display} -- session ${detail.session}${detail.pendingAsk ? ' -- waiting for your answer' : ''}`
: `${detail.display} -- session ${detail.sessions} dormant`);
renderMeter(detail);
statusPane.set(detail.status);
agendaPane.set(detail.agenda);
$('conflict').hidden = true;
// the owner's table, live only for the panes: a block edit rides a
// turn, and turns need a live session -- dormancy edits the
// carryover (the review window's one editing surface). Anyone else
// was redirected to the story above.
statusPane.setEditable(detail.phase === 'live');
agendaPane.setEditable(detail.phase === 'live');
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = false;
$('table-tabs').hidden = true; // the tabs are the live session's
if (detail.phase === 'live') {
// the table has two faces: the curated projection (thinking never
// crosses the wire, variant turns carry only the picked one) and
// the raw audit log (everything as it rode the wire)
$('table-tabs').hidden = false;
$('tab-table').classList.toggle('active', !rawOpen);
$('tab-raw').classList.toggle('active', rawOpen);
if (rawOpen) {
/** @type {TableResponse} */ const session = await api(`/runs/${id}/session`);
if (seq !== state.seq) return;
renderRaw(session.entries);
} else {
/** @type {TableResponse} */ const session = await api(`/runs/${id}/table`);
if (seq !== state.seq) return;
renderTranscript(session.entries, { onConflict: showConflict, onRaw: showRawEntry });
}
} else if (detail.phase === 'dormant') {
// the review window: the carryover is the preview of the next
// contwin's opening, rendered exactly as the table will hold it
/** @type {?CarryoverResponse} */ const carry = await api(`/runs/${id}/carryover`).catch(() => null);
if (seq !== state.seq) return;
$('transcript').textContent = '';
if (carry && carry.entries.length) renderTranscript(carry.entries, {});
else $('transcript').appendChild(el('div', 'hint', 'nothing carries -- the next session opens on the bundle alone'));
$('transcript').prepend(dormantBar(detail, carry));
} else {
$('transcript').textContent = '';
}
// controls
$('session-open').hidden = detail.phase !== 'dormant';
if (!$('session-open').hidden) $('session-open').textContent = `start session ${detail.sessions}`;
$('hk-run').hidden = detail.phase !== 'live';
$('hk-rerun').hidden = !(detail.phase === 'dormant' && detail.sessions >= 2);
$('hk-replay').hidden = !((detail.phase === 'live') || (detail.phase === 'dormant' && detail.sessions >= 2));
$('hk-override-row').hidden = !(detail.phase === 'dormant' && detail.ready === false);
setInput(detail.phase === 'live' && !detail.pendingAsk);
/** @type {HTMLInputElement} */ ($('gm-input')).placeholder = 'GM line -- Ctrl+Space sends';
// models: the owner's per-run overrides
$('models-pane').hidden = false;
const mlist = await modelList();
if (seq !== state.seq) return;
models.fill(detail.run.models, detail.run.modelDefaults, detail.run.params, detail.run.paramDefaults, mlist);
// pending ask: the modal re-presents after a refresh -- the owner's
// to answer
if (detail.pendingAsk) {
$('ask-question').textContent = detail.pendingAsk;
/** @type {HTMLDialogElement} */ ($('ask-modal')).showModal();
/** @type {HTMLInputElement} */ ($('ask-answer')).focus();
} else {
/** @type {HTMLDialogElement} */ ($('ask-modal')).close();
}
// housekeeping state
/** @type {JobState} */ const hk = await api(`/runs/${id}/housekeeping`);
if (seq !== state.seq) return;
renderHk(hk);
// the GM's notepad -- skip the reload if a save failed (dirty wins)
await loadNotes(id, seq);
}
// the dormant bar: the review window's banner over the carryover
// preview, with the one button that leaves it
/** @param {RunDetail} detail @param {?CarryoverResponse} carry @returns {HTMLElement} */
function dormantBar(detail, carry) {
const bar = el('div', 'beat');
const ending = carry?.ends === 'gm'
? 'the carryover ends on your turn -- start sends it automatically as her cue'
: 'the table waits for your input once the session is live';
bar.appendChild(el('span', null, `session ${detail.sessions} is dormant -- the review window. ${ending}`));
const b = el('button', 'primary', `start session ${detail.sessions}`);
b.addEventListener('click', startRun);
bar.appendChild(b);
return bar;
}
/** @param {string} text */
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
c.hidden = false;
}
// one entry's wire form, inline on the table: the raw session is the
// audit surface, fetched on demand -- the same data the raw tab
// shows, one entry at a time (the walks are index-aligned: table
// entry i is session entry i). Thinking, the whole variants block,
// the rides as sent, tool arguments, the request record (resolved
// model + effective params) -- everything the table curates away, in
// place, no tab switch.
/** @param {number} idx @param {HTMLElement} slot @returns {Promise<void>} */
async function showRawEntry(idx, slot) {
let entry;
try {
/** @type {TableResponse} */ const session = await api(`/runs/${state.runId}/session`);
entry = session.entries[idx];
} catch (e) {
banner(e.message);
return;
}
if (!entry || entry.t !== 'msg') {
banner('the raw entry could not be found -- refresh and try again');
return;
}
const block = el('div', 'raw-block');
if (entry.m.role === 'assistant' && entry.m.reasoning_content) {
block.appendChild(el('div', 'who', 'thinking'));
block.appendChild(el('pre', 'raw-thinking', entry.m.reasoning_content));
}
if (entry.via) block.appendChild(el('div', 'machinery', viaLine(entry.via)));
block.appendChild(el('div', 'who', entry.m.role === 'user' ? 'gm -- as sent' : 'player -- as sent'));
block.appendChild(el('pre', null, String(entry.m.content ?? '')));
for (const c of entry.m.tool_calls ?? []) {
block.appendChild(el('div', 'machinery', `[tool call] ${c.function.name}`));
if (c.function.arguments) block.appendChild(el('pre', null, String(c.function.arguments)));
}
slot.appendChild(block);
}
// --- the GM's notepad: always on screen, auto-saved -------------------
//
// A debounced save (1s after the last keystroke, immediate on blur),
// flushed when leaving the play view or switching runs. gm.md never
// reaches any model -- this is the GM's own notes.
/** @type {?ReturnType<typeof setTimeout>} */ let notesTimer = null;
let notesDirty = false;
/** @param {string} id @param {number} seq @returns {Promise<void>} */
async function loadNotes(id, seq) {
/** @type {?NotesResponse} */ const notes = await api(`/runs/${id}/notes`).catch(() => null);
if (!notes || seq !== state.seq || notesDirty) return;
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = notes.content;
}
function notesInput() {
notesDirty = true;
$('notes-state').textContent = 'unsaved';
clearTimeout(notesTimer ?? undefined);
notesTimer = setTimeout(saveNotes, 1000);
}
/** @returns {Promise<void>} */
async function saveNotes() {
clearTimeout(notesTimer ?? undefined);
if (!notesDirty || !state.runId) return;
const content = /** @type {HTMLTextAreaElement} */ ($('gm-notes')).value;
try {
// keepalive: the flush must survive leaving the page entirely
await api(`/runs/${state.runId}/notes`, { method: 'PUT', body: { content }, keepalive: true });
notesDirty = false;
$('notes-state').textContent = 'saved';
} catch (e) {
$('notes-state').textContent = 'not saved';
banner(e.message);
}
}
// start: the dormant session goes live. If the carryover ends on a GM
// turn, the server sends it automatically as her cue.
/** @returns {Promise<void>} */
async function startRun() {
const override = /** @type {HTMLInputElement} */ ($('hk-override')).checked;
hideBanner();
setBusy(true, 'starting...');
/** @type {?string} */ let failed = null;
let failedCls = undefined;
try {
const r = await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } });
/** @type {HTMLInputElement} */ ($('hk-override')).checked = false;
if (r.autoSend) logEvent('nav', 'the carryover ended on a GM turn -- sent automatically as her cue');
} catch (e) {
if (e.status === 409 && e.detail?.hint) {
failed = `${e.message}\n${e.detail.hint}`;
failedCls = 'info';
} else if (e.status === 422 && e.detail?.errors) {
failed = `the carryover did not pass the start lint:\n${e.detail.errors.join('\n')}`;
} else {
failed = e.message;
}
}
setBusy(false);
render();
if (failed) banner(failed, failedCls); // render() clears the banner -- set it after
}
/** @param {string} stateText @param {?string} [cls] */
function setHk(stateText, cls) {
const h = $('hk-state');
h.textContent = stateText;
h.className = cls ?? '';
}
/** @param {JobState} hk */
function renderHk(hk) {
if (hk.state === 'running') {
setHk(hk.phase === 'rerun' ? 're-running housekeeping...' : 'stopping & housekeeping...', '');
startPoll();
return;
}
stopPoll();
if (hk.state === 'applied') {
setHk(`applied -- session ${hk.session} housekept\nsession ${hk.target} is ready to start`, 'applied');
loadLog(); // idempotent -- also covers a refresh while applied
} else if (hk.state === 'pending') {
setHk(`housekeeping of session ${hk.session} never finished -- re-run it, apply a manifest by hand, or start with the override`, 'rejected');
} else if (hk.state === 'rejected') {
setHk(`rejected -- held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
} else {
setHk('idle', '');
}
}
/** @param {boolean} ok */
function setInput(ok) {
/** @type {HTMLInputElement} */ ($('gm-input')).disabled = !ok;
/** @type {HTMLButtonElement} */ ($('gm-send')).disabled = !ok;
$('gm-stack').classList.toggle('off', !ok); // the overlay dims with the box
}
// --- actions -----------------------------------------------------------
/** @returns {Promise<void>} */
async function sendTurn() {
const line = /** @type {HTMLInputElement} */ ($('gm-input')).value.trim();
if (!line || !state.runId) return;
// staged block edits ride the turn (the override): only the kinds
// staged attach, whole-list
/** @type {{ line: string, status?: string[], agenda?: string[] }} */ const body = { line };
if (statusPane.staged) body.status = statusPane.staged;
if (agendaPane.staged) body.agenda = agendaPane.staged;
if ((body.status || body.agenda) && line.startsWith('(')) {
banner('a block edit cannot ride an OOC turn -- send it as a normal GM turn, or discard the edit');
return; // the line stays in the box, the staging stays staged
}
/** @type {HTMLInputElement} */ ($('gm-input')).value = '';
renderInputHl();
setInput(false);
setBusy(true);
let failed = null;
try {
await api(`/runs/${state.runId}/turn`, { method: 'POST', body });
statusPane.clearStaged(); // sent -- the panes re-render from the scan
agendaPane.clearStaged();
} catch (e) {
failed = e.message;
/** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line
renderInputHl();
}
setBusy(false);
render();
if (failed) banner(failed); // render() clears the banner -- set it after (the runGone lesson)
}
/** @returns {Promise<void>} */
async function sendAnswer() {
const answer = /** @type {HTMLInputElement} */ ($('ask-answer')).value.trim();
if (!answer || !state.runId) return;
/** @type {HTMLInputElement} */ ($('ask-answer')).value = '';
setBusy(true);
let failed = null;
try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
} catch (e) {
failed = e.message;
/** @type {HTMLInputElement} */ ($('ask-answer')).value = answer;
}
setBusy(false);
render();
if (failed) banner(failed); // render() clears the banner -- set it after
}
// fork: a copy of this run under you -- any run, anyone's, including
// yours. Lands you in the fork.
/** @returns {Promise<void>} */
async function forkRun() {
if (!state.runId) return;
setBusy(true, 'forking...');
try {
const r = await api(`/runs/${state.runId}/fork`, { method: 'POST', body: {} });
setBusy(false);
logEvent('nav', `forked ${state.runId} -> ${r.run}`);
navigate(`/runs/${r.run}`);
} catch (e) {
setBusy(false);
banner(e.message);
}
}
// dry-run: the housekeeper reads the session log, the manifest lands
// in the pane -- nothing applied, the session stays open
/** @returns {Promise<void>} */
async function replayHousekeeping() {
setBusy(true, 'the housekeeper reads...');
try {
const r = await api(`/runs/${state.runId}/housekeeping/replay`, { method: 'POST', body: {} });
$('hk-replay-content').textContent = r.parsed
? JSON.stringify(r.manifest, null, 2)
: `${r.reason}\n\nraw output: ${r.file}`;
/** @type {HTMLDetailsElement} */ ($('hk-replay-log')).hidden = false;
/** @type {HTMLDetailsElement} */ ($('hk-replay-log')).open = true;
} catch (e) {
banner(e.message);
}
setBusy(false);
}
// --- housekeeping poll + log -------------------------------------------
/** @type {?ReturnType<typeof setInterval>} */ let poll = null;
function startPoll() {
stopPoll();
poll = setInterval(async () => {
if (!state.runId || state.view !== 'play') return stopPoll();
const hk = await api(`/runs/${state.runId}/housekeeping`).catch(() => null);
if (hk && hk.state !== 'running') render();
}, 3000);
}
function stopPoll() {
if (poll) clearInterval(poll);
poll = null;
}
/** @returns {Promise<void>} */
async function loadLog() {
try {
/** @type {HousekeepingLogResponse} */ const log = await api(`/runs/${state.runId}/housekeeping/log`);
$('hk-log-content').textContent = log.content;
/** @type {HTMLDetailsElement} */ ($('hk-log')).hidden = false;
/** @type {HTMLDetailsElement} */ ($('hk-log')).open = true;
} catch {
$('hk-log').hidden = true;
}
}
// --- wiring ---
armedButton($('hk-run'), {
label: 'stop session',
confirm: 'sure? click again to stop, carry & housekeep',
fire: async () => {
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('stopping & housekeeping...', '');
startPoll();
} catch (e) {
banner(e.message);
}
render();
},
});
// the re-run: a fresh housekeeping pass over the finished predecessor,
// rebased -- the dormant session's rings are replaced, hand edits and all
armedButton($('hk-rerun'), {
label: 're-run housekeeping',
confirm: 'sure? click again -- the dormant session\'s rings are replaced, hand edits included',
fire: async () => {
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('re-running housekeeping...', '');
startPoll();
} catch (e) {
banner(e.message);
}
render();
},
});
$('gm-send').addEventListener('click', sendTurn);
// the GM input: Enter is a plain newline, Ctrl+Space sends (the
// button rides for mouse days)
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === ' ' && e.ctrlKey) { e.preventDefault(); sendTurn(); }
});
// the GM input's highlight overlay: the setup editor's stack pattern
// -- the pre behind a transparent-text textarea renders the tokens in
// place. Every character stays (the asterisks too) so the caret never
// desyncs from the visible glyphs, and the tokens are colour-only
// (GM, 2026-11-16): real faces shift advance widths and dragged the
// caret with them -- same glyphs, same widths, only paint differs
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderInputHl() {
const ta = /** @type {HTMLTextAreaElement} */ ($('gm-input'));
const hl = $('gm-hl');
const esc = ta.value.replace(/[&<>]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
// per-line tokens, matching the transcript's renderer: bold and
// italics never span lines
hl.innerHTML = esc
.replace(/(\*\*[^*\n]+\*\*|\*[^*\n]+\*)/g, (m) => (m.startsWith('**') ? `<span class="emph">${m}</span>` : `<span class="narration">${m}</span>`))
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>');
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
}
$('gm-input').addEventListener('input', renderInputHl);
$('gm-input').addEventListener('scroll', renderInputHl);
$('ask-send').addEventListener('click', sendAnswer);
$('ask-answer').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnswer(); }
});
$('session-open').addEventListener('click', startRun);
$('hk-replay').addEventListener('click', replayHousekeeping);
$('fork-btn').addEventListener('click', forkRun);
// the table's tabs: switching re-renders -- the same pass a turn
// takes, fetching the face that is open
$('tab-table').addEventListener('click', () => { if (rawOpen) { rawOpen = false; render(); } });
$('tab-raw').addEventListener('click', () => { if (!rawOpen) { rawOpen = true; render(); } });
$('story-link').addEventListener('click', () => { if (state.runId) navigate(`/runs/${state.runId}/story`); });
$('gm-notes').addEventListener('input', notesInput);
$('gm-notes').addEventListener('blur', saveNotes);
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce