Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b3cbe4296 | ||
|
|
1e8a20074d | ||
|
|
2e78c7e593 | ||
|
|
fbfcd942be | ||
|
|
5a7e6765f8 | ||
|
|
69b3931c35 | ||
|
|
b7116be9c3 | ||
|
|
0f3135e36a | ||
|
|
b0dd4d3e2f | ||
|
|
e8c6c7e3a4 | ||
|
|
fe671844ea | ||
|
|
b3eaa8fd81 | ||
|
|
07baa87381 | ||
|
|
5e67fd9289 | ||
|
|
ffc7db130f | ||
|
|
d6de22aaf8 | ||
|
|
f4134fff9a | ||
|
|
122659a488 | ||
|
|
40afaaf6ad |
No files matched your search
@@ -108,7 +108,7 @@ export class ProxyPage {
|
||||
rows.push({ ...view(this.#providers, key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
|
||||
}
|
||||
}
|
||||
return { rows, groups };
|
||||
return { rows, groups, credentialNames: response.files.map(row => row?.name).filter(identifier) };
|
||||
}
|
||||
#public(row) {
|
||||
const { accountId, provider, displayName, status, priority } = row;
|
||||
@@ -271,13 +271,13 @@ export class ProxyPage {
|
||||
fields(args, ['accountId', 'confirm']);
|
||||
if (typeof args.accountId !== 'string' || !/^[a-f0-9]{12}$/.test(args.accountId) || args.confirm !== true) refuse('invalid-request');
|
||||
return this.#write(async () => {
|
||||
const { rows, groups } = await this.#accounts();
|
||||
const { rows, groups, credentialNames } = await this.#accounts();
|
||||
const original = this.#lock ? structuredClone(groups) : null;
|
||||
const matches = rows.filter(row => row.accountId === args.accountId);
|
||||
if (matches.length !== 1) refuse('invalid-request');
|
||||
const row = matches[0];
|
||||
// The DELETE names a credential file; another listed account on the same name would go too.
|
||||
if (row.source === 'oauth' && rows.some(r => r !== row && r.source === 'oauth' && r.name === row.name)) refuse('invalid-request');
|
||||
if (row.source === 'oauth' && credentialNames.filter(name => name === row.name).length !== 1) refuse('invalid-request');
|
||||
if (this.#lock && !isDeepStrictEqual(await this.#client.getUpstreamGroups(), original)) refuse('proxy-down');
|
||||
this.#beforeMutation('proxy.account.remove');
|
||||
try {
|
||||
|
||||
@@ -223,6 +223,14 @@ test('remove: two listed accounts on one credential name, or one account id list
|
||||
await assert.rejects(d.call('proxy.account.remove', { accountId: id('oauth-one.json'), confirm: true }), { code: 'invalid-request' });
|
||||
for (const x of [s, d]) { assert.equal(x.state.calls.some(c => !c.startsWith('GET ')), false); assert.equal(x.state.files.length, 2); }
|
||||
});
|
||||
test('remove: a credential with an unusable id still prevents deleting its shared name', async t => {
|
||||
for (const badId of ['', null, 'x'.repeat(513)]) {
|
||||
const s = await fakeManagement(t, { files: [oauth(), oauth({ id: badId, name: 'oauth-one.json' })] });
|
||||
await assert.rejects(s.call('proxy.account.remove', { accountId: id('oauth-one.json'), confirm: true }), { code: 'invalid-request' });
|
||||
assert.equal(s.state.calls.some(c => !c.startsWith('GET ')), false);
|
||||
assert.equal(s.state.files.length, 2);
|
||||
}
|
||||
});
|
||||
test('remove: under the lock, key groups that change between the read and the write refuse with proxy-down before the fence', async t => {
|
||||
const fs = await import('node:fs'); const { join } = await import('node:path'); const { tmpdir } = await import('node:os');
|
||||
const { createProxyLock } = await import('../src/proxy-lock.mjs');
|
||||
|
||||
@@ -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 || "/";
|
||||
|
||||
@@ -157,20 +157,25 @@ export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgent
|
||||
try { list = await riders(); } catch { throw failure('outcome-unknown'); }
|
||||
const named = (Array.isArray(list) ? list : []).filter(r => typeof r?.id === 'string' && ORG_ID.test(r.id));
|
||||
const riding = named.filter(r => r.cliproxy === true);
|
||||
if (!riding.length) throw failure('not-configured');
|
||||
const unanswered = new Set(named.filter(r => typeof r.cliproxy !== 'boolean').map(r => r.id));
|
||||
if (!riding.length) throw failure(unanswered.size ? 'proxy-down' : 'not-configured');
|
||||
let root;
|
||||
try { root = typeof rootAgents === 'function' ? await rootAgents() : undefined; } catch { root = undefined; }
|
||||
const answers = await Promise.all(riding.map(async r => {
|
||||
let routes = null, named = null;
|
||||
try { routes = await r.call('routes'); } catch { routes = null; }
|
||||
try { named = typeof r.file === 'function' ? modelsNamed((await r.file())?.document) : null; } catch { named = null; }
|
||||
let routes = null, named = null, noLaunchReply = false, document = null;
|
||||
try { routes = await r.call('routes'); } catch (error) { noLaunchReply = error?.code === 'launch-not-configured'; }
|
||||
try { document = typeof r.file === 'function' ? (await r.file())?.document : null; named = modelsNamed(document); } catch { named = null; }
|
||||
// A separate file read can observe a newer launch than the bus did. Treat that race and
|
||||
// unreadable files as unknown, never as proof that no model is in use.
|
||||
const noLaunch = noLaunchReply && named !== null && !Object.hasOwn(document, 'launch');
|
||||
const fromRoot = root === undefined ? null : rootModelsNamed(root, r.id);
|
||||
return { id: r.id, routes, named: named && fromRoot ? [...named, ...fromRoot] : null };
|
||||
return { id: r.id, routes, noLaunch, named: named && fromRoot ? [...named, ...fromRoot] : null };
|
||||
}));
|
||||
const providers = new Map(), usedBy = new Map();
|
||||
let ready = false;
|
||||
for (const { id, routes } of answers) {
|
||||
for (const { id, routes, noLaunch } of answers) {
|
||||
// routes explicitly refuses before reading a catalogue when the organization has no launch.
|
||||
if (noLaunch) continue;
|
||||
const c = routes?.catalogue;
|
||||
if (c?.status !== 'ready' || !Array.isArray(c.models)) { unanswered.add(id); continue; }
|
||||
ready = true;
|
||||
@@ -181,8 +186,9 @@ export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgent
|
||||
if (!providers.get(provider).includes(m.model)) providers.get(provider).push(m.model);
|
||||
}
|
||||
}
|
||||
if (!ready) throw failure('proxy-down');
|
||||
for (const { id, routes, named } of answers) {
|
||||
if (!ready) throw failure(!unanswered.size && answers.every(a => a.noLaunch) ? 'not-configured' : 'proxy-down');
|
||||
for (const { id, routes, named, noLaunch } of answers) {
|
||||
if (noLaunch) continue;
|
||||
if (!routes || typeof routes.instances !== 'object' || routes.instances === null || named === null) { unanswered.add(id); continue; }
|
||||
const table = routes.providerModels && typeof routes.providerModels === 'object' ? routes.providerModels : {};
|
||||
const legacy = routes.catalogue?.legacy && typeof routes.catalogue.legacy === 'object' ? routes.catalogue.legacy : {};
|
||||
|
||||
@@ -114,6 +114,38 @@ test('an organization whose usage is unknown (its file unreadable, its bus down,
|
||||
}
|
||||
});
|
||||
|
||||
test('a riding organization explicitly without launch is answered, while a bus failure remains unanswered', async t => {
|
||||
const noLaunch = { ...rider('bolt', []), call: async () => { throw Object.assign(new Error('no launch'), { code: 'launch-not-configured' }); } };
|
||||
const down = { ...rider('crux', []), call: async () => { throw new Error('down'); } };
|
||||
const c = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')]), noLaunch, down] });
|
||||
assert.deepEqual((await c.models({ seed: true })).unanswered, ['crux']);
|
||||
const onlyAnswered = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')]), noLaunch] });
|
||||
const view = await onlyAnswered.models({ seed: true });
|
||||
assert.deepEqual(view.unanswered, []);
|
||||
assert.equal(existsSync(offeredFile(onlyAnswered.dataRoot)), true);
|
||||
await onlyAnswered.modelsSet({ provider: 'z.ai', on: [], revision: view.revision });
|
||||
});
|
||||
|
||||
test('a no-launch response with a newer launch or unreadable file stays unanswered and blocks an unconfirmed switch off', async t => {
|
||||
const noLaunch = async () => { throw Object.assign(new Error('no launch'), { code: 'launch-not-configured' }); };
|
||||
for (const file of [async () => ({ document: { launch: { models: {} }, roles: {} } }), async () => { throw new Error('unreadable'); }, async () => ({ document: null })]) {
|
||||
const c = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')]), { ...rider('bolt', []), call: noLaunch, file }] });
|
||||
const view = await c.models({ seed: true });
|
||||
assert.deepEqual(view.unanswered, ['bolt']);
|
||||
assert.equal(existsSync(offeredFile(c.dataRoot)), false);
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: [], revision: view.revision }), { code: 'models-in-use' });
|
||||
}
|
||||
});
|
||||
|
||||
test('all riders confirmed without launch are not configured; a failed read is proxy-down', async t => {
|
||||
const noLaunch = { ...rider('bolt', []), call: async () => { throw Object.assign(new Error('no launch'), { code: 'launch-not-configured' }); } };
|
||||
const configured = control(t, { riders: [noLaunch] });
|
||||
await assert.rejects(configured.models({ seed: true }), { code: 'not-configured' });
|
||||
assert.equal(existsSync(offeredFile(configured.dataRoot)), false);
|
||||
const down = control(t, { riders: [{ ...noLaunch, file: async () => { throw new Error('unreadable'); } }] });
|
||||
await assert.rejects(down.models({ seed: true }), { code: 'proxy-down' });
|
||||
});
|
||||
|
||||
test('in use counts every place the organization file names a model and the root agents it takes: project agents, root copies; not an excluded or assistant root agent, not launch.models itself', async t => {
|
||||
const models = [entry('zai', 'glm-5'), entry('zai', 'glm-4.6'), entry('codex', 'gpt-5'), entry('codex', 'gpt-5-mini')];
|
||||
const routes = { instances: { chief: { model: 'g5' } }, providerModels: { g5: entry('zai', 'glm-5'), g46: entry('zai', 'glm-4.6'), gpt: entry('codex', 'gpt-5'), mini: entry('codex', 'gpt-5-mini') } };
|
||||
@@ -166,6 +198,9 @@ test(`a model kept on while its account is signed out counts against the ${MAX_O
|
||||
// glm-0 is in use and this switches it off, but the list is too long first: no ask for a save that cannot be written.
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(1), revision: before.revision }), { code: 'models-invalid' }, `${all.length - 1} on plus 10 kept is past ${MAX_ON}`);
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(1), revision: before.revision, confirmInUse: true }), { code: 'models-invalid' });
|
||||
// Exactly 257 including the 10 kept models must refuse before asking about glm-0.
|
||||
assert.equal(all.slice(6).length + away.length, MAX_ON + 1);
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(6), revision: before.revision }), { code: 'models-invalid' });
|
||||
assert.equal(readOffered(c.dataRoot).revision, before.revision);
|
||||
assert.deepEqual(c.receipts, []);
|
||||
const saved = await c.modelsSet({ provider: 'z.ai', on: all.slice(7), revision: before.revision, confirmInUse: true });
|
||||
@@ -228,6 +263,7 @@ test('a damaged file: the read and the write answer outcome-unknown and write no
|
||||
test('no organization riding is not-configured; none answering a ready catalogue is proxy-down; a busy lock refuses the write', async t => {
|
||||
await assert.rejects(control(t, { riders: [] }).models(), { code: 'not-configured' });
|
||||
await assert.rejects(control(t, { riders: [{ ...rider('acme', []), cliproxy: false }] }).models(), { code: 'not-configured' });
|
||||
await assert.rejects(control(t, { riders: [{ ...rider('acme', []), cliproxy: undefined }] }).models(), { code: 'proxy-down' });
|
||||
const down = { id: 'acme', cliproxy: true, call: async () => { throw new Error('down'); } };
|
||||
await assert.rejects(control(t, { riders: [down, rider('bolt', [], { catalogue: { status: 'unavailable', models: [] } })] }).models(), { code: 'proxy-down' });
|
||||
await assert.rejects(control(t, { riders: [rider('acme', [entry('zai', 'glm-5')])], busy: true }).modelsSet({ provider: 'z.ai', on: [], revision: 'a'.repeat(16) }), { code: 'proxy-admin-busy' });
|
||||
|
||||
@@ -25,8 +25,27 @@
|
||||
// E2E6 P1-1: a poll reloads this state; the last save's receipt and the open review list stay.
|
||||
// A failed poll keeps the last good read only while the page holds the form (dirty, or a field has
|
||||
// focus), so the held form is not dropped (review P3). A clean form shows the read error (re-check P3).
|
||||
const held=org=>{const form=[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org)?.querySelector('[data-autonomy-form]');return !!form&&(form.hasAttribute('data-live-dirty')||form.contains(document.activeElement));};
|
||||
async function load(org) {const prev=states.get(org),keep={status:prev?.status??'',reviewOpen:prev?.reviewOpen===true};try{states.set(org,{...await call(org,''),...keep});}catch(error){states.set(org,prev&&!prev.error&&held(org)?{...prev,...keep}:{error:error.message,...keep});}}
|
||||
// The settings section the page draws now for this organization (a decision notice carries the org too).
|
||||
const live=org=>[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org&&!n.hasAttribute('data-autonomy-decision'));
|
||||
const held=org=>{const form=live(org)?.querySelector('[data-autonomy-form]');return !!form&&(form.hasAttribute('data-live-dirty')||form.contains(document.activeElement));};
|
||||
// Each organization keeps one state object for the life of the page. A save or review keeps a reference
|
||||
// to it across its own request, so a load that ends meanwhile writes its read into that object in place
|
||||
// and never swaps it: the receipt lands where the next draw reads it. A load that began before the last
|
||||
// applied read, or before a save answered, carries older values, so its answer is dropped.
|
||||
const own=['status','reviewOpen','began','shown'];
|
||||
function put(s,read) {for(const k of Object.keys(s))if(!own.includes(k))delete s[k];for(const [k,v]of Object.entries(read))if(!own.includes(k))s[k]=v;}
|
||||
const stateOf=org=>{if(!states.has(org))states.set(org,{error:'Autonomy could not be read.',status:'',reviewOpen:false,began:0,shown:0});return states.get(org);};
|
||||
async function load(org) {
|
||||
const s=stateOf(org),began=++s.began;let read,failed=false;
|
||||
try{read=await call(org,'');}catch(error){read={error:error.message};failed=true;}
|
||||
if(began<s.shown)return;
|
||||
s.shown=began;
|
||||
if(failed&&!s.error&&held(org))return;
|
||||
put(s,read);
|
||||
}
|
||||
// A result said on this organization's status line: kept in its state for the next draw, and written to
|
||||
// the line the page draws now.
|
||||
function say(org,text) {const s=stateOf(org);s.status=text;const line=live(org)?.querySelector('[data-autonomy-status]');if(line)line.textContent=text;}
|
||||
function section(org) {
|
||||
const s=states.get(org);
|
||||
if(!s || s.error)return `<section class="panel" data-autonomy><h3>Autonomy</h3><p>${esc(s?.error??'Autonomy could not be read.')}</p></section>`;
|
||||
@@ -51,13 +70,22 @@
|
||||
}
|
||||
document.addEventListener('submit',async e=>{
|
||||
if(!e.target.matches('[data-autonomy-form]'))return;e.preventDefault();
|
||||
const form=e.target,section=form.closest('[data-autonomy-org]'),org=section.dataset.autonomyOrg,s=states.get(org),fields=new FormData(form);
|
||||
const form=e.target,org=form.closest('[data-autonomy-org]').dataset.autonomyOrg,s=states.get(org),fields=new FormData(form);
|
||||
const autonomy=Object.fromEntries(classes.map(k=>[k,fields.get(k)]));autonomy.notices=fields.has('notices');autonomy.reverseWindowHours=Number(fields.get('reverseWindowHours'));
|
||||
if(fields.get('authorityResolver'))autonomy.authorityResolver=fields.get('authorityResolver');
|
||||
const button=form.querySelector('button[type="submit"]'),status=form.querySelector('[data-autonomy-status]');button.disabled=true;
|
||||
const button=form.querySelector('button[type="submit"]');button.disabled=true;
|
||||
let base=s.revision;try{if(form.dataset.revision)base=JSON.parse(form.dataset.revision);}catch{/* drawn without one */}
|
||||
try{const r=await call(org,'',{revision:base,autonomy});s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));s.status=`Saved. Receipt ${r.transaction}.`;form.dataset.revision=JSON.stringify(r.revision);delete form.dataset.liveDirty;status.textContent=s.status;}
|
||||
catch(error){s.status=error.message;status.textContent=s.status;}finally{button.disabled=false;}
|
||||
// A load that began before the save answered is dropped. A load that ended during the save read either
|
||||
// the revision the save sent, from before it committed, or one at or after the save. One that is neither
|
||||
// was written after the save by someone else: it stays, and the save's values do not replace it.
|
||||
// A redraw during the save may have drawn a new form from an older read. A clean new form is drawn again
|
||||
// from the state, which now holds the newest read known, so it shows that and saves against its revision.
|
||||
// A new form the owner is editing stays: it saves against its own revision and fails closed.
|
||||
try{const r=await call(org,'',{revision:base,autonomy}),sent=JSON.stringify(base);s.shown=++s.began;
|
||||
if([sent,JSON.stringify(r.revision)].includes(JSON.stringify(s.revision))){s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));}
|
||||
form.dataset.revision=JSON.stringify(r.revision);delete form.dataset.liveDirty;s.status=`Saved. Receipt ${r.transaction}.`;
|
||||
const el=live(org),drawn=el?.querySelector('[data-autonomy-form]');if(drawn&&drawn!==form&&!held(org))el.outerHTML=section(org);say(org,s.status);}
|
||||
catch(error){say(org,error.message);}finally{button.disabled=false;}
|
||||
});
|
||||
// An edited form is dirty until it saves: holdLive keeps a dirty form through every poll.
|
||||
const dirty=e=>{const form=e.target.closest?.('[data-autonomy-form]');if(form)form.dataset.liveDirty='1';};
|
||||
@@ -71,8 +99,8 @@
|
||||
const review=button.dataset.autonomyReview,reverse=button.hasAttribute('data-autonomy-reverse');
|
||||
const body=review?{decisionClass:review}:reverse?{id:section.dataset.autonomyDecision}:{id:section.dataset.autonomyDecision,confirm:button.dataset.autonomyConfirm==='yes',...(button.dataset.autonomyConfirm==='no'?{reason:section.querySelector('[data-autonomy-reason]').value}:{})};
|
||||
button.disabled=true;
|
||||
try{const r=await call(org,review?'review':reverse?'reverse':'confirm',body);status.textContent=review?'Trail review recorded.':reverse?(r.restart||r.trailPending?'Reversal committed. Completion needs recovery: inspect the decision trail and the stopped agent before requesting relaunch.':'Reversal recorded.'):(body.confirm?'Confirmation recorded. Refresh the inbox for current state.':'Returned to arbiter. Refresh the inbox for current state.');}
|
||||
catch(error){status.textContent=error.message;}finally{button.disabled=false;}
|
||||
try{const r=await call(org,review?'review':reverse?'reverse':'confirm',body);if(review)return say(org,'Trail review recorded.');status.textContent=reverse?(r.restart||r.trailPending?'Reversal committed. Completion needs recovery: inspect the decision trail and the stopped agent before requesting relaunch.':'Reversal recorded.'):(body.confirm?'Confirmation recorded. Refresh the inbox for current state.':'Returned to arbiter. Refresh the inbox for current state.');}
|
||||
catch(error){if(review)say(org,error.message);else status.textContent=error.message;}finally{button.disabled=false;}
|
||||
});
|
||||
window.MosaicAutonomy={load,section,notice};
|
||||
})();
|
||||
@@ -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,
|
||||
@@ -764,7 +767,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'proxy-uncertain': 'Mosaic could not confirm the remove: the model service is between writes. Check the service and the list before trying again.',
|
||||
'proxy-down': 'The model service stopped answering, so Mosaic could not confirm the remove. Check the service and the list before trying again.',
|
||||
'proxy-admin-busy': 'Another setup action is running. Try again when it finishes.',
|
||||
'invalid-request': 'The model service no longer lists this account. Read the accounts again.',
|
||||
'invalid-request': 'Mosaic could not identify one account to remove. It may no longer be listed, have a duplicate ID, or share a credential with another account. Read the accounts again.',
|
||||
'human-required': 'Only the instance owner removes an account.',
|
||||
};
|
||||
async function adminCall(path, args) {
|
||||
@@ -809,8 +812,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
removeBusy = true; removeAsk.error = null; paintAccounts();
|
||||
try {
|
||||
await adminCall('accounts/remove', { accountId: account.accountId });
|
||||
removeAsk = null; message(`${name} account removed.`);
|
||||
await refresh(); await setup.reread();
|
||||
let removalMessage = `${name} account removed.`;
|
||||
removeAsk = null; message(removalMessage);
|
||||
try { await refresh(); } catch (error) { removalMessage += ` The account list could not be refreshed: ${error.message}`; message(removalMessage); }
|
||||
await setup.reread({ onError: error => message(`${removalMessage} The setup status could not be refreshed: ${error.message}`) });
|
||||
} catch (error) {
|
||||
if (removeAsk) removeAsk.error = error.message; message(error.message);
|
||||
// The outcome may be unknown: read the list again so it shows what the service holds now.
|
||||
@@ -843,7 +848,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 +858,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;
|
||||
}));
|
||||
@@ -920,7 +938,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'models-offered-conflict': 'The model list changed since this page read it. Read it again, then make your change.',
|
||||
'models-invalid': 'The model service no longer lists one of these models. Read the list again.',
|
||||
'proxy-down': 'No organization that uses your model service answered, so its models can\'t be listed now.',
|
||||
'not-configured': 'No organization uses your model service yet. Its models show here once one does.',
|
||||
'not-configured': 'No organization with a configured model launch uses your model service yet. Its models show here once one does.',
|
||||
'proxy-admin-busy': 'Another change to the model service is running. Try again in a moment.',
|
||||
'outcome-unknown': 'The outcome is unknown. Read the list again before you try again.',
|
||||
};
|
||||
@@ -937,8 +955,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
catch (error) { if (round === offeredRound) box.replaceChildren(el('p', offeredSays(error.code), 'small muted')); return; }
|
||||
if (round !== offeredRound) return;
|
||||
const providers = Array.isArray(view?.providers) ? view.providers : [];
|
||||
if (!providers.length) { box.replaceChildren(el('p', 'Your model service lists no models yet.', 'small muted')); return; }
|
||||
box.replaceChildren(...providers.map(p => offeredList(p, view.revision, open.has(p.provider), saved === p.provider)));
|
||||
const quiet = Array.isArray(view?.unanswered) ? view.unanswered.filter(id => typeof id === 'string').map(id => window.MosaicOrg?.row?.(id)?.label || id) : [];
|
||||
const notice = quiet.length ? [el('p', `Not answering now, so it is not known which models they use: ${quiet.join(', ')}. A model you switch off may stop working for them.`, 'offered-unanswered banner ref')] : [];
|
||||
if (!providers.length) { box.replaceChildren(...notice, el('p', 'Your model service lists no models yet.', 'small muted')); return; }
|
||||
box.replaceChildren(...notice, ...providers.map(p => offeredList(p, view.revision, open.has(p.provider), saved === p.provider)));
|
||||
}
|
||||
function offeredList(p, revision, open, saved) {
|
||||
const name = String(p.label), models = Array.isArray(p.models) ? p.models : [];
|
||||
@@ -1367,7 +1387,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 +1420,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;
|
||||
@@ -1884,10 +1904,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
focusStep();
|
||||
}
|
||||
// True once the answer is painted, so a caller can say the list on the page is the new one.
|
||||
async function load() {
|
||||
async function load({ onError } = {}) {
|
||||
if (!enabled || loading) return false; loading = true; let painted = false;
|
||||
try { state = await admin('status'); setProviders(state.providers); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.init.initialized) await accountsReady(); }
|
||||
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); }
|
||||
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); onError?.(error); }
|
||||
finally { loading = false; }
|
||||
return painted;
|
||||
}
|
||||
@@ -1962,7 +1982,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
start(config) { enabled = true; sendOk = config.proxyAdminSend === true; return load(); },
|
||||
accounts(n) { accountCount = n; if (state) { paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); } },
|
||||
// A sign-in, a key or a restart can change the next step: read the whole status again.
|
||||
async reread() { if (!enabled) return; triageSet = null; await load(); },
|
||||
async reread(options) { if (!enabled) return; triageSet = null; await load(options); },
|
||||
enabled: () => enabled,
|
||||
serviceDone: () => running(),
|
||||
// An organization whose model list is ready, for Models offered. The open one first.
|
||||
|
||||
@@ -62,21 +62,29 @@
|
||||
}
|
||||
// E2E6 P1-1, P2-2: a poll reloads the list but keeps the open preview, the project picked for each
|
||||
// pack and the last receipt. A kept preview applies by its digest, so a stale one is refused by the bus.
|
||||
// Each organization has one state object for the life of the page. A click keeps a reference to it
|
||||
// across its own request, so a load that ends meanwhile updates the read fields in place and never
|
||||
// swaps the object: the click's preview or receipt lands where the next draw reads it. A load that
|
||||
// began before the last applied one carries older reads, so its answer is dropped.
|
||||
async function load(org) {
|
||||
const prev = states.get(org);
|
||||
const s = { packs: null, applied: [], writable: false, error: null, projects: null, preview: prev?.preview ?? null, status: prev?.status ?? '', picks: prev?.picks ?? {} };
|
||||
if (!states.has(org)) states.set(org, { packs: null, applied: [], writable: false, error: 'Starter packs could not be read.', projects: null, preview: null, status: '', picks: {}, began: 0, shown: 0 });
|
||||
const s = states.get(org);
|
||||
const began = ++s.began;
|
||||
const read = { packs: null, applied: [], writable: false, error: null, projects: null };
|
||||
try {
|
||||
const value = await call(`${base(org)}/packs`);
|
||||
s.packs = Array.isArray(value?.packs) ? value.packs.filter(p => p && typeof p === 'object' && p.pack && typeof p.pack === 'object') : [];
|
||||
s.applied = Array.isArray(value?.applied) ? value.applied.filter(a => plainObj(a) && typeof a.id === 'string' && Array.isArray(a.hired) && Array.isArray(a.open)) : [];
|
||||
s.writable = value?.writable === true;
|
||||
} catch (error) { s.error = error.message; }
|
||||
read.packs = Array.isArray(value?.packs) ? value.packs.filter(p => p && typeof p === 'object' && p.pack && typeof p.pack === 'object') : [];
|
||||
read.applied = Array.isArray(value?.applied) ? value.applied.filter(a => plainObj(a) && typeof a.id === 'string' && Array.isArray(a.hired) && Array.isArray(a.open)) : [];
|
||||
read.writable = value?.writable === true;
|
||||
} catch (error) { read.error = error.message; }
|
||||
// A project pack needs a code project. The workflow read lists them; when it fails, a project pack
|
||||
// says so instead of guessing.
|
||||
if (s.packs?.some(p => p.pack.scope === 'project')) {
|
||||
try { const w = await call(`${base(org)}/workflows`); s.projects = w && typeof w.projects === 'object' ? Object.keys(w.projects).sort() : null; } catch { s.projects = null; }
|
||||
if (read.packs?.some(p => p.pack.scope === 'project')) {
|
||||
try { const w = await call(`${base(org)}/workflows`); read.projects = w && typeof w.projects === 'object' ? Object.keys(w.projects).sort() : null; } catch { read.projects = null; }
|
||||
}
|
||||
states.set(org, s);
|
||||
if (began < s.shown) return;
|
||||
s.shown = began;
|
||||
Object.assign(s, read);
|
||||
}
|
||||
const markText = m => MARKS[m] ?? m;
|
||||
function itemRow(item) {
|
||||
|
||||
@@ -51,3 +51,145 @@ for(const [width,height]of [[1440,900],[390,844]])for(const theme of ['light','d
|
||||
await waitFor(b,`/Reversal recorded/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(reverses,1);
|
||||
await b.screenshot(join(shots,`reverse-${width}-${theme}.png`));
|
||||
});
|
||||
|
||||
// The organization page reads autonomy again on a poll and after any write that changes the organization
|
||||
// (mosaic-org-changed). A save or review receipt must survive a reload that overlaps it, in either order,
|
||||
// and an older read that answers last must not put its older values back.
|
||||
// hold(verb) makes the next call of that verb wait: its answer is computed when the call arrives, then held
|
||||
// until release(). arrived resolves when the call has arrived.
|
||||
function holds(){
|
||||
const pending=new Map();
|
||||
return {
|
||||
hold(verb){const h={};h.arrived=new Promise(r=>{h.reached=r;});h.wait=new Promise(r=>{h.release=r;});pending.set(verb,[...(pending.get(verb)??[]),h]);return h;},
|
||||
take:verb=>pending.get(verb)?.shift(),
|
||||
};
|
||||
}
|
||||
async function raceFixture(t,gates){
|
||||
const state={writes:0,reviews:0,setting:{merge:'out of the loop'},revision:'a'.repeat(64)};
|
||||
const answer=(verb,args)=>{
|
||||
if(verb==='autonomy.get.console')return {revision:state.revision,autonomy:state.setting,levels:{'cross-role':'out of the loop',merge:state.setting.merge,policy:'out of the loop',authority:'in the loop'}};
|
||||
if(verb==='autonomy.set.console'){assert.equal(args.revision,state.revision);state.writes++;state.setting=args.autonomy;state.revision=String(state.writes+1).repeat(64);return {revision:state.revision,transaction:`10000000-0000-4000-8000-00000000000${state.writes}`};}
|
||||
if(verb==='autonomy.review.console'){state.reviews++;return {recorded:true};}
|
||||
throw Object.assign(new Error('not-configured'),{code:'not-configured'});
|
||||
};
|
||||
const call=async(verb,args)=>{const value=answer(verb,args),held=gates.take(verb);if(held){held.reached();await held.wait;}return value;};
|
||||
const server=await startServer({port:0,sso:createDevOwner(),send:async()=>({}),organizations:{list:async()=>[{id:'acme',label:'Acme',busHealthy:true}],resolve:async()=>({busHealthy:true,decisionWrite:async()=>({}),requestRead:call,requestWrite:call,send:async()=>({}),reads:{business:async()=>({business:{id:'acme',projects:[],instances:[]}}),settings:async()=>({}),queue:async()=>({rows:[]})},bus:{instances:async()=>({instances:{}}),agents:async()=>[],'thread.claims':async()=>[],tasks:async()=>[],inbox:async()=>[],messages:async()=>({messages:[]})},chat:{projects:async()=>[],threads:async()=>[]}})},log:()=>{}});
|
||||
t.after(()=>close(server));const b=await browser({machine:false});t.after(()=>b.close());
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/organization`);
|
||||
await waitFor(b,`document.querySelector('[data-autonomy-form] button[type=submit]')`);
|
||||
return {b,state};
|
||||
}
|
||||
const reload=b=>b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
|
||||
const markDrawn=b=>b.evaluate(`document.querySelector('[data-autonomy]').dataset.drawn='before';true`);
|
||||
const redrawn=b=>waitFor(b,`document.querySelector('[data-autonomy-form]') && !document.querySelector('[data-autonomy]').dataset.drawn`);
|
||||
const statusText=b=>b.evaluate(`document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent`);
|
||||
const submit=(b,level)=>b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value=${JSON.stringify(level)};document.querySelector('[data-autonomy-form]').requestSubmit();true`);
|
||||
// Count each autonomy read by the revision it carries, once the reading load has used it: a task queued
|
||||
// after the answer runs after the load's last step. A poll that reads meanwhile counts under its own revision.
|
||||
const countReads=b=>b.evaluate(`{const f=window.fetch;window.__autonomyRead={};window.fetch=async(...a)=>{const r=await f(...a);if(String(a[0]).endsWith('/api/orgs/acme/autonomy')&&!a[1]?.method){const j=r.json.bind(r);r.json=()=>j().then(v=>{setTimeout(()=>{window.__autonomyRead[v.revision]=(window.__autonomyRead[v.revision]??0)+1});return v})}return r}}true`);
|
||||
const readUsed=(b,revision)=>waitFor(b,`window.__autonomyRead[${JSON.stringify(revision)}]>=1`);
|
||||
|
||||
test('AU owner settings: a save that lands while a reload of autonomy is held keeps its receipt and revision',{timeout:60000},async t=>{
|
||||
const gates=holds();const {b,state}=await raceFixture(t,gates);
|
||||
// The reload's read arrives first and answers after the save has been drawn.
|
||||
const list=gates.hold('autonomy.get.console');
|
||||
await reload(b);await list.arrived;
|
||||
await submit(b,'in the loop');
|
||||
await waitFor(b,`/^Saved\\. Receipt /.test(document.querySelector('[data-autonomy-status]').textContent)`);
|
||||
assert.equal(state.writes,1);
|
||||
await markDrawn(b);list.release();await redrawn(b);
|
||||
assert.match(await statusText(b),/^Saved\. Receipt 10000000-0000-4000-8000-000000000001\.$/,'the reload kept the receipt');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify(state.revision),'the form saves against the revision the save answered');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'in the loop','the form shows what was saved');
|
||||
// The next save is not a revision conflict.
|
||||
await submit(b,'near the loop');
|
||||
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000002\\.$/.test(document.querySelector('[data-autonomy-status]').textContent)`);
|
||||
assert.equal(state.writes,2);
|
||||
});
|
||||
|
||||
test('AU owner settings: a save that answers after a reload has drawn the page keeps its receipt',{timeout:60000},async t=>{
|
||||
const gates=holds();const {b,state}=await raceFixture(t,gates);
|
||||
// The save arrives first and answers after a reload has drawn the page again.
|
||||
const save=gates.hold('autonomy.set.console');
|
||||
await submit(b,'in the loop');await save.arrived;
|
||||
await markDrawn(b);await reload(b);await redrawn(b);
|
||||
save.release();
|
||||
await waitFor(b,`/^Saved\\. Receipt /.test(document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent)`);
|
||||
await markDrawn(b);await reload(b);await redrawn(b);
|
||||
assert.match(await statusText(b),/^Saved\. Receipt 10000000-0000-4000-8000-000000000001\.$/,'a later reload keeps the receipt');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify(state.revision));
|
||||
});
|
||||
|
||||
test('AU owner settings: a trail review that answers after a reload has drawn the page is said',{timeout:60000},async t=>{
|
||||
const gates=holds();const {b,state}=await raceFixture(t,gates);
|
||||
await b.evaluate(`document.querySelector('[data-autonomy-review-list]').open=true;true`);
|
||||
const review=gates.hold('autonomy.review.console');
|
||||
await b.evaluate(`document.querySelector('[data-autonomy-review=merge]').click();true`);await review.arrived;
|
||||
await markDrawn(b);await reload(b);await redrawn(b);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-review-list]').open`),true,'the review list stays open');
|
||||
review.release();
|
||||
await waitFor(b,`document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent==='Trail review recorded.'`);
|
||||
assert.equal(state.reviews,1);
|
||||
await markDrawn(b);await reload(b);await redrawn(b);
|
||||
assert.equal(await statusText(b),'Trail review recorded.','a later reload keeps the review receipt');
|
||||
});
|
||||
|
||||
test('AU owner settings: an older read of autonomy that answers last does not replace a newer one',{timeout:60000},async t=>{
|
||||
const gates=holds();const {b,state}=await raceFixture(t,gates);
|
||||
await countReads(b);
|
||||
const older=gates.hold('autonomy.get.console');
|
||||
await reload(b);await older.arrived;
|
||||
// Another writer changes the organization; a newer read answers first.
|
||||
state.setting={merge:'near the loop'};state.revision='c'.repeat(64);
|
||||
await reload(b);
|
||||
// The page draws after all of the dashboard's reads, so wait for the draw as well as the read.
|
||||
await waitFor(b,`document.querySelector('[data-autonomy-form] select[name=merge]')?.value==='near the loop' && window.__autonomyRead[${JSON.stringify('c'.repeat(64))}]>=1`);
|
||||
older.release();
|
||||
await readUsed(b,'a'.repeat(64));
|
||||
const drawn=await b.evaluate(`window.MosaicAutonomy.section('acme')`);
|
||||
assert.match(drawn,/<option selected>near the loop<\/option>/,'the older values were not put back');
|
||||
assert.match(drawn,new RegExp(`data-revision=""${'c'.repeat(64)}""`),'the newer revision stays');
|
||||
});
|
||||
|
||||
test('AU owner settings: a save that answers after a redraw from an older read draws what was saved',{timeout:60000},async t=>{
|
||||
const gates=holds();const {b,state}=await raceFixture(t,gates);
|
||||
// The reload's read is served before the save commits. It draws a clean new form while the save is held.
|
||||
const read=gates.hold('autonomy.get.console');
|
||||
await reload(b);await read.arrived;
|
||||
const save=gates.hold('autonomy.set.console');
|
||||
await submit(b,'in the loop');await save.arrived;
|
||||
assert.equal(state.writes,1);
|
||||
await markDrawn(b);read.release();await redrawn(b);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'out of the loop','the older read was drawn');
|
||||
save.release();
|
||||
await waitFor(b,`/^Saved\\. Receipt /.test(document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent)`);
|
||||
// Before any further reload, the drawn form shows the save and carries its revision.
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify(state.revision),'the drawn form saves against the revision the save answered');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'in the loop','the drawn form shows what was saved');
|
||||
assert.match(await statusText(b),/^Saved\. Receipt 10000000-0000-4000-8000-000000000001\.$/);
|
||||
await submit(b,'near the loop');
|
||||
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000002\\.$/.test(document.querySelector('[data-autonomy-status]').textContent)`);
|
||||
assert.equal(state.writes,2,'the next save is not a revision conflict');
|
||||
});
|
||||
|
||||
test('AU owner settings: a save that answers after a newer read by another writer leaves the newer read',{timeout:60000},async t=>{
|
||||
const gates=holds();const {b,state}=await raceFixture(t,gates);
|
||||
// The save commits, then another writer commits, and a reload draws that newer read before the save answers.
|
||||
const save=gates.hold('autonomy.set.console');
|
||||
await submit(b,'in the loop');await save.arrived;
|
||||
assert.equal(state.writes,1);
|
||||
state.setting={merge:'near the loop'};state.revision='c'.repeat(64);
|
||||
await markDrawn(b);await reload(b);await redrawn(b);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'near the loop','the newer read was drawn');
|
||||
save.release();
|
||||
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000001\\.$/.test(document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent)`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'near the loop','the drawn form keeps the newer read');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify('c'.repeat(64)));
|
||||
const drawn=await b.evaluate(`window.MosaicAutonomy.section('acme')`);
|
||||
assert.match(drawn,/<option selected>near the loop<\/option>/,'the state keeps the newer read');
|
||||
assert.match(drawn,/data-autonomy-status role="status">Saved\. Receipt 10000000-0000-4000-8000-000000000001\./,'the state keeps the receipt');
|
||||
// The next save goes against the newer revision and is not a conflict.
|
||||
await submit(b,'in the loop');
|
||||
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000002\\.$/.test(document.querySelector('[data-autonomy-status]').textContent)`);
|
||||
assert.equal(state.writes,2);
|
||||
});
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -31,7 +31,7 @@ const PREVIEW = {
|
||||
|
||||
// busy: the bus's apply committed but its hire loop did not run (hireError), and the packs read lists one line a
|
||||
// member's pack hire left in the owner's inbox (fromPack), one raised some other way and one refused.
|
||||
async function fixture(t, { busy = false } = {}) {
|
||||
async function fixture(t, { busy = false, gates = null } = {}) {
|
||||
const verbs = [], decisions = [];
|
||||
const hired = new Map(); // name -> its pack provenance, as the bus's instances read reports it
|
||||
let applied = null, route = false, instanceReads = 0;
|
||||
@@ -46,19 +46,22 @@ async function fixture(t, { busy = false } = {}) {
|
||||
const listed = () => applied ? [{ id: 'software-team', origin: 'shipped', project: null, hired: [...hired.keys()],
|
||||
open: PREVIEW.hires.filter(h => !hired.has(h.name)).map(h => ({ name: h.name, reason: `Proposed by starter pack software-team for ${h.definition} work.`,
|
||||
...(!busy || h.name === 'scout-1' ? { state: 'refused', code: 'pack-hire-route-missing' } : { state: 'awaiting-owner', decision: `inbox-${h.name}`, ...(h.name === 'coder-1' ? { fromPack: true } : {}) }) })) }] : [];
|
||||
const read = async (verb, args) => {
|
||||
const readAnswer = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'packs.console') return { packs: PACKS, applied: listed() };
|
||||
if (verb === 'pack.preview.console') return PREVIEW;
|
||||
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const write = async (verb, args) => {
|
||||
const writeAnswer = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'pack.apply.console') { applied = true; return { revision: REV('f'), added: ['board'], pack: { id: args.pack, version: '1.0.0' }, ...(busy ? { hires: [], hireError: 'organization-busy' } : { hires: hireLoop() }) }; }
|
||||
if (verb === 'pack.hire.console') return { pack: args.pack, hires: hireLoop() };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
// A held call is answered when it arrives, then waits for release() (holds() below).
|
||||
const gated = answer => async (verb, args) => { const value = await answer(verb, args), held = gates?.take(verb); if (held) { held.reached(); await held.wait; } return value; };
|
||||
const read = gated(readAnswer), write = gated(writeAnswer);
|
||||
const decisionWrite = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'hire.start.console' && args.op === 'fire' && hired.has(args.name)) { hired.delete(args.name); return { id: 'fire-1', op: 'resolved', choice: 'yes' }; }
|
||||
@@ -184,3 +187,80 @@ test('PD an apply whose hire loop did not run says so; the owner card counts a p
|
||||
// coder-1 was left in the inbox by a pack hire, so the owner's pack hire approves it; reviewer-1 is the inbox's.
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 2 proposed agents');
|
||||
});
|
||||
|
||||
// hold(verb) makes the next call of that verb wait: its answer is computed when the call arrives, then held
|
||||
// until release(). arrived resolves when the call has arrived.
|
||||
function holds() {
|
||||
const pending = new Map();
|
||||
return {
|
||||
hold(verb) {
|
||||
const h = {};
|
||||
h.arrived = new Promise(r => { h.reached = r; });
|
||||
h.wait = new Promise(r => { h.release = r; });
|
||||
pending.set(verb, [...(pending.get(verb) ?? []), h]);
|
||||
return h;
|
||||
},
|
||||
take: verb => pending.get(verb)?.shift(),
|
||||
};
|
||||
}
|
||||
const reload = b => b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
|
||||
const markDrawn = b => b.evaluate(`document.querySelector('[data-packs]').dataset.drawn='before';true`);
|
||||
const redrawn = (b, what) => waitFor(b, `document.querySelector('[data-packs]') && !document.querySelector('[data-packs]').dataset.drawn`, what);
|
||||
// Count each packs answer once the reading load has used it. With no project pack listed the load has no
|
||||
// further read, so a task queued after the answer runs after the load's last step.
|
||||
const countPacksAnswers = b => b.evaluate(`{const f=window.fetch;window.__packsDone=0;window.fetch=async(...a)=>{const r=await f(...a);if(String(a[0]).endsWith('/api/orgs/acme/packs')){const j=r.json.bind(r);r.json=()=>j().finally(()=>setTimeout(()=>{window.__packsDone++}))}return r}}true`);
|
||||
const HIRED = 'Hired scout-1. Already hired: coder-1, reviewer-1.';
|
||||
// Apply the pack with no route, so scout-1 is left to hire, then set the route.
|
||||
async function applied(t, gates) {
|
||||
const f = await fixture(t, { gates });
|
||||
await f.b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/organization`);
|
||||
await waitFor(f.b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
|
||||
await f.b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
|
||||
await waitFor(f.b, `document.querySelector('[data-pack-apply]')`, 'preview');
|
||||
await f.b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
|
||||
await waitFor(f.b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'') && document.querySelector('[data-pack-hire-button]')`, 'apply status and hire button');
|
||||
f.setRoute(true);
|
||||
return f;
|
||||
}
|
||||
|
||||
// The page reads the packs again on a poll and after any write that changes the organization
|
||||
// (mosaic-org-changed). A hire receipt must survive a reload that overlaps the hire, in either order.
|
||||
test('PD a hire receipt that lands while an earlier read of the packs is held is kept', { timeout: 90000 }, async t => {
|
||||
const gates = holds();
|
||||
const { b, verbs } = await applied(t, gates);
|
||||
await countPacksAnswers(b);
|
||||
// A reload's packs read is held. The hire answers, reads the packs itself and asks the page to read
|
||||
// everything again; both of those reads answer first. Then the held read answers last.
|
||||
const earlier = gates.hold('packs.console');
|
||||
await reload(b);
|
||||
await earlier.arrived;
|
||||
await b.evaluate(`document.querySelector('[data-pack-hire-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-packs-status]')?.textContent==='${HIRED}' && window.__packsDone>=2`, 'hire status');
|
||||
earlier.release();
|
||||
await waitFor(b, `window.__packsDone>=3`, 'held read answered');
|
||||
await markDrawn(b);
|
||||
await reload(b);
|
||||
await redrawn(b, 'page drawn again after the held read');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), HIRED, 'the hire receipt is kept');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]')`), null, 'nothing left to hire');
|
||||
assert.deepEqual(verbs.filter(([v]) => v === 'pack.hire.console').map(([, a]) => a), [{ pack: 'software-team' }]);
|
||||
});
|
||||
|
||||
test('PD a hire that answers after a reload has drawn the page keeps its receipt', { timeout: 90000 }, async t => {
|
||||
const gates = holds();
|
||||
const { b, verbs } = await applied(t, gates);
|
||||
// The hire arrives first and answers after a reload has drawn the page again.
|
||||
const hire = gates.hold('pack.hire.console');
|
||||
await b.evaluate(`document.querySelector('[data-pack-hire-button]').click();true`);
|
||||
await hire.arrived;
|
||||
await markDrawn(b);
|
||||
await reload(b);
|
||||
await redrawn(b, 'page drawn again during the hire');
|
||||
hire.release();
|
||||
await waitFor(b, `document.querySelector('[data-packs-status]')?.textContent==='${HIRED}'`, 'hire status');
|
||||
await markDrawn(b);
|
||||
await reload(b);
|
||||
await redrawn(b, 'page drawn again after the hire');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), HIRED, 'a later reload keeps the hire receipt');
|
||||
assert.deepEqual(verbs.filter(([v]) => v === 'pack.hire.console').map(([, a]) => a), [{ pack: 'software-team' }]);
|
||||
});
|
||||
@@ -35,7 +35,23 @@ const PREVIEW = {
|
||||
skills: { notEnabled: ['lint-fix'] }, chief: true, plan: {}, digest: REV('d'),
|
||||
};
|
||||
|
||||
async function fixture(t, { send = true } = {}) {
|
||||
// hold(verb) makes the next read of that verb wait: its answer is computed when the read arrives, then
|
||||
// held until release(). arrived resolves when the read has arrived.
|
||||
function holds() {
|
||||
const pending = new Map();
|
||||
return {
|
||||
hold(verb) {
|
||||
const h = {};
|
||||
h.arrived = new Promise(r => { h.reached = r; });
|
||||
h.wait = new Promise(r => { h.release = r; });
|
||||
pending.set(verb, [...(pending.get(verb) ?? []), h]);
|
||||
return h;
|
||||
},
|
||||
take: verb => pending.get(verb)?.shift(),
|
||||
};
|
||||
}
|
||||
|
||||
async function fixture(t, { send = true, gates = null, packs = () => PACKS } = {}) {
|
||||
const verbs = [];
|
||||
let flows = {
|
||||
revision: REV('a'),
|
||||
@@ -48,13 +64,18 @@ async function fixture(t, { send = true } = {}) {
|
||||
},
|
||||
templates: ['coder', 'reviewer'],
|
||||
};
|
||||
const read = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'packs.console') return { packs: PACKS };
|
||||
const answer = (verb, args) => {
|
||||
if (verb === 'packs.console') return { packs: packs() };
|
||||
if (verb === 'pack.preview.console') return { ...PREVIEW, project: args.project ?? null };
|
||||
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
|
||||
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
|
||||
};
|
||||
const read = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
const value = answer(verb, args), held = gates?.take(verb);
|
||||
if (held) { held.reached(); await held.wait; }
|
||||
return value;
|
||||
};
|
||||
const write = async (verb, args) => {
|
||||
verbs.push([verb, args]);
|
||||
if (verb === 'pack.apply.console') return { revision: REV('f'), added: ['board', 'definitions.reviewer'], pack: { id: args.pack, version: '1.0.0' }, hires: [{ name: 'lead-reviewer', state: 'refused', code: 'definition-not-hireable' }] };
|
||||
@@ -128,6 +149,85 @@ test('SP6 pack picker: list, preview with marks, flagged, credential and noHire
|
||||
assert.deepEqual(verbs.filter(([v]) => v === 'pack.preview.console').at(-1)[1], { pack: 'web-project', project: 'site' });
|
||||
});
|
||||
|
||||
// The page reads the packs again on a poll and after any write that changes the organization
|
||||
// (mosaic-org-changed). A preview the owner asked for must survive a reload that overlaps it, in either
|
||||
// order, and an older reload that answers last must not put its older list back.
|
||||
const reload = b => b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
|
||||
const markDrawn = b => b.evaluate(`document.querySelector('[data-packs]').dataset.drawn='before';true`);
|
||||
const redrawn = (b, what) => waitFor(b, `document.querySelector('[data-packs]') && !document.querySelector('[data-packs]').dataset.drawn`, what);
|
||||
|
||||
test('SP6 pack picker: a preview that overlaps a reload of the packs is kept, in either order', { timeout: 60000 }, async t => {
|
||||
const gates = holds();
|
||||
const { b, verbs } = await fixture(t, { gates });
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
|
||||
// The reload's packs read starts first and answers after the preview has been drawn.
|
||||
const list = gates.hold('packs.console');
|
||||
await reload(b);
|
||||
await list.arrived;
|
||||
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-pack-preview="software-team"]')`, 'preview');
|
||||
await markDrawn(b);
|
||||
list.release();
|
||||
await redrawn(b, 'page drawn again after the reload');
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-pack-preview="software-team"]')`), 'the reload kept the preview');
|
||||
// The preview's read starts first and answers after the reload has drawn the page.
|
||||
const preview = gates.hold('pack.preview.console');
|
||||
await b.evaluate(`document.querySelector('[data-pack="web-project"] [data-pack-preview-button]').click();true`);
|
||||
await preview.arrived;
|
||||
await markDrawn(b);
|
||||
await reload(b);
|
||||
await redrawn(b, 'page drawn again during the preview');
|
||||
preview.release();
|
||||
await waitFor(b, `/for project site/.test(document.querySelector('[data-pack-preview] h4')?.textContent??'')`, 'project preview after the reload');
|
||||
assert.deepEqual(verbs.filter(([v]) => v === 'pack.preview.console').map(([, a]) => a), [{ pack: 'software-team' }, { pack: 'web-project', project: 'site' }]);
|
||||
});
|
||||
|
||||
// Count each packs answer once the reading load has used it. With no project pack listed the load has
|
||||
// no further read, so a task queued after the answer runs after the load's last step.
|
||||
const countPacksAnswers = b => b.evaluate(`{const f=window.fetch;window.__packsDone=0;window.fetch=async(...a)=>{const r=await f(...a);if(String(a[0]).endsWith('/api/orgs/acme/packs')){const j=r.json.bind(r);r.json=()=>j().finally(()=>setTimeout(()=>{window.__packsDone++}))}return r}}true`);
|
||||
|
||||
test('SP6 pack picker: an older read of the packs that answers last does not replace a newer one', { timeout: 60000 }, async t => {
|
||||
const gates = holds();
|
||||
let packs = [PACKS[0]];
|
||||
const { b } = await fixture(t, { gates, packs: () => packs });
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
|
||||
await countPacksAnswers(b);
|
||||
const older = gates.hold('packs.console');
|
||||
await reload(b);
|
||||
await older.arrived;
|
||||
packs = [PACKS[0], { id: 'later', origin: 'installed', pack: { label: 'Later pack', description: 'Installed after the first read.', version: '0.1.0', scope: 'organization' } }];
|
||||
await reload(b);
|
||||
await waitFor(b, `document.querySelector('[data-pack="later"]') && window.__packsDone===1`, 'newer list drawn');
|
||||
older.release();
|
||||
await waitFor(b, `window.__packsDone===2`, 'older read answered');
|
||||
assert.match(await b.evaluate(`window.MosaicPacks.section('acme')`), /data-pack="later"/, 'the older list was not put back');
|
||||
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-pack-preview="software-team"]')`, 'preview');
|
||||
assert.ok(await b.evaluate(`!!document.querySelector('[data-pack="later"]')`), 'the drawn list is the newer one');
|
||||
});
|
||||
|
||||
test('SP6 pack picker: an apply receipt that lands while an earlier read of the packs is held is kept', { timeout: 60000 }, async t => {
|
||||
const gates = holds();
|
||||
const { b, verbs } = await fixture(t, { gates, packs: () => [PACKS[0]] });
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
|
||||
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
|
||||
await waitFor(b, `document.querySelector('[data-pack-apply]')`, 'preview');
|
||||
await countPacksAnswers(b);
|
||||
// A reload's packs read is held. The apply answers, reads the packs itself and asks the page to read
|
||||
// everything again; both of those reads answer first. Then the held read answers last.
|
||||
const earlier = gates.hold('packs.console');
|
||||
await reload(b);
|
||||
await earlier.arrived;
|
||||
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
|
||||
await waitFor(b, `/^Applied\./.test(document.querySelector('[data-packs-status]')?.textContent??'') && window.__packsDone===2`, 'apply status');
|
||||
assert.equal(verbs.filter(([v]) => v === 'pack.apply.console').length, 1);
|
||||
earlier.release();
|
||||
await waitFor(b, `window.__packsDone===3`, 'held read answered');
|
||||
const drawn = await b.evaluate(`window.MosaicPacks.section('acme')`);
|
||||
assert.match(drawn, /data-packs-status>Applied\. Added board, definitions\.reviewer\./, 'the receipt is kept');
|
||||
assert.doesNotMatch(drawn, /data-pack-preview=/, 'the applied preview does not come back');
|
||||
});
|
||||
|
||||
test('SP6 pack picker without send previews but offers no apply', { timeout: 60000 }, async t => {
|
||||
const { b } = await fixture(t, { send: false });
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
@@ -89,12 +89,53 @@ test('account-remove: Remove posts exactly { accountId }, reads the list again a
|
||||
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
|
||||
});
|
||||
|
||||
test('account-remove: a failed refresh after a successful remove keeps the success and the refresh error', { timeout: 90000 }, async t => {
|
||||
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL },
|
||||
'POST /api/proxy/admin/accounts/remove': { body: { accountId: A, provider: 'claude', removed: true } } } });
|
||||
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
|
||||
await wait('!!document.querySelector("#proxy-remove-yes")');
|
||||
await b.evaluate(`window.__scenario['GET /api/proxy/accounts'] = { status: 503, body: { error: 'proxy-down' } }; document.querySelector('#proxy-remove-yes').click(); true`);
|
||||
await wait('document.querySelector("#proxy-message").textContent.includes("not answering")');
|
||||
assert.equal(await b.evaluate('document.querySelector("#proxy-message").textContent'), 'Claude account removed. The account list could not be refreshed: The model service is not answering.');
|
||||
assert.equal((await writes(b)).length, 1);
|
||||
});
|
||||
|
||||
test('account-remove: a failed setup status refresh remains visible beside successful removal', { timeout: 90000 }, async t => {
|
||||
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL },
|
||||
'POST /api/proxy/admin/accounts/remove': { body: { accountId: A, provider: 'claude', removed: true } } } });
|
||||
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
|
||||
await wait('!!document.querySelector("#proxy-remove-yes")');
|
||||
await b.evaluate(`window.__scenario['GET /api/proxy/admin/status'] = { status: 503, body: { error: 'outcome-unknown' } }; document.querySelector('#proxy-remove-yes').click(); true`);
|
||||
await wait('document.querySelector("#proxy-setup-message").textContent.length > 0');
|
||||
assert.match(await b.evaluate('document.querySelector("#proxy-message").textContent'), /^Claude account removed\..*setup status could not be refreshed/i);
|
||||
assert.equal((await writes(b)).length, 1);
|
||||
});
|
||||
|
||||
test('account-remove: a late setup warning keeps the removal receipt when priority is saved meanwhile', { timeout: 90000 }, async t => {
|
||||
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL },
|
||||
'POST /api/proxy/admin/accounts/remove': { body: { accountId: A, provider: 'claude', removed: true } },
|
||||
'POST /api/proxy/priority/set': { body: { accountId: B, priority: 0 } } } });
|
||||
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
|
||||
await wait('!!document.querySelector("#proxy-remove-yes")');
|
||||
await b.evaluate(`(() => { const real = window.fetch; window.__held = false; window.fetch = (input, init) => {
|
||||
if (String(input) === '/api/proxy/admin/status') { window.__held = true; return new Promise(resolve => { window.__releaseStatus = () => resolve(new Response(JSON.stringify({ error: 'outcome-unknown' }), { status: 503, headers: { 'Content-Type': 'application/json' } })); }); }
|
||||
return real(input, init); }; window.__scenario['GET /api/proxy/accounts'] = { body: { accounts: ${JSON.stringify(LIST.slice(1))} } }; document.querySelector('#proxy-remove-yes').click(); return true; })()`);
|
||||
await wait('window.__held');
|
||||
await b.evaluate('document.querySelector("#proxy-order form").requestSubmit(); true');
|
||||
await wait('document.querySelector("#proxy-message").textContent === "Priority saved."');
|
||||
await b.evaluate('window.__releaseStatus(); true');
|
||||
await wait('document.querySelector("#proxy-message").textContent.includes("setup status could not be refreshed")');
|
||||
assert.match(await b.evaluate('document.querySelector("#proxy-message").textContent'), /^Claude account removed\./);
|
||||
assert.equal(await b.evaluate('document.querySelector("#proxy-order [role=status]").textContent'), 'Priority saved.');
|
||||
});
|
||||
|
||||
test('account-remove: remove-write-refused and remove-unconfirmed are named in the ask and the account stays', { timeout: 90000 }, async t => {
|
||||
// No refusal says nothing was removed: a refused or unanswered write may still have taken effect.
|
||||
for (const [code, words] of [['remove-write-refused', 'The model service refused to remove the account. Check the list before trying again.'],
|
||||
['remove-unconfirmed', 'Mosaic asked the model service to remove the account, but it is still listed. Read the accounts again before trying again.'],
|
||||
['proxy-uncertain', 'Mosaic could not confirm the remove: the model service is between writes. Check the service and the list before trying again.'],
|
||||
['proxy-down', 'The model service stopped answering, so Mosaic could not confirm the remove. Check the service and the list before trying again.'],
|
||||
['invalid-request', 'Mosaic could not identify one account to remove. It may no longer be listed, have a duplicate ID, or share a credential with another account. Read the accounts again.'],
|
||||
['some-new-code', 'The remove could not be confirmed. Nothing was retried. Read the accounts again before trying again.']]) {
|
||||
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL }, 'POST /api/proxy/admin/accounts/remove': { status: 400, body: { error: code } } } });
|
||||
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
|
||||
|
||||
@@ -202,6 +202,14 @@ test('models-offered page: an organization that is not answering is named in the
|
||||
assert.equal((await writes())[1].body.confirmInUse, true);
|
||||
});
|
||||
|
||||
test('models-offered page: unanswered organizations are visible before saving', { timeout: 90000 }, async t => {
|
||||
const { b, wait, writes } = await setup(t, { admin: { models: { ...VIEW, unanswered: ['lab', 'zeta'] } } });
|
||||
await openOffered(b, wait);
|
||||
assert.equal(await b.evaluate('document.querySelector("#proxy-offered-list .offered-unanswered")?.textContent'),
|
||||
'Not answering now, so it is not known which models they use: Lab Bench, zeta. A model you switch off may stop working for them.');
|
||||
assert.deepEqual(await writes(), []);
|
||||
});
|
||||
|
||||
test('models-offered page: a save after another change is refused as a conflict, worded, with Read the list again; a busy or unknown answer is worded too', { timeout: 90000 }, async t => {
|
||||
const conflict = { status: 409, body: { error: 'models-offered-conflict' } };
|
||||
const busy = { status: 409, body: { error: 'proxy-admin-busy' } };
|
||||
@@ -242,7 +250,7 @@ test('models-offered page: a page without proxyAdmin sends no /api/proxy/admin/
|
||||
test('models-offered page: a read the model service cannot answer is worded, never an empty list', { timeout: 90000 }, async t => {
|
||||
for (const [body, line] of [
|
||||
[{ error: 'proxy-down' }, /No organization that uses your model service answered/],
|
||||
[{ error: 'not-configured' }, /No organization uses your model service yet/],
|
||||
[{ error: 'not-configured' }, /No organization with a configured model launch uses your model service yet/],
|
||||
[{ error: 'outcome-unknown' }, /The outcome is unknown/],
|
||||
]) {
|
||||
const { b, wait } = await setup(t, { admin: { models: { status: 503, body } } });
|
||||
|
||||
@@ -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