Compare commits

...
5 Commits
6 changed files with 154 additions and 36 deletions

No files matched your search

@@ -240,8 +240,8 @@ export async function lifecycleFixture(t) {
}
async function consoleBrowser(t, f) {
const b = await browser(); t.after(() => b.close());
b.on('Fetch.requestPaused', ({ requestId, request: incoming }) => {
let b = await browser(); const consolePage = b; t.after(() => consolePage.close());
consolePage.on('Fetch.requestPaused', ({ requestId, request: incoming }) => {
const url = new URL(incoming.url);
if (incoming.method === 'POST') f.recordOwner(url.pathname);
const req = httpRequest({ host: '127.0.0.1', port: f.port, path: url.pathname + url.search, method: incoming.method,
@@ -249,9 +249,9 @@ async function consoleBrowser(t, f) {
const parts = []; res.on('data', part => parts.push(part)); res.on('end', () => {
const responseHeaders = Object.entries(res.headers).filter(([name]) => !['connection','keep-alive','transfer-encoding'].includes(name))
.flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map(value => ({ name, value: String(value) })));
b.call('Fetch.fulfillRequest', { requestId, responseCode: res.statusCode, responseHeaders, body: Buffer.concat(parts).toString('base64') }).catch(() => {});
consolePage.call('Fetch.fulfillRequest', { requestId, responseCode: res.statusCode, responseHeaders, body: Buffer.concat(parts).toString('base64') }).catch(() => {});
});
}); req.on('error', () => b.call('Fetch.failRequest', { requestId, errorReason: 'Failed' }).catch(() => {})); req.end(incoming.postData);
}); req.on('error', () => consolePage.call('Fetch.failRequest', { requestId, errorReason: 'Failed' }).catch(() => {})); req.end(incoming.postData);
});
await b.call('Fetch.enable', { patterns: [{ urlPattern: ORIGIN + '/*', requestStage: 'Request' }] });
const s = await f.current(); await b.navigate(`${ORIGIN}/#/inbox/${s.selection.decision}`);
@@ -267,7 +267,10 @@ async function consoleBrowser(t, f) {
await wait('document.querySelector("#decide-status")?.textContent.startsWith("Recorded")');
},
async offline(html) {
await b.call('Fetch.disable');
// The Console can still poll during navigation. Close it before observing the downloaded file.
await b.close();
b = await browser(); const offlinePage = b; t.after(() => offlinePage.close());
external.length = 0;
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.__now=1000;Date.now=()=>window.__now;window.__ticks=[];window.setInterval=fn=>{window.__ticks.push(fn);return window.__ticks.length;};window.__sounds=0;window.AudioContext=class{currentTime=0;destination={};resume(){}createOscillator(){return{connect(){},frequency:{value:0},start(){window.__sounds++},stop(){}}}createGain(){return{connect(){},gain:{value:0}}}};` });
await b.call('Network.enable'); await b.call('Network.emulateNetworkConditions', { offline: true, latency: 0, downloadThroughput: 0, uploadThroughput: 0 });
b.on('Network.requestWillBeSent', ({ request }) => { if (/^https?:/.test(request.url)) external.push(request.url); });
+27 -11
View File
@@ -597,6 +597,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<details id="proxy-setup-lines" class="proxy-setup-lines" hidden><summary>The service\'s last lines</summary><div class="inside" data-log></div></details>'
+ '<div id="proxy-setup-fixtures" class="banner mk-note" hidden></div>';
const accounts = '<p id="proxy-message" role="status" aria-live="polite">Reading accounts…</p>'
+ '<p class="small muted">Model setup has not checked whether a model answers.</p>'
+ '<p id="proxy-readonly" class="muted" hidden>This Console is read-only. Sign-in and account changes are unavailable.</p>'
+ '<div data-accounts-part><ul id="proxy-accounts" class="rows" aria-label="Accounts"></ul>'
// #1873 account-remove: the instance owner removes an account here; anyone else is told where.
@@ -610,8 +611,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<div class="form-foot"><button type="submit" id="proxy-login-go" hidden>Sign in</button></div></fieldset></form>'
+ '<form id="proxy-apikey" class="settings-form" hidden><fieldset data-write disabled><div class="field"><label for="proxy-apikey-key" id="proxy-apikey-label">API key</label>'
+ '<input id="proxy-apikey-key" name="key" type="password" autocomplete="off" spellcheck="false" maxlength="4096" required>'
+ '<p class="help small muted">Mosaic checks it with <span id="proxy-apikey-provider">the provider</span>, keeps it in your model service, and never shows it again.</p></div>'
+ '<div class="form-foot"><button type="submit">Check and add</button><button type="button" id="proxy-apikey-cancel">Cancel</button></div></fieldset><p id="proxy-apikey-message" role="status"></p></form>'
+ '<p class="help small muted">Mosaic saves the key for <span id="proxy-apikey-provider">the provider</span> in your model service and never shows it again. Saving does not check whether a model answers.</p></div>'
+ '<div class="form-foot"><button type="submit">Save account</button><button type="button" id="proxy-apikey-cancel">Cancel</button></div></fieldset><p id="proxy-apikey-message" role="status"></p></form>'
+ '</div></details>'
+ '<div id="proxy-signin" hidden><ol id="proxy-signin-progress" class="progress" aria-label="Sign-in progress"></ol>'
+ '<p class="form-foot"><a id="proxy-authorize" target="_blank" rel="noopener noreferrer" hidden>Open the sign-in tab again</a><button type="button" id="proxy-login-cancel" disabled>Cancel sign-in</button></p>'
@@ -671,9 +672,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
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'];
// Account metadata does not prove that a model answered.
const HEALTH = { ready: ['badge-muted', 'Saved'], active: ['badge-muted', 'Saved'], error: ['badge-danger', 'Error'], unavailable: ['badge-danger', 'Not available'], disabled: ['badge-muted', 'Disabled'] };
const health = account => ['error', 'unavailable'].includes(account.status) && account.reason?.startsWith('The account needs to sign in again.')
? ['badge-danger', 'Sign-in needed'] : HEALTH[account.status] ?? ['badge-muted', 'Unknown'];
function mount() {
const $ = id => document.getElementById(id);
const root = $('proxy-setup');
@@ -739,6 +741,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
function paintAccountCard() {
const addBox = $('proxy-add-box');
addBox.hidden = !canWrite || Boolean(login);
$('proxy-accounts').querySelectorAll('[data-account-fix]').forEach(button => { button.disabled = 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';
@@ -746,10 +749,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
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));
const bad = accountList.filter(a => ['error', 'unavailable', 'disabled'].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(' · '));
else if (bad.length) setCard('accounts', 'bad', `${bad.map(a => `${providerLabel(a.provider)}: ${health(a)[1].toLowerCase()}`).join(' · ')}. Check the account rows below.`);
else setCard('accounts', 'done', accountList.map(a => `${providerLabel(a.provider)} ${health(a)[1].toLowerCase()}`).join(' · '));
focusStep();
}
// #1873 account-remove (Jason 2026-11-20): the owner's Remove asks in place and names what moves,
@@ -843,7 +846,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
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}`);
const [cls, word] = health(account), badge = el('span', word, `badge ${cls}`);
li.dataset.account = account.accountId; li.append(name, kind, badge);
if (proxyAdmin && canWrite) {
const remove = el('button', 'Remove'); remove.type = 'button'; remove.dataset.remove = account.accountId;
@@ -853,6 +856,19 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
}
// The accounts read says why an account is not working (account.reason, a7362a8fc and later). Absent, nothing shows.
if (typeof account.reason === 'string' && account.reason) li.append(el('p', account.reason, 'small muted account-reason'));
if (['error', 'unavailable', 'disabled'].includes(account.status)) {
if (canWrite && [...providerSelect.options].some(option => option.value === account.provider)) {
const fix = el('button', 'Add account'); fix.type = 'button'; fix.dataset.accountFix = '';
fix.disabled = Boolean(login);
fix.setAttribute('aria-label', `Add account for ${account.displayName}`);
fix.addEventListener('click', () => {
const add = $('proxy-add-box'); add.open = true;
providerSelect.value = account.provider;
paintProvider(); (keyed(providerSelect.value) ? $('proxy-apikey-key') : $('proxy-login-go')).focus();
});
li.append(fix);
} else li.append(el('p', canWrite ? 'This provider is not available here. Ask the owner to check Model setup.' : 'Ask the owner to add an account in Model setup.', 'small muted'));
}
if (removeAsk?.accountId === account.accountId && proxyAdmin && canWrite) li.append(removeBox(account));
return li;
}));
@@ -1367,7 +1383,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
const PROGRESS = [['fetch', { ok: 'Downloaded and checked', run: 'Downloading and checking…', todo: 'Download and check', bad: 'Download and check: did not finish' }],
['init', { ok: 'Configured', run: 'Configuring…', todo: 'Configure', bad: 'Configure: did not finish' }],
['start', { ok: 'Started the service', run: 'Starting the service…', todo: 'Start the service', bad: 'Start the service: did not finish' }],
['answer', { ok: 'Answers on this machine', run: 'Checking it answers…', todo: 'Check it answers', bad: 'Check it answers: no answer yet' }]];
['answer', { ok: 'Service reachable on this machine', run: 'Checking the service…', todo: 'Check the service', bad: 'Service not reachable yet' }]];
const stageOf = step => step === 'fetch' || step === 'init' ? step : step === 'unit-install' || step === 'unit-start' ? 'start' : 'answer';
// Each line is done only when the status read says so.
function progressDone() {
@@ -1400,7 +1416,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
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 (next === 'accounts') { setCard('service', 'done', state.unit.port ? `Running. Service reachable on this machine, port ${state.unit.port}.` : 'Running. Service reachable 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;
+3 -3
View File
@@ -69,12 +69,12 @@ export async function browser({ machine = true, args = [] } = {}) {
}
const { targetId } = await send('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true });
const call = (method, params) => send(method, params, sessionId);
const call = (method, params, ms) => send(method, params, sessionId, ms);
await call('Page.enable');
await call('Runtime.enable');
if (machine) await call('Page.addScriptToEvaluateOnNewDocument', { source: `try { localStorage.setItem('mosaic-console-board', '{"machine":true}'); } catch {}` });
const evaluate = async expression => {
const r = await call('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
const evaluate = async (expression, ms) => {
const r = await call('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, ms);
if (r.exceptionDetails) throw new Error(r.exceptionDetails.text + ': ' + r.result.description);
return r.result.value;
};
@@ -35,4 +35,7 @@ test('signed-in Console buttons deliver the approved original request and downlo
assert.equal(await page.clock(), '25:00');
await page.advance(10000); assert.equal(await page.clock(), '25:00');
assert.deepEqual(await page.externalRequests(), []);
// A remote resource in the downloaded file must still be observed while the browser is offline.
await page.offline('<!doctype html><img src="https://external.invalid/tracker">');
assert.deepEqual(await page.externalRequests(), ['https://external.invalid/tracker']);
});
@@ -261,6 +261,69 @@ const installed = { ...configured, unit: { ...configured.unit, installed: true }
const running = { ...installed, unit: { ...installed.unit, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] };
const config = { send: true, devOwner: true, proxyAdmin: true, proxyAdminSend: true };
const accounts = list => ({ 'GET /api/proxy/accounts': { body: { accounts: list } }, 'GET /api/proxy/keys': { body: { keys: [] } } });
test('setup states describe saved accounts and offer a repair without claiming a model answered', { timeout: 90000 }, async t => {
const list = [
{ accountId: 'a1', provider: 'claude', displayName: 'Claude', status: 'ready', priority: 0 },
{ accountId: 'a2', provider: 'z.ai', displayName: 'Key', status: 'active', priority: 0 },
{ accountId: 'a3', provider: 'codex', displayName: 'Sign in', status: 'error', priority: 0, reason: 'The account needs to sign in again. Sign in again, or add another account.' },
{ accountId: 'a4', provider: 'claude', displayName: 'Unavailable', status: 'unavailable', priority: 0 },
{ accountId: 'a5', provider: 'z.ai', displayName: 'Disabled', status: 'disabled', priority: 0 },
];
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null } } });
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 5');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li[data-account] .badge")].map(e=>e.textContent)'), ['Saved', 'Saved', 'Sign-in needed', 'Not available', 'Disabled']);
assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts").dataset.state'), 'bad');
assert.match(await b.evaluate('document.querySelector("#setup-step-accounts").textContent'), /Model setup has not checked whether a model answers/);
assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /Service reachable/);
assert.match(await b.evaluate('document.querySelector("#proxy-apikey .help").textContent'), /does not check whether a model answers/i);
assert.equal(await b.evaluate('document.querySelector("#proxy-apikey button[type=submit]").textContent'), 'Save account');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li[data-account]")].map(row=>row.querySelectorAll("[data-account-fix]").length)'), [0, 0, 1, 1, 1]);
await b.evaluate('document.querySelector("[data-account=a3] [data-account-fix]").click(); true');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-add-box").open, document.querySelector("#proxy-provider").value, document.activeElement.id]'), [true, 'codex', 'proxy-login-go']);
await b.evaluate('document.querySelector("[data-account=a5] [data-account-fix]").click(); true');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-provider").value, document.activeElement.id]'), ['z.ai', 'proxy-apikey-key']);
assert.deepEqual(await b.evaluate('window.__writes'), []);
});
test('bad account repair respects provider availability and active sign-in', { timeout: 90000 }, async t => {
const list = ['codex', 'z.ai', 'other', 'missing'].map((provider, i) => ({ accountId: `a${i}`, provider, displayName: `Account ${i}`, status: 'error', priority: 0 }));
for (const width of [1440, 390]) {
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null },
'POST /api/proxy/login/start': { body: { url: 'https://claude.ai/oauth/authorize?state=s4', state: 's4' } }, 'POST /api/proxy/login/status': { body: { status: 'wait' } }, 'POST /api/proxy/login/cancel': { body: { status: 'cancelled' } } } });
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.open = () => null;' });
await b.viewport(width, width === 390 ? 844 : 900);
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4');
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-account=a2], [data-account=a3]")].every(row => !row.querySelector("[data-account-fix]") && row.textContent.includes("provider is not available"))'), true);
const ax = await b.call('Accessibility.getFullAXTree');
assert.ok(ax.nodes.some(n => n.role?.value === 'button' && n.name?.value === 'Add account for Account 0'));
await b.evaluate('document.querySelector("[data-account=a0] [data-account-fix]").click(); document.querySelector("#proxy-login-start").requestSubmit(); true');
await wait('!document.querySelector("#proxy-signin").hidden');
assert.equal(await b.evaluate('document.querySelector("[data-account=a1] [data-account-fix]").disabled'), true);
await b.evaluate('document.querySelector("#proxy-login-cancel").click(); true');
await wait('document.querySelector("#proxy-signin").hidden');
await b.evaluate('document.querySelector("[data-account=a1] [data-account-fix]").focus(); true');
await b.key('Enter');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-provider").value, document.activeElement.id, document.activeElement.checkVisibility()]'), ['z.ai', 'proxy-apikey-key', true]);
assert.deepEqual(await b.evaluate('window.__writes.map(w => w.path)'), ['/api/proxy/login/start', '/api/proxy/login/cancel']);
await b.close();
}
});
test('bad account without a provider or write access gives guidance without a repair shortcut', { timeout: 90000 }, async t => {
const list = [{ accountId: 'a1', provider: 'codex', displayName: 'Account', status: 'error', priority: 0 }];
for (const [owner, providers] of [[true, []], [false, publicProviders()]]) {
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': { send: owner, devOwner: true, proxyAdmin: owner, proxyAdminSend: owner }, '/api/proxy/admin/status': { ...running, providers }, 'GET /api/proxy/accounts': { body: { accounts: list, providers } }, '/api/triage/route': { route: null } } });
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
await wait('document.querySelector("#proxy-accounts li[data-account]")');
assert.equal(await b.evaluate('document.querySelector("[data-account-fix]")'), null);
assert.match(await b.evaluate('document.querySelector("#proxy-accounts li").innerText'), owner ? /provider is not available/ : /Ask the owner to add an account in Model setup/);
assert.deepEqual(await b.evaluate('window.__writes'), []);
await b.close();
}
});
const admin = b => b.evaluate('window.__writes.filter(w => w.path.startsWith("/api/proxy/admin/")).map(w => w.path.slice(17))');
// A primary button is one drawn with the accent fill, whatever its class: a submit is drawn that way too.
const primaries = b => b.evaluate(`(() => { const host = document.querySelector(".model-setup"), probe = document.createElement("button"); probe.className = "btn primary"; host.append(probe);
@@ -290,7 +353,7 @@ test('settings-s4: one press runs fetch, init, install and start in that order,
await wait('document.querySelector("#setup-step-service").dataset.state === "done"');
assert.deepEqual(await admin(b), ['fetch', 'init', 'unit/install', 'unit/start']);
assert.deepEqual(await b.evaluate('JSON.parse(window.__writes.find(w => w.path === "/api/proxy/admin/init").body)'), { generate: true });
assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /^Running\. Answers on this machine, port 18432\.$/);
assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /^Running\. Service reachable on this machine, port 18432\.$/);
await wait('document.querySelector("#setup-step-accounts").dataset.state === "next"');
assert.deepEqual(await primaries(b), ['proxy-login-go'], 'the one primary moves to step 2');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude');
@@ -311,13 +374,43 @@ test('settings-s4: a step that fails stops the run with Try again, keeps the fin
assert.deepEqual(await admin(b), ['init', 'unit/install'], 'nothing is retried by itself');
assert.equal(await b.evaluate('document.querySelector("#setup-step-service [data-step-badge]").textContent'), 'Setup stopped');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.className)'), ['ok', 'ok', 'bad', 'todo']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.firstChild.textContent)'), ['Downloaded and checked', 'Configured', 'Start the service: did not finish', 'Check it answers']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.firstChild.textContent)'), ['Downloaded and checked', 'Configured', 'Start the service: did not finish', 'Check the service']);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-lines").checkVisibility() && document.querySelector("#proxy-setup-lines summary").textContent'), "The service's last lines");
assert.deepEqual(await primaries(b), ['proxy-setup-go']);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-tech summary").textContent'), 'Technical details: release, service, history');
});
test('service progress names the unreachable service after a failed start', { timeout: 90000 }, async t => {
const down = { ...running, unit: { ...running.unit, listening: false }, next: ['unit-restart'] };
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit-start', time: T } } }, ...accounts([]), '/api/triage/route': { route: null } } });
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { let reads = 0; Object.defineProperty(window.__scenario, '/api/proxy/admin/status', { configurable: true, get() {
if (!window.__writes.some(w => w.path === '/api/proxy/admin/unit/start')) return ${JSON.stringify(installed)};
return ++reads === 1 ? { ...${JSON.stringify(down)}, busy: 'starting' } : ${JSON.stringify(down)};
} }); })();` });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "unit-start"');
await b.evaluate('document.querySelector("#proxy-setup-go").click(); true');
await wait('document.querySelector("#proxy-setup-progress [data-stage=answer]")?.className === "run"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-progress [data-stage=answer]").firstChild.textContent'), 'Checking the service…');
await wait('document.querySelector("#proxy-setup-progress [data-stage=answer]")?.className === "bad"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-progress [data-stage=answer]").firstChild.textContent'), 'Service not reachable yet');
});
test('service progress names a reachable service during setup', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit-start', time: T } } }, ...accounts([]), '/api/triage/route': { route: null } } });
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { let reads = 0; Object.defineProperty(window.__scenario, '/api/proxy/admin/status', { configurable: true, get() {
if (!window.__writes.some(w => w.path === '/api/proxy/admin/unit/start')) return ${JSON.stringify(installed)};
return ++reads === 1 ? { ...${JSON.stringify(running)}, next: ['fence-clear'], busy: 'starting' } : ${JSON.stringify(running)};
} }); })();` });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "unit-start"');
await b.evaluate('document.querySelector("#proxy-setup-go").click(); true');
await wait('document.querySelector("#proxy-setup-progress [data-stage=answer]")?.className === "ok"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-progress [data-stage=answer]").firstChild.textContent'), 'Service reachable on this machine');
await wait('document.querySelector("#setup-step-service").dataset.state === "done"');
});
test('settings-s4: ?step= opens a done card; without it a done card folds to its line', { timeout: 90000 }, async t => {
const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }];
for (const [hash, shown] of [['#/settings/model-setup?step=accounts', true], ['#/settings/model-setup', false]]) {
@@ -344,15 +437,15 @@ test('settings-s4: accounts read as rows with kind and health, the provider pick
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li")].map(li => [...li.children].map(c => c.innerText.replace(/\\s+/g, " ").trim()))'), [
// #1873 account-remove: the instance owner's rows end in Remove.
['Claude', 'Subscription Claude work', 'Ready', 'Remove'], ['ChatGPT / Codex', 'Subscription Codex home', 'Not working', 'Remove'], ['z.ai', 'API key z.ai key', 'Off', 'Remove'], ['Claude', 'Subscription Claude old', 'Unknown', 'Remove']]);
['Claude', 'Subscription Claude work', 'Saved', 'Remove'], ['ChatGPT / Codex', 'Subscription Codex home', 'Error', 'Remove', 'Add account'], ['z.ai', 'API key z.ai key', 'Disabled', 'Remove', 'Add account'], ['Claude', 'Subscription Claude old', 'Unknown', 'Remove']]);
assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts").dataset.state'), 'bad', 'an account that is not working needs the owner');
assert.match(await b.evaluate('document.querySelector("#setup-step-accounts [data-step-summary]").textContent'), /ChatGPT \/ Codex \(subscription\): not working/);
assert.match(await b.evaluate('document.querySelector("#setup-step-accounts [data-step-summary]").textContent'), /ChatGPT \/ Codex \(subscription\): error/);
// #1873 account-remove: removing is built; the owner sees no note, only each row's Remove.
assert.doesNotMatch(await b.evaluate('document.querySelector("#setup-step-accounts").textContent'), /Removing an account is not built yet/);
assert.equal(await b.evaluate('document.querySelector("#proxy-remove-note").hidden'), true);
// The provider picks how to add: a sign-in for a subscription, Check and add for an API key.
await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-login-go").checkVisibility(), document.querySelector("#proxy-apikey").checkVisibility(), document.querySelector("#proxy-apikey button[type=submit]").textContent]'), [false, true, 'Check and add']);
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-login-go").checkVisibility(), document.querySelector("#proxy-apikey").checkVisibility(), document.querySelector("#proxy-apikey button[type=submit]").textContent]'), [false, true, 'Save account']);
assert.ok((await primaries(b)).length <= 1, 'one primary button with the key form open');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "codex"; s.dispatchEvent(new Event("change")); return true; })()');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to ChatGPT / Codex');
@@ -387,8 +480,8 @@ test('settings-s4 chat-fail F3: an account row shows the accounts read\'s reason
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li")].map(li => [...li.children].map(c => c.textContent.replace(/\\s+/g, " ").trim()))'), [
['Claude', 'SubscriptionClaude work', 'Not available', 'Remove', out], ['ChatGPT / Codex', 'SubscriptionCodex home', 'Not working', 'Remove', signin],
['Claude', 'SubscriptionClaude spare', 'Not working', 'Remove'], ['ChatGPT / Codex', 'SubscriptionCodex work', 'Ready', 'Remove']], `${width}: the reason follows the state; absent or empty shows nothing`);
['Claude', 'SubscriptionClaude work', 'Not available', 'Remove', out, 'Add account'], ['ChatGPT / Codex', 'SubscriptionCodex home', 'Sign-in needed', 'Remove', signin, 'Add account'],
['Claude', 'SubscriptionClaude spare', 'Error', 'Remove', 'Add account'], ['ChatGPT / Codex', 'SubscriptionCodex work', 'Saved', 'Remove']], `${width}: the reason follows the state; absent or empty shows nothing`);
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-accounts img").length + (window.__xss ?? 0)'), 0, 'the reason is text, never markup');
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-accounts .account-reason")].every(p => p.checkVisibility() && p.getBoundingClientRect().right <= document.documentElement.clientWidth)'), true);
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}: nothing scrolls sideways`);
@@ -10,7 +10,7 @@ import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const waitFor = b => (expression, ms = 6000) => b.evaluate(`(async()=>{for(let i=0;i<${Math.ceil(ms / 30)};i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`, ms + 10000);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
async function fixture({ empty = false, bootless = false } = {}) {
@@ -267,25 +267,28 @@ test('a restart started on one organization finishes on that organization after
// Every agent request read and write is recorded, whichever organization it names; the bus answers
// are stubs (terminate, closed requests, one launch). Only acme's instances read is stubbed and
// recorded (the session gone): beta's own page reads beta's instances, which is not the chain.
const init = `window.__chain = []; const original = window.fetch;
const init = `window.__chain = []; window.__requestIds = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (options.method === 'POST' && /\\/agent\\/terminate$/.test(s)) { __chain.push(s); x = { request: '${END}' }; return ${json}; }
if (options.method === 'POST' && /\\/agent\\/terminate$/.test(s)) { __chain.push(s); await new Promise(r => { window.__releaseTerminate = r; }); x = { request: '${END}' }; return ${json}; }
if (options.method === 'POST' && /\\/agent\\/launch$/.test(s)) { __chain.push(s); x = { request: '${LAUNCHED}' }; return ${json}; }
if (/\\/agent\\/request\\?/.test(s)) { __chain.push(s.split('?')[0]); const id = new URL(s, location.href).searchParams.get('id');
if (/\\/agent\\/request\\?/.test(s)) { __chain.push(s.split('?')[0]); const id = new URL(s, location.href).searchParams.get('id'); __requestIds.push(id);
x = { request: id, instance: 'coder', action: id === '${END}' ? 'end' : 'launch', state: 'closed', done: { run: id === '${END}' ? null : 'run-9' }, cancelled: null }; return ${json}; }
if (s === '/api/orgs/acme/bus/instances' && window.__restarting) { __chain.push(s); x = { rows: [{ instances: { coder: { running: [] } } }] }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/acme/organization', init });
await wait('window.MosaicAgents && document.querySelector("[data-org-dashboard] h1")');
// The button the Routing receipt offers (agents.js restartMarkup), placed on acme's page.
await b.evaluate('window.__restarting = true; document.querySelector("[data-org-dashboard]").insertAdjacentHTML("beforeend", window.MosaicAgents.restartMarkup("coder")); document.querySelector("[data-agent-restart=coder]").click()');
await wait('window.__chain.length >= 1');
// Start the same chain as the Routing receipt button and observe its final status.
await b.evaluate('window.__restarting = true; document.querySelector("[data-org-dashboard]").insertAdjacentHTML("beforeend", window.MosaicAgents.restartMarkup("coder")); void window.MosaicAgents.restart("coder", false, { text(step) { window.__restartStep = step; } }); true');
await wait('typeof window.__releaseTerminate === "function"');
await b.evaluate('location.hash = "#/orgs/beta/organization"');
await wait('location.hash === "#/orgs/beta/organization"');
// Done when the chain has launched and read the launch request back, or as soon as any of it names beta.
await wait('window.__chain.some(u => u.includes("/orgs/beta/")) || (window.__chain.some(u => /\\/agent\\/launch$/.test(u)) && window.__chain.filter(u => /\\/agent\\/request$/.test(u)).length >= 2)', 30000);
await wait('window.MosaicOrg?.id === "beta" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
await b.evaluate('window.__releaseTerminate()');
// Stop on a cross-org request or after the launch response has been consumed successfully.
await wait('window.__chain.some(u => u.includes("/orgs/beta/")) || window.__restartStep === "restarted"', 30000);
assert.equal(await b.evaluate('window.__restartStep'), 'restarted');
const chain = await b.evaluate('window.__chain');
assert.deepEqual([...new Set(chain)], ['/api/orgs/acme/agent/terminate', '/api/orgs/acme/agent/request', '/api/orgs/acme/bus/instances', '/api/orgs/acme/agent/launch'], chain.join(' '));
assert.deepEqual(await b.evaluate('window.__requestIds'), [END, LAUNCHED]);
// beta's page draws nothing of acme's chain.
assert.equal(await b.evaluate('!!document.querySelector("[data-agent-restart-status=coder]")'), false);
});