feat(webui): an organization's Models page offers one choice, use your models or its own, with a fresh read before each write; slice 4 follow-ups (#1873) #2007

Merged
jason.woltje merged 7 commits from settings-s5 into refactor 2026-11-20 04:31:28 +00:00
7 changed files with 601 additions and 36 deletions

No files matched your search

+90 -16
View File
@@ -703,7 +703,14 @@
<h2 id="b-for-you">Open decisions <span class="count">${rows.length}</span></h2>${body}
<p class="small muted">Open a decision for its seen, DM and closing history.</p>`;
}
const messageText = m => m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ') ? `The assistant couldn't reply. Try again, or check Agents.<span class="source">Details: ${txt(m.body.slice('The turn failed: '.length))}</span>` : txt(m.body);
// #1873 settings slice 5: a failed turn whose body carries its own "\nDetails: " part (chat.js
// messageBody) shows its cause and that part once.
const messageText = m => {
if (m.from_role === 'human' || typeof m.body !== 'string' || !m.body.startsWith('The turn failed: ')) return txt(m.body);
const rest = m.body.slice('The turn failed: '.length), at = rest.indexOf('\nDetails: ');
if (at > 0) return `The assistant couldn't reply: ${txt(rest.slice(0, at))}<span class="source">Details: ${txt(rest.slice(at + '\nDetails: '.length))}</span>`;
return `The assistant couldn't reply. Try again, or check Agents.<span class="source">Details: ${txt(rest)}</span>`;
};
async function messagesView(get, q) {
const after = q.get('after');
if (after !== null && !SAFE.test(after)) return notFound('The message cursor is not a message id.');
@@ -1299,6 +1306,9 @@
}
const routesApplyMarkup=()=>routesApply?.length?`<ul class="routes-apply" aria-label="How the change reaches each agent">${routesApply.map(a=>`<li><b>${txt(a.name)}</b>: ${txt(a.text)}${a.restart&&canSend&&!isTester?` ${window.MosaicAgents?.restartMarkup(a.name,a.thread)??''}`:''}</li>`).join('')}</ul>`:'';
let harnessSettings=null, harnessDraft=null, harnessLoading=false, harnessReceipt='', harnessBusy=false;
// #1873 settings slice 5: the organization's one choice, Use your models (the cliproxy module in
// its model-provider list, from the plugins read above) or its own model service (Coming later).
let modelsReceipt='', modelsReceiptKind='', modelsBusy=false, modelsFocus=false;
function readHarnesses(){
if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true;const epoch=orgEpoch;
fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;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(()=>{if(epoch!==orgEpoch)return;harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{if(epoch!==orgEpoch)return;harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
@@ -1345,11 +1355,48 @@
if(owner&&serviceState==='not-running')return `<p class="small warn" id="routes-catalogue">${lead} The model service is not running. ${setupLink('Open Model setup')}. ${thinking}</p>${words}`;
if(owner&&(serviceLoading||(serviceState===null&&triageOwner)))return `<p class="small warn" id="routes-catalogue">${lead} Checking the model service. ${thinking}</p>`;
if(owner&&serviceState===false)return `<div class="banner routes-catalogue" id="routes-catalogue" role="status"><p>${lead}${plain} The model service's status could not be read. ${thinking}</p>${words}<p class="actions">${recheck}</p></div>`;
return `<p class="small warn" id="routes-catalogue">${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.':''}</p>${words}`;
return `<p class="small warn" id="routes-catalogue">${lead}${plain} ${thinking}${owner?' A new model needs the model service: ask the instance owner to set it up, or press Stop using your models when this organization does not need it.':''}</p>${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);});
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);});
// The choice reads only the plugins read: before it answers the radios wait, and a failed read
// says so with Read again. Use your models writes at once; Stop using your models is the way back.
// While the organization needs a restart, its banner's Restart is the one primary and the choice waits.
// A Console with no organizations says "this business": lowercase inside a sentence, capitalized
// at its start (cap).
const modelsWho=cap=>window.MosaicOrg?(window.MosaicOrg.label||window.MosaicOrg.id):cap?'This business':'this business';
const modelsWhose=cap=>`${modelsWho(cap)}'s`;
// settings-s5 review P2-3: a choice that is not in force says when the model service behind it is
// not set up or not answering (the owner's status read, as on the catalogue line). The choice
// still writes: riding before setup is the design's "Nothing set up" state.
function modelsService(){
const link=text=>`<a href="#/settings/model-setup">${text}</a>`;
return serviceState==='not-set-up'?`<p class="small warn" id="models-service">Your model service isn't set up. ${link('Set it up in Model setup')}.</p>`
:serviceState==='not-running'?`<p class="small warn" id="models-service">Your model service isn't answering. ${link('Restart it in Model setup')}.</p>`
:serviceState==='fenced'?`<p class="small warn" id="models-service">Your model service is waiting for a restart to finish. ${link('Open Model setup to finish it')}.</p>`:'';
}
function modelsChoice(restartFirst){
const who=txt(modelsWho()), Who=txt(modelsWho(true)), whose=txt(modelsWhose()), Whose=txt(modelsWhose(true));
const names=harnessSettings&&Array.isArray(harnessSettings.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[];
const read=!!harnessSettings, on=read&&names.includes('cliproxy'), wait=!read||modelsBusy||restartFirst||out();
if(triageOwner)readService();
const now=harnessSettings===false?`Which models ${who} uses could not be read.`:!read?`Reading ${whose} models…`:on?`Now: ${who} uses your models.`:`Now: ${who} does not use your models. Its agents use only the models in its own organization file.`;
const change=!read?'':restartFirst?`<p class="small" id="models-wait">You can change ${whose} models after it restarts.</p>`
:on?`<p class="small muted" id="models-change">Its agents can use the models your accounts offer. To switch back, press Stop using your models. A route on one of your models then stops working until you change it.</p>`
:`<p class="small muted" id="models-change">Choose Use your models to switch. ${Whose} agents can then use the models your accounts offer. While your model service is down, a launch that needs it is refused. A running agent keeps its model until it starts again.</p>${modelsService()}`;
// P2-1: while the organization needs a restart every control here waits. Stop is left out, as in
// the mockup, since a disabled button here looks no different from an enabled one.
const stop=on&&!restartFirst?`<button type="button" id="models-stop"${modelsBusy||out()?' disabled':''}>${modelsBusy?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Stop using your models'}</button>`:'';
const again=harnessSettings===false?'<button type="button" id="models-read">Read again</button>':'';
// P3-1: Use your models has no button of its own, so its write shows Saving in the status line.
const status=modelsBusy&&!on?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':txt(modelsReceipt);
return `<fieldset class="models-source" id="models-source"><legend>Where ${who} gets its models</legend>`
+`<label class="choice"><input type="radio" name="models-source" id="models-yours" value="yours"${on?' checked':''}${wait?' disabled':''}><strong>Use your models</strong><span class="badge badge-ok">Recommended</span><span class="small muted">${Who} uses the model service and accounts in Model setup. Nothing to sign in to.</span></label>`
+`<label class="choice off"><input type="radio" name="models-source" id="models-own" value="own" disabled><strong>Use its own model service</strong><span class="badge badge-muted">Coming later</span><span class="small muted">${Who} would run a second model service with its own accounts. Planned, not built yet, so you can't choose it today.</span></label>`
+`<p id="models-in-force">${now}</p>${change}<p class="actions">${stop}${again}</p>`
+`<p role="status" id="models-receipt" class="${modelsBusy&&!on?'':modelsReceiptKind}" tabindex="-1" data-focus-key="models-receipt">${status}</p></fieldset>`;
}
function routesSection(view,instanceInfo){
const title='<h2 id="routes-title">Routing</h2>';
readHarnesses();
@@ -1381,7 +1428,7 @@
// settings-p3 (re-check 3 P3-5): a ready catalogue the bus picked up late says agents start on these
// models after a restart; that notice gets the organization's Restart (not primary: Save routes is).
const catalogueInfo=v.catalogue?.status==='ready'?`<p class="small muted">Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.</p>${(v.catalogue.notices??[]).map(n=>`<p class="small warn">${txt(n)}${n===window.MosaicConsole?.RESTART_TO_LAUNCH&&window.MosaicOrg?.id?` ${window.MosaicConsole.orgRestartButton(window.MosaicOrg.id,{name:window.MosaicOrg.label||window.MosaicOrg.id})}`:''}</p>`).join('')}`:v.catalogue?.status==='unavailable'?catalogueLine(proxyOn,v.catalogue):'<p class="small muted">Model catalogue not enabled.</p>';
const providerControl=canSend&&!isTester?`<button type="button" id="provider-switch" data-enabled="${proxyOn}">${proxyOn?'Stop using the model service':'Use your models'}</button><p role="status" id="provider-switch-status"></p>`:'';
const providerControl=canSend&&!isTester?modelsChoice(/ data-primary[ >]/.test(catalogueInfo)):'';
const harnessControl=canSend&&!isTester?`<fieldset class="harness-control"><legend>Harnesses</legend>${harnessSettings ? [...new Set([...harnessSettings.available.harness,...(harnessSettings.plugins.harness??[])])].map(name=>`<label><input type="checkbox" data-harness="${esc(name)}"${(harnessDraft??harnessSettings.plugins.harness??[]).includes(name)?' checked':''}${harnessBusy?' disabled':''}> ${txt(name)}</label>`).join('')+` <button type="button" id="harness-save"${harnessBusy?' disabled':''}>Save harnesses</button>` : '<p>Harnesses unavailable.</p><button type="button" id="harness-read">Read harnesses again</button>'}<p role="status" id="harness-status">${txt(harnessReceipt)}</p></fieldset>`:'';
const off=v.harnesses.length?'':'<p class="small warn">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.</p>';
return `<section class="panel routing-panel" aria-labelledby="routes-title"><span class="sr-only">${title}</span>${catalogueInfo}${providerControl}${harnessControl}${off}<form id="routes-form"><div class="table-wrap" tabindex="0" role="region" aria-label="Routes, scroll for all columns"><table id="routes-table"><thead><tr><th scope="col" rowspan="2">Agent</th><th scope="colgroup" colspan="3">Primary</th><th scope="colgroup" colspan="3">Fallback</th></tr><tr>${ROUTE_CELLS.map(([,l])=>`<th scope="col">${l.replace('Fallback ','')}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div><p class="small muted">${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}</p><div class="settings-actions route-actions${routesDraft?' has-draft':''}"><button type="submit"${/ data-primary[ >]/.test(catalogueInfo)?' class="route-save-quiet"':''}${disabled}>${routesBusy?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save routes'}</button> <button type="button" id="routes-reload"${routesDraft?'':' hidden'}${routesBusy||!routesDraft?' disabled':''}>Discard draft</button><p role="status" id="routes-receipt" class="${routesReceipt.startsWith('Outcome unknown')?'banner ref':routesReceipt.includes('Draft kept')?'banner err':routesReceipt.includes('saved')?'settings-success':''}">${txt(routesReceipt)}</p></div>${routesApplyMarkup()}</form></section>`;
@@ -1409,7 +1456,7 @@
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 does not need the model service: press Stop using the model service, then save again.':'';
return moved.length&&moved.every(key=>module(key)&&module(key)!=='cliproxy'&&names.includes(module(key)))?' This change does not need your models: press Stop using your models, 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;}
@@ -1429,17 +1476,32 @@
catch{if(epoch!==orgEpoch)return;harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;}
finally{if(epoch===orgEpoch){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');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true;const epoch=orgEpoch;
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?'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);
}catch(error){if(epoch!==orgEpoch)return;status.textContent=error.message;button.disabled=false;}
});
// The fresh read decides: a page that shows a stale choice is redrawn from it and nothing is written.
async function setModels(want){
if(!canSend||isTester||modelsBusy||!harnessSettings)return;
const who=modelsWho(true), shown=(harnessSettings.plugins?.['model-provider']??[]).includes('cliproxy');
let sent=false;
if(routesDraft){modelsReceipt='Save or discard the route draft first.';modelsReceiptKind='banner err';modelsFocus=true;render(false);return;}
modelsBusy=true;modelsReceipt='';modelsReceiptKind='';render(false);const epoch=orgEpoch;
try{const read=await fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'});const settings=await read.json();if(epoch!==orgEpoch)return;
if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??'')||!Array.isArray(settings.available?.harness))throw Error('read');
const names=Array.isArray(settings.plugins?.['model-provider'])?settings.plugins['model-provider']:[], on=names.includes('cliproxy');
if(on!==shown){harnessSettings=settings;modelsReceipt=`${modelsWhose(true)} models changed since this page read it. The page now shows the current choice; choose again to change it.`;modelsReceiptKind='banner ref';return;}
if(on===want)return;
const next=want?[...names,'cliproxy']:names.filter(n=>n!=='cliproxy');
sent=true;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'});
const result=await response.json().catch(()=>({}));if(epoch!==orgEpoch)return;
if(!response.ok){modelsReceipt=`Not changed. ${result.message||result.error||'The change was refused.'}`;modelsReceiptKind='banner err';return;}
modelsReceipt=want?`Saved. ${who} uses your models. An agent picks them up the next time it starts.`:`Saved. ${who} no longer uses your models. An agent on one of them keeps it until it starts again.`;modelsReceiptKind='settings-success';
harnessSettings=null;routesView=null;last.delete('routes');window.MosaicModelDots?.read?.();
// P3-2: a failed read before the write changed nothing and says so, with Read again.
}catch{if(epoch!==orgEpoch)return;if(sent){modelsReceipt='Outcome unknown. Read the page again before trying.';modelsReceiptKind='banner ref';harnessSettings=null;}else{modelsReceipt='Not changed. Nothing was written.';modelsReceiptKind='banner err';harnessSettings=false;}}
// P2-4: the render that shows the outcome moves focus to it (render() below).
// Recheck N2: only while the page is still shown; a switch left mid-write does not take focus later.
finally{if(epoch===orgEpoch){modelsBusy=false;modelsFocus=!!modelsReceipt&&routeOf().split('?')[0]==='/settings/routing';if(!out())render(harnessSettings===null);}}
}
document.addEventListener('change',e=>{if(e.target.id==='models-yours'&&e.target.checked)setModels(true);});
document.addEventListener('click',e=>{if(e.target.closest?.('#models-stop'))setModels(false);else if(e.target.id==='models-read'){harnessSettings=null;harnessReceipt='';modelsReceipt='';modelsReceiptKind='';render(false);}});
document.addEventListener('click',e=>{if(e.target.matches?.('.fallback-toggle'))e.target.closest('tr')?.classList.add('fallback-open');});
document.addEventListener('click',e=>{if(e.target.id!=='routes-reload')return;routesDraft=null;routesView=null;routesReceipt='';routesApply=null;last.delete('routes');render(true);});
document.addEventListener('submit',async e=>{
@@ -1525,6 +1587,9 @@
const notify = typeof n.binding==='string' ? `<code>${txt(n.binding)}</code>` : n.refused ? `Could not be read: <code>${txt(n.refused)}</code>` : '<span class="muted">None set</span>';
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:()=>`<section class="panel"><dl class="kv"><dt>Address</dt><dd><code>${txt(s.address)||'unknown'}</code></dd><dt>Release</dt><dd>${txt(s.release)||'unknown'}</dd><dt>Business</dt><dd>${txt(s.business)||none}</dd><dt>Board</dt><dd><code>${txt(s.board)||'unknown'}</code></dd><dt>Notifier binding</dt><dd>${notify}</dd></dl></section>`};
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. 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.'};
// settings-s5 review P2-2: the header says where the models come from only from the plugins read.
const riding=harnessSettings?(harnessSettings.plugins?.['model-provider']??[]).includes('cliproxy'):null;
if(window.MosaicOrg&&!isTester)helpers.routing=`The models ${modelsWhose()} agents use.${riding===true?' They come from your accounts in Model setup.':riding===false?' They come from its own organization file.':''} ${helpers.routing}`;
return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`);
}
let settingsFocusDisclosure=false;
@@ -1911,6 +1976,8 @@
if ((navigated || path !== '/settings/organizations') && orgCleanup) {orgCleanup();orgCleanup=null;}
// Leaving a decision discards its confirmation immediately, including a preview in flight.
if (answer && (navigated || path !== (answer.org ? '/inbox' : `/inbox/${answer.id}`))) answer = null;
// Recheck N1: arriving at Models reads the model service again; a status read on an earlier visit may be out of date.
if (navigated && path === '/settings/routing' && (typeof shown === 'string' ? shown.split('?')[0] : shown) !== path && !serviceLoading) serviceState = null;
const g = ++gen, routeVersion = routesEditVersion;
const current = () => g === gen && route === routeOf() && !out();
// In organization mode #/ is the cross-organization dashboard; the processing controls stay on the board.
@@ -1923,6 +1990,8 @@
window.MosaicChat?.leave(chatPath);
if (path === '/business') { location.replace('#/settings/business'); return; }
if (path === '/settings/display') { location.replace('#/settings/appearance'); return; }
// #1873 settings slice 5: Members is gone from the nav; its old addresses land on the organization's Agents page.
if (path === '/settings/members') { location.replace(`#/settings/agents${window.MosaicOrg ? `?org=${enc(window.MosaicOrg.id)}` : ''}`); return; }
// #1873 settings slice 4: the owner's page is Model setup; its old address lands there, query kept.
if (path === '/settings/model-proxy') { location.replace(`#/settings/model-setup${query ? `?${query}` : ''}`); return; }
// #1873 SP6: the Assistant page draws its own thread panes (assistant.js); every other page
@@ -2046,7 +2115,11 @@
sections(path);
const h1 = $('bus-view').querySelector('h1');
document.title = path === '/settings/business' && $('settings-page-title') ? `Settings · ${window.MosaicOrg ? 'Organization' : 'Business'} · Mosaic Console` : `${h1 ? h1.textContent : 'Console'} · Mosaic Console`;
if (k) restore(k);
// settings-s5 review P2-4: after a switch on Organization > Models, focus goes to its outcome line.
// Recheck N2: a render that paints no outcome line drops the request instead of keeping it.
const focusModels = modelsFocus && $('models-receipt'); modelsFocus = false;
if (focusModels) { if (k) restore(k); focusModels.focus({ preventScroll: true }); }
else if (k) restore(k);
// Message on the Board (row 95) lands in the form it opened, addressed to the role.
else if (focusSend && $('send-body')) { $('send-body').focus(); announce(`Message to ${draft.to}`); }
// SP17: a step link on an organization's Workflows card lands in that step's title field.
@@ -2261,6 +2334,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 = '';
modelsReceipt = ''; modelsReceiptKind = ''; modelsBusy = false; modelsFocus = false;
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;
+27 -10
View File
@@ -972,10 +972,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
}
function row(dl, term, text) { const dt = document.createElement('dt'), dd = document.createElement('dd'); dt.textContent = term; dd.textContent = text; dl.append(dt, dd); }
function paintState() {
// #1873 settings slice 5: the timeouts init chose, from the same read. Null is not set in
// proxy.json, so the model service uses its default.
const timeouts = s => !s || typeof s !== 'object' ? '' : `, wait for a first answer${s.firstOutputSeconds == null ? ': the default' : ` ${human(s.firstOutputSeconds)} seconds`}, old key kept${s.rotateGraceMinutes == null ? ' after a new one: the default' : ` ${human(s.rotateGraceMinutes)} minutes after a new one`}`;
const { release, init, unit, fence, initLock } = state, dl = $('proxy-setup-state'); dl.replaceChildren();
row(dl, 'Release', !release.fetched ? `Not fetched (pinned ${release.version}, panel ${release.panelVersion})` : release.verified ? `Fetched ${release.version}, panel ${release.panelVersion}, hashes verified` : `Fetched ${release.version}, hashes not verified (${release.problem})`);
const files = init.files.filter(f => f.present).map(f => f.label).join(', ') || 'none';
row(dl, 'Initialized', init.initialized ? `Yes, port ${init.settings?.port ?? '—'}` : init.partial ? `Partly (${init.problem ?? 'incomplete'}). Present: ${files}` : init.problem ? `No (${init.problem})` : 'No');
row(dl, 'Initialized', init.initialized ? `Yes, port ${init.settings?.port ?? '—'}${timeouts(init.settings)}` : init.partial ? `Partly (${init.problem ?? 'incomplete'}). Present: ${files}` : init.problem ? `No (${init.problem})` : 'No');
row(dl, 'Service', `${unit.unit}: ${unit.installed ? 'installed' : 'not installed'}, ${unit.active}${unit.pid ? `, pid ${unit.pid}` : ''}${unit.port ? `, port ${unit.port} ${unit.listening ? 'answering' : 'not answering'}` : ''}${unit.error ? ` (${unit.error})` : ''}`);
row(dl, 'Fence', !fence.set ? 'Clear' : fence.invalid ? 'Set (unreadable fence file)' : `Set after ${fence.op ?? 'a key write'}${fence.org ? ` for ${fence.org}` : ''}${fence.time ? ` at ${window.MosaicLocalTime(fence.time)}` : ''}`);
row(dl, 'Init lock', !initLock.present ? 'None' : initLock.clearable ? 'Stale: the bus is stopped and no model service files exist' : `Held: ${initLock.blockers.join('; ')}`);
@@ -1118,7 +1121,16 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
function paintOrgsCard() {
const line = $('setup-step-organizations').querySelector('[data-step-summary]'), go = $('proxy-ride-go');
go.className = 'btn'; delete line.dataset.next;
if (!running() || !accountCount) { setCard('organizations', 'wait', 'Opens after your first account.'); return; }
// settings-s5: before the first account, an organization the sidebar already marks "can't start" is
// named here, so the card and the mark agree.
if (!running() || !accountCount) {
const blocked = running() ? cantStart().map(f => nameOf(f.id)) : [];
if (!blocked.length) { setCard('organizations', 'wait', 'Opens after your first account.'); return; }
const one = blocked.length === 1;
// The card stays closed (Move needs a model from an account), with the mark's word on its badge.
setCard('organizations', 'wait', `Opens after your first account. ${listNames(blocked)} can't start now: ${one ? 'it uses' : 'they use'} stand-in models and ${one ? 'its bus is' : 'their buses are'} stopped. After your first account, move ${one ? 'it' : 'them'} to your models under Use your models in every organization, then start ${one ? 'its bus' : 'their buses'}.`, { badge: ['badge-danger', "Can't start"] });
return;
}
const step = orgStep(), names = needRestart().filter(restartHelps).map(o => nameOf(o.id));
// settings-p3 (rebase re-check P3-1, settings-s4 P3): the Ride all box still lists an organization,
// so not "every". One that turned the model service off is not waiting on anything: it is named.
@@ -1200,7 +1212,11 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
// After init, Advanced shows the settings init wrote, read-only.
const dl = $('proxy-setup-settings'), s = init.initialized && init.settings && typeof init.settings === 'object' ? init.settings : null;
dl.hidden = !s; $('proxy-setup-settings-note').hidden = !s; dl.replaceChildren();
if (s) { row(dl, 'Port', human(s.port)); if (s.firstOutputSeconds !== undefined) row(dl, 'Wait for a first answer', `${human(s.firstOutputSeconds)} seconds`); }
if (s) {
row(dl, 'Port', human(s.port));
if (s.firstOutputSeconds !== undefined) row(dl, 'Wait for a first answer', s.firstOutputSeconds === null ? 'The default' : `${human(s.firstOutputSeconds)} seconds`);
if (s.rotateGraceMinutes !== undefined) row(dl, 'Old key kept after a new one', s.rotateGraceMinutes === null ? 'The default' : `${human(s.rotateGraceMinutes)} minutes`);
}
}
// Programs that drive models: the harnesses this Console offers an organization, read on open.
let programsRead = false;
@@ -1255,15 +1271,15 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ 'Admission gets stricter there: every launch route is checked, direct Anthropic routes too, and while the model service is down or fenced every launch in that organization is refused. '
+ (ready ? `${ready} ${ready === 1 ? 'organization can' : 'organizations can'} ride now.` : 'No organization is waiting to ride.');
const go = $('proxy-ride-go'); go.disabled = !sendOk || Boolean(state.busy) || !ready;
$('proxy-ride-skips').replaceChildren(...rideSkips().map(s => li(`Skipped ${s.id}: ${rideReason(s.reason)}`)));
$('proxy-ride-skips').replaceChildren(...rideSkips().map(s => li(`Skipped ${nameOf(s.id)}: ${rideReason(s.reason)}`)));
const listedFixtures = rideResult?.fixtures ?? fixtures.map(f => ({ id: f.id, running: f.running }));
$('proxy-ride-fixtures').replaceChildren(...listedFixtures.map(f => {
// running null: no bus status here (the single-business Console), so moving is not available.
const name = nameOf(f.id);
if (f.running === null) return li(`${name} uses stand-in models. Moving it is not available on this Console.`);
// settings-s4 review F2: running false is what the sidebar marks "can't start"; say so, and the fix.
const item = li(f.running === false ? `${name} can't start: it uses stand-in models and its bus is stopped. Move it to the owner's models, then start its bus. `
: `${name} uses stand-in models, can be moved to the owner's models.${f.running === true ? ' Its bus is running: stop it first.' : ''} `);
const item = li(f.running === false ? `${name} can't start: it uses stand-in models and its bus is stopped. Move it to your models under Use your models in every organization, then start its bus. `
: `${name} uses stand-in models, can be moved to your models.${f.running === true ? ' Its bus is running: stop it first.' : ''} `);
const move = document.createElement('button'); move.type = 'button'; move.className = 'btn'; move.textContent = `Move ${name}`;
move.dataset.rideMove = f.id; move.disabled = !sendOk || Boolean(state.busy);
move.addEventListener('click', () => { if (!move.disabled) rideMove(f.id); });
@@ -1281,13 +1297,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
});
};
const rideMove = id => {
if (!window.confirm(`Move ${id} to your models? Its stand-in models are replaced by a model your model service lists. After this, its agents spend real tokens on your account. Its bus stays stopped: start it when you are ready.`)) return;
if (!window.confirm(`Move ${nameOf(id)} to your models? Its stand-in models are replaced by a model your model service lists. After this, its agents spend real tokens on your account. Its bus stays stopped: start it when you are ready.`)) return;
return act('ride-move', async () => {
const result = await admin('ride-move', { org: id });
if (!result.moved) { rideSay(`${id} was not moved. ${rideReason(result.reason)}`, 'error'); return; }
if (!result.moved) { rideSay(`${nameOf(id)} was not moved. ${rideReason(result.reason)}`, 'error'); return; }
addReceipt(result.receipt);
if (rideResult) rideResult = { ...rideResult, fixtures: rideResult.fixtures.filter(f => f.id !== id) };
rideSay(`${id} now uses ${result.model}. Start its bus when you are ready. It spends real tokens from now on.`, 'success');
rideSay(`${nameOf(id)} now uses ${result.model}. Start its bus when you are ready. It spends real tokens from now on.`, 'success');
});
};
$('proxy-ride-go').addEventListener('click', () => { if (!$('proxy-ride-go').disabled) rideAll(); });
@@ -1494,5 +1510,6 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
document.addEventListener('mosaic-org-restarted', () => { read(); });
const begin = () => { (window.MosaicOrg?.ready ?? Promise.resolve()).then(read, () => {}); };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', begin, { once: true }); else begin();
window.MosaicModelDots = { get: id => marks.get(id) ?? null };
// settings-s5: a page that changes what the status says (an organization's Models choice) asks for a fresh read.
window.MosaicModelDots = { get: id => marks.get(id) ?? null, read };
})();
+14
View File
@@ -339,6 +339,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
.rows li{display:grid;grid-template-columns:7rem minmax(0,1fr) auto;gap:6px var(--gap,12px);align-items:center;padding:10px 0;border-top:1px solid var(--line)}
.rows li>span:first-child{font-weight:600;color:var(--strong)}
.rows li>.account-reason{grid-column:2/-1;margin:0}
.rows li.muted{display:block}
.progress{list-style:none;margin:var(--gap,12px) 0 0;padding:0;display:grid;gap:6px}
.progress li::before{display:inline-block;width:1.4em;color:var(--muted)}
.progress .ok::before{content:"✓";color:var(--success)}.progress .run::before{content:"●";color:var(--action)}.progress .todo::before{content:"○"}.progress .bad::before{content:"✕";color:var(--danger)}
@@ -375,6 +376,19 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
.settings-content fieldset.harness-control{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px}
.settings-content fieldset.harness-control>legend{flex-basis:100%}
.settings-content fieldset.harness-control>:is(button,p){flex-basis:100%}
/* #1873 settings slice 5: an organization's one choice (mockup org-models). A choice not built yet is dashed and disabled. */
/* settings-s5 review P3-4: the choice cards sit in the form column, as .settings-form does. */
.settings-content fieldset.models-source{display:grid;gap:8px;max-width:28rem}
.settings-content fieldset.models-source>legend{font-size:14px;color:var(--strong);margin-bottom:8px}
.settings-content fieldset.models-source>p{margin:0}
.choice{display:grid;grid-template-columns:auto 1fr auto;gap:4px 10px;align-items:start;padding:12px;border:1px solid var(--border);border-radius:var(--r);cursor:pointer}
.choice input{margin-top:4px}
.choice:has(input:checked){border-color:var(--action);background:var(--raised)}
.choice:has(input:disabled){cursor:default}
.choice.off{color:var(--muted);cursor:not-allowed;border-style:dashed;background:transparent}
.choice strong{color:var(--strong)}.choice.off strong{color:var(--muted)}
.choice .small{grid-column:2/4;margin:0}
.choice:has(input:focus-visible){outline:2px solid var(--focus);outline-offset:2px}
.settings-content :is(.instance-form,.level-form) textarea,.settings-content .assistant-form textarea{display:block;width:100%}
.route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}}
@media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}}
@@ -177,7 +177,7 @@ test('Ride all confirms the stricter admission, paints skips and stand-in organi
await wait(`document.querySelector("#proxy-ride")?.checkVisibility() && document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="ride-all"`);
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").className'), 'btn primary');
assert.match(await b.evaluate('document.querySelector("#proxy-ride-text").textContent'), /every launch route is checked, direct Anthropic routes too.*2 organizations can ride now/);
assert.match(await b.evaluate('document.querySelector("#proxy-ride-fixtures li").textContent'), /^west uses stand-in models, can be moved to the owner's models\./);
assert.match(await b.evaluate('document.querySelector("#proxy-ride-fixtures li").textContent'), /^west uses stand-in models, can be moved to your models\./);
// The first Ride all's own reload paints, then waits on the accounts read for good.
await b.evaluate('document.querySelector("#proxy-ride-go").click()');
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/ride-all")');
@@ -399,7 +399,7 @@ test('settings-p3: a stand-in organization with no bus status is not offered a M
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-ride-fixtures li")');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-ride-fixtures li")].map(li => li.firstChild.textContent.trim())'),
['west uses stand-in models. Moving it is not available on this Console.', "east uses stand-in models, can be moved to the owner's models."]);
['west uses stand-in models. Moving it is not available on this Console.', "east uses stand-in models, can be moved to your models."]);
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=west]")'), null);
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=east]").disabled'), false);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
+12 -7
View File
@@ -197,8 +197,9 @@ 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("Use your models")');
await b.evaluate('document.querySelector("#provider-switch").click();true');
// settings-s5: the switch is the Use your models choice; choosing it writes at once.
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use your models")&&!document.querySelector("#models-yours").disabled');
await b.evaluate('document.querySelector("#models-yours").click();true');
await wait('posts.length===1');const payload=await b.evaluate('posts[0]');
assert.deepEqual(payload.plugins,{'model-provider':['cliproxy']});
const before=JSON.parse(readFileSync(file,'utf8')).plugins;
@@ -271,7 +272,7 @@ 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'], 'Stop using the model service', /can't see your models yet\. Your model service isn't set up 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','cliproxy'], 'Stop using your models', /can't see your models yet\. Your model service isn't set up 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 your models 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;});
@@ -287,13 +288,17 @@ test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disab
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(${JSON.stringify(label)})&&!!document.querySelector('[data-harness]')`);
// settings-s5: in force, the way back is Stop using your models; not in force, the Use your models choice.
const control=label==='Stop using your models'?'#models-stop':'#models-yours';
await wait(`!!document.querySelector(${JSON.stringify(control)})&&!document.querySelector(${JSON.stringify(control)}).disabled&&!!document.querySelector('[data-harness]')`);
// settings-s5 review P3-3: a Console with no organizations says "this business" mid-sentence.
assert.equal(await b.evaluate('document.querySelector("#models-source legend").textContent'),'Where this business gets its models');
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): the bus's cause reads as a plain line; its own words sit under Technical details.
assert.deepEqual(notices,[],providers.join(','));
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".routing-panel > details.routes-cause-detail p")].map(p=>p.textContent)'),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');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".routing-panel > details.routes-cause-detail p")].map(p=>p.textContent)'),label==='Stop using your models'?['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(${JSON.stringify(control)}).click();true`);
await wait('posts.length===1');const payload=await b.evaluate('posts[0]');
assert.deepEqual(payload.plugins,{'model-provider':next},providers.join(','));
const result=await call('plugins.set',payload);await b.evaluate(`window.answer(200,${JSON.stringify(result)});true`);
@@ -309,7 +314,7 @@ 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 does not need the model service: press Stop using the model service, then save again\. Draft kept\.$/],
[['fixture','cliproxy'], false, 'coder', 'model-catalogue-unavailable', /Nothing changed\. This change does not need your models: press Stop using your models, 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 service, or to stop using it when the change does not need it\. Draft kept\.$/],
@@ -187,7 +187,7 @@ test('settings-s4 review F2: a stand-in organization with its bus stopped reads
assert.equal(await text(STEP3), "The model service is set up. Gamma Home can't start: it uses stand-in models and its bus is stopped. Move it to your models under Use your models in every organization, then start its bus.");
assert.equal(await b.evaluate('document.querySelector("#setup-step-organizations").dataset.state'), 'bad');
const item = await b.evaluate('document.querySelector("#proxy-ride-fixtures li").firstChild.textContent.trim()');
assert.equal(item, "Gamma Home can't start: it uses stand-in models and its bus is stopped. Move it to the owner's models, then start its bus.");
assert.equal(item, "Gamma Home can't start: it uses stand-in models and its bus is stopped. Move it to your models under Use your models in every organization, then start its bus.");
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=gamma]").textContent'), 'Move Gamma Home');
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=gamma]").checkVisibility()'), true);
// The organizations that need nothing get no mark.
@@ -0,0 +1,455 @@
// #1873 settings slice 5 (DESIGN.md 3.4, 12 slice 5, mockups org-models and org-models-restart): an
// organization's Models page offers one choice, "Use your models" (the cliproxy model-provider module
// through plugins.set) or "Use its own model service" (Coming later), says from the plugins read which
// one is in force and what a switch changes, and switches both ways. Also the items slice 4 left: the
// Ride all lines name an organization by its display name, step 3 and the "can't start" mark agree
// before the first account, the sidebar marks follow a switch, a failed turn shows "Details:" once in
// Messages, the old Members addresses land on Agents, and Technical details shows the port and
// timeouts the status read carries.
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 LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
{ id: 'north', label: 'North Works', theme: 'cobalt', busHealthy: true },
];
const VIEW = {
business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi'], models: ['fixture-deterministic'],
providerModels: { 'fixture-deterministic': { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic' } },
levels: { pi: ['off', 'low'] }, instances: {}, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] },
};
async function orgFixture({ routes = {}, messages = [] } = {}) {
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: { chief: { definition: 'chief-of-staff' } }, projects: {} },
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: new Date().toISOString(), 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;
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, total: messages.length }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => ({ ...VIEW, ...(routes[id] ?? {}), business: id }), 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' } } };
}
// The model service is set up and answering. init.settings is what the status read carries after init
// (model-proxy admin.mjs initState).
const SERVICE_UP = { next: ['accounts'], init: { initialized: true, partial: false, problem: null, settings: { port: 18432, rotateGraceMinutes: 30, firstOutputSeconds: 90 }, files: [] },
release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] };
const SERVICE_DOWN = { ...SERVICE_UP, next: ['unit-start'], unit: { ...SERVICE_UP.unit, active: 'inactive', listening: false, healthy: false } };
const REV = n => String(n).repeat(64).slice(0, 64);
const pluginsRead = providers => ({ revision: REV('b'), available: { harness: ['pi'], 'model-provider': ['fixture', 'cliproxy'] }, plugins: { harness: ['pi'], 'model-provider': providers } });
// The instance owner's flags and every model service read and write, by path suffix (display.js
// scopes some reads under /api/orgs/<id>/). plugins.set merges the module lists the way the bus does
// and may carry a new setup status (__s5.afterSet). window.confirm answers yes and records its text.
const ownerStub = ({ service = SERVICE_UP, plugins = pluginsRead(['fixture']), accounts = [], posts = {}, afterSet = null, setStatus = 200 } = {}) => `(() => {
const real = window.fetch.bind(window);
window.__s5 = ${JSON.stringify({ service, plugins, accounts, posts, afterSet, setStatus })}; window.__sets = []; window.__writes = []; window.__confirms = [];
window.confirm = text => { window.__confirms.push(text); return true; };
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 !== 'GET' && path.endsWith('/proxy/plugins/set')) {
const body = JSON.parse(init.body); window.__sets.push({ path, body });
if (__s5.setStatus !== 200) return json({ error: 'plugins-refused', message: 'The bus refused the change (plugins-refused).' }, __s5.setStatus);
__s5.plugins = { ...__s5.plugins, revision: String(__s5.sets = (__s5.sets ?? 0) + 1).repeat(64).slice(0, 64), plugins: { ...__s5.plugins.plugins, ...body.plugins } };
if (__s5.afterSet) __s5.service = __s5.afterSet;
return json({ revision: __s5.plugins.revision, plugins: __s5.plugins.plugins });
}
if (method !== 'GET' && /\\/proxy\\//.test(path)) { window.__writes.push(path); const key = Object.keys(__s5.posts).find(k => path.endsWith(k)); const a = key ? __s5.posts[key] : { status: 500, body: { error: 'stub' } };
if (a.service) __s5.service = a.service; return json(a.body ?? {}, a.status ?? 200); }
if (method !== 'GET') return real(input, init);
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(__s5.plugins);
if (path.endsWith('/proxy/admin/status')) return json(__s5.service);
if (path.endsWith('/proxy/accounts')) return json({ accounts: __s5.accounts });
if (path.endsWith('/proxy/keys')) return json({ keys: [] });
if (path.endsWith('/triage/route')) return json({ route: null });
return real(input, init);
};
})();`;
async function setup(t, { path, viewport = [1440, 900], fixture = {}, stub = {} } = {}) {
const { organizations, agentLevels } = await orgFixture(fixture);
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, triage: null, 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: ownerStub(stub) });
await b.navigate(`http://127.0.0.1:${server.address().port}${path}`);
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<250;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error("wait failed: "+${JSON.stringify(expression)}+" HASH "+location.hash)})()`);
const text = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`);
const click = sel => b.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) throw Error("no ${sel.replace(/"/g, '')}"); el.click(); return true; })()`);
return { b, wait, text, click };
}
const mark = id => `document.querySelector('[data-workspace-org=${id}] .ws-dot')?.title`;
const STEP3 = '#setup-step-organizations [data-step-summary]';
// ---- Organization > Models --------------------------------------------------------------------
test('settings-s5: Acme Studio\'s models reads which choice is in force from the plugins read, switches to your models and back', { timeout: 90000 }, async t => {
const { b, wait, text, click } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-source") && document.querySelector("#models-in-force")?.textContent.includes("does not use")');
assert.equal(await text('#settings-page-title'), "Acme Studio's models");
assert.equal(await text('#models-source legend'), 'Where Acme Studio gets its models');
// Review P2-2: the header says where the models come from only from the plugins read.
assert.match(await text('.settings-helper'), /The models Acme Studio's agents use\. They come from its own organization file\./);
assert.doesNotMatch(await text('.settings-helper'), /your accounts/);
// Not in force: the radio is not checked, and the line says what is in force and what a switch changes.
assert.equal(await b.evaluate('document.querySelector("#models-yours").checked'), false);
assert.equal(await text('#models-in-force'), "Now: Acme Studio does not use your models. Its agents use only the models in its own organization file.");
assert.match(await text('#models-change'), /^Choose Use your models to switch\. Acme Studio's agents can then use the models your accounts offer\./);
// Use its own model service: dashed, disabled, Coming later.
assert.equal(await b.evaluate('document.querySelector("#models-own").disabled'), true);
assert.equal(await b.evaluate('document.querySelector("#models-own").closest("label").classList.contains("off")'), true);
assert.equal(await b.evaluate('document.querySelector("#models-own").closest("label").querySelector(".badge").textContent'), 'Coming later');
assert.match(await b.evaluate('document.querySelector("#models-own").closest("label").textContent'), /Planned, not built yet, so you can't choose it today\./);
assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#models-own").closest("label")).borderTopStyle'), 'dashed');
// The old button is gone.
assert.equal(await b.evaluate('!!document.querySelector("#provider-switch")'), false);
// Switch to your models: one write, the model-provider list only, with cliproxy added.
await click('#models-yours');
await wait('window.__sets.length === 1');
assert.deepEqual(await b.evaluate('window.__sets[0].body'), { revision: REV_B, plugins: { 'model-provider': ['fixture', 'cliproxy'] } });
await wait('document.querySelector("#models-in-force")?.textContent.startsWith("Now: Acme Studio uses your models")');
assert.equal(await b.evaluate('document.querySelector("#models-yours").checked'), true);
assert.match(await text('#models-receipt'), /^Saved\. Acme Studio uses your models\./);
assert.equal(await b.evaluate('document.querySelector("#models-receipt").classList.contains("settings-success")'), true);
assert.match(await text('#models-change'), /Stop using your models/);
// Review P2-4: focus moves to the Saved line.
await wait('document.activeElement?.id === "models-receipt"');
await wait('/They come from your accounts in Model setup\./.test(document.querySelector(".settings-helper")?.textContent ?? "")');
// And back: Stop using your models removes cliproxy and keeps the other module.
await click('#models-stop');
await wait('window.__sets.length === 2');
assert.deepEqual(await b.evaluate('window.__sets[1].body.plugins'), { 'model-provider': ['fixture'] });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use your models")');
assert.equal(await b.evaluate('document.querySelector("#models-yours").checked'), false);
assert.match(await text('#models-receipt'), /^Saved\. Acme Studio no longer uses your models\./);
assert.equal(await b.evaluate('!!document.querySelector("#models-stop")'), false);
await wait('document.activeElement?.id === "models-receipt"');
});
const REV_B = REV('b');
test('settings-s5: a refused switch says so and the page keeps the choice the read shows', { timeout: 90000 }, async t => {
const { b, wait, text, click } = await setup(t, { path: '/#/settings/routing?org=acme', stub: { setStatus: 409 } });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
await click('#models-yours');
await wait('window.__sets.length === 1 && /refused/.test(document.querySelector("#models-receipt")?.textContent ?? "")');
assert.equal(await text('#models-receipt'), 'Not changed. The bus refused the change (plugins-refused).');
assert.equal(await b.evaluate('document.querySelector("#models-yours").checked'), false);
assert.match(await text('#models-in-force'), /does not use your models/);
});
test('settings-s5: a stale page does not write, it shows the current choice first', { timeout: 90000 }, async t => {
const { b, wait, click } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
// Someone else switched Acme Studio on since the page read it.
await b.evaluate('__s5.plugins = { ...__s5.plugins, plugins: { ...__s5.plugins.plugins, "model-provider": ["fixture", "cliproxy"] } }; true');
await click('#models-yours');
await wait('document.querySelector("#models-in-force")?.textContent.startsWith("Now: Acme Studio uses your models")');
assert.equal(await b.evaluate('window.__sets.length'), 0);
assert.match(await b.evaluate('document.querySelector("#models-receipt").textContent'), /changed since this page read it/);
});
test('settings-s5: while the plugins read is out the choice waits, and a failed read says so with Read again', { timeout: 90000 }, async t => {
const { b, wait, text } = await setup(t, { path: '/#/settings/routing?org=acme', stub: { plugins: { broken: true } } });
await wait('/could not be read/.test(document.querySelector("#models-in-force")?.textContent ?? "")');
assert.equal(await text('#models-in-force'), "Which models Acme Studio uses could not be read.");
assert.equal(await b.evaluate('document.querySelector("#models-yours").disabled'), true);
assert.equal(await b.evaluate('!!document.querySelector("#models-read")'), true);
});
test('settings-s5: an organization that needs a restart shows the banner with Restart as the one primary, and the choice waits', { timeout: 90000 }, async t => {
const routes = { acme: { catalogue: { status: 'unavailable', notices: [], models: [] } } };
const { b, wait, text } = await setup(t, { path: '/#/settings/routing?org=acme', fixture: { routes }, stub: { plugins: pluginsRead(['fixture', 'cliproxy']) } });
await wait('document.querySelector("#routes-catalogue.banner [data-primary]") && document.querySelector("#models-in-force")?.textContent.startsWith("Now: Acme Studio uses")');
assert.match(await text('#routes-catalogue'), /Acme Studio can't see your models yet\./);
assert.match(await text('#routes-catalogue [data-primary]'), /Restart Acme Studio/);
// The banner sits above the choice.
assert.equal(await b.evaluate('!!(document.querySelector("#routes-catalogue").compareDocumentPosition(document.querySelector("#models-source")) & Node.DOCUMENT_POSITION_FOLLOWING)'), true);
assert.equal(await b.evaluate('document.querySelector("#models-yours").checked && document.querySelector("#models-yours").disabled'), true);
assert.equal(await text('#models-wait'), "You can change Acme Studio's models after it restarts.");
// Review P2-1: Stop using your models waits too: it is not offered until the restart.
assert.equal(await b.evaluate('!!document.querySelector("#models-stop")'), false);
// One primary: the routes Save is quiet.
assert.equal(await b.evaluate('document.querySelector("#routes-form [type=submit]").classList.contains("route-save-quiet")'), true);
});
// Review P2-3: a choice not in force says when the model service behind it is not set up or not
// answering, with a link to Model setup. The choice itself still writes.
test('settings-s5: Use your models says when the model service is not set up or not answering', { timeout: 90000 }, async t => {
for (const [service, line, link] of [
[{ ...SERVICE_UP, init: { initialized: false, partial: false, problem: null, files: [] } }, "Your model service isn't set up. Set it up in Model setup.", 'Set it up in Model setup'],
[SERVICE_DOWN, "Your model service isn't answering. Restart it in Model setup.", 'Restart it in Model setup'],
]) {
const { b, wait, text } = await setup(t, { path: '/#/settings/routing?org=acme', stub: { service } });
await wait('document.querySelector("#models-service") && document.querySelector("#models-in-force")?.textContent.includes("does not use")');
assert.equal(await text('#models-service'), line);
assert.deepEqual(await b.evaluate('[document.querySelector("#models-service a").textContent, document.querySelector("#models-service a").getAttribute("href")]'), [link, '#/settings/model-setup']);
assert.equal(await b.evaluate('document.querySelector("#models-yours").disabled'), false);
}
// Up and answering: no line.
const { b, wait } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
await new Promise(r => setTimeout(r, 300));
assert.equal(await b.evaluate('!!document.querySelector("#models-service")'), false);
});
// Review P3-1: while Use your models writes, the status line says Saving.
test('settings-s5: Use your models shows Saving while its write is out', { timeout: 90000 }, async t => {
const { b, wait, text, click } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
await b.evaluate(`(() => { const f = window.fetch; window.fetch = async (input, init = {}) => { if ((init.method || 'GET') !== 'GET' && String(input).endsWith('/proxy/plugins/set')) await new Promise(r => { window.__release = r; }); return f(input, init); }; return true; })()`);
await click('#models-yours');
await wait('typeof window.__release === "function" && document.querySelector("#models-receipt")?.textContent.trim() === "Saving…"');
assert.equal((await text('#models-receipt')).trim(), 'Saving…');
assert.equal(await b.evaluate('!!document.querySelector("#models-receipt .settings-spinner")'), true);
await b.evaluate('window.__release(); true');
await wait('/^Saved\./.test(document.querySelector("#models-receipt")?.textContent ?? "")');
});
// Recheck N1: the not set up line goes once the owner sets the service up and comes back to Models.
test('settings-s5: coming back to Models after setting the service up reads it again, and the not set up line goes', { timeout: 90000 }, async t => {
const { b, wait } = await setup(t, { path: '/#/settings/routing?org=acme', stub: { service: { ...SERVICE_UP, init: { initialized: false, partial: false, problem: null, files: [] } } } });
await wait('document.querySelector("#models-service") && document.querySelector("#models-in-force")?.textContent.includes("does not use")');
await b.evaluate(`window.__s5.service = ${JSON.stringify(SERVICE_UP)}; location.hash = '#/settings/agents?org=acme'; true`);
await wait('location.hash.startsWith("#/settings/agents") && !document.querySelector("#models-in-force") && document.querySelector("#settings-page-title")');
await b.evaluate(`location.hash = '#/settings/routing?org=acme'; true`);
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use") && !document.querySelector("#models-service")');
});
// Recheck N2: a switch left while it writes does not move focus on the next visit to Models.
test('settings-s5: leaving Models while a switch writes, the next visit focuses the page title, not the outcome line', { timeout: 90000 }, async t => {
const { b, wait, click } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
await b.evaluate(`(() => { const f = window.fetch; window.fetch = async (input, init = {}) => { if ((init.method || 'GET') !== 'GET' && String(input).endsWith('/proxy/plugins/set')) await new Promise(r => { window.__release = r; }); return f(input, init); }; return true; })()`);
await click('#models-yours');
await wait('typeof window.__release === "function"');
await b.evaluate(`location.hash = '#/settings/agents?org=acme'; true`);
await wait('location.hash.startsWith("#/settings/agents") && !document.querySelector("#models-in-force") && document.querySelector("#settings-page-title")');
await b.evaluate('window.__release(); true');
await wait('window.__sets.length === 1');
await new Promise(r => setTimeout(r, 400));
await b.evaluate(`location.hash = '#/settings/routing?org=acme'; true`);
await wait('document.querySelector("#models-in-force")?.textContent.includes("uses your models") && /^Saved\./.test(document.querySelector("#models-receipt")?.textContent ?? "")');
await new Promise(r => setTimeout(r, 300));
assert.equal(await b.evaluate('document.activeElement?.id'), 'settings-page-title');
});
// Review P3-2: a failed read before the write says nothing was written, and offers Read again.
test('settings-s5: a switch whose first read fails says Not changed, not Outcome unknown', { timeout: 90000 }, async t => {
const { b, wait, text, click } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
await b.evaluate('__s5.plugins = { broken: true }; true');
await click('#models-yours');
await wait('/^Not changed/.test(document.querySelector("#models-receipt")?.textContent ?? "")');
assert.equal(await text('#models-receipt'), 'Not changed. Nothing was written.');
assert.equal(await b.evaluate('window.__sets.length'), 0);
assert.equal(await b.evaluate('!!document.querySelector("#models-read")'), true);
assert.equal(await text('#models-in-force'), 'Which models Acme Studio uses could not be read.');
});
test('settings-s5: at 390 the Models page does not scroll sideways and the choice takes a visible focus', { timeout: 90000 }, async t => {
const { b, wait } = await setup(t, { path: '/#/settings/routing?org=acme', viewport: [390, 844] });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true);
await b.evaluate('document.querySelector("#models-yours").focus(); true');
assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none');
});
// Review P3-4: at 1440 the choice cards sit in the form column, not the whole card width.
test('settings-s5: at 1440 the choice sits in the form column', { timeout: 90000 }, async t => {
const { b, wait } = await setup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")');
const [choice, panel] = await b.evaluate('[document.querySelector("#models-source").getBoundingClientRect().width, document.querySelector(".routing-panel").getBoundingClientRect().width]');
assert.ok(choice <= 448 + 1 && panel > choice + 200, `${choice} in ${panel}`);
});
// ---- Sidebar marks follow a switch -------------------------------------------------------------
test('settings-s5: the sidebar marks read the setup status again after an organization stops using your models', { timeout: 90000 }, async t => {
const paused = { ...SERVICE_DOWN, ride: [{ id: 'acme', state: 'already' }] };
const after = { ...SERVICE_DOWN, ride: [{ id: 'acme', state: 'removed' }] };
const { wait, click } = await setup(t, { path: '/#/settings/routing?org=acme', stub: { service: paused, plugins: pluginsRead(['fixture', 'cliproxy']), afterSet: after } });
await wait(`${mark('acme')} === 'paused' && document.querySelector("#models-stop")`);
await click('#models-stop');
await wait(`window.__sets.length === 1 && ${mark('acme')} === 'bus running'`);
});
// ---- Model setup: display names, step 3 and the mark ------------------------------------------
test('settings-s5: Move, its result and the skipped lines name the organization by its display name, in the Ride line\'s words', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready' } }],
ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'bus-down' }, { id: 'gamma', state: 'fixture', running: false }] };
const moved = { ...service, ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'bus-down' }, { id: 'gamma', state: 'already' }] };
const accounts = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }];
const { b, wait, text, click } = await setup(t, { path: '/#/settings/model-setup', stub: { service, accounts, posts: { '/admin/ride-move': { body: { moved: true, model: 'Claude Sonnet 5.5', receipt: { op: 'ride-move', time: '2026-11-19T10:00:00.000Z' } }, service: moved } } } });
await wait('document.querySelector("[data-ride-move=gamma]")');
assert.equal(await text('#proxy-ride-skips li'), 'Skipped North Works: Its bus is not running. Start it, then ride again.');
const item = await b.evaluate('document.querySelector("#proxy-ride-fixtures li").firstChild.textContent.trim()');
assert.equal(item, "Gamma Home can't start: it uses stand-in models and its bus is stopped. Move it to your models under Use your models in every organization, then start its bus.");
// Step 3 uses the same words.
assert.match(await text(STEP3), /Gamma Home can't start: it uses stand-in models and its bus is stopped\. Move it to your models under Use your models in every organization, then start its bus\./);
await click('[data-ride-move=gamma]');
await wait('window.__confirms.length === 1');
assert.match(await b.evaluate('window.__confirms[0]'), /^Move Gamma Home to your models\?/);
await wait('/now uses/.test(document.querySelector("#proxy-ride-message")?.textContent ?? "")');
assert.equal(await text('#proxy-ride-message'), 'Gamma Home now uses Claude Sonnet 5.5. Start its bus when you are ready. It spends real tokens from now on.');
});
test('settings-s5: a Move that is refused names the organization by its display name', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, ride: [{ id: 'gamma', state: 'fixture', running: false }] };
const accounts = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }];
const { wait, text, click } = await setup(t, { path: '/#/settings/model-setup', stub: { service, accounts, posts: { '/admin/ride-move': { body: { moved: false, reason: 'bus-down' } } } } });
await wait('document.querySelector("[data-ride-move=gamma]")');
await click('[data-ride-move=gamma]');
await wait('/not moved/.test(document.querySelector("#proxy-ride-message")?.textContent ?? "")');
assert.equal(await text('#proxy-ride-message'), 'Gamma Home was not moved. Its bus is not running. Start it, then ride again.');
});
test('settings-s5: before the first account, step 3 names the organization the sidebar marks "can\'t start"', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, ride: [{ id: 'gamma', state: 'fixture', running: false }] };
const { b, wait, text } = await setup(t, { path: '/#/settings/model-setup', stub: { service, accounts: [] } });
await wait(`${mark('gamma')} === "can't start" && document.querySelector("#setup-step-organizations")?.dataset.state`);
await wait(`/Gamma Home/.test(document.querySelector(${JSON.stringify(STEP3)})?.textContent ?? "")`);
assert.equal(await text(STEP3), "Opens after your first account. Gamma Home can't start now: it uses stand-in models and its bus is stopped. After your first account, move it to your models under Use your models in every organization, then start its bus.");
// The card stays closed until there is an account to move it with, and its badge carries the mark's word.
assert.equal(await b.evaluate('document.querySelector("#setup-step-organizations").dataset.state'), 'wait');
assert.equal(await text('#setup-step-organizations [data-step-badge]'), "Can't start");
assert.equal(await b.evaluate('document.querySelector("#setup-step-organizations [data-step-badge]").classList.contains("badge-danger")'), true); // The empty account list reads as one line, not squeezed into the name column.
assert.equal(await b.evaluate('(() => { const li = document.querySelector("#proxy-accounts li.muted"); const r = document.createRange(); r.selectNodeContents(li); return li.textContent === "No accounts yet." && r.getClientRects().length === 1; })()'), true);
});
test('settings-s5: Technical details and Advanced show the port and timeouts the status read carries', { timeout: 90000 }, async t => {
const { b, wait } = await setup(t, { path: '/#/settings/model-setup' });
await wait('document.querySelector("#proxy-setup-state dd")');
const rows = await b.evaluate('Object.fromEntries([...document.querySelectorAll("#proxy-setup-state dt")].map(dt => [dt.textContent, dt.nextElementSibling.textContent]))');
assert.equal(rows.Initialized, 'Yes, port 18432, wait for a first answer 90 seconds, old key kept 30 minutes after a new one');
const advanced = await b.evaluate('Object.fromEntries([...document.querySelectorAll("#proxy-setup-settings dt")].map(dt => [dt.textContent, dt.nextElementSibling.textContent]))');
assert.deepEqual(advanced, { Port: '18432', 'Wait for a first answer': '90 seconds', 'Old key kept after a new one': '30 minutes' });
});
test('settings-s5: timeouts init left at the default read as the default', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, init: { ...SERVICE_UP.init, settings: { port: 18432, rotateGraceMinutes: null, firstOutputSeconds: null } } };
const { b, wait } = await setup(t, { path: '/#/settings/model-setup', stub: { service } });
await wait('document.querySelector("#proxy-setup-state dd")');
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup-state dt")].find(dt => dt.textContent === "Initialized").nextElementSibling.textContent'),
'Yes, port 18432, wait for a first answer: the default, old key kept after a new one: the default');
const advanced = await b.evaluate('Object.fromEntries([...document.querySelectorAll("#proxy-setup-settings dt")].map(dt => [dt.textContent, dt.nextElementSibling.textContent]))');
assert.deepEqual(advanced, { Port: '18432', 'Wait for a first answer': 'The default', 'Old key kept after a new one': 'The default' });
});
// ---- Messages and the old Members addresses ---------------------------------------------------
test('settings-s5: a failed turn in Messages shows its cause, and "Details:" once', { timeout: 90000 }, async t => {
const messages = [{ id: 'm1', from_role: 'chief', to_role: 'human', class: 'reply', at: '2026-11-19T10:00:00.000Z', read: true,
body: 'The turn failed: Acme Studio can\'t see your models yet. Restart it in Settings.\nDetails: model-catalogue-unavailable' }];
const { b, wait } = await setup(t, { path: '/#/orgs/acme/messages', fixture: { messages } });
await wait('document.querySelector(".s1-message")');
const shown = await b.evaluate('document.querySelector(".s1-message").textContent');
assert.equal(shown.match(/Details:/g)?.length, 1, shown);
assert.match(shown, /^The assistant couldn't reply: Acme Studio can't see your models yet\. Restart it in Settings\.Details: model-catalogue-unavailable$/);
});
test('settings-s5: a failed turn without a Details part keeps the general line', { timeout: 90000 }, async t => {
const messages = [{ id: 'm1', from_role: 'chief', to_role: 'human', class: 'reply', at: '2026-11-19T10:00:00.000Z', read: true, body: 'The turn failed: spawn-refused' }];
const { b, wait } = await setup(t, { path: '/#/orgs/acme/messages', fixture: { messages } });
await wait('document.querySelector(".s1-message")');
assert.equal(await b.evaluate('document.querySelector(".s1-message").textContent'), "The assistant couldn't reply. Try again, or check Agents.Details: spawn-refused");
});
test('settings-s5: #/settings/members and #/orgs/<id>/settings/members land on that organization\'s Agents page', { timeout: 90000 }, async t => {
const { b, wait } = await setup(t, { path: '/#/orgs/north/settings/members' });
await wait('location.hash === "#/settings/agents?org=north" && document.querySelector("#settings-nav a[href=\'#/settings/agents?org=north\'][aria-current=page]")');
await b.evaluate('location.hash = "#/settings/members"; true');
await wait('location.hash === "#/settings/agents?org=north" && document.querySelector("#settings-page-title")?.textContent === "Agents"');
});
// Shots for the build report, beside the mockups: run with MOSAIC_UX_SHOTS=<dir>. Each page is shot whole
// at 390 and 1440, light and dark, and measured: nothing scrolls sideways, and every control Tab reaches
// shows a focus ring.
test('shots', { timeout: 900000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => {
const { mkdir, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const dir = process.env.MOSAIC_UX_SHOTS; await mkdir(dir, { recursive: true });
const settle = () => new Promise(r => setTimeout(r, 1000));
const reasons = [
{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'unavailable', priority: 2, reason: 'The account is out of usage. It resets at 2026-11-20 05:00 UTC. Wait until then, or add another account.' },
{ accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'error', priority: 1, reason: 'The account needs to sign in again. Sign in again, or add another account.' },
{ accountId: 'a3', provider: 'codex', displayName: 'Codex work', status: 'active', priority: 0 },
];
const failed = [{ id: 'm1', from_role: 'chief', to_role: 'human', class: 'reply', at: '2026-11-19T10:00:00.000Z', read: true,
body: 'The turn failed: Acme Studio can\'t see your models yet. Restart it in Settings.\nDetails: model-catalogue-unavailable' }];
const PAGES = [
{ name: 'org-models', path: '/#/settings/routing?org=acme', ready: 'document.querySelector("#models-in-force")?.textContent.includes("does not use")' },
{ name: 'org-models-riding', path: '/#/settings/routing?org=acme', ready: 'document.querySelector("#models-in-force")?.textContent.includes("does not use")',
after: async (b, wait) => { await b.evaluate('document.querySelector("#models-yours").click(); true'); await wait('/^Saved/.test(document.querySelector("#models-receipt")?.textContent ?? "")'); } },
{ name: 'org-models-not-set-up', path: '/#/settings/routing?org=acme', stub: { service: { ...SERVICE_UP, init: { initialized: false, partial: false, problem: null, files: [] } } },
ready: 'document.querySelector("#models-service") && document.querySelector("#models-in-force")?.textContent.includes("does not use")' },
{ name: 'org-models-restart', path: '/#/settings/routing?org=acme', fixture: { routes: { acme: { catalogue: { status: 'unavailable', notices: [], models: [] } } } }, stub: { plugins: pluginsRead(['fixture', 'cliproxy']) },
ready: 'document.querySelector("#routes-catalogue.banner [data-primary]") && document.querySelector("#models-in-force")?.textContent.startsWith("Now: Acme Studio uses")' },
{ name: 'account-reasons', path: '/#/settings/model-setup?step=accounts', stub: { accounts: reasons }, ready: 'document.querySelectorAll("#proxy-accounts .account-reason").length === 2' },
{ name: 'step3-cant-start', path: '/#/settings/model-setup', stub: { service: { ...SERVICE_UP, ride: [{ id: 'gamma', state: 'fixture', running: false }] }, accounts: [] },
ready: `/Gamma Home/.test(document.querySelector(${JSON.stringify(STEP3)})?.textContent ?? "")` },
{ name: 'technical-details', path: '/#/settings/model-setup', ready: 'document.querySelector("#proxy-setup-state dd")',
after: async b => { await b.evaluate('document.querySelector("#proxy-setup-advanced").open = true; document.querySelector("#proxy-setup-tech").open = true; true'); } },
{ name: 'messages-details', path: '/#/orgs/acme/messages', fixture: { messages: failed }, ready: 'document.querySelector(".s1-message")' },
];
const report = [];
for (const page of PAGES) for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) {
const { b, wait } = await setup(t, { path: page.path, fixture: page.fixture, stub: page.stub, viewport: [width, width === 390 ? 844 : 900] });
await b.call('Emulation.setScrollbarsHidden', { hidden: true });
await b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });
await wait(`(${page.ready}) && !!window.MosaicAppearance`);
await b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`);
if (page.after) await page.after(b, wait, width);
await settle();
const sideways = await b.evaluate('document.documentElement.scrollWidth > document.documentElement.clientWidth');
const noRing = [], seen = new Set();
for (let i = 0; i < 120; i++) {
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
const r = await b.evaluate(`(() => { const e = document.activeElement; if (!e || e === document.body) return null; const cs = getComputedStyle(e);
const ring = (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none');
return { key: e.id || e.getAttribute('href') || e.tagName + ':' + (e.textContent || '').trim().slice(0, 30), ring }; })()`);
if (!r || seen.has(r.key)) break; seen.add(r.key);
if (!r.ring) noRing.push(r.key);
}
await b.evaluate('document.activeElement?.blur(); window.scrollTo(0, 0); true'); await settle();
const shot = `${page.name}-${width}-${scheme}.png`;
let metrics = await b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize;
await b.viewport(width, Math.ceil(size.height)); await settle();
metrics = await b.call('Page.getLayoutMetrics'); size = metrics.cssContentSize || metrics.contentSize;
const { data } = await 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, sideways, noRing });
await b.close();
}
await writeFile(join(dir, 'measure.json'), JSON.stringify(report, null, 1));
for (const r of report) {
assert.equal(r.sideways, false, `${r.shot} scrolls sideways`);
assert.deepEqual(r.noRing, [], `${r.shot}: controls with no visible focus ring`);
}
});