`;
}
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,23 @@
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=.
+ 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='));
+ // 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();}});
@@ -1739,7 +1765,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, `
${state}, so ${txt(name)} can't be read. Start it again to see and change this page. Nothing was written.
`);
}
@@ -1881,7 +1907,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 +1923,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 +2007,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 +2015,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 +2041,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..c3d32bf45 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.
@@ -560,48 +581,125 @@ 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 = '
Set up the model service
'
- + '
The model service lets your organizations use your own model accounts. Each step is checked on this machine. Keys are never shown.
'
- + ''
+ // #1873 settings slice 4 (DESIGN.md section 3): Model setup is four step cards. 1 Model service and
+ // 3 Organizations and 4 Triage are the instance owner's (config.proxyAdmin); 2 Accounts and models is
+ // everyone's. The first card that is not done is open; a done card shows one line. Every line on a
+ // card comes from a read on this page: the setup status, the accounts, an organization's routes,
+ // the Triage route. Advanced and Technical details follow the cards.
+ const card = (key, n, title, body, admin) => ``
+ + `${n}
${title}
Waiting`
+ + ``
+ + `
${body}
`;
+ const service = ''
+ + ''
+ ''
- + '
Organizations that can\'t use your models yet
'
+ + 'The service\'s last lines
This page can\'t read the service\'s lines yet. What the service said last, when the host reported it:
Nothing reported.
'
+ + '';
+ const accounts = '
Reading accounts…
'
+ + '
This Console is read-only. Sign-in and account changes are unavailable.
'
+ + '
'
+ + '
Removing an account is not built yet.
'
+ + 'Account order
Higher priority is used first. Credential values are never shown.
An organization connects to the model service the next time it reads its models. These still can\'t see your models, need a restart before their agents start on them, or are not running. Each one says why. Where a restart helps, it has a Restart button: the organization stops for a moment and starts again.
'
+ '
'
- + '
Use your models in every organization
'
+ + '
Use your models in every organization
'
+ ''
- + '
'
- + 'Initialize the model service'
- + 'Technical details'
- + '
'
- + '
Service controls
Install renders the unit the same way as mosaic proxy unit install.
Each organization switches these on or off on its own Models page. Claude subscription models run only in Claude Code. Turning a program off for every organization is not built yet.
'
+ + ''
+ + '
Changing these after setup is not built yet.
';
+ const tech = 'Technical details: release, service, history
'
+ + '
'
+ + '
Service controls
Install renders the unit the same way as mosaic proxy unit install.
'
+ ''
+ '
'
- + '
Organizations
Organization
Proxy
Catalogue
Models
'
+ + '
Organizations
Organization
Proxy
Catalogue
Models
'
+ '
'
- + '
Receipts
No setup actions on this page yet.
\n';
- const markup = setupMarkup + '
Reading accounts…
\n
This Console is read-only. Sign-in and account changes are unavailable.
\n
Accounts
\n
Higher priority is used first. Account names are stable identifiers; credential values are never displayed.
\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',
@@ -618,10 +716,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);
+ // 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() {
+ 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 = await call('accounts');
+ accountList = Array.isArray(accounts?.accounts) ? accounts.accounts : [];
+ accountsDown = null;
+ paintAccounts(); paintOrder();
+ 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.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);
+ }
+ 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;
@@ -637,56 +863,16 @@ 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);
@@ -695,39 +881,43 @@ 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);
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.',
@@ -738,10 +928,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.',
@@ -793,46 +983,87 @@ 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'];
+ // 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() {
+ 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], 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';
@@ -856,12 +1087,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.
@@ -870,13 +1102,55 @@ 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));
+ // 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] = {
+ '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);
@@ -888,7 +1162,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];
@@ -910,23 +1184,40 @@ 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; });
- $('proxy-setup-paste-choice').hidden = !pasteAllowed; $('proxy-setup-paste-note').hidden = pasteAllowed;
+ 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;
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`); }
}
+ // 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.',
@@ -946,10 +1237,15 @@ 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; };
+ // 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;
@@ -959,14 +1255,16 @@ 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.' : ''} `);
- 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;
@@ -994,17 +1292,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;
@@ -1013,13 +1310,58 @@ 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. 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 = { 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', 'firstOutputSeconds']) if (f[name].value !== '') args[name] = Number(f[name].value);
+ 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);
@@ -1027,50 +1369,40 @@ 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();
- 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(); },
- stop() { enabled = false; clearTimeout(timer); timer = null; const f = form.elements; f.key.value = ''; f.confirm.value = ''; },
+ 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; },
};
})();
- // 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;
- message('Accounts and client keys loaded.');
+ accountsShown = true; accountsDown = null; $('proxy-message').classList.remove('empty'); showAccounts(true);
+ applyWrite();
+ message('');
+ paintAccountCard();
}
// #1873 settings slice 1 (D3): a restart from this page's list reads the status again.
const onRestarted = () => { setup.reread(); };
@@ -1078,33 +1410,89 @@ 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,
+ }).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
// 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, 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';
+ // 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 => {
+ 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..aa391ff0e 100644
--- a/packages/webui/src/public/shell.css
+++ b/packages/webui/src/public/shell.css
@@ -291,7 +291,10 @@ 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}
+/* #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}
.settings-segments input,.palette-tile input{position:absolute;opacity:0;width:1px;height:1px}
@@ -309,6 +312,45 @@ 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)}
+.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)}
+.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}.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}
@@ -356,7 +398,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 +414,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/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.