From af1bbf7859abc36b6e2daed280dd4290c4ee0a06 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:38:47 -0600 Subject: [PATCH 01/14] =?UTF-8?q?feat(webui):=20settings-s4=20nav=20and=20?= =?UTF-8?q?addresses:=20Settings=20nav=20in=20four=20groups=20(You;=20Your?= =?UTF-8?q?=20models=20with=20Model=20setup=20and,=20for=20the=20instance?= =?UTF-8?q?=20owner,=20Triage;=20All=20organizations;=20This=20organizatio?= =?UTF-8?q?n=20with=20an=20organization=20picker=20above=20Models,=20Agent?= =?UTF-8?q?s,=20Launch=20limits,=20Token=20use,=20Assistant=20and=20Organi?= =?UTF-8?q?zation=20file);=20an=20organization's=20pages=20live=20at=20#/s?= =?UTF-8?q?ettings/=3Forg=3D=20and=20the=20old=20#/orgs//set?= =?UTF-8?q?tings/=20form=20lands=20there;=20#/settings/model-proxy?= =?UTF-8?q?=20opens=20Model=20setup=20at=20#/settings/model-setup;=20the?= =?UTF-8?q?=20phone=20section=20button=20reads=20"=20=C2=B7=20"?= =?UTF-8?q?;=20the=20breadcrumb=20names=20the=20organization=20on=20its=20?= =?UTF-8?q?Settings=20pages;=20no=20Members=20row=20(#1873,=20lane=20setti?= =?UTF-8?q?ngs-s4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webui/src/public/brand.js | 4 +- packages/webui/src/public/bus.js | 55 ++++++++++++++----- packages/webui/src/public/display.js | 31 +++++++++-- packages/webui/src/public/triage-settings.js | 2 +- .../tests/agent-levels-edit-browser.test.mjs | 2 +- .../webui/tests/org-switch-browser.test.mjs | 9 ++- .../webui/tests/settings-s1-browser.test.mjs | 12 ++-- .../tests/triage-settings-browser.test.mjs | 2 +- packages/webui/tests/views.test.mjs | 3 +- 9 files changed, 86 insertions(+), 34 deletions(-) diff --git a/packages/webui/src/public/brand.js b/packages/webui/src/public/brand.js index 9c729f475..02a8d9e9c 100644 --- a/packages/webui/src/public/brand.js +++ b/packages/webui/src/public/brand.js @@ -183,7 +183,9 @@ function breadcrumbs() { draw(); // SP1: every page inside an organization says which one, after the dashboard: Dashboard / Acme / ... - const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) ? window.MosaicOrg : null; + // #1873 settings slice 4: an organization's Settings page names it with ?org=, so it says which one too. + const page = /^#\/settings\/([^/?]+)/.exec(location.hash)?.[1], orgSettings = !!page && !!window.MosaicOrg?.orgPage?.(page) && /[?&]org=/.test(location.hash); + const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) || orgSettings ? window.MosaicOrg : null; if (box && org?.id && !box.querySelector('[data-crumb-org]') && !/^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) box.insertAdjacentHTML('afterbegin', `Dashboard${escape(org.label)}`); // SP7: a trail with nothing above the page only repeats the page's heading, so the heading names it once. if (!box) return; diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index f7cb69ae7..5e4082fea 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1329,7 +1329,7 @@ const cause=window.MosaicConsole?.catalogueCause?.(label,catalogue?.notices,catalogue?.reason)??null; const words=!cause?'':cause.plain?`
Technical details

${txt(cause.detail)}

`:`

${txt(cause.detail)}

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

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

${words}`; if(owner)readService(); const recheck=''; @@ -1478,21 +1478,36 @@ }); // Organizations is writable when the server allows org setup, which it does in organization mode where send is off. const readonlyPage = page => !['appearance','business','console','triage'].includes(page) && !(page === 'organizations' && orgSetup) && !canSend && !isTester; - const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model setup'],['triage','Triage'],['console','Console'],['about','About']]; - function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`), dot='unsaved changes';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);} + const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-setup','Model setup'],['triage','Triage'],['console','Console'],['about','About']]; + function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href^="#/settings/${page}"]`), dot='unsaved changes';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);} + // #1873 settings slice 4 (DESIGN.md section 2): four groups. You; Your models; All organizations; + // This organization, whose heading holds the organization picker. An organization's own pages carry + // ?org= so the address base never changes with the organization. Testers keep their short list. + const ORG_SETTINGS = ['routing','agents','limits','tokens','assistant','business','names']; function settingsShell(page, body, helper='') { - const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages.filter(([id])=>id!=='triage'||triageOwner); - const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; + const org = window.MosaicOrg, orgId = org?.id ?? null, orgName = orgId ? (org.label || orgId) : null; + const scoped = id => ORG_SETTINGS.includes(id); + const href = id => `#/settings/${id}${orgId && scoped(id) ? `?org=${enc(orgId)}` : ''}`; + const labels = isTester ? Object.fromEntries([['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']]) : { appearance:'Appearance', 'model-setup':'Model setup', triage:'Triage', organizations:'Organizations', console:'Console', about:'About', routing: org ? 'Models' : 'Routing', agents:'Agents', limits:'Launch limits', tokens:'Token use', assistant:'Assistant', business: org ? 'Organization file' : 'Business' }; + const label = labels[page] || 'Appearance'; const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft()))||(id==='triage'&&window.MosaicTriageRoute?.hasDraft()); const dot='unsaved changes'; - const links=pages.map(([id,name],i)=>`${i===0?'
Your browser
':i===1?'
This instance
':''}${name}${isDirty(id)?dot:''}`).join('') + (!isTester ? '
Members and invites not built
' : ''); - return `${head('Settings','Your browser and this instance.')}

${label}

${helper}

${readonlyPage(page)?'

Read only. Saving requires signed-in send mode.

':''}${body}
`; + const a = id => `${labels[id]}${isDirty(id)?dot:''}`; + const group = (title, ids) => ids.length ? `
${title}
${ids.map(a).join('')}` : ''; + const rows = org ? org.rows() : []; + const picker = org && rows.length ? `
` : `
${org ? 'This organization' : 'This business'}
`; + const links = isTester ? group('Settings', ['appearance','business','routing','agents','names']) + : group('You', ['appearance']) + group('Your models', ['model-setup', ...(triageOwner ? ['triage'] : [])]) + group(org ? 'All organizations' : 'This instance', ['organizations','console','about']) + + picker + ['routing','agents','limits','tokens','assistant','business'].map(a).join(''); + const where = orgName && scoped(page) ? `${txt(orgName)} · ` : ''; + const title = org && page === 'routing' && orgName ? `${txt(orgName)}'s models` : label; + return `${head('Settings','Your models, your organizations and this browser.')}

${title}

${helper}

${readonlyPage(page)?'

Read only. Saving requires signed-in send mode.

':''}${body}
`; } async function settingsView(get, page='appearance') { if (page==='business') return businessView(get); if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.'); if (page==='organizations') { await configRead; return settingsShell(page,window.MosaicOrgCreate.markup,'Create an organization from the template, edit it, and finish its setup. Each step names the command it equals.'); } - if (page==='model-proxy') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Your model service, the accounts it uses and their priority, and the keys agents use to reach it.'); } + if (page==='model-setup') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Your model service, your accounts and the models they offer. Every organization uses them, including organizations you add later, unless it sets up its own.'); } // #1873 triage-settings: Settings > Triage (triage-settings.js), the instance owner's only; anyone else gets no page. if (page==='triage') { await configRead; if (!triageOwner || !window.MosaicTriageRoute) return notFound(); return settingsShell(page,await window.MosaicTriageRoute.section(),'The model Triage uses, what runs it, and its daily token limit. Only the instance owner sees this page.'); } // F3: Settings > Console (console-restart.js). The server checks the owner, Origin and trail. @@ -1508,12 +1523,20 @@ if (page==='routing') { await window.MosaicConsole?.ready; try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch); const notify = typeof n.binding==='string' ? `${txt(n.binding)}` : n.refused ? `Could not be read: ${txt(n.refused)}` : 'None set'; - const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
Address
${txt(s.address)||'unknown'}
Release
${txt(s.release)||'unknown'}
Business
${txt(s.business)||none}
Board
${txt(s.board)||'unknown'}
Notifier binding
${notify}
`, 'model-proxy':()=>'
Open Model setup
'}; + const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
Address
${txt(s.address)||'unknown'}
Release
${txt(s.release)||'unknown'}
Business
${txt(s.business)||none}
Board
${txt(s.board)||'unknown'}
Notifier binding
${notify}
`}; 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.'}; return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`); } let settingsFocusDisclosure=false; - document.addEventListener('change', e => { if (e.target.id === 'org-picker') window.MosaicOrg?.switchTo(e.target.value); }); + document.addEventListener('change', e => { if (e.target.id === 'org-picker') window.MosaicOrg?.switchTo(e.target.value); else if (e.target.id === 'org-pick') pickSettingsOrg(e.target.value); }); + // Slice 4: the picker re-reads the page in place. An organization's page keeps its page with the new + // ?org=; any other Settings page stays where it is and its organization links follow the pick. + function pickSettingsOrg(id) { + const org = window.MosaicOrg; if (!org || !id) return; + const [path, query = ''] = routeOf().split('?'), page = path.split('/')[2] || 'appearance'; + const rest = query.split('&').filter(p => p && !p.startsWith('org=')); + location.hash = ORG_SETTINGS.includes(page) ? `#/settings/${page}?${[`org=${enc(id)}`, ...rest].join('&')}` : `#/orgs/${enc(id)}${path}${query ? `?${query}` : ''}`; + } document.addEventListener('click', e=>{const b=e.target.closest?.('#settings-disclosure');if(b){b.setAttribute('aria-expanded',String(b.getAttribute('aria-expanded')!=='true'));return;} if(e.target.closest?.('#settings-nav a')) { const b=$('settings-disclosure'); if(b?.getAttribute('aria-expanded')==='true') {b.setAttribute('aria-expanded','false');settingsFocusDisclosure=true;b.focus();} }}); document.addEventListener('keydown', e=>{if(e.key==='Escape' && $('settings-disclosure')?.getAttribute('aria-expanded')==='true'){e.preventDefault();$('settings-disclosure').setAttribute('aria-expanded','false');$('settings-disclosure').focus();}}); @@ -1739,7 +1762,7 @@ const why = window.MosaicConsole?.orgDownReason?.(id, label, v => { const p = document.querySelector(`[data-org-down="${CSS.escape(id)}"] [data-org-down-why]`); if (p) { p.innerHTML = whyText(v); p.hidden = !p.innerHTML; } }) ?? null; // settings-p3 (re-check 3 P3-4): after a refusal a restart can't clear, Restart is not the primary. const restart = window.MosaicConsole?.orgRestartButton?.(id, { name: label, primary: !(window.MosaicConsole?.orgRefusal?.(id)?.restart === false || why?.restart === false) }) || ''; - return settingsShell(page, `

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

`); + return settingsShell(page, `

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

`); } return settingsShell(page, ``); } @@ -1881,7 +1904,7 @@ // On the cross-organization pages a filter or selection changes only the query: that is a // repaint of the same page, not a navigation (no loading view, focus and scroll kept). const samePage = drawerPage(path) && typeof shown === 'string' && shown.split('?')[0] === path; - if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;} + if (path !== '/settings/model-setup' && proxyCleanup) {proxyCleanup();proxyCleanup=null;} 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; @@ -1897,6 +1920,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 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 // stops their polling. It is a system page: an organization's address for it, and the old // Side by side address, land on `#/assistant`. @@ -1979,7 +2004,7 @@ sections(path); schedule(); return; } - if (path === '/settings/model-proxy' && shown === route && !navigated) return; + if (path === '/settings/model-setup' && shown === route && !navigated) return; if (path === '/settings/triage' && shown === route && !navigated) return; if (path === '/settings/organizations' && shown?.split('?')[0] === path && !navigated) return; if (($('agent-dialog')?.open || document.querySelector('.agent-more[aria-expanded=true]')) && !navigated) { schedule(); return; } @@ -1987,7 +2012,7 @@ let html, state = 'fresh'; const live = reader(true); try { - if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/triage','/settings/organizations'].includes(path)) { + if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-setup','/settings/triage','/settings/organizations'].includes(path)) { try { await live('messages'); } catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; } } @@ -2013,7 +2038,7 @@ if (path.startsWith('/docs/')) paintDoc(); if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]')); if ($('bus-view').querySelector('[data-org-down]')) { const down = $('bus-down'); if (down) down.hidden = true; } - if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount(); + if (path === '/settings/model-setup') { proxyCleanup?.(); proxyCleanup=window.MosaicProxy.mount(); } if (path === '/settings/organizations') orgCleanup=window.MosaicOrgCreate.mount(); sections(path); const h1 = $('bus-view').querySelector('h1'); diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 7c9812507..2ca821ae2 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -17,7 +17,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // #1873 settings slice 1 (section 5): a fix link goes only to a Settings page that exists for this viewer. // Settings > Triage exists only where /api/config says proxyAdmin (bus.js triageOwner); Model setup always does. const TRIAGE_FIX = { href: '#/settings/triage', label: 'Open Triage settings' }; - const SERVICE_FIX = { href: '#/settings/model-proxy', label: 'Open Model setup' }; + const SERVICE_FIX = { href: '#/settings/model-setup', label: 'Open Model setup' }; const pageExists = fix => fix !== TRIAGE_FIX || config?.proxyAdmin === true; const fixLink = fix => { const a = el('a', 'triage-fix', fix.label); a.href = fix.href; a.addEventListener('click', () => close()); return a; }; // An organization's name from the Console's own list, or its id when the list does not hold it. @@ -369,7 +369,12 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( (() => { const nativeFetch = window.fetch.bind(window); // SP13: the organization segment stops at `/` or `?`, so `#/orgs/?agent=…` names . - const orgOf = hash => /^#\/orgs\/([^/?]+)/.exec(hash)?.[1] ?? null; + // #1873 settings slice 4: Settings pages keep one base, #/settings/. An organization's own + // pages name it with ?org=; the old #/orgs//settings/ form still lands there. + const ORG_PAGES = new Set(['routing', 'agents', 'limits', 'tokens', 'assistant', 'business', 'names']); + const settingsOf = hash => /^#\/(?:orgs\/[^/?]+\/)?settings\/([^/?]+)/.exec(hash)?.[1] ?? null; + const orgParam = hash => { const q = hash.split('?')[1]; const v = q ? new URLSearchParams(q).get('org') : null; return v ? encodeURIComponent(v) : null; }; + const orgOf = hash => /^#\/orgs\/([^/?]+)/.exec(hash)?.[1] ?? (/^#\/settings\//.test(hash) ? orgParam(hash) : null); const atLoad = orgOf(location.hash); if (!atLoad && !document.documentElement.hasAttribute('data-organizations')) return; // current: the scoping organization as its hash segment. settled: false only while the first @@ -390,9 +395,23 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // organization's agents; `#/orgs//agents` is that table for one organization. SP4: `#/tasks` is // one task board for every organization; `#/orgs//tasks` is that board, scoped to one. // SP6: `#/assistant` is the Assistant page, threads of any organization side by side. - const system = hash => { const bare = tail(hash).split('?')[0]; return bare === '/dashboard' || (!orgOf(hash) && (bare === '/inbox' || bare === '/agents' || bare === '/tasks' || bare === '/assistant')); }; + // A Settings page that is not an organization's is a system page at #/settings/. The old + // #/orgs//settings/ form of one keeps its organization, as it did before slice 4. + const system = hash => { const bare = tail(hash).split('?')[0], page = settingsOf(hash); return bare === '/dashboard' || bare === '/settings' || (page !== null && !ORG_PAGES.has(page) && !/^#\/orgs\//.test(hash)) || (!orgOf(hash) && (bare === '/inbox' || bare === '/agents' || bare === '/tasks' || bare === '/assistant')); }; + // An organization page's query gets org= first; the prefix, when there is one, wins over ?org=. + const withOrg = (query, seg) => [`org=${seg}`, ...query.split('&').filter(p => p && !p.startsWith('org='))].join('&'); const normalize = (hash, seg = current) => { const path = tail(hash), bare = path.split('?')[0], named = /^#\/orgs\/([^/?]+)$/.exec(hash.split('?')[0])?.[1]; + const page = settingsOf(hash); + if (bare === '/settings') return `#/settings${path.slice(bare.length)}`; + if (page !== null && /^\/settings\/[^/?]+$/.test(bare)) { + const query = path.slice(bare.length + 1), prefix = /^#\/orgs\/([^/?]+)/.exec(hash)?.[1]; + // An old prefix on a system page still names an organization (a switch, or Organizations' + // finish-setup link), and Organizations reads its own ?org=, so that address is kept as it is. + if (!ORG_PAGES.has(page)) return prefix ? hash : `#/settings/${page}${query ? `?${query}` : ''}`; + const org = prefix ?? orgParam(hash) ?? seg; + return org ? `#/settings/${page}?${prefix || !orgParam(hash) ? withOrg(query, org) : query}` : `#/settings/${page}${query ? `?${query}` : ''}`; + } if (named) return `#/orgs/${named}/organization${hash.slice(hash.split('?')[0].length)}`; if (bare === '/' || bare === '/dashboard') return `#/dashboard${path.slice(bare.length)}`; return orgOf(hash) || !seg || system(hash) ? hash : `#/orgs/${seg}${path}`; @@ -501,7 +520,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( dialog.innerHTML = '

You have an unsaved draft. Stay here or discard it and continue.

'; document.body.append(dialog); const close = () => { dialog.close(); dialog.remove(); }; - const stay = () => { const picker = document.getElementById('org-picker'); if (picker && current) picker.value = decodeURIComponent(current); close(); }; + const stay = () => { for (const picker of document.querySelectorAll('#org-picker, #org-pick')) if (current) picker.value = decodeURIComponent(current); close(); }; dialog.querySelector('[data-stay]').onclick = stay; dialog.querySelector('[data-discard]').onclick = () => { close(); discard(); skipGuard = true; location.hash = next; }; dialog.addEventListener('cancel', e => { e.preventDefault(); stay(); }); @@ -537,10 +556,12 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // SP3: whether this address is a system page (no organization's), for the shell's theme scope. system: () => system(location.hash), switchTo: next => { const path = route().split('?')[0]; location.hash = `#/orgs/${encodeURIComponent(next)}${path === '/dashboard' || path === '/' ? '/organization' : route()}`; }, + // Slice 4: whether this Settings page is an organization's own (it carries ?org=). + orgPage: page => ORG_PAGES.has(page), }); Object.defineProperty(window, 'MosaicOrg', { configurable: true, enumerable: true, get: () => (current || !settled ? api : undefined) }); })(); -if (document.documentElement.hasAttribute('data-settings-proxy-document') && !location.hash) location.hash = '#/settings/model-proxy'; +if (document.documentElement.hasAttribute('data-settings-proxy-document') && !location.hash) location.hash = '#/settings/model-setup'; /* Browser-local sidebar density. No authority or project data is stored here. */ (() => { // #1873 SP1: the key follows the open organization, read again when it changes. diff --git a/packages/webui/src/public/triage-settings.js b/packages/webui/src/public/triage-settings.js index 6af4d58ce..6a63be4b8 100644 --- a/packages/webui/src/public/triage-settings.js +++ b/packages/webui/src/public/triage-settings.js @@ -55,7 +55,7 @@ + (d.harness && !hs.includes(d.harness) ? `` : '') + hs.map(h => ``).join(''); const status = data?.choices?.status; - const catalogue = status === 'ready' ? '' : `

No organization can show your models right now, so no route can be saved. Open Model setup to see why each organization can't see your models.

`; + const catalogue = status === 'ready' ? '' : `

No organization can show your models right now, so no route can be saved. Open Model setup to see why each organization can't see your models.

`; const conflictButton = conflict ? ' ' : ''; return `${catalogue}
` + `` diff --git a/packages/webui/tests/agent-levels-edit-browser.test.mjs b/packages/webui/tests/agent-levels-edit-browser.test.mjs index 31c661bdd..663fa1872 100644 --- a/packages/webui/tests/agent-levels-edit-browser.test.mjs +++ b/packages/webui/tests/agent-levels-edit-browser.test.mjs @@ -125,7 +125,7 @@ test('both drafts survive a refresh render and the other form\'s save; a draft k assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#agent-levels-root-form .filters")).display'), 'grid', 'the level forms keep the Settings form layout'); await type(b, 'agent-levels-root-form', { name: 'drafted', vars: 'limits.network=none' }); await type(b, 'agent-levels-project-form', { name: 'helper', form: 'narrow', vars: 'limits.tools=read' }); - assert.equal(await b.evaluate('!!document.querySelector("#settings-nav a[href$=\'settings/agents\'] .settings-dot")'), true, 'the nav marks unsaved changes'); + assert.equal(await b.evaluate('!!document.querySelector("#settings-nav a[href^=\'#/settings/agents\'] .settings-dot")'), true, 'the nav marks unsaved changes'); // A full Settings render, as the ten-second poll does: the edit box is a new node, the drafts are in it. await b.evaluate('document.getElementById("agent-levels-edit").dataset.old = "1"; document.getElementById("refresh").click()'); await wait('document.getElementById("agent-levels-edit") && !document.getElementById("agent-levels-edit").dataset.old'); diff --git a/packages/webui/tests/org-switch-browser.test.mjs b/packages/webui/tests/org-switch-browser.test.mjs index 223721882..ba6760b1f 100644 --- a/packages/webui/tests/org-switch-browser.test.mjs +++ b/packages/webui/tests/org-switch-browser.test.mjs @@ -145,7 +145,8 @@ test('sidebar lists organizations and navigating changes the route and header', await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelectorAll('[data-workspace-org]').length===2 && document.querySelector('#settings-page-title'))return;await new Promise(r=>setTimeout(r,30))}throw Error('Organizations did not appear')})()`); await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent==='Alpha')return;await new Promise(r=>setTimeout(r,30))}throw Error('organization crumb missing')})()`); assert.equal(await b.evaluate(`document.querySelector('#current-organization')`), null, 'the header does not name an organization'); - assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization'); + // settings slice 4: the page's nav label and title is Organization file. + assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization file'); await b.evaluate('window.__sameDocument = true'); assert.equal(await b.evaluate(`!!document.querySelector('#org-picker')`), false); assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-workspace-org]')].map(o=>o.dataset.workspaceOrg)`), ['alpha', 'beta']); @@ -194,7 +195,8 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy await b.evaluate(`document.querySelector('[data-workspace-org=beta] a').click()`); await wait('!!document.querySelector("dialog[open] [data-stay]")'); await b.evaluate(`document.querySelector('[data-stay]').click()`); - assert.match(await b.evaluate('location.hash'), /^#\/orgs\/alpha\//); + // settings slice 4: an organization's Settings page names it with ?org=. + assert.equal(await b.evaluate('location.hash'), '#/settings/business?org=alpha'); assert.equal(await b.evaluate(`window.MosaicOrg.id`), 'alpha'); await b.evaluate(`location.hash='#/chat/threads/${thread}'`); await wait('!!document.querySelector("#chat-body")'); @@ -204,7 +206,8 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy await b.evaluate(`document.querySelector('[data-discard]').click()`).catch(() => {}); let switched = false; for (let i = 0; i < 150 && !switched; i++) { - try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Beta'`); } catch {} + // settings slice 4: the old address lands on the organization's Settings page with ?org=, and its crumb names it. + try { switched = await b.evaluate(`location.hash === '#/settings/business?org=beta' && document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Beta'`); } catch {} if (!switched) await new Promise(r => setTimeout(r, 30)); } assert.equal(switched, true); diff --git a/packages/webui/tests/settings-s1-browser.test.mjs b/packages/webui/tests/settings-s1-browser.test.mjs index 37bbf5f28..813a3f5da 100644 --- a/packages/webui/tests/settings-s1-browser.test.mjs +++ b/packages/webui/tests/settings-s1-browser.test.mjs @@ -170,7 +170,7 @@ test('settings-s1 B1: a model-key-collision catalogue says two models share a na assert.match(line, /Two of your models get the same short name, so Acme Studio can't tell them apart\. A restart won't change that\./); assert.doesNotMatch(line, /Restart Acme Studio|model proxy/i); assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null, 'a restart comes back to the same state'); - assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a[href=\'#/settings/model-proxy\']")?.textContent'), 'Open Model setup'); + assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a[href=\'#/settings/model-setup\']")?.textContent'), 'Open Model setup'); }); test('settings-s1 B1: a set fence reads as a restart to finish, not as a stopped service; a status read that fails offers Check again', { timeout: 90000 }, async t => { @@ -180,7 +180,7 @@ test('settings-s1 B1: a set fence reads as a restart to finish, not as a stopped const line = await text('#routes-catalogue'); assert.match(line, /Your model service is waiting for a restart to finish\. Open Model setup to finish it\./); assert.doesNotMatch(line, /not running/); - assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a").getAttribute("href")'), '#/settings/model-proxy'); + assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a").getAttribute("href")'), '#/settings/model-setup'); assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null); await b.close(); } @@ -192,8 +192,8 @@ test('settings-s1 B1: a set fence reads as a restart to finish, not as a stopped test('settings-s1 B1: with the model service not set up or not running, Routing links to its page and offers no Restart', { timeout: 90000 }, async t => { for (const [service, expect, href] of [ - [SERVICE.fresh, /Your model service isn't set up yet\. Set up the model service\./, '#/settings/model-proxy'], - [SERVICE.stopped, /The model service is not running\. Open Model setup\./, '#/settings/model-proxy'], + [SERVICE.fresh, /Your model service isn't set up yet\. Set up the model service\./, '#/settings/model-setup'], + [SERVICE.stopped, /The model service is not running\. Open Model setup\./, '#/settings/model-setup'], ]) { const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub({ service }) }); await wait('document.querySelector("#routes-catalogue a")'); @@ -235,9 +235,9 @@ test('settings-s1 B6: a stopped organization keeps its refused restart on screen await b.evaluate('location.hash = "#/orgs/gamma/settings/routing"'); await wait('document.querySelector("[data-org-down=gamma]:not([data-old]) [data-org-restart=gamma]")'); assert.equal(await b.evaluate(primary), false, 'still not primary after rendering again'); const links = await b.evaluate('[...document.querySelectorAll("[data-org-down=gamma] a")].map(a => [a.textContent, a.getAttribute("href")])'); - assert.deepEqual(links, [['Appearance', '#/settings/appearance'], ['Model setup', '#/settings/model-proxy'], ['Triage', '#/settings/triage'], ['Console', '#/settings/console']]); + assert.deepEqual(links, [['Appearance', '#/settings/appearance'], ['Model setup', '#/settings/model-setup'], ['Triage', '#/settings/triage'], ['Console', '#/settings/console']]); // A link from the stopped page opens an instance page. - await b.evaluate('document.querySelector("[data-org-down=gamma] a[href=\'#/settings/model-proxy\']").click(); true'); + await b.evaluate('document.querySelector("[data-org-down=gamma] a[href=\'#/settings/model-setup\']").click(); true'); await wait('document.querySelector("#proxy-setup") || document.querySelector("h1")?.textContent === "Model setup"'); assert.notEqual(await text('h1'), 'Not found'); }); diff --git a/packages/webui/tests/triage-settings-browser.test.mjs b/packages/webui/tests/triage-settings-browser.test.mjs index aff0022e2..0b3f81f7e 100644 --- a/packages/webui/tests/triage-settings-browser.test.mjs +++ b/packages/webui/tests/triage-settings-browser.test.mjs @@ -222,7 +222,7 @@ test('a catalogue that is not ready says so and offers no model', { timeout: 900 await wait('document.getElementById("triage-route-catalogue")'); assert.match(await text(b, 'triage-route-catalogue'), /No organization can show your models right now, so no route can be saved\. Open Model setup to see why each organization can.t see your models\./); assert.equal(await b.evaluate('document.getElementById("triage-route-catalogue").dataset.status'), 'bus-unavailable'); - assert.equal(await b.evaluate('document.querySelector("#triage-route-catalogue a").getAttribute("href")'), '#/settings/model-proxy'); + assert.equal(await b.evaluate('document.querySelector("#triage-route-catalogue a").getAttribute("href")'), '#/settings/model-setup'); assert.deepEqual(await options(b, 'triage-route-model'), [['', 'Choose a model', false]]); }); diff --git a/packages/webui/tests/views.test.mjs b/packages/webui/tests/views.test.mjs index 908192a81..6ae6bd37f 100644 --- a/packages/webui/tests/views.test.mjs +++ b/packages/webui/tests/views.test.mjs @@ -186,7 +186,8 @@ test('Queue, Business and Settings in their five states, with no move button', { // The owner's model proxy is reached from Settings, never from the Console tree. await go('#/settings', 'Settings'); assert.equal(await count('nav.tree a[href="/proxy"]'), 0); - assert.equal(await count('#settings-nav a[href="#/settings/model-proxy"]'), 1); + // Slice 4 names the page Model setup; the old #/settings/model-proxy address still opens it. + assert.equal(await count('#settings-nav a[href="#/settings/model-setup"]'), 1); // About holds the notifier and instance facts; browser appearance saves immediately. await go('#/settings/about', 'Settings'); -- 2.54.0 From 78d1ef77057166160dd983b728274bcab5eb3d67 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:38:58 -0600 Subject: [PATCH 02/14] feat(webui): settings-s4 Model setup: four step cards (Model service, Accounts and models, Organizations, Triage) with at most one primary button on the page; one press runs download, set up, install and start in order, each step once, reading the status after each, with a progress list; a step that fails stops with Try again and opens "The service's last lines"; done cards fold to their line, ?step= opens one; accounts as rows with kind and a health badge, a provider select that offers "Sign in to " or "Check and add" for an API key, a cancellable sign-in with the paste-back form, and "Removing an account is not built yet."; Models offered read-only per provider with a count, a search box past eight and "Coming later"; Advanced and Technical details folded; the Ride all done line does not count an organization that turned the model service off; MosaicModelDots reads the setup status for the sidebar marks (#1873, lane settings-s4) --- packages/webui/src/public/display.js | 752 +++++++++++++----- packages/webui/src/public/shell.css | 46 +- packages/webui/tests/proxy-browser.test.mjs | 2 +- .../webui/tests/proxy-setup-browser.test.mjs | 161 ++-- .../tests/settings-review-browser.test.mjs | 12 +- 5 files changed, 696 insertions(+), 277 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 2ca821ae2..9b2a76598 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -581,48 +581,132 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo // No browser storage, request/body logging, key reveal, or automatic write retry. (() => { 'use strict'; - // #1873: setup from nothing to a working proxy. Shown only to the instance owner (config.proxyAdmin). - // #1873 settings slice 1 (D3, D4): the next step and its one button come first, then the kept list - // of organizations that need a restart and the Ride all box (ride-default). Done steps, the service controls, the fence, the init lock, - // the organization table and the receipts sit under Technical details. - const setupMarkup = '\n'; - const markup = setupMarkup + '

Reading accounts…

\n\n

Accounts

\n

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

\n
AccountProviderStatusPriorityModels
\n

Sign in to an account

\n
Subscription account
\n

\n

\n
Finish sign-in

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

\n

Add an API key

\n
z.ai

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

\n

Client keys

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

\n
Key IDManaged byAgentIssuedState
\n'; + + '

History

  1. No setup actions on this page yet.
' + + '

Client keys

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

' + + '
Key IDManaged byAgentIssuedState
' + + '
'; + const markup = '
' + + card('service', 1, 'Model service', service, true) + + card('accounts', 2, 'Accounts and models', accounts, false) + + card('organizations', 3, 'Organizations', organizations, true) + + card('triage', 4, 'Triage', triage, true) + + advanced + tech + '
\n'; + const STEP_KEYS = ['service', 'accounts', 'organizations', 'triage']; + const BADGE = { done: ['badge-ok', 'Done'], next: ['badge-attn', 'Next'], wait: ['badge-muted', 'Waiting'], work: ['badge-attn', 'Working'], bad: ['badge-danger', 'Needs you'], off: ['badge-muted', 'Not yet'] }; + const CARD_CLASS = { done: 'done', next: 'next', work: 'next', bad: 'blocked', wait: 'waiting', off: 'waiting' }; + // An account's health from its status in the accounts read. Anything else reads Unknown. + const HEALTH = { ready: ['badge-ok', 'Ready'], active: ['badge-ok', 'Ready'], error: ['badge-danger', 'Not working'], unavailable: ['badge-danger', 'Not available'], disabled: ['badge-muted', 'Off'] }; + const health = status => HEALTH[status] ?? ['badge-muted', 'Unknown']; function mount() { const $ = id => document.getElementById(id); - let canWrite = false, login = null, poll = null; - const busy = new Set(), priorityReceipts = new Map(); + const root = $('proxy-setup'); + let canWrite = false, login = null, poll = null, accountList = null, accountsDown = null; + const busy = new Set(), priorityReceipts = new Map(), opened = new Set(); + const wanted = new URLSearchParams(location.hash.split('?')[1] ?? '').get('step'); + if (STEP_KEYS.includes(wanted)) opened.add(wanted); + let scrolled = false; const message = (text, loginOnly = false) => { $(loginOnly ? 'proxy-login-message' : 'proxy-message').textContent = text; }; const formBusy=(form,on)=>{for(const control of form.querySelectorAll('fieldset,input,select,button')){if(on){control.dataset.wasDisabled=String(control.disabled);control.disabled=true;}else if(control.dataset.wasDisabled!==undefined){control.disabled=control.dataset.wasDisabled==='true';delete control.dataset.wasDisabled;}}const button=form.querySelector('button[type=submit]');if(button){if(on){button.dataset.label=button.textContent;button.innerHTML=' Saving…';}else if(button.dataset.label){button.textContent=button.dataset.label;delete button.dataset.label;}}}; const receipt=(id,text,kind)=>{const el=$(id);el.textContent=text;el.className=kind==='error'?'banner err':kind==='success'?'settings-success':'';}; const cell = value => { const td = document.createElement('td'); td.textContent = value ?? '—'; return td; }; + const el = (tag, text, className) => { const e = document.createElement(tag); if (text !== undefined) e.textContent = text; if (className) e.className = className; return e; }; + // The provider select is this page's one list of providers: rows and buttons take their names + // and kinds (subscription or API key) from its option labels. + const providerSelect = $('proxy-provider'); + const providerLabel = p => [...providerSelect.options].find(o => o.value === p)?.textContent ?? String(p ?? 'Unknown'); + const providerShort = p => providerLabel(p).replace(/\s*\([^)]*\)$/, ''); + const providerKind = p => { const k = /\(([^)]*)\)$/.exec(providerLabel(p))?.[1] ?? ''; return k ? k[0].toUpperCase() + k.slice(1) : ''; }; + const keyed = p => providerKind(p) === 'API key'; + // One card's badge, line and body. A done card folds to its line; Show opens it again. + function setCard(key, kind, summary, { badge } = {}) { + const box = $(`setup-step-${key}`); if (!box) return; + const [cls, word] = badge ?? BADGE[kind]; + box.className = `panel setup-step ${CARD_CLASS[kind]}`; box.dataset.state = kind; + box.querySelector('.step-n').textContent = kind === 'done' ? '✓' : box.dataset.n; + const b = box.querySelector('[data-step-badge]'); b.className = `badge ${cls}`; b.textContent = word; + box.querySelector('[data-step-summary]').textContent = summary; + const shown = kind === 'wait' ? false : kind === 'done' ? opened.has(key) : true; + const body = box.querySelector('.body'), toggle = box.querySelector('.step-toggle'), title = box.querySelector('h3').textContent; + body.hidden = !shown; toggle.hidden = kind !== 'done'; + toggle.setAttribute('aria-expanded', String(shown)); toggle.textContent = shown ? 'Hide' : 'Show'; toggle.setAttribute('aria-label', `${shown ? 'Hide' : 'Show'} ${title}`); + } + root.querySelectorAll('.step-toggle').forEach(toggle => toggle.addEventListener('click', () => { + const box = toggle.closest('.setup-step'), key = box.id.replace('setup-step-', ''), body = box.querySelector('.body'); + const shown = body.hidden; body.hidden = !shown; if (shown) opened.add(key); else opened.delete(key); + toggle.setAttribute('aria-expanded', String(shown)); toggle.textContent = shown ? 'Hide' : 'Show'; toggle.setAttribute('aria-label', `${shown ? 'Hide' : 'Show'} ${box.querySelector('h3').textContent}`); + })); + // ?step=service|accounts|organizations|triage opens that card and scrolls to it once. + function focusStep() { + if (scrolled || !STEP_KEYS.includes(wanted)) return; + const box = $(`setup-step-${wanted}`); if (!box || box.hidden || box.dataset.state === undefined) return; + scrolled = true; box.scrollIntoView({ block: 'start' }); + } async function call(path, args) { const response = await fetch('/api/proxy/' + path, { cache: 'no-store', credentials: 'same-origin', method: args === undefined ? 'GET' : 'POST', @@ -639,10 +723,138 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo } return value; } + // Card 2, Accounts and models: everyone's. The owner's card waits for step 1. + function paintAccountCard() { + const addBox = $('proxy-add-box'); + addBox.hidden = !canWrite || Boolean(login); + // The page has one primary button: here while no account is added and step 1 is done. + const first = canWrite && !login && accountList !== null && !accountList.length && !accountsDown && (!setup.enabled() || setup.serviceDone()); + for (const b of [$('proxy-login-go'), $('proxy-apikey').querySelector('button[type=submit]')]) b.className = first ? 'btn primary' : 'btn'; + if (setup.enabled() && !setup.serviceDone()) { setCard('accounts', 'wait', 'Waiting for step 1.'); return focusStep(); } + if (accountsDown) { setCard('accounts', 'off', accountsDown, { badge: ['badge-muted', 'Not available'] }); return focusStep(); } + if (accountList === null) { setCard('accounts', 'work', 'Reading accounts…', { badge: ['badge-muted', 'Reading'] }); return focusStep(); } + if (login) { setCard('accounts', 'work', `Signing in to ${providerShort(login.provider)}.`); return focusStep(); } + const bad = accountList.filter(a => ['error', 'unavailable'].includes(a.status)); + if (!accountList.length) { if (canWrite) addBox.open = true; setCard('accounts', 'next', 'Add an account once. Every organization that uses your models gets its models.'); } + else if (bad.length) setCard('accounts', 'bad', `${bad.map(a => `${providerLabel(a.provider)}: ${health(a.status)[1].toLowerCase()}`).join(' · ')}. Its models are not offered until it works. Add the account again under Add an account.`); + else setCard('accounts', 'done', accountList.map(a => `${providerLabel(a.provider)} ${health(a.status)[1].toLowerCase()}`).join(' · ')); + focusStep(); + } + function paintAccounts() { + const list = $('proxy-accounts'); + if (!accountList.length) { list.replaceChildren(el('li', 'No accounts yet.', 'muted')); return; } + list.replaceChildren(...accountList.map(account => { + const li = el('li'), name = el('span', providerShort(account.provider)), kind = el('span', providerKind(account.provider) || '—'); + kind.append(el('br'), el('small', account.displayName, 'muted')); + const [cls, word] = health(account.status), badge = el('span', word, `badge ${cls}`); + li.dataset.account = account.accountId; li.append(name, kind, badge); return li; + })); + } + function paintOrder() { + const list = $('proxy-order'); + $('proxy-account-order').hidden = !accountList.length; + list.replaceChildren(...accountList.map(account => { + const li = el('li'), name = el('span', account.displayName), form = document.createElement('form'); + const input = document.createElement('input'); input.type = 'number'; input.min = '-1000'; input.max = '1000'; input.step = '1'; input.value = account.priority; + input.setAttribute('aria-label', `Priority for ${account.displayName}`); input.disabled = !canWrite; + const save = document.createElement('button'); save.type = 'submit'; save.className='proxy-priority-save'; save.textContent = 'Set priority'; save.disabled = !canWrite; save.hidden = !canWrite; + const note=document.createElement('p');note.setAttribute('role','status');if(priorityReceipts.has(account.accountId)){note.className='settings-success';note.textContent=priorityReceipts.get(account.accountId);}form.append(input, save, note); form.addEventListener('submit', async event => { + event.preventDefault(); const busyKey='priority:'+account.accountId;if (!canWrite || busy.has(busyKey) || !input.checkValidity()) return; + busy.add(busyKey);priorityReceipts.delete(account.accountId); note.textContent='';note.className='';input.disabled = true; save.disabled = true; save.innerHTML = ' Saving…'; + try { await call('priority/set', { accountId: account.accountId, priority: Number(input.value) }); message('Priority saved.');priorityReceipts.set(account.accountId,'Priority saved.');note.className='settings-success';note.textContent='Priority saved.';await refresh(); } + catch (error) { message(error.message);note.className='banner err';note.textContent=error.message; } + finally { busy.delete(busyKey); input.disabled = !canWrite; save.disabled = !canWrite; save.textContent='Set priority'; } + }); + li.append(name, form, el('span')); + // An API-key account names the models it serves; the server returns the list only for those. + if (Array.isArray(account.models)) { + const modelsForm = document.createElement('form'); modelsForm.dataset.proxyModels = ''; modelsForm.className = 'proxy-models-form'; + const label = document.createElement('label'); label.textContent = `Models for ${account.displayName}`; + const area = document.createElement('textarea'); area.name = 'models'; area.rows = 2; area.value = account.models.join(', '); area.disabled = !canWrite; + label.append(area); const saveModels = document.createElement('button'); saveModels.type = 'submit'; saveModels.className = 'proxy-priority-save'; saveModels.textContent = 'Save models'; saveModels.disabled = !canWrite; + modelsForm.append(label, saveModels); modelsForm.addEventListener('submit', async event => { + event.preventDefault(); const busyKey = 'models:' + account.accountId; + if (!canWrite || busy.has(busyKey)) return; + const models = area.value.split(/[,\n]/).map(value => value.trim()).filter(Boolean); + busy.add(busyKey); area.disabled = true; saveModels.disabled = true; + try { await call('group/models/set', { accountId: account.accountId, models }); message('Models saved.'); await refresh(); } + catch (error) { message(error.message); } + finally { busy.delete(busyKey); area.disabled = !canWrite; saveModels.disabled = !canWrite; } + }); + li.append(modelsForm); + } + return li; + })); + } + async function refresh() { + const [accounts, keys] = await Promise.all([call('accounts'), call('keys')]); + accountList = Array.isArray(accounts?.accounts) ? accounts.accounts : []; + accountsDown = null; + paintAccounts(); paintOrder(); + $('proxy-keys').replaceChildren(...keys.keys.map(key => { + 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; + })); + if ($('proxy-offered').open) readOffered(); + setup.accounts(accountList.length); + paintAccountCard(); + } + // Models offered: read-only, from the routes read of an organization whose model list is ready. + // Turning one model on or off is not built yet, so each switch reads Coming later. + let offeredRound = 0; + async function readOffered() { + const box = $('proxy-offered-list'), round = ++offeredRound; + if (!accountList?.length) { box.replaceChildren(el('p', 'Add an account first. Its models show here.', 'small muted')); return; } + const source = setup.readyOrg(); + const url = source ? `/api/orgs/${encodeURIComponent(source)}/bus/routes` : '/api/bus/routes'; + box.replaceChildren(el('p', 'Reading the models…', 'small muted')); + let catalogue = null; + try { const r = await fetch(url, { cache: 'no-store', redirect: 'manual' }); catalogue = r.ok ? (await r.json())?.rows?.[0]?.catalogue : null; } catch { catalogue = null; } + if (round !== offeredRound) return; + if (!catalogue || catalogue.status !== 'ready' || !Array.isArray(catalogue.models)) { + box.replaceChildren(el('p', 'No organization shows your models yet, so this page can\'t list them. They show here once an organization uses your model service.', 'small muted')); + return; + } + const norm = s => String(s ?? '').toLowerCase().replace(/[^a-z0-9]/g, ''); + const models = catalogue.models.filter(m => m && m.module === 'cliproxy' && m.available === true); + const from = el('p', `Read from ${source ? (window.MosaicOrg?.row?.(source)?.label || source) : 'this organization'}'s model list.`, 'small muted'); + box.replaceChildren(from, ...[...new Set(accountList.map(a => a.provider))].map(provider => { + const mine = models.filter(m => norm(m.upstream) === norm(provider)), name = providerShort(provider); + const details = el('details'), summary = el('summary', `${name} models offered: ${mine.length}`), inside = el('div', undefined, 'inside'); + details.dataset.offered = provider; details.append(summary, inside); + if (!mine.length) { inside.append(el('p', `No ${name} models are listed yet.`, 'small muted')); return details; } + const list = el('ul', undefined, 'model-list'); + list.append(...mine.map(m => { const li = el('li'), label = el('label'), box2 = document.createElement('input'); box2.type = 'checkbox'; box2.checked = true; box2.disabled = true; + label.append(box2, ` ${m.model}${m.reason === 'unverified' ? ' (unverified)' : ''}`); li.dataset.model = String(m.model).toLowerCase(); li.append(label, el('span', 'Coming later', 'small muted')); return li; })); + if (mine.length > 8) { + const field = el('div', undefined, 'field'), id = `proxy-find-${norm(provider)}`, label = el('label', `Find a ${name} model`), input = document.createElement('input'); + label.htmlFor = id; input.id = id; input.type = 'search'; input.autocomplete = 'off'; + input.addEventListener('input', () => { const q = input.value.trim().toLowerCase(); list.querySelectorAll('li').forEach(li => { li.hidden = Boolean(q) && !li.dataset.model.includes(q); }); }); + field.append(label, input); inside.append(field); + } + inside.append(list); return details; + })); + } + $('proxy-offered').addEventListener('toggle', () => { if ($('proxy-offered').open) readOffered(); }); + // Add an account: the provider picks a sign-in or an API key. + function paintProvider() { + const p = providerSelect.value, apikey = keyed(p); + const go = $('proxy-login-go'); go.textContent = `Sign in to ${providerShort(p)}`; go.hidden = apikey; + $('proxy-apikey').hidden = !apikey; $('proxy-apikey-label').textContent = `${providerShort(p)} API key`; + } + providerSelect.addEventListener('change', paintProvider); + function paintSignin() { + $('proxy-signin').hidden = !login; + if (!login) return; + const name = providerShort(login.provider), item = (cls, text) => el('li', text, cls); + $('proxy-signin-progress').replaceChildren(item('ok', `Opened ${name}'s sign-in in a new tab`), item('run', 'Waiting for you to finish signing in there…')); + $('proxy-authorize').textContent = `Open ${name}'s sign-in again`; + $('proxy-login-cancel').disabled = !canWrite; + } function endLogin() { clearTimeout(poll); poll = null; login = null; $('proxy-authorize').removeAttribute('href'); $('proxy-authorize').hidden = true; $('proxy-login-submit').elements.redirect_url.value = ''; + paintSignin(); paintAccountCard(); } async function status() { if (!login) return; @@ -658,56 +870,17 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo else message(result.reason === 'login-timeout' ? 'Sign-in took too long. Try again.' : 'Account sign-in failed. Try again.', true); } catch (error) { if (active === login) { endLogin(); message(error.message, true); } } } - async function refresh() { - const [accounts, keys] = await Promise.all([call('accounts'), call('keys')]); - setup.accounts(Array.isArray(accounts?.accounts) ? accounts.accounts.length : null); - const rows = accounts.accounts.map(account => { - const row = document.createElement('tr'); - row.append(cell(account.displayName), cell(account.provider), cell(account.status)); - const td = document.createElement('td'), form = document.createElement('form'); - const input = document.createElement('input'); input.type = 'number'; input.min = '-1000'; input.max = '1000'; input.step = '1'; input.value = account.priority; - input.setAttribute('aria-label', `Priority for ${account.displayName}`); input.disabled = !canWrite; - const save = document.createElement('button'); save.type = 'submit'; save.className='proxy-priority-save'; save.textContent = 'Set priority'; save.disabled = !canWrite; save.hidden = !canWrite; - const receipt=document.createElement('p');receipt.setAttribute('role','status');if(priorityReceipts.has(account.accountId)){receipt.className='settings-success';receipt.textContent=priorityReceipts.get(account.accountId);}form.append(input, save, receipt); form.addEventListener('submit', async event => { - event.preventDefault(); const busyKey='priority:'+account.accountId;if (!canWrite || busy.has(busyKey) || !input.checkValidity()) return; - busy.add(busyKey);priorityReceipts.delete(account.accountId); receipt.textContent='';receipt.className='';input.disabled = true; save.disabled = true; save.innerHTML = ' Saving…'; - try { await call('priority/set', { accountId: account.accountId, priority: Number(input.value) }); message('Priority saved.');priorityReceipts.set(account.accountId,'Priority saved.');receipt.className='settings-success';receipt.textContent='Priority saved.';await refresh(); } - catch (error) { message(error.message);receipt.className='banner err';receipt.textContent=error.message; } - finally { busy.delete(busyKey); input.disabled = !canWrite; save.disabled = !canWrite; save.textContent='Set priority'; } - }); - td.append(form); row.append(td); - const modelsCell = document.createElement('td'); - if (account.provider === 'z.ai' && Array.isArray(account.models)) { - const modelsForm = document.createElement('form'); modelsForm.dataset.proxyModels = ''; - const label = document.createElement('label'); label.textContent = 'Models'; - const input = document.createElement('textarea'); input.name = 'models'; input.rows = 2; input.value = account.models.join(', '); input.disabled = !canWrite; - label.append(input); const saveModels = document.createElement('button'); saveModels.type = 'submit'; saveModels.textContent = 'Save models'; saveModels.disabled = !canWrite; - modelsForm.append(label, saveModels); modelsForm.addEventListener('submit', async event => { - event.preventDefault(); const busyKey = 'models:' + account.accountId; - if (!canWrite || busy.has(busyKey)) return; - const models = input.value.split(/[,\n]/).map(value => value.trim()).filter(Boolean); - busy.add(busyKey); input.disabled = true; saveModels.disabled = true; - try { await call('group/models/set', { accountId: account.accountId, models }); message('Models saved.'); await refresh(); } - catch (error) { message(error.message); } - finally { busy.delete(busyKey); input.disabled = !canWrite; saveModels.disabled = !canWrite; } - }); - modelsCell.append(modelsForm); - } - row.append(modelsCell); return row; - }); - $('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(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))); $('proxy-login-start').addEventListener('submit', async event => { event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('login-start') || login) return; - busy.add('login-start');formBusy(form,true); + const provider = providerSelect.value; + if (keyed(provider)) { $('proxy-apikey').elements.key.focus(); return; } + busy.add('login-start');formBusy(form,true);$('proxy-login-message').className=''; try { - login = await call('login/start', { provider: event.currentTarget.elements.provider.value }); + const started = await call('login/start', { provider }); + login = { ...started, provider }; $('proxy-authorize').href = login.url; $('proxy-authorize').hidden = false; + paintSignin(); paintAccountCard(); window.open(login.url, '_blank', 'noopener,noreferrer'); message('Complete account sign-in in the new tab, or use the sign-in link.', true); poll = setTimeout(status, 2000); @@ -716,36 +889,41 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }); $('proxy-login-submit').addEventListener('submit', async event => { event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('login-submit') || !login) return; - const input = event.currentTarget.elements.redirect_url, redirect_url = input.value; input.value = ''; + const input = event.currentTarget.elements.redirect_url, redirect_url = input.value.trim(); input.value = ''; busy.add('login-submit');formBusy(form,true); try { await call('login/submit', { redirect_url }); message('Address submitted. Waiting for sign-in confirmation…', true); } catch (error) { message(error.message, true);$('proxy-login-message').className='banner err'; } finally { busy.delete('login-submit');formBusy(form,false); } }); $('proxy-login-cancel').addEventListener('click', async event => { - const form=event.currentTarget.form;if (!canWrite || busy.has('login-cancel') || !login) return; - busy.add('login-cancel');formBusy(form,true); clearTimeout(poll); + const button=event.currentTarget;if (!canWrite || busy.has('login-cancel') || !login) return; + busy.add('login-cancel');button.disabled=true; clearTimeout(poll); try { await call('login/cancel', { state: login.state }); endLogin(); message('Sign-in cancelled.', true); } catch (error) { endLogin(); message(error.message, true); } - finally { busy.delete('login-cancel');formBusy(form,false); } + finally { busy.delete('login-cancel');button.disabled=!canWrite; } }); + const resetProvider = () => { providerSelect.selectedIndex = 0; paintProvider(); }; + $('proxy-apikey-cancel').addEventListener('click', () => { $('proxy-apikey').elements.key.value = ''; receipt('proxy-apikey-message','',''); resetProvider(); providerSelect.focus(); }); $('proxy-apikey').addEventListener('submit', async event => { event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('apikey')) return; - const input = event.currentTarget.elements.key, key = input.value; input.value = ''; + const input = event.currentTarget.elements.key, key = input.value.trim(), provider = providerSelect.value; input.value = ''; busy.add('apikey');receipt('proxy-apikey-message','','');formBusy(form,true); - try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.');receipt('proxy-apikey-message','API key added.','success');await refresh();await setup.reread(); } + try { await call('apikey/add', { provider, key }); message('API key added.');receipt('proxy-apikey-message','API key added.','success');resetProvider();await refresh();await setup.reread(); } catch (error) { message(error.message);receipt('proxy-apikey-message',error.message,'error'); } finally { busy.delete('apikey');formBusy(form,false); } }); // #1873 setup controller. Every action is a POST the server checks again (owner, Origin, // Fetch Metadata); this code only offers the next step. Pasted keys stay in their fields - // until submit, which clears them before the request is answered. + // until the chain starts, which clears them before any request is answered. const setup = (() => { - const box = $('proxy-setup'), form = $('proxy-setup-init'); + const form = $('proxy-setup-init'); let state = null, timer = null, enabled = false, sendOk = false, seenFetch = null, loading = false; // #1873 settings slice 1 (D1): the steps after "accounts" come from what this page reads itself: // the account count (refresh), the organizations in the status, and the Triage route. let accountCount = null, triageSet = null; + // settings slice 4: one press runs fetch, init, install and start. chain holds that run: the steps + // it posted (each at most once, so nothing is retried by itself) and where it stopped. + let chain = null; const listed = new Set(); const esc = v => String(v).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); const pasteAllowed = location.protocol === 'https:' || ['localhost', '[::1]'].includes(location.hostname) || /^127\./.test(location.hostname); @@ -759,10 +937,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo 'proxy-key-invalid': 'The key must be 1 to 4096 printable characters with no spaces.', 'proxy-config-invalid': 'The port must be 1024 to 65535 and not 8317.', 'proxy-rotate-grace-invalid': 'Key rotation grace must be 1 to 1440 minutes.', - 'proxy-first-output-invalid': 'First output timeout must be 1 to 3600 seconds.', + 'proxy-first-output-invalid': 'Wait for a first answer must be 1 to 3600 seconds.', 'proxy-already-initialized': 'The model service is already initialized. Init never overwrites it.', - 'proxy-port-in-use': 'That port is in use. Choose another or leave it empty.', - 'proxy-init-busy': 'An init lock is held. See Init lock above.', + 'proxy-port-in-use': 'That port is in use. Choose another under Advanced or leave it empty.', + 'proxy-init-busy': 'An init lock is held. See Init lock under Technical details.', 'proxy-install-missing': 'The pinned release is not fetched yet.', 'proxy-install-invalid': 'The fetched release failed its hash check. Fetch again.', 'proxy-restart-required': 'Restart the model service from this page first.', @@ -814,46 +992,83 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo } // settings-p3 (re-check 3 P3-1): where the hand steps for a held init lock or a partial init are written. const README_STEPS = ['The hand steps for a stale init lock and a partial init are in ', 'packages/model-proxy/README.md']; - function paintNext() { - const next = state.next?.[0], box = $('proxy-setup-next'); - const steps = { - fetch: ['Fetch the pinned release', `Next: fetch CLIProxyAPI ${state.release.version}. Every file is checked against its pinned SHA-256 before it is installed.`, fetchRelease], - 'init-lock-clear': ['Clear the stale init lock', 'Next: an init lock is left from an init that did not finish. The bus is stopped and no model service files exist, so it can be cleared.', clearLock], - 'init-lock-wait': ['Check again', `An init lock is held and cannot be cleared: ${state.initLock.blockers.join('; ')}. Stop the bus, then check again. Model service files that are left must be resolved by hand. Do not delete them to make init run again.`, load, README_STEPS], - 'init-repair': ['Check again', 'Setup is partly done. Init never overwrites model service files that already exist, so they must be resolved by hand. Do not delete them to make init run again. Then check again.', load, README_STEPS], - init: ['Initialize the model service', 'Next: initialize. The bus generates the management key unless you paste your own.', () => { $('proxy-setup-init-box').open = true; form.elements.port.focus(); }], - 'unit-install': ['Install the model service', `Next: install ${state.unit.unit}.`, () => unitAction('install')], - 'unit-start': ['Start the model service', `Next: start ${state.unit.unit}.`, () => unitAction('start')], - 'unit-restart': ['Restart the model service', state.fence.set ? (fence => fence.invalid || !fence.time ? 'A key write had an uncertain outcome, so key writes are fenced. The fence file has no readable time, so a restart from this page cannot be proven against it: restart the model service, confirm it answers, then clear the fence.' : 'A key write had an uncertain outcome, so key writes are fenced. Restart the model service; after this page confirms the new process, clear the fence.')(state.fence) : 'The service is running but does not answer on its port. Restart it.', () => unitAction('restart'), - state.fence.set && (state.fence.invalid || !state.fence.time) ? 'mosaic proxy fence clear --proxy-restarted' : null], - 'fence-clear': ['Clear the fence', 'The model service was restarted from this page and the new process answers on its port. Clear the fence with that evidence.', clearFence], - accounts: ['Add an account', state.next?.includes('ride-all') ? 'The model service is running. Sign in to a model account or add an API key below. Then use Ride all below.' : 'The model service is running. Sign in to a model account or add an API key below.', () => $('proxy-signin-title')?.scrollIntoView({ block: 'start' })], - 'triage-route': ['Open Triage settings', 'Next: choose the model Triage uses. Triage is the assistant that answers questions about this instance.', () => { location.hash = '#/settings/triage'; }], - 'ride-all': ['Go to Ride all', 'Next: let your organizations use your models. Ride all is below.', () => $('proxy-ride')?.scrollIntoView({ block: 'start' })], - }; - const step = next === 'accounts' ? afterAccounts() : next; - if (['restart-orgs', 'checking-orgs', 'orgs-blocked', 'done'].includes(step)) { - const names = needRestart().filter(restartHelps).map(o => nameOf(o.id)); - const p = document.createElement('p'); p.dataset.next = step; - // settings-p3 (rebase re-check P3-1): the Ride all box below still lists an organization, so not "every". - p.textContent = step === 'done' ? (rideListed() ? 'The model service is set up. Some organizations still need a step under Use your models in every organization.' : 'The model service is set up and every organization can see your models.') - : step === 'checking-orgs' ? 'Checking why each organization can\'t see your models.' - : step === 'orgs-blocked' ? 'The model service is set up. Some organizations still can\'t see your models. Each one says why under Organizations that can\'t use your models yet.' - : `Next: restart ${names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`}. ${names.length === 1 ? 'It' : 'Each'} has a Restart button under Organizations that can't use your models yet.`; - box.replaceChildren(p); return; - } - const [label, text, action, command] = steps[step] ?? ['Check again', 'Status read.', load]; - const p = document.createElement('p'); p.textContent = text; - // A step only a terminal can finish keeps its exact command under Technical details. - const cli = command ? Object.assign(document.createElement('details'), { className: 'proxy-setup-cli' }) : null; - if (cli) { const s = document.createElement('summary'), q = document.createElement('p'), c = document.createElement('code'), [lead, code] = Array.isArray(command) ? command : ['Run this in a terminal on this machine: ', command]; s.textContent = 'Technical details'; q.className = 'small muted'; q.textContent = lead; c.textContent = code; q.append(c); cli.append(s, q); } - const button = document.createElement('button'); button.type = 'button'; button.className = 'btn primary'; button.id = 'proxy-setup-go'; button.dataset.next = step ?? ''; - button.textContent = state.busy ? 'Working…' : label; - const write = !['init-lock-wait', 'init-repair', 'accounts', 'init', 'ride-all', 'triage-route'].includes(step); - button.disabled = Boolean(state.busy) || (write && !sendOk); - button.addEventListener('click', () => { if (!button.disabled) action(); }); - box.replaceChildren(...(cli ? [p, cli, button] : [p, button])); + const CHAIN = ['fetch', 'init', 'unit-install', 'unit-start']; + const PROGRESS = [['fetch', 'Downloaded and checked'], ['init', 'Configured'], ['start', 'Starting the service…'], ['answer', 'Checking it answers']]; + const stageOf = step => step === 'fetch' || step === 'init' ? step : step === 'unit-install' || step === 'unit-start' ? 'start' : 'answer'; + // Each line is done only when the status read says so. + function progressDone() { + const { release, init, unit } = state, started = unit.installed && unit.active === 'active', next = state.next?.[0]; + return { fetch: release.fetched && release.verified, init: init.initialized, start: started, answer: started && next !== 'unit-restart' && !CHAIN.includes(next) }; } + function paintProgress(show) { + const ol = $('proxy-setup-progress'); ol.hidden = !show; if (!show) return; + const ok = progressDone(); let first = true; + const words = { ok: 'done', run: 'in progress', todo: 'not started', bad: 'stopped here' }; + ol.replaceChildren(...PROGRESS.map(([key, text]) => { + let cls = ok[key] ? 'ok' : 'todo'; + if (!ok[key] && chain?.failed && stageOf(chain.failed.at) === key) cls = 'bad'; + else if (!ok[key] && first && (chain?.running || state.fetch?.state === 'running')) cls = 'run'; + if (!ok[key]) first = false; + const li = el('li', text, cls); li.dataset.stage = key; li.append(el('span', ` (${words[cls]})`, 'sr-only')); return li; + })); + } + function goButton(label, next, disabled, action) { + const button = el('button', label, 'btn primary'); button.type = 'button'; button.id = 'proxy-setup-go'; button.dataset.next = next ?? ''; + button.disabled = disabled; button.addEventListener('click', () => { if (!button.disabled) action(); }); return button; + } + function cliDetails(command) { + const cli = Object.assign(document.createElement('details'), { className: 'proxy-setup-cli' }); + const s = el('summary', 'Technical details'), q = el('p', undefined, 'small muted'), c = el('code'), [lead, code] = Array.isArray(command) ? command : ['Run this in a terminal on this machine: ', command]; + q.textContent = lead; c.textContent = code; q.append(c); cli.append(s, q); return cli; + } + // Card 1, Model service. + function paintService() { + const next = state.next?.[0], box = $('proxy-setup-next'), lines = $('proxy-setup-lines'); + const ok = progressDone(), some = Object.values(ok).some(Boolean), fetching = state.fetch?.state === 'running'; + paintFixtures(next !== 'accounts'); + if (next === 'accounts') { setCard('service', 'done', state.unit.port ? `Running. Answers on this machine, port ${state.unit.port}.` : 'Running. Answers on this machine.'); box.replaceChildren(); paintProgress(false); lines.hidden = true; return; } + if (chain?.running || (fetching && CHAIN.includes(next))) { + setCard('service', 'work', chain?.running ? 'Setting up. Keep this page open; if you leave, Continue setup picks up from here.' : 'Downloading the release. Keep this page open.'); + box.replaceChildren(goButton('Working…', next, true, () => {})); paintProgress(true); lines.hidden = true; return; + } + let failed = chain?.failed ?? null; + if (!failed && next === 'fetch' && state.fetch?.state === 'failed') failed = { at: 'fetch', reason: `The download failed. ${explain(state.fetch.error)}` }; + if (failed && (CHAIN.includes(next) || next === 'unit-restart')) { + setCard('service', 'bad', `${failed.reason} The steps that finished are kept. No organization was touched.`, { badge: ['badge-danger', 'Setup stopped'] }); + box.replaceChildren(el('p', 'Try again starts from the step that failed.', 'small muted'), goButton('Try again', next, !sendOk || Boolean(state.busy), runChain)); + paintProgress(true); lines.hidden = false; lines.open = true; + $('proxy-setup-log').textContent = state.unit?.error ? String(state.unit.error) : 'Nothing reported.'; + return; + } + lines.hidden = true; + if (CHAIN.includes(next)) { + const fresh = next === 'fetch' && !some; + setCard('service', 'next', fresh ? 'Lets your agents use the accounts you sign in to. It runs on this machine and takes about a minute to set up.' : 'Setup is partly done. Continue setup picks up from the step that is not done yet.'); + box.replaceChildren(goButton(state.busy ? 'Working…' : fresh ? 'Set up model service' : 'Continue setup', next, !sendOk || Boolean(state.busy), runChain)); + paintProgress(!fresh); return; + } + paintProgress(false); + const fence = state.fence ?? {}; + const steps = { + 'init-lock-clear': ['An earlier setup left a lock.', 'Clear the stale init lock', 'An init lock is left from an init that did not finish. The bus is stopped and no model service files exist, so it can be cleared.', clearLock], + 'init-lock-wait': ['Setup is held by a lock.', 'Check again', `An init lock is held and cannot be cleared: ${state.initLock.blockers.join('; ')}. Stop the bus, then check again. Model service files that are left must be resolved by hand. Do not delete them to make init run again.`, load, README_STEPS], + 'init-repair': ['Setup is partly done and needs a hand step.', 'Check again', 'Setup is partly done. Init never overwrites model service files that already exist, so they must be resolved by hand. Do not delete them to make init run again. Then check again.', load, README_STEPS], + 'unit-restart': fence.set ? ['Key writes are paused until a restart.', 'Restart model service', fence.invalid || !fence.time ? 'A key write had an uncertain outcome, so key writes are fenced. The fence file has no readable time, so a restart from this page cannot be proven against it: restart the model service, confirm it answers, then clear the fence.' : 'A key write had an uncertain outcome, so key writes are fenced. Restart the model service; after this page confirms the new process, clear the fence.', () => unitAction('restart'), fence.invalid || !fence.time ? 'mosaic proxy fence clear --proxy-restarted' : null] + : ['The service is running but does not answer on its port.', 'Restart model service', 'Restart it. The organizations wait until it answers.', () => unitAction('restart')], + 'fence-clear': ['One step left: clear the fence.', 'Clear the fence', 'The model service was restarted from this page and the new process answers on its port. Clear the fence with that evidence.', clearFence], + }; + const [headline, label, text, action, command] = steps[next] ?? ['Status read.', 'Check again', 'Check the status again.', load]; + setCard('service', 'bad', headline, next === 'unit-restart' && !fence.set ? { badge: ['badge-danger', 'Not answering'] } : {}); + const write = !['init-lock-wait', 'init-repair'].includes(next) && Boolean(steps[next]); + box.replaceChildren(...[el('p', text), command ? cliDetails(command) : null, goButton(state.busy ? 'Working…' : label, next, Boolean(state.busy) || (write && !sendOk), action)].filter(Boolean)); + } + // Organizations on stand-in models are named before setup: step 3 offers to move them. + function paintFixtures(show) { + const note = $('proxy-setup-fixtures'), ids = (Array.isArray(state.ride) ? state.ride : []).filter(r => r.state === 'fixture').map(r => nameOf(r.id)); + note.hidden = !show || !ids.length; if (note.hidden) return; + note.replaceChildren(el('p', `${listNames(ids)} ${ids.length === 1 ? 'uses' : 'use'} stand-in models. After setup and your first account, step 3 offers to move ${ids.length === 1 ? 'it' : 'each one'} to your models.`)); + } + const listNames = names => names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`; // #1873 settings slice 1 (D1, D3): steps after "accounts", and the kept restart list. const nameOf = id => window.MosaicOrg?.row?.(id)?.label || id; const running = () => state?.next?.[0] === 'accounts'; @@ -877,12 +1092,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo fetch(`/api/orgs/${encodeURIComponent(id)}/bus/routes`, { cache: 'no-store', redirect: 'manual' }) .then(async r => { const c = r.ok ? (await r.json())?.rows?.[0]?.catalogue : null; if (!c || typeof c !== 'object') throw Error(); return { known: true, ready: c.status === 'ready', cause: window.MosaicConsole?.catalogueCause?.(nameOf(id), c.notices, c.reason) ?? null }; }) .catch(() => ({ known: false })) - .then(got => { if (causes.get(id)?.round !== round) return; causes.set(id, { round, ...got }); if (enabled && state) { paintNext(); paintRestart(); } }); + .then(got => { if (causes.get(id)?.round !== round) return; causes.set(id, { round, ...got }); if (enabled && state) { paintRestart(); paintOrgsCard(); paintTriageCard(); } }); } const unread = o => o.catalogue?.status === 'unavailable' && !('known' in (causes.get(o.id) ?? {})); const restartHelps = o => { const c = causes.get(o.id); return launchRestart(o) || (o.catalogue?.status === 'unavailable' && c?.known === true && !c.ready && (!c.cause || c.cause.restart)); }; const seenReady = o => !launchRestart(o) && (o.catalogue?.status === 'ready' || causes.get(o.id)?.ready === true); - function afterAccounts() { + // Step 3's own state: Ride all, a check, a restart, or who still can't see the models. + function orgStep() { if (!accountCount) return 'accounts'; // ride-default: Ride all is next while an organization can ride now. Stand-in organizations alone // do not hold the step: their Move buttons are optional and Ride all would be disabled. @@ -891,13 +1107,51 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const waiting = needRestart().filter(o => !seenReady(o)); if (waiting.some(unread)) return 'checking-orgs'; if (waiting.some(restartHelps)) return 'restart-orgs'; - if (triageSet === false) return 'triage-route'; return waiting.length ? 'orgs-blocked' : 'done'; } + // The page's one next step after the service runs. Triage comes after Ride all, the checks and restarts. + function afterAccounts() { + const step = orgStep(); + if (['accounts', 'ride-all', 'checking-orgs', 'restart-orgs'].includes(step)) return step; + return triageSet === false ? 'triage-route' : step; + } async function readTriage() { try { const r = await fetch('/api/triage/route', { cache: 'no-store', redirect: 'manual' }); const v = r.ok ? await r.json() : null; triageSet = v && typeof v === 'object' ? !!v.route : null; } catch { triageSet = null; } } + // Card 3, Organizations. The line carries data-next, the step it names. + 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; } + 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. + const removed = rideSkips().filter(s => s.reason === 'removed').map(s => nameOf(s.id)); + const doneLine = rideListed() ? 'The model service is set up. Some organizations still need a step under Use your models in every organization.' + : removed.length ? `The model service is set up and every organization that uses it can see your models. ${listNames(removed)} turned it off, and Ride all leaves ${removed.length === 1 ? 'it' : 'them'} off.` + : 'The model service is set up and every organization can see your models.'; + const [kind, text, badge] = { + 'ride-all': ['next', 'Next: let your organizations use your models. Ride all is below.'], + 'checking-orgs': ['work', 'Checking why each organization can\'t see your models.', ['badge-muted', 'Checking']], + 'restart-orgs': ['bad', `Next: restart ${listNames(names)}. ${names.length === 1 ? 'It' : 'Each'} has a Restart button under Organizations that can't use your models yet.`], + 'orgs-blocked': ['bad', 'The model service is set up. Some organizations still can\'t see your models. Each one says why under Organizations that can\'t use your models yet.'], + done: [rideListed() ? 'bad' : 'done', doneLine], + }[step]; + setCard('organizations', kind, text, badge ? { badge } : {}); + line.dataset.next = step; + if (step === 'ride-all') go.className = 'btn primary'; + } + // Card 4, Triage: the Triage route read. + function paintTriageCard() { + const link = $('proxy-setup-triage'); link.className = 'btn'; + if (!running() || !accountCount) { setCard('triage', 'wait', 'Opens after your first account.'); return; } + if (triageSet === true) { setCard('triage', 'done', 'A model is chosen for Triage.'); return; } + if (triageSet === null) { setCard('triage', 'off', 'Triage\'s setting could not be read. Open the Triage page to see it.'); return; } + const nextUp = afterAccounts() === 'triage-route'; + setCard('triage', nextUp ? 'next' : 'off', nextUp ? 'Next: choose the model Triage uses. Triage is the assistant that answers questions about this instance.' : 'Triage is the assistant that answers questions about this instance. Choose its model on the Triage page.'); + if (nextUp) link.className = 'btn primary'; + } function paintRestart() { const box = $('proxy-setup-restart'), list = $('proxy-setup-restart-list'); for (const o of needRestart()) listed.add(o.id); @@ -909,7 +1163,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const noRestart = cfg?.tester === true || cfg?.user === true ? 'Only the instance owner can restart it.' : 'Restart from here needs organization setup on this Console.'; list.innerHTML = orgs.map(o => { const status = o.catalogue?.status, name = nameOf(o.id), c = causes.get(o.id); - const routing = `Open ${esc(name)}'s Routing`; + const routing = `Open ${esc(name)}'s Models page`; let badge, word, why, restart = true, fix = '', detail = ''; if (launchRestart(o)) [badge, word, why] = ['badge-attn', 'Restart needed', `${name} can see your models. Its agents start on them after a restart.`]; else if (seenReady(o)) [badge, word, why, restart] = ['badge-ok', 'Ready', `${name} can see your models now.`, false]; @@ -931,23 +1185,41 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }).join(''); } function paintControls() { - const { release, init, unit, initLock, busy } = state; - const canInit = sendOk && !busy && release.fetched && release.verified && !init.initialized && !init.partial && !initLock.present; - form.querySelectorAll('[data-setup-write]').forEach(el => { el.disabled = !canInit; }); + const { init, unit, initLock, busy } = state; + // The settings can be chosen before the release is fetched: Set up model service uses them at init. + const canInit = sendOk && !busy && !chain?.running && !init.initialized && !init.partial && !initLock.present; + form.querySelectorAll('[data-setup-write]').forEach(e => { e.disabled = !canInit; }); + form.hidden = init.initialized; $('proxy-setup-paste-choice').hidden = !pasteAllowed; $('proxy-setup-paste-note').hidden = pasteAllowed; const allow = { install: !unit.installed, start: unit.installed && unit.active !== 'active', restart: unit.installed && unit.active === 'active', stop: unit.installed && unit.active === 'active' }; - box.querySelectorAll('[data-unit]').forEach(button => { button.disabled = !sendOk || Boolean(busy) || !init.initialized || !allow[button.dataset.unit]; }); + root.querySelectorAll('[data-unit]').forEach(button => { button.disabled = !sendOk || Boolean(busy) || Boolean(chain?.running) || !init.initialized || !allow[button.dataset.unit]; }); const orgs = $('proxy-setup-orgs'); if (!Array.isArray(state.organizations)) orgs.replaceChildren(Object.assign(document.createElement('tr'), { innerHTML: 'Organizations could not be read.' })); else if (!state.organizations.length) orgs.replaceChildren(Object.assign(document.createElement('tr'), { innerHTML: 'No organizations.' })); else orgs.replaceChildren(...state.organizations.map(org => { const tr = document.createElement('tr'); tr.append(cell(org.id), cell(org.proxy === 'shared' ? 'Shared (this instance)' : org.proxy), cell(org.catalogue?.status ?? org.error ?? 'unknown'), cell(Number.isInteger(org.catalogue?.models) ? String(org.catalogue.models) : '—')); return tr; })); paintRide(); $('proxy-setup-own').textContent = state.ownProxy?.available ? 'An organization can use its own model service.' : 'Use its own model service: coming later. It is planned and not built yet, so an organization can\'t choose it today.'; + // 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.rotateGraceMinutes !== undefined) row(dl, 'Key rotation grace', `${human(s.rotateGraceMinutes)} minutes`); } } + // Programs that drive models: the harnesses this Console offers an organization, read on open. + let programsRead = false; + $('proxy-setup-advanced').addEventListener('toggle', async () => { + if (!$('proxy-setup-advanced').open || programsRead) return; programsRead = true; + const list = $('proxy-setup-programs'); list.replaceChildren(el('li', 'Reading…', 'muted')); + try { + const r = await fetch('/api/proxy/plugins', { cache: 'no-store', redirect: 'manual' }); const v = r.ok ? await r.json() : null; + const names = Array.isArray(v?.available?.harness) ? v.available.harness.filter(n => typeof n === 'string') : null; + if (!names) throw Error(); + list.replaceChildren(...(names.length ? names.map(n => el('li', n)) : [el('li', 'No programs are installed.', 'muted')])); + } catch { programsRead = false; list.replaceChildren(el('li', 'The programs could not be read.', 'muted')); } + }); // #1873 ride-default: Ride all and the fixture move. The server decides each organization again; // this code only words the answer. Every write asks first, in plain words, what changes. const RIDE_REASONS = { - removed: 'It used your model service, or Ride all may have added it, and it is off now. Ride all leaves it off. To use it there, choose Use your models on its Routing page.', + removed: 'It used your model service, or Ride all may have added it, and it is off now. Ride all leaves it off. To use it there, choose Use your models on its Models page.', 'not-recorded': 'Console could not record the change first, so it was not made.', 'bus-down': 'Its bus is not running. Start it, then ride again.', 'no-proxy-client': 'Its bus started before the model service was set up. Restart its bus, then ride again.', @@ -967,10 +1239,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }; const rideReason = code => RIDE_REASONS[code] ?? `The change was refused (${code}).`; let rideResult = null; - // What the Ride all box lists (paintRide): organizations that can ride, skipped ones and stand-in ones. + const rideSkips = () => rideResult?.skipped ?? (Array.isArray(state?.ride) ? state.ride : []).filter(r => !['ready', 'already', 'fixture'].includes(r.state)).map(r => ({ id: r.id, reason: r.state })); + // What the Ride all box lists that still needs a step: organizations that can ride, skipped ones and + // stand-in ones. settings-s4 (P3): an organization that turned the model service off ("removed") is + // listed but needs nothing, so it is not counted. const rideListed = () => { const ride = Array.isArray(state.ride) ? state.ride : []; - return ride.filter(r => r.state === 'ready').length + (rideResult?.skipped ?? ride.filter(r => !['ready', 'already', 'fixture'].includes(r.state))).length + (rideResult?.fixtures ?? ride.filter(r => r.state === 'fixture')).length; }; - const li = text => { const el = document.createElement('li'); el.textContent = text; return el; }; + return ride.filter(r => r.state === 'ready').length + rideSkips().filter(s => s.reason !== 'removed').length + (rideResult?.fixtures ?? ride.filter(r => r.state === 'fixture')).length; }; + const li = text => { const item = document.createElement('li'); item.textContent = text; return item; }; function paintRide() { const box = $('proxy-ride'), ride = Array.isArray(state.ride) ? state.ride : null; box.hidden = !ride || !state.init?.initialized; @@ -980,10 +1255,9 @@ 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; - const skips = (rideResult?.skipped ?? ride.filter(r => !['ready', 'already', 'fixture'].includes(r.state)).map(r => ({ id: r.id, reason: r.state }))); - $('proxy-ride-skips').replaceChildren(...skips.map(s => li(`Skipped ${s.id}: ${rideReason(s.reason)}`))); - const listed = rideResult?.fixtures ?? fixtures.map(f => ({ id: f.id, running: f.running })); - $('proxy-ride-fixtures').replaceChildren(...listed.map(f => { + $('proxy-ride-skips').replaceChildren(...rideSkips().map(s => li(`Skipped ${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. if (f.running === null) return li(`${f.id} uses stand-in models. Moving it is not available on this Console.`); const item = li(`${f.id} uses stand-in models, can be moved to the owner's models.${f.running === true ? ' Its bus is running: stop it first.' : ''} `); @@ -1015,17 +1289,16 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }; $('proxy-ride-go').addEventListener('click', () => { if (!$('proxy-ride-go').disabled) rideAll(); }); function paint() { - paintState(); paintNext(); paintControls(); paintReceipts(); paintRestart(); - // An initialized proxy keeps the init form folded after a reload too. - if (state.init.initialized) $('proxy-setup-init-box').open = false; - // #1873 settings slice 1 (D4): the init form shows only while init is the next step. - $('proxy-setup-init-box').hidden = state.next?.[0] !== 'init'; + paintState(); paintControls(); paintReceipts(); paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); paintAccountCard(); const job = state.fetch; - if (job.state === 'running') say(`Fetching: ${STEPS[job.step] ?? job.step ?? 'starting'}…`); + if (job.state === 'running') say(`Downloading: ${STEPS[job.step] ?? job.step ?? 'starting'}…`); else if (job.state === 'failed' && seenFetch !== 'failed') { say(`Fetch failed. ${explain(job.error)}`, 'error'); seenFetch = 'failed'; } else if (job.state === 'done' && job.receipt && seenFetch !== job.receipt.time) { seenFetch = job.receipt.time; if (!state.receipts?.some(r => r.op === 'fetch' && r.time === job.receipt.time)) addReceipt(job.receipt); say(`Fetched ${job.receipt.version}; archive, panel and executable hashes verified.`, 'success'); } clearTimeout(timer); timer = null; - if (enabled && (job.state === 'running' || state.busy)) timer = setTimeout(load, 1000); + if (enabled && !chain?.running && (job.state === 'running' || state.busy)) timer = setTimeout(load, 1000); + // The sidebar's model marks read the same status (MosaicModelDots). + document.dispatchEvent(new CustomEvent('mosaic-proxy-status', { detail: state })); + focusStep(); } async function load() { if (!enabled || loading) return; loading = true; @@ -1034,13 +1307,64 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo finally { loading = false; } } async function act(label, action) { - if (!sendOk || state?.busy) return; - state = { ...state, busy: label }; paintNext(); paintControls(); say('Working…'); + if (!sendOk || state?.busy || chain?.running) return; + state = { ...state, busy: label }; paintService(); paintControls(); say('Working…'); // A load still waiting on accounts makes the load below return at once, so the answer is // painted here first from the state already read. try { await action(); } catch (error) { say(error.message, 'error'); } finally { if (state) { state = { ...state, busy: null }; paint(); } await load(); } } - const fetchRelease = () => act('fetch', async () => { await admin('fetch', {}); seenFetch = null; say('Fetch started.'); }); + // The settings under Advanced, read when the chain starts. A pasted key leaves its fields at once. + function initArgs() { + const f = form.elements, args = {}; + const pasted = pasteAllowed && f.keySource.value === 'paste', key = f.key.value, confirm = f.confirm.value; + f.key.value = ''; f.confirm.value = ''; + if (!form.checkValidity()) { $('proxy-setup-advanced').open = true; form.reportValidity(); say('A setting under Advanced is out of range.', 'error'); return null; } + for (const name of ['port', 'rotateGraceMinutes', 'firstOutputSeconds']) if (f[name].value !== '') args[name] = Number(f[name].value); + if (pasted) { + if (!key) { $('proxy-setup-advanced').open = true; say('Type the key in both fields under Advanced, or choose the generated key.', 'error'); return null; } + if (key !== confirm) { $('proxy-setup-advanced').open = true; say(explain('proxy-key-mismatch'), 'error'); return null; } + args.key = key; args.confirm = confirm; + } else args.generate = true; + return args; + } + const stop = (at, reason) => Object.assign(new Error(reason), { at }); + const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); + // One press: fetch, then init, then install, then start, each posted once and only when the status + // read names it as the next step. A step outside the chain (a lock, a fence) ends the run and shows itself. + async function runChain() { + if (!sendOk || state?.busy || chain?.running) return; + const first = state?.next?.[0]; + const args = ['fetch', 'init'].includes(first) ? initArgs() : {}; + if (args === null) return; + chain = { running: true, tried: new Set(), first, failed: null, step: null }; + clearTimeout(timer); timer = null; say(''); + paint(); + try { + // The first step is the one the button named, from the status already shown; each later one is read again. + for (let i = 0; i < 900 && enabled; i++) { + if (i > 0) { state = await admin('status'); causeRound++; } + const next = state.next?.[0]; + if (state.busy || state.fetch?.state === 'running') { paint(); await pause(1000); continue; } + if (next === 'fetch' && chain.tried.has('fetch')) throw stop('fetch', state.fetch?.state === 'failed' ? `The download failed. ${explain(state.fetch.error)}` : 'The download did not finish.'); + if (next === 'unit-restart' && chain.tried.has('unit-start')) throw stop('answer', 'The service started but did not answer.'); + const runnable = CHAIN.includes(next) || (next === 'unit-restart' && first === 'unit-restart' && !state.fence?.set); + if (!runnable) break; + if (chain.tried.has(next)) throw stop(next, next === 'unit-restart' ? 'The service restarted but still did not answer.' : 'This step did not finish.'); + chain.tried.add(next); chain.step = next; paint(); + try { + if (next === 'fetch') { await admin('fetch', {}); seenFetch = null; } + else if (next === 'init') { const result = await admin('init', args); delete args.key; delete args.confirm; addReceipt(result.receipt); } + else { const result = await admin(`unit/${next.slice(5)}`, {}); addReceipt(result.receipt); } + } catch (error) { throw stop(next, error.message); } + } + } catch (error) { chain.failed = { at: error.at ?? chain.step ?? 'fetch', reason: error.message }; } + finally { + delete args.key; delete args.confirm; + chain.running = false; if (!chain.failed) chain = null; + if (state) paint(); + await load(); + } + } const clearLock = () => act('init-lock-clear', async () => { const result = await admin('init-lock/clear', {}); addReceipt(result.receipt); say('Stale init lock cleared.', 'success'); }); const unitAction = op => act(`unit-${op}`, async () => { const result = await admin(`unit/${op}`, {}); addReceipt(result.receipt); @@ -1049,49 +1373,40 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }); const clearFence = () => act('fence-clear', async () => { const result = await admin('fence/clear', {}); addReceipt(result.receipt); say(result.cleared ? 'Fence cleared.' : 'The fence was not set.', 'success'); }); form.elements.keySource.forEach?.(radio => radio.addEventListener('change', () => { $('proxy-setup-paste').hidden = form.elements.keySource.value !== 'paste'; })); - form.addEventListener('submit', event => { - event.preventDefault(); - const f = form.elements, args = {}; - const pasted = pasteAllowed && f.keySource.value === 'paste', key = f.key.value, confirm = f.confirm.value; - f.key.value = ''; f.confirm.value = ''; - if (!sendOk || state?.busy) return; - for (const name of ['port', 'rotateGraceMinutes', 'firstOutputSeconds']) if (f[name].value !== '') args[name] = Number(f[name].value); - if (pasted) { - if (!key) return say('Type the key in both fields, or choose the generated key.', 'error'); - if (key !== confirm) return say(explain('proxy-key-mismatch'), 'error'); - args.key = key; args.confirm = confirm; - } else args.generate = true; - act('init', async () => { - const result = await admin('init', args); addReceipt(result.receipt); - $('proxy-setup-init-box').open = false; - // #1873 settings slice 1 (D3): which organizations need a restart is a list on this page once the service runs. - say(`Initialized on port ${result.settings.port}${args.generate ? ' with a generated key' : ''}. Install and start the service next.`, 'success'); - }); - }); + form.addEventListener('submit', event => event.preventDefault()); $('proxy-setup-render').addEventListener('click', async () => { const pre = $('proxy-setup-unit-file'); if (!pre.hidden) { pre.hidden = true; return; } try { const result = await admin('unit/render'); pre.textContent = result.text; pre.hidden = false; } catch (error) { say(error.message, 'error'); } }); - box.querySelectorAll('[data-unit]').forEach(button => button.addEventListener('click', () => { if (!button.disabled) unitAction(button.dataset.unit); })); + root.querySelectorAll('[data-unit]').forEach(button => button.addEventListener('click', () => { if (!button.disabled) unitAction(button.dataset.unit); })); return { - start(config) { enabled = true; sendOk = config.proxyAdminSend === true; box.hidden = false; return load(); }, - accounts(n) { accountCount = n; if (state) { paintNext(); paintRestart(); } }, + start(config) { enabled = true; sendOk = config.proxyAdminSend === true; return load(); }, + accounts(n) { accountCount = n; if (state) { paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); } }, // A sign-in, a key or a restart can change the next step: read the whole status again. async reread() { if (!enabled) return; triageSet = null; await load(); }, + enabled: () => enabled, + serviceDone: () => running(), + // An organization whose model list is ready, for Models offered. The open one first. + readyOrg() { const orgs = Array.isArray(state?.organizations) ? state.organizations.filter(o => o.proxy === 'shared' && o.catalogue?.status === 'ready') : []; return (orgs.find(o => o.id === window.MosaicOrg?.id) ?? orgs[0])?.id ?? null; }, stop() { enabled = false; clearTimeout(timer); timer = null; const f = form.elements; f.key.value = ''; f.confirm.value = ''; }, }; })(); - // Panels the not-configured state hides come back once the proxy answers. + // The account parts the not-configured state hides come back once the proxy answers. let accountsShown = true; + const showAccounts = on => { root.querySelectorAll('[data-accounts-part]').forEach(part => { part.hidden = !on; }); }; + function applyWrite() { + root.querySelectorAll('[data-write]').forEach(fieldset => { fieldset.disabled = !canWrite; }); + $('proxy-readonly').hidden = canWrite || !accountsShown; + paintProvider(); + } async function accountsReady() { if (accountsShown) return; try { await refresh(); } catch { return; } - accountsShown = true; $('proxy-message').classList.remove('empty'); - document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el => { el.hidden = false; }); - if (!canWrite) document.querySelectorAll('[aria-labelledby=proxy-signin-title],[aria-labelledby=proxy-apikey-title]').forEach(el => { el.hidden = true; }); - $('proxy-readonly').hidden = canWrite; + accountsShown = true; accountsDown = null; $('proxy-message').classList.remove('empty'); showAccounts(true); + applyWrite(); message('Accounts and client keys loaded.'); + paintAccountCard(); } // #1873 settings slice 1 (D3): a restart from this page's list reads the status again. const onRestarted = () => { setup.reread(); }; @@ -1099,33 +1414,86 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const cleanup = () => { document.removeEventListener('mosaic-org-restarted', onRestarted); setup.stop(); clearTimeout(poll); login = null; const redirect=$('proxy-login-submit')?.elements.redirect_url, key=$('proxy-apikey')?.elements.key; if(redirect)redirect.value='';if(key)key.value=''; }; window.addEventListener('pagehide', cleanup, {once:true}); let devOwner = false, proxyAdmin = false; + const NOT_SET = 'The model service is not set up on this instance.'; fetch('/api/config', { cache: 'no-store' }).then(r => r.json()).then(config => { // F3: an organization's settings writes go with settingsSend (the org Console has no global send). canWrite = (config.send === true || config.settingsSend === true) && config.tester !== true && config.user !== true; devOwner = config.devOwner === true; - document.querySelectorAll('[data-write]').forEach(fieldset => { fieldset.disabled = !canWrite; }); - $('proxy-readonly').hidden = canWrite; - if (!canWrite) document.querySelectorAll('[aria-labelledby=proxy-signin-title],[aria-labelledby=proxy-apikey-title]').forEach(el=>el.hidden=true); proxyAdmin = config.proxyAdmin === true; - if (proxyAdmin) setup.start(config); + applyWrite(); + root.classList.toggle('solo', !proxyAdmin); + if (proxyAdmin) { root.querySelectorAll('[data-admin]').forEach(part => { part.hidden = false; }); setup.start(config); } + paintAccountCard(); return refresh(); }).then(() => message('Accounts and client keys loaded.')).catch(error => { message(error.message); - // #1873: on the setup page a stopped proxy hides the account panels like an unconfigured one, + // #1873: on the setup page a stopped proxy hides the account parts like an unconfigured one, // and the setup load brings them back once the service answers. // Any failed read hides them, not only proxy-down: a proxy that is initialized but not yet answering // can fail with another code, and a stale error over an empty table would stay after Start. - if (proxyAdmin && error.message !== 'The model service is not set up on this instance.') { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el=>el.hidden=true); message(error.code === 'proxy-down' ? 'The model service is not running yet. Follow the next step under Set up the model service.' : `Accounts could not be read${error.code ? ` (${error.code})` : ''}. Follow the next step under Set up the model service; the account panels return once the service answers.`); return; } - if(error.message==='The model service is not set up on this instance.') { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel:not(#proxy-setup), #proxy-refresh').forEach(el=>el.hidden=true); - // #1873: the owner sets the proxy up on this page (Proxy setup above); no terminal note. - if (proxyAdmin) { message('The model service is not set up yet. Follow the next step under Set up the model service.'); return; } - // F3: on a dev instance, say plainly why this page cannot set the proxy up and what does. - // Setup takes a management key typed twice at a terminal and writes the proxy's credentials; - // this page never handles that key. Account sign-in (a provider's own OAuth) then runs here. - if (devOwner) { const org = window.MosaicOrg?.id, note = document.createElement('div'); note.id = 'proxy-dev-setup'; note.className = 'panel'; - note.innerHTML = '

Set up the model service

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

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

'; - note.querySelector('code').textContent = `mosaic proxy fetch\nmosaic proxy init${org ? ` --org ${org}` : ''}`; - $('proxy-message').after(note); } } }); + const hide = () => { accountsShown = false; $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden = true; showAccounts(false); }; + if (proxyAdmin && error.message !== NOT_SET) { hide(); message(error.code === 'proxy-down' ? 'The model service is not running yet. Step 1 sets it up.' : `Accounts could not be read${error.code ? ` (${error.code})` : ''}. Step 1 shows what to do; your accounts show here once the service answers.`); } + else if (error.message === NOT_SET) { hide(); + // #1873: the owner sets the proxy up on this page (step 1); no terminal note. + if (proxyAdmin) message('The model service is not set up yet. Step 1 sets it up.'); + // F3: on a dev instance, say plainly why this page cannot set the proxy up and what does. + // Setup takes a management key typed twice at a terminal and writes the proxy's credentials; + // this page never handles that key. Account sign-in (a provider's own OAuth) then runs here. + else if (devOwner) { const org = window.MosaicOrg?.id, note = document.createElement('div'); note.id = 'proxy-dev-setup'; note.className = 'panel'; + note.innerHTML = '

Set up the model service

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

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

'; + note.querySelector('code').textContent = `mosaic proxy fetch\nmosaic proxy init${org ? ` --org ${org}` : ''}`; + $('proxy-message').after(note); } } + if (!accountsShown) accountsDown = proxyAdmin && error.message !== NOT_SET ? null : $('proxy-message').textContent; + paintAccountCard(); }); return cleanup; } window.MosaicProxy={markup,mount}; })(); +// #1873 settings slice 4 (CHANGES-R3 item 3): the sidebar's model marks, from reads only. The +// instance owner's setup status says, per organization: needs restart (a ready catalogue its bus +// picked up late, or one it can't see that a restart can fix, by its own routes read), can't start +// (stand-in models with its bus stopped while the model service runs) or paused (the model service +// is set up but not answering, for an organization that uses it). Anyone else gets no marks. +(() => { + 'use strict'; + const marks = new Map(); let round = 0, owner = null, last = ''; + const publish = () => document.dispatchEvent(new CustomEvent('mosaic-model-dots')); + async function compute(status) { + if (!status || typeof status !== 'object') return; + const orgs = Array.isArray(status.organizations) ? status.organizations : [], ride = Array.isArray(status.ride) ? status.ride : []; + const key = JSON.stringify([status.next?.[0], status.init?.initialized, orgs.map(o => [o.id, o.catalogue?.status, o.catalogue?.launchRestart]), ride.map(r => [r.id, r.state, r.running])]); + if (key === last) return; last = key; + const turn = ++round, next = new Map(), serviceUp = status.next?.[0] === 'accounts'; + if (status.init?.initialized && !serviceUp) for (const r of ride) if (r.state === 'already') next.set(r.id, 'paused'); + if (serviceUp) { + for (const r of ride) if (r.state === 'fixture' && r.running === false) next.set(r.id, 'cant'); + await Promise.all(orgs.filter(o => !next.has(o.id)).map(async o => { + const c = o.catalogue; + if (c?.status === 'ready' && c.launchRestart === true) { next.set(o.id, 'restart'); return; } + if (c?.status !== 'unavailable') return; + try { + const r = await fetch(`/api/orgs/${encodeURIComponent(o.id)}/bus/routes`, { cache: 'no-store', redirect: 'manual' }); + const cat = r.ok ? (await r.json())?.rows?.[0]?.catalogue : null; + if (!cat || typeof cat !== 'object' || cat.status === 'ready') return; + const cause = window.MosaicConsole?.catalogueCause?.(o.id, cat.notices, cat.reason) ?? null; + if (!cause || cause.restart) next.set(o.id, 'restart'); + } catch { /* unread: no mark */ } + })); + } + if (turn !== round) return; + marks.clear(); for (const [id, mark] of next) marks.set(id, mark); publish(); + } + async function read() { + if (!window.MosaicOrg) return; + try { + if (owner === null) { const r = await fetch('/api/config', { cache: 'no-store' }); owner = r.ok && (await r.json())?.proxyAdmin === true; } + if (!owner) return; + const r = await fetch('/api/proxy/admin/status', { cache: 'no-store', redirect: 'manual' }); + if (r.ok) { last = ''; await compute(await r.json()); } + } catch { /* unread: the marks stay as last read */ } + } + document.addEventListener('mosaic-proxy-status', e => { compute(e.detail); }); + 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 }; +})(); diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index de1c073d8..6f4ae1256 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -291,7 +291,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .settings-content input:disabled,.settings-content select:disabled,.settings-content textarea:disabled{background:var(--raised);border-color:var(--line);color:var(--muted)} .settings-content button,.settings-content summary{min-height:44px;min-width:44px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);padding:8px 18px;font:inherit;cursor:pointer} .settings-content button[type=submit]{background:var(--accent-fill);color:var(--on-accent);border-color:var(--accent-fill)} -.settings-content :is(button,input,select,textarea,a,summary):focus-visible,#settings-nav a:focus-visible,#settings-disclosure:focus-visible{outline:2px solid var(--focus);outline-offset:2px} +.settings-content :is(button,input,select,textarea,a,summary):focus-visible,#settings-nav a:focus-visible,#settings-nav select:focus-visible,#settings-disclosure:focus-visible{outline:2px solid var(--focus);outline-offset:2px} .settings-segments{display:inline-flex;max-width:100%;border:1px solid var(--border);border-radius:var(--r);overflow:hidden} .settings-segments label{position:relative;display:block} .settings-segments input,.palette-tile input{position:absolute;opacity:0;width:1px;height:1px} @@ -309,6 +309,44 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .palette-swatches{display:flex;gap:6px}.palette-swatches i{display:block;width:16px;height:16px;border-radius:50%;background:var(--swatch-canvas);border:1px solid var(--line)}.palette-swatches i:nth-child(2){background:var(--swatch-action);border:0}.palette-swatches i:nth-child(3){background:var(--swatch-accent);border:0} .settings-browser-status{color:var(--success)!important;margin:0!important}.settings-browser-status:not(:empty){margin-top:10px!important}.settings-browser-status.warning{color:var(--warning)!important} .settings-readonly{padding:12px 16px;background:var(--raised);border-radius:var(--r)} +/* #1873 settings slice 4: the organization picker in the nav, and Model setup's step cards. */ +#settings-nav .org-pick{display:flex;flex-direction:column;gap:6px} +#settings-nav .org-pick label{font:inherit;color:inherit} +#settings-nav .org-pick select{min-height:44px;max-width:100%;font:inherit;font-size:14px;color:var(--text);background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:0 10px} +.settings-content .panel.setup-step{display:block;margin:0 0 var(--gap,12px)} +.setup-step>header{display:flex;align-items:center;gap:var(--gap,12px)} +.setup-step>header h3{flex:1;margin:0} +.step-n{flex:none;display:inline-grid;place-items:center;width:28px;height:28px;border-radius:50%;border:1px solid var(--border);font-weight:700;color:var(--muted)} +.setup-step.done .step-n{border-color:var(--success);color:var(--success)} +.setup-step.next .step-n{border-color:var(--action);color:var(--action)} +.setup-step.blocked .step-n{border-color:var(--danger);color:var(--danger)} +.setup-step .summary{margin:6px 0 0 40px} +.setup-step .body{margin:var(--gap,12px) 0 0 40px;min-width:0} +.setup-step.waiting{color:var(--muted)} +.setup-step.waiting h3{color:var(--muted)} +.settings-form{display:grid;gap:var(--pad,16px);max-width:28rem;margin:0} +.settings-form .field{display:flex;flex-direction:column;gap:6px;margin:0;min-width:0} +.settings-form .field>label,.settings-form legend,.settings-form .lbl{font-weight:600;color:var(--strong)} +.settings-form .field :is(input,select){width:100%} +.settings-form .w-num{max-width:12rem} +.settings-form .help{margin:0} +.settings-form .form-foot{display:flex;align-items:center;gap:var(--gap,12px);flex-wrap:wrap} +.settings-form fieldset{border:0;margin:0;padding:0;display:grid;gap:8px;min-width:0} +.rows{margin:var(--gap,12px) 0 0;padding:0;list-style:none} +.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)} +.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)} +.mk-note{border-left:3px solid var(--warning);padding-left:10px} +.model-list{display:grid;gap:0;margin:0;padding:0;list-style:none} +.model-list li{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:center;min-height:44px;padding:4px 0;border-top:1px solid var(--line)} +.model-list li .small{margin-left:auto} +.setup-log{font:13px/1.5 var(--mono,monospace);white-space:pre-wrap;overflow-wrap:anywhere;margin:var(--gap,12px) 0 0;padding:10px;border:1px solid var(--line);border-radius:var(--r);background:var(--raised)} +.err-line{color:var(--danger)} +.settings-content details{margin-top:var(--gap,12px)} +.settings-content details>.inside{margin-top:var(--gap,12px)} +@media(max-width:759px){.rows li{grid-template-columns:1fr}.setup-step .summary,.setup-step .body{margin-left:0}.settings-form{max-width:none}.settings-form .w-num{max-width:none}} @media(max-width:959px) and (min-width:760px){.settings-layout{grid-template-columns:180px minmax(0,1fr);gap:24px}} @media(max-width:759px){.settings-layout{display:block}.settings-layout>div:first-child{margin-bottom:20px}#settings-disclosure{width:100%;min-height:44px;display:flex;align-items:center;gap:12px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);text-align:left}#settings-disclosure small{color:var(--muted)}#settings-disclosure span{margin-left:auto}#settings-disclosure[aria-expanded=false]+#settings-nav{display:none}#settings-nav{padding:12px 0}.settings-content>h2{font-size:21px}.palette-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.palette-content{min-height:64px;padding:7px}.palette-tile input:checked+.palette-content{padding:6px}.settings-segments{display:flex;width:100%}.settings-segments label{flex:1;min-width:0}.settings-segments span,.settings-appearance .panel:last-child .settings-segments span{min-width:0;padding:0 4px}.settings-content .table-wrap{max-width:100%}} .settings-content [aria-invalid=true]{border:2px solid var(--danger)!important} @@ -356,7 +394,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .settings-segments:has(input:focus-visible){outline:2px solid var(--focus);outline-offset:2px} .settings-segments input:focus-visible+span{outline:none} #proxy-authorize:not([hidden]){display:inline-flex;align-items:center;min-height:44px} -.settings-content #proxy-accounts .proxy-priority-save{background:var(--surface);color:var(--text);border-color:var(--border)} +.settings-content #proxy-order .proxy-priority-save{background:var(--surface);color:var(--text);border-color:var(--border)} @media(min-width:760px){#routes-table select{min-width:132px}} @media(max-width:759px){ #agents-table :is(th,td,code){min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;word-break:break-word} @@ -372,9 +410,9 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} @media (max-width:759px) { .table-wrap:has(.s1-agents), .table-wrap:has(.s1-authority), .table-wrap:has(.s1-creds), .table-wrap:has(#token-usage-table), .table-wrap:has(#token-limits-table), - .table-wrap:has(#proxy-accounts), .table-wrap:has(#proxy-keys) { overflow-x:scroll; max-width:100%; } + .table-wrap:has(#proxy-keys) { overflow-x:scroll; max-width:100%; } .s1-agents, .s1-authority, .s1-creds, #token-usage-table, #token-limits-table, - .table-wrap:has(#proxy-accounts) table, .table-wrap:has(#proxy-keys) table { min-width:650px; } + .table-wrap:has(#proxy-keys) table { min-width:650px; } .s1-authority :is(th,td), .s1-creds :is(th,td) { white-space:nowrap; } /* #1873 A2: the root and project agent level grids scroll inside their card. */ .table-wrap:has(#agent-levels-root-grid), .table-wrap:has(#agent-levels-project-grid) { overflow-x:scroll; max-width:100%; } diff --git a/packages/webui/tests/proxy-browser.test.mjs b/packages/webui/tests/proxy-browser.test.mjs index 830504ec9..01283fcd5 100644 --- a/packages/webui/tests/proxy-browser.test.mjs +++ b/packages/webui/tests/proxy-browser.test.mjs @@ -78,7 +78,7 @@ test('proxy browser OAuth opens safely, callback wait stays pending, status ok c test('proxy browser read-only disables account changes', { timeout: 60000 }, async t => { const { b, state } = await setup(t, true); assert.equal(await b.evaluate('[...document.querySelectorAll("[data-write]")].every(e=>e.disabled)'), true); - assert.equal(await b.evaluate('document.querySelector("#proxy-accounts input").disabled'), true); + assert.equal(await b.evaluate('document.querySelector("#proxy-order input").disabled'), true); assert.equal(state.routes.some(r => r.endsWith('/apikey/add') || r.endsWith('/login/start')), false); }); diff --git a/packages/webui/tests/proxy-setup-browser.test.mjs b/packages/webui/tests/proxy-setup-browser.test.mjs index 3902e530a..25181edf8 100644 --- a/packages/webui/tests/proxy-setup-browser.test.mjs +++ b/packages/webui/tests/proxy-setup-browser.test.mjs @@ -1,5 +1,7 @@ // #1873 the Proxy setup panel in a real browser: the next step is one button, init sends a // generated-key request unless the owner pastes a key on loopback, and pasted fields are cleared. +// settings slice 4: the page is four step cards (Model service, Accounts and models, Organizations, +// Triage); one press runs fetch, init, install and start, each posted once. import test from 'node:test'; import assert from 'node:assert/strict'; import { w15Fixture } from './w15-fixture.mjs'; @@ -22,28 +24,34 @@ const fenced = { ...base, release: fetched.release, init: { initialized: true, p const unconfigured = { 'GET /api/proxy/accounts': { status: 503, body: { error: 'not-configured' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'not-configured' } } }; const scenario = (status, config = {}) => ({ '/api/config': { send: true, devOwner: true, proxyAdmin: true, proxyAdminSend: true, ...config }, '/api/proxy/admin/status': status, ...unconfigured }); const writes = b => b.evaluate('window.__writes.filter(w=>w.path.startsWith("/api/proxy/admin/")).map(w=>({path:w.path,body:JSON.parse(w.body)}))'); +// Step 3's line names the step it holds in data-next. +const STEP3 = '#setup-step-organizations [data-step-summary]'; -test('a fresh instance shows the fetch step as one button, the not-built own proxy, and no terminal note', { timeout: 90000 }, async t => { +test('a fresh instance shows Set up model service as one button, the not-built own proxy, and no terminal note', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(base), 'POST /api/proxy/admin/fetch': { status: 202, body: { state: 'running' } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fetch"'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup").hidden'), false); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Fetch the pinned release'); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-next p").textContent'), /CLIProxyAPI 8\.0\.42/); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Set up model service'); + assert.equal(await b.evaluate('document.querySelector("#setup-step-service [data-step-badge]").textContent'), 'Next'); + assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /about a minute to set up/); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-state").textContent'), /pinned 8\.0\.42/); assert.match(await b.evaluate('document.querySelector("#proxy-setup-own").textContent'), /not built/); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-orgs td").textContent'), 'acme'); - await wait('document.querySelector("#proxy-message")?.textContent.includes("Follow the next step under Set up the model service")'); + await wait('document.querySelector("#proxy-message")?.textContent.includes("Step 1 sets it up")'); assert.equal(await b.evaluate('!!document.querySelector("#proxy-dev-setup")'), false, 'the page replaces the terminal note'); - assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-init [data-setup-write]:not([disabled])").length'), 0, 'init waits for a verified release'); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/fetch")'); + // The status still names the download, so the run stops there: nothing is retried by itself. + await wait('document.querySelector("#setup-step-service").dataset.state==="bad"'); assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/fetch', body: {} }]); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Try again'); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); test('without send the next-step button is disabled and nothing is posted', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: scenario(base, { send: false, proxyAdminSend: false }) }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fetch"'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").disabled'), true); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); @@ -52,23 +60,24 @@ test('without send the next-step button is disabled and nothing is posted', { ti test('init sends generate by default; a pasted key on loopback is sent with its confirmation and the fields are cleared', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fetched), 'POST /api/proxy/admin/init': { body: { settings: { port: 18432 }, receipt: { op: 'init', time: T, port: 18432, generated: true } } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init"'); - await b.evaluate('document.querySelector("#proxy-setup-go").click()'); - await wait('document.querySelector("#proxy-setup-init-box").open===true'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Continue setup'); + // The settings sit under Advanced and go with the press. + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-paste-choice").hidden'), false, 'loopback page offers the paste choice'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-paste").hidden'), true); - await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="18432";f.requestSubmit();})()'); + await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="18432";document.querySelector("#proxy-setup-go").click();})()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/init")'); - await wait('document.querySelector("#proxy-setup-message").textContent.includes("with a generated key")'); assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/init', body: { port: 18432, generate: true } }]); assert.match(await b.evaluate('document.querySelector("#proxy-setup-receipts").textContent'), /init/); - await wait('!document.querySelector("#proxy-setup-init [data-setup-write]").disabled'); - await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.keySource.value="paste";f.querySelector("[value=paste]").dispatchEvent(new Event("change"));f.elements.port.value="";f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0002";f.requestSubmit();})()'); + // The status still names init, so the run stops there; Try again starts from it. + await wait('document.querySelector("#proxy-setup-go")?.textContent==="Try again" && !document.querySelector("#proxy-setup-init [data-setup-write]").disabled'); + await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.keySource.value="paste";f.querySelector("[value=paste]").dispatchEvent(new Event("change"));f.elements.port.value="";f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0002";document.querySelector("#proxy-setup-go").click();})()'); await wait('document.querySelector("#proxy-setup-message").textContent.includes("proxy-key-mismatch")'); assert.equal((await writes(b)).length, 1, 'a mismatch is refused in the page'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").elements.key.value'), '', 'the key field is cleared on submit'); - await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0001";f.requestSubmit();})()'); + await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0001";document.querySelector("#proxy-setup-go").click();})()'); await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/init").length===2'); assert.deepEqual((await writes(b))[1], { path: '/api/proxy/admin/init', body: { key: 'pa-browser-sentinel-0001', confirm: 'pa-browser-sentinel-0001' } }); assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup-init input[type=password]")].every(i=>i.value==="")'), true); @@ -77,7 +86,7 @@ test('init sends generate by default; a pasted key on loopback is sent with its test('after a confirmed restart the next step clears the fence and shows the receipt', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fenced), 'POST /api/proxy/admin/fence/clear': { body: { cleared: true, receipt: { op: 'fence.clear', time: T, pid: 4242 } } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fence-clear"'); assert.match(await b.evaluate('document.querySelector("#proxy-setup-state").textContent'), /new pid 4242/); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); @@ -91,10 +100,10 @@ test('a stopped proxy hides the account panels with a setup note, and starting t unit: { unit: 'mosaic-proxy.service', installed: true, active: 'inactive' }, next: ['unit-start'] }; const down = { 'GET /api/proxy/accounts': { status: 503, body: { error: 'proxy-down' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'proxy-down' } } }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(installed), ...down, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit.start', time: T, pid: 4242 } } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-start"'); await wait('document.querySelector("#proxy-message").textContent.includes("not running yet")'); - assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-apikey-title]").hidden'), true); + assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].every(e=>e.hidden)'), true); await b.evaluate(`Object.assign(window.__scenario, { 'GET /api/proxy/accounts': { body: { accounts: [] } }, 'GET /api/proxy/keys': { body: { keys: [] } }, '/api/proxy/admin/status': ${JSON.stringify({ ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, @@ -102,8 +111,7 @@ test('a stopped proxy hides the account panels with a setup note, and starting t await b.evaluate('document.querySelector("#proxy-setup-go").click()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/unit/start")'); await wait('document.querySelector("#proxy-message").textContent.includes("Accounts and client keys loaded")'); - assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-apikey-title]").hidden'), false); - assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), false); + assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].some(e=>e.hidden)'), false); }); test('an initialized proxy whose accounts read fails with another code also hides the panels until it answers', { timeout: 90000 }, async t => { @@ -111,23 +119,23 @@ test('an initialized proxy whose accounts read fails with another code also hide unit: { unit: 'mosaic-proxy.service', installed: true, active: 'inactive' }, next: ['unit-start'] }; const failing = { 'GET /api/proxy/accounts': { status: 503, body: { error: 'outcome-unknown' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'outcome-unknown' } } }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(installed), ...failing, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit.start', time: T, pid: 4242 } } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-start"'); - await wait('document.querySelector("#proxy-message").textContent.includes("the account panels return once the service answers")'); - assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), true); + await wait('document.querySelector("#proxy-message").textContent.includes("your accounts show here once the service answers")'); + assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].every(e=>e.hidden)'), true); await b.evaluate(`Object.assign(window.__scenario, { 'GET /api/proxy/accounts': { body: { accounts: [] } }, 'GET /api/proxy/keys': { body: { keys: [] } }, '/api/proxy/admin/status': ${JSON.stringify({ ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] })} })`); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); await wait('document.querySelector("#proxy-message").textContent.includes("Accounts and client keys loaded")'); - assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), false); + assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].some(e=>e.hidden)'), false); }); test('a fence with no readable time names the --proxy-restarted path instead of a page restart', { timeout: 90000 }, async t => { const timeless = { ...fenced, fence: { set: true, invalid: true }, restart: null, next: ['unit-restart'] }; const { f, b, wait } = await w15Fixture(t, { scenario: scenario(timeless) }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-restart"'); const text = await b.evaluate('document.querySelector("#proxy-setup-next > p").textContent'); assert.match(text, /no readable time.*restart the model service, confirm it answers, then clear the fence\./); @@ -138,37 +146,39 @@ test('a fence with no readable time names the --proxy-restarted path instead of assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next details.proxy-setup-cli p").textContent'), 'Run this in a terminal on this machine: mosaic proxy fence clear --proxy-restarted'); }); -test('after a reload the receipts come from status, and an initialized proxy folds the init form', { timeout: 90000 }, async t => { +test('after a reload the receipts come from status, and an initialized proxy shows its settings read-only', { timeout: 90000 }, async t => { const initialized = { ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, receipts: [{ op: 'fetch', time: T, version: '8.0.42' }, { op: 'init', time: T, generated: true, port: 18432 }], next: ['unit-install'] }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(initialized), 'POST /api/proxy/admin/unit/install': { body: { receipt: { op: 'unit.install', time: T } } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-install"'); assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-receipts li strong")].map(s=>s.textContent)'), ['init', 'fetch'], 'newest first, from proxy-admin.jsonl'); - await b.evaluate('document.querySelector("#proxy-setup-init-box").open = true'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").hidden'), true, 'init is done, so its form is gone'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-settings").textContent'), 'Port18432'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-settings-note").textContent'), 'Changing these after setup is not built yet.'); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/unit/install")'); - await wait('document.querySelector("#proxy-setup-init-box").open===false'); }); // #1873 ride-default: the Ride all box. The confirm names the stricter admission, the answer's // skips and stand-in organizations are painted even while an earlier load still waits on the // accounts read, and the move confirm says the organization spends real tokens after it. test('Ride all confirms the stricter admission, paints skips and stand-in organizations while a load waits, and the move warns of real tokens', { timeout: 90000 }, async t => { - const running = { ...fenced, fence: { set: false }, restart: null, next: ['ride-all'], + const running = { ...fenced, fence: { set: false }, restart: null, next: ['accounts', 'ride-all'], ride: [{ id: 'north', state: 'ready' }, { id: 'south', state: 'ready' }, { id: 'west', state: 'fixture' }] }; - const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running), + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running), ...answering(1), '/api/triage/route': savedRoute, 'POST /api/proxy/admin/ride-all': { body: { added: ['south'], already: [], skipped: [], fixtures: [{ id: 'west' }], receipt: { op: 'ride.all', time: T } } }, 'POST /api/proxy/admin/ride-move': { body: { moved: false, reason: 'bus-running' } } } }); - // The first accounts and keys reads answer not-configured; every later pair never answers, so a load stays in flight. + // The first accounts and keys reads answer; every later pair never answers, so a load stays in flight. await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { const inner = window.fetch; let n = 0; window.__confirms = []; window.confirm = text => { window.__confirms.push(text); return true; }; window.fetch = (input, init) => { const url = String(typeof input === 'string' ? input : input.url); if (url.includes('/api/proxy/accounts') && n++ > 0) return new Promise(() => {}); if (url.includes('/api/proxy/keys') && n > 1) return new Promise(() => {}); return inner(input, init); }; })();` }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-ride")?.hidden===false && document.querySelector("#proxy-setup-go")?.dataset.next==="ride-all"'); + await b.navigate(f.base + '/#/settings/model-setup'); + 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\./); // The first Ride all's own reload paints, then waits on the accounts read for good. @@ -208,7 +218,7 @@ test('Ride all confirms the stricter admission, paints skips and stand-in organi await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/ride-all").length===3'); await wait('document.querySelectorAll("#proxy-ride-skips li").length===3'); assert.deepEqual(JSON.parse(await b.evaluate('JSON.stringify([...document.querySelectorAll("#proxy-ride-skips li")].map(li=>li.textContent))')), [ - 'Skipped north: It used your model service, or Ride all may have added it, and it is off now. Ride all leaves it off. To use it there, choose Use your models on its Routing page.', + 'Skipped north: It used your model service, or Ride all may have added it, and it is off now. Ride all leaves it off. To use it there, choose Use your models on its Models page.', 'Skipped south: Console could not record the change first, so it was not made.', // Re-check 3 (P3-3): a damaged receipts line stops every add until someone repairs it. 'Skipped east: Its organization file, its change log or the model service\'s receipts could not be read. A damaged line in the receipts must be repaired by hand before Ride all adds again.']); @@ -234,7 +244,7 @@ test('settings-s1 B2: once the service runs, the organizations that cannot see t const orgs = [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'beta', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }, { id: 'gamma', proxy: 'shared', catalogue: { status: 'ready', models: 3 } }, { id: 'delta', proxy: 'shared', catalogue: { status: 'disabled' } }]; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, '/api/orgs/acme/bus/routes': routes(), 'POST /api/orgs/acme/restart/bus': restarted } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===2'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-restart").checkVisibility()'), true); assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-restart-list li")].map(li=>[li.dataset.restartOrg, li.querySelector(".badge").className, li.querySelector(".badge").textContent, li.querySelector("[data-org-restart]")?.textContent ?? null])'), @@ -242,7 +252,7 @@ test('settings-s1 B2: once the service runs, the organizations that cannot see t assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null, 'the next step is the list, so no second button'); // acme's bus names no cause, so a restart connects it. beta is not running: it keeps its Restart // and its refusal, and does not hold the next step. - assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart acme\. It has a Restart button under Organizations that can't use your models yet\./); + assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart acme\. It has a Restart button under Organizations that can't use your models yet\./); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-restart-title").textContent'), "Organizations that can't use your models yet"); // A restart reads the status again; the organization stays on the list, now ready, so the owner sees it worked. await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...running, organizations: [{ ...orgs[0], catalogue: { status: 'ready', models: 3 } }, ...orgs.slice(1)] })}`); @@ -253,7 +263,7 @@ test('settings-s1 B2: once the service runs, the organizations that cannot see t assert.deepEqual(await b.evaluate('window.__writes.map(w=>w.method+" "+w.path)'), ['POST /api/orgs/acme/restart/bus']); assert.equal(await b.evaluate('document.querySelector("[data-restart-org=acme] [data-org-restart]")'), null, 'a ready organization has no Restart'); assert.equal(await b.evaluate('document.querySelector("[data-restart-org=acme] .badge").className'), 'badge badge-ok'); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^The model service is set up\. Some organizations still can't see your models\./); + assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^The model service is set up\. Some organizations still can't see your models\./); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -265,7 +275,7 @@ test('settings-s1 B2: Restart shows only where the organization\'s own cause all const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, '/api/orgs/acme/bus/routes': routes(), '/api/orgs/lab/bus/routes': routes([FIXTURE]), '/api/orgs/lock/bus/routes': routes([lock]), 'GET /api/orgs/odd/bus/routes': { status: 500, body: { error: 'x' } }, '/api/orgs/clash/bus/routes': routes([], 'unavailable', 'model-key-collision') } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===5 && !/Checking why/.test(document.querySelector("#proxy-setup-restart-list").textContent)'); const rows = await b.evaluate('Object.fromEntries([...document.querySelectorAll("#proxy-setup-restart-list li")].map(li=>[li.dataset.restartOrg, {badge: li.querySelector(".badge").className, why: li.querySelector(":scope > .small").textContent, restart: li.querySelector("[data-org-restart]")?.textContent ?? null, link: li.querySelector(":scope > .small a")?.getAttribute("href") ?? null, detail: li.querySelector("details summary")?.textContent ?? null}]))'); assert.deepEqual(rows.acme, { badge: 'badge badge-attn', why: "acme can't read your models from the model service yet. A restart connects it.", restart: 'Restart acme', link: null, detail: null }); @@ -274,14 +284,14 @@ test('settings-s1 B2: Restart shows only where the organization\'s own cause all assert.deepEqual(rows.lock, { badge: 'badge badge-attn', why: "lock can't open the model service's shared lock. A restart opens it again.", restart: 'Restart lock', link: null, detail: 'Technical details' }); // Two models that slug to one key: a restart reads the same catalogue again (review 2, P2-A). assert.deepEqual(rows.clash, { badge: 'badge badge-attn', why: "Two of your models get the same short name, so clash can't tell them apart. A restart won't change that. Take one of them out of an API key's Models list on Model setup. If both come from signed-in accounts, this can't be changed from Console yet.", restart: null, link: null, detail: 'Technical details' }); - assert.deepEqual(rows.odd, { badge: 'badge badge-attn', why: "odd can't see your models, and its reason could not be read. Open odd's Routing", restart: null, link: '#/orgs/odd/settings/routing', detail: null }); + assert.deepEqual(rows.odd, { badge: 'badge badge-attn', why: "odd can't see your models, and its reason could not be read. Open odd's Models page", restart: null, link: '#/settings/routing?org=odd', detail: null }); assert.equal(await b.evaluate('document.querySelector("[data-restart-org=lab] details").textContent.includes("fixture-proxy-configured")'), true, 'the bus line is kept under Technical details'); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart acme and lock\./); + assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart acme and lock\./); assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup-restart-list").innerText'), /model proxy/i, 'the bus line shows only once Technical details is opened'); // Once acme and lock see the models, only the fixture, the collision and the unread one are left, and none holds a step. await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...running, organizations: [{ ...orgs[0], catalogue: { status: 'ready', models: 2 } }, orgs[1], { ...orgs[2], catalogue: { status: 'ready', models: 2 } }, orgs[3], orgs[4]] })}`); await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-org-restarted", { detail: { id: "acme" } })); true'); - await wait('/^The model service is set up\\. Some organizations still/.test(document.querySelector("#proxy-setup-next").textContent)'); + await wait(`/^The model service is set up\\. Some organizations still/.test(document.querySelector(${JSON.stringify(STEP3)}).textContent)`); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null); assert.deepEqual(await b.evaluate('window.__writes.map(w=>w.method+" "+w.path)'), [], 'nothing restarts by itself'); }); @@ -290,7 +300,7 @@ test('settings-s1 B2: a refused restart keeps its reason on the list across the const orgs = [{ id: 'lab', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }]; const refusal = { status: 409, body: { error: 'bus-start-refused', message: 'bus start refused: fixture-proxy-configured' } }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, 'POST /api/orgs/lab/restart/bus': refusal } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("[data-org-restart=lab]")'); await b.evaluate('document.querySelector("[data-org-restart=lab]").click()'); await wait('document.querySelector("[data-restart-org=lab] .org-restart-refused")'); @@ -302,9 +312,10 @@ test('settings-s1 B2: a refused restart keeps its reason on the list across the test('settings-s1 B3: a sign-in reads the whole status again and the next step follows accounts, organizations, then the Triage route', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }] }, { orgSetup: true }), ...answering(0), '/api/triage/route': { route: null }, '/api/orgs/acme/bus/routes': routes(), 'POST /api/proxy/login/status': { body: { status: 'error', reason: 'login-timeout' } } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="accounts"'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Add an account'); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait('document.querySelector("#setup-step-accounts")?.dataset.state==="next"'); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude'); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").className'), 'btn primary'); await b.evaluate(`window.open = () => null; window.__scenario['POST /api/proxy/login/start'] = { body: { url: location.origin + '/signin-stub', state: 's1' } }`); // A sign-in that runs out of time says so plainly. await b.evaluate('document.querySelector("#proxy-login-start").requestSubmit()'); @@ -312,15 +323,14 @@ test('settings-s1 B3: a sign-in reads the whole status again and the next step f // The next sign-in finishes. The status read after it is the one that names acme, so the step proves the reread. await b.evaluate(`Object.assign(window.__scenario, ${JSON.stringify({ ...answering(1), 'POST /api/proxy/login/status': { body: { status: 'ok' } }, '/api/proxy/admin/status': { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }] } })})`); await b.evaluate('document.querySelector("#proxy-login-start").requestSubmit()'); - await wait('document.querySelector("#proxy-setup-next [data-next]")?.dataset.next==="restart-orgs"'); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart acme\./); + await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="restart-orgs"`); + assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart acme\./); assert.equal(await b.evaluate('document.querySelector("#proxy-login-message").textContent'), 'Account signed in.'); // acme restarts and can see the models; the Triage route is not set, so that is the step after. await b.evaluate(`Object.assign(window.__scenario, ${JSON.stringify({ 'POST /api/orgs/acme/restart/bus': restarted, '/api/proxy/admin/status': { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }] } })})`); await b.evaluate('document.querySelector("[data-org-restart=acme]").click()'); - await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="triage-route"'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Open Triage settings'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").disabled'), false); + await wait('document.querySelector("#setup-step-triage")?.dataset.state==="next"'); + assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-setup-triage").textContent, document.querySelector("#proxy-setup-triage").className]'), ['Set up Triage', 'btn primary']); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -330,10 +340,10 @@ test('settings-s1 B3 with ride-default: Ride all follows accounts while an organ const riding = { ...running, next: ['accounts', 'ride-all'], organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'north', state: 'ready' }, { id: 'west', state: 'fixture' }] }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(riding), ...answering(1), '/api/triage/route': { route: null } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="ride-all"'); - // settings-p3 (rebase re-check P3-3): the step button is not a second "Ride all"; it goes to the box's own button. - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Go to Ride all'); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="ride-all"`); + // settings-s4: the step is Ride all's own button, the page's primary one. + assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").className'), 'btn primary'); assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup button")].filter(e=>e.checkVisibility()&&e.textContent==="Ride all").length'), 1, 'one Ride all button'); assert.equal(await b.evaluate('document.querySelector("#proxy-ride").checkVisibility()'), true, 'the Ride all box is not folded under Technical details'); assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), false); @@ -341,7 +351,7 @@ test('settings-s1 B3 with ride-default: Ride all follows accounts while an organ await b.evaluate(`window.confirm = () => true; Object.assign(window.__scenario, ${JSON.stringify({ '/api/proxy/admin/status': { ...riding, ride: [{ id: 'north', state: 'already' }, { id: 'west', state: 'fixture' }] }, 'POST /api/proxy/admin/ride-all': { body: { added: ['north'], already: [], skipped: [], fixtures: [{ id: 'west' }], receipt: { op: 'ride.all', time: T } } } })})`); await b.evaluate('document.querySelector("#proxy-ride-go").click()'); - await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="triage-route"'); + await wait('document.querySelector("#setup-step-triage")?.dataset.state==="next"'); assert.equal(await b.evaluate('document.querySelector("[data-ride-move=west]").checkVisibility()'), true); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -350,8 +360,8 @@ test('settings-s1 B3 with ride-default: Ride all follows accounts while an organ test('settings-p3: Ride all is not the next step when the owner cannot send', { timeout: 90000 }, async t => { const riding = { ...running, next: ['accounts', 'ride-all'], organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'north', state: 'ready' }] }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(riding, { proxyAdminSend: false }), ...answering(1), '/api/triage/route': { route: null } } }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="triage-route"'); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait('document.querySelector("#setup-step-triage")?.dataset.state==="next"'); assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), true); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -361,14 +371,14 @@ test('settings-p3: Ride all is not the next step when the owner cannot send', { test('settings-p3: the done line does not say every organization while the Ride all box still lists one', { timeout: 90000 }, async t => { const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'west', state: 'fixture' }] }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(done), ...answering(1), '/api/triage/route': savedRoute } }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-setup-next [data-next]")?.dataset.next==="done"'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), 'The model service is set up. Some organizations still need a step under Use your models in every organization.'); - assert.equal(await b.evaluate('document.querySelector("#proxy-ride").checkVisibility() && document.querySelector("#proxy-ride h3").textContent'), 'Use your models in every organization'); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="done"`); + assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), 'The model service is set up. Some organizations still need a step under Use your models in every organization.'); + assert.equal(await b.evaluate('document.querySelector("#proxy-ride").checkVisibility() && document.querySelector("#proxy-ride h4").textContent'), 'Use your models in every organization'); // Once nothing is listed there, the line says every organization. await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...done, ride: [{ id: 'acme', state: 'already' }] })}`); await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-org-restarted", { detail: { id: "acme" } })); true'); - await wait('document.querySelector("#proxy-setup-next").textContent==="The model service is set up and every organization can see your models."'); + await wait(`document.querySelector(${JSON.stringify(STEP3)}).textContent==="The model service is set up and every organization can see your models."`); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -377,9 +387,9 @@ test('settings-p3: the done line does not say every organization while the Ride test('settings-p3: the done line does not say every organization while one can still ride and the owner cannot send', { timeout: 90000 }, async t => { const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'ready' }] }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(done, { proxyAdminSend: false }), ...answering(1), '/api/triage/route': savedRoute } }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-setup-next [data-next]")?.dataset.next==="done"'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), 'The model service is set up. Some organizations still need a step under Use your models in every organization.'); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="done"`); + assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), 'The model service is set up. Some organizations still need a step under Use your models in every organization.'); assert.match(await b.evaluate('document.querySelector("#proxy-ride-text").textContent'), /1 organization can ride now\./); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -389,7 +399,7 @@ test('settings-p3: the done line does not say every organization while one can s test('settings-p3: a stand-in organization with no bus status is not offered a Move', { timeout: 90000 }, async t => { const state = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'west', state: 'fixture', running: null }, { id: 'east', state: 'fixture' }] }; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(state), ...answering(1), '/api/triage/route': savedRoute } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + 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."]); @@ -403,11 +413,11 @@ test('settings-p3: a stand-in organization with no bus status is not offered a M test('settings-p3: an organization whose agents start on the models only after a restart is listed and holds the next step', { timeout: 90000 }, async t => { const orgs = [{ id: 'late', proxy: 'shared', catalogue: { status: 'ready', models: 2, launchRestart: true } }]; const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute } }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===1'); assert.deepEqual(await b.evaluate('(li=>[li.querySelector(".badge").className, li.querySelector(".badge").textContent, li.querySelector(":scope > .small").textContent, li.querySelector("[data-org-restart]")?.textContent ?? null])(document.querySelector("[data-restart-org=late]"))'), ['badge badge-attn', 'Restart needed', 'late can see your models. Its agents start on them after a restart.', 'Restart late']); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart late\./); + assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart late\./); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -416,7 +426,7 @@ test('settings-p3: an organization whose agents start on the models only after a test('settings-p3: the init lock and partial init steps say what to do, with the README path under Technical details', { timeout: 90000 }, async t => { const held = { ...fetched, initLock: { present: true, clearable: false, blockers: ['the bus for acme is running'] }, next: ['init-lock-wait'] }; const { f, b, wait } = await w15Fixture(t, { scenario: scenario(held) }); - await b.navigate(f.base + '/#/settings/model-proxy'); + await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init-lock-wait"'); const read = 'JSON.stringify({text: document.querySelector("#proxy-setup-next > p").textContent, summary: document.querySelector("#proxy-setup-next details summary")?.textContent, lead: document.querySelector("#proxy-setup-next details p")?.textContent, code: document.querySelector("#proxy-setup-next details code")?.textContent, open: document.querySelector("#proxy-setup-next details")?.open, button: document.querySelector("#proxy-setup-go").textContent})'; assert.deepEqual(JSON.parse(await b.evaluate(read)), { @@ -434,12 +444,13 @@ test('settings-p3: the init lock and partial init steps say what to do, with the test('settings-s1 B4: only the next step has a button; done steps, Fence, Init lock and the service controls sit under Technical details', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running), ...answering(0), '/api/triage/route': savedRoute } }); - await b.navigate(f.base + '/#/settings/model-proxy'); - await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="accounts"'); - assert.deepEqual(await b.evaluate(`${visible('#proxy-setup button')}.map(e=>e.id||e.textContent)`), ['proxy-setup-go'], 'one visible button in the setup panel'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init-box").checkVisibility()'), false, 'init is done, so its form is gone'); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait('document.querySelector("#setup-step-accounts")?.dataset.state==="next"'); + assert.deepEqual(await b.evaluate(`${visible('.settings-content .primary')}.map(e=>e.id||e.textContent)`), ['proxy-login-go'], 'one primary button on the page'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null, 'step 1 is done, so it has no button'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").checkVisibility()'), false, 'init is done, so its form is gone'); const tech = await b.evaluate('(()=>{const d=document.querySelector("#proxy-setup-tech");return {summary:d.querySelector("summary").textContent,open:d.open,terms:[...d.querySelectorAll("dt")].map(x=>x.textContent),units:d.querySelectorAll("[data-unit]").length,receipts:!!d.querySelector("#proxy-setup-receipts")}})()'); - assert.deepEqual(tech, { summary: 'Technical details', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock'], units: 4, receipts: true }); + assert.deepEqual(tech, { summary: 'Technical details: release, service, history', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock'], units: 4, receipts: true }); assert.equal(await b.evaluate(`${visible('#proxy-setup dt, #proxy-setup [data-unit]')}.length`), 0, 'nothing technical shows until it is opened'); // Technical details opens by keyboard and shows the controls. await b.evaluate('document.querySelector("#proxy-setup-tech summary").focus()'); diff --git a/packages/webui/tests/settings-review-browser.test.mjs b/packages/webui/tests/settings-review-browser.test.mjs index 21548152f..0628933d1 100644 --- a/packages/webui/tests/settings-review-browser.test.mjs +++ b/packages/webui/tests/settings-review-browser.test.mjs @@ -14,7 +14,7 @@ async function page(t,section,width=1440,options={}) { await wait(`document.querySelector('#settings-page-title')?.textContent===${JSON.stringify(({agents:'Agents',routing:'Routing',limits:'Launch limits',assistant:'Assistant',appearance:'Appearance','model-proxy':'Model setup'})[section])}`); if(section==='agents')await wait('!!document.querySelector(".agent-more")'); if(section==='routing')await wait('!!document.querySelector("[data-route]")'); - if(section==='model-proxy')await wait('!!document.querySelector("#proxy-accounts form")'); + if(section==='model-proxy')await wait('!!document.querySelector("#proxy-order form")'); return x; } async function pointer(b,sel,xpart=.5){const pt=await b.evaluate(`(()=>{let e=document.querySelector(${JSON.stringify(sel)});e.scrollIntoView({block:'center'});let r=e.getBoundingClientRect();return {x:r.left+r.width*${xpart},y:r.top+r.height/2}})()`);for(const type of ['mousePressed','mouseReleased'])await b.call('Input.dispatchMouseEvent',{type,...pt,button:'left',clickCount:1});} @@ -29,13 +29,13 @@ test('F6 add agent labels left aligned with launch on own row',opts,async t=>{co test('F7 maximum length agent values wrap at 390',opts,async t=>{const {b}=await page(t,'agents',390);assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);}); test('F8 root proxy route mounts its settings section',opts,async t=>{const {b}=await page(t,'model-proxy');assert.equal(await b.evaluate('location.pathname'),'/');assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts")'),true);}); test('F9 add agent saving and refusal remain local and visible',opts,async t=>{const {b,wait}=await page(t,'agents');await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');await input(b,'#instance-add-form [data-instance-field=instance]','new-coder');await b.evaluate(`document.querySelector('#instance-add-form select').value='coder';window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#instance-add-form').requestSubmit()`);await wait('!!window.__answer && !!document.querySelector("#instance-add-form .settings-spinner")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-change-form select").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("#instances-receipt")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .banner.err")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-add-form .banner.err").getBoundingClientRect().bottom<=document.querySelector("#instance-add-form button[type=submit]").getBoundingClientRect().top'),true);}); -test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await pointer(b,'#settings-nav a[href="#/settings/model-proxy"]');await wait('!!document.querySelector("#proxy-accounts form")');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-accounts button")).backgroundColor===getComputedStyle(document.querySelector("#proxy-refresh")).backgroundColor'),true);}); +test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await pointer(b,'#settings-nav a[href="#/settings/model-setup"]');await wait('!!document.querySelector("#proxy-order form")');await pointer(b,'#setup-step-accounts .step-toggle');await wait('!document.querySelector("#setup-step-accounts-body").hidden');await pointer(b,'#proxy-add-box summary');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-order .proxy-priority-save")).backgroundColor===getComputedStyle(document.querySelector("#proxy-refresh")).backgroundColor'),true);}); test('F11 Vars fields have labels and mobile agent values identify columns',opts,async t=>{const {b,wait}=await page(t,'agents',390);assert.equal(await b.evaluate('document.querySelector("#instance-add-form textarea").labels.length>0'),true);assert.match(await b.evaluate('document.querySelector("#agents-table tbody tr").innerText'),/Definition/);assert.equal(await b.evaluate('document.querySelector("#agents-table tbody td").getAttribute("headers")'), 'agent-col-definition');await b.viewport(1440,1000);await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');assert.equal(await b.evaluate('document.querySelector("#instance-change-form textarea").labels.length>0'),true);}); test('F12 collapsed section announces current draft and clears after discard',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`(()=>{let e=[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking');e.value='xhigh';e.dispatchEvent(new Event('change',{bubbles:true}))})()`);assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),true);assert.match(await b.evaluate('document.querySelector("#settings-disclosure").textContent'),/unsaved changes/);await pointer(b,'#routes-reload');await wait('!document.querySelector("#settings-nav .settings-dot")');assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),false);}); test('F13 each browser save receipt expires independently',opts,async t=>{const {b}=await page(t,'appearance');await b.evaluate('document.querySelector("[name=theme][value=dim]").focus();document.querySelector("[name=theme][value=dim]").click();document.querySelector("[name=palette][value=grove]").focus();document.querySelector("[name=palette][value=grove]").click();document.querySelector("[name=density][value=compact]").focus();document.querySelector("[name=density][value=compact]").click()');await b.evaluate('new Promise(r=>setTimeout(r,4200))');assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".settings-browser-status")].map(e=>e.textContent)'),['','','']);}); test('F14 settings subtitle is 16px and fallback option is None',opts,async t=>{const {b,wait}=await page(t,'appearance');assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#bus-view .page-head p")).fontSize'),'16px');await b.evaluate('location.hash="#/settings/routing"');await wait('!!document.querySelector(".fallback-cell select")');assert.equal(await b.evaluate('document.querySelector(".fallback-cell select option").textContent'),'None');}); test('F9 assistant saving shows spinner and local refusal',opts,async t=>{const {b,wait}=await page(t,'assistant');await input(b,'[data-assistant-field=definition]','changed');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('.assistant-form').requestSubmit()`);await wait('!!window.__answer && !!document.querySelector(".assistant-form .settings-spinner")');assert.equal(await b.evaluate('!!document.querySelector(".assistant-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("[data-assistant-receipt]")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('document.querySelector("[data-assistant-receipt]").classList.contains("err")'),true);}); -test('F9 proxy priority disables input and shows saving',opts,async t=>{const {b,wait}=await page(t,'model-proxy');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#proxy-accounts form').requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-accounts input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#proxy-apikey [name=key]").matches(":disabled")'),false);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-accounts form .banner.err")');await b.evaluate(`window.__answer=null;let f=document.querySelector('#proxy-apikey');f.elements.key.value='fixture-key';f.requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-apikey .settings-spinner")'),true);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-apikey-message.banner.err")');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").value'), '');}); +test('F9 proxy priority disables input and shows saving',opts,async t=>{const {b,wait}=await page(t,'model-proxy');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#proxy-order form').requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-order input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-order .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#proxy-apikey [name=key]").matches(":disabled")'),false);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-order form .banner.err")');await b.evaluate(`window.__answer=null;let f=document.querySelector('#proxy-apikey');f.elements.key.value='fixture-key';f.requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-apikey .settings-spinner")'),true);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-apikey-message.banner.err")');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").value'), '');}); test('F3 routing refusal remains visible and announced in the phone draft bar',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`__scenario['POST /api/routes']={status:409,body:{message:'Fixture conflict',sent:false}};[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking').focus()`);await b.key('ArrowDown');await wait('!!document.querySelector("#settings-disclosure .settings-dot")');await pointer(b,'#routes-form button[type=submit]');await wait('document.querySelector("#routes-receipt")?.textContent.includes("Fixture conflict")');assert.deepEqual(await b.evaluate(`(()=>{const e=document.querySelector('#routes-receipt'),r=e.getBoundingClientRect();return {visible:r.width>0&&r.height>0,role:e.getAttribute('role'),banner:e.classList.contains('err')}})()`),{visible:true,role:'status',banner:true});}); test('F9 simultaneous assistant card refusals stay with their own drafts',opts,async t=>{const {b,wait}=await page(t,'assistant');await b.evaluate(`window.__answers={};window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answers[u]=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o)`);await input(b,'[data-assistant-field=definition]','changed');await b.evaluate('document.querySelector(".assistant-form").requestSubmit()');await wait('!!window.__answers["/api/settings"] && !!document.querySelector(".assistant-form .settings-spinner")');await input(b,'[data-assistant-field=name]','Wren');await b.key('Enter');await wait('!!window.__answers["/api/name"]');await b.evaluate(`__answers['/api/name'](409,{message:'Name refused',sent:false})`);await wait('document.querySelector("[data-assistant-kind=name]")?.textContent.includes("Name refused")');await b.evaluate(`__answers['/api/settings'](409,{message:'Settings refused',sent:false})`);await wait('document.querySelector("[data-assistant-kind=settings]")?.textContent.includes("Settings refused")');assert.match(await b.evaluate('document.querySelector("[data-assistant-kind=name]").textContent'),/Name refused/);assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").value'),'Wren');assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=definition]").value'),'changed');}); test('S5 routing remains inside its panel and reaches the last fallback control',opts,async t=>{ @@ -46,8 +46,10 @@ test('S5 routing remains inside its panel and reaches the last fallback control' test('S5 mobile token use, proxy and held roles expose their clipped columns',opts,async t=>{ const {b,wait}=await page(t,'model-proxy',390); await b.evaluate(`__scenario['/api/bus/usage']={rows:[{total:{input:1,output:2,cacheWrite:3,cacheRead:4,unknownTurns:5}}]};__scenario['/api/bus/agents']={rows:[{role:'assistant',state:'idle',attention:'none',holder:'fixture',at:'2026-11-06T10:25:00Z'}]}`); - for(const [route,selector] of [['/settings/model-proxy','#proxy-accounts'],['/settings/tokens','#token-usage-table'],['/agents','.s1-agents']]){ - if(route!=='/settings/model-proxy')await b.evaluate(`location.hash=${JSON.stringify('#'+route)}`); + // settings slice 4: accounts are rows that wrap, not a table, so they fit the phone with nothing clipped. + assert.deepEqual(await b.evaluate('(()=>{const e=document.querySelector("#proxy-accounts");return {fits:e.getBoundingClientRect().right<=document.documentElement.clientWidth,page:document.documentElement.scrollWidth<=innerWidth}})()'),{fits:true,page:true}); + for(const [route,selector] of [['/settings/tokens','#token-usage-table'],['/agents','.s1-agents']]){ + await b.evaluate(`location.hash=${JSON.stringify('#'+route)}`); await wait(`document.querySelector(${JSON.stringify(selector)})`); const r=await b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(selector)}).closest('.table-wrap');return {overflow:getComputedStyle(e).overflowX,scroll:e.scrollWidth,client:e.clientWidth,right:e.getBoundingClientRect().right,viewport:document.documentElement.clientWidth}})()`); assert.ok(r.right<=r.viewport && r.scroll>r.client && r.overflow==='scroll',route+' '+JSON.stringify(r)); -- 2.54.0 From 32b56b8351d7aed937e8f8f6f524c9c2943efbac Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:38:58 -0600 Subject: [PATCH 03/14] =?UTF-8?q?feat(webui):=20settings-s4=20sidebar=20ma?= =?UTF-8?q?rks:=20an=20organization=20whose=20models=20need=20a=20restart?= =?UTF-8?q?=20reads=20"needs=20restart"=20(=E2=97=90),=20one=20on=20stand-?= =?UTF-8?q?in=20models=20whose=20bus=20can't=20start=20reads=20"can't=20st?= =?UTF-8?q?art"=20(=E2=96=B2),=20and=20one=20riding=20a=20model=20service?= =?UTF-8?q?=20that=20is=20set=20up=20but=20not=20running=20reads=20"paused?= =?UTF-8?q?"=20(=E2=97=90);=20restart=20and=20paused=20show=20only=20on=20?= =?UTF-8?q?a=20running=20bus;=20the=20dashboard's=20Model=20setup=20card?= =?UTF-8?q?=20links=20#/settings/model-setup;=20an=20organization's=20Sett?= =?UTF-8?q?ings=20page=20marks=20it=20in=20the=20sidebar=20(#1873,=20lane?= =?UTF-8?q?=20settings-s4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webui/src/public/workspace.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 0fc9740b0..f89fbc160 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -52,7 +52,11 @@ } const av = (org, size = '') => ``; const label = org => org.label || org.id; - const state = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : org.busStopped ? ['s-offline', '○', 'bus stopped'] : ['s-offline', '○', 'bus unavailable']); + // #1873 settings slice 4: the instance owner's model marks (display.js MosaicModelDots) sit over the + // bus state. Can't start always shows; needs restart and paused only on a running bus. + const MODEL_MARKS = { cant: ['s-error', '▲', "can't start"], restart: ['s-waiting', '◐', 'needs restart'], paused: ['s-waiting', '◐', 'paused'] }; + const busState = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : org.busStopped ? ['s-offline', '○', 'bus stopped'] : ['s-offline', '○', 'bus unavailable']); + const state = org => { const mark = org.invalid ? null : window.MosaicModelDots?.get(org.id); return mark === 'cant' || (mark && org.busHealthy) ? MODEL_MARKS[mark] : busState(org); }; // A status mark: a glyph plus its word, shown or read aloud only. const dot = (cls, glyph, word, shown = false) => `${shown ? esc(word) : `${esc(word)}`}`; const orgHref = id => `#/orgs/${enc(id)}`; @@ -126,7 +130,7 @@ const key = focusKey(root); if (orgError || !orgs) { root.innerHTML = `

${orgError ? 'Organizations unavailable' : 'Reading organizations…'}

`; return; } // SP1: a system route (the dashboard) marks no organization; an organization route marks its own. - const here = route(), selected = /^#\/orgs\//.test(location.hash) ? window.MosaicOrg?.id : null; + const here = route(), selected = /^#\/orgs\//.test(location.hash) || /^#\/settings\/[^?]+\?(?:[^#]*&)?org=/.test(location.hash) ? window.MosaicOrg?.id : null; const rows = orgs.map(org => { const [cls, glyph, word] = state(org), mine = org.id === selected, current = mine && here === '/organization'; return `
  • ${av(org)}${esc(label(org))}${dot(cls, glyph, word, cls !== 's-working')}
  • `; @@ -157,6 +161,7 @@ }); window.addEventListener('hashchange', () => { if (orgs) paint(); }); document.addEventListener('mosaic-org-list', e => refresh(e.detail?.rows)); + document.addEventListener('mosaic-model-dots', () => { if (orgs) paint(); }); // ---------- organization dashboard (sample 03) ---------- const SAFE = /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,159}$/; @@ -200,7 +205,7 @@ ['ledger', 'Launch limits', !s ? unread : s.launch?.refused ? unread : Number.isFinite(total) ? `${plural(total, 'session')} at once` : 'No session limit', 'org file', 'limits'], ['talk', 'Assistant', 'The assistant agent and its seat names', 'org file', 'assistant'], ['ledger', 'Token use', 'Usage and limits per provider and model', 'system', 'tokens'], - ['term', 'Model setup', 'Your model service and its accounts', 'system', 'model-proxy'], + ['term', 'Model setup', 'Your model service and its accounts', 'system', 'model-setup'], ['restart', 'Console', 'Console restart', 'system', 'console'], ['business', 'Organizations', orgCount === null ? unread : plural(orgCount, 'organization'), 'system', 'organizations'], ['flag', 'About', typeof s?.release === 'string' ? `Release ${s.release}` : 'Address, release and notifier', 'system', 'about'], @@ -307,7 +312,7 @@ const bus = restart ? (org.busHealthy ? `${restart}` : '') : ` `; // SP11 (#1873): the line beside the disabled reload says how a change to the organization file loads. const reload = ``; - const [bcls, bglyph] = state(org); + const [bcls, bglyph] = busState(org); const meta = `

    Kind not recordedid ${esc(id)}Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : org.busStopped ? `bus stopped, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}The bus reads the organization file when it starts. To load a change to the file, restart the bus.

    `; const projectName = pid => projectRows?.find(p => p.id === pid)?.name || pid; -- 2.54.0 From b9b3e56821a32cbe457af52a51a89c90b200e88a Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:38:58 -0600 Subject: [PATCH 04/14] test(webui): settings-s4: nav groups, the picker and ?org= pages, the old addresses, the phone section button with no sideways scroll, the three sidebar marks, the one-press chain in order, a failed step with Try again and last lines, ?step=, account rows and the provider-picked add form with sign-in cancel and paste-back, Models offered read-only with search, and the done line with a removed organization; all 11 fail on 6c5ec23b4 (#1873, lane settings-s4) --- .../webui/tests/settings-s4-browser.test.mjs | 303 ++++++++++++++++++ 1 file changed, 303 insertions(+) create mode 100644 packages/webui/tests/settings-s4-browser.test.mjs diff --git a/packages/webui/tests/settings-s4-browser.test.mjs b/packages/webui/tests/settings-s4-browser.test.mjs new file mode 100644 index 000000000..644d2a0f3 --- /dev/null +++ b/packages/webui/tests/settings-s4-browser.test.mjs @@ -0,0 +1,303 @@ +// #1873 settings slice 4 (DESIGN.md sections 2 and 4, CHANGES-R3): the Settings nav in four groups with +// the organization picker, organization pages at #/settings/?org=, the old addresses still +// open their pages, Model setup's four step cards and its one-press chain, the accounts list with +// health badges, Models offered read-only, the sidebar's model marks, and the Ride all done line that +// does not count an organization that turned the model service off. +// Part A runs the real server with fake organization buses (acme and north answer, gamma is stopped). +// Part B is the single-business Console with every API answer explicit (w15-fixture.mjs). +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'; +import { w15Fixture } from './w15-fixture.mjs'; + +// ---- Part A: organizations ------------------------------------------------------------------- +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() { + 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 }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => ({ ...VIEW, 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 instance owner's flags on /api/config and the model service status, by path suffix (display.js +// scopes some reads under /api/orgs//). Everything else is the real server. +const SERVICE_UP = { next: ['accounts'], init: { initialized: true, 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 }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] }; +const ownerStub = (service = SERVICE_UP) => `(() => { + const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service })}; + 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') 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/admin/status')) return json(__s4.service); + if (path.endsWith('/proxy/accounts')) return json({ accounts: [] }); + if (path.endsWith('/proxy/keys')) return json({ keys: [] }); + if (path.endsWith('/triage/route')) return json({ route: null }); + return real(input, init); + }; +})();`; + +async function orgSetup(t, { path, viewport = [1440, 900], service } = {}) { + const { organizations, agentLevels } = await orgFixture(); + 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(service) }); + 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)})()`); + return { b, wait, text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`) }; +} + +test('settings-s4: the nav has four groups, the organization pages carry ?org=, the picker switches organization, and there is no Members row', { timeout: 90000 }, async t => { + const { b, wait, text } = await orgSetup(t, { path: '/#/settings/routing?org=acme' }); + await wait('document.querySelector("#org-pick") && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=acme\'][aria-current=page]")'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav .settings-group")].map(g => (g.querySelector("label") ?? g).textContent.trim())'), + ['You', 'Your models', 'All organizations', 'This organization']); + const links = await b.evaluate('[...document.querySelectorAll("#settings-nav a")].map(a => a.getAttribute("href"))'); + assert.deepEqual(links.slice(0, 2), ['#/settings/appearance', '#/settings/model-setup']); + assert.ok(links.includes('#/settings/triage'), 'the instance owner sees Triage under Your models'); + for (const page of ['organizations', 'console', 'about']) assert.ok(links.includes(`#/settings/${page}`), page); + const orgLinks = links.filter(h => /\?org=/.test(h)); + assert.deepEqual(orgLinks.map(h => h.replace(/^#\/settings\/|\?org=acme$/g, '')), ['routing', 'agents', 'limits', 'tokens', 'assistant', 'business']); + assert.equal(links.some(h => /members/.test(h)), false, 'no Members row'); + // The picker lists every organization, the open one selected, and sits above the organization's pages. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#org-pick option")].map(o => [o.value, o.textContent, o.selected])'), + [['acme', 'Acme Studio', true], ['gamma', 'Gamma Home', false], ['north', 'North Works', false]]); + assert.match(await text('#breadcrumbs'), /Acme Studio/); + // Every page is one click from the open nav: all its links are visible at 1440. + assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].every(a => a.checkVisibility())'), true); + await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "north"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await wait('location.hash === "#/settings/routing?org=north" && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=north\']")'); + await wait('/North Works/.test(document.querySelector("#breadcrumbs")?.textContent ?? "")'); + // Keyboard: the picker takes focus with a visible ring. + await b.evaluate('document.querySelector("#org-pick").focus(); true'); + assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none'); +}); + +test('settings-s4: the old addresses still open their pages', { timeout: 90000 }, async t => { + const { b, wait } = await orgSetup(t, { path: '/#/orgs/acme/settings/routing' }); + await wait('location.hash === "#/settings/routing?org=acme"'); + await b.evaluate('location.hash = "#/settings/model-proxy"; true'); + await wait('location.hash === "#/settings/model-setup" && document.querySelector("#proxy-setup")'); + assert.equal(await b.evaluate('document.querySelector("#settings-page-title")?.textContent'), 'Model setup'); + await b.evaluate('location.hash = "#/orgs/acme/settings/model-proxy"; true'); + await wait('!location.hash.includes("model-proxy") && document.querySelector("#proxy-setup")'); + assert.equal(await b.evaluate('document.querySelector("#settings-page-title")?.textContent'), 'Model setup'); + await b.evaluate('location.hash = "#/orgs/north/settings/agents"; true'); + await wait('location.hash === "#/settings/agents?org=north"'); +}); + +test('settings-s4: at 390 the section button names the organization and the page, and nothing scrolls sideways', { timeout: 90000 }, async t => { + const { b, wait } = await orgSetup(t, { path: '/#/settings/routing?org=acme', viewport: [390, 844] }); + await wait('document.querySelector("#settings-disclosure strong")?.textContent.includes("Models")'); + assert.equal(await b.evaluate('document.querySelector("#settings-disclosure strong").textContent.trim()'), 'Acme Studio · Models'); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true); + await b.evaluate('location.hash = "#/settings/model-setup"; true'); + await wait('document.querySelector("#setup-step-service")?.dataset.state'); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true); +}); + +const mark = id => `document.querySelector('[data-workspace-org=${id}] .ws-dot')?.title`; +test('settings-s4: the sidebar marks an organization that needs a restart and one that can\'t start, from the setup status', { timeout: 90000 }, async t => { + const service = { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready' } }], + ride: [{ id: 'gamma', state: 'fixture', running: false }] }; + const { b, wait } = await orgSetup(t, { path: '/#/dashboard', service }); + await wait(`${mark('acme')} === 'needs restart' && ${mark('gamma')} === "can't start"`); + assert.equal(await b.evaluate(mark('north')), 'bus running'); + assert.equal(await b.evaluate("document.querySelector('[data-workspace-org=acme] .ws-dot b').textContent"), '◐'); + assert.equal(await b.evaluate("document.querySelector('[data-workspace-org=gamma] .ws-dot b').textContent"), '▲'); +}); + +test('settings-s4: the sidebar marks an organization paused while the model service is set up but not running', { timeout: 90000 }, async t => { + const service = { ...SERVICE_UP, next: ['unit-start'], unit: { ...SERVICE_UP.unit, active: 'inactive', listening: false }, ride: [{ id: 'acme', state: 'already' }] }; + const { b, wait } = await orgSetup(t, { path: '/#/dashboard', service }); + await wait(`${mark('acme')} === 'paused'`); + assert.equal(await b.evaluate(mark('north')), 'bus running', 'an organization that does not use the model service has no mark'); + assert.equal(await b.evaluate(mark('gamma')), 'bus stopped'); +}); + +// ---- Part B: Model setup --------------------------------------------------------------------- +const T = '2026-11-11T12:00:00.000Z'; +const fresh = { + release: { fetched: false, verified: false, version: '8.0.42', panelVersion: '1.26.7' }, + init: { initialized: false, partial: false, files: [] }, + unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' }, + fence: { set: false }, initLock: { present: false, clearable: false, blockers: [] }, fetch: { state: 'idle' }, restart: null, busy: null, + organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }], ownProxy: { available: false, state: 'not built', reason: 'One proxy per instance.' }, next: ['fetch'], +}; +const fetched = { ...fresh, release: { ...fresh.release, fetched: true, verified: true }, fetch: { state: 'done', receipt: { op: 'fetch', time: T, version: '8.0.42' } }, next: ['init'] }; +const configured = { ...fetched, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, next: ['unit-install'] }; +const installed = { ...configured, unit: { ...configured.unit, installed: true }, next: ['unit-start'] }; +const running = { ...installed, unit: { ...installed.unit, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] }; +const config = { send: true, devOwner: true, proxyAdmin: true, proxyAdminSend: true }; +const accounts = list => ({ 'GET /api/proxy/accounts': { body: { accounts: list } }, 'GET /api/proxy/keys': { body: { keys: [] } } }); +const admin = b => b.evaluate('window.__writes.filter(w => w.path.startsWith("/api/proxy/admin/")).map(w => w.path.slice(17))'); +const primaries = b => b.evaluate('[...document.querySelectorAll(".settings-content .primary, #proxy-setup .primary")].filter(e => e.checkVisibility()).map(e => e.id || e.textContent)'); +const STEP3 = '#setup-step-organizations [data-step-summary]'; + +// The status the page reads follows the writes it has made, as the host's would. +const following = stages => `(() => { + const stages = ${JSON.stringify(stages)}; + const status = () => { const paths = window.__writes.map(w => w.path); let s = stages[0][1]; for (const [path, next] of stages) if (!path || paths.includes(path)) s = next; return s; }; + Object.defineProperty(window.__scenario, '/api/proxy/admin/status', { get: status, enumerable: true, configurable: true }); +})();`; + +test('settings-s4: one press runs fetch, init, install and start in that order, each once, and step 2 is next', { timeout: 90000 }, async t => { + const receipt = op => ({ body: { receipt: { op, time: T } } }); + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, 'POST /api/proxy/admin/fetch': { status: 202, body: { state: 'running' } }, + 'POST /api/proxy/admin/init': receipt('init'), 'POST /api/proxy/admin/unit/install': receipt('unit-install'), 'POST /api/proxy/admin/unit/start': receipt('unit-start'), ...accounts([]), '/api/triage/route': { route: null } } }); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: following([[null, fresh], ['/api/proxy/admin/fetch', fetched], ['/api/proxy/admin/init', configured], ['/api/proxy/admin/unit/install', installed], ['/api/proxy/admin/unit/start', running]]) }); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "fetch"'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Set up model service'); + assert.deepEqual(await primaries(b), ['proxy-setup-go'], 'one primary button on the page'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".setup-step h3")].map(h => h.textContent)'), ['Model service', 'Accounts and models', 'Organizations', 'Triage']); + assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts").dataset.state'), 'wait'); + await b.evaluate('document.querySelector("#proxy-setup-go").click(); true'); + await wait('document.querySelector("#setup-step-service").dataset.state === "done"'); + assert.deepEqual(await admin(b), ['fetch', 'init', 'unit/install', 'unit/start']); + assert.deepEqual(await b.evaluate('JSON.parse(window.__writes.find(w => w.path === "/api/proxy/admin/init").body)'), { generate: true }); + assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /^Running\. Answers on this machine, port 18432\.$/); + await wait('document.querySelector("#setup-step-accounts").dataset.state === "next"'); + assert.deepEqual(await primaries(b), ['proxy-login-go'], 'the one primary moves to step 2'); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude'); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); +}); + +test('settings-s4: a step that fails stops the run with Try again, keeps the finished steps, and shows the service\'s last lines', { timeout: 90000 }, async t => { + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, 'POST /api/proxy/admin/init': { body: { receipt: { op: 'init', time: T } } }, + 'POST /api/proxy/admin/unit/install': { status: 500, body: { error: 'unit-install-failed' } }, 'GET /api/proxy/accounts': { status: 503, body: { error: 'not-configured' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'not-configured' } } } }); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: following([[null, fetched], ['/api/proxy/admin/init', configured]]) }); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "init"'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Continue setup'); + // Resume: the download is done, the rest is not started. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => [li.dataset.stage, li.className])'), [['fetch', 'ok'], ['init', 'todo'], ['start', 'todo'], ['answer', 'todo']]); + await b.evaluate('document.querySelector("#proxy-setup-go").click(); true'); + await wait('document.querySelector("#setup-step-service").dataset.state === "bad" && document.querySelector("#proxy-setup-go")?.textContent === "Try again"'); + assert.deepEqual(await admin(b), ['init', 'unit/install'], 'nothing is retried by itself'); + assert.equal(await b.evaluate('document.querySelector("#setup-step-service [data-step-badge]").textContent'), 'Setup stopped'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.className)'), ['ok', 'ok', 'bad', 'todo']); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-lines").checkVisibility() && document.querySelector("#proxy-setup-lines summary").textContent'), "The service's last lines"); + assert.deepEqual(await primaries(b), ['proxy-setup-go']); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-tech summary").textContent'), 'Technical details: release, service, history'); +}); + +test('settings-s4: ?step= opens a done card; without it a done card folds to its line', { timeout: 90000 }, async t => { + const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }]; + for (const [hash, shown] of [['#/settings/model-setup?step=accounts', true], ['#/settings/model-setup', false]]) { + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null } } }); + await b.navigate(f.base + '/' + hash); + await wait('document.querySelector("#setup-step-accounts")?.dataset.state === "done"'); + assert.equal(await b.evaluate('!document.querySelector("#setup-step-accounts-body").hidden'), shown, hash); + assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts .step-toggle").textContent'), shown ? 'Hide' : 'Show'); + await b.close(); + } +}); + +test('settings-s4: accounts read as rows with kind and health, the provider picks sign-in or a key, and a sign-in can be cancelled', { timeout: 90000 }, async t => { + const list = [ + { accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 2 }, + { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'error', priority: 1 }, + { accountId: 'a3', provider: 'z.ai', displayName: 'z.ai key', status: 'disabled', priority: 0, models: ['glm-4.6'] }, + { accountId: 'a4', provider: 'claude', displayName: 'Claude old', status: 'mystery', priority: 0 }, + ]; + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null }, + 'POST /api/proxy/login/start': { body: { url: 'https://claude.ai/oauth/authorize?state=s4', state: 's4' } }, 'POST /api/proxy/login/status': { body: { status: 'wait' } }, 'POST /api/proxy/login/cancel': { body: { status: 'cancelled' } }, 'POST /api/proxy/login/submit': { body: { status: 'wait' } } } }); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.open = () => null;' }); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li")].map(li => [...li.children].map(c => c.innerText.replace(/\\s+/g, " ").trim()))'), [ + ['Claude', 'Subscription Claude work', 'Ready'], ['ChatGPT / Codex', 'Subscription Codex home', 'Not working'], ['z.ai', 'API key z.ai key', 'Off'], ['Claude', 'Subscription Claude old', 'Unknown']]); + assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts").dataset.state'), 'bad', 'an account that is not working needs the owner'); + assert.match(await b.evaluate('document.querySelector("#setup-step-accounts [data-step-summary]").textContent'), /ChatGPT \/ Codex \(subscription\): not working/); + assert.match(await b.evaluate('document.querySelector("#setup-step-accounts").textContent'), /Removing an account is not built yet\./); + // The provider picks how to add: a sign-in for a subscription, Check and add for an API key. + await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()'); + assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-login-go").checkVisibility(), document.querySelector("#proxy-apikey").checkVisibility(), document.querySelector("#proxy-apikey button[type=submit]").textContent]'), [false, true, 'Check and add']); + await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "codex"; s.dispatchEvent(new Event("change")); return true; })()'); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to ChatGPT / Codex'); + await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "claude"; s.dispatchEvent(new Event("change")); document.querySelector("#proxy-login-start").requestSubmit(); return true; })()'); + await wait('!document.querySelector("#proxy-signin").hidden'); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-return summary").textContent'), 'The sign-in tab did not come back'); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-cancel").disabled'), false); + // Paste-back: the address from a tab that did not come back goes to login/submit and the box is cleared. + await b.evaluate('(() => { const f = document.querySelector("#proxy-login-submit"); f.elements.redirect_url.value = "http://localhost:54545/callback?code=c&state=s4"; f.requestSubmit(); return true; })()'); + await wait('window.__writes.some(w => w.path === "/api/proxy/login/submit") && /Address submitted/.test(document.querySelector("#proxy-login-message").textContent)'); + assert.deepEqual(await b.evaluate('JSON.parse(window.__writes.find(w => w.path === "/api/proxy/login/submit").body)'), { redirect_url: 'http://localhost:54545/callback?code=c&state=s4' }); + assert.equal(await b.evaluate('document.querySelector("#proxy-login-submit").elements.redirect_url.value'), ''); + await b.evaluate('document.querySelector("#proxy-login-cancel").click(); true'); + await wait('document.querySelector("#proxy-signin").hidden && document.querySelector("#proxy-login-message").textContent === "Sign-in cancelled."'); + assert.deepEqual(await b.evaluate('window.__writes.map(w => w.path)').then(p => p.filter(x => /login\/(start|cancel)/.test(x))), ['/api/proxy/login/start', '/api/proxy/login/cancel']); +}); + +test('settings-s4: Models offered lists each provider\'s models read-only with a count, a search past eight, and Coming later', { timeout: 90000 }, async t => { + const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }, { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'active', priority: 0 }]; + const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-model-${i}`, available: true })) + .concat([{ module: 'cliproxy', upstream: 'codex', model: 'gpt-x', available: true }, { module: 'cliproxy', upstream: 'codex', model: 'gpt-gone', available: false }, { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic', available: true }]); + const status = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 11 } }] }; + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': status, ...accounts(list), '/api/triage/route': { route: null }, + '/api/orgs/acme/bus/routes': { rows: [{ catalogue: { status: 'ready', models } }] } } }); + await b.navigate(f.base + '/#/settings/model-setup?step=accounts'); + await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 2'); + await b.evaluate('document.querySelector("#proxy-offered").open = true; true'); + await wait('document.querySelectorAll("#proxy-offered-list details[data-offered]").length === 2'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list details[data-offered] > summary")].map(s => s.textContent)'), ['Claude models offered: 10', 'ChatGPT / Codex models offered: 1']); + assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list input[type=checkbox]")].every(c => c.disabled)'), true, 'read-only'); + assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list li")].every(li => li.lastElementChild.textContent === "Coming later")'), true); + assert.equal(await b.evaluate('!!document.querySelector("#proxy-offered-list details[data-offered=claude] input[type=search]")'), true, 'more than eight: a search box'); + assert.equal(await b.evaluate('!!document.querySelector("#proxy-offered-list details[data-offered=codex] input[type=search]")'), false, 'one model: no search box'); + await b.evaluate('(() => { document.querySelector("#proxy-offered-list details[data-offered=claude]").open = true; const i = document.querySelector("#proxy-offered-list details[data-offered=claude] input[type=search]"); i.value = "model-7"; i.dispatchEvent(new Event("input")); return true; })()'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list details[data-offered=claude] li")].filter(li => !li.hidden).map(li => li.dataset.model)'), ['claude-model-7']); + assert.deepEqual(await b.evaluate('window.__writes'), [], 'reading the models writes nothing'); +}); + +test('settings-s4 P3: the done line names an organization that turned the model service off and does not count it as waiting', { timeout: 90000 }, async t => { + const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }]; + const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'removed' }] }; + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': done, ...accounts(list), '/api/triage/route': { route: { model: 'm' } } } }); + await b.navigate(f.base + '/#/settings/model-setup'); + await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next === "done"`); + assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), 'The model service is set up and every organization that uses it can see your models. north turned it off, and Ride all leaves it off.'); + assert.equal(await b.evaluate('document.querySelector("#setup-step-organizations").dataset.state'), 'done'); + assert.deepEqual(await primaries(b), [], 'nothing left to do: no primary button'); + assert.deepEqual(await b.evaluate('window.__unexpected'), []); +}); -- 2.54.0 From 50ca7f03410fc030f0e3783e1e4670fc9135816a Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:46:21 -0600 Subject: [PATCH 05/14] =?UTF-8?q?fix(webui):=20settings-s4=20shots=20round?= =?UTF-8?q?:=20a=20progress=20line=20reads=20what=20happened=20at=20each?= =?UTF-8?q?=20step=20(done,=20under=20way,=20not=20started,=20or=20"did=20?= =?UTF-8?q?not=20finish"=20where=20the=20run=20stopped),=20so=20a=20failed?= =?UTF-8?q?=20step=20no=20longer=20reads=20"Starting=20the=20service?= =?UTF-8?q?=E2=80=A6";=20an=20account's=20health=20badge=20keeps=20its=20o?= =?UTF-8?q?wn=20width=20on=20a=20phone;=20the=20model=20search=20box=20has?= =?UTF-8?q?=20a=20placeholder;=20the=20slice=204=20test=20file=20takes=20s?= =?UTF-8?q?hots=20at=20390=20and=201440,=20light=20and=20dark,=20with=20MO?= =?UTF-8?q?SAIC=5FUX=5FSHOTS=20set,=20and=20checks=20sideways=20scroll,=20?= =?UTF-8?q?select=20fit=20and=20a=20visible=20focus=20ring=20on=20every=20?= =?UTF-8?q?control=20it=20tabs=20to=20(#1873,=20lane=20settings-s4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/webui/src/public/display.js | 10 +- packages/webui/src/public/shell.css | 2 +- .../webui/tests/settings-s4-browser.test.mjs | 111 +++++++++++++++++- 3 files changed, 113 insertions(+), 10 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 9b2a76598..fd3a8855d 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -827,7 +827,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo label.append(box2, ` ${m.model}${m.reason === 'unverified' ? ' (unverified)' : ''}`); li.dataset.model = String(m.model).toLowerCase(); li.append(label, el('span', 'Coming later', 'small muted')); return li; })); if (mine.length > 8) { const field = el('div', undefined, 'field'), id = `proxy-find-${norm(provider)}`, label = el('label', `Find a ${name} model`), input = document.createElement('input'); - label.htmlFor = id; input.id = id; input.type = 'search'; input.autocomplete = 'off'; + label.htmlFor = id; input.id = id; input.type = 'search'; input.autocomplete = 'off'; input.placeholder = 'Part of a name'; input.addEventListener('input', () => { const q = input.value.trim().toLowerCase(); list.querySelectorAll('li').forEach(li => { li.hidden = Boolean(q) && !li.dataset.model.includes(q); }); }); field.append(label, input); inside.append(field); } @@ -993,7 +993,11 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo // settings-p3 (re-check 3 P3-1): where the hand steps for a held init lock or a partial init are written. const README_STEPS = ['The hand steps for a stale init lock and a partial init are in ', 'packages/model-proxy/README.md']; const CHAIN = ['fetch', 'init', 'unit-install', 'unit-start']; - const PROGRESS = [['fetch', 'Downloaded and checked'], ['init', 'Configured'], ['start', 'Starting the service…'], ['answer', 'Checking it answers']]; + // Each line reads as what happened: done, under way, not started, or the step where the run stopped. + const PROGRESS = [['fetch', { ok: 'Downloaded and checked', run: 'Downloading and checking…', todo: 'Download and check', bad: 'Download and check: did not finish' }], + ['init', { ok: 'Configured', run: 'Configuring…', todo: 'Configure', bad: 'Configure: did not finish' }], + ['start', { ok: 'Started the service', run: 'Starting the service…', todo: 'Start the service', bad: 'Start the service: did not finish' }], + ['answer', { ok: 'Answers on this machine', run: 'Checking it answers…', todo: 'Check it answers', bad: 'Check it answers: no answer yet' }]]; const stageOf = step => step === 'fetch' || step === 'init' ? step : step === 'unit-install' || step === 'unit-start' ? 'start' : 'answer'; // Each line is done only when the status read says so. function progressDone() { @@ -1009,7 +1013,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo if (!ok[key] && chain?.failed && stageOf(chain.failed.at) === key) cls = 'bad'; else if (!ok[key] && first && (chain?.running || state.fetch?.state === 'running')) cls = 'run'; if (!ok[key]) first = false; - const li = el('li', text, cls); li.dataset.stage = key; li.append(el('span', ` (${words[cls]})`, 'sr-only')); return li; + const li = el('li', text[cls], cls); li.dataset.stage = key; li.append(el('span', ` (${words[cls]})`, 'sr-only')); return li; })); } function goButton(label, next, disabled, action) { diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 6f4ae1256..a7f1a2cb8 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -346,7 +346,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .err-line{color:var(--danger)} .settings-content details{margin-top:var(--gap,12px)} .settings-content details>.inside{margin-top:var(--gap,12px)} -@media(max-width:759px){.rows li{grid-template-columns:1fr}.setup-step .summary,.setup-step .body{margin-left:0}.settings-form{max-width:none}.settings-form .w-num{max-width:none}} +@media(max-width:759px){.rows li{grid-template-columns:1fr}.rows li>.badge{justify-self:start}.setup-step .summary,.setup-step .body{margin-left:0}.settings-form{max-width:none}.settings-form .w-num{max-width:none}} @media(max-width:959px) and (min-width:760px){.settings-layout{grid-template-columns:180px minmax(0,1fr);gap:24px}} @media(max-width:759px){.settings-layout{display:block}.settings-layout>div:first-child{margin-bottom:20px}#settings-disclosure{width:100%;min-height:44px;display:flex;align-items:center;gap:12px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);text-align:left}#settings-disclosure small{color:var(--muted)}#settings-disclosure span{margin-left:auto}#settings-disclosure[aria-expanded=false]+#settings-nav{display:none}#settings-nav{padding:12px 0}.settings-content>h2{font-size:21px}.palette-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.palette-content{min-height:64px;padding:7px}.palette-tile input:checked+.palette-content{padding:6px}.settings-segments{display:flex;width:100%}.settings-segments label{flex:1;min-width:0}.settings-segments span,.settings-appearance .panel:last-child .settings-segments span{min-width:0;padding:0 4px}.settings-content .table-wrap{max-width:100%}} .settings-content [aria-invalid=true]{border:2px solid var(--danger)!important} diff --git a/packages/webui/tests/settings-s4-browser.test.mjs b/packages/webui/tests/settings-s4-browser.test.mjs index 644d2a0f3..e72e290a6 100644 --- a/packages/webui/tests/settings-s4-browser.test.mjs +++ b/packages/webui/tests/settings-s4-browser.test.mjs @@ -58,31 +58,34 @@ async function orgFixture() { // scopes some reads under /api/orgs//). Everything else is the real server. const SERVICE_UP = { next: ['accounts'], init: { initialized: true, 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 }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] }; -const ownerStub = (service = SERVICE_UP) => `(() => { - const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service })}; +const ownerStub = (service = SERVICE_UP, extra = {}) => `(() => { + const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service, accounts: [], routes: null, posts: {}, ...extra })}; window.__writes = []; 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' && /\\/proxy\\//.test(path)) { window.__writes.push(path); const key = Object.keys(__s4.posts).find(k => path.endsWith(k)); const a = key ? __s4.posts[key] : { status: 500, body: { error: 'stub' } }; + if (a === 'hang') return new Promise(() => {}); if (a.service) __s4.service = a.service; return json(a.body ?? {}, a.status ?? 200); } if (method !== 'GET') return real(input, init); + if (__s4.routes && /\\/bus\\/routes$/.test(path)) return json(__s4.routes); 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/admin/status')) return json(__s4.service); - if (path.endsWith('/proxy/accounts')) return json({ accounts: [] }); + if (path.endsWith('/proxy/accounts')) return json({ accounts: __s4.accounts }); if (path.endsWith('/proxy/keys')) return json({ keys: [] }); if (path.endsWith('/triage/route')) return json({ route: null }); return real(input, init); }; })();`; -async function orgSetup(t, { path, viewport = [1440, 900], service } = {}) { +async function orgSetup(t, { path, viewport = [1440, 900], service, extra } = {}) { const { organizations, agentLevels } = await orgFixture(); 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(service) }); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: ownerStub(service, extra) }); 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)})()`); - return { b, wait, text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`) }; + return { b, wait, base: `http://127.0.0.1:${server.address().port}`, text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`) }; } test('settings-s4: the nav has four groups, the organization pages carry ?org=, the picker switches organization, and there is no Members row', { timeout: 90000 }, async t => { @@ -215,6 +218,7 @@ test('settings-s4: a step that fails stops the run with Try again, keeps the fin assert.deepEqual(await admin(b), ['init', 'unit/install'], 'nothing is retried by itself'); assert.equal(await b.evaluate('document.querySelector("#setup-step-service [data-step-badge]").textContent'), 'Setup stopped'); assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.className)'), ['ok', 'ok', 'bad', 'todo']); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.firstChild.textContent)'), ['Downloaded and checked', 'Configured', 'Start the service: did not finish', 'Check it answers']); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-lines").checkVisibility() && document.querySelector("#proxy-setup-lines summary").textContent'), "The service's last lines"); assert.deepEqual(await primaries(b), ['proxy-setup-go']); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts'); @@ -301,3 +305,98 @@ test('settings-s4 P3: the done line names an organization that turned the model assert.deepEqual(await primaries(b), [], 'nothing left to do: no primary button'); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); + +// Shots for the build report, beside the mockups: run with MOSAIC_UX_SHOTS=. Each page is shot whole +// at 390 and 1440, light and dark. Every page is measured: nothing scrolls sideways, every visible select +// shows its chosen text, and every visible control shows a focus ring when it takes keyboard focus. +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, 1200)); + const fresh = { ...SERVICE_UP, release: { ...SERVICE_UP.release, fetched: false, verified: false }, init: { initialized: false, partial: false, files: [] }, + unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' }, fetch: { state: 'idle' }, organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }, { id: 'north', proxy: 'shared', catalogue: null }], next: ['fetch'] }; + const fetched = { ...fresh, release: { ...fresh.release, fetched: true, verified: true }, next: ['init'] }; + const configured = { ...fetched, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, next: ['unit-install'] }; + const ready = [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }]; + const up = { ...SERVICE_UP, organizations: ready, ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'already' }, { id: 'gamma', state: 'bus-down' }] }; + const accounts = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }, { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'active', priority: 0 }]; + const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-sonnet-4-${i}`, available: true })) + .concat(['gpt-5.1', 'gpt-5.1-codex'].map(model => ({ module: 'cliproxy', upstream: 'codex', model, available: true }))); + const routes = { rows: [{ ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models, notices: [] } }] }; + const go = 'document.querySelector("#proxy-setup-go").click(); true'; + const PAGES = [ + { name: 'nav-open', path: '/#/settings/routing?org=acme', ready: 'document.querySelector("#org-pick")', after: async (b, wait, width) => { + if (width === 390) { await b.evaluate('document.querySelector("#settings-disclosure").click(); true'); await wait('document.querySelector("#settings-nav a").checkVisibility()'); } } }, + { name: 'models-nothing', path: '/#/settings/model-setup', service: fresh, ready: 'document.querySelector("#proxy-setup-go")?.dataset.next === "fetch"' }, + { name: 'models-setting-up', path: '/#/settings/model-setup', service: fetched, extra: { posts: { '/admin/init': { body: { receipt: { op: 'init' } }, service: configured }, '/admin/unit/install': 'hang' } }, + ready: 'document.querySelector("#proxy-setup-go")?.dataset.next === "init"', after: async (b, wait) => { await b.evaluate(go); await wait('document.querySelector("#proxy-setup-progress li.run")'); } }, + { name: 'models-setup-failed', path: '/#/settings/model-setup', service: fetched, extra: { posts: { '/admin/init': { body: { receipt: { op: 'init' } }, service: configured }, '/admin/unit/install': { status: 500, body: { error: 'unit-install-failed' } } } }, + ready: 'document.querySelector("#proxy-setup-go")?.dataset.next === "init"', after: async (b, wait) => { await b.evaluate(go); await wait('document.querySelector("#proxy-setup-go").textContent === "Try again"'); } }, + { name: 'models-running', path: '/#/settings/model-setup', service: { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 0 } }] }, ready: 'document.querySelector("#setup-step-accounts")?.dataset.state === "next"' }, + { name: 'models-accounts', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2' }, + { name: 'models-accounts-signin', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes, posts: { '/login/start': { body: { url: 'https://claude.ai/oauth/authorize?state=shot', state: 'shot' } }, '/login/status': { body: { status: 'wait' } } } }, + ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async (b, wait) => { + await b.evaluate('window.open = () => null; document.querySelector("#proxy-add-box").open = true; document.querySelector("#proxy-login-start").requestSubmit(); true'); await wait('!document.querySelector("#proxy-signin").hidden'); } }, + { name: 'models-accounts-key', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async b => { + await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()'); } }, + { name: 'models-offered', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async (b, wait) => { + await b.evaluate('document.querySelector("#proxy-offered").open = true; true'); await wait('document.querySelector("#proxy-offered-list details[data-offered=claude]")'); + await b.evaluate('document.querySelector("#proxy-offered-list details[data-offered=claude]").open = true; true'); } }, + { name: 'models-problems', path: '/#/settings/model-setup', service: { ...up, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }], + ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'already' }, { id: 'gamma', state: 'fixture', running: false }] }, extra: { accounts: [accounts[0], { ...accounts[1], status: 'error' }], routes }, + ready: 'document.querySelector("#setup-step-accounts")?.dataset.state === "bad"' }, + { name: 'models-advanced', path: '/#/settings/model-setup', service: up, extra: { accounts, routes }, ready: 'document.querySelector("#setup-step-service")?.dataset.state === "done"', after: async b => { + await b.evaluate('document.querySelector("#proxy-setup-advanced").open = true; document.querySelector("#proxy-setup-tech").open = true; true'); } }, + { name: 'org-models', path: '/#/settings/routing?org=acme', service: up, ready: 'document.querySelector(".routing-panel select, .routing-panel")' }, + { name: 'sidebar-marks', path: '/#/dashboard', service: { ...up, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }], ride: [{ id: 'gamma', state: 'fixture', running: false }] }, + ready: `${mark('acme')} === 'needs restart'`, viewportOnly: true }, + ]; + const report = []; + for (const page of PAGES) for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) { + const f = await orgSetup(t, { path: '/', service: page.service ?? up, extra: page.extra, viewport: [width, width === 390 ? 844 : 900] }); + await f.b.call('Emulation.setScrollbarsHidden', { hidden: true }); + await f.b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] }); + await f.b.navigate(`${f.base}/?shot=${page.name}-${scheme}-${width}${page.path.slice(1)}`); + await f.wait(`(${page.ready}) && !!window.MosaicAppearance`); + await f.b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`); + if (page.after) await page.after(f.b, f.wait, width); + await settle(); + const fit = await f.b.evaluate(`(() => { + const out = [], probe = document.createElement('span'); probe.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap'; document.body.append(probe); + for (const s of document.querySelectorAll('select')) { if (!s.checkVisibility()) continue; const cs = getComputedStyle(s), r = s.getBoundingClientRect(); + probe.style.font = cs.font; probe.textContent = s.selectedOptions[0]?.textContent ?? ''; + out.push({ label: s.id || s.name, text: probe.textContent, need: Math.ceil(probe.getBoundingClientRect().width), room: Math.floor(s.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight)), inside: r.left >= 0 && r.right <= innerWidth + 0.5 }); } + probe.remove(); return { selects: out, sideways: document.documentElement.scrollWidth > document.documentElement.clientWidth }; + })()`); + // Keyboard focus: Tab through the page and note any control whose ring is not visible. + const noRing = [], seen = new Set(); + for (let i = 0; i < 120; i++) { + await f.b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }); + await f.b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }); + const r = await f.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 f.b.evaluate('document.activeElement?.blur(); window.scrollTo(0, 0); true'); await settle(); + const shot = `${page.name}-${width}-${scheme}.png`; + if (page.viewportOnly) await f.b.screenshot(join(dir, shot)); + else { + let metrics = await f.b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize; + await f.b.viewport(width, Math.ceil(size.height)); await settle(); + metrics = await f.b.call('Page.getLayoutMetrics'); size = metrics.cssContentSize || metrics.contentSize; + const { data } = await f.b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height), scale: 1 } }); + await writeFile(join(dir, shot), Buffer.from(data, 'base64')); + } + report.push({ page: page.name, width, scheme, shot, ...fit, noRing }); + await f.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`); + if (r.width === 390) for (const s of r.selects) { assert.ok(s.inside, `${r.shot}: ${s.label} runs off screen`); assert.ok(s.need <= s.room, `${r.shot}: ${s.label} cuts "${s.text}" (${s.need} > ${s.room})`); } + } +}); -- 2.54.0 From 15801ccb07555e311f8bd860fcd702c1b9e09ee6 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:50:47 -0600 Subject: [PATCH 06/14] fix(webui): settings-s4: Model setup shows one primary button: a submit there reads as a plain button unless display.js marks it primary, so Finish sign-in and Check and add no longer look primary beside the card's own; the sign-in row wraps with a gap at 390; the test counts primaries by their drawn fill, and checks one primary while signing in and with the key form open (#1873, lane settings-s4) --- packages/webui/src/public/shell.css | 3 +++ packages/webui/tests/settings-s4-browser.test.mjs | 8 +++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index a7f1a2cb8..d9d19bd92 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -291,6 +291,9 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .settings-content input:disabled,.settings-content select:disabled,.settings-content textarea:disabled{background:var(--raised);border-color:var(--line);color:var(--muted)} .settings-content button,.settings-content summary{min-height:44px;min-width:44px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);padding:8px 18px;font:inherit;cursor:pointer} .settings-content button[type=submit]{background:var(--accent-fill);color:var(--on-accent);border-color:var(--accent-fill)} +/* #1873 settings slice 4: Model setup has at most one primary button, which display.js marks .primary; its other submits read as plain buttons. */ +.settings-content .model-setup button[type=submit]:not(.primary){background:var(--surface);color:var(--text);border-color:var(--border)} +#proxy-signin .form-foot{display:flex;flex-wrap:wrap;align-items:center;gap:var(--gap,12px)} .settings-content :is(button,input,select,textarea,a,summary):focus-visible,#settings-nav a:focus-visible,#settings-nav select:focus-visible,#settings-disclosure:focus-visible{outline:2px solid var(--focus);outline-offset:2px} .settings-segments{display:inline-flex;max-width:100%;border:1px solid var(--border);border-radius:var(--r);overflow:hidden} .settings-segments label{position:relative;display:block} diff --git a/packages/webui/tests/settings-s4-browser.test.mjs b/packages/webui/tests/settings-s4-browser.test.mjs index e72e290a6..bef18796c 100644 --- a/packages/webui/tests/settings-s4-browser.test.mjs +++ b/packages/webui/tests/settings-s4-browser.test.mjs @@ -172,7 +172,10 @@ const running = { ...installed, unit: { ...installed.unit, active: 'active', pid const config = { send: true, devOwner: true, proxyAdmin: true, proxyAdminSend: true }; const accounts = list => ({ 'GET /api/proxy/accounts': { body: { accounts: list } }, 'GET /api/proxy/keys': { body: { keys: [] } } }); const admin = b => b.evaluate('window.__writes.filter(w => w.path.startsWith("/api/proxy/admin/")).map(w => w.path.slice(17))'); -const primaries = b => b.evaluate('[...document.querySelectorAll(".settings-content .primary, #proxy-setup .primary")].filter(e => e.checkVisibility()).map(e => e.id || e.textContent)'); +// A primary button is one drawn with the accent fill, whatever its class: a submit is drawn that way too. +const primaries = b => b.evaluate(`(() => { const host = document.querySelector(".model-setup"), probe = document.createElement("button"); probe.className = "btn primary"; host.append(probe); + const fill = getComputedStyle(probe).backgroundColor; probe.remove(); + return [...host.querySelectorAll("button, a")].filter(e => e.checkVisibility() && getComputedStyle(e).backgroundColor === fill).map(e => e.id || e.textContent); })()`); const STEP3 = '#setup-step-organizations [data-step-summary]'; // The status the page reads follows the writes it has made, as the host's would. @@ -257,10 +260,13 @@ test('settings-s4: accounts read as rows with kind and health, the provider pick // The provider picks how to add: a sign-in for a subscription, Check and add for an API key. await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()'); assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-login-go").checkVisibility(), document.querySelector("#proxy-apikey").checkVisibility(), document.querySelector("#proxy-apikey button[type=submit]").textContent]'), [false, true, 'Check and add']); + assert.ok((await primaries(b)).length <= 1, 'one primary button with the key form open'); await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "codex"; s.dispatchEvent(new Event("change")); return true; })()'); assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to ChatGPT / Codex'); await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "claude"; s.dispatchEvent(new Event("change")); document.querySelector("#proxy-login-start").requestSubmit(); return true; })()'); await wait('!document.querySelector("#proxy-signin").hidden'); + assert.ok((await primaries(b)).length <= 1, 'one primary button while signing in'); + assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-login-submit button[type=submit]")).backgroundColor === getComputedStyle(document.querySelector("#proxy-login-cancel")).backgroundColor'), true, 'Finish sign-in is a plain button'); assert.equal(await b.evaluate('document.querySelector("#proxy-login-return summary").textContent'), 'The sign-in tab did not come back'); assert.equal(await b.evaluate('document.querySelector("#proxy-login-cancel").disabled'), false); // Paste-back: the address from a tab that did not come back goes to login/submit and the box is cleared. -- 2.54.0 From d502a75e57488c57c791542e674cefb3af02dfd1 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:50:47 -0600 Subject: [PATCH 07/14] test(webui): settings-s4: the Business settings test reads the slice 4 nav (You, Your models, This instance, This business with Business last) in place of the old Your browser and This instance list; Business is still in Settings and not in the sidebar, and still visible in the phone disclosure (#1873, lane settings-s4) --- .../webui/tests/s16-business-settings-browser.test.mjs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/webui/tests/s16-business-settings-browser.test.mjs b/packages/webui/tests/s16-business-settings-browser.test.mjs index 21fd16d94..f7c9dcf08 100644 --- a/packages/webui/tests/s16-business-settings-browser.test.mjs +++ b/packages/webui/tests/s16-business-settings-browser.test.mjs @@ -14,8 +14,9 @@ async function open(t, tester=false) { test('Business moves from sidebar to first instance Settings section',opts,async t=>{ const {b}=await open(t); assert.equal(await b.evaluate('[...document.querySelectorAll("#sections a")].filter(e=>e.getAttribute("href")==="#/business").length'),0); - assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim()).slice(0,4)'),['Your browser','Appearance','This instance','Business']); - assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(e=>e.getAttribute("href")==="#/settings/business").nextElementSibling.textContent.trim()'),'Launch limits'); + // #1873 settings slice 4 (DESIGN.md section 2): the nav reads in four groups; a single-business Console's own pages sit under "This business", Business last. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim())'),['You','Appearance','Your models','Model setup','This instance','Organizations','Console','About','This business','Routing','Agents','Launch limits','Token use','Assistant','Business']); + assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(e=>e.getAttribute("href")==="#/settings/business").nextElementSibling'),null); }); test('legacy Business bookmark replaces its history entry and retains its data',opts,async t=>{ @@ -35,11 +36,11 @@ test('legacy Business bookmark replaces its history entry and retains its data', await b.evaluate('history.back()'); await wait('location.hash==="#/settings/appearance"'); }); -test('mobile disclosure lists Business first in This instance',opts,async t=>{ +test('mobile disclosure lists Business under This business',opts,async t=>{ const {b}=await open(t); await b.viewport(390,844); await b.evaluate('document.querySelector("#settings-disclosure").click()'); assert.equal(await b.evaluate('document.querySelector("#settings-disclosure").getAttribute("aria-expanded")'),'true'); - assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim()).slice(0,4)'),['Your browser','Appearance','This instance','Business']); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim())'),['You','Appearance','Your models','Model setup','This instance','Organizations','Console','About','This business','Routing','Agents','Launch limits','Token use','Assistant','Business']); assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(e=>e.getAttribute("href")==="#/settings/business").getClientRects().length>0'),true); }); -- 2.54.0 From 57e86d9867b9412bf8a3929e51cf278e875880fa Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:58:37 -0600 Subject: [PATCH 08/14] test(webui): settings-s4: tests that pinned the old addresses read the slice 4 ones: the dashboard's Model setup row and Triage's fix link open #/settings/model-setup, and the single-pane switch tests go to #/settings/?org=beta (their #/orgs/acme/... starts still pass through the old-address redirect) (#1873, lane settings-s4) --- .../webui/tests/single-pane-browser.test.mjs | 16 ++++++++-------- .../webui/tests/triage-drawer-browser.test.mjs | 2 +- .../tests/unified-workspace-browser.test.mjs | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/webui/tests/single-pane-browser.test.mjs b/packages/webui/tests/single-pane-browser.test.mjs index 79154ae4a..5899f12e5 100644 --- a/packages/webui/tests/single-pane-browser.test.mjs +++ b/packages/webui/tests/single-pane-browser.test.mjs @@ -211,8 +211,8 @@ test('a switch stops following an agent request: no poll reaches the next organi await wait('window.__reads.length >= 1'); assert.deepEqual(await b.evaluate('window.__posts'), ['/api/orgs/acme/agent/launch']); assert.match(await b.evaluate('window.__reads[0]'), /^\/api\/orgs\/acme\/agent\/request\?id=/); - await b.evaluate('location.hash = "#/orgs/beta/settings/agents"'); - await wait('location.hash === "#/orgs/beta/settings/agents" && document.querySelector("#agents-section [data-agent-name=chief]") && !document.querySelector("#agents-section [data-agent-name=reviewer]")'); + await b.evaluate('location.hash = "#/settings/agents?org=beta"'); + await wait('location.hash === "#/settings/agents?org=beta" && document.querySelector("#agents-section [data-agent-name=chief]") && !document.querySelector("#agents-section [data-agent-name=reviewer]")'); const seen = await b.evaluate('window.__reads.length'); // Two poll periods pass on beta's page. await new Promise(r => setTimeout(r, 4500)); @@ -239,13 +239,13 @@ test('a save still in flight at a switch: its answer is not drawn on the next or await b.evaluate(`(() => { const i = document.querySelector(${JSON.stringify(total)}); i.value = "5"; i.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector(${JSON.stringify(submit)}).click(); })()`); await wait('typeof window.__release === "function"'); assert.equal(await b.evaluate('window.__posts[0]?.revision'), 'a'.repeat(64)); - await b.evaluate('location.hash = "#/orgs/beta/settings/limits"'); - await wait(`location.hash === "#/orgs/beta/settings/limits" && document.querySelector(${JSON.stringify(total)})?.value === "7"`); + await b.evaluate('location.hash = "#/settings/limits?org=beta"'); + await wait(`location.hash === "#/settings/limits?org=beta" && document.querySelector(${JSON.stringify(total)})?.value === "7"`); // beta's Save is its own: not held by acme's write. assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false); await b.evaluate('window.__release()'); await new Promise(r => setTimeout(r, 700)); - assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits'); + assert.equal(await b.evaluate('location.hash'), '#/settings/limits?org=beta'); assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value`), '7'); assert.equal(await b.evaluate('document.getElementById("launch-settings-receipt")?.textContent.trim() ?? ""'), ''); assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false); @@ -420,15 +420,15 @@ test('a read still in flight at a switch: its answer is not kept for the next or // A fresh read of acme's settings starts and is held. await b.evaluate('window.__holdAcme = true; location.hash = "#/orgs/acme/settings/tokens"'); await wait('window.__acme.length >= 1'); - await b.evaluate('window.__holdBeta = true; location.hash = "#/orgs/beta/settings/limits"'); - await wait('location.hash === "#/orgs/beta/settings/limits" && window.__beta.length >= 1'); + await b.evaluate('window.__holdBeta = true; location.hash = "#/settings/limits?org=beta"'); + await wait('location.hash === "#/settings/limits?org=beta" && window.__beta.length >= 1'); // acme answers after the switch; then beta's read fails. await b.evaluate('window.__acme.forEach(r => r())'); await new Promise(r => setTimeout(r, 400)); await b.evaluate('window.__beta.forEach(r => r())'); await wait('document.querySelector("#bus-view .banner")'); await new Promise(r => setTimeout(r, 400)); - assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits'); + assert.equal(await b.evaluate('location.hash'), '#/settings/limits?org=beta'); assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value ?? null`), null, 'acme\'s held answer was drawn on beta'); assert.equal(await b.evaluate('!!document.querySelector("#bus-view .s1-stale")'), false); assert.match(await b.evaluate('document.getElementById("bus-view").innerText'), /beta settings read failed/); diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs index 9c1b85692..58e01bf8f 100644 --- a/packages/webui/tests/triage-drawer-browser.test.mjs +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -487,7 +487,7 @@ test('settings-s1 B5: route refusals read as plain lines with the fix link; the const { ROUTE_REFUSALS } = await import('../src/triage-host.mjs'); const cases = [ ['triage-harness-incompatible', /^Not sent\. The model Triage uses doesn't run with claude-code, the program its route says runs it\. Choose a model that runs with claude-code, or another program, in Triage settings\. Open Triage settings$/, '#/settings/triage'], - ['triage-proxy-down', /^Not sent\. The model service isn't running, so Triage can't start\. Open Model setup$/, '#/settings/model-proxy'], + ['triage-proxy-down', /^Not sent\. The model service isn't running, so Triage can't start\. Open Model setup$/, '#/settings/model-setup'], ['triage-model-not-offered', /^Not sent\. The model Triage uses is no longer offered\./, '#/settings/triage'], ['triage-key-missing', /^Not sent\. Triage isn't turned on yet: it needs a Triage key, and none is issued on this instance\.$/, null], ]; diff --git a/packages/webui/tests/unified-workspace-browser.test.mjs b/packages/webui/tests/unified-workspace-browser.test.mjs index b366bd068..358404807 100644 --- a/packages/webui/tests/unified-workspace-browser.test.mjs +++ b/packages/webui/tests/unified-workspace-browser.test.mjs @@ -59,7 +59,7 @@ const refusingAdmin = () => createOrgAdmin({ service: {}, context: async () => ( const SETTINGS = ['Identity', 'Appearance', 'Projects', 'Agents and roles', 'Models and routing', 'Arbiters', 'Task tracker', 'Channels', 'Launch limits', 'Assistant', 'Token use', 'Model setup', 'Console', 'Organizations', 'About', 'Members and invites', 'Bus', 'Archive or delete']; const TAGS = ['org file', 'override', 'system', 'root', 'not built', 'danger']; // Every page the Settings view has for the owner (bus.js settingsPages). -const SETTINGS_PAGES = ['appearance', 'business', 'limits', 'organizations', 'routing', 'agents', 'assistant', 'tokens', 'model-proxy', 'console', 'about']; +const SETTINGS_PAGES = ['appearance', 'business', 'limits', 'organizations', 'routing', 'agents', 'assistant', 'tokens', 'model-setup', 'console', 'about']; test('workspace navigation exposes all organizations and remembers project grouping', async t => { const organizations = { -- 2.54.0 From d692ca9b8184f0fe602190816cf09806dc992a13 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 18:17:45 -0600 Subject: [PATCH 09/14] fix(webui): settings-s4 review F3: Model setup drops what design section 10 removes: "Use my own key" and its key fields (the service key is always made on this machine, so init always sends generate), the key rotation grace field and its settings row, the Client keys table with its refresh button and the keys read, and the "Accounts and client keys loaded" line; the setup cleanup no longer clears the removed key fields; the Advanced help says Claude Code, not "the Claude harness" (N5); the tests that pinned the removed parts read the new page (#1873, lane settings-s4) --- packages/webui/src/public/display.js | 44 +++++-------------- packages/webui/tests/proxy-browser.test.mjs | 11 +++-- .../webui/tests/proxy-setup-browser.test.mjs | 25 +++++------ .../tests/settings-review-browser.test.mjs | 2 +- 4 files changed, 31 insertions(+), 51 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index fd3a8855d..0fe2068ac 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -627,17 +627,12 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const triage = '

    Set up Triage

    '; const advanced = ''; const tech = '
    Technical details: release, service, history
    ' @@ -648,9 +643,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo + '

    Organizations

    OrganizationProxyCatalogueModels
    ' + '

    ' + '

    History

    1. No setup actions on this page yet.
    ' - + '

    Client keys

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

    ' - + '
    Key IDManaged byAgentIssuedState
    ' - + '
    '; + + ''; const markup = '
    ' + card('service', 1, 'Model service', service, true) + card('accounts', 2, 'Accounts and models', accounts, false) @@ -787,13 +780,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo })); } async function refresh() { - const [accounts, keys] = await Promise.all([call('accounts'), call('keys')]); + const accounts = await call('accounts'); accountList = Array.isArray(accounts?.accounts) ? accounts.accounts : []; accountsDown = null; paintAccounts(); paintOrder(); - $('proxy-keys').replaceChildren(...keys.keys.map(key => { - 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; - })); if ($('proxy-offered').open) readOffered(); setup.accounts(accountList.length); paintAccountCard(); @@ -870,7 +860,6 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo else message(result.reason === 'login-timeout' ? 'Sign-in took too long. Try again.' : 'Account sign-in failed. Try again.', true); } catch (error) { if (active === login) { endLogin(); message(error.message, true); } } } - $('proxy-refresh').addEventListener('click', () => refresh().then(() => message('Accounts and client keys refreshed.')).catch(e => message(e.message))); $('proxy-login-start').addEventListener('submit', async event => { event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('login-start') || login) return; const provider = providerSelect.value; @@ -926,7 +915,6 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo let chain = null; const listed = new Set(); const esc = v => String(v).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); - const pasteAllowed = location.protocol === 'https:' || ['localhost', '[::1]'].includes(location.hostname) || /^127\./.test(location.hostname); const STEPS = { start: 'Starting', 'download-archive': 'Downloading the release archive', 'verify-archive': 'Checking the archive hash', 'download-panel': 'Downloading the panel', 'verify-panel': 'Checking the panel hash', 'extract-binary': 'Extracting the executable', 'verify-binary': 'Checking the executable hash', install: 'Installing', done: 'Done' }; const REASONS = { 'human-required': 'Only the instance owner can set up the model service.', @@ -1194,7 +1182,6 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const canInit = sendOk && !busy && !chain?.running && !init.initialized && !init.partial && !initLock.present; form.querySelectorAll('[data-setup-write]').forEach(e => { e.disabled = !canInit; }); form.hidden = init.initialized; - $('proxy-setup-paste-choice').hidden = !pasteAllowed; $('proxy-setup-paste-note').hidden = pasteAllowed; const allow = { install: !unit.installed, start: unit.installed && unit.active !== 'active', restart: unit.installed && unit.active === 'active', stop: unit.installed && unit.active === 'active' }; root.querySelectorAll('[data-unit]').forEach(button => { button.disabled = !sendOk || Boolean(busy) || Boolean(chain?.running) || !init.initialized || !allow[button.dataset.unit]; }); const orgs = $('proxy-setup-orgs'); @@ -1206,7 +1193,7 @@ 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.rotateGraceMinutes !== undefined) row(dl, 'Key rotation grace', `${human(s.rotateGraceMinutes)} minutes`); } + if (s) { row(dl, 'Port', human(s.port)); if (s.firstOutputSeconds !== undefined) row(dl, 'Wait for a first answer', `${human(s.firstOutputSeconds)} seconds`); } } // Programs that drive models: the harnesses this Console offers an organization, read on open. let programsRead = false; @@ -1317,18 +1304,12 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo // painted here first from the state already read. try { await action(); } catch (error) { say(error.message, 'error'); } finally { if (state) { state = { ...state, busy: null }; paint(); } await load(); } } - // The settings under Advanced, read when the chain starts. A pasted key leaves its fields at once. + // The settings under Advanced, read when the chain starts. settings-s4 (design section 10, A8): + // the service key is always generated on this machine; there is no pasted key. function initArgs() { - const f = form.elements, args = {}; - const pasted = pasteAllowed && f.keySource.value === 'paste', key = f.key.value, confirm = f.confirm.value; - f.key.value = ''; f.confirm.value = ''; + const f = form.elements, args = { generate: true }; if (!form.checkValidity()) { $('proxy-setup-advanced').open = true; form.reportValidity(); say('A setting under Advanced is out of range.', 'error'); return null; } - for (const name of ['port', 'rotateGraceMinutes', 'firstOutputSeconds']) if (f[name].value !== '') args[name] = Number(f[name].value); - if (pasted) { - if (!key) { $('proxy-setup-advanced').open = true; say('Type the key in both fields under Advanced, or choose the generated key.', 'error'); return null; } - if (key !== confirm) { $('proxy-setup-advanced').open = true; say(explain('proxy-key-mismatch'), 'error'); return null; } - args.key = key; args.confirm = confirm; - } else args.generate = true; + for (const name of ['port', 'firstOutputSeconds']) if (f[name].value !== '') args[name] = Number(f[name].value); return args; } const stop = (at, reason) => Object.assign(new Error(reason), { at }); @@ -1376,7 +1357,6 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo else say({ install: 'Model service installed.', start: 'Model service started and answering.', stop: 'Model service stopped.', restart: 'Model service restarted; the new process answers.' }[op], 'success'); }); const clearFence = () => act('fence-clear', async () => { const result = await admin('fence/clear', {}); addReceipt(result.receipt); say(result.cleared ? 'Fence cleared.' : 'The fence was not set.', 'success'); }); - form.elements.keySource.forEach?.(radio => radio.addEventListener('change', () => { $('proxy-setup-paste').hidden = form.elements.keySource.value !== 'paste'; })); form.addEventListener('submit', event => event.preventDefault()); $('proxy-setup-render').addEventListener('click', async () => { const pre = $('proxy-setup-unit-file'); @@ -1393,7 +1373,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo serviceDone: () => running(), // An organization whose model list is ready, for Models offered. The open one first. readyOrg() { const orgs = Array.isArray(state?.organizations) ? state.organizations.filter(o => o.proxy === 'shared' && o.catalogue?.status === 'ready') : []; return (orgs.find(o => o.id === window.MosaicOrg?.id) ?? orgs[0])?.id ?? null; }, - stop() { enabled = false; clearTimeout(timer); timer = null; const f = form.elements; f.key.value = ''; f.confirm.value = ''; }, + stop() { enabled = false; clearTimeout(timer); timer = null; }, }; })(); // The account parts the not-configured state hides come back once the proxy answers. @@ -1409,7 +1389,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo try { await refresh(); } catch { return; } accountsShown = true; accountsDown = null; $('proxy-message').classList.remove('empty'); showAccounts(true); applyWrite(); - message('Accounts and client keys loaded.'); + message(''); paintAccountCard(); } // #1873 settings slice 1 (D3): a restart from this page's list reads the status again. @@ -1429,7 +1409,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo if (proxyAdmin) { root.querySelectorAll('[data-admin]').forEach(part => { part.hidden = false; }); setup.start(config); } paintAccountCard(); return refresh(); - }).then(() => message('Accounts and client keys loaded.')).catch(error => { message(error.message); + }).then(() => message('')).catch(error => { message(error.message); // #1873: on the setup page a stopped proxy hides the account parts like an unconfigured one, // and the setup load brings them back once the service answers. // Any failed read hides them, not only proxy-down: a proxy that is initialized but not yet answering diff --git a/packages/webui/tests/proxy-browser.test.mjs b/packages/webui/tests/proxy-browser.test.mjs index 01283fcd5..56f7eb451 100644 --- a/packages/webui/tests/proxy-browser.test.mjs +++ b/packages/webui/tests/proxy-browser.test.mjs @@ -42,7 +42,8 @@ async function setup(t, readonly = false, refusal = null) { await b.navigate(`http://127.0.0.1:${server.address().port}/#/settings/model-proxy`); const wait = expression => b.evaluate(`(async()=>{for(let n=0;n<600;n++){if(${expression})return true;await new Promise(r=>setTimeout(r,25));}throw Error('proxy UI condition timed out');})()`); await wait('window.__stubReady === true && document.readyState === "complete" && document.querySelector("#proxy-message")'); - if (!refusal) await wait('document.querySelector("#proxy-message").textContent.includes("loaded")'); + // The status line reads "Reading accounts…" until the accounts are painted, then empties. + if (!refusal) await wait('document.querySelector("#proxy-message").textContent==="" && document.querySelector("#proxy-accounts").children.length>0'); return { b, state, wait }; } test('proxy browser clears write-only key immediately, sends once and renders data as text', { timeout: 60000 }, async t => { @@ -106,7 +107,9 @@ test('proxy browser saves the configured model names for a z.ai group', { timeou 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()`)); +test('settings-s4: Model setup shows no client keys table and reads no keys (design section 10)', { timeout: 60000 }, async t => { + const {b,state}=await setup(t); + assert.equal(await b.evaluate(`Boolean(document.querySelector('#proxy-keys, #proxy-refresh'))`),false); + assert.doesNotMatch(await b.evaluate('document.body.innerText'),/Client keys|Accounts and client keys/); + assert.equal(state.routes.some(r=>r.startsWith('/api/proxy/keys')),false); }); diff --git a/packages/webui/tests/proxy-setup-browser.test.mjs b/packages/webui/tests/proxy-setup-browser.test.mjs index 25181edf8..c4bd129d5 100644 --- a/packages/webui/tests/proxy-setup-browser.test.mjs +++ b/packages/webui/tests/proxy-setup-browser.test.mjs @@ -58,30 +58,27 @@ test('without send the next-step button is disabled and nothing is posted', { ti assert.deepEqual(await writes(b), []); }); -test('init sends generate by default; a pasted key on loopback is sent with its confirmation and the fields are cleared', { timeout: 90000 }, async t => { +test('init always sends generate; there is no pasted key, and Try again sends generate again', { timeout: 90000 }, async t => { const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fetched), 'POST /api/proxy/admin/init': { body: { settings: { port: 18432 }, receipt: { op: 'init', time: T, port: 18432, generated: true } } } } }); await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init"'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Continue setup'); // The settings sit under Advanced and go with the press. assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-paste-choice").hidden'), false, 'loopback page offers the paste choice'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-paste").hidden'), true); + // settings-s4 (design section 10, A8 and A2): no "Use my own key", no key fields, no rotation grace. + assert.equal(await b.evaluate('Boolean(document.querySelector("#proxy-setup-paste-choice, #proxy-setup-paste, #proxy-setup-key, #proxy-setup-confirm, #proxy-setup-grace, [name=keySource]"))'), false); + assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-init input[type=password], #proxy-setup-advanced input[type=password]").length'), 0); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-init").textContent'), /Mosaic makes the service key on this machine/); + assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup").textContent'), /Use my own key|Key rotation grace/); await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="18432";document.querySelector("#proxy-setup-go").click();})()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/init")'); - assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/init', body: { port: 18432, generate: true } }]); + assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/init', body: { generate: true, port: 18432 } }]); assert.match(await b.evaluate('document.querySelector("#proxy-setup-receipts").textContent'), /init/); // The status still names init, so the run stops there; Try again starts from it. await wait('document.querySelector("#proxy-setup-go")?.textContent==="Try again" && !document.querySelector("#proxy-setup-init [data-setup-write]").disabled'); - await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.keySource.value="paste";f.querySelector("[value=paste]").dispatchEvent(new Event("change"));f.elements.port.value="";f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0002";document.querySelector("#proxy-setup-go").click();})()'); - await wait('document.querySelector("#proxy-setup-message").textContent.includes("proxy-key-mismatch")'); - assert.equal((await writes(b)).length, 1, 'a mismatch is refused in the page'); - assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").elements.key.value'), '', 'the key field is cleared on submit'); - await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0001";document.querySelector("#proxy-setup-go").click();})()'); + await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="";document.querySelector("#proxy-setup-go").click();})()'); await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/init").length===2'); - assert.deepEqual((await writes(b))[1], { path: '/api/proxy/admin/init', body: { key: 'pa-browser-sentinel-0001', confirm: 'pa-browser-sentinel-0001' } }); - assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup-init input[type=password]")].every(i=>i.value==="")'), true); - assert.equal(await b.evaluate('document.body.innerText.includes("pa-browser-sentinel")'), false); + assert.deepEqual((await writes(b))[1], { path: '/api/proxy/admin/init', body: { generate: true } }); }); test('after a confirmed restart the next step clears the fence and shows the receipt', { timeout: 90000 }, async t => { @@ -110,7 +107,7 @@ test('a stopped proxy hides the account panels with a setup note, and starting t unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] })} })`); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/unit/start")'); - await wait('document.querySelector("#proxy-message").textContent.includes("Accounts and client keys loaded")'); + await wait('[...document.querySelectorAll("[data-accounts-part]")].length>0 && [...document.querySelectorAll("[data-accounts-part]")].every(e=>!e.hidden)'); assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].some(e=>e.hidden)'), false); }); @@ -128,7 +125,7 @@ test('an initialized proxy whose accounts read fails with another code also hide '/api/proxy/admin/status': ${JSON.stringify({ ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] })} })`); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); - await wait('document.querySelector("#proxy-message").textContent.includes("Accounts and client keys loaded")'); + await wait('[...document.querySelectorAll("[data-accounts-part]")].length>0 && [...document.querySelectorAll("[data-accounts-part]")].every(e=>!e.hidden)'); assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].some(e=>e.hidden)'), false); }); diff --git a/packages/webui/tests/settings-review-browser.test.mjs b/packages/webui/tests/settings-review-browser.test.mjs index 0628933d1..be64d59fb 100644 --- a/packages/webui/tests/settings-review-browser.test.mjs +++ b/packages/webui/tests/settings-review-browser.test.mjs @@ -29,7 +29,7 @@ test('F6 add agent labels left aligned with launch on own row',opts,async t=>{co test('F7 maximum length agent values wrap at 390',opts,async t=>{const {b}=await page(t,'agents',390);assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);}); test('F8 root proxy route mounts its settings section',opts,async t=>{const {b}=await page(t,'model-proxy');assert.equal(await b.evaluate('location.pathname'),'/');assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts")'),true);}); test('F9 add agent saving and refusal remain local and visible',opts,async t=>{const {b,wait}=await page(t,'agents');await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');await input(b,'#instance-add-form [data-instance-field=instance]','new-coder');await b.evaluate(`document.querySelector('#instance-add-form select').value='coder';window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#instance-add-form').requestSubmit()`);await wait('!!window.__answer && !!document.querySelector("#instance-add-form .settings-spinner")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-change-form select").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("#instances-receipt")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .banner.err")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-add-form .banner.err").getBoundingClientRect().bottom<=document.querySelector("#instance-add-form button[type=submit]").getBoundingClientRect().top'),true);}); -test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await pointer(b,'#settings-nav a[href="#/settings/model-setup"]');await wait('!!document.querySelector("#proxy-order form")');await pointer(b,'#setup-step-accounts .step-toggle');await wait('!document.querySelector("#setup-step-accounts-body").hidden');await pointer(b,'#proxy-add-box summary');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-order .proxy-priority-save")).backgroundColor===getComputedStyle(document.querySelector("#proxy-refresh")).backgroundColor'),true);}); +test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await pointer(b,'#settings-nav a[href="#/settings/model-setup"]');await wait('!!document.querySelector("#proxy-order form")');await pointer(b,'#setup-step-accounts .step-toggle');await wait('!document.querySelector("#setup-step-accounts-body").hidden');await pointer(b,'#proxy-add-box summary');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-order .proxy-priority-save")).backgroundColor===getComputedStyle(document.querySelector("#proxy-login-cancel")).backgroundColor'),true);}); test('F11 Vars fields have labels and mobile agent values identify columns',opts,async t=>{const {b,wait}=await page(t,'agents',390);assert.equal(await b.evaluate('document.querySelector("#instance-add-form textarea").labels.length>0'),true);assert.match(await b.evaluate('document.querySelector("#agents-table tbody tr").innerText'),/Definition/);assert.equal(await b.evaluate('document.querySelector("#agents-table tbody td").getAttribute("headers")'), 'agent-col-definition');await b.viewport(1440,1000);await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');assert.equal(await b.evaluate('document.querySelector("#instance-change-form textarea").labels.length>0'),true);}); test('F12 collapsed section announces current draft and clears after discard',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`(()=>{let e=[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking');e.value='xhigh';e.dispatchEvent(new Event('change',{bubbles:true}))})()`);assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),true);assert.match(await b.evaluate('document.querySelector("#settings-disclosure").textContent'),/unsaved changes/);await pointer(b,'#routes-reload');await wait('!document.querySelector("#settings-nav .settings-dot")');assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),false);}); test('F13 each browser save receipt expires independently',opts,async t=>{const {b}=await page(t,'appearance');await b.evaluate('document.querySelector("[name=theme][value=dim]").focus();document.querySelector("[name=theme][value=dim]").click();document.querySelector("[name=palette][value=grove]").focus();document.querySelector("[name=palette][value=grove]").click();document.querySelector("[name=density][value=compact]").focus();document.querySelector("[name=density][value=compact]").click()');await b.evaluate('new Promise(r=>setTimeout(r,4200))');assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".settings-browser-status")].map(e=>e.textContent)'),['','','']);}); -- 2.54.0 From 23964b12242d0b7424bf972657bc755818e80228 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 18:17:54 -0600 Subject: [PATCH 10/14] fix(webui): settings-s4 review F1: the organization picker on a page that is not an organization's (Model setup, Appearance, Organizations) opens that organization's Routing page at #/settings/routing?org=, so the address base no longer changes to #/orgs// (#1873, lane settings-s4) --- packages/webui/src/public/bus.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 5e4082fea..1ae74376a 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1530,12 +1530,15 @@ let settingsFocusDisclosure=false; document.addEventListener('change', e => { if (e.target.id === 'org-picker') window.MosaicOrg?.switchTo(e.target.value); else if (e.target.id === 'org-pick') pickSettingsOrg(e.target.value); }); // Slice 4: the picker re-reads the page in place. An organization's page keeps its page with the new - // ?org=; any other Settings page stays where it is and its organization links follow the pick. + // ?org=. function pickSettingsOrg(id) { const org = window.MosaicOrg; if (!org || !id) return; const [path, query = ''] = routeOf().split('?'), page = path.split('/')[2] || 'appearance'; const rest = query.split('&').filter(p => p && !p.startsWith('org=')); - location.hash = ORG_SETTINGS.includes(page) ? `#/settings/${page}?${[`org=${enc(id)}`, ...rest].join('&')}` : `#/orgs/${enc(id)}${path}${query ? `?${query}` : ''}`; + // settings-s4 review F1: from a page that is not an organization's (Model setup, Appearance, + // Organizations) the picker opens that organization's first page, Routing, and keeps the + // single-pane address base; it never builds an #/orgs// address. + location.hash = ORG_SETTINGS.includes(page) ? `#/settings/${page}?${[`org=${enc(id)}`, ...rest].join('&')}` : `#/settings/routing?org=${enc(id)}`; } document.addEventListener('click', e=>{const b=e.target.closest?.('#settings-disclosure');if(b){b.setAttribute('aria-expanded',String(b.getAttribute('aria-expanded')!=='true'));return;} if(e.target.closest?.('#settings-nav a')) { const b=$('settings-disclosure'); if(b?.getAttribute('aria-expanded')==='true') {b.setAttribute('aria-expanded','false');settingsFocusDisclosure=true;b.focus();} }}); document.addEventListener('keydown', e=>{if(e.key==='Escape' && $('settings-disclosure')?.getAttribute('aria-expanded')==='true'){e.preventDefault();$('settings-disclosure').setAttribute('aria-expanded','false');$('settings-disclosure').focus();}}); -- 2.54.0 From 799df9cb9f4e737019a5c0a980330634927abca0 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 18:17:54 -0600 Subject: [PATCH 11/14] fix(webui): settings-s4 review F2 and N8: an organization the sidebar marks "can't start" (stand-in models, bus stopped) is named on Model setup step 3 by its display name in the same words, with the fix (move it to your models, then start its bus), and its Ride all line and Move button use the display name; the paused mark needs the service itself down (not running or not listening), so a fence left to clear no longer marks organizations paused (#1873, lane settings-s4) --- packages/webui/src/public/display.js | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 0fe2068ac..eccc1005a 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -1120,7 +1120,11 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo // 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. const removed = rideSkips().filter(s => s.reason === 'removed').map(s => nameOf(s.id)); - const doneLine = rideListed() ? 'The model service is set up. Some organizations still need a step under Use your models in every organization.' + // settings-s4 review F2: an organization the sidebar marks "can't start" (stand-in models, bus + // stopped) is named here in the same words, with what fixes it. + const cant = cantStart().map(f => nameOf(f.id)); + const doneLine = cant.length ? `The model service is set up. ${listNames(cant)} can't start: ${cant.length === 1 ? 'it uses' : 'they use'} stand-in models and ${cant.length === 1 ? 'its bus is' : 'their buses are'} stopped. Move ${cant.length === 1 ? 'it' : 'them'} to your models under Use your models in every organization, then start ${cant.length === 1 ? 'its bus' : 'their buses'}.` + : rideListed() ? 'The model service is set up. Some organizations still need a step under Use your models in every organization.' : removed.length ? `The model service is set up and every organization that uses it can see your models. ${listNames(removed)} turned it off, and Ride all leaves ${removed.length === 1 ? 'it' : 'them'} off.` : 'The model service is set up and every organization can see your models.'; const [kind, text, badge] = { @@ -1237,6 +1241,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const rideListed = () => { const ride = Array.isArray(state.ride) ? state.ride : []; return ride.filter(r => r.state === 'ready').length + rideSkips().filter(s => s.reason !== 'removed').length + (rideResult?.fixtures ?? ride.filter(r => r.state === 'fixture')).length; }; const li = text => { const item = document.createElement('li'); item.textContent = text; return item; }; + // The rule the sidebar's "can't start" mark uses (MosaicModelDots below): stand-in models with the bus stopped. + const cantStart = () => (Array.isArray(state?.ride) ? state.ride : []).filter(r => r.state === 'fixture' && r.running === false); function paintRide() { const box = $('proxy-ride'), ride = Array.isArray(state.ride) ? state.ride : null; box.hidden = !ride || !state.init?.initialized; @@ -1250,9 +1256,12 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo 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. - if (f.running === null) return li(`${f.id} uses stand-in models. Moving it is not available on this Console.`); - const item = li(`${f.id} uses stand-in models, can be moved to the owner's 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 ${f.id}`; + 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 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); }); item.append(move); return item; @@ -1444,10 +1453,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo async function compute(status) { if (!status || typeof status !== 'object') return; const orgs = Array.isArray(status.organizations) ? status.organizations : [], ride = Array.isArray(status.ride) ? status.ride : []; - const key = JSON.stringify([status.next?.[0], status.init?.initialized, orgs.map(o => [o.id, o.catalogue?.status, o.catalogue?.launchRestart]), ride.map(r => [r.id, r.state, r.running])]); + const key = JSON.stringify([status.next?.[0], status.init?.initialized, status.unit?.active, status.unit?.listening, orgs.map(o => [o.id, o.catalogue?.status, o.catalogue?.launchRestart]), ride.map(r => [r.id, r.state, r.running])]); if (key === last) return; last = key; const turn = ++round, next = new Map(), serviceUp = status.next?.[0] === 'accounts'; - if (status.init?.initialized && !serviceUp) for (const r of ride) if (r.state === 'already') next.set(r.id, 'paused'); + // settings-s4 review N8: paused only while the service itself is down (not running or not + // listening), not on any other next step such as a fence to clear. + const down = status.unit?.active !== 'active' || status.unit?.listening === false; + if (status.init?.initialized && !serviceUp && down) for (const r of ride) if (r.state === 'already') next.set(r.id, 'paused'); if (serviceUp) { for (const r of ride) if (r.state === 'fixture' && r.running === false) next.set(r.id, 'cant'); await Promise.all(orgs.filter(o => !next.has(o.id)).map(async o => { -- 2.54.0 From 940ac53b65a329db0d9f02bc287b306b4cb0a504 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 18:17:54 -0600 Subject: [PATCH 12/14] test(webui): settings-s4 review: the picker from Model setup, Appearance and Organizations lands on #/settings/routing?org= (F1); the can't start mark and the step 3 words and Ride all line agree (F2); no paused mark with only a fence to clear (N8); every control under Advanced shows a focus ring before setup, and the fixture service reads healthy (N9); F1, F2 and N8 fail with the display.js and bus.js of e717824c5 (#1873, lane settings-s4) --- .../webui/tests/settings-s4-browser.test.mjs | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/packages/webui/tests/settings-s4-browser.test.mjs b/packages/webui/tests/settings-s4-browser.test.mjs index bef18796c..318f9c357 100644 --- a/packages/webui/tests/settings-s4-browser.test.mjs +++ b/packages/webui/tests/settings-s4-browser.test.mjs @@ -57,7 +57,7 @@ async function orgFixture() { // The instance owner's flags on /api/config and the model service status, by path suffix (display.js // scopes some reads under /api/orgs//). Everything else is the real server. const SERVICE_UP = { next: ['accounts'], init: { initialized: true, 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 }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] }; + 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 ownerStub = (service = SERVICE_UP, extra = {}) => `(() => { const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service, accounts: [], routes: null, posts: {}, ...extra })}; window.__writes = []; const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); @@ -156,6 +156,51 @@ test('settings-s4: the sidebar marks an organization paused while the model serv assert.equal(await b.evaluate(mark('gamma')), 'bus stopped'); }); +// settings-s4 review F1: the picker on a page that is not an organization's keeps the #/settings/ base. +test('settings-s4 review F1: picking an organization from Model setup opens its Routing page at #/settings/routing?org=', { timeout: 90000 }, async t => { + const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup' }); + await wait('document.querySelector("#org-pick") && document.querySelector("#proxy-setup")'); + await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "north"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await wait('location.hash === "#/settings/routing?org=north" && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=north\'][aria-current=page]")'); + await wait('/North Works/.test(document.querySelector("#breadcrumbs")?.textContent ?? "")'); + assert.equal(await b.evaluate('location.hash.includes("#/orgs/")'), false); + for (const from of ['appearance', 'organizations']) { + await b.evaluate(`location.hash = "#/settings/${from}"; true`); + await wait(`document.querySelector("#settings-nav a[href='#/settings/${from}'][aria-current=page]") && document.querySelector("#org-pick")`); + await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "acme"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await wait('location.hash === "#/settings/routing?org=acme" && document.querySelector("#org-pick")?.value === "acme"'); + await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "north"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await wait('location.hash === "#/settings/routing?org=north"'); + } +}); + +// settings-s4 review F2: the organization the sidebar marks "can't start" is named on step 3 in the same words. +test('settings-s4 review F2: a stand-in organization with its bus stopped reads "can\'t start" in the sidebar and on Model setup step 3, with the fix', { timeout: 90000 }, async t => { + const service = { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }], + ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'already' }, { id: 'gamma', state: 'fixture', running: false }] }; + const accounts = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }]; + const { b, wait, text } = await orgSetup(t, { path: '/#/settings/model-setup', service, extra: { accounts } }); + await wait(`${mark('gamma')} === "can't start"`); + await wait(`/can't start/.test(document.querySelector(${JSON.stringify(STEP3)})?.textContent ?? "")`); + 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(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. + assert.equal(await b.evaluate(mark('acme')), 'bus running'); +}); + +// settings-s4 review N8: a fence to clear while the service runs is not "paused". +test('settings-s4 review N8: no paused mark while the service runs and only a fence is left to clear', { timeout: 90000 }, async t => { + const service = { ...SERVICE_UP, next: ['fence-clear'], fence: { set: true }, ride: [{ id: 'acme', state: 'already' }] }; + const { b, wait } = await orgSetup(t, { path: '/#/dashboard', service }); + await wait(`${mark('acme')} === 'bus running' && ${mark('north')} === 'bus running'`); + await new Promise(r => setTimeout(r, 1500)); + assert.equal(await b.evaluate(mark('acme')), 'bus running'); +}); + // ---- Part B: Model setup --------------------------------------------------------------------- const T = '2026-11-11T12:00:00.000Z'; const fresh = { @@ -300,6 +345,25 @@ test('settings-s4: Models offered lists each provider\'s models read-only with a assert.deepEqual(await b.evaluate('window.__writes'), [], 'reading the models writes nothing'); }); +test('settings-s4 review N9: before setup, every control under Advanced takes focus with a visible ring', { timeout: 90000 }, async t => { + const fresh = { ...SERVICE_UP, release: { ...SERVICE_UP.release, fetched: false, verified: false }, init: { initialized: false, partial: false, files: [] }, + unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' }, organizations: [], next: ['fetch'] }; + const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: fresh }); + await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "fetch" && !document.querySelector("#proxy-setup-advanced").hidden'); + await b.evaluate('(() => { const d = document.querySelector("#proxy-setup-advanced"); d.open = true; d.querySelector("summary").focus(); return true; })()'); + await wait('document.querySelector("#proxy-setup-advanced").open && document.activeElement?.closest("#proxy-setup-advanced")'); + const visited = [], noRing = []; + for (let i = 0; i < 20; 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.closest("#proxy-setup-advanced")) return null; const cs = getComputedStyle(e); + return { key: e.id || e.name || e.tagName, ring: (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none') }; })()`); + if (!r) break; visited.push(r.key); if (!r.ring) noRing.push(r.key); + } + assert.ok(visited.includes('proxy-setup-port') && visited.includes('proxy-setup-first'), JSON.stringify(visited)); + assert.deepEqual(noRing, []); +}); + test('settings-s4 P3: the done line names an organization that turned the model service off and does not count it as waiting', { timeout: 90000 }, async t => { const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }]; const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'removed' }] }; -- 2.54.0 From ae53b1988ac1281d98c450e25c24d989a64f3455 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 18:25:36 -0600 Subject: [PATCH 13/14] feat(webui): settings-s4: an account row on Model setup shows why the account is not working, from the accounts read's reason field (chat-fail F3, a7362a8fc and later), as text beside its state; with no reason field, or an empty one, nothing shows; the test is red with the display.js of 12e99db49 (#1873, lane settings-s4) --- packages/webui/src/public/display.js | 5 +++- packages/webui/src/public/shell.css | 3 ++- .../webui/tests/settings-s4-browser.test.mjs | 24 +++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index eccc1005a..c3d32bf45 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -740,7 +740,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const li = el('li'), name = el('span', providerShort(account.provider)), kind = el('span', providerKind(account.provider) || '—'); kind.append(el('br'), el('small', account.displayName, 'muted')); const [cls, word] = health(account.status), badge = el('span', word, `badge ${cls}`); - li.dataset.account = account.accountId; li.append(name, kind, badge); return li; + li.dataset.account = account.accountId; li.append(name, kind, badge); + // The accounts read says why an account is not working (account.reason, a7362a8fc and later). Absent, nothing shows. + if (typeof account.reason === 'string' && account.reason) li.append(el('p', account.reason, 'small muted account-reason')); + return li; })); } function paintOrder() { diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index d9d19bd92..aa391ff0e 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -338,6 +338,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .rows{margin:var(--gap,12px) 0 0;padding:0;list-style:none} .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} .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)} @@ -349,7 +350,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .err-line{color:var(--danger)} .settings-content details{margin-top:var(--gap,12px)} .settings-content details>.inside{margin-top:var(--gap,12px)} -@media(max-width:759px){.rows li{grid-template-columns:1fr}.rows li>.badge{justify-self:start}.setup-step .summary,.setup-step .body{margin-left:0}.settings-form{max-width:none}.settings-form .w-num{max-width:none}} +@media(max-width:759px){.rows li{grid-template-columns:1fr}.rows li>.badge{justify-self:start}.rows li>.account-reason{grid-column:auto}.setup-step .summary,.setup-step .body{margin-left:0}.settings-form{max-width:none}.settings-form .w-num{max-width:none}} @media(max-width:959px) and (min-width:760px){.settings-layout{grid-template-columns:180px minmax(0,1fr);gap:24px}} @media(max-width:759px){.settings-layout{display:block}.settings-layout>div:first-child{margin-bottom:20px}#settings-disclosure{width:100%;min-height:44px;display:flex;align-items:center;gap:12px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);text-align:left}#settings-disclosure small{color:var(--muted)}#settings-disclosure span{margin-left:auto}#settings-disclosure[aria-expanded=false]+#settings-nav{display:none}#settings-nav{padding:12px 0}.settings-content>h2{font-size:21px}.palette-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.palette-content{min-height:64px;padding:7px}.palette-tile input:checked+.palette-content{padding:6px}.settings-segments{display:flex;width:100%}.settings-segments label{flex:1;min-width:0}.settings-segments span,.settings-appearance .panel:last-child .settings-segments span{min-width:0;padding:0 4px}.settings-content .table-wrap{max-width:100%}} .settings-content [aria-invalid=true]{border:2px solid var(--danger)!important} diff --git a/packages/webui/tests/settings-s4-browser.test.mjs b/packages/webui/tests/settings-s4-browser.test.mjs index 318f9c357..4e05bc2f0 100644 --- a/packages/webui/tests/settings-s4-browser.test.mjs +++ b/packages/webui/tests/settings-s4-browser.test.mjs @@ -324,6 +324,30 @@ test('settings-s4: accounts read as rows with kind and health, the provider pick assert.deepEqual(await b.evaluate('window.__writes.map(w => w.path)').then(p => p.filter(x => /login\/(start|cancel)/.test(x))), ['/api/proxy/login/start', '/api/proxy/login/cancel']); }); +test('settings-s4 chat-fail F3: an account row shows the accounts read\'s reason beside its state, as text, and nothing when the field is absent or empty', { timeout: 90000 }, async t => { + const out = 'The account is out of usage. It resets at 2099-03-04 05:06 UTC. Wait until then, or add another account.'; + const signin = 'The account needs to sign in again. Sign in again, or add another account. '; + const list = [ + { accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'unavailable', priority: 2, reason: out }, + { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'error', priority: 1, reason: signin }, + { accountId: 'a3', provider: 'claude', displayName: 'Claude spare', status: 'error', priority: 0, reason: '' }, + { accountId: 'a4', provider: 'codex', displayName: 'Codex work', status: 'active', priority: 0 }, + ]; + for (const width of [1440, 390]) { + const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null } } }); + await b.viewport(width, width === 390 ? 844 : 900); + await b.navigate(f.base + '/#/settings/model-setup?step=accounts'); + await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li")].map(li => [...li.children].map(c => c.textContent.replace(/\\s+/g, " ").trim()))'), [ + ['Claude', 'SubscriptionClaude work', 'Not available', out], ['ChatGPT / Codex', 'SubscriptionCodex home', 'Not working', signin], + ['Claude', 'SubscriptionClaude spare', 'Not working'], ['ChatGPT / Codex', 'SubscriptionCodex work', 'Ready']], `${width}: the reason follows the state; absent or empty shows nothing`); + assert.equal(await b.evaluate('document.querySelectorAll("#proxy-accounts img").length + (window.__xss ?? 0)'), 0, 'the reason is text, never markup'); + assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-accounts .account-reason")].every(p => p.checkVisibility() && p.getBoundingClientRect().right <= document.documentElement.clientWidth)'), true); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}: nothing scrolls sideways`); + await b.close(); + } +}); + test('settings-s4: Models offered lists each provider\'s models read-only with a count, a search past eight, and Coming later', { timeout: 90000 }, async t => { const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }, { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'active', priority: 0 }]; const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-model-${i}`, available: true })) -- 2.54.0 From 524132b42b3423a59b121c500fe49fcc6dd19797 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 18:47:38 -0600 Subject: [PATCH 14/14] test(webui): settings-s4 review F1: each organization pick waits for the picker and changes it in one step, since a route change repaints the select; the final gate caught the select missing for a moment between a wait and the pick; the test still fails with the bus.js and display.js of e717824c5 (#1873, lane settings-s4) --- packages/webui/tests/settings-s4-browser.test.mjs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/webui/tests/settings-s4-browser.test.mjs b/packages/webui/tests/settings-s4-browser.test.mjs index 4e05bc2f0..cbac26670 100644 --- a/packages/webui/tests/settings-s4-browser.test.mjs +++ b/packages/webui/tests/settings-s4-browser.test.mjs @@ -159,17 +159,19 @@ test('settings-s4: the sidebar marks an organization paused while the model serv // settings-s4 review F1: the picker on a page that is not an organization's keeps the #/settings/ base. test('settings-s4 review F1: picking an organization from Model setup opens its Routing page at #/settings/routing?org=', { timeout: 90000 }, async t => { const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup' }); + // A route change repaints the picker, so the pick waits for the select and changes it in one step. + const pick = id => wait(`(() => { const s = document.querySelector("#org-pick"); if (!s || ![...s.options].some(o => o.value === "${id}")) return false; s.value = "${id}"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()`); await wait('document.querySelector("#org-pick") && document.querySelector("#proxy-setup")'); - await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "north"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await pick('north'); await wait('location.hash === "#/settings/routing?org=north" && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=north\'][aria-current=page]")'); await wait('/North Works/.test(document.querySelector("#breadcrumbs")?.textContent ?? "")'); assert.equal(await b.evaluate('location.hash.includes("#/orgs/")'), false); for (const from of ['appearance', 'organizations']) { await b.evaluate(`location.hash = "#/settings/${from}"; true`); await wait(`document.querySelector("#settings-nav a[href='#/settings/${from}'][aria-current=page]") && document.querySelector("#org-pick")`); - await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "acme"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await pick('acme'); await wait('location.hash === "#/settings/routing?org=acme" && document.querySelector("#org-pick")?.value === "acme"'); - await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "north"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()'); + await pick('north'); await wait('location.hash === "#/settings/routing?org=north"'); } }); -- 2.54.0