diff --git a/packages/webui/src/cli.mjs b/packages/webui/src/cli.mjs index bef2d9fdd..5f9b62908 100644 --- a/packages/webui/src/cli.mjs +++ b/packages/webui/src/cli.mjs @@ -38,6 +38,7 @@ import { createTriageHost } from './triage-host.mjs'; import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snapshot.mjs'; import { busesStopped } from '../../cli/src/proxy-admin-host.mjs'; import { agentLevelsWriteRoutes } from './agent-levels-write.mjs'; +import { triageRouteRoutes } from './triage-route-http.mjs'; import { RESTART_EXIT } from '../../cli/src/org-console.mjs'; import { ID_PATTERN, systemOnly } from '../../organization/src/vocabulary.mjs'; import { selectorScope } from '../../organization/src/selector.mjs'; @@ -262,8 +263,24 @@ try { const trail = system ? actionTrail(join(system.dataRoot, 'console')) : null; // #1873 A2: Settings > Agents writes for the root and project levels, beside the levels read. const agentLevelRoutes = organizations ? [agentLevelsWriteRoutes({ configDir: configDir(), rolesDir: rolesDir(), trail })] : []; + // #1873 triage-settings: Settings > Triage reads and saves the route store for the instance owner. + // The model is checked against the catalogue each active organization's bus answers with, as an + // organization's route change is. The Triage host above still gets route: null; saving starts nothing. + const triageRoutes = system && (devOwner || ssoOn) ? [triageRouteRoutes({ + dataRoot: system.dataRoot, log: line => console.log(line), + catalogues: async () => { + const read = async call => { try { return (await call('routes'))?.catalogue ?? { status: 'unknown' }; } catch { return { status: 'bus-unavailable' }; } }; + if (!organizations) return ownerCall ? [await read(ownerCall)] : []; + // Every active organization is asked at once, so a hung bus costs one timeout, not one each. + const active = (await listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance })).filter(org => org.state === 'active'); + return Promise.all(active.map(org => { + let paths; try { paths = orgPaths(org.root); } catch { return { status: 'bus-unavailable' }; } + return read(busCaller({ dataRoot: org.root, socket: paths.socket, business: org.id, timeoutMs: 5000 })); + })); + }, + })] : []; try { - server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null }); + server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: [...agentLevelRoutes, ...triageRoutes], preselect: options.business ?? null }); } catch (err) { sso?.close(); throw err; } if (testerSocket) { const call = busCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, cli: TESTER_CLI }); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index b2d498976..d4580a70f 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -321,7 +321,7 @@ // render. That read marks nothing. Row 150 (#1644): since row 142, `mosaic talk` prints only the // reply to its own message, so a reply to a Console send stays unread in `mosaic inbox` until // the human marks it read with `mosaic inbox --read`. - let isTester = false, orgSetup = false; + let isTester = false, orgSetup = false, triageOwner = false; // Both Docs and project direction use the same owner-only records setup action. window.MosaicRecords = { markup(project) { @@ -1431,13 +1431,13 @@ }); }); // Organizations is writable when the server allows org setup, which it does in organization mode where send is off. - const readonlyPage = page => !['appearance','business','console'].includes(page) && !(page === 'organizations' && orgSetup) && !canSend && !isTester; - const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['console','Console'],['about','About']]; + const readonlyPage = page => !['appearance','business','console','triage'].includes(page) && !(page === 'organizations' && orgSetup) && !canSend && !isTester; + const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['triage','Triage'],['console','Console'],['about','About']]; function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`), dot='unsaved changes';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);} function settingsShell(page, body, helper='') { - const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages; + const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages.filter(([id])=>id!=='triage'||triageOwner); const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; - const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft())); + const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft()))||(id==='triage'&&window.MosaicTriageRoute?.hasDraft()); const dot='unsaved changes'; const links=pages.map(([id,name],i)=>`${i===0?'
Your browser
':i===1?'
This instance
':''}${name}${isDirty(id)?dot:''}`).join('') + (!isTester ? '
Members and invites not built
' : ''); return `${head('Settings','Your browser and this instance.')}

${label}

${helper}

${readonlyPage(page)?'

Read only. Saving requires signed-in send mode.

':''}${body}
`; @@ -1447,6 +1447,8 @@ if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.'); if (page==='organizations') { await configRead; return settingsShell(page,window.MosaicOrgCreate.markup,'Create an organization from the template, edit it, and finish its setup. Each step names the command it equals.'); } if (page==='model-proxy') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Accounts used by this instance, their priority, and the client keys assigned to agents.'); } + // #1873 triage-settings: Settings > Triage (triage-settings.js), the instance owner's only; anyone else gets no page. + if (page==='triage') { await configRead; if (!triageOwner || !window.MosaicTriageRoute) return notFound(); return settingsShell(page,await window.MosaicTriageRoute.section(),'The model, harness and daily token cap Triage uses. Only the instance owner sees this page.'); } // F3: Settings > Console (console-restart.js). The server checks the owner, Origin and trail. if (page==='console') { await configRead; await window.MosaicConsole?.ready; return settingsShell(page,window.MosaicConsole?.settingsMarkup()??'

The Console controls did not load. Reload the page to try again.

','Restart this Console on the same address and configuration.'); } const s = await get.api('settings'), n = s.notifier || {}; @@ -1910,13 +1912,14 @@ return; } if (path === '/settings/model-proxy' && shown === route && !navigated) return; + if (path === '/settings/triage' && shown === route && !navigated) return; if (path === '/settings/organizations' && shown?.split('?')[0] === path && !navigated) return; if (($('agent-dialog')?.open || document.querySelector('.agent-more[aria-expanded=true]')) && !navigated) { schedule(); return; } if (navigated || (shown !== route && !samePage)) { unmountEditor(); $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); } let html, state = 'fresh'; const live = reader(true); try { - if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/organizations'].includes(path)) { + if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/triage','/settings/organizations'].includes(path)) { try { await live('messages'); } catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; } } @@ -2113,6 +2116,8 @@ canMessage = !isTester && c?.send === true; chatSend = !isTester && c?.chatSend === true; orgSetup = !isTester && c?.orgSetup === true; + // #1873 triage-settings: /api/config says proxyAdmin to the instance owner only, the same owner /api/triage/route serves. + triageOwner = !isTester && c?.proxyAdmin === true; window.MosaicOrgBusStopped = !!window.MosaicOrg && c?.devOwner === true && orgSetup && c?.chatSend === false; // The header menu offers "New organization" to the owner of a Console with organizations; nobody else can create one. if (orgSetup && !$('org-new-link')) { const a = document.createElement('a'); a.id = 'org-new-link'; a.href = NEW_ORG; a.setAttribute('role', 'menuitem'); a.textContent = 'New organization'; document.querySelector('#avatar-menu > a[href="#/settings"]')?.after(a); } diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index fced404b5..49eec5c95 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -345,7 +345,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( return orgOf(hash) || !seg || system(hash) ? hash : `#/orgs/${seg}${path}`; }; // /api/workspace reads and writes across organizations (U1, U4b), so it keeps its own path. - const unscoped = /^\/api\/(?:workspace(?:\/|\?|$)|orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/(?:levels|root)(?:\?|$))/; + const unscoped = /^\/api\/(?:workspace(?:\/|\?|$)|orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/(?:levels|root)(?:\?|$)|triage\/route(?:\?|$))/; window.fetch = (input, init) => { if (typeof input !== 'string' || !input.startsWith('/api/') || unscoped.test(input)) return nativeFetch(input, init); const send = () => nativeFetch(current ? `/api/orgs/${current}/${input.slice('/api/'.length)}` : input, init); diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index d6b78363e..7883af3fa 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -7,7 +7,7 @@ - + diff --git a/packages/webui/src/public/triage-settings.js b/packages/webui/src/public/triage-settings.js new file mode 100644 index 000000000..30ed5813a --- /dev/null +++ b/packages/webui/src/public/triage-settings.js @@ -0,0 +1,133 @@ +/* #1873 triage-settings: Settings > Triage, the instance owner's Triage model route. It reads and + writes /api/triage/route (triage-route-http.mjs); the server checks the owner, the Origin and Fetch + Metadata, the catalogue and the time zone, and the store keeps the revision and the receipt. This + file only asks and reports. bus.js offers the page only when /api/config says proxyAdmin, which is + the same owner the route serves. The fields live here, so a repaint keeps what the owner typed. */ +(() => { + 'use strict'; + const $ = id => document.getElementById(id); + const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); + const PATH = '/api/triage/route'; + // The time zones this browser knows, offered as suggestions only; the server decides. + const zones = (() => { try { return Intl.supportedValuesOf('timeZone'); } catch { return []; } })(); + // draft holds the typed fields; base is the revision they were read at, which a save sends, so a + // change saved elsewhere since then answers as stale instead of being written over. + let data = null, readLine = '', draft = null, base = 0, busy = false, line = '', conflict = false; + + const call = init => window.fetch(PATH, { cache: 'no-store', redirect: 'manual', ...init }); + // The stored route's fields, or empty ones: there is no default model, harness, cap or zone. + const fromRoute = r => ({ model: r?.model ?? '', harness: r?.harness ?? '', cap: r ? String(r.cap) : '', timeZone: r?.timeZone ?? '' }); + + async function read() { + readLine = ''; + let r, a = null; + try { r = await call({ method: 'GET' }); } catch { data = null; readLine = 'The Triage route could not be read. Reload the page to try again.'; return; } + try { a = await r.json(); } catch { /* refused below */ } + if (r.type === 'opaqueredirect') { data = null; readLine = 'Sign in again, then reload.'; return; } + if (!r.ok || !a || typeof a !== 'object') { data = null; readLine = typeof a?.message === 'string' ? a.message : 'The Triage route could not be read.'; return; } + // An untouched page follows the store; typed fields stay, with the revision they were read at. + const untouched = draft === null || JSON.stringify(draft) === JSON.stringify(fromRoute(data?.route ?? null)); + data = a; + if (untouched) { draft = fromRoute(a.route); base = Number.isSafeInteger(a.revision) ? a.revision : 0; } + } + + const models = () => (Array.isArray(data?.choices?.models) ? data.choices.models : []); + const harnessesOf = key => models().find(m => m.key === key)?.harnesses ?? []; + + function stored() { + const r = data?.route; + if (!r) return `

Not set. ${esc(data?.routeMessage ?? 'No Triage route is set.')}

`; + return `

Stored route: ${esc(r.model)} on ${esc(r.harness)}, cap ${esc(Number(r.cap).toLocaleString('en-US'))} tokens a day, reset ${esc(r.reset)} ${esc(r.timeZone)}. Revision ${esc(r.revision)}, saved ${esc(r.updatedAt)}.

`; + } + + function form() { + const d = draft ?? fromRoute(null); + const send = data?.send === true; + const off = busy || !send ? ' disabled' : ''; + const list = models(); + const offered = list.some(m => m.key === d.model); + const modelOptions = `` + + (d.model && !offered ? `` : '') + + list.map(m => ``).join(''); + const hs = harnessesOf(d.model); + const harnessOptions = `` + + (d.harness && !hs.includes(d.harness) ? `` : '') + + hs.map(h => ``).join(''); + const status = data?.choices?.status; + const catalogue = status === 'ready' ? '' : `

No organization bus offered a model catalogue (${esc(status ?? 'unknown')}), so no route can be saved now.

`; + const conflictButton = conflict ? ' ' : ''; + return `${catalogue}
` + + `` + + `` + + `` + + `` + + `` + + `
${zones.map(z => ``).join('')}` + + `
${conflictButton} ${esc(line)}
` + + `
${send ? '' : '

This Console is read-only, so the route cannot be saved here.

'}`; + } + + function markup() { + const body = data === null + ? `

${esc(readLine || 'The Triage route could not be read.')}

${esc(line)}

` + : `${stored()}${form()}

${esc(data.note ?? 'Saving a route does not start Triage. The key and the wiring are separate.')}

`; + return `

Triage model route

${body}
`; + } + const repaint = () => { const panel = $('triage-route'); if (panel) panel.outerHTML = markup(); }; + + // Called by bus.js when the page draws: a fresh read each time, the typed fields kept. + async function section() { await read(); return markup(); } + + async function save() { + if (busy || data?.send !== true) return; + const d = draft ?? fromRoute(null); + const cap = /^\d+$/.test(d.cap.trim()) ? Number(d.cap.trim()) : d.cap.trim() === '' ? null : Number.NaN; + const body = { model: d.model, harness: d.harness, cap: Number.isFinite(cap) ? cap : d.cap, timeZone: d.timeZone.trim(), revision: base }; + busy = true; conflict = false; line = 'Saving…'; repaint(); + let r, a = null; + try { r = await call({ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); } + catch { busy = false; line = 'Outcome unknown. Reload the route to see whether it was saved.'; conflict = true; repaint(); return; } + try { a = await r.json(); } catch { /* refused below */ } + busy = false; + if (r.ok && a?.route) { + data = { ...data, route: a.route, revision: a.revision, routeMessage: undefined }; + draft = fromRoute(a.route); base = a.revision; + line = `Saved. Revision ${a.revision}.`; + repaint(); + $('triage-route-line')?.focus?.(); + return; + } + if (r.type === 'opaqueredirect') line = 'Sign in again, then retry.'; + else line = typeof a?.message === 'string' ? a.message : 'The route was refused. Nothing was saved.'; + if (r.status === 409 && a?.error === 'triage-route-stale') conflict = true; + repaint(); + $(conflict ? 'triage-route-reload' : 'triage-route-save')?.focus(); + } + + async function reload() { + if (busy) return; + draft = null; conflict = false; line = ''; + await read(); + line = data ? 'Route read again. Your fields now show the stored route.' : ''; + repaint(); + } + + const field = { 'triage-route-model': 'model', 'triage-route-harness': 'harness', 'triage-route-cap': 'cap', 'triage-route-zone': 'timeZone' }; + document.addEventListener('input', e => { + const k = field[e.target?.id]; if (!k || !$('triage-route')) return; + draft = { ...(draft ?? fromRoute(null)), [k]: e.target.value }; + }); + document.addEventListener('change', e => { + if (e.target?.id !== 'triage-route-model') return; + // A new model narrows the harness list; a harness the model does not take is cleared. + const d = draft = { ...(draft ?? fromRoute(null)), model: e.target.value }; + const hs = harnessesOf(d.model); + if (!hs.includes(d.harness)) d.harness = hs.length === 1 ? hs[0] : ''; + repaint(); $('triage-route-model')?.focus(); + }); + document.addEventListener('submit', e => { if (e.target?.id !== 'triage-route-form') return; e.preventDefault(); save(); }); + document.addEventListener('click', e => { if (e.target?.id === 'triage-route-reload') reload(); }); + + const hasDraft = () => !!(draft && data && JSON.stringify(draft) !== JSON.stringify(fromRoute(data.route))); + window.MosaicTriageRoute = { section, hasDraft }; +})(); diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index aadf23ba3..873c05a57 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -66,7 +66,7 @@ const files = new Map([ ['/', ['index.html', 'text/html; charset=utf-8']], ['/proxy.js', ['proxy.js', 'text/javascript; charset=utf-8']], ['/project-remote.js', ['project-remote.js', 'text/javascript; charset=utf-8']], - ...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'project-archive.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js', 'org-create.js', 'console-restart.js', 'onboarding.js', 'workspace-data.js', 'workspace.js', 'tasks-board.js', 'assistant.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]), + ...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'project-archive.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js', 'org-create.js', 'console-restart.js', 'onboarding.js', 'workspace-data.js', 'workspace.js', 'tasks-board.js', 'assistant.js', 'triage-settings.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]), ['/files.js', ['files.js', 'text/javascript; charset=utf-8']], ['/projects.js', ['projects.js', 'text/javascript; charset=utf-8']], ['/projects.css', ['projects.css', 'text/css; charset=utf-8']], diff --git a/packages/webui/src/triage-route-http.mjs b/packages/webui/src/triage-route-http.mjs new file mode 100644 index 000000000..4311c6686 --- /dev/null +++ b/packages/webui/src/triage-route-http.mjs @@ -0,0 +1,263 @@ +// #1873 triage-settings: the owner's read and write of the Triage model route, for Settings > Triage. +// GET and POST /api/triage/route register through serve.mjs's route table, so the server's session +// and Origin checks run first; this module then takes the proxy-admin gate (the instance owner's own +// session on the public name, never a tester or a granted user) and the same-origin checks again. +// A write goes through the route store (triage-route-store.mjs), so the lock, the revision compare +// and the receipt are the store's. Before it, the model and harness are checked the way an +// organization's route change is (checkRoutes in packages/organization/src/launch-settings.mjs): +// offered by the catalogue, available, and compatible with the harness. +// +// The catalogue lives in each organization's bus (the trusted bus boot builds it; nothing outside +// a bus holds the proxy client), so the Console reads it through each active organization's +// `routes` verb, as the proxy setup page does, and merges the answers (mergeCatalogues). +// +// Saving a route starts nothing: the Triage host is not wired to the store in this slice. +// No key, path, env value or exception text reaches a response or a log line. +import { readdirSync, lstatSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { checkRoutes } from '../../organization/src/launch-settings.mjs'; +import { isDailyModelQuota } from '../../plugins/src/model-quota.mjs'; +import { readRoute, writeRoute } from './triage-route-store.mjs'; + +export const TRIAGE_ROUTE_PATH = '/api/triage/route'; +export const BODY_MAX = 16384; +export const POST_KEYS = Object.freeze(['model', 'harness', 'cap', 'timeZone', 'revision']); +export const NOT_SET_MESSAGE = 'No Triage route is set.'; +export const NOT_STARTED_NOTE = 'Saving a route does not start Triage. The key and the wiring are separate.'; + +const HARNESS_ROOT = fileURLToPath(new URL('../../plugins/harness/', import.meta.url)); +// The same shapes the store holds (triage-route-store.mjs). +const MODEL_KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const HARNESS_NAME = /^[a-z][a-z0-9-]{0,31}$/; +const ACTOR = /^[a-z][a-z0-9-]{0,31}$/; +// The store's zone rule (its knownZone): isDailyModelQuota's zone shape, then Intl. +const knownZone = zone => typeof zone === 'string' && zone !== '' + && isDailyModelQuota('000000000000', { limit: 0, since: '2000-01-01T00:00:00.000Z', reset: '00:00', timeZone: zone }); +// The zone as Intl names it, so "america/chicago" is kept as "America/Chicago". A known zone that +// Intl renames to something the store would not take is kept as typed. +export function canonicalZone(zone) { + try { + const named = new Intl.DateTimeFormat('en-US', { timeZone: zone }).resolvedOptions().timeZone; + return knownZone(named) ? named : zone; + } catch { return zone; } +} + +const STATUS = Object.freeze({ + 'human-required': 403, + 'read-only': 403, + 'cross-origin': 403, + 'cross-site': 403, + 'method-not-allowed': 405, + 'invalid-request': 400, + 'triage-cap-invalid': 400, + 'triage-zone-required': 400, + 'triage-zone-unknown': 400, + 'unknown-model': 400, + 'model-harness-incompatible': 400, + 'harness-off': 400, + 'triage-route-invalid': 400, + 'triage-route-stale': 409, + 'triage-route-busy': 409, + 'model-provider-unavailable': 503, + 'triage-route-unreadable': 503, + 'triage-route-unrecorded': 500, + 'outcome-unknown': 503, +}); +// Fixed words for each code. The store's own messages name lock files, so none is forwarded. +const MESSAGES = Object.freeze({ + 'human-required': 'Only the instance owner can read or set the Triage route.', + 'read-only': 'This Console was started without writes, so the route cannot be saved.', + 'cross-origin': 'The request did not come from this Console page.', + 'cross-site': 'The request did not come from this Console page.', + 'method-not-allowed': 'This address takes GET and POST only.', + 'invalid-request': 'The request is not a Triage route. It takes model, harness, cap, timeZone and revision.', + 'triage-cap-invalid': 'The cap must be a whole number of tokens, 1 or more.', + 'triage-zone-required': 'A time zone is required. There is no default.', + 'triage-zone-unknown': 'That time zone is not known. Use a name like Europe/Berlin or America/Chicago.', + 'unknown-model': 'The model catalogue does not offer that model.', + 'model-harness-incompatible': 'That harness cannot run that model.', + 'harness-off': 'No harness module of that name is installed.', + 'triage-route-invalid': 'The route was refused as invalid.', + 'triage-route-stale': 'The route changed since this page read it. Reload the route before saving again.', + 'triage-route-busy': 'Another save of the route is in progress. Try again.', + 'model-provider-unavailable': 'The model catalogue cannot confirm that model now, so the route was not saved.', + 'triage-route-unreadable': 'The stored route could not be read.', + 'triage-route-unrecorded': 'The route was saved, but its receipt line was not written.', + 'outcome-unknown': 'The route service did not answer.', +}); + +const json = (res, status, value) => { + res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); + res.end(JSON.stringify(value)); +}; +const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null); +const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const identity = m => JSON.stringify([m.provider, m.model, m.module, m.upstream]); + +// The installed harness modules: a directory under packages/plugins/harness with an index.mjs. +export function installedHarnesses(root = HARNESS_ROOT) { + try { + return readdirSync(root).filter(name => HARNESS_NAME.test(name) && (() => { + try { return lstatSync(join(root, name, 'index.mjs')).isFile(); } catch { return false; } + })()).sort(); + } catch { return []; } +} + +// Each active organization's catalogue, merged into the one the Triage route is checked against. +// Only ready answers count. A key is offered when a ready catalogue lists it, and dropped when two +// catalogues disagree on what it is (provider, model, module, upstream). It is available only when +// every catalogue listing it says so, and its harnesses are those every listing names that are +// installed here. Status is ready when one catalogue is; otherwise the first status seen. +export function mergeCatalogues(list, harnesses) { + const ready = (Array.isArray(list) ? list : []).filter(c => c?.status === 'ready' && Array.isArray(c.models)); + if (!ready.length) { + const first = (Array.isArray(list) ? list : []).find(c => typeof c?.status === 'string')?.status; + return { status: first && first !== 'ready' ? first : 'unavailable', models: [] }; + } + const merged = new Map(), dropped = new Set(); + for (const catalogue of ready) { + for (const m of catalogue.models) { + if (!plain(m) || typeof m.key !== 'string' || !MODEL_KEY.test(m.key) || dropped.has(m.key)) continue; + const names = Array.isArray(m.harnesses) ? m.harnesses.filter(h => typeof h === 'string') : []; + const held = merged.get(m.key); + if (!held) { + merged.set(m.key, { key: m.key, label: typeof m.label === 'string' && m.label ? m.label : m.key, provider: m.provider, model: m.model, module: m.module, upstream: m.upstream, available: m.available === true, harnesses: names }); + continue; + } + if (identity(held) !== identity(m)) { merged.delete(m.key); dropped.add(m.key); continue; } + held.available = held.available && m.available === true; + held.harnesses = held.harnesses.filter(h => names.includes(h)); + } + } + const installed = new Set(harnesses); + const models = [...merged.values()].map(m => ({ ...m, harnesses: m.harnesses.filter(h => installed.has(h)) })).sort((a, b) => a.key.localeCompare(b.key)); + return { status: 'ready', models }; +} + +// The organization route check, called as it is for an organization's change: one role whose +// vars name the harness and model, launch.models holding the catalogue's own entry for that key +// (none when it is not offered), plugins.harness the installed harness modules, and +// plugins.model-provider the entry's module. It throws unknown-model, model-provider-unavailable, +// model-harness-incompatible or harness-off. +export function checkTriageRoute({ model, harness, catalogue, harnesses }) { + if (catalogue?.status !== 'ready') { + const error = new Error('model-provider-unavailable'); error.code = 'model-provider-unavailable'; throw error; + } + const offered = catalogue.models.find(m => m.key === model) ?? null; + const entry = offered ? { provider: offered.provider, model: offered.model, module: offered.module, upstream: offered.upstream } : null; + checkRoutes({ + proposed: { + roles: { triage: { vars: { harness, model } } }, + launch: { models: entry ? { [model]: entry } : {} }, + plugins: { harness: [...harnesses], 'model-provider': entry ? [entry.module] : [] }, + }, + old: null, + levels: () => null, + catalogue, + }); +} + +// What the signed-in owner is recorded as: their account id, or the dev local owner's subject. +export function ownerActor(session) { + if (typeof session?.account === 'string' && ACTOR.test(session.account)) return session.account; + if (session?.provider === 'local-dev' && typeof session.sub === 'string' && ACTOR.test(session.sub)) return session.sub; + return null; +} + +const view = doc => doc ? { + model: doc.model, harness: doc.harness, cap: doc.cap.limit, reset: doc.cap.reset, timeZone: doc.cap.timeZone, + revision: doc.revision, updatedAt: doc.updatedAt, +} : null; +// The panel's choices: no provider, upstream or module, only what a select shows. +const choices = catalogue => ({ + status: catalogue.status, + models: catalogue.models.map(m => ({ key: m.key, label: m.label, available: m.available, harnesses: [...m.harnesses] })), +}); + +async function readBody(req) { + if ((req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase() !== 'application/json') throw Error(); + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > BODY_MAX) throw Error(); + chunks.push(chunk); + } + const value = JSON.parse(Buffer.concat(chunks)); + if (!plain(value) || Object.keys(value).some(k => !POST_KEYS.includes(k))) throw Error(); + return value; +} + +// Registers both routes. `catalogues` returns each active organization's `routes` catalogue (or a +// status when its bus did not answer); `harnesses` lists the installed harness modules. +export function triageRouteRoutes({ dataRoot, catalogues, harnesses = installedHarnesses, log = () => {} }) { + async function catalogue() { + let list; + try { list = await catalogues(); } catch { list = []; } + return mergeCatalogues(list, harnesses()); + } + async function handle(req, res, context) { + const done = (status, value) => { + // Method, path and status only. + log(`${new Date().toISOString()} ${req.method} ${TRIAGE_ROUTE_PATH} ${status}`); + return json(res, status, value); + }; + const refuse = (code, extra = {}) => done(STATUS[code] ?? 503, { error: code, message: MESSAGES[code] ?? MESSAGES['outcome-unknown'], ...extra }); + if (req.method !== 'GET' && req.method !== 'POST') return refuse('method-not-allowed'); + // The proxy-admin gate: the instance owner's own session, never a tester or a granted user. + if (context.owner !== true || !context.session) return refuse('human-required'); + // A write needs this Console's Origin and same-origin Fetch Metadata, exactly once each. A read + // refuses another site's Origin or Fetch Metadata and lets their absence through, as the packs and + // request reads do: a browser sends no Origin on a same-origin GET, and Chromium sends no + // Fetch Metadata to a LAN http origin (serve.mjs marks only a LAN write). + if (req.method === 'POST') { + if (one(req, 'origin') !== context.origin) return refuse('cross-origin'); + if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse('cross-site'); + } else { + if (req.headersDistinct.origin && one(req, 'origin') !== context.origin) return refuse('cross-origin'); + if (req.headersDistinct['sec-fetch-site'] && !['same-origin', 'none'].includes(one(req, 'sec-fetch-site'))) return refuse('cross-site'); + } + if (req.method === 'GET') { + let doc; + try { doc = readRoute(dataRoot); } catch (error) { return refuse(error?.code === 'triage-route-unreadable' ? 'triage-route-unreadable' : 'outcome-unknown'); } + const route = view(doc); + return done(200, { + route, ...(route ? {} : { routeMessage: NOT_SET_MESSAGE }), revision: route ? route.revision : 0, + choices: choices(await catalogue()), send: context.send === true, note: NOT_STARTED_NOTE, + }); + } + if (context.send !== true) return refuse('read-only'); + let body; + try { body = await readBody(req); } catch { return refuse('invalid-request'); } + const { model, harness, cap, timeZone, revision } = body; + if (typeof model !== 'string' || !MODEL_KEY.test(model)) return refuse('unknown-model'); + if (typeof harness !== 'string' || !HARNESS_NAME.test(harness)) return refuse('harness-off'); + if (!Number.isSafeInteger(cap) || cap < 1) return refuse('triage-cap-invalid'); + if (timeZone === undefined || timeZone === null || timeZone === '') return refuse('triage-zone-required'); + if (!knownZone(timeZone)) return refuse('triage-zone-unknown'); + const zone = canonicalZone(timeZone); + if (!Number.isSafeInteger(revision) || revision < 0) return refuse('invalid-request'); + try { checkTriageRoute({ model, harness, catalogue: await catalogue(), harnesses: harnesses() }); } + catch (error) { + const code = ['unknown-model', 'model-provider-unavailable', 'model-harness-incompatible', 'harness-off'].includes(error?.code) ? error.code : 'outcome-unknown'; + return refuse(code); + } + const by = ownerActor(context.session); + if (by === null) return refuse('human-required'); + try { + const doc = writeRoute(dataRoot, { model, harness, limit: cap, timeZone: zone, by, revision }); + return done(200, { route: view(doc), revision: doc.revision, note: NOT_STARTED_NOTE }); + } catch (error) { + const code = typeof error?.code === 'string' && Object.hasOwn(MESSAGES, error.code) && error.code.startsWith('triage-route-') ? error.code : 'outcome-unknown'; + if (code !== 'triage-route-stale') return refuse(code); + let stored = null; + try { stored = view(readRoute(dataRoot)); } catch { /* the conflict still stands */ } + return refuse(code, { revision: stored ? stored.revision : 0 }); + } + } + return registered => { + registered.add('GET', TRIAGE_ROUTE_PATH, handle); + registered.add('POST', TRIAGE_ROUTE_PATH, handle); + }; +} diff --git a/packages/webui/tests/browser.test.mjs b/packages/webui/tests/browser.test.mjs index a52dbd10a..044a178ad 100644 --- a/packages/webui/tests/browser.test.mjs +++ b/packages/webui/tests/browser.test.mjs @@ -18,8 +18,8 @@ test('served Console browser: real board fixtures, keyboard, drafts, receipts, t assert.equal(await b.evaluate('document.querySelector("#session-count").textContent'), '3 of 4'); await b.evaluate('document.querySelector("#hide-offline").click()'); assert.equal(await b.evaluate('document.querySelectorAll("table.sessions tbody tr").length'), 4); - // Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. U5 (#1873) added panes.js (Side by side) just before bus.js; SP6 replaces it with assistant.js (the Assistant page), which bus.js mounts. - assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/assistant.js', '/bus.js', '/requests.js']); + // Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. triage-settings (#1873) adds triage-settings.js after console-restart.js. U5 (#1873) added panes.js (Side by side) just before bus.js; SP6 replaces it with assistant.js (the Assistant page), which bus.js mounts. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/triage-settings.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/assistant.js', '/bus.js', '/requests.js']); assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/processing.js"]').length`), 1); assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/chat.js"]').length`), 1); assert.equal(await b.evaluate('!!window.injected'), false); diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs index 8e05d03b8..a6b8a25d3 100644 --- a/packages/webui/tests/triage-drawer-browser.test.mjs +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -98,6 +98,9 @@ async function setup(t, { host = fakeHost(), triage = host.triage, send = true, // The page focuses its heading when its first render ends (bus.js). Open after that, as a person would, or // that late focus can land after the drawer's own. +// The Settings > Triage panel script (triage-settings, #1873) is a static file every page loads, like +// every other page module; it carries no data. These checks are about Triage traffic, so they skip it. +const SETTINGS_SCRIPT = 'GET /triage-settings.js'; const open = async f => { await f.wait('document.querySelector("#triage-open")'); await f.wait('document.activeElement?.tagName === "H1"', 100).catch(() => {}); await f.click('#triage-open'); await f.wait('["off", "cap", "running", "stopped"].includes(document.querySelector("#triage-drawer #triage-state")?.dataset.kind)'); }; const type = async (f, words) => { await f.b.evaluate('document.querySelector("#triage-text").focus()'); await f.b.call('Input.insertText', { text: words }); }; const sendAndWait = async (f, before) => { await f.click('#triage-send'); await f.wait(`document.querySelector("#triage-send-status").textContent.trim() && document.querySelector("#triage-send-status").textContent !== ${JSON.stringify(before)} && !document.querySelector("#triage-send").disabled`); return f.text('#triage-send-status'); }; @@ -109,7 +112,7 @@ test('item 1: a session that is not the instance owner gets no entry, no drawer await f.wait('document.querySelector("#dashboard-kpis")'); await sleep(1500); assert.equal(await f.b.evaluate('document.querySelector("#triage-open, #triage-drawer, [id^=triage]")'), null); - assert.deepEqual(f.requests.filter(r => /triage/i.test(r)), []); + assert.deepEqual(f.requests.filter(r => /triage/i.test(r) && r !== SETTINGS_SCRIPT), []); } // A Triage host, but a signed-in session that is not the root owner. { @@ -119,7 +122,7 @@ test('item 1: a session that is not the instance owner gets no entry, no drawer await sleep(1500); assert.equal(await f.b.evaluate('document.querySelector("[id^=triage]")'), null); assert.equal(await f.b.evaluate('document.body.innerHTML.includes("Triage")'), false, 'no Triage words in the page'); - assert.deepEqual(f.requests.filter(r => /triage/i.test(r)), []); + assert.deepEqual(f.requests.filter(r => /triage/i.test(r) && r !== SETTINGS_SCRIPT), []); } }); @@ -135,7 +138,7 @@ test('item 1: the owner gets one Triage entry in the top bar on the dashboard an assert.equal(await f.b.evaluate('document.querySelector("#triage-open").getAttribute("aria-expanded")'), 'true'); // From inside an organization the read is still the system route, never the organization's. assert.ok(f.triageReads() >= 1); - assert.deepEqual(f.requests.filter(r => /triage/.test(r) && r !== 'GET /api/triage'), []); + assert.deepEqual(f.requests.filter(r => /triage/.test(r) && r !== 'GET /api/triage' && r !== SETTINGS_SCRIPT), []); assert.ok(f.requests.includes('GET /api/config'), 'the unscoped config read'); // The same entry on the system dashboard. await f.b.evaluate('location.hash = "#/dashboard"'); diff --git a/packages/webui/tests/triage-route-http.test.mjs b/packages/webui/tests/triage-route-http.test.mjs new file mode 100644 index 000000000..8c527be37 --- /dev/null +++ b/packages/webui/tests/triage-route-http.test.mjs @@ -0,0 +1,393 @@ +// #1873 triage-settings: GET and POST /api/triage/route over the real HTTP boundary. Only the instance +// owner reaches them, a write is same-origin, the model and harness are checked as an organization's +// route change is, the store does the write (one receipt), and no key or path reaches a response. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { request } from 'node:http'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startServer } from '../src/serve.mjs'; +import { createDevOwner } from '../src/dev-owner.mjs'; +import { consoleAccess } from '../src/access.mjs'; +import { createSsoSession } from './helpers/sso-session.mjs'; +import { routePaths, readRoute, writeRoute } from '../src/triage-route-store.mjs'; +import { triageRouteRoutes, mergeCatalogues, installedHarnesses, ownerActor, TRIAGE_ROUTE_PATH, NOT_STARTED_NOTE } from '../src/triage-route-http.mjs'; + +const SECRET = 'sk-triage-route-sentinel-0123456789abcdef'; +const T = '2026-11-18T12:00:00.000Z'; +const model = (key, extra = {}) => ({ key, module: 'anthropic', upstream: 'cliproxy', provider: 'anthropic', model: `claude-${key}`, label: key.toUpperCase(), available: true, reason: null, harnesses: ['claude-code', 'pi'], ...extra }); +// One catalogue as an organization's `routes` verb answers. A leaked field would carry the sentinel. +const READY = () => ({ status: 'ready', observedAt: T, notices: [`key ${SECRET} at /srv/proxy/keys.json`], models: [ + model('sonnet', { reason: `${SECRET} /home/owner/.config/mosaic-dev/proxy.json` }), + model('glm-flash', { module: 'opencode', provider: 'zai', model: 'glm-5.3-flash', harnesses: ['pi'] }), + model('down', { available: false, reason: 'proxy says no' }), +] }); +const BODY = { model: 'sonnet', harness: 'claude-code', cap: 200000, timeZone: 'Europe/Berlin', revision: 0 }; + +const send = (port, path, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve, reject) => { + const req = request({ host: '127.0.0.1', port, path, method, headers }, res => { + let text = ''; res.on('data', c => { text += c; }); res.on('end', () => resolve({ status: res.statusCode, text, json: (() => { try { return JSON.parse(text); } catch { return null; } })() })); + }); + req.on('error', reject); req.end(body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body)); +}); +const receipts = root => { const f = routePaths(root).receipts; return existsSync(f) ? readFileSync(f, 'utf8').split('\n').filter(Boolean).map(l => JSON.parse(l)) : []; }; + +async function devServer(t, { catalogues = async () => [READY()], harnesses = () => ['claude-code', 'pi'], ...options } = {}) { + const root = mkdtempSync(join(tmpdir(), 'tr-http-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const logs = [], routeLogs = []; + const s = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso: createDevOwner(), send: async () => ({}), log: line => logs.push(line), + routes: [triageRouteRoutes({ dataRoot: root, catalogues, harnesses, log: line => routeLogs.push(line) })], ...options }); + t.after(() => new Promise(r => s.close(r))); + const port = s.address().port; + const origin = `http://127.0.0.1:${port}`; + const read = { host: `127.0.0.1:${port}`, 'sec-fetch-site': 'same-origin' }; + const write = { ...read, origin, 'content-type': 'application/json' }; + const get = (headers = read) => send(port, TRIAGE_ROUTE_PATH, { headers }); + const post = (body = BODY, headers = write) => send(port, TRIAGE_ROUTE_PATH, { method: 'POST', headers, body }); + return { s, port, root, logs, routeLogs, read, write, get, post }; +} + +test('GET without a stored route says it is not set and offers the catalogue models with their harnesses', async t => { + const f = await devServer(t); + const r = await f.get(); + assert.equal(r.status, 200); + assert.equal(r.json.route, null); + assert.equal(r.json.routeMessage, 'No Triage route is set.'); + assert.equal(r.json.revision, 0); + assert.equal(r.json.send, true); + assert.equal(r.json.note, NOT_STARTED_NOTE); + assert.deepEqual(r.json.choices, { status: 'ready', models: [ + { key: 'down', label: 'DOWN', available: false, harnesses: ['claude-code', 'pi'] }, + { key: 'glm-flash', label: 'GLM-FLASH', available: true, harnesses: ['pi'] }, + { key: 'sonnet', label: 'SONNET', available: true, harnesses: ['claude-code', 'pi'] }, + ] }); + assert.equal(r.text.includes(SECRET), false); + assert.equal(r.text.includes(f.root), false); + assert.equal(r.text.includes('/srv/') || r.text.includes('/home/'), false); +}); + +test('GET with a stored route returns its model, harness, cap, reset, zone, revision and time, and no path or actor detail', async t => { + const f = await devServer(t); + writeRoute(f.root, { model: 'sonnet', harness: 'pi', limit: 5000, timeZone: 'America/Chicago', by: 'local-dev-owner' }, { now: () => new Date(T) }); + const r = await f.get(); + assert.equal(r.status, 200); + assert.deepEqual(r.json.route, { model: 'sonnet', harness: 'pi', cap: 5000, reset: '00:00', timeZone: 'America/Chicago', revision: 1, updatedAt: T }); + assert.equal(r.json.revision, 1); + assert.equal(Object.hasOwn(r.json, 'routeMessage'), false); + assert.equal(r.text.includes(f.root), false); +}); + +test('POST writes through the store: one receipt, the signed-in owner as updatedBy, the revision moves', async t => { + const f = await devServer(t); + const r = await f.post(); + assert.equal(r.status, 200, r.text); + assert.equal(r.json.route.model, 'sonnet'); + assert.equal(r.json.route.harness, 'claude-code'); + assert.equal(r.json.route.cap, 200000); + assert.equal(r.json.route.timeZone, 'Europe/Berlin'); + assert.equal(r.json.route.reset, '00:00'); + assert.equal(r.json.revision, 1); + assert.equal(r.json.note, NOT_STARTED_NOTE); + const doc = readRoute(f.root); + assert.equal(doc.updatedBy, 'local-dev-owner'); + assert.equal(doc.cap.limit, 200000); + const lines = receipts(f.root); + assert.equal(lines.length, 1); + assert.equal(lines[0].by, 'local-dev-owner'); + assert.equal(lines[0].revision, 1); + const again = await f.post({ ...BODY, harness: 'pi', revision: 1 }); + assert.equal(again.status, 200); + assert.equal(receipts(f.root).length, 2); + for (const line of f.routeLogs) assert.match(line, /^\S+ (GET|POST) \/api\/triage\/route \d{3}$/); +}); + +test('a stale revision answers 409 with the stored revision and writes nothing', async t => { + const f = await devServer(t); + assert.equal((await f.post()).status, 200); + const stale = await f.post({ ...BODY, cap: 9 }); + assert.equal(stale.status, 409); + assert.equal(stale.json.error, 'triage-route-stale'); + assert.equal(stale.json.revision, 1); + assert.match(stale.json.message, /changed since this page read it/); + assert.equal(readRoute(f.root).cap.limit, 200000); + assert.equal(receipts(f.root).length, 1); +}); + +test('a model the catalogue does not offer, or one it marks unavailable, is refused and nothing is written', async t => { + const f = await devServer(t); + const unknown = await f.post({ ...BODY, model: 'opus' }); + assert.equal(unknown.status, 400); + assert.equal(unknown.json.error, 'unknown-model'); + const down = await f.post({ ...BODY, model: 'down' }); + assert.equal(down.status, 503); + assert.equal(down.json.error, 'model-provider-unavailable'); + for (const bad of [7, ['sonnet'], { key: 'sonnet' }, 'BAD KEY', '']) { + const r = await f.post({ ...BODY, model: bad }); + assert.equal(r.status, 400, JSON.stringify(bad)); + assert.equal(r.json.error, 'unknown-model', JSON.stringify(bad)); + } + assert.equal(readRoute(f.root), null); + assert.deepEqual(receipts(f.root), []); +}); + +test('a harness the model is not compatible with, or one not installed, is refused', async t => { + const f = await devServer(t); + const wrong = await f.post({ ...BODY, model: 'glm-flash', harness: 'claude-code' }); + assert.equal(wrong.status, 400); + assert.equal(wrong.json.error, 'model-harness-incompatible'); + // Installed here is only pi: the catalogue's claude-code is not offered and not accepted. + const g = await devServer(t, { harnesses: () => ['pi'] }); + assert.deepEqual((await g.get()).json.choices.models.find(m => m.key === 'sonnet').harnesses, ['pi']); + const off = await g.post({ ...BODY, harness: 'claude-code' }); + assert.equal(off.status, 400); + assert.ok(['model-harness-incompatible', 'harness-off'].includes(off.json.error), off.text); + const bad = await f.post({ ...BODY, harness: 'Not A Name' }); + assert.equal(bad.json.error, 'harness-off'); + assert.equal(readRoute(f.root), null); + assert.equal(readRoute(g.root), null); +}); + +test('the installed harness check is the organization one: a compatible harness no module provides is harness-off', async t => { + const catalogue = READY(); catalogue.models[0].harnesses = ['claude-code', 'pi', 'ghost']; + // harnesses() lists ghost so the merged catalogue keeps it; the check gets the installed list without it. + let calls = 0; + const f = await devServer(t, { catalogues: async () => [catalogue], harnesses: () => (++calls % 2 === 1 ? ['claude-code', 'pi', 'ghost'] : ['claude-code', 'pi']) }); + const r = await f.post({ ...BODY, harness: 'ghost' }); + assert.equal(r.json.error, 'harness-off', r.text); +}); + +test('a catalogue that is not ready, or no organization bus answering, refuses the write and shows no choices', async t => { + for (const catalogues of [async () => [{ status: 'starting', models: [] }], async () => [{ status: 'bus-unavailable' }], async () => [], async () => { throw new Error(SECRET); }]) { + const f = await devServer(t, { catalogues }); + const r = await f.get(); + assert.equal(r.status, 200); + assert.deepEqual(r.json.choices.models, []); + assert.notEqual(r.json.choices.status, 'ready'); + const w = await f.post(); + assert.equal(w.status, 503); + assert.equal(w.json.error, 'model-provider-unavailable'); + assert.equal(w.text.includes(SECRET) || r.text.includes(SECRET), false); + assert.equal(readRoute(f.root), null); + } +}); + +test('a missing or unknown time zone is refused; there is no default', async t => { + const f = await devServer(t); + const { timeZone, ...noZone } = BODY; + for (const body of [noZone, { ...BODY, timeZone: '' }, { ...BODY, timeZone: null }]) { + const r = await f.post(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.equal(r.json.error, 'triage-zone-required', JSON.stringify(body)); + } + for (const zone of ['Mars/Olympus', 'not a zone', 42]) { + const r = await f.post({ ...BODY, timeZone: zone }); + assert.equal(r.status, 400, String(zone)); + assert.equal(r.json.error, 'triage-zone-unknown', String(zone)); + } + assert.equal(readRoute(f.root), null); + const lower = await f.post({ ...BODY, timeZone: 'america/chicago' }); + assert.equal(lower.status, 200, JSON.stringify(lower.json)); + assert.equal(readRoute(f.root).cap.timeZone, 'America/Chicago', 'a zone in another case is stored in its canonical spelling'); + assert.equal(lower.json.route.timeZone, 'America/Chicago'); +}); + +test('a cap that is not a positive whole number is refused', async t => { + const f = await devServer(t); + for (const cap of [0, -1, 1.5, '1000', null, undefined, Number.MAX_SAFE_INTEGER + 1, true]) { + const body = { ...BODY, cap }; if (cap === undefined) delete body.cap; + const r = await f.post(body); + assert.equal(r.status, 400, String(cap)); + assert.equal(r.json.error, 'triage-cap-invalid', String(cap)); + } + assert.equal((await f.post({ ...BODY, cap: 1 })).status, 200, 'one token is a cap'); +}); + +test('a body with another key, a bad revision, a wrong type or too many bytes is invalid-request', async t => { + const f = await devServer(t); + for (const body of [{ ...BODY, by: 'mallory' }, { ...BODY, revision: -1 }, { ...BODY, revision: '0' }, [BODY], 'null', '{', JSON.stringify({ ...BODY, model: 'a'.repeat(17000) })]) { + const r = await f.post(body); + assert.equal(r.status, 400, typeof body === 'string' ? body.slice(0, 20) : JSON.stringify(body).slice(0, 60)); + assert.equal(r.json.error, 'invalid-request'); + } + const { revision, ...noRevision } = BODY; + assert.equal((await f.post(noRevision)).json.error, 'invalid-request', 'the revision is required'); + const text = await f.post(BODY, { ...f.write, 'content-type': 'text/plain' }); + assert.equal(text.json.error, 'invalid-request'); + assert.equal(readRoute(f.root), null); +}); + +test('both routes refuse a cross-origin request; a read may omit the metadata; a write needs both checks exactly once', async t => { + const f = await devServer(t); + // Read: a foreign Origin or cross-site Fetch Metadata is refused. Missing metadata is the repo GET convention. + const evil = await f.get({ ...f.read, origin: 'http://evil.example' }); + assert.equal(evil.status, 403); + assert.match(evil.json.error, /^cross-origin/, 'the serve gate or the handler refuses it'); + const bare = await f.get({ host: f.read.host }); + assert.equal(bare.status, 200, 'a read with no Origin and no Fetch Metadata is allowed'); + assert.equal((await f.get({ ...f.read, 'sec-fetch-site': 'none' })).status, 200, 'a typed address is allowed'); + const cross = await f.get({ ...f.read, 'sec-fetch-site': 'cross-site' }); + assert.equal(cross.status, 403); + assert.equal(cross.json.error, 'cross-site'); + assert.equal((await f.get({ host: f.read.host, 'sec-fetch-site': 'same-site' })).status, 403); + assert.equal((await f.get({ ...f.read, origin: `http://127.0.0.1:${f.port}` })).status, 200, 'a matching Origin on a read is fine'); + // Write: missing Origin, foreign Origin, missing or cross-site Fetch Metadata. + const { origin, ...noOrigin } = f.write; + const missing = await f.post(BODY, noOrigin); + assert.equal(missing.status, 403); + assert.match(missing.json.error, /^cross-origin/, 'the serve gate or the handler refuses it'); + assert.equal((await f.post(BODY, { ...f.write, origin: 'http://evil.example' })).status, 403); + const { 'sec-fetch-site': _, ...noSite } = f.write; + assert.equal((await f.post(BODY, noSite)).status, 403); + assert.equal((await f.post(BODY, { ...f.write, 'sec-fetch-site': 'same-site' })).status, 403); + assert.equal(readRoute(f.root), null); + assert.deepEqual(receipts(f.root), []); +}); + +test('a LAN dev host reads the route with no Fetch Metadata and writes with its own Origin', async t => { + const f = await devServer(t, { devAllowHosts: ['lanbox'] }); + const host = `lanbox:${f.port}`; + const r = await f.get({ host }); + assert.equal(r.status, 200); + assert.equal(r.json.route, null); + const w = await f.post(BODY, { host, origin: `http://${host}`, 'content-type': 'application/json' }); + assert.equal(w.status, 200, JSON.stringify(w.json)); + assert.equal(readRoute(f.root).model, BODY.model); + const foreign = await f.post(BODY, { host, origin: 'http://evil.example', 'content-type': 'application/json' }); + assert.equal(foreign.status, 403); + assert.equal(readRoute(f.root).revision, 1); +}); + +test('the handler holds the same-origin line itself: a doubled Origin or Sec-Fetch-Site is refused', async t => { + const root = mkdtempSync(join(tmpdir(), 'tr-unit-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + let handler; + triageRouteRoutes({ dataRoot: root, catalogues: async () => [READY()], harnesses: () => ['claude-code', 'pi'] })({ add: (method, path, fn) => { handler = fn; } }); + const call = (method, headersDistinct, extra = {}) => new Promise(resolve => { + const res = { writeHead(status) { this.status = status; }, end(text) { resolve({ status: this.status, json: JSON.parse(text) }); } }; + const req = { method, headersDistinct, headers: { 'content-type': 'application/json' }, async *[Symbol.asyncIterator]() { yield Buffer.from(JSON.stringify(BODY)); } }; + handler(req, res, { owner: true, session: { provider: 'local-dev', sub: 'local-dev-owner' }, origin: 'https://console.example', send: true, ...extra }); + }); + const o = 'https://console.example'; + for (const method of ['PUT', 'DELETE', 'PATCH']) assert.equal((await call(method, { origin: [o], 'sec-fetch-site': ['same-origin'] })).json.error, 'method-not-allowed', method); + assert.equal(readRoute(root), null); + assert.equal((await call('GET', { origin: [o, o], 'sec-fetch-site': ['same-origin'] })).json.error, 'cross-origin'); + assert.equal((await call('GET', { 'sec-fetch-site': ['same-origin', 'same-origin'] })).json.error, 'cross-site'); + assert.equal((await call('GET', { origin: ['https://evil.example'], 'sec-fetch-site': ['same-origin'] })).json.error, 'cross-origin'); + assert.equal((await call('POST', { origin: [o, o], 'sec-fetch-site': ['same-origin'] })).json.error, 'cross-origin'); + assert.equal((await call('POST', { origin: [o], 'sec-fetch-site': ['same-origin', 'same-origin'] })).json.error, 'cross-site'); + assert.equal((await call('POST', { origin: [o], 'sec-fetch-site': ['same-origin'] }, { send: false })).json.error, 'read-only'); + assert.equal((await call('GET', { 'sec-fetch-site': ['same-origin'] }, { owner: false })).json.error, 'human-required'); + assert.equal((await call('POST', { origin: [o], 'sec-fetch-site': ['same-origin'] }, { owner: false })).json.error, 'human-required'); + assert.equal((await call('POST', { origin: [o], 'sec-fetch-site': ['same-origin'] }, { session: { provider: 'oidc', sub: 'Owner Sub' } })).json.error, 'human-required', 'an owner with no recordable name is refused'); + assert.equal(readRoute(root), null); + assert.equal((await call('POST', { origin: [o], 'sec-fetch-site': ['same-origin'] })).status, 200); +}); + +test('a read-only Console reads the route but refuses a write', async t => { + const f = await devServer(t, { send: null }); + const r = await f.get(); + assert.equal(r.status, 200); + assert.equal(r.json.send, false); + const w = await f.post(); + assert.equal(w.status, 403); + assert.equal(w.json.error, 'read-only'); + assert.equal(readRoute(f.root), null); +}); + +test('an SSO root owner reads and writes as their account; a granted user and a signed-out caller reach neither route', async t => { + const access = { accessVersion: 1, revision: 1, + users: [{ id: 'alice', home: 'local', subjects: [{ provider: 'writer', sub: 'alice-sub' }] }], + grants: [{ id: 'g-1', user: 'alice', business: 'demo', projects: ['*'], instances: ['*'], level: 'collaborator' }] }; + const auth = await createSsoSession(t, { host: 'console.example', users: consoleAccess({ load: () => access, business: () => 'demo' }) }); + const root = mkdtempSync(join(tmpdir(), 'tr-sso-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const s = await startServer({ port: 0, sso: auth.sso, send: async () => ({}), log: () => {}, + routes: [triageRouteRoutes({ dataRoot: root, catalogues: async () => [READY()], harnesses: () => ['claude-code', 'pi'] })] }); + t.after(() => new Promise(r => s.close(r))); + const port = s.address().port; + const owner = auth.writeHeaders(await auth.signIn(port)); + assert.equal((await send(port, TRIAGE_ROUTE_PATH, { headers: owner })).status, 200); + const saved = await send(port, TRIAGE_ROUTE_PATH, { method: 'POST', headers: owner, body: BODY }); + assert.equal(saved.status, 200, saved.text); + assert.match(readRoute(root).updatedBy, /^u-[0-9a-f]{12}$/); + const alice = auth.writeHeaders(await auth.signIn(port, { sub: 'alice-sub' })); + const aliceRead = await send(port, TRIAGE_ROUTE_PATH, { headers: alice }); + assert.equal(aliceRead.status, 403); + assert.ok(['owner-only', 'human-required'].includes(aliceRead.json.error), aliceRead.text); + assert.equal(aliceRead.text.includes('sonnet'), false, 'a granted user sees no route'); + const aliceWrite = await send(port, TRIAGE_ROUTE_PATH, { method: 'POST', headers: alice, body: { ...BODY, revision: 1, cap: 7 } }); + assert.equal(aliceWrite.status, 403); + const nobody = await send(port, TRIAGE_ROUTE_PATH, { headers: { host: 'console.example', 'sec-fetch-site': 'same-origin' } }); + assert.equal(nobody.status, 401); + const nobodyWrite = await send(port, TRIAGE_ROUTE_PATH, { method: 'POST', headers: { host: 'console.example', origin: 'https://console.example', 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' }, body: { ...BODY, revision: 1 } }); + assert.equal(nobodyWrite.status, 401); + // Cross-origin as the owner, on the public name. + assert.equal((await send(port, TRIAGE_ROUTE_PATH, { method: 'POST', headers: { ...owner, origin: 'https://evil.example' }, body: { ...BODY, revision: 1 } })).status, 403); + assert.equal((await send(port, TRIAGE_ROUTE_PATH, { headers: { ...owner, origin: 'https://evil.example' } })).status, 403); + assert.equal(readRoute(root).revision, 1); + assert.equal(readRoute(root).cap.limit, 200000); + assert.equal(receipts(root).length, 1); +}); + +test('the tester listener reaches neither route', async t => { + const { startTesterSocket } = await import('../src/tester-socket.mjs'); + const { testerRequest } = await import('../../cli/src/tester-http.mjs'); + const root = mkdtempSync(join(tmpdir(), 'tr-tester-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const s = await startTesterSocket({ dataRoot: root, log: () => {}, routes: [triageRouteRoutes({ dataRoot: root, catalogues: async () => [READY()], harnesses: () => ['claude-code', 'pi'] })] }); + t.after(() => new Promise(r => s.close(r))); + for (const method of ['GET', 'POST']) { + const r = await testerRequest({ dataRoot: root, path: TRIAGE_ROUTE_PATH, method, body: method === 'POST' ? BODY : undefined }); + assert.equal(r.status, 403, method); + } + assert.equal(readRoute(root), null); +}); + +test('a busy store and an unreadable store answer with fixed words and no path', async t => { + const f = await devServer(t); + assert.equal((await f.post()).status, 200); + const { lock, file } = routePaths(f.root); + writeFileSync(lock, JSON.stringify({ pid: process.pid, at: T }), { mode: 0o600 }); + const busy = await f.post({ ...BODY, revision: 1 }); + assert.equal(busy.status, 409); + assert.equal(busy.json.error, 'triage-route-busy'); + assert.equal(busy.text.includes(f.root) || busy.text.includes('route.lock'), false); + rmSync(lock); + writeFileSync(file, '{not json', { mode: 0o600 }); + const broken = await f.get(); + assert.equal(broken.status, 503); + assert.equal(broken.json.error, 'triage-route-unreadable'); + assert.equal(broken.text.includes(f.root) || broken.text.includes('route.json'), false); + const brokenWrite = await f.post({ ...BODY, revision: 1 }); + assert.equal(brokenWrite.json.error, 'triage-route-unreadable'); + assert.equal(brokenWrite.text.includes(f.root), false); +}); + +test('no response or log line carries the sentinel, the data root or a store path', async t => { + const f = await devServer(t); + const all = [await f.get(), await f.post(), await f.get(), await f.post({ ...BODY, cap: 0 }), await f.post({ ...BODY, model: 'opus' }), await f.post({ ...BODY, revision: 0 }), await f.post(BODY, { ...f.write, origin: 'http://evil.example' })]; + const text = all.map(r => r.text).join('\n') + f.routeLogs.join('\n') + f.logs.join('\n'); + for (const needle of [SECRET, f.root, 'route.json', 'route.lock', 'route-receipts', '/srv/', '/home/', 'cliproxy', 'anthropic']) assert.equal(text.includes(needle), false, needle); +}); + +test('mergeCatalogues: a key two catalogues disagree on is dropped; availability and harnesses must hold everywhere', () => { + const a = { status: 'ready', models: [model('sonnet'), model('glm', { harnesses: ['pi'] }), model('x', { available: false })] }; + const b = { status: 'ready', models: [model('sonnet', { harnesses: ['pi'] }), model('glm', { upstream: 'other' }), model('x'), model('y', { available: false })] }; + a.models.push(model('y')); + const merged = mergeCatalogues([a, b, { status: 'bus-unavailable' }], ['claude-code', 'pi']); + assert.equal(merged.status, 'ready'); + assert.deepEqual(merged.models.map(m => [m.key, m.available, m.harnesses]), [['sonnet', true, ['pi']], ['x', false, ['claude-code', 'pi']], ['y', false, ['claude-code', 'pi']]]); + assert.deepEqual(mergeCatalogues([{ status: 'starting' }], ['pi']), { status: 'starting', models: [] }); + assert.deepEqual(mergeCatalogues([], ['pi']), { status: 'unavailable', models: [] }); + assert.deepEqual(mergeCatalogues([{ status: 'ready', models: [{ key: 'BAD KEY', harnesses: ['pi'] }, null] }], ['pi']).models, []); +}); + +test('installedHarnesses lists the harness modules on disk; ownerActor names the account or the dev owner', () => { + assert.deepEqual(installedHarnesses(), ['claude-code', 'pi']); + assert.equal(ownerActor({ account: 'u-0123456789ab', provider: 'writer', sub: 'x' }), 'u-0123456789ab'); + assert.equal(ownerActor({ provider: 'local-dev', sub: 'local-dev-owner' }), 'local-dev-owner'); + assert.equal(ownerActor({ provider: 'writer', sub: 'owner-sub' }), null); + assert.equal(ownerActor(null), null); +}); diff --git a/packages/webui/tests/triage-settings-browser.test.mjs b/packages/webui/tests/triage-settings-browser.test.mjs new file mode 100644 index 000000000..f971da001 --- /dev/null +++ b/packages/webui/tests/triage-settings-browser.test.mjs @@ -0,0 +1,262 @@ +// #1873 triage-settings: Settings > Triage in a real browser. The owner sees "not set", picks a model, +// a harness from that model's list, a cap and a time zone, and saves in three clicks; a refusal is one +// line and keeps the fields; a stale revision offers a re-read; a second Save while one runs does +// nothing; anyone /api/config does not call the owner gets no Triage page and no route read. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { w15Fixture } from './w15-fixture.mjs'; + +const T = '2026-11-18T12:00:00.000Z'; +const NOTE = 'Saving a route does not start Triage. The key and the wiring are separate.'; +const choices = { status: 'ready', models: [ + { key: 'down', label: 'Down', available: false, harnesses: ['claude-code'] }, + { key: 'glm-flash', label: 'GLM Flash', available: true, harnesses: ['pi'] }, + { key: 'sonnet', label: 'Sonnet', available: true, harnesses: ['claude-code', 'pi'] }, +] }; +const unset = { route: null, routeMessage: 'No Triage route is set.', revision: 0, choices, send: true, note: NOTE }; +const route = (over = {}) => ({ model: 'sonnet', harness: 'pi', cap: 200000, reset: '00:00', timeZone: 'Europe/Berlin', revision: 1, updatedAt: T, ...over }); +const config = (over = {}) => ({ send: true, devOwner: true, sso: true, proxyAdmin: true, proxyAdminSend: true, ...over }); +const scenario = (read = unset, extra = {}, cfg = {}) => ({ '/api/config': config(cfg), '/api/triage/route': read, ...extra }); +const writes = b => b.evaluate('window.__writes.filter(w=>w.path==="/api/triage/route").map(w=>({method:w.method,body:JSON.parse(w.body)}))'); +// The fixture answers in the page, so no resource timing exists: count the route reads in a wrapper. +const countReads = b => b.call('Page.addScriptToEvaluateOnNewDocument', { source: '(()=>{window.__routeReads=0;const prev=window.fetch;window.fetch=(i,init)=>{try{if(new URL(typeof i==="string"?i:i.url,location.href).pathname==="/api/triage/route"&&(init?.method??"GET")==="GET")window.__routeReads++;}catch{}return prev(i,init);};})()' }); +const reads = b => b.evaluate('window.__routeReads'); +const pick = (b, id, value) => b.evaluate(`(()=>{const el=document.getElementById(${JSON.stringify(id)});el.value=${JSON.stringify(value)};el.dispatchEvent(new Event('input',{bubbles:true}));el.dispatchEvent(new Event('change',{bubbles:true}));})()`); +const type = (b, id, value) => b.evaluate(`(()=>{const el=document.getElementById(${JSON.stringify(id)});el.value=${JSON.stringify(value)};el.dispatchEvent(new Event('input',{bubbles:true}));})()`); +const text = (b, id) => b.evaluate(`document.getElementById(${JSON.stringify(id)})?.textContent ?? null`); +const value = (b, id) => b.evaluate(`document.getElementById(${JSON.stringify(id)})?.value ?? null`); +const options = (b, id) => b.evaluate(`[...document.getElementById(${JSON.stringify(id)}).options].map(o=>[o.value,o.textContent,o.disabled])`); +async function fill(b, { model = 'sonnet', harness = 'claude-code', cap = '150000', zone = 'America/Chicago' } = {}) { + await pick(b, 'triage-route-model', model); + if (harness !== null) await pick(b, 'triage-route-harness', harness); + await type(b, 'triage-route-cap', cap); + await type(b, 'triage-route-zone', zone); +} + +test('the owner sees Triage in Settings, "not set" before a first save, the catalogue choices and the note', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: scenario() }); + await countReads(b); + await b.navigate(f.base + '/#/settings'); + await wait('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\')'); + await b.evaluate('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\').click()'); + await wait('document.getElementById("triage-route-stored")'); + assert.match(await text(b, 'triage-route-stored'), /^Not set\. No Triage route is set\.$/); + assert.ok(await reads(b) >= 1, 'the owner page reads the route (the counter works)'); + assert.equal(await text(b, 'triage-route-note'), NOTE); + assert.equal(await text(b, 'settings-page-title'), 'Triage'); + assert.deepEqual(await options(b, 'triage-route-model'), [['', 'Choose a model', false], ['down', 'Down (down) (unavailable)', true], ['glm-flash', 'GLM Flash (glm-flash)', false], ['sonnet', 'Sonnet (sonnet)', false]]); + assert.deepEqual(await options(b, 'triage-route-harness'), [['', 'Choose a model first', false]]); + assert.equal(await value(b, 'triage-route-cap'), '', 'no default cap'); + assert.equal(await value(b, 'triage-route-zone'), '', 'no default time zone'); + assert.equal(await value(b, 'triage-route-reset'), '00:00'); + assert.equal(await b.evaluate('document.getElementById("triage-route-reset").readOnly'), true); + assert.equal(await b.evaluate('document.querySelector(".settings-readonly")'), null); + assert.equal(await b.evaluate('document.getElementById("triage-route-catalogue")'), null); + // The harness list follows the model; a model with one harness picks it. + await pick(b, 'triage-route-model', 'glm-flash'); + assert.deepEqual(await options(b, 'triage-route-harness'), [['', 'Choose a harness', false], ['pi', 'pi', false]]); + assert.equal(await value(b, 'triage-route-harness'), 'pi'); + await pick(b, 'triage-route-model', 'sonnet'); + assert.deepEqual((await options(b, 'triage-route-harness')).map(o => o[0]), ['', 'claude-code', 'pi']); + assert.equal(await value(b, 'triage-route-harness'), 'pi', 'a harness the new model takes is kept'); + assert.deepEqual(await writes(b), []); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); + assert.deepEqual(await b.evaluate('window.__errors'), []); +}); + +test('Save posts the fields and the read revision once, then shows the stored route; three clicks from Settings', { timeout: 90000 }, async t => { + const saved = route({ harness: 'claude-code', cap: 150000, timeZone: 'America/Chicago' }); + const { f, b, wait } = await w15Fixture(t, { scenario: scenario(unset, { 'POST /api/triage/route': { body: { route: saved, revision: 1, note: NOTE } } }) }); + await b.navigate(f.base + '/#/settings'); + await wait('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\')'); + await b.evaluate('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\').click()'); + await wait('document.getElementById("triage-route-model")'); + await fill(b, { zone: ' America/Chicago ' }); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait('document.getElementById("triage-route-line")?.textContent==="Saved. Revision 1."'); + assert.equal(await b.evaluate('document.activeElement?.id'), 'triage-route-line', 'focus lands on the saved line, not the page body'); + assert.deepEqual(await writes(b), [{ method: 'POST', body: { model: 'sonnet', harness: 'claude-code', cap: 150000, timeZone: 'America/Chicago', revision: 0 } }]); + assert.match(await text(b, 'triage-route-stored'), /Stored route: sonnet on claude-code, cap 150,000 tokens a day, reset 00:00 America\/Chicago\. Revision 1/); + assert.equal(await value(b, 'triage-route-cap'), '150000'); + // The next save carries the new revision. + await type(b, 'triage-route-cap', '9000'); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait('window.__writes.filter(w=>w.path==="/api/triage/route").length===2'); + assert.equal((await writes(b))[1].body.revision, 1); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); +}); + +test('a stored route fills the fields; each refusal is one plain line and keeps the fields', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...unset, route: route(), routeMessage: undefined, revision: 1 }) }); + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.getElementById("triage-route-model")?.value==="sonnet"'); + assert.equal(await value(b, 'triage-route-harness'), 'pi'); + assert.equal(await value(b, 'triage-route-cap'), '200000'); + assert.equal(await value(b, 'triage-route-zone'), 'Europe/Berlin'); + assert.match(await text(b, 'triage-route-stored'), /^Stored route: sonnet on pi, cap 200,000 tokens a day, reset 00:00 Europe\/Berlin\. Revision 1, saved 2026-11-18T12:00:00\.000Z\.$/); + for (const [error, message, status] of [['triage-zone-unknown', 'The time zone is not one this Console knows.', 400], ['model-harness-incompatible', 'That harness does not run this model.', 400], ['model-provider-unavailable', 'The model provider is not available now.', 503]]) { + await b.evaluate(`Object.assign(window.__scenario, {'POST /api/triage/route': {status: ${status}, body: {error: ${JSON.stringify(error)}, message: ${JSON.stringify(message)}}}})`); + await fill(b, { zone: 'Mars/Olympus', cap: '777' }); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`); + assert.equal(await value(b, 'triage-route-model'), 'sonnet'); + assert.equal(await value(b, 'triage-route-harness'), 'claude-code'); + assert.equal(await value(b, 'triage-route-cap'), '777'); + assert.equal(await value(b, 'triage-route-zone'), 'Mars/Olympus'); + assert.equal(await b.evaluate('document.getElementById("triage-route-reload")'), null, 'only a conflict offers a re-read'); + assert.equal(await b.evaluate('document.getElementById("triage-route-save").disabled'), false); + } + assert.match(await text(b, 'triage-route-stored'), /Revision 1/, 'a refusal leaves the stored line alone'); + // A refusal with no readable answer still says one line. + await b.evaluate(`Object.assign(window.__scenario, {'POST /api/triage/route': {status: 500, body: {}}})`); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait('document.getElementById("triage-route-line")?.textContent==="The route was refused. Nothing was saved."'); + assert.equal(await value(b, 'triage-route-cap'), '777'); + // Leaving the page and coming back reads the route again and keeps what was typed. + await b.evaluate('location.hash="#/settings/appearance"'); + await wait('!document.getElementById("triage-route")'); + await b.evaluate('location.hash="#/settings/triage"'); + await wait('document.getElementById("triage-route-cap")'); + assert.equal(await value(b, 'triage-route-cap'), '777'); + assert.equal(await value(b, 'triage-route-zone'), 'Mars/Olympus'); + assert.match(await text(b, 'triage-route-stored'), /Revision 1/); +}); + +test('a stale revision says so, keeps the fields, and Reload route reads the stored route again', { timeout: 90000 }, async t => { + const message = 'The Triage route changed since this page read it. Reload the route, then save again.'; + const { f, b, wait } = await w15Fixture(t, { scenario: scenario(unset, { 'POST /api/triage/route': { status: 409, body: { error: 'triage-route-stale', message, revision: 2 } } }) }); + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.getElementById("triage-route-model")'); + await fill(b, { cap: '5000' }); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`); + assert.equal(await value(b, 'triage-route-cap'), '5000'); + assert.equal(await b.evaluate('document.activeElement?.id'), 'triage-route-reload'); + await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify({ ...unset, route: route({ revision: 2, model: 'glm-flash', cap: 42 }), routeMessage: undefined, revision: 2 })}`); + await b.evaluate('document.getElementById("triage-route-reload").click()'); + await wait('document.getElementById("triage-route-model")?.value==="glm-flash"'); + assert.equal(await value(b, 'triage-route-cap'), '42'); + assert.match(await text(b, 'triage-route-stored'), /Revision 2/); + assert.equal(await b.evaluate('document.getElementById("triage-route-reload")'), null); + await b.evaluate(`window.__scenario['POST /api/triage/route'] = {body: {route: ${JSON.stringify(route({ revision: 3, model: 'glm-flash', cap: 42 }))}, revision: 3, note: ${JSON.stringify(NOTE)}}}`); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait('document.getElementById("triage-route-line")?.textContent==="Saved. Revision 3."'); + assert.equal((await writes(b)).at(-1).body.revision, 2, 'the save after a re-read carries the stored revision'); +}); + +test('an untouched page follows the store; typed fields keep the revision they were read at, so a later save is stale', { timeout: 90000 }, async t => { + const stored = (over, revision) => ({ ...unset, route: route({ revision, ...over }), routeMessage: undefined, revision }); + const message = 'The Triage route changed since this page read it. Reload the route, then save again.'; + const { f, b, wait } = await w15Fixture(t, { scenario: scenario(stored({}, 1), { 'POST /api/triage/route': { status: 409, body: { error: 'triage-route-stale', message, revision: 3 } } }) }); + const away = async () => { + await b.evaluate('location.hash="#/settings/appearance"'); + await wait('!document.getElementById("triage-route")'); + await b.evaluate('location.hash="#/settings/triage"'); + await wait('document.getElementById("triage-route-cap")'); + }; + const dot = 'document.querySelector(\'#settings-nav a[href="#/settings/triage"] .settings-dot\') !== null'; + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.getElementById("triage-route-model")?.value==="sonnet"'); + // Saved elsewhere while this page sat untouched: the page shows the new route, with no unsaved mark. + await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify(stored({ model: 'glm-flash', cap: 42 }, 2))}`); + await away(); + assert.equal(await value(b, 'triage-route-model'), 'glm-flash'); + assert.equal(await value(b, 'triage-route-cap'), '42'); + assert.match(await text(b, 'triage-route-stored'), /Revision 2/); + assert.equal(await b.evaluate(dot), false); + // Typed at revision 2, then saved elsewhere again: the typed fields stay and the save sends revision 2. + await type(b, 'triage-route-cap', '9000'); + await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify(stored({ model: 'sonnet', cap: 1 }, 3))}`); + await away(); + assert.equal(await value(b, 'triage-route-model'), 'glm-flash'); + assert.equal(await value(b, 'triage-route-cap'), '9000'); + assert.match(await text(b, 'triage-route-stored'), /Revision 3/); + assert.equal(await b.evaluate(dot), true, 'the typed fields are marked unsaved'); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`); + const last = (await writes(b)).at(-1).body; + assert.equal(last.revision, 2, 'the save carries the revision the typed fields were read at, not the newest read'); + assert.equal(last.model, 'glm-flash'); + assert.equal(last.cap, 9000); +}); + +test('a second Save while one runs does nothing', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: scenario(unset, { 'POST /api/triage/route': { body: { route: route(), revision: 1, note: NOTE } } }) }); + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.getElementById("triage-route-model")'); + // Hold the POST until the test lets it go. + await b.evaluate('(()=>{const prev=window.fetch;window.__posts=0;window.fetch=(input,init)=>init?.method==="POST"?(window.__posts++,new Promise(r=>{window.__release=()=>r(prev(input,init));})):prev(input,init);})()'); + await fill(b); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait('typeof window.__release==="function"'); + assert.equal(await text(b, 'triage-route-save'), 'Saving…'); + assert.equal(await b.evaluate('document.getElementById("triage-route-save").disabled'), true); + // A click on the disabled button, a form submit (Enter) and a direct requestSubmit all do nothing. + await b.evaluate('document.getElementById("triage-route-save").click()'); + await b.evaluate('document.getElementById("triage-route-form").requestSubmit()'); + await b.evaluate('document.getElementById("triage-route-form").dispatchEvent(new Event("submit",{bubbles:true,cancelable:true}))'); + assert.equal(await b.evaluate('window.__writes.filter(w=>w.path==="/api/triage/route").length'), 0, 'the held POST is not recorded yet'); + assert.equal(await b.evaluate('window.__posts'), 1, 'no second POST left the page'); + await b.evaluate('window.__release()'); + await wait('document.getElementById("triage-route-line")?.textContent==="Saved. Revision 1."'); + assert.equal((await writes(b)).length, 1); +}); + +test('a read-only Console shows the route with Save off and posts nothing', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...unset, send: false }, {}, { send: false, proxyAdminSend: false }) }); + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.getElementById("triage-route-save")'); + assert.equal(await b.evaluate('document.getElementById("triage-route-save").disabled'), true); + assert.match(await text(b, 'triage-route-readonly'), /read-only/); + assert.equal(await b.evaluate('document.querySelector(".settings-readonly")'), null, 'the panel says read-only once, from the route\'s own answer'); + await b.evaluate('document.getElementById("triage-route-form").dispatchEvent(new Event("submit",{bubbles:true,cancelable:true}))'); + assert.deepEqual(await writes(b), []); +}); + +test('a catalogue that is not ready says so and offers no model', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...unset, choices: { status: 'bus-unavailable', models: [] } }) }); + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.getElementById("triage-route-catalogue")'); + assert.match(await text(b, 'triage-route-catalogue'), /No organization bus offered a model catalogue \(bus-unavailable\)/); + assert.deepEqual(await options(b, 'triage-route-model'), [['', 'Choose a model', false]]); +}); + +test('a non-owner sees no Triage section and the page reads no route', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: scenario(unset, {}, { proxyAdmin: undefined, proxyAdminSend: undefined, user: true }) }); + await countReads(b); + await b.navigate(f.base + '/#/settings'); + await wait('document.querySelector(\'#settings-nav a[href="#/settings/appearance"]\')'); + assert.equal(await b.evaluate('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\')'), null); + await b.navigate(f.base + '/#/settings/triage'); + await wait('document.querySelector(".nf")'); + assert.equal(await b.evaluate('document.getElementById("triage-route")'), null); + assert.equal(await reads(b), 0, 'no route read for a non-owner'); + assert.deepEqual(await writes(b), []); +}); + +// Shots for the build report: run with MOSAIC_UX_SHOTS=. Not set, filled and one refusal, at 390 +// and 1440, light and dark. +test('shots', { timeout: 300000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => { + const { f, b, wait, capture } = await w15Fixture(t, { slice: 'triage', scenario: scenario(unset, { 'POST /api/triage/route': { status: 400, body: { error: 'triage-zone-unknown', message: 'The time zone is not one this Console knows.' } } }) }); + const results = []; + for (const scheme of ['light', 'dark']) { + await b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] }); + for (const width of [390, 1440]) { + await b.viewport(width, width === 390 ? 844 : 900); + // A fresh document each round, so the kept fields of the last round do not carry over. + await b.navigate(`${f.base}/?shot=${scheme}-${width}#/settings/triage`); + await wait('document.getElementById("triage-route-model") && !!window.MosaicAppearance'); + await b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`); + // No sideways scroll at either width. + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${scheme} ${width} scrolls sideways`); + results.push(await capture(`notset-${scheme}`, width, '#/settings/triage')); + await fill(b); + results.push(await capture(`filled-${scheme}`, width, '#/settings/triage')); + await type(b, 'triage-route-zone', 'Mars/Olympus'); + await b.evaluate('document.getElementById("triage-route-save").click()'); + await wait('document.getElementById("triage-route-line")?.textContent.includes("time zone")'); + results.push(await capture(`refusal-${scheme}`, width, '#/settings/triage')); + } + } + for (const r of results) { assert.deepEqual(r.errors, [], r.full); assert.deepEqual(r.unexpected, [], r.full); } +});