Files
tiny-worlds/web/widgets.mjs
T
mute eefb721675 the sheet round: the GM's ledger of arbitrated run state -- the second state channel, split from status and agenda by truth model (GM, 2026-11-17). The rulings first: status and agenda are narrative self-report (their truth is "she said so", the scan caches her latest words); the sheet is actual run state (its truth is "the GM set so", the record IS the truth event -- nothing cached from anyone's words). The override channel promoted to a standing section, and that precedent decided the presentation: the sheet renders as its OWN authoritative system chunk at the freshest end, never a canon-point stamp, which would read as her words -- the same reason the override composes as hers and the sheet never does. Schemaless JSON in the tag (the mind-verb philosophy: the substrate teaches the channel, the package teaches the vocabulary -- the invariants rule the GM wrote is one universal paragraph with deliberately non-box examples, clothes and grades, and the propose-additions line as her schema-evolution channel); details learnt in-place; NO package gating -- the channel is universal and "optional, if given" makes the invariant forward-compatible in every bundle that never sets one. The build: a sheet record rides the GM turn like the override (readSheet: object-ness is the route's only law, 400 loud on arrays and scalars, nothing appended; OOC turns refuse it exactly like block edits); scanState derives newest-wins whole-set -- an absent key drops, never keeps, and {} is a live empty ledger (a truthy check, never falsy); the boundary state note carries it across stops and the dormant read path serves it; renderView appends the chunk once per assembly so one live copy holds by construction; the guard is the <model> sibling (an emitted <sheet> conflicts with "the GM's ledger -- propose changes in prose", healed in-turn, cap 3, and her emission never applies -- the scan holds the GM's record); every strip surface learned the tag (the view's STRIP_HERS, the story's verbs, the table's chip regex -- the standing grep-every-strip-list lesson, applied); and the web gains sheetEditor, the paneEditor's JSON sibling in widgets.mjs (same stage/pending/discard pattern, bad JSON refuses at the stage), the third pane in the aside, the send attaching body.sheet, and [sheet] machinery lines on both table and raw walks. The mock's sheet-guard branch is CUE-KEYED, not position-keyed: the carried tail shifts the script's counts (session 4's log starts the script over -- the battery's first attempt landed on the ask position and crashed renderView on the unpaired call; the battery now answers the script ask and moves on), while a marked GM turn is immune to every shift -- mockModel reads the view, the marked turn earns the emission, the conflict it earns earns the plain-prose heal. check-reminder is sheet-aware (the chunk is a legitimate third system surface; the count and freshest-end assertions tolerate exactly one, and the freshest-end check now allows her latest reply and/or the chunk to follow the reminder). Verified: smoke ALL PASS with +15 sheet assertions (newest-wins, whole-set semantics, the chunk one-live-copy -- ANCHORED with startsWith because the invariants bundle itself mentions the tag and a bare regex matches it twice, an honest test bug caught by an honest test), the guard's conflict and heal with her emission kept verbatim in the raw log and never applied, the view and story strips, the empty ledger rendering its chunk, the boundary note carrying the sheet, the dormant read deriving it, and session 5 deriving it from the carried note end to end), restart + reminder checks green, typecheck green on both programs, check-repo clean (it caught the round's own prose twice: "window" is a retired term in README, the contwin vocabulary wins), and a browser pass over the pane end to end with zero console errors -- staging, the pending marker, the ride, the scan re-render, and both machinery lines on the table. Docs: README's protocol passage carries the sheet with the numbers-live-on-the-sheet line (prose numbers die with the contwin; sheet numbers ride the scan forever) -- NOT in the memory tiers table, where the first draft wrongly put it (the GM's ruling: the sheet belongs in neither memories nor records); the identity tier lost its loose "character sheet" name now that the term is technical; DICTIONARY gains the sheet entry with the history line (dice retired into variant literature, sheets arrived as the state machinery -- the tabletop metaphor completing while its realism stays advisory, players hold their own pencils in the real thing and we don't, for drift); ROADMAP parks the bookkeeper extension (the housekeeper's arithmetic sibling: reads the setting's rules prose and the latest turns, computes the ledger delta from a purchase in her prose, lands it as a STAGED edit -- applied on the GM's next turn or discarded; sheet-only authority, curator fallback, per-package opt-in because an agent cannot bookkeep what is not arithmetic). The GM's prompt-side edits ride the same commit: invariants' "Character's sheet" section (the universal rule, the trailing-clause flag taken in review), the reminder's inventory line gaining "the sheet (optional)", and la caramba's gm.md lore updates. The box package (the first consumer) and detention stay untracked WIP, untouched. The 2026-11-17 roadmap audit rides the same commit (GM: "done items can retire"): retired outright -- the SPA-vs-bridge and voice-examples decisions (long resolved) and steal items #1, #3, #4, #8, #11 (done, or in #8's case never work -- the housekeeper model is per-run selection, built); retired with tombstones -- the multiuser section (built 2026-11-14, the rulings live in DECISIONS #22-31 and README, the lifecycle tail kept visible) and the SPA v1 section (all four phases done, the API sketch superseded by README's living API docs, the substrate doctrine in README), with the one unbuilt design it held -- the turn-surgery saga rule -- surviving as its own bullet cross-referenced at steal #2; amended in place, dated -- seed.json (dead, successors named: the authored carryover and memory.json), turn-0.md (dead: her authored opening turn), the upstream model listing (never queried in play since discovery), the delta-tag transport (the full-block protocol, the sheet named), the service step (multiuser built, hosting remains), the carryover editor (the raw file-editor surface exists, the purpose-built UI stays deferred); kept -- the operator's queue, the landscape and receipts, the live constraints, the open steals with numbering preserved so cross-references resolve, the deferred tasks, the distant points, the rejections, the notes. 582 lines to 338; the first deletion pass duplicated the steal-list header and the verification re-read caught it
2026-11-17 22:50:59 +00:00

345 lines
16 KiB
JavaScript

// 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 edit stages, the send rides it
// with the turn; the section shell stays in index.html
// - modelsBox: the per-run player/housekeeper selects over the
// registry plus the sampling knobs (knobs.mjs owns the knob row
// and its definitions table); 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 { knobsBox } from './knobs.mjs';
// two-click confirm -- the second click within 5s fires; anything
// else disarms. Each button owns its own arm state.
/** @param {HTMLElement} btn @param {{ label: string, confirm: string, fire: () => Promise<void> }} opts */
export function armedButton(btn, { label, confirm, fire }) {
/** @type {?ReturnType<typeof setTimeout>} */ 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. The edit does
// not save anywhere -- it STAGES a block edit that rides the next
// GM turn (the server logs the override on the turn; the composition
// overwrites her newest blocks with it). setEditable(false) is the
// not-live state: no edit button, an open editor cancels, a staged
// edit drops -- dormancy edits the carryover, not the panes.
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[] }} PaneOpts */
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[], staged: ?string[], clearStaged: () => void }} Pane */
/** @param {PaneOpts} opts @returns {Pane} */
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText }) {
const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body;
const editBtn = el('button', null, 'edit');
(/** @type {HTMLElement} */ (sec.querySelector('.pane-head'))).appendChild(editBtn);
const editor = el('div', 'pane-editor');
editor.hidden = true;
const area = /** @type {HTMLTextAreaElement} */ (el('textarea'));
area.rows = rows;
area.placeholder = placeholder;
const actions = el('div', 'pane-editor-actions');
const saveBtn = el('button', null, 'stage');
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)
const pending = el('div', 'pane-pending');
pending.hidden = true;
pending.appendChild(el('span', null, 'edited -- rides your next turn'));
const dropBtn = el('button', null, 'discard edit');
pending.appendChild(dropBtn);
editor.after(pending);
/** @type {string[]} */ let items = [];
/** @type {?string[]} */ let staged = null;
let mayEdit = false;
let open = false;
const sync = () => {
bodyEl.hidden = open;
editBtn.hidden = open || !mayEdit;
editor.hidden = !open;
pending.hidden = staged === null;
};
const renderBody = () => {
const show = staged ?? items;
bodyEl.textContent = show.length ? format(show) : empty;
bodyEl.classList.toggle('empty', !show.length);
};
const openEditor = () => {
area.value = toText(staged ?? items);
open = true;
sync();
area.focus();
};
const cancel = () => { open = false; sync(); };
const doSave = () => { staged = fromText(area.value); cancel(); renderBody(); };
const dropStaged = () => { staged = null; sync(); renderBody(); };
editBtn.addEventListener('click', openEditor);
cancelBtn.addEventListener('click', cancel);
saveBtn.addEventListener('click', doSave);
dropBtn.addEventListener('click', dropStaged);
return {
set(next) { items = next ?? []; renderBody(); },
setEditable(ok) { mayEdit = ok; cancel(); if (!ok) dropStaged(); },
reset() { cancel(); dropStaged(); },
get items() { return items; },
get staged() { return staged; },
clearStaged: dropStaged,
};
}
// the sheet pane: the same stage-and-ride pattern as the block panes,
// JSON-typed -- the GM's ledger of arbitrated run state (GM,
// 2026-11-17: the model reads it, never writes it; her proposals
// arrive in prose). A record is a whole set: staging replaces the
// entire object, an empty object is a deliberate empty ledger. Bad
// JSON refuses at the stage -- the server would refuse it at the turn.
/** @typedef {{ set: (next?: ?Record<string, unknown>) => void, setEditable: (ok: boolean) => void, reset: () => void, staged: ?Record<string, unknown>, clearStaged: () => void }} SheetPane */
/** @param {string} section @param {string} body @returns {SheetPane} */
export function sheetEditor(section, body) {
const sec = $(section);
const bodyEl = $(body);
const editBtn = el('button', null, 'edit');
(/** @type {HTMLElement} */ (sec.querySelector('.pane-head'))).appendChild(editBtn);
const editor = el('div', 'pane-editor');
editor.hidden = true;
const area = /** @type {HTMLTextAreaElement} */ (el('textarea'));
area.rows = 6;
area.placeholder = 'the sheet is JSON -- the GM\'s ledger of the run\'s objective state';
const actions = el('div', 'pane-editor-actions');
const saveBtn = el('button', null, 'stage');
const cancelBtn = el('button', null, 'cancel');
actions.appendChild(saveBtn);
actions.appendChild(cancelBtn);
editor.appendChild(area);
editor.appendChild(actions);
bodyEl.after(editor);
const pending = el('div', 'pane-pending');
pending.hidden = true;
pending.appendChild(el('span', null, 'edited -- rides your next turn'));
const dropBtn = el('button', null, 'discard edit');
pending.appendChild(dropBtn);
editor.after(pending);
/** @type {?Record<string, unknown>} */ let sheet = null; // the current truth (never a falsy check -- {} is a live empty ledger)
/** @type {?Record<string, unknown>} */ let staged = null;
let mayEdit = false;
let open = false;
const sync = () => {
bodyEl.hidden = open;
editBtn.hidden = open || !mayEdit;
editor.hidden = !open;
pending.hidden = staged === null;
};
const renderBody = () => {
const show = staged ?? sheet;
bodyEl.textContent = show == null ? 'nothing tracked' : JSON.stringify(show, null, 2);
bodyEl.classList.toggle('empty', show == null);
};
const openEditor = () => {
area.value = JSON.stringify(staged ?? sheet ?? {}, null, 2);
open = true;
sync();
area.focus();
};
const cancel = () => { open = false; sync(); };
const doSave = () => {
try {
const parsed = JSON.parse(area.value);
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
banner('the sheet wants a JSON object');
return;
}
staged = /** @type {Record<string, unknown>} */ (parsed);
} catch (e) {
banner(`the sheet is JSON -- ${String(e.message ?? e).split('\n')[0]}`);
return;
}
cancel();
renderBody();
};
const dropStaged = () => { staged = null; sync(); renderBody(); };
editBtn.addEventListener('click', openEditor);
cancelBtn.addEventListener('click', cancel);
saveBtn.addEventListener('click', doSave);
dropBtn.addEventListener('click', dropStaged);
return {
set(next) { sheet = next ?? null; renderBody(); },
setEditable(ok) { mayEdit = ok; cancel(); if (!ok) dropStaged(); },
reset() { cancel(); dropStaged(); },
get staged() { return staged; },
clearStaged: dropStaged,
};
}
// the model registry, fetched once per session -- the selectors read
// the saved registry, never the live provider (discovery is the op's
// manual act; a listing fetch every render would hammer the endpoint
// for a list that rarely changes)
/** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ let cachedRegistry = null;
/** @returns {Promise<import('./shapes.mjs').ModelsRegistryResponse>} */
export async function modelList() {
if (!cachedRegistry) cachedRegistry = /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => /** @type {import('./shapes.mjs').ModelsRegistryResponse} */ ({ phase: 'none', discovered: null, refined: null, curator: null, defaults: {}, models: [], job: null })));
return cachedRegistry;
}
// a context ceiling as the short human form: 1048576 -> "1M",
// 524288 -> "512K". Null when the provider stated nothing.
/** @param {?number} tokens @returns {?string} */
export function fmtCeiling(tokens) {
if (tokens == null || !Number.isFinite(tokens) || tokens <= 0) return null;
return tokens >= 1048576 ? `${Math.round(tokens / 1048576)}M` : `${Math.round(tokens / 1024)}K`;
}
// A select's "" value means "deployment default"; a current override
// missing from the registry stays selectable, so a stale pick never
// silently rewrites itself. One plain list, sorted by id (GM,
// 2026-11-16: the family grouping left the user guessing what a
// family name means, and the curator's tier labels only made sense
// inside their groups -- the id is the self-describing name). The
// input ceiling rides along -- the user picks against the contwin,
// so the context limit belongs in the open.
/** @param {HTMLSelectElement} sel @param {?string} current @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {?string} [def] */
function fillSelect(sel, current, reg, def) {
sel.textContent = '';
/** @param {string} v @param {string} label */
const mk = (v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
sel.appendChild(o);
};
mk('', `deployment default${def ? ` -- ${def}` : ' (unset)'}`);
const usableModels = reg.models.filter((m) => m.inference !== false && (m.roles?.player ?? true));
const extras = current && !usableModels.some((m) => m.id === current) ? [current] : [];
for (const m of [...usableModels].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
const ceil = fmtCeiling(m.input);
mk(m.id, ceil ? `${m.id} \u00b7 ${ceil}` : m.id);
}
for (const x of extras) mk(x, `${x} (not in the registry)`);
sel.value = current ?? '';
}
// the models box: player/housekeeper selects over the registry, the
// sampling knobs per role (one shared hint bar under both rows), and
// one save. The mount keeps its id -- the CSS panels it. The knob
// rows rebuild when the model select changes: the effort knob's
// default is measured per model, so switching the model switches the
// honest default.
/** @param {string|HTMLElement} mount @param {{ title: string }} opts */
export function modelsBox(mount, { title }) {
const root = typeof mount === 'string' ? $(mount) : mount;
root.textContent = '';
root.appendChild(el('h2', null, title));
const playerSel = /** @type {HTMLSelectElement} */ (el('select'));
const houseSel = /** @type {HTMLSelectElement} */ (el('select'));
const pField = el('label', 'field', 'player ');
pField.appendChild(playerSel);
const hField = el('label', 'field', 'housekeeper ');
hField.appendChild(houseSel);
root.appendChild(pField);
root.appendChild(hField);
const knobHint = el('div', 'knob-hint'); // one bar, both roles
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|string|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
root.appendChild(playerKnobs.wrap);
root.appendChild(houseKnobs.wrap);
root.appendChild(knobHint);
// the latest fill's inputs -- the select-change refresh rebuilds
// the knob rows against them (the effort context follows the
// newly-picked model)
/** @type {?{ params: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, paramDefaults: ?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }, reg: import('./shapes.mjs').ModelsRegistryResponse }} */ let last = null;
// the effort knob's context: the currently-selected model's
// measured ladder (null when the registry has none for it)
/** @param {'player'|'housekeeper'} role @param {import('./shapes.mjs').ModelsRegistryResponse} reg @returns {?{ measured: Record<string, number>, fallback: ?string }} */
const effortOf = (role, reg) => {
const id = (role === 'player' ? playerSel.value : houseSel.value)
|| reg.defaults?.[role] || null;
const m = id ? reg.models.find((x) => x.id === id) : null;
return m?.efforts ? { measured: m.efforts, fallback: m.effortDefault ?? null } : null;
};
/** rebuild both knob rows against the current selects and the
* latest fill (fill and select-change both land here) */
function rebuildKnobs() {
if (!last) return;
const pk = knobsBox('player', last.params?.player ?? undefined, last.paramDefaults?.player ?? undefined, knobHint, effortOf('player', last.reg));
const hk = knobsBox('housekeeper', last.params?.housekeeper ?? undefined, last.paramDefaults?.housekeeper ?? undefined, knobHint, effortOf('housekeeper', last.reg));
playerKnobs.wrap.replaceWith(pk.wrap);
houseKnobs.wrap.replaceWith(hk.wrap);
playerKnobs = pk;
houseKnobs = hk;
}
playerSel.addEventListener('change', rebuildKnobs);
houseSel.addEventListener('change', rebuildKnobs);
if (!root.querySelector('.registry-hint')) {
const hint = el('div', 'hint registry-hint', '');
root.appendChild(hint);
}
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 {
// the knob read throws on an empty override -- same banner, nothing sent
const params = { player: playerKnobs.read(), housekeeper: houseKnobs.read() };
await api(`/runs/${state.runId}/model`, {
method: 'POST',
body: {
player: playerSel.value || null,
housekeeper: houseSel.value || null,
params,
},
});
saveState.textContent = 'saved';
} catch (e) {
banner(e.message);
saveState.textContent = 'not saved';
}
});
return {
/** @param {?{ player?: ?string, housekeeper?: ?string }} models @param {?{ player?: ?string, housekeeper?: ?string }} defaults @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} params @param {?{ player?: ?import('../server/shapes.mjs').RoleParams, housekeeper?: ?import('../server/shapes.mjs').RoleParams }} paramDefaults @param {import('./shapes.mjs').ModelsRegistryResponse} reg */
fill(models, defaults, params, paramDefaults, reg) {
fillSelect(playerSel, models?.player ?? null, reg, defaults?.player);
fillSelect(houseSel, models?.housekeeper ?? null, reg, defaults?.housekeeper);
last = { params: params ?? null, paramDefaults: paramDefaults ?? null, reg };
rebuildKnobs();
const hint = root.querySelector('.registry-hint');
if (hint) {
hint.textContent = reg.phase === 'none'
? 'no models discovered -- the op runs discovery from the admin block on home'
: reg.phase === 'preliminary'
? 'preliminary registry -- unrefined: the op can run refine to verify and label the models'
: '';
}
saveState.textContent = '';
},
};
}