From e70b6bd6842e32c3bfa35ef8e3cc93ebb7927da6 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 11:00:09 -0600 Subject: [PATCH 1/5] feat(webui): settings slice 1: Routing says why an organization can't see your models: the model service is not set up or not running (a link to its page), the bus names its cause (that line and Check again, plus Restart only for the lock cause), or the service runs and the bus names none (Restart); Model proxy keeps a Restart per organization whose catalogue is not ready, rereads the whole status after a sign-in, works out the steps after accounts from accounts, organizations and the Triage route, and shows only the next step's button with the rest under Technical details; Triage refusals are plain lines with a link to the page that fixes them, and the harness refusal names Claude Code; a stopped organization keeps its refused restart on screen and keeps the instance pages reachable; at phone width a Routing model select takes the whole row (#1873, lane settings-s1) --- packages/webui/src/public/bus.js | 69 ++++- packages/webui/src/public/console-restart.js | 53 +++- packages/webui/src/public/display.js | 214 ++++++++++---- packages/webui/src/public/shell.css | 23 ++ packages/webui/src/public/triage-settings.js | 22 +- .../webui/tests/proxy-setup-browser.test.mjs | 112 +++++++- packages/webui/tests/routes-browser.test.mjs | 12 +- .../webui/tests/settings-s1-browser.test.mjs | 272 ++++++++++++++++++ .../tests/triage-drawer-browser.test.mjs | 91 +++++- .../tests/triage-settings-browser.test.mjs | 29 +- 10 files changed, 784 insertions(+), 113 deletions(-) create mode 100644 packages/webui/tests/settings-s1-browser.test.mjs diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 862fada7f..2d40fe5b1 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1306,6 +1306,42 @@ const ROUTE_CELLS=[['harness','Harness'],['model','Model'],['thinking','Thinking'],['fallback.harness','Fallback harness'],['fallback.model','Fallback model'],['fallback.thinking','Fallback thinking']]; const routeCells=r=>({harness:r.harness??'',model:r.model??'',thinking:r.thinking??'','fallback.harness':r.fallback?.harness??'','fallback.model':r.fallback?.model??'','fallback.thinking':r.fallback?.thinking??''}); const sameCells=(a,b)=>ROUTE_CELLS.every(([k])=>a[k]===b[k]); + // #1873 settings slice 1 (D2): an organization that lists the model service but cannot see its + // models. For the instance owner the page reads the model service's state once per visit, so the + // line says which is true: the service is not set up or not running (a link to its page), or it + // runs and this organization still cannot read it. A running bus picks the service up at its next + // catalogue read (proxy-pickup), so when the bus names a cause the line shows that cause and a + // Check again that rereads; a Restart would not help there, and with the dev fixture it would stop + // the organization. Only a running service with no cause from the bus offers Restart. The Restart + // follows that state; it is never offered on a guess. + let serviceState=null, serviceLoading=false; + function readService(){ + if(serviceLoading||serviceState!==null||isTester||!triageOwner||!window.MosaicOrg)return; serviceLoading=true;const epoch=orgEpoch; + fetch('/api/proxy/admin/status',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok||!v||typeof v!=='object')throw Error(); + serviceState=v.init?.initialized!==true?'not-set-up':v.unit?.active==='active'&&v.unit?.healthy===true&&v.fence?.set!==true?'running':'not-running';}) + .catch(()=>{if(epoch!==orgEpoch)return;serviceState=false;}).finally(()=>{if(epoch!==orgEpoch)return;serviceLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);}); + } + function catalogueLine(proxyOn,catalogue){ + const org=txt(window.MosaicOrg?.label||'This organization'), id=window.MosaicOrg?.id, owner=canSend&&!isTester; + const lead=`${org} can't see your models yet.`, thinking='A change to thinking alone still saves.'; + // The bus's own cause lines (proxy-pickup), shown as it wrote them. + const causes=(Array.isArray(catalogue?.notices)?catalogue.notices:[]).filter(n=>typeof n==='string'&&n).map(n=>`

${txt(n)}

`).join(''); + if(!proxyOn)return `

${lead} ${thinking}

${causes}`; + if(owner)readService(); + const recheck=''; + // Only the lock cause asks for a restart; with the dev fixture or a key that does not load the + // start is refused too, and a restart would stop the organization. + const lockCause=(catalogue?.notices??[]).some(n=>typeof n==='string'&&n.includes('(proxy-lock-invalid)')); + if(owner&&serviceState==='running'&&causes)return ``; + if(owner&&serviceState==='running')return ``; + if(owner&&serviceState==='not-set-up')return `

${lead} Your model service isn't set up yet. Set up the model service. ${thinking}

`; + if(owner&&serviceState==='not-running')return `

${lead} The model service is not running. Open the model service settings. ${thinking}

${causes}`; + if(owner&&(serviceLoading||(serviceState===null&&triageOwner)))return `

${lead} Checking the model service. ${thinking}

`; + return `

${lead} ${thinking}${owner?' A new model needs the model service: ask the instance owner to set it up, or press Stop using the model service when this organization does not need it.':''}

${causes}`; + } + // Check again rereads Routing; the bus looks for the model service at that read. A draft is kept. + document.addEventListener('click',e=>{if(e.target.id!=='routes-recheck')return;e.target.disabled=true;serviceState=null;routesView=null;last.delete('routes');render(true);}); + document.addEventListener('mosaic-org-restarted',e=>{if(e.detail?.id!==window.MosaicOrg?.id)return;serviceState=null;routesView=null;last.delete('routes');const path=routeOf().split('?')[0];if(path==='/settings/routing'||document.querySelector('[data-org-down]'))render(true);}); function routesSection(view,instanceInfo){ const title='

Routing

'; readHarnesses(); @@ -1334,8 +1370,8 @@ // fixture-only catalogue is ready with no model proxy). Before the setting is read it falls // back to the catalogue status, as before. const proxyOn=harnessSettings?(Array.isArray(harnessSettings.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[]).includes('cliproxy'):v.catalogue?.status!=='disabled'; - const catalogueInfo=v.catalogue?.status==='ready'?`

Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.

${(v.catalogue.notices??[]).map(n=>`

${txt(n)}

`).join('')}`:v.catalogue?.status==='unavailable'?`

Model catalogue unavailable. A change to thinking alone still saves.${proxyOn&&canSend&&!isTester?' A new model needs the catalogue: set up the model proxy, or, when this organization has none, press Disable model proxy catalogue.':''}

${(v.catalogue.notices??[]).map(n=>`

${txt(n)}

`).join('')}`:'

Model catalogue not enabled.

'; - const providerControl=canSend&&!isTester?`

`:''; + const catalogueInfo=v.catalogue?.status==='ready'?`

Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.

${(v.catalogue.notices??[]).map(n=>`

${txt(n)}

`).join('')}`:v.catalogue?.status==='unavailable'?catalogueLine(proxyOn,v.catalogue):'

Model catalogue not enabled.

'; + const providerControl=canSend&&!isTester?`

`:''; const harnessControl=canSend&&!isTester?`
Harnesses${harnessSettings ? [...new Set([...harnessSettings.available.harness,...(harnessSettings.plugins.harness??[])])].map(name=>``).join('')+` ` : '

Harnesses unavailable.

'}

${txt(harnessReceipt)}

`:''; const off=v.harnesses.length?'':'

No harness is switched on in the business file\'s plugins.harness, so every launch refuses harness-off and a save that changes a harness refuses too. Switch one on under Harnesses.

'; return `
${title}${catalogueInfo}${providerControl}${harnessControl}${off}
${ROUTE_CELLS.map(([,l])=>``).join('')}${rows}
AgentPrimaryFallback
${l.replace('Fallback ','')}

${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

${txt(routesReceipt)}

${routesApplyMarkup()}
`; @@ -1357,13 +1393,13 @@ // A viewer without the switch is sent to the owner. function catalogueStep(code,routes){ if(!['model-catalogue-unavailable','model-provider-unavailable'].includes(code))return ''; - if(!canSend||isTester)return ' Ask the organization\'s owner to set up the model proxy, or to disable the model proxy catalogue when the change needs no proxy.'; + if(!canSend||isTester)return ' Ask the organization\'s owner to set up the model service, or to stop using it when the change does not need it.'; const names=Array.isArray(harnessSettings?.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[]; if(!names.includes('cliproxy'))return ''; const moved=Object.entries(routes).flatMap(([name,r])=>{const was=routesView?.instances?.[name]??{}; return [[r.harness,r.model,was.harness,was.model],[r.fallback?.harness,r.fallback?.model,was.fallback?.harness,was.fallback?.model]].filter(([h,m,wh,wm])=>m&&(h!==wh||m!==wm)).map(([,m])=>m);}); const module=key=>routesView?.providerModels?.[key]?.module; - return moved.length&&moved.every(key=>module(key)&&module(key)!=='cliproxy'&&names.includes(module(key)))?' This change needs no model proxy: press Disable model proxy catalogue, then save again.':''; + return moved.length&&moved.every(key=>module(key)&&module(key)!=='cliproxy'&&names.includes(module(key)))?' This change does not need the model service: press Stop using the model service, then save again.':''; } const routesAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&Array.isArray(r.harnesses)&&Array.isArray(r.models)&&[r.levels,r.instances].every(o=>o&&typeof o==='object'&&!Array.isArray(o)); for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('#routes-form');if(!form||!routesView)return;routesDraft=routesFields(form);routesEditVersion++;markSettingsDraft('routing',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('routes-reload');if(discard){discard.hidden=false;discard.disabled=false;} @@ -1388,7 +1424,7 @@ try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(epoch!==orgEpoch)return;if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.'); const names=Array.isArray(settings.plugins?.['model-provider'])?settings.plugins['model-provider']:[]; // The fresh read decides: a stale label never turns the proxy module on when it meant off. - const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=`${on?'Disable':'Enable'} model proxy catalogue`;button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;} + const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=on?'Stop using the model service':'Use your models';button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;} const next=on?names.filter(n=>n!=='cliproxy'):[...names,'cliproxy']; const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'}); if(epoch!==orgEpoch)return;if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true); @@ -1459,10 +1495,10 @@ // #1873 A2: the root and project agent levels (agents.js MosaicAgentLevels), the owner's only. let agentLevels=''; if (page==='agents' && window.MosaicOrg && window.MosaicAgentLevels && !isTester) agentLevels = await window.MosaicAgentLevels.section().catch(()=>''); - if (page==='routing') { try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } + if (page==='routing') { await window.MosaicConsole?.ready; try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch); const notify = typeof n.binding==='string' ? `${txt(n.binding)}` : n.refused ? `Could not be read: ${txt(n.refused)}` : 'None set'; - const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
Address
${txt(s.address)||'unknown'}
Release
${txt(s.release)||'unknown'}
Business
${txt(s.business)||none}
Board
${txt(s.board)||'unknown'}
Notifier binding
${notify}
`, 'model-proxy':()=>'
Open model proxy settings
'}; + const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
Address
${txt(s.address)||'unknown'}
Release
${txt(s.release)||'unknown'}
Business
${txt(s.business)||none}
Board
${txt(s.board)||'unknown'}
Notifier binding
${notify}
`, 'model-proxy':()=>'
Open model service settings
'}; const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'}; return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`); } @@ -1675,6 +1711,21 @@ // After a refusal nothing read before is shown anywhere: not in a view, the palette or the Inbox count. function forget() { window.MosaicChat?.forget(); last.clear(); inboxCount = null; messageCount = null; } const failedView = (err, path) => `${head(path === '/queue' ? 'Queue' : failTitle(err))}${empty('Nothing to show.', refusal(err) ? 'The view stays empty until the problem above is fixed.' : err.module ? 'Read again.' : 'Read again, or come back when the bus answers.')}`; + // #1873 settings slice 1 (D7): an organization page under Settings that cannot be read keeps the + // Settings nav, so the instance pages (Appearance, Model service, Triage, Console) stay one link + // away. When the organization's bus is down the page says so in plain words and offers Restart, + // whose refusal stays on screen (console-restart.js keeps it per organization); the header's own + // "Bus unavailable" banner steps aside on this page so there is one Restart, not two. + function settingsFailed(err, path) { + const page = path.split('/')[2] || 'appearance', id = window.MosaicOrg?.id, row = id ? window.MosaicOrg.row?.(id) : null; + const org = txt(window.MosaicOrg?.label || id || ''), name = settingsPages.find(([p]) => p === page)?.[1] || 'this page'; + if (id && row?.busHealthy === false && !refusal(err)) { + const restart = window.MosaicConsole?.orgRestartButton?.(id, { name: window.MosaicOrg.label || id, primary: true }) || ''; + const state = row.busStopped ? `${org} is stopped` : `${org} isn't running`; + return settingsShell(page, `

This instance's own pages still work: Appearance, Model service${triageOwner ? ', Triage' : ''} and Console.

`); + } + return settingsShell(page, ``); + } const staleBanner = err => ``; // Freshness line in the command bar for bus pages. const stamp = iso => { const t = Date.parse(iso); return Number.isFinite(t) ? `${new Date(t).toISOString().slice(11, 19)} UTC` : 'unknown'; }; @@ -1928,7 +1979,7 @@ if (err.code === 'signed-out') return; const kept = reader(false); try { if (refusal(err)) throw err; html = await view(kept, path, new URLSearchParams(query), opts, current); readAt = kept.oldest(); html = staleBanner(err) + html; state = 'stale'; } - catch { html = failedView(err, path) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; } + catch { if (window.MosaicOrg && path.startsWith('/settings/')) { await window.MosaicConsole?.ready; html = settingsFailed(err, path); } else html = failedView(err, path) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; } if (refusal(err)) forget(); } if (!current()) return; @@ -1944,6 +1995,7 @@ syncAppearance(true); if (path.startsWith('/docs/')) paintDoc(); if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]')); + if ($('bus-view').querySelector('[data-org-down]')) { const down = $('bus-down'); if (down) down.hidden = true; } if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount(); if (path === '/settings/organizations') orgCleanup=window.MosaicOrgCreate.mount(); sections(path); @@ -2164,6 +2216,7 @@ instanceView = null; instanceDrafts = { add: null, change: null }; instanceReceipt = ''; instanceReceiptOp = null; instanceReceipts = Object.create(null); routesView = null; routesDraft = null; routesReceipt = ''; routesEditVersion++; harnessSettings = null; harnessDraft = null; harnessReceipt = ''; + serviceState = null; serviceLoading = false; // A file draft is keyed by project and path only; the page reload that used to drop it is gone. docKey = null; docStates.clear(); pkAll = []; pkShown = []; pkAt = 0; configRead = switchRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => applyConfig(c, { quiet: true })).catch(() => {}); diff --git a/packages/webui/src/public/console-restart.js b/packages/webui/src/public/console-restart.js index 5ab4a989c..895d52e71 100644 --- a/packages/webui/src/public/console-restart.js +++ b/packages/webui/src/public/console-restart.js @@ -175,6 +175,8 @@ } } catch (error) { busReceipt = error instanceof SyntaxError || error?.name === 'TypeError' ? 'Outcome unknown. Check the bus with mosaic bus status before retrying.' : error.message; + // #1873 D7: the refusal follows the organization onto its Settings pages. + if (!(error instanceof SyntaxError || error?.name === 'TypeError')) orgReceipts.set(id, { ok: false, ...refusalLine(window.MosaicOrg?.label || id, error.message) }); } finally { busBusy = false; paintBus(); } }); @@ -196,5 +198,54 @@ } finally { busBusy = false; paintBus(); } } - window.MosaicConsole = Object.freeze({ ready, settingsMarkup, busButton, attachBus, get busRestart() { return busAllowed(); }, get config() { return config; } }); + // #1873 settings slice 1 (D2, D3, D7): a Restart button for one named organization, for pages that + // list organizations by id (Routing, Model proxy, a stopped organization's Settings). Each + // organization keeps its own receipt, so a refusal stays on screen across repaints until the next + // press. It calls the same POST /api/orgs//restart/bus as the header's Restart bus. + const orgReceipts = new Map(), orgBusy = new Set(); + const orgAllowed = () => config?.orgSetup === true && config?.tester !== true && config?.user !== true; + // The refusal the bus host wrote, with one plain line in front when its code is known. + function refusalLine(name, message) { + const text = String(message || 'The restart was refused. Nothing was retried.'); + if (/\bfixture-proxy-configured\b/.test(text)) return { plain: `${name} runs on test models, which can't share this machine with your model service. It did not start.`, detail: text }; + return { plain: `${name} did not start.`, detail: text }; + } + function orgRestartButton(id, { name = id, label = `Restart ${name}`, primary = false } = {}) { + if (!orgAllowed() || typeof id !== 'string' || !id) return ''; + const busy = orgBusy.has(id), r = orgReceipts.get(id); + const receipt = !r ? '' : r.ok ? esc(r.text) : `${esc(r.plain)} ${esc(r.detail)}`; + return ` ${receipt}`; + } + const paintOrg = id => document.querySelectorAll(`[data-org-restart-box="${CSS.escape(id)}"]`).forEach(el => { + const b = el.querySelector('[data-org-restart]'); + el.outerHTML = orgRestartButton(id, { name: b?.dataset.orgName || id, label: b?.dataset.label, primary: b?.hasAttribute('data-primary') }); + }); + async function restartOrg(id, name) { + if (orgBusy.has(id) || !orgAllowed()) return null; + orgBusy.add(id); orgReceipts.delete(id); paintOrg(id); + let result; + try { + const response = await nativeFetch(`/api/orgs/${encodeURIComponent(id)}/restart/bus`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}', cache: 'no-store', redirect: 'manual' }); + if (response.type === 'opaqueredirect') throw new Error('Sign in again, then retry.'); + const body = await response.json(); + if (!response.ok || body.outcome !== 'done' || body.step !== 'bus-restart') throw new Error(body.message || 'The restart was refused. Nothing was retried.'); + result = { ok: true, healthy: body.healthy === true, text: `${name} ${body.restarted ? 'restarted' : 'started'} at ${clock()}. ${body.healthy ? 'It answers.' : `It has not answered yet. Check it with mosaic bus status ${id}.`}` }; + } catch (error) { + result = error instanceof SyntaxError || error?.name === 'TypeError' + ? { ok: false, plain: 'Outcome unknown.', detail: `Check it with mosaic bus status ${id} before you press Restart again.` } + : { ok: false, ...refusalLine(name, error.message) }; + } + orgBusy.delete(id); orgReceipts.set(id, result); paintOrg(id); + if (id === window.MosaicOrg?.id) { busReceipt = result.ok ? result.text : `${result.plain} ${result.detail}`; paintBus(); } + await Promise.resolve(window.MosaicOrg?.refreshList?.()).catch(() => {}); + document.dispatchEvent(new CustomEvent('mosaic-org-restarted', { detail: { id, ok: result.ok, healthy: result.healthy === true } })); + return result; + } + document.addEventListener('click', e => { + const button = e.target.closest?.('[data-org-restart]'); + if (!button || button.disabled) return; + restartOrg(button.dataset.orgRestart, button.dataset.orgName || button.dataset.orgRestart); + }); + + window.MosaicConsole = Object.freeze({ ready, settingsMarkup, busButton, attachBus, orgRestartButton, restartOrg, orgRefusal: id => orgReceipts.get(id) ?? null, get busRestart() { return busAllowed(); }, get config() { return config; } }); })(); diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 98fdc12c1..96a5efeb8 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -13,7 +13,15 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const clean = (value, max = 8000) => (typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value)).replace(/\r\n?/g, '\n').replace(HIDDEN, '').slice(0, max); const when = value => window.MosaicLocalTime(clean(value, 64)); const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; }; - const NO_ROUTE = 'No model route is set for Triage, so Triage will not start. The instance owner sets the route first.'; + const NO_ROUTE = 'Triage has no model chosen yet, so it will not start.'; + // #1873 settings slice 1 (section 5): a fix link goes only to a Settings page that exists for this viewer. + // Settings > Triage exists only where /api/config says proxyAdmin (bus.js triageOwner); Model proxy always does. + const TRIAGE_FIX = { href: '#/settings/triage', label: 'Open Triage settings' }; + const SERVICE_FIX = { href: '#/settings/model-proxy', label: 'Open model service settings' }; + const pageExists = fix => fix !== TRIAGE_FIX || config?.proxyAdmin === true; + const fixLink = fix => { const a = el('a', 'triage-fix', fix.label); a.href = fix.href; a.addEventListener('click', () => close()); return a; }; + // An organization's name from the Console's own list, or its id when the list does not hold it. + const orgName = id => { const name = window.MosaicOrg?.row?.(id)?.label; return typeof name === 'string' && name ? clean(name, 200) : clean(id) || 'unnamed'; }; let config = null, entry = null, drawer = null, parts = null, timer = null, gen = 0, sending = false, lastTranscript = '', lastHealth = '', shown = []; const read = () => systemFetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).catch(() => null); @@ -43,6 +51,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( x.addEventListener('click', close); hd.append(title, x); const state = el('p', 'triage-state'); state.id = 'triage-state'; state.setAttribute('role', 'status'); + const stateFix = el('p', 'triage-state-fix'); stateFix.id = 'triage-state-fix'; stateFix.hidden = true; const usage = el('p', 'note triage-usage'); usage.id = 'triage-usage'; usage.hidden = true; const healthSec = el('details', 'triage-health-sec'); healthSec.open = true; const healthSum = el('summary', '', 'Health'); @@ -52,10 +61,10 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const transcript = el('ol', 'triage-transcript'); transcript.id = 'triage-transcript'; transcript.tabIndex = 0; transcript.setAttribute('aria-label', 'Triage conversation'); const compose = el('div', 'triage-compose'); - drawer.append(hd, state, usage, healthSec, convo, transcript, compose); + drawer.append(hd, state, stateFix, usage, healthSec, convo, transcript, compose); drawer.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(); } }); document.body.append(drawer); - parts = { title, state, usage, health, transcript, compose, box: null, send: null, status: null, off: null }; + parts = { title, state, stateFix, usage, health, transcript, compose, box: null, send: null, status: null, off: null }; } // The message box is built once and never rewritten or removed by a read, so a draft survives every @@ -90,16 +99,17 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( if (!canSend) { parts.off.textContent = READ_ONLY; parts.box.disabled = parts.send.disabled = true; return; } // A route that is not set, or a session over its cap, turns the box off and says why. const until = typeof view.overCapUntil === 'string' && view.overCapUntil ? view.overCapUntil : null; - const reason = view.route !== 'set' ? 'Sending is off: no model route is set for Triage.' - : until ? `Sending is off: Triage is over its daily token cap until ${when(until)}.` : ''; + const reason = view.route !== 'set' ? 'Sending is off: Triage has no model chosen yet.' + : until ? `Sending is off: Triage used its daily token limit. It takes messages again at ${when(until)}.` : ''; parts.off.textContent = reason; parts.box.disabled = !!reason; parts.send.disabled = !!reason || sending; } const stateLine = view => { - if (view.route !== 'set') return clean(view.routeMessage) || NO_ROUTE; - if (view.overCapUntil) return clean(view.capMessage) ? `${clean(view.capMessage)} Local time: ${when(view.overCapUntil)}.` : `Triage is over its daily token cap. It takes messages again at ${when(view.overCapUntil)}.`; + // The page's own plain line (section 5), with the fix link under it; the read's routeMessage is the older wording. + if (view.route !== 'set') return NO_ROUTE; + if (view.overCapUntil) return `Triage used its daily token limit. It takes messages again at ${when(view.overCapUntil)}.`; if (view.running === true) return 'Running.'; const x = view.lastExit; if (x && typeof x === 'object') { @@ -115,7 +125,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const usageLine = view => { if (!Object.hasOwn(view, 'usageToday')) return ''; const u = view.usageToday, c = view.cap; - if (u === 'not set' || c === 'not set') return 'Daily token cap: not set.'; + if (u === 'not set' || c === 'not set') return 'Daily token limit: not set.'; if (notRead(u) || notRead(c)) return "Today's token usage: not read."; const n = v => (Number.isSafeInteger(v) ? v.toLocaleString() : 'not read'); const reset = typeof view.resetsAt === 'string' && Number.isFinite(Date.parse(view.resetsAt)) ? ` Resets at ${when(view.resetsAt)}.` : ''; @@ -128,7 +138,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( if (notRead(s)) return ['Health: not read']; const lines = []; lines.push(notRead(s.console) ? 'Console: not read' : `Console: ${clean(s.console.state) || 'not read'}, ${when(s.console.at)}`); - if (notRead(s.proxy)) lines.push('Proxy: not read'); + if (notRead(s.proxy)) lines.push('Model service: not read'); else { const p = s.proxy; const words = [p.healthy === true ? 'healthy' : p.healthy === false ? 'not healthy' : 'health not read']; @@ -136,7 +146,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( if (p.installed === false) words.push('not installed'); if (typeof p.active === 'string' && p.active) words.push(`unit ${clean(p.active)}`); if (p.fence === true) words.push('fence set'); - lines.push(`Proxy: ${words.join(', ')}`); + lines.push(`Model service: ${words.join(', ')}`); } lines.push(`System config: ${configWords(s.systemConfig)}`); const orgs = s.organizations; @@ -144,9 +154,12 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( else if (!orgs.list.length) lines.push('Organizations: none'); else for (const o of orgs.list) { if (!o || typeof o !== 'object') continue; - const bus = notRead(o.bus) ? 'bus not read' : `bus ${clean(o.bus.state) || 'not read'}${o.bus.lastStart && o.bus.lastStart.ok === false ? `, last start failed ${when(o.bus.lastStart.at)}` : ''}`; + // #1873 settings slice 1 (D7): a refused last start reads as not running, never as running. The + // read carries the time only, not the reason, so the line says where the reason is shown. + const refused = !notRead(o.bus) && o.bus.lastStart && o.bus.lastStart.ok === false; + const bus = notRead(o.bus) ? 'bus not read' : refused ? `not running: its last start failed at ${when(o.bus.lastStart.at)} (bus ${clean(o.bus.state) || 'not read'}). Restart it on the dashboard to see why` : `bus ${clean(o.bus.state) || 'not read'}`; const proc = notRead(o.processing) ? 'processing not read' : o.processing.invalid === true ? 'processing state not valid' : o.processing.halted === true ? 'processing stopped' : 'processing on'; - lines.push(`${clean(o.id) || 'unnamed'}: ${bus}, ${proc}, config ${configWords(o.config)}`); + lines.push(`${orgName(o.id)}: ${bus}, ${proc}, config ${configWords(o.config)}`); } return lines; } @@ -187,6 +200,11 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24, top = t.scrollTop; parts.state.textContent = stateLine(view); parts.state.dataset.kind = view.route !== 'set' ? 'off' : view.overCapUntil ? 'cap' : view.running === true ? 'running' : 'stopped'; + // The fix link exists only while the route is not set and its page exists, so no link sits hidden in the drawer. + const fixable = view.route !== 'set' && pageExists(TRIAGE_FIX); + parts.stateFix.hidden = !fixable; + if (!fixable) parts.stateFix.replaceChildren(); + else if (!parts.stateFix.firstChild) parts.stateFix.append(fixLink(TRIAGE_FIX)); const usage = usageLine(view); parts.usage.textContent = usage; parts.usage.hidden = !usage; @@ -268,13 +286,21 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( if (code === 'triage-route-invalid' || code === 'triage-start-failed') return { text: `Not delivered: ${code === 'triage-start-failed' ? 'the Triage session did not start' : 'Triage did not start because the model route\'s answer is not usable'}. The message is in the conversation with the Console's note; it was not sent again.` }; // This one can come before or after the message is written. if (code === 'triage-dir-unsafe') return { text: 'Not delivered: a Triage directory is not safe to use. It was not sent again: check the conversation before you send it again.' }; - // A route refusal (no key, the proxy down, the model no longer offered, ...) carries its own plain line. + // #1873 settings slice 1 (section 5): a route refusal reads as what is missing, with the page that fixes it. + // Slice 1 has no way to issue a Triage key, so that line ends at what is missing. + if (status === 409 && code === 'triage-key-missing') return { text: 'Not sent. Triage isn\'t turned on yet: it needs a Triage key, and none is issued on this instance.' }; + if (status === 409 && code === 'triage-proxy-down') return { text: 'Not sent. The model service isn\'t running, so Triage can\'t start.', link: SERVICE_FIX }; + if (status === 409 && code === 'triage-harness-incompatible') return { text: 'Not sent. Triage runs only with Claude Code. Choose Claude Code under "Runs with" in Triage settings.', link: TRIAGE_FIX }; + if (status === 409 && code === 'triage-model-not-offered') return { text: 'Not sent. The model Triage uses is no longer offered. Choose another model in Triage settings.', link: TRIAGE_FIX }; + if (status === 409 && code === 'triage-catalogue-unavailable') return { text: 'Not sent. The model service can\'t confirm Triage\'s model right now, so Triage can\'t start.', link: SERVICE_FIX }; + // Any other route refusal (an unsafe key file, ...) carries its own plain line. if (status === 409 && /^triage-(key|proxy|model|catalogue|harness)-/.test(code) && typeof body.message === 'string') return { text: `Not sent. ${clean(body.message)}` }; - if (status === 409) return { text: code === 'triage-no-route' ? 'Not sent: no model route is set for Triage. The instance owner sets the route first.' : code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' }; + if (status === 409 && code === 'triage-no-route') return { text: 'Not sent. Triage has no model chosen yet.', link: TRIAGE_FIX }; + if (status === 409) return { text: code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' }; if (status === 429) { if (code === 'triage-over-cap') { const until = typeof body.until === 'string' ? clean(body.until) : ''; - return { text: until ? `Not sent: Triage is over its daily token cap. It takes messages again at ${when(until)} (${until}).` : 'Not sent: Triage is over its daily token cap.' }; + return { text: until ? `Not sent: Triage used its daily token limit. It takes messages again at ${when(until)} (${until}).` : 'Not sent: Triage used its daily token limit.', link: TRIAGE_FIX }; } return { text: 'Not sent: Triage has too many messages waiting. Try again in a moment.' }; } @@ -303,6 +329,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // The status line can grow the composer; a reader at the bottom of the transcript stays there. const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24; parts.status.textContent = result.text; + if (result.link && pageExists(result.link)) parts.status.append(' ', fixLink(result.link)); parts.status.dataset.kind = result.sent ? 'ok' : result.unknown ? 'unknown' : 'refused'; // Only a 202 clears the box, and only when the reader has not typed more since. if (result.sent && parts.box.value === text) parts.box.value = ''; @@ -374,7 +401,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const banner = document.getElementById('bus-down'); if (!banner) return; const org = rowsSeen.find(row => current && row.id === decodeURIComponent(current) && !row.invalid), path = route().split('?')[0]; - if (system(location.hash) || (path === '/organization' && org?.busHealthy === false) || (banner.dataset.orgBus && org?.busHealthy !== false)) { banner.hidden = true; delete banner.dataset.orgBus; return; } + if (system(location.hash) || ((path === '/organization' || document.querySelector('#bus-view [data-org-down]')) && org?.busHealthy === false) || (banner.dataset.orgBus && org?.busHealthy !== false)) { banner.hidden = true; delete banner.dataset.orgBus; return; } if (org?.busHealthy === false) { banner.textContent = 'Bus unavailable'; banner.hidden = false; banner.dataset.orgBus = '1'; window.MosaicConsole?.attachBus(banner, 'Restart the bus'); } }; // Idempotent: each read replaces the banner, and removes it on recovery. @@ -480,6 +507,9 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // The open organization's name as the last list read gave it, for the breadcrumb. get label() { const id = current ? decodeURIComponent(current) : null, row = id && rowsSeen.find(r => r.id === id); return id ? (typeof row?.label === 'string' && row.label ? row.label : id) : null; }, ready, route, get list() { return list; }, readList, refreshList, + // #1873 settings slice 1: an organization's row as the last list read gave it (name and bus state), or null. + row: id => { const r = rowsSeen.find(x => x.id === id && !x.invalid); return r ? Object.freeze({ id: r.id, label: typeof r.label === 'string' && r.label ? r.label : r.id, busHealthy: r.busHealthy, busStopped: r.busStopped === true }) : null; }, + rows: () => rowsSeen.filter(x => !x.invalid).map(r => Object.freeze({ id: r.id, label: typeof r.label === 'string' && r.label ? r.label : r.id, busHealthy: r.busHealthy, busStopped: r.busStopped === true })), // SP3: whether this address is a system page (no organization's), for the shell's theme scope. system: () => system(location.hash), switchTo: next => { const path = route().split('?')[0]; location.hash = `#/orgs/${encodeURIComponent(next)}${path === '/dashboard' || path === '/' ? '/organization' : route()}`; }, @@ -507,13 +537,20 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo (() => { 'use strict'; // #1873: setup from nothing to a working proxy. Shown only to the instance owner (config.proxyAdmin). - const setupMarkup = '\n'; + const markup = setupMarkup + '

Reading accounts…

\n\n

Accounts

\n

Higher priority is used first. Account names are stable identifiers; credential values are never displayed.

\n
AccountProviderStatusPriorityModels
\n

Sign in to an account

\n
Subscription account
\n

\n

\n
Finish sign-in

If the sign-in tab does not return, copy its full address and paste it here.

\n

Add an API key

\n
z.ai

The key is sent once and cleared from this field. It will never be shown again.

\n

Client keys

Only key IDs are shown. Hire and fire manage agent keys.

\n
Key IDManaged byAgentIssuedState
\n'; function mount() { const $ = id => document.getElementById(id); let canWrite = false, login = null, poll = null; @@ -550,8 +586,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const value = await response.json(); if (!response.ok) { if (response.status === 401) throw new Error('Sign in to the Console again.'); - if (value.error === 'not-configured') throw new Error(typeof value.reason === 'string' && value.reason ? value.reason : 'The model proxy is not configured for this instance.'); - if (value.error === 'proxy-down') throw Object.assign(new Error('The model proxy is not answering.'), { code: 'proxy-down' }); + if (value.error === 'not-configured') throw new Error(typeof value.reason === 'string' && value.reason ? value.reason : 'The model service is not set up on this instance.'); + if (value.error === 'proxy-down') throw Object.assign(new Error('The model service is not answering.'), { code: 'proxy-down' }); if (value.error === 'login-state-unknown') throw new Error('This sign-in has ended. Start a new sign-in.'); if (value.error === 'apikey-invalid') throw new Error('Enter a nonempty API key, with no spaces or line breaks.'); throw new Error('The operation could not be confirmed. Nothing was retried. Refresh before trying again.'); @@ -571,12 +607,15 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo if (active !== login) return; if (result.status === 'wait') { message('Waiting for account sign-in…', true); poll = setTimeout(status, 2000); return; } endLogin(); - if (result.status === 'ok') { message('Account signed in.', true); await refresh(); } - else message(result.reason === 'login-timeout' ? 'Sign-in timed out. Start again.' : 'Account sign-in failed. Start again.', true); + // #1873 settings slice 1 (D1): a sign-in can be the step that finishes setup, so the page + // reads the whole setup status again, not only the accounts. + if (result.status === 'ok') { message('Account signed in.', true); await refresh(); await setup.reread(); } + else message(result.reason === 'login-timeout' ? 'Sign-in took too long. Try again.' : 'Account sign-in failed. Try again.', true); } catch (error) { if (active === login) { endLogin(); message(error.message, true); } } } async function refresh() { const [accounts, keys] = await Promise.all([call('accounts'), call('keys')]); + setup.accounts(Array.isArray(accounts?.accounts) ? accounts.accounts.length : null); const rows = accounts.accounts.map(account => { const row = document.createElement('tr'); row.append(cell(account.displayName), cell(account.provider), cell(account.status)); @@ -649,7 +688,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('apikey')) return; const input = event.currentTarget.elements.key, key = input.value; input.value = ''; busy.add('apikey');receipt('proxy-apikey-message','','');formBusy(form,true); - try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.');receipt('proxy-apikey-message','API key added.','success');await refresh(); } + try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.');receipt('proxy-apikey-message','API key added.','success');await refresh();await setup.reread(); } catch (error) { message(error.message);receipt('proxy-apikey-message',error.message,'error'); } finally { busy.delete('apikey');formBusy(form,false); } }); @@ -659,10 +698,15 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const setup = (() => { const box = $('proxy-setup'), form = $('proxy-setup-init'); let state = null, timer = null, enabled = false, sendOk = false, seenFetch = null, loading = false; + // #1873 settings slice 1 (D1): the steps after "accounts" come from what this page reads itself: + // the account count (refresh), the organizations in the status, and the Triage route. + let accountCount = null, triageSet = null; + const listed = new Set(); + const esc = v => String(v).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); const pasteAllowed = location.protocol === 'https:' || ['localhost', '[::1]'].includes(location.hostname) || /^127\./.test(location.hostname); const STEPS = { start: 'Starting', 'download-archive': 'Downloading the release archive', 'verify-archive': 'Checking the archive hash', 'download-panel': 'Downloading the panel', 'verify-panel': 'Checking the panel hash', 'extract-binary': 'Extracting the executable', 'verify-binary': 'Checking the executable hash', install: 'Installing', done: 'Done' }; const REASONS = { - 'human-required': 'Only the instance owner can set up the proxy.', + 'human-required': 'Only the instance owner can set up the model service.', 'read-only': 'This Console is read-only.', 'proxy-admin-busy': 'Another setup action is running. Wait for it to finish.', 'proxy-key-transport': 'A pasted key travels only over HTTPS or loopback. Use the generated key.', @@ -671,20 +715,20 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo 'proxy-config-invalid': 'The port must be 1024 to 65535 and not 8317.', 'proxy-rotate-grace-invalid': 'Key rotation grace must be 1 to 1440 minutes.', 'proxy-first-output-invalid': 'First output timeout must be 1 to 3600 seconds.', - 'proxy-already-initialized': 'The proxy is already initialized. Init never overwrites it.', + 'proxy-already-initialized': 'The model service is already initialized. Init never overwrites it.', 'proxy-port-in-use': 'That port is in use. Choose another or leave it empty.', 'proxy-init-busy': 'An init lock is held. See Init lock above.', 'proxy-install-missing': 'The pinned release is not fetched yet.', 'proxy-install-invalid': 'The fetched release failed its hash check. Fetch again.', - 'proxy-restart-required': 'Restart the proxy from this page first.', + 'proxy-restart-required': 'Restart the model service from this page first.', 'proxy-restart-unconfirmed': 'The restart could not be confirmed on the host. Restart again.', 'proxy-init-lock-held': 'The init lock cannot be cleared yet.', 'proxy-init-lock-absent': 'There is no init lock.', 'proxy-unit-exists': 'A different proxy unit file is installed. Check it with mosaic proxy unit render.', - 'proxy-unit-missing': 'The proxy service is not installed.', - 'proxy-unit-unhealthy': 'The proxy service started but does not answer on its port.', + 'proxy-unit-missing': 'The model service is not installed.', + 'proxy-unit-unhealthy': 'The model service started but does not answer on its port.', 'proxy-unit-failed': 'systemd refused the action.', - 'not-configured': 'Proxy setup is not available on this Console.', + 'not-configured': 'Model service setup is not available on this Console.', 'outcome-unknown': 'The outcome is unknown. Check the status before retrying.', }; const explain = code => `${REASONS[code] ?? 'The action was refused.'} (${code})`; @@ -730,23 +774,67 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo 'init-lock-clear': ['Clear the stale init lock', 'Next: an init lock is left from an init that did not finish. The bus is stopped and no proxy files exist, so it can be cleared.', clearLock], 'init-lock-wait': ['Check again', `An init lock is held and cannot be cleared: ${state.initLock.blockers.join('; ')}. Stop the bus and remove partial state as the model-proxy README says, then check again.`, load], 'init-repair': ['Check again', 'Setup is partly done. Init never overwrites existing proxy files; resolve them as the model-proxy README says, then check again.', load], - init: ['Initialize the proxy', 'Next: initialize. The bus generates the management key unless you paste your own.', () => { $('proxy-setup-init-box').open = true; form.elements.port.focus(); }], - 'unit-install': ['Install the proxy service', `Next: install ${state.unit.unit}.`, () => unitAction('install')], - 'unit-start': ['Start the proxy service', `Next: start ${state.unit.unit}.`, () => unitAction('start')], - 'unit-restart': ['Restart the proxy service', state.fence.set ? (fence => fence.invalid || !fence.time ? 'A key write had an uncertain outcome, so key writes are fenced. The fence file has no readable time, so a restart from this page cannot be proven against it: restart the proxy service, confirm it answers, then run mosaic proxy fence clear --proxy-restarted.' : 'A key write had an uncertain outcome, so key writes are fenced. Restart the proxy; after this page confirms the new process, clear the fence.')(state.fence) : 'The service is running but does not answer on its port. Restart it.', () => unitAction('restart')], - 'fence-clear': ['Clear the fence', 'The proxy was restarted from this page and the new process answers on its port. Clear the fence with that evidence.', clearFence], - accounts: ['Add an account', state.next?.includes('ride-all') ? 'The proxy is running. Sign in to an account or add an API key below. Then use Ride all under Organizations.' : 'The proxy is running. Sign in to an account or add an API key below.', () => $('proxy-signin-title')?.scrollIntoView({ block: 'start' })], - 'ride-all': ['Ride all', 'Next: let your organizations use your models. See Ride all under Organizations.', () => $('proxy-ride')?.scrollIntoView({ block: 'start' })], + init: ['Initialize the model service', 'Next: initialize. The bus generates the management key unless you paste your own.', () => { $('proxy-setup-init-box').open = true; form.elements.port.focus(); }], + 'unit-install': ['Install the model service', `Next: install ${state.unit.unit}.`, () => unitAction('install')], + 'unit-start': ['Start the model service', `Next: start ${state.unit.unit}.`, () => unitAction('start')], + 'unit-restart': ['Restart the model service', state.fence.set ? (fence => fence.invalid || !fence.time ? 'A key write had an uncertain outcome, so key writes are fenced. The fence file has no readable time, so a restart from this page cannot be proven against it: restart the proxy service, confirm it answers, then run mosaic proxy fence clear --proxy-restarted.' : 'A key write had an uncertain outcome, so key writes are fenced. Restart the model service; after this page confirms the new process, clear the fence.')(state.fence) : 'The service is running but does not answer on its port. Restart it.', () => unitAction('restart')], + 'fence-clear': ['Clear the fence', 'The model service was restarted from this page and the new process answers on its port. Clear the fence with that evidence.', clearFence], + accounts: ['Add an account', state.next?.includes('ride-all') ? 'The model service is running. Sign in to a model account or add an API key below. Then use Ride all below.' : 'The model service is running. Sign in to a model account or add an API key below.', () => $('proxy-signin-title')?.scrollIntoView({ block: 'start' })], + 'triage-route': ['Open Triage settings', 'Next: choose the model Triage uses. Triage is the assistant that answers questions about this instance.', () => { location.hash = '#/settings/triage'; }], + 'ride-all': ['Ride all', 'Next: let your organizations use your models. See Ride all below.', () => $('proxy-ride')?.scrollIntoView({ block: 'start' })], }; - const [label, text, action] = steps[next] ?? ['Check again', 'Status read.', load]; + const step = next === 'accounts' ? afterAccounts() : next; + if (step === 'restart-orgs' || step === 'done') { + const names = needRestart().map(o => nameOf(o.id)); + const p = document.createElement('p'); p.dataset.next = step; + p.textContent = step === 'done' ? 'The model service is set up and every organization can see your models.' + : `Next: restart ${names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`}. ${names.length === 1 ? 'It' : 'Each'} has a Restart button under Organizations that need a restart.`; + box.replaceChildren(p); return; + } + const [label, text, action] = steps[step] ?? ['Check again', 'Status read.', load]; const p = document.createElement('p'); p.textContent = text; - const button = document.createElement('button'); button.type = 'button'; button.className = 'btn primary'; button.id = 'proxy-setup-go'; button.dataset.next = next ?? ''; + const button = document.createElement('button'); button.type = 'button'; button.className = 'btn primary'; button.id = 'proxy-setup-go'; button.dataset.next = step ?? ''; button.textContent = state.busy ? 'Working…' : label; - const write = !['init-lock-wait', 'init-repair', 'accounts', 'init', 'ride-all'].includes(next); + const write = !['init-lock-wait', 'init-repair', 'accounts', 'init', 'ride-all', 'triage-route'].includes(step); button.disabled = Boolean(state.busy) || (write && !sendOk); button.addEventListener('click', () => { if (!button.disabled) action(); }); box.replaceChildren(p, button); } + // #1873 settings slice 1 (D1, D3): steps after "accounts", and the kept restart list. + const nameOf = id => window.MosaicOrg?.row?.(id)?.label || id; + const running = () => state?.next?.[0] === 'accounts'; + // An organization that cannot see the models while the service runs. "disabled" is left out: that + // organization does not use the model service, and a restart would not change it. + const needRestart = () => (running() && Array.isArray(state.organizations) ? state.organizations : []).filter(o => ['unavailable', 'bus-unavailable'].includes(o.catalogue?.status)); + function afterAccounts() { + if (!accountCount) return 'accounts'; + // ride-default: Ride all is next while an organization can ride now. Stand-in organizations alone + // do not hold the step: their Move buttons are optional and Ride all would be disabled. + if (state.next?.includes('ride-all') && Array.isArray(state.ride) && state.ride.some(r => r.state === 'ready')) return 'ride-all'; + if (needRestart().length) return 'restart-orgs'; + if (triageSet === false) return 'triage-route'; + return 'done'; + } + async function readTriage() { + try { const r = await fetch('/api/triage/route', { cache: 'no-store', redirect: 'manual' }); const v = r.ok ? await r.json() : null; triageSet = v && typeof v === 'object' ? !!v.route : null; } + catch { triageSet = null; } + } + function paintRestart() { + const box = $('proxy-setup-restart'), list = $('proxy-setup-restart-list'); + for (const o of needRestart()) listed.add(o.id); + const orgs = Array.isArray(state?.organizations) ? state.organizations.filter(o => listed.has(o.id)) : []; + box.hidden = !running() || !orgs.length; + if (box.hidden) { list.replaceChildren(); return; } + list.innerHTML = orgs.map(o => { + const status = o.catalogue?.status, name = nameOf(o.id); + const [badge, word, why] = status === 'ready' ? ['badge-ok', 'Ready', `${name} can see your models now.`] + : status === 'bus-unavailable' ? ['badge-danger', 'Not running', `${name} is not running.`] + : status === 'unavailable' ? ['badge-attn', 'Can\'t see models', `${name} can\'t read your models from the model service yet.`] + : ['badge-muted', 'Unknown', `${name}'s models could not be read.`]; + const restart = status === 'ready' ? '' : (window.MosaicConsole?.orgRestartButton?.(o.id, { name }) || 'Only the instance owner can restart it.'); + return `
  • ${esc(name)} ${word}${esc(why)}${restart}
  • `; + }).join(''); + } function paintControls() { const { release, init, unit, initLock, busy } = state; const canInit = sendOk && !busy && release.fetched && release.verified && !init.initialized && !init.partial && !initLock.present; @@ -827,9 +915,11 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }; $('proxy-ride-go').addEventListener('click', () => { if (!$('proxy-ride-go').disabled) rideAll(); }); function paint() { - paintState(); paintNext(); paintControls(); paintReceipts(); + paintState(); paintNext(); paintControls(); paintReceipts(); paintRestart(); // An initialized proxy keeps the init form folded after a reload too. if (state.init.initialized) $('proxy-setup-init-box').open = false; + // #1873 settings slice 1 (D4): the init form shows only while init is the next step. + $('proxy-setup-init-box').hidden = state.next?.[0] !== 'init'; const job = state.fetch; if (job.state === 'running') say(`Fetching: ${STEPS[job.step] ?? job.step ?? 'starting'}…`); else if (job.state === 'failed' && seenFetch !== 'failed') { say(`Fetch failed. ${explain(job.error)}`, 'error'); seenFetch = 'failed'; } @@ -839,7 +929,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo } async function load() { if (!enabled || loading) return; loading = true; - try { state = await admin('status'); paint(); if (state.init.initialized) await accountsReady(); } + try { state = await admin('status'); if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); if (state.init.initialized) await accountsReady(); } catch (error) { say(error.message, 'error'); } finally { loading = false; } } @@ -855,7 +945,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const unitAction = op => act(`unit-${op}`, async () => { const result = await admin(`unit/${op}`, {}); addReceipt(result.receipt); if (op === 'restart' && result.evidence?.confirmed !== true) say('The service restarted but the new process could not be confirmed. The fence stays set.', 'error'); - else say({ install: 'Proxy service installed.', start: 'Proxy service started and answering.', stop: 'Proxy service stopped.', restart: 'Proxy service restarted; the new process answers.' }[op], 'success'); + else say({ install: 'Model service installed.', start: 'Model service started and answering.', stop: 'Model service stopped.', restart: 'Model service restarted; the new process answers.' }[op], 'success'); }); const clearFence = () => act('fence-clear', async () => { const result = await admin('fence/clear', {}); addReceipt(result.receipt); say(result.cleared ? 'Fence cleared.' : 'The fence was not set.', 'success'); }); form.elements.keySource.forEach?.(radio => radio.addEventListener('change', () => { $('proxy-setup-paste').hidden = form.elements.keySource.value !== 'paste'; })); @@ -874,8 +964,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo act('init', async () => { const result = await admin('init', args); addReceipt(result.receipt); $('proxy-setup-init-box').open = false; - say(`Initialized on port ${result.settings.port}${args.generate ? ' with a generated key' : ''}. Install and start the service next. Other organizations' buses read the proxy settings when they start: restart a bus before its agents use the proxy.`, 'success'); - window.MosaicConsole?.attachBus?.($('proxy-setup-bus'), 'Restart this organization\'s bus'); + // #1873 settings slice 1 (D3): which organizations need a restart is a list on this page once the service runs. + say(`Initialized on port ${result.settings.port}${args.generate ? ' with a generated key' : ''}. Install and start the service next.`, 'success'); }); }); $('proxy-setup-render').addEventListener('click', async () => { @@ -886,6 +976,9 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo box.querySelectorAll('[data-unit]').forEach(button => button.addEventListener('click', () => { if (!button.disabled) unitAction(button.dataset.unit); })); return { start(config) { enabled = true; sendOk = config.proxyAdminSend === true; box.hidden = false; return load(); }, + accounts(n) { accountCount = n; if (state) { paintNext(); paintRestart(); } }, + // A sign-in, a key or a restart can change the next step: read the whole status again. + async reread() { if (!enabled) return; triageSet = null; await load(); }, stop() { enabled = false; clearTimeout(timer); timer = null; const f = form.elements; f.key.value = ''; f.confirm.value = ''; }, }; })(); @@ -900,7 +993,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo $('proxy-readonly').hidden = canWrite; message('Accounts and client keys loaded.'); } - const cleanup = () => { setup.stop(); clearTimeout(poll); login = null; const redirect=$('proxy-login-submit')?.elements.redirect_url, key=$('proxy-apikey')?.elements.key; if(redirect)redirect.value='';if(key)key.value=''; }; + // #1873 settings slice 1 (D3): a restart from this page's list reads the status again. + const onRestarted = () => { setup.reread(); }; + document.addEventListener('mosaic-org-restarted', onRestarted); + const cleanup = () => { document.removeEventListener('mosaic-org-restarted', onRestarted); setup.stop(); clearTimeout(poll); login = null; const redirect=$('proxy-login-submit')?.elements.redirect_url, key=$('proxy-apikey')?.elements.key; if(redirect)redirect.value='';if(key)key.value=''; }; window.addEventListener('pagehide', cleanup, {once:true}); let devOwner = false, proxyAdmin = false; fetch('/api/config', { cache: 'no-store' }).then(r => r.json()).then(config => { @@ -918,15 +1014,15 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo // and the setup load brings them back once the service answers. // Any failed read hides them, not only proxy-down: a proxy that is initialized but not yet answering // can fail with another code, and a stale error over an empty table would stay after Start. - if (proxyAdmin && error.message !== 'The model proxy is not configured for this instance.') { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el=>el.hidden=true); message(error.code === 'proxy-down' ? 'The model proxy is not running yet. Follow the next step under Proxy setup.' : `Accounts could not be read${error.code ? ` (${error.code})` : ''}. Follow the next step under Proxy setup; the account panels return once the proxy answers.`); return; } - if(error.message==='The model proxy is not configured for this instance.') { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el=>el.hidden=true); + if (proxyAdmin && error.message !== 'The model service is not set up on this instance.') { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el=>el.hidden=true); message(error.code === 'proxy-down' ? 'The model service is not running yet. Follow the next step under Set up the model service.' : `Accounts could not be read${error.code ? ` (${error.code})` : ''}. Follow the next step under Set up the model service; the account panels return once the service answers.`); return; } + if(error.message==='The model service is not set up on this instance.') { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el=>el.hidden=true); // #1873: the owner sets the proxy up on this page (Proxy setup above); no terminal note. - if (proxyAdmin) { message('The model proxy is not set up yet. Follow the next step under Proxy setup.'); return; } + if (proxyAdmin) { message('The model service is not set up yet. Follow the next step under Set up the model service.'); return; } // F3: on a dev instance, say plainly why this page cannot set the proxy up and what does. // Setup takes a management key typed twice at a terminal and writes the proxy's credentials; // this page never handles that key. Account sign-in (a provider's own OAuth) then runs here. if (devOwner) { const org = window.MosaicOrg?.id, note = document.createElement('div'); note.id = 'proxy-dev-setup'; note.className = 'panel'; - note.innerHTML = '

    Set up the model proxy

    Nothing else on this dev Console asks for a sign-in. The proxy is the exception: its setup asks for a management key, typed twice, and writes the proxy\'s credentials. This page never handles that key, so setup runs once in a terminal on this machine:

    Then refresh this page. Signing in to a Claude or Codex account is the provider\'s own sign-in, which cannot be skipped. It runs here, under Sign in to an account, with one button.

    '; + note.innerHTML = '

    Set up the model service

    Nothing else on this dev Console asks for a sign-in. The model service is the exception: its setup asks for a management key, typed twice, and writes its credentials. This page never handles that key, so setup runs once in a terminal on this machine:

    Then refresh this page. Signing in to a Claude or Codex account is the provider\'s own sign-in, which cannot be skipped. It runs here, under Sign in to an account, with one button.

    '; note.querySelector('code').textContent = `mosaic proxy fetch\nmosaic proxy init${org ? ` --org ${org}` : ''}`; $('proxy-message').after(note); } } }); return cleanup; diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index daaec1d47..a19c9e372 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -98,6 +98,17 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap} .console-reconnect>span{flex:1 1 220px;min-width:0;overflow-wrap:anywhere} .bus-restart{display:inline-flex;flex-wrap:wrap;gap:6px 10px;align-items:center;min-width:0} .bus-restart [role=status]:empty{display:none} +/* #1873 settings slice 1: a Restart for one named organization (console-restart.js orgRestartButton). */ +.org-restart{display:inline-flex;flex-wrap:wrap;gap:6px 10px;align-items:center;min-width:0;max-width:100%} +.org-restart [data-org-restart]{min-height:var(--action-target);white-space:normal;text-align:left} +.org-restart [role=status]{min-width:0;overflow-wrap:anywhere} +.org-restart [role=status]:empty{display:none} +.org-restart .org-restart-refused strong,.org-restart-refused strong{color:var(--strong)} +.org-restart [data-org-restart-detail]{display:block} +.routes-catalogue{flex-direction:column;align-items:stretch} +.routes-catalogue>p{flex:none} +.settings-content .org-down .banner p{margin:0 0 8px} +.settings-content .org-down .banner p:last-child{margin-bottom:0} .routes-apply{margin:12px 0 0;padding-left:18px;display:grid;gap:8px} .routes-apply li{overflow-wrap:anywhere} .agent-restart{display:inline-flex;flex-wrap:wrap;gap:6px 10px;align-items:center;min-width:0} @@ -109,6 +120,18 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap} .proxy-setup-buttons{display:flex;flex-wrap:wrap;gap:8px}.proxy-setup-buttons button{min-height:44px} #proxy-setup pre{overflow-x:auto;max-width:100%;font-size:12px}#proxy-setup h3{margin:16px 0 4px}#proxy-setup details{margin:0 0 12px}#proxy-setup summary{min-height:44px;display:flex;align-items:center;cursor:pointer} #proxy-setup-receipts{padding-left:20px;overflow-wrap:anywhere;font-size:13px} +/* #1873 settings slice 1 (D3, D4): the kept restart list and Technical details. */ +.proxy-setup-restart{margin:0 0 12px} +.proxy-setup-restart-list{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:8px} +.proxy-setup-restart-list li{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r);min-width:0} +.proxy-setup-restart-list li>.small{flex:1 1 220px;min-width:0;overflow-wrap:anywhere} +.proxy-setup-restart-name{display:inline-flex;flex-wrap:wrap;align-items:center;gap:6px;min-width:0} +.proxy-setup-tech>summary{font-weight:600} +#triage-route-harness-help{display:block;margin-top:4px;max-width:36ch} +#triage-route select{max-width:100%} +.triage-state-fix{margin:0 0 8px}.triage-fix{white-space:normal} +/* #1873 settings slice 1: at phone width a model select takes the whole row, so a long model name is not cut. */ +@media(max-width:759px){.routing-panel #routes-table td:nth-of-type(2),.routing-panel #routes-table td:nth-of-type(5){grid-column:1/-1}.routing-panel #routes-table select{width:100%;max-width:100%}} @media(max-width:479px){.proxy-setup-state{grid-template-columns:1fr}.proxy-setup-state dd{margin-bottom:6px}} /* Stream S4: which organization this is, in words. Colour (the theme) is never the only cue; the strip appears whenever the theme is not the built-in one. */ .org-cue{margin:0 0 12px;padding:6px 10px;border:1px solid var(--line);border-left:4px solid var(--action);border-radius:var(--r-table);background:var(--raised);color:var(--text);font-size:13px;overflow-wrap:anywhere}.skel-rows{display:grid;gap:10px;padding:14px 12px;border:1px solid var(--line);border-radius:var(--r-table);background:var(--surface)} diff --git a/packages/webui/src/public/triage-settings.js b/packages/webui/src/public/triage-settings.js index 30ed5813a..8654e00a6 100644 --- a/packages/webui/src/public/triage-settings.js +++ b/packages/webui/src/public/triage-settings.js @@ -33,11 +33,15 @@ const models = () => (Array.isArray(data?.choices?.models) ? data.choices.models : []); const harnessesOf = key => models().find(m => m.key === key)?.harnesses ?? []; + // #1873 settings slice 1 (section 9): the owner reads a harness by its product name; the id stays the value. + const HARNESS_NAMES = { 'claude-code': 'Claude Code', codex: 'Codex', opencode: 'OpenCode' }; + const harnessName = h => HARNESS_NAMES[h] ?? h; + const savedAt = v => (Number.isFinite(Date.parse(v)) ? window.MosaicLocalTime(v) : 'at an unknown time'); 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)}.

    `; + if (!r) return `

    Not set. Triage has no model chosen yet, so it will not start.

    `; + return `

    Saved route: ${esc(r.model)}, runs with ${esc(harnessName(r.harness))}. Daily token limit ${esc(Number(r.cap).toLocaleString('en-US'))}, resets at ${esc(r.reset)} ${esc(r.timeZone)}. Saved ${esc(savedAt(r.updatedAt))}.

    `; } function form() { @@ -50,16 +54,16 @@ + (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 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 catalogue = status === 'ready' ? '' : `

    No organization can show your models right now, so no route can be saved. Open model service settings to see which organizations need a restart.

    `; const conflictButton = conflict ? ' ' : ''; return `${catalogue}
    ` + `` - + `` - + `` + + `` + + `` + `` + `` + `
    ${zones.map(z => ``).join('')}` @@ -92,7 +96,7 @@ 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}.`; + line = `Saved ${savedAt(a.route.updatedAt)}.`; repaint(); $('triage-route-line')?.focus?.(); return; diff --git a/packages/webui/tests/proxy-setup-browser.test.mjs b/packages/webui/tests/proxy-setup-browser.test.mjs index 3b0b7b7e3..b5d3e7af0 100644 --- a/packages/webui/tests/proxy-setup-browser.test.mjs +++ b/packages/webui/tests/proxy-setup-browser.test.mjs @@ -32,7 +32,7 @@ test('a fresh instance shows the fetch step as one button, the not-built own pro assert.match(await b.evaluate('document.querySelector("#proxy-setup-next p").textContent'), /CLIProxyAPI 8\.0\.42/); assert.match(await b.evaluate('document.querySelector("#proxy-setup-own").textContent'), /not built/); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-orgs td").textContent'), 'acme'); - await wait('document.querySelector("#proxy-message")?.textContent.includes("Follow the next step under Proxy setup")'); + await wait('document.querySelector("#proxy-message")?.textContent.includes("Follow the next step under Set up the model service")'); assert.equal(await b.evaluate('!!document.querySelector("#proxy-dev-setup")'), false, 'the page replaces the terminal note'); assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-init [data-setup-write]:not([disabled])").length'), 0, 'init waits for a verified release'); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); @@ -113,7 +113,7 @@ test('an initialized proxy whose accounts read fails with another code also hide const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(installed), ...failing, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit.start', time: T, pid: 4242 } } } } }); await b.navigate(f.base + '/#/settings/model-proxy'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-start"'); - await wait('document.querySelector("#proxy-message").textContent.includes("the account panels return once the proxy answers")'); + await wait('document.querySelector("#proxy-message").textContent.includes("the account panels return once the service answers")'); assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), true); await b.evaluate(`Object.assign(window.__scenario, { 'GET /api/proxy/accounts': { body: { accounts: [] } }, 'GET /api/proxy/keys': { body: { keys: [] } }, @@ -208,3 +208,111 @@ test('Ride all confirms the stricter admission, paints skips and stand-in organi 'Skipped east: Its organization file, its change log or the proxy\'s receipts could not be read. A damaged line in the proxy\'s receipts must be repaired by hand before Ride all adds again.']); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); + +// #1873 settings slice 1 (DESIGN.md sections 4 and 9, D1, D3, D4). The service runs ("accounts" is the +// server's next step); the steps after it come from what the page reads: accounts, organizations, Triage route. +const running = { ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, + unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] }; +const account = { accountId: 'a1', displayName: 'Claude work', provider: 'claude', status: 'active', priority: 0 }; +const answering = (n = 1) => ({ 'GET /api/proxy/accounts': { body: { accounts: Array.from({ length: n }, () => account) } }, 'GET /api/proxy/keys': { body: { keys: [] } } }); +const savedRoute = { route: { model: 'm', harness: 'claude-code', cap: 1000, reset: '00:00', timeZone: 'UTC', revision: 1, updatedAt: T } }; +const restarted = { body: { outcome: 'done', step: 'bus-restart', restarted: true, healthy: true } }; +const visible = sel => `[...document.querySelectorAll(${JSON.stringify(sel)})].filter(e=>e.checkVisibility())`; + +test('settings-s1 B2: once the service runs, the organizations that cannot see the models stay listed, each with its own Restart', { timeout: 90000 }, async t => { + const orgs = [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'beta', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }, + { id: 'gamma', proxy: 'shared', catalogue: { status: 'ready', models: 3 } }, { id: 'delta', proxy: 'shared', catalogue: { status: 'disabled' } }]; + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, 'POST /api/orgs/acme/restart/bus': restarted } }); + await b.navigate(f.base + '/#/settings/model-proxy'); + await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===2'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-restart").checkVisibility()'), true); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-restart-list li")].map(li=>[li.dataset.restartOrg, li.querySelector(".badge").className, li.querySelector(".badge").textContent, li.querySelector("[data-org-restart]")?.textContent ?? null])'), + [['acme', 'badge badge-attn', "Can't see models", 'Restart acme'], ['beta', 'badge badge-danger', 'Not running', 'Restart beta']]); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null, 'the next step is the list, so no second button'); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart acme and beta\./); + // A restart reads the status again; the organization stays on the list, now ready, so the owner sees it worked. + await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...running, organizations: [{ ...orgs[0], catalogue: { status: 'ready', models: 3 } }, ...orgs.slice(1)] })}`); + await b.evaluate('document.querySelector("[data-org-restart=acme]").focus()'); + assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none', 'the focused Restart shows a focus ring'); + await b.key('Enter', 'Enter'); + await wait('document.querySelector("[data-restart-org=acme] .badge")?.textContent==="Ready"'); + assert.deepEqual(await b.evaluate('window.__writes.map(w=>w.method+" "+w.path)'), ['POST /api/orgs/acme/restart/bus']); + assert.equal(await b.evaluate('document.querySelector("[data-restart-org=acme] [data-org-restart]")'), null, 'a ready organization has no Restart'); + assert.equal(await b.evaluate('document.querySelector("[data-restart-org=acme] .badge").className'), 'badge badge-ok'); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart beta\./); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); +}); + +test('settings-s1 B2: a refused restart keeps its reason on the list across the status read that follows', { timeout: 90000 }, async t => { + const orgs = [{ id: 'lab', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }]; + const refusal = { status: 409, body: { error: 'bus-start-refused', message: 'bus start refused: fixture-proxy-configured' } }; + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, 'POST /api/orgs/lab/restart/bus': refusal } }); + await b.navigate(f.base + '/#/settings/model-proxy'); + await wait('document.querySelector("[data-org-restart=lab]")'); + await b.evaluate('document.querySelector("[data-org-restart=lab]").click()'); + await wait('document.querySelector("[data-restart-org=lab] .org-restart-refused")'); + await new Promise(r => setTimeout(r, 300)); + assert.equal(await b.evaluate('document.querySelector("[data-restart-org=lab] [data-org-restart-receipt] strong").textContent'), "lab runs on test models, which can't share this machine with your model service. It did not start."); + assert.equal(await b.evaluate('document.querySelector("[data-restart-org=lab] .badge").className'), 'badge badge-danger', 'a refused organization is never green'); +}); + +test('settings-s1 B3: a sign-in reads the whole status again and the next step follows accounts, organizations, then the Triage route', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }] }, { orgSetup: true }), ...answering(0), '/api/triage/route': { route: null }, + 'POST /api/proxy/login/status': { body: { status: 'error', reason: 'login-timeout' } } } }); + await b.navigate(f.base + '/#/settings/model-proxy'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="accounts"'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Add an account'); + await b.evaluate(`window.open = () => null; window.__scenario['POST /api/proxy/login/start'] = { body: { url: location.origin + '/signin-stub', state: 's1' } }`); + // A sign-in that runs out of time says so plainly. + await b.evaluate('document.querySelector("#proxy-login-start").requestSubmit()'); + await wait('document.querySelector("#proxy-login-message").textContent==="Sign-in took too long. Try again."'); + // The next sign-in finishes. The status read after it is the one that names acme, so the step proves the reread. + await b.evaluate(`Object.assign(window.__scenario, ${JSON.stringify({ ...answering(1), 'POST /api/proxy/login/status': { body: { status: 'ok' } }, '/api/proxy/admin/status': { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }] } })})`); + await b.evaluate('document.querySelector("#proxy-login-start").requestSubmit()'); + await wait('document.querySelector("#proxy-setup-next [data-next]")?.dataset.next==="restart-orgs"'); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart acme\./); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-message").textContent'), 'Account signed in.'); + // acme restarts and can see the models; the Triage route is not set, so that is the step after. + await b.evaluate(`Object.assign(window.__scenario, ${JSON.stringify({ 'POST /api/orgs/acme/restart/bus': restarted, '/api/proxy/admin/status': { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }] } })})`); + await b.evaluate('document.querySelector("[data-org-restart=acme]").click()'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="triage-route"'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Open Triage settings'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").disabled'), false); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); +}); + +// Rebase onto ride-default: with an account, Ride all is the step after accounts while an organization can +// ride now, and its box shows outside Technical details. Stand-in organizations alone do not hold the step. +test('settings-s1 B3 with ride-default: Ride all follows accounts while an organization can ride, and only then', { timeout: 90000 }, async t => { + const riding = { ...running, next: ['accounts', 'ride-all'], organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], + ride: [{ id: 'north', state: 'ready' }, { id: 'west', state: 'fixture' }] }; + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(riding), ...answering(1), '/api/triage/route': { route: null } } }); + await b.navigate(f.base + '/#/settings/model-proxy'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="ride-all"'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Ride all'); + assert.equal(await b.evaluate('document.querySelector("#proxy-ride").checkVisibility()'), true, 'the Ride all box is not folded under Technical details'); + assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), false); + // Ride all adds north. Only a stand-in organization is left: the step moves on to the Triage route, and Move stays offered. + await b.evaluate(`window.confirm = () => true; Object.assign(window.__scenario, ${JSON.stringify({ '/api/proxy/admin/status': { ...riding, ride: [{ id: 'north', state: 'already' }, { id: 'west', state: 'fixture' }] }, + 'POST /api/proxy/admin/ride-all': { body: { added: ['north'], already: [], skipped: [], fixtures: [{ id: 'west' }], receipt: { op: 'ride.all', time: T } } } })})`); + await b.evaluate('document.querySelector("#proxy-ride-go").click()'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="triage-route"'); + assert.equal(await b.evaluate('document.querySelector("[data-ride-move=west]").checkVisibility()'), true); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); +}); + +test('settings-s1 B4: only the next step has a button; done steps, Fence, Init lock and the service controls sit under Technical details', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running), ...answering(0), '/api/triage/route': savedRoute } }); + await b.navigate(f.base + '/#/settings/model-proxy'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="accounts"'); + assert.deepEqual(await b.evaluate(`${visible('#proxy-setup button')}.map(e=>e.id||e.textContent)`), ['proxy-setup-go'], 'one visible button in the setup panel'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init-box").checkVisibility()'), false, 'init is done, so its form is gone'); + const tech = await b.evaluate('(()=>{const d=document.querySelector("#proxy-setup-tech");return {summary:d.querySelector("summary").textContent,open:d.open,terms:[...d.querySelectorAll("dt")].map(x=>x.textContent),units:d.querySelectorAll("[data-unit]").length,receipts:!!d.querySelector("#proxy-setup-receipts")}})()'); + assert.deepEqual(tech, { summary: 'Technical details', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock'], units: 4, receipts: true }); + assert.equal(await b.evaluate(`${visible('#proxy-setup dt, #proxy-setup [data-unit]')}.length`), 0, 'nothing technical shows until it is opened'); + // Technical details opens by keyboard and shows the controls. + await b.evaluate('document.querySelector("#proxy-setup-tech summary").focus()'); + await b.key('Enter', 'Enter'); + await wait('document.querySelector("#proxy-setup-tech").open'); + assert.equal(await b.evaluate(`${visible('#proxy-setup [data-unit]')}.length`), 4); +}); diff --git a/packages/webui/tests/routes-browser.test.mjs b/packages/webui/tests/routes-browser.test.mjs index ba77b11cc..159710e85 100644 --- a/packages/webui/tests/routes-browser.test.mjs +++ b/packages/webui/tests/routes-browser.test.mjs @@ -197,7 +197,7 @@ test('Routing switch writes the model-provider setting and keeps other modules', await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`const original=window.fetch;window.posts=[];window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify({send:true}));if(url==='/api/proxy/plugins')return new Response(JSON.stringify(${JSON.stringify(settings)}));if(url==='/api/proxy/plugins/set'){posts.push(JSON.parse(options.body));return new Promise(r=>window.answer=(status,body)=>r(new Response(JSON.stringify(body),{status})));}return original(url,options);};`}); await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/routing`); const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed');})()`); - await wait('document.querySelector("#provider-switch")?.textContent.startsWith("Enable")'); + await wait('document.querySelector("#provider-switch")?.textContent.startsWith("Use your models")'); await b.evaluate('document.querySelector("#provider-switch").click();true'); await wait('posts.length===1');const payload=await b.evaluate('posts[0]'); assert.deepEqual(payload.plugins,{'model-provider':['cliproxy']}); @@ -271,8 +271,8 @@ test('quick fallback edits survive the harness redraw', {timeout:60000}, async t // organization's catalogue is ready with no proxy, and its switch reads Enable. test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disable and removes cliproxy only; a fixture-only org reads Enable', {timeout:90000}, async t => { for (const [providers, label, line, next] of [ - [['fixture','cliproxy'], 'Disable', /Model catalogue unavailable\. A change to thinking alone still saves\. A new model needs the catalogue: set up the model proxy, or, when this organization has none, press Disable model proxy catalogue\./, ['fixture']], - [['fixture'], 'Enable', /^Model catalogue, observed /, ['fixture','cliproxy']], + [['fixture','cliproxy'], 'Stop using the model service', /can't see your models yet\. A change to thinking alone still saves\. A new model needs the model service: ask the instance owner to set it up, or press Stop using the model service when this organization does not need it\./, ['fixture']], + [['fixture'], 'Use your models', /^Model catalogue, observed /, ['fixture','cliproxy']], ]) { const root=tmp(t,'d3-switch-'), f=fixture(root,'acme',doc=>{doc.plugins['model-provider']=providers;return doc;}); const dir=join(root,'config'),file=join(dir,'businesses','acme.json'); @@ -291,7 +291,7 @@ test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disab const [info,...notices]=await b.evaluate('[document.querySelector(".routing-panel > p.small")?.textContent,...[...document.querySelectorAll(".routing-panel > p.small.warn")].slice(1).map(p=>p.textContent)]'); assert.match(info,line,providers.join(',')); // proxy-pickup (#1873): an unavailable catalogue shows the bus's cause line under it. - assert.deepEqual(notices,label==='Disable'?['The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.']:[],providers.join(',')); + assert.deepEqual(notices,label==='Stop using the model service'?['The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.']:[],providers.join(',')); await b.evaluate('document.querySelector("#provider-switch").click();true'); await wait('posts.length===1');const payload=await b.evaluate('posts[0]'); assert.deepEqual(payload.plugins,{'model-provider':next},providers.join(',')); @@ -308,10 +308,10 @@ test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disab test('D3 Routing: a catalogue refusal names Disable only when it can make the save apply, and sends a tester to the owner', {timeout:90000}, async t => { const refusal=code=>({error:code,message:`${code}: the reason. Nothing changed.`,sent:false}); for (const [providers, tester, instance, code, expect] of [ - [['fixture','cliproxy'], false, 'coder', 'model-catalogue-unavailable', /Nothing changed\. This change needs no model proxy: press Disable model proxy catalogue, then save again\. Draft kept\.$/], + [['fixture','cliproxy'], false, 'coder', 'model-catalogue-unavailable', /Nothing changed\. This change does not need the model service: press Stop using the model service, then save again\. Draft kept\.$/], [['fixture','cliproxy'], false, 'reviewer', 'model-catalogue-unavailable', /Nothing changed\. Draft kept\.$/], [['fixture'], false, 'reviewer', 'model-provider-unavailable', /Nothing changed\. Draft kept\.$/], - [['fixture','cliproxy'], true, 'coder', 'model-catalogue-unavailable', /Nothing changed\. Ask the organization's owner to set up the model proxy, or to disable the model proxy catalogue when the change needs no proxy\. Draft kept\.$/], + [['fixture','cliproxy'], true, 'coder', 'model-catalogue-unavailable', /Nothing changed\. Ask the organization's owner to set up the model service, or to stop using it when the change does not need it\. Draft kept\.$/], ]) { const label=`${providers.join(',')} tester=${tester} ${instance}`; const view={business:'acme',revision:'a'.repeat(64),harnesses:['pi','claude-code'],models:['fixture-deterministic','proxy-x'], diff --git a/packages/webui/tests/settings-s1-browser.test.mjs b/packages/webui/tests/settings-s1-browser.test.mjs new file mode 100644 index 000000000..8938fed9a --- /dev/null +++ b/packages/webui/tests/settings-s1-browser.test.mjs @@ -0,0 +1,272 @@ +// #1873 settings slice 1, bullets 1 and 6 (DESIGN.md sections 3.4, 5 and 9; DEFECTS D2 and D7). +// B1: Routing in an organization that lists the model service but cannot see its models says why, +// and offers Restart only when the model service runs and the bus names no cause. A running bus picks +// the service up at its next catalogue read (proxy-pickup); when it still cannot, its cause line shows +// with Check again, because a restart would not fix that cause. B6: a stopped organization's Settings page +// keeps a refused restart's reason on screen and keeps the instance pages one link away. +// Every bus is a fake: acme answers, gamma is stopped. The page's own reads of the routes, the +// plugin list and the model service state are answered by a fetch stub; the rest is the real server. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { fileURLToPath } from 'node:url'; +import { startServer } from '../src/serve.mjs'; +import { createDevOwner } from '../src/dev-owner.mjs'; +import { browser } from './browser.mjs'; +import { close } from './fixture.mjs'; +import { ReadError } from '../src/reads.mjs'; + +const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString(); +const LIST = [ + { id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true }, + { id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true }, +]; +const ROLES = { acme: { chief: { definition: 'chief-of-staff' }, coder: { definition: 'coder' } }, gamma: { chief: { definition: 'chief-of-staff' } } }; + +// The routes acme's bus answers; a test swaps it to show a restart that brought the catalogue up. +const state = { view: null }; + +async function fixture() { + const { checkRootAgents } = await import('../../organization/src/index.mjs'); + const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url)); + const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) }; + const empty = () => Promise.resolve([]); + const member = org => ({ + id: org.id, doc: { appearance: { theme: org.theme }, roles: ROLES[org.id], projects: {} }, + status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }), + options: () => ({ bus: { inbox: empty, agents: empty, 'thread.claims': empty, tasks: empty, usage: () => Promise.resolve({}), limits: () => Promise.resolve({}), decisions: empty }, chat: { threads: empty, projects: empty } }), + }); + const organizations = { + list: async () => LIST, + members: async () => LIST.map(member), + resolve: async id => { + const org = LIST.find(o => o.id === id); if (!org) return null; + // As in production, a stopped organization keeps its reads; each one that needs the bus fails. + if (!org.busHealthy) return { busHealthy: false, reads: { settings: async () => { throw new ReadError('bus-unavailable'); } }, bus: {}, chat: { projects: empty, threads: empty } }; + return { + busHealthy: true, + reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {} }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, + bus: { messages: async () => ({ messages: [], unread: 0 }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => state.view, instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) }, + chat: { projects: empty, threads: empty }, + }; + }, + }; + return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } }; +} + +const VIEW = { + business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi', 'claude-code'], models: ['fixture-deterministic'], + providerModels: { 'fixture-deterministic': { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic' } }, + levels: { pi: ['off', 'low'], 'claude-code': ['off', 'low'] }, + instances: { coder: { harness: 'pi', model: 'fixture-deterministic', thinking: 'off', fallback: null } }, + catalogue: { status: 'unavailable', models: [], notices: [] }, +}; +const PLUGINS = { revision: 'b'.repeat(64), plugins: { harness: ['pi', 'claude-code'], 'model-provider': ['fixture', 'cliproxy'] }, available: { harness: ['pi', 'claude-code'] } }; +const SERVICE = { + running: { init: { initialized: true }, unit: { active: 'active', healthy: true }, fence: { set: false } }, + stopped: { init: { initialized: true }, unit: { active: 'inactive', healthy: false }, fence: { set: false } }, + fresh: { init: { initialized: false }, unit: { active: 'inactive', healthy: false }, fence: { set: false } }, +}; +const DONE = { status: 200, body: { outcome: 'done', step: 'bus-restart', restarted: true, healthy: true } }; +const REFUSED = { status: 409, body: { error: 'bus-start-refused', message: 'bus start refused: fixture-proxy-configured' } }; + +// The stub answers by path suffix, so it serves both the scoped reads (display.js scopes /api/x to +// /api/orgs//x) and console-restart.js, which binds fetch before that wrapper. The routes come +// from acme's fake bus. /api/config is the +// server's own answer with the instance owner's flags added; the dev owner is not a root owner here. +const stub = ({ service = SERVICE.running, restart = DONE, extra = {} } = {}) => `(() => { + const real = window.fetch.bind(window); window.__writes = []; + window.__s1 = ${JSON.stringify({ plugins: PLUGINS, service, restart, extra })}; + const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + window.fetch = async (input, init = {}) => { + const url = new URL(typeof input === 'string' ? input : input.url, location.href), path = url.pathname, method = (init.method || 'GET').toUpperCase(); + if (method === 'POST' && /^\\/api\\/orgs\\/[^/]+\\/restart\\/bus$/.test(path)) { __writes.push(path); return json(__s1.restart.body, __s1.restart.status); } + if (method !== 'GET') return real(input, init); + for (const [suffix, body] of Object.entries(__s1.extra)) if (path.endsWith(suffix)) return json(body); + if (/\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(path)) { const c = await (await real(input, init)).json(); return json({ ...c, orgSetup: true, proxyAdmin: true, proxyAdminSend: true, ...(/\\/orgs\\//.test(path) ? { settingsSend: true } : {}) }); } + if (path.endsWith('/proxy/plugins')) return json(__s1.plugins); + if (path.endsWith('/proxy/admin/status')) return json(__s1.service); + return real(input, init); + }; +})();`; + +async function setup(t, { viewport = [1440, 900], path, init, triage = null, view = VIEW }) { + state.view = view; + const { organizations, agentLevels } = await fixture(); + const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, triage, send: async () => ({}), log: () => {} }); + t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + await b.viewport(...viewport); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: init }); + const base = `http://127.0.0.1:${server.address().port}`; + await b.navigate(`${base}${path}`); + const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error("wait failed: "+${JSON.stringify(expression)}+" HASH "+location.hash+" BODY "+(document.querySelector("main")?.innerText??document.body.innerText).slice(0,600))})()`); + return { b, base, wait, text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) }; +} + +test('settings-s1 B1: with the model service running and no cause from the bus, Routing offers the organization\'s Restart', { timeout: 90000 }, async t => { + const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub() }); + await wait('document.querySelector("#routes-catalogue [data-org-restart=acme]")'); + const line = await text('#routes-catalogue'); + assert.match(line, /^Acme Studio can't see your models yet\. Your model service is running, but Acme Studio can't read your models from it\. Restart Acme Studio to connect it again\./); + assert.doesNotMatch(line, /model proxy/i); + const button = await b.evaluate('(() => { const e = document.querySelector("#routes-catalogue [data-org-restart=acme]"); return { text: e.textContent, primary: e.classList.contains("primary") }; })()'); + assert.deepEqual(button, { text: 'Restart Acme Studio', primary: true }); + // Keyboard: the button takes focus with a visible ring and Enter presses it. + await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart=acme]").focus(); true'); + assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none'); + state.view = { ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] } }; + await b.key('Enter', 'Enter'); + await wait('window.__writes.length === 1'); + assert.deepEqual(await b.evaluate('window.__writes'), ['/api/orgs/acme/restart/bus']); + // The page reads the routes again after the restart, and a ready catalogue has no Restart line. + await wait('!document.querySelector("#routes-catalogue") && /Model catalogue, observed/.test(document.querySelector(".routing-panel")?.textContent ?? "")'); +}); + +test('settings-s1 B1: when the bus names why it cannot use the running model service, Routing shows that line and Check again, and the lock cause adds a secondary Restart', { timeout: 90000 }, async t => { + const cause = 'The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.'; + const view = { ...VIEW, catalogue: { status: 'unavailable', reason: 'proxy-not-configured', models: [], notices: [cause] } }; + const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub(), view }); + await wait('document.querySelector("#routes-catalogue #routes-recheck")'); + const line = await text('#routes-catalogue'); + assert.match(line, /^Acme Studio can't see your models yet\. Your model service is running, but Acme Studio can't use it\. Acme Studio says why:/); + assert.ok(line.includes(cause), line); + // The lock cause asks for a restart, so a secondary Restart sits beside Check again. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#routes-catalogue [data-org-restart]")].map(e => [e.textContent, e.classList.contains("primary")])'), [['Restart Acme Studio', false]]); + // Keyboard: Check again takes focus with a visible ring; Enter rereads, and the bus has the service now. + await b.evaluate('document.querySelector("#routes-recheck").focus(); true'); + assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none'); + state.view = { ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] } }; + await b.key('Enter', 'Enter'); + await wait('!document.querySelector("#routes-catalogue") && /Model catalogue, observed/.test(document.querySelector(".routing-panel")?.textContent ?? "")'); + assert.deepEqual(await b.evaluate('window.__writes'), [], 'Check again writes nothing'); +}); + +test('settings-s1 B1: a cause a restart cannot fix, such as the dev fixture, offers Check again and no Restart', { timeout: 90000 }, async t => { + const cause = 'This organization routes launches to the dev fixture, which the host refuses next to a model proxy (fixture-proxy-configured). Remove the fixture or stop using it here.'; + const view = { ...VIEW, catalogue: { status: 'unavailable', reason: 'proxy-not-configured', models: [], notices: [cause] } }; + const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub(), view }); + await wait('document.querySelector("#routes-catalogue #routes-recheck")'); + assert.ok((await text('#routes-catalogue')).includes(cause)); + assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null, 'a restart would be refused and stop the organization'); +}); + +test('settings-s1 B1: with the model service not set up or not running, Routing links to its page and offers no Restart', { timeout: 90000 }, async t => { + for (const [service, expect, href] of [ + [SERVICE.fresh, /Your model service isn't set up yet\. Set up the model service\./, '#/settings/model-proxy'], + [SERVICE.stopped, /The model service is not running\. Open the model service settings\./, '#/settings/model-proxy'], + ]) { + const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub({ service }) }); + await wait('document.querySelector("#routes-catalogue a")'); + assert.match(await text('#routes-catalogue'), expect); + assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null); + assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a").getAttribute("href")'), href); + await b.close(); + } +}); + +test('settings-s1 B6: a stopped organization keeps its refused restart on screen and keeps the instance pages reachable', { timeout: 90000 }, async t => { + const { b, wait, text } = await setup(t, { path: '/#/orgs/gamma/settings/routing', init: stub({ restart: REFUSED }) }); + await wait('document.querySelector("[data-org-down=gamma] [data-org-restart=gamma]")'); + assert.match(await text('[data-org-down=gamma] .banner.err'), /^Gamma Home is stopped, so Routing can't be read\./); + // One Restart on the page: the header's bus banner steps aside. + assert.equal(await b.evaluate('[...document.querySelectorAll("[data-org-restart], #bus-restart")].filter(e => e.offsetParent).length'), 1); + await b.evaluate('document.querySelector("[data-org-down=gamma] [data-org-restart=gamma]").click(); true'); + await wait('window.__writes.length === 1 && document.querySelector("[data-org-down=gamma] [data-org-restart-detail]")'); + // The page renders again after the restart; the refusal stays, with its plain line first. + await new Promise(r => setTimeout(r, 500)); + const receipt = await text('[data-org-down=gamma] [data-org-restart-receipt]'); + assert.match(receipt, /^Gamma Home runs on test models, which can't share this machine with your model service\. It did not start\./); + assert.match(receipt, /bus start refused: fixture-proxy-configured/); + const links = await b.evaluate('[...document.querySelectorAll("[data-org-down=gamma] a")].map(a => [a.textContent, a.getAttribute("href")])'); + assert.deepEqual(links, [['Appearance', '#/settings/appearance'], ['Model service', '#/settings/model-proxy'], ['Triage', '#/settings/triage'], ['Console', '#/settings/console']]); + // A link from the stopped page opens an instance page. + await b.evaluate('document.querySelector("[data-org-down=gamma] a[href=\'#/settings/model-proxy\']").click(); true'); + await wait('document.querySelector("#proxy-setup") || document.querySelector("h1")?.textContent === "Model proxy"'); + assert.notEqual(await text('h1'), 'Not found'); +}); + +// Shots for the build report, current beside proposed: run with MOSAIC_UX_SHOTS=, on this tree and on +// the base tree with this file copied in. Each waits only for what both trees draw, then settles. At 390 +// every visible select must show its chosen text in full, and no page scrolls sideways. +test('shots', { timeout: 600000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => { + const { mkdir, writeFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + const { TriageError, ROUTE_REFUSALS } = await import('../src/triage-host.mjs'); + const dir = process.env.MOSAIC_UX_SHOTS; await mkdir(dir, { recursive: true }); + const settle = () => new Promise(r => setTimeout(r, 1500)); + const T = new Date(Date.now() - 20 * 60000).toISOString(); + const status = { release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' }, + init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, + unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', healthy: true, pid: 4242, port: 18432, listening: true }, + fence: { set: false }, initLock: { present: false, clearable: false, blockers: [] }, fetch: { state: 'idle' }, restart: null, busy: null, + organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'gamma', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }], + ownProxy: { available: false, state: 'not built', reason: 'The configuration has one proxy per instance.' }, next: ['accounts'] }; + const triageRead = { route: { model: 'sonnet', harness: 'claude-code', cap: 200000, reset: '00:00', timeZone: 'Europe/Berlin', revision: 1, updatedAt: T }, revision: 1, send: true, + choices: { status: 'ready', models: [{ key: 'sonnet', label: 'Sonnet', available: true, harnesses: ['claude-code', 'pi'] }, { key: 'glm-flash', label: 'GLM Flash', available: true, harnesses: ['pi'] }] }, + note: 'Saving a route does not start Triage. The key and the wiring are separate.' }; + const extra = { '/proxy/accounts': { accounts: [{ accountId: 'a1', displayName: 'Claude work', provider: 'claude', status: 'active', priority: 0 }] }, '/proxy/keys': { keys: [] }, '/api/triage/route': triageRead }; + const snapshot = { snapshotVersion: 1, at: T, console: { state: 'answering', at: T }, proxy: 'not read', systemConfig: { valid: true, exit: 0, code: null }, + organizations: { count: 2, list: [{ id: 'acme', bus: { state: 'running', lastStart: { ok: true, at: T } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } }, + { id: 'gamma', bus: { state: 'stopped', lastStart: { ok: false, at: T } }, processing: 'not read', config: { valid: true, exit: 0, code: null } }] } }; + const triage = { snapshotAt: () => Date.now(), refresh: async () => null, + state: async () => ({ route: 'set', running: false, lastExit: null, overCapUntil: null, snapshot, transcript: [] }), + message: async () => { throw new TriageError('triage-harness-incompatible', ROUTE_REFUSALS['triage-harness-incompatible']); } }; + const PAGES = [ + { name: 'routing', path: '/#/orgs/acme/settings/routing', ready: 'document.querySelector(".routing-panel select")' }, + // proxy-pickup: the bus names why it cannot use the running model service. + { name: 'routing-cause', path: '/#/orgs/acme/settings/routing', ready: 'document.querySelector(".routing-panel select")', + view: { ...VIEW, catalogue: { status: 'unavailable', reason: 'proxy-not-configured', models: [], notices: ['The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.'] } } }, + { name: 'model-service', path: '/#/orgs/acme/settings/model-proxy', ready: 'document.querySelector("#proxy-setup") && !document.querySelector("#proxy-setup").hidden' }, + { name: 'triage-settings', path: '/#/orgs/acme/settings/triage', ready: 'document.querySelector("#triage-route select")' }, + { name: 'org-down', path: '/#/orgs/gamma/settings/routing', ready: 'document.querySelector("h1")', after: async (b, wait) => { + const restart = await b.evaluate('!!document.querySelector("[data-org-restart=gamma], #bus-restart")'); + if (restart) { await b.evaluate('document.querySelector("[data-org-restart=gamma]")?.click() ?? document.querySelector("#bus-restart")?.click(); true'); await wait('window.__writes.length > 0'); } + } }, + { name: 'triage-drawer', path: '/#/dashboard', viewportOnly: true, ready: 'document.querySelector("#triage-open")', after: async (b, wait) => { + await b.evaluate('document.querySelector("#triage-open").click(); true'); + await wait('document.querySelector("#triage-text") && !document.querySelector("#triage-text").disabled'); + await b.evaluate('document.querySelector("#triage-text").focus(); true'); await b.call('Input.insertText', { text: 'is gamma healthy?' }); + await b.evaluate('document.querySelector("#triage-send").click(); true'); + await wait('document.querySelector("#triage-send-status")?.textContent.trim()'); + } }, + ]; + const report = []; + for (const page of PAGES) { + const f = await setup(t, { path: '/', init: stub({ service: status, restart: REFUSED, extra }), triage, view: page.view ?? VIEW }); + // A phone draws its scrollbar over the page; headless Chromium would take 15px of the 390 for it. + await f.b.call('Emulation.setScrollbarsHidden', { hidden: true }); + for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) { + await f.b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] }); + await f.b.viewport(width, width === 390 ? 844 : 900); + await f.b.navigate(`${f.base}/?shot=${page.name}-${scheme}-${width}${page.path.slice(1)}`); + await f.wait(`(${page.ready}) && !!window.MosaicAppearance`); + await f.b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`); + if (page.after) await page.after(f.b, f.wait); + await settle(); + const fit = await f.b.evaluate(`(() => { + const out = [], probe = document.createElement('span'); probe.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap'; document.body.append(probe); + for (const s of document.querySelectorAll('select')) { if (!s.checkVisibility()) continue; const cs = getComputedStyle(s), r = s.getBoundingClientRect(); + probe.style.font = cs.font; probe.textContent = s.selectedOptions[0]?.textContent ?? ''; + const room = s.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight); + out.push({ label: s.getAttribute('aria-label') || s.id || s.name, text: probe.textContent, need: Math.ceil(probe.getBoundingClientRect().width), room: Math.floor(room), inside: r.left >= 0 && r.right <= innerWidth + 0.5 }); } + probe.remove(); return { selects: out, sideways: document.documentElement.scrollWidth > document.documentElement.clientWidth }; + })()`); + const shot = `${page.name}-${width}-${scheme}.png`; + // The drawer is fixed to the window, so its shot is the window; every other page is shot whole. + if (page.viewportOnly) await f.b.screenshot(join(dir, shot)); + else { + const metrics = await f.b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize; + const { data } = await f.b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height), scale: 1 } }); + await writeFile(join(dir, shot), Buffer.from(data, 'base64')); + } + report.push({ page: page.name, width, scheme, shot, ...fit }); + } + await f.b.close(); + } + await writeFile(join(dir, 'measure.json'), JSON.stringify(report, null, 1)); + // Only the measurement is reported for the base tree; this tree must pass it. + if (!process.env.MOSAIC_UX_SHOTS_BASE) for (const r of report) { + assert.equal(r.sideways, false, `${r.shot} scrolls sideways`); + if (r.width === 390) for (const s of r.selects) { assert.ok(s.inside, `${r.shot}: ${s.label} runs off screen`); assert.ok(s.need <= s.room, `${r.shot}: ${s.label} cuts "${s.text}" (${s.need} > ${s.room})`); } + } +}); diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs index a6b8a25d3..658aeb219 100644 --- a/packages/webui/tests/triage-drawer-browser.test.mjs +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -9,7 +9,6 @@ import { fileURLToPath } from 'node:url'; import { startServer } from '../src/serve.mjs'; import { createDevOwner } from '../src/dev-owner.mjs'; import { TriageError, NOT_STARTED } from '../src/triage-host.mjs'; -import { capMessage, NO_ROUTE_MESSAGE } from '../src/triage-http.mjs'; import { browser } from './browser.mjs'; import { close } from './fixture.mjs'; @@ -77,9 +76,10 @@ function fakeHost(over = {}) { return { h, triage }; } -async function setup(t, { host = fakeHost(), triage = host.triage, send = true, sso = createDevOwner(), viewport = [1440, 900], path = '/#/dashboard', init = null } = {}) { +// proxyAdmin: a stand-in model service admin, so /api/config says proxyAdmin and Settings > Triage exists. +async function setup(t, { host = fakeHost(), triage = host.triage, send = true, sso = createDevOwner(), viewport = [1440, 900], path = '/#/dashboard', init = null, proxyAdmin = null } = {}) { const { organizations, agentLevels } = await orgFixture(); - const server = await startServer({ port: 0, sso, organizations, agentLevels, triage, send: send ? async () => ({}) : null, log: () => {} }); + const server = await startServer({ port: 0, sso, organizations, agentLevels, triage, proxyAdmin, send: send ? async () => ({}) : null, log: () => {} }); t.after(() => close(server)); const b = await browser({ machine: false }); t.after(() => b.close()); await b.viewport(...viewport); @@ -157,12 +157,13 @@ test('item 1: at 390 wide the entry stays visible and one click opens the drawer }); test('item 2 and 3: route not set says so, and the message box is off with the reason', async t => { - const f = await setup(t, { host: fakeHost({ route: 'not set' }) }); + const f = await setup(t, { host: fakeHost({ route: 'not set' }), proxyAdmin: {} }); await open(f); - assert.match(await f.text('#triage-state'), new RegExp(NO_ROUTE_MESSAGE.slice(0, 40))); + assert.equal(await f.text('#triage-state'), 'Triage has no model chosen yet, so it will not start.'); + assert.equal(await f.b.evaluate('document.querySelector("#triage-state-fix a")?.getAttribute("href")'), '#/settings/triage'); assert.equal(await f.b.evaluate('document.querySelector("#triage-text")?.disabled'), true); assert.equal(await f.b.evaluate('document.querySelector("#triage-send")?.disabled'), true); - assert.match(await f.text('#triage-send-off'), /no model route is set/i); + assert.match(await f.text('#triage-send-off'), /no model chosen yet/i); }); test('item 2: over cap shows the cap message and the time it takes messages again', async t => { @@ -170,10 +171,10 @@ test('item 2: over cap shows the cap message and the time it takes messages agai const f = await setup(t, { host: fakeHost({ overCapUntil: until }) }); await open(f); const state = await f.text('#triage-state'); - assert.ok(state.includes(capMessage(until)), state); const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(until)})`); - assert.ok(state.includes(`Local time: ${local}.`), state); - assert.match(await f.text('#triage-send-off'), /daily token cap/i); + assert.equal(state, `Triage used its daily token limit. It takes messages again at ${local}.`); + assert.equal(await f.b.evaluate('document.querySelector("#triage-state-fix").hidden'), true, 'a set route shows no fix link'); + assert.match(await f.text('#triage-send-off'), /daily token limit/i); }); test('item 2: running, last exit, and the health snapshot with "not read" shown as that', async t => { @@ -183,9 +184,9 @@ test('item 2: running, last exit, and the health snapshot with "not read" shown assert.match(await f.text('#triage-state'), /^Running/); const health = await f.text('#triage-health'); assert.match(health, /Console: answering/); - assert.match(health, /Proxy: not read/); + assert.match(health, /Model service: not read/); assert.match(health, /System config: valid/); - assert.match(health, /acme: bus running, processing on, config valid/); + assert.match(health, /Acme Studio: bus running, processing on, config valid/); assert.match(health, /gamma: bus not read, processing not read, config not valid \(org-config-invalid\)/); assert.doesNotMatch(health.split('\n').find(l => l.startsWith('gamma')), /healthy|running/); // The next poll picks up a stopped session and its last exit, and a snapshot that read nothing. @@ -194,7 +195,7 @@ test('item 2: running, last exit, and the health snapshot with "not read" shown await f.wait('/Last exit/.test(document.querySelector("#triage-state").textContent)', 300); assert.match(await f.text('#triage-state'), /Not running\. Last exit: code 1/); const after = await f.text('#triage-health'); - assert.match(after, /Proxy: healthy/); + assert.match(after, /Model service: healthy/); assert.match(after, /System config: not read/); assert.match(after, /Organizations: not read/); // No snapshot at all. @@ -240,8 +241,8 @@ test('item 3: each send answer has plain words, a refused send keeps the draft, assert.equal(await draft(), 'is acme healthy?', `${label}: the draft stays`); }; await type(f, 'is acme healthy?'); - await refused(() => { host.h.next = new TriageError('triage-no-route', 'x'); }, /Not sent.*no model route is set/i, '409'); - await refused(() => { const e = new TriageError('triage-over-cap', 'x'); e.until = until; host.h.next = e; }, new RegExp(`Not sent.*daily token cap.*${until.slice(0, 16)}`), '429'); + await refused(() => { host.h.next = new TriageError('triage-no-route', 'x'); }, /Not sent.*no model chosen yet/i, '409'); + await refused(() => { const e = new TriageError('triage-over-cap', 'x'); e.until = until; host.h.next = e; }, new RegExp(`Not sent.*daily token limit.*${until.slice(0, 16)}`), '429'); await refused(() => { host.h.next = new TriageError('triage-message-too-long', 'x'); }, /Not sent.*too long/i, '400'); await refused(() => f.b.evaluate('window.__force403 = true'), /Not sent.*read-only/i, '403'); await f.b.evaluate('window.__force403 = false'); @@ -444,7 +445,7 @@ test('triage-followups: with no drawer open the first render still focuses the h test('triage-cap: one usage line from the read: not set, the count against the cap with the reset, not read, and markup as text', async t => { const f = await setup(t, { host: fakeHost({ usageToday: 'not set', cap: 'not set', resetsAt: 'not set' }) }); await open(f); - assert.equal(await f.text('#triage-usage'), 'Daily token cap: not set.'); + assert.equal(await f.text('#triage-usage'), 'Daily token limit: not set.'); assert.equal(await f.b.evaluate('document.querySelector("#triage-usage").hidden'), false); const resetsAt = new Date(Date.now() + 5 * 3600000).toISOString(); const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(resetsAt)})`); @@ -470,3 +471,63 @@ test('triage-cap: a read without the usage fields shows no usage line', async t await open(f); assert.equal(await f.b.evaluate('document.querySelector("#triage-usage").hidden'), true); }); + +// #1873 settings slice 1, bullet 5 (DESIGN.md section 5): a route refusal is a plain line that says what is +// missing, with a link to the Settings page that fixes it. The harness refusal names Claude Code. The key +// refusal has no fix page in slice 1, so it ends at what is missing and offers no link. +test('settings-s1 B5: route refusals read as plain lines with the fix link; the harness line names Claude Code', async t => { + const host = fakeHost({ running: false }); + const f = await setup(t, { host, proxyAdmin: {} }); + await open(f); + await type(f, 'is acme healthy?'); + const { ROUTE_REFUSALS } = await import('../src/triage-host.mjs'); + const cases = [ + ['triage-harness-incompatible', /^Not sent\. Triage runs only with Claude Code\. Choose Claude Code under "Runs with" in Triage settings\. Open Triage settings$/, '#/settings/triage'], + ['triage-proxy-down', /^Not sent\. The model service isn't running, so Triage can't start\. Open model service settings$/, '#/settings/model-proxy'], + ['triage-model-not-offered', /^Not sent\. The model Triage uses is no longer offered\./, '#/settings/triage'], + ['triage-key-missing', /^Not sent\. Triage isn't turned on yet: it needs a Triage key, and none is issued on this instance\.$/, null], + ]; + let status = ''; + for (const [code, pattern, href] of cases) { + host.h.next = new TriageError(code, ROUTE_REFUSALS[code]); + status = await sendAndWait(f, status); + assert.match(status, pattern, code); + assert.doesNotMatch(status, /harness|proxy/i, `${code}: no internal word`); + assert.equal(await f.b.evaluate('document.querySelector("#triage-send-status a")?.getAttribute("href") ?? null'), href, `${code}: fix link`); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'is acme healthy?', `${code}: the draft stays`); + } + // The fix link is reachable by keyboard and goes to its page, closing the drawer. + host.h.next = new TriageError('triage-harness-incompatible', ROUTE_REFUSALS['triage-harness-incompatible']); + status = await sendAndWait(f, status); + await f.b.evaluate('document.querySelector("#triage-send-status a").focus()'); + assert.equal(await f.b.evaluate('document.activeElement?.textContent'), 'Open Triage settings'); + assert.notEqual(await f.b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none', 'the focused link shows a focus ring'); + await f.b.key('Enter', 'Enter'); + // The Settings pages live inside the open organization, so the shell scopes the address to it. + await f.wait('/^#(\\/orgs\\/acme)?\\/settings\\/triage$/.test(location.hash) && document.querySelector("#triage-drawer").hidden && document.querySelector("#triage-route")'); + assert.notEqual(await f.text('h1'), 'Not found'); +}); + +// Settings > Triage exists only where /api/config says proxyAdmin, so without it no line links there. +test('settings-s1 B5: without the Triage settings page the refusal keeps its line and offers no link to it', async t => { + const host = fakeHost({ route: 'not set' }); + const f = await setup(t, { host }); + await open(f); + assert.equal(await f.text('#triage-state'), 'Triage has no model chosen yet, so it will not start.'); + assert.equal(await f.b.evaluate('document.querySelector("#triage-state-fix").hidden && !document.querySelector("#triage-state-fix a")'), true); + assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer a[href=\'#/settings/triage\']")'), null); +}); + +// #1873 settings slice 1, bullet 6 (D7): an organization whose last start was refused reads as not +// running in the Health list, never as running. The snapshot carries the time of the refused start but +// not its reason (triage-snapshot.mjs keeps lastStart {ok, at} only), so the line says where to see why. +test('settings-s1 B6: a refused last start reads as not running in Health, with the time and where to see why', async t => { + const snapshot = SNAPSHOT(); + const failedAt = at(30); + snapshot.organizations.list[0] = { id: 'acme', bus: { state: 'stopped', lastStart: { ok: false, at: failedAt } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } }; + const f = await setup(t, { host: fakeHost({ running: true, snapshot }) }); + await open(f); + const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(failedAt)})`); + const line = (await f.text('#triage-health')).split('\n').find(l => l.startsWith('Acme Studio')); + assert.equal(line, `Acme Studio: not running: its last start failed at ${local} (bus stopped). Restart it on the dashboard to see why, processing on, config valid`); +}); diff --git a/packages/webui/tests/triage-settings-browser.test.mjs b/packages/webui/tests/triage-settings-browser.test.mjs index f971da001..08a5873a5 100644 --- a/packages/webui/tests/triage-settings-browser.test.mjs +++ b/packages/webui/tests/triage-settings-browser.test.mjs @@ -40,7 +40,7 @@ test('the owner sees Triage in Settings, "not set" before a first save, the cata 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.match(await text(b, 'triage-route-stored'), /^Not set\. Triage has no model chosen yet, so it will not start\.$/); 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'); @@ -54,7 +54,7 @@ test('the owner sees Triage in Settings, "not set" before a first save, the cata 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.deepEqual(await options(b, 'triage-route-harness'), [['', 'Choose what runs it', 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']); @@ -73,10 +73,10 @@ test('Save posts the fields and the read revision once, then shows the stored ro 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."'); + await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.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.match(await text(b, 'triage-route-stored'), /^Saved route: sonnet, runs with Claude Code\. Daily token limit 150,000, resets at 00:00 America\/Chicago\. Saved .+\.$/); assert.equal(await value(b, 'triage-route-cap'), '150000'); // The next save carries the new revision. await type(b, 'triage-route-cap', '9000'); @@ -93,7 +93,8 @@ test('a stored route fills the fields; each refusal is one plain line and keeps 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\.$/); + assert.equal(await text(b, 'triage-route-stored'), `Saved route: sonnet, runs with pi. Daily token limit 200,000, resets at 00:00 Europe/Berlin. Saved ${await b.evaluate('window.MosaicLocalTime("2026-11-18T12:00:00.000Z")')}.`); + assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '1'); 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' }); @@ -106,7 +107,7 @@ test('a stored route fills the fields; each refusal is one plain line and keeps 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'); + assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.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()'); @@ -119,7 +120,7 @@ test('a stored route fills the fields; each refusal is one plain line and keeps 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/); + assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '1'); }); test('a stale revision says so, keeps the fields, and Reload route reads the stored route again', { timeout: 90000 }, async t => { @@ -136,11 +137,11 @@ test('a stale revision says so, keeps the fields, and Reload route reads the sto 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-stored").dataset.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."'); + await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="3"'); assert.equal((await writes(b)).at(-1).body.revision, 2, 'the save after a re-read carries the stored revision'); }); @@ -162,7 +163,7 @@ test('an untouched page follows the store; typed fields keep the revision they w 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('document.getElementById("triage-route-stored").dataset.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'); @@ -170,7 +171,7 @@ test('an untouched page follows the store; typed fields keep the revision they w 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('document.getElementById("triage-route-stored").dataset.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)}`); @@ -198,7 +199,7 @@ test('a second Save while one runs does nothing', { timeout: 90000 }, async t => 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."'); + await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="1"'); assert.equal((await writes(b)).length, 1); }); @@ -217,7 +218,9 @@ test('a catalogue that is not ready says so and offers no model', { timeout: 900 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.match(await text(b, 'triage-route-catalogue'), /No organization can show your models right now, so no route can be saved\. Open model service settings/); + assert.equal(await b.evaluate('document.getElementById("triage-route-catalogue").dataset.status'), 'bus-unavailable'); + assert.equal(await b.evaluate('document.querySelector("#triage-route-catalogue a").getAttribute("href")'), '#/settings/model-proxy'); assert.deepEqual(await options(b, 'triage-route-model'), [['', 'Choose a model', false]]); }); -- 2.54.0 From 48a2ed675c68f4f050831051f89ef7477bd6b709 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 11:41:32 -0600 Subject: [PATCH 2/5] fix(webui): settings slice 1 review round: Model setup reads each organization's own routes and offers Restart only where the bus names no cause or one a restart clears, so the dev fixture gets its plain line and a Routing link and only a restartable organization holds the next step; the bus's cause codes read as plain lines with its words under Technical details, and the lock cause gets a primary Restart; a set fence reads as a restart to finish; a failed status read offers Check again; Save routes steps back while Restart is the primary; the page is named Model setup and owner text says model service; Routing explains harness and preflight; the drawer's harness refusal asks for a model that runs with Claude Code; the Triage page says daily token limit and that Triage also needs its key (#1873, lane settings-s1) --- packages/model-proxy/README.md | 2 +- packages/webui/README.md | 11 ++- packages/webui/src/decision-http.mjs | 8 +- packages/webui/src/public/bus.js | 60 ++++++++------- packages/webui/src/public/console-restart.js | 24 +++++- packages/webui/src/public/display.js | 76 ++++++++++++++----- packages/webui/src/public/proxy.js | 2 +- packages/webui/src/public/shell.css | 4 + packages/webui/src/public/triage-settings.js | 6 +- packages/webui/src/public/workspace.js | 2 +- packages/webui/src/triage-route-http.mjs | 2 +- packages/webui/tests/decision-http.test.mjs | 6 +- .../webui/tests/hire-inbox-browser.test.mjs | 4 +- packages/webui/tests/proxy-browser.test.mjs | 4 +- .../webui/tests/proxy-setup-browser.test.mjs | 38 +++++++++- packages/webui/tests/routes-browser.test.mjs | 7 +- .../tests/settings-redesign-browser.test.mjs | 10 +-- .../tests/settings-review-browser.test.mjs | 2 +- .../webui/tests/settings-s1-browser.test.mjs | 46 ++++++++--- .../tests/triage-drawer-browser.test.mjs | 4 +- .../tests/triage-settings-browser.test.mjs | 4 +- .../tests/unified-workspace-browser.test.mjs | 2 +- 22 files changed, 231 insertions(+), 93 deletions(-) diff --git a/packages/model-proxy/README.md b/packages/model-proxy/README.md index b712113c7..7bb75fb5c 100644 --- a/packages/model-proxy/README.md +++ b/packages/model-proxy/README.md @@ -148,7 +148,7 @@ follow-up; do not run those writers concurrently with organization buses. ### Setup from the Console (#1873) -Settings > Model proxy has a Proxy setup panel for the instance owner: the +Settings > Model setup (route `#/settings/model-proxy`) has a Proxy setup panel for the instance owner: the `--dev-local-owner` owner on a dev Console, or the root owner under `--sso`. Agents, testers and grant holders get `human-required` on every setup route, read or write. The panel shows the release (pinned version, hashes verified), diff --git a/packages/webui/README.md b/packages/webui/README.md index b7341ec5c..251773213 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -1376,7 +1376,7 @@ The existing user notice names the governance records visible to the owner. ## Model proxy page (P4, #1828) -The owner's Settings → Model proxy page (`/settings/model-proxy`) signs in Claude/Codex accounts, accepts write-only +The owner's Settings → Model setup page (named Model proxy before #1873) (`/settings/model-proxy`) signs in Claude/Codex accounts, accepts write-only z.ai API keys, sets account priority, and lists client-key IDs. It uses only `/api/proxy/` routes over the owner's human bus transport. The old `/proxy` bookmark redirects to this page after the same access checks. A missing instance proxy refuses `not-configured`; it does not ask for a management key. That key @@ -1394,6 +1394,15 @@ retires the state. Refreshing the page does not restore a pending login. Usage is reserved on this page for P5; P4 adds no usage source. PIN changes require the offline upgrade acceptance documented in packages/model-proxy. +Settings slice 1 (#1873). Once the service runs, the page lists each organization that can't see +the models, or is not running. For each one that can't see them it reads that organization's own +routes (`GET /api/orgs//bus/routes`, the read Routing uses) and shows the bus's cause as a +plain line, with the bus's words under Technical details. A Restart shows only when the bus names +no cause or a cause a fresh start clears; with the dev fixture a restart is refused and stops the +organization, so that row links to its Routing instead. Only an organization a restart can help +holds the next step. A refused restart keeps its reason on its row. Only the next step has a +button; done steps, Fence, Init lock and the service controls sit under Technical details. + Archived project routes use the inclusive project read for the name, saved threads and room history. They offer Unarchive in send mode; thread creation, resume, sending and clear controls are unavailable while archived. Archive styling uses only `.project-archive-control` and `.project-archived-filter`. ### Recovering local process state diff --git a/packages/webui/src/decision-http.mjs b/packages/webui/src/decision-http.mjs index d0ac4078c..a48ecb053 100644 --- a/packages/webui/src/decision-http.mjs +++ b/packages/webui/src/decision-http.mjs @@ -60,11 +60,11 @@ const NONE = ' Nothing was applied.'; const EITHER = ' Part of it may already be applied: check the Agents page before trying again.'; const CHECK = ' Check the Agents page and the inbox before trying again.'; const HIRE_START_REFUSALS = { - 'model-provider-unavailable': [409, 'The model proxy does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model proxy.' + NONE], - 'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model proxy, then try again.' + NONE], + 'model-provider-unavailable': [409, 'The model service does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model setup.' + NONE], + 'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model setup, then try again.' + NONE], 'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness.' + NONE], 'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies.' + NONE], - 'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Model proxy.' + NONE], + 'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Model setup.' + NONE], 'harness-off': [409, 'This harness is not switched on for the organization. Pick a harness listed under Settings > Routing, or ask the owner to switch it on.' + NONE], 'harness-refused': [409, 'The harness refused this route. Clear Thinking, or pick another model or harness under Settings > Routing.' + NONE], 'template-system-only': [409, 'This role template is for the system, not for an organization. Pick another template.' + NONE], @@ -100,7 +100,7 @@ const HIRE_START_REFUSALS = { 'credential-scope-exceeded': [409, 'The requested credential scope is wider than the role allows.' + CHECK], // The fields passed the shape check below, so a malformed answer here is a value the organization // checks refused: most often a model that is not a launch.models key. - 'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Model proxy and a role the organization checks accept.' + EITHER], + 'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Model setup and a role the organization checks accept.' + EITHER], }; // A reply the endpoint cannot read as a definite answer: no answer, or the bus server's request // codes. Anything else that reads as a code is a definite refusal. diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 2d40fe5b1..afc14cbcd 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1308,36 +1308,44 @@ const sameCells=(a,b)=>ROUTE_CELLS.every(([k])=>a[k]===b[k]); // #1873 settings slice 1 (D2): an organization that lists the model service but cannot see its // models. For the instance owner the page reads the model service's state once per visit, so the - // line says which is true: the service is not set up or not running (a link to its page), or it - // runs and this organization still cannot read it. A running bus picks the service up at its next - // catalogue read (proxy-pickup), so when the bus names a cause the line shows that cause and a - // Check again that rereads; a Restart would not help there, and with the dev fixture it would stop - // the organization. Only a running service with no cause from the bus offers Restart. The Restart - // follows that state; it is never offered on a guess. + // line says which is true: the service is not set up, not running or waiting on a restart after + // a key write (a link to its page), or it runs and this organization still cannot read it. A + // running bus picks the service up at its next catalogue read (proxy-pickup), so a Restart is + // offered only when the state says it helps: the bus names no cause, or names one a fresh start + // clears (MosaicConsole.catalogueCause). With the dev fixture a restart is refused and stops the + // organization, so that cause gets its plain line and Check again. The Restart is never a guess. let serviceState=null, serviceLoading=false; function readService(){ if(serviceLoading||serviceState!==null||isTester||!triageOwner||!window.MosaicOrg)return; serviceLoading=true;const epoch=orgEpoch; fetch('/api/proxy/admin/status',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok||!v||typeof v!=='object')throw Error(); - serviceState=v.init?.initialized!==true?'not-set-up':v.unit?.active==='active'&&v.unit?.healthy===true&&v.fence?.set!==true?'running':'not-running';}) + serviceState=v.init?.initialized!==true?'not-set-up':v.fence?.set===true?'fenced':v.unit?.active==='active'&&v.unit?.healthy===true?'running':'not-running';}) .catch(()=>{if(epoch!==orgEpoch)return;serviceState=false;}).finally(()=>{if(epoch!==orgEpoch)return;serviceLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);}); } function catalogueLine(proxyOn,catalogue){ - const org=txt(window.MosaicOrg?.label||'This organization'), id=window.MosaicOrg?.id, owner=canSend&&!isTester; + const label=window.MosaicOrg?.label||'This organization', org=txt(label), id=window.MosaicOrg?.id, owner=canSend&&!isTester; const lead=`${org} can't see your models yet.`, thinking='A change to thinking alone still saves.'; - // The bus's own cause lines (proxy-pickup), shown as it wrote them. - const causes=(Array.isArray(catalogue?.notices)?catalogue.notices:[]).filter(n=>typeof n==='string'&&n).map(n=>`

    ${txt(n)}

    `).join(''); - if(!proxyOn)return `

    ${lead} ${thinking}

    ${causes}`; + // The bus's cause (proxy-pickup). A known cause reads as one plain line with the bus's words + // under Technical details; an unknown one shows the bus's words as they are. + const cause=window.MosaicConsole?.catalogueCause?.(label,catalogue?.notices)??null; + const words=!cause?'':cause.plain?`
    Technical details

    ${txt(cause.detail)}

    `:`

    ${txt(cause.detail)}

    `; + const plain=cause?.plain?` ${txt(cause.plain)}`:''; + const setupLink=text=>`${text}`; + if(!proxyOn)return `

    ${lead}${plain} ${thinking}

    ${words}`; if(owner)readService(); const recheck=''; - // Only the lock cause asks for a restart; with the dev fixture or a key that does not load the - // start is refused too, and a restart would stop the organization. - const lockCause=(catalogue?.notices??[]).some(n=>typeof n==='string'&&n.includes('(proxy-lock-invalid)')); - if(owner&&serviceState==='running'&&causes)return ``; - if(owner&&serviceState==='running')return ``; - if(owner&&serviceState==='not-set-up')return `

    ${lead} Your model service isn't set up yet. Set up the model service. ${thinking}

    `; - if(owner&&serviceState==='not-running')return `

    ${lead} The model service is not running. Open the model service settings. ${thinking}

    ${causes}`; + const restart=primary=>window.MosaicConsole?.orgRestartButton?.(id,{name:label,primary})??''; + if(owner&&serviceState==='running'&&cause){ + const fix=cause.fix==='service'?` ${setupLink('Open Model setup')}.`:''; + const next=cause.restart?`Restart ${org} to try again. It stops for a moment and starts again.`:cause.fix==='routing'?'Choose another model below for each agent that uses a test model, save, then check again.':'Check again once that is fixed.'; + return ``; + } + if(owner&&serviceState==='running')return ``; + if(owner&&serviceState==='not-set-up')return `

    ${lead} Your model service isn't set up yet. ${setupLink('Set up the model service')}. ${thinking}

    `; + if(owner&&serviceState==='fenced')return `

    ${lead} Your model service is waiting for a restart to finish. ${setupLink('Open Model setup to finish it')}. ${thinking}

    `; + if(owner&&serviceState==='not-running')return `

    ${lead} The model service is not running. ${setupLink('Open Model setup')}. ${thinking}

    ${words}`; if(owner&&(serviceLoading||(serviceState===null&&triageOwner)))return `

    ${lead} Checking the model service. ${thinking}

    `; - return `

    ${lead} ${thinking}${owner?' A new model needs the model service: ask the instance owner to set it up, or press Stop using the model service when this organization does not need it.':''}

    ${causes}`; + if(owner&&serviceState===false)return ``; + return `

    ${lead}${plain} ${thinking}${owner?' A new model needs the model service: ask the instance owner to set it up, or press Stop using the model service when this organization does not need it.':''}

    ${words}`; } // Check again rereads Routing; the bus looks for the model service at that read. A draft is kept. document.addEventListener('click',e=>{if(e.target.id!=='routes-recheck')return;e.target.disabled=true;serviceState=null;routesView=null;last.delete('routes');render(true);}); @@ -1373,8 +1381,8 @@ const catalogueInfo=v.catalogue?.status==='ready'?`

    Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.

    ${(v.catalogue.notices??[]).map(n=>`

    ${txt(n)}

    `).join('')}`:v.catalogue?.status==='unavailable'?catalogueLine(proxyOn,v.catalogue):'

    Model catalogue not enabled.

    '; const providerControl=canSend&&!isTester?`

    `:''; const harnessControl=canSend&&!isTester?`
    Harnesses${harnessSettings ? [...new Set([...harnessSettings.available.harness,...(harnessSettings.plugins.harness??[])])].map(name=>``).join('')+` ` : '

    Harnesses unavailable.

    '}

    ${txt(harnessReceipt)}

    `:''; - const off=v.harnesses.length?'':'

    No harness is switched on in the business file\'s plugins.harness, so every launch refuses harness-off and a save that changes a harness refuses too. Switch one on under Harnesses.

    '; - return `
    ${title}${catalogueInfo}${providerControl}${harnessControl}${off}
    ${ROUTE_CELLS.map(([,l])=>``).join('')}${rows}
    AgentPrimaryFallback
    ${l.replace('Fallback ','')}

    ${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

    ${txt(routesReceipt)}

    ${routesApplyMarkup()}
    `; + const off=v.harnesses.length?'':'

    No harness is switched on for this organization, so every launch is refused, and so is a save that changes a harness. Switch one on under Harnesses.

    '; + return `
    ${title}${catalogueInfo}${providerControl}${harnessControl}${off}
    ${ROUTE_CELLS.map(([,l])=>``).join('')}${rows}
    AgentPrimaryFallback
    ${l.replace('Fallback ','')}

    ${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

    ${txt(routesReceipt)}

    ${routesApplyMarkup()}
    `; } function routesFields(form){const draft=Object.fromEntries(Object.keys(routesView.instances).map(name=>[name,routeCells(routesView.instances[name])]));for(const el of form.querySelectorAll('[data-route]')){const [name,key]=JSON.parse(el.dataset.route);if(draft[name])draft[name][key]=el.value;}return draft;} // The changed rows only. A fallback with all three cells empty is cleared; one with some set goes @@ -1468,7 +1476,7 @@ }); // 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','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']]; + 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 setup'],['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.filter(([id])=>id!=='triage'||triageOwner); @@ -1482,9 +1490,9 @@ if (page==='business') return businessView(get); 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.'); } + if (page==='model-proxy') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Your model service, the accounts it uses and their priority, and the keys agents use to reach it.'); } // #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.'); } + if (page==='triage') { await configRead; if (!triageOwner || !window.MosaicTriageRoute) return notFound(); return settingsShell(page,await window.MosaicTriageRoute.section(),'The model Triage uses, what runs it, and its daily token limit. 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 || {}; @@ -1498,8 +1506,8 @@ if (page==='routing') { await window.MosaicConsole?.ready; try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch); const notify = typeof n.binding==='string' ? `${txt(n.binding)}` : n.refused ? `Could not be read: ${txt(n.refused)}` : 'None set'; - const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
    Address
    ${txt(s.address)||'unknown'}
    Release
    ${txt(s.release)||'unknown'}
    Business
    ${txt(s.business)||none}
    Board
    ${txt(s.board)||'unknown'}
    Notifier binding
    ${notify}
    `, 'model-proxy':()=>'
    Open model service settings
    '}; - const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'}; + const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
    Address
    ${txt(s.address)||'unknown'}
    Release
    ${txt(s.release)||'unknown'}
    Business
    ${txt(s.business)||none}
    Board
    ${txt(s.board)||'unknown'}
    Notifier binding
    ${notify}
    `, 'model-proxy':()=>'
    Open Model setup
    '}; + const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change. A harness is the program that runs the model, such as Claude Code. Preflight is the check a launch makes before it starts.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'}; return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`); } let settingsFocusDisclosure=false; diff --git a/packages/webui/src/public/console-restart.js b/packages/webui/src/public/console-restart.js index 895d52e71..9a250aba4 100644 --- a/packages/webui/src/public/console-restart.js +++ b/packages/webui/src/public/console-restart.js @@ -199,7 +199,7 @@ } // #1873 settings slice 1 (D2, D3, D7): a Restart button for one named organization, for pages that - // list organizations by id (Routing, Model proxy, a stopped organization's Settings). Each + // list organizations by id (Routing, Model setup, a stopped organization's Settings). Each // organization keeps its own receipt, so a refusal stays on screen across repaints until the next // press. It calls the same POST /api/orgs//restart/bus as the header's Restart bus. const orgReceipts = new Map(), orgBusy = new Set(); @@ -210,6 +210,26 @@ if (/\bfixture-proxy-configured\b/.test(text)) return { plain: `${name} runs on test models, which can't share this machine with your model service. It did not start.`, detail: text }; return { plain: `${name} did not start.`, detail: text }; } + // #1873 review P1-1, P2-2: the cause a running bus gives for a catalogue it cannot read + // (runtime.mjs pickProxy), as one plain line. `restart` says whether a restart can fix it: the + // lock and the organization binding load again at a fresh start; with the dev fixture or a key + // or settings file that does not load, the start is refused too or reads the same file. `fix` + // names the page that fixes it. The bus's own words stay in `detail`; an unknown cause has no + // plain line, so the page shows the bus's words. + function catalogueCause(name, notices) { + const list = (Array.isArray(notices) ? notices : []).filter(n => typeof n === 'string' && n); + if (!list.length) return null; + const detail = list.join(' '), code = /\(([a-z][a-z-]*)\)/.exec(detail)?.[1] ?? (/has not been set up/.test(detail) ? 'proxy-not-set-up' : null); + const known = { + 'fixture-proxy-configured': [`${name} runs on test models, which can't share this machine with your model service.`, false, 'routing'], + 'proxy-lock-invalid': [`${name} can't open the model service's shared lock. A restart opens it again.`, true, null], + 'invalid-host-request': [`${name} isn't linked to this instance's model service. A restart links it again.`, true, null], + 'proxy-management-key-invalid': [`${name} can't load the model service's key, so it can't reach the model service.`, false, 'service'], + 'proxy-down': [`${name} couldn't check the model service just now. Check again in a moment.`, false, null], + 'proxy-not-set-up': ['Your model service isn\'t set up yet.', false, 'service'], + }[code] ?? (/^proxy-/.test(code ?? '') ? [`${name} can't load the model service's settings.`, false, 'service'] : null); + return known ? { code, plain: known[0], restart: known[1], fix: known[2], detail } : { code, plain: null, restart: false, fix: null, detail }; + } function orgRestartButton(id, { name = id, label = `Restart ${name}`, primary = false } = {}) { if (!orgAllowed() || typeof id !== 'string' || !id) return ''; const busy = orgBusy.has(id), r = orgReceipts.get(id); @@ -247,5 +267,5 @@ restartOrg(button.dataset.orgRestart, button.dataset.orgName || button.dataset.orgRestart); }); - window.MosaicConsole = Object.freeze({ ready, settingsMarkup, busButton, attachBus, orgRestartButton, restartOrg, orgRefusal: id => orgReceipts.get(id) ?? null, get busRestart() { return busAllowed(); }, get config() { return config; } }); + window.MosaicConsole = Object.freeze({ ready, settingsMarkup, busButton, attachBus, orgRestartButton, restartOrg, catalogueCause, orgRefusal: id => orgReceipts.get(id) ?? null, get busRestart() { return busAllowed(); }, get config() { return config; } }); })(); diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 96a5efeb8..d44c2850c 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -15,9 +15,9 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; }; const NO_ROUTE = 'Triage has no model chosen yet, so it will not start.'; // #1873 settings slice 1 (section 5): a fix link goes only to a Settings page that exists for this viewer. - // Settings > Triage exists only where /api/config says proxyAdmin (bus.js triageOwner); Model proxy always does. + // Settings > Triage exists only where /api/config says proxyAdmin (bus.js triageOwner); Model setup always does. const TRIAGE_FIX = { href: '#/settings/triage', label: 'Open Triage settings' }; - const SERVICE_FIX = { href: '#/settings/model-proxy', label: 'Open model service settings' }; + const SERVICE_FIX = { href: '#/settings/model-proxy', label: 'Open Model setup' }; const pageExists = fix => fix !== TRIAGE_FIX || config?.proxyAdmin === true; const fixLink = fix => { const a = el('a', 'triage-fix', fix.label); a.href = fix.href; a.addEventListener('click', () => close()); return a; }; // An organization's name from the Console's own list, or its id when the list does not hold it. @@ -290,7 +290,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // Slice 1 has no way to issue a Triage key, so that line ends at what is missing. if (status === 409 && code === 'triage-key-missing') return { text: 'Not sent. Triage isn\'t turned on yet: it needs a Triage key, and none is issued on this instance.' }; if (status === 409 && code === 'triage-proxy-down') return { text: 'Not sent. The model service isn\'t running, so Triage can\'t start.', link: SERVICE_FIX }; - if (status === 409 && code === 'triage-harness-incompatible') return { text: 'Not sent. Triage runs only with Claude Code. Choose Claude Code under "Runs with" in Triage settings.', link: TRIAGE_FIX }; + if (status === 409 && code === 'triage-harness-incompatible') return { text: 'Not sent. Triage runs only with Claude Code, and the chosen model doesn\'t run with it. Choose a model that runs with Claude Code in Triage settings.', link: TRIAGE_FIX }; if (status === 409 && code === 'triage-model-not-offered') return { text: 'Not sent. The model Triage uses is no longer offered. Choose another model in Triage settings.', link: TRIAGE_FIX }; if (status === 409 && code === 'triage-catalogue-unavailable') return { text: 'Not sent. The model service can\'t confirm Triage\'s model right now, so Triage can\'t start.', link: SERVICE_FIX }; // Any other route refusal (an unsafe key file, ...) carries its own plain line. @@ -544,8 +544,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo + '

    The model service lets your organizations use your own model accounts. Each step is checked on this machine. Keys are never shown.

    ' + '
    ' + '

    ' - + '