Compare commits

...
Author SHA1 Message Date
jason.woltje 7264134899 Correct the final-stop notes from review, and name the cap and an unknown signal plainly
The header no longer claims stderr never carries an environment value: the
error line is pi's message as sent, and run-task redacts it. A comment says
why a worker fails a length stop with text while a managed session does
not. An unknown signal exits 1 rather than 128, and the over-cap line names
the 64 MiB cap. TOOLS.md notes that the wrapper is process 1 in the
container and passes SIGINT to pi.
2026-11-21 15:58:10 -06:00
jason.woltje 66d66eb736 Judge a pi worker run by its final stop reason, and print the cause of a failed run
In text print mode pi exits 1 on an error or aborted stop, but a length
stop exits 0 with nothing printed, so run-task recorded an empty success.
The worker entrypoint now sets MOSAIC_PI_FINAL_STOP=1 for headless pi.
adapter.sh then runs pi through final-stop.mjs, which uses --mode json,
keeps the last agent_end and fails the run on an error, aborted or length
stop with one plain line on stderr. A finished stop prints the answer as
text mode does. run-task also prints the cause line that show prints. The
reason stays exit-nonzero, with no new field. The mock adapter is unchanged.
2026-11-21 15:35:49 -06:00
jason.woltje baf5714443 Keep the Triage key state through a failed read, and stop a replaced decision draw
Re-check fix round. Triage settings hold the key state apart from the
read data, so a read that fails after a key change cannot let an older
read put back the old key state. The decision view checks that its draw
is still current after reading earlier versions, so a draw a newer one
replaced does not change the kept notice results.
2026-11-21 00:04:03 -06:00
jason.woltje 5f7adb7670 Keep a reload's route across a key change, and drop a result when its decision returns
Review fix round. A key change in Triage settings no longer drops a
Reload route read that was in flight. The read still draws its route
and revision, and keeps the newer key state. A decision notice drops
its kept result when the decision comes back into the inbox after a
draw saw it gone.
2026-11-20 23:52:05 -06:00
jason.woltje fc60809b80 Keep decision notice results, and drop older triage and workflow reads
The decision notice on an inbox decision kept its result only in the
page node, so the next poll redraw lost it, and a confirmed or reversed
decision left the inbox read with its notice. The result is now kept in
page memory per decision; a redraw keeps the result line and keeps both
buttons off while an answer is in flight.

Settings > Triage applied every route read. A read from an earlier visit
or a Reload route read that answered after a save or key change put back
the old route, revision or key state, and the next save was refused as
stale. Reads are now numbered as they start; one older than what the
page has drawn is dropped, and a save or key change takes a new number.

Workflows applied plain loads in the order they answered. Each
organization's loads are now numbered too, and an older load that
answers last, or fails last, is dropped. The SP17 write epochs are
unchanged.
2026-11-20 23:41:38 -06:00
jason.woltje 9b3cbe4296 Test that a hire receipt survives an overlapping packs reload
Two forced-order tests for the hire click. They fail without the packs state fix in 5a7e6765f.
2026-11-20 23:25:29 -06:00
jason.woltje 1e8a20074d Keep a newer autonomy read that lands during a save
Re-check of 7cba209dc (P3-1): a save can commit, another writer can
commit after it, and a poll can draw that newer read before the save
answers. The save then wrote its own older values into the state, and
the new redraw painted them over the newer form. It failed closed, but
the page showed older values.

A save that answers now writes its values into the state only when the
state still holds the revision it sent or the one it got back. Any other
revision was written after the save, so it stays. The redraw draws from
that state, so it never paints older values.

The older-read test waits for the draw as well as the read, since the
dashboard draws only after all its reads (re-check P3-2). A new test
forces the newer-writer order.
2026-11-20 22:48:55 -06:00
jason.woltje 2e78c7e593 Draw an autonomy save over a clean form drawn from an older read
Review of a4a035d17 (P3-1): a reload whose read was served before a save
committed could redraw a clean form while the save was in flight. The
save then wrote its revision to the form it started on, which the page
no longer drew. The drawn form showed the old levels next to the receipt,
and a second save before the next poll was refused as a revision
conflict.

A save that answers now draws the settings section again from the saved
state when the drawn form is a different, clean form. A form the owner is
editing stays, so it saves against its own revision and fails closed.
The live section lookup skips decision notices for the hold check too.

The older-read test now waits on the held read by the revision it
carries, so a poll in the window cannot move its count (P3-3). A new test
forces the P3-1 order and checks the drawn form before any reload.
2026-11-20 22:48:55 -06:00
jason.woltje fbfcd942be Keep an autonomy save or review receipt that overlaps a reload
The autonomy panel built a new state object on every load and copied the
status from the state it found when the load began. A save kept the old
object across its own request. So a save that answered while a poll or
an organization change was reading autonomy wrote its receipt and its new
revision to an object the page no longer drew, or the load copied the
empty status forward before the receipt existed. The next draw then
showed no receipt and the old revision, so the next save was refused as
a revision conflict. A trail review wrote its line only to the node it
started on, which a redraw replaces.

Each organization now keeps one state object. A load writes its read into
it when it ends. A load that began before the last applied read, or
before a save answered, is dropped. A save or review result is kept in
that state and written to the status line the page draws now.

Browser tests hold the fixture's calls to force each order of a save
against a reload, a review against a reload, and an older read that
answers after a newer one.
2026-11-20 22:48:55 -06:00
jason.woltje 5a7e6765f8 Keep a pack preview or receipt that overlaps a packs reload
The pack picker built a new state object on every load and copied the
preview and receipt from the state it found when the load began. A click
kept the old object across its own request. So a preview or a hire receipt
that answered while a poll or an apply's page reload was reading the packs
was written to an object the page no longer drew, or was copied away
before it existed. Under host load this dropped the project preview in the
SP6 pack picker test and the hire status in the pack hire test.

Each organization now keeps one state object. A load writes its read
fields into it when it ends, and a load that began before the last one
applied is dropped, so an older list never replaces a newer one.

One browser test holds the fixture's reads to force each order of the
overlap, a second forces an older packs read to answer last, and a third
holds a reload's packs read while an apply's receipt lands.
2026-11-20 20:33:47 -06:00
jason.woltje 69b3931c35 Resolve recheck follow-up cases 2026-11-20 19:43:53 -06:00
jason.woltje b7116be9c3 Address review of proxy administration follow-ups 2026-11-20 19:43:53 -06:00
jason.woltje 0f3135e36a Show unanswered organizations with offered models 2026-11-20 19:43:53 -06:00
jason.woltje b0dd4d3e2f Recognize organizations without a launch in model survey 2026-11-20 19:43:53 -06:00
jason.woltje e8c6c7e3a4 Test the 257 model limit boundary 2026-11-20 19:43:53 -06:00
jason.woltje fe671844ea Guard shared credential names with invalid account IDs 2026-11-20 19:43:53 -06:00
jason.woltje b3eaa8fd81 Preserve account removal success when refresh fails 2026-11-20 19:43:53 -06:00
jason.woltje 07baa87381 Clarify account removal ambiguity 2026-11-20 19:43:53 -06:00
24 changed files with 1361 additions and 67 deletions

No files matched your search

+5 -1
View File
@@ -31,6 +31,7 @@ Optional, adapter-specific (documented per adapter):
| Variable | Meaning |
|---|---|
| `MOSAIC_MOCK_RESPONSE` | mock only: the verbatim response to emit |
| `MOSAIC_PI_FINAL_STOP` | pi only, `1` from `src/run-agent.sh` for a headless worker: judge the run by pi's final stop reason (`final-stop.mjs`) |
**Outputs:**
@@ -53,7 +54,10 @@ Optional, adapter-specific (documented per adapter):
## Included adapters
- `pi` — the `@earendil-works/pi-coding-agent` CLI (not pinned; #1873) in noninteractive
print mode (`-p`), ambient discovery disabled, stdin detached.
print mode (`-p`), ambient discovery disabled, stdin detached. A worker run
(`MOSAIC_PI_FINAL_STOP=1`) goes through `final-stop.mjs`: pi runs with
`--mode json`, the answer is printed only on a finished stop, and an error,
aborted or output-limit stop exits 1 with one line on stderr.
- `mock` — deterministic echo of `MOSAIC_MOCK_RESPONSE`. Test-only: never use
it where a real model response is required.
- `claude` — the host's `claude` CLI, for managed sessions only (below):
+8
View File
@@ -148,5 +148,13 @@ if [ -n "${MOSAIC_MODEL_EVENT_MONITOR:-}" ] && [ "$INTERACTIVE" != "1" ]; then
STREAM="$(dirname "$0")/../../packages/plugins/harness/pi/model-stream.mjs"
exec node "$STREAM" pi "$MOSAIC_FIRST_OUTPUT_DIR" "${MOSAIC_PI_BIN:-pi}" "$@" --mode json
fi
# worker-stop-reason: a run-task worker (src/run-agent.sh sets MOSAIC_PI_FINAL_STOP=1) is judged
# by pi's final stop reason as well as its exit status. Text mode exits 0 on a "length" stop with
# nothing printed; final-stop.mjs runs pi with --mode json, prints the answer as text mode does on
# a finished stop, and fails the run on an error, aborted or length stop with one line on stderr.
# Managed sessions never set it and keep text mode.
if [ "${MOSAIC_PI_FINAL_STOP:-}" = "1" ] && [ "$INTERACTIVE" != "1" ]; then
exec node "$(dirname "$0")/final-stop.mjs" "${MOSAIC_PI_BIN:-pi}" "$@"
fi
# #1873 S2: the binary the harness module found (MOSAIC_PI_BIN, its path inside the sandbox).
exec "${MOSAIC_PI_BIN:-pi}" "$@"
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env node
// worker-stop-reason: judge a headless pi worker run by pi's final stop reason, not only its exit
// status. The worker entrypoint (src/run-agent.sh) asks for this with MOSAIC_PI_FINAL_STOP=1, and
// adapter.sh then runs `node final-stop.mjs <pi> <args...>` in place of `<pi> <args...>`.
//
// Why: in text print mode (-p) pi 0.85.1 exits 1 on an "error" or "aborted" stop, but a "length"
// stop (the model reached its output limit) exits 0 with nothing on stdout or stderr, so run-task
// recorded an empty success. Only the JSON event stream says how the run ended: its last
// agent_end event carries the run's messages, and the last assistant message's stopReason is the
// final stop. Proved against pi 0.85.1 with a fake provider on loopback (packages/plugins/tests/
// pi-final-stop.test.mjs).
//
// This runs pi with `--mode json` and keeps only the last agent_end line (bounded). Then:
// pi exited nonzero the same code, pi's own stderr already said why
// pi was stopped by a signal 128 + the signal number, one line on stderr
// final stop "stop" the text parts, each followed by "\n" (as text mode prints), exit 0
// final stop "toolUse" nothing, exit 0 (a tool ended the run; text mode prints nothing)
// final stop "error"/"aborted" exit 1, one line: pi stopped on an error: <pi's error message>
// final stop "length" exit 1, one line: the model reached its output limit
// anything else exit 1, one line (fail closed: no final answer to judge)
// stdout carries the answer only on success. An error line carries pi's error message as the
// provider sent it, as text mode printed it; run-task redacts known secret values before it shows
// the cause (runCause in scripts/mosaic-task.mjs).
import { spawn } from "node:child_process";
import { realpathSync } from "node:fs";
import { constants } from "node:os";
import { fileURLToPath } from "node:url";
export const AGENT_END_PREFIX = '{"type":"agent_end"';
// The cap on the one line kept. agent_end carries every message of the run, tool results too.
export const MAX_AGENT_END_BYTES = 64 * 1024 * 1024;
const MAX_LINE_CHARS = 2000;
const oneLine = (text) => {
const line = String(text).replace(/\s+/g, " ").trim();
return line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)}...` : line;
};
// The judgement for the last agent_end line pi wrote (null when it wrote none):
// { ok: true, answer } or { ok: false, message }.
export function judgeFinalStop(agentEndLine) {
if (agentEndLine === null) return { ok: false, message: "pi ended without a final answer: it reported no end of run" };
let event;
try { event = JSON.parse(agentEndLine); } catch { return { ok: false, message: "pi ended without a final answer: its end of run could not be read" }; }
const messages = Array.isArray(event?.messages) ? event.messages : [];
let last = null;
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i]?.role === "assistant") { last = messages[i]; break; }
}
if (!last) return { ok: false, message: "pi ended without a final answer: the model gave no reply" };
const reason = last.stopReason;
if (reason === "stop" || reason === "toolUse") {
if (messages[messages.length - 1] !== last) return { ok: true, answer: "" };
const parts = Array.isArray(last.content) ? last.content : [];
return { ok: true, answer: parts.filter((p) => p?.type === "text" && typeof p.text === "string").map((p) => `${p.text}\n`).join("") };
}
if (reason === "error" || reason === "aborted") {
const said = typeof last.errorMessage === "string" && last.errorMessage.trim() ? oneLine(last.errorMessage) : `request ${reason}`;
return { ok: false, message: `pi stopped on an error: ${said}` };
}
// A worker run fails on "length" even with partial text: the answer was cut off. A managed
// session first turn (packages/plugins/harness/pi/model-stream.mjs) counts length with text as
// output; that turn is a conversation, a worker run is a finished job.
if (reason === "length") return { ok: false, message: "pi stopped with no finished answer: the model reached its output limit" };
return { ok: false, message: `pi ended without a final answer: it stopped for an unknown reason (${oneLine(String(reason)).slice(0, 40)})` };
}
// Keeps the last line that starts with AGENT_END_PREFIX out of a byte stream, holding at most
// one such line (up to max bytes) in memory. Other lines pass through unkept.
export function agentEndKeeper(max = MAX_AGENT_END_BYTES) {
let chunks = [];
let size = 0;
let state = "start"; // start: at a line start; keep: in an agent_end line; skip: in another line
let head = Buffer.alloc(0);
let last = null;
let tooBig = false;
const finishLine = () => {
if (state === "keep") {
if (size > max) tooBig = true;
else { last = Buffer.concat(chunks).toString("utf8"); tooBig = false; }
}
chunks = []; size = 0; state = "start"; head = Buffer.alloc(0);
};
const feedPart = (part) => {
if (state === "start") {
head = Buffer.concat([head, part]);
const prefix = Buffer.from(AGENT_END_PREFIX);
const n = Math.min(head.length, prefix.length);
if (!head.subarray(0, n).equals(prefix.subarray(0, n))) { state = "skip"; head = Buffer.alloc(0); return; }
if (head.length < prefix.length) return;
state = "keep"; part = head; head = Buffer.alloc(0);
}
if (state === "keep") {
size += part.length;
if (size <= max) chunks.push(part); else chunks = [];
}
};
return {
write(buffer) {
let at = 0;
while (at < buffer.length) {
const nl = buffer.indexOf(10, at);
if (nl === -1) { feedPart(buffer.subarray(at)); return; }
feedPart(buffer.subarray(at, nl));
finishLine();
at = nl + 1;
}
},
end() {
if (state === "keep") finishLine();
return { line: tooBig ? null : last, tooBig };
},
};
}
async function main(argv) {
const [pi, ...args] = argv;
if (!pi) { process.stderr.write("pi final stop: no pi binary was given\n"); return 2; }
const keeper = agentEndKeeper();
const child = spawn(pi, [...args, "--mode", "json"], { stdio: ["inherit", "pipe", "inherit"] });
const forward = (signal) => { try { child.kill(signal); } catch {} };
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) process.on(signal, () => forward(signal));
child.stdout.on("data", (buffer) => keeper.write(buffer));
const outcome = await new Promise((resolve) => {
child.on("error", (error) => resolve({ error }));
child.on("close", (code, signal) => resolve({ code, signal }));
});
if (outcome.error) {
process.stderr.write(`pi final stop: pi could not be started (${outcome.error.code ?? "spawn error"})\n`);
return 127;
}
if (outcome.signal) {
process.stderr.write(`pi final stop: pi was stopped by ${outcome.signal}\n`);
const number = constants.signals[outcome.signal];
return Number.isInteger(number) && number > 0 ? 128 + number : 1;
}
if (outcome.code !== 0) return outcome.code ?? 1;
const { line, tooBig } = keeper.end();
const verdict = tooBig
? { ok: false, message: `pi ended without a final answer: its end of run was over ${MAX_AGENT_END_BYTES / (1024 * 1024)} MiB` }
: judgeFinalStop(line);
if (!verdict.ok) {
process.stderr.write(`${verdict.message}\n`);
return 1;
}
await new Promise((resolve) => process.stdout.write(verdict.answer, resolve));
return 0;
}
let isMain = false;
try { isMain = realpathSync(process.argv[1] ?? "") === realpathSync(fileURLToPath(import.meta.url)); } catch {}
if (isMain) process.exitCode = await main(process.argv.slice(2));
+18 -1
View File
@@ -78,7 +78,24 @@ the expected text`, `processing was halted during the run`). Otherwise it is
progress and warning lines passed over, redacted (paths, links, emails,
key-shaped strings) and withheld when it holds a value from the environment.
With no such line it says the worker container could not be started or the
worker exited with its code and wrote nothing that can be shown.
worker exited with its code and wrote nothing that can be shown. `mosaic-task
run` prints the same line as `cause: <reason>` after `response:` when the run
did not succeed.
A pi worker is judged by pi's final stop reason as well as its exit status
(worker-stop-reason). In print mode pi exits 0 when the model reaches its
output limit, with nothing printed, so that run used to count as succeeded.
The container's entrypoint sets `MOSAIC_PI_FINAL_STOP=1` for a headless pi
run, and the pi adapter then runs pi through `adapters/pi/final-stop.mjs`,
which reads pi's JSON event stream. A finished stop prints the answer as
before. An error or aborted stop fails with `pi stopped on an error: <pi's
error>`, and an output-limit stop fails with `pi stopped with no finished
answer: the model reached its output limit`. The reason stays
`exit-nonzero`, and the line is the `worker said:` cause. Managed sessions
don't set the variable and keep text mode. In the container the wrapper is
process 1 and passes SIGTERM, SIGINT and SIGHUP to pi, so a SIGINT that
reaches the container now stops pi (exit 130). Before, pi was process 1 and
ignored SIGINT.
Legacy worker containers use a typed per-launch mount contract. Task, mission,
user and session-fork snapshots are read-only. A fork source is opened without
+3 -3
View File
@@ -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');
+14 -8
View File
@@ -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' });
@@ -0,0 +1,282 @@
// worker-stop-reason: a run-task worker run is judged by pi's final stop reason, not only its exit
// status (adapters/pi/final-stop.mjs). The real pi runs through adapters/pi/adapter.sh against a
// fake Anthropic Messages provider on 127.0.0.1 port 0: no real model, no other network.
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import http from "node:http";
import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { locate } from "../harness/pi/binary.mjs";
import { agentEndKeeper, judgeFinalStop } from "../../../adapters/pi/final-stop.mjs";
import { fixture, tmp } from "../../cli/tests/helpers.mjs";
const REPO = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
const ADAPTER = join(REPO, "adapters", "pi", "adapter.sh");
const FINAL_STOP = join(REPO, "adapters", "pi", "final-stop.mjs");
const TASK = join(REPO, "scripts", "mosaic-task.mjs");
const scratch = (t) => {
const dir = mkdtempSync(join(tmpdir(), "fs"));
t.after(() => rmSync(dir, { recursive: true, force: true }));
return dir;
};
const agentEnd = (...messages) => JSON.stringify({ type: "agent_end", messages });
const assistant = (stopReason, extra = {}) => ({ role: "assistant", content: [{ type: "text", text: "partial" }], stopReason, ...extra });
// --- The judge -----------------------------------------------------------------------------------
test("final stop: a finished stop passes with the text parts as text mode prints them", () => {
const line = agentEnd({ role: "user", content: "hi" }, { role: "assistant", stopReason: "stop", content: [{ type: "thinking", thinking: "x" }, { type: "text", text: "OK" }, { type: "text", text: "two" }] });
assert.deepEqual(judgeFinalStop(line), { ok: true, answer: "OK\ntwo\n" });
assert.deepEqual(judgeFinalStop(agentEnd({ role: "assistant", stopReason: "stop", content: [] })), { ok: true, answer: "" });
});
test("final stop: an error, aborted or length stop fails with one plain line", () => {
assert.deepEqual(judgeFinalStop(agentEnd(assistant("error", { errorMessage: "401 invalid\nx-api-key" }))), { ok: false, message: "pi stopped on an error: 401 invalid x-api-key" });
assert.deepEqual(judgeFinalStop(agentEnd(assistant("aborted"))), { ok: false, message: "pi stopped on an error: request aborted" });
assert.deepEqual(judgeFinalStop(agentEnd(assistant("length"))), { ok: false, message: "pi stopped with no finished answer: the model reached its output limit" });
const long = judgeFinalStop(agentEnd(assistant("error", { errorMessage: "e".repeat(5000) })));
assert.equal(long.ok, false);
assert.ok(long.message.length < 2100);
});
test("final stop: no end of run, no reply or an unknown stop reason fails closed", () => {
assert.equal(judgeFinalStop(null).ok, false);
assert.equal(judgeFinalStop("{not json").ok, false);
assert.equal(judgeFinalStop(agentEnd({ role: "user", content: "hi" })).ok, false);
assert.match(judgeFinalStop(agentEnd(assistant("deferred"))).message, /unknown reason \(deferred\)/);
assert.equal(judgeFinalStop(agentEnd(assistant(undefined))).ok, false);
});
test("final stop: a tool that ends the run passes with nothing printed, as text mode does", () => {
const line = agentEnd(assistant("toolUse"), { role: "toolResult", content: [{ type: "text", text: "done" }] });
assert.deepEqual(judgeFinalStop(line), { ok: true, answer: "" });
});
test("final stop: the keeper keeps the last agent_end line across chunk splits and skips other lines", () => {
const k = agentEndKeeper();
const first = agentEnd(assistant("error", { errorMessage: "retrying" }));
const last = agentEnd({ role: "assistant", stopReason: "stop", content: [{ type: "text", text: "é OK" }] });
const stream = Buffer.from(`{"type":"session"}\n${first}\n{"type":"message_end","note":"{\\"type\\":\\"agent_end\\"}"}\n${last}\n{"type":"agent_start"}\n`);
for (let i = 0; i < stream.length; i += 3) k.write(stream.subarray(i, i + 3));
assert.deepEqual(k.end(), { line: last, tooBig: false });
const unterminated = agentEndKeeper();
unterminated.write(Buffer.from(last));
assert.equal(unterminated.end().line, last);
const none = agentEndKeeper();
none.write(Buffer.from('{"type":"agent_start"}\n'));
assert.deepEqual(none.end(), { line: null, tooBig: false });
});
test("final stop: an agent_end line over the cap is not kept, and a later one replaces it", () => {
const small = agentEnd(assistant("stop"));
const big = agentEnd(assistant("stop", { pad: "x".repeat(300) }));
assert.ok(small.length < 200 && big.length > 200);
const k = agentEndKeeper(200);
k.write(Buffer.from(`${small}\n${big}\n`));
assert.deepEqual(k.end(), { line: null, tooBig: true });
const again = agentEndKeeper(200);
again.write(Buffer.from(`${big}\n${small}\n`));
assert.deepEqual(again.end(), { line: small, tooBig: false });
});
// --- final-stop.mjs with a stand-in pi -----------------------------------------------------------
function standIn(dir, body) {
const file = join(dir, "pi-stand-in.mjs");
writeFileSync(file, `#!${process.execPath}\n${body}\n`, { mode: 0o755 });
return file;
}
const runFinalStop = (pi, args = []) => spawnSync(process.execPath, [FINAL_STOP, pi, ...args], { encoding: "utf8", timeout: 20000, input: "" });
test("final stop: an error stop that pi reports with exit 0 is a failed run", (t) => {
const dir = scratch(t);
const pi = standIn(dir, `process.stdout.write(${JSON.stringify(`{"type":"session"}\n${agentEnd(assistant("error", { errorMessage: "529 overloaded" }))}\n`)}); process.exit(0);`);
const r = runFinalStop(pi);
assert.equal(r.status, 1);
assert.equal(r.stdout, "");
assert.equal(r.stderr, "pi stopped on an error: 529 overloaded\n");
});
test("final stop: pi gets its arguments plus --mode json, and its own exit code and stderr pass through", (t) => {
const dir = scratch(t);
const pi = standIn(dir, `(await import("node:fs")).writeFileSync(${JSON.stringify(join(dir, "argv"))}, JSON.stringify(process.argv.slice(2))); process.stderr.write("pi said no\\n"); process.exit(3);`);
const r = runFinalStop(pi, ["-p", "two words"]);
assert.equal(r.status, 3);
assert.equal(r.stderr, "pi said no\n");
assert.equal(r.stdout, "");
assert.deepEqual(JSON.parse(readFileSync(join(dir, "argv"), "utf8")), ["-p", "two words", "--mode", "json"]);
});
test("final stop: a pi that can't start or dies on a signal fails with one line", (t) => {
const dir = scratch(t);
const missing = runFinalStop(join(dir, "no-such-pi"));
assert.equal(missing.status, 127);
assert.match(missing.stderr, /^pi final stop: pi could not be started \(ENOENT\)\n$/);
const killed = runFinalStop(standIn(dir, `process.kill(process.pid, "SIGKILL");`));
assert.equal(killed.status, 137);
assert.equal(killed.stderr, "pi final stop: pi was stopped by SIGKILL\n");
});
// --- The real pi through adapter.sh -------------------------------------------------------------
function sse(res, events) {
res.writeHead(200, { "content-type": "text/event-stream", connection: "close" });
for (const [type, data] of events) res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`);
res.end();
}
const START = { message: { id: "m1", type: "message", role: "assistant", model: "probe-model", content: [], stop_reason: null, usage: { input_tokens: 1, output_tokens: 0 } } };
const reply = (text, stop) => [
["message_start", START],
...(text === null ? [] : [
["content_block_start", { index: 0, content_block: { type: "text", text: "" } }],
["content_block_delta", { index: 0, delta: { type: "text_delta", text } }],
["content_block_stop", { index: 0 }],
]),
["message_delta", { delta: { stop_reason: stop }, usage: { output_tokens: 1 } }],
["message_stop", {}],
];
const SCENARIOS = {
ok: (req, res) => sse(res, reply("OK", "end_turn")),
"status-401": (req, res) => { res.writeHead(401, { "content-type": "application/json" }); res.end(JSON.stringify({ type: "error", error: { type: "authentication_error", message: "invalid x-api-key" } })); },
"length-empty": (req, res) => sse(res, reply(null, "max_tokens")),
"length-text": (req, res) => sse(res, reply("partial", "max_tokens")),
refusal: (req, res) => sse(res, reply(null, "refusal")),
};
async function provider(t, scenario) {
const server = http.createServer((req, res) => { req.resume(); req.on("end", () => SCENARIOS[scenario](req, res)); });
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
t.after(() => { server.closeAllConnections(); server.close(); });
return `http://127.0.0.1:${server.address().port}`;
}
const PI = locate(process.env);
async function adapterRun(t, scenario, { finalStop }) {
assert.ok(PI.bin, PI.problem);
const dir = scratch(t);
const agentDir = join(dir, "agent");
mkdirSync(agentDir);
const url = await provider(t, scenario);
writeFileSync(join(agentDir, "models.json"), JSON.stringify({ providers: { probe: { baseUrl: url, api: "anthropic-messages", apiKey: "probe-dummy", models: [{ id: "probe-model" }] } } }));
writeFileSync(join(dir, "system.md"), "Answer briefly.\n");
const env = {
PATH: `${dirname(process.execPath)}:/usr/bin:/bin`,
HOME: dir,
TMPDIR: dir,
LANG: "C.UTF-8",
PI_CODING_AGENT_DIR: agentDir,
PI_OFFLINE: "1",
PI_SKIP_VERSION_CHECK: "1",
PI_PROVIDER: "probe",
PI_MODEL: "probe-model",
MOSAIC_PI_BIN: PI.bin,
MOSAIC_SYSTEM_PROMPT_FILE: join(dir, "system.md"),
MOSAIC_REQUEST: "Say OK",
MOSAIC_WORKSPACE: join(dir, "ws"),
...(finalStop ? { MOSAIC_PI_FINAL_STOP: "1" } : {}),
};
const child = spawn("/bin/sh", [ADAPTER], { env, stdio: ["ignore", "pipe", "pipe"] });
let stdout = "", stderr = "";
child.stdout.on("data", (d) => (stdout += d));
child.stderr.on("data", (d) => (stderr += d));
const status = await new Promise((resolve) => child.on("close", (code, signal) => resolve(signal ?? code)));
return { status, stdout, stderr };
}
test("real pi: without the final-stop check a length stop exits 0 with nothing printed (the gap)", async (t) => {
const r = await adapterRun(t, "length-empty", { finalStop: false });
assert.deepEqual({ status: r.status, stdout: r.stdout, stderr: r.stderr }, { status: 0, stdout: "", stderr: "" });
});
test("real pi: with the check a normal stop still passes and prints the answer as text mode does", async (t) => {
const plain = await adapterRun(t, "ok", { finalStop: false });
const judged = await adapterRun(t, "ok", { finalStop: true });
assert.deepEqual({ status: plain.status, stdout: plain.stdout }, { status: 0, stdout: "OK\n" });
assert.deepEqual({ status: judged.status, stdout: judged.stdout, stderr: judged.stderr }, { status: 0, stdout: "OK\n", stderr: "" });
});
test("real pi: with the check a length stop fails, with or without partial text", async (t) => {
for (const scenario of ["length-empty", "length-text"]) {
const r = await adapterRun(t, scenario, { finalStop: true });
assert.deepEqual({ status: r.status, stdout: r.stdout, stderr: r.stderr }, { status: 1, stdout: "", stderr: "pi stopped with no finished answer: the model reached its output limit\n" }, scenario);
}
});
test("real pi: with the check a provider error stop (pi exits 0 in JSON mode) fails with pi's error text", async (t) => {
const r = await adapterRun(t, "status-401", { finalStop: true });
assert.equal(r.status, 1);
assert.equal(r.stdout, "");
assert.match(r.stderr, /^pi stopped on an error: 401 .*authentication_error.*invalid x-api-key.*\n$/);
const refused = await adapterRun(t, "refusal", { finalStop: true });
assert.equal(refused.status, 1);
assert.equal(refused.stderr, "pi stopped on an error: The model refused to complete the request\n");
});
// --- src/run-agent.sh sets the check for pi only -------------------------------------------------
function entrypoint(t) {
const root = scratch(t);
const opt = join(root, "opt");
for (const d of ["src", "processing-control", "contracts", "adapters/pi"]) mkdirSync(join(opt, d), { recursive: true });
writeFileSync(join(opt, "src", "run-agent.sh"), readFileSync(join(REPO, "src", "run-agent.sh"), "utf8").replaceAll("/opt/mosaic", opt), { mode: 0o755 });
writeFileSync(join(opt, "src", "load-contracts.sh"), '#!/bin/sh\nprintf "prompt\\n" > "$2"\n', { mode: 0o755 });
writeFileSync(join(opt, "processing-control", "entrypoint.mjs"), "");
cpSync(join(REPO, "adapters", "mock"), join(opt, "adapters", "mock"), { recursive: true });
chmodSync(join(opt, "adapters", "mock", "adapter.sh"), 0o755);
writeFileSync(join(opt, "adapters", "pi", "adapter.sh"), '#!/bin/sh\n(env | grep "^MOSAIC_" | sort) >&2\necho pi-stand-in\n', { mode: 0o755 });
return (adapter, extra = {}) => spawnSync(join(opt, "src", "run-agent.sh"), ["the request"], {
encoding: "utf8",
timeout: 20000,
env: { PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, HOME: root, MOSAIC_ADAPTER: adapter, MOSAIC_SYSTEM_PROMPT_FILE: join(root, "prompt.md"), MOSAIC_MOCK_RESPONSE: "MOCK_OK", ...extra },
});
}
test("run-agent.sh: a headless pi worker gets MOSAIC_PI_FINAL_STOP=1, and the mock sees exactly the variables it did", (t) => {
const run = entrypoint(t);
const pi = run("pi");
assert.equal(pi.status, 0, pi.stderr);
assert.match(pi.stderr, /^MOSAIC_PI_FINAL_STOP=1$/m);
const mock = run("mock");
assert.equal(mock.status, 0, mock.stderr);
assert.equal(mock.stdout, "MOCK_OK\n");
const vars = mock.stderr.split("\n").filter((l) => l.startsWith("MOSAIC_")).map((l) => l.split("=")[0]);
assert.deepEqual(vars, ["MOSAIC_ADAPTER", "MOSAIC_MOCK_RESPONSE", "MOSAIC_REQUEST", "MOSAIC_SYSTEM_PROMPT_FILE"]);
const interactive = run("pi", { MOSAIC_INTERACTIVE: "1" });
assert.equal(interactive.status, 0, interactive.stderr);
assert.doesNotMatch(interactive.stderr, /MOSAIC_PI_FINAL_STOP/);
});
// --- run-task prints the cause of a failed run ---------------------------------------------------
function runTask(t, dockerBody) {
const root = tmp(t), f = fixture(root), bin = join(root, "bin");
mkdirSync(bin);
writeFileSync(join(bin, "docker"), `#!${process.execPath}\n${dockerBody}\n`, { mode: 0o755 });
f.env.PATH = `${bin}:${f.env.PATH}`;
const task = join(root, "task.json");
writeFileSync(task, JSON.stringify({ taskVersion: 1, id: "one", prompt: "request" }));
const r = spawnSync(process.execPath, [TASK, "run", task], { env: f.env, encoding: "utf8", timeout: 20000 });
const runs = join(f.dataRoot, "runs");
const [id] = readdirSync(runs);
return { r, id, record: JSON.parse(readFileSync(join(runs, id, "result.json"), "utf8")) };
}
test("run-task: a worker that stops on an error is a failed run whose cause the terminal shows", (t) => {
const { r, id, record } = runTask(t, 'process.stderr.write("pi stopped on an error: 401 invalid x-api-key\\n"); process.exit(1);');
assert.equal(r.status, 1, r.stderr);
assert.equal(record.status, "failed");
assert.equal(record.reason, "exit-nonzero");
assert.equal(r.stdout, `run: ${id}\nstatus: failed (exit-nonzero)\nresponse: \ncause: worker said: pi stopped on an error: 401 invalid x-api-key\n`);
});
test("run-task: a succeeded run prints no cause line", (t) => {
const { r, id, record } = runTask(t, 'console.log("normal response");');
assert.equal(r.status, 0, r.stderr);
assert.equal(record.status, "succeeded");
assert.equal(r.stdout, `run: ${id}\nstatus: succeeded\nresponse: normal response\n`);
});
+66 -15
View File
@@ -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>`;
@@ -42,22 +61,52 @@
<p data-autonomy-status role="status">${esc(s.status)}</p></form>
${s.writable?`<details data-autonomy-review-list${s.reviewOpen?' open':''}><summary${fk('review-list')}>Review reversals before moving out of the loop</summary><p>Read the decision trail and its reversals before recording your review.</p>${classes.map(k=>`<button class="btn" type="button" data-autonomy-review="${k}"${fk(`review-${k}`)}>Record review: ${labels[k]}</button>`).join('')}</details>`:''}</section>`;
}
// Decision notices on /inbox/<id>. The bus page draws that view again on every poll, and a decision the
// owner confirmed, returned or reversed leaves the inbox read, so its notice is gone from the next draw.
// The owner's result for each decision is kept here, in page memory, and the notice is drawn from it:
// the result line stays, a call in flight keeps its buttons off, and a notice whose decision has left
// the read is drawn with its result line only. A decision that comes back into the read after a draw
// saw it gone (an arbiter resolving it again) is a new question, so its old result is dropped.
const answers=new Map(),answerKey=(org,id)=>JSON.stringify([org,id]);
const noticeNode=(org,id)=>[...document.querySelectorAll('[data-autonomy-decision]')].find(n=>n.dataset.autonomyDecision===id&&n.dataset.autonomyOrg===org);
function notice(d) {
if(!d?.autonomy)return '';
const a=d.autonomy,org=d.business??window.MosaicOrg?.id;
return `<section class="panel" data-autonomy-decision="${esc(d.id)}" data-autonomy-org="${esc(org??'')}"><h2>${a.pending?'Confirm the arbiter resolution':'Decision near the loop'}</h2>
${a.pending?'<p>The arbiter resolved this decision. It has no effect until you confirm.</p><label>Reason for returning to the arbiter<input data-autonomy-reason maxlength="500"></label><p><button class="btn" data-autonomy-confirm="yes">Confirm resolution</button> <button class="btn" data-autonomy-confirm="no">Return to arbiter</button></p>':`<p>The agent resolved this decision. Reverse is available until ${esc(a.reverseUntil)}. A reverse cannot undo messages, work already done or code already shipped.</p><button class="btn" data-autonomy-reverse>Reverse decision</button>`}
<p role="status" data-autonomy-status></p></section>`;
if(!d)return '';
const org=d.business??window.MosaicOrg?.id??'',k=answerKey(org,d.id);
let kept=answers.get(k);
if(kept&&!kept.busy){if(!d.autonomy)kept.gone=true;else if(kept.gone){answers.delete(k);kept=undefined;}}
const line=`<p role="status" data-autonomy-status>${esc(kept?.text??'')}</p>`;
const open=`<section class="panel" data-autonomy-decision="${esc(d.id)}" data-autonomy-org="${esc(org)}">`;
if(!d.autonomy)return kept?`${open}<h2>${esc(kept.title)}</h2>${line}</section>`:'';
const a=d.autonomy,off=kept?.busy?' disabled':'';
return `${open}<h2>${a.pending?'Confirm the arbiter resolution':'Decision near the loop'}</h2>
${a.pending?`<p>The arbiter resolved this decision. It has no effect until you confirm.</p><label>Reason for returning to the arbiter<input data-autonomy-reason maxlength="500"></label><p><button class="btn" data-autonomy-confirm="yes"${off}>Confirm resolution</button> <button class="btn" data-autonomy-confirm="no"${off}>Return to arbiter</button></p>`:`<p>The agent resolved this decision. Reverse is available until ${esc(a.reverseUntil)}. A reverse cannot undo messages, work already done or code already shipped.</p><button class="btn" data-autonomy-reverse${off}>Reverse decision</button>`}
${line}</section>`;
}
// A notice's result: kept for the next draw, and written to the notice the page draws now.
function told(org,id,text) {
const k=answerKey(org,id);answers.set(k,{...answers.get(k),busy:false,text});
const node=noticeNode(org,id);if(!node)return;
const line=node.querySelector('[data-autonomy-status]');if(line)line.textContent=text;
for(const b of node.querySelectorAll('[data-autonomy-confirm],[data-autonomy-reverse]'))b.disabled=false;
}
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';};
@@ -67,12 +116,14 @@
document.addEventListener('toggle',e=>{if(!e.target.matches?.('[data-autonomy-review-list]'))return;const s=states.get(e.target.closest('[data-autonomy-org]')?.dataset.autonomyOrg);if(s)s.reviewOpen=e.target.open;},true);
document.addEventListener('click',async e=>{
const button=e.target.closest('[data-autonomy-confirm],[data-autonomy-reverse],[data-autonomy-review]');if(!button)return;
const section=button.closest('[data-autonomy-org]'),org=section.dataset.autonomyOrg,status=section.querySelector('[data-autonomy-status]');
const section=button.closest('[data-autonomy-org]'),org=section.dataset.autonomyOrg,id=section.dataset.autonomyDecision;
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}:{})};
const body=review?{decisionClass:review}:reverse?{id}:{id,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;}
// A notice takes one answer at a time: both of its buttons stay off until this one is told.
if(!review){const k=answerKey(org,id);answers.set(k,{text:'',...answers.get(k),title:section.querySelector('h2')?.textContent??'',busy:true});for(const b of section.querySelectorAll('[data-autonomy-confirm],[data-autonomy-reverse]'))b.disabled=true;}
try{const r=await call(org,review?'review':reverse?'reverse':'confirm',body);if(review)return say(org,'Trail review recorded.');told(org,id,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 told(org,id,error.message);}finally{button.disabled=false;}
});
window.MosaicAutonomy={load,section,notice};
})();
+3
View File
@@ -751,6 +751,9 @@
return `<li class="s1-opt"><p><b class="s1-key">${txt(o.key)}</b> ${txt(o.text)} ${approving ? badge(`approves ${d.authorization.action}`, 'attn') : ''}${o.key === d.recommendation ? badge('recommended', 'ok') : ''}${chosen ? badge('chosen', 'ok') : ''}</p>${copy}</li>`;
}).join('')}</ol>`;
const earlier = await chain(get, d);
// A newer draw may have begun while the earlier versions were read. This one is dropped, so stop
// here: the notice below keeps the owner's results, and only a draw that lands may change them.
if (!current()) return '';
const history = [...d.seen.map(s => `<li>Seen by ${txt(s.by)}${s.via ? ` via ${txt(s.via)}` : ''} ${when(s.at)}</li>`), ...(c ? [`<li>${esc(c.op)} by ${txt(c.by)}${c.via ? ` via ${txt(c.via)}` : ''} ${when(c.at)}</li>`] : [])];
// Without SSO, or under SSO without --send, the Console says why it has no buttons and never
// draws a disabled one (design section 5).
+13 -9
View File
@@ -767,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) {
@@ -812,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.
@@ -936,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.',
};
@@ -953,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 : [];
@@ -1900,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;
}
@@ -1978,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.
+17 -9
View File
@@ -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) {
+21 -7
View File
@@ -15,22 +15,35 @@
// draft holds the typed fields; base is the revision they were read at, which a save sends, so a
// change saved elsewhere since then answers as stale instead of being written over.
let data = null, readLine = '', draft = null, base = 0, busy = false, line = '', conflict = false;
// Reads answer in any order. began numbers each read as it starts. shown is the newest read or save
// the page has drawn its route from, and keyShown the newest read or key change it has drawn its key
// state from. A read older than shown is dropped, so a slow read cannot put back the route and
// revision a save or a newer read replaced. A read older than keyShown takes the key state the page
// holds instead of its own: a key change does not touch the route, so the read's route still stands.
// That key state is kept in key, apart from data, so a failed read that clears data keeps it.
let began = 0, shown = 0, keyShown = 0, key;
const call = init => window.fetch(PATH, { cache: 'no-store', redirect: 'manual', ...init });
// The stored route's fields, or empty ones: there is no default model, harness, cap or zone.
const fromRoute = r => ({ model: r?.model ?? '', harness: r?.harness ?? '', cap: r ? String(r.cap) : '', timeZone: r?.timeZone ?? '' });
// It says whether the page took this read (false when a newer read or write had drawn first).
async function read() {
readLine = '';
const n = ++began;
const failed = text => { if (n < shown) return false; shown = n; data = null; readLine = text; return true; };
let r, a = null;
try { r = await call({ method: 'GET' }); } catch { data = null; readLine = 'The Triage route could not be read. Reload the page to try again.'; return; }
try { r = await call({ method: 'GET' }); } catch { return failed('The Triage route could not be read. Reload the page to try again.'); }
try { a = await r.json(); } catch { /* refused below */ }
if (r.type === 'opaqueredirect') { data = null; readLine = 'Sign in again, then reload.'; return; }
if (!r.ok || !a || typeof a !== 'object') { data = null; readLine = typeof a?.message === 'string' ? a.message : 'The Triage route could not be read.'; return; }
if (r.type === 'opaqueredirect') return failed('Sign in again, then reload.');
if (!r.ok || !a || typeof a !== 'object') return failed(typeof a?.message === 'string' ? a.message : 'The Triage route could not be read.');
if (n < shown) return false;
shown = n; readLine = '';
// An untouched page follows the store; typed fields stay, with the revision they were read at.
const untouched = draft === null || JSON.stringify(draft) === JSON.stringify(fromRoute(data?.route ?? null));
if (n < keyShown) a = { ...a, access: key }; else { keyShown = n; key = a.access; }
data = a;
if (untouched) { draft = fromRoute(a.route); base = Number.isSafeInteger(a.revision) ? a.revision : 0; }
return true;
}
const models = () => (Array.isArray(data?.choices?.models) ? data.choices.models : []);
@@ -99,7 +112,7 @@
catch { busy = false; accessLine = 'Outcome unknown. Reload the page to see the key state.'; repaint(); return; }
try { a = await r.json(); } catch { /* refused below */ }
busy = false;
if (a?.access && data) data = { ...data, access: a.access };
if (a?.access && data) { data = { ...data, access: a.access }; key = a.access; keyShown = ++began; }
if (r.type === 'opaqueredirect') accessLine = 'Sign in again, then retry.';
else if (r.ok) accessLine = ACTION_LINE[a?.key?.action] ?? (op === 'off' ? 'Triage is off.' : 'Access was repaired.');
else accessLine = typeof a?.message === 'string' ? a.message : 'The Triage key was not changed.';
@@ -131,6 +144,7 @@
busy = false;
if (r.ok && a?.route) {
data = { ...data, route: a.route, revision: a.revision, routeMessage: undefined };
shown = ++began;
draft = fromRoute(a.route); base = a.revision;
line = `Saved ${savedAt(a.route.updatedAt)}.` + (a.key?.error ? ` ${a.key.message}` : ACTION_LINE[a.key?.action] ? ` ${ACTION_LINE[a.key.action]}` : '');
repaint();
@@ -147,8 +161,8 @@
async function reload() {
if (busy) return;
draft = null; conflict = false; line = '';
await read();
line = data ? 'Route read again. Your fields now show the stored route.' : '';
// A save that landed while this read was out has drawn the newer route and its receipt; keep both.
if (await read()) line = data ? 'Route read again. Your fields now show the stored route.' : '';
repaint();
}
+10 -2
View File
@@ -60,18 +60,26 @@
w.epoch++; w.inflight++;
try { return await fn(); } finally { w.inflight--; w.epoch++; }
}
// Two reads with no write between them can still answer out of order (the dashboard card and the page,
// or a poll and a navigation). Each organization numbers its reads as they start; a read that answers
// after a newer one has been kept is dropped, so an older answer cannot put back what a newer one replaced.
const reads = new Map();
const readOrder = org => { if (!reads.has(org)) reads.set(org, { began: 0, kept: 0 }); return reads.get(org); };
async function load(org) {
const prev = states.get(org), w = writeState(org), began = w.epoch;
const order = readOrder(org), n = ++order.began;
const s = { data: null, known: new Set(), error: null };
const raced = () => !!prev?.data && (w.inflight > 0 || w.epoch !== began);
try { await read(org, s); if (raced()) return; } catch (error) {
if (raced()) return;
const older = () => n < order.kept;
try { await read(org, s); if (raced() || older()) return; } catch (error) {
if (raced() || older()) return;
// Review P3: a failed poll while a change to this organization's workflows is held keeps the last good
// read, so the page still draws the change and its form, and graftLive puts the held form and focus back.
// SP17: the failure is still said; the page draws the last read under that line.
if (prev?.data && held(org).length) Object.assign(s, { data: prev.data, known: prev.known, readError: error.message });
else s.error = error.message;
}
order.kept = n;
states.set(org, s);
}
const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])];
@@ -51,3 +51,262 @@ 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="&quot;${'c'.repeat(64)}&quot;"`),'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);
});
// The decision notice on #/orgs/<org>/inbox/<id>. The bus page draws that view again on every poll (and on a
// fresh config, which is how these tests ask for a draw), and a decision the owner confirmed, returned or
// reversed leaves the inbox read, as the broker's inbox does. The owner's result must stay on the notice.
const decisionId='10000000-0000-4000-8000-0000000000d1';
const earlierId='10000000-0000-4000-8000-0000000000d0';
async function noticeFixture(t,gates,{autonomy,supersedes=false}){
const state={confirms:0,reverses:0,refuse:null,inbox:true};
const row=()=>({...(supersedes?{supersedes:earlierId}:{}),id:decisionId,business:'acme',at:'2026-11-11T12:00:00.000Z',class:'gated',action:'git.merge.protected',route_to:'cto',raised_by_role:'coder',raised_by_run:'coder-run',question:'Land the reviewed change?',options:[{key:'yes',text:'Land'},{key:'no',text:'Revise'}],recommendation:'yes',blocking:false,autonomy});
const answer=(verb,args)=>{
if(state.refuse){const code=state.refuse;state.refuse=null;throw Object.assign(new Error(code),{code});}
if(verb==='decision.confirm.console'){state.confirms++;state.inbox=false;return {op:args.confirm?'confirmed':'declined'};}
if(verb==='decision.reverse.console'){state.reverses++;state.inbox=false;return {reversed:true};}
throw Object.assign(new Error('not-configured'),{code:'not-configured'});
};
// The answer (or refusal) is settled when the call arrives; a held call gives it on release().
const call=async(verb,args)=>{let value,error;try{value=answer(verb,args);}catch(e){error=e;}const held=gates.take(verb);if(held){held.reached();await held.wait;}if(error)throw error;return value;};
// The earlier version's trail read, which a draw of a superseding decision waits on, can be held.
const earlier=async()=>{const held=gates.take('trail:earlier');if(held){held.reached();await held.wait;}return [{id:earlierId,business:'acme',at:'2026-11-11T11:00:00.000Z',class:'gated',action:'git.merge.protected',route_to:'cto',raised_by_role:'coder',raised_by_run:'coder-run',question:'Land the earlier change?',options:[{key:'yes',text:'Land'}],recommendation:'yes',blocking:false,table:'decisions'}];};
const trail=async id=>id===earlierId?earlier():[{...row(),table:'decisions'},{table:'events',kind:'action.allowed',body:{operation:'decision.raise',decision:id,approvalChoice:'yes',target:'vikunja:1/2'}}];
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()=>state.inbox?[row()]:[],trail,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/inbox/${decisionId}`);
await waitFor(b,`document.querySelector('[data-autonomy-decision] button')`);
return {b,state};
}
// Draw the decision view again, the way a bus restart's fresh config does, and wait until it has drawn.
const drawAgain=async b=>{
await b.evaluate(`document.querySelector('[aria-labelledby=b-q]').dataset.drawn='before';true`);
await b.evaluate(`fetch('/api/config',{cache:'no-store'}).then(r=>r.json()).then(c=>document.dispatchEvent(new CustomEvent('mosaic-config',{detail:c})));true`);
await waitFor(b,`document.querySelector('[aria-labelledby=b-q]') && !document.querySelector('[aria-labelledby=b-q]').dataset.drawn`);
};
const noticeLine=b=>b.evaluate(`document.querySelector('[data-autonomy-decision] [data-autonomy-status]')?.textContent ?? null`);
const noticeButtons=b=>b.evaluate(`[...document.querySelectorAll('[data-autonomy-decision] button')].map(x=>[x.textContent,x.disabled])`);
test('AU decision notice: a confirm that answers after a redraw is said, and stays after the decision leaves the inbox',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await noticeFixture(t,gates,{autonomy:{pending:true}});
const confirm=gates.hold('decision.confirm.console');
await b.evaluate(`document.querySelector('[data-autonomy-confirm=yes]').click();true`);await confirm.arrived;
// The broker has recorded the confirm, so the inbox read no longer carries the decision's marker. A draw while
// the answer is still on its way keeps the notice, with no button to answer twice.
await drawAgain(b);
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-decision] h2')?.textContent ?? null`),'Confirm the arbiter resolution','a redraw in flight keeps the notice');
assert.deepEqual(await noticeButtons(b),[],'a redrawn notice takes no second answer while one is in flight');
confirm.release();
await waitFor(b,`/^Confirmation recorded/.test(document.querySelector('[data-autonomy-decision] [data-autonomy-status]')?.textContent)`);
assert.equal(state.confirms,1);
// The confirmed decision has left the inbox read. The next draw keeps the notice and its result line.
await drawAgain(b);
assert.equal(await noticeLine(b),'Confirmation recorded. Refresh the inbox for current state.','the redraw keeps the result');
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-decision] h2').textContent`),'Confirm the arbiter resolution');
assert.deepEqual(await noticeButtons(b),[],'a decision that left the read offers no answer');
});
test('AU decision notice: a reverse result stays on the next draws',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await noticeFixture(t,gates,{autonomy:{notice:true,reverseUntil:'2099-01-01T00:00:00Z'}});
await b.evaluate(`document.querySelector('[data-autonomy-reverse]').click();true`);
await waitFor(b,`document.querySelector('[data-autonomy-decision] [data-autonomy-status]')?.textContent==='Reversal recorded.'`);
assert.equal(state.reverses,1);
await drawAgain(b);
assert.equal(await noticeLine(b),'Reversal recorded.','the first redraw keeps the result');
await drawAgain(b);
assert.equal(await noticeLine(b),'Reversal recorded.','a later redraw keeps the result');
});
test('AU decision notice: a refused confirm is kept on the redrawn notice, with its buttons on',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await noticeFixture(t,gates,{autonomy:{pending:true}});
state.refuse='storage-refused';
const confirm=gates.hold('decision.confirm.console');
await b.evaluate(`document.querySelector('[data-autonomy-confirm=yes]').click();true`);await confirm.arrived;
assert.deepEqual(await noticeButtons(b),[['Confirm resolution',true],['Return to arbiter',true]],'the notice takes one answer at a time');
// A refusal leaves the decision in the inbox read. A draw while it is in flight keeps the buttons off.
await drawAgain(b);
assert.deepEqual(await noticeButtons(b),[['Confirm resolution',true],['Return to arbiter',true]],'a redrawn notice takes no second answer while one is in flight');
confirm.release();
await waitFor(b,`/trail write was refused/.test(document.querySelector('[data-autonomy-decision] [data-autonomy-status]')?.textContent)`);
await drawAgain(b);
assert.equal(await noticeLine(b),'The trail write was refused. Inspect the decision trail before retrying.','the redraw keeps the refusal');
assert.deepEqual(await noticeButtons(b),[['Confirm resolution',false],['Return to arbiter',false]],'the decision is still open, so it can be answered again');
assert.equal(state.confirms,0);
});
test('AU decision notice: a returned decision that comes back to the inbox draws a fresh notice',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await noticeFixture(t,gates,{autonomy:{pending:true}});
await b.evaluate(`document.querySelector('[data-autonomy-confirm=no]').click();true`);
await waitFor(b,`/^Returned to arbiter/.test(document.querySelector('[data-autonomy-decision] [data-autonomy-status]')?.textContent)`);
assert.equal(state.confirms,1);
// The returned decision has left the inbox read. The next draw keeps the result line.
await drawAgain(b);
assert.equal(await noticeLine(b),'Returned to arbiter. Refresh the inbox for current state.','the redraw keeps the result');
// The arbiter resolves it again, so it is back in the inbox and waits for a new answer.
state.inbox=true;
await drawAgain(b);
assert.equal(await noticeLine(b),'','the old result is not shown on the new question');
assert.deepEqual(await noticeButtons(b),[['Confirm resolution',false],['Return to arbiter',false]]);
});
test('AU decision notice: a draw that a newer draw replaced does not drop the result',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await noticeFixture(t,gates,{autonomy:{pending:true},supersedes:true});
// Count the earlier-version trail answers the page has taken.
await b.evaluate(`(()=>{const prev=window.fetch;window.__earlier=0;window.fetch=(input,init)=>{const p=prev(input,init);if(!String(input).includes(${JSON.stringify(earlierId)}))return p;return p.then(r=>{const json=r.json.bind(r);r.json=()=>json().then(v=>{setTimeout(()=>{window.__earlier++;});return v;});return r;});};return true;})()`);
// A draw starts while the decision is still in the inbox, and waits on the earlier version's trail.
const slow=gates.hold('trail:earlier');
await b.evaluate(`fetch('/api/config',{cache:'no-store'}).then(r=>r.json()).then(c=>document.dispatchEvent(new CustomEvent('mosaic-config',{detail:c})));true`);
await slow.arrived;
await b.evaluate(`document.querySelector('[data-autonomy-confirm=yes]').click();true`);
await waitFor(b,`/^Confirmation recorded/.test(document.querySelector('[data-autonomy-decision] [data-autonomy-status]')?.textContent)`);
assert.equal(state.confirms,1);
// A newer draw reads the decision gone and draws the result. Then the replaced draw gets its answer.
await drawAgain(b);
assert.equal(await noticeLine(b),'Confirmation recorded. Refresh the inbox for current state.');
const taken=await b.evaluate('window.__earlier');
slow.release();
await waitFor(b,`window.__earlier===${taken+1}`);
await drawAgain(b);
assert.equal(await noticeLine(b),'Confirmation recorded. Refresh the inbox for current state.','the replaced draw does not drop the result');
});
@@ -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');
@@ -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 } } });
@@ -265,3 +265,160 @@ test('shots', { timeout: 300000, skip: !process.env.MOSAIC_UX_SHOTS }, async t =
}
for (const r of results) { assert.deepEqual(r.errors, [], r.full); assert.deepEqual(r.unexpected, [], r.full); }
});
// A read of the route that answers after a save or key change. bus.js reads the route each time the
// owner opens the page, and only then (a poll does not redraw it). An owner who opens Triage, leaves
// while the read is slow and opens it again gets a second read; the first one can answer last. The
// fixture answers a read as it arrives, so the held read carries the store as it was then. release()
// lets the page have it, and __consumed is set once the page has taken its answer.
const holdNextRead = b => b.evaluate('(()=>{const prev=window.fetch;window.__held=null;window.__consumed=false;window.__arm=true;window.fetch=(input,init)=>{const path=new URL(typeof input==="string"?input:input.url,location.href).pathname;if(window.__arm&&path==="/api/triage/route"&&(init?.method??"GET")==="GET"){window.__arm=false;const answer=prev(input,init).then(r=>{const json=r.json.bind(r);r.json=()=>json().then(v=>{setTimeout(()=>{window.__consumed=true;});return v;});return r;});return new Promise(r=>{window.__held=()=>r(answer);});}return prev(input,init);};return true;})()');
const stored2 = (over, revision) => ({ ...unset, route: route({ revision, ...over }), routeMessage: undefined, revision });
// Open Triage with its read held, leave, and open it again: the second read draws the page.
async function slowFirstVisit(b, wait) {
await b.evaluate('location.hash="#/settings/appearance"');
await wait('!document.getElementById("triage-route")');
await holdNextRead(b);
await b.evaluate('location.hash="#/settings/triage"');
await wait('typeof window.__held==="function"');
await b.evaluate('location.hash="#/settings/appearance"');
await wait('document.getElementById("settings-page-title")?.textContent==="Appearance"');
await b.evaluate('location.hash="#/settings/triage"');
await wait('document.getElementById("triage-route-cap")');
}
// Repaint the panel from the page's memory, as a model change does.
const repaintPanel = b => pick(b, 'triage-route-model', 'sonnet');
test('a read that answers after a save keeps the saved route and revision, so the next save is not stale', { timeout: 90000 }, async t => {
const saved = route({ cap: 9000, revision: 2 });
const { f, b, wait } = await w15Fixture(t, { scenario: scenario(stored2({}, 1), { 'POST /api/triage/route': { body: { route: saved, revision: 2, note: NOTE } } }) });
await b.navigate(f.base + '/#/settings/triage');
await wait('document.getElementById("triage-route-stored")?.dataset.revision==="1"');
await slowFirstVisit(b, wait);
// The held read left with revision 1. The owner saves on the page the second read drew.
await type(b, 'triage-route-cap', '9000');
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify(stored2({ cap: 9000 }, 2))}`);
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="2"');
await b.evaluate('window.__held();true');
await wait('window.__consumed===true');
await repaintPanel(b);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '2', 'the older read does not put back revision 1');
assert.equal(await value(b, 'triage-route-cap'), '9000', 'the older read does not put back the old route');
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('window.__writes.filter(w=>w.path==="/api/triage/route").length===2');
assert.equal((await writes(b)).at(-1).body.revision, 2, 'the next save sends the saved revision');
assert.deepEqual(await b.evaluate('window.__errors'), []);
});
test('a read that answers after a key change keeps the new key state', { timeout: 90000 }, async t => {
const before = { key: 'missing' }, after = { key: 'issued', keyId: 'k-2', rotateBy: '2026-12-18' };
const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...stored2({}, 1), access: before }, { 'POST /api/triage/access': { body: { access: after, key: { action: 'issued' } } } }) });
await b.navigate(f.base + '/#/settings/triage');
await wait('document.getElementById("triage-access")?.dataset.key==="missing"');
await slowFirstVisit(b, wait);
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify({ ...stored2({}, 1), access: after })}`);
await b.evaluate('document.getElementById("triage-access-repair").click()');
await wait('document.getElementById("triage-access-line")?.textContent==="A Triage key was issued." && document.getElementById("triage-access")?.dataset.key==="issued"');
await b.evaluate('window.__held();true');
await wait('window.__consumed===true');
await repaintPanel(b);
assert.equal(await b.evaluate('document.getElementById("triage-access").dataset.key'), 'issued', 'the older read does not put back the missing key');
assert.deepEqual(await b.evaluate('window.__errors'), []);
});
test('a Reload route read that answers after a save keeps the saved route, its receipt and its revision', { timeout: 90000 }, async t => {
const message = 'The Triage route changed since this page read it. Reload the route, then save again.';
const { f, b, wait } = await w15Fixture(t, { scenario: scenario(stored2({}, 1), { 'POST /api/triage/route': { status: 409, body: { error: 'triage-route-stale', message, revision: 3 } } }) });
await b.navigate(f.base + '/#/settings/triage');
await wait('document.getElementById("triage-route-stored")?.dataset.revision==="1"');
await type(b, 'triage-route-cap', '5000');
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`);
// Reload route reads revision 3, held. The owner types the route again and saves before it answers.
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify(stored2({ cap: 3 }, 3))}`);
await holdNextRead(b);
await b.evaluate('document.getElementById("triage-route-reload").click()');
await wait('typeof window.__held==="function"');
const saved = route({ harness: 'claude-code', cap: 150000, timeZone: 'America/Chicago', revision: 4 });
await b.evaluate(`window.__scenario['POST /api/triage/route'] = {body: {route: ${JSON.stringify(saved)}, revision: 4, note: ${JSON.stringify(NOTE)}}}`);
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify(stored2({ harness: 'claude-code', cap: 150000, timeZone: 'America/Chicago' }, 4))}`);
await fill(b);
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="4"');
const receipt = await text(b, 'triage-route-line');
await b.evaluate('window.__held();true');
await wait('window.__consumed===true');
await repaintPanel(b);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '4', 'the reload read does not put back revision 3');
assert.equal(await value(b, 'triage-route-cap'), '150000');
assert.equal(await text(b, 'triage-route-line'), receipt, 'the save receipt stays');
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('window.__writes.filter(w=>w.path==="/api/triage/route").length===3');
assert.equal((await writes(b)).at(-1).body.revision, 4, 'the next save sends the saved revision');
assert.deepEqual(await b.evaluate('window.__errors'), []);
});
test('a Reload route read that answers after a key change keeps the new key state', { timeout: 90000 }, async t => {
const message = 'The Triage route changed since this page read it. Reload the route, then save again.';
const before = { key: 'missing' }, after = { key: 'issued', keyId: 'k-2', rotateBy: '2026-12-18' };
const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...stored2({}, 1), access: before }, { 'POST /api/triage/route': { status: 409, body: { error: 'triage-route-stale', message, revision: 1 } }, 'POST /api/triage/access': { body: { access: after, key: { action: 'issued' } } } }) });
await b.navigate(f.base + '/#/settings/triage');
await wait('document.getElementById("triage-access")?.dataset.key==="missing"');
await type(b, 'triage-route-cap', '5000');
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`);
// Reload route reads revision 3 and the missing key, held. The owner repairs access before it answers.
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify({ ...stored2({ cap: 3 }, 3), access: before })}`);
await holdNextRead(b);
await b.evaluate('document.getElementById("triage-route-reload").click()');
await wait('typeof window.__held==="function"');
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify({ ...stored2({ cap: 3 }, 3), access: after })}`);
await b.evaluate('document.getElementById("triage-access-repair").click()');
await wait('document.getElementById("triage-access-line")?.textContent==="A Triage key was issued." && document.getElementById("triage-access")?.dataset.key==="issued"');
await b.evaluate('window.__held();true');
await wait('window.__consumed===true');
// A key change does not touch the route, so the reload still draws the route it read, with the new key.
assert.equal(await b.evaluate('document.getElementById("triage-access").dataset.key'), 'issued', 'the reload read does not put back the missing key');
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '3', 'the reload read draws the stored revision');
assert.equal(await value(b, 'triage-route-cap'), '3', 'the fields show the stored route');
assert.equal(await text(b, 'triage-route-line'), 'Route read again. Your fields now show the stored route.');
assert.equal(await b.evaluate('document.getElementById("triage-route-reload")'), null);
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('window.__writes.filter(w=>w.path==="/api/triage/route").length===2');
assert.equal((await writes(b)).at(-1).body.revision, 3, 'the next save sends the revision the reload read');
assert.deepEqual(await b.evaluate('window.__errors'), []);
});
// Hold the next two route reads. Each answers as it arrives (so it carries the store as it was then);
// __holds[i].release() lets the page have it and __holds[i].fail() fails it as a network error does.
// __taken counts the reads the page has taken, answered or failed.
const holdTwoReads = b => b.evaluate('(()=>{const prev=window.fetch;window.__holds=[];window.__taken=0;window.fetch=(input,init)=>{const path=new URL(typeof input==="string"?input:input.url,location.href).pathname;if(window.__holds.length<2&&path==="/api/triage/route"&&(init?.method??"GET")==="GET"){const answer=prev(input,init).then(r=>{const json=r.json.bind(r);r.json=()=>json().then(v=>{setTimeout(()=>{window.__taken++;});return v;});return r;});return new Promise((ok,no)=>{window.__holds.push({release:()=>ok(answer),fail:()=>{answer.catch(()=>{});setTimeout(()=>{window.__taken++;});no(new TypeError("Failed to fetch"));}});});}return prev(input,init);};return true;})()');
test('a Reload route read that fails after a key change does not let an older read put back the old key state', { timeout: 90000 }, async t => {
const message = 'The Triage route changed since this page read it. Reload the route, then save again.';
const before = { key: 'missing' }, after = { key: 'issued', keyId: 'k-2', rotateBy: '2026-12-18' };
const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...stored2({}, 1), access: before }, { 'POST /api/triage/route': { status: 409, body: { error: 'triage-route-stale', message, revision: 3 } }, 'POST /api/triage/access': { body: { access: after, key: { action: 'issued' } } } }) });
await b.navigate(f.base + '/#/settings/triage');
await wait('document.getElementById("triage-access")?.dataset.key==="missing"');
await type(b, 'triage-route-cap', '5000');
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`);
// Two clicks on Reload route, both reads held with the missing key. Repair access lands first.
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify({ ...stored2({ cap: 3 }, 3), access: before })}`);
await holdTwoReads(b);
await b.evaluate('document.getElementById("triage-route-reload").click()');
await wait('window.__holds.length===1');
await b.evaluate('document.getElementById("triage-route-reload").click()');
await wait('window.__holds.length===2');
await b.evaluate(`window.__scenario['/api/triage/route'] = ${JSON.stringify({ ...stored2({ cap: 3 }, 3), access: after })}`);
await b.evaluate('document.getElementById("triage-access-repair").click()');
await wait('document.getElementById("triage-access-line")?.textContent==="A Triage key was issued." && document.getElementById("triage-access")?.dataset.key==="issued"');
// The first read fails, so the page says the route could not be read. The second then answers.
await b.evaluate('window.__holds[0].fail();true');
await wait('window.__taken===1');
await b.evaluate('window.__holds[1].release();true');
await wait('window.__taken===2');
assert.equal(await b.evaluate('document.getElementById("triage-access")?.dataset.key ?? null'), 'issued', 'the older read does not put back the missing key');
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '3', 'the newer read draws its route');
assert.deepEqual(await b.evaluate('window.__errors'), []);
});
@@ -55,6 +55,7 @@ function store(writable) {
st.view = org => (st.down[org.id] ? { ...org, busHealthy: false, ...(st.down[org.id] === 'stopped' ? { busStopped: true } : {}) } : org);
// SP17: hold('read') holds the next workflow read, which answers with the file as it was when the read
// began; hold('write') holds the next write before it reaches the file. Each returns the release.
// st.onHeld, when set, is called as a held read arrives.
st.hold = which => { let open; st.held[which] = new Promise(r => { open = r; }); return open; };
const fail = code => Object.assign(new Error(code), { code });
st.write = (id, verb, args) => {
@@ -86,9 +87,11 @@ function organizations(reads, st) {
const org = LIST.find(o => o.id === id); if (!org) return null;
const workflowsRead = async () => {
reads.push(id);
if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' });
const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer', 'triage'] };
const h = st.held.read; if (h) { st.held.read = null; await h; }
// The answer, or the refusal, is settled as the read arrives; a held read gives it on release.
const error = st.failRead ? Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }) : null;
const answer = error ? null : { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer', 'triage'] };
const h = st.held.read; if (h) { st.held.read = null; st.onHeld?.(); await h; }
if (error) throw error;
return answer;
};
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, workflowsRead, chat: { projects: async () => [], threads: async () => [] } };
@@ -1040,3 +1043,40 @@ test('SP17: the bar Save with a new step typed in the add form says so and keeps
await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved');
assert.deepEqual(st.writes.at(-1).args.workflow.steps.map(s => [s.title, s.roles]), [['Build it', ['coder']], ['Check', ['human']], ['Ship', ['human']]]);
});
// Two reads with no write between them: the older one answers last. The page keeps the newer read, so what
// it draws next and the revision its next Save sends come from the newer read. A fetch wrapper in the page
// counts each workflow read the page has taken, so the test knows when the older one landed.
const countTaken = b => b.evaluate(`(()=>{const prev=window.fetch;window.__wfTaken=0;window.fetch=(input,init)=>{const url=typeof input==='string'?input:input.url;const p=prev(input,init);if(!/\\/workflows$/.test(new URL(url,location.href).pathname)||(init?.method??'GET')!=='GET')return p;return p.then(r=>{const json=r.json.bind(r);r.json=()=>json().finally(()=>setTimeout(()=>window.__wfTaken++));return r;});};return true})()`);
async function olderLast(t, { olderFails }) {
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' });
await wait(`${boxes}.length === 2 && document.querySelector('[data-wfg-detail]')`, 'site graph');
await countTaken(b);
const repaint = () => b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`);
// The older read takes the file as it is now (or is refused), and is held.
const arrived = new Promise(r => { st.onHeld = r; });
const openOld = st.hold('read');
st.failRead = olderFails;
await repaint();
await arrived;
st.failRead = false;
// Another writer changes this workflow. A newer read takes that and draws it.
st.change('acme', doc => { doc.projects.site.workflows.change.description = 'Changed elsewhere.'; });
const fresh = st.revs.acme;
await repaint();
await wait(`/Changed elsewhere\\./.test(document.querySelector('#bus-view .sub')?.textContent) && window.__wfTaken === 1`, 'newer read drawn');
// The older read answers last.
openOld();
await wait(`window.__wfTaken === 2`, 'older read taken');
assert.doesNotMatch(await b.evaluate(`window.MosaicWorkflows.card('acme')`), /data-wfg-error/, 'the page still holds a read');
assert.match(await b.evaluate(`window.MosaicWorkflows.card('acme')`), /data-wfg-card-step/);
await retitle(b, wait, 2, 'Ship the release');
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-stale]')`), null);
await b.evaluate(press('[data-wfg-save]'));
await wait(`/Saved change\\.|changed since this page read it/.test(${text('[data-wfg-status]')})`, 'save answered');
assert.equal(st.writes.length, 1);
assert.equal(st.writes[0].args.revision, fresh, 'the Save sends the revision the newer read took');
assert.match(await b.evaluate(text('[data-wfg-status]')), /Saved change\./);
}
test('an older workflow read that answers after a newer one does not put back what the newer one read', { timeout: 60000 }, t => olderLast(t, { olderFails: false }));
test('an older workflow read that fails after a newer one answered keeps the newer read', { timeout: 60000 }, t => olderLast(t, { olderFails: true }));
+3 -1
View File
@@ -536,7 +536,9 @@ async function runTask(taskFile, options = {}) {
writeOnce(path.join(runDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
if (!haltGeneration && !proc.error && proc.status === 0) unregisterRuntime(resolved.dataRoot, managed.id);
process.stdout.write(`run: ${runId}\nstatus: ${status}${reason ? ` (${reason})` : ""}\nresponse: ${response}\n`);
// worker-stop-reason: a failed run also says why on the terminal, with the line `show` prints.
const cause = status === "succeeded" ? null : runCause(resolved.dataRoot, runId, result);
process.stdout.write(`run: ${runId}\nstatus: ${status}${reason ? ` (${reason})` : ""}\nresponse: ${response}\n${cause ? `cause: ${cause}\n` : ""}`);
process.exit(status === "succeeded" ? 0 : 1);
}
+6
View File
@@ -40,4 +40,10 @@ fi
export MOSAIC_SYSTEM_PROMPT_FILE
# worker-stop-reason: a headless pi worker is judged by pi's final stop reason (adapters/pi/
# final-stop.mjs). Set for pi only, so the mock and other adapters see the environment they did.
if [ "$ADAPTER" = "pi" ] && [ "${MOSAIC_INTERACTIVE:-}" != "1" ]; then
export MOSAIC_PI_FINAL_STOP=1
fi
exec "$ADAPTER_SCRIPT"