From 8a6a641b423a259b558e42605e497f7c6e02d201 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 21:08:13 -0600 Subject: [PATCH 1/2] Enable harness selection in routing --- docs/SESSIONS.md | 1 + packages/bus/src/runtime.mjs | 6 ++- packages/bus/tests/plugins-verb.test.mjs | 12 ++++++ packages/webui/src/proxy-http.mjs | 4 +- packages/webui/src/public/app.js | 2 +- packages/webui/src/public/bus.js | 41 +++++++++++++++---- packages/webui/src/public/display.js | 3 +- packages/webui/src/public/shell.css | 7 ++++ packages/webui/tests/dev-local-owner.test.mjs | 4 ++ packages/webui/tests/proxy-browser.test.mjs | 7 +++- packages/webui/tests/proxy-page.test.mjs | 19 +++++++++ packages/webui/tests/routes-browser.test.mjs | 40 ++++++++++++++++++ packages/webui/tests/shell.test.mjs | 4 +- 13 files changed, 132 insertions(+), 18 deletions(-) diff --git a/docs/SESSIONS.md b/docs/SESSIONS.md index 820e3f0af..2ae534ce4 100644 --- a/docs/SESSIONS.md +++ b/docs/SESSIONS.md @@ -2108,3 +2108,4 @@ are never rewritten or removed; corrections are new entries. 2026-11-06 UTC | Codex implementation sub-agent | dev local owner named data-root claim correction on ui-dev | Both entry points use the existing named-instance validator; missing, mismatched and hard-linked claims refuse before startup. Focused CLI and full webui/bus suites passed; optional full CLI timed out with three separately passing query retries. Evidence: /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; local candidate for independent review, no push or deployment. 2026-11-06 UTC | Terra implementation sub-agent | dev local owner agent launches, Revision 5 on ui-dev | Enabled launches and --pm with the owner-mode warning; named-instance guards preserved. Focused tests, Node 24 bus suite and CLI host/launcher tests passed; evidence in /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; local candidate for independent review, no push or deployment. 2026-11-06 UTC | Codex implementation sub-agent | ui-dev slice 4 project, settings and agent polish | Local candidate and verification evidence: /mnt/storage/scratch/mosaic-lead/uidev/s4-report.md. Queue refused linked worktree; no push, merge or deployment. +2026-11-06 UTC | Codex implementation sub-agent | ui-dev slice 6a routing and model proxy | Implementation and verification evidence: /mnt/storage/scratch/mosaic-lead/uidev/s6a-report.md. Queue refused linked worktree; no push, merge or deployment. diff --git a/packages/bus/src/runtime.mjs b/packages/bus/src/runtime.mjs index 613e26005..b7e5e5128 100644 --- a/packages/bus/src/runtime.mjs +++ b/packages/bus/src/runtime.mjs @@ -104,7 +104,9 @@ export async function harnessLevels({ log = (e) => process.stderr.write(`plugins log({ event: 'harness-levels-failed', name, message: e.message }); } } - return (name) => levels.get(name) ?? null; + const lookup = (name) => levels.get(name) ?? null; + lookup.names = [...levels.keys()].sort(); + return lookup; } // Row 224 C2-05b: a host-only adapter. A failed fetch keeps serving immutable old // objects, as C2-03a requires; no caller may select a repo, commit or sync --accept. @@ -735,7 +737,7 @@ export async function startBroker({ return getProjectRemote(writer, id, args.project); } if(verb==='limits')return withTokens(id,settings.read(id)); - if(verb==='plugins')return plugins.read(id); + if(verb==='plugins')return {...plugins.read(id), available:{harness:levels.names ?? []}}; // Row 256 (#1761): the actor is the reader, so endProtected is the delete check for that reader. if(verb==='instances')return instances.read(id,actor); // Row 65 (mos-0840): the Console's routing table. diff --git a/packages/bus/tests/plugins-verb.test.mjs b/packages/bus/tests/plugins-verb.test.mjs index 74f8d0a65..3cb92e08d 100644 --- a/packages/bus/tests/plugins-verb.test.mjs +++ b/packages/bus/tests/plugins-verb.test.mjs @@ -90,3 +90,15 @@ test('vikunja:19/309 through the broker, a patch switches the kinds it names and assert.equal(code({}), 'invalid-plugins'); assert.equal(code({ 'search-source': 'no-such-module' }), 'unknown-plugin'); }); + +test('plugins read advertises loadable harnesses even when switched off', async t => { + const {startBroker}=await import('../src/runtime.mjs'); + const {businessDoc,rolesCopy,systemFor,writeJson}=await import('../../business/tests/helpers.mjs'); + const root=mkdtempSync(join(tmpdir(),'plugins-available-'));t.after(()=>rmSync(root,{recursive:true,force:true})); + const rolesDir=rolesCopy(root);const doc=businessDoc(root,'demo');doc.plugins={harness:['claude-code']}; + writeJson(join(root,'businesses/demo.json'),doc);mkdirSync(join(root,'data'),{mode:0o700}); + const host=await startBroker({dataRoot:join(root,'data'),businesses:{demo:{id:'demo',human:'jason',arbiters:{technical:'coder',delivery:'coder'},roles:{coder:{authority:{withinRole:[],crossRole:[]}}}}},organization:{dir:root,rolesDir,system:systemFor(root)}});t.after(()=>host.close()); + const human=host.broker.bindHuman({business:'demo',human:'jason',via:'cli',outsideAgent:true}); + const view=host.broker.request(human,{verb:'plugins'}); + assert.deepEqual(view.plugins.harness,['claude-code']);assert.ok(view.available.harness.includes('pi'));assert.ok(view.available.harness.includes('claude-code')); +}); diff --git a/packages/webui/src/proxy-http.mjs b/packages/webui/src/proxy-http.mjs index 1ef906e23..eac1929fe 100644 --- a/packages/webui/src/proxy-http.mjs +++ b/packages/webui/src/proxy-http.mjs @@ -47,10 +47,10 @@ export async function proxyHTTP(req, res, { path, call, named, tester, granted, || route[2].some(k => !Object.hasOwn(args, k))) throw Error(); } catch { return done(400, { error: 'invalid-request' }); } } - if (path === '/api/proxy/plugins/set' && (!args.plugins || typeof args.plugins !== 'object' || Array.isArray(args.plugins) || Object.keys(args.plugins).length !== 1 || !Array.isArray(args.plugins['model-provider']))) return done(400, { error: 'invalid-request' }); + if (path === '/api/proxy/plugins/set' && (!args.plugins || typeof args.plugins !== 'object' || Array.isArray(args.plugins) || Object.keys(args.plugins).length !== 1 || !['harness', 'model-provider'].includes(Object.keys(args.plugins)[0]) || !Array.isArray(Object.values(args.plugins)[0]) || !Object.values(args.plugins)[0].every(name => typeof name === 'string'))) return done(400, { error: 'invalid-request' }); try { return done(200, await call(route[1], args)); } catch (error) { - const code = codes.includes(error.code) ? error.code : 'outcome-unknown'; + const code = codes.includes(error.code) || (path === '/api/proxy/plugins/set' && typeof error.code === 'string' && /^[a-z-]{1,64}$/.test(error.code)) ? error.code : 'outcome-unknown'; return done(code === 'human-required' ? 403 : ['not-configured', 'proxy-down', 'outcome-unknown'].includes(code) ? 503 : 400, { error: code }); } } diff --git a/packages/webui/src/public/app.js b/packages/webui/src/public/app.js index 0ba789cf9..452858735 100644 --- a/packages/webui/src/public/app.js +++ b/packages/webui/src/public/app.js @@ -303,7 +303,7 @@ $('session-count').textContent = visible.length === group.length ? String(group.length) : `${visible.length} of ${group.length}`; $('sessions').innerHTML = table(visible); $('footer').textContent = data.sessions.length ? Object.entries(data.counts || {}).map(([s, n]) => `${s} ${n}`).join(' · ') : 'No machine sessions'; - $('status').textContent = `Scanned ${Number.isFinite(Date.parse(data.generatedAt)) ? new Date(data.generatedAt).toLocaleString() : 'unknown'} · ${paused ? 'auto-refresh paused' : 'refresh every 10s'}`; + $('status').textContent = `Scanned ${window.MosaicLocalTime(data.generatedAt)} · ${paused ? 'auto-refresh paused' : 'refresh every 10s'}`; fresh(); inspect(); convForm(); if (conv) convStatus(); restore(focus); } // Freshness line in the command bar: when the board last scanned, and warning words when the last refresh failed. diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index b0cb33a86..ac2acab5d 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -913,12 +913,18 @@ // sends it and the bus says why it refuses. A fallback is set by choosing all three or cleared by // choosing none for all three. Save sends the changed rows through routes.set. Drafts survive // polling and refusals; nothing retries. - let routesView=null, routesDraft=null, routesBusy=false, routesReceipt=''; + let routesView=null, routesDraft=null, routesBusy=false, routesReceipt='', routesEditVersion=0; + let harnessSettings=null, harnessDraft=null, harnessLoading=false, harnessReceipt='', harnessBusy=false; + function readHarnesses(){ + if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true; + fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);}); + } 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]); function routesSection(view,instanceInfo){ const title='

Routing

'; + readHarnesses(); if(!view)return `
${title}

The routes could not be read, so there is nothing to change. Read again to retry; they come from the bus host with your identity.

`; if(!routesDraft)routesView=view; const v=routesView, disabled=!(canSend || isTester)||out()||routesBusy?' disabled':''; @@ -937,10 +943,11 @@ return select(name,key,[...new Set([...legacy,...offered.map(m=>m.key)])],c[key],(v.providerModels?.[c[key]]||enabled&&v.models.includes(c[key]))?'unavailable':'not in the model table',labels);}; const thinking=(key,h)=>select(name,key,levelsOf(c[h]),c[key],c[h]?`not applied by ${c[h]}`:'no harness'); return `${txt(name)}${instanceInfo?.instances?.[name]?.definition?`${txt(instanceInfo.instances[name].definition)}`:''}${harness('harness')}${model('model')}${thinking('thinking','harness')}${harness('fallback.harness')}${model('fallback.model')}${thinking('fallback.thinking','fallback.harness')}`;}).join(''); - const catalogueInfo=v.catalogue?.status==='ready'?`

Model proxy catalogue, observed ${txt(v.catalogue.observedAt??'unknown')}.

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

${txt(n)}

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

Model catalogue unavailable.

':'

Model catalogue not enabled.

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

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

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

${txt(n)}

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

Model catalogue unavailable.

':'

Model catalogue not enabled.

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

`:''; - 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. mosaic plugins set switches one on.

'; - return `
${title}${catalogueInfo}${providerControl}${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)}

`; + 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)}

`; } 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 @@ -955,16 +962,30 @@ } const unknownRoutes='Outcome unknown. Read the routes again before trying. Draft kept.'; 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);markSettingsDraft('routing',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('routes-reload');if(discard)discard.hidden=false; + 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;} // A harness change redraws the row so its thinking cell offers that harness's levels. if(kind==='change'&&/harness"\]$/.test(e.target.dataset?.route??''))render(false);}); + document.addEventListener('click',e=>{if(e.target.id==='harness-read'){harnessSettings=null;harnessReceipt='';render(false);}}); + document.addEventListener('change',e=>{if(e.target.matches?.('[data-harness]'))harnessDraft=[...document.querySelectorAll('[data-harness]:checked')].map(x=>x.dataset.harness);}); + document.addEventListener('click',async e=>{if(e.target.id!=='harness-save'||!canSend||isTester||harnessBusy||!harnessSettings)return; + const selected=[...document.querySelectorAll('[data-harness]:checked')].map(x=>x.dataset.harness); + const old=harnessSettings.plugins.harness??[]; + if(routesDraft){harnessReceipt='Save or discard the route draft first.';render(false);return;} + if(harnessSettings.revision!==routesView?.revision){harnessReceipt='The business changed. Reload this page before saving harnesses.';render(false);return;} + const used=old.filter(n=>!selected.includes(n) && Object.values(routesView.instances).some(r=>r.harness===n || r.fallback?.harness===n)); + if(used.length){harnessReceipt=`A saved route uses ${used.join(', ')}. Change the route before switching it off.`;render(false);return;} + harnessBusy=true;const button=e.target;button.disabled=true;harnessReceipt=''; + try{const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});const result=await response.json();if(!response.ok){harnessReceipt=result.message||result.error||'Harness setting was refused.';return;}harnessSettings={...result,available:harnessSettings.available};harnessDraft=null;harnessReceipt='Harnesses saved. The next launch uses the new settings.';routesView=null;last.delete('routes');} + catch{harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;} + finally{harnessBusy=false;if(!out())render(false);} + }); document.addEventListener('click',async e=>{if(e.target.id!=='provider-switch'||!canSend||isTester)return; - const button=e.target,status=$('provider-switch-status');button.disabled=true; + const button=e.target,status=$('provider-switch-status');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true; try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();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']:[]; const next=button.dataset.enabled==='true'?names.filter(n=>n!=='cliproxy'):[...new Set([...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(!response.ok)throw Error('Provider setting was refused.');routesView=null;last.delete('routes');render(true); + if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true); }catch(error){status.textContent=error.message;button.disabled=false;} }); document.addEventListener('click',e=>{if(e.target.matches?.('.fallback-toggle'))e.target.closest('tr')?.classList.add('fallback-open');}); @@ -974,7 +995,7 @@ routesDraft=routesFields(e.target);let payload;try{payload=routesPayload(routesDraft);}catch(err){routesReceipt=err.message;render(false);return;} routesBusy=true;routesReceipt='';render(false); try{const response=await fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){routesReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json(); - if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;} + if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;harnessSettings=null;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;} else routesReceipt=response.ok||result?.sent==='unknown'?unknownRoutes:`${result?.message||'Refused.'} Draft kept.`;}} catch{routesReceipt=unknownRoutes;}finally{routesBusy=false;if(!out())render(false);} }); @@ -1310,7 +1331,7 @@ if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;} // Leaving a decision discards its confirmation immediately, including a preview in flight. if (answer && (navigated || path !== `/inbox/${answer.id}`)) answer = null; - const g = ++gen; + const g = ++gen, routeVersion = routesEditVersion; const current = () => g === gen && route === routeOf() && !out(); document.body.classList.toggle('on-bus', !board); $('bus-view').hidden = board; @@ -1381,6 +1402,8 @@ } if (!current()) return; freshBus(state, SOURCES[path.split('/')[1]]); + // A route edit after the markup was prepared must win over that pending redraw. + if(path==='/settings/routing' && routeVersion!==routesEditVersion){render(false);return;} const k = !navigated && shown === route ? keep() : null; unmountEditor(); $('bus-view').innerHTML = html; shown = route; diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 41aedea0c..617f9b6b1 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -1,3 +1,4 @@ +window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : 'unknown'; if (document.documentElement.hasAttribute('data-settings-proxy-document') && !location.hash) location.hash = '#/settings/model-proxy'; /* Browser-local sidebar density. No authority or project data is stored here. */ (() => { @@ -95,7 +96,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo $('proxy-accounts').replaceChildren(...rows); if (!rows.length) { const row = document.createElement('tr'); const td = cell('No accounts configured.'); td.colSpan = 5; row.append(td); $('proxy-accounts').append(row); } $('proxy-keys').replaceChildren(...keys.keys.map(key => { - const row = document.createElement('tr'); row.append(cell(key.keyId), cell(key.management), cell(key.agent), cell(key.issuedAt), cell(key.state)); return row; + const row = document.createElement('tr'); row.append(cell(key.keyId), cell(key.management), cell(key.agent), cell(window.MosaicLocalTime(key.issuedAt)), cell(key.state)); return row; })); } $('proxy-refresh').addEventListener('click', () => refresh().then(() => message('Accounts and client keys refreshed.')).catch(e => message(e.message))); diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 65163f2ea..03d7b1aad 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -329,3 +329,10 @@ body:not(:has(.project-chat)) .content { padding-bottom:calc(22px + var(--foot-h section[aria-label="Proxy-reported usage"] .table-wrap { overflow-x:scroll; } section[aria-label="Proxy-reported usage"] table { min-width:650px; } } + +@media(max-width:759px){ + .settings-content .route-actions{position:fixed;z-index:20;bottom:0;left:0;right:0;padding:12px;background:var(--surface);border-top:1px solid var(--line)} + .settings-content .route-actions button{flex:1} + .settings-content:not(.readonly) .route-actions #routes-reload[hidden]{display:block!important} + .settings-content:has(.route-actions){padding-bottom:100px} +} diff --git a/packages/webui/tests/dev-local-owner.test.mjs b/packages/webui/tests/dev-local-owner.test.mjs index 8fe66684f..c9507d9e3 100644 --- a/packages/webui/tests/dev-local-owner.test.mjs +++ b/packages/webui/tests/dev-local-owner.test.mjs @@ -2,11 +2,15 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { request } from 'node:http'; +import { fileURLToPath } from 'node:url'; import { startServer } from '../src/serve.mjs'; import { createDevOwner } from '../src/dev-owner.mjs'; import { DEV_OWNER } from '../../cli/src/dev-local-owner.mjs'; import { close } from './fixture.mjs'; +// CLI paths below are repository-relative, including under npm --prefix packages/webui test. +process.chdir(fileURLToPath(new URL('../../..', import.meta.url))); + const cli = 'packages/webui/src/cli.mjs'; const run = (args, env = {}) => spawnSync(process.execPath, [cli, 'serve', ...args], { encoding: 'utf8', env: { ...process.env, ...env } }); test('dev owner refuses incompatible flags before loading configuration', () => { diff --git a/packages/webui/tests/proxy-browser.test.mjs b/packages/webui/tests/proxy-browser.test.mjs index cbf7db0f6..e80c1032d 100644 --- a/packages/webui/tests/proxy-browser.test.mjs +++ b/packages/webui/tests/proxy-browser.test.mjs @@ -17,7 +17,7 @@ async function setup(t, readonly = false, refusal = null) { const chunks = []; for await (const c of req) chunks.push(c); const args = chunks.length ? JSON.parse(Buffer.concat(chunks)) : {}; if (req.url.endsWith('/accounts')) return send({ accounts: [{ accountId: 'a'.repeat(12), provider: 'claude', displayName: '', status: 'ready', priority: state.priority }, { accountId: 'c'.repeat(12), provider: 'z.ai', displayName: 'Fixture z.ai account', status: 'active', priority: 0, models: state.models }] }); - if (req.url.endsWith('/keys')) return send({ keys: [{ keyId: 'b'.repeat(12), management: 'sentinel', agent: null, issuedAt: null, state: null }] }); + if (req.url.endsWith('/keys')) return send({ keys: [{ keyId: 'b'.repeat(12), management: 'sentinel', agent: null, issuedAt: '2026-11-07T02:24:02.021Z', state: null }] }); if (req.url.endsWith('/apikey/add')) { state.receivedKey = args.key === 'p4-browser-key'; await new Promise(r => { state.release = r; }); return send({ added: true }); @@ -105,3 +105,8 @@ test('proxy browser saves the configured model names for a z.ai group', { timeou assert.deepEqual(state.models, ['fixture-one', 'fixture-two', 'fixture-three']); assert.equal(state.routes.filter(r => r.endsWith('/group/models/set')).length, 1); }); + +test('client key issued time is displayed in local time', { timeout: 60000 }, async t => { + const {b}=await setup(t); + assert.equal(await b.evaluate(`document.querySelector('#proxy-keys tr td:nth-child(4)').textContent`),await b.evaluate(`new Date('2026-11-07T02:24:02.021Z').toLocaleString()`)); +}); diff --git a/packages/webui/tests/proxy-page.test.mjs b/packages/webui/tests/proxy-page.test.mjs index ac4a8948e..8e37bda23 100644 --- a/packages/webui/tests/proxy-page.test.mjs +++ b/packages/webui/tests/proxy-page.test.mjs @@ -185,3 +185,22 @@ test('ambiguous model mappings pass their named refusal to the owner', async t = const response=await call(s,'/api/proxy/group/models/set','POST',{accountId:'a'.repeat(12),models:['fixture']}); assert.equal(response.status,400);assert.deepEqual(JSON.parse(response.text),{error:'models-ambiguous'}); }); + +test('plugin switch accepts only one allowed kind with string names', async t => { + const {s,calls}=await setup(t); + const revision='a'.repeat(64); + for (const plugins of [{harness:['pi','claude-code']},{'model-provider':['cliproxy']}]) { + assert.equal((await call(s,'/api/proxy/plugins/set','POST',{revision,plugins})).status,200); + assert.deepEqual(calls.at(-1),['plugins.set',{revision,plugins}]); + } + const count=calls.length; + for (const plugins of [{harness:[1]},{harness:'pi'},{harness:['pi'], 'model-provider':[]},{channel:[]},{}]) + assert.equal((await call(s,'/api/proxy/plugins/set','POST',{revision,plugins})).status,400); + assert.equal(calls.length,count); +}); + +test('plugin refusal code is returned to the owner', async t => { + const {s}=await setup(t,{proxyCall:async()=>{throw Object.assign(new Error('private'),{code:'revision-conflict'});}}); + const response=await call(s,'/api/proxy/plugins/set','POST',{revision:'a'.repeat(64),plugins:{harness:['pi']}}); + assert.equal(response.status,400);assert.deepEqual(JSON.parse(response.text),{error:'revision-conflict'}); +}); diff --git a/packages/webui/tests/routes-browser.test.mjs b/packages/webui/tests/routes-browser.test.mjs index cc728eab8..9782a306a 100644 --- a/packages/webui/tests/routes-browser.test.mjs +++ b/packages/webui/tests/routes-browser.test.mjs @@ -224,3 +224,43 @@ test('Routing marks a saved legacy selection unavailable and filters incompatibl const options=await b.evaluate(`(async()=>{for(let n=0;n<200;n++){const el=document.querySelector('select[aria-label="coder model"]');if(el)return [...el.options].map(o=>({value:o.value,label:o.textContent}));await new Promise(r=>setTimeout(r,20));}throw Error('routing missing');})()`); assert.deepEqual(options,[{value:'legacy-missing',label:'legacy-missing (unavailable)'}]); }); + +test('enabling a discovered harness refreshes Routing and offers its compatible model', {timeout:60000}, async t => { + const root=tmp(t,'harness-switch-'),f=fixture(root,'acme',doc=>{doc.plugins.harness=['claude-code'];doc.plugins['model-provider']=['cliproxy'];for(const r of Object.values(doc.roles)){r.vars.harness='claude-code';delete r.vars['fallback.harness'];delete r.vars['fallback.model'];delete r.vars['fallback.thinking'];}return doc;}); + const dir=join(root,'config'); + const offered={key:'fixture-pi',module:'cliproxy',upstream:'zai',provider:'zai',model:'fixture-pi',label:'Fixture pi',available:true,reason:null,harnesses:['pi']}; + const modelCatalogue={read:async()=>({status:'ready',observedAt:'2026-11-07T02:24:02.021Z',models:[offered],notices:[]}),invalidate(){}}; + const host=await startBroker({dataRoot:f.dataRoot,businesses:{acme:{id:'acme',human:'jason',arbiters:{technical:'coder',delivery:'coder'},roles:{coder:{authority:{withinRole:[],crossRole:[]}}}}},organization:{dir,rolesDir:f.roles,system:systemFor(root)},modelCatalogue});t.after(()=>host.close()); + const human=host.broker.bindHuman({business:'acme',human:'jason',via:'cli',outsideAgent:true});const call=async(verb,args)=>structuredClone(await host.broker.request(human,{verb,args})); + const web=await startServer({port:0,board:'http://127.0.0.1:9',bus:{messages:async()=>({messages:[],unread:0}),usage:async()=>{throw Error('fixture')},routes:()=>call('routes')},reads:{settings:()=>({business:'acme',release:'fixture',notifier:{}})},log:()=>{}});t.after(()=>close(web)); + const b=await browser();t.after(()=>b.close());const settings=await call('plugins'); + 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: '+${JSON.stringify(expr)});})()`); + await wait('!!document.querySelector("[data-harness=pi]")'); + await b.evaluate('document.querySelector("[data-harness=pi]").click();document.querySelector("#harness-save").click();true');await wait('posts.length===1'); + const payload=await b.evaluate('posts[0]');assert.deepEqual(payload.plugins.harness,['claude-code','pi']);assert.equal(payload.revision,settings.revision); + const result=await call('plugins.set',payload);await b.evaluate(`window.answer(200,${JSON.stringify(result)});true`); + const cell=(name,key)=>`document.querySelector(${JSON.stringify(`[data-route='${JSON.stringify([name,key])}']`)})`; + await wait(`[...${cell('coder','harness')}.options].some(o=>o.value==='pi')`); + await b.evaluate(`${cell('coder','harness')}.value='pi';${cell('coder','harness')}.dispatchEvent(new Event('change',{bubbles:true}));true`); + await wait(`[...${cell('coder','model')}.options].some(o=>o.value==='fixture-pi')`); + assert.match(await b.evaluate('document.querySelector("#harness-status").textContent'),/^Harnesses saved\./); + await b.evaluate('document.querySelector("#routes-reload").click();true');await wait('document.querySelector("#routes-reload")?.hidden'); + await b.evaluate('document.querySelector("[data-harness=claude-code]").click();document.querySelector("#harness-save").click();true'); + await wait('document.querySelector("#harness-status")?.textContent.includes("saved route")'); + assert.equal(await b.evaluate('posts.length'),1,'a harness used by a saved route is not switched off'); +}); + +test('quick fallback edits survive the harness redraw', {timeout:60000}, async t => { + const view={business:'acme',revision:'a'.repeat(64),harnesses:['pi','claude-code'],models:['first','second'],providerModels:{},levels:{pi:['low','high'],'claude-code':['low','high']},instances:{coder:{harness:'pi',model:'first',thinking:'low',fallback:{harness:'pi',model:'first',thinking:'low'}}},catalogue:{status:'disabled'}}; + const web=await startServer({port:0,board:'http://127.0.0.1:9',bus:{messages:async()=>({messages:[],unread:0}),usage:async()=>{throw Error('fixture')},routes:async()=>view},reads:{settings:()=>({business:'acme',release:'fixture',notifier:{}})},log:()=>{}});t.after(()=>close(web));const b=await browser();t.after(()=>b.close()); + await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`const original=window.fetch;window.fetch=(u,o)=>u==='/api/config'?Promise.resolve(new Response(JSON.stringify({send:true}))):original(u,o);`});await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/routing`); + const cell=key=>`document.querySelector(${JSON.stringify(`[data-route='${JSON.stringify(['coder',key])}']`)})`; + await b.evaluate(`(async()=>{for(let n=0;n<200&&!${cell('fallback.harness')};n++)await new Promise(r=>setTimeout(r,30));})()`); + await b.evaluate(`(async()=>{for(let n=0;n<200&&document.querySelector('#routes-form button[type=submit]').disabled;n++)await new Promise(r=>setTimeout(r,30));})()`);await b.viewport(390,900);assert.equal(await b.evaluate(`getComputedStyle(document.querySelector('.route-actions')).position`),'fixed');assert.equal(await b.evaluate(`getComputedStyle(document.querySelector('#routes-reload')).display`)!=='none',true);await b.viewport(1440,1000);assert.notEqual(await b.evaluate(`getComputedStyle(document.querySelector('.route-actions')).position`),'fixed'); + // Inject the two quick edits after the next render has built its markup but before it paints. + await b.evaluate(`{const status=document.querySelector('#fresh-bus'),descriptor=Object.getOwnPropertyDescriptor(Element.prototype,'innerHTML');let armed=true;Object.defineProperty(status,'innerHTML',{configurable:true,get(){return descriptor.get.call(this)},set(value){descriptor.set.call(this,value);if(!armed)return;armed=false;for(const [e,v] of [[${cell('fallback.model')},'second'],[${cell('fallback.thinking')},'high']]){e.value=v;e.dispatchEvent(new Event('change',{bubbles:true}));}}});const e=${cell('fallback.harness')};e.value='claude-code';e.dispatchEvent(new Event('change',{bubbles:true}));}true`); + await b.evaluate('new Promise(r=>setTimeout(r,500))'); + assert.deepEqual(await b.evaluate(`[${cell('fallback.harness')}.value,${cell('fallback.model')}.value,${cell('fallback.thinking')}.value]`),['claude-code','second','high']); +}); diff --git a/packages/webui/tests/shell.test.mjs b/packages/webui/tests/shell.test.mjs index eb294a2cb..5d7dddf91 100644 --- a/packages/webui/tests/shell.test.mjs +++ b/packages/webui/tests/shell.test.mjs @@ -62,8 +62,8 @@ test('shipped strings are unchanged, and the web keeps its write boundary', () = // and the provider switch writes only the model-provider plugin setting. assert.doesNotMatch(src, /]*>[^<]*(Resolve|Decide|Approve)/i); const writes = read('bus.js').toString().match(/fetch\([^;]*method:\s*['"](POST|PUT|PATCH|DELETE)[^;]*;/g) ?? []; - assert.deepEqual(writes, ["fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', redirect: 'manual' });", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});", "fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "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'});", "fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/project-file', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(sent), cache: 'no-store', redirect: 'manual' });", "fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });"]); - assert.equal(read('bus.js').toString().split(/method:/).length - 1, 9); + assert.deepEqual(writes, ["fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', redirect: 'manual' });", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});", "fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});", "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'});", "fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/project-file', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(sent), cache: 'no-store', redirect: 'manual' });", "fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });"]); + assert.equal(read('bus.js').toString().split(/method:/).length - 1, 10); assert.deepEqual([...read('bus.js').toString().matchAll(/decidePost\(([^,]*),/g)].map(m => m[1]), ['url', '`/api/decisions/${enc(a.id)}/confirmation`', '`/api/decisions/${enc(a.id)}/resolve`']); // Row 155 (#1649): the one fetch(url, ...) posts only to these three routes, each a literal. // Row 176 (#1674): the tester name form adds a second /api/name caller. From 617d7e4a7acc43637134ea42c4c268db6cc1f0f8 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 21:25:32 -0600 Subject: [PATCH 2/2] Keep Routing when a route edit lands during a harness save A harness or catalogue save clears routesView. A route draft made while the save was in flight kept routesSection from adopting the fresh read, so the next render dereferenced a null view and Routing disappeared until a page reload. Adopt the fresh view whenever none is held; the draft keeps its cells. S6a review P2 1. --- packages/webui/src/public/bus.js | 4 ++- .../routes-harness-race-browser.test.mjs | 32 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 packages/webui/tests/routes-harness-race-browser.test.mjs diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index ac2acab5d..a63fbcefa 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -926,7 +926,9 @@ const title='

Routing

'; readHarnesses(); if(!view)return `
${title}

The routes could not be read, so there is nothing to change. Read again to retry; they come from the bus host with your identity.

`; - if(!routesDraft)routesView=view; + // A harness or catalogue save clears routesView; a draft made while it was in flight keeps its + // cells over the fresh read. + if(!routesDraft||!routesView)routesView=view; const v=routesView, disabled=!(canSend || isTester)||out()||routesBusy?' disabled':''; const cells=name=>routesDraft?.[name]??routeCells(v.instances[name]); const select=(name,key,list,current,why,labels={})=>{const offered=current===''||list.includes(current)?list:[...list,current]; diff --git a/packages/webui/tests/routes-harness-race-browser.test.mjs b/packages/webui/tests/routes-harness-race-browser.test.mjs new file mode 100644 index 000000000..6a9de1623 --- /dev/null +++ b/packages/webui/tests/routes-harness-race-browser.test.mjs @@ -0,0 +1,32 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { browser } from './browser.mjs'; +import { startServer } from '../src/serve.mjs'; +import { close } from './fixture.mjs'; + +// A route edit made while a harness save is in flight keeps the Routing form and the draft. +const initial = { business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi'], models: ['first', 'second'], providerModels: {}, levels: { pi: ['low', 'high'], 'claude-code': ['low', 'high'] }, instances: { coder: { harness: 'pi', model: 'first', thinking: 'low', fallback: null } }, catalogue: { status: 'disabled', models: [], notices: [] } }; +const settings = { business: 'acme', revision: initial.revision, plugins: { harness: ['pi'] }, available: { harness: ['pi', 'claude-code'] } }; + +test('a route edit during a harness save keeps Routing and the draft', async () => { + const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', bus: { messages: async () => ({ messages: [], unread: 0 }), usage: async () => { throw Error('fixture'); }, routes: async () => initial }, reads: { settings: () => ({ business: 'acme', release: 'fixture', notifier: {} }) }, log() {} }); + let b; + try { + b = await browser(); + const errors = []; + b.on('Runtime.exceptionThrown', x => errors.push(x.exceptionDetails?.exception?.description ?? x.exceptionDetails?.text)); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.routeView=${JSON.stringify(initial)};window.harnessView=${JSON.stringify(settings)};window.pluginPosts=[];window.routeReads=0;const original=window.fetch;window.fetch=async(u,o={})=>{if(u==='/api/config')return new Response(JSON.stringify({send:true}));if(u==='/api/proxy/plugins')return new Response(JSON.stringify(harnessView));if(u==='/api/bus/routes'){routeReads++;return new Response(JSON.stringify({rows:[routeView],at:new Date().toISOString()}));}if(u==='/api/proxy/plugins/set'){pluginPosts.push(JSON.parse(o.body));return new Promise(r=>window.answerHarness=(status,body)=>r(new Response(JSON.stringify(body),{status})));}return original(u,o);};` }); + const wait = expr => b.evaluate(`(async()=>{for(let n=0;n<500;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,20));}throw Error('wait: '+${JSON.stringify(expr)});})()`); + const cell = key => `document.querySelector(${JSON.stringify(`[data-route='${JSON.stringify(['coder', key])}']`)})`; + await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/routing`); + await wait('!!document.querySelector("#harness-save")'); + await b.evaluate('document.querySelector("[data-harness=claude-code]").click();document.querySelector("#harness-save").click();true'); + await wait('pluginPosts.length===1'); + await b.evaluate(`${cell('model')}.value='second';${cell('model')}.dispatchEvent(new Event('change',{bubbles:true}));window.routeView={...routeView,revision:'c'.repeat(64),harnesses:['pi','claude-code']};window.answerHarness(200,{business:'acme',revision:'c'.repeat(64),plugins:{harness:['pi','claude-code']},transaction:'fixture'});true`); + await wait('document.querySelector("#harness-status")?.textContent.includes("Harnesses saved")'); + await wait('routeReads>=2'); + assert.equal(await b.evaluate('!!document.querySelector("#routes-form")'), true); + assert.equal(await b.evaluate(`${cell('model')}.value`), 'second'); + assert.deepEqual(errors, []); + } finally { await b?.close(); await close(web); } +});