Files

429 lines
19 KiB
JavaScript
Raw Permalink Normal View History

// 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)));
2026-11-15 22:37:06 +00:00
// 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;
2026-11-16 21:32:02 +00:00
/** @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 ---------------------------------------------
2026-11-16 21:32:02 +00:00
//
// 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.
2026-11-16 21:32:02 +00:00
/** @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() }, domain401: true });
} 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;
2026-11-17 02:21:38 +00:00
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'
2026-11-17 02:21:38 +00:00
? `${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);
2026-11-17 02:21:38 +00:00
}
// 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) {
2026-11-16 21:32:02 +00:00
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';
2026-11-16 21:32:02 +00:00
}
/** @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) {
2026-11-16 21:32:02 +00:00
// 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));
2026-11-16 21:32:02 +00:00
if (!r || seq !== state.seq || state.view !== 'home') return;
if (r.providers.some((p) => p.job?.state === 'running')) renderProvidersAdmin(r, seq);
2026-11-16 21:32:02 +00:00
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 }, domain401: true }); } catch (e) { banner(e.message); return; }
dropModelCache();
render();
2026-11-16 21:32:02 +00:00
});
$('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 }, domain401: true });
} catch (e) { banner(e.message); return; } // still refused -- the ask stays open
closeAddForm();
dropModelCache();
2026-11-16 21:32:02 +00:00
render();
return;
}
if (!slug || !baseUrl) { banner('slug and baseUrl are both required'); return; }
try {
await api('/providers', { method: 'POST', body: { slug, baseUrl }, domain401: true });
} 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();
2026-11-16 21:32:02 +00:00
});
$('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);
}
});