From 78d1ef77057166160dd983b728274bcab5eb3d67 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 17:38:58 -0600 Subject: [PATCH] feat(webui): settings-s4 Model setup: four step cards (Model service, Accounts and models, Organizations, Triage) with at most one primary button on the page; one press runs download, set up, install and start in order, each step once, reading the status after each, with a progress list; a step that fails stops with Try again and opens "The service's last lines"; done cards fold to their line, ?step= opens one; accounts as rows with kind and a health badge, a provider select that offers "Sign in to " or "Check and add" for an API key, a cancellable sign-in with the paste-back form, and "Removing an account is not built yet."; Models offered read-only per provider with a count, a search box past eight and "Coming later"; Advanced and Technical details folded; the Ride all done line does not count an organization that turned the model service off; MosaicModelDots reads the setup status for the sidebar marks (#1873, lane settings-s4) --- packages/webui/src/public/display.js | 752 +++++++++++++----- packages/webui/src/public/shell.css | 46 +- packages/webui/tests/proxy-browser.test.mjs | 2 +- .../webui/tests/proxy-setup-browser.test.mjs | 161 ++-- .../tests/settings-review-browser.test.mjs | 12 +- 5 files changed, 696 insertions(+), 277 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 2ca821ae2..9b2a76598 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -581,48 +581,132 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo // No browser storage, request/body logging, key reveal, or automatic write retry. (() => { 'use strict'; - // #1873: setup from nothing to a working proxy. Shown only to the instance owner (config.proxyAdmin). - // #1873 settings slice 1 (D3, D4): the next step and its one button come first, then the kept list - // of organizations that need a restart and the Ride all box (ride-default). Done steps, the service controls, the fence, the init lock, - // the organization table and the receipts sit under Technical details. - const setupMarkup = '\n'; - const markup = setupMarkup + '

Reading accounts…

\n\n

Accounts

\n

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

\n
AccountProviderStatusPriorityModels
\n

Sign in to an account

\n
Subscription account
\n

\n

\n
Finish sign-in

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

\n

Add an API key

\n
z.ai

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

\n

Client keys

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

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

History

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

Client keys

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

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

Set up the model service

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

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

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

Set up the model service

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

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

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