Files
tiny-worlds/web/app.mjs
T

1379 lines
48 KiB
JavaScript
Raw Normal View History

// web/app.mjs — the SPA: strictly a client of the REST API.
//
// Path-routed views: / (home: runs to pick up), /new (package picker),
// /runs/<id>/setup (the editor; start = open window + send turn-0),
// /runs/<id> (play). The server serves the shell for any extensionless
// path. The transcript renders three registers by the ruled markers:
// plain text is speech, *italics* is narration, a line opening with
// `(` is OOC (closing paren optional; a lone paren is an empty OOC
// line and is skipped). The <status> blocks riding GM turns and the
// paper tags on player turns are machinery, not prose — they render
// as chips and pane state, mirroring the live-context policy.
const $ = (id) => document.getElementById(id);
const TOKEN_KEY = 'rp-token';
const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
const state = {
view: null, runId: null, seq: 0, poll: null, paper: [],
files: null, drafts: {}, currentFile: null, fileSpecs: {}, repoPrompts: {},
vars: [], pkg: null, log: [],
me: null, // the signed-in user ({ id, name, superuser }) or null
};
// --- diagnostics: a rolling event log that survives refreshes ---------------
//
// The api() choke point records every server call (status + duration),
// uncaught errors land here, and so do navigation ejections — the
// "why did the app throw me out" history the ten-second banner loses.
// Kept in sessionStorage; the header's "log" button shows it.
function logEvent(kind, text) {
state.log.push(`${new Date().toISOString().slice(11, 19)} ${kind} ${text}`);
if (state.log.length > 300) state.log.splice(0, state.log.length - 300);
try { sessionStorage.setItem('diag', JSON.stringify(state.log)); } catch {}
}
try { state.log = JSON.parse(sessionStorage.getItem('diag') ?? '[]'); } catch { state.log = []; }
function renderDiag() {
const d = $('diag');
d.textContent = state.log.join('\n');
d.scrollTop = d.scrollHeight;
}
function toggleDiag() {
const d = $('diag');
d.hidden = !d.hidden;
if (!d.hidden) renderDiag();
}
async function api(path, opts = {}) {
const started = performance.now();
const label = `${opts.method ?? 'GET'} ${path}`;
try {
const res = await fetch(`/api${path}`, {
method: opts.method ?? 'GET',
headers: {
...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
...(authToken() ? { authorization: `Bearer ${authToken()}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page — the notepad flush
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const e = 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}`);
// a rejected token ends the session: drop it and show the claim
// view — every path leads there until a fresh one is claimed
if (res.status === 401 && path !== '/session' && authToken()) {
try { localStorage.removeItem(TOKEN_KEY); } catch {}
state.me = null;
logEvent('nav', 'signed out: token rejected');
setTimeout(render, 0);
}
throw e;
}
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms`);
return data;
} catch (e) {
if (!e.status) logEvent('api', `${label} FAILED ${Math.round(performance.now() - started)}ms — ${e.message}`); // network level
throw e;
}
}
window.addEventListener('error', (e) => logEvent('error', e.message));
window.addEventListener('unhandledrejection', (e) => logEvent('error', `unhandled: ${e.reason?.message ?? e.reason}`));
// --- register rendering -------------------------------------------------------
// splits text into spans: *italics* = narration, **bold** = emphasis
function renderSpans(el, text) {
const parts = String(text).split(/(\*\*[^*]+\*\*|\*[^*\n]+\*)/g);
for (const p of parts) {
if (!p) continue;
if (p.startsWith('**') && p.endsWith('**')) {
const b = document.createElement('strong');
b.textContent = p.slice(2, -2);
el.appendChild(b);
} else if (p.startsWith('*') && p.endsWith('*') && p.length > 2) {
const i = document.createElement('em');
i.className = 'narration';
i.textContent = p.slice(1, -1);
el.appendChild(i);
} else {
el.appendChild(document.createTextNode(p));
}
}
}
// one content block (a GM or player turn) -> DOM lines
function renderContent(el, text, { extract }) {
let body = String(text ?? '');
let status = null;
let conflict = null;
let agenda = null;
if (extract) {
const sm = body.match(/<status>([\s\S]*?)<\/status>/);
if (sm) { status = sm[1]; body = body.replace(sm[0], ''); }
const cm = body.match(/<conflict>([\s\S]*?)<\/conflict>/);
if (cm) { conflict = cm[1]; body = body.replace(cm[0], ''); }
const am = body.match(/<agenda>([\s\S]*?)<\/agenda>/);
if (am) { agenda = am[1]; body = body.replace(am[0], ''); }
}
const tags = [];
for (const m of body.matchAll(/<(lost|gained|add|drop)>([\s\S]*?)<\/\1>/g)) {
tags.push({ kind: m[1], items: m[2].split('\n').flatMap((l) => l.split(',')).map((x) => x.trim()).filter(Boolean) });
}
for (const t of tags) body = body.replace(new RegExp(`<${t.kind}>[\\s\\S]*?</${t.kind}>`), '');
let narr = false; // an open multi-line narration block
for (const line of body.split('\n')) {
const t = line.trim();
if (!t) { el.appendChild(document.createElement('br')); continue; }
if (t.startsWith('(')) {
if (t === '(') continue; // empty OOC — skip
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
el.appendChild(d);
continue;
}
if (t.startsWith('<')) {
// substrate lines: an opening <tag> is always OOC (invariants.md).
// Known blocks were extracted above; whatever remains is an
// unknown or unbalanced tag — keep it visible, styled as OOC
const d = document.createElement('div');
d.className = 'line ooc';
d.textContent = t;
el.appendChild(d);
continue;
}
const stars = (line.match(/\*/g) ?? []).length;
if (!narr && stars % 2 === 0) {
// balanced: spans carry the registers — mixed lines
// (`*foo* bar *baz*`), whole-line narration (`*she sleeps.*`),
// bold — all render correctly
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
el.appendChild(d);
continue;
}
if (!narr && !(t.startsWith('*') && !t.startsWith('**'))) {
// a stray unpaired * mid-line is not a block opener — render
// as-is; the stray stays literal
const d = document.createElement('div');
d.className = 'line speech';
renderSpans(d, line);
el.appendChild(d);
continue;
}
// block narration: an unpaired leading * opens a multi-line
// block, a trailing * closes it
let content = line.replace(/^\s*\*/, '');
narr = true;
if (t.endsWith('*') && !t.endsWith('**')) {
narr = false;
content = content.trimEnd().slice(0, -1);
}
const d = document.createElement('div');
d.className = 'line narration';
renderSpans(d, content);
el.appendChild(d);
}
if (tags.length) {
const wrap = document.createElement('div');
wrap.className = 'tags';
for (const t of tags) {
for (const item of t.items) {
const c = document.createElement('span');
c.className = `chip ${t.kind}`;
c.textContent = item;
wrap.appendChild(c);
}
}
el.appendChild(wrap);
}
return { status, conflict, agenda };
}
// --- transcript ---------------------------------------------------------------
function el(tag, cls, text) {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}
function renderTranscript(entries) {
const t = $('transcript');
t.textContent = '';
const bundleParts = [];
let flushBundle = () => {
if (!bundleParts.length) return;
const d = el('details', 'bundle');
d.appendChild(el('summary', null, `window bundle — ${bundleParts.map((p) => p.part).join(', ')}`));
for (const p of bundleParts) {
const sec = el('details');
sec.appendChild(el('summary', null, p.part));
sec.appendChild(el('pre', null, p.m.content));
d.appendChild(sec);
}
t.appendChild(d);
bundleParts.length = 0;
};
for (const e of entries) {
if (e.t === 'bundle') {
// every part is inspectable, read-only: system (guards +
// substrate + craft), backdrop, character, the rings
bundleParts.push(e);
continue;
}
flushBundle();
if (e.t === 'msg' && e.reminder) {
// 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);
if (e === newest) {
const d = el('details', 'bundle');
d.appendChild(el('summary', null, 'turn reminder — rides every GM turn'));
d.appendChild(el('pre', null, e.m.content));
t.appendChild(d);
}
continue;
}
if (e.t === 'msg') {
if (e.m.role === 'user' && e.conflictOnly) {
// the self-heal message: error traffic on its own, never GM prose
t.appendChild(el('div', 'machinery', `[conflict] ${String(e.m.content).replace(/<\/?conflict>/g, '').trim()}`));
continue;
}
if (e.m.role === 'user') gmTurn(e.m.content, 'GM');
else if (e.m.role === 'assistant') playerTurn(e);
continue;
}
if (e.t === 'tool') {
t.appendChild(el('div', 'machinery', `${e.ask ? '[ruling] ' : '[tool result] '}${String(e.m.content).split('\n')[0]}`));
continue;
}
if (e.t === 'note') renderNote(e);
}
flushBundle();
t.scrollTop = t.scrollHeight;
function gmTurn(content, who) {
const d = el('div', 'turn gm');
d.appendChild(el('div', 'who', who));
const body = el('div');
d.appendChild(body);
const { conflict } = renderContent(body, content, { extract: true });
if (conflict) showConflict(conflict);
t.appendChild(d);
}
function playerTurn(e) {
const d = el('div', 'turn player');
d.appendChild(el('div', 'who', 'player'));
const body = el('div');
d.appendChild(body);
if (e.m.reasoning_content) d.appendChild(el('div', 'machinery', '[thinking is logged for the housekeeper, not shown]'));
renderContent(body, e.m.content, { extract: false });
for (const c of e.m.tool_calls ?? []) {
d.appendChild(el('div', 'machinery', `[tool call] ${c.function.name}`));
}
t.appendChild(d);
}
function renderNote(e) {
let text = null;
if (e.kind === 'window') text = `window opened ${e.at}${e.fresh ? ' — fresh' : ''}`;
else if (e.kind === 'seed') text = `seed ${e.ok ? 'applied' : 'failed'}: ${e.detail}`;
else if (e.kind === 'ingest') text = `turn-0 paper ${e.ok === false ? 'INGEST FAILED' : 'ingested'}${e.ok === false ? `: ${(e.detail ?? '').split('\n')[0]}` : ''}`;
else if (e.kind === 'ask') text = `ask_gm: ${e.question}`;
else if (e.kind === 'paper') text = `paper: lost ${JSON.stringify(e.applied?.lost ?? [])}, gained ${JSON.stringify(e.applied?.gained ?? [])}`;
if (text) t.appendChild(el('div', 'machinery', text));
}
}
// --- panes --------------------------------------------------------------------
function renderPaper(paper) {
state.paper = paper ?? [];
const p = $('paper');
if (!state.paper.length) {
p.textContent = 'a blank sheet';
p.classList.add('empty');
return;
}
p.classList.remove('empty');
p.textContent = state.paper.join(', '); // compact, mirroring the <status> wire format
}
// the agenda pane mirrors the wire: the queue numbered from the top,
// exactly as the model cites it
function renderAgenda(agenda) {
state.agenda = agenda ?? [];
const a = $('agenda');
if (!state.agenda.length) {
a.textContent = 'a clear head';
a.classList.add('empty');
return;
}
a.classList.remove('empty');
a.textContent = state.agenda.map((d, i) => `${i}. ${d}`).join('; ');
}
// the GM's out-of-band agenda override: whole-queue replace via agenda-set
function editAgenda() {
$('agenda-edit-area').value = state.agenda.join('\n');
$('agenda').hidden = true;
$('agenda-edit').hidden = true;
$('agenda-editor').hidden = false;
$('agenda-edit-area').focus();
}
function cancelAgendaEdit() {
$('agenda-editor').hidden = true;
$('agenda').hidden = false;
$('agenda-edit').hidden = false;
}
async function saveAgenda() {
const items = $('agenda-edit-area').value
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
.map((x) => x.trim()).filter(Boolean);
try {
await api(`/runs/${state.runId}/agenda`, { method: 'POST', body: { items } });
} catch (e) {
banner(e.message);
return; // stay in the editor — nothing was changed
}
cancelAgendaEdit();
render();
}
// the GM's out-of-band override: whole-paper replace via paper-set
function editPaper() {
$('paper-edit-area').value = state.paper.join('\n');
$('paper').hidden = true;
$('paper-edit').hidden = true;
$('paper-editor').hidden = false;
$('paper-edit-area').focus();
}
function cancelPaperEdit() {
$('paper-editor').hidden = true;
$('paper').hidden = false;
$('paper-edit').hidden = false;
}
async function savePaper() {
// one per line, commas tolerated as separators — same split the clerk uses
const items = $('paper-edit-area').value
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+/, '').split(','))
.map((x) => x.trim()).filter(Boolean);
try {
await api(`/runs/${state.runId}/paper`, { method: 'POST', body: { items } });
} catch (e) {
banner(e.message);
return; // stay in the editor — nothing was changed
}
cancelPaperEdit();
render();
}
function showConflict(text) {
const c = $('conflict');
c.textContent = `conflict: ${text}`;
c.hidden = false;
}
function renderMeter(detail) {
const fill = $('context-fill');
const label = $('context-label');
const c = detail?.context;
if (!c || c.used == null) {
fill.style.width = '0';
label.textContent = '';
return;
}
const pct = c.pct ?? 0;
fill.style.width = `${Math.min(100, pct)}%`;
fill.classList.toggle('hot', pct > 85);
label.textContent = c.window ? `${pct}% — close & housekeep past 85%` : '';
}
function setHk(stateText, cls) {
const h = $('hk-state');
h.textContent = stateText;
h.className = cls ?? '';
}
// in-page notices — no JS alert()/confirm(): they block the embedded pane
let bannerTimer = null;
function banner(text, kind = 'error') {
const b = $('banner');
b.textContent = text;
b.className = kind;
b.hidden = false;
clearTimeout(bannerTimer);
bannerTimer = setTimeout(() => { b.hidden = true; }, 10000);
}
function hideBanner() {
$('banner').hidden = true;
}
// --- routing --------------------------------------------------------------------
function navigate(p) {
history.pushState({}, '', p);
render();
}
window.addEventListener('popstate', render);
async function render() {
const seq = ++state.seq;
stopPoll();
hideBanner();
const p = location.pathname;
if (!state.me) return viewClaim(seq); // signed out: every path leads to the claim
let m;
if (p === '/') return viewHome(seq);
if (p === '/new') return viewNew(seq);
if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/setup$/))) return viewSetup(m[1], seq);
if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) return viewPlay(m[1], seq);
navigate('/');
}
function show(view) {
if (state.view === 'play' && view !== 'play') saveNotes(); // flush the pad when leaving play
state.view = view;
for (const v of ['claim', 'home', 'new', 'setup', 'play']) $(`view-${v}`).hidden = v !== view;
document.body.classList.toggle('play', view === 'play');
// 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
$('who').textContent = state.me ? `${state.me.name}${state.me.superuser ? ' · op' : ''}` : '';
$('who').title = state.me?.id ?? '';
$('window-info').textContent = '';
$('conflict').hidden = true;
renderMeter(null);
cancelPaperEdit(); // a stale open editor must never leave the pane hidden
cancelAgendaEdit();
if (view !== 'play') $('ask-modal').close();
}
// --- the claim view ---------------------------------------------------------------
async function viewClaim(seq) {
show('claim');
$('claim-code').value = '';
$('claim-name').value = '';
let fresh = false;
try { fresh = (await api('/session')).fresh; } catch {} // public: works signed out
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();
}
// --- home -----------------------------------------------------------------------
async function viewHome(seq) {
show('home');
const runs = await api('/runs');
if (seq !== state.seq) return;
const list = $('run-list');
list.textContent = '';
if (!runs.length) {
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 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
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.models?.player ? ` · ${r.models.player}` : ''}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
// another user's draft is read-only: the play view says so; your own opens the editor
card.addEventListener('click', () => navigate(r.lastSession || !mine ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
list.appendChild(card);
}
await renderAdmin(seq);
}
const ownershipTag = (r, mine) =>
(mine ? ' · yours' : r.owner == null ? ' · ownerless' : ` · ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
// --- admin (superuser, on home): invites and users -------------------------------
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false;
const [inv, us] = await Promise.all([api('/invites'), api('/users')]);
if (seq !== state.seq) return;
const invList = $('invite-list');
invList.textContent = '';
for (const i of inv.invites) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `#${i.id} ${i.kind} — ${i.state}`));
if (i.state === 'unclaimed') {
const b = el('button', null, 'revoke');
b.addEventListener('click', async () => {
try { await api(`/invites/${i.id}`, { method: 'DELETE' }); render(); } catch (e) { banner(e.message); }
});
row.appendChild(b);
}
invList.appendChild(row);
}
const userList = $('user-list');
userList.textContent = '';
for (const u of us.users) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `${u.name} · ${u.id}${u.superuser ? ' · op' : ''}`));
if (u.id !== state.me.id) {
const b = el('button', 'danger', 'revoke');
b.addEventListener('click', () => revokeUser(u, b));
row.appendChild(b);
}
userList.appendChild(row);
}
}
// revocation destroys the identity — two-click armed, like every destructive act
let revokeArmed = null;
function revokeUser(u, btn) {
if (revokeArmed === null) {
btn.textContent = 'sure? click again';
revokeArmed = setTimeout(() => { revokeArmed = null; btn.textContent = 'revoke'; }, 5000);
return;
}
clearTimeout(revokeArmed);
revokeArmed = null;
btn.textContent = 'revoke';
api(`/users/${u.id}/revoke`, { method: 'POST', body: {} })
.then(() => render())
.catch((e) => banner(e.message));
}
function runStateText(r) {
if (!r.lastSession) return 'draft — not started yet';
if (r.open) return `window open${r.pendingAsk ? ' — waiting for your answer' : ''}`;
if (r.lastSession !== r.lastHousekept) return 'window closed, never housekept';
return 'window closed';
}
function runStateClass(r) {
if (!r.lastSession) return 'draft';
if (r.pendingAsk) return 'attention';
if (r.open) return 'ok';
if (r.lastSession !== r.lastHousekept) return 'attention';
return '';
}
// --- new run: the package picker, then the naming form ------------------------
async function viewNew(seq) {
show('new');
$('package-pick').hidden = false;
$('create-form').hidden = true;
const pkgs = await api('/packages');
if (seq !== state.seq) return;
const list = $('package-list');
list.textContent = '';
for (const p of pkgs) {
const card = el('button', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} · ${origin} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete — missing backdrop or character'));
card.addEventListener('click', () => pickPackage(p));
list.appendChild(card);
}
}
// the naming form: package display name (defaults to the package's
// own) and the main character's name (rolled from the dictionary,
// unused by any run). Runs of the same package need distinct names.
async function pickPackage(p) {
state.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();
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;
}
// --- models: per-run overrides of the deployment defaults --------------------
//
// The upstream listing is fetched once per session (a live /models
// call every render would hammer the endpoint for a list that rarely
// changes). A select's "" value means "deployment default"; a current
// override missing from the listing stays selectable, so a stale pick
// never silently rewrites itself.
async function modelList() {
if (!state.modelList) state.modelList = await api('/models').catch(() => []);
return state.modelList;
}
function fillModelSelect(sel, current, list, def) {
sel.textContent = '';
const mk = (v, label) => {
const o = el('option', null, label);
o.value = v;
sel.appendChild(o);
};
mk('', `deployment default${def ? ` — ${def}` : ' (unset)'}`);
const opts = [...list];
if (current && !opts.includes(current)) opts.push(current);
for (const m of opts) mk(m, m);
sel.value = current ?? '';
}
async function saveModels(playerSel, housekeeperSel, stateEl) {
try {
await api(`/runs/${state.runId}/model`, {
method: 'POST',
body: { player: playerSel.value || null, housekeeper: housekeeperSel.value || null },
});
stateEl.textContent = 'saved';
} catch (e) {
banner(e.message);
stateEl.textContent = 'not saved';
}
}
// --- setup: the editor + start -----------------------------------------------------
// one list, in bundle-assembly order: the repo-fed system message
// parts (read-only — the user should understand how the model is
// prompted), the craft tail and GM messages (editable), then the
// initial state, then run config (read-only). Everything the run
// sends, nothing it doesn't.
const EDIT_LIST = [
{ name: 'system.md', mode: 'ro', source: 'repo' },
{ name: 'invariants.md', mode: 'ro', source: 'repo' },
{ name: 'reminder.md', mode: 'ro', source: 'repo' }, // rides every turn as its own system chunk
{ name: 'handbook.md', mode: 'rw', source: 'run' },
{ name: 'backdrop.md', mode: 'rw', source: 'run' },
{ name: 'character.md', mode: 'rw', source: 'run' },
{ name: 'seed.json', mode: 'rw', source: 'run' }, // the rings it seeds — turn-0 wakes into them
{ name: 'turn-0.md', mode: 'rw', source: 'run' },
{ name: 'settings.json', mode: 'ro', source: 'run' },
{ name: 'run.json', mode: 'ro', source: 'run' },
];
// the prompts declare their own inputs: every $TOKEN in any prompt
// file (repo-fed or run copy) becomes a fillable input in setup
function scanVars(prompts, files) {
const texts = [
prompts.system, prompts.invariants, prompts.reminder,
files['handbook.md']?.content,
files['backdrop.md']?.content, files['character.md']?.content, files['turn-0.md']?.content,
];
const found = new Set();
for (const t of texts) {
if (!t) continue;
for (const m of t.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)) found.add(m[1]);
}
return [...found].sort();
}
function collectVars() {
const vars = {};
for (const inp of $('setup-vars-list').querySelectorAll('input')) vars[inp.dataset.token] = inp.value.trim();
return vars;
}
async function saveVars() {
const vars = collectVars();
if (!Object.keys(vars).length) return;
await api(`/runs/${state.runId}/vars`, { method: 'POST', body: { vars } });
$('setup-vars-state').textContent = 'saved';
}
async function viewSetup(id, seq) {
show('setup');
state.runId = id;
state.drafts = {};
state.currentFile = null;
let detail, files, prompts;
try {
[detail, files, prompts] = await Promise.all([
api(`/runs/${id}`),
api(`/runs/${id}/files`),
api('/prompts'),
]);
} catch (e) { if (e.status === 404) {
const from = location.pathname;
navigate('/'); // render() clears the banner first — set it after
banner(`run ${id} is gone — deleted?`);
logEvent('nav', `left ${from} for home: run gone (404)`);
return;
}
return banner(`could not reach the server: ${e.message}`); // stay put — transient
}
if (seq !== state.seq) return;
if (!detail.draft) return navigate(`/runs/${id}`); // started runs live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only — fork to edit
state.files = files.files;
state.repoPrompts = {
'system.md': prompts.system ?? '',
'invariants.md': prompts.invariants ?? '',
'reminder.md': prompts.reminder ?? '',
};
$('setup-title').textContent = detail.display;
$('setup-state').textContent = `${detail.run.package} · ${id} — draft; edits land when the window opens`;
$('setup-start').disabled = false;
$('setup-start').textContent = 'start';
// prompt vars: the $TOKENS the prompts declare, filled per run
state.vars = scanVars(prompts, state.files);
let currentVars = {};
try { currentVars = JSON.parse(state.files['settings.json']?.content ?? '{}').vars ?? {}; } catch {}
const varsList = $('setup-vars-list');
varsList.textContent = '';
$('setup-vars').hidden = !state.vars.length;
$('setup-vars-state').textContent = '';
for (const tok of state.vars) {
const row = el('label', 'field', `$${tok}`);
const inp = el('input');
inp.dataset.token = tok;
inp.value = currentVars[tok] ?? '';
row.appendChild(inp);
varsList.appendChild(row);
}
// models: per-run overrides, selected from the upstream listing
const mlist = await modelList();
if (seq !== state.seq) return;
fillModelSelect($('model-player'), detail.run.models?.player ?? null, mlist, detail.run.modelDefaults?.player);
fillModelSelect($('model-housekeeper'), detail.run.models?.housekeeper ?? null, mlist, detail.run.modelDefaults?.housekeeper);
$('models-state').textContent = '';
const nav = $('setup-files');
nav.textContent = '';
state.fileSpecs = {};
for (const e of EDIT_LIST) {
const runFile = state.files[e.name];
const spec = {
...e,
exists: e.source === 'repo' ? true : !!runFile?.exists,
content: e.source === 'repo' ? state.repoPrompts[e.name] : (runFile?.content ?? ''),
};
state.fileSpecs[e.name] = spec;
const item = el('button', `file-item${e.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
item.appendChild(el('span', 'file-name', e.name + (spec.exists ? '' : ' (new)')));
item.appendChild(el('span', 'file-dirty', ''));
item.addEventListener('click', () => selectFile(e.name));
nav.appendChild(item);
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
$('savepkg-name').value = '';
}
function selectFile(f) {
const prev = state.currentFile;
if (prev === f) return;
if (prev && state.fileSpecs[prev]?.mode === 'rw') stashDraft(prev);
state.currentFile = f;
const spec = state.fileSpecs[f] ?? { mode: 'rw', source: 'run', exists: false };
const content = spec.source === 'repo'
? (state.repoPrompts[f] ?? '')
: (state.drafts[f] ?? spec.content ?? '');
$('setup-edit').value = content;
$('setup-edit').disabled = spec.mode !== 'rw';
$('setup-save').hidden = spec.mode !== 'rw';
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
renderHighlight();
markNav();
}
// the highlight overlay: known sigils (gold) and every $VAR (green)
// light up in place; unknown @-words are the author's own text and
// stay plain — @ syntax is not owned here
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 hl = $('edit-hl');
const esc = ta.value.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
hl.innerHTML = esc
.replace(VAR_RE, '<span class="tok-var">$&</span>')
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
+ '\n\u200b'; // keep the trailing empty line's height honest
hl.scrollTop = ta.scrollTop;
hl.scrollLeft = ta.scrollLeft;
}
function stashDraft(f) {
if (state.fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
const v = $('setup-edit').value;
if (v === (state.files[f]?.content ?? '')) { delete state.drafts[f]; markNav(); return; }
state.drafts[f] = v;
markNav();
}
function markNav() {
const items = $('setup-files').children;
for (const item of items) {
const name = item.querySelector('.file-name').textContent.replace(' (new)', '');
item.classList.toggle('dirty', state.drafts[name] !== undefined);
item.classList.toggle('current', name === state.currentFile);
}
}
async function saveFile() {
const f = state.currentFile;
if (!f) return;
$('setup-save').disabled = true;
try {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: $('setup-edit').value } });
state.files[f].content = $('setup-edit').value;
state.files[f].exists = true;
delete state.drafts[f];
$('setup-edit-state').textContent = 'saved';
markNav();
} catch (e) {
banner(e.message);
$('setup-edit-state').textContent = 'not saved';
}
$('setup-save').disabled = false;
}
async function saveDirty() {
stashDraft(state.currentFile);
for (const [f, content] of Object.entries({ ...state.drafts })) {
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
state.files[f].content = content;
state.files[f].exists = true;
delete state.drafts[f];
}
markNav();
}
// 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.
async function saveAsPackage() {
const name = $('savepkg-name').value.trim();
if (!name) return banner('the package needs a display name');
$('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 = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
$('savepkg-btn').disabled = false;
}
// delete this draft: two-click armed (destructive), then home.
// A played run refuses server-side — stories are deleted by hand.
let deleteArmed = null;
async function deleteDraft() {
const btn = $('setup-delete');
if (deleteArmed === null) {
btn.textContent = 'sure? click again to delete';
deleteArmed = setTimeout(() => {
deleteArmed = null;
btn.textContent = 'delete draft';
}, 5000);
return;
}
clearTimeout(deleteArmed);
deleteArmed = null;
btn.textContent = 'delete draft';
try {
await api(`/runs/${state.runId}`, { method: 'DELETE' });
navigate('/');
} catch (e) {
banner(e.message);
}
}
async function startRun() {
const id = state.runId;
const btn = $('setup-start');
// the prompts' own inputs must be filled — the guard at window-open
// is the backstop, not the first line of defense
for (const [tok, v] of Object.entries(collectVars())) {
if (!v) {
banner(`$${tok} is unfilled — a prompt declares it, the run needs it`);
return;
}
}
btn.disabled = true;
btn.textContent = 'starting…';
try {
await saveVars();
await saveDirty();
} catch (e) {
banner(`did not start — ${e.message}`);
btn.disabled = false;
btn.textContent = 'start';
return;
}
let opened = false;
try {
await api(`/runs/${id}/windows`, { method: 'POST', body: {} });
opened = true;
} catch (e) {
banner(e.message);
}
if (opened && state.files['turn-0.md']?.exists) {
try {
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
} catch (e) {
banner(`${e.message} — the beat can be sent from the play view`);
}
}
navigate(`/runs/${id}`);
}
// --- play --------------------------------------------------------------------------
async function viewPlay(id, seq) {
show('play');
await saveNotes(); // flush the pad for the previous run before switching
state.runId = id;
notesDirty = false;
$('gm-notes').value = '';
$('notes-state').textContent = '';
await refreshPlay(id, seq);
}
async function refreshPlay(id, seq) {
let detail;
try {
detail = await api(`/runs/${id}`);
} catch (e) {
if (e.status === 404) {
const from = location.pathname;
navigate('/'); // render() clears the banner first — set it after
banner(`run ${id} is gone — deleted?`);
logEvent('nav', `left ${from} for home: run gone (404)`);
return;
}
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;
if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence
show('play');
state.runId = id;
$('window-info').textContent = `${detail.display} — a draft, not yours`;
$('transcript').textContent = '';
$('transcript').appendChild(el('div', 'hint', 'this run is still a draft — fork it to make it yours and edit it'));
return;
}
$('window-info').textContent = (detail.open
? `${detail.display} — window ${detail.window}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
: `${detail.display} — no open window`)
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating');
renderMeter(detail);
renderPaper(detail.paper);
renderAgenda(detail.agenda);
$('conflict').hidden = true;
// spectator mode: read everything, mutate nothing — the fork is the
// way in. Ownerless runs are spectators for everyone alike.
$('paper-edit').hidden = !mine;
$('agenda-edit').hidden = !mine;
$('gm-notes').readOnly = !mine;
let beatNeeded = false;
if (detail.open) {
const session = await api(`/runs/${id}/session`);
if (seq !== state.seq) return;
renderTranscript(session.entries);
beatNeeded = mine && detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
} else {
$('transcript').textContent = '';
}
// the opening beat, if start was interrupted or the window was opened directly
if (beatNeeded) await offerBeat(id, seq);
// controls
$('window-open').hidden = detail.open || !mine;
$('hk-run').hidden = !detail.open || !mine;
$('hk-replay').hidden = !detail.lastSession || !mine; // any session log is replayable, by the owner
setInput(detail.open && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine
? 'GM line — Enter sends, Shift+Enter newlines'
: 'spectating — fork this run to continue it as yours';
// models: the owner's per-run overrides
$('models-pane').hidden = !mine;
if (mine) {
const mlist = await modelList();
if (seq !== state.seq) return;
fillModelSelect($('pm-player'), detail.run.models?.player ?? null, mlist, detail.run.modelDefaults?.player);
fillModelSelect($('pm-housekeeper'), detail.run.models?.housekeeper ?? null, mlist, detail.run.modelDefaults?.housekeeper);
}
// pending ask: the modal re-presents after a refresh — the owner's
// 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();
} else {
$('ask-modal').close();
}
// housekeeping state
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 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 paper.
let notesTimer = null;
let notesDirty = false;
async function loadNotes(id, seq) {
const notes = await api(`/runs/${id}/notes`).catch(() => null);
if (!notes || seq !== state.seq || notesDirty) return;
$('gm-notes').value = notes.content;
}
function notesInput() {
notesDirty = true;
$('notes-state').textContent = 'unsaved';
clearTimeout(notesTimer);
notesTimer = setTimeout(saveNotes, 1000);
}
async function saveNotes() {
clearTimeout(notesTimer);
if (!notesDirty || !state.runId) return;
const content = $('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);
}
}
async function offerBeat(id, seq) {
let hasTurn0 = true;
try {
const files = await api(`/runs/${id}/files`);
if (seq !== state.seq) return;
hasTurn0 = files.files['turn-0.md']?.exists === true;
} catch { /* try the endpoint anyway */ }
if (!hasTurn0) return;
const bar = el('div', 'beat');
bar.appendChild(el('span', null, 'the window is open; the opening beat has not been sent'));
const b = el('button', 'primary', 'send the opening beat');
b.addEventListener('click', async () => {
setBusy(true);
try {
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
} catch (e) {
banner(e.message);
}
setBusy(false);
render();
});
bar.appendChild(b);
$('transcript').prepend(bar);
}
function renderHk(hk) {
if (hk.state === 'running') {
setHk('housekeeping…', '');
startPoll();
return;
}
stopPoll();
if (hk.state === 'applied') {
setHk(`applied — window ${hk.window ?? ''}\nnext window open`, 'applied');
loadLog(); // idempotent — also covers a refresh while applied
} else if (hk.state === 'rejected') {
setHk(`rejected — held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
} else {
setHk('idle', '');
}
}
function setInput(ok) {
$('gm-input').disabled = !ok;
$('gm-send').disabled = !ok;
}
// --- actions -------------------------------------------------------------------------
async function sendTurn() {
const line = $('gm-input').value.trim();
if (!line || !state.runId) return;
$('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
}
setBusy(false);
render();
}
async function sendAnswer() {
const answer = $('ask-answer').value.trim();
if (!answer || !state.runId) return;
$('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;
}
setBusy(false);
render();
}
function setBusy(on, text = 'her turn…') {
$('busy').hidden = !on; // model calls take their time — say so
if (on) $('busy').textContent = text;
}
// fork: a copy of this run under you — any run, anyone's, including
// yours. Lands you in the fork.
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);
}
}
async function openWindow() {
const override = $('hk-override').checked;
hideBanner();
try {
await api(`/runs/${state.runId}/windows`, { method: 'POST', body: { override } });
$('hk-override').checked = false;
} catch (e) {
if (e.status === 409 && e.detail?.hint) {
banner(`${e.message}\n${e.detail.hint}`, 'info');
} else {
banner(e.message);
}
}
render();
}
// two-click confirm — the second click within 5s fires; anything else disarms
let hkArmed = null;
async function runHousekeeping() {
const btn = $('hk-run');
if (hkArmed === null) {
btn.textContent = 'sure? click again to close & housekeep';
hkArmed = setTimeout(() => {
hkArmed = null;
btn.textContent = 'close window & housekeep';
}, 5000);
return;
}
clearTimeout(hkArmed);
hkArmed = null;
btn.textContent = 'close window & housekeep';
hideBanner();
try {
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
setHk('housekeeping…', '');
startPoll();
} catch (e) {
banner(e.message);
}
render();
}
// dry-run: the housekeeper reads the session log, the manifest lands
// in the pane — nothing applied, the window stays open
async function replayWrap() {
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}`;
$('hk-replay-log').hidden = false;
$('hk-replay-log').open = true;
} catch (e) {
banner(e.message);
}
setBusy(false);
}
function startPoll() {
stopPoll();
state.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 (state.poll) clearInterval(state.poll);
state.poll = null;
}
async function loadLog() {
try {
const log = await api(`/runs/${state.runId}/housekeeping/log`);
$('hk-log-content').textContent = log.content;
$('hk-log').hidden = false;
$('hk-log').open = true;
} catch {
$('hk-log').hidden = true;
}
}
// --- wiring --------------------------------------------------------------------------
$('home-link').addEventListener('click', (e) => { e.preventDefault(); navigate('/'); });
$('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() } });
try { localStorage.setItem(TOKEN_KEY, r.token); } catch {}
state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
banner(err.message);
}
});
$('invite-mint').addEventListener('click', async () => {
try {
const r = await api('/invites', { method: 'POST', body: {} });
$('invite-code').textContent = r.code; // shown once — it is never listed again
render();
} catch (e) {
banner(e.message);
}
});
$('new-run-btn').addEventListener('click', () => navigate('/new'));
$('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();
if (!name) return banner('the package needs a display name');
if (!pc) return banner('the main character needs a name');
try {
const r = await api('/runs', { method: 'POST', body: { package: state.pkg?.name, pc, name } });
navigate(`/runs/${r.run.id}/setup`);
} catch (err) {
banner(err.message);
}
});
$('setup-vars-save').addEventListener('click', async () => {
try {
await saveVars();
} catch (e) {
banner(e.message);
$('setup-vars-state').textContent = 'not saved';
}
});
$('setup-save').addEventListener('click', saveFile);
$('models-save').addEventListener('click', () => saveModels($('model-player'), $('model-housekeeper'), $('models-state')));
$('pm-save').addEventListener('click', () => saveModels($('pm-player'), $('pm-housekeeper'), $('pm-state')));
$('setup-delete').addEventListener('click', deleteDraft);
$('setup-edit').addEventListener('input', () => {
if (state.currentFile) stashDraft(state.currentFile);
$('setup-edit-state').textContent = 'unsaved';
renderHighlight();
});
$('setup-edit').addEventListener('scroll', () => {
$('edit-hl').scrollTop = $('setup-edit').scrollTop;
$('edit-hl').scrollLeft = $('setup-edit').scrollLeft;
});
$('setup-start').addEventListener('click', startRun);
$('savepkg-btn').addEventListener('click', saveAsPackage);
$('fork-btn').addEventListener('click', forkRun);
$('gm-send').addEventListener('click', sendTurn);
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendTurn(); }
});
$('ask-send').addEventListener('click', sendAnswer);
$('ask-answer').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnswer(); }
});
$('window-open').addEventListener('click', openWindow);
$('hk-run').addEventListener('click', runHousekeeping);
$('hk-replay').addEventListener('click', replayWrap);
$('paper-edit').addEventListener('click', editPaper);
$('paper-cancel').addEventListener('click', cancelPaperEdit);
$('paper-save').addEventListener('click', savePaper);
$('agenda-edit').addEventListener('click', editAgenda);
$('agenda-cancel').addEventListener('click', cancelAgendaEdit);
$('agenda-save').addEventListener('click', saveAgenda);
$('gm-notes').addEventListener('input', notesInput);
$('gm-notes').addEventListener('blur', saveNotes);
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
$('diag-btn').addEventListener('click', toggleDiag);
// --- boot --------------------------------------------------------------------------
// restore the session from the stored token; a rejected or absent
// token leaves me signed out, and every path leads to the claim view
(async () => {
if (authToken()) {
try {
const s = await api('/session');
state.me = s.user;
if (!state.me) { try { localStorage.removeItem(TOKEN_KEY); } catch {} }
} catch {
state.me = null;
}
}
render();
})();