Files
tiny-worlds/web/widgets.mjs
T
mute 894737fcf3 the 2026-11-16 rounds, the whole day in one commit: model discovery (the two-step op act -- discover scrapes the provider metadata, refine runs the deterministic battery over every id and hands the adjudicated results to the best passing model for the curated registry; state/models.json is the truth of selectable models and gates all model use, a fresh deployment has none; the five named sampling knobs ride run.json params over server.json params, sent only when set; the curator call retries once on the host's network hiccups, its output strictly validated with the machine-list fallback, and the do-not-deliberate line keeps its thinking tokens down); the pick rule reworked on the GM's rulings -- the dv endpoint's 5.2/5.3-max flip was an alias (one model behind both ids), the rank keys on the reasoning bucket not the raw token count (within-bucket differences are sampling noise, the thresholds sit in the endpoint's observed gaps) and full ties settle sort-lex-pick-bottom, with the mock registry carrying a canned tie pair (mock/mock-tie) and the smoke asserting the lex-bottom pick; the play-protocol batch (OOC GM turns carry no cache blocks, memory.json is authored draft applied by the start gate's reapply over a fresh db, /story filters OOC whole, the per-turn raw control on the table); the tunables UX round (web/knobs.mjs: the definitions table with the GM's hint texts and the probed this-endpoint bounds, the per-knob explicit override toggle replacing implicit empty-means-unset diffing, the shared focus-driven hint bar; the run detail and /model responses carry paramDefaults, the deployment layer -- the only default anyone can honestly name); request recording (every provider call lands its resolved model + effective params on the msg event as via, a failed call lands a req event with the failure, both surface on the raw tab and the per-turn raw control on no model-facing surface, a req riding the slidwin tail passes the start lint as conversation machinery; the housekeeping pass log names its model via the clerk's --model flag); the mind verb (<mind> JSON in a player turn sets its sampling for its next turn -- one-shot, max_tokens excluded, a budget not a mind; bounds enforced in KNOB_BOUNDS with the range named in the conflict and the heal restatement the statement that counts; derive() makes a statement live until a player reply consumes it, honest across restarts, session boundaries and forks -- an unconsumed mind rides on); the full-block protocol (the GM rewrote system/invariants/reminder to eliminate the diff verbs: she emits whole <status>/<agenda> at her turn tail, a present block is a whole-list set, absent means unchanged never blank, over-cap agendas evict from the bottom silently -- ruled a feature, silent to her, the note shows the GM; renderView strips every copy and stamps the newest of each kind at the tail of her most recent prose turn, her own emission, so the context reads as the same sequence of events the game had; GM prose goes pure, old logs' composited rides strip, they were never GM words; <mind> is write-only, its tags strip from the view; every turn of hers carries its <model> block -- the params it rode, bare JSON from the via record, the current call included, suppressed when nothing is set, emitting one refused with a pointer at <mind>; the clerk's status-apply/agenda-apply delta verbs RETIRED with their dispatch and collectors, status-set/agenda-set are the player path now; the story strips her blocks, the table chips them; the smoke imports renderView and asserts the view policy directly -- the pattern for testing view-only policy no API exposes); and the opening event RETIRED (the start gate seeds the clerk from her last authored turn's blocks -- the GM moved la-caramba's initial status into her opening turn; old carryovers keep their events as inert history; the event's pre-existing double-landing in every started log, pre-bundle and in-carry, died with the branch); smoke ALL PASS + restart + reminder + repo checks green, browser passes over the knob UX and the new chips and notes with zero console errors, typecheck green on both programs; README and DICTIONARY carry the durable design, HANDOFF trimmed to the map
2026-11-16 21:32:02 +00:00

241 lines
11 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 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 { render } from './router.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. save(items)
// resolves on success and throws on failure -- a failed save keeps
// the editor open, nothing was changed. setEditable(false) is the
// not-the-owner state: no edit button, an open editor cancels.
/** @typedef {{ section: string|HTMLElement, body: string|HTMLElement, empty: string, placeholder: string, rows: number, format: (items: string[]) => string, toText: (items: string[]) => string, fromText: (text: string) => string[], save: (items: string[]) => Promise<unknown> }} PaneOpts */
/** @typedef {{ set: (next?: ?string[]) => void, setEditable: (ok: boolean) => void, reset: () => void, items: string[] }} Pane */
/** @param {PaneOpts} opts @returns {Pane} */
export function paneEditor({ section, body, empty, placeholder, rows, format, toText, fromText, save }) {
const sec = typeof section === 'string' ? $(section) : section;
const bodyEl = typeof body === 'string' ? $(body) : body;
const editBtn = el('button', null, 'edit');
(/** @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, '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)
/** @type {string[]} */ 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 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. The registry's usable models group by
// family; the label is the curator's (or the id before refinement),
// and 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] : [];
/** @type {Record<string, import('../server/shapes.mjs').RegistryModel[]>} */ const byFamily = {};
for (const m of usableModels) {
const f = m.family ?? m.id;
(byFamily[f] ??= []).push(m);
}
const families = Object.keys(byFamily).sort();
for (const f of families) {
const group = /** @type {HTMLOptGroupElement} */ (el('optgroup'));
group.label = f;
for (const m of byFamily[f]) {
const label = m.label ?? m.id;
const ceil = fmtCeiling(m.input);
const o = /** @type {HTMLOptionElement} */ (el('option', null, ceil ? `${label} \u00b7 ${ceil}` : label));
o.value = m.id;
group.appendChild(o);
}
sel.appendChild(group);
}
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.
/** @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|null> }} */ let playerKnobs = knobsBox('player', undefined, undefined, knobHint);
/** @type {{ wrap: HTMLElement, read: () => Record<string, number|null> }} */ let houseKnobs = knobsBox('housekeeper', undefined, undefined, knobHint);
root.appendChild(playerKnobs.wrap);
root.appendChild(houseKnobs.wrap);
root.appendChild(knobHint);
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);
const pk = knobsBox('player', params?.player ?? undefined, paramDefaults?.player ?? undefined, knobHint);
const hk = knobsBox('housekeeper', params?.housekeeper ?? undefined, paramDefaults?.housekeeper ?? undefined, knobHint);
playerKnobs.wrap.replaceWith(pk.wrap);
houseKnobs.wrap.replaceWith(hk.wrap);
playerKnobs = pk;
houseKnobs = hk;
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 = '';
},
};
}