jsdoc typing round, phases 3-4: the clerk (tool/memory.mjs) and the SPA (web/) typed under strict -- row shapes local to their owners (the clerk's five tables in its header; the SPA's response envelopes in the new web/shapes.mjs, the server's shared shapes imported at their use sites: User, LogEvent, JobState, HttpError); the db boundary cast at every .get()/.all(), fail as @returns {never} so guard-narrowing works; web via a second tsconfig (tsconfig.web.json: DOM libs in their own program, node types riding along because shapes.mjs's Provider typedef pulls provider.mjs in), npm run typecheck runs both; every non-annotation delta audited onto a small intended list (COUNT(*) Number() wraps, impossible-path guards, ?? ''/?? undefined null-absorbers, the RewordOp reason fix -- the validator demands it, the reminder-find naming its tag); smoke 110/110 + restart + reminder + repo checks + a zero-console-error browser pass green; the typing round is complete

This commit is contained in:
2026-11-15 19:57:07 +00:00
parent f81b188ce1
commit 8d4a6b91df
22 changed files with 567 additions and 227 deletions
+11 -2
View File
@@ -5,20 +5,27 @@
// embedded browser pane. Errors and notices land in the banner
// instead; destructive confirms are two-click armed (widgets.mjs).
/** @typedef {import('../server/shapes.mjs').User} User */
import { $ } from './dom.mjs';
// identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out
// -- the lifecycle story is a roadmap extension point
/** @param {?User} [me] */
export function setWho(me) {
$('who').textContent = me ? `${me.name}${me.superuser ? ' \u00b7 op' : ''}` : '';
$('who').title = me?.id ?? '';
}
/** @param {string} text */
export function setSessionInfo(text) {
$('session-info').textContent = text;
}
/** The run detail (GET /runs/:id) carries the meter's numbers; null
* is the router's "no run addressed" reset.
* @param {?{ context?: ?{ used?: ?number, pct?: ?number, contwin?: ?boolean } }} [detail] */
export function renderMeter(detail) {
const fill = $('context-fill');
const label = $('context-label');
@@ -34,18 +41,20 @@ export function renderMeter(detail) {
label.textContent = c.contwin ? `${pct}% -- close & housekeep past 85%` : '';
}
/** @param {boolean} on @param {string} [text] */
export function setBusy(on, text = 'her turn...') {
$('busy').hidden = !on; // model calls take their time -- say so
if (on) $('busy').textContent = text;
}
let bannerTimer = null;
/** @type {?ReturnType<typeof setTimeout>} */ let bannerTimer = null;
/** @param {string} text @param {string} [kind] */
export function banner(text, kind = 'error') {
const b = $('banner');
b.textContent = text;
b.className = kind;
b.hidden = false;
clearTimeout(bannerTimer);
clearTimeout(bannerTimer ?? undefined);
bannerTimer = setTimeout(() => { b.hidden = true; }, 10000);
}
+8 -1
View File
@@ -4,16 +4,23 @@
// rejected token ends the session -- drop it and show the claim view;
// every path leads there until a fresh one is claimed.
/** @typedef {import('../server/shapes.mjs').HttpError} HttpError */
/** One api() call: method + body + the keepalive flag. */
/** @typedef {{ method?: string, body?: unknown, keepalive?: boolean }} ApiOpts */
import { logEvent } from './log.mjs';
import { state } from './state.mjs';
import { render } from './router.mjs';
const TOKEN_KEY = 'rp-token';
/** @returns {string} */
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
/** @param {string} t */
export const setToken = (t) => { try { localStorage.setItem(TOKEN_KEY, t); } catch { /* storage blocked -- the session just won't persist */ } };
export const clearToken = () => { try { localStorage.removeItem(TOKEN_KEY); } catch { /* same */ } };
/** @param {string} path @param {ApiOpts} [opts] @returns {Promise<any>} */
export async function api(path, opts = {}) {
const started = performance.now();
const label = `${opts.method ?? 'GET'} ${path}`;
@@ -29,7 +36,7 @@ export async function api(path, opts = {}) {
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const e = new Error(data.error ?? `${res.status}`);
const e = /** @type {HttpError} */ (new Error(data.error ?? `${res.status}`));
e.detail = data.detail;
e.status = res.status;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms -- ${e.message}`);
+5 -2
View File
@@ -1,8 +1,11 @@
// web/dom.mjs -- the two DOM helpers everything else builds on.
export const $ = (id) => document.getElementById(id);
/** The id is static in index.html; a miss is a runtime crash by
* design (fail loud, never render a half-view). @param {string} id @returns {HTMLElement} */
export const $ = (id) => /** @type {HTMLElement} */ (document.getElementById(id));
// one element, class and text in the common shape
/** One element, class and text in the common shape.
* @param {string} tag @param {?string} [cls] @param {?string} [text] @returns {HTMLElement} */
export function el(tag, cls, text) {
const e = document.createElement(tag);
if (cls) e.className = cls;
+2 -1
View File
@@ -8,9 +8,10 @@
import { $ } from './dom.mjs';
const log = [];
/** @type {string[]} */ const log = [];
try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt -- start empty */ }
/** @param {string} kind @param {string} text */
export function logEvent(kind, text) {
log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`);
if (log.length > 300) log.splice(0, log.length - 300);
+13
View File
@@ -12,9 +12,16 @@ import { state } from './state.mjs';
import { banner, hideBanner, renderMeter, setWho, setSessionInfo } from './chrome.mjs';
import { logEvent } from './log.mjs';
/** One registered view: its pane element id, its enter (arg = the
* path-captured run id), and its optional leave. */
/** @typedef {{ el: string, enter: (arg: ?string, seq: number) => void|Promise<void>, leave?: () => void }} ViewDef */
/** @type {Record<string, ViewDef>} */
const views = {};
/** @param {Record<string, ViewDef>} map */
export function registerViews(map) { Object.assign(views, map); }
/** @param {string} p */
export function navigate(p) {
history.pushState({}, '', p);
render();
@@ -22,11 +29,14 @@ export function navigate(p) {
window.addEventListener('popstate', () => render());
/** @returns {Promise<void>} */
export async function render() {
const seq = ++state.seq;
hideBanner();
const p = location.pathname;
/** @type {?string} */
let name = null;
/** @type {?string} */
let arg = null;
let m;
if (p === '/') name = 'home';
@@ -35,10 +45,12 @@ export async function render() {
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/story$/))) { name = 'story'; arg = m[1]; }
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; }
else return navigate('/');
if (!name) return; // unreachable: the routing always names a view or navigates home
if (!state.me) name = 'claim'; // signed out: every path leads to the claim
await show(name, arg, seq);
}
/** @param {string} name @param {?string} arg @param {number} seq @returns {Promise<void>} */
async function show(name, arg, seq) {
const prev = state.view;
if (prev && prev !== name && views[prev].leave) views[prev].leave();
@@ -53,6 +65,7 @@ async function show(name, arg, seq) {
// a run that vanished under us (deleted, 404): leave loudly for home.
// render() clears the banner first -- set it after the navigate.
/** @param {string} id @param {string} from */
export function runGone(id, from) {
navigate('/');
banner(`run ${id} is gone -- deleted?`);
+43
View File
@@ -0,0 +1,43 @@
// web/shapes.mjs -- the SPA's wire shapes: the REST responses the
// views consume. No runtime code: like server/shapes.mjs, this module
// exists so the tsc checker (JSDoc mode, no emit) and the humans
// reading the code agree on the load-bearing shapes. The server's own
// shared shapes (User, LogEvent, JobState, RunMeta) are imported from
// ../server/shapes.mjs at their use sites -- the API response
// envelopes live here because main.mjs's handlers build them as
// untyped literals; the smoke owns their behavioral truth.
export {};
/** One run card as GET /runs serves it (the clerk's listing,
* enriched by the server with the live-session state). fill is
* present exactly when the run is initialized. */
/** @typedef {{ id: string, package: string, models: ?{ player?: ?string, housekeeper?: ?string }, owner: ?string, ownerName: ?string, created: ?string, forked: ?number, pc: ?string, display: string, sessions: number, phase: ?string, ready: ?boolean, initialized: boolean, fill?: { a: number, b: number, cold: number }, open: boolean, session: ?number, pendingAsk: ?string }} RunCard */
/** GET /runs/:id -- the run detail: identity, the phase bookkeeping,
* her two blocks, the fill, the context meter's numbers. */
/** @typedef {{ run: { id: string, package: ?string, created: ?string, forked: ?number, owner: ?string, ownerName: ?string, models: { player?: ?string, housekeeper?: ?string }, modelDefaults: { player?: ?string, housekeeper?: ?string } }, display: string, open: boolean, phase: ?string, session: ?number, sessions: number, draft: boolean, ready: ?boolean, status: string[], agenda: string[], records: number, fill: Record<string, number>, events: number, pendingAsk: ?string, usage: ?{ promptTokens: number, completionTokens: number }, context: ?{ used: number, contwin: ?boolean, pct: ?number } }} RunDetail */
/** GET /runs/:id/table -- the live session's projection (thinking
* never crosses the wire, variant turns carry only the picked one). */
/** @typedef {{ run: string, session: number, entries: import('../server/shapes.mjs').LogEvent[], pendingAsk: ?string }} TableResponse */
/** GET /runs/:id/carryover -- the dormant session's opening material,
* projected like the table; ends decides the opening flow. */
/** @typedef {{ run: string, session: number, ready: boolean, entries: import('../server/shapes.mjs').LogEvent[], ends: ?('gm'|'player') }} CarryoverResponse */
/** GET /runs/:id/story -- the whole deliverable, read-only: every
* non-dropped literature turn, across all sessions in order. */
/** @typedef {{ run: string, sessions: { session: number, turns: { who: string, text: string }[] }[] }} StoryResponse */
/** GET /api/runs/:id/files -- the editor surface: a fixed whitelist,
* each file with its phase-truth mode. */
/** @typedef {{ session: number, phase: ?string, files: Record<string, { mode: string, exists: boolean, content?: string }> }} FilesResponse */
/** GET /api/prompts -- the repo-fed prompts, read-only context. */
/** @typedef {{ system: ?string, invariants: ?string, reminder: ?string }} PromptsResponse */
/** GET /api/runs/:id/notes -- the GM's notepad. */
/** @typedef {{ content: string }} NotesResponse */
/** GET /api/runs/:id/housekeeping/log -- the latest apply log. */
/** @typedef {{ content: string }} HousekeepingLogResponse */
+3
View File
@@ -6,6 +6,9 @@
// play both write here; saves address it). Everything else is
// module-local to the view or widget that owns it.
/** @typedef {import('../server/shapes.mjs').User} User */
/** @type {{ view: ?string, seq: number, me: ?User, runId: ?string }} */
export const state = {
view: null, // the active view name ('claim' | 'home' | ...)
seq: 0,
+13 -2
View File
@@ -8,9 +8,15 @@
// delta tags on player turns are machinery, not prose -- they render
// as chips and pane state, mirroring the live-context policy.
/** @typedef {import('../server/shapes.mjs').LogEvent} LogEvent */
/** @typedef {import('../server/shapes.mjs').BundleEvent} BundleEvent */
/** @typedef {import('../server/shapes.mjs').MsgEvent} MsgEvent */
/** @typedef {import('../server/shapes.mjs').NoteEvent} NoteEvent */
import { $, el } from './dom.mjs';
// splits text into spans: *italics* = narration, **bold** = emphasis
/** @param {HTMLElement} target @param {string} text */
function renderSpans(target, text) {
const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g);
for (const p of parts) {
@@ -34,6 +40,7 @@ function renderSpans(target, text) {
// the riding blocks (status/conflict/agenda) out of GM prose; the
// delta tags on player turns always render as chips. Exported for
// the story view, which renders the same registers.
/** @param {HTMLElement} target @param {?string} text @param {{ extract?: boolean }} opts @returns {{ status: ?string, conflict: ?string, agenda: ?string }} */
export function renderContent(target, text, { extract }) {
let body = String(text ?? '');
let status = null;
@@ -128,10 +135,11 @@ export function renderContent(target, text, { extract }) {
// turn -- the play view owns where it lands (the status pane). The
// opening event (her opening status) renders as machinery, mirroring
// the wire policy: it is set once, never re-sent.
/** @param {LogEvent[]} entries @param {{ onConflict?: (text: string) => void }} [opts] */
export function renderTranscript(entries, { onConflict } = {}) {
const t = $('transcript');
t.textContent = '';
const bundleParts = [];
/** @type {BundleEvent[]} */ const bundleParts = [];
const flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
@@ -158,7 +166,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
// the turn reminder: the transcript mirrors the live-context
// policy -- one collapsed card for the newest copy, superseded
// ones elide (the log keeps every as-sent chunk)
const newest = [...entries].reverse().find((x) => x.reminder);
const newest = [...entries].reverse().find((x) => x.t === 'msg' && x.reminder);
if (e === newest) {
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder -- rides every GM turn'));
@@ -190,6 +198,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
flushBundle();
t.scrollTop = t.scrollHeight;
/** @param {?string} content @param {string} who */
function gmTurn(content, who) {
const d = el('div', 'turn gm');
d.appendChild(el('div', 'who', who));
@@ -199,6 +208,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
if (conflict) onConflict?.(conflict);
t.appendChild(d);
}
/** @param {MsgEvent} e */
function playerTurn(e) {
const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player'));
@@ -210,6 +220,7 @@ export function renderTranscript(entries, { onConflict } = {}) {
}
t.appendChild(d);
}
/** @param {NoteEvent} e */
function renderNote(e) {
let text = null;
if (e.kind === 'session') text = `session ${e.n} opened`;
+5 -4
View File
@@ -9,22 +9,23 @@ import { banner } from './chrome.mjs';
import { logEvent } from './log.mjs';
import { navigate } from './router.mjs';
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
$('claim-code').value = '';
$('claim-name').value = '';
/** @type {HTMLInputElement} */ ($('claim-code')).value = '';
/** @type {HTMLInputElement} */ ($('claim-name')).value = '';
let fresh = false;
try { fresh = (await api('/session')).fresh; } catch { /* public: works signed out; a dead server shows the plain hint */ }
if (seq !== state.seq) return;
$('claim-hint').textContent = fresh
? 'this deployment has no users yet -- the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator';
$('claim-code').focus();
/** @type {HTMLInputElement} */ ($('claim-code')).focus();
}
$('claim-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const r = await api('/claim', { method: 'POST', body: { code: $('claim-code').value.trim(), name: $('claim-name').value.trim() } });
const r = await api('/claim', { method: 'POST', body: { code: /** @type {HTMLInputElement} */ ($('claim-code')).value.trim(), name: /** @type {HTMLInputElement} */ ($('claim-name')).value.trim() } });
setToken(r.token);
state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
+11 -2
View File
@@ -8,8 +8,11 @@ import { banner } from './chrome.mjs';
import { navigate, render } from './router.mjs';
import { armedButton } from './widgets.mjs';
/** @typedef {import('./shapes.mjs').RunCard} RunCard */
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
const runs = await api('/runs');
/** @type {RunCard[]} */ const runs = await api('/runs');
if (seq !== state.seq) return;
const list = $('run-list');
list.textContent = '';
@@ -17,7 +20,7 @@ export async function enter(arg, seq) {
list.appendChild(el('div', 'hint', 'no runs yet -- start one from a package'));
}
for (const r of runs) {
const mine = state.me && r.owner === state.me.id;
const mine = !!(state.me && r.owner === state.me.id);
const card = el('button', 'card run-card');
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta -- chrome, never model-facing
@@ -31,15 +34,18 @@ export async function enter(arg, seq) {
await renderAdmin(seq);
}
/** @param {RunCard} r @param {boolean} mine @returns {string} */
const ownershipTag = (r, mine) =>
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
/** @param {number} t @returns {string} */
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
/** @param {RunCard} r @returns {string} */
function runStateText(r) {
if (r.phase === 'live') return `session open${r.pendingAsk ? ' -- waiting for your answer' : ''}`;
if (r.phase === 'dormant') {
@@ -48,6 +54,7 @@ function runStateText(r) {
}
return 'no sessions';
}
/** @param {RunCard} r @returns {string} */
function runStateClass(r) {
if (r.pendingAsk) return 'attention';
if (r.phase === 'live') return 'ok';
@@ -56,10 +63,12 @@ function runStateClass(r) {
return '';
}
/** @param {number} seq @returns {Promise<void>} */
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false;
/** @type {[{ invites: { id: number, kind: string, created_at: string, state: string }[] }, { users: import('../server/shapes.mjs').User[] }]} */
const [inv, us] = await Promise.all([api('/invites'), api('/users')]);
if (seq !== state.seq) return;
const invList = $('invite-list');
+11 -8
View File
@@ -9,8 +9,9 @@ import { state } from './state.mjs';
import { banner } from './chrome.mjs';
import { navigate } from './router.mjs';
let pkg = null; // the picked package -- the view owns it
/** @type {?{ display: string, name: string }} */ let pkg = null; // the picked package -- the view owns it
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
$('package-pick').hidden = false;
$('create-form').hidden = true;
@@ -29,25 +30,27 @@ export async function enter(arg, seq) {
}
}
/** @param {{ display: string, name: string }} p */
async function pickPackage(p) {
pkg = p;
$('package-pick').hidden = true;
$('create-form').hidden = false;
$('create-title').textContent = `start -- ${p.display}`;
$('create-name').value = p.display;
$('create-pc').value = '';
$('create-pc').placeholder = 'rolling a name...';
$('create-pc').focus();
/** @type {HTMLInputElement} */ ($('create-name')).value = p.display;
const pcInp = /** @type {HTMLInputElement} */ ($('create-pc'));
pcInp.value = '';
pcInp.placeholder = 'rolling a name...';
pcInp.focus();
const roll = await api('/names').catch(() => null);
if (state.view !== 'new' || $('create-form').hidden) return;
if ($('create-pc').value === '' && roll?.name) $('create-pc').value = roll.name;
if (pcInp.value === '' && roll?.name) pcInp.value = roll.name;
}
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => {
e.preventDefault();
const name = $('create-name').value.trim();
const pc = $('create-pc').value.trim();
const name = /** @type {HTMLInputElement} */ ($('create-name')).value.trim();
const pc = /** @type {HTMLInputElement} */ ($('create-pc')).value.trim();
if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name');
try {
+57 -34
View File
@@ -3,6 +3,13 @@
// 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';
@@ -49,23 +56,26 @@ const models = modelsBox('models-pane', { title: 'models' });
export function leave() {
saveNotes();
stopPoll();
$('ask-modal').close();
/** @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
statusPane.reset();
agendaPane.reset();
$('conflict').hidden = true;
await saveNotes(); // flush the pad for the previous run before switching
state.runId = id;
notesDirty = false;
$('gm-notes').value = '';
/** @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) {
let detail;
/** @type {RunDetail} */ let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
@@ -73,7 +83,7 @@ async function refreshPlay(id, seq) {
return banner(`could not reach the server: ${e.message}`); // stay put -- transient
}
if (seq !== state.seq) return;
const mine = state.me && detail.run.owner === state.me.id;
const mine = !!(state.me && detail.run.owner === state.me.id);
if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence
@@ -96,19 +106,19 @@ async function refreshPlay(id, seq) {
// way in. Ownerless runs are spectators for everyone alike.
statusPane.setEditable(mine);
agendaPane.setEditable(mine);
$('gm-notes').readOnly = !mine;
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).readOnly = !mine;
if (detail.phase === 'live') {
// the table: the live session's projection -- thinking never
// crosses the wire, variant turns carry only the picked one (the
// raw /session is the audit surface, one fetch away)
const session = await api(`/runs/${id}/table`);
/** @type {TableResponse} */ const session = await api(`/runs/${id}/table`);
if (seq !== state.seq) return;
renderTranscript(session.entries, { onConflict: showConflict });
} 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
const carry = await api(`/runs/${id}/carryover`).catch(() => null);
/** @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, {});
@@ -126,7 +136,7 @@ async function refreshPlay(id, seq) {
$('hk-replay').hidden = !((detail.phase === 'live') || (detail.phase === 'dormant' && detail.sessions >= 2)) || !mine;
$('hk-override-row').hidden = !(detail.phase === 'dormant' && detail.ready === false) || !mine;
setInput(detail.phase === 'live' && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine
/** @type {HTMLInputElement} */ ($('gm-input')).placeholder = mine
? 'GM line -- Enter sends, Shift+Enter newlines'
: 'spectating -- fork this run to continue it as yours';
@@ -142,14 +152,14 @@ async function refreshPlay(id, seq) {
// to answer; a spectator follows the thread in the transcript
if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal();
$('ask-answer').focus();
/** @type {HTMLDialogElement} */ ($('ask-modal')).showModal();
/** @type {HTMLInputElement} */ ($('ask-answer')).focus();
} else {
$('ask-modal').close();
/** @type {HTMLDialogElement} */ ($('ask-modal')).close();
}
// housekeeping state
const hk = await api(`/runs/${id}/housekeeping`);
/** @type {JobState} */ const hk = await api(`/runs/${id}/housekeeping`);
if (seq !== state.seq) return;
renderHk(hk);
@@ -159,6 +169,7 @@ async function refreshPlay(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'
@@ -171,6 +182,7 @@ function dormantBar(detail, carry) {
return bar;
}
/** @param {string} text */
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
@@ -183,26 +195,28 @@ function showConflict(text) {
// flushed when leaving the play view or switching runs. gm.md never
// reaches any model -- this is the GM's own notes.
let notesTimer = null;
/** @type {?ReturnType<typeof setTimeout>} */ let notesTimer = null;
let notesDirty = false;
/** @param {string} id @param {number} seq @returns {Promise<void>} */
async function loadNotes(id, seq) {
const notes = await api(`/runs/${id}/notes`).catch(() => null);
/** @type {?NotesResponse} */ const notes = await api(`/runs/${id}/notes`).catch(() => null);
if (!notes || seq !== state.seq || notesDirty) return;
$('gm-notes').value = notes.content;
/** @type {HTMLTextAreaElement} */ ($('gm-notes')).value = notes.content;
}
function notesInput() {
notesDirty = true;
$('notes-state').textContent = 'unsaved';
clearTimeout(notesTimer);
clearTimeout(notesTimer ?? undefined);
notesTimer = setTimeout(saveNotes, 1000);
}
/** @returns {Promise<void>} */
async function saveNotes() {
clearTimeout(notesTimer);
clearTimeout(notesTimer ?? undefined);
if (!notesDirty || !state.runId) return;
const content = $('gm-notes').value;
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 });
@@ -216,13 +230,14 @@ async function saveNotes() {
// 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 = $('hk-override').checked;
const override = /** @type {HTMLInputElement} */ ($('hk-override')).checked;
hideBanner();
setBusy(true, 'starting...');
try {
const r = await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } });
$('hk-override').checked = false;
/** @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) {
@@ -237,12 +252,14 @@ async function startRun() {
render();
}
/** @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...', '');
@@ -262,39 +279,42 @@ function renderHk(hk) {
}
}
/** @param {boolean} ok */
function setInput(ok) {
$('gm-input').disabled = !ok;
$('gm-send').disabled = !ok;
/** @type {HTMLInputElement} */ ($('gm-input')).disabled = !ok;
/** @type {HTMLButtonElement} */ ($('gm-send')).disabled = !ok;
}
// --- actions -----------------------------------------------------------
/** @returns {Promise<void>} */
async function sendTurn() {
const line = $('gm-input').value.trim();
const line = /** @type {HTMLInputElement} */ ($('gm-input')).value.trim();
if (!line || !state.runId) return;
$('gm-input').value = '';
/** @type {HTMLInputElement} */ ($('gm-input')).value = '';
setInput(false);
setBusy(true);
try {
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
} catch (e) {
banner(e.message);
$('gm-input').value = line; // a failed send must not eat the line
/** @type {HTMLInputElement} */ ($('gm-input')).value = line; // a failed send must not eat the line
}
setBusy(false);
render();
}
/** @returns {Promise<void>} */
async function sendAnswer() {
const answer = $('ask-answer').value.trim();
const answer = /** @type {HTMLInputElement} */ ($('ask-answer')).value.trim();
if (!answer || !state.runId) return;
$('ask-answer').value = '';
/** @type {HTMLInputElement} */ ($('ask-answer')).value = '';
setBusy(true);
try {
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
} catch (e) {
banner(e.message);
$('ask-answer').value = answer;
/** @type {HTMLInputElement} */ ($('ask-answer')).value = answer;
}
setBusy(false);
render();
@@ -302,6 +322,7 @@ async function sendAnswer() {
// 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...');
@@ -318,6 +339,7 @@ async function forkRun() {
// 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 {
@@ -325,8 +347,8 @@ async function replayHousekeeping() {
$('hk-replay-content').textContent = r.parsed
? JSON.stringify(r.manifest, null, 2)
: `${r.reason}\n\nraw output: ${r.file}`;
$('hk-replay-log').hidden = false;
$('hk-replay-log').open = true;
/** @type {HTMLDetailsElement} */ ($('hk-replay-log')).hidden = false;
/** @type {HTMLDetailsElement} */ ($('hk-replay-log')).open = true;
} catch (e) {
banner(e.message);
}
@@ -335,7 +357,7 @@ async function replayHousekeeping() {
// --- housekeeping poll + log -------------------------------------------
let poll = null;
/** @type {?ReturnType<typeof setInterval>} */ let poll = null;
function startPoll() {
stopPoll();
@@ -350,12 +372,13 @@ function stopPoll() {
poll = null;
}
/** @returns {Promise<void>} */
async function loadLog() {
try {
const log = await api(`/runs/${state.runId}/housekeeping/log`);
/** @type {HousekeepingLogResponse} */ const log = await api(`/runs/${state.runId}/housekeeping/log`);
$('hk-log-content').textContent = log.content;
$('hk-log').hidden = false;
$('hk-log').open = true;
/** @type {HTMLDetailsElement} */ ($('hk-log')).hidden = false;
/** @type {HTMLDetailsElement} */ ($('hk-log')).open = true;
} catch {
$('hk-log').hidden = true;
}
+47 -30
View File
@@ -5,6 +5,10 @@
// it) or start (the dormant session goes live; a carryover ending on
// a GM turn sends automatically as her cue).
/** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').FilesResponse} FilesResponse */
/** @typedef {import('./shapes.mjs').PromptsResponse} PromptsResponse */
import { $, el } from './dom.mjs';
import { api } from './client.mjs';
import { state } from './state.mjs';
@@ -32,19 +36,23 @@ const EDIT_LIST = [
];
// the editor's working set -- module-local, reset on every enter
let files = null; // { name: { content, exists } }
let drafts = {}; // unsaved edits by file name
let currentFile = null;
let fileSpecs = {};
let repoPrompts = {};
/** @type {Record<string, { mode: string, exists: boolean, content?: string }>} */ let files = {}; // the API surface, empty until enter
/** @type {Record<string, string>} */ let drafts = {}; // unsaved edits by file name
/** @type {?string} */ let currentFile = null;
/** @type {Record<string, { name: string, mode: string, source: string, exists: boolean, content: string }>} */ let fileSpecs = {};
/** @type {Record<string, string>} */ let repoPrompts = {};
const models = modelsBox('setup-models', { title: 'models -- per-run, over the deployment defaults' });
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters setup with a run id
state.runId = id;
drafts = {};
currentFile = null;
let detail, filesResp, prompts;
/** @type {RunDetail} */ let detail;
/** @type {FilesResponse} */ let filesResp;
/** @type {PromptsResponse} */ let prompts;
try {
[detail, filesResp, prompts] = await Promise.all([
api(`/runs/${id}`),
@@ -57,7 +65,7 @@ export async function enter(id, seq) {
}
if (seq !== state.seq) return;
if (detail.phase !== 'dormant') return navigate(`/runs/${id}`); // live sessions live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only -- fork to edit
if (!state.me || detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only -- fork to edit (the router guarantees signed-in)
files = filesResp.files;
repoPrompts = {
@@ -69,7 +77,7 @@ export async function enter(id, seq) {
$('setup-state').textContent = detail.draft
? `${detail.run.package} \u00b7 ${id} -- draft; edits land when the session starts`
: `${detail.run.package} \u00b7 ${id} -- session ${detail.sessions} dormant, the review window`;
$('setup-start').disabled = false;
/** @type {HTMLButtonElement} */ ($('setup-start')).disabled = false;
$('setup-start').textContent = `start session ${detail.sessions}`;
// draft-only affordances: deletion and save-as-package (a package is
// a starting point, never a snapshot)
@@ -78,7 +86,7 @@ export async function enter(id, seq) {
// prompt vars: the $TOKENS the prompts declare, filled per run
const vars = scanVars(prompts, files);
let currentVars = {};
/** @type {Record<string, string>} */ let currentVars = {};
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings -- empty vars */ }
const varsList = $('setup-vars-list');
varsList.textContent = '';
@@ -86,7 +94,7 @@ export async function enter(id, seq) {
$('setup-vars-state').textContent = '';
for (const tok of vars) {
const row = el('label', 'field', `$${tok}`);
const inp = el('input');
const inp = /** @type {HTMLInputElement} */ (el('input'));
inp.dataset.token = tok;
inp.value = currentVars[tok] ?? '';
row.appendChild(inp);
@@ -120,13 +128,14 @@ export async function enter(id, seq) {
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
$('savepkg-name').value = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
}
// the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or the session's own, the carryover included -- it
// expands at start like every authored surface) becomes a fillable
// input in setup
/** @param {PromptsResponse} prompts @param {Record<string, { content?: string }>} files @returns {string[]} */
function scanVars(prompts, files) {
const texts = [
prompts.system, prompts.invariants, prompts.reminder,
@@ -141,12 +150,14 @@ function scanVars(prompts, files) {
return [...found].sort();
}
/** @returns {Record<string, string>} */
function collectVars() {
const vars = {};
for (const inp of $('setup-vars-list').querySelectorAll('input')) vars[inp.dataset.token] = inp.value.trim();
/** @type {Record<string, string>} */ const vars = {};
for (const inp of /** @type {NodeListOf<HTMLInputElement>} */ ($('setup-vars-list').querySelectorAll('input'))) vars[/** @type {string} */ (inp.dataset.token)] = inp.value.trim();
return vars;
}
/** @returns {Promise<void>} */
async function saveVars() {
const vars = collectVars();
if (!Object.keys(vars).length) return;
@@ -154,6 +165,7 @@ async function saveVars() {
$('setup-vars-state').textContent = 'saved';
}
/** @param {string} f */
function selectFile(f) {
const prev = currentFile;
if (prev === f) return;
@@ -163,8 +175,8 @@ function selectFile(f) {
const content = spec.source === 'repo'
? (repoPrompts[f] ?? '')
: (drafts[f] ?? spec.content ?? '');
$('setup-edit').value = content;
$('setup-edit').disabled = spec.mode !== 'rw';
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).value = content;
/** @type {HTMLTextAreaElement} */ ($('setup-edit')).disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
renderHighlight();
@@ -177,9 +189,9 @@ function selectFile(f) {
const SIGIL_RE = /@(PC|Package)\b/g;
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
function renderHighlight() {
const ta = $('setup-edit');
const ta = /** @type {HTMLTextAreaElement} */ ($('setup-edit'));
const hl = $('edit-hl');
const esc = ta.value.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
const esc = ta.value.replace(/[&<>]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
@@ -188,9 +200,10 @@ function renderHighlight() {
hl.scrollLeft = ta.scrollLeft;
}
/** @param {string} f */
function stashDraft(f) {
if (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
const v = $('setup-edit').value;
const v = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
drafts[f] = v;
markNav();
@@ -199,23 +212,24 @@ function stashDraft(f) {
function markNav() {
const items = $('setup-files').children;
for (const item of items) {
const name = item.querySelector('.file-name').textContent.replace(' (new)', '');
const name = (/** @type {HTMLElement} */ (item.querySelector('.file-name'))).textContent.replace(' (new)', '');
const dirty = drafts[name] !== undefined;
item.classList.toggle('dirty', dirty);
// the dirty marker is authored text, never css-generated -- the
// rendered text must match the source (house rule, 2026-11-15)
item.querySelector('.file-dirty').textContent = dirty ? '*' : '';
(/** @type {HTMLElement} */ (item.querySelector('.file-dirty'))).textContent = dirty ? '*' : '';
item.classList.toggle('current', name === currentFile);
}
}
/** @returns {Promise<void>} */
async function saveFile() {
const f = currentFile;
if (!f) return;
$('setup-save').disabled = true;
/** @type {HTMLButtonElement} */ ($('setup-save')).disabled = true;
try {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: $('setup-edit').value } });
files[f].content = $('setup-edit').value;
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value } });
files[f].content = /** @type {HTMLTextAreaElement} */ ($('setup-edit')).value;
files[f].exists = true;
delete drafts[f];
$('setup-edit-state').textContent = 'saved';
@@ -224,11 +238,12 @@ async function saveFile() {
banner(e.message);
$('setup-edit-state').textContent = 'not saved';
}
$('setup-save').disabled = false;
/** @type {HTMLButtonElement} */ ($('setup-save')).disabled = false;
}
/** @returns {Promise<void>} */
async function saveDirty() {
stashDraft(currentFile);
if (currentFile != null) stashDraft(currentFile); // unreachable guard: enter always selects a file first
for (const [f, content] of Object.entries({ ...drafts })) {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
files[f].content = content;
@@ -241,26 +256,28 @@ async function saveDirty() {
// save the run's craft as a new user package -- published to every user
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
/** @returns {Promise<void>} */
async function saveAsPackage() {
const name = $('savepkg-name').value.trim();
const name = /** @type {HTMLInputElement} */ ($('savepkg-name')).value.trim();
if (!name) return banner('the package needs a display name');
$('savepkg-btn').disabled = true;
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = true;
$('savepkg-state').textContent = 'saving...';
try {
await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved -- ${r.package.id}`;
$('savepkg-name').value = '';
/** @type {HTMLInputElement} */ ($('savepkg-name')).value = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
$('savepkg-btn').disabled = false;
/** @type {HTMLButtonElement} */ ($('savepkg-btn')).disabled = false;
}
/** @returns {Promise<void>} */
async function startRun() {
const id = state.runId;
const btn = $('setup-start');
const btn = /** @type {HTMLButtonElement} */ ($('setup-start'));
// the prompts' own inputs must be filled -- the guard at start is
// the backstop, not the first line of defense
for (const [tok, v] of Object.entries(collectVars())) {
+8 -3
View File
@@ -15,11 +15,16 @@ import { banner } from './chrome.mjs';
import { navigate, runGone } from './router.mjs';
import { renderContent } from './transcript.mjs';
let storyRun = null;
/** @typedef {import('./shapes.mjs').RunDetail} RunDetail */
/** @typedef {import('./shapes.mjs').StoryResponse} StoryResponse */
/** @type {?string} */ let storyRun = null;
/** @param {?string} id @param {number} seq @returns {Promise<void>} */
export async function enter(id, seq) {
if (id == null) return; // unreachable: the router only enters the story with a run id
storyRun = id;
let detail;
/** @type {RunDetail} */ let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
@@ -28,7 +33,7 @@ export async function enter(id, seq) {
}
if (seq !== state.seq) return;
$('story-title').textContent = `${detail.display} -- the story`;
const story = await api(`/runs/${id}/story`).catch(() => null);
/** @type {?StoryResponse} */ const story = await api(`/runs/${id}/story`).catch(() => null);
if (seq !== state.seq) return;
if (!story) return banner('the story could not be read');
const box = $('story');
+18 -9
View File
@@ -16,8 +16,9 @@ import { render } from './router.mjs';
// two-click confirm -- the second click within 5s fires; anything
// else disarms. Each button owns its own arm state.
/** @param {HTMLElement} btn @param {{ label: string, confirm: string, fire: () => Promise<void> }} opts */
export function armedButton(btn, { label, confirm, fire }) {
let timer = null;
/** @type {?ReturnType<typeof setTimeout>} */ let timer = null;
btn.addEventListener('click', async () => {
if (timer === null) {
btn.textContent = confirm;
@@ -35,14 +36,17 @@ export function armedButton(btn, { label, confirm, fire }) {
// resolves on success and throws on failure -- a failed save keeps
// the editor open, nothing was changed. setEditable(false) is the
// spectator state: no edit button, an open editor cancels.
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[], save: (items: string[]) => Promise<unknown> }} PaneOpts */
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[] }} Pane */
/** @param {PaneOpts} opts @returns {Pane} */
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body;
const editBtn = el('button', null, 'edit');
sec.querySelector('.pane-head').appendChild(editBtn);
(/** @type {HTMLElement} */ (sec.querySelector('.pane-head'))).appendChild(editBtn);
const editor = el('div', 'pane-editor');
editor.hidden = true;
const area = el('textarea');
const area = /** @type {HTMLTextAreaElement} */ (el('textarea'));
area.rows = rows;
area.placeholder = placeholder;
const actions = el('div', 'pane-editor-actions');
@@ -54,7 +58,7 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
editor.appendChild(actions);
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
let items = [];
/** @type {string[]} */ let items = [];
let mayEdit = false;
let open = false;
@@ -102,19 +106,22 @@ export function paneEditor({ section, body, empty, placeholder, rows, format, to
// the upstream model listing, fetched once per session -- a live
// /models call every render would hammer the endpoint for a list
// that rarely changes
let cachedModels = null;
/** @type {?string[]} */ let cachedModels = null;
/** @returns {Promise<string[]>} */
export async function modelList() {
if (!cachedModels) cachedModels = await api('/models').catch(() => []);
if (!cachedModels) cachedModels = /** @type {string[]} */ (await api('/models').catch(() => []));
return cachedModels;
}
// A select's "" value means "deployment default"; a current override
// missing from the listing stays selectable, so a stale pick never
// silently rewrites itself.
/** @param {HTMLSelectElement} sel @param {?string} current @param {string[]} list @param {?string} [def] */
function fillSelect(sel, current, list, def) {
sel.textContent = '';
/** @param {string} v @param {string} label */
const mk = (v, label) => {
const o = el('option', null, label);
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
@@ -127,12 +134,13 @@ function fillSelect(sel, current, list, def) {
// the models box: player/housekeeper selects + save, posting the
// per-run overrides. The mount keeps its id -- the CSS panels it.
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';
root.appendChild(el('h2', null, title));
const playerSel = el('select');
const houseSel = el('select');
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper ');
@@ -158,6 +166,7 @@ export function modelsBox(mount, { title }) {
}
});
return {
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {string[]} list */
fill(models, defaults, list) {
fillSelect(playerSel, models?.player ?? null, list, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper);