From e1b56d9ea7bebc0384c64f1318d78f9988398a10 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 22:53:50 -0600 Subject: [PATCH 1/4] feat(webui): settings-s5b: Model setup's Technical details shows when the service key was made (GET /api/proxy/admin/service-key, never the key, with renewal not built yet), the setup history a page at a time (GET /api/proxy/admin/history, withheld rows plain, an empty page with a next page still offers Show older) and the service's last lines (GET /api/proxy/admin/log, as the answer gives them); a failed step 1 opens the lines; each read waits until its box opens, a failed read says so with Read again, and none of it is read or shown for a non-owner; the raw receipts list is gone; leaving the Models page for any page drops its focus request; tests red on e6f6f5445 (#1873, lane settings-s5b) --- packages/webui/src/public/bus.js | 3 + packages/webui/src/public/display.js | 164 ++++++- packages/webui/src/public/shell.css | 5 +- .../webui/tests/proxy-setup-browser.test.mjs | 38 +- .../webui/tests/settings-s5b-browser.test.mjs | 428 ++++++++++++++++++ 5 files changed, 610 insertions(+), 28 deletions(-) create mode 100644 packages/webui/tests/settings-s5b-browser.test.mjs diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index c9b979233..ec6512db9 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1978,6 +1978,9 @@ if (answer && (navigated || path !== (answer.org ? '/inbox' : `/inbox/${answer.id}`))) answer = null; // Recheck N1: arriving at Models reads the model service again; a status read on an earlier visit may be out of date. if (navigated && path === '/settings/routing' && (typeof shown === 'string' ? shown.split('?')[0] : shown) !== path && !serviceLoading) serviceState = null; + // settings-s5b: a focus request for the Models outcome line belongs to that page. Going anywhere else drops it, + // including Assistant, Projects and the board, which return before the focus chain at the end of render. + if (navigated && path !== '/settings/routing') modelsFocus = false; const g = ++gen, routeVersion = routesEditVersion; const current = () => g === gen && route === routeOf() && !out(); // In organization mode #/ is the cross-organization dashboard; the processing controls stay on the board. diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index c9a70580f..fa2397a44 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -593,7 +593,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo const service = '
' + '' + '

' - + '' + // settings-s5b: the lines come from GET /api/proxy/admin/log, read when the box opens (readLog in the controller). + + '' + ''; const accounts = '

Reading accounts…

' + '' @@ -642,7 +643,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo + '' + '

Organizations

OrganizationProxyCatalogueModels
' + '

' - + '

History

  1. No setup actions on this page yet.
' + // settings-s5b: the service key, the service's lines and the setup history, read when they open (owner only). + + '
Service key
Not read yet.
' + + '
The service\'s last lines
' + + '

History

Not read yet.

' + + '
    ' + + '

    ' + + '

    ' + ''; const markup = '
    ' + card('service', 1, 'Model service', service, true) @@ -957,19 +964,142 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo } const say = (text, kind) => receipt('proxy-setup-message', text, kind); const human = value => value === null || value === undefined ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(value); - function addReceipt(record) { - if (!record || typeof record !== 'object') return; - const list = $('proxy-setup-receipts'); list.querySelector('li.muted')?.remove(); - const li = document.createElement('li'), op = document.createElement('strong'); op.textContent = record.op ?? 'action'; - const details = Object.entries(record).filter(([k]) => k !== 'op' && k !== 'time').map(([k, v]) => `${k}: ${human(v)}`).join(', '); - li.append(op, ` ${window.MosaicLocalTime(record.time)}${details ? ' — ' + details : ''}`); - list.prepend(li); + // settings-s5b: History, the service key and the service's lines come from their own reads + // (GET /api/proxy/admin/history, service-key and log). Nothing reads them until their box opens, + // and only the instance owner's page starts this controller. A write's receipt reads them again + // when Technical details is open, so the page never shows a raw receipt. + const techOpen = () => $('proxy-setup-tech')?.open === true; + function addReceipt() { if (enabled && techOpen()) { readKey(); readHistory(true); } } + const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`; + const count = n => Number.isInteger(n) && n > 0 ? n : 0; + // A failed read says what the answer's code means here; a request that got no answer says so. A code + // shaped like a Mosaic key is not shown, even though it passes admin()'s letters-and-hyphens check. + const failText = (error, words) => !error?.code ? (error instanceof TypeError ? 'The Console did not answer.' : String(error?.message ?? 'The Console did not answer.')) + : /ms[kotp][-_]/i.test(error.code) ? 'The Console refused the read.' : words[error.code] ? `${words[error.code]} (${error.code})` : error.message; + const retryButton = (id, action) => { const button = el('button', 'Read again'); button.type = 'button'; if (id) button.id = id; button.addEventListener('click', action); return button; }; + // The service's last lines: one read paints every box. The lines show as the answer has them: + // the route removes key-shaped text; this page adds nothing and takes nothing away. + const LOG_WORDS = { 'not-configured': 'The model service is not installed, so it has no lines yet.', 'outcome-unknown': 'The host could not read the service\'s lines.', 'invalid-request': 'The Console refused the request.' }; + let logRound = 0, logAnswer = null; + function paintLog() { + for (const box of root.querySelectorAll('[data-log]')) { + if (!logAnswer) { box.replaceChildren(el('p', 'Reading the service\'s lines…', 'small muted')); continue; } + if (logAnswer.error) { box.replaceChildren(el('p', `The service's lines could not be read. ${logAnswer.error}`, 'banner err'), retryButton(null, readLog)); continue; } + const { lines, redacted, dropped } = logAnswer, notes = ['Mosaic removes anything that looks like a key.']; + if (redacted) notes.push(`It removed something from ${plural(redacted, 'line')}.`); + if (dropped) notes.push(`${plural(dropped, 'line')} ${dropped === 1 ? 'was' : 'were'} left out.`); + const parts = [el('p', notes.join(' '), 'small muted')]; + parts.push(lines.length ? el('pre', lines.join('\n'), 'setup-log') : el('p', dropped ? 'No line is left to show.' : 'The service has written nothing yet.', 'small muted')); + parts.push(retryButton(null, readLog)); + box.replaceChildren(...parts); + } } - // #1873: receipts survive a reload: status carries the last few from proxy-admin.jsonl. - function paintReceipts() { - if (!Array.isArray(state.receipts) || !state.receipts.length) return; - $('proxy-setup-receipts').replaceChildren(); state.receipts.forEach(addReceipt); + async function readLog() { + if (!enabled) return; + // A Read again pressed in a box keeps focus there once the answer is painted. + const from = [...root.querySelectorAll('[data-log]')].find(box => box.contains(document.activeElement)); + const round = ++logRound; logAnswer = null; paintLog(); + let answer; + try { + const value = await admin('log?lines=20'); + if (!value || !Array.isArray(value.lines)) throw Object.assign(new Error('The answer could not be read.'), { code: 'outcome-unknown' }); + answer = { lines: value.lines.filter(line => typeof line === 'string'), redacted: count(value.redacted), dropped: count(value.dropped) }; + } catch (error) { answer = { error: failText(error, LOG_WORDS) }; } + if (round !== logRound || !enabled) return; + logAnswer = answer; paintLog(); + from?.querySelector('button')?.focus(); } + // When the service key was made. Never the key: the answer has no key, and this shows only its time. + const KEY_WORDS = { 'not-configured': 'Model service setup is not available on this Console.', 'outcome-unknown': 'The host could not check the key.' }; + let keyRound = 0; + async function readKey() { + if (!enabled) return; + const round = ++keyRound, dd = $('proxy-setup-keymade-text').parentElement, refocus = document.activeElement?.id === 'proxy-setup-keymade-retry'; + dd.replaceChildren(el('span', 'Reading…', 'muted')); dd.firstChild.id = 'proxy-setup-keymade-text'; + let text, failed = false; + try { + const value = await admin('service-key'); + if (!value || typeof value !== 'object') throw Object.assign(new Error('The answer could not be read.'), { code: 'outcome-unknown' }); + const renewed = value.renewal !== 'not-built' && Number.isFinite(Date.parse(value.renewedAt)) ? ` Last renewed ${window.MosaicLocalTime(value.renewedAt)}.` : ' Renewing it is not built yet.'; + if (value.problem === 'missing') text = 'Not made yet. Set up model service in step 1 makes it. You never see it.'; + else if (value.problem === 'unreadable') text = 'Mosaic can\'t tell when it was made: the service\'s settings file is not one it can check. You never see the key.'; + else if (Number.isFinite(Date.parse(value.madeAt))) text = `Mosaic made it on ${window.MosaicLocalTime(value.madeAt)}. You never see it.${renewed}`; + else text = `When it was made is not known. You never see it.${renewed}`; + } catch (error) { failed = true; text = `When it was made could not be read. ${failText(error, KEY_WORDS)}`; } + if (round !== keyRound || !enabled) return; + const span = el('span', text, failed ? 'err-line' : undefined); span.id = 'proxy-setup-keymade-text'; + dd.replaceChildren(span, ...(failed ? [' ', retryButton('proxy-setup-keymade-retry', readKey)] : [])); + if (refocus) { if (failed) $('proxy-setup-keymade-retry').focus(); else { span.tabIndex = -1; span.focus(); } } + } + // Setup history, a page at a time. The first page holds the newest entries, oldest first within + // it; the list shows newest first. A page can be empty and still name an older one. + const HISTORY_WORDS = { 'not-configured': 'Model service setup is not available on this Console.', 'outcome-unknown': 'The host could not read the history.', 'invalid-request': 'The Console refused that page.' }; + const FEW = 3; + const hist = { entries: [], next: null, loading: false, expanded: false, error: null, emptyPage: false, round: 0, read: false }; + const orgName = id => { const label = typeof id === 'string' ? window.MosaicOrg?.row?.(id)?.label : null; return typeof label === 'string' && label ? label : null; }; + const providerOf = p => typeof p === 'string' && [...providerSelect.options].some(o => o.value === p) ? providerShort(p) : null; + // A name shown as written, unless it holds text shaped like a Mosaic key. + const shownName = v => typeof v === 'string' && v && v.length <= 64 && !/ms[kotp][-_]/i.test(v) ? v : null; + function historyText(entry) { + if (!entry || typeof entry !== 'object' || entry.withheld === true) return null; + const org = orgName(entry.org), provider = providerOf(entry.provider), some = org ?? 'An organization'; + const n = (v, word) => Number.isInteger(v) && v >= 0 ? plural(v, word) : null; + const label = { + 'account.proxy.apikey.add': provider ? `${provider} account added` : 'Account added', + 'account.proxy.login.complete': 'Signed in to an account', + 'account.proxy.priority.set': Number.isInteger(entry.priority) ? `Account order changed, priority ${entry.priority}` : 'Account order changed', + 'account.proxy.group.models.set': n(entry.models, 'model') ? `Models chosen for an account, ${n(entry.models, 'model')}` : 'Models chosen for an account', + fetch: 'Release downloaded and checked', init: 'Set up', 'init-lock.clear': 'Stale setup lock cleared', 'fence.clear': 'Key writes resumed', + 'unit.install': 'Service installed', 'unit.start': 'Started', 'unit.stop': 'Stopped', 'unit.restart': 'Restarted', + 'ride-all': 'Organizations switched to your models', 'ride-move': `${some} switched to your models`, 'ride-intent': `Switching ${org ?? 'an organization'} to your models`, + 'ride-not-added': `${some} was not switched to your models`, 'ride-removed': `${some} stopped using your models`, + }[entry.op] ?? 'Other setup action'; + const inOrg = org && String(entry.op).startsWith('account.') ? ` in ${org}` : ''; + const user = entry.user === '[redacted]' ? 'someone whose name looked like an email address, so it is hidden' : shownName(entry.user); + return `${label}${inOrg} · ${window.MosaicLocalTime(entry.time)}${user ? ` · by ${user}` : ''}`; + } + function paintHistory() { + const list = $('proxy-setup-history'), msg = $('proxy-setup-history-message'), all = $('proxy-setup-history-all'), older = $('proxy-setup-history-older'), retry = $('proxy-setup-history-retry'); + list.replaceChildren(...hist.entries.map((entry, i) => { + const text = historyText(entry), li = el('li', text ?? 'Withheld. The Console kept this entry back because it may hold a secret.', text ? undefined : 'muted'); + if (!text) li.dataset.withheld = ''; + li.hidden = !hist.expanded && i >= FEW; return li; + })); + const more = hist.next !== null; + all.hidden = !hist.read || (hist.entries.length <= FEW && !more); + all.textContent = hist.expanded ? 'Show fewer' : 'Show all'; all.setAttribute('aria-expanded', String(hist.expanded)); + older.hidden = !hist.expanded || !more || Boolean(hist.error); + older.disabled = hist.loading; older.textContent = hist.loading ? 'Reading…' : 'Show older'; + retry.hidden = !hist.error; + msg.className = hist.error ? 'banner err' : 'small muted'; + msg.textContent = hist.error ? `History could not be read. ${hist.error}` + : hist.loading && !hist.entries.length ? 'Reading…' + : !hist.read ? 'Not read yet.' + : hist.emptyPage && more ? 'That page of history had no entries to show. Show older reads further back.' + : !hist.entries.length && !more ? 'No setup history yet.' : ''; + } + async function readHistory(reset) { + if (!enabled || (hist.loading && !reset)) return; + if (reset) Object.assign(hist, { entries: [], next: null, expanded: false, read: false, emptyPage: false }); + const round = ++hist.round, before = hist.next, from = ['proxy-setup-history-older', 'proxy-setup-history-retry'].find(id => document.activeElement?.id === id); + Object.assign(hist, { loading: true, error: null }); paintHistory(); + try { + const value = await admin(`history?limit=25${before === null ? '' : `&before=${encodeURIComponent(before)}`}`); + const next = value?.next; + if (!value || !Array.isArray(value.entries) || !(next === null || (Number.isInteger(next) && next >= 0))) throw Object.assign(new Error('The answer could not be read.'), { code: 'outcome-unknown' }); + if (round !== hist.round || !enabled) return; + hist.entries.push(...value.entries.slice().reverse()); + Object.assign(hist, { next, read: true, emptyPage: value.entries.length === 0 }); + } catch (error) { if (round !== hist.round || !enabled) return; hist.error = failText(error, HISTORY_WORDS); } + hist.loading = false; paintHistory(); + // The button pressed keeps focus while it stays; when it goes, focus lands on Show fewer or the heading. + if (from) { const back = [$(from), $('proxy-setup-history-all')].find(b => !b.hidden); if (back) back.focus(); else { const h = $('proxy-setup-history-title'); h.tabIndex = -1; h.focus(); } } + } + $('proxy-setup-history-all').addEventListener('click', () => { hist.expanded = !hist.expanded; paintHistory(); }); + $('proxy-setup-history-older').addEventListener('click', () => { if (!hist.loading && hist.next !== null) readHistory(false); }); + $('proxy-setup-history-retry').addEventListener('click', () => readHistory(!hist.read)); + $('proxy-setup-tech').addEventListener('toggle', () => { if (techOpen() && enabled) { readKey(); readHistory(true); } }); + $('proxy-setup-tech-lines').addEventListener('toggle', () => { if ($('proxy-setup-tech-lines').open && enabled) readLog(); }); function row(dl, term, text) { const dt = document.createElement('dt'), dd = document.createElement('dd'); dt.textContent = term; dd.textContent = text; dl.append(dt, dd); } function paintState() { // #1873 settings slice 5: the timeouts init chose, from the same read. Null is not set in @@ -1034,8 +1164,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo 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.'; + paintProgress(true); + if (lines.hidden) { lines.hidden = false; lines.open = true; readLog(); } return; } lines.hidden = true; @@ -1308,11 +1438,11 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo }; $('proxy-ride-go').addEventListener('click', () => { if (!$('proxy-ride-go').disabled) rideAll(); }); function paint() { - paintState(); paintControls(); paintReceipts(); paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); paintAccountCard(); + paintState(); paintControls(); paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); paintAccountCard(); const job = state.fetch; 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'); } + else if (job.state === 'done' && job.receipt && seenFetch !== job.receipt.time) { seenFetch = job.receipt.time; addReceipt(job.receipt); say(`Fetched ${job.receipt.version}; archive, panel and executable hashes verified.`, 'success'); } clearTimeout(timer); timer = null; if (enabled && !chain?.running && (job.state === 'running' || state.busy)) timer = setTimeout(load, 1000); // The sidebar's model marks read the same status (MosaicModelDots). diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 8dbebf6b5..e91a7356d 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -119,7 +119,10 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap} .proxy-setup-next{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;margin:0 0 12px}.proxy-setup-next p{margin:0;flex:1 1 280px} .proxy-setup-buttons{display:flex;flex-wrap:wrap;gap:8px}.proxy-setup-buttons button{min-height:44px} #proxy-setup pre{overflow-x:auto;max-width:100%;font-size:12px}#proxy-setup h3{margin:16px 0 4px}#proxy-setup details{margin:0 0 12px}#proxy-setup summary{min-height:44px;display:flex;align-items:center;cursor:pointer} -#proxy-setup-receipts{padding-left:20px;overflow-wrap:anywhere;font-size:13px} +/* settings-s5b: the setup history (GET /api/proxy/admin/history), the service key and the service's lines. */ +#proxy-setup-history{padding-left:20px;overflow-wrap:anywhere;font-size:13px;margin:0 0 8px}#proxy-setup-history li{padding:2px 0} +.proxy-setup-history-foot{display:flex;flex-wrap:wrap;gap:8px;margin:0}.proxy-setup-history-foot button,[data-log] button,#proxy-setup-keymade-retry{min-height:44px} +[data-log] .setup-log{margin:8px 0}[data-log] p{margin:0 0 8px}#proxy-setup-history-message:empty{display:none} /* #1873 settings slice 1 (D3, D4): the kept restart list and Technical details. */ .proxy-setup-restart{margin:0 0 12px} .proxy-setup-restart-list{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:8px} diff --git a/packages/webui/tests/proxy-setup-browser.test.mjs b/packages/webui/tests/proxy-setup-browser.test.mjs index c021b0133..24175f113 100644 --- a/packages/webui/tests/proxy-setup-browser.test.mjs +++ b/packages/webui/tests/proxy-setup-browser.test.mjs @@ -26,9 +26,12 @@ const scenario = (status, config = {}) => ({ '/api/config': { send: true, devOwn 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]'; +// settings-s5b: Technical details reads the setup history from GET /api/proxy/admin/history, not from receipts. +const history = entries => ({ '/api/proxy/admin/history?limit=25': { entries, next: null }, '/api/proxy/admin/service-key': { madeAt: T, renewedAt: null, renewal: 'not-built', problem: null } }); +const historyItems = b => b.evaluate('[...document.querySelectorAll("#proxy-setup-history li")].map(li=>li.textContent.split(" · ")[0])'); 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' } } } }); + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(base), 'POST /api/proxy/admin/fetch': { status: 202, body: { state: 'running' } }, '/api/proxy/admin/log?lines=20': { unit: 'mosaic-proxy.service', lines: [], redacted: 0, dropped: 0 } } }); 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); @@ -46,6 +49,8 @@ test('a fresh instance shows Set up model service as one button, the not-built o 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'); + // settings-s5b: a failed step 1 opens the service's last lines, read from the log route. + await wait('document.querySelector("#proxy-setup-lines").open && /written nothing yet/.test(document.querySelector("#proxy-setup-lines [data-log]").textContent)'); assert.deepEqual(await b.evaluate('window.__unexpected'), []); }); @@ -59,7 +64,7 @@ test('without send the next-step button is disabled and nothing is posted', { ti }); test('init always sends generate; there is no pasted key, and Try again sends generate again', { timeout: 90000 }, async t => { - const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fetched), 'POST /api/proxy/admin/init': { body: { settings: { port: 18432 }, receipt: { op: 'init', time: T, port: 18432, generated: true } } } } }); + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fetched), ...history([{ op: 'init', time: T }]), 'POST /api/proxy/admin/init': { body: { settings: { port: 18432 }, receipt: { op: 'init', time: T, port: 18432, generated: true } } } } }); await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init"'); assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Continue setup'); @@ -73,7 +78,11 @@ test('init always sends generate; there is no pasted key, and Try again sends ge await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="18432";document.querySelector("#proxy-setup-go").click();})()'); await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/init")'); assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/init', body: { generate: true, port: 18432 } }]); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-receipts").textContent'), /init/); + // settings-s5b: the receipt is not shown raw; the history read under Technical details names it. + assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup").textContent'), /generated/); + await b.evaluate('document.querySelector("#proxy-setup-tech").open = true'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 1'); + assert.deepEqual(await historyItems(b), ['Set up']); // 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.port.value="";document.querySelector("#proxy-setup-go").click();})()'); @@ -82,14 +91,20 @@ test('init always sends generate; there is no pasted key, and Try again sends ge }); 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 } } } } }); + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fenced), ...history([]), 'POST /api/proxy/admin/fence/clear': { body: { cleared: true, receipt: { op: 'fence.clear', time: T, pid: 4242 } } } } }); await b.navigate(f.base + '/#/settings/model-setup'); await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fence-clear"'); + await b.evaluate('document.querySelector("#proxy-setup-tech").open = true'); + await wait('document.querySelector("#proxy-setup-history-message").textContent === "No setup history yet."'); + await b.evaluate(`window.__scenario['/api/proxy/admin/history?limit=25'] = { entries: [{ op: 'fence.clear', time: '${T}' }], next: null }`); assert.match(await b.evaluate('document.querySelector("#proxy-setup-state").textContent'), /new pid 4242/); await b.evaluate('document.querySelector("#proxy-setup-go").click()'); await wait('document.querySelector("#proxy-setup-message").textContent.includes("Fence cleared")'); assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/fence/clear', body: {} }]); - assert.match(await b.evaluate('document.querySelector("#proxy-setup-receipts").textContent'), /fence\.clear.*pid: 4242/); + // settings-s5b: with Technical details open, the write reads the history again. + await wait('document.querySelectorAll("#proxy-setup-history li").length === 1'); + assert.deepEqual(await historyItems(b), ['Key writes resumed']); + assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup").textContent'), /pid: 4242/); }); test('a stopped proxy hides the account panels with a setup note, and starting the service brings them back', { timeout: 90000 }, async t => { @@ -143,13 +158,16 @@ 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 shows its settings read-only', { timeout: 90000 }, async t => { +test('after a reload the history comes from the history read, not the status receipts, 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 } } } } }); + const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(initialized), ...history([{ op: 'fetch', time: T }, { op: 'init', time: T }]), 'POST /api/proxy/admin/unit/install': { body: { receipt: { op: 'unit.install', time: T } } } } }); 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'); + assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-history li").length'), 0, 'nothing is read before Technical details opens'); + await b.evaluate('document.querySelector("#proxy-setup-tech").open = true'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 2'); + assert.deepEqual(await historyItems(b), ['Set up', 'Release downloaded and checked'], 'newest first, from the history read'); 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.'); @@ -446,8 +464,8 @@ test('settings-s1 B4: only the next step has a button; done steps, Fence, Init l 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: release, service, history', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock'], units: 4, receipts: true }); + 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,history:!!d.querySelector("#proxy-setup-history")}})()'); + assert.deepEqual(tech, { summary: 'Technical details: release, service, history', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock', 'Service key'], units: 4, history: 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-s5b-browser.test.mjs b/packages/webui/tests/settings-s5b-browser.test.mjs new file mode 100644 index 000000000..34d309c39 --- /dev/null +++ b/packages/webui/tests/settings-s5b-browser.test.mjs @@ -0,0 +1,428 @@ +// #1873 settings-s5b (DESIGN.md 3.1, mockups models-setup-failed and models-advanced): Model setup +// shows the service's last lines (GET /api/proxy/admin/log) on step 1 when setup stopped and under +// Technical details, when the service key was made (GET /api/proxy/admin/service-key), and the setup +// history a page at a time (GET /api/proxy/admin/history). All three are the instance owner's: a page +// without proxyAdmin shows none of them and sends no /api/proxy/admin/ request. Also: a focus request +// for an organization's Models outcome line is dropped when the owner goes to any other page. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { fileURLToPath } from 'node:url'; +import { startServer } from '../src/serve.mjs'; +import { createDevOwner } from '../src/dev-owner.mjs'; +import { browser } from './browser.mjs'; +import { close } from './fixture.mjs'; + +const LIST = [ + { id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true }, + { id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: true }, +]; +const VIEW = { + business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi'], models: ['fixture-deterministic'], + providerModels: { 'fixture-deterministic': { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic' } }, + levels: { pi: ['off', 'low'] }, instances: {}, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] }, +}; + +async function orgFixture() { + const { checkRootAgents } = await import('../../organization/src/index.mjs'); + const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url)); + const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) }; + const empty = () => Promise.resolve([]); + const member = org => ({ + id: org.id, doc: { appearance: { theme: org.theme }, roles: { chief: { definition: 'chief-of-staff' } }, projects: {} }, + status: async () => ({ healthy: true, pid: 4242, boot: null }), + options: () => ({ bus: { inbox: empty, agents: empty, 'thread.claims': empty, tasks: empty, usage: () => Promise.resolve({}), limits: () => Promise.resolve({}), decisions: empty }, chat: { threads: empty, projects: empty } }), + }); + const organizations = { + list: async () => LIST, + members: async () => LIST.map(member), + resolve: async id => { + const org = LIST.find(o => o.id === id); if (!org) return null; + return { + busHealthy: true, + reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {} }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, + bus: { messages: async () => ({ messages: [], unread: 0, total: 0 }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => ({ ...VIEW, business: id }), instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) }, + chat: { projects: empty, threads: empty }, + }; + }, + }; + return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } }; +} + +const T = n => `2026-11-19T10:0${n}:00.000Z`; +const SERVICE_UP = { next: ['accounts'], init: { initialized: true, partial: false, problem: null, settings: { port: 18432, rotateGraceMinutes: 30, firstOutputSeconds: 90 }, files: [] }, + release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' }, + unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] }; +// Setup stopped: the download failed, so step 1 says so and opens the service's last lines. +const SERVICE_FAILED = { ...SERVICE_UP, next: ['fetch'], release: { fetched: false, verified: false, version: '8.0.42', panelVersion: '1.26.7' }, + init: { initialized: false, partial: false, problem: null, files: [] }, unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' }, + fetch: { state: 'failed', error: 'proxy-install-invalid' } }; +const LOG_OK = { unit: 'mosaic-proxy.service', lines: ['Nov 19 10:00:01 host proxy[4242]: listening on 127.0.0.1:18432', 'Nov 19 10:00:02 host proxy[4242]: loaded key [redacted]'], redacted: 1, dropped: 2 }; +const KEY_OK = { madeAt: T(3), renewedAt: null, renewal: 'not-built', problem: null }; +// Three pages, newest first: the first holds four entries (one withheld), the second is empty but +// names a third, and the third holds the oldest entry. +const PAGE1 = { entries: [{ op: 'unit.start', time: T(4), user: 'jason' }, { op: 'init', time: T(5), user: '[redacted]' }, { withheld: true }, + { op: 'account.proxy.apikey.add', time: T(7), org: 'acme', accountId: 'a1b2c3d4e5f6', user: 'jason' }], next: 3 }; +const PAGE2 = { entries: [], next: 1 }; +const PAGE3 = { entries: [{ op: 'ride-move', time: T(1), org: 'gamma', user: 'jason' }], next: null }; +const PAGES = { 'history?limit=25': PAGE1, 'history?limit=25&before=3': PAGE2, 'history?limit=25&before=1': PAGE3 }; +const LOG = 'log?lines=20'; +const OK = { [LOG]: LOG_OK, 'service-key': KEY_OK, ...PAGES }; + +// The instance owner's flags (or not), the setup status, and the three reads by name and query. An +// answer may be a list: each read takes the next one and the last one stays. window.__admin records +// every /api/proxy/admin/ request the page sends, window.__holds pauses a read by name. +const stub = ({ owner = true, service = SERVICE_UP, admin = OK } = {}) => `(() => { + const real = window.fetch.bind(window); + window.__s5b = ${JSON.stringify({ owner, service, admin })}; window.__admin = []; window.__writes = []; window.__holds = {}; + const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + window.fetch = async (input, init = {}) => { + const url = new URL(typeof input === 'string' ? input : input.url, location.href), path = url.pathname, method = (init.method || 'GET').toUpperCase(); + const at = path.indexOf('/proxy/admin/'); + if (at >= 0) { + const name = path.slice(at + 13) + url.search; window.__admin.push(method + ' ' + name); + if (method !== 'GET') { window.__writes.push(path); return json({ error: 'stub' }, 500); } + if (name === 'status') return json(__s5b.service); + if (window.__holds[name]) await new Promise(r => { window.__holds[name] = r; }); + let a = __s5b.admin[name]; + if (Array.isArray(a)) a = a.length > 1 ? a.shift() : a[0]; + if (!a) return json({ error: 'fixture-unexpected-api' }, 403); + return a.status ? json(a.body, a.status) : json(a); + } + if (method !== 'GET' && /\\/proxy\\//.test(path)) { window.__writes.push(path); return json({ error: 'stub' }, 500); } + if (method !== 'GET') return real(input, init); + if (/\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(path)) { const c = await (await real(input, init)).json(); return json({ ...c, orgSetup: true, proxyAdmin: __s5b.owner, proxyAdminSend: __s5b.owner, ...(/\\/orgs\\//.test(path) ? { settingsSend: true } : {}) }); } + if (path.endsWith('/proxy/plugins')) return json({ revision: 'b'.repeat(64), available: { harness: ['pi'], 'model-provider': ['fixture', 'cliproxy'] }, plugins: { harness: ['pi'], 'model-provider': ['fixture'] } }); + if (path.endsWith('/proxy/accounts')) return json({ accounts: [] }); + if (path.endsWith('/proxy/keys')) return json({ keys: [] }); + if (path.endsWith('/triage/route')) return json({ route: null }); + return real(input, init); + }; +})();`; + +async function setup(t, { path = '/#/settings/model-setup', viewport = [1440, 900], ...options } = {}) { + const { organizations, agentLevels } = await orgFixture(); + const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, triage: null, send: async () => ({}), log: () => {} }); + t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + await b.viewport(...viewport); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: stub(options) }); + await b.navigate(`http://127.0.0.1:${server.address().port}${path}`); + const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<250;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error("wait failed: "+${JSON.stringify(expression)}+" HASH "+location.hash)})()`); + const text = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`); + const click = sel => b.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) throw Error("no ${sel.replace(/"/g, '')}"); el.click(); return true; })()`); + const reads = () => b.evaluate('window.__admin.filter(r => r !== "GET status")'); + return { b, wait, text, click, reads }; +} +const READY = 'document.querySelector("#proxy-setup-state dd") && !document.querySelector("#setup-step-service").hidden'; +const openTech = b => b.evaluate('(() => { const d = document.querySelector("#proxy-setup-tech"); d.open = true; return true; })()'); +const items = b => b.evaluate('[...document.querySelectorAll("#proxy-setup-history li")].map(li => ({ text: li.textContent, hidden: li.hidden, withheld: li.hasAttribute("data-withheld") }))'); +const KEY_TEXT = /ms[kotp]-[A-Za-z0-9_-]{4,}/i; + +// ---- Each part renders from its read --------------------------------------------------------- +test('settings-s5b: Technical details shows when the service key was made, the service\'s last lines and the newest history, and reads none of them until it opens', { timeout: 90000 }, async t => { + const { b, wait, text, click, reads } = await setup(t); + await wait(READY); + await new Promise(r => setTimeout(r, 300)); + assert.deepEqual(await reads(), [], 'nothing is read before Technical details opens'); + await openTech(b); + await wait('/Mosaic made it on/.test(document.querySelector("#proxy-setup-keymade-text")?.textContent ?? "") && document.querySelectorAll("#proxy-setup-history li").length === 4'); + // The service key: when it was made, that renewal is not built, never the key. + assert.equal(await text('#proxy-setup-keymade dt'), 'Service key'); + const key = await text('#proxy-setup-keymade-text'); + assert.match(key, /^Mosaic made it on .+\. You never see it\. Renewing it is not built yet\.$/); + assert.equal(key.includes(await b.evaluate(`window.MosaicLocalTime(${JSON.stringify(T(3))})`)), true); + // History, newest first, three shown with Show all; the withheld entry is a plain row. + const list = await items(b); + assert.deepEqual(list.map(i => i.hidden), [false, false, false, true]); + assert.match(list[0].text, /^Account added in Acme Studio · .+ · by jason$/); + assert.equal(list[1].text, 'Withheld. The Console kept this entry back because it may hold a secret.'); + assert.equal(list[1].withheld, true); + assert.match(list[2].text, /^Set up · .+ · by someone whose name looked like an email address, so it is hidden$/); + assert.match(list[3].text, /^Started · .+ · by jason$/); + assert.equal(await text('#proxy-setup-history-all'), 'Show all'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), true); + // The lines: read when their box opens, shown as the answer has them, with what was removed. + assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25']); + await b.evaluate('document.querySelector("#proxy-setup-tech-lines").open = true; true'); + await wait('document.querySelector("#proxy-setup-tech-lines pre.setup-log")'); + assert.equal(await text('#proxy-setup-tech-lines summary'), 'The service\'s last lines'); + assert.equal(await text('#proxy-setup-tech-lines pre.setup-log'), LOG_OK.lines.join('\n')); + assert.equal(await text('#proxy-setup-tech-lines [data-log] p'), 'Mosaic removes anything that looks like a key. It removed something from 1 line. 2 lines were left out.'); + assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET log?lines=20']); + // Read again reads the lines once more. + await click('#proxy-setup-tech-lines [data-log] button'); + await wait('window.__admin.filter(r => r === "GET log?lines=20").length === 2 && document.querySelector("#proxy-setup-tech-lines pre.setup-log")'); +}); + +test('settings-s5b: when setup stops, step 1 opens the service\'s last lines from the log read', { timeout: 90000 }, async t => { + const { b, wait, text, reads } = await setup(t, { service: SERVICE_FAILED }); + await wait('document.querySelector("#proxy-setup-go")?.textContent === "Try again" && document.querySelector("#proxy-setup-lines pre.setup-log")'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-lines").hidden'), false); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-lines").open'), true); + assert.equal(await text('#proxy-setup-lines pre.setup-log'), LOG_OK.lines.join('\n')); + assert.match(await text('#proxy-setup-lines [data-log] p'), /^Mosaic removes anything that looks like a key\./); + assert.doesNotMatch(await text('#proxy-setup-lines'), /can't read the service's lines yet|Nothing reported/); + // The status read polls; the lines are read once, not on every paint. + await new Promise(r => setTimeout(r, 1500)); + assert.deepEqual(await reads(), ['GET log?lines=20']); +}); + +test('settings-s5b: a service key that is not made yet, or that cannot be checked, says so', { timeout: 90000 }, async t => { + const { b, wait, text } = await setup(t, { admin: { ...OK, 'service-key': [{ madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'missing' }, { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'unreadable' }] } }); + await wait(READY); await openTech(b); + await wait('/Not made yet/.test(document.querySelector("#proxy-setup-keymade-text")?.textContent ?? "")'); + assert.equal(await text('#proxy-setup-keymade-text'), 'Not made yet. Set up model service in step 1 makes it. You never see it.'); + await b.evaluate('document.querySelector("#proxy-setup-tech").open = false; true'); + await new Promise(r => setTimeout(r, 100)); + await openTech(b); + await wait('/can.t tell/.test(document.querySelector("#proxy-setup-keymade-text")?.textContent ?? "")'); + assert.match(await text('#proxy-setup-keymade-text'), /^Mosaic can't tell when it was made/); +}); + +// ---- Failed reads ----------------------------------------------------------------------------- +test('settings-s5b: each failed read shows its line with Read again, and Read again works', { timeout: 90000 }, async t => { + const fail = code => ({ status: 503, body: { error: code } }); + const { b, wait, text, click, reads } = await setup(t, { admin: { ...OK, [LOG]: [fail('outcome-unknown'), LOG_OK], 'service-key': [fail('not-configured'), KEY_OK], 'history?limit=25': [fail('outcome-unknown'), PAGE1] } }); + await wait(READY); await openTech(b); + // The service key. + await wait('document.querySelector("#proxy-setup-keymade-retry")'); + assert.equal(await text('#proxy-setup-keymade-text'), 'When it was made could not be read. Model service setup is not available on this Console. (not-configured)'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-keymade-text").classList.contains("err-line")'), true); + await b.evaluate('document.querySelector("#proxy-setup-keymade-retry").focus(); document.querySelector("#proxy-setup-keymade-retry").click(); true'); + await wait('/Mosaic made it on/.test(document.querySelector("#proxy-setup-keymade-text")?.textContent ?? "")'); + assert.equal(await b.evaluate('!!document.querySelector("#proxy-setup-keymade-retry")'), false); + assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-keymade-text', 'focus stays on the answer, not the page'); + // History. + await wait('!document.querySelector("#proxy-setup-history-retry").hidden'); + assert.equal(await text('#proxy-setup-history-message'), 'History could not be read. The host could not read the history. (outcome-unknown)'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-message").className'), 'banner err'); + assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-history li").length'), 0); + await click('#proxy-setup-history-retry'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 4'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-retry").hidden'), true); + assert.equal(await text('#proxy-setup-history-message'), ''); + // The lines. + await b.evaluate('document.querySelector("#proxy-setup-tech-lines").open = true; true'); + await wait('document.querySelector("#proxy-setup-tech-lines [data-log] .banner.err")'); + assert.equal(await text('#proxy-setup-tech-lines [data-log] .banner.err'), 'The service\'s lines could not be read. The host could not read the service\'s lines. (outcome-unknown)'); + assert.equal(await b.evaluate('!!document.querySelector("#proxy-setup-tech-lines pre")'), false); + await b.evaluate('(() => { const r = document.querySelector("#proxy-setup-tech-lines [data-log] button"); r.focus(); r.click(); return true; })()'); + await wait('document.querySelector("#proxy-setup-tech-lines pre.setup-log")'); + assert.equal(await b.evaluate('document.activeElement?.closest("[data-log]") !== null && document.activeElement.textContent === "Read again"'), true); + assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET service-key', 'GET history?limit=25', 'GET log?lines=20', 'GET log?lines=20']); +}); + +// ---- Owner only ------------------------------------------------------------------------------- +test('settings-s5b: a page that is not the instance owner\'s shows none of the three and sends no /api/proxy/admin/ request', { timeout: 90000 }, async t => { + // The owner's page, as the control: the three parts are there and read. + { + const { b, wait } = await setup(t, { service: SERVICE_FAILED }); + await wait('document.querySelector("#proxy-setup-lines pre.setup-log")'); + await openTech(b); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 4 && /Mosaic made it/.test(document.querySelector("#proxy-setup-keymade-text").textContent)'); + } + const { b, wait } = await setup(t, { owner: false, service: SERVICE_FAILED }); + await wait('window.MosaicProxy && document.querySelector("#proxy-setup") && document.querySelector("#settings-page-title")'); + await new Promise(r => setTimeout(r, 800)); + // Opening every box on the page, even the hidden ones, still reads nothing. + await b.evaluate('document.querySelectorAll("#proxy-setup details").forEach(d => { d.open = true; }); true'); + await new Promise(r => setTimeout(r, 800)); + assert.deepEqual(await b.evaluate('window.__admin'), []); + const shown = sel => b.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(sel)}); return !!e && e.getClientRects().length > 0; })()`); + for (const sel of ['#proxy-setup-keymade', '#proxy-setup-keymade-text', '#proxy-setup-tech-lines', '#proxy-setup-lines', '#proxy-setup-history', '#proxy-setup-history-message', '#proxy-setup-history-all']) + assert.equal(await shown(sel), false, `${sel} is not shown`); + assert.equal(await b.evaluate('document.querySelectorAll("[data-log] pre, [data-log] .banner, #proxy-setup-history li").length'), 0); +}); + +// ---- History paging --------------------------------------------------------------------------- +test('settings-s5b: history pages back one page at a time, shows each entry once, and an empty page with an older one still offers it', { timeout: 90000 }, async t => { + const { b, wait, text, click, reads } = await setup(t); + await wait(READY); await openTech(b); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 4'); + await click('#proxy-setup-history-all'); + assert.deepEqual((await items(b)).map(i => i.hidden), [false, false, false, false]); + assert.equal(await text('#proxy-setup-history-all'), 'Show fewer'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-all").getAttribute("aria-expanded")'), 'true'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), false); + // Two quick presses send one read. + await b.evaluate('window.__holds["history?limit=25&before=3"] = true; true'); + await b.evaluate('(() => { const o = document.querySelector("#proxy-setup-history-older"); o.focus(); o.click(); o.click(); return true; })()'); + await wait('typeof window.__holds["history?limit=25&before=3"] === "function"'); + assert.equal(await text('#proxy-setup-history-older'), 'Reading…'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").disabled'), true); + await b.evaluate('window.__holds["history?limit=25&before=3"](); true'); + // The empty page: no new entry, a line that says so, and Show older still there. + await wait('/no entries to show/.test(document.querySelector("#proxy-setup-history-message").textContent)'); + assert.equal(await text('#proxy-setup-history-message'), 'That page of history had no entries to show. Show older reads further back.'); + assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-history li").length'), 4); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), false); + assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-history-older'); + await click('#proxy-setup-history-older'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 5'); + const list = await items(b); + assert.match(list[4].text, /^Gamma Home switched to your models · .+ · by jason$/); + assert.equal(new Set(list.map(i => i.text)).size, list.length, 'each entry once'); + // The last page: no Show older, focus goes to Show fewer, no empty-page line. + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), true); + assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-history-all'); + assert.equal(await text('#proxy-setup-history-message'), ''); + assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET history?limit=25&before=3', 'GET history?limit=25&before=1']); + // Closing and opening Technical details starts from the newest page again. + await b.evaluate('document.querySelector("#proxy-setup-tech").open = false; true'); + await new Promise(r => setTimeout(r, 100)); + await openTech(b); + await wait('window.__admin.filter(r => r === "GET history?limit=25").length === 2 && document.querySelectorAll("#proxy-setup-history li").length === 4'); + assert.equal(await text('#proxy-setup-history-all'), 'Show all'); +}); + +test('settings-s5b: a history with no entries says so, and a first page that is empty but names an older one offers it', { timeout: 90000 }, async t => { + const { b, wait, text, click } = await setup(t, { admin: { ...OK, 'history?limit=25': [{ entries: [], next: null }, { entries: [], next: 1 }] } }); + await wait(READY); await openTech(b); + await wait('document.querySelector("#proxy-setup-history-message").textContent === "No setup history yet."'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-all").hidden'), true); + await b.evaluate('document.querySelector("#proxy-setup-tech").open = false; true'); + await new Promise(r => setTimeout(r, 100)); + await openTech(b); + await wait('/no entries to show/.test(document.querySelector("#proxy-setup-history-message").textContent)'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-all").hidden'), false); + await click('#proxy-setup-history-all'); + assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), false); + await click('#proxy-setup-history-older'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 1'); + assert.match((await items(b))[0].text, /^Gamma Home switched to your models/); + assert.equal(await text('#proxy-setup-history-message'), ''); +}); + +test('settings-s5b: a withheld entry shows as withheld and nothing else from it', { timeout: 90000 }, async t => { + const { b, wait } = await setup(t, { admin: { ...OK, 'history?limit=25': { entries: [{ withheld: true, op: 'init', time: T(2), user: 'jason', org: 'acme' }, { withheld: true }], next: null } } }); + await wait(READY); await openTech(b); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 2'); + for (const item of await items(b)) { + assert.equal(item.text, 'Withheld. The Console kept this entry back because it may hold a secret.'); + assert.equal(item.withheld, true); + } + assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup-history li")].every(li => li.classList.contains("muted"))'), true); +}); + +// ---- No key text ------------------------------------------------------------------------------ +test('settings-s5b: key-shaped text in an unexpected field of any answer never reaches the page', { timeout: 90000 }, async t => { + const k = p => `${p}-AAAAbbbbCCCCdddd0123456789`; + const admin = { + [LOG]: { unit: k('msk'), lines: ['plain line'], redacted: 0, dropped: 0, key: k('mso'), note: k('mst') }, + 'service-key': { madeAt: k('msk'), renewedAt: k('mso'), renewal: k('mst'), problem: k('msp'), key: k('msk') }, + 'history?limit=25': { entries: [ + { op: k('msk'), time: k('mso'), user: k('mst'), org: k('msp'), provider: k('msk'), accountId: k('mso'), models: k('mst'), priority: k('msp'), note: k('msk') }, + { op: 'account.proxy.apikey.add', time: T(2), user: `x${k('msk')}`, org: k('mso'), provider: k('mst') }, + { op: 'ride-move', time: T(3), org: `${k('msp')}`, user: 'jason' }, + { withheld: true, note: k('msk') }, + ], next: null }, + }; + { + const { b, wait } = await setup(t, { admin }); + await wait(READY); await openTech(b); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 4 && !/Reading/.test(document.querySelector("#proxy-setup-keymade-text").textContent)'); + await b.evaluate('document.querySelector("#proxy-setup-history-all").click(); document.querySelector("#proxy-setup-tech-lines").open = true; true'); + await wait('document.querySelector("#proxy-setup-tech-lines pre.setup-log")'); + const page = await b.evaluate('document.querySelector("#proxy-setup").textContent + "\\n" + document.body.innerText'); + assert.doesNotMatch(page, KEY_TEXT); + const list = await items(b); + assert.match(list[3].text, /^Other setup action · unknown$/); + assert.match(list[2].text, /^Account added · /); + assert.match(list[1].text, /^An organization switched to your models · /); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-keymade-text").textContent'), /^When it was made is not known\./); + } + // A refusal whose code is shaped like a key. + const refused = { status: 400, body: { error: 'msk-abcdefghijklmnop' } }; + const { b, wait } = await setup(t, { admin: { [LOG]: refused, 'service-key': refused, 'history?limit=25': refused } }); + await wait(READY); await openTech(b); + await b.evaluate('document.querySelector("#proxy-setup-tech-lines").open = true; true'); + await wait('document.querySelector("#proxy-setup-keymade-retry") && !document.querySelector("#proxy-setup-history-retry").hidden && document.querySelector("#proxy-setup-tech-lines .banner.err")'); + const page = await b.evaluate('document.querySelector("#proxy-setup").textContent + "\\n" + document.body.innerText'); + assert.doesNotMatch(page, KEY_TEXT); + assert.match(await b.evaluate('document.querySelector("#proxy-setup-history-message").textContent'), /^History could not be read\. The Console refused the read\.$/); +}); + +// ---- Models focus follow-up ------------------------------------------------------------------- +// The settings-s5 re-check left one window: a switch whose follow-up read is still out when the owner +// goes to a page that returns before render's focus chain (Assistant, Projects, the board) kept its focus request. +for (const [name, away] of [['Assistant', '#/assistant'], ['the board', '#/board']]) +test(`settings-s5b: leaving Models for ${name} while a switch's follow-up read is out, the next visit does not focus the outcome line`, { timeout: 90000 }, async t => { + const { b, wait, click } = await setup(t, { path: '/#/settings/routing?org=acme' }); + await wait('document.querySelector("#models-in-force")?.textContent.includes("does not use")'); + // plugins.set succeeds; the routes read that the render after it awaits waits until released. + await b.evaluate(`(() => { const f = window.fetch; window.__sets = 0; + window.fetch = async (input, init = {}) => { const u = new URL(String(input?.url ?? input), location.href).pathname, m = (init.method || 'GET').toUpperCase(); + if (m !== 'GET' && u.endsWith('/proxy/plugins/set')) { window.__sets++; return new Response(JSON.stringify({ revision: 'c'.repeat(64) }), { status: 200, headers: { 'content-type': 'application/json' } }); } + if (m === 'GET' && u.endsWith('/proxy/plugins') && window.__sets) return new Response(JSON.stringify({ revision: 'c'.repeat(64), available: { harness: ['pi'], 'model-provider': ['fixture', 'cliproxy'] }, plugins: { harness: ['pi'], 'model-provider': ['fixture', 'cliproxy'] } }), { status: 200, headers: { 'content-type': 'application/json' } }); + if (m === 'GET' && u.endsWith('/routes') && window.__sets && !window.__released) { await new Promise(r => { window.__release = r; }); window.__released = true; } + return f(input, init); }; return true; })()`); + await click('#models-yours'); + await wait('typeof window.__release === "function"'); + await b.evaluate(`location.hash = ${JSON.stringify(away)}; true`); + await wait('!location.hash.startsWith("#/settings/") && !document.querySelector("#models-in-force")'); + await new Promise(r => setTimeout(r, 300)); + await b.evaluate('window.__release(); true'); + await new Promise(r => setTimeout(r, 400)); + await b.evaluate(`location.hash = '#/settings/routing?org=acme'; true`); + await wait('/^Saved\\./.test(document.querySelector("#models-receipt")?.textContent ?? "") && document.querySelector("#models-in-force")?.textContent.includes("uses your models")'); + await new Promise(r => setTimeout(r, 300)); + assert.notEqual(await b.evaluate('document.activeElement?.id'), 'models-receipt'); +}); + +// ---- Shots ------------------------------------------------------------------------------------ +test('shots', { timeout: 900000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => { + const { mkdir, writeFile } = await import('node:fs/promises'); + const { join } = await import('node:path'); + const dir = process.env.MOSAIC_UX_SHOTS; await mkdir(dir, { recursive: true }); + const settle = () => new Promise(r => setTimeout(r, 1000)); + const fail = { status: 503, body: { error: 'outcome-unknown' } }; + const SHOTS = [ + { name: 'setup-failed-lines', options: { service: SERVICE_FAILED }, ready: 'document.querySelector("#proxy-setup-lines pre.setup-log")' }, + { name: 'technical-details', ready: READY, + after: async (b, wait) => { await b.evaluate('document.querySelector("#proxy-setup-tech").open = true; true'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 4 && /Mosaic made it/.test(document.querySelector("#proxy-setup-keymade-text").textContent)'); } }, + { name: 'technical-details-all', ready: READY, + after: async (b, wait) => { await b.evaluate('document.querySelector("#proxy-setup-tech").open = true; true'); + await wait('document.querySelectorAll("#proxy-setup-history li").length === 4'); + await b.evaluate('document.querySelector("#proxy-setup-history-all").click(); document.querySelector("#proxy-setup-tech-lines").open = true; true'); + await wait('document.querySelector("#proxy-setup-tech-lines pre.setup-log")'); } }, + { name: 'technical-details-failed', options: { admin: { [LOG]: fail, 'service-key': fail, 'history?limit=25': fail } }, ready: READY, + after: async (b, wait) => { await b.evaluate('document.querySelector("#proxy-setup-tech").open = true; document.querySelector("#proxy-setup-tech-lines").open = true; true'); + await wait('document.querySelector("#proxy-setup-keymade-retry") && !document.querySelector("#proxy-setup-history-retry").hidden && document.querySelector("#proxy-setup-tech-lines .banner.err")'); } }, + ]; + const report = []; + for (const shot of SHOTS) for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) { + const { b, wait } = await setup(t, { ...(shot.options ?? {}), viewport: [width, width === 390 ? 844 : 900] }); + await b.call('Emulation.setScrollbarsHidden', { hidden: true }); + await b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] }); + await wait(`(${shot.ready}) && !!window.MosaicAppearance`); + await b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`); + if (shot.after) await shot.after(b, wait); + await settle(); + const sideways = await b.evaluate('document.documentElement.scrollWidth > document.documentElement.clientWidth'); + const noRing = [], seen = new Set(); + for (let i = 0; i < 160; i++) { + await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }); + await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 }); + const r = await b.evaluate(`(() => { const e = document.activeElement; if (!e || e === document.body) return null; const cs = getComputedStyle(e); + const ring = (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none'); + return { key: e.id || e.getAttribute('href') || e.tagName + ':' + (e.textContent || '').trim().slice(0, 30), ring }; })()`); + if (!r || seen.has(r.key)) break; seen.add(r.key); + if (!r.ring) noRing.push(r.key); + } + await b.evaluate('document.activeElement?.blur(); window.scrollTo(0, 0); true'); await settle(); + const file = `${shot.name}-${width}-${scheme}.png`; + let metrics = await b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize; + await b.viewport(width, Math.ceil(size.height)); await settle(); + metrics = await b.call('Page.getLayoutMetrics'); size = metrics.cssContentSize || metrics.contentSize; + const { data } = await b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height), scale: 1 } }); + await writeFile(join(dir, file), Buffer.from(data, 'base64')); + report.push({ page: shot.name, width, scheme, shot: file, sideways, noRing }); + await b.close(); + } + await writeFile(join(dir, 'measure.json'), JSON.stringify(report, null, 1)); + for (const r of report) { + assert.equal(r.sideways, false, `${r.shot} scrolls sideways`); + assert.deepEqual(r.noRing, [], `${r.shot}: controls with no visible focus ring`); + } +}); -- 2.54.0 From d03ae494e802706afd259ff7c5f11ba0177b32ee Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 22:59:03 -0600 Subject: [PATCH 2/4] fix(webui): settings-s5b: in Technical details the service key and the history sit right after Release and Service, as models-advanced shows them, with the service's last lines after the history; history entries are not numbered (#1873, lane settings-s5b) --- packages/webui/src/public/display.js | 16 +++++++++------- packages/webui/src/public/shell.css | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index fa2397a44..dcb762341 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -638,18 +638,20 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo + '
    '; const tech = '
    Technical details: release, service, history
    ' + '' + + '
    ' + '
    '; const markup = '
    ' + card('service', 1, 'Model service', service, true) diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index e91a7356d..60873e229 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -120,7 +120,7 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap} .proxy-setup-buttons{display:flex;flex-wrap:wrap;gap:8px}.proxy-setup-buttons button{min-height:44px} #proxy-setup pre{overflow-x:auto;max-width:100%;font-size:12px}#proxy-setup h3{margin:16px 0 4px}#proxy-setup details{margin:0 0 12px}#proxy-setup summary{min-height:44px;display:flex;align-items:center;cursor:pointer} /* settings-s5b: the setup history (GET /api/proxy/admin/history), the service key and the service's lines. */ -#proxy-setup-history{padding-left:20px;overflow-wrap:anywhere;font-size:13px;margin:0 0 8px}#proxy-setup-history li{padding:2px 0} +#proxy-setup-history{list-style:none;padding-left:0;overflow-wrap:anywhere;font-size:13px;margin:0 0 8px}#proxy-setup-history li{padding:2px 0} .proxy-setup-history-foot{display:flex;flex-wrap:wrap;gap:8px;margin:0}.proxy-setup-history-foot button,[data-log] button,#proxy-setup-keymade-retry{min-height:44px} [data-log] .setup-log{margin:8px 0}[data-log] p{margin:0 0 8px}#proxy-setup-history-message:empty{display:none} /* #1873 settings slice 1 (D3, D4): the kept restart list and Technical details. */ -- 2.54.0 From 3b17326b7453aeb0986e7cb94020e4add33549e7 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 23:17:08 -0600 Subject: [PATCH 3/4] fix(webui): settings-s5b review: Show older shows whenever there is an older page and nothing read is folded away, and what it reads stays open; Show all only when entries are folded (P2-1); an older page not further back than the one asked for is outcome unknown (P3-1); when the pressed history button goes, focus lands on Read again, Show older, Show fewer, then the heading (P3-2); a service that is not installed has no lines, said plainly, not as a failed read (P3-3); an unknown history action reads Other setup action, even one named like an object property (P3-4); a hidden user reads "someone whose name Mosaic hid" (P3-5); a test holds a stale history answer (P3-6); the service key is the last row of the state list and fails in the same banner style with Read again (P3-7); the setup-stops test now refuses a real unit start; tests red on d03ae494e (#1873, lane settings-s5b) --- packages/webui/src/public/display.js | 55 +++++---- .../webui/tests/settings-s5b-browser.test.mjs | 104 +++++++++++++++--- 2 files changed, 127 insertions(+), 32 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index dcb762341..c33e0a817 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -638,9 +638,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo + '
    '; const tech = '
    Technical details: release, service, history
    ' + '