Files
tiny-worlds/web/view-home.mjs
T
mute 0ddb9a218d the package-authoring round: fork is the verb, the scaffold flag is the ready-to-run gate, the package editor is the owner's surface, and /packages is the launchpad
The design conversation settled the verb question (developer, 2026-11-19): a "create new package" with a base selector is fork under another name, so the SPA gains one list at /packages with three acts per card -- start (the run-create flow, unchanged), fork (any package, system or user, by anyone: the copy lands in state/packages owned by the forker, pc stripped, display name asked inline, the fork landing straight in the editor -- nobody forks to immediately start), and edit (the owner's own user packages only). /new retires to a redirect onto /packages; the source link (code.fleshless.org/hackmaster/tiny-worlds) rides the header.

The template's unplayability became machinery instead of a naming special-case: settings.json carries the "scaffold" flag (the records-bool precedent -- authored content carries the marker, machinery reads it). Create refuses a scaffold loudly on both ends ("fork it to author, then flip scaffold off in the editor"), the listing marks it, the SPA disables its start. The developer's ruling over my clear-the-flag draft: the flag RIDES FORKS UNTOUCHED -- a scaffold fork stays a scaffold until its author flips it off, so the flag is the package's doneness state, and publishing your own scaffold for others to fork is free. The settings editor is raw JSON for now (native UI later, the developer's "ready to run" toggle its eventual shape), with a hint teaching the keys.

The package editor (/packages/:name): every file of a user package is authoring material -- settings included -- with the cheap save lints (memory.json and settings.json must parse as JSON objects; the carryover passes the authored lint, the run surface's exact gate), the deep checks staying at the start gate where they already lived. The gates mirror the run precedent: system packages are repo-side and refuse ("fork to edit"); an ownerless user package is readable, forkable, never editable -- and an ownerless package IS forkable, the copy is yours.

The refactor the editor forced: the setup view's file-editor machinery (nav, textarea + the sigil/var highlight overlay, drafts, dirty marks, the save flow) extracted into widgets.mjs's fileEditor factory, parameterized over DOM ids and a PUT call -- setup keeps its run-side couplings (the phase-gated rw, the addressed session), the package editor is the simpler parameterization, and the editor CSS generalized from id selectors to classes so both surfaces share it.

En-route bug found and fixed: cmdCreate always copied the REPO's handbook.md into the run, so a user package's handbook -- which save-package faithfully copies out -- was silently ignored on re-create; the author's craft edit died in the round-trip. Create now prefers the package's own handbook when it carries one, else the repo's shared copy. The smoke proves the round-trip: a handbook marker authored through the package editor surfaces in the created run's files.

Browser-pass find: the pkgedit header state span and the editor's save-state span shared the id pkgedit-state, so the widget's select() wiped the header line -- the editor's span renamed (pkgedit-edit-state), verified rendering.

Verified: typecheck green both programs; smoke ALL PASS (+20 -- the fork battery: the template fork owner-stamped scaffold-preserved pc-stripped, create refusing the scaffold on both ends, the playable fork carrying no scaffold, fork validation, the editor gates owner-200/non-owner-403/system-repo-side-403/unknown-404, the raw-JSON and carryover save lints, the ready-to-run flip, create from the flipped fork, the handbook round-trip; and the ownerless pair: the editor refuses, the fork succeeds); restart + reminder checks green (6 runs); a browser pass on --mock --debug end to end -- the paste token re-landing after the state wipe, /new redirecting with the URL honest, the template card disabled with the scaffold note, boutique disabled as incomplete, the fork form prefill and submit landing in the editor, the scaffold state line, the settings flip and save making the card startable, the start-form flow intact, zero console errors; check-repo clean; the debug server back on the real state. Docs: README's packages passage (fork, scaffold, the editor, the gates), the booting flow, the layout tree (the clerk's fork-package verb, the view list, widgets.mjs); DICTIONARY's package, scaffold, and fork entries. The developer's queue line ('"create new package" in SPA') is struck by them in the same round. packages/detention stays untracked WIP, untouched.
2026-11-19 11:11:23 +00:00

429 lines
19 KiB
JavaScript

// 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, fmtCeiling, dropModelCache } from './widgets.mjs';
import { EFFORT_LEVELS } from './knobs.mjs';
/** @typedef {import('./shapes.mjs').RunCard} RunCard */
/** @param {?string} arg @param {number} seq @returns {Promise<void>} */
export async function enter(arg, seq) {
/** @type {RunCard[]} */ 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} \u00b7 ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} \u00b7 ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} \u00b7 ${r.id}${specTag(r.models?.player)}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
// your own draft opens the editor; anyone else's run opens at
// the story -- the table is the owner's
card.addEventListener('click', () => navigate(!mine ? `/runs/${r.id}/story` : r.phase === 'dormant' && r.sessions === 1 ? `/runs/${r.id}/setup` : `/runs/${r.id}`));
list.appendChild(card);
}
await renderAdmin(seq);
}
/** @param {RunCard} r @param {boolean} mine @returns {string} */
const ownershipTag = (r, mine) =>
(mine ? ' \u00b7 yours' : r.owner == null ? ' \u00b7 ownerless' : ` \u00b7 ${r.ownerName ?? 'someone'}'s`);
// the card's model garnish: a spec renders as provider/model
/** @param {{ provider?: string, model?: string }|null|undefined} pick @returns {string} */
const specTag = (pick) => (pick && pick.provider ? ` \u00b7 ${pick.provider}/${pick.model ?? '?'}` : '');
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
/** @param {number} t @returns {string} */
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
/** @param {RunCard} r @returns {string} */
function runStateText(r) {
if (r.phase === 'live') return `session open${r.pendingAsk ? ' -- waiting for your answer' : ''}`;
if (r.phase === 'dormant') {
if (r.sessions === 1) return 'draft -- not started yet';
return r.ready === false ? 'dormant -- housekeeping pending' : `dormant -- session ${r.sessions} waits`;
}
return 'no sessions';
}
/** @param {RunCard} r @returns {string} */
function runStateClass(r) {
if (r.pendingAsk) return 'attention';
if (r.phase === 'live') return 'ok';
if (r.phase === 'dormant' && r.sessions > 1 && r.ready === false) return 'attention';
if (r.sessions === 1 && r.phase === 'dormant') return 'draft';
return '';
}
/** @param {number} seq @returns {Promise<void>} */
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false;
/** @type {[{ invites: { id: number, kind: string, created_at: string, state: string }[] }, { users: import('../server/shapes.mjs').User[] }, import('./shapes.mjs').ModelsRegistryResponse]} */
const [inv, us, reg] = await Promise.all([api('/invites'), api('/users'), api('/models')]);
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} \u00b7 ${u.id}${u.superuser ? ' \u00b7 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);
}
renderProvidersAdmin(reg, seq);
}
// --- providers: the op's surface ---------------------------------------------
//
// The provider cards: the state line, the selection (the default
// {model, effort} pair -- also the refine curator), discover and
// refine (both armed: discover resets a refined section to the
// scrape, refine sends real traffic over every model on the
// provider), remove (the o/f singleton holds while it is all that
// stands), the refine meter with its surviving receipt, the model
// list, and the curator's recommendation beside the selection --
// intel, one click to apply. The add flow is the binary choice:
// opencode/free (disabled when present) or a custom provider.
/** @param {import('./shapes.mjs').ProviderPayload} p @returns {string} */
function providerStateLine(p) {
if (p.phase === 'none') {
// the probe record is the card's truth (developer, 2026-11-19): an auth
// refusal opens the key path (never on o/f -- its auth failure is
// upstream breakage, not a prompt); any other failure names
// itself; no probe yet is a provider that was never scraped
if (p.probe?.outcome === 'auth') {
return p.slug === 'opencode/free'
? 'upstream auth failure -- nothing to fix on this side, wait'
: 'discovery refused -- it wants an API key';
}
if (p.probe?.outcome === 'error') return `discovery failed -- ${p.probe.detail}`;
return 'not discovered yet';
}
if (p.phase === 'preliminary') return `${p.models.length} scraped, unrefined (discovered ${fmtStamp(p.discovered)})`;
const usable = p.models.filter((m) => m.inference !== false).length;
const def = p.default ? ` \u00b7 default ${p.default.model} at ${p.default.effort}` : ' \u00b7 no default selected';
return `refined -- ${usable}/${p.models.length} usable${def}${p.curator && p.curator !== 'curated' ? ` \u00b7 ${p.curator}` : ''} (refined ${fmtStamp(p.refined)})`;
}
/** @param {import('./shapes.mjs').ProviderPayload} p @param {number} seq */
function renderProviderCard(p, seq) {
const card = el('div', 'provider-card');
const running = p.job?.state === 'running';
const head = el('div', 'admin-row');
head.appendChild(el('span', 'grow', `${p.slug} \u00b7 ${providerStateLine(p)}`));
const rm = el('button', 'danger', 'remove');
armedButton(rm, {
label: 'remove',
confirm: 'the runs riding it block until re-picked -- click again',
fire: async () => {
try { await api(`/providers/${encodeURIComponent(p.slug)}`, { method: 'DELETE', body: {} }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
head.appendChild(rm);
card.appendChild(head);
// the acts
const acts = el('div', 'form-actions');
const disc = /** @type {HTMLButtonElement} */ (el('button', null, 'discover'));
const refi = /** @type {HTMLButtonElement} */ (el('button', null, 'refine'));
disc.disabled = running;
refi.disabled = running || p.phase === 'none';
armedButton(disc, {
label: 'discover',
confirm: 'resets this provider\'s section to a fresh scrape -- the battery results are re-earned by refining. click again',
fire: async () => {
try { await api(`/providers/${encodeURIComponent(p.slug)}/discover`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
armedButton(refi, {
label: 'refine',
confirm: 'sends real traffic over every model on this provider -- may cost a buck. click again',
fire: async () => {
try { await api(`/providers/${encodeURIComponent(p.slug)}/refine`, { method: 'POST', body: {} }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
acts.appendChild(disc);
acts.appendChild(refi);
// the key control (developer, 2026-11-19): remove re-probes the keyless
// endpoint -- a provider gone public lands working, a locked one
// re-opens the ask (that is the key-replacement path). o/f never
// carries a key, so the control never shows on it.
if (p.hasKey) {
const rmk = /** @type {HTMLButtonElement} */ (el('button', null, 'remove key'));
armedButton(rmk, {
label: 'remove key',
confirm: 'the key leaves the config and the endpoint is probed again -- click again',
fire: async () => {
try {
const res = await api(`/providers/${encodeURIComponent(p.slug)}/auth`, { method: 'DELETE', body: {} });
if (res.probe && res.probe !== 'ok') banner(res.detail ?? 'the endpoint failed the keyless probe');
} catch (e) { banner(e.message); return; }
dropModelCache();
render();
},
});
acts.appendChild(rmk);
}
card.appendChild(acts);
// the ask (developer, 2026-11-19): a provider whose last probe met an auth
// refusal opens the key path -- the token is checked on reception,
// saved on success, asked again on the next refusal
if (p.probe?.outcome === 'auth' && p.slug !== 'opencode/free') {
const ask = el('div', 'admin-row');
const lab = el('label', 'field', 'API key ');
const key = /** @type {HTMLInputElement} */ (el('input'));
key.type = 'password';
key.autocomplete = 'off';
lab.appendChild(key);
const send = el('button', null, 'send key');
send.addEventListener('click', async () => {
if (!key.value.trim()) { banner('enter the key first'); return; }
try {
await api(`/providers/${encodeURIComponent(p.slug)}/auth`, { method: 'POST', body: { apiKey: key.value.trim() } });
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
dropModelCache();
render();
});
ask.appendChild(lab);
ask.appendChild(send);
card.appendChild(ask);
}
// the refine meter: the bar moves only on real step completions,
// the label names the call running now, and the lines are the
// receipt -- they survive the job, so a landed pass keeps its
// verdicts and a rejected one keeps its post-mortem
if (p.job?.steps) {
const j = p.job;
const st = j.steps ?? { total: 0, done: 0, label: '' };
const meter = el('div', 'refine-progress');
const top = el('div', 'refine-topline');
top.appendChild(el('span', 'refine-count', `${st.done}/${st.total} \u00b7 ${j.state}`));
top.appendChild(el('span', 'refine-label hint', j.state === 'running'
? `${st.label}${st.chars != null ? ` \u00b7 ${st.chars} chars` : ''}`
: (j.state === 'rejected' ? `rejected -- ${j.reason ?? ''}` : st.label)));
const bar = el('div', 'refine-bar');
const fill = el('div', 'refine-fill');
fill.style.width = `${st.total ? Math.min(100, Math.round((100 * st.done) / st.total)) : 0}%`;
bar.appendChild(fill);
const lines = el('div', 'refine-lines');
for (const l of j.lines ?? []) lines.appendChild(el('div', 'refine-line', l));
meter.appendChild(top);
meter.appendChild(bar);
card.appendChild(meter);
card.appendChild(lines);
}
// the selection: the provider's default pair, also the refine
// curator. The curator's recommendation sits beside it -- intel
// only, applied by the op's click (never auto-landed)
if (p.models.length) {
const sel = el('div', 'admin-row');
const selLab = el('label', 'field', 'default ');
const mod = /** @type {HTMLSelectElement} */ (el('select'));
const eff = /** @type {HTMLSelectElement} */ (el('select'));
/** @param {HTMLSelectElement} s @param {string} v @param {string} label */
const mk = (s, v, label) => {
const o = /** @type {HTMLOptionElement} */ (el('option', null, label));
o.value = v;
s.appendChild(o);
};
mk(mod, '', '(none)');
for (const m of [...p.models].filter((x) => x.inference !== false).sort((a, b) => (a.id < b.id ? -1 : 1))) mk(mod, m.id, m.id);
mod.value = p.default?.model ?? '';
mk(eff, '', '(level)');
for (const lv of EFFORT_LEVELS) mk(eff, lv, lv);
eff.value = p.default?.effort ?? '';
const save = el('button', null, 'set default');
save.addEventListener('click', async () => {
if (!mod.value || !eff.value) { banner('the default is a pair -- pick a model and an effort level'); return; }
try {
await api(`/providers/${encodeURIComponent(p.slug)}/default`, { method: 'POST', body: { model: mod.value, effort: eff.value } });
} catch (e) { banner(e.message); return; }
dropModelCache();
render();
});
selLab.appendChild(mod);
selLab.appendChild(eff);
sel.appendChild(selLab);
sel.appendChild(save);
card.appendChild(sel);
if (p.recommendation && (p.recommendation.model !== p.default?.model || p.recommendation.effort !== p.default?.effort)) {
const rec = el('div', 'admin-row');
rec.appendChild(el('span', 'grow', `the curator recommends ${p.recommendation.model} at ${p.recommendation.effort}`));
const apply = el('button', null, 'apply');
apply.addEventListener('click', async () => {
try {
await api(`/providers/${encodeURIComponent(p.slug)}/default`, { method: 'POST', body: { model: p.recommendation?.model, effort: p.recommendation?.effort } });
} catch (e) { banner(e.message); return; }
dropModelCache();
render();
});
rec.appendChild(apply);
card.appendChild(rec);
}
}
// the model list
for (const m of p.models) {
const row = el('div', 'admin-row');
const facts = [
m.id,
m.label && m.label !== m.id ? m.label : null,
m.family ? `(${m.family})` : null,
fmtCeiling(m.input) ? `${fmtCeiling(m.input)} in` : null,
m.output ? `${fmtCeiling(m.output)} out` : null,
m.status === 'unrefined' ? 'unrefined' : null,
m.inference === false ? 'FAILED the inference probe' : null,
m.inference !== false && m.reasoning ? `reasoning ${m.reasoning}` : null,
m.latency != null ? `${m.latency}ms` : null,
].filter(Boolean).join(' \u00b7 ');
row.appendChild(el('span', 'grow', facts));
if (m.description) row.appendChild(el('span', 'hint', m.description));
card.appendChild(row);
}
return card;
}
/** @param {import('./shapes.mjs').ModelsRegistryResponse} reg @param {number} seq */
function renderProvidersAdmin(reg, seq) {
const list = $('provider-list');
list.textContent = '';
const none = !reg.providers.length;
/** @type {HTMLDivElement} */ ($('providers-banner')).hidden = !none;
if (none) {
$('providers-banner').textContent = 'no providers configured -- add opencode/free (the anonymous fallback) or a custom provider; the server also self-heals this on restart';
}
/** @type {HTMLButtonElement} */ ($('provider-add-of')).disabled = reg.providers.some((p) => p.slug === 'opencode/free');
for (const p of reg.providers) list.appendChild(renderProviderCard(p, seq));
if (reg.providers.some((p) => p.job?.state === 'running') && seq === state.seq) {
// the job follows itself home: poll until it lands, then re-render
setTimeout(async () => {
const r = /** @type {?import('./shapes.mjs').ModelsRegistryResponse} */ (await api('/models').catch(() => null));
if (!r || seq !== state.seq || state.view !== 'home') return;
if (r.providers.some((p) => p.job?.state === 'running')) renderProvidersAdmin(r, seq);
else render();
}, 2000);
}
}
/** @param {?string} iso @returns {string} */
function fmtStamp(iso) {
return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC` : '?';
}
// the add flow (developer, 2026-11-19): the binary choice, and the probe
// decides the key path. o/f is one click; custom opens the inline
// form taking ONLY the endpoint -- a working keyless listing never
// sees a key field. A 401/403 stands the provider broken and opens
// the key field: the key rides the auth route, checked on reception,
// saved on success, asked again on the next refusal. Every other
// failure refuses the add outright (nothing stands, the form stays).
/** @type {?string} */ let authTarget = null; // set when an add landed broken on auth -- the form's next go keys it
function closeAddForm() {
authTarget = null;
/** @type {HTMLFormElement} */ ($('provider-form')).hidden = true;
/** @type {HTMLInputElement} */ ($('provider-slug')).value = '';
/** @type {HTMLInputElement} */ ($('provider-base')).value = '';
/** @type {HTMLInputElement} */ ($('provider-key')).value = '';
/** @type {HTMLLabelElement} */ ($('provider-key-field')).hidden = true;
}
$('provider-add-of').addEventListener('click', async () => {
try { await api('/providers', { method: 'POST', body: { builtin: true } }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
});
$('provider-add-custom').addEventListener('click', () => { /** @type {HTMLFormElement} */ ($('provider-form')).hidden = false; });
$('provider-add-cancel').addEventListener('click', () => closeAddForm());
$('provider-add-go').addEventListener('click', async () => {
const slug = /** @type {HTMLInputElement} */ ($('provider-slug')).value.trim();
const baseUrl = /** @type {HTMLInputElement} */ ($('provider-base')).value.trim();
const apiKey = /** @type {HTMLInputElement} */ ($('provider-key')).value.trim();
if (authTarget) {
// the provider stands broken -- this go sends the key, not another add
if (!apiKey) { banner('the endpoint wants a key -- enter one or cancel'); return; }
try {
await api(`/providers/${encodeURIComponent(authTarget)}/auth`, { method: 'POST', body: { apiKey } });
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
closeAddForm();
dropModelCache();
render();
return;
}
if (!slug || !baseUrl) { banner('slug and baseUrl are both required'); return; }
try {
await api('/providers', { method: 'POST', body: { slug, baseUrl } });
} catch (e) {
if (e.status === 401 || e.status === 403) {
authTarget = slug;
/** @type {HTMLLabelElement} */ ($('provider-key-field')).hidden = false;
banner(e.message);
return;
}
banner(e.message); return; // refused outright (or bad input) -- nothing stands
}
closeAddForm();
dropModelCache();
render();
});
$('new-run-btn').addEventListener('click', () => navigate('/packages'));
$('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);
}
});