spa modules and terminology: app.mjs split into flat es modules (router lifecycle, shared widgets, views own their state), mock smoke in test/; DICTIONARY.md rules the terms, four renames swept clean through the machinery - paper->status (run summary command is report now), window->session, wrap->housekeeping, context window->contwin; no dual-accepts by ruling, old data migrates once in the clerk (restore self-heals old dumps)
This commit is contained in:
+27
-1362
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
||||
// web/chrome.mjs — the shared page chrome: header identity, session
|
||||
// info, the context meter, the busy note, the notice banner.
|
||||
//
|
||||
// In-page notices only — no JS alert()/confirm(): they block the
|
||||
// embedded browser pane. Errors and notices land in the banner
|
||||
// instead; destructive confirms are two-click armed (widgets.mjs).
|
||||
|
||||
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
|
||||
export function setWho(me) {
|
||||
$('who').textContent = me ? `${me.name}${me.superuser ? ' · op' : ''}` : '';
|
||||
$('who').title = me?.id ?? '';
|
||||
}
|
||||
|
||||
export function setSessionInfo(text) {
|
||||
$('session-info').textContent = text;
|
||||
}
|
||||
|
||||
export 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.contwin ? `${pct}% — close & housekeep past 85%` : '';
|
||||
}
|
||||
|
||||
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;
|
||||
export 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);
|
||||
}
|
||||
|
||||
export function hideBanner() {
|
||||
$('banner').hidden = true;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// web/client.mjs — the REST client: the one fetch choke point.
|
||||
//
|
||||
// Every call is logged to the diagnostics (status + duration); a
|
||||
// rejected token ends the session — drop it and show the claim view;
|
||||
// every path leads there until a fresh one is claimed.
|
||||
|
||||
import { logEvent } from './log.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { render } from './router.mjs';
|
||||
|
||||
const TOKEN_KEY = 'rp-token';
|
||||
|
||||
export const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
|
||||
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 */ } };
|
||||
|
||||
export 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}`);
|
||||
if (res.status === 401 && path !== '/session' && authToken()) {
|
||||
clearToken();
|
||||
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;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// web/dom.mjs — the two DOM helpers everything else builds on.
|
||||
|
||||
export const $ = (id) => document.getElementById(id);
|
||||
|
||||
// one element, class and text in the common shape
|
||||
export function el(tag, cls, text) {
|
||||
const e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text !== undefined) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
+11
-41
@@ -10,7 +10,7 @@
|
||||
<header>
|
||||
<a id="home-link" href="/">rp-test</a>
|
||||
<span id="who"></span>
|
||||
<div id="window-info"></div>
|
||||
<div id="session-info"></div>
|
||||
<div id="context-meter" title="context usage of the last call">
|
||||
<div id="context-bar"><div id="context-fill"></div></div>
|
||||
<span id="context-label"></span>
|
||||
@@ -49,7 +49,7 @@
|
||||
<section id="view-new" hidden>
|
||||
<h1>new run</h1>
|
||||
<div id="package-pick">
|
||||
<p class="hint">a run is a copy of the package — everything stays editable until the window opens</p>
|
||||
<p class="hint">a run is a copy of the package — everything stays editable until the session opens</p>
|
||||
<div id="package-list"></div>
|
||||
</div>
|
||||
<form id="create-form" hidden>
|
||||
@@ -78,15 +78,7 @@
|
||||
<span id="setup-vars-state"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="setup-models">
|
||||
<h2>models — per-run, over the deployment defaults</h2>
|
||||
<label class="field">player <select id="model-player"></select></label>
|
||||
<label class="field">housekeeper <select id="model-housekeeper"></select></label>
|
||||
<div class="form-actions">
|
||||
<button id="models-save">save models</button>
|
||||
<span id="models-state"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="setup-models"></div>
|
||||
<div id="setup-savepkg">
|
||||
<input id="savepkg-name" placeholder="new package display name" autocomplete="off">
|
||||
<button id="savepkg-btn">save as package</button>
|
||||
@@ -115,32 +107,16 @@
|
||||
<aside id="play-aside">
|
||||
<section id="status-pane">
|
||||
<div class="pane-head">
|
||||
<h2>her paper</h2>
|
||||
<button id="paper-edit">edit</button>
|
||||
</div>
|
||||
<div id="paper"></div>
|
||||
<div id="paper-editor" hidden>
|
||||
<textarea id="paper-edit-area" rows="5" placeholder="one description per line — empty clears the paper"></textarea>
|
||||
<div class="pane-editor-actions">
|
||||
<button id="paper-save">save</button>
|
||||
<button id="paper-cancel">cancel</button>
|
||||
</div>
|
||||
<h2>her status</h2>
|
||||
</div>
|
||||
<div id="status"></div>
|
||||
<div id="conflict" hidden></div>
|
||||
</section>
|
||||
<section id="agenda-pane">
|
||||
<div class="pane-head">
|
||||
<h2>her agenda</h2>
|
||||
<button id="agenda-edit">edit</button>
|
||||
</div>
|
||||
<div id="agenda"></div>
|
||||
<div id="agenda-editor" hidden>
|
||||
<textarea id="agenda-edit-area" rows="4" placeholder="one item per line, top first — empty clears the agenda"></textarea>
|
||||
<div class="pane-editor-actions">
|
||||
<button id="agenda-save">save</button>
|
||||
<button id="agenda-cancel">cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="notes-pane">
|
||||
<div class="pane-head">
|
||||
@@ -152,11 +128,11 @@
|
||||
<section id="housekeeping">
|
||||
<h2>housekeeping</h2>
|
||||
<div id="hk-state"></div>
|
||||
<button id="hk-run" hidden>close window & housekeep</button>
|
||||
<label id="hk-override-wrap"><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label>
|
||||
<button id="window-open" hidden>open window</button>
|
||||
<button id="hk-replay" hidden title="run the housekeeper over the session log — nothing applied">dry-run the wrap</button>
|
||||
<details id="hk-log" hidden><summary>window log</summary><pre id="hk-log-content"></pre></details>
|
||||
<button id="hk-run" hidden>close session & housekeep</button>
|
||||
<label id="hk-override-row"><input type="checkbox" id="hk-override"> override: skip the unhousekept check</label>
|
||||
<button id="session-open" hidden>open session</button>
|
||||
<button id="hk-replay" hidden title="run the housekeeper over the session log — nothing applied">dry-run housekeeping</button>
|
||||
<details id="hk-log" hidden><summary>session log</summary><pre id="hk-log-content"></pre></details>
|
||||
<details id="hk-replay-log" hidden><summary>replay manifest</summary><pre id="hk-replay-content"></pre></details>
|
||||
</section>
|
||||
<section id="fork-pane">
|
||||
@@ -164,13 +140,7 @@
|
||||
<p class="hint">a copy of this run — yours to continue</p>
|
||||
<button id="fork-btn">fork this run</button>
|
||||
</section>
|
||||
<section id="models-pane" hidden>
|
||||
<h2>models</h2>
|
||||
<label class="field">player <select id="pm-player"></select></label>
|
||||
<label class="field">housekeeper <select id="pm-housekeeper"></select></label>
|
||||
<button id="pm-save">save models</button>
|
||||
<span id="pm-state"></span>
|
||||
</section>
|
||||
<section id="models-pane" hidden></section>
|
||||
</aside>
|
||||
|
||||
<footer>
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
// web/log.mjs — 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.
|
||||
|
||||
import { $ } from './dom.mjs';
|
||||
|
||||
const log = [];
|
||||
try { log.push(...JSON.parse(sessionStorage.getItem('diag') ?? '[]')); } catch { /* fresh or corrupt — start empty */ }
|
||||
|
||||
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);
|
||||
try { sessionStorage.setItem('diag', JSON.stringify(log)); } catch { /* storage full or blocked — the in-memory copy lives on */ }
|
||||
}
|
||||
|
||||
function renderDiag() {
|
||||
const d = $('diag');
|
||||
d.textContent = log.join('\n');
|
||||
d.scrollTop = d.scrollHeight;
|
||||
}
|
||||
|
||||
$('diag-btn').addEventListener('click', () => {
|
||||
const d = $('diag');
|
||||
d.hidden = !d.hidden;
|
||||
if (!d.hidden) renderDiag();
|
||||
});
|
||||
|
||||
window.addEventListener('error', (e) => logEvent('error', e.message));
|
||||
window.addEventListener('unhandledrejection', (e) => logEvent('error', `unhandled: ${e.reason?.message ?? e.reason}`));
|
||||
@@ -0,0 +1,59 @@
|
||||
// web/router.mjs — path routing and the view lifecycle.
|
||||
//
|
||||
// Views register { el, enter, leave? } at boot (app.mjs). render()
|
||||
// routes the path, then show() runs the previous view's leave and
|
||||
// the next view's enter — each view owns its own teardown, so the
|
||||
// router never has to know a pane's internals. Stale async work is
|
||||
// dropped by the seq guard: a view captures seq at enter and checks
|
||||
// it after every await.
|
||||
|
||||
import { $ } from './dom.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner, hideBanner, renderMeter, setWho, setSessionInfo } from './chrome.mjs';
|
||||
import { logEvent } from './log.mjs';
|
||||
|
||||
const views = {};
|
||||
export function registerViews(map) { Object.assign(views, map); }
|
||||
|
||||
export function navigate(p) {
|
||||
history.pushState({}, '', p);
|
||||
render();
|
||||
}
|
||||
|
||||
window.addEventListener('popstate', () => render());
|
||||
|
||||
export async function render() {
|
||||
const seq = ++state.seq;
|
||||
hideBanner();
|
||||
const p = location.pathname;
|
||||
let name = null;
|
||||
let arg = null;
|
||||
let m;
|
||||
if (p === '/') name = 'home';
|
||||
else if (p === '/new') name = 'new';
|
||||
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)\/setup$/))) { name = 'setup'; arg = m[1]; }
|
||||
else if ((m = p.match(/^\/runs\/([a-z0-9-]+)$/))) { name = 'play'; arg = m[1]; }
|
||||
else return navigate('/');
|
||||
if (!state.me) name = 'claim'; // signed out: every path leads to the claim
|
||||
await show(name, arg, seq);
|
||||
}
|
||||
|
||||
async function show(name, arg, seq) {
|
||||
const prev = state.view;
|
||||
if (prev && prev !== name && views[prev].leave) views[prev].leave();
|
||||
state.view = name;
|
||||
for (const [n, v] of Object.entries(views)) $(v.el).hidden = n !== name;
|
||||
document.body.classList.toggle('play', name === 'play');
|
||||
setWho(state.me);
|
||||
setSessionInfo('');
|
||||
renderMeter(null);
|
||||
await views[name].enter(arg, seq);
|
||||
}
|
||||
|
||||
// a run that vanished under us (deleted, 404): leave loudly for home.
|
||||
// render() clears the banner first — set it after the navigate.
|
||||
export function runGone(id, from) {
|
||||
navigate('/');
|
||||
banner(`run ${id} is gone — deleted?`);
|
||||
logEvent('nav', `left ${from} for home: run gone (404)`);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// web/state.mjs — the shared runtime state.
|
||||
//
|
||||
// Deliberately small: auth (me), the render sequence (seq — the
|
||||
// async race guard; a view captures it at enter and checks it after
|
||||
// every await), and the currently addressed run (runId — setup and
|
||||
// play both write here; saves address it). Everything else is
|
||||
// module-local to the view or widget that owns it.
|
||||
|
||||
export const state = {
|
||||
view: null, // the active view name ('claim' | 'home' | ...)
|
||||
seq: 0,
|
||||
me: null, // the signed-in user ({ id, name, superuser }) or null
|
||||
runId: null,
|
||||
};
|
||||
+7
-11
@@ -56,7 +56,7 @@ header {
|
||||
#home-link { color: var(--accent); text-decoration: none; font-weight: 600; letter-spacing: 0.04em; }
|
||||
#home-link:hover { text-decoration: underline; }
|
||||
|
||||
#window-info { color: var(--dim); font-size: 13px; margin-left: auto; white-space: nowrap; }
|
||||
#session-info { color: var(--dim); font-size: 13px; margin-left: auto; white-space: nowrap; }
|
||||
|
||||
#context-meter { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--dim); visibility: hidden; }
|
||||
body.play #context-meter { visibility: visible; }
|
||||
@@ -131,7 +131,6 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
|
||||
/* --- identity + admin --- */
|
||||
|
||||
#who { color: var(--dim); font-size: 13px; }
|
||||
#logout-btn { font-size: 11px; padding: 1px 8px; color: var(--dim); }
|
||||
|
||||
#claim-form { max-width: 480px; }
|
||||
|
||||
@@ -162,7 +161,6 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
|
||||
#models-pane .field { margin-bottom: 6px; }
|
||||
#models-pane .field select { flex: 1; }
|
||||
#models-pane button { width: 100%; margin-top: 4px; }
|
||||
#pm-state { color: var(--dim); font-size: 11px; }
|
||||
|
||||
/* the naming form (new run) and the vars box (setup) */
|
||||
#create-form { max-width: 560px; }
|
||||
@@ -183,7 +181,7 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
|
||||
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
|
||||
text-transform: uppercase; color: var(--dim); font-weight: normal;
|
||||
}
|
||||
#setup-vars-state, #models-state { color: var(--dim); font-size: 12px; }
|
||||
#setup-vars-state, .save-state { color: var(--dim); font-size: 12px; }
|
||||
#setup-models .field select { flex: 1; }
|
||||
|
||||
/* --- setup: the editor --- */
|
||||
@@ -323,15 +321,13 @@ body.play #play-aside { display: block; }
|
||||
.pane-head h2 { flex: 1; margin: 4px 0 8px; }
|
||||
.pane-head button { font-size: 11px; padding: 1px 8px; color: var(--dim); }
|
||||
|
||||
#paper { margin: 0; line-height: 1.5; }
|
||||
#paper.empty { color: var(--dim); font-style: italic; }
|
||||
#status { margin: 0; line-height: 1.5; }
|
||||
#status.empty { color: var(--dim); font-style: italic; }
|
||||
|
||||
#agenda-pane { margin-top: 16px; }
|
||||
#agenda { margin: 0; line-height: 1.5; }
|
||||
#agenda.empty { color: var(--dim); font-style: italic; }
|
||||
#agenda-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
|
||||
|
||||
#paper-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
|
||||
.pane-editor textarea { width: 100%; resize: vertical; font: 13px/1.5 inherit; }
|
||||
.pane-editor-actions { display: flex; gap: 6px; margin-top: 6px; }
|
||||
.pane-editor-actions button { font-size: 12px; padding: 2px 12px; }
|
||||
|
||||
@@ -358,13 +354,13 @@ body.play #play-aside { display: block; }
|
||||
#hk-log pre { white-space: pre-wrap; font-size: 12px; max-height: 40vh; overflow-y: auto; }
|
||||
|
||||
#housekeeping button { width: 100%; margin-top: 6px; }
|
||||
#hk-override-wrap { display: block; margin-top: 6px; color: var(--dim); font-size: 12px; }
|
||||
#hk-override-row { display: block; margin-top: 6px; color: var(--dim); font-size: 12px; }
|
||||
|
||||
/* --- footer (play) --- */
|
||||
|
||||
footer {
|
||||
grid-area: footer;
|
||||
display: flex; gap: 8px; padding: 10px 14px;
|
||||
gap: 8px; padding: 10px 14px;
|
||||
background: var(--panel); border-top: 1px solid var(--line);
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
// web/transcript.mjs — the transcript: register rendering and the
|
||||
// entry walk.
|
||||
//
|
||||
// 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>/<agenda> blocks riding GM turns and the
|
||||
// delta tags on player turns are machinery, not prose — they render
|
||||
// as chips and pane state, mirroring the live-context policy.
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
|
||||
// splits text into spans: *italics* = narration, **bold** = emphasis
|
||||
function renderSpans(target, 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);
|
||||
target.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);
|
||||
target.appendChild(i);
|
||||
} else {
|
||||
target.appendChild(document.createTextNode(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// one content block (a GM or player turn) -> DOM lines. extract pulls
|
||||
// the riding blocks (status/conflict/agenda) out of GM prose; the
|
||||
// delta tags on player turns always render as chips.
|
||||
function renderContent(target, 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) { target.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;
|
||||
target.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;
|
||||
target.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);
|
||||
target.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);
|
||||
target.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);
|
||||
target.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);
|
||||
}
|
||||
}
|
||||
target.appendChild(wrap);
|
||||
}
|
||||
return { status, conflict, agenda };
|
||||
}
|
||||
|
||||
// the entry walk. onConflict receives a conflict block found on a GM
|
||||
// turn — the play view owns where it lands (the status pane).
|
||||
export function renderTranscript(entries, { onConflict } = {}) {
|
||||
const t = $('transcript');
|
||||
t.textContent = '';
|
||||
const bundleParts = [];
|
||||
const flushBundle = () => {
|
||||
if (!bundleParts.length) return;
|
||||
const d = el('details', 'bundle');
|
||||
d.appendChild(el('summary', null, `session 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) onConflict?.(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 === 'session') text = `session 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 status ${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 === 'status') text = `status: lost ${JSON.stringify(e.applied?.lost ?? [])}, gained ${JSON.stringify(e.applied?.gained ?? [])}`;
|
||||
if (text) t.appendChild(el('div', 'machinery', text));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// web/view-claim.mjs — the invite claim: the only public screen.
|
||||
// A single-use invite code is exchanged for a persistent token; the
|
||||
// display name is a freeform label, collisions allowed.
|
||||
|
||||
import { $ } from './dom.mjs';
|
||||
import { api, setToken } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { logEvent } from './log.mjs';
|
||||
import { navigate } from './router.mjs';
|
||||
|
||||
export async function enter(arg, seq) {
|
||||
$('claim-code').value = '';
|
||||
$('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();
|
||||
}
|
||||
|
||||
$('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() } });
|
||||
setToken(r.token);
|
||||
state.me = r.user;
|
||||
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
banner(err.message);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
// web/view-home.mjs — home: the run list (display names, live state,
|
||||
// the ownership garnish) plus the superuser admin (invites, users).
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { navigate, render } from './router.mjs';
|
||||
import { armedButton } from './widgets.mjs';
|
||||
|
||||
export async function enter(arg, seq) {
|
||||
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`;
|
||||
}
|
||||
|
||||
function runStateText(r) {
|
||||
if (!r.lastSession) return 'draft — not started yet';
|
||||
if (r.open) return `session open${r.pendingAsk ? ' — waiting for your answer' : ''}`;
|
||||
if (r.lastSession !== r.lastHousekept) return 'session closed, never housekept';
|
||||
return 'session 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 '';
|
||||
}
|
||||
|
||||
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');
|
||||
// revocation destroys the identity — two-click armed, like
|
||||
// every destructive act
|
||||
armedButton(b, {
|
||||
label: 'revoke',
|
||||
confirm: 'sure? click again',
|
||||
fire: async () => {
|
||||
try { await api(`/users/${u.id}/revoke`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
|
||||
render();
|
||||
},
|
||||
});
|
||||
row.appendChild(b);
|
||||
}
|
||||
userList.appendChild(row);
|
||||
}
|
||||
}
|
||||
|
||||
$('new-run-btn').addEventListener('click', () => navigate('/new'));
|
||||
$('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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
// web/view-new.mjs — new run: the package picker, then the naming
|
||||
// form — the package display name plus the main character's name,
|
||||
// rolled from the dictionary, unused by any run. Runs of the same
|
||||
// package need distinct pc names.
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
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
|
||||
|
||||
export async function enter(arg, seq) {
|
||||
$('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);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
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;
|
||||
}
|
||||
|
||||
$('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: pkg?.name, pc, name } });
|
||||
navigate(`/runs/${r.run.id}/setup`);
|
||||
} catch (err) {
|
||||
banner(err.message);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,386 @@
|
||||
// web/view-play.mjs — the play surface: the transcript, her two
|
||||
// blocks (the status pane and the agenda pane — one widget, two
|
||||
// instances), the GM notepad, housekeeping (close session, the
|
||||
// dry-run replay), fork, and the input line.
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner, hideBanner, renderMeter, setBusy, setSessionInfo } from './chrome.mjs';
|
||||
import { navigate, render, runGone } from './router.mjs';
|
||||
import { logEvent } from './log.mjs';
|
||||
import { armedButton, modelList, modelsBox, paneEditor } from './widgets.mjs';
|
||||
import { renderTranscript } from './transcript.mjs';
|
||||
|
||||
// her two blocks, split along the seam: how she is (the status) vs
|
||||
// what she means to do (the agenda). Both render compact, mirroring
|
||||
// the wire formats the model cites.
|
||||
const statusPane = paneEditor({
|
||||
section: 'status-pane',
|
||||
body: 'status',
|
||||
empty: 'a blank sheet',
|
||||
placeholder: 'one description per line — empty clears the status',
|
||||
rows: 5,
|
||||
format: (items) => items.join(', '), // compact, mirroring the <status> wire format
|
||||
toText: (items) => items.join('\n'),
|
||||
fromText: (text) => text
|
||||
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+/, '').split(','))
|
||||
.map((x) => x.trim()).filter(Boolean),
|
||||
save: (items) => api(`/runs/${state.runId}/status`, { method: 'POST', body: { items } }),
|
||||
});
|
||||
const agendaPane = paneEditor({
|
||||
section: 'agenda-pane',
|
||||
body: 'agenda',
|
||||
empty: 'a clear head',
|
||||
placeholder: 'one item per line, top first — empty clears the agenda',
|
||||
rows: 4,
|
||||
// the queue numbered from the top, exactly as the model cites it
|
||||
format: (items) => items.map((d, i) => `${i}. ${d}`).join('; '),
|
||||
toText: (items) => items.join('\n'),
|
||||
fromText: (text) => text
|
||||
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
|
||||
.map((x) => x.trim()).filter(Boolean),
|
||||
save: (items) => api(`/runs/${state.runId}/agenda`, { method: 'POST', body: { items } }),
|
||||
});
|
||||
|
||||
const models = modelsBox('models-pane', { title: 'models' });
|
||||
|
||||
export function leave() {
|
||||
saveNotes();
|
||||
stopPoll();
|
||||
$('ask-modal').close();
|
||||
}
|
||||
|
||||
export async function enter(id, seq) {
|
||||
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 = '';
|
||||
$('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) return runGone(id, location.pathname);
|
||||
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
|
||||
setSessionInfo(`${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;
|
||||
}
|
||||
|
||||
setSessionInfo((detail.open
|
||||
? `${detail.display} — session ${detail.session}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
|
||||
: `${detail.display} — no open session`)
|
||||
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating'));
|
||||
renderMeter(detail);
|
||||
statusPane.set(detail.status);
|
||||
agendaPane.set(detail.agenda);
|
||||
$('conflict').hidden = true;
|
||||
|
||||
// spectator mode: read everything, mutate nothing — the fork is the
|
||||
// way in. Ownerless runs are spectators for everyone alike.
|
||||
statusPane.setEditable(mine);
|
||||
agendaPane.setEditable(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, { onConflict: showConflict });
|
||||
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 session was opened directly
|
||||
if (beatNeeded) await offerBeat(id, seq);
|
||||
|
||||
// controls
|
||||
$('session-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;
|
||||
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
function showConflict(text) {
|
||||
const c = $('conflict');
|
||||
c.textContent = `conflict: ${text}`;
|
||||
c.hidden = false;
|
||||
}
|
||||
|
||||
// --- the GM's notepad: always on screen, auto-saved -------------------
|
||||
//
|
||||
// A debounced save (1s after the last keystroke, immediate on blur),
|
||||
// flushed when leaving the play view or switching runs. gm.md never
|
||||
// reaches any model — this is the GM's own notes.
|
||||
|
||||
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 session 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 setHk(stateText, cls) {
|
||||
const h = $('hk-state');
|
||||
h.textContent = stateText;
|
||||
h.className = cls ?? '';
|
||||
}
|
||||
|
||||
function renderHk(hk) {
|
||||
if (hk.state === 'running') {
|
||||
setHk('housekeeping…', '');
|
||||
startPoll();
|
||||
return;
|
||||
}
|
||||
stopPoll();
|
||||
if (hk.state === 'applied') {
|
||||
setHk(`applied — session ${hk.session ?? ''}\nnext session 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();
|
||||
}
|
||||
|
||||
// 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 openSession() {
|
||||
const override = $('hk-override').checked;
|
||||
hideBanner();
|
||||
try {
|
||||
await api(`/runs/${state.runId}/sessions`, { 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();
|
||||
}
|
||||
|
||||
// dry-run: the housekeeper reads the session log, the manifest lands
|
||||
// in the pane — nothing applied, the session stays open
|
||||
async function replayHousekeeping() {
|
||||
setBusy(true, 'the housekeeper reads…');
|
||||
try {
|
||||
const r = await api(`/runs/${state.runId}/housekeeping/replay`, { method: 'POST', body: {} });
|
||||
$('hk-replay-content').textContent = r.parsed
|
||||
? JSON.stringify(r.manifest, null, 2)
|
||||
: `${r.reason}\n\nraw output: ${r.file}`;
|
||||
$('hk-replay-log').hidden = false;
|
||||
$('hk-replay-log').open = true;
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
}
|
||||
setBusy(false);
|
||||
}
|
||||
|
||||
// --- housekeeping poll + log -------------------------------------------
|
||||
|
||||
let poll = null;
|
||||
|
||||
function startPoll() {
|
||||
stopPoll();
|
||||
poll = setInterval(async () => {
|
||||
if (!state.runId || state.view !== 'play') return stopPoll();
|
||||
const hk = await api(`/runs/${state.runId}/housekeeping`).catch(() => null);
|
||||
if (hk && hk.state !== 'running') render();
|
||||
}, 3000);
|
||||
}
|
||||
function stopPoll() {
|
||||
if (poll) clearInterval(poll);
|
||||
poll = null;
|
||||
}
|
||||
|
||||
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 ---
|
||||
|
||||
armedButton($('hk-run'), {
|
||||
label: 'close session & housekeep',
|
||||
confirm: 'sure? click again to close & housekeep',
|
||||
fire: async () => {
|
||||
hideBanner();
|
||||
try {
|
||||
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
|
||||
setHk('housekeeping…', '');
|
||||
startPoll();
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
}
|
||||
render();
|
||||
},
|
||||
});
|
||||
|
||||
$('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(); }
|
||||
});
|
||||
$('session-open').addEventListener('click', openSession);
|
||||
$('hk-replay').addEventListener('click', replayHousekeeping);
|
||||
$('fork-btn').addEventListener('click', forkRun);
|
||||
$('gm-notes').addEventListener('input', notesInput);
|
||||
$('gm-notes').addEventListener('blur', saveNotes);
|
||||
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
|
||||
@@ -0,0 +1,319 @@
|
||||
// web/view-setup.mjs — the draft editor: the full assembly in bundle
|
||||
// order (the repo-fed prompts read-only, the run's craft editable,
|
||||
// config read-only), the prompt-declared $TOKEN inputs, per-run
|
||||
// models, and the two exits — save as package (publishes it) or
|
||||
// start (opens the session, sends turn-0).
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { navigate, runGone } from './router.mjs';
|
||||
import { armedButton, modelList, modelsBox } from './widgets.mjs';
|
||||
|
||||
// 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 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 = {};
|
||||
|
||||
const models = modelsBox('setup-models', { title: 'models — per-run, over the deployment defaults' });
|
||||
|
||||
export async function enter(id, seq) {
|
||||
state.runId = id;
|
||||
drafts = {};
|
||||
currentFile = null;
|
||||
let detail, filesResp, prompts;
|
||||
try {
|
||||
[detail, filesResp, prompts] = await Promise.all([
|
||||
api(`/runs/${id}`),
|
||||
api(`/runs/${id}/files`),
|
||||
api('/prompts'),
|
||||
]);
|
||||
} catch (e) {
|
||||
if (e.status === 404) return runGone(id, location.pathname);
|
||||
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
|
||||
|
||||
files = filesResp.files;
|
||||
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 session opens`;
|
||||
$('setup-start').disabled = false;
|
||||
$('setup-start').textContent = 'start';
|
||||
|
||||
// prompt vars: the $TOKENS the prompts declare, filled per run
|
||||
const vars = scanVars(prompts, files);
|
||||
let currentVars = {};
|
||||
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings — empty vars */ }
|
||||
const varsList = $('setup-vars-list');
|
||||
varsList.textContent = '';
|
||||
$('setup-vars').hidden = !vars.length;
|
||||
$('setup-vars-state').textContent = '';
|
||||
for (const tok of 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;
|
||||
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
|
||||
|
||||
const nav = $('setup-files');
|
||||
nav.textContent = '';
|
||||
fileSpecs = {};
|
||||
for (const e of EDIT_LIST) {
|
||||
const runFile = files[e.name];
|
||||
const spec = {
|
||||
...e,
|
||||
exists: e.source === 'repo' ? true : !!runFile?.exists,
|
||||
content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''),
|
||||
};
|
||||
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 = '';
|
||||
}
|
||||
|
||||
// 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';
|
||||
}
|
||||
|
||||
function selectFile(f) {
|
||||
const prev = currentFile;
|
||||
if (prev === f) return;
|
||||
if (prev && fileSpecs[prev]?.mode === 'rw') stashDraft(prev);
|
||||
currentFile = f;
|
||||
const spec = fileSpecs[f] ?? { mode: 'rw', source: 'run', exists: false };
|
||||
const content = spec.source === 'repo'
|
||||
? (repoPrompts[f] ?? '')
|
||||
: (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) => ({ '&': '&', '<': '<', '>': '>' }[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 (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
|
||||
const v = $('setup-edit').value;
|
||||
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
|
||||
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', drafts[name] !== undefined);
|
||||
item.classList.toggle('current', name === currentFile);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveFile() {
|
||||
const f = currentFile;
|
||||
if (!f) return;
|
||||
$('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;
|
||||
files[f].exists = true;
|
||||
delete 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(currentFile);
|
||||
for (const [f, content] of Object.entries({ ...drafts })) {
|
||||
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
|
||||
files[f].content = content;
|
||||
files[f].exists = true;
|
||||
delete 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;
|
||||
}
|
||||
|
||||
async function startRun() {
|
||||
const id = state.runId;
|
||||
const btn = $('setup-start');
|
||||
// the prompts' own inputs must be filled — the guard at session-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}/sessions`, { method: 'POST', body: {} });
|
||||
opened = true;
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
}
|
||||
if (opened && 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}`);
|
||||
}
|
||||
|
||||
// --- wiring ---
|
||||
|
||||
// delete this draft: two-click armed (destructive), then home.
|
||||
// A played run refuses server-side — stories are deleted by hand.
|
||||
armedButton($('setup-delete'), {
|
||||
label: 'delete draft',
|
||||
confirm: 'sure? click again to delete',
|
||||
fire: async () => {
|
||||
try {
|
||||
await api(`/runs/${state.runId}`, { method: 'DELETE' });
|
||||
navigate('/');
|
||||
} catch (e) {
|
||||
banner(e.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);
|
||||
$('setup-edit').addEventListener('input', () => {
|
||||
if (currentFile) stashDraft(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);
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
// web/widgets.mjs — the small factories the views share.
|
||||
//
|
||||
// Three patterns that were hand-copied per use, now one each:
|
||||
// - armedButton: the two-click confirm (no JS confirm() — it blocks
|
||||
// the embedded pane; every destructive act is armed instead)
|
||||
// - paneEditor: the status/agenda pattern — a body line, an edit
|
||||
// button, an inline editor; the section shell stays in index.html
|
||||
// - modelsBox: the per-run player/housekeeper selects over the
|
||||
// upstream listing; setup and the play aside each carry one
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { render } from './router.mjs';
|
||||
|
||||
// two-click confirm — the second click within 5s fires; anything
|
||||
// else disarms. Each button owns its own arm state.
|
||||
export function armedButton(btn, { label, confirm, fire }) {
|
||||
let timer = null;
|
||||
btn.addEventListener('click', async () => {
|
||||
if (timer === null) {
|
||||
btn.textContent = confirm;
|
||||
timer = setTimeout(() => { timer = null; btn.textContent = label; }, 5000);
|
||||
return;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
btn.textContent = label;
|
||||
await fire();
|
||||
});
|
||||
}
|
||||
|
||||
// a pane: body line + edit button + inline editor. save(items)
|
||||
// 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.
|
||||
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);
|
||||
const editor = el('div', 'pane-editor');
|
||||
editor.hidden = true;
|
||||
const area = el('textarea');
|
||||
area.rows = rows;
|
||||
area.placeholder = placeholder;
|
||||
const actions = el('div', 'pane-editor-actions');
|
||||
const saveBtn = el('button', null, 'save');
|
||||
const cancelBtn = el('button', null, 'cancel');
|
||||
actions.appendChild(saveBtn);
|
||||
actions.appendChild(cancelBtn);
|
||||
editor.appendChild(area);
|
||||
editor.appendChild(actions);
|
||||
bodyEl.after(editor); // before anything that follows the body (#conflict on the status pane)
|
||||
|
||||
let items = [];
|
||||
let mayEdit = false;
|
||||
let open = false;
|
||||
|
||||
const sync = () => {
|
||||
bodyEl.hidden = open;
|
||||
editBtn.hidden = open || !mayEdit;
|
||||
editor.hidden = !open;
|
||||
};
|
||||
const renderBody = () => {
|
||||
bodyEl.textContent = items.length ? format(items) : empty;
|
||||
bodyEl.classList.toggle('empty', !items.length);
|
||||
};
|
||||
const openEditor = () => {
|
||||
area.value = toText(items);
|
||||
open = true;
|
||||
sync();
|
||||
area.focus();
|
||||
};
|
||||
const cancel = () => { open = false; sync(); };
|
||||
const doSave = async () => {
|
||||
const next = fromText(area.value);
|
||||
try {
|
||||
await save(next);
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
return; // stay in the editor — nothing was changed
|
||||
}
|
||||
items = next;
|
||||
cancel();
|
||||
render(); // the server's truth re-renders the panes
|
||||
};
|
||||
|
||||
editBtn.addEventListener('click', openEditor);
|
||||
cancelBtn.addEventListener('click', cancel);
|
||||
saveBtn.addEventListener('click', doSave);
|
||||
|
||||
return {
|
||||
set(next) { items = next ?? []; renderBody(); },
|
||||
setEditable(ok) { mayEdit = ok; cancel(); },
|
||||
reset() { cancel(); },
|
||||
get items() { return items; },
|
||||
};
|
||||
}
|
||||
|
||||
// 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;
|
||||
export async function modelList() {
|
||||
if (!cachedModels) cachedModels = 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.
|
||||
function fillSelect(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 ?? '';
|
||||
}
|
||||
|
||||
// the models box: player/housekeeper selects + save, posting the
|
||||
// per-run overrides. The mount keeps its id — the CSS panels it.
|
||||
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 pField = el('label', 'field', 'player ');
|
||||
pField.appendChild(playerSel);
|
||||
const hField = el('label', 'field', 'housekeeper ');
|
||||
hField.appendChild(houseSel);
|
||||
root.appendChild(pField);
|
||||
root.appendChild(hField);
|
||||
const saveBtn = el('button', null, 'save models');
|
||||
const saveState = el('span', 'save-state');
|
||||
const actions = el('div', 'form-actions');
|
||||
actions.appendChild(saveBtn);
|
||||
actions.appendChild(saveState);
|
||||
root.appendChild(actions);
|
||||
saveBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
await api(`/runs/${state.runId}/model`, {
|
||||
method: 'POST',
|
||||
body: { player: playerSel.value || null, housekeeper: houseSel.value || null },
|
||||
});
|
||||
saveState.textContent = 'saved';
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
saveState.textContent = 'not saved';
|
||||
}
|
||||
});
|
||||
return {
|
||||
fill(models, defaults, list) {
|
||||
fillSelect(playerSel, models?.player ?? null, list, defaults?.player);
|
||||
fillSelect(houseSel, models?.housekeeper ?? null, list, defaults?.housekeeper);
|
||||
saveState.textContent = '';
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user