e60fd63d2b
the provider round (2026-11-18, batteries-included): providers are first-class entities, the config is server-written state (state/config.json), and a fresh clone boots playable -- the opencode/free singleton auto-added and discovered on the empty list, playable with zero secrets. Every request resolves a full spec {provider, model, effort}: no unset effort, the per-run params layer retired, the mind verb the only sampling source. The registry is per-provider sections (state/models.json), refine caches adjudications under the double spec tuple (state/refine-cache.json), run picks are invalidatable (a removed provider or drifted model blocks the run with the note naming what died), and the housekeeper inherits the player spec's provider default (#16 closed). The no-legacy pass died the same day it shipped: bootImport deleted (server.json is bind + contwin), the registry's v1/v2 in-memory migrations deleted (models.json rewritten on disk into the per-provider shape), bare-string model picks deleted (Chloe's run.json migrated to spec objects, shape-preserving), the clerk's create model arg deleted, apiKeyEnv and the contextWindow alias gone. The live arc proven from a bare boot: invite minted, o/f auto-added, a custom provider with a bogus key (the recognizable 401), the auth fixed (13 models), the default pair selected, and a real glm-5.3 turn through the full path. Two live findings: opencode.ai serves 89 models keyless but 401s an empty Bearer header (the auth header rides only when a key exists), and the failure log line rides stderr.
the provider-flow round (2026-11-19, GM-designed): discovery IS the probe. The add takes only the endpoint -- {slug, baseUrl} or {builtin: true}, an apiKey in the body 400s (the auth route is the only key path) -- and a working keyless listing never sees a key field. A 401/403 stands the provider broken: the entity carries a probe record (outcome ok/auth/error, detail, at), the card opens the ask, and only the explicit acts move the record -- add, key, remove-key, discover; usage errors are transient and the op's to fix, nothing in the runtime flips provider state. The auth route is probe-then-save: the candidate key checks on reception, saves only on success -- a still-refused key never reaches the config, the previous state returns, the ask repeats. Every other discovery failure refuses the add outright with rollback: an endpoint that cannot answer is not a provider, nothing stands (the old code let it stand on any failure). The remove-key control (custom providers, armed) clears and re-probes: a provider gone public lands working keyless, a locked one re-opens the ask -- which is the key-replacement path. o/f never asks in any state: its auth failures are upstream breakage to show, not a prompt. The universal retry rule: NO automatic retries anywhere -- every inference call is user-initiated (the send, the housekeeping run, the refine) and every act has its manual retry; the curator's one auto-retry (the 2026-11-17 hiccup lesson) is deleted, the machine-label fallback the designed outcome. And failures never cache (GM: a failure is the absence of a measurement, not a measurement) -- the adjudication cache skips inference:false entries, the receipt line says "never cached, retried at every refine", and a transient battery error can never pin a false verdict; gev's 400s cost one cheap probe per refine and self-heal the day the backend learns tools. En-route fix the smoke earned: the create route validated body.spec AFTER the clerk built the run dir -- a refused spec left an orphan run (restart-check's exact count caught the sixth run); the spec validates first now, nothing lands on refusal.
the sheet's transport at the lint: the record is the only channel, the tag is view machinery composed by renderView, never authored by anyone -- the authored gate names the tag in any content (hers would never apply and primes the guarded emission; GM prose rides the view and story raw, the GM-side strips do not know it), names a sheet record on her turn, and checks object-ness on GM-turn records and boundary state notes both kinds; her emitted sheet in a carried tail stays legitimate history (the log keeps guard-conflicted emissions verbatim, and a stop can move one into the slidwin). The carryover editor teaches its own format now: a per-file hint between the editor and the save bar (one JSON object per line; status and agenda ride her turns; the sheet rides yours as the "sheet" field, never as a tag; the sigils and $VARS expand at start on the authored opening only).
the packages: template (the base for new packages -- the mood-indexed voice examples, the settings comment convention, non-playable as-is) and box (the sheet's first consumer: an incremental-game economy as ERP, GP and BP as two currencies with the room pushing her to fund her own punishments; the opening turn third-person per the typography ruling, ending on the display that needs a second read; the amnesiac rings empty by design; the erased name reading "(redacted)" after sigil expansion). The review found and fixed: both carryovers were pretty-printed JSON with duplicate keys -- unstartable under every per-line reader, flattened to true JSONL; the box's opening sheet rode her authored prose -- dead on every surface (the scan reads GM-turn records only, the strips eat it) and priming the exact emission the guard conflicts -- moved to the GM turn's sheet record, the override's shape; the gm.md "take of leave" typo fixed in all three packages.
the lint's rule 4 scoped to the substrate (GM, 2026-11-19): a banned word in a package's prose is fine -- the packages are the fiction and their words are the story's; README and the root prompts stay patrolled, and the box's "Or windows" is an architectural plural in a padded cell.
verified: typecheck green both programs; smoke ALL PASS (+27 the provider-flow battery: apiKey-on-add 400, the dead-endpoint refusal with config rollback, the auth-standing card with its probe record, probe-then-save both ways, the remove-key round trip, the o/f guards, the failures-never-cache proof over mock-fail -- verdict with the marker, absent from the cache file, re-probed fresh while the passing three serve from cache, not selectable, no orphan run; +8 the sheet-transport lint battery); restart + reminder checks green; a browser pass driving the whole add-flow machine on a mock+debug server (the hidden key field opening on the 401, the key landing through the auth route, the remove-key round trip re-opening the ask, the dead add refusing with the banner and no card, zero console errors beyond the expected 401/500 resource lines); check-repo clean with the box's windows. detention stays untracked WIP, untouched.
765 lines
31 KiB
JavaScript
765 lines
31 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, sheetEditor } from './widgets.mjs';
|
|
import { renderRaw, renderTranscript, stickBottom, 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;
|
|
|
|
// --- the rewind (GM, 2026-11-17) -------------------------------------------------
|
|
//
|
|
// The GM's take-back, staged client-side and committed by the send:
|
|
// clicking rewind on one of your turns fills the box with that turn's
|
|
// words (the expanded line as logged -- $vars are baked, the log is
|
|
// truth) and arms the send; sending replaces the turn and everything
|
|
// after it leaves the log (truncation -- fork first if you want the
|
|
// branch kept). Until the send the log is untouched: a reload or the
|
|
// cancel drops the gesture whole. The tinted composer is the mark --
|
|
// the note under it says what the colour means and names the cut.
|
|
|
|
/** @type {?{ idx: number, drop: number, label: string }} */ let pendingRewind = null;
|
|
let entryCount = 0; // the log length the last render saw -- the send's expect
|
|
|
|
/** @returns {void} */
|
|
function syncRewind() {
|
|
const blocked = pendingRewind !== null || /** @type {HTMLTextAreaElement} */ ($('gm-input')).value.trim().length > 0;
|
|
for (const b of /** @type {NodeListOf<HTMLButtonElement>} */ ($('transcript').querySelectorAll('button.rewind-toggle'))) {
|
|
b.disabled = blocked;
|
|
// the armed confirm text holds its place until it fires or disarms
|
|
b.textContent = b.dataset.armed === '1'
|
|
? 'sure? click again to rewind here'
|
|
: (blocked ? 'to rewind delete your current input' : 'rewind');
|
|
}
|
|
$('rewind-note').hidden = pendingRewind === null;
|
|
$('gm-stack').classList.toggle('rewind-pending', pendingRewind !== null);
|
|
if (pendingRewind) {
|
|
$('rewind-note-text').textContent =
|
|
`rewind armed: sending replaces this turn and drops the ${pendingRewind.drop} entries after it -- the tinted box marks the outgoing rewrite`;
|
|
}
|
|
}
|
|
|
|
/** @param {number} idx @param {string} text @param {HTMLButtonElement} btn */
|
|
function offerRewind(idx, text, btn) {
|
|
/** @type {?ReturnType<typeof setTimeout>} */ let timer = null;
|
|
btn.addEventListener('click', () => {
|
|
if (btn.disabled) return;
|
|
if (btn.dataset.armed !== '1') {
|
|
btn.dataset.armed = '1';
|
|
syncRewind();
|
|
clearTimeout(timer ?? undefined);
|
|
timer = setTimeout(() => { btn.dataset.armed = ''; if (btn.isConnected) syncRewind(); }, 5000);
|
|
return;
|
|
}
|
|
clearTimeout(timer ?? undefined);
|
|
btn.dataset.armed = '';
|
|
// the gesture: client-side only -- the send commits it. The label
|
|
// is the first words of the turn as the note's handle on it
|
|
pendingRewind = { idx, drop: entryCount - idx, label: text.split('\n')[0].slice(0, 60) };
|
|
/** @type {HTMLTextAreaElement} */ ($('gm-input')).value = text;
|
|
renderInputHl();
|
|
syncRewind();
|
|
/** @type {HTMLTextAreaElement} */ ($('gm-input')).focus();
|
|
});
|
|
}
|
|
|
|
/** @returns {void} */
|
|
function cancelRewind() {
|
|
pendingRewind = null;
|
|
/** @type {HTMLTextAreaElement} */ ($('gm-input')).value = '';
|
|
renderInputHl();
|
|
syncRewind();
|
|
}
|
|
|
|
// 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),
|
|
});
|
|
|
|
// the sheet: the GM's ledger, the same stage-and-ride pattern -- an
|
|
// edit rides the next GM turn as the record; the panes re-render from
|
|
// the scan
|
|
const theSheet = sheetEditor('sheet-pane', 'sheet');
|
|
|
|
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
|
|
pendingRewind = null; // the gesture belongs to the run it was staged on
|
|
entryCount = 0;
|
|
statusPane.reset();
|
|
agendaPane.reset();
|
|
theSheet.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);
|
|
theSheet.set(detail.sheet);
|
|
$('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');
|
|
theSheet.setEditable(detail.phase === 'live');
|
|
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = false;
|
|
|
|
// a pending gesture cannot outlive the live session (a stop or a
|
|
// failed send ends the table it was staged on)
|
|
if (detail.phase !== 'live') pendingRewind = null;
|
|
$('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;
|
|
entryCount = session.entries.length;
|
|
renderRaw(session.entries);
|
|
} else {
|
|
/** @type {TableResponse} */ const session = await api(`/runs/${id}/table`);
|
|
if (seq !== state.seq) return;
|
|
entryCount = session.entries.length;
|
|
// the rewind control rides GM turns while it may fire: a pending
|
|
// ask refuses sends anyway, so the buttons stay off until it
|
|
// resolves (the server would refuse -- the surface says so first)
|
|
renderTranscript(session.entries, {
|
|
onConflict: showConflict,
|
|
onRaw: showRawEntry,
|
|
...(detail.pendingAsk ? {} : { onRewind: offerRewind }),
|
|
});
|
|
}
|
|
syncRewind();
|
|
} 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));
|
|
syncRewind();
|
|
} else {
|
|
$('transcript').textContent = '';
|
|
syncRewind();
|
|
}
|
|
|
|
// 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.modelState, detail.run.providerDefaults, 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...');
|
|
meterStart(); // the start can auto-send her opening turn -- meter it too
|
|
/** @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;
|
|
}
|
|
}
|
|
meterStop();
|
|
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
|
|
}
|
|
|
|
// --- the turn meter ------------------------------------------------------
|
|
//
|
|
// Her turn can run for minutes on a max-effort model, and a held-open
|
|
// request gives no sign of life. The progress route carries the
|
|
// streaming callback's live record (the phase in flight, its running
|
|
// chars) plus the scale the bar guesstimates against (GM, 2026-11-17:
|
|
// a guesstimate, but an informed one): the only true budget is
|
|
// max_tokens when the knobs set one (reasoning counts inside it),
|
|
// else her own history -- the longest turn she has completed in this
|
|
// session, in the same chars the meter counts. Reaching 100% and
|
|
// continuing pushes the bar back: the scale grows by quarters until
|
|
// the count fits, so the bar lands near 80% and climbs again -- the
|
|
// same arithmetic every poll, nothing accumulates. No scale at all
|
|
// (a fresh run, her opening turn) falls back to a chunk-driven
|
|
// animation: a segment strip that steps ONLY when characters
|
|
// actually arrived -- never a free-running spinner, which would
|
|
// claim liveness the stream may not have.
|
|
|
|
let meterSeq = 0;
|
|
/** @type {?ReturnType<typeof setTimeout>} */ let meterTimer = null;
|
|
/** @type {?HTMLElement} */ let meterBox = null;
|
|
let meterSeg = 0; // the fallback strip's lit segment
|
|
let meterChars = 0; // the last seen count -- growth steps the strip
|
|
|
|
/** @returns {void} */
|
|
function meterStart() {
|
|
meterSeq++;
|
|
meterSeg = 0;
|
|
meterChars = 0;
|
|
meterSchedule(300);
|
|
}
|
|
|
|
/** @returns {void} */
|
|
function meterStop() {
|
|
meterSeq++;
|
|
if (meterTimer) clearTimeout(meterTimer ?? undefined);
|
|
meterTimer = null;
|
|
meterBox?.remove();
|
|
meterBox = null;
|
|
}
|
|
|
|
/** @param {number} delay @returns {void} */
|
|
function meterSchedule(delay) {
|
|
const seq = meterSeq;
|
|
if (meterTimer) clearTimeout(meterTimer ?? undefined);
|
|
meterTimer = setTimeout(() => { void meterTick(seq); }, delay);
|
|
}
|
|
|
|
/** @param {number} seq @returns {Promise<void>} */
|
|
async function meterTick(seq) {
|
|
if (seq !== meterSeq || !state.runId) return;
|
|
try {
|
|
const p = await api(`/runs/${state.runId}/progress`);
|
|
if (seq !== meterSeq) return;
|
|
meterDraw(p);
|
|
} catch { /* a missed poll keeps the last frame -- the next tick retries */ }
|
|
if (seq === meterSeq) meterSchedule(1000);
|
|
}
|
|
|
|
/** One progress read.
|
|
* @typedef {{ inFlight: boolean, phase?: 'thinking'|'prose', thinking?: number, prose?: number, started?: number, scale?: ?number, scaleKind?: ?'budget'|'history' }} ProgressRead */
|
|
|
|
/** @param {ProgressRead} p @returns {void} */
|
|
function meterDraw(p) {
|
|
const t = $('transcript');
|
|
// a tab switch or a render wiped the transcript -- rebuild in place
|
|
const fresh = !meterBox || !meterBox.isConnected;
|
|
if (fresh) {
|
|
meterBox = el('div', 'turn-live');
|
|
t.appendChild(meterBox);
|
|
}
|
|
const box = /** @type {HTMLElement} */ (meterBox); // the local carries the narrowing
|
|
// never yank the scroller: stick only if the GM was already at the
|
|
// bottom -- reading back while she writes stays put
|
|
const sc = /** @type {?HTMLElement} */ (t.closest('main'));
|
|
const atBottom = sc ? sc.scrollHeight - sc.scrollTop - sc.clientHeight < 40 : false;
|
|
box.textContent = '';
|
|
const total = (p.thinking ?? 0) + (p.prose ?? 0);
|
|
const elapsed = p.started ? Math.max(0, Math.round((Date.now() - p.started) / 1000)) : 0;
|
|
const line = el('div', 'turn-live-line');
|
|
const who = el('span', null, p.inFlight
|
|
? `her turn -- ${p.phase === 'prose' ? 'writing' : 'thinking'}`
|
|
: 'her turn...');
|
|
line.appendChild(who);
|
|
/** @type {string[]} */ const facts = [];
|
|
if (p.inFlight) facts.push(`${total} chars`, `${elapsed}s`);
|
|
if (p.inFlight && p.scale && p.scaleKind) {
|
|
// the push-back arithmetic: grow the scale by quarters until the
|
|
// count fits -- a 100% crossing lands the bar near 80% again
|
|
let s = p.scale;
|
|
while (s < total) s *= 1.25;
|
|
const pct = Math.round((100 * total) / s);
|
|
facts.push(`${pct}% of ${p.scaleKind === 'budget' ? 'the budget' : 'her longest'}`);
|
|
}
|
|
if (facts.length) line.appendChild(el('span', 'hint', ` \u00b7 ${facts.join(' \u00b7 ')}`));
|
|
box.appendChild(line);
|
|
if (p.inFlight && p.scale) {
|
|
let s = p.scale;
|
|
while (s < total) s *= 1.25;
|
|
const bar = el('div', 'turn-live-bar');
|
|
const fill = el('div', 'turn-live-fill');
|
|
fill.style.width = `${Math.min(100, Math.round((100 * total) / s))}%`;
|
|
bar.appendChild(fill);
|
|
box.appendChild(bar);
|
|
} else if (p.inFlight) {
|
|
// the fallback strip: twelve segments, one lit, stepping only on
|
|
// real arrivals -- a stall shows as a stall
|
|
if (total > meterChars) meterSeg = (meterSeg + 1) % 12;
|
|
const segs = el('div', 'turn-live-segs');
|
|
for (let i = 0; i < 12; i++) segs.appendChild(el('span', i === meterSeg ? 'turn-live-seg on' : 'turn-live-seg'));
|
|
box.appendChild(segs);
|
|
}
|
|
meterChars = total;
|
|
if (fresh || atBottom) stickBottom(t);
|
|
}
|
|
|
|
// --- 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. The staged sheet rides the same way --
|
|
// the GM's ledger record ({} is a live empty ledger, so the null
|
|
// check, not truthiness). The pending rewind names the GM turn this
|
|
// send replaces; expect states the log this was composed against --
|
|
// a stale tab refuses before anything rides
|
|
/** @type {{ line: string, status?: string[], agenda?: string[], sheet?: Record<string, unknown>, rewind?: number, expect?: number }} */ const body = { line, expect: entryCount };
|
|
if (pendingRewind) body.rewind = pendingRewind.idx;
|
|
if (statusPane.staged) body.status = statusPane.staged;
|
|
if (agendaPane.staged) body.agenda = agendaPane.staged;
|
|
if (theSheet.staged !== null) body.sheet = theSheet.staged;
|
|
if ((body.status || body.agenda || body.sheet !== undefined) && 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);
|
|
meterStart();
|
|
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();
|
|
theSheet.clearStaged();
|
|
pendingRewind = null; // committed -- the new log is the truth now
|
|
} catch (e) {
|
|
failed = e.message;
|
|
/** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line
|
|
renderInputHl();
|
|
// a 400 refused before anything touched the log (validation,
|
|
// expansion, a bad rewind target) -- the gesture stays armed for
|
|
// the re-send. Anything else may have moved the log: drop it and
|
|
// let the re-render show the truth
|
|
if (e.status !== 400) pendingRewind = null;
|
|
}
|
|
meterStop();
|
|
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);
|
|
meterStart();
|
|
let failed = null;
|
|
try {
|
|
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer, expect: entryCount } });
|
|
} catch (e) {
|
|
failed = e.message;
|
|
/** @type {HTMLInputElement} */ ($('ask-answer')).value = answer;
|
|
}
|
|
meterStop();
|
|
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(); }
|
|
});
|
|
// text in the box blocks the rewind gesture (GM, 2026-11-17): the
|
|
// button disables and renames rather than hiding, so the affordance
|
|
// says what unlocks it. Clearing the box re-enables it
|
|
$('gm-input').addEventListener('input', syncRewind);
|
|
$('rewind-cancel').addEventListener('click', cancelRewind);
|
|
|
|
// 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>} */ ({ '&': '&', '<': '<', '>': '>' })[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
|