Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e67fd9289 | ||
|
|
ffc7db130f | ||
|
|
d6de22aaf8 | ||
|
|
f4134fff9a | ||
|
|
122659a488 | ||
|
|
40afaaf6ad |
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); });
|
||||
|
||||
@@ -72,8 +72,15 @@ trust and `--no-approve` would then hide a seal flag the binary ignores.
|
||||
Then one sealed rpc run per loader flag leaves out only that flag: its
|
||||
kind must show, and no other kind (an MCP server may show beside an
|
||||
extension when `--help` lists no `--no-mcp`, since pi then ties MCP to
|
||||
`--no-extensions`). So each loader flag is shown to keep its own kind
|
||||
out, and no other seal flag, nor their order, can stand in for it. Five
|
||||
`--no-extensions`). If `--no-extensions` also disables the MCP loader,
|
||||
the check leaves out both it and `--no-mcp` in one additional rpc run.
|
||||
That run must show MCP and no kind beyond MCP and extensions. Together
|
||||
with the run leaving out only `--no-extensions` (extensions load, MCP
|
||||
does not), this proves `--no-mcp` with its loader enabled. The planted
|
||||
MCP servers have distinct names so a trusted project entry cannot hide
|
||||
the user entry. No version comparison selects these checks.
|
||||
So each loader flag is shown to keep its own kind out, and no other
|
||||
seal flag, nor their order, can stand in for it. Five
|
||||
sealed `-p` runs have a bus session's shape: the arguments the adapter
|
||||
passes for a session, in its order, from `sessionShape` in
|
||||
`src/pi-fit.mjs`, with two `-e` and `--session-dir`. The adapter's four
|
||||
|
||||
@@ -28,7 +28,9 @@
|
||||
// kind it keeps out must show, and no other kind (pi without --no-mcp ties MCP to
|
||||
// --no-extensions, so an MCP server may show beside an extension). So each loader flag
|
||||
// is shown to keep its own kind out, and no other seal flag, nor the order they come
|
||||
// in, can stand in for it.
|
||||
// in, can stand in for it. If --no-extensions also disables the MCP loader, a run
|
||||
// without both it and --no-mcp must show MCP and extensions only. Paired with the
|
||||
// --no-extensions one-out run, this proves --no-mcp with its loader enabled.
|
||||
// session five -p runs in a bus session's shape, with the arguments adapters/pi/adapter.sh
|
||||
// passes for a session, in its order (sessionShape below): two -e, --session-dir in
|
||||
// place of --no-session, a fixed --provider and --model, -p and a message. The
|
||||
@@ -570,13 +572,26 @@ async function judge(found, { levels, who, digest, run }) {
|
||||
|
||||
// Each loader flag on its own: with every other seal flag on, its kind must show.
|
||||
for (const [flag, kind, pending] of oneOut) {
|
||||
const r = await pending;
|
||||
const but = `with every seal flag but ${flag}`;
|
||||
let r = await pending;
|
||||
let but = `with every seal flag but ${flag}`;
|
||||
if (r.stopped) return unsure(`the start ${but} ${r.stopped}`);
|
||||
if (!r.answer.state || !r.answer.commands) return unsure(`it didn't answer get_state and get_commands ${but}`);
|
||||
if (r.prompt === null) return unsure(`its -e extension didn't see the system prompt ${but}`);
|
||||
// pi-152: MCP can itself be a built-in extension. Removing --no-mcp alone then leaves its
|
||||
// loader disabled. The earlier --no-extensions one-out run proved that extensions load but
|
||||
// MCP stays off with --no-mcp. Remove that flag too: MCP must now run, and no unrelated kind
|
||||
// may load. This pair proves the flag, without demanding that the two seals be independent.
|
||||
let pairedMcp = false;
|
||||
if (flag === "--no-mcp" && r.seen.length === 0) {
|
||||
pairedMcp = true;
|
||||
but = "with every seal flag but --no-extensions and --no-mcp";
|
||||
r = await rpcRun(without("--no-extensions", "--no-mcp"));
|
||||
if (r.stopped) return unsure(`the start ${but} ${r.stopped}`);
|
||||
if (!r.answer.state || !r.answer.commands) return unsure(`it didn't answer get_state and get_commands ${but}`);
|
||||
if (r.prompt === null) return unsure(`its -e extension didn't see the system prompt ${but}`);
|
||||
}
|
||||
if (!r.seen.some((s) => s.kind === kind)) return unsure(`it didn't load a planted ${kind} ${but}`);
|
||||
const others = r.seen.filter((s) => s.kind !== kind && !(flag === "--no-extensions" && !noMcp && s.kind === "MCP server"));
|
||||
const others = r.seen.filter((s) => s.kind !== kind && !(pairedMcp && s.kind === "extension") && !(flag === "--no-extensions" && !noMcp && s.kind === "MCP server"));
|
||||
if (others.length) return refuse(`loaded a planted ${others.map((s) => s.source).join(", ")} ${but}`);
|
||||
}
|
||||
|
||||
@@ -896,7 +911,9 @@ function plant(scratch) {
|
||||
const marks = join(scratch, "marks");
|
||||
const put = (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); };
|
||||
const ext = (source) => `import { writeFileSync } from "node:fs";\nexport default function (): void { writeFileSync(${JSON.stringify(join(marks, markerName(source)))}, ""); }\n`;
|
||||
const mcp = (source) => JSON.stringify({ mcpServers: { fit: { command: "/bin/sh", args: ["-c", `: > ${join(marks, markerName(source))}`] } } });
|
||||
// A trusted project's server replaces a user server with the same name (pi 1.5.2). The
|
||||
// control must see a user source independently of project trust, so use a name per source.
|
||||
const mcp = (source) => JSON.stringify({ mcpServers: { [markerName(source)]: { command: "/bin/sh", args: ["-c", `: > ${join(marks, markerName(source))}`] } } });
|
||||
const skill = (name) => `---\nname: ${name}\ndescription: a planted skill\n---\nA planted skill.\n`;
|
||||
const prompt = "A planted prompt template.\n";
|
||||
const agent = join(scratch, "home", ".pi", "agent");
|
||||
|
||||
@@ -124,6 +124,52 @@ test("pi-unpin S3: a stand-in that touches the planted MCP marker under the seal
|
||||
for (const [kind, line] of Object.entries(lines)) assert.equal((await fit(standIn(t, { sealLeak: [kind] }).env)).message, `pi 2.0.0 (MOSAIC_PI_BIN) ${line}`, kind);
|
||||
});
|
||||
|
||||
// pi-152: a trusted project MCP entry replaces a user entry of the same name. The positive
|
||||
// control needs a user source, so the fixture must keep the two servers distinct.
|
||||
test("pi-152: project MCP name precedence does not hide the user positive control", SKIP, async t => {
|
||||
const s = standIn(t, { extraFlags: ["--no-mcp"], mcpProjectOverride: true });
|
||||
const r = await fit(s.env);
|
||||
assert.equal(r.ok, true, r.message);
|
||||
assert.equal(r.noMcp, true);
|
||||
});
|
||||
|
||||
test("pi-152: MCP name precedence still refuses a user server loaded under the seal flags", SKIP, async t => {
|
||||
const s = standIn(t, { extraFlags: ["--no-mcp"], mcpProjectOverride: true, sealLeak: ["mcp"] });
|
||||
const r = await fit(s.env);
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.undecided, false);
|
||||
assert.equal(r.message, "pi 2.0.0 (MOSAIC_PI_BIN) loaded a planted user mcp.json with the seal flags on");
|
||||
noPath(r.message, s.paths);
|
||||
});
|
||||
|
||||
test("pi-152: --no-mcp is proved even when --no-extensions also disables the MCP loader", SKIP, async t => {
|
||||
const s = standIn(t, { extraFlags: ["--no-mcp"], mcpProjectOverride: true, mcpAlso: "--no-extensions" });
|
||||
const r = await fit(s.env);
|
||||
assert.equal(r.ok, true, r.message);
|
||||
assert.equal(r.noMcp, true);
|
||||
});
|
||||
|
||||
test("pi-152: --no-extensions cannot mask an ignored --no-mcp", SKIP, async t => {
|
||||
const s = standIn(t, { extraFlags: ["--no-mcp"], mcpProjectOverride: true, standIn: ["--no-mcp", "--no-extensions"] });
|
||||
const r = await fit(s.env);
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.undecided, false);
|
||||
assert.equal(r.message, "pi 2.0.0 (MOSAIC_PI_BIN) loaded a planted user mcp.json with every seal flag but --no-extensions");
|
||||
noPath(r.message, s.paths);
|
||||
});
|
||||
|
||||
test("pi-152: the paired MCP control still refuses unrelated ambient sources", SKIP, async t => {
|
||||
const s = standIn(t, {
|
||||
extraFlags: ["--no-mcp"], mcpProjectOverride: true, mcpAlso: "--no-extensions",
|
||||
leakWith: ["--no-context-files"], leakWithoutAll: ["--no-extensions", "--no-mcp"],
|
||||
});
|
||||
const r = await fit(s.env);
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.undecided, false);
|
||||
assert.match(r.message, /loaded a planted .*user skill.*user AGENTS.md.* with every seal flag but --no-extensions and --no-mcp$/);
|
||||
noPath(r.message, s.paths);
|
||||
});
|
||||
|
||||
// pi-skills: the worker's shape. pi 0.85.1 adds a --skill directory to discovery, so the adapter
|
||||
// keeps --no-skills in front of each --skill; the fit check's last -p run passes the adapter's -p
|
||||
// argv with MOSAIC_SKILLS (workerShape) and two --skill directories.
|
||||
@@ -423,11 +469,11 @@ test("pi-unpin S3 re-check 7: a pi that loads every kind when TERM, TZ or LC_ALL
|
||||
}
|
||||
});
|
||||
|
||||
// Re-check 5 item 2: the --no-mcp run is the only one that shows --no-mcp alone keeps MCP out.
|
||||
// This pi keeps MCP out with --no-mcp or with --no-context-files, so every other run hides that
|
||||
// --no-mcp does nothing on its own.
|
||||
// Re-check 5 item 2: another seal must not hide whether --no-mcp works. This pi keeps MCP out
|
||||
// with --no-mcp or --no-context-files. Even the paired control that enables extensions cannot
|
||||
// show MCP, so the check still cannot tell.
|
||||
test("pi-unpin S3 re-check 5: a pi whose --no-mcp works only beside another seal flag is can't tell at the --no-mcp run", SKIP, async t => {
|
||||
assert.equal((await fit(standIn(t, { extraFlags: ["--no-mcp"], mcpAlso: "--no-context-files" }).env)).message, "pi 2.0.0 (MOSAIC_PI_BIN) can't be checked: it didn't load a planted MCP server with every seal flag but --no-mcp");
|
||||
assert.equal((await fit(standIn(t, { extraFlags: ["--no-mcp"], mcpAlso: "--no-context-files" }).env)).message, "pi 2.0.0 (MOSAIC_PI_BIN) can't be checked: it didn't load a planted MCP server with every seal flag but --no-extensions and --no-mcp");
|
||||
assert.equal((await fit(standIn(t, { extraFlags: ["--no-mcp"] }).env)).ok, true);
|
||||
});
|
||||
|
||||
|
||||
@@ -37,8 +37,11 @@
|
||||
// none. `needs`: a flag the loader flags work only with; without it they do
|
||||
// nothing. `leakWithout`: flags; when any of them is absent, every kind loads.
|
||||
// `leakWith`: flags; when all of them are given, every kind loads (with
|
||||
// `leakWithout` too, both must hold). `mcpAlso`: a flag that keeps MCP servers out
|
||||
// as well as their own flag does. `leakNoAgentDir`: every kind loads when
|
||||
// `leakWithout` too, both must hold). `leakWithoutAll`: every listed flag must be
|
||||
// absent, combined with the other leak conditions. `mcpAlso`: a flag that keeps MCP servers out
|
||||
// as well as their own flag does. `mcpProjectOverride`: like pi 1.5.2, merge the
|
||||
// user and trusted project's .pi/mcp.json by name, with project entries winning;
|
||||
// ignore .mcp.json. `leakNoAgentDir`: every kind loads when
|
||||
// PI_CODING_AGENT_DIR is unset, as in a bus session. `leakNoVar`: names; every
|
||||
// kind loads when any of them is unset (TERM, TZ, LC_ALL in a unit-started bus).
|
||||
// `leakNoMatch`: with -c, every
|
||||
@@ -233,7 +236,7 @@ if (modelRun) {
|
||||
if (fs.existsSync(marker)) ignoreAll = true;
|
||||
else { fs.writeFileSync(marker, ""); leak = new Set(ALL); }
|
||||
}
|
||||
if ((K.leakWith || K.leakWithout) && (K.leakWith || []).every(has) && (!K.leakWithout || K.leakWithout.some((f) => !has(f)))) leak = new Set(ALL);
|
||||
if ((K.leakWith || K.leakWithout || K.leakWithoutAll) && (K.leakWith || []).every(has) && (!K.leakWithout || K.leakWithout.some((f) => !has(f))) && (!K.leakWithoutAll || K.leakWithoutAll.every((f) => !has(f)))) leak = new Set(ALL);
|
||||
if (K.leakNoAgentDir && !process.env.PI_CODING_AGENT_DIR) leak = new Set(ALL);
|
||||
if (K.leakNoVar && K.leakNoVar.some((n) => process.env[n] === undefined)) leak = new Set(ALL);
|
||||
if (K.leakNoMatch && has("-c") && !storedFor(val("--session-dir"))) leak = new Set(ALL);
|
||||
@@ -280,9 +283,12 @@ if (modelRun) {
|
||||
}
|
||||
const mcpFlag = (K.extraFlags || []).includes("--no-mcp") ? "--no-mcp" : "--no-extensions";
|
||||
if (!ignoreAll && (!(sealed(mcpFlag) || (K.mcpAlso && has(K.mcpAlso))) || leak.has("mcp"))) {
|
||||
for (const f of [path.join(agent, "mcp.json"), path.join(cwd, ".pi", "mcp.json"), path.join(cwd, ".mcp.json")]) {
|
||||
for (const s of Object.values(json(f)?.mcpServers || {})) cp.spawnSync(s.command, s.args || [], { stdio: "ignore" });
|
||||
}
|
||||
const configs = K.mcpProjectOverride
|
||||
? [path.join(agent, "mcp.json"), ...(trusted ? [path.join(cwd, ".pi", "mcp.json")] : [])]
|
||||
: [path.join(agent, "mcp.json"), path.join(cwd, ".pi", "mcp.json"), path.join(cwd, ".mcp.json")];
|
||||
const entries = configs.map((f) => json(f)?.mcpServers || {});
|
||||
const servers = K.mcpProjectOverride ? Object.values(Object.assign({}, ...entries)) : entries.flatMap(Object.values);
|
||||
for (const s of servers) cp.spawnSync(s.command, s.args || [], { stdio: "ignore" });
|
||||
}
|
||||
if (on("skills", "--no-skills") || (K.skillLeak && has("--skill") && !ignoreAll)) {
|
||||
const home = process.env.HOME || "/";
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user