e60fd63d2b
the provider round (2026-11-18, batteries-included): providers are first-class entities, the config is server-written state (state/config.json), and a fresh clone boots playable -- the opencode/free singleton auto-added and discovered on the empty list, playable with zero secrets. Every request resolves a full spec {provider, model, effort}: no unset effort, the per-run params layer retired, the mind verb the only sampling source. The registry is per-provider sections (state/models.json), refine caches adjudications under the double spec tuple (state/refine-cache.json), run picks are invalidatable (a removed provider or drifted model blocks the run with the note naming what died), and the housekeeper inherits the player spec's provider default (#16 closed). The no-legacy pass died the same day it shipped: bootImport deleted (server.json is bind + contwin), the registry's v1/v2 in-memory migrations deleted (models.json rewritten on disk into the per-provider shape), bare-string model picks deleted (Chloe's run.json migrated to spec objects, shape-preserving), the clerk's create model arg deleted, apiKeyEnv and the contextWindow alias gone. The live arc proven from a bare boot: invite minted, o/f auto-added, a custom provider with a bogus key (the recognizable 401), the auth fixed (13 models), the default pair selected, and a real glm-5.3 turn through the full path. Two live findings: opencode.ai serves 89 models keyless but 401s an empty Bearer header (the auth header rides only when a key exists), and the failure log line rides stderr.
the provider-flow round (2026-11-19, GM-designed): discovery IS the probe. The add takes only the endpoint -- {slug, baseUrl} or {builtin: true}, an apiKey in the body 400s (the auth route is the only key path) -- and a working keyless listing never sees a key field. A 401/403 stands the provider broken: the entity carries a probe record (outcome ok/auth/error, detail, at), the card opens the ask, and only the explicit acts move the record -- add, key, remove-key, discover; usage errors are transient and the op's to fix, nothing in the runtime flips provider state. The auth route is probe-then-save: the candidate key checks on reception, saves only on success -- a still-refused key never reaches the config, the previous state returns, the ask repeats. Every other discovery failure refuses the add outright with rollback: an endpoint that cannot answer is not a provider, nothing stands (the old code let it stand on any failure). The remove-key control (custom providers, armed) clears and re-probes: a provider gone public lands working keyless, a locked one re-opens the ask -- which is the key-replacement path. o/f never asks in any state: its auth failures are upstream breakage to show, not a prompt. The universal retry rule: NO automatic retries anywhere -- every inference call is user-initiated (the send, the housekeeping run, the refine) and every act has its manual retry; the curator's one auto-retry (the 2026-11-17 hiccup lesson) is deleted, the machine-label fallback the designed outcome. And failures never cache (GM: a failure is the absence of a measurement, not a measurement) -- the adjudication cache skips inference:false entries, the receipt line says "never cached, retried at every refine", and a transient battery error can never pin a false verdict; gev's 400s cost one cheap probe per refine and self-heal the day the backend learns tools. En-route fix the smoke earned: the create route validated body.spec AFTER the clerk built the run dir -- a refused spec left an orphan run (restart-check's exact count caught the sixth run); the spec validates first now, nothing lands on refusal.
the sheet's transport at the lint: the record is the only channel, the tag is view machinery composed by renderView, never authored by anyone -- the authored gate names the tag in any content (hers would never apply and primes the guarded emission; GM prose rides the view and story raw, the GM-side strips do not know it), names a sheet record on her turn, and checks object-ness on GM-turn records and boundary state notes both kinds; her emitted sheet in a carried tail stays legitimate history (the log keeps guard-conflicted emissions verbatim, and a stop can move one into the slidwin). The carryover editor teaches its own format now: a per-file hint between the editor and the save bar (one JSON object per line; status and agenda ride her turns; the sheet rides yours as the "sheet" field, never as a tag; the sigils and $VARS expand at start on the authored opening only).
the packages: template (the base for new packages -- the mood-indexed voice examples, the settings comment convention, non-playable as-is) and box (the sheet's first consumer: an incremental-game economy as ERP, GP and BP as two currencies with the room pushing her to fund her own punishments; the opening turn third-person per the typography ruling, ending on the display that needs a second read; the amnesiac rings empty by design; the erased name reading "(redacted)" after sigil expansion). The review found and fixed: both carryovers were pretty-printed JSON with duplicate keys -- unstartable under every per-line reader, flattened to true JSONL; the box's opening sheet rode her authored prose -- dead on every surface (the scan reads GM-turn records only, the strips eat it) and priming the exact emission the guard conflicts -- moved to the GM turn's sheet record, the override's shape; the gm.md "take of leave" typo fixed in all three packages.
the lint's rule 4 scoped to the substrate (GM, 2026-11-19): a banned word in a package's prose is fine -- the packages are the fiction and their words are the story's; README and the root prompts stay patrolled, and the box's "Or windows" is an architectural plural in a padded cell.
verified: typecheck green both programs; smoke ALL PASS (+27 the provider-flow battery: apiKey-on-add 400, the dead-endpoint refusal with config rollback, the auth-standing card with its probe record, probe-then-save both ways, the remove-key round trip, the o/f guards, the failures-never-cache proof over mock-fail -- verdict with the marker, absent from the cache file, re-probed fresh while the passing three serve from cache, not selectable, no orphan run; +8 the sheet-transport lint battery); restart + reminder checks green; a browser pass driving the whole add-flow machine on a mock+debug server (the hidden key field opening on the 401, the key landing through the auth route, the remove-key round trip re-opening the ask, the dead add refusing with the banner and no card, zero console errors beyond the expected 401/500 resource lines); check-repo clean with the box's windows. detention stays untracked WIP, untouched.
429 lines
19 KiB
JavaScript
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 (GM, 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 (GM, 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 (GM, 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 (GM, 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('/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);
|
|
}
|
|
});
|