Compare commits

..
Author SHA1 Message Date
jason.woltje 37c3854849 fix(model-proxy): settings-backend A1 review P3-1 and P3-3: a short Mosaic key glued to a word (xmso-..., _msk-...) is redacted by one added line after the copied key-prefix line, which the pin test now expects; a history entry whose redacted values, or keys and values, read together still hold an environment secret split across them is answered as { withheld: true }; comments name the split-key journal limit (P3-2) and the unmarked non-object answer (P3-9) (#1873, lane settings-backend-a1) 2026-11-19 21:09:58 -06:00
jason.woltje db2dc96aa2 feat(model-proxy): settings-backend A1: three instance-owner reads under /api/proxy/admin/ for Model setup: the model service's last log lines with keys and secrets removed (log), the service key's made-at time from proxy.json's mtime with no renewal yet (service-key), and setup history a page at a time (history); account writes through /api/proxy/* and an organization's proxy routes now join that history by label only; redaction is chat-fail's list with the mso-, mst- and msp- prefixes added, pinned to failure-notice.mjs (#1873, lane settings-backend-a1) 2026-11-19 21:09:58 -06:00
jason.woltje f666590d54 fix(proxy-scope): slice 4 review round 1: a save runs ensure only when it creates the route, so after Turn Triage off only Repair access brings a key back; the key walk stops at a bus whose outcome is unknown and the whole walk has one 30 s deadline; the status reads the same riding list the walk asks; a repeated sweep refusal is logged when it appears or changes and then once an hour; Off asks first and each key action has its own plain line; the host send-path test asserts the stop before it waits (#1873, lane proxy-scope-s4) 2026-11-19 20:41:55 -06:00
jason.woltje 2f20346719 feat(proxy-scope): slice 4: the bus issues, rotates and retires the Triage key through proxy.triage.key (op ensure or revoke), for the instance owner's path-bound proof only; a riding bus sweeps a due rotation or retirement under the instance proxy lock, re-reads the file, never issues the first key and does the work once across buses; the Console asks one riding organization's bus on the first save, Repair access and Off, shows triage-no-riding-bus and rotation overdue, and stops a session at its key's retireAt with triage-key-rotated; answers, events and receipts carry key ids only (#1873, lane proxy-scope-s4) 2026-11-19 20:41:55 -06:00
jason.woltje 524132b42b test(webui): settings-s4 review F1: each organization pick waits for the picker and changes it in one step, since a route change repaints the select; the final gate caught the select missing for a moment between a wait and the pick; the test still fails with the bus.js and display.js of e717824c5 (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje ae53b1988a feat(webui): settings-s4: an account row on Model setup shows why the account is not working, from the accounts read's reason field (chat-fail F3, a7362a8fc and later), as text beside its state; with no reason field, or an empty one, nothing shows; the test is red with the display.js of 12e99db49 (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 940ac53b65 test(webui): settings-s4 review: the picker from Model setup, Appearance and Organizations lands on #/settings/routing?org= (F1); the can't start mark and the step 3 words and Ride all line agree (F2); no paused mark with only a fence to clear (N8); every control under Advanced shows a focus ring before setup, and the fixture service reads healthy (N9); F1, F2 and N8 fail with the display.js and bus.js of e717824c5 (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 799df9cb9f fix(webui): settings-s4 review F2 and N8: an organization the sidebar marks "can't start" (stand-in models, bus stopped) is named on Model setup step 3 by its display name in the same words, with the fix (move it to your models, then start its bus), and its Ride all line and Move button use the display name; the paused mark needs the service itself down (not running or not listening), so a fence left to clear no longer marks organizations paused (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 23964b1224 fix(webui): settings-s4 review F1: the organization picker on a page that is not an organization's (Model setup, Appearance, Organizations) opens that organization's Routing page at #/settings/routing?org=<id>, so the address base no longer changes to #/orgs/<id>/ (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje d692ca9b81 fix(webui): settings-s4 review F3: Model setup drops what design section 10 removes: "Use my own key" and its key fields (the service key is always made on this machine, so init always sends generate), the key rotation grace field and its settings row, the Client keys table with its refresh button and the keys read, and the "Accounts and client keys loaded" line; the setup cleanup no longer clears the removed key fields; the Advanced help says Claude Code, not "the Claude harness" (N5); the tests that pinned the removed parts read the new page (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 57e86d9867 test(webui): settings-s4: tests that pinned the old addresses read the slice 4 ones: the dashboard's Model setup row and Triage's fix link open #/settings/model-setup, and the single-pane switch tests go to #/settings/<page>?org=beta (their #/orgs/acme/... starts still pass through the old-address redirect) (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje d502a75e57 test(webui): settings-s4: the Business settings test reads the slice 4 nav (You, Your models, This instance, This business with Business last) in place of the old Your browser and This instance list; Business is still in Settings and not in the sidebar, and still visible in the phone disclosure (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 15801ccb07 fix(webui): settings-s4: Model setup shows one primary button: a submit there reads as a plain button unless display.js marks it primary, so Finish sign-in and Check and add no longer look primary beside the card's own; the sign-in row wraps with a gap at 390; the test counts primaries by their drawn fill, and checks one primary while signing in and with the key form open (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 50ca7f0341 fix(webui): settings-s4 shots round: a progress line reads what happened at each step (done, under way, not started, or "did not finish" where the run stopped), so a failed step no longer reads "Starting the service…"; an account's health badge keeps its own width on a phone; the model search box has a placeholder; the slice 4 test file takes shots at 390 and 1440, light and dark, with MOSAIC_UX_SHOTS set, and checks sideways scroll, select fit and a visible focus ring on every control it tabs to (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje b9b3e56821 test(webui): settings-s4: nav groups, the picker and ?org= pages, the old addresses, the phone section button with no sideways scroll, the three sidebar marks, the one-press chain in order, a failed step with Try again and last lines, ?step=, account rows and the provider-picked add form with sign-in cancel and paste-back, Models offered read-only with search, and the done line with a removed organization; all 11 fail on 6c5ec23b4 (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 32b56b8351 feat(webui): settings-s4 sidebar marks: an organization whose models need a restart reads "needs restart" (◐), one on stand-in models whose bus can't start reads "can't start" (▲), and one riding a model service that is set up but not running reads "paused" (◐); restart and paused show only on a running bus; the dashboard's Model setup card links #/settings/model-setup; an organization's Settings page marks it in the sidebar (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje 78d1ef7705 feat(webui): settings-s4 Model setup: four step cards (Model service, Accounts and models, Organizations, Triage) with at most one primary button on the page; one press runs download, set up, install and start in order, each step once, reading the status after each, with a progress list; a step that fails stops with Try again and opens "The service's last lines"; done cards fold to their line, ?step=<card> opens one; accounts as rows with kind and a health badge, a provider select that offers "Sign in to <provider>" or "Check and add" for an API key, a cancellable sign-in with the paste-back form, and "Removing an account is not built yet."; Models offered read-only per provider with a count, a search box past eight and "Coming later"; Advanced and Technical details folded; the Ride all done line does not count an organization that turned the model service off; MosaicModelDots reads the setup status for the sidebar marks (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje af1bbf7859 feat(webui): settings-s4 nav and addresses: Settings nav in four groups (You; Your models with Model setup and, for the instance owner, Triage; All organizations; This organization with an organization picker above Models, Agents, Launch limits, Token use, Assistant and Organization file); an organization's pages live at #/settings/<page>?org=<id> and the old #/orgs/<id>/settings/<page> form lands there; #/settings/model-proxy opens Model setup at #/settings/model-setup; the phone section button reads "<Org> · <Page>"; the breadcrumb names the organization on its Settings pages; no Members row (#1873, lane settings-s4) 2026-11-19 18:49:24 -06:00
jason.woltje a7362a8fc5 test(webui): tasks-board: the fixture task is due in 2099, so the card still reads due, not overdue, after 20 Nov 2026 passes; the expected label carries the year (#1873, lane chat-fail) 2026-11-19 18:20:43 -06:00
jason.woltje 5a07f9e1f9 test(bus): chat-fail pickup-launch: the fixture runs its Claude model on claude-code, since a legacy Claude entry counts as OAuth and runs there only; the host launcher's env carries a stand-in session login, because claude-code's preflight needs one and this launcher boots with no proxy, and a stand-in adapter path skips only the binary check, so each launch still stops at the model gate with model-provider-unavailable and no assertion changed (#1873, lane chat-fail) 2026-11-19 17:08:06 -06:00
jason.woltje 07eca4a670 fix(chat-fail): review round 3: the link, email and mixed-run redaction patterns start only where a run without spaces starts, so redacting the whole kept stdout stays linear (a 128000-character run took 10 to 15 s, now a few ms) and matches the same text; a long text that redacts below the read limit is not cut and keeps its first word, and a cause that is only [redacted] is dropped; the proxy page reads relogin, plural and past forms of an expired sign-in as a sign-in (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje fc9e4dfca8 fix(chat-fail): review round 2: the F1 cause is redacted over the whole text before the tail cut, so a cut that lands between a key word and its value no longer shows the value; the account sign-in words in the proxy page match whole words only ("assigning" and "logging" no longer read as a sign-in) and a prefixed or "is expired" token counts (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje 10a35ce65a fix(chat-fail): review round 1: the F1 cause decodes %XX, HTML references and NFKC forms before the secret and redaction checks, redacts the value after a quoted or space-separated key word and Windows and UNC paths, and is read from the tail of the output, with the cause on the retry log line too; a launch-failed start posts only when the same message is refused twice, project-pending and processing-halted are waits, and a refused post is tried again and logged once; the proxy reason refuses an impossible date, checks quota_blocked before the message words and no longer reads a bare "expired" as a sign-in (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje 3b9cac5452 fix(bus): chat-fail F3: an account the proxy reports as unavailable or in error carries one plain reason with the next step, built only from the fields of the existing account read (requires_sign_in, refresh_error, quota_blocked, next_retry_after, and status_message matched against fixed patterns and never shown); with nothing more it says the model service gave no reason. No new proxy call; working, turned-off and unknown rows keep their exact fields (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje bc6d3565b0 fix(bus): chat-fail F2: a refused thread start and a proxy-stall stop each put one plain line in the chat, with the cause and next step, once per unanswered message and not once per retry; a start that only waits (a free place, a run still ending, a held lock, a lost race) puts none. The line comes from the launcher through a trusted launch op, not a socket verb, from the thread's instance with from_run bus, so no schema change and no new refusal code (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje 72ea7272ec fix(harness): chat-fail F1: the turn-failure code moves into the mounted harness failure-notice.mjs, so a sandboxed runner loads it; the separate file was outside RUNNER_FILES and every sandboxed run died with ERR_MODULE_NOT_FOUND (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje 27a359590e fix(harness): chat-fail F1: a failed turn's chat line carries the harness's error as a plain cause and next step, cleaned, redacted and capped, with the technical reason under it (#1873, lane chat-fail) 2026-11-19 16:36:16 -06:00
jason.woltje 6c5ec23b47 test(model-proxy): settings-p3 ride-fence: the launch fixture runs its Claude model on claude-code, since a legacy Claude entry counts as OAuth and runs there only; a stand-in adapter path skips only the binary check, so the before launch still reaches the limit checks and the fenced launch after Ride all is still refused with proxy-uncertain (#1873, lane settings-p3) 2026-11-19 15:44:31 -06:00
jason.woltje dd0a8612c8 fix(webui, model-proxy): settings-p3 review P2-1, P3-1 to P3-3: the done line counts an organization that can still ride, so an owner who can't send is not told every organization can see the models; an organization that took cliproxy during a Ride all run reads as already using it, not refused; the stopped page's refusal repaint is tested before the page renders again; a stand-in organization with no bus status (the single-business Console) reads that moving is not available there, with no Move button, from the status summary as well as after a run (#1873, lane settings-p3) 2026-11-19 15:16:59 -06:00
jason.woltje 9276277970 test(webui): settings-p3 shots: the Model setup shot shows the Ride all box below the restart list, with one organization that can ride, one skipped and one on stand-in models; a full-page shot grows the window to the page so the fixed footer covers nothing (#1873, lane settings-p3) 2026-11-19 15:04:56 -06:00
jason.woltje 517a3fe467 fix(webui): settings-p3 P3-1 to P3-11, rebase re-check 1 to 4, Routing help: Model setup says what to do for a held init lock or a partial init, with the README path under Technical details, and both lines are tested; the triage-drawer fixture case says its pair is synthetic; a model-key collision names a step; a fixture refusal leaves Restart on the stopped page but not primary; a ready catalogue the bus picked up late keeps its organization on Model setup's restart list with a Restart, holds the next step, and gets a Restart beside its notice on Routing; the README names the Model setup page; the NO_GUESS pin counts both uses; a reason that is not a stop reads "Last check:"; the why line sits under the headline; orgDownReason tells every waiting caller, each with its own name; the done line does not say every organization while the Ride all box lists one; Ride all is the next step only when the owner can send; the step button reads "Go to Ride all"; Ride all text says model service; the single-business fixture move says nothing about a bus it can't see; the Routing help names no harness (#1873, lane settings-p3) 2026-11-19 15:04:56 -06:00
jason.woltje 149712816b fix(model-proxy): settings-p3 R1, R2: Ride all reads each organization's file and change log again before its add, not only the receipts, so an add and remove saved on its Settings page during a run is not put back; a list that can't be read again, a change log that can't be read or an organization no longer listed skips the add as unreadable; with no bus status (the single-business Console) a fixture move answers not-available instead of bus-running, and whether its bus runs is unknown (#1873, lane settings-p3) 2026-11-19 15:04:56 -06:00
jason.woltje 4f63176676 test(triage): review round 5: a host bundle file replaced with a FIFO is refused before the host reads it (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje 1e0aba8b37 fix(triage): review round 4: the host refuses a pi command value (a string that starts with "!") in any file the module wrote, checks each host bundle file after env() whether or not the scan reaches it, and records ctime for the rest of the run directory (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje 680bb90af3 fix(triage): review round 3: the host checks every URL in a file the module wrote under bundle/, home/, work/ or tmp/, as written or as a URL parser reads it; refuses a backslash in a file JSON.parse refuses; refuses a change to its own bundle files or the rest of the run directory; and a refused start removes work/ and tmp/ too (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje 6a24cf743d test(triage): a declared harness file with a second hard link is refused (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje 06ee172a9d fix(triage): review round 2: the host reads every file under the run's bundle/, home/, work/ and tmp/ after bundle() and env(), refuses a link or a key there, and reads a JSON file decoded too, so an escaped key or URL is seen as the harness sees it (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje 66676804eb test(triage): write() refuses a bundle file that holds the key before the file exists, so the key never rests on disk until the scan (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje a3ad6578c4 fix(harness): review round: a legacy model entry (a provider or route name, no module) carries no account data, so a Claude-named model on it is treated as OAuth and held to claude-code; the Triage host refuses a key in any bundle/ file and any URL but the proxy's in a harness file; the models.json comment says what route() can and cannot see (#1873, lane harness-matrix) 2026-11-19 14:43:26 -06:00
jason.woltje 77a951cfe7 fix(harness): the harness rule keys on the account kind: a Claude model from an API key runs on claude-code and pi; an OAuth Claude model, or a group model whose name an OAuth Claude account offers, runs on claude-code only (#1873, lane harness-matrix)
Jason 2026-11-19: Claude models through an API key may run on any harness; OAuth Claude models only
on claude-code. The name check is gone. The catalogue reads every Claude OAuth account's model names,
whatever the account's state, and holds a group model with one of those names to claude-code, since
the proxy routes by name across every account. route() has no account data, so it holds upstream
claude only; admission and Triage hold the rest through the catalogue.
2026-11-19 14:43:26 -06:00
jason.woltje cd58ac23cd feat(harness): an OAuth Claude model runs on claude-code only; Triage runs on claude-code or pi through the proxy (#1873, lane harness-matrix)
cliproxy holds a model to claude-code when its upstream is claude, when an OAuth Claude account
offers the same name, or when the name contains "claude"; every other proxy model runs on
claude-code and pi. The catalogue, the launch (sessionModel and the models.json list) and the
provider route apply the one rule and refuse with model-harness-incompatible, so a stored
Claude-on-pi route is refused, never rewritten. The other route's pi provider is mosaic-proxy-other.

Triage: the route asks the provider for the transport on the stored harness and holds the
harness's env() to one contract (the key, unchanged, under exactly one of ANTHROPIC_AUTH_TOKEN or
ANTHROPIC_API_KEY; the URL only as ANTHROPIC_BASE_URL), with no list of harness names. The host
gives the module the real proxy and transport, checks each file it writes under the session's HOME
(regular, one link, no key) and binds it read-only after the run directory, and refuses a route env
with no key name or two. PATH starts with node_modules/.bin, as a bus session's does.

Tests: claude-code runs a z.ai and a codex proxy model against a stand-in (real claude binary);
pi answers Triage through a stand-in under bwrap; every new fence has a test.
2026-11-19 14:43:26 -06:00
jason.woltje fbaae25d06 fix(webui): settings slice 1: no harness names written into the page: Settings > Triage shows each harness by the id its module is installed under, from the route read, and its help line says the list holds only the programs the model runs with; the drawer's harness refusal reads the route and names its harness by that id, or keeps a plain line without a name when the route can't be read (#1873, lane settings-s1) 2026-11-19 14:38:04 -06:00
jason.woltje c9d64a341e fix(webui): settings slice 1: the failed settings read and failedView share one copy of the line every failed read ends with, so the shipped-strings pin in shell.test finds it once again (#1873, lane settings-s1) 2026-11-19 14:04:14 -06:00
jason.woltje 4cbf3f07b0 fix(webui): settings slice 1 review round 2: a model-key-collision catalogue says two models share a short name and offers no Restart, so it no longer holds Model setup's next step; the dev fixture line says it can't be changed from Console yet instead of asking for a Routing change that does not remove the fixture; Model setup owner text says model service in the init lock, repair and fence steps, and the fence clear command sits under Technical details with where to run it; the Health list and the stopped-organization page show the reason the workspace read already carries; the stopped page links to Model setup by its name; the hire start refusals point at Settings > Routing for models (#1873, lane settings-s1) 2026-11-19 14:04:14 -06:00
jason.woltje 48a2ed675c fix(webui): settings slice 1 review round: Model setup reads each organization's own routes and offers Restart only where the bus names no cause or one a restart clears, so the dev fixture gets its plain line and a Routing link and only a restartable organization holds the next step; the bus's cause codes read as plain lines with its words under Technical details, and the lock cause gets a primary Restart; a set fence reads as a restart to finish; a failed status read offers Check again; Save routes steps back while Restart is the primary; the page is named Model setup and owner text says model service; Routing explains harness and preflight; the drawer's harness refusal asks for a model that runs with Claude Code; the Triage page says daily token limit and that Triage also needs its key (#1873, lane settings-s1) 2026-11-19 14:04:14 -06:00
jason.woltje e70b6bd684 feat(webui): settings slice 1: Routing says why an organization can't see your models: the model service is not set up or not running (a link to its page), the bus names its cause (that line and Check again, plus Restart only for the lock cause), or the service runs and the bus names none (Restart); Model proxy keeps a Restart per organization whose catalogue is not ready, rereads the whole status after a sign-in, works out the steps after accounts from accounts, organizations and the Triage route, and shows only the next step's button with the rest under Technical details; Triage refusals are plain lines with a link to the page that fixes them, and the harness refusal names Claude Code; a stopped organization keeps its refused restart on screen and keeps the instance pages reachable; at phone width a Routing model select takes the whole row (#1873, lane settings-s1) 2026-11-19 14:03:27 -06:00
100 changed files with 6723 additions and 621 deletions

No files matched your search

+135 -1
View File
@@ -554,6 +554,62 @@ const INSTALLER_COMMENT = 'mosaic-installer-';
// business ID_PATTERN, which starts with [a-z0-9], so no instance can be named this.
const NOTICE_ROLE = '_bus';
const NOTICE_RUN = 'bus';
// #1873 chat-fail F2: the one plain line a refused thread start, or a run the model proxy stopped
// for silence (proxy-stall), leaves in the conversation for each message it left unanswered
// (failureNotice below). It is here, not in a file of its own, because the runner imports this
// file in the session sandbox, which mounts only RUNNER_FILES (packages/seat/src/sandbox.mjs).
//
// The line has the form a failed turn's reply has (packages/harness/src/failure-notice.mjs), so the
// chat renders it the same way: "The turn failed: <cause and next step>\nDetails: <code>". The
// text is fixed per code. A refusal's own reason is never put in it: it can name paths, models
// and accounts. Codes are the launcher's existing refusal codes and the existing proxy-stall stop
// reason; none is added here.
const MODEL = "the model this agent uses isn't available from the model service now. Pick another model, or check Settings > Model setup.";
const PROXY = "the model proxy isn't ready. Check Settings > Model setup.";
const ACCOUNT = "the agent's model account isn't signed in or set up. Sign in again, or check the account in Settings > Model setup.";
const LIMIT = "the agent reached a usage limit. Wait for it to reset, or check the limits in Settings.";
const SETUP = "the agent's setup can't start now. Check the agent in Agents.";
const OTHER = "the assistant couldn't start. Try again later, or check the agent in Agents.";
const LINES = new Map([
['proxy-stall', "the model service gave no answer in time, so the turn was stopped. Try again, or check the account in Settings > Model setup."],
['model-provider-unavailable', MODEL],
['model-catalogue-unavailable', MODEL],
['model-harness-incompatible', MODEL],
['proxy-uncertain', PROXY],
['no-session-credential', PROXY],
['account-credential-missing', ACCOUNT],
['account-credential-ambiguous', ACCOUNT],
['account-is-credential', ACCOUNT],
['credential-unavailable', ACCOUNT],
['limit-reached', LIMIT],
['limit-check-failed', LIMIT],
['harness-off', SETUP],
['harness-refused', SETUP],
['harness-failed', SETUP],
['unsupported-harness', SETUP],
['thinking-unsupported', SETUP],
['plugin-disabled', SETUP],
['skill-not-enabled', SETUP],
['skill-refused', SETUP],
['no-role-contract', SETUP],
['definition-holds-credential', SETUP],
['project-archived', "this project is archived, so the assistant can't reply here."],
]);
// A start that waits for a free place, a run that is still ending, a held lock, a lost race, a
// project still being set up or an operator's pause starts by itself once that clears: no line.
const WAITS = new Set(['capacity-full', 'instance-running', 'legacy-run-live', 'session-workspace-busy',
'processing-generation-changed', 'proxy-lock-busy', 'project-pending', 'processing-halted']);
const NOTICE_CODE = /^[a-z][a-z-]{0,63}$/;
// The body for a code, or null when the code leaves no line.
function failureNoticeBody(code) {
if (typeof code !== 'string' || !NOTICE_CODE.test(code) || WAITS.has(code)) return null;
const line = LINES.get(code) ?? (code.startsWith('proxy-') ? PROXY : OTHER);
return `The turn failed: ${line}\nDetails: ${code === 'proxy-stall' ? 'stopped' : 'start refused'}: ${code}`;
}
// Row 143 (#1637, REQ-PROJ-4): a human save of this file through project.file.save sends one notice to each
// instance of these definitions. Their answer goes to the instance of SPEC_ANSWER_TO, the chief of staff,
// because only the user and the chief of staff may send to the assistant (REQ-ASSIST-2).
@@ -652,6 +708,7 @@ export class Broker {
#credentialVerbs;
#proxyInit;
#proxyFenceClear;
#proxyTriageKey;
#proxyPage;
#project;
#library;
@@ -716,7 +773,7 @@ export class Broker {
#processing;
#taskTracker;
// credentialStatus is the runtime's metadata-only Credentials.status(); the broker never gets use().
constructor({ store, businesses, pluginService = null, secretCheck = () => {}, credentialStatus = () => [], organization = null, hires = null, autonomy = null, project = null, library = null, usage = null, limits = null, harnessOn = null, credentialVerbs = null, proxyInit = null, proxyFenceClear = null, proxyPage = null, hostGrant = null, hostKeys = null, processing = null, testerOn = null, grantScope = null, roleFile = null, giteaGrant = null, copyGrant = null, copyLaunch = null, copyRevoker = null, giteaKeys = null, access = null, accessStamp = null, compactions = null, requestLifecycle = null, requirementsHost = null, workspaceRead = null, taskTracker = null }) {
constructor({ store, businesses, pluginService = null, secretCheck = () => {}, credentialStatus = () => [], organization = null, hires = null, autonomy = null, project = null, library = null, usage = null, limits = null, harnessOn = null, credentialVerbs = null, proxyInit = null, proxyFenceClear = null, proxyTriageKey = null, proxyPage = null, hostGrant = null, hostKeys = null, processing = null, testerOn = null, grantScope = null, roleFile = null, giteaGrant = null, copyGrant = null, copyLaunch = null, copyRevoker = null, giteaKeys = null, access = null, accessStamp = null, compactions = null, requestLifecycle = null, requirementsHost = null, workspaceRead = null, taskTracker = null }) {
if (!object(businesses) || !Object.keys(businesses).length) fail('invalid-business');
// Row 194 b15 (sage-2501): the function-argument checks come before anything reads the store.
if (harnessOn !== null && typeof harnessOn !== 'function') throw new TypeError('harnessOn must be a function');
@@ -746,6 +803,7 @@ export class Broker {
this.#credentialVerbs = credentialVerbs;
this.#proxyInit = proxyInit;
this.#proxyFenceClear = proxyFenceClear;
this.#proxyTriageKey = proxyTriageKey;
this.#proxyPage = proxyPage;
this.#hostGrant = hostGrant;
this.#hostKeys = hostKeys;
@@ -2006,6 +2064,61 @@ export class Broker {
this.#launcherReleased.add(key);
return { released: true };
}
// #1873 chat-fail F2: a thread start the launcher refused, or a run the model proxy stopped for
// silence (proxy-stall), leaves the person who wrote no answer. This puts one plain line in the
// conversation for each message from the human, a user or the tester it left unanswered, as a
// RESULT in reply to it, the way #landMessage reports a refused landing. A message in a thread is
// to or from the thread's instance (trigger message_threads_match), so the line is from the
// instance, with from_run NOTICE_RUN: no run sent it, the bus did, and a failed turn's own line is
// the instance's too. With { thread, session } the messages are the session's pending ones, for a
// refused start; with { run } they are the ones delivered to that run and never read, for a
// stopped run. A message the instance has already answered gets no line, so a refusal the
// launcher meets on every tick leaves one line per message. The text is fixed per code
// (failureNoticeBody above). Trusted launcher API, deliberately NOT a socket verb.
failureNotice(record) {
keys(record, ['business', 'code', 'thread', 'session', 'run'], ['business', 'code']);
this.#business(identifier(record.business));
if (typeof record.code !== 'string' || !NOTICE_CODE.test(record.code)) fail('invalid-request');
const byRun = record.run !== undefined;
if (byRun === (record.thread !== undefined || record.session !== undefined)) fail('invalid-request');
let session = null, instance, where, param;
if (byRun) {
const run = this.#runs.get(record.business + ':' + identifier(record.run)) ?? fail('unknown-run');
session = run.session ?? null;
instance = run.role;
where = `EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op='delivered' AND d.holder_run=?)
AND NOT EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op='read')`;
param = run.run;
} else {
session = identifier(record.session);
const se = this.#store.get('SELECT instance FROM sessions WHERE id=? AND thread=? AND business=?', session, identifier(record.thread), record.business) ?? fail('session-not-found');
instance = se.instance;
where = `NOT EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op IN ('delivered','read'))`;
param = null;
}
const body = failureNoticeBody(record.code);
if (body === null) return { posted: 0 };
const scope = session ? 'm.id IN (SELECT message FROM message_threads WHERE session=?)' : 'NOT EXISTS(SELECT 1 FROM message_threads mt WHERE mt.message=m.id)';
return this.#store.transaction(() => {
const open = this.#store.all(
`SELECT m.id, m.from_role FROM messages m WHERE m.business=? AND m.to_role=? AND ${scope}
AND m.from_role IN ('human','user','tester') AND ${where}
AND NOT EXISTS(SELECT 1 FROM message_cancels x WHERE x.message=m.id)
AND NOT EXISTS(SELECT 1 FROM messages n WHERE n.in_reply_to=m.id AND n.from_role=m.to_role)
ORDER BY m.seq`,
...[record.business, instance, ...(session ? [session] : []), ...(param === null ? [] : [param])],
);
for (const m of open) {
const mid = randomUUID();
this.#store.run(
'INSERT INTO messages(id,at,business,from_role,from_run,to_role,class,in_reply_to,decision,corrects,body) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
mid, this.#now(), record.business, instance, NOTICE_RUN, m.from_role, 'RESULT', m.id, null, null, body,
);
this.#route(record.business, mid, m.from_role, session);
}
return { posted: open.length };
});
}
// Row 271 (264d, #1776, D7 steps 3-5): the business's clears still in the launcher's hands, as of
// each op's latest row. An open op waits for its drained run's stop and exit proof, then its
// retirement. A retired op whose successor hasn't started, and wasn't cancelled, waits for its
@@ -6109,6 +6222,27 @@ export class Broker {
return result;
}).catch(error => { throw this.#refused(s, new BusError(/^proxy-[a-z-]+$/.test(error.code ?? '') ? error.code : 'proxy-down'), { verb: request.verb }); });
}
// proxy-scope slice 4 (Jason 2026-11-19): ensure or revoke the instance's Triage key through the
// proxy this bus rides. Owner only, before every other gate, like proxy.fence.clear. The
// answer, the event and the refusal carry key ids and codes only, never a key.
if (request.verb === 'proxy.triage.key') {
this.#human(s);
if (!this.#proxyTriageKey) fail('not-configured');
const args = request.args ?? {};
keys(args, ['op'], ['op']);
if (args.op !== 'ensure' && args.op !== 'revoke') fail('invalid-request');
const ID = /^[0-9a-f]{12}$/;
const idList = v => Array.isArray(v) && v.every(id => typeof id === 'string' && ID.test(id));
return Promise.resolve().then(() => this.#proxyTriageKey(args.op)).then(result => {
const ACTIONS = args.op === 'ensure' ? ['issued', 'held', 'replaced'] : ['revoked', 'none'];
if (!object(result) || !ACTIONS.includes(result.action) || !idList(result.addedKeyIds) || !idList(result.removedKeyIds)
|| (args.op === 'ensure' && !(typeof result.keyId === 'string' && ID.test(result.keyId)))) fail('proxy-client-response');
const answer = { op: args.op, action: result.action, addedKeyIds: [...result.addedKeyIds], removedKeyIds: [...result.removedKeyIds],
...(args.op === 'ensure' ? { keyId: result.keyId, rotateBy: /^\d{4}-\d{2}-\d{2}$/.test(result.rotateBy ?? '') ? result.rotateBy : null } : {}) };
this.#store.transaction(() => this.#event(s, 'action.allowed', { call: 'proxy.triage.key', ...answer }, null));
return answer;
}).catch(error => { throw this.#refused(s, error instanceof BusError ? error : new BusError('storage-unavailable', 'triage-key-failed'), { verb: request.verb }); });
}
// FED R3 (design 3.5, 3.7 trigger 1): a user reaches the collaborator list only, and each
// request reads the access file again, so a removed or expired grant refuses the next one.
let grants = null;
+3
View File
@@ -28,6 +28,7 @@ const LAUNCH_OPS = new Set([
'landHeld',
'threadsState',
'threadIdle',
'failureNotice',
'mayLaunch',
'landHolders',
'landRelease',
@@ -67,6 +68,8 @@ function launchOp(m) {
// Row 121 (#1615): the launcher's view of the business's threads, and its idle release.
if (m.op === 'threadsState') return runtime.threadsState(m.business);
if (m.op === 'threadIdle') return runtime.threadIdle(m.record);
// #1873 chat-fail F2: one plain line per message a refused thread start or a proxy-stall stop left unanswered.
if (m.op === 'failureNotice') return runtime.failureNotice(m.record);
// Row 125 (#1619, REQ-LIMIT-4): the limit checks' answer before a launch (async).
if (m.op === 'mayLaunch') return runtime.mayLaunch(m);
// Row 156 (#1651): the launcher's landing pass: who holds a merge decision, and the stop of a
+40 -2
View File
@@ -20,6 +20,42 @@ function view(id, provider, status, priority) {
return { accountId: keyId(id), provider, displayName: `${providerName(provider)} account ${keyId(id)}`,
status, priority: priorityOk(priority) ? priority : 0 };
}
// #1873 chat-fail F3: one plain line under an account the proxy reports as not working, with
// the next step. It is built only from the structured fields of the account read this page
// already makes. status_message is matched against fixed patterns and never shown; a label,
// email, recovery hint or refresh error message is never read into the line.
const SIGN_IN = 'The account needs to sign in again. Sign in again, or add another account.';
const NO_REASON = 'The model service gave no reason. Wait and try again later, sign in again, or add another account.';
const USAGE_TEXT = /usage limit|quota|rate.?limit|limit reached|too many requests|\b429\b|insufficient.?balance|credit balance/i;
// A bare "expired" is not enough: a usage window expires too.
const SIGN_IN_TEXT = /\b401\b|unauthori[sz]ed|invalid.?grant|\b(?:\w*[_-])?(?:tokens?|sessions?|credentials?|logins?|auth\w*|grants?)\s+(?:(?:has|have|is|are|was|were)\s+)?(?:been\s+)?expired|\brevoked\b|\bsign.?in\b|\b(?:re-?)?log.?in\b|\bre-?auth/i;
const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
// A reset time the read gives, as "YYYY-MM-DD HH:MM UTC" made from the parsed date, only when
// it is a valid RFC 3339 time still ahead of now. Anything else gives no time.
function resetTime(value, now) {
const m = typeof value === 'string' ? RFC3339.exec(value) : null;
if (!m || +m[2] < 1 || +m[2] > 12 || +m[3] < 1 || +m[3] > 31 || +m[4] > 23 || +m[5] > 59 || +m[6] > 59) return null;
// A day the month doesn't have (02-31) would roll into the next month, so it is refused.
const day = new Date(Date.UTC(2000, +m[2] - 1, +m[3]));
day.setUTCFullYear(+m[1]);
if (day.getUTCMonth() !== +m[2] - 1 || day.getUTCDate() !== +m[3]) return null;
const at = Date.parse(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}${m[8]}`);
if (!Number.isFinite(at) || at <= now) return null;
return `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
}
function accountReason(row, now) {
const message = typeof row.status_message === 'string' ? row.status_message.slice(0, 4096) : '';
const time = resetTime(row.next_retry_after, now);
const usage = time ? `The account is out of usage. It resets at ${time}. Wait until then, or add another account.`
: 'The account is out of usage. Wait until it resets, or add another account.';
// The structured flags come first, then the message patterns.
if (row.requires_sign_in === true || (object(row.refresh_error) && Object.keys(row.refresh_error).length > 0)) return SIGN_IN;
if (row.quota_blocked === true) return usage;
if (SIGN_IN_TEXT.test(message)) return SIGN_IN;
if (USAGE_TEXT.test(message)) return usage;
if (time) return `The model service paused this account until ${time}. Wait until then, sign in again, or add another account.`;
return NO_REASON;
}
export class ProxyPage {
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #pending = new Map(); #writes = Promise.resolve();
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null }) {
@@ -51,7 +87,8 @@ export class ProxyPage {
const provider = ['claude', 'codex'].includes(row.provider) ? row.provider : 'other';
const status = row.disabled === true ? 'disabled' : row.unavailable === true ? 'unavailable'
: ['ready', 'active', 'error', 'disabled', 'unavailable'].includes(row.status) ? row.status : 'unknown';
rows.push({ ...view(row.id, provider, status, row.priority), source: 'oauth', name: row.name });
rows.push({ ...view(row.id, provider, status, row.priority), source: 'oauth', name: row.name,
...(['unavailable', 'error'].includes(status) ? { reason: accountReason(row, this.#now()) } : {}) });
}
for (const [groupIndex, group] of groups.entries()) {
if (!Array.isArray(group?.keys)) continue;
@@ -69,7 +106,8 @@ export class ProxyPage {
}
#public(row) {
const { accountId, provider, displayName, status, priority } = row;
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && provider === 'z.ai' ? { models: row.models } : {}) };
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && provider === 'z.ai' ? { models: row.models } : {}),
...(typeof row.reason === 'string' ? { reason: row.reason } : {}) };
}
#session(state, scope, { reportTimeout = false } = {}) {
const entry = stateOk(state) ? this.#pending.get(state) : null;
+4
View File
@@ -87,6 +87,10 @@ group("proxy-key-mismatch", "R1: a pasted management key is confirmed before ini
group("proxy-lock-busy proxy-lock-invalid", "R4: one proxy key write at a time", "Wait for the running proxy write to finish and retry. An invalid lock file needs the owner to inspect the proxy state directory.");
group("proxy-not-configured proxy-unit-usage proxy-unit-exists proxy-unit-dropin proxy-unit-copy proxy-unit-path proxy-unit-missing proxy-unit-unhealthy proxy-unit-failed", "R1/R4: proxy user unit is explicit creation", "Initialize the proxy first, then install the unit from the Proxy page or with mosaic proxy unit install. An existing unit or drop-in is never replaced; remove it by hand. An unhealthy unit: read its journal by unit name and restart it.");
group("proxy-client-invalid proxy-client-refused proxy-client-response", "R1: proxy management answers", "Check the proxy unit is running and its port answers on the Proxy page, then retry. Upstream bodies are never shown.");
// proxy-scope slice 4 (Jason 2026-11-19): the Triage key lives with a bus that rides the owner's
// proxy, and a Triage session on a key past its retireAt ends before the key leaves the proxy.
group("triage-no-riding-bus", "R1/R4: the Triage key is issued and rotated by a bus that rides the owner's proxy", "Triage needs one organization that uses the owner's models. Start an organization that rides the owner's model proxy, then repair Triage access from Settings, Triage.");
group("triage-key-rotated", "R1/R6: a session ends when its Triage key's grace ends", "The Triage key was rotated and the old key's grace has ended. Send the next message; Triage starts again on the current key.");
group(
"block-recipient block-reply-required block-sender message-recipient-refused message-sender-refused tester-reply-required tester-thread-human user-reply-required user-thread-human",
"Role messaging: permitted sender, recipient and reply context",
+86 -3
View File
@@ -34,6 +34,7 @@ import { createModelCatalogue } from './model-catalogue.mjs';
import { sha256 } from '../../model-proxy/src/common.mjs';
import { initializeProxy, loadProxy } from '../../model-proxy/src/settings.mjs';
import { createProxyLock } from './proxy-lock.mjs';
import { ensureKey, readKey as readTriageKey, revokeKeys, sweepDue, sweepKeys } from './triage-key.mjs';
import { verifyRestart } from '../../model-proxy/src/admin.mjs';
import { ModelKeys, modelOrganization, stopModelRuns, MODEL_STOP_TIMEOUT_MS } from './model-keys.mjs';
import { instanceSettings } from '../../organization/src/instance-settings.mjs';
@@ -622,6 +623,10 @@ export async function startBroker({
// P1 validated sidecar from the trusted host; never a socket request setting.
proxy = null,
org = null, instanceDataRoot = null, instanceConfigDir = null,
// proxy-scope slice 4: the Triage key sweep on a riding org bus. intervalMs (default 30 s) and
// marginMs (default 30 s past a retiring key's retireAt, so the Console stops a session on it
// first) are in-process seams, as are now and hook (triage-key.mjs's clock and stage hook).
triageKeys = {},
// Host-only preparation/admission capabilities. The host builds its own from the organization writer and `trackers`
// (request-host.mjs); anything given here replaces the host's, and a capability nothing supplies leaves a setup wait.
requestServices = {},
@@ -657,6 +662,8 @@ export async function startBroker({
throw new BusError('invalid-host-request');
let modelProxyClient = null, proxyPage = null, proxyUsage = null, usageTimer = null, proxyLock = null, proxyPort = null;
let modelKeys = null, modelTimer = null, modelSweep = null, modelCatalogues = null;
// proxy-scope slice 4: the settings of the proxy this bus rides (boot, picked up or initialized).
let proxySettings = null, triageTimer = null, triageSweepRun = null;
const modelRuns = new Map();
let store, credentials, server, adapter, processing, syncTimer = null, syncPass = null, accessTimer = null, requestTimer = null, copyLaunch = null, copyRevoker = null, copyTimer = null;
// #1873 CB4: a revoke's stop waits for the broker; a start that fails before it exists stops nothing.
@@ -707,7 +714,7 @@ export async function startBroker({
proxyLock = createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${proxy.port}` });
}
modelProxyClient = await loadManagementClient({ configDir: org ? instanceConfigDir : organization.dir, proxy, receipt: proxyReceipt });
proxyPort = proxy.port;
proxyPort = proxy.port; proxySettings = proxy;
}
// Row 234 (#1740, r6 X4 third bullet): each host grant record gives its agent a store reference to
@@ -845,7 +852,7 @@ export async function startBroker({
// is no client: static text and a refusal code, never a path or a key.
let lateProxy = false, proxyCause = null, proxySync = Promise.resolve();
const dropLateProxy = cause => {
if (lateProxy) { modelProxyClient = null; proxyPage = null; proxyPort = null; proxyLock = null; lateProxy = false; modelCatalogues?.invalidate?.(); }
if (lateProxy) { modelProxyClient = null; proxyPage = null; proxyPort = null; proxyLock = null; proxySettings = null; lateProxy = false; modelCatalogues?.invalidate?.(); }
proxyCause = cause;
};
// The host refuses fixture-proxy-configured at boot when a dev fixture is recorded for the
@@ -879,11 +886,65 @@ export async function startBroker({
catch { return dropLateProxy('The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.'); }
}
proxyCause = null;
proxySettings = found;
// Same port, key and lock still load: keep the client and its page, which holds login states.
if (modelProxyClient) return;
modelProxyClient = client; proxyPort = found.port; proxyLock = lock; lateProxy = true;
configureProxyPage(); modelCatalogues?.invalidate?.();
}
// proxy-scope slice 4: what triage-key.mjs needs from a riding org bus. A key error becomes a bus
// refusal the table already holds: proxy codes it knows pass through, the rest name the key
// store's code in the reason only. Neither carries a key, a path or upstream text.
// The verb checks the proxy first, as proxy.fence.clear does; the sweep uses what this bus holds
// and never picks a proxy up on its own timer.
const triageOptions = async ({ sync = true } = {}) => {
if (sync) await syncProxy();
if (org === null || !organization || !proxyLock || !modelProxyClient || !proxySettings || typeof instanceConfigDir !== 'string' || typeof instanceDataRoot !== 'string')
throw new BusError('triage-no-riding-bus');
return { configDir: instanceConfigDir, system: { dataRoot: instanceDataRoot, proxy: proxySettings }, client: modelProxyClient, lock: proxyLock,
...(triageKeys.now ? { now: triageKeys.now } : {}), ...(triageKeys.hook ? { hook: triageKeys.hook } : {}) };
};
const TRIAGE_PASS = new Set(['proxy-lock-busy', 'proxy-lock-invalid', 'proxy-lock-uncertain', 'proxy-client-invalid', 'proxy-client-refused', 'proxy-client-response', 'proxy-management-key-invalid']);
const TRIAGE_MAP = { 'triage-key-no-proxy': 'triage-no-riding-bus', 'triage-key-raced': 'proxy-lock-busy', 'triage-key-unconfirmed': 'proxy-lock-uncertain',
'proxy-uncertain': 'proxy-lock-uncertain', 'proxy-client-down': 'proxy-client-response', 'proxy-client-redirect': 'proxy-client-response', 'triage-key-proxy-open': 'proxy-not-configured' };
const triageRefusal = error => {
if (error instanceof BusError) return error;
const code = typeof error?.code === 'string' ? error.code : '';
if (TRIAGE_PASS.has(code)) return new BusError(code);
if (Object.hasOwn(TRIAGE_MAP, code)) return new BusError(TRIAGE_MAP[code], code);
return new BusError('storage-unavailable', /^triage-key-[a-z-]+$/.test(code) ? code : 'triage-key-failed');
};
// The sweep: a cheap read of the file first, so the proxy is asked only when something is due;
// sweepKeys decides again under the lock. It never issues: no file, nothing.
const triageMarginMs = Number.isSafeInteger(triageKeys.marginMs) && triageKeys.marginMs >= 0 ? triageKeys.marginMs : 30_000;
// A refusal that repeats on every tick is logged when it first appears or changes, and then once
// an hour while it stays the same; any other outcome clears it.
let triageLastRefusal = null;
const sweepRefused = (now, entry) => {
const sig = `${entry.code}|${entry.reason ?? ''}`;
if (triageLastRefusal?.sig === sig && now - triageLastRefusal.at < 3_600_000) return;
triageLastRefusal = { sig, at: now };
proxyReceipt({ action: 'triage.key.sweep-refused', ...entry });
};
const sweepTriage = async () => {
let opts;
try { opts = await triageOptions({ sync: false }); } catch { return { action: 'none' }; }
const now = (opts.now ?? Date.now)();
let record;
try { record = readTriageKey(opts.configDir); } catch { sweepRefused(now, { code: 'triage-key-unreadable' }); return { action: 'none' }; }
if (!sweepDue(record, now, triageMarginMs)) { triageLastRefusal = null; return { action: 'none' }; }
try {
const result = await sweepKeys(opts, { marginMs: triageMarginMs });
triageLastRefusal = null;
if (result.action !== 'none') proxyReceipt({ action: `triage.key.${result.action}`, keyId: result.keyId ?? null, addedKeyIds: result.addedKeyIds, removedKeyIds: result.removedKeyIds });
return result;
} catch (error) {
const refusal = triageRefusal(error);
sweepRefused(now, { code: refusal.code, ...(typeof refusal.reason === 'string' ? { reason: refusal.reason } : {}) });
return { action: 'refused', code: refusal.code };
}
};
const triageSweepOnce = () => (triageSweepRun ??= sweepTriage().finally(() => { triageSweepRun = null; }));
// One check at a time; an unexpected failure drops a late client, never keeps it.
const syncProxy = () => (proxySync = proxySync.then(pickProxy).catch(() => dropLateProxy('The model proxy could not be checked (proxy-down). Try again shortly.')));
// Unavailable with no client: the catalogue names the cause instead of a bare unavailable.
@@ -1419,7 +1480,7 @@ export async function startBroker({
const lock = org && !proxyLock ? createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${settings.port}` }) : proxyLock;
// proxy-pickup: a client this bus did not boot with is checked again like a picked-up one.
if (!proxy) { lateProxy = true; proxyCause = null; }
modelProxyClient = client; proxyPort = settings.port; proxyLock = lock;
modelProxyClient = client; proxyPort = settings.port; proxyLock = lock; proxySettings = settings;
configureProxyPage(); modelCatalogues?.invalidate?.();
return settings;
} : null,
@@ -1430,6 +1491,15 @@ export async function startBroker({
if (!proxyLock || !modelProxyClient) throw new BusError('not-configured', proxyCause ?? undefined);
return proxyLock.clear({ restarted: true, read: () => modelProxyClient.getKeys(), verify: previous => verifyRestart(evidence, { fence: previous, port: proxyPort }) });
} : null,
// proxy-scope slice 4 (Jason 2026-11-19): ensure or revoke the instance's Triage key through the
// proxy this org bus rides, under the bus's own client and instance proxy lock. The answer is
// ids only. A no-org bus, or an org bus with no proxy client and lock, refuses
// triage-no-riding-bus.
proxyTriageKey: async (op) => {
const opts = await triageOptions();
try { return op === 'ensure' ? await ensureKey(opts) : await revokeKeys(opts); }
catch (error) { throw triageRefusal(error); }
},
credentialVerbs: organization
? credentialVerbs({ credentials, writer: organizationWriter({ dir: organization.dir, rolesDir: organization.rolesDir, dataRoot:instanceRoot ?? dataRoot }),
organizations: () => Object.keys(businesses), boot: copies?.definitions ? { org: copies.org, definitions: copies.definitions } : null })
@@ -1737,6 +1807,12 @@ export async function startBroker({
}, access.intervalMs ?? ACCESS_SWEEP_MS);
accessTimer.unref();
}
// proxy-scope slice 4: only an org bus sweeps the Triage key; each tick checks it still rides.
if (org !== null && organization) {
triageTimer = setInterval(() => { triageSweepOnce(); },
Number.isSafeInteger(triageKeys.intervalMs) && triageKeys.intervalMs > 0 ? triageKeys.intervalMs : 30_000);
triageTimer.unref();
}
if (modelKeys) {
modelTimer = setInterval(() => {
if (modelSweep) return;
@@ -1864,6 +1940,8 @@ export async function startBroker({
},
threadsState: (business) => broker.threadsState(business),
threadIdle: (r) => broker.threadIdle(r),
// #1873 chat-fail F2: the plain line a refused thread start or a proxy-stall stop leaves.
failureNotice: (r) => broker.failureNotice(r),
// Row 125 (#1619, REQ-LIMIT-4): the launcher asks the limit checks before every launch.
mayLaunch: async ({ business, instance, provider, model, account = null }) => {
processingWork();
@@ -1903,6 +1981,8 @@ export async function startBroker({
definitionScan,
launches: bound,
readers: readCaps,
// proxy-scope slice 4: one Triage key sweep now, as the timer runs it (tests).
triageKeySweep: () => triageSweepOnce(),
async close() {
clearInterval(copyTimer);
brokerUp(null);
@@ -1911,6 +1991,8 @@ export async function startBroker({
await proxyUsage.close();
clearInterval(modelTimer);
await modelSweep;
clearInterval(triageTimer);
await triageSweepRun;
clearInterval(accessTimer);
await stopSync();
await server.close();
@@ -1928,6 +2010,7 @@ export async function startBroker({
clearInterval(usageTimer);
await proxyUsage?.close();
clearInterval(modelTimer);
clearInterval(triageTimer);
clearInterval(accessTimer);
await server?.close();
await adapter?.close?.();
+2
View File
@@ -155,6 +155,8 @@ export async function serve({ broker, path, authenticateHuman = null, authentica
// Row 236 (#1742): the grants verbs may call Gitea several times, 15 s each at most.
GRANTS_VERBS.includes(r.verb) ||
r.verb === 'proxy.init' ||
// proxy-scope slice 4: the Triage key verb waits on the proxy lock and the proxy.
r.verb === 'proxy.triage.key' ||
(r.verb === 'decision.raise' && (Object.hasOwn(r.args ?? {}, 'spec_path') || Object.hasOwn(r.args ?? {}, 'spec_commit') ||
Object.hasOwn(r.args ?? {}, 'grant')))) {
const own = transient;
File renamed without changes.
@@ -1,5 +1,9 @@
// #1873 triage-key: Triage's own model proxy client key, issued from the owner's terminal
// (design report reports/triage-route-design.md slice 3, Jason's ruling 2026-11-18).
// (design report reports/triage-route-design.md slice 3, Jason's ruling 2026-11-18), and since
// proxy-scope slice 4 (Jason's ruling 2026-11-19) by the bus too: the verb proxy.triage.key
// (ensure, revoke) and a riding org bus's sweep call this module with the bus's own management
// client and instance proxy lock. It moved here from packages/cli/src so the bus can import it; the
// terminal verbs (packages/cli/src/triage.mjs) call it unchanged.
//
// <configDir>/secrets/triage/model (directory 0700, file 0600, the running user's)
// { version, key, keyId, issuedAt, rotateBy, retiring: [{ key, keyId, issuedAt, retireAt }] }
@@ -16,9 +20,11 @@
// uncertain fence, which every proxy writer on the instance refuses until a human clears it
// (`mosaic proxy fence clear --proxy-restarted`).
//
// Nothing runs on a timer. rotate records when the old key's grace ends; the key stays in the proxy
// until a later retire, rotate or issue removes it, and status says when that is due. The same goes
// for rotateBy: status marks it due; only rotate replaces the key.
// rotate records when the old key's grace ends; the key stays in the proxy until a later retire,
// rotate, issue or sweep removes it, and status says when that is due. A riding org bus runs
// sweepKeys on a timer: under the lock it reads the file again and rotates when rotateBy is due, or
// retires keys whose grace (plus a margin, so the Console stops a session on the key first) has
// passed. The sweep only replaces a key that exists; it never issues the first one.
//
// Nothing here prints, logs or records a key. Receipts and output carry key ids only (the first 12
// hex of sha256(key), the id the bus uses). Messages name files and options, never values.
@@ -27,7 +33,7 @@ import { closeSync, constants, fchmodSync, fsyncSync, lstatSync, openSync, readd
import { randomBytes } from "node:crypto";
import { join } from "node:path";
import { isDeepStrictEqual } from "node:util";
import { createProxyLock } from "../../bus/src/proxy-lock.mjs";
import { createProxyLock } from "./proxy-lock.mjs";
import { loadManagementClient } from "../../model-proxy/src/client.mjs";
// #1873 triage-wiring: the key file's reader lives in triage-key-file.mjs (node built-ins only), so
@@ -136,20 +142,24 @@ const proxyFailure = (code) => {
};
// opts.uid, opts.now and opts.hook(stage) are test seams; a stage hook may throw or kill the process.
function context({ configDir, system, uid, fileUid, now, hook }) {
// opts.client and opts.lock: the bus passes its own management client and instance proxy lock, so a
// bus change runs under the lock object its model key sweep uses and reads no key file of its own.
function context({ configDir, system, uid, fileUid, now, hook, client, lock }) {
if (!system?.proxy || !Number.isInteger(system.proxy.port)) throw new TriageKeyError("triage-key-no-proxy", "the instance has no model proxy set up (proxy.json)");
return {
configDir, dataRoot: system.dataRoot, proxy: system.proxy, stateDir: join(system.dataRoot, "proxy"),
uid: uid ?? process.getuid(), fileUid, now: now ?? Date.now, hook: hook ?? (() => {}),
uid: uid ?? process.getuid(), fileUid, now: now ?? Date.now, hook: hook ?? (() => {}), client, lock,
};
}
function lockFor(c) {
if (c.lock) return c.lock;
try { return createProxyLock({ stateDir: c.stateDir, identity: `${c.configDir}:${c.proxy.port}` }); }
catch (e) { throw proxyFailure(e.code ?? "proxy-lock-invalid"); }
}
async function clientFor(c) {
if (c.client) return c.client;
try { return await loadManagementClient({ configDir: c.configDir, proxy: c.proxy }); }
catch (e) { throw proxyFailure(e.code ?? "proxy-management-key-invalid"); }
}
@@ -162,9 +172,10 @@ function checkSentinel(c, keys) {
}
// Under the instance proxy lock: read the list, check the sentinel, run `plan`, write the result.
// `plan(keys, record)` returns { after, record, removed, added, done }; `record` null leaves the
// file alone. The proxy changes first, then the file, then one receipt line.
async function change(c, op, plan) {
// `plan(keys, record)` returns { after, record, remove, op, done }; `record` null leaves the file
// alone, `remove` true unlinks it (revoke), `op` names the change when the plan picks it (sweep).
// The proxy changes first, then the file, then one receipt line.
async function change(c, opName, plan) {
const lock = lockFor(c);
const client = await clientFor(c);
try {
@@ -173,6 +184,8 @@ async function change(c, op, plan) {
checkSentinel(c, before);
const current = readKey(c.configDir, { uid: c.uid, fileUid: c.fileUid });
const result = plan(before, current);
const op = result.op ?? opName;
const remove = result.remove === true && current !== null;
if (result.record) prepareDirs(c.configDir, c.uid);
removeTemps(c.configDir);
receiptsReady(c.stateDir, c.uid);
@@ -195,8 +208,8 @@ async function change(c, op, plan) {
}
c.hook("write");
let unsynced = false;
if (result.record) {
try { writeKey(c.configDir, result.record, c.uid, c.hook); }
if (result.record || remove) {
try { if (remove) unlinkKey(c.configDir, c.hook); else writeKey(c.configDir, result.record, c.uid, c.hook); }
catch (e) {
if (e instanceof NotSynced) unsynced = true;
else throw new TriageKeyError("triage-key-unwritten", `the proxy list changed but ${keyPaths(c.configDir).file} was not written (${e.message}); fix the file's directory, then run mosaic triage key ${op} again, which clears what this run left`);
@@ -204,7 +217,7 @@ async function change(c, op, plan) {
}
c.hook("receipt");
// A run that changed neither the proxy nor the file leaves no receipt.
if (added.length || removed.length || result.record) receipt(c.stateDir, c.uid, { op: `triage.key.${op}`, time: new Date(c.now()).toISOString(), addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) });
if (added.length || removed.length || result.record || remove) receipt(c.stateDir, c.uid, { op: `triage.key.${op}`, time: new Date(c.now()).toISOString(), addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) });
// The file is in place and the receipt written; only its durability is in doubt.
if (unsynced) throw new TriageKeyError("triage-key-unsynced", `${keyPaths(c.configDir).file} was written but its directory could not be synced, so it may not survive a power loss; run mosaic triage key status`);
return { ...result.done, addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) };
@@ -215,6 +228,18 @@ async function change(c, op, plan) {
}
}
// Revoke's file step: unlink, then sync the directory, with writeKey's stages and failures.
function unlinkKey(configDir, hook = () => {}) {
const { dir, file } = keyPaths(configDir);
try { hook("rename"); unlinkSync(file); }
catch (e) { if (e?.code !== "ENOENT") throw unreadable("the key file cannot be removed"); }
try {
hook("sync");
const dfd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY);
try { fsyncSync(dfd); } finally { closeSync(dfd); }
} catch { throw new NotSynced(); }
}
const newKey = (configDir) => keyPrefix(configDir) + randomBytes(32).toString("base64url");
// Keys in the Triage namespace that the file does not hold: left by a crash between the PUT and the
@@ -235,39 +260,117 @@ export async function issueKey(opts) {
});
}
// Retiring keys whose grace has passed, or that the proxy no longer holds.
const dueOf = (record, keys, nowMs) => record.retiring.filter((r) => Date.parse(r.retireAt) <= nowMs || !keys.includes(r.key));
// Retiring keys whose grace (plus marginMs, 0 for the terminal verbs) has passed, or that the proxy
// no longer holds.
const dueOf = (record, keys, nowMs, marginMs = 0) => record.retiring.filter((r) => Date.parse(r.retireAt) + marginMs <= nowMs || !keys.includes(r.key));
const rotateDueAt = (record) => Date.parse(`${record.rotateBy}T00:00:00Z`);
// The rotate plan, shared by the terminal verb and the sweep.
function rotatePlan(c, before, current, nowMs, marginMs = 0) {
const orphans = orphansOf(c.configDir, before, current);
const due = dueOf(current, before, nowMs, marginMs);
const keep = before.includes(current.key);
const retiring = [...current.retiring.filter((r) => !due.includes(r)),
...(keep ? [{ key: current.key, keyId: current.keyId, issuedAt: current.issuedAt, retireAt: retireAtFor(nowMs, c.proxy) }] : [])];
if (retiring.length > MAX_RETIRING) throw new TriageKeyError("triage-key-failed", "too many keys are retiring; run mosaic triage key retire once their grace has passed");
const key = newKey(c.configDir);
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring };
const drop = [...orphans, ...due.map((r) => r.key)];
return {
after: [...before.filter((k) => !drop.includes(k)), key], record,
done: { keyId: record.keyId, rotateBy: record.rotateBy, old: keep ? { keyId: current.keyId, retireAt: retiring.at(-1).retireAt } : { keyId: current.keyId, lost: true } },
};
}
export async function rotateKey(opts) {
const c = context(opts);
return change(c, "rotate", (before, current) => {
if (!current) throw new TriageKeyError("triage-key-not-issued", "no Triage key is issued; use mosaic triage key issue");
const nowMs = c.now();
const orphans = orphansOf(c.configDir, before, current);
const due = dueOf(current, before, nowMs);
const keep = before.includes(current.key);
const retiring = [...current.retiring.filter((r) => !due.includes(r)),
...(keep ? [{ key: current.key, keyId: current.keyId, issuedAt: current.issuedAt, retireAt: retireAtFor(nowMs, c.proxy) }] : [])];
if (retiring.length > MAX_RETIRING) throw new TriageKeyError("triage-key-failed", "too many keys are retiring; run mosaic triage key retire once their grace has passed");
const key = newKey(c.configDir);
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring };
const drop = [...orphans, ...due.map((r) => r.key)];
return {
after: [...before.filter((k) => !drop.includes(k)), key], record,
done: { keyId: record.keyId, rotateBy: record.rotateBy, old: keep ? { keyId: current.keyId, retireAt: retiring.at(-1).retireAt } : { keyId: current.keyId, lost: true } },
};
return rotatePlan(c, before, current, c.now());
});
}
function retirePlan(c, before, current, nowMs, marginMs = 0) {
const orphans = orphansOf(c.configDir, before, current);
const due = current ? dueOf(current, before, nowMs, marginMs) : [];
const record = current && due.length ? { ...current, retiring: current.retiring.filter((r) => !due.includes(r)) } : null;
const drop = [...orphans, ...due.map((r) => r.key)];
return { after: before.filter((k) => !drop.includes(k)), record, done: { droppedKeyIds: due.map((r) => r.keyId) } };
}
export async function retireKeys(opts) {
const c = context(opts);
return change(c, "retire", (before, current) => {
return change(c, "retire", (before, current) => retirePlan(c, before, current, c.now()));
}
// proxy-scope slice 4: the bus verb proxy.triage.key op ensure. Leaves a held key alone, issues one
// when none exists, replaces one the proxy lost. Never prints the key; the answer is ids only.
// issued no file: a new key (keys in the namespace the file does not hold are removed)
// held the proxy holds the file's key: only orphans and retiring keys the proxy lost go
// replaced the proxy does not hold the file's key: a new key, the old one marked lost
export async function ensureKey(opts) {
const c = context(opts);
return change(c, "ensure", (before, current) => {
const nowMs = c.now();
const orphans = orphansOf(c.configDir, before, current);
const due = current ? dueOf(current, before, nowMs) : [];
const record = current && due.length ? { ...current, retiring: current.retiring.filter((r) => !due.includes(r)) } : null;
const drop = [...orphans, ...due.map((r) => r.key)];
return { after: before.filter((k) => !drop.includes(k)), record, done: { droppedKeyIds: due.map((r) => r.keyId) } };
const fresh = (retiring) => {
const key = newKey(c.configDir);
return { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring };
};
if (!current) {
const record = fresh([]);
return { after: [...before.filter((k) => !orphans.includes(k)), record.key], record, done: { action: "issued", keyId: record.keyId, rotateBy: record.rotateBy } };
}
const lost = current.retiring.filter((r) => !before.includes(r.key));
const retiring = current.retiring.filter((r) => !lost.includes(r));
if (before.includes(current.key)) {
return {
after: before.filter((k) => !orphans.includes(k)), record: lost.length ? { ...current, retiring } : null,
done: { action: "held", keyId: current.keyId, rotateBy: current.rotateBy },
};
}
const record = fresh(retiring);
return {
after: [...before.filter((k) => !orphans.includes(k)), record.key], record,
done: { action: "replaced", keyId: record.keyId, rotateBy: record.rotateBy, old: { keyId: current.keyId, lost: true } },
};
});
}
// proxy-scope slice 4: op revoke, when the owner turns Triage off. Every name in this instance's
// Triage namespace leaves the proxy list, then the key file goes. No file and no names: nothing.
export async function revokeKeys(opts) {
const c = context(opts);
return change(c, "revoke", (before, current) => {
const mine = before.filter(inNamespace(c.configDir));
return { after: before.filter((k) => !mine.includes(k)), record: null, remove: true, done: { action: mine.length || current ? "revoked" : "none" } };
});
}
// What a sweep would do from the file alone: "rotate" when rotateBy has come, "retire" when a
// retiring key's grace plus marginMs has passed, else null. A cheap check without the lock or the
// proxy; sweepKeys decides again under the lock.
export function sweepDue(record, nowMs, marginMs = 0) {
if (!record) return null;
if (rotateDueAt(record) <= nowMs) return "rotate";
return record.retiring.some((r) => Date.parse(r.retireAt) + marginMs <= nowMs) ? "retire" : null;
}
// The bus sweep. Under the instance proxy lock it reads the file again and acts only if the action
// is still due, so two buses that wake together change the proxy once. No file: nothing, ever.
export async function sweepKeys(opts, { marginMs = 0 } = {}) {
const c = context(opts);
return change(c, "sweep", (before, current) => {
const nowMs = c.now();
const due = sweepDue(current, nowMs, marginMs);
if (due === "rotate") {
const plan = rotatePlan(c, before, current, nowMs, marginMs);
return { ...plan, op: "rotate", done: { action: "rotated", ...plan.done } };
}
if (due === "retire") {
const plan = retirePlan(c, before, current, nowMs, marginMs);
return { ...plan, op: "retire", done: { action: "retired", ...plan.done } };
}
return { after: before, record: null, done: { action: "none" } };
});
}
@@ -0,0 +1,50 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startBroker } from '../src/runtime.mjs';
import { checkedTransport } from '../../harness/src/bundle.mjs';
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only. A stored route that puts an
// OAuth Claude model on pi is refused at launch admission with model-harness-incompatible, even when a stale
// catalogue row still says pi. A z.ai and a codex model are admitted on pi.
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } }, coder: { authority: { withinRole: [], crossRole: [] } } };
async function admission(t, entry, catalogueRow) {
const root = mkdtempSync(join(tmpdir(), 'harness-matrix-')); t.after(() => rmSync(root, { recursive: true, force: true }));
const rolesDir = rolesCopy(root), doc = businessDoc(root, 'demo');
doc.plugins = { ...doc.plugins, harness: ['pi'], 'model-provider': ['cliproxy'] };
doc.launch.models['fixture-key'] = entry;
doc.roles.coder.vars = { ...doc.roles.coder.vars, harness: 'pi', model: 'fixture-key', thinking: 'low' };
writeJson(join(root, 'businesses/demo.json'), doc); mkdirSync(join(root, 'data'), { mode: 0o700 });
const modelCatalogue = { invalidate() {}, read: async () => ({ status: 'ready', notices: [], models: [{ module: 'cliproxy', available: true, ...catalogueRow }] }) };
const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles } }, organization: { dir: root, rolesDir, system: systemFor(root) }, modelCatalogue });
t.after(() => bus.close());
const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
const revision = bus.broker.request(human, { verb: 'limits' }).revision;
// The launcher's own transport check refuses first; admission is the second gate, so the request
// carries the transport the provider would give with no harness named.
const transport = checkedTransport(entry);
return bus.modelAdmission({ business: 'demo', instance: 'coder', modelKey: 'fixture-key', harness: 'pi', revision, entry, provider: entry.provider, model: entry.model, account: null, route: 'primary', transport });
}
test('#1873 a stored Claude route on pi is refused model-harness-incompatible at admission, even with a stale catalogue row that says pi', async t => {
const entry = { provider: 'anthropic', model: 'claude-opus-5-5', module: 'cliproxy', upstream: 'claude' };
assert.deepEqual(await admission(t, entry, { upstream: 'claude', model: 'claude-opus-5-5', harnesses: ['claude-code', 'pi'] }), { allow: false, code: 'model-harness-incompatible' });
});
test('#1873 a Claude model from an API-key group (upstream other) is admitted on pi; one whose name an OAuth account offers is refused', async t => {
const entry = { provider: 'other', model: 'anthropic/claude-sonnet-5-5', module: 'cliproxy', upstream: 'other' };
assert.deepEqual(await admission(t, entry, { upstream: 'other', model: 'anthropic/claude-sonnet-5-5', harnesses: ['claude-code', 'pi'] }), { allow: true });
// The catalogue holds a group model to claude-code when an OAuth Claude account offers its name.
assert.deepEqual(await admission(t, entry, { upstream: 'other', model: 'anthropic/claude-sonnet-5-5', harnesses: ['claude-code'] }), { allow: false, code: 'model-harness-incompatible' });
});
test('#1873 a z.ai and a codex model are admitted on pi', async t => {
for (const [provider, upstream, model] of [['zai', 'zai', 'glm-fixture'], ['codex', 'codex', 'gpt-fixture']]) {
const entry = { provider, model, module: 'cliproxy', upstream };
assert.deepEqual(await admission(t, entry, { upstream, model, harnesses: ['claude-code', 'pi'] }), { allow: true }, provider);
}
});
@@ -27,7 +27,9 @@ export async function ownershipFixture(t,{launches=true,listed=true,keep=false,r
// Available before any acquired resource/setup can fail; no later f/launcher TDZ.
const launchLog=()=>{const file=launchLogFile(join(root,'data'),'acme');return fs.existsSync(file)?fs.readFileSync(file,'utf8').trim().split('\n').filter(Boolean).map(line=>JSON.parse(line)):[];};
t.after(async()=>{const failures=[];for(const g of gates)g.release();try{await waitFor(()=>active.size===0,'owned operations did not settle',5000);}catch{failures.push('owned-operation-close');}for(const close of [...closers].reverse()){try{await close();}catch{failures.push('owned-close');}}try{server?.closeAllConnections();if(server?.listening)await new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));}catch{failures.push('owned-server-close');}try{checkHistory({logs,proxyReceipts,trace});}catch{failures.push('value-free-receipts');}try{checkHistory({launch:launchLog()});}catch{failures.push('owned-launch-log-guard');}if(stderr)process.stderr.write=stderr;try{fs.rmSync(root,{recursive:true,force:true});}catch{failures.push('owned-root-close');}if(failures.length)throw new AggregateError(failures.map(code=>Error(code)),'owned managed fixture cleanup failed');});
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:['pi']};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness:'pi'};doc.roles.chief.vars.model='claude-opus-5-5';doc.roles.aide={definition:'aide',vars:{harness:'pi',model:'claude-opus-5-5',thinking:'high'}};if(listed)doc.launch.instances.push('aide');if(keep)doc.launch.keep=['aide'];if(retired)doc.retired=['alpha'];if(noHire)doc.launch.noHire=['aide'];if(!listed)delete doc.roles.aide;return doc;});
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:['pi']};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness:'pi'};doc.roles.chief.vars.model='claude-opus-5-5';doc.roles.aide={definition:'aide',vars:{harness:'pi',model:'claude-opus-5-5',thinking:'high'}};if(listed)doc.launch.instances.push('aide');if(keep)doc.launch.keep=['aide'];if(retired)doc.retired=['alpha'];if(noHire)doc.launch.noHire=['aide'];if(!listed)delete doc.roles.aide;doc.launch.models['claude-opus-5-5']={provider:'zai',model:'fixture-aide-model'};return doc;});
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only, so on pi the model key
// claude-opus-5-5 names a non-Claude upstream model.
// The established scratch aide pattern only; repository roles/policy stay untouched.
for(const name of ['aide','helper']){fs.writeFileSync(join(f.roles,name+'.md'),'# Scratch aide\n\n## Authority\n');writeJson(join(f.roles,name+'.json'),{roleVersion:2,name,title:'Aide',contract:name+'.md',tools:['read'],network:'api-only',authority:{withinRole:['message.send'],crossRole:[]},credentials:[]});}
const chiefFile=join(f.roles,'chief-of-staff.json');
@@ -74,6 +76,7 @@ export async function ownershipFixture(t,{launches=true,listed=true,keep=false,r
case 'landRelease':return bus.landRelease(m.record);
case 'threadsState':return bus.threadsState(m.business);
case 'threadIdle':return bus.threadIdle(m.record);
case 'failureNotice':return bus.failureNotice(m.record);
case 'lifecycleRequests':return bus.lifecycleRequests(m.business);
case 'lifecycleTake':return bus.lifecycleTake(m.record);
case 'lifecycleDelete':return bus.lifecycleDelete(m.record);
+11 -4
View File
@@ -80,7 +80,9 @@ function instance(t) {
// A real organization bus on the instance, started with no proxy unless `binding.proxy` gives one.
async function orgBus(t, f, id, { providers = ['cliproxy'], binding = {} } = {}) {
const doc = businessDoc(f.root, id);
doc.plugins = { harness: ['pi'], 'model-provider': providers };
// The coder's model is a Claude model on a legacy entry, which counts as OAuth and runs on
// claude-code only, so the organization enables claude-code.
doc.plugins = { harness: ['claude-code'], 'model-provider': providers };
writeJson(join(f.configDir, 'businesses', `${id}.json`), doc);
const business = loadBusiness(id, { dir: f.configDir, rolesDir: f.rolesDir }), resolved = {};
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system: f.system, business, instance: name });
@@ -113,7 +115,7 @@ async function pickModel(o) {
const view = await o.ask('routes');
assert.equal(view.catalogue.status, 'ready');
assert.ok(view.catalogue.models.some(m => m.key === MODEL));
await o.ask('routes.set', { revision: view.revision, routes: { coder: { harness: 'pi', model: MODEL, thinking: 'low', fallback: null } } });
await o.ask('routes.set', { revision: view.revision, routes: { coder: { harness: 'claude-code', model: MODEL, thinking: 'low', fallback: null } } });
}
// The host launcher as cli.mjs builds it for a bus that booted with no proxy.json: its system has
@@ -123,7 +125,10 @@ async function hostLauncher(t, f, o, { system = {} } = {}) {
initializeControl(o.dataRoot);
// A launch whose role names a skill that is not enabled refuses before the model gate.
if (!fs.existsSync(join(f.dataRoot, 'skills-enabled'))) fs.cpSync(REPO_SKILLS, join(f.dataRoot, 'skills-enabled'), { recursive: true });
const env = withoutHostCredentials(humanEnv({ MOSAIC_CONFIG: join(f.configDir, 'config.json'), MOSAIC_ROLES_DIR: f.rolesDir }), { piKey: true });
// claude-code's preflight needs a session login or a proxy key, and this launcher boots with no
// proxy, so the env carries a stand-in login (as launcher.test.mjs does). No adapter ever runs.
const env = withoutHostCredentials(humanEnv({ MOSAIC_CONFIG: join(f.configDir, 'config.json'), MOSAIC_ROLES_DIR: f.rolesDir }));
env.CLAUDE_CODE_OAUTH_TOKEN = 'stand-in';
const answers = [], ops = [];
const host = { business: o.id, beforeClose: () => {}, op: async m => {
ops.push(m.op);
@@ -134,7 +139,9 @@ async function hostLauncher(t, f, o, { system = {} } = {}) {
return {};
} };
const cliproxy = JSON.stringify(pathToFileURL(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).pathname).href);
const makeLoader = await fakeHarnesses(t, { pi: null }, write => write('model-provider', 'cliproxy', `export * from ${cliproxy};\n`));
// The stand-in adapter path skips only the binary check; the launch stops at the model gate or
// authorizeLaunch, before any adapter runs.
const makeLoader = await fakeHarnesses(t, { 'claude-code': '/fixture-unused' }, write => write('model-provider', 'cliproxy', `export * from ${cliproxy};\n`));
// The validated system config shape (mosaic-config.mjs), as cli.mjs passes it with the org root.
const config = { configVersion: 1, environment: 'development', dataRoot: o.dataRoot, instanceRoot: f.dataRoot,
execution: { backend: 'docker', provider: 'zai', model: 'glm-5.3-flash', adapter: 'mock' }, ...system };
@@ -0,0 +1,82 @@
// #1873 chat-fail F3: an account the proxy reports as not working carries one plain line,
// built only from the structured fields of the proxy's own account read. No upstream text,
// label or email is ever reflected, and no new proxy call is made.
import test from 'node:test';
import assert from 'node:assert/strict';
import { fakeManagement } from './proxy-page-fixture.mjs';
const PRIVATE = ['p4-private-label', 'p4-private-email', 'p4-private-token', 'p4-private-message'];
const oauth = extra => ({ id: 'oauth-one.json', name: 'oauth-one.json', provider: 'claude', label: PRIVATE[0],
email: PRIVATE[1], token: PRIVATE[2], status: 'ready', priority: 3, ...extra });
const SIGN_IN = 'The account needs to sign in again. Sign in again, or add another account.';
const USAGE = 'The account is out of usage. Wait until it resets, or add another account.';
const usageAt = time => `The account is out of usage. It resets at ${time}. Wait until then, or add another account.`;
const PAUSED = time => `The model service paused this account until ${time}. Wait until then, sign in again, or add another account.`;
const NO_REASON = 'The model service gave no reason. Wait and try again later, sign in again, or add another account.';
async function reasonOf(t, extra) {
const s = await fakeManagement(t, { files: [oauth(extra)] });
const result = await s.call('proxy.accounts');
const text = JSON.stringify(result);
for (const value of PRIVATE) assert.equal(text.includes(value), false, `${value} reached the page`);
assert.deepEqual(s.state.calls, ['GET /v8/management/credentials', 'GET /v8/management/config/api-keys/claude'], 'no new proxy call');
return result.accounts[0];
}
test('an account that must sign in again says so, from requires_sign_in or a refresh error', async t => {
for (const extra of [{ status: 'error', requires_sign_in: true, next_action: 'sign_in', recovery_hint: PRIVATE[3] },
{ status: 'error', refresh_error: { code: 'invalid_grant', message: PRIVATE[3], http_status: 400 } },
{ unavailable: true, status_message: `401 Unauthorized ${PRIVATE[3]}` },
{ status: 'error', status_message: `token expired ${PRIVATE[3]}` }])
assert.equal((await reasonOf(t, extra)).reason, SIGN_IN, JSON.stringify(extra));
});
test('an account out of usage names the reset time when the read carries one', async t => {
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after: '2099-03-04T05:06:07Z' })).reason,
usageAt('2099-03-04 05:06 UTC'));
assert.equal((await reasonOf(t, { status: 'error', status_message: `usage limit reached ${PRIVATE[3]}`, next_retry_after: '2099-03-04T05:06:07+02:00' })).reason,
usageAt('2099-03-04 03:06 UTC'));
// No time, a past time or a value that is not a time gives no time, never the value itself.
for (const next_retry_after of [undefined, '2000-01-01T00:00:00Z', PRIVATE[3], '2099-13-40T99:99:99Z', 12345, { at: 1 }])
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after })).reason, USAGE, String(next_retry_after));
});
test('a paused account with only a retry time says until when', async t => {
assert.equal((await reasonOf(t, { unavailable: true, status_message: PRIVATE[3], next_retry_after: '2099-03-04T05:06:07.123456789Z' })).reason,
PAUSED('2099-03-04 05:06 UTC'));
});
test('a failing account with nothing more in the read says the model service gave no reason', async t => {
for (const extra of [{ status: 'error' }, { unavailable: true }, { status: 'unavailable', status_message: PRIVATE[3] },
{ status: 'error', status_message: 42, refresh_error: null, requires_sign_in: 'yes', quota_blocked: 1 }])
assert.equal((await reasonOf(t, extra)).reason, NO_REASON, JSON.stringify(extra));
});
test('a working, turned-off or unknown account keeps exactly its fields and gets no line', async t => {
for (const extra of [{}, { status: 'active', status_message: 'usage limit reached' }, { disabled: true, requires_sign_in: true }, { status: 'mystery' }])
assert.deepEqual(Object.keys(await reasonOf(t, extra)).sort(), ['accountId', 'displayName', 'priority', 'provider', 'status'], JSON.stringify(extra));
});
test('every line is plain: no em dash, no control character, at most one sentence pair', () => {
for (const line of [SIGN_IN, USAGE, usageAt('2099-03-04 05:06 UTC'), PAUSED('2099-03-04 05:06 UTC'), NO_REASON]) {
assert.doesNotMatch(line, /[—\u0000-\u001f\u007f]/);
assert.ok(line.length <= 160, line);
}
});
// Review round 1: a day the month doesn't have is refused, not rolled into the next month.
test('an impossible date gives no reset time; a real leap day does', async t => {
for (const next_retry_after of ['2099-02-31T00:00:00Z', '2099-04-31T10:00:00Z', '2099-02-29T00:00:00Z'])
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after })).reason, USAGE, next_retry_after);
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, next_retry_after: '2096-02-29T01:02:03Z' })).reason, usageAt('2096-02-29 01:02 UTC'));
});
// Review round 1: quota_blocked wins over a message word, and a bare "expired" is not a sign-in.
test('an account blocked on usage whose message says expired gets the usage line', async t => {
assert.equal((await reasonOf(t, { unavailable: true, quota_blocked: true, status_message: `usage window expired ${PRIVATE[3]}` })).reason, USAGE);
assert.equal((await reasonOf(t, { status: 'error', status_message: `trial window expired ${PRIVATE[3]}` })).reason, NO_REASON);
for (const status_message of ['session expired', 'credentials expired', 'OAuth token has expired'])
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, SIGN_IN, status_message);
});
// Review round 2: the sign-in words match whole words only, and a prefixed or "is expired" token counts.
test('a message word inside another word is not a sign-in; a prefixed or "is expired" token is', async t => {
for (const status_message of ['assigning a slot', 'logging paused', 'design input'])
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, NO_REASON, status_message);
for (const status_message of ['access_token expired', 'token is expired', 'refresh-token has been expired', 'please sign in'])
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, SIGN_IN, status_message);
});
// Review round 3: "relogin", plurals and past forms of "expired" read as a sign-in too.
test('relogin, plural and past forms of an expired sign-in say sign in again', async t => {
for (const status_message of ['relogin required', 'tokens have expired', 'session was expired', 'credentials were expired'])
assert.equal((await reasonOf(t, { status: 'error', status_message })).reason, SIGN_IN, status_message);
});
+77
View File
@@ -656,3 +656,80 @@ test('C2-09a: creative bindLaunch without a thread refuses thread-required', t =
assert.equal(ctx.count('SELECT count(*) n FROM threads'), 0);
assert.equal(ctx.count('SELECT count(*) n FROM role_claims'), 0);
});
// #1873 chat-fail F2: the launcher's trusted failureNotice puts one plain line in the conversation
// for each message a refused start or a stalled run left unanswered.
const LIMIT_LINE = "The turn failed: the agent reached a usage limit. Wait for it to reset, or check the limits in Settings.\nDetails: start refused: limit-reached";
const STALL_LINE = "The turn failed: the model service gave no answer in time, so the turn was stopped. Try again, or check the account in Settings > Model setup.\nDetails: stopped: proxy-stall";
const lines = (store, id) => store.all("SELECT * FROM messages WHERE in_reply_to=? AND from_run='bus'", id);
test('#1873 F2: a refused start puts one line per pending message in its session, once, and none for a wait', (t) => {
const { b, store, call, A, B } = twoThreads(t);
b.endLaunch({ business: 'demo', run: 'a-run', reason: 'idle' });
const session = store.get('SELECT session FROM session_defaults WHERE thread=?', A).session;
const notice = (code, extra = {}) => b.failureNotice({ business: 'demo', thread: A, session, code, ...extra });
const one = call('human', 'thread.send', { thread: A, body: 'one' });
const two = call('human', 'thread.send', { thread: A, body: 'two' });
const other = call('human', 'thread.send', { thread: B, body: 'for B' });
// A start that waits for a free place leaves no line.
for (const code of ['capacity-full', 'instance-running', 'legacy-run-live', 'session-workspace-busy', 'processing-generation-changed', 'proxy-lock-busy', 'project-pending', 'processing-halted']) assert.deepEqual(notice(code), { posted: 0 });
assert.deepEqual(notice('limit-reached'), { posted: 2 });
for (const sent of [one, two]) {
const [line] = lines(store, sent.id);
assert.equal(line.body, LIMIT_LINE);
assert.deepEqual([line.class, line.from_role, line.to_role, line.from_run], ['RESULT', 'assistant', 'human', 'bus']);
assert.equal(store.get('SELECT session FROM message_threads WHERE message=?', line.id).session, session, 'the line is in the session');
}
assert.deepEqual(lines(store, other.id), [], "another thread's message gets none");
// Every retry meets the same refusal: still one line each, under any code.
assert.deepEqual(notice('limit-reached'), { posted: 0 });
assert.deepEqual(notice('model-provider-unavailable'), { posted: 0 });
assert.equal(lines(store, one.id).length, 1);
// The message stays pending, so the next start still takes it.
assert.equal(b.threadsState('demo').find((s) => s.thread === A).pending, 2);
const three = call('human', 'thread.send', { thread: A, body: 'three' });
assert.deepEqual(notice('some-new-code'), { posted: 1 });
assert.match(lines(store, three.id)[0].body, /^The turn failed: the assistant couldn't start\. .*\nDetails: start refused: some-new-code$/);
});
test('#1873 F2: a stalled run puts one line on each message delivered to it and unread, thread or role', (t) => {
const { b, store, call, A } = twoThreads(t);
const taken = call('human', 'thread.send', { thread: A, body: 'taken' });
assert.deepEqual(call('a', 'message.receive').map((m) => m.id), [taken.id]);
const waiting = call('human', 'thread.send', { thread: A, body: 'still waiting' });
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'a-run', code: 'proxy-stall' }), { posted: 1 });
assert.equal(lines(store, taken.id)[0].body, STALL_LINE);
assert.deepEqual(lines(store, waiting.id), [], 'a message the run never took waits for the next run');
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'a-run', code: 'proxy-stall' }), { posted: 0 });
// A read message was answered by the turn: no line.
const read = call('human', 'thread.send', { thread: A, body: 'read' });
call('a', 'message.receive');
call('a', 'message.read', { id: read.id });
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'a-run', code: 'proxy-stall' }), { posted: 1 }, 'only waiting, delivered now');
assert.deepEqual(lines(store, read.id), []);
// A role run: the human's message to the chief, outside any thread.
const asked = call('human', 'message.send', { to: 'chief', class: 'REQUEST', body: 'chief, please' });
assert.ok(call('chief', 'message.receive').some((m) => m.id === asked.id));
assert.deepEqual(b.failureNotice({ business: 'demo', run: 'chief-run', code: 'proxy-stall' }), { posted: 1 });
const [line] = lines(store, asked.id);
assert.deepEqual([line.body, line.from_role, line.to_role], [STALL_LINE, 'chief', 'human']);
assert.equal(store.get('SELECT count(*) n FROM message_threads WHERE message=?', line.id).n, 0);
});
test('#1873 F2: failureNotice refuses a malformed record before any write', (t) => {
const { b, store, A } = twoThreads(t);
const session = store.get('SELECT session FROM session_defaults WHERE thread=?', A).session;
const before = store.get('SELECT count(*) n FROM messages').n;
const bad = [
[{ business: 'demo', code: 'limit-reached' }, 'invalid-request'],
[{ business: 'demo', code: 'limit-reached', run: 'a-run', thread: A, session }, 'invalid-request'],
[{ business: 'demo', code: 'Limit Reached', run: 'a-run' }, 'invalid-request'],
[{ business: 'demo', code: 'x'.repeat(65), run: 'a-run' }, 'invalid-request'],
[{ business: 'demo', code: 7, run: 'a-run' }, 'invalid-request'],
[{ business: 'demo', code: 'limit-reached', run: 'a-run', why: 'secret text' }, 'invalid-request'],
[{ business: 'demo', code: 'limit-reached', run: 'nobody-run' }, 'unknown-run'],
[{ business: 'demo', code: 'limit-reached', thread: A, session: 'no-such-session' }, 'session-not-found'],
];
for (const [record, code] of bad) assert.throws(() => b.failureNotice(record), { code }, JSON.stringify(record));
assert.equal(store.get('SELECT count(*) n FROM messages').n, before);
});
+305
View File
@@ -0,0 +1,305 @@
// proxy-scope slice 4 (#1873): the Triage key in the bus. Real organization buses on one instance,
// a stand-in proxy management server on loopback and a temporary config directory; nothing here
// reads a real config, proxy or secret. Each test scans every answer, event, receipt line and
// stderr line for every Triage key the stand-in ever held.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createHash, randomBytes } from 'node:crypto';
import { startBroker } from '../src/runtime.mjs';
import { busOrganization } from '../src/organization-context.mjs';
import { keyPaths, readKey } from '../src/triage-key.mjs';
import { Registry } from '../../seat/src/session.mjs';
import { loadBusiness } from '../../organization/src/organization-config.mjs';
import { resolveInstance } from '../../organization/src/resolve.mjs';
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
const NOW = Date.parse('2026-11-18T12:00:00.000Z');
const MIN = 60_000, HOUR = 60 * MIN, DAY = 24 * HOUR;
const MANAGE = 'fx1873-s4-manage';
const KEY_PATH = '/v8/management/config/access/api-keys';
const sha = s => createHash('sha256').update(s).digest('hex');
const tag = dir => sha(dir).slice(0, 12);
const id = key => sha(key).slice(0, 12);
const b64 = () => randomBytes(32).toString('base64url');
const code = name => e => e.code === name;
// Every Triage key the stand-in ever held, and every text a bus produced, across the file.
const SEEN = new Set();
const TEXTS = [];
function leaks(text) {
for (const key of SEEN) {
const secret = key.slice(-43);
if (text.includes(key) || text.includes(secret)) return key.slice(0, 8);
for (let i = 0; i + 8 <= secret.length; i++) if (text.includes(secret.slice(i, i + 8))) return key.slice(0, 8);
}
return null;
}
// Every stderr line while the test runs: the bus's model-proxy receipt lines go there.
function captureStderr(t) {
const write = process.stderr.write, lines = [];
process.stderr.write = (chunk, ...rest) => { lines.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); };
t.after(() => { process.stderr.write = write; TEXTS.push(lines.join('')); });
return lines;
}
async function instance(t) {
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'tkb-')));
const configDir = join(root, 'config');
fs.mkdirSync(join(configDir, 'secrets'), { recursive: true, mode: 0o700 });
fs.chmodSync(configDir, 0o700); fs.chmodSync(join(configDir, 'secrets'), 0o700);
fs.writeFileSync(join(configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
fs.mkdirSync(join(root, 'proxy'), { mode: 0o700 });
const sentinel = `msk-${tag(configDir)}-sentinel-${b64()}`, orgKey = `mso-${tag(configDir)}-other-key-${b64()}`;
// triagePuts counts the writes that changed a Triage name; the organization buses' own key
// reconcile writes the list too, and those do not count.
const state = { keys: [sentinel, 'foreign-client-key', orgKey], puts: [], triagePuts: 0 };
const triageNames = list => JSON.stringify(list.filter(k => k.startsWith('mst-')).sort());
const server = http.createServer(async (req, res) => {
if (req.url !== KEY_PATH) {
const key = req.headers.authorization?.slice(7);
res.writeHead(state.keys.includes(key) ? 200 : 401); res.end('{}'); return;
}
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end('{}'); return; }
if (req.method === 'GET') { res.end(JSON.stringify(state.keys)); return; }
const chunks = []; for await (const c of req) chunks.push(c);
const next = JSON.parse(Buffer.concat(chunks));
for (const k of next) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
state.puts.push(next);
if (triageNames(next) !== triageNames(state.keys)) state.triagePuts++;
state.keys = next;
res.end('{"status":"ok"}');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
const closers = [];
t.after(async () => {
for (const close of closers.reverse()) await close().catch(() => {});
server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
const receipts = join(root, 'proxy', 'mosaic-keys.receipts.jsonl');
if (fs.existsSync(receipts)) TEXTS.push(fs.readFileSync(receipts, 'utf8'));
fs.rmSync(root, { recursive: true, force: true });
});
const rolesDir = rolesCopy(root), system = systemFor(root);
const f = {
root, configDir, port, state, closers, rolesDir, system, sentinel, orgKey, clock: { now: NOW },
prefix: `mst-${tag(configDir)}-triage-`,
file: keyPaths(configDir).file,
record: () => readKey(configDir),
triageKeys: () => f.state.keys.filter(k => k.startsWith(f.prefix)),
receipts: () => {
const p = join(root, 'proxy', 'mosaic-keys.receipts.jsonl');
return fs.existsSync(p) ? fs.readFileSync(p, 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse) : [];
},
// A real organization bus on this instance. `proxy: false` starts it with no proxy settings, as
// a bus on an instance with no proxy.json does.
async bus(orgId, { proxy = true, triageKeys = {} } = {}) {
const doc = businessDoc(root, orgId);
doc.plugins = { ...doc.plugins, harness: ['pi'] };
writeJson(join(configDir, 'businesses', `${orgId}.json`), doc);
const business = loadBusiness(orgId, { dir: configDir, rolesDir }), resolved = {};
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system, business, instance: name });
const dataRoot = join(root, `${orgId}-bus`);
fs.mkdirSync(dataRoot, { mode: 0o700 }); new Registry(dataRoot);
const bus = await startBroker({ dataRoot, businesses: { [orgId]: busOrganization(business, resolved) },
organization: { dir: configDir, rolesDir, system }, ...(proxy ? { proxy: { port, binary: '/fixture-unused' } } : {}),
org: { id: orgId }, instanceDataRoot: root, instanceConfigDir: configDir,
triageKeys: { intervalMs: 3_600_000, now: () => f.clock.now, ...triageKeys } });
closers.push(() => bus.close());
const cap = bus.broker.bindHuman({ business: orgId, human: business.human ?? doc.human, via: 'cli', outsideAgent: true });
const ask = async (verb, args) => {
try { const answer = await bus.broker.request(cap, { verb, args }); TEXTS.push(JSON.stringify(answer)); return answer; }
catch (error) { TEXTS.push(JSON.stringify({ code: error.code, reason: error.reason, message: error.message, nextStep: error.nextStep })); throw error; }
};
const sweep = async () => { const r = await bus.triageKeySweep(); TEXTS.push(JSON.stringify(r)); return r; };
return { bus, ask, sweep, dataRoot };
},
};
return f;
}
// Every byte under a bus's data root (its store, with events and refusals, and its logs), as text.
function eventsText(b, called = true) {
const out = [];
const walk = dir => {
for (const name of fs.readdirSync(dir)) {
const p = join(dir, name), st = fs.lstatSync(p);
if (st.isDirectory()) walk(p);
else if (st.isFile()) out.push(fs.readFileSync(p).toString('latin1'));
}
};
walk(b.dataRoot);
if (called) assert.ok(out.join('').includes('proxy.triage.key'), 'the store holds the verb\'s events');
return out.join('\n');
}
test('ensure issues one key, a second ensure keeps it, and both answers carry ids only', async t => {
captureStderr(t);
const f = await instance(t);
const a = await f.bus('alpha');
const first = await a.ask('proxy.triage.key', { op: 'ensure' });
assert.equal(first.action, 'issued');
assert.equal(f.triageKeys().length, 1);
const record = f.record();
assert.equal(first.keyId, record.keyId);
assert.equal(first.keyId, id(f.triageKeys()[0]));
assert.deepEqual(first.addedKeyIds, [record.keyId]);
assert.equal(fs.statSync(f.file).mode & 0o777, 0o600);
const second = await a.ask('proxy.triage.key', { op: 'ensure' });
assert.deepEqual(second, { op: 'ensure', action: 'held', addedKeyIds: [], removedKeyIds: [], keyId: record.keyId, rotateBy: record.rotateBy });
assert.equal(f.triageKeys().length, 1, 'ensure twice gives one key');
assert.equal(f.record().key, record.key);
// Through a second riding bus on the same instance: still the one key.
const b = await f.bus('beta');
assert.equal((await b.ask('proxy.triage.key', { op: 'ensure' })).action, 'held');
assert.equal(f.triageKeys().length, 1);
assert.equal(f.state.triagePuts, 1, 'only the first ensure wrote the proxy list');
// The receipt names the change by op and ids.
const receipts = f.receipts().filter(r => r.op?.startsWith('triage.'));
assert.deepEqual(receipts.map(r => [r.op, r.addedKeyIds, r.removedKeyIds]), [['triage.key.ensure', [record.keyId], []]]);
for (const text of [eventsText(a), eventsText(b)]) assert.equal(leaks(text), null);
});
test('ensure replaces a key the proxy lost, and revoke removes every Triage name and the file', async t => {
captureStderr(t);
const f = await instance(t);
const a = await f.bus('alpha');
const issued = await a.ask('proxy.triage.key', { op: 'ensure' });
// The proxy loses the key (removed by hand): ensure issues a new one and names the old as lost.
f.state.keys = f.state.keys.filter(k => !k.startsWith(f.prefix));
const replaced = await a.ask('proxy.triage.key', { op: 'ensure' });
assert.equal(replaced.action, 'replaced');
assert.notEqual(replaced.keyId, issued.keyId);
assert.equal(f.triageKeys().length, 1);
// An orphan in the namespace (a crash left it) goes with revoke too.
const orphan = `${f.prefix}${b64()}`; SEEN.add(orphan);
f.state.keys.push(orphan);
const revoked = await a.ask('proxy.triage.key', { op: 'revoke' });
assert.equal(revoked.action, 'revoked');
assert.deepEqual(revoked.removedKeyIds.sort(), [replaced.keyId, id(orphan)].sort());
assert.equal(f.triageKeys().length, 0);
assert.equal(fs.existsSync(f.file), false);
assert.equal(f.record(), null);
// Revoke again: nothing to do, nothing written.
const puts = f.state.triagePuts;
assert.deepEqual(await a.ask('proxy.triage.key', { op: 'revoke' }), { op: 'revoke', action: 'none', addedKeyIds: [], removedKeyIds: [] });
assert.equal(f.state.triagePuts, puts);
// Namespace guard: the sentinel, the organization key and the foreign key are still there.
for (const k of [f.sentinel, f.orgKey, 'foreign-client-key']) assert.ok(f.state.keys.includes(k), k.slice(0, 4));
assert.equal(leaks(eventsText(a)), null);
});
test('a bus that does not ride the owner\'s proxy refuses triage-no-riding-bus, and its sweep does nothing', async t => {
captureStderr(t);
const f = await instance(t);
const loose = await f.bus('loose', { proxy: false });
await assert.rejects(loose.ask('proxy.triage.key', { op: 'ensure' }), e => e.code === 'triage-no-riding-bus'
&& /^Triage needs one organization that uses the owner's models\./.test(e.nextStep));
await assert.rejects(loose.ask('proxy.triage.key', { op: 'revoke' }), code('triage-no-riding-bus'));
assert.equal(f.state.triagePuts, 0);
// With a key issued through a riding bus and its rotation due, the loose bus still does nothing.
const a = await f.bus('alpha');
await a.ask('proxy.triage.key', { op: 'ensure' });
f.clock.now += 31 * DAY;
assert.deepEqual(await loose.sweep(), { action: 'none' });
assert.equal(f.state.triagePuts, 1);
});
test('the sweep rotates when rotateBy comes, once across two buses that wake together, and again a rotation later', async t => {
captureStderr(t);
const f = await instance(t);
const a = await f.bus('alpha'), b = await f.bus('beta');
const issued = await a.ask('proxy.triage.key', { op: 'ensure' });
// Not due yet: neither bus touches the proxy.
assert.deepEqual([await a.sweep(), await b.sweep()], [{ action: 'none' }, { action: 'none' }]);
assert.equal(f.state.triagePuts, 1);
f.clock.now = Date.parse(`${issued.rotateBy}T00:00:00Z`);
const both = await Promise.all([a.sweep(), b.sweep()]);
assert.deepEqual(both.map(r => r.action).sort(), ['none', 'rotated']);
assert.equal(f.state.triagePuts, 2, 'two buses rotated once');
const rotated = both.find(r => r.action === 'rotated');
const record = f.record();
assert.equal(rotated.keyId, record.keyId);
assert.deepEqual(record.retiring.map(r => r.keyId), [issued.keyId]);
assert.equal(f.triageKeys().length, 2, 'the old key stays live through its grace');
// Inside the grace both buses leave it; at retireAt plus the margin one of them retires it.
const retireAt = Date.parse(record.retiring[0].retireAt);
f.clock.now = retireAt + 10_000;
assert.deepEqual((await Promise.all([a.sweep(), b.sweep()])).map(r => r.action), ['none', 'none']);
f.clock.now = retireAt + 30_000;
const retired = await Promise.all([a.sweep(), b.sweep()]);
assert.deepEqual(retired.map(r => r.action).sort(), ['none', 'retired']);
assert.equal(f.state.triagePuts, 3);
assert.deepEqual(f.triageKeys().map(id), [record.keyId]);
assert.deepEqual(f.record().retiring, []);
// A second rotation 30 days on: again once.
f.clock.now = Date.parse(`${record.rotateBy}T00:00:00Z`) + HOUR;
const again = await Promise.all([b.sweep(), a.sweep()]);
assert.deepEqual(again.map(r => r.action).sort(), ['none', 'rotated']);
assert.equal(f.state.triagePuts, 4);
assert.equal(f.triageKeys().length, 2);
// Namespace guard across every sweep.
for (const k of [f.sentinel, f.orgKey, 'foreign-client-key']) assert.ok(f.state.keys.includes(k), k.slice(0, 4));
const ops = f.receipts().filter(r => r.op?.startsWith('triage.')).map(r => r.op);
assert.deepEqual(ops, ['triage.key.ensure', 'triage.key.rotate', 'triage.key.retire', 'triage.key.rotate']);
for (const bus of [a, b]) assert.equal(leaks(eventsText(bus, bus === a)), null);
});
test('the sweep never issues the first key, and a sweep refusal is a receipt line with a code only', async t => {
const lines = captureStderr(t);
const f = await instance(t);
const a = await f.bus('alpha');
f.clock.now += 400 * DAY;
assert.deepEqual(await a.sweep(), { action: 'none' });
assert.equal(f.state.triagePuts, 0);
assert.equal(f.record(), null);
// A due rotation on a proxy with no sentinel (it may be another proxy): refused, nothing written.
await a.ask('proxy.triage.key', { op: 'ensure' });
f.state.keys = f.state.keys.filter(k => k !== f.sentinel);
f.clock.now += 31 * DAY;
const r = await a.sweep();
assert.deepEqual(r, { action: 'refused', code: 'proxy-not-configured' });
assert.equal(f.state.triagePuts, 1);
const refusal = lines.join('').split('\n').filter(l => l.includes('triage.key.sweep-refused'));
assert.equal(refusal.length, 1);
assert.deepEqual(JSON.parse(refusal[0].replace(/^model-proxy: /, '')), { action: 'triage.key.sweep-refused', code: 'proxy-not-configured', reason: 'triage-key-proxy-open' });
// The same refusal on the next ticks is not logged again within the hour; after it, once more.
const refusals = () => lines.join('').split('\n').filter(l => l.includes('triage.key.sweep-refused')).length;
for (let i = 0; i < 3; i++) { f.clock.now += 30_000; assert.equal((await a.sweep()).code, 'proxy-not-configured'); }
assert.equal(refusals(), 1);
f.clock.now += HOUR;
await a.sweep();
assert.equal(refusals(), 2);
});
test('a revoke stopped between the proxy write and the file is finished by the next revoke; ensure after a stopped revoke replaces the key', async t => {
captureStderr(t);
const f = await instance(t);
let stage = null;
const a = await f.bus('alpha', { triageKeys: { hook: s => { if (s === stage) throw new Error(`stop at ${s}`); } } });
await a.ask('proxy.triage.key', { op: 'ensure' });
stage = 'write';
await assert.rejects(a.ask('proxy.triage.key', { op: 'revoke' }), e => e.code === 'storage-unavailable' && !/stop at/.test(e.message));
assert.equal(f.triageKeys().length, 0, 'the proxy write happened');
assert.ok(f.record(), 'the file stayed');
stage = null;
// ensure now sees a file whose key the proxy lacks: a new key, the old named lost.
const replaced = await a.ask('proxy.triage.key', { op: 'ensure' });
assert.equal(replaced.action, 'replaced');
stage = 'rename';
await assert.rejects(a.ask('proxy.triage.key', { op: 'revoke' }), code('storage-unavailable'));
stage = null;
assert.equal((await a.ask('proxy.triage.key', { op: 'revoke' })).action, 'revoked');
assert.equal(f.record(), null);
assert.equal(f.triageKeys().length, 0);
});
test('no answer, event, receipt line or stderr line in this file holds any Triage key the stand-in saw', () => {
assert.ok(SEEN.size >= 8, `only ${SEEN.size} keys were seen`);
assert.ok(TEXTS.length >= 30, `only ${TEXTS.length} texts`);
for (const text of TEXTS) assert.equal(leaks(text), null);
});
+125
View File
@@ -0,0 +1,125 @@
// proxy-scope slice 4 (#1873): the bus verb proxy.triage.key at the broker. Only the instance
// owner's path-bound proof (a human cap from the cli transport, outside any agent) reaches the
// runtime's hook; an agent, a tester, a Console proof, a grant holder and an organization owner get
// human-required, a reader read-only. The answer and the event carry key ids only, and a hook
// failure that is not a bus refusal becomes storage-unavailable with no text of its own.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Broker, BusError } from '../src/broker.mjs';
import { Store } from '../src/store.mjs';
import { REFUSALS } from '../src/refusals.mjs';
const role = { authority: { withinRole: ['message.send'], crossRole: [] } };
const code = name => error => error.code === name;
const SUBJECT = { provider: 'fixture', iss: 'https://sso.invalid', sub: 'owner-1' };
// A Triage key as triage-key.mjs makes them, so a leak check has a real-looking value to look for.
const KEY = `mst-0123456789ab-triage-${'Q'.repeat(20)}xY_-${'z'.repeat(19)}`;
function fixture(t, { proxyTriageKey = null } = {}) {
const store = new Store(fs.mkdtempSync(join(tmpdir(), 'tkv-bus-')));
t.after(() => store.close());
const b = new Broker({ store, proxyTriageKey, businesses: { demo: { id: 'demo', human: 'owner', arbiters: { technical: 'chief', delivery: 'chief' }, vars: { 'bus.tester': true }, roles: { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } }, coder: role } } } });
return {
store, b,
human: b.bindHuman({ business: 'demo', human: 'owner', via: 'cli', outsideAgent: true }),
tester: b.bindTester({ business: 'demo' }), reader: b.bindReader({ business: 'demo' }),
agent: b.bindLaunch({ business: 'demo', role: 'coder', run: 'tkv-run', harness: 'pi' }),
// The owner's Console proof, a granted account that holds org.hire, and an organization owner
// who is not the instance owner: none is the path-bound cli proof.
console: b.bindConsole({ business: 'demo', human: 'owner', subject: SUBJECT }),
grant: b.bindHireConsole({ business: 'demo', actor: 'grantee', subject: { ...SUBJECT, sub: 'grantee-1' }, rights: ['org.hire', 'decide'] }),
orgOwner: b.bindHireConsole({ business: 'demo', actor: 'orgowner', subject: { ...SUBJECT, sub: 'orgowner-1' }, rights: ['org.hire'], owner: true }),
};
}
const events = store => JSON.stringify(store.all('SELECT body FROM events'));
const bodies = store => store.all('SELECT body FROM events').map(r => JSON.parse(r.body));
test('proxy.triage.key refuses an agent, a tester, a Console proof, a grant holder and an organization owner with human-required, and a reader with read-only', async t => {
let calls = 0;
const f = fixture(t, { proxyTriageKey: async () => { calls++; return { action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-19', addedKeyIds: ['0123456789ab'], removedKeyIds: [] }; } });
for (const op of ['ensure', 'revoke']) {
for (const [name, cap] of [['agent', f.agent], ['tester', f.tester], ['console', f.console], ['grant', f.grant], ['orgOwner', f.orgOwner]])
assert.throws(() => f.b.request(cap, { verb: 'proxy.triage.key', args: { op } }), code('human-required'), `${name} ${op}`);
assert.throws(() => f.b.request(f.reader, { verb: 'proxy.triage.key', args: { op } }), code('read-only'));
}
assert.equal(calls, 0);
// The same verb runs for the owner's cli proof.
const answer = await f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } });
assert.equal(answer.action, 'issued');
assert.equal(calls, 1);
});
test('proxy.triage.key takes op ensure or revoke and nothing else, and a bus with no hook is not-configured', async t => {
let calls = 0;
const f = fixture(t, { proxyTriageKey: async () => { calls++; return { action: 'none', addedKeyIds: [], removedKeyIds: [] }; } });
for (const args of [{}, { op: 'rotate' }, { op: 'issue' }, { op: 'ensure', key: KEY }, { op: 'revoke', force: true }, { op: ['ensure'] }])
assert.throws(() => f.b.request(f.human, { verb: 'proxy.triage.key', args }), code('invalid-request'), JSON.stringify(args));
assert.throws(() => f.b.request(f.human, { verb: 'proxy.triage.key' }), code('invalid-request'));
assert.equal(calls, 0);
assert.equal(events(f.store).includes(KEY), false);
assert.equal(events(f.store).includes(KEY.slice(-43)), false);
const g = fixture(t);
assert.throws(() => g.b.request(g.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } }), code('not-configured'));
});
test('the answer and the event of each op carry ids only, even when the hook returns more', async t => {
const seen = [];
const f = fixture(t, { proxyTriageKey: async op => {
seen.push(op);
// A hook that returns the key beside the ids: the broker copies the named fields only.
return op === 'ensure'
? { action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-19', addedKeyIds: ['0123456789ab'], removedKeyIds: ['ba9876543210'], key: KEY, old: { key: KEY } }
: { action: 'revoked', addedKeyIds: [], removedKeyIds: ['0123456789ab'], key: KEY };
} });
const ensure = await f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } });
assert.deepEqual(ensure, { op: 'ensure', action: 'issued', addedKeyIds: ['0123456789ab'], removedKeyIds: ['ba9876543210'], keyId: '0123456789ab', rotateBy: '2026-12-19' });
const revoke = await f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'revoke' } });
assert.deepEqual(revoke, { op: 'revoke', action: 'revoked', addedKeyIds: [], removedKeyIds: ['0123456789ab'] });
assert.deepEqual(seen, ['ensure', 'revoke']);
assert.deepEqual(bodies(f.store).filter(b => b.call === 'proxy.triage.key'), [{ call: 'proxy.triage.key', ...ensure }, { call: 'proxy.triage.key', ...revoke }]);
for (const text of [JSON.stringify(ensure), JSON.stringify(revoke), events(f.store)]) {
assert.equal(text.includes(KEY), false);
assert.equal(text.includes(KEY.slice(-43)), false);
}
});
test('an answer the broker cannot vouch for refuses proxy-client-response and records no allowed event', async t => {
const answers = [
null, { action: 'issued' },
{ action: 'deleted', keyId: '0123456789ab', addedKeyIds: [], removedKeyIds: [] },
{ action: 'issued', keyId: KEY, addedKeyIds: [], removedKeyIds: [] },
{ action: 'issued', keyId: '0123456789ab', addedKeyIds: [KEY], removedKeyIds: [] },
{ action: 'held', keyId: '0123456789ab', addedKeyIds: [], removedKeyIds: 'none' },
];
let next = 0;
const f = fixture(t, { proxyTriageKey: async () => answers[next++] });
for (const answer of answers)
await assert.rejects(f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } }), code('proxy-client-response'), JSON.stringify(answer));
await assert.rejects(Promise.resolve().then(() => fixture(t, { proxyTriageKey: async () => ({ action: 'issued', addedKeyIds: [], removedKeyIds: [] }) }))
.then(g => g.b.request(g.human, { verb: 'proxy.triage.key', args: { op: 'revoke' } })), code('proxy-client-response'));
assert.equal(bodies(f.store).some(b => b.call === 'proxy.triage.key'), false);
assert.equal(events(f.store).includes(KEY.slice(-43)), false);
});
test('a bus refusal from the hook passes through with its guidance; any other failure is storage-unavailable and names nothing from the error', async t => {
const f = fixture(t, { proxyTriageKey: async op => { throw op === 'ensure' ? new BusError('triage-no-riding-bus') : Object.assign(new Error(`boom ${KEY} /home/x`), { code: 'EACCES' }); } });
await assert.rejects(f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'ensure' } }), e => e.code === 'triage-no-riding-bus'
&& /Triage needs one organization that uses the owner's models/.test(e.nextStep ?? REFUSALS['triage-no-riding-bus'].nextStep));
await assert.rejects(f.b.request(f.human, { verb: 'proxy.triage.key', args: { op: 'revoke' } }), e => e.code === 'storage-unavailable'
&& !JSON.stringify({ ...e, message: e.message }).includes(KEY.slice(-43)) && !String(e.message).includes('/home/x'));
assert.equal(events(f.store).includes(KEY.slice(-43)), false);
});
test('the two slice 4 codes have refusal-table entries with a next step and no absolute path', () => {
for (const c of ['triage-no-riding-bus', 'triage-key-rotated']) {
const entry = REFUSALS[c];
assert.ok(entry, c);
assert.equal(typeof entry.nextStep, 'string', c);
assert.ok(entry.nextStep.length > 20, c);
assert.equal(/\/(home|mnt|srv|tmp)\//.test(entry.nextStep), false, c);
}
assert.match(REFUSALS['triage-no-riding-bus'].nextStep, /^Triage needs one organization that uses the owner's models\./);
});
+34 -1
View File
@@ -302,6 +302,11 @@ export function createLauncher({
let ticking = false;
const stopping = new Set();
const refusedThreads = new Map();
// #1873 chat-fail F2: the refusal and message each thread session's plain line was asked for.
const noticedThreads = new Map();
// #1873 F2: the last refusal seen per thread start, and the last failed post of its line.
const refusalSeen = new Map();
const noticeFailed = new Map();
const startedFor = new Map();
// Row 271 (264d): each clear's stop time (by op), and each clear refusal logged once (by op and code).
const clearStops = new Map();
@@ -896,7 +901,13 @@ export function createLauncher({
}
children.set(run, exited);
const outputWatch = admittedProxy ? watchModelOutput({ runDir, armAtFirstTurn: true, keyId: modelKeyId, seconds: system.proxy.firstOutputSeconds ?? 120,
stop: () => host.op({ op: 'modelStall', business: b.id, role: instance, run, keyId: modelKeyId }), receipt: record }) : null;
stop: async () => {
const out = await host.op({ op: 'modelStall', business: b.id, role: instance, run, keyId: modelKeyId });
// #1873 chat-fail F2: the message the stopped turn was on gets one plain line, as a failed turn's.
try { await host.op({ op: 'failureNotice', record: { business: b.id, run, code: 'proxy-stall' } }); }
catch (err) { log(`run ${run}: failure line refused: ${err.code ?? 'failed'}`); }
return out;
}, receipt: record }) : null;
exited.then(async ({ code, signal }) => {
outputWatch?.cancel();
let receipt;
@@ -1066,8 +1077,30 @@ export function createLauncher({
await start({ instance: t.instance, launchedBy: b.human, ...where, legacy: t.legacy, legacyThread: legacyThreads.has(t.thread), ...(await check(t.instance, where)) });
startedFor.set(key, signature);
refusedThreads.delete(key);
noticedThreads.delete(key);
refusalSeen.delete(key);
noticeFailed.delete(key);
} catch (e) {
const code = e instanceof Refusal ? e.code : "launch-failed";
// #1873 chat-fail F2: the person who wrote gets one plain line per message the refusal
// leaves unanswered. Asked once per code and message; the bus keeps it to one per message.
// launch-failed can be a lost race that the next try wins, so it gets a line only when
// the same message is refused with it twice in a row. A post that fails is tried again
// on the next tick, and its failure is logged once.
const noticed = `${code}|${signature}`;
const repeated = refusalSeen.get(key) === noticed;
refusalSeen.set(key, noticed);
if (noticedThreads.get(key) !== noticed && (code !== "launch-failed" || repeated)) {
try {
await host.op({ op: "failureNotice", record: { business: b.id, thread: t.thread, session: t.session, code } });
noticedThreads.set(key, noticed);
noticeFailed.delete(key);
} catch (err) {
const failed = `${noticed}|${err.code ?? "failed"}`;
if (noticeFailed.get(key) !== failed) log(`thread ${t.thread} session ${t.session}: failure line refused: ${err.code ?? "failed"}`);
noticeFailed.set(key, failed);
}
}
// Logged once per code, not once per tick.
if (refusedThreads.get(key) === code) return;
refusedThreads.set(key, code);
+2 -2
View File
@@ -16,7 +16,7 @@
//
// mosaic triage key issue | rotate | retire | status
//
// Triage's own model proxy client key (packages/cli/src/triage-key.mjs). Human verbs as well,
// Triage's own model proxy client key (packages/bus/src/triage-key.mjs, shared with the bus). Human verbs as well,
// refused in an agent run before anything is read. No output names a key, only its id.
import { lstatSync } from "node:fs";
import { join } from "node:path";
@@ -24,7 +24,7 @@ import { fileURLToPath } from "node:url";
import { readRoute, RouteStoreError, writeRoute } from "../../webui/src/triage-route-store.mjs";
import { loadSystem } from "./config.mjs";
import { configDir } from "../../organization/src/organization-config.mjs";
import { issueKey, keyPaths, keyStatus, retireKeys, rotateKey, TriageKeyError } from "./triage-key.mjs";
import { issueKey, keyPaths, keyStatus, retireKeys, rotateKey, TriageKeyError } from "../../bus/src/triage-key.mjs";
import { CliError } from "./errors.mjs";
import { refuseInsideAgent } from "./transport.mjs";
+1
View File
@@ -105,6 +105,7 @@ async function start(t, { f, adapter }, { businessId = "acme", orgRoot, copyTran
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -99,6 +99,7 @@ async function start(t, { f, adapter }) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
+1
View File
@@ -30,6 +30,7 @@ const ops = {
credentialStatus: m => runtime.credentialStatus(m.business, m.role),
threadsState: m => runtime.threadsState(m.business),
threadIdle: m => runtime.threadIdle(m.record),
failureNotice: m => runtime.failureNotice(m.record),
mayLaunch: m => runtime.mayLaunch(m),
landHeld: m => runtime.landHeld(m.record),
landHolders: m => runtime.landHolders(m.business),
@@ -77,6 +77,7 @@ async function start(t, { f, adapter }, threadIdle) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => threadIdle(runtime, m),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -95,6 +95,7 @@ async function start(t, { f, adapter }, { tickMs = 100, ops: replace } = {}) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -48,6 +48,7 @@ function requestHost(x) {
landHeld: m => x.bus.landHeld(m.record), landHolders: m => x.bus.landHolders(m.business),
sessionClears: m => x.bus.sessionClears(m.business),
threadsState: m => x.bus.threadsState(m.business), lifecycleRequests: m => x.bus.lifecycleRequests(m.business),
failureNotice: m => x.bus.failureNotice(m.record),
'request.admission': m => x.bus.admission(m), 'request.launches': m => x.bus.requestLaunches(m.business),
'request.launchResult': m => x.bus.requestLaunchResult(m.record), 'request.manifest': m => x.bus.requestManifest(m.record),
'request.release': m => x.bus.requestRelease(m.cap, m.record), 'request.chief': m => x.bus.requestChief(m.business),
+2 -1
View File
@@ -151,7 +151,8 @@ const log = (f) => readFileSync(launchLogFile(f.dataRoot, "acme"), "utf8").trim(
test('P3 proxy key reaches the spawned runner but never session.json or the bundle', { skip, timeout: 30000 }, async t => {
const proxy = { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' };
const prepared = prepare(t, doc => {
doc.launch.models['claude-opus-5-5'] = { provider: 'proxy', model: 'claude-fixture', route: 'anthropic' };
// #1873 harness-matrix: a Claude route on pi is refused, so the key check rides a non-Claude proxy route.
doc.launch.models['claude-opus-5-5'] = { provider: 'proxy', model: 'fixture-route-model', route: 'glm' };
return doc;
});
const { launcher, f, close } = await setup(t, doc => doc, prepared, { testProxy: proxy });
+1
View File
@@ -95,6 +95,7 @@ async function start(t, { f, adapter }, options = {}) {
definitionScan: (m) => runtime.definitionScan({ business: m.business, definition: m.definition, entry: m.entry }),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -21,12 +21,20 @@ const id = value => createHash('sha256').update(value).digest('hex').slice(0,12)
// #774 R2: extra names more harnesses to switch on and load (a fallback route's); real names the
// harnesses loaded as the real module, so their own preflight runs; hostEnv adds launcher env
// such as MOSAIC_CLAUDE_BIN.
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only, so the pi stream case reads
// a non-Claude model the proxy serves in Anthropic format (upstream other) from a stand-in catalogue.
// The chief's model key stays claude-opus-5-5; on pi its upstream model is not a Claude name.
export const PI_CHIEF_MODEL='fixture-chief-model';
const STREAM_OTHER=Object.freeze({provider:'other',model:'fixture-stream-model',module:'cliproxy',upstream:'other'});
const streamCatalogue=()=>({invalidate(){},read:async()=>({status:'ready',observedAt:'2026-11-19T00:00:00.000Z',notices:[],
models:[{key:'other-fixture-stream-model',module:'cliproxy',upstream:'other',provider:'other',model:'fixture-stream-model',label:'other / fixture-stream-model',available:true,reason:'unverified',harnesses:['claude-code','pi']}]})});
export async function managedLaunchFixture(t,{proxy=true,launches=true,refuseProbe=false,harness='pi',bwrap=null,admit=null,extra=[],real=[],hostEnv={},modelStream=null,modelCatalogue=null}={}){
const root=fs.mkdtempSync(join(tmpdir(),'ml653-')),closers=[],history=new Set(['fx653-manage']),proxyReceipts=[],logs=[];
let server,bus,launcher,stderr;const trace={preflightAttempts:0,successfulPreflights:0,enableBeforeSpawn:[],bindings:[],stalls:[],ops:[]};
const checkHistory=entries=>{const text=JSON.stringify(entries);for(const value of history)if(text.includes(value))throw Error('fixture credential leaked');};
t.after(async()=>{const failures=[];for(const close of [...closers].reverse()){try{await close();}catch{failures.push('owned-close');}}try{server?.closeAllConnections();if(server?.listening)await new Promise((resolve,reject)=>server.close(e=>e?reject(e):resolve()));}catch{failures.push('owned-server-close');}try{checkHistory({logs,proxyReceipts,trace});}catch{failures.push('value-free-receipts');}if(stderr)process.stderr.write=stderr;try{fs.rmSync(root,{recursive:true,force:true});}catch{failures.push('owned-root-close');}if(failures.length)throw new AggregateError(failures.map(code=>Error(code)),'owned managed fixture cleanup failed');});
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:[harness,...extra]};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness};doc.roles.chief.vars.model='claude-opus-5-5';if(modelStream){doc.launch.models['claude-opus-5-5']={provider:'anthropic',model:'claude-opus-5-5'};}return doc;});
const f=fixture(root,'acme',doc=>{doc.plugins={...doc.plugins,harness:[harness,...extra]};for(const role of Object.values(doc.roles))role.vars={...role.vars,harness};doc.roles.chief.vars.model='claude-opus-5-5';if(harness==='pi')doc.launch.models['claude-opus-5-5']={provider:'zai',model:PI_CHIEF_MODEL};if(modelStream){doc.launch.models['claude-opus-5-5']=harness==='pi'?STREAM_OTHER:{provider:'anthropic',model:'claude-opus-5-5'};if(harness==='pi')doc.plugins={...doc.plugins,'model-provider':['cliproxy']};}return doc;});
if(modelStream&&harness==='pi'&&!modelCatalogue)modelCatalogue=streamCatalogue();
const env={PATH:process.env.PATH,HOME:process.env.HOME,TMPDIR:process.env.TMPDIR,MOSAIC_CONFIG:f.config,MOSAIC_ROLES_DIR:f.roles,...hostEnv};
// The nonproxy positive fixture supplies its own fake pi login. Managed
// proxy fixtures deliberately hold no upstream credential at all.
@@ -90,6 +98,7 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
case 'landRelease':return bus.landRelease(m.record);
case 'threadsState':return bus.threadsState(m.business);
case 'threadIdle':return bus.threadIdle(m.record);
case 'failureNotice':return bus.failureNotice(m.record);
case 'lifecycleRequests':return bus.lifecycleRequests(m.business);
case 'sessionClears':return bus.sessionClears(m.business);
default:throw Error('fixture unrequested trusted operation');
@@ -11,8 +11,11 @@ async function launched(t,options){const f=await managedLaunchFixture(t,options)
test('653 actual managed proxy launch stays idle unarmed then stops first silent turn through trusted runtime',{skip,timeout:30000},async t=>{
const {f,s}=await launched(t);assert.equal(f.trace.successfulPreflights,1);assert.deepEqual(f.trace.enableBeforeSpawn,[true]);assert.equal(f.trace.bindings[0].modelKeyId,f.expectedKeyId());assert.equal(s.modelKeyId,f.expectedKeyId());assert.notEqual(s.pid,s.runnerPid);
await pause(1250);assert.equal(f.trace.stalls.length,0,'idle beyond configured initial budget does not stop');assert.equal(fs.existsSync(join(s.runDir,'proxy-first-turn')),false);assert.equal(startTimeOf(s.runnerPid),s.runnerStartTime);
const before=process.hrtime.bigint();f.send('SILENT');await waitFor(()=>fs.existsSync(join(s.runDir,'proxy-first-turn')),'actual managed adapter turn publishes marker');const stamp=BigInt(fs.readFileSync(join(s.runDir,'proxy-first-turn'),'utf8').trim().split(' ')[1]);assert.ok(stamp>=before&&stamp<=process.hrtime.bigint());assert.equal(fs.existsSync(join(s.runDir,'proxy-first-output')),false);
await waitFor(()=>f.trace.stalls.length===1,'actual caller watcher reaches trusted modelStall');assert.deepEqual(f.trace.stalls,[{run:s.run,keyId:s.modelKeyId,stopped:true}]);await waitFor(()=>f.sessions().length===0,'normal managed exit unregisters session');assert.equal(f.launchLog().some(r=>r.action==='proxy-stall'&&r.keyIds?.includes(s.modelKeyId)&&!r.code),true);f.assertHistoryGuard();f.valueFree();
const before=process.hrtime.bigint();const sent=f.send('SILENT');await waitFor(()=>fs.existsSync(join(s.runDir,'proxy-first-turn')),'actual managed adapter turn publishes marker');const stamp=BigInt(fs.readFileSync(join(s.runDir,'proxy-first-turn'),'utf8').trim().split(' ')[1]);assert.ok(stamp>=before&&stamp<=process.hrtime.bigint());assert.equal(fs.existsSync(join(s.runDir,'proxy-first-output')),false);
await waitFor(()=>f.trace.stalls.length===1,'actual caller watcher reaches trusted modelStall');assert.deepEqual(f.trace.stalls,[{run:s.run,keyId:s.modelKeyId,stopped:true}]);await waitFor(()=>f.sessions().length===0,'normal managed exit unregisters session');assert.equal(f.launchLog().some(r=>r.action==='proxy-stall'&&r.keyIds?.includes(s.modelKeyId)&&!r.code),true);f.assertHistoryGuard();
// #1873 chat-fail F2: the stopped turn's message gets one plain line, as a failed turn's.
const line=await f.reply(sent);assert.equal(line.body,"The turn failed: the model service gave no answer in time, so the turn was stopped. Try again, or check the account in Settings > Model setup.\nDetails: stopped: proxy-stall");assert.deepEqual([line.from_role,line.from_run,line.class],['chief','bus','RESULT']);
f.valueFree();
});
test('653 actual managed proxy output cancels caller watcher and first timestamp never resets',{skip,timeout:30000},async t=>{
const {f,s}=await launched(t);const first=f.send('OUTPUT');const answer=await f.reply(first);assert.equal(answer.body,'fx653-private-output');const file=join(s.runDir,'proxy-first-turn'),stamp=fs.readFileSync(file,'utf8');assert.equal(fs.statSync(file).mode&0o777,0o600);assert.equal(fs.readFileSync(join(s.runDir,'proxy-first-output'),'utf8'),'output\n');
+27 -7
View File
@@ -34,10 +34,11 @@ function privateArtifacts(f, session, keys) {
f.valueFree();
}
// #1873 harness-matrix: an OAuth Claude model runs on claude-code only, so pi joins the z.ai and
// codex routes on a non-Claude model, and a Claude route on pi refuses below.
const ROUTE_MODEL = 'fixture-route-model';
for (const [provider, route, generated, api] of [
['zai', null, 'mosaic-proxy-glm', 'openai-completions'],
['anthropic', null, 'anthropic', 'anthropic-messages'],
['proxy', 'anthropic', 'anthropic', 'anthropic-messages'],
['proxy', 'glm', 'mosaic-proxy-glm', 'openai-completions'],
['proxy', 'codex', 'mosaic-proxy-codex', 'openai-responses'],
]) {
@@ -45,8 +46,7 @@ for (const [provider, route, generated, api] of [
const f = await managedLaunchFixture(t);
assert.deepEqual(f.upstreamCredentialNames, [], 'managed proxy fixture has no inherited fake upstream credential');
editBusiness(f, doc => {
doc.launch.models['claude-opus-5-5'].provider = provider;
if (route) doc.launch.models['claude-opus-5-5'].route = route;
doc.launch.models['claude-opus-5-5'] = { provider, model: ROUTE_MODEL, ...(route ? { route } : {}) };
});
const answer = await f.launcher.launchPm();
const session = f.sessions().find(value => value.run === answer.run);
@@ -69,7 +69,7 @@ for (const [provider, route, generated, api] of [
assert.equal(models.providers[generated].api, api);
assert.equal(models.providers[generated].baseUrl,
other.baseUrl + (api === 'anthropic-messages' ? '' : '/v1'));
assert.equal(models.providers[generated].models.some(model => model.id === 'claude-opus-5-5'), true);
assert.equal(models.providers[generated].models.some(model => model.id === ROUTE_MODEL), true);
for (const value of Object.values(models.providers)) assert.equal(value.apiKey, '$ANTHROPIC_API_KEY');
for (const key of [own.key, other.key]) assert.equal(text.includes(key), false, 'models contain no key value');
assert.equal(fs.statSync(path).mode & 0o777, 0o600);
@@ -79,6 +79,26 @@ for (const [provider, route, generated, api] of [
});
}
// A legacy entry with no provider plugin gets no catalogue check, so a Claude-named model on a z.ai
// or codex route is treated as OAuth too (review P1-1).
for (const [provider, route, name] of [['anthropic', null], ['proxy', 'anthropic'], ['zai', null, 'claude-opus-5-5'], ['proxy', 'glm', 'claude-opus-5-5'], ['proxy', 'codex', 'claude-sonnet-5-5']]) {
test(`#1873 a stored Claude route ${provider}${route ? ':' + route : ''}${name ? ' ' + name : ''} on pi refuses model-harness-incompatible with no key acquisition or session`, { skip, timeout: 30000 }, async t => {
const f = await managedLaunchFixture(t);
editBusiness(f, doc => {
doc.launch.models['claude-opus-5-5'].provider = provider;
if (route) doc.launch.models['claude-opus-5-5'].route = route;
if (name) doc.launch.models['claude-opus-5-5'].model = name;
});
await assert.rejects(f.launcher.launchPm(), error => error.code === 'model-harness-incompatible');
assert.equal(f.trace.preflightAttempts, 0, 'refused before P2 issues a key');
assert.equal(f.trace.bindings.length, 0);
assert.equal(f.sessions().length, 0);
assert.equal(f.runDirectories().length, 0);
assert.equal(f.launchLog().some(e => e.event === 'refused' && e.code === 'model-harness-incompatible'), true);
f.valueFree();
});
}
test('P3 joined Claude harness receives the admitted P2 key only through transient auth env', { skip, timeout: 30000 }, async t => {
const f = await managedLaunchFixture(t, { harness: 'claude-code' });
assert.deepEqual(f.upstreamCredentialNames, [], 'Claude proxy fixture holds no upstream credential');
@@ -117,7 +137,7 @@ test('P3 joined unsupported provider refuses with no key acquisition, fallback,
test('row 332 R2 joined pi launch goes live when launch.models also holds an unroutable entry, which models.json leaves out', { skip, timeout: 30000 }, async t => {
const f = await managedLaunchFixture(t);
editBusiness(f, doc => {
doc.launch.models['claude-opus-5-5'].provider = 'anthropic';
doc.launch.models['claude-opus-5-5'] = { provider: 'zai', model: ROUTE_MODEL };
doc.launch.models.router = { provider: 'openrouter', model: 'x' };
});
const answer = await f.launcher.launchPm();
@@ -126,7 +146,7 @@ test('row 332 R2 joined pi launch goes live when launch.models also holds an unr
assert.equal(f.trace.successfulPreflights, 1);
assert.equal(f.runDirectories().length, 1, 'one run directory, the live one');
const { providers } = JSON.parse(fs.readFileSync(join(session.runDir, 'home', '.pi', 'agent', 'models.json'), 'utf8'));
assert.equal(providers.anthropic.models.some(model => model.id === 'claude-opus-5-5'), true);
assert.equal(providers['mosaic-proxy-glm'].models.some(model => model.id === ROUTE_MODEL), true);
assert.equal(Object.values(providers).some(value => value.models.some(model => model.id === 'x')), false, 'no openrouter entry');
privateArtifacts(f, session, [f.bus.credentials.modelRecord('acme/chief').key]);
});
@@ -95,6 +95,7 @@ function requestHost(x) {
landHeld: m => x.bus.landHeld(m.record), landHolders: m => x.bus.landHolders(m.business),
sessionClears: m => x.bus.sessionClears(m.business),
threadsState: m => x.bus.threadsState(m.business), lifecycleRequests: m => x.bus.lifecycleRequests(m.business),
failureNotice: m => x.bus.failureNotice(m.record),
'request.admission': m => x.bus.admission(m), 'request.launches': m => x.bus.requestLaunches(m.business),
'request.launchResult': m => x.bus.requestLaunchResult(m.record), 'request.manifest': m => x.bus.requestManifest(m.record),
'request.release': m => x.bus.requestRelease(m.cap, m.record), 'request.chief': m => x.bus.requestChief(m.business),
@@ -96,6 +96,7 @@ async function start(t, { f, adapter, access }, threadsState) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => threadsState(runtime, m),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -92,6 +92,7 @@ async function start(t, { f, adapter }, { tickMs = 100, stopTimeoutMs } = {}) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -112,6 +112,7 @@ async function start(t, { f, adapter }, { tickMs = 100, ops: replace } = {}) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
+73
View File
@@ -93,6 +93,7 @@ async function start(t, { f, adapter }, { tickMs = 100, ops: replace } = {}) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
@@ -496,6 +497,78 @@ test("REQ-LIMIT-3 REQ-LIMIT-4 a thread start whose instance is at its token limi
assert.equal(launchLog(f).filter((e) => e.event === "refused" && e.thread === A).length, 1);
});
// #1873 chat-fail F2: a refused start leaves one plain line in the chat for each message it left
// unanswered, with the cause and next step, never one per retry and never the refusal's reason.
const LIMIT_LINE = "The turn failed: the agent reached a usage limit. Wait for it to reset, or check the limits in Settings.\nDetails: start refused: limit-reached";
test("#1873 F2 a refused thread start puts one plain line per unanswered message in the chat, not one per retry", { skip, timeout: 60000 }, async (t) => {
const prepared = prepare(t, { edit: atLimit });
const { f } = prepared;
const host = await start(t, prepared);
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
const A = host.call("thread.create", { project, name: "alpha" }).id;
const first = host.call("thread.send", { thread: A, body: "for A" });
const lines = (sent) => host.call("thread.messages", { thread: A }).filter((m) => m.in_reply_to === sent.id);
const [line] = await until(() => lines(first).length && lines(first));
assert.equal(line.body, LIMIT_LINE);
assert.deepEqual([line.from_role, line.from_run], ["assistant", "bus"]);
assert.equal(line.to_role, "human");
assert.equal(line.class, "RESULT");
assert.doesNotMatch(line.body, /token-limit|tokens\.instances|"limit"/, "the refusal's reason stays out of the chat");
for (let i = 0; i < 3; i++) await host.launcher.tick();
assert.equal(lines(first).length, 1, "a retry adds no line");
// A second message gets its own line; the first keeps its one.
const second = host.call("thread.send", { thread: A, body: "again" });
await until(() => lines(second).length);
for (let i = 0; i < 3; i++) await host.launcher.tick();
assert.deepEqual(lines(second).map((m) => m.body), [LIMIT_LINE]);
assert.equal(lines(first).length, 1);
assert.deepEqual(threadRuns(f, A), []);
// The messages stay pending: the start is retried and answers them once the limit allows.
assert.equal(launchLog(f).filter((e) => e.event === "refused" && e.thread === A).length, 1);
});
// #1873 review round 1 (P2-2): launch-failed can be a lost race that the next try wins, so one
// such refusal posts nothing and the answer arrives alone; the same refusal twice posts one line.
const failedLines = (host, thread) => host.call("thread.messages", { thread }).filter((m) => m.body.startsWith("The turn failed"));
test("#1873 F2 one launch-failed refusal that the next start clears leaves no failure line", { skip, timeout: 60000 }, async (t) => {
const prepared = prepare(t);
let throws = 1;
const host = await start(t, prepared, { ops: (runtime) => ({ landHeld: (m) => { if (throws-- > 0) throw new Error("fixture: lost race"); return runtime.landHeld(m.record); } }) });
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
const A = host.call("thread.create", { project, name: "alpha" }).id;
const sent = host.call("thread.send", { thread: A, body: "for A" });
const reply = await until(() => host.call("thread.messages", { thread: A }).find((m) => m.in_reply_to === sent.id && m.class === "RESULT"));
assert.match(reply.body, /THREAD \{/, "the first reply is the answer");
assert.equal(throws, -1, "the first start was refused");
assert.deepEqual(failedLines(host, A), []);
});
test("#1873 F2 the same launch-failed refusal twice for one message posts one line", { skip, timeout: 60000 }, async (t) => {
const prepared = prepare(t);
const host = await start(t, prepared, { ops: () => ({ landHeld: () => { throw new Error("fixture: always refused"); } }) });
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
const A = host.call("thread.create", { project, name: "alpha" }).id;
host.call("thread.send", { thread: A, body: "for A" });
const [line] = await until(() => failedLines(host, A).length && failedLines(host, A));
assert.match(line.body, /\nDetails: start refused: launch-failed$/);
for (let i = 0; i < 3; i++) await host.launcher.tick();
assert.equal(failedLines(host, A).length, 1);
});
// #1873 review round 1 (P3-3): a line whose post fails is posted on a later tick, once.
test("#1873 F2 a failure line whose post is refused once arrives on a later tick, exactly once", { skip, timeout: 60000 }, async (t) => {
const prepared = prepare(t, { edit: atLimit });
let throws = 1;
const host = await start(t, prepared, { ops: (runtime) => ({ failureNotice: (m) => { if (throws-- > 0) throw new Error("fixture: bus busy"); return runtime.failureNotice(m.record); } }) });
const project = host.call("project.create", { name: "stack work", repo: "stack" }).id;
const A = host.call("thread.create", { project, name: "alpha" }).id;
host.call("thread.send", { thread: A, body: "for A" });
const [line] = await until(() => failedLines(host, A).length && failedLines(host, A));
assert.equal(line.body, LIMIT_LINE);
assert.equal(throws, -1, "the first post was refused");
for (let i = 0; i < 3; i++) await host.launcher.tick();
assert.equal(failedLines(host, A).length, 1);
assert.equal(host.logs.filter((l) => /failure line refused/.test(l)).length, 1);
});
test("REQ-LIMIT-4 a thread run at its token limit stops at the end of its turn: the reply lands, and the end record names the limit", { skip, timeout: 60000 }, async (t) => {
const prepared = prepare(t, { edit: atLimit });
const { f } = prepared;
@@ -97,6 +97,7 @@ async function start(t, { f, adapter, access }) {
credentialStatus: (m) => runtime.credentialStatus(m.business, m.role),
threadsState: (m) => runtime.threadsState(m.business),
threadIdle: (m) => runtime.threadIdle(m.record),
failureNotice: (m) => runtime.failureNotice(m.record),
mayLaunch: (m) => runtime.mayLaunch(m),
landHeld: (m) => runtime.landHeld(m.record),
landHolders: (m) => runtime.landHolders(m.business),
+1 -1
View File
@@ -12,7 +12,7 @@ import { join } from "node:path";
import { createHash, randomBytes } from "node:crypto";
import { run } from "../src/cli.mjs";
import { AGENT_MARKERS } from "../src/transport.mjs";
import { DEFAULT_ROTATE_GRACE_MINUTES, keyPaths, retireAtFor, rotateByFor } from "../src/triage-key.mjs";
import { DEFAULT_ROTATE_GRACE_MINUTES, keyPaths, retireAtFor, rotateByFor } from "../../bus/src/triage-key.mjs";
import { ModelKeys } from "../../bus/src/model-keys.mjs";
import { ManagementClient } from "../../model-proxy/src/client.mjs";
import { startBroker } from "../../bus/src/runtime.mjs";
+8 -3
View File
@@ -100,7 +100,8 @@ export function sessionModel(resolved, models = null, which = "primary", { proxy
if (models === null) return { harness, provider: null, model, thinking };
const entry = Object.hasOwn(models, model) ? models[model] : null;
if (!entry) throw new BundleError(`instance ${resolved.instance}: unknown model table selection for ${ROUTE_VARS[which][1]} var`);
const transport = entry.provider === "proxy" || proxy ? checkedTransport(entry, null, resolver) : null;
// #1873 harness-matrix: the route's own harness, so a model the module holds off it refuses here.
const transport = entry.provider === "proxy" || proxy ? checkedTransport(entry, harness, resolver) : null;
return { harness, provider: entry.provider, model: entry.model, modelKey: model, thinking,
...(transport ? { proxyRoute: transport.routeId, proxyTransport: transport } : {}) };
@@ -432,9 +433,13 @@ export function buildBundle({ dir, resolved, contract, arbiter = false, tracker
];
// The module's own files. A name the bundle already wrote refuses at write (flag wx).
const transports = {};
// #1873 harness-matrix: only models the provider's route() lets this session's harness run, so a
// pi session's models.json never names an upstream claude model or a Claude-named legacy entry.
// route() has no account data: a module entry the catalogue holds to claude-code for an OAuth name
// can still be listed. Only the session's own model is admitted against the catalogue.
if (proxy) for (const [key, entry] of Object.entries(models ?? {})) {
try { transports[key] = checkedTransport(entry, null, resolver); }
catch (e) { if (e?.code !== 'proxy-provider-unsupported') throw e; }
try { transports[key] = checkedTransport(entry, model.harness, resolver); }
catch (e) { if (!['proxy-provider-unsupported', 'model-harness-incompatible'].includes(e?.code)) throw e; }
}
const own = harness.bundle({ dir, files: { ...files }, session: { ...session, ...model }, write, quote, models, proxy, transports });
Object.assign(files, own.files);
+153
View File
@@ -1,2 +1,155 @@
// Shared by the sender and recipient's reply-cycle check.
export const LENGTH_FAILURE_NOTICE_PREFIX = 'Mosaic turn failure: ';
// #1873 chat-fail F1: the plain cause of a failed turn. It lives here, not in a file of its own,
// because the session sandbox mounts only RUNNER_FILES (packages/seat/src/sandbox.mjs) and this
// file is already one of them.
//
// The adapter contract (adapters/README.md) puts the answer on stdout and makes a
// nonzero exit a failure. A harness that ends on an error result may still print that
// result on stdout before it exits nonzero. That text is the only cause the runner
// has, so the chat line carries it, made safe first:
//
// 0. %XX escapes and HTML character references are decoded and the text is put in NFKC
// form, so an encoded or full-width email, path or secret is seen as itself.
// 1. ANSI escapes go, every control, format, separator, surrogate and private-use
// character goes, and whitespace collapses to single spaces.
// 2. If a secret the turn's environment holds (a variable named like a key, token,
// secret, password or credential) appears in the text, even split by whitespace or
// controls, no text is shown at all.
// 3. Links, email addresses, absolute and Windows paths, "Bearer x" values, the value after
// a key word ("key: x", "\"api_key\":\"x\"", "token x"), known key prefixes and long
// letter-and-digit runs become [redacted].
// 4. The rest is cut to CAUSE_MAX characters.
//
// Only the last READ_MAX characters are classified and shown. A harness prints its error
// result last, and an answer streamed before the failure may itself talk about limits or
// signing in. Redaction runs over the whole text first, so the cut never parts a key word
// from its value.
//
// Three causes are recognised from the text and shown as a fixed plain line with the
// next step: the account is out of usage, its sign-in expired or was refused, or it
// doesn't offer the model. Anything else shows the cleaned text. The fixed lines never
// carry any of the error's own words.
export const CAUSE_MAX = 300;
const READ_MAX = 2000;
export const PLAIN = Object.freeze({
usage: "the model account is out of usage. Check Settings > Model setup.",
signin: "the model account's sign-in expired or was refused. Sign in again in Settings > Model setup.",
model: "the model this agent uses isn't offered by its account. Pick another model in Settings > Model setup.",
});
export const WITHHELD = "the error text held a secret, so it isn't shown. Check Settings > Model setup.";
const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
// Cf (format: zero-width, bidi overrides) is removed so a split token rejoins and is seen.
const INVISIBLE = /[\p{Cf}\p{Cs}\p{Co}]/gu;
// Cc (C0, DEL, C1), line and paragraph separators become spaces.
const BREAKS = /[\p{Cc}\p{Zl}\p{Zp}]/gu;
const USAGE = /usage limit|hit your [\w -]{0,24}limit|(?<!context |output |token |length )limit reached|credit balance is too low|insufficient[_ ]quota|quota (?:exceeded|exhausted)|exceeded your current quota|out of (?:usage|credits)/i;
const SIGNIN = /(?:oauth |access |auth )?token (?:has )?expired|invalid api key|invalid x-api-key|invalid bearer token|authentication_error|authentication failed|run \/login|not logged in|unauthori[sz]ed|(?:error|status)[: ]+401\b|sign[- ]?in (?:again|required|expired)|log ?in (?:again|required|expired)|invalid_grant/i;
const MODEL = /issue with the selected model|model_not_found|\bmodel\b.{0,80}\b(?:not found|does not exist|not available|isn't available|not supported|may not exist|not offered|no access)|not_found_error.{0,80}\bmodel\b|unknown model|no such model/i;
const ENTITY = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", commat: "@", lowbar: "_", period: ".", colon: ":", sol: "/", bsol: "\\", num: "#", equals: "=", hyphen: "-", dash: "-" };
function codePoint(n) {
return Number.isInteger(n) && n > 0 && n <= 0x10ffff && (n < 0xd800 || n > 0xdfff) ? String.fromCodePoint(n) : " ";
}
// %XX escapes (twice encoded included) and HTML character references are decoded, then NFKC
// folds full-width and compatibility forms to their plain letters.
export function decodeText(text) {
let out = String(text);
for (let i = 0; i < 3; i++) {
const next = out
.replace(/(?:%[0-9a-f]{2})+/gi, run => { try { return decodeURIComponent(run); } catch { return run.replace(/%([0-9a-f]{2})/gi, (_, h) => String.fromCharCode(parseInt(h, 16))); } })
.replace(/&#(\d{1,7});?|&#x([0-9a-f]{1,6});?|&([a-z]{2,7});/gi, (all, dec, hex, name) =>
dec ? codePoint(Number(dec)) : hex ? codePoint(parseInt(hex, 16)) : ENTITY[name.toLowerCase()] ?? all);
if (next === out) break;
out = next;
}
return out.normalize("NFKC");
}
// The text with every space, control, format, mark, surrogate and private-use character gone,
// for the env-secret check.
function compactText(text) {
return decodeText(text).replace(ANSI, "").replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{M}\p{Z}\s]/gu, "");
}
const SECRET_NAME = /KEY|TOKEN|SECRET|PASS|CRED|AUTH|COOKIE/i;
// Values from the turn's environment that must never reach a chat line.
export function secretValues(env) {
const out = [];
for (const [name, value] of Object.entries(env ?? {})) {
if (typeof value !== "string" || !SECRET_NAME.test(name)) continue;
const compact = compactText(value);
if (compact.length >= 8) out.push(compact);
}
return out;
}
// A key word, with any prefix joined by _ or - (access_token, client_secret, x-api-key).
const KEY_WORD = "(?:\\w*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization|cookie|session)";
// Redaction runs over the whole text, up to the runner's 128000 characters, so a pattern that
// could start anywhere inside a long run without spaces starts only where the run starts: it
// matches the same text in linear time, not quadratic.
const REDACT = [
/(?<![a-z0-9+.-])[a-z0-9+.-]+:\/\/\S*/gi, // any link, its userinfo and query included, from the run's start
/\bwww\.\S+/gi,
/(?<!\S)(?=\S*\S@\S)\S+/g, // email addresses and user@host: the whole run holding the @
/(?:^|(?<=[\s("'=:]))(?:~|\.{1,2})?\/\S+/g, // absolute and home paths
/\b[A-Za-z]:\\\S*/g, // Windows paths
/\\\\\S+/g, // UNC paths
/\b(?:bearer|basic)\s+\S+/gi,
// The value after a key word: "key: x", "key=x" and the JSON form "\"api_key\":\"x\"" always;
// "token x" with only a space when x is quoted, holds a digit or is 8 characters or more.
new RegExp(`\\b${KEY_WORD}["']?\\s*[:=]\\s*(?:"[^"]*"?|'[^']*'?|[^\\s,;}]+)`, "gi"),
new RegExp(`\\b${KEY_WORD}["']?\\s+(?:"[^"]*"?|'[^']*'?|(?=[^\\s"',;}]*\\d)[^\\s"',;}]+|[^\\s"',;}]{8,})`, "gi"),
/\b(?:sk|msk|rk|pk|ghp|gho|ghs|glpat|xox[a-z])[-_]\S+/gi,
/\beyJ\S+/g, // JWT
// A long run that mixes letters and digits, or any very long run, reads as a key.
/[A-Za-z0-9_\-+/=.]{32,}/g,
/(?<![A-Za-z0-9_\-+/=.])(?=[A-Za-z0-9_\-+/=.]*\d)(?=[A-Za-z0-9_\-+/=.]*[A-Za-z])[A-Za-z0-9_\-+/=.]{16,}/g,
];
export function cleanText(text) {
return String(text).replace(ANSI, "").replace(INVISIBLE, "").replace(BREAKS, " ").replace(/\s+/g, " ").trim();
}
// A text read from its tail keeps its end, where the error is; any other keeps its start.
function cap(text, fromEnd = false, n = CAUSE_MAX) {
const chars = Array.from(text);
if (chars.length <= n) return text;
return fromEnd ? "..." + chars.slice(-(n - 3)).join("") : chars.slice(0, n - 3).join("") + "...";
}
// The plain cause for a failed turn's stdout, or null when there is no text.
// `secrets` is secretValues(env) for the turn.
export function turnCause(stdout, secrets = []) {
if (typeof stdout !== "string") return null;
const decoded = decodeText(stdout);
const clean = cleanText(decoded);
if (!clean) return null;
// The secret check covers the whole text, not only the part that is read.
const compact = compactText(stdout);
if (secrets.some(value => compact.includes(value))) return WITHHELD;
// Only the tail is classified and shown. Redaction runs over the whole text before any cut,
// so a cut that lands between a key word and its value can't leave the value bare.
const tail = clean.length > READ_MAX;
const read = tail ? clean.slice(-READ_MAX) : clean;
if (USAGE.test(read)) return PLAIN.usage;
if (SIGNIN.test(read)) return PLAIN.signin;
if (MODEL.test(read)) return PLAIN.model;
let shown = clean;
for (const re of REDACT) shown = shown.replace(re, "[redacted]");
shown = shown.replace(/(?:\[redacted\]\s*){2,}/g, "[redacted] ").trim();
// The cut drops the partial word it lands in; a redacted text short enough needs no cut.
if (shown.length > READ_MAX) shown = shown.slice(-READ_MAX).replace(/^\S+\s*/, "");
// Text that redacts to nothing but [redacted] says nothing; the technical reason stands alone.
return shown && shown !== "[redacted]" ? cap(shown, tail) : null;
}
// The chat body for a failed turn: the plain cause first, the technical reason after.
export const DETAILS = "\nDetails: ";
export function failureBody(turn) {
return turn.cause ? `The turn failed: ${turn.cause}${DETAILS}${turn.reason}` : `The turn failed: ${turn.reason}`;
}
+10 -5
View File
@@ -41,7 +41,7 @@ import { createServer, connect } from "node:net";
import { basename, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { Client } from "../../bus/src/client.mjs";
import { LENGTH_FAILURE_NOTICE_PREFIX } from "./failure-notice.mjs";
import { LENGTH_FAILURE_NOTICE_PREFIX, failureBody, secretValues, turnCause } from "./failure-notice.mjs";
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
import { firstOutputMarker, firstTurnMarker } from './first-output.mjs';
import { GUARD_CODES, FIXED_TEXTS } from "../../library/src/reply-protocol.mjs";
@@ -508,7 +508,12 @@ function runTurn({ session, request, n, env, onChild }) {
const missing = missingCommand(stderrTail(errPath));
return resolve({ ok: false, reason: `adapter exited 127${missing ? ` (command not found: ${missing})` : ""}` });
}
if (code !== 0) return resolve({ ok: false, reason: signal ? `adapter killed by ${signal}` : `adapter exited ${code}` });
if (signal) return resolve({ ok: false, reason: `adapter killed by ${signal}` });
if (code !== 0) {
// #1873 chat-fail F1: an adapter that ends on an error result prints it on stdout.
const cause = turnCause(out, secretValues(env));
return resolve({ ok: false, reason: `adapter exited ${code}`, ...(cause ? { cause } : {}) });
}
// A "marker" harness (row 65: the module's turnEnd()) writes the marker when its turn ends.
if (session.turnEnd === "marker" && !existsSync(marker)) return resolve({ ok: false, reason: `${session.harness} exited before the turn ended (no turn marker)` });
resolve({ ok: true, text: out.trim() });
@@ -801,11 +806,11 @@ export async function main(runDir, { stdin = process.stdin, env = process.env, l
catch (e) { log(`runner: failure record for ${m.id} failed: ${e.code ?? e.message}`); if (ended(e, false)) break loop; }
continue;
}
if (!turn.ok) log(`runner: turn ${n} for message ${m.id} failed: ${turn.reason}`);
if (!turn.ok) log(`runner: turn ${n} for message ${m.id} failed: ${turn.reason}${turn.cause ? ` (${turn.cause})` : ""}`);
try {
if (!isLengthFailureNotice(m) && m.class !== "RESULT" && (m.class === "REQUEST" || ["human", "tester", "user"].includes(m.from_role) || m.in_reply_to_class !== "RESULT")) {
if (!library) {
const body = turn.ok ? turn.text || "(the session gave no answer)" : `The turn failed: ${turn.reason}`;
const body = turn.ok ? turn.text || "(the session gave no answer)" : failureBody(turn);
await client.call("message.send", { to: m.from_role, body: clip(body) + unslop.note(), class: "RESULT", in_reply_to: m.id });
unslop.sent();
} else {
@@ -858,7 +863,7 @@ export async function main(runDir, { stdin = process.stdin, env = process.env, l
await client.call("message.read", { id: m.id });
continue;
}
if (!retry.ok) log(`runner: retry turn ${n} for message ${m.id} failed: ${retry.reason}`);
if (!retry.ok) log(`runner: retry turn ${n} for message ${m.id} failed: ${retry.reason}${retry.cause ? ` (${retry.cause})` : ""}`);
try { await send(retry); }
catch (again) {
if (!GUARD_CODES.includes(again.code) && again.code !== "request-too-large") throw again;
@@ -205,3 +205,14 @@ test('a library continuation that succeeds sends the cited RESULT once', async t
assert.equal(f.count(),2);
assert.equal(f.store.get("SELECT count(*) n FROM messages WHERE from_role='coder'").n,1);
});
// #1873 chat-fail review round 1: a failed citation retry logs its plain cause, as the first turn does.
test('a failed citation retry logs the plain cause of the failure', async t => {
let sends = 0;
const f = await setup(t, commit => [{ text: citedBody([fixtureCite(commit)]) }, { text: 'Claude AI usage limit reached', exitCode: 1 }], {
guard: async () => { if (sends++ === 0) throw new GuardError('citation-unavailable', 'The library is busy.'); return null; },
});
await f.call(f.human, 'message.send', { to: 'coder', body: 'Fixture question.', class: 'REQUEST' });
await until(() => /runner: retry turn \d+ for message \S+ failed: /.test(f.log()));
assert.match(f.log(), /runner: retry turn \d+ for message \S+ failed: adapter exited 1 \(the model account is out of usage/);
});
@@ -0,0 +1,142 @@
import { fixtureCacheEnv } from '../../../scripts/testing/lane-fixtures.mjs';
// #1873 harness-matrix: claude-code runs a proxy model that is not a Claude model. The host's claude
// CLI runs through adapters/claude with the bundle and env a z.ai or codex selection gives, against a
// local stand-in for the proxy's Anthropic-format route. The stand-in records the path, the model
// name claude sends and the hash of the key it carries. Scratch CLAUDE_CONFIG_DIR and HOME, a fixture
// key, nonessential traffic off: nothing reaches a real model or account. Whether the real proxy
// turns that request into a z.ai or codex call is proved only on the dev instance.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { createServer as createHttp } from 'node:http';
import { spawn, spawnSync } from 'node:child_process';
import { mkdirSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { buildBundle, checkedTransport } from '../src/bundle.mjs';
import { adapterEnv } from '../src/runner.mjs';
import { fakeToolSocket, HARNESS, REPO, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
import * as cliproxy from '../../plugins/model-provider/cliproxy/index.mjs';
const ADAPTER = join(REPO, 'adapters', 'claude', 'adapter.sh');
const which = spawnSync('sh', ['-c', 'command -v claude'], { encoding: 'utf8' });
const CLAUDE = which.status === 0 ? which.stdout.trim() : null;
const skip = CLAUDE ? false : 'claude is not on PATH';
const sha = (s) => createHash('sha256').update(s).digest('hex');
// The proxy's Anthropic-format route, as a stand-in: every /v1/messages answers with one text block.
async function standIn(t, text) {
const seen = [];
const server = createHttp((req, res) => {
let raw = '';
req.on('data', (c) => (raw += c));
req.on('end', () => {
const auth = String(req.headers.authorization ?? '').replace(/^Bearer /, '');
const apiKey = String(req.headers['x-api-key'] ?? '');
if (req.method !== 'POST' || !/^\/v1\/messages(\?|$)/.test(req.url)) {
seen.push({ path: req.url, method: req.method, authSha: auth ? sha(auth) : null, apiKeySha: apiKey ? sha(apiKey) : null });
res.writeHead(req.url.includes('count_tokens') ? 200 : 404, { 'content-type': 'application/json' });
return res.end(JSON.stringify(req.url.includes('count_tokens') ? { input_tokens: 10 } : { type: 'error', error: { type: 'not_found_error', message: 'stand-in' } }));
}
const body = JSON.parse(raw || '{}');
seen.push({ path: req.url.split('?')[0], method: req.method, model: body.model, authSha: auth ? sha(auth) : null, apiKeySha: apiKey ? sha(apiKey) : null });
const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify({ type: event, ...data })}\n\n`);
if (!body.stream) {
res.writeHead(200, { 'content-type': 'application/json' });
return res.end(JSON.stringify({ id: 'msg_si', type: 'message', role: 'assistant', model: body.model, content: [{ type: 'text', text }], stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 10, output_tokens: 5 } }));
}
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
send('message_start', { message: { id: 'msg_si', type: 'message', role: 'assistant', model: body.model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 } } });
send('content_block_start', { index: 0, content_block: { type: 'text', text: '' } });
send('content_block_delta', { index: 0, delta: { type: 'text_delta', text } });
send('content_block_stop', { index: 0 });
send('message_delta', { delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 5 } });
send('message_stop', {});
res.end();
});
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
t.after(() => server.close());
return { url: `http://127.0.0.1:${server.address().port}`, seen };
}
function turn(env, request, cwd) {
return new Promise((resolve) => {
const child = spawn('/bin/sh', [ADAPTER], { cwd, env: { ...env, ...fixtureCacheEnv(env.CLAUDE_CONFIG_DIR), MOSAIC_REQUEST: request }, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
let stdout = '', stderr = '';
child.stdout.on('data', (b) => (stdout += b));
child.stderr.on('data', (b) => (stderr += b));
const clock = setTimeout(() => process.kill(-child.pid, 'SIGKILL'), 120_000);
child.on('close', (code) => { clearTimeout(clock); resolve({ code, stdout, stderr }); });
});
}
const SELECTIONS = {
zai: { provider: 'zai', model: 'glm-fixture', module: 'cliproxy', upstream: 'zai' },
codex: { provider: 'codex', model: 'gpt-fixture', module: 'cliproxy', upstream: 'codex' },
};
// The route's api and endpoint describe pi's wire. claude-code ignores them: its env is the proxy
// root and the key, and it always posts Anthropic Messages there, whatever the upstream.
test('#1873 the catalogue offers a z.ai and a codex model to claude-code and pi, and the route admits both harnesses', async () => {
const c = await cliproxy.catalogue({
listAccounts: async () => ({ files: [{ provider: 'codex', name: 'codex-fixture.json', status: 'active' }] }),
listModels: async () => ({ models: [{ id: 'gpt-fixture' }] }),
listGroups: async () => [{ 'base-url': cliproxy.ZAI_URL, keys: [{}], models: [{ name: 'glm-fixture' }] }],
now: () => 1,
});
assert.equal(c.status, 'ready');
for (const [name, entry] of Object.entries(SELECTIONS)) {
const row = c.models.find((m) => m.upstream === entry.upstream && m.model === entry.model);
assert.deepEqual(row?.harnesses, ['claude-code', 'pi'], name);
for (const harness of ['claude-code', 'pi']) {
assert.deepEqual(cliproxy.preflight({ selection: entry, harness, catalogue: c }), { allow: true }, `${name} ${harness}`);
assert.equal(checkedTransport(entry, harness).piProvider, `mosaic-proxy-${entry.upstream === 'zai' ? 'glm' : 'codex'}`, `${name} ${harness}`);
}
}
});
for (const [name, entry] of Object.entries(SELECTIONS)) {
test(`#1873 claude-code sends the ${name} model name to the proxy's Anthropic-format route with the session key`, { skip }, async (t) => {
const dir = scratch(t, 'mosaic-claude-proxy-');
const workspace = join(dir, 'ws'); mkdirSync(workspace);
const runDir = join(dir, 'run'); mkdirSync(runDir, { mode: 0o700 });
const api = await standIn(t, `stand-in answer for ${entry.model}`);
const key = `fx1873-claude-${name}`;
const resolved = resolvedFor(t, 'coder', (d) => {
d.launch.models.proxied = entry;
d.roles.coder.vars = { harness: 'claude-code', model: 'proxied', thinking: 'low', 'limits.tools': ['read'] };
});
const sock = await fakeToolSocket(t, dir, (tool, args) => ({ tool, args }));
const session = { workspace, sessionDir: join(dir, 'session'), toolSocket: sock.path, turnMarker: join(dir, 'turn.done'), runDir };
const bundle = buildBundle({
dir: join(runDir, 'bundle'), resolved, models: { proxied: entry }, contract: '# Coder\n',
harness: HARNESS['claude-code'], skillsDir: REPO_SKILLS, proxy: { baseUrl: api.url, key },
session: { ...session, run: 'r1873', launchedBy: 'pm' },
});
// The proxy's names come from the harness module's env, and nothing on disk holds the key.
assert.equal(bundle.env.ANTHROPIC_BASE_URL, api.url);
assert.equal(bundle.env.ANTHROPIC_AUTH_TOKEN, key);
assert.equal(Object.hasOwn(bundle.env, 'ANTHROPIC_API_KEY'), false);
for (const file of Object.values(bundle.files)) if (typeof file === 'string') {
let text = ''; try { text = readFileSync(file, 'utf8'); } catch {}
assert.equal(text.includes(key), false, file);
}
const s = { ...session, harness: 'claude-code', provider: entry.provider, model: entry.model, bundle: bundle.files, harnessEnv: bundle.env };
const env = adapterEnv(s, {
PATH: `${dirname(CLAUDE)}:${dirname(process.execPath)}:/usr/bin:/bin`,
HOME: join(dir, 'home'), CLAUDE_CONFIG_DIR: join(dir, 'claude-config'),
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_TELEMETRY: '1', DISABLE_AUTOUPDATER: '1', DISABLE_ERROR_REPORTING: '1',
});
const r = await turn(env, 'Message 1 from pm, class ASSIGNMENT:\n\nsay hello', workspace);
assert.equal(r.code, 0, r.stderr.replaceAll(key, '<key>'));
assert.match(r.stdout, new RegExp(`stand-in answer for ${entry.model}`));
const messages = api.seen.filter((x) => x.path === '/v1/messages');
assert.ok(messages.length >= 1, JSON.stringify(api.seen));
// The main turn names the selected model. Claude Code may add its own small background
// requests; every request carries the session key as a bearer token and none uses x-api-key.
assert.ok(messages.some((x) => x.model === entry.model), JSON.stringify(messages.map((x) => x.model)));
for (const x of api.seen) { assert.equal(x.authSha, sha(key), x.path); assert.equal(x.apiKeySha, null, x.path); }
assert.equal(r.stdout.includes(key) || r.stderr.includes(key), false);
});
}
+34 -23
View File
@@ -10,6 +10,7 @@ const models = {
a: { provider: 'proxy', model: 'claude-fixture', route: 'anthropic' },
z: { provider: 'proxy', model: 'glm-fixture', route: 'glm' },
g: { provider: 'proxy', model: 'gpt-fixture', route: 'codex' },
o: { provider: 'other', model: 'fixture-other', module: 'cliproxy', upstream: 'other' },
};
function build(t, selection, proxy, declared) {
const root = scratch(t, 'p332-'), runDir = join(root, 'run');
@@ -32,14 +33,22 @@ function assertSafe(value) {
else if (value && typeof value === 'object') for (const item of Object.values(value)) assertSafe(item);
}
test('P3 Anthropic route uses messages at proxy root and the declared model id', t => {
const b = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a: models.a });
const { anthropic } = JSON.parse(b.text).providers;
assert.equal(anthropic.api, 'anthropic-messages');
assert.equal(anthropic.baseUrl, 'http://127.0.0.1:12345');
assert.deepEqual(anthropic.models.map(m => m.id), ['claude-fixture']);
assert.equal(b.env.PI_PROVIDER, 'anthropic');
assert.equal(b.env.PI_MODEL, 'claude-fixture');
// #1873 harness-matrix: a Claude account model runs on claude-code only, so a pi session on it
// refuses before any file is written.
test('a proxy Claude route on pi refuses model-harness-incompatible before model config generation', t => {
for (const a of [models.a, { provider: 'anthropic', model: 'fixture-chat' }, { provider: 'anthropic', model: 'fixture-chat', module: 'cliproxy', upstream: 'claude' }])
assert.throws(() => build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a }), { code: 'model-harness-incompatible' }, JSON.stringify(a));
});
test('an other-upstream route uses messages at proxy root under its own pi provider, never pi\'s built-in anthropic', t => {
const b = build(t, 'o', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { o: models.o });
const providers = JSON.parse(b.text).providers;
assert.deepEqual(Object.keys(providers), ['mosaic-proxy-other']);
assert.equal(providers['mosaic-proxy-other'].api, 'anthropic-messages');
assert.equal(providers['mosaic-proxy-other'].baseUrl, 'http://127.0.0.1:12345');
assert.deepEqual(providers['mosaic-proxy-other'].models.map(m => m.id), ['fixture-other']);
assert.equal(b.env.PI_PROVIDER, 'mosaic-proxy-other');
assert.equal(b.env.PI_MODEL, 'fixture-other');
});
test('P3 omitted route refuses proxy-route-missing before model config generation', t => {
@@ -82,9 +91,11 @@ test('P3 a declared Codex route generates only the single build-time responses p
test('P3 models file is private, references the one session key, and stores no executable values or keys', t => {
const key = 'fx332-agent-a';
const b = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key }, { a: models.a, z: models.z });
const b = build(t, 'z', { baseUrl: 'http://127.0.0.1:12345', key }, { a: models.a, z: models.z, o: models.o });
const document = JSON.parse(b.text);
assert.deepEqual(Object.keys(document.providers).sort(), ['anthropic', 'mosaic-proxy-glm']);
// #1873: the Claude account entry is left out of a pi session's file.
assert.deepEqual(Object.keys(document.providers).sort(), ['mosaic-proxy-glm', 'mosaic-proxy-other']);
assert.ok(!b.text.includes('claude-fixture'));
for (const provider of Object.values(document.providers)) assert.equal(provider.apiKey, '$ANTHROPIC_API_KEY');
assertSafe(document);
assert.ok(!b.text.includes(key));
@@ -96,20 +107,20 @@ test('P3 models file is private, references the one session key, and stores no e
});
test('P3 every launch regenerates proxy port, declared models and own key without caching', t => {
const first = build(t, 'a', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { a: models.a, z: models.z });
const second = build(t, 'a', { baseUrl: 'http://127.0.0.1:23456', key: 'fx332-agent-b' }, {
a: { provider: 'proxy', model: 'changed-model-id', route: 'anthropic' },
const first = build(t, 'z', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, { g: models.g, z: models.z });
const second = build(t, 'z', { baseUrl: 'http://127.0.0.1:23456', key: 'fx332-agent-b' }, {
g: { provider: 'proxy', model: 'changed-model-id', route: 'codex' },
z: { provider: 'proxy', model: 'changed-glm-id', route: 'glm' },
});
assert.equal(second.env.ANTHROPIC_API_KEY, 'fx332-agent-b');
assert.ok(!JSON.stringify(second).includes('fx332-agent-a'));
const { providers } = JSON.parse(second.text);
assert.deepEqual(Object.keys(providers), ['anthropic', 'mosaic-proxy-glm']);
assert.equal(providers.anthropic.baseUrl, 'http://127.0.0.1:23456');
assert.deepEqual(providers.anthropic.models.map(m => m.id), ['changed-model-id']);
assert.deepEqual(Object.keys(providers), ['mosaic-proxy-codex', 'mosaic-proxy-glm']);
assert.equal(providers['mosaic-proxy-codex'].baseUrl, 'http://127.0.0.1:23456/v1');
assert.deepEqual(providers['mosaic-proxy-codex'].models.map(m => m.id), ['changed-model-id']);
assert.equal(providers['mosaic-proxy-glm'].baseUrl, 'http://127.0.0.1:23456/v1');
assert.deepEqual(providers['mosaic-proxy-glm'].models.map(m => m.id), ['changed-glm-id']);
assert.equal(JSON.parse(first.text).providers.anthropic.baseUrl, 'http://127.0.0.1:12345');
assert.equal(JSON.parse(first.text).providers['mosaic-proxy-glm'].baseUrl, 'http://127.0.0.1:12345/v1');
});
// Row 332 R2 (#1830, review F2): launch.models is open table data. An entry whose provider has no
@@ -121,14 +132,14 @@ test('row 332 R2 an unroutable model table entry is left out of models.json and
glm: { provider: 'zai', model: 'glm-fixture' },
router: { provider: 'openrouter', model: 'x' },
};
const b = build(t, 'opus', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, declared);
const b = build(t, 'glm', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, declared);
const { providers } = JSON.parse(b.text);
assert.deepEqual(Object.keys(providers).sort(), ['anthropic', 'mosaic-proxy-glm']);
assert.deepEqual(providers.anthropic.models.map(m => m.id), ['claude-fixture']);
// #1873: the Claude account entry is one a pi session can't run, so it is left out too.
assert.deepEqual(Object.keys(providers).sort(), ['mosaic-proxy-glm']);
assert.deepEqual(providers['mosaic-proxy-glm'].models.map(m => m.id), ['glm-fixture']);
assert.ok(!Object.values(providers).some(p => p.models.some(m => m.id === 'x')), 'the openrouter entry is not written');
assert.equal(b.env.PI_MODEL, 'claude-fixture');
assert.throws(() => build(t, 'opus', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, {
assert.equal(b.env.PI_MODEL, 'glm-fixture');
assert.throws(() => build(t, 'glm', { baseUrl: 'http://127.0.0.1:12345', key: 'fx332-agent-a' }, {
...declared, broken: { provider: 'proxy', model: 'claude-fixture' },
}), { code: 'proxy-route-missing' });
});
@@ -140,7 +151,7 @@ test('row 332 R2 a session proxy context without a key or loopback URL refuses i
{ baseUrl: 'http://localhost:12345', key: 'fx332-agent-a' },
{ baseUrl: 'http://127.0.0.1:12345' },
]) {
assert.throws(() => build(t, 'a', proxy, { a: models.a }),
assert.throws(() => build(t, 'z', proxy, { z: models.z }),
{ code: 'invalid-proxy-context', message: 'invalid session proxy context' }, JSON.stringify(proxy));
}
});
+25 -5
View File
@@ -3,12 +3,12 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { sessionModel } from '../src/bundle.mjs';
const resolved = { instance: 'fixture', vars: { harness: 'pi', model: 'selected', thinking: 'low' } };
for (const [provider, model, expected] of [
['anthropic', 'glm-looking-id', 'anthropic'],
['zai', 'gpt-looking-id', 'glm'],
for (const [provider, model, expected, harness] of [
['anthropic', 'glm-looking-id', 'anthropic', 'claude-code'],
['zai', 'gpt-looking-id', 'glm', 'pi'],
]) {
test(`joined proxy context maps provider ${provider} by identity, not model name`, () => {
const selected = sessionModel(resolved, { selected: { provider, model } }, 'primary', { proxy: true });
const selected = sessionModel({ ...resolved, vars: { ...resolved.vars, harness } }, { selected: { provider, model } }, 'primary', { proxy: true });
assert.equal(selected.proxyRoute, expected);
assert.equal(selected.provider, provider, 'public/accounting provider identity is retained');
assert.equal(selected.model, model);
@@ -31,7 +31,7 @@ test('provider proxy still requires an explicit route inside joined context', ()
assert.throws(() => sessionModel(resolved, { selected: { provider: 'proxy', model: 'fixture', route: 'custom' } }, 'primary', { proxy: true }), {
code: 'proxy-route-unknown',
});
assert.equal(sessionModel(resolved, { selected: { provider: 'proxy', model: 'claude-looking-id', route: 'codex' } }, 'primary', { proxy: true }).proxyRoute, 'codex');
assert.equal(sessionModel(resolved, { selected: { provider: 'proxy', model: 'fixture-codex-id', route: 'codex' } }, 'primary', { proxy: true }).proxyRoute, 'codex');
});
test('a module-backed selection carries the provider transport descriptor without changing accounting', () => {
const selected = sessionModel(resolved, { selected: { provider: 'codex', model: 'fixture-codex', module: 'cliproxy', upstream: 'codex' } }, 'primary', { proxy: true });
@@ -52,3 +52,23 @@ test('transport accepts bounded compatibility flags declared by a provider modul
const resolver=()=>({provider:'fixture',model:'fixture-id',routeId:'fixture',endpoint:'v1',api:'openai-completions',piProvider:'fixture',compat:{supportsStore:false,thinkingFormat:'openai'}});
assert.deepEqual(sessionModel(resolved,{selected:entry},'primary',{proxy:true,resolver}).proxyTransport.compat,{supportsStore:false,thinkingFormat:'openai'});
});
// #1873 harness-matrix: the launch checks the route's own harness, so a stored OAuth Claude route on pi
// is refused before any run, with or without a model-provider module switched on.
test('a stored proxy Claude route on pi refuses model-harness-incompatible at launch', () => {
for (const selected of [{ provider: 'anthropic', model: 'fixture-chat' }, { provider: 'proxy', route: 'anthropic', model: 'fixture-chat' },
{ provider: 'anthropic', model: 'fixture-chat', module: 'cliproxy', upstream: 'claude' }])
assert.throws(() => sessionModel(resolved, { selected }, 'primary', { proxy: true }), { code: 'model-harness-incompatible' }, JSON.stringify(selected));
// Jason 2026-11-19: the rule keys on the account kind. A module entry, whose kind the catalogue
// knows, runs on pi with a Claude name. A legacy entry carries no account data, so a Claude name
// there is treated as OAuth.
for (const selected of [{ provider: 'other', model: 'anthropic/claude-sonnet-5-5', module: 'cliproxy', upstream: 'other' },
{ provider: 'zai', model: 'claude-looking-id', module: 'cliproxy', upstream: 'zai' }, { provider: 'zai', model: 'glm-fixture' }])
assert.equal(sessionModel(resolved, { selected }, 'primary', { proxy: true }).model, selected.model, JSON.stringify(selected));
for (const selected of [{ provider: 'proxy', route: 'codex', model: 'claude-looking-id' }, { provider: 'zai', model: 'claude-looking-id' }, { provider: 'proxy', route: 'glm', model: 'claude-opus-5-5' }])
assert.throws(() => sessionModel(resolved, { selected }, 'primary', { proxy: true }), { code: 'model-harness-incompatible' }, JSON.stringify(selected));
const claudeCode = { ...resolved, vars: { ...resolved.vars, harness: 'claude-code' } };
assert.equal(sessionModel(claudeCode, { selected: { provider: 'anthropic', model: 'fixture-chat' } }, 'primary', { proxy: true }).proxyRoute, 'anthropic');
for (const selected of [{ provider: 'zai', model: 'fixture-zai' }, { provider: 'codex', model: 'fixture-codex', module: 'cliproxy', upstream: 'codex' }])
assert.equal(sessionModel(claudeCode, { selected }, 'primary', { proxy: true }).provider, selected.provider);
});
+59 -1
View File
@@ -322,6 +322,63 @@ test("r127 an adapter exit 127 names the program that wasn't found, through the
r.child.kill("SIGTERM"); await r.exited;
});
// #1873 chat-fail F1: a turn that ended on the harness's error result showed only "adapter exited 1".
// The real claude adapter prints the CLI's final error result on stdout and exits with the CLI's code.
test("chat-fail F1 an error result from the harness reaches the chat line as a plain cause and next step", async t => {
const ctx = await setup(t, {session:{harness:"claude-code", turnEnd:"exit", adapter:new URL("../../../adapters/claude/adapter.sh", import.meta.url).pathname}});
const sessionFile = join(ctx.runDir, "session.json");
const session = JSON.parse(readFileSync(sessionFile, "utf8"));
const bin = join(ctx.dir, "model-fixture");
const result = {type:"result", subtype:"success", is_error:true, result:"You've hit your limit \u00b7 resets 3pm (UTC)"};
writeFileSync(bin, `#!${process.execPath}\nconsole.log(${JSON.stringify(JSON.stringify(result))});\nprocess.exit(1);\n`, {mode:0o755});
session.harnessEnv = {MOSAIC_CLAUDE_BIN:bin, MOSAIC_THINKING:"low", MOSAIC_CLAUDE_SETTINGS:session.bundle.policy, MOSAIC_CLAUDE_MCP_CONFIG:session.bundle.tools};
writeFileSync(sessionFile, JSON.stringify(session));
ctx.inbox = [];
const r = startRunner(ctx.runDir, ctx.cap);
t.after(() => r.child.kill("SIGKILL"));
const sent = ctx.call(ctx.pm, "message.send", {to:"coder", body:"hello", class:"REQUEST"});
const [reply] = await until(replies(ctx));
await until(() => ctx.store.get("SELECT 1 FROM deliveries WHERE message=? AND op='read'", sent.id));
assert.equal(reply.body, "The turn failed: the model account is out of usage. Check Settings > Model setup.\nDetails: adapter exited 1");
assert.match(r.stderr(), /failed: adapter exited 1 \(the model account is out of usage/);
r.child.kill("SIGTERM"); await r.exited;
});
test("chat-fail F1 error text is cleaned, redacted and capped; a held secret withholds it; no text keeps the bare reason", async t => {
const secret = "fixture-secret-0123456789abcdef";
const ctx = await setup(t, {session:{harnessEnv:{MOSAIC_FIXTURE_TOKEN:secret}}});
const adapter = join(ctx.dir, "adapter.sh");
// HOSTILE: ANSI, C0, C1, DEL, bidi and zero-width characters, a link with a query and userinfo, an
// email, a path, a Bearer value, key prefixes, a JWT and a long text. LEAK: the turn's own secret,
// split by a newline and a zero-width space. QUIET: nothing on stdout.
writeFileSync(adapter, [
'case "$MOSAIC_REQUEST" in',
// The long text comes first: the harness prints its error result last, and only the tail is read.
`*HOSTILE*) head -c 2000 /dev/zero | tr '\\0' 'w'; printf '\\n\\033[31mAPI Error: 500\\033[0m \\001\\177\\302\\205 boom \\342\\200\\256evil\\342\\200\\213 https://u:[email protected]/x?key=abc [email protected] /home/someone/.config/x Bearer abc.def sk-ant-api03-zzz msk-abcdef eyJhbGciOi.eyJzdWIi.sig AbCdEf0123456789XyZ\\n'; exit 1 ;;`,
`*LEAK*) printf 'failed: fixture-secret-01234\\n5678\\342\\200\\2139abcdef\\n'; exit 1 ;;`,
`*QUIET*) exit 1 ;;`,
'esac',
].join("\n") + "\n");
ctx.inbox = [];
const r = startRunner(ctx.runDir, ctx.cap);
t.after(() => r.child.kill("SIGKILL"));
for (const body of ["HOSTILE", "LEAK", "QUIET"]) ctx.call(ctx.pm, "message.send", {to:"coder", body});
await until(() => replies(ctx)() && ctx.inbox.length >= 3);
const [hostile, leak, quiet] = ctx.inbox.map(m => m.body);
const [cause, details] = hostile.slice("The turn failed: ".length).split("\nDetails: ");
assert.equal(details, "adapter exited 1");
// The long token before the error is redacted as a whole: it shows, if at all, as one [redacted].
assert.match(cause, /^(?:\[redacted\] )?API Error: 500 boom evil /);
assert.ok(Array.from(cause).length <= 300, cause.length);
assert.equal(cause.includes("www"), false, "the long text before the error is not shown");
assert.doesNotMatch(hostile, /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/u, "no control or format character but the one separating newline");
for (const bad of ["pw@", "example.com", "key=abc", "mail@", "/home/someone", "abc.def", "sk-ant", "msk-abcdef", "eyJhbGciOi", "AbCdEf0123456789XyZ"]) assert.equal(hostile.includes(bad), false, bad);
assert.equal(leak, "The turn failed: the error text held a secret, so it isn't shown. Check Settings > Model setup.\nDetails: adapter exited 1");
assert.equal(quiet, "The turn failed: adapter exited 1");
for (const line of [...ctx.inbox.map(m => m.body), r.stderr()]) assert.equal(line.replace(/\s|\u200b/g, "").includes(secret), false);
r.child.kill("SIGTERM"); await r.exited;
});
test("r127 an adapter whose own command is missing names it; a 127 with no such line keeps the bare reason", async t => {
const ctx = await setup(t);
const adapter = join(ctx.dir, "adapter.sh");
@@ -394,7 +451,8 @@ for (const [harness, exit, activity] of [['claude-code', 1, false], ['claude-cod
const r = startRunner(ctx.runDir, ctx.cap, { MOSAIC_MODEL_ACTIVITY_SOURCE: 'adapter' });
t.after(async () => { r.child.kill('SIGTERM'); await r.exited; });
const reply = await ask(ctx);
if (exit) assert.match(reply.body, /The turn failed: adapter exited 1/);
// #1873 chat-fail F1: the error text on stdout is the turn's plain cause.
if (exit) assert.equal(reply.body, 'The turn failed: API Error: 400 synthetic-result\nDetails: adapter exited 1');
else assert.equal(reply.body, 'API Error: 400 synthetic-result');
const marker = join(ctx.runDir, 'proxy-first-output');
assert.equal(existsSync(marker), activity);
@@ -0,0 +1,114 @@
// #1873 chat-fail F1: the plain cause of a failed turn, from the harness's error text.
import { test } from "node:test";
import assert from "node:assert/strict";
import { CAUSE_MAX, PLAIN, WITHHELD, cleanText, failureBody, secretValues, turnCause } from "../src/failure-notice.mjs";
test("the three recognised causes map to a fixed plain line that carries none of the error's words", () => {
for (const text of ["Claude AI usage limit reached|1700000000", "You've hit your limit \u00b7 resets 3pm (UTC)",
"5-hour limit reached \u2219 resets 9pm", "Credit balance is too low", '{"error":{"type":"insufficient_quota"}}', "Quota exceeded for this account"])
assert.equal(turnCause(text), PLAIN.usage, text);
for (const text of ["OAuth token has expired. Please obtain a new token or refresh your existing token.", "Invalid API key \u00b7 Please run /login",
'API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}', "Not logged in"])
assert.equal(turnCause(text), PLAIN.signin, text);
for (const text of ["There's an issue with the selected model (some-model). It may not exist or you may not have access to it.",
'{"error":{"type":"not_found_error","message":"model: some-model"}}', "model_not_found", "The model some-model does not exist"])
assert.equal(turnCause(text), PLAIN.model, text);
// Other limits are not the account's usage.
for (const text of ["Context limit reached \u00b7 /compact or /clear to continue", "output limit reached"])
assert.notEqual(turnCause(text), PLAIN.usage, text);
for (const line of Object.values(PLAIN)) assert.doesNotMatch(line, /\u2014/, "no em dash in UI text");
});
test("no text, or text that is only controls or one long token, gives no cause", () => {
for (const text of [undefined, null, "", " \n\t", "\u0000\u001b[0m\u200b", "x".repeat(5000)]) assert.equal(turnCause(text), null, JSON.stringify(text));
});
test("control, format and separator characters go and the cause is capped", () => {
assert.equal(cleanText("a\u0000b\u0007c\u001b[1;31md\u001b]0;title\u0007e\u007ff\u0085g\u2028h\u2029i\u202ej\u2066k\u200bl\ufeffm\tn\r\no"), "a b cde f g h ijklm n o");
const long = turnCause("word ".repeat(400));
assert.ok(Array.from(long).length <= CAUSE_MAX && long.endsWith("..."), long.length);
// Astral characters are cut whole, never into a lone surrogate.
const astral = turnCause("\u{1f600}".repeat(400));
assert.equal(/[\ud800-\udfff]/u.test(astral.replace(/\u{1f600}/gu, "")), false);
});
test("secrets, links, emails, paths and key-like runs never reach the cause", () => {
const secret = "s3cr3t-value-for-the-fixture";
const secrets = secretValues({ MOSAIC_MODEL_KEY: secret, MOSAIC_PROXY_TOKEN: "tok-0123456789", PATH: "/usr/bin:/bin", SHORT_KEY: "abc" });
assert.deepEqual(secrets, [secret, "tok-0123456789"]);
for (const text of [`boom ${secret}`, `boom ${secret.slice(0, 9)}\n${secret.slice(9)}`, `boom ${secret.slice(0, 5)}\u200b${secret.slice(5)}`, `boom ${secret.slice(0, 5)}\u0000${secret.slice(5)}`])
assert.equal(turnCause(text, secrets), WITHHELD, JSON.stringify(text));
const shown = turnCause("API Error: 500 at https://user:[email protected]/a?token=zz and www.host.example/q, [email protected], /home/u/.config/mosaic-dev/x ~/x ./y "
+ "Bearer abc.def Authorization: Basic Zm9v api_key=k1 token: k2 sk-ant-api03-k3 ghp_k4 xoxb-k5 eyJa.b.c " + "A1".repeat(10) + " " + "z".repeat(40), secrets);
for (const bad of ["user:pw", "host.example", "token=zz", "ops@", "/home/u", "~/x", "./y", "abc.def", "Zm9v", "k1", "k2", "sk-ant", "ghp_", "xoxb", "eyJa", "A1A1", "zzzz"])
assert.equal(shown.includes(bad), false, `${bad} in ${shown}`);
assert.match(shown, /^API Error: 500 at \[redacted\]/);
});
test("the chat body puts the plain cause first and the technical reason after", () => {
assert.equal(failureBody({ reason: "adapter exited 1", cause: PLAIN.usage }), `The turn failed: ${PLAIN.usage}\nDetails: adapter exited 1`);
assert.equal(failureBody({ reason: "adapter exited 1" }), "The turn failed: adapter exited 1");
});
test("review round 1: quoted keys, short or letters-only values and a space separator are redacted", () => {
for (const [text, value] of [['{"error":"bad","password":"hunter2hunte"}', "hunter2hunte"], ['{"api_key":"abcdefghijklmno"}', "abcdefghijklmno"],
['auth failed for key "Zq8xPw2LmN4"', "Zq8xPw2LmN4"], ["token abcd1234efgh567 rejected", "abcd1234efgh567"],
["secret qwertyuiopasdfghjklzxcvbnmqwer", "qwertyuiop"], ['{"access_token":"shortvalue1"}', "shortvalue1"], ["client_secret=abc", "abc"]]) {
const shown = turnCause(text);
assert.ok(shown === null || !shown.includes(value), `${value} in ${shown}`);
}
// Ordinary words after "key" or "session" are left alone.
assert.equal(turnCause("API Error: 500 the key point is the session ended"), "API Error: 500 the key point is the session ended");
});
test("review round 1: encoded emails, Windows and UNC paths and encoded env secrets never reach the cause", () => {
for (const [text, bad] of [["mail jason%40example.com", "example"], ["mail jason%2540example.com", "example"], ["mail jason\uff20example.com", "example"],
["mail jason&#64;example.com", "example"], ["read C:\\Users\\jason\\.claude\\creds.json", "jason"], ["read \\\\server\\share\\creds", "server"]]) {
const shown = turnCause(text);
assert.ok(shown === null || !shown.includes(bad), `${bad} in ${shown}`);
}
const secrets = secretValues({ MOSAIC_PROXY_KEY: "pxy_0123456789abcd" });
for (const text of ["boom pxy%5F0123456789abcd", "boom pxy&#95;0123456789abcd", "boom pxy&#x5f;0123456789abcd", "boom pxy_01234\u030156789abcd", "boom \uff50xy_0123456789abcd"])
assert.equal(turnCause(text, secrets), WITHHELD, JSON.stringify(text));
});
test("review round 1: a long output is read from its end, so an answer that talks about limits is not the cause", () => {
const cause = turnCause("Here is how limits work: usage limit reached means wait. " + "x ".repeat(1500) + "Error: adapter crashed: segfault");
assert.notEqual(cause, PLAIN.usage);
assert.match(cause, /segfault$/);
assert.equal(turnCause("y ".repeat(1500) + "Claude AI usage limit reached"), PLAIN.usage);
});
// Review round 2: the tail cut can land between a key word and its value. Redaction runs
// before the cut, so the value is still redacted with its key word gone.
test("review round 2: a tail cut between a key word and its value never shows the value", () => {
for (const [key, value] of [["password:", "Zq8xPw2LmN"], ["Bearer", "Zq8xPw2LmN"], ['"api_key":', '"Zq8xPw2LmN"'], ["token", "Zq8xPw2LmN4"]]) {
// The last 2000 characters start just before the value, so the cut parts it from its key
// word; a near miss on either side is checked too.
for (let shift = -2; shift <= 2; shift++) {
const end = " then the adapter crashed";
const head = ` ${value} https://e.example/`;
const tail = head + "a".repeat(2000 - head.length - end.length + shift) + end;
const cause = turnCause("w ".repeat(300) + key + tail);
assert.ok(cause !== null && !cause.includes("Zq8xPw2LmN"), `${key} shift ${shift}: ${cause}`);
assert.match(cause, /then the adapter crashed$/);
}
}
});
// Review round 3: redaction runs over the whole kept stdout (up to 128000 characters), so a long
// run with no spaces (base64, a data URI, minified JSON) must not make it slow.
test("review round 3: a 128000-character run with no spaces is redacted in well under a second", () => {
const N = 128000;
for (const run of ["a".repeat(N), "a.".repeat(N / 2), "a-".repeat(N / 2), "a/".repeat(N / 2), "a:".repeat(N / 2), 'a"'.repeat(N / 2)]) {
const started = performance.now();
const cause = turnCause(`${run} then the adapter crashed`);
const took = performance.now() - started;
assert.ok(took < 1000, `${run.slice(0, 4)}... took ${Math.round(took)} ms`);
assert.match(cause, /then the adapter crashed$/);
}
});
// Review round 3: a long text that redacts down below the read limit isn't cut, so its first word stays.
test("review round 3: a long text that redaction makes short keeps its first word", () => {
assert.equal(turnCause(`Crash: adapter died at https://e.example/${"a".repeat(2500)}`), "Crash: adapter died at [redacted]");
});
+2 -2
View File
@@ -64,7 +64,7 @@ code is in that same tree, a restart picks it up. If it is in another tree,
the unit keeps the old PIN until it is installed again from the new tree:
stop it, remove its unit file, then `mosaic proxy unit install` from the new
tree, because install never replaces a unit. Then run `mosaic proxy fetch` (or Fetch on the Console's
Model proxy settings), which installs the new release beside the old one
Model setup page), which installs the new release beside the old one
under `<dataRoot>/opt/cliproxyapi/<version>/`. Then restart the proxy with
`mosaic proxy unit restart`. Before the fetch, the proxy fails to start with
`proxy-install-missing`, and keeps failing until the fetch is done. Restart the bus and
@@ -148,7 +148,7 @@ follow-up; do not run those writers concurrently with organization buses.
### Setup from the Console (#1873)
Settings > Model proxy has a Proxy setup panel for the instance owner: the
Settings > Model setup (route `#/settings/model-proxy`) has a Proxy setup panel for the instance owner: the
`--dev-local-owner` owner on a dev Console, or the root owner under `--sso`.
Agents, testers and grant holders get `human-required` on every setup route,
read or write. The panel shows the release (pinned version, hashes verified),
+55 -7
View File
@@ -7,7 +7,8 @@ import { homedir } from 'node:os';
import { fetchPinned } from './fetch.mjs';
import { PIN } from './common.mjs';
import { localRide, riddenOrgs } from './ride.mjs';
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, receiptsText, createUnitControl, FILE_LABELS } from './admin.mjs';
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, receiptsText, createUnitControl, FILE_LABELS, LOG_LINES, receiptHistory, serviceKeyState } from './admin.mjs';
import { secretValues } from './redact.mjs';
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
const failure = code => Object.assign(new Error(code), { code });
@@ -60,17 +61,24 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
// intent. Any other failure leaves it: the add may have happened.
async function rideOne(rider, wasRidden) {
const id = rider.id, local = decide(rider, wasRidden);
if (local === 'fixture') return { id, outcome: 'fixture', running: !(await stopped(rider)) };
// settings-p3 (R2): with no bus status (the single-business Console) whether its bus runs is unknown (null).
if (local === 'fixture') return { id, outcome: 'fixture', running: typeof rider.status === 'function' ? !(await stopped(rider)) : null };
if (local !== 'ready') return { id, outcome: local === 'already' ? 'already' : 'skipped', reason: local };
let current;
try { current = await rider.call('plugins'); } catch { return { id, outcome: 'skipped', reason: 'bus-down' }; }
try { await rider.call('proxy.accounts'); } catch (error) { return { id, outcome: 'skipped', reason: error?.code === 'not-configured' ? 'no-proxy-client' : 'proxy-check-failed' }; }
const providers = Array.isArray(current?.plugins?.['model-provider']) ? current.plugins['model-provider'] : [];
if (providers.includes('cliproxy')) return { id, outcome: 'already' };
// The receipts are read again here: a removal saved while this run worked on earlier
// organizations is on file now, and the decision above came from the run's first read.
const now = ridden()(id);
if (now !== false) return { id, outcome: 'skipped', reason: now === null ? 'unreadable' : 'removed' };
// The organization (its file and change log) and the receipts are read again here: an add and
// remove saved on its Settings page, or a removal saved while this run worked on earlier
// organizations, is on file now, and the decision above came from the run's first read
// (settings-p3 R1). A read that fails, or an organization no longer listed, is skipped as unreadable.
let fresh;
try { fresh = (await riders()).find(r => r?.id === id); } catch { fresh = null; }
if (!fresh) return { id, outcome: 'skipped', reason: 'unreadable' };
const again = decide(fresh, ridden());
if (again === 'already') return { id, outcome: 'already' };
if (again !== 'ready') return { id, outcome: 'skipped', reason: again };
try { receipt({ op: 'ride-intent', org: id }); } catch { return { id, outcome: 'skipped', reason: 'not-recorded' }; }
try { await rider.call('plugins.set', { revision: current.revision, plugins: { 'model-provider': [...providers, 'cliproxy'] } }); }
catch (error) {
@@ -83,7 +91,12 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
return { id, outcome: 'added' };
}
async function rideSummary() {
try { const wasRidden = ridden(); return (await riders()).map(r => ({ id: r.id, state: decide(r, wasRidden) })); } catch { return null; }
// settings-p3 (review P3-3): a stand-in organization with no bus status (the single-business
// Console) can't be moved; running null says so before any Ride all run.
try {
const wasRidden = ridden();
return (await riders()).map(r => { const state = decide(r, wasRidden); return state === 'fixture' && typeof r.status !== 'function' ? { id: r.id, state, running: null } : { id: r.id, state }; });
} catch { return null; }
}
function nextSteps({ release, init, unitState, fence, lock }) {
if (!release.fetched || release.problem) return ['fetch'];
@@ -221,6 +234,9 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
if (!rider) return { org, moved: false, reason: 'unknown' };
const local = decide(rider, ridden());
if (local !== 'fixture') return { org, moved: false, reason: local };
// settings-p3 (R2): with no bus status (the single-business Console) its bus can't be shown
// stopped, so stopping it would not help: moving is not available there.
if (typeof rider.status !== 'function') return { org, moved: false, reason: 'not-available' };
if (!(await stopped(rider))) return { org, moved: false, reason: 'bus-running' };
if (typeof move !== 'function') return { org, moved: false, reason: 'not-available' };
const owner = await ownerModels();
@@ -239,6 +255,38 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
if (typeof org !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(org)) throw failure('proxy-org-invalid');
return receipt({ op: 'ride-removed', org });
},
// #1873 settings-backend A1: three reads for the instance owner's setup page.
// The proxy unit's last journal lines, redacted. A unit that is not installed is not-configured;
// a unit state that cannot be read is outcome-unknown, as is a journal that cannot be read.
async log({ lines = LOG_LINES.default } = {}) {
if (typeof control.log !== 'function') throw failure('not-configured');
const state = await unitStatus();
if (state.error) throw failure('outcome-unknown');
if (!state.installed) throw failure('not-configured');
return control.log(lines, { secrets: secretValues(env) });
},
// When the service key was made, from proxy.json's mtime; never the key or any part of it.
serviceKey() { return serviceKeyState(configDir); },
// The setup history, a page at a time (receiptHistory).
history({ limit, before = null } = {}) { return receiptHistory(dataRoot, { limit, before, secrets: secretValues(env) }); },
// An account change made through /api/proxy/* or an organization's /api/orgs/<id>/proxy/*,
// recorded after its bus call answered. Labels only: the provider id, a 12-hex account id, a
// priority or a model count, the organization whose route carried it, and the signed-in name.
// Never a key, a login state, a callback URL, a model list or a body. Answers null when the verb
// is not an account change, true when recorded and false when the append failed.
recordAccount({ verb, args = {}, result = null, user = null, org = null } = {}) {
const label = value => (typeof value === 'string' && /^[a-z0-9][a-z0-9._-]{0,31}$/.test(value) ? value : null);
const account = value => (typeof value === 'string' && /^[a-f0-9]{12}$/.test(value) ? value : null);
let record;
if (verb === 'proxy.apikey.add') record = { op: 'account.proxy.apikey.add', provider: label(args.provider) };
else if (verb === 'proxy.login.status' && result?.status === 'ok') record = { op: 'account.proxy.login.complete' };
else if (verb === 'proxy.priority.set') record = { op: 'account.proxy.priority.set', accountId: account(args.accountId), priority: Number.isSafeInteger(args.priority) ? args.priority : null };
else if (verb === 'proxy.group.models.set') record = { op: 'account.proxy.group.models.set', accountId: account(args.accountId), models: Array.isArray(args.models) ? args.models.length : null };
else return null;
if (typeof org === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(org)) record.org = org;
if (typeof user === 'string' && user) record.user = user.slice(0, 64);
try { receipt(record); return true; } catch { return false; }
},
async initLockClear() {
return exclusive('init-lock-clear', async () => ({ receipt: clearInitLock({ configDir, dataRoot, buses: await buses(), now }) }));
},
+132
View File
@@ -9,6 +9,7 @@ import { execFile } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { PIN, refuse } from './common.mjs';
import { installPaths, loadProxy, verifyInstall } from './settings.mjs';
import { holdsSecret, redactLine, redactValue } from './redact.mjs';
const REPO = fileURLToPath(new URL('../../../', import.meta.url)).replace(/\/$/, '');
export const INSTANCE_NAME = /^[a-z][a-z0-9]{1,15}$/;
@@ -142,6 +143,135 @@ export function recentReceipts(dataRoot, limit = 10) {
} finally { fs.closeSync(fd); }
}
// #1873 settings-backend A1 (item 9): the setup history, one page at a time, newest page first and
// oldest first within a page. `before` is a byte offset the previous page answered as `next`: the
// start of a line. The file is read the way ownedText reads (no symlink, no FIFO, owned by the
// Console's user, no group or other bits) and backward from `before` in 64 KB chunks. A partial
// last line (a write in progress) waits for a later read; a line that does not parse, or is longer
// than 64 KB, is skipped. Each entry is redacted (redact.mjs) before it is answered, so a receipt
// that ever held key text shows none. An entry whose redacted values read together, or whose keys
// and values read together, still hold an environment secret split across them is answered as
// { withheld: true }; pieces kept apart by another whole field are not seen (known limit). A missing
// file is an empty history; any other failure to read refuses outcome-unknown. `uid` is a test seam.
export const HISTORY_LIMIT = Object.freeze({ min: 1, max: 100, default: 25 });
const HISTORY_CHUNK = 65536, HISTORY_LINE_MAX = 65536, HISTORY_SCAN_MAX = 2000;
// A redacted entry's values joined in order, with each object key before its value when `keys`.
const entryText = (value, keys) => (value !== null && typeof value === 'object'
? Object.entries(value).map(([key, item]) => (keys && !Array.isArray(value) ? key : '') + entryText(item, keys)).join('')
: String(value));
export function receiptHistory(dataRoot, { limit = HISTORY_LIMIT.default, before = null, uid = process.getuid(), secrets = [] } = {}) {
if (!Number.isSafeInteger(limit)) refuse('invalid-request');
const n = Math.min(HISTORY_LIMIT.max, Math.max(HISTORY_LIMIT.min, limit));
if (before !== null && !(Number.isSafeInteger(before) && before >= 0)) refuse('invalid-request');
let fd;
try { fd = fs.openSync(receiptFile(dataRoot), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); }
catch (error) {
if (error.code !== 'ENOENT') refuse('outcome-unknown');
if (before !== null && before !== 0) refuse('invalid-request');
return { entries: [], next: null };
}
try {
let stat;
try { stat = fs.fstatSync(fd); } catch { refuse('outcome-unknown'); }
if (!stat.isFile() || stat.uid !== uid || (stat.mode & 0o077)) refuse('outcome-unknown');
const size = stat.size;
if (before !== null && before > size) refuse('invalid-request');
// A window over the file: `buf` holds bytes [start, start + buf.length).
let start = 0, buf = Buffer.alloc(0);
const readAt = (offset, length) => {
const out = Buffer.alloc(length);
let got;
try { got = fs.readSync(fd, out, 0, length, offset); } catch { refuse('outcome-unknown'); }
if (got !== length) refuse('outcome-unknown');
return out;
};
// The offset of the last newline in [0, from), or -1.
const lastNewline = from => {
let pos = from;
while (pos > 0) {
if (!(pos > start && pos <= start + buf.length)) { start = Math.max(0, pos - HISTORY_CHUNK); buf = readAt(start, pos - start); }
const i = buf.lastIndexOf(0x0a, pos - start - 1);
if (i >= 0) return start + i;
pos = start;
}
return -1;
};
const bytes = (from, to) => (from >= start && to <= start + buf.length ? buf.subarray(from - start, to - start) : readAt(from, to - from));
// `cursor` is always 0 or the offset just after a newline: the end of the next line to read.
let cursor;
if (before === null) cursor = lastNewline(size) + 1;
else if (before > 0 && bytes(before - 1, before)[0] !== 0x0a) refuse('invalid-request');
else cursor = before;
const entries = [];
for (let scanned = 0; cursor > 0 && entries.length < n && scanned < HISTORY_SCAN_MAX; scanned++) {
const lineStart = lastNewline(cursor - 1) + 1, lineEnd = cursor - 1;
if (lineEnd - lineStart <= HISTORY_LINE_MAX) {
let value = null;
try { value = JSON.parse(bytes(lineStart, lineEnd).toString('utf8')); } catch { /* torn line */ }
if (value && typeof value === 'object' && !Array.isArray(value) && typeof value.op === 'string') {
const safe = redactValue(value, secrets);
const split = holdsSecret(entryText(safe, false), secrets) || holdsSecret(entryText(safe, true), secrets);
entries.push(split ? { withheld: true } : safe);
}
}
cursor = lineStart;
}
entries.reverse();
return { entries, next: cursor > 0 ? cursor : null };
} finally { fs.closeSync(fd); }
}
// #1873 settings-backend A1 (item 7): when the service key was made. proxy.json is created in the
// same init step as the management key, with exclusive create, and is never rewritten, so its
// mtime is the key's creation time. Only proxy.json is lstat'ed: the key file is never opened or
// stat'ed, and nothing is read. A missing proxy.json is `missing`; a symlink, a non-file, one owned
// by another user or one that cannot be examined is `unreadable`, with no date. There is no
// renewal yet (proxy-scope: no rotation in the MVP), so renewedAt is null and renewal 'not-built'.
export function serviceKeyState(configDir, { uid = process.getuid() } = {}) {
const out = { madeAt: null, renewedAt: null, renewal: 'not-built', problem: null };
let stat;
try { stat = fs.lstatSync(path.join(configDir, 'proxy.json')); }
catch (error) { out.problem = error.code === 'ENOENT' ? 'missing' : 'unreadable'; return out; }
if (!stat.isFile() || stat.uid !== uid || !Number.isFinite(stat.mtimeMs) || stat.mtimeMs <= 0) { out.problem = 'unreadable'; return out; }
out.madeAt = new Date(stat.mtimeMs).toISOString();
return out;
}
// #1873 settings-backend A1 (item 3): the proxy unit's last journal lines, made safe to show. The
// unit name is unitName()'s, never the caller's; `lines` is clamped to 1..200. journalctl runs
// through `run` (defaultRun: its timeout and 1 MB cap). A missing journalctl, a nonzero exit or a
// timeout refuses outcome-unknown, with no lines and no other source tried. Each line is redacted
// (redact.mjs) and cut to 300 characters; a line that cannot be shown is dropped, never shown raw.
// A secret from `secrets` found across the shown lines, though in no one line, drops every line.
export const LOG_LINES = Object.freeze({ min: 1, max: 200, default: 50 });
export async function unitLog({ run = defaultRun, unit, lines = LOG_LINES.default, env, secrets = [] } = {}) {
if (typeof unit !== 'string' || !/^mosaic-proxy(-[a-z][a-z0-9]{1,15})?\.service$/.test(unit)) refuse('proxy-unit-usage');
if (!Number.isSafeInteger(lines)) refuse('invalid-request');
const n = Math.min(LOG_LINES.max, Math.max(LOG_LINES.min, lines));
let result;
try { result = await run('journalctl', ['--user', '-u', unit, '-n', String(n), '-o', 'cat', '--no-pager', '-q'], { env, timeout: 15000 }); }
catch { refuse('outcome-unknown'); }
if (!result || result.code !== 0 || typeof result.stdout !== 'string') refuse('outcome-unknown');
const raw = result.stdout.split('\n');
if (raw.at(-1) === '') raw.pop();
const kept = raw.slice(-n);
const out = [];
let redacted = 0, dropped = 0;
try {
for (const line of kept) {
const safe = redactLine(line, secrets);
if (safe.text === null) { if (line.trim()) dropped++; continue; }
if (safe.redacted) redacted++;
out.push(safe.text);
}
// The lines that will be shown, read together: a secret split across them drops them all.
// Only environment secrets are checked this way. A key pattern broken across two journal
// lines, each part too short for the long-run rules, is a known limit shared with chat-fail.
if (holdsSecret(out.join(''), secrets)) { dropped += out.length; out.length = 0; }
} catch { refuse('outcome-unknown'); }
return { unit, lines: out, redacted, dropped };
}
export function unitName(instance) {
if (instance !== null && instance !== undefined && instance !== 'dev' && !INSTANCE_NAME.test(instance)) refuse('proxy-unit-usage');
return instance && instance !== 'dev' ? `mosaic-proxy-${instance}.service` : 'mosaic-proxy.service';
@@ -215,6 +345,8 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
return {
unit,
status,
// settings-backend A1: the unit's last journal lines, redacted (unitLog).
log(lines, { secrets = [] } = {}) { return unitLog({ run, unit, lines, env, secrets }); },
async render() { return (await service('render')).stdout; },
async install() { await service('install'); return status(); },
async start() {
+92
View File
@@ -0,0 +1,92 @@
// #1873 settings-backend A1: redaction for the model service's log lines and the setup history,
// read by the instance owner on the setup page.
//
// It is the redaction chat-fail landed for a failed turn's cause (packages/harness/src/failure-notice.mjs,
// its REDACT list), with Mosaic's own key prefixes added to the key-prefix line: mso- (an organization's
// model key), mst- (the Triage key) and msp-, beside msk- (the owner's). One line is added after it:
// those four Mosaic prefixes with no word boundary, so a key glued to a word (xmso-...) is caught
// too. Over-redaction there is the safe side. failure-notice.mjs does not
// export its list, and packages/harness/ belongs to another lane now, so the list is copied here.
// tests/redact.test.mjs fails when a copied line no longer matches failure-notice.mjs.
//
// A text is decoded (%XX, HTML references, NFKC) and cleaned (ANSI, controls, whitespace) with
// failure-notice's own exported helpers before it is redacted. A text that holds one of the
// Console's environment secrets (secretValues), even split by spaces or controls, is withheld
// whole. A text that redacts to nothing but [redacted] says nothing and is dropped.
import { cleanText, decodeText } from '../../harness/src/failure-notice.mjs';
export { secretValues } from '../../harness/src/failure-notice.mjs';
export const LINE_MAX = 300;
export const REDACTED = '[redacted]';
// Copied from failure-notice.mjs. The key-prefix line adds mso, mst and msp, and the line after
// it is Mosaic's own; every other line is failure-notice's.
const KEY_WORD = "(?:\\w*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization|cookie|session)";
const REDACT = [
/(?<![a-z0-9+.-])[a-z0-9+.-]+:\/\/\S*/gi, // any link, its userinfo and query included, from the run's start
/\bwww\.\S+/gi,
/(?<!\S)(?=\S*\S@\S)\S+/g, // email addresses and user@host: the whole run holding the @
/(?:^|(?<=[\s("'=:]))(?:~|\.{1,2})?\/\S+/g, // absolute and home paths
/\b[A-Za-z]:\\\S*/g, // Windows paths
/\\\\\S+/g, // UNC paths
/\b(?:bearer|basic)\s+\S+/gi,
new RegExp(`\\b${KEY_WORD}["']?\\s*[:=]\\s*(?:"[^"]*"?|'[^']*'?|[^\\s,;}]+)`, "gi"),
new RegExp(`\\b${KEY_WORD}["']?\\s+(?:"[^"]*"?|'[^']*'?|(?=[^\\s"',;}]*\\d)[^\\s"',;}]+|[^\\s"',;}]{8,})`, "gi"),
/\b(?:sk|msk|mso|mst|msp|rk|pk|ghp|gho|ghs|glpat|xox[a-z])[-_]\S+/gi,
/ms[kotp][-_]\S+/gi, // Mosaic's prefixes glued to a word: added here, not in failure-notice.mjs
/\beyJ\S+/g, // JWT
/[A-Za-z0-9_\-+/=.]{32,}/g,
/(?<![A-Za-z0-9_\-+/=.])(?=[A-Za-z0-9_\-+/=.]*\d)(?=[A-Za-z0-9_\-+/=.]*[A-Za-z])[A-Za-z0-9_\-+/=.]{16,}/g,
];
// The text with every space, mark and separator gone, after cleanText, for the secret check.
// cleanText has already removed ANSI, format, surrogate and private-use characters and turned
// controls into spaces, so this removes the same set failure-notice's compactText does.
const compact = clean => clean.replace(/[\p{M}\p{Z}\s]/gu, '');
function cap(text, n = LINE_MAX) {
const chars = Array.from(text);
return chars.length <= n ? text : chars.slice(0, n - 3).join('') + '...';
}
// One text made safe to show. Answers { text, redacted } where text is null when nothing can be
// shown: an empty text, one holding a secret (withheld: true), or one that redacts to only
// [redacted]. Redaction runs over the whole text before the cap, so the cut never parts a key word
// from its value. `secrets` is secretValues(env).
export function redactLine(line, secrets = []) {
const clean = cleanText(decodeText(String(line)));
if (!clean) return { text: null, redacted: false };
if (secrets.length) {
const flat = compact(clean);
if (secrets.some(value => flat.includes(value))) return { text: null, redacted: true, withheld: true };
}
let shown = clean;
for (const re of REDACT) shown = shown.replace(re, REDACTED);
shown = shown.replace(/(?:\[redacted\]\s*){2,}/g, `${REDACTED} `).trim();
if (!shown || shown === REDACTED) return { text: null, redacted: true };
return { text: cap(shown), redacted: shown !== clean };
}
// True when the whole text, joined with no spaces, holds a secret: one split across lines is seen.
export function holdsSecret(text, secrets = []) {
if (!secrets.length) return false;
const flat = compact(cleanText(decodeText(String(text))));
return secrets.some(value => flat.includes(value));
}
// A stored value made safe to show: strings are redacted, and a string that cannot be shown
// becomes [redacted]. Keys that redaction would change are dropped with their value. Depth and
// size are bounded; anything past the bound becomes null.
export function redactValue(value, secrets = [], depth = 0) {
if (value === null || typeof value === 'number' || typeof value === 'boolean') return value;
if (typeof value === 'string') return value === '' ? '' : redactLine(value, secrets).text ?? REDACTED;
if (depth >= 4 || typeof value !== 'object') return null;
if (Array.isArray(value)) return value.slice(0, 64).map(item => redactValue(item, secrets, depth + 1));
const out = {};
for (const [key, item] of Object.entries(value).slice(0, 64)) {
if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(key) || redactLine(key, secrets).text !== key) continue;
out[key] = redactValue(item, secrets, depth + 1);
}
return out;
}
@@ -227,3 +227,83 @@ test('status carries the last receipts from proxy-admin.jsonl, so the page shows
assert.equal(receipts.length, 10);
assert.ok(receipts.every(r => r.op === 'unit.stop'));
});
// #1873 settings-backend A1: the controller's three reads and the account-change record.
function a1Fixture(t, { unitState = { installed: true, active: 'active', healthy: true }, log = undefined, statusError = false, env = {} } = {}) {
const root = fs.mkdtempSync(join(tmpdir(), 'pc-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const calls = [];
const unit = {
unit: 'mosaic-proxy-zz.service',
status: async () => { if (statusError) throw Object.assign(new Error('systemctl gone'), { code: 'proxy-unit-failed' }); return { unit: 'mosaic-proxy-zz.service', ...unitState }; },
...(log === undefined ? { log: async (lines, options) => { calls.push({ lines, options }); return { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 }; } } : log === null ? {} : { log }),
};
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, now: () => new Date(0), env });
return { admin, calls, configDir, dataRoot };
}
test('log reads the unit journal with the env secrets; a missing unit or log reader is not-configured, an unreadable state outcome-unknown', async t => {
const { admin, calls } = a1Fixture(t, { env: { MOSAIC_PROXY_KEY: 'plainwordsonly', PATH: '/usr/bin' } });
assert.deepEqual(await admin.log(), { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 });
assert.deepEqual(calls, [{ lines: 50, options: { secrets: ['plainwordsonly'] } }]);
await admin.log({ lines: 7 });
assert.equal(calls[1].lines, 7);
await assert.rejects(a1Fixture(t, { unitState: { installed: false, active: 'inactive', healthy: false } }).admin.log(), code('not-configured'));
await assert.rejects(a1Fixture(t, { log: null }).admin.log(), code('not-configured'));
await assert.rejects(a1Fixture(t, { statusError: true }).admin.log(), code('outcome-unknown'));
const failing = a1Fixture(t, { log: async () => { throw Object.assign(new Error('journal'), { code: 'outcome-unknown' }); } });
await assert.rejects(failing.admin.log(), code('outcome-unknown'));
});
test('serviceKey and history read the configured directories', async t => {
const { admin, configDir, dataRoot } = a1Fixture(t);
assert.equal(admin.serviceKey().problem, 'missing');
fs.writeFileSync(join(configDir, 'proxy.json'), '{}', { mode: 0o600 });
assert.equal(admin.serviceKey().problem, null);
assert.match(admin.serviceKey().madeAt, /^\d{4}-\d\d-\d\dT/);
assert.deepEqual(admin.history(), { entries: [], next: null });
admin.recordAccount({ verb: 'proxy.login.status', result: { status: 'ok' } });
assert.deepEqual(admin.history({ limit: 5 }), { entries: [{ time: new Date(0).toISOString(), op: 'account.proxy.login.complete' }], next: null });
assert.equal(receipts(dataRoot).length, 1);
});
test('history withholds an env secret a receipt holds', async t => {
const { admin, dataRoot } = a1Fixture(t, { env: { PROXY_TOKEN: 'plainwordsonly' } });
fs.mkdirSync(join(dataRoot, 'state'), { recursive: true, mode: 0o700 });
fs.writeFileSync(receiptFile(dataRoot), JSON.stringify({ op: 'x', note: 'plain words only' }) + '\n', { mode: 0o600 });
assert.deepEqual(admin.history().entries, [{ op: 'x', note: '[redacted]' }]);
});
test('recordAccount records account changes by label only, never a key, login state, callback or model name', async t => {
const { admin, dataRoot } = a1Fixture(t);
const KEY = 'sk-proj-Ab3dE5fG7hJ9kL1mN3pQ5rS7tU9vW1xY';
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: 'openai', key: KEY }, result: { added: true }, user: 'jason', org: 'acme' }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: KEY, key: KEY } }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.login.status', args: { state: 'state-secret-123' }, result: { status: 'ok' } }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.login.status', args: { state: 'state-secret-123' }, result: { status: 'wait' } }), null);
assert.equal(admin.recordAccount({ verb: 'proxy.priority.set', args: { accountId: '0123456789ab', priority: 2 } }), true);
assert.equal(admin.recordAccount({ verb: 'proxy.group.models.set', args: { accountId: 'not-hex', models: ['secret-model-name', 'b'] }, org: '../x' }), true);
for (const verb of ['proxy.login.start', 'proxy.login.submit', 'proxy.login.cancel', 'plugins.set', 'proxy.accounts', undefined]) {
assert.equal(admin.recordAccount({ verb, args: { redirect_url: 'https://cb.example/?code=abc', provider: 'x' } }), null, String(verb));
}
const all = receipts(dataRoot);
const at = new Date(0).toISOString();
assert.deepEqual(all, [
{ time: at, op: 'account.proxy.apikey.add', provider: 'openai', org: 'acme', user: 'jason' },
{ time: at, op: 'account.proxy.apikey.add', provider: null },
{ time: at, op: 'account.proxy.login.complete' },
{ time: at, op: 'account.proxy.priority.set', accountId: '0123456789ab', priority: 2 },
{ time: at, op: 'account.proxy.group.models.set', accountId: null, models: 2 },
]);
const text = fs.readFileSync(receiptFile(dataRoot), 'utf8');
for (const bit of ['Ab3dE5', 'state-secret', 'secret-model', 'cb.example', 'code=abc']) assert.equal(text.includes(bit), false, bit);
});
test('recordAccount answers false, and throws nothing, when the history cannot be written', async t => {
const { admin, dataRoot } = a1Fixture(t);
fs.mkdirSync(join(dataRoot, 'state'), { mode: 0o700 });
fs.mkdirSync(receiptFile(dataRoot));
assert.equal(admin.recordAccount({ verb: 'proxy.apikey.add', args: { provider: 'openai', key: 'k' } }), false);
});
+198
View File
@@ -6,12 +6,15 @@ import fs from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { PIN } from '../src/common.mjs';
import { installPaths } from '../src/settings.mjs';
import {
processTree, pidListensOn, processStartMs, verifyRestart, initLockStatus, clearInitLock, initFiles, initState,
fenceState, createUnitControl, releaseState, receiptFile, unitName,
unitLog, serviceKeyState, receiptHistory, appendReceipt, LOG_LINES, HISTORY_LIMIT,
} from '../src/admin.mjs';
import { secretValues } from '../src/redact.mjs';
const code = name => error => error.code === name;
const scratch = t => { const dir = fs.mkdtempSync(join(tmpdir(), 'pa-')); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); return dir; };
@@ -193,3 +196,198 @@ test('unit actions map proxy-service refusals by code and refuse a missing unit'
assert.equal(started.healthy, true); assert.deepEqual(verbs, ['start']);
assert.throws(() => createUnitControl({ unitDir: 'relative' }), code('proxy-unit-path'));
});
// #1873 settings-backend A1: the reads behind the setup page's log, service key and history.
// Planted keys, one of each Mosaic prefix and short enough that only the prefix rule finds them,
// plus long ones of the real shapes.
const TAIL = 'Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE';
const PLANTED = ['msk-tag-qwertyu', 'mso-tag-acme-qwerty', 'mst-tag-triage-zxcvb', 'msp-tag-plmokn',
`msk-k1a2-${TAIL}`, `mso-k1a2-acme-${TAIL}`, `mst-k1a2-triage-${TAIL}`, `msp-k1a2-${TAIL}`];
const ENV_SECRET = 'plainwordsonly';
const leaks = text => [...PLANTED, ...PLANTED.map(k => k.slice(4)), TAIL.slice(0, 10), ENV_SECRET].filter(bit => text.includes(bit));
function journal(stdout, { code: exit = 0, calls = [] } = {}) {
return async (command, args, options) => { calls.push({ command, args, options }); if (stdout instanceof Error) throw stdout; return { code: exit, stdout, stderr: 'raw stderr msk-tag-qwertyu' }; };
}
test('unitLog asks journalctl for the named unit only, clamps the line count, and shows no planted key', async () => {
const calls = [];
const lines = ['proxy listening on 127.0.0.1:18432', ...PLANTED.map(k => `upstream refused ${k} for model x`), `auth with ${ENV_SECRET} ok`, 'msk-tag-qwertyu', '', 'last line'];
const result = await unitLog({ run: journal(lines.join('\n') + '\n', { calls }), unit: 'mosaic-proxy-zz.service', lines: 10000, env: { X: '1' }, secrets: secretValues({ PROXY_KEY: ENV_SECRET }) });
assert.deepEqual(calls[0].args, ['--user', '-u', 'mosaic-proxy-zz.service', '-n', String(LOG_LINES.max), '-o', 'cat', '--no-pager', '-q']);
assert.equal(calls[0].command, 'journalctl');
assert.deepEqual(calls[0].options.env, { X: '1' });
assert.equal(result.unit, 'mosaic-proxy-zz.service');
assert.equal(result.lines[0], 'proxy listening on 127.0.0.1:18432', 'a line with nothing secret shows as it is');
assert.equal(result.lines.at(-1), 'last line');
assert.equal(result.lines.filter(l => l === 'upstream refused [redacted] for model x').length, PLANTED.length);
assert.equal(result.redacted, PLANTED.length, 'shown lines with a redaction; dropped lines count in dropped');
assert.equal(result.dropped, 2, 'the env-secret line and the key-only line are dropped, the blank one is not counted');
assert.deepEqual(leaks(JSON.stringify(result)), []);
// At least one line, and a line count that is not an integer is refused.
await unitLog({ run: journal('x\n', { calls }), unit: 'mosaic-proxy.service', lines: 0 });
assert.equal(calls.at(-1).args[4], '1');
await assert.rejects(unitLog({ run: journal('x\n'), unit: 'mosaic-proxy.service', lines: 2.5 }), code('invalid-request'));
await assert.rejects(unitLog({ run: journal('x\n'), unit: 'mosaic-proxy.service', lines: '5' }), code('invalid-request'));
});
test('unitLog keeps only the last lines asked for and never takes a unit name it was not given by unitName', async () => {
const many = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
assert.deepEqual((await unitLog({ run: journal(many), unit: 'mosaic-proxy.service', lines: 3 })).lines, ['line 27', 'line 28', 'line 29']);
for (const unit of ['sshd.service', 'mosaic-proxy.service; rm', '../mosaic-proxy.service', 'mosaic-proxy-A.service', undefined]) {
await assert.rejects(unitLog({ run: journal('x'), unit, lines: 5 }), code('proxy-unit-usage'), String(unit));
}
});
test('a journal that cannot be read refuses outcome-unknown with no lines and no other source', async () => {
for (const run of [journal(Object.assign(new Error('spawn journalctl ENOENT'), { code: 'ENOENT' })), journal('partial msk-tag-qwertyu', { code: 1 }), async () => ({ code: 0, stdout: null }), async () => null]) {
await assert.rejects(unitLog({ run, unit: 'mosaic-proxy.service', lines: 5 }), error => error.code === 'outcome-unknown' && !leaks(String(error.message) + JSON.stringify(error)).length);
}
});
test('a secret split across journal lines drops every line', async () => {
const result = await unitLog({ run: journal('ok one\nplain\nwordsonly\nok two\n'), unit: 'mosaic-proxy.service', lines: 10, secrets: [ENV_SECRET] });
assert.deepEqual(result.lines, []);
assert.equal(result.dropped, 4);
});
test('createUnitControl.log runs unitLog for its own unit', async () => {
const calls = [];
const control = createUnitControl({ instance: 'zz', port: () => 1, run: journal('hello msk-tag-qwertyu\n', { calls }), probe: async () => true, waitMs: 0, pollMs: 0 });
assert.deepEqual(await control.log(5), { unit: 'mosaic-proxy-zz.service', lines: ['hello [redacted]'], redacted: 1, dropped: 0 });
assert.equal(calls[0].args[2], 'mosaic-proxy-zz.service');
});
test('serviceKeyState answers proxy.json\'s mtime and never opens or stats the key file', t => {
const dir = scratch(t);
assert.deepEqual(serviceKeyState(dir), { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'missing' });
const files = initFiles(dir, join(dir, 'data'));
fs.writeFileSync(files.settings, '{}', { mode: 0o600 });
fs.mkdirSync(join(files.key, '..'), { recursive: true, mode: 0o700 });
fs.writeFileSync(files.key, 'msk-k1a2-' + TAIL, { mode: 0o600 });
fs.utimesSync(join(dir, 'proxy.json'), new Date(Date.UTC(2026, 10, 1, 8)), new Date(Date.UTC(2026, 10, 1, 8)));
const spies = ['openSync', 'readFileSync', 'statSync', 'lstatSync', 'accessSync', 'existsSync', 'realpathSync', 'readdirSync'].map(name => t.mock.method(fs, name));
const state = serviceKeyState(dir);
const seen = spies.flatMap(spy => spy.mock.calls.map(call => String(call.arguments[0])));
spies.forEach(spy => spy.mock.restore());
assert.deepEqual(state, { madeAt: '2026-11-01T08:00:00.000Z', renewedAt: null, renewal: 'not-built', problem: null });
assert.deepEqual(seen, [join(dir, 'proxy.json')]);
assert.deepEqual(leaks(JSON.stringify(state)), []);
});
test('serviceKeyState gives no date for a proxy.json that is a symlink, a directory or another user\'s', t => {
const dir = scratch(t), other = scratch(t);
fs.writeFileSync(join(other, 'real.json'), '{}');
fs.symlinkSync(join(other, 'real.json'), join(dir, 'proxy.json'));
assert.deepEqual(serviceKeyState(dir), { madeAt: null, renewedAt: null, renewal: 'not-built', problem: 'unreadable' });
fs.rmSync(join(dir, 'proxy.json')); fs.mkdirSync(join(dir, 'proxy.json'));
assert.equal(serviceKeyState(dir).problem, 'unreadable');
fs.rmSync(join(dir, 'proxy.json'), { recursive: true }); fs.writeFileSync(join(dir, 'proxy.json'), '{}');
assert.equal(serviceKeyState(dir, { uid: process.getuid() + 1 }).problem, 'unreadable');
assert.equal(serviceKeyState(dir).problem, null);
});
// A receipt file with `count` entries; some lines padded so the file crosses several 64 KB chunks.
function history(t, count, { pad = 0 } = {}) {
const dataRoot = scratch(t);
for (let i = 0; i < count; i++) appendReceipt(dataRoot, { time: new Date(i * 1000).toISOString(), op: 'fetch', n: i, ...(pad ? { note: 'word '.repeat(pad) } : {}) });
return dataRoot;
}
const pages = (dataRoot, limit, extra = {}) => {
const seen = []; let before = null, guard = 0;
do {
const page = receiptHistory(dataRoot, { limit, before, ...extra });
seen.push(page.entries.map(e => e.n));
before = page.next;
} while (before !== null && ++guard < 1000);
return seen;
};
test('receiptHistory pages newest first, oldest first within a page, each entry exactly once across chunks', t => {
const dataRoot = history(t, 300, { pad: 150 });
assert.ok(fs.statSync(receiptFile(dataRoot)).size > 3 * 65536, 'the file spans several chunks');
const seen = pages(dataRoot, 7);
assert.deepEqual(seen[0], [293, 294, 295, 296, 297, 298, 299]);
assert.deepEqual(seen.flat().sort((a, b) => a - b), Array.from({ length: 300 }, (_, i) => i));
assert.equal(new Set(seen.flat()).size, 300);
assert.deepEqual(seen.reverse().flat(), Array.from({ length: 300 }, (_, i) => i), 'pages read back to front are the whole history in order');
const first = receiptHistory(dataRoot);
assert.equal(first.entries.length, HISTORY_LIMIT.default);
assert.equal(receiptHistory(dataRoot, { limit: 1000 }).entries.length, HISTORY_LIMIT.max, 'limit is clamped');
assert.equal(receiptHistory(dataRoot, { limit: 0 }).entries.length, 1);
assert.deepEqual(Object.keys(first.entries[0]).sort(), ['n', 'note', 'op', 'time']);
});
test('receiptHistory skips a torn line and a partial last line, and a write after a page does not repeat or lose entries', t => {
const dataRoot = history(t, 5);
const file = receiptFile(dataRoot);
const text = fs.readFileSync(file, 'utf8').split('\n');
text.splice(2, 0, '{"op":"torn', '[1,2]', '{"no":"op"}', 'x'.repeat(70000));
// The last line is a whole object whose newline is not written yet: it waits for the newline.
fs.writeFileSync(file, text.join('\n') + '{"op":"partial","n":99}');
const first = receiptHistory(dataRoot, { limit: 2 });
assert.deepEqual(first.entries.map(e => e.n), [3, 4]);
assert.deepEqual(receiptHistory(dataRoot, { limit: 1 }).entries.map(e => e.n), [4], 'not shown before its newline');
fs.appendFileSync(file, '\n'); appendReceipt(dataRoot, { op: 'fetch', n: 100 });
const rest = receiptHistory(dataRoot, { limit: 10, before: first.next });
assert.deepEqual(rest.entries.map(e => e.n), [0, 1, 2]);
assert.equal(rest.next, null);
assert.deepEqual(receiptHistory(dataRoot, { limit: 3 }).entries.map(e => e.n), [4, 99, 100], 'the finished line shows on the next newest read');
});
test('receiptHistory refuses a cursor that is not a line start, past the end, negative or not an integer', t => {
const dataRoot = history(t, 3);
const size = fs.statSync(receiptFile(dataRoot)).size;
for (const before of [1, size + 1, -1, 1.5, '10', Number.MAX_SAFE_INTEGER + 2]) {
assert.throws(() => receiptHistory(dataRoot, { before }), code('invalid-request'), String(before));
}
assert.throws(() => receiptHistory(dataRoot, { limit: 'all' }), code('invalid-request'));
assert.deepEqual(receiptHistory(dataRoot, { before: 0 }), { entries: [], next: null });
assert.equal(receiptHistory(dataRoot, { before: size }).entries.length, 3);
});
test('receiptHistory withholds an entry whose fields hold an environment secret split across them', t => {
const dataRoot = scratch(t);
appendReceipt(dataRoot, { op: 'fetch', n: 1 });
appendReceipt(dataRoot, { op: 'x', a: 'plainword', b: 'sonly' });
appendReceipt(dataRoot, { op: 'x', plainw: 'ordsonly' });
appendReceipt(dataRoot, { op: 'x', list: ['plainwo', 'rdsonly'] });
appendReceipt(dataRoot, { op: 'fetch', n: 2 });
const all = receiptHistory(dataRoot, { limit: 10, secrets: secretValues({ PROXY_TOKEN: ENV_SECRET }) });
assert.deepEqual(all.entries, [{ op: 'fetch', n: 1 }, { withheld: true }, { withheld: true }, { withheld: true }, { op: 'fetch', n: 2 }]);
assert.equal(receiptHistory(dataRoot, { limit: 10 }).entries[1].a, 'plainword', 'with no secrets nothing is withheld');
});
test('receiptHistory: a missing file is an empty history; a symlink, FIFO, directory, group-readable or foreign file refuses', t => {
const dataRoot = scratch(t);
assert.deepEqual(receiptHistory(dataRoot), { entries: [], next: null });
assert.throws(() => receiptHistory(dataRoot, { before: 5 }), code('invalid-request'));
appendReceipt(dataRoot, { op: 'fetch' });
const file = receiptFile(dataRoot);
fs.chmodSync(file, 0o640);
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'));
fs.chmodSync(file, 0o600);
assert.throws(() => receiptHistory(dataRoot, { uid: process.getuid() + 1 }), code('outcome-unknown'));
assert.equal(receiptHistory(dataRoot).entries.length, 1);
const elsewhere = join(scratch(t), 'x.jsonl'); fs.writeFileSync(elsewhere, '{"op":"planted"}\n', { mode: 0o600 });
fs.rmSync(file); fs.symlinkSync(elsewhere, file);
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'));
fs.rmSync(file); fs.mkdirSync(file);
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'));
fs.rmSync(file, { recursive: true });
execFileSync('mkfifo', ['-m', '600', file]);
assert.throws(() => receiptHistory(dataRoot), code('outcome-unknown'), 'a FIFO is refused without blocking');
});
test('receiptHistory shows no planted key from any receipt field, nested value or key name', t => {
const dataRoot = scratch(t);
for (const key of PLANTED) appendReceipt(dataRoot, { time: new Date(0).toISOString(), op: 'init', note: `made ${key}`, nested: { list: [key, { deeper: key }] }, [key.replace(/-/g, '_')]: 1 });
appendReceipt(dataRoot, { op: 'init', env: ENV_SECRET, [`x${ENV_SECRET}`]: 1 });
appendReceipt(dataRoot, { op: PLANTED[1] });
const all = receiptHistory(dataRoot, { limit: 100, secrets: secretValues({ PROXY_TOKEN: ENV_SECRET }) });
assert.equal(all.entries.length, PLANTED.length + 2);
assert.deepEqual(leaks(JSON.stringify(all)), []);
assert.deepEqual(all.entries[0], { time: new Date(0).toISOString(), op: 'init', note: 'made [redacted]', nested: { list: ['[redacted]', { deeper: '[redacted]' }] } });
assert.deepEqual(all.entries.at(-2), { op: 'init', env: '[redacted]' });
assert.deepEqual(all.entries.at(-1), { op: '[redacted]' });
});
+122
View File
@@ -0,0 +1,122 @@
// #1873 settings-backend A1: the redaction the setup page's log and history reads use. It is
// chat-fail's list (packages/harness/src/failure-notice.mjs) with Mosaic's key prefixes added.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { redactLine, redactValue, holdsSecret, secretValues, REDACTED, LINE_MAX } from '../src/redact.mjs';
// Short keys of each Mosaic prefix, letters only, so no long-run or mixed-run rule catches them:
// only the key-prefix line does.
const SHORT = { msk: 'msk-tag-qwertyu', mso: 'mso-tag-acme-qwerty', mst: 'mst-tag-triage-zxcvb', msp: 'msp-tag-plmokn' };
for (const [prefix, key] of Object.entries(SHORT)) {
test(`a short ${prefix}- key is redacted from a line, and the rest of the line stays`, () => {
const safe = redactLine(`proxy said ${key} was refused`);
assert.equal(safe.text, `proxy said ${REDACTED} was refused`);
assert.equal(safe.redacted, true);
assert.equal(safe.text.includes(key), false);
// Upper case, and joined by _ instead of -, too.
assert.equal(redactLine(`proxy said ${key.toUpperCase()} x`).text, `proxy said ${REDACTED} x`);
assert.equal(redactLine(`proxy said ${key.replace('-', '_')} x`).text, `proxy said ${REDACTED} x`);
});
}
test('a short Mosaic key glued to a word or an underscore is redacted', () => {
for (const key of Object.values(SHORT)) {
for (const glued of [`x${key}`, `_${key}`, `id=x${key}`, `9${key.toUpperCase()}`]) {
const safe = redactLine(`proxy said ${glued} was refused`);
assert.equal(safe.redacted, true, glued);
assert.equal(safe.text.toLowerCase().includes(key.slice(4)), false, glued);
assert.match(safe.text, / was refused$/);
}
}
});
test('the real key shapes of each prefix are redacted', () => {
const tail = 'Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE';
for (const key of [`msk-k1a2-${tail}`, `mso-k1a2-acme-${tail}`, `mst-k1a2-triage-${tail}`, `msp-k1a2-${tail}`, `sk-ant-${tail}`]) {
const safe = redactLine(`key ${key} rejected by upstream`);
assert.equal(safe.text.includes(key.slice(0, 12)), false, key.slice(0, 4));
assert.equal(safe.text.includes(tail.slice(0, 8)), false, key.slice(0, 4));
}
});
test('bearer and basic tokens, key=value pairs, links, emails and paths never show', () => {
const line = 'POST https://u:[email protected]/v1?key=abc Authorization: Bearer abcdefgh api_key=hunter2 token "quoted value" '
+ 'by [email protected] from /home/jane/.config/mosaic-dev/proxy.json and ~/.mosaic/x C:\\Users\\j \\\\host\\share Basic dXNlcjpwYXNz eyJhbGciOi.x.y';
const safe = redactLine(line);
for (const bit of ['u:p@', 'api.example', 'abcdefgh', 'hunter2', 'quoted value', 'jane@', '/home/jane', '.config', '.mosaic', 'Users', 'share', 'dXNlcjpwYXNz', 'eyJhbGci']) {
assert.equal(safe.text.includes(bit), false, bit);
}
assert.match(safe.text, /^POST /);
});
test('a line holding an environment secret is withheld whole, even split by spaces, controls or encoding', () => {
const secrets = secretValues({ MOSAIC_PROXY_KEY: 'plainwordsonly', HOME: '/home/x', SHORT_TOKEN: 'abc' });
assert.deepEqual(secrets, ['plainwordsonly'], 'only secret-named values of 8 or more characters');
for (const line of ['started with plainwordsonly', 'started with plain words only', 'started p\u0000lainwords\u200bonly', 'started %70lainwordsonly', 'started &#112;lainwordsonly']) {
assert.deepEqual(redactLine(line, secrets), { text: null, redacted: true, withheld: true }, JSON.stringify(line));
}
assert.equal(holdsSecret('plain\nwords\nonly', secrets), true, 'split across lines');
assert.equal(holdsSecret('nothing here', secrets), false);
assert.equal(holdsSecret('plainwordsonly', []), false);
});
test('a line that is empty, blank or only redactions is dropped; a long one is cut to the line cap', () => {
assert.deepEqual(redactLine(''), { text: null, redacted: false });
assert.deepEqual(redactLine(' \u0000\t '), { text: null, redacted: false });
assert.deepEqual(redactLine(`${SHORT.mso} ${SHORT.mst}`), { text: null, redacted: true });
assert.equal(redactLine(`a ${SHORT.mso} ${SHORT.mst} b`).text, `a ${REDACTED} b`, 'repeated redactions collapse');
const long = redactLine('word '.repeat(200));
assert.equal(Array.from(long.text).length, LINE_MAX);
assert.match(long.text, /\.\.\.$/);
assert.equal(redactLine('\u001b[31mred\u001b[0m text').text, 'red text', 'ANSI goes');
});
test('a stored value is redacted all through: strings, nested strings, and keys that read as secrets', () => {
const value = { op: 'account.proxy.apikey.add', time: '2026-11-19T12:34:56.789Z', provider: 'openai', note: `got ${SHORT.mso}`, deep: { list: [SHORT.msk, 3, true, null] }, [SHORT.mst.replace(/-/g, '_')]: 'x', 'bad key': 1 };
const out = redactValue(value);
assert.deepEqual(out, { op: 'account.proxy.apikey.add', time: '2026-11-19T12:34:56.789Z', provider: 'openai', note: `got ${REDACTED}`, deep: { list: [REDACTED, 3, true, null] } });
assert.equal(JSON.stringify(out).includes('qwerty'), false);
// Depth and size are bounded.
assert.deepEqual(redactValue({ a: { b: { c: { d: { e: 1 } } } } }), { a: { b: { c: { d: null } } } });
assert.equal(redactValue(Array.from({ length: 100 }, (_, i) => i)).length, 64);
assert.equal(redactValue('plainwordsonly', ['plainwordsonly']), REDACTED);
assert.equal(redactValue(undefined), null);
});
// chat-fail's shape: redaction runs over a whole line before the cut, so a long run with no spaces
// must stay linear.
test('a 128000-character run with no spaces is redacted in well under a second', () => {
const N = 128000;
const secrets = secretValues({ API_KEY: 'plainwordsonly' });
for (const run of ['a'.repeat(N), 'a.'.repeat(N / 2), 'a-'.repeat(N / 2), 'a/'.repeat(N / 2), 'a:'.repeat(N / 2), 'a"'.repeat(N / 2), 'mso-'.repeat(N / 4), 'a@'.repeat(N / 2)]) {
const started = performance.now();
const safe = redactLine(`${run} then the unit stopped`, secrets);
const took = performance.now() - started;
assert.ok(took < 1000, `${run.slice(0, 4)}... took ${Math.round(took)} ms`);
assert.ok(safe.text === null || Array.from(safe.text).length <= LINE_MAX);
}
// A run that reads as a key is redacted whole, so the words after it show.
assert.equal(redactLine(`${'a'.repeat(N)} then the unit stopped`).text, `${REDACTED} then the unit stopped`);
});
// The list is a copy of failure-notice.mjs's. Every line must still match it, except the key-prefix
// line, which is the original with mso, mst and msp added after msk, and Mosaic's glued-prefix line
// right after it.
test('the redaction list matches failure-notice.mjs line for line, with only the prefixes and one line added', () => {
const source = file => fs.readFileSync(fileURLToPath(new URL(file, import.meta.url)), 'utf8');
const block = text => {
const body = /const REDACT = \[\n([\s\S]*?)\n\];/.exec(text)[1];
return body.split('\n').map(line => line.trim()).filter(line => line && !line.startsWith('//')).map(line => line.replace(/,\s*\/\/ .*$/, ',').replace(/,$/, ''));
};
const keyWord = text => /const KEY_WORD = (.*);/.exec(text)[1];
const theirs = source('../../harness/src/failure-notice.mjs'), ours = source('../src/redact.mjs');
assert.equal(keyWord(ours), keyWord(theirs));
const expected = block(theirs).map(line => line.replace('(?:sk|msk|rk|', '(?:sk|msk|mso|mst|msp|rk|'));
assert.equal(expected.filter((line, i) => line !== block(theirs)[i]).length, 1, 'the original has one key-prefix line');
const at = expected.findIndex(line => line.includes('(?:sk|msk|mso|mst|msp|rk|'));
expected.splice(at + 1, 0, '/ms[kotp][-_]\\S+/gi');
assert.deepEqual(block(ours), expected);
});
@@ -102,10 +102,12 @@ test('after Ride all the launcher asks admission for a direct anthropic route an
};
const launchOf = async riding => {
const root = tmp(t);
// A Claude model on a legacy entry counts as OAuth and runs on claude-code only. The stand-in adapter
// path skips only the binary check; the launch stops at authorizeLaunch, before any adapter runs.
const f = fixture(root, 'acme', doc => {
doc.plugins = { ...doc.plugins, harness: ['pi'] };
doc.plugins = { ...doc.plugins, harness: ['claude-code'] };
doc.launch.models['claude-opus-5-5'] = { provider: 'anthropic', model: 'claude-opus-5-5' };
doc.roles.coder.vars = { harness: 'pi', model: 'claude-opus-5-5', thinking: 'low' };
doc.roles.coder.vars = { harness: 'claude-code', model: 'claude-opus-5-5', thinking: 'low' };
return doc;
});
if (riding) await ride(join(root, 'config', 'businesses', 'acme.json'));
@@ -119,7 +121,7 @@ test('after Ride all the launcher asks admission for a direct anthropic route an
if (x.op === 'authorizeLaunch') throw Object.assign(Error('fixture authorization stop'), { code: 'fixture-policy' });
return {};
} };
const makeLoader = await fakeHarnesses(t, { pi: null }, write => write('model-provider', 'cliproxy', `export * from ${JSON.stringify(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).href)};`));
const makeLoader = await fakeHarnesses(t, { 'claude-code': '/fixture-unused' }, write => write('model-provider', 'cliproxy', `export * from ${JSON.stringify(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).href)};`));
const system = { ...JSON.parse(readFileSync(f.config, 'utf8')), proxy: { port: 1, binary: '/fixture-unused' } };
const launcher = createLauncher({ host, system, env: f.env, makeLoader, bwrap: '/usr/bin/true', log: () => {} });
return { answer: await launcher.fromSession('fixture-cap', 'coder'), ops };
+45 -3
View File
@@ -201,6 +201,43 @@ test('a removal saved while Ride all works on earlier organizations is read befo
assert.equal(g2.calls.some(([v]) => v === 'plugins.set'), false);
});
test('settings-p3 R1: the change log is read again before each add, and a read that fails skips the add', async t => {
// While Ride all works on 'first', the owner adds cliproxy to 'late' on its Settings page and takes it
// off again. Only its change log shows that; the receipts do not. The run's first read showed nothing.
let lateLog = '';
const first = bus({ providers: [] }), late = bus({ providers: [] });
const firstCall = async (verb, args) => { if (verb === 'plugins') lateLog = committed([{ path: 'plugins.model-provider', old: [], new: ['cliproxy'] }]) + committed([{ path: 'plugins.model-provider', old: ['cliproxy'], new: [] }]); return first.call(verb, args); };
const f = admin(t, { riders: async () => [{ id: 'first', fixture: false, cliproxy: false, changes: '', call: firstCall }, { id: 'late', fixture: false, cliproxy: false, changes: lateLog, call: late.call }] });
const r = await f.admin.rideAll();
assert.deepEqual(r.added, ['first']); assert.deepEqual(r.skipped, [{ id: 'late', reason: 'removed' }]);
assert.equal(late.calls.some(([v]) => v === 'plugins.set'), false);
assert.deepEqual(receipts(f.dataRoot).filter(x => x.org === 'late').map(x => x.op), []);
// Fail closed: a change log that can no longer be read, an organization that is no longer listed,
// or a list that can't be read again skips the add as unreadable, with no intent and no plugins.set.
for (const [name, again] of [
['log unreadable', b => [{ id: 'o', fixture: false, cliproxy: false, changes: null, call: b.call }]],
['no longer listed', () => []],
['list throws', () => { throw new Error('read failed'); }],
]) {
const b = bus({ providers: [] });
let reads = 0;
const g = admin(t, { riders: async () => (reads++ === 0 ? [{ id: 'o', fixture: false, cliproxy: false, changes: '', call: b.call }] : again(b)) });
assert.deepEqual((await g.admin.rideAll()).skipped, [{ id: 'o', reason: 'unreadable' }], name);
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false, name);
assert.deepEqual(receipts(g.dataRoot).filter(x => x.op === 'ride-intent'), [], name);
}
});
test('settings-p3 review P3-1: an organization that took cliproxy during the run reads as already using it, with no add', async t => {
const b = bus({ providers: [] });
let reads = 0;
const f = admin(t, { riders: async () => [{ id: 'o', fixture: false, cliproxy: reads++ > 0, changes: '', call: b.call }] });
const r = await f.admin.rideAll();
assert.deepEqual([r.added, r.already, r.skipped], [[], ['o'], []]);
assert.equal(b.calls.some(([v]) => v === 'plugins.set'), false);
assert.deepEqual(receipts(f.dataRoot).filter(x => x.op === 'ride-intent'), []);
});
test('an intent receipt that cannot be written stops that add before plugins.set', async t => {
const b = bus({ providers: [] });
const f = admin(t, { riders: async () => [{ id: 'w', fixture: false, cliproxy: false, changes: '', call: b.call }] });
@@ -388,10 +425,15 @@ test('a fixture organization moves only when stopped, with a proxy, a riding bus
assert.deepEqual(await f.admin.rideMove({ org: 'nope', principal }), { org: 'nope', moved: false, reason: 'unknown' });
assert.deepEqual(await f.admin.rideMove({ org: 'real', principal }), { org: 'real', moved: false, reason: 'ready' });
assert.deepEqual(await f.admin.rideMove({ org: 'live', principal }), { org: 'live', moved: false, reason: 'bus-running' });
// A slow or busy bus that does not answer, a status that cannot be read, or no status at all is running.
for (const org of ['busy', 'unproven', 'no-status']) assert.deepEqual(await f.admin.rideMove({ org, principal }), { org, moved: false, reason: 'bus-running' }, org);
// A slow or busy bus that does not answer, or a status that cannot be read, is running.
for (const org of ['busy', 'unproven']) assert.deepEqual(await f.admin.rideMove({ org, principal }), { org, moved: false, reason: 'bus-running' }, org);
// settings-p3 R2: no status at all (the single-business Console) can never show the bus stopped, so
// "stop its bus" would not help: moving is not available there, and whether it runs is unknown.
assert.deepEqual(await f.admin.rideMove({ org: 'no-status', principal }), { org: 'no-status', moved: false, reason: 'not-available' });
const listed = await f.admin.rideAll();
assert.deepEqual(listed.fixtures, [{ id: 'stand-in', running: false }, { id: 'live', running: true }, { id: 'busy', running: true }, { id: 'unproven', running: true }, { id: 'no-status', running: true }]);
assert.deepEqual(listed.fixtures, [{ id: 'stand-in', running: false }, { id: 'live', running: true }, { id: 'busy', running: true }, { id: 'unproven', running: true }, { id: 'no-status', running: null }]);
// settings-p3 review P3-3: the status summary says so before any run, without asking any bus.
assert.deepEqual((await f.admin.status()).ride.filter(r => r.state === 'fixture'), [{ id: 'stand-in', state: 'fixture' }, { id: 'live', state: 'fixture' }, { id: 'busy', state: 'fixture' }, { id: 'unproven', state: 'fixture' }, { id: 'no-status', state: 'fixture', running: null }]);
ownerNow = { ...owner, proxy: false };
assert.deepEqual(await f.admin.rideMove({ org: 'stand-in', principal }), { org: 'stand-in', moved: false, reason: 'no-proxy' });
ownerNow = { ...owner, riding: false };
@@ -5,7 +5,12 @@ export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
const MODEL = MODEL_ID;
const MAX_MODELS = 10000;
const family = url => url === ZAI_URL ? 'zai' : 'other';
const harnesses = upstream => upstream === 'claude' ? ['claude-code', 'pi'] : ['pi'];
// #1873 (Jason 2026-11-19): a Claude model from an OAuth account runs on claude-code only;
// a model from an API key, Claude or not, runs on claude-code and pi. The rule keys on the account
// kind: the proxy lists OAuth accounts (credentials, upstream `claude`) apart from API-key groups.
// It routes a request by model name across every account, so a group model whose name an OAuth
// Claude account offers (`oauth`) could be served by that account and is held to claude-code too.
const harnesses = (upstream, oauth = false) => upstream === 'claude' || oauth ? ['claude-code'] : ['claude-code', 'pi'];
const slug = (upstream, model) => `${upstream}-${model}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/g, '');
export async function catalogue({ listAccounts, listModels, listGroups, now }) {
@@ -25,12 +30,20 @@ export async function catalogue({ listAccounts, listModels, listGroups, now }) {
reason: upstream === 'other' || upstream === 'codex' ? 'unverified' : null, harnesses: harnesses(upstream) });
if (models.length > MAX_MODELS) throw Error();
};
// Every OAuth Claude account's names, whatever its state: one disabled, cooling down or signed
// out now can serve a request later, before the catalogue is read again.
const oauth = new Set();
for (const row of accounts.files) {
if (!['claude', 'codex'].includes(row?.provider) || row.disabled === true || row.unavailable === true || !['ready', 'active'].includes(row.status)) continue;
if (!['claude', 'codex'].includes(row?.provider)) continue;
const listed = row.disabled !== true && row.unavailable !== true && ['ready', 'active'].includes(row.status);
if (!listed && row.provider !== 'claude') continue;
if (typeof row.name !== 'string' || !row.name || row.name.length > 512) throw Error();
const response = await listModels(row.name);
if (!Array.isArray(response?.models) || response.models.length > MAX_MODELS) throw Error();
for (const model of response.models) add(row.provider, model?.id);
for (const model of response.models) {
if (row.provider === 'claude' && typeof model?.id === 'string') oauth.add(model.id.toLowerCase());
if (listed) add(row.provider, model?.id);
}
}
for (const group of groups) {
if (!Array.isArray(group?.keys)) throw Error();
@@ -43,6 +56,7 @@ export async function catalogue({ listAccounts, listModels, listGroups, now }) {
if (!Array.isArray(group.models) || group.models.length > MAX_MODELS) throw Error();
for (const model of group.models) add(upstream, model?.alias || model?.name);
}
for (const m of models) m.harnesses = harnesses(m.upstream, oauth.has(m.model.toLowerCase()));
return { status: 'ready', observedAt: now(), models, notices: [...new Set(notices)] };
} catch (error) {
return { status: 'unavailable', observedAt: null, models: [], notices: [], ...(error.code === 'model-key-collision' ? { reason: error.code } : {}) };
@@ -61,7 +75,9 @@ const ROUTES = Object.freeze({
claude: { routeId: 'anthropic', endpoint: 'root', api: 'anthropic-messages', piProvider: 'anthropic', compat: null },
zai: { routeId: 'glm', endpoint: 'v1', api: 'openai-completions', piProvider: 'mosaic-proxy-glm', compat: { thinkingFormat: 'zai', zaiToolStream: true } },
codex: { routeId: 'codex', endpoint: 'v1', api: 'openai-responses', piProvider: 'mosaic-proxy-codex', compat: null },
other: { routeId: 'anthropic', endpoint: 'root', api: 'anthropic-messages', piProvider: 'anthropic', compat: null },
// #1873: its own pi provider, never pi's built-in "anthropic", whose Claude models an entry there
// would keep and send to the proxy.
other: { routeId: 'anthropic', endpoint: 'root', api: 'anthropic-messages', piProvider: 'mosaic-proxy-other', compat: null },
});
export function route({ selection, harness }) {
let upstream = selection?.upstream;
@@ -72,7 +88,11 @@ export function route({ selection, harness }) {
}
if (!upstream) upstream = ({ anthropic: 'claude', zai: 'zai' })[selection?.provider];
if (!Object.hasOwn(ROUTES, upstream ?? '')) return { code: 'proxy-provider-unsupported' };
if (harness && !harnesses(upstream).includes(harness)) return { code: 'model-harness-incompatible' };
// A selection that names this module came from the catalogue, which knows the account kind and is
// checked at admission. A legacy one (a provider or route name only) gets no catalogue check, so
// the kind is unknown and a model named as Claude is treated as OAuth.
const legacyClaude = selection?.module !== 'cliproxy' && /claude/i.test(String(selection?.model ?? ''));
if (harness && !harnesses(upstream, legacyClaude).includes(harness)) return { code: 'model-harness-incompatible' };
if (typeof selection.model !== 'string' || !MODEL.test(selection.model)) return { code: 'model-provider-unavailable' };
return { provider: selection.provider ?? upstream, model: selection.model, upstream, ...ROUTES[upstream] };
}
@@ -17,15 +17,16 @@ test('catalogue attributes configured accounts, uses aliases, and enforces harne
const result = await catalogue(deps());
assert.equal(result.status, 'ready');
const zai = result.models.find(x => x.upstream === 'zai');
assert.deepEqual([zai.key, zai.model, zai.available, zai.harnesses], ['zai-fixture-alias', 'fixture-alias', true, ['pi']]);
assert.deepEqual([zai.key, zai.model, zai.available, zai.harnesses], ['zai-fixture-alias', 'fixture-alias', true, ['claude-code', 'pi']]);
const claude = result.models.find(x => x.upstream === 'claude');
assert.deepEqual(claude.harnesses, ['claude-code', 'pi']);
assert.deepEqual(preflight({ selection: zai, harness: 'claude-code', catalogue: result }), { allow: false, code: 'model-harness-incompatible' });
assert.deepEqual(claude.harnesses, ['claude-code']);
assert.deepEqual(preflight({ selection: zai, harness: 'claude-code', catalogue: result }), { allow: true });
assert.deepEqual(preflight({ selection: zai, harness: 'fixture-harness', catalogue: result }), { allow: false, code: 'model-harness-incompatible' });
assert.deepEqual(preflight({ selection: zai, harness: 'pi', catalogue: result }), { allow: true });
assert.ok(!JSON.stringify(result).includes('credential-1'));
});
test('an empty group offers no models; unknown groups offer pi only and are unverified', async () => {
test('an empty group offers no models; unknown groups offer claude-code and pi and are unverified', async () => {
const d = deps();
d.listAccounts = async () => ({ files: [] });
d.listGroups = async () => [
@@ -34,7 +35,7 @@ test('an empty group offers no models; unknown groups offer pi only and are unve
];
const c = await catalogue(d);
assert.equal(c.models.length, 1);
assert.deepEqual([c.models[0].upstream, c.models[0].harnesses, c.models[0].reason], ['other', ['pi'], 'unverified']);
assert.deepEqual([c.models[0].upstream, c.models[0].harnesses, c.models[0].reason], ['other', ['claude-code', 'pi'], 'unverified']);
assert.ok(c.notices.includes('z.ai account has no models configured. Add them on Model proxy.'));
});
@@ -50,7 +51,7 @@ test('module declares only supported transports and legacy routes without wideni
assert.deepEqual(route({ selection: { upstream: 'codex', model: 'fixture-codex' }, harness: 'pi' }), {
provider: 'codex', model: 'fixture-codex', upstream: 'codex', routeId: 'codex', endpoint: 'v1', api: 'openai-responses', piProvider: 'mosaic-proxy-codex', compat: null,
});
assert.equal(route({ selection: { upstream: 'zai', model: 'fixture-zai' }, harness: 'claude-code' }).code, 'model-harness-incompatible');
assert.equal(route({ selection: { upstream: 'zai', model: 'fixture-zai' }, harness: 'fixture-harness' }).code, 'model-harness-incompatible');
assert.equal(route({ selection: { provider: 'proxy', route: 'unknown', model: 'fixture' }, harness: 'pi' }).code, 'proxy-route-unknown');
assert.equal(route({ selection: { provider: 'proxy', model: 'fixture' }, harness: 'pi' }).code, 'proxy-route-missing');
});
@@ -68,3 +69,113 @@ test('a second fixture module resolves independently and ambiguous legacy mappin
assert.equal(selectModelProvider([first,second],{...entry,module:'first-fixture'}),null);
assert.equal(selectModelProvider([first,second,{...second,name:'third-fixture'}],entry),null);
});
// #1873 harness-matrix (Jason 2026-11-19): a Claude model from an OAuth account runs on
// claude-code only; every other proxy model runs on claude-code and pi.
test('an OAuth Claude model is offered on claude-code only and refused on pi at catalogue, preflight and route', async () => {
const { route } = await import('../model-provider/cliproxy/index.mjs');
const c = await catalogue(deps());
const claude = c.models.find(x => x.upstream === 'claude');
assert.deepEqual(claude.harnesses, ['claude-code']);
assert.deepEqual(preflight({ selection: claude, harness: 'pi', catalogue: c }), { allow: false, code: 'model-harness-incompatible' });
assert.deepEqual(preflight({ selection: claude, harness: 'claude-code', catalogue: c }), { allow: true });
for (const selection of [{ upstream: 'claude', model: 'fixture-chat' }, { provider: 'anthropic', model: 'fixture-chat' }, { provider: 'proxy', route: 'anthropic', model: 'fixture-chat' }]) {
assert.equal(route({ selection, harness: 'pi' }).code, 'model-harness-incompatible', JSON.stringify(selection));
assert.equal(route({ selection, harness: 'claude-code' }).upstream, 'claude');
}
});
test('a z.ai and a codex model run on claude-code and pi', async () => {
const { route } = await import('../model-provider/cliproxy/index.mjs');
const d = deps();
d.listAccounts = async () => ({ files: [{ name: 'credential-3', provider: 'codex', status: 'active' }] });
d.listModels = async () => ({ models: [{ id: 'fixture-codex' }] });
const c = await catalogue(d);
for (const upstream of ['zai', 'codex']) {
const m = c.models.find(x => x.upstream === upstream);
assert.deepEqual(m.harnesses, ['claude-code', 'pi'], upstream);
for (const harness of ['claude-code', 'pi']) {
assert.deepEqual(preflight({ selection: m, harness, catalogue: c }), { allow: true }, `${upstream} ${harness}`);
assert.equal(route({ selection: { upstream, model: m.model }, harness }).upstream, upstream, `${upstream} ${harness}`);
}
}
assert.equal(route({ selection: { provider: 'zai', model: 'fixture-zai' }, harness: 'claude-code' }).routeId, 'glm');
assert.equal(route({ selection: { provider: 'proxy', route: 'codex', model: 'fixture-codex' }, harness: 'claude-code' }).routeId, 'codex');
});
test('an API-key model runs on claude-code and pi whatever its name; the rule keys on the account kind', async () => {
const { route } = await import('../model-provider/cliproxy/index.mjs');
const d = deps();
// Jason 2026-11-19: a Claude model from an API key runs on any harness. A name that says Claude,
// or an OpenRouter-style anthropic/ name, is not an OAuth account.
d.listGroups = async () => [{ 'base-url': 'https://fixture.invalid', keys: [{ auth_index: 'k' }], models: [
{ name: 'upstream-x', alias: 'Claude-Fixture' }, { name: 'anthropic/claude-sonnet-5-5' }, { name: 'claude-upstream', alias: 'fixture-safe' }] },
{ 'base-url': ZAI, keys: [{ auth_index: 'z' }], models: [{ name: 'claude-zai-fixture' }] }];
const c = await catalogue(d);
for (const [upstream, model] of [['other', 'Claude-Fixture'], ['other', 'anthropic/claude-sonnet-5-5'], ['other', 'fixture-safe'], ['zai', 'claude-zai-fixture']]) {
const row = c.models.find(x => x.upstream === upstream && x.model === model);
assert.deepEqual(row.harnesses, ['claude-code', 'pi'], model);
for (const harness of ['claude-code', 'pi'])
assert.deepEqual(preflight({ selection: row, harness, catalogue: c }), { allow: true }, `${model} ${harness}`);
}
for (const upstream of ['other', 'zai', 'codex'])
for (const model of ['claude-fixture', 'anthropic/claude-sonnet-5-5', 'fixture-safe'])
for (const harness of ['claude-code', 'pi'])
assert.equal(route({ selection: { module: 'cliproxy', upstream, model }, harness }).upstream, upstream, `${upstream} ${model} ${harness}`);
});
test('a legacy selection carries no account data, so a Claude-named model on it is treated as OAuth and held to claude-code', async () => {
const { route } = await import('../model-provider/cliproxy/index.mjs');
// A legacy entry (a provider or route name, no module) gets no catalogue check at launch, and the
// proxy may serve its name from an OAuth Claude account.
for (const selection of [{ provider: 'zai', model: 'claude-opus-5-5' }, { provider: 'proxy', route: 'glm', model: 'Claude-Opus-5-5' },
{ provider: 'proxy', route: 'codex', model: 'claude-sonnet-5-5' }, { upstream: 'other', model: 'anthropic/claude-sonnet-5-5' }]) {
assert.equal(route({ selection, harness: 'pi' }).code, 'model-harness-incompatible', JSON.stringify(selection));
assert.equal(route({ selection, harness: 'claude-code' }).model, selection.model, JSON.stringify(selection));
// The same name from the catalogue, where the account kind is known, runs on pi.
if (selection.upstream || selection.provider === 'zai') assert.equal(route({ selection: { ...selection, module: 'cliproxy' }, harness: 'pi' }).model, selection.model);
}
for (const selection of [{ provider: 'zai', model: 'glm-fixture' }, { provider: 'proxy', route: 'codex', model: 'gpt-fixture' }])
assert.equal(route({ selection, harness: 'pi' }).model, selection.model, JSON.stringify(selection));
});
test('an API-key model whose name an OAuth Claude account offers stays on claude-code, the account listed or not (fail closed)', async () => {
const { route } = await import('../model-provider/cliproxy/index.mjs');
// The proxy routes by model name across every account, so a group model named as an OAuth Claude
// account's model can be served by that account. A disabled, unavailable or signed-out account
// can serve it later, before the catalogue is read again, so its names count too.
for (const state of [{ status: 'active' }, { status: 'active', disabled: true }, { status: 'active', unavailable: true }, { status: 'error' }]) {
const d = deps();
d.listAccounts = async () => ({ files: [{ name: 'credential-1', provider: 'claude', ...state }, { name: 'credential-2', provider: 'codex', status: 'active' }] });
d.listModels = async name => ({ models: name === 'credential-1' ? [{ id: 'Fixture-Chat' }] : [{ id: 'fixture-codex' }] });
d.listGroups = async () => [{ 'base-url': 'https://fixture.invalid', keys: [{ auth_index: 'k' }], models: [{ name: 'fixture-chat' }, { name: 'fixture-safe' }] },
{ 'base-url': ZAI, keys: [{ auth_index: 'z' }], models: [{ name: 'upstream', alias: 'FIXTURE-CHAT' }] }];
const c = await catalogue(d);
const label = JSON.stringify(state);
assert.equal(c.status, 'ready', label);
const by = (upstream, model) => c.models.find(x => x.upstream === upstream && x.model === model);
assert.deepEqual(by('other', 'fixture-chat').harnesses, ['claude-code'], label);
assert.deepEqual(by('zai', 'FIXTURE-CHAT').harnesses, ['claude-code'], label);
assert.deepEqual(by('other', 'fixture-safe').harnesses, ['claude-code', 'pi'], label);
assert.deepEqual(by('codex', 'fixture-codex').harnesses, ['claude-code', 'pi'], label);
assert.deepEqual(preflight({ selection: by('other', 'fixture-chat'), harness: 'pi', catalogue: c }), { allow: false, code: 'model-harness-incompatible' }, label);
// Only a usable account's models are offered as rows.
assert.equal(c.models.some(x => x.upstream === 'claude'), state.status === 'active' && !state.disabled && !state.unavailable, label);
}
// route() has no account data: it holds upstream claude only, and admission holds the rest by the catalogue.
assert.equal(route({ selection: { upstream: 'other', model: 'fixture-chat' }, harness: 'pi' }).upstream, 'other');
});
test('a Claude OAuth account whose models cannot be read makes the catalogue unavailable, listed or not', async () => {
for (const state of [{ status: 'active' }, { status: 'active', disabled: true }]) {
const d = deps();
d.listAccounts = async () => ({ files: [{ name: 'credential-1', provider: 'claude', ...state }] });
d.listModels = async () => { throw new Error('fixture private error'); };
assert.equal((await catalogue(d)).status, 'unavailable', JSON.stringify(state));
}
// A codex account that is not usable is not read at all.
const d = deps();
d.listAccounts = async () => ({ files: [{ name: 'credential-2', provider: 'codex', status: 'active', disabled: true }] });
d.listModels = async () => { throw new Error('fixture private error'); };
assert.equal((await catalogue(d)).status, 'ready');
});
+16 -1
View File
@@ -313,7 +313,7 @@ export function checkHostedRoute({ adapter, harnessMounts, installRoots, protect
// just made there, never a link the session left: bwrap resolves a bind's source on the host.
// The adapter and the mounts pass checkHostedRoute against `installRoots`, `protectedPaths` and
// `codeRoot` with its `codeHolder` here too; without install roots nothing binds.
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, codeHolder = null, relaySocket, node = process.execPath, readOnly = [] }) {
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, codeHolder = null, relaySocket, node = process.execPath, readOnly = [], harnessFiles = [] }) {
if (relaySocket !== join(runDir, "relay.sock")) throw new Error("hosted binds: the relay socket must be the run directory's relay.sock");
const healthDest = join(runDir, "work", "health");
for (const p of [runDir, healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work"), healthDest]) {
@@ -326,6 +326,20 @@ export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], in
try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${relative(runDir, p)} is missing`); }
if (!ok(st)) throw new Error(`hosted binds: ${relative(runDir, p)} is not what the host made`);
}
// #1873 harness-matrix: a harness's own config file the host wrote under the session's HOME (pi's
// models.json), bound read-only over the writable run directory so the session cannot change
// the proxy it reaches. Each is a regular file, not a link, inside runDir/home.
const homeDir = join(runDir, "home");
if (!Array.isArray(harnessFiles) || harnessFiles.length > HOSTED_MOUNTS_MAX) refuseRoute("harness-files", "too many harness files");
for (const f of harnessFiles) {
if (!cleanPath(f) || !f.startsWith(homeDir + "/")) refuseRoute("harness-files", "a harness file is outside the session's HOME");
let st;
try { st = lstatSync(f); } catch { refuseRoute("harness-files", "a harness file is missing"); }
if (!st.isFile() || st.nlink !== 1) refuseRoute("harness-files", "a harness file is not a regular file");
for (let parent = dirname(f); parent.length > runDir.length; parent = dirname(parent)) {
if (lstatSync(parent).isSymbolicLink()) refuseRoute("harness-files", "a harness file's directory is a link");
}
}
const route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, codeHolder, runDir, node });
const out = systemBinds(node);
for (const f of RUNNER_FILES) out.push({ kind: "ro", src: f, why: "a repository file the runner loads" });
@@ -337,6 +351,7 @@ export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], in
{ kind: "ro", src: healthDir, dest: healthDest, why: "the health snapshots the Console writes, read-only, inside the workspace the read tools reach" },
{ kind: "ro", src: join(runDir, "bundle"), why: "the run's bundle stays as the host wrote it" },
{ kind: "ro", src: join(runDir, "session.json"), why: "the session file stays as the host wrote it" },
...harnessFiles.map((f) => ({ kind: "ro", src: f, why: "the harness's own config file, as the host wrote it" })),
{ kind: "ro", src: relaySocket, why: "the host's relay, the only broker the runner reaches" },
{ kind: "rw", src: join(runDir, "tmp"), dest: "/tmp", why: "a private /tmp, on disk in the run directory" },
);
+32 -1
View File
@@ -4,7 +4,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:net";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { linkSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { HOSTED_MOUNTS_MAX, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../src/sandbox.mjs";
@@ -243,3 +243,34 @@ test("each mount field is read once, and no mount's dest lies in or around anoth
}
assert.equal(hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: "/opt/x", why: "w" }, { src: join(p.install, "n"), dest: "/opt/xy", why: "w" }] }).filter((b) => b.dest?.startsWith("/opt/")).length, 2);
});
// #1873 harness-matrix: a harness's own config file under the session's HOME (pi's models.json) is
// bound read-only after the writable run directory, so the session cannot change the proxy it
// reaches. A file outside HOME, a link, a hard link, a missing file or a linked directory is refused.
test("hosted binds hold a harness file read-only over the run directory, and refuse one outside HOME or not a plain file", async (t) => {
const p = await layout(t);
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
const agentDir = join(p.runDir, "home", ".pi", "agent");
mkdirSync(agentDir, { recursive: true });
const file = join(agentDir, "models.json");
writeFileSync(file, "{}");
const list = hostedBinds({ ...base, harnessFiles: [file] });
const rw = list.findIndex((b) => b.kind === "rw" && b.src === p.runDir);
const ro = list.findIndex((b) => b.kind === "ro" && b.src === file && b.dest === undefined);
assert.ok(rw >= 0 && ro > rw, "read-only, after the writable run directory");
const refused = (files, label) => assert.throws(() => hostedBinds({ ...base, harnessFiles: files }), (e) => e.code === "hosted-binds-refused" && e.fence === "harness-files", label);
writeFileSync(join(p.runDir, "work", "x.json"), "{}");
refused([join(p.runDir, "work", "x.json")], "outside HOME");
refused([join(p.runDir, "home", "..", "work", "x.json")], "a .. path");
refused([join(p.runDir, "home", "absent.json")], "missing");
refused([join(p.runDir, "home")], "a directory");
symlinkSync(join(p.runDir, "work", "x.json"), join(p.runDir, "home", "link.json"));
refused([join(p.runDir, "home", "link.json")], "a link");
linkSync(join(p.runDir, "work", "x.json"), join(p.runDir, "home", "hard.json"));
refused([join(p.runDir, "home", "hard.json")], "a hard link");
mkdirSync(join(p.runDir, "work", "d"));
writeFileSync(join(p.runDir, "work", "d", "m.json"), "{}");
symlinkSync(join(p.runDir, "work", "d"), join(p.runDir, "home", "dlink"));
refused([join(p.runDir, "home", "dlink", "m.json")], "a linked directory");
refused(Array.from({ length: 9 }, () => file), "too many");
});
+11 -1
View File
@@ -1376,7 +1376,7 @@ The existing user notice names the governance records visible to the owner.
## Model proxy page (P4, #1828)
The owner's Settings → Model proxy page (`/settings/model-proxy`) signs in Claude/Codex accounts, accepts write-only
The owner's Settings → Model setup page (named Model proxy before #1873) (`/settings/model-proxy`) signs in Claude/Codex accounts, accepts write-only
z.ai API keys, sets account priority, and lists client-key IDs. It uses only
`/api/proxy/` routes over the owner's human bus transport. The old `/proxy` bookmark redirects to this page after the same access checks. A missing instance
proxy refuses `not-configured`; it does not ask for a management key. That key
@@ -1394,6 +1394,16 @@ retires the state. Refreshing the page does not restore a pending login.
Usage is reserved on this page for P5; P4 adds no usage source. PIN changes
require the offline upgrade acceptance documented in packages/model-proxy.
Settings slice 1 (#1873). Once the service runs, the page lists each organization that can't see
the models, or is not running. For each one that can't see them it reads that organization's own
routes (`GET /api/orgs/<id>/bus/routes`, the read Routing uses) and shows the bus's cause as a
plain line, with the bus's words under Technical details. A Restart shows only when the bus names
no cause or a cause a fresh start clears. With the dev fixture a restart is refused and stops the
organization, and no endpoint removes the fixture provider yet, so that row says it can't be changed
from Console. Two models that get the same short name (`model-key-collision`) get no Restart either.
Only an organization a restart can help holds the next step. A refused restart keeps its reason on its row. Only the next step has a
button; done steps, Fence, Init lock and the service controls sit under Technical details.
Archived project routes use the inclusive project read for the name, saved threads and room history. They offer Unarchive in send mode; thread creation, resume, sending and clear controls are unavailable while archived. Archive styling uses only `.project-archive-control` and `.project-archived-filter`.
### Recovering local process state
+22 -2
View File
@@ -45,6 +45,8 @@ import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snaps
import { busesStopped } from '../../cli/src/proxy-admin-host.mjs';
import { agentLevelsWriteRoutes } from './agent-levels-write.mjs';
import { triageRouteRoutes } from './triage-route-http.mjs';
import { keyState, ridingOrgs, triageKeyCall } from './triage-access.mjs';
import { readKey as readTriageKey } from '../../bus/src/triage-key-file.mjs';
import { RESTART_EXIT } from '../../cli/src/org-console.mjs';
import { ID_PATTERN, systemOnly } from '../../organization/src/vocabulary.mjs';
import { selectorScope } from '../../organization/src/selector.mjs';
@@ -226,7 +228,7 @@ try {
// (read only) and, through `call`, from its bus as the owner. A file that cannot be read gives
// undefined fields, which Ride all names as unreadable. The change log is read with the writer's
// own check (no symlink, a regular file this user owns, not group or world writable).
const rideRiders = async () => {
const rideRiders = async ({ timeoutMs = 5000, deadline } = {}) => {
const writer = organizationWriter({ dir: configDir(), rolesDir: rolesDir() });
const local = id => readRider({ id, read: () => writer.read(id).document, readLog: () => ownedText(writer.logFile(id), { mask: 0o022 }), isFixture: orgUsesFixture });
const down = async () => { throw Object.assign(new Error('the bus is not reachable'), { code: 'no-bus-host' }); };
@@ -235,7 +237,7 @@ try {
const out = [];
for (const org of await listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance })) {
if (org.state !== 'active') continue;
let call = down; try { const paths = orgPaths(org.root); call = busCaller({ dataRoot: org.root, socket: paths.socket, business: org.id, timeoutMs: 5000 }); } catch {}
let call = down; try { const paths = orgPaths(org.root); call = busCaller({ dataRoot: org.root, socket: paths.socket, business: org.id, timeoutMs, ...(deadline ? { deadline } : {}) }); } catch {}
// The organization admin page's stopped test reads this bus status (its process id).
out.push({ ...local(org.id), call, status: () => orgBusStatus({ configDir: configDir(), dataRoot: system.dataRoot, instance }, org.id) });
}
@@ -292,6 +294,8 @@ try {
const triage = triageRoute ? createTriageHost({
dataRoot: system.dataRoot, route: triageRoute, proxyPort: triageProxyPort, tokenPattern: triageTokenPattern(configDir()),
devOwner: Boolean(devOwner), log: line => console.log(line),
// proxy-scope slice 4: a session on a key past its retireAt stops with triage-key-rotated.
keyRecord: () => readTriageKey(configDir()),
readSnapshot: () => composeSnapshot({
orgs: () => listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance }),
busStatus: id => orgBusStatus({ configDir: configDir(), dataRoot: system.dataRoot, instance }, id),
@@ -325,6 +329,22 @@ try {
// next admit.
const triageRoutes = system && (devOwner || ssoOn) ? [triageRouteRoutes({
dataRoot: system.dataRoot, log: line => console.log(line),
// proxy-scope slice 4: the Triage key through one riding organization's bus (proxy.triage.key),
// as Proxy setup's init asks one bus. The Console reads the key file's state only; it never
// loads the proxy management client or the key verbs' module.
access: {
state: () => keyState(configDir()),
// The same list the key walk asks (cliproxy, not a fixture), read from local files only.
// The owner's proxy must be set up (proxy.json names a port), as ownerModels reads it.
riding: async () => {
let proxy = false;
try { proxy = Number.isInteger(loadProxy(configDir(), system.dataRoot)?.port); } catch {}
return proxy && ridingOrgs(await rideRiders()).length > 0;
},
// One 30 s deadline over the whole walk, not 30 s for each bus.
key: op => { const deadline = Date.now() + 30000; return triageKeyCall({ riders: () => rideRiders({ timeoutMs: 30000, deadline }), op }); },
stop: () => (triage ? triage.stop() : Promise.resolve()),
},
catalogues: async () => {
const read = async call => { try { return (await call('routes'))?.catalogue ?? { status: 'unknown' }; } catch { return { status: 'bus-unavailable' }; } };
if (!organizations) return ownerCall ? [await read(ownerCall)] : [];
+4 -4
View File
@@ -60,11 +60,11 @@ const NONE = ' Nothing was applied.';
const EITHER = ' Part of it may already be applied: check the Agents page before trying again.';
const CHECK = ' Check the Agents page and the inbox before trying again.';
const HIRE_START_REFUSALS = {
'model-provider-unavailable': [409, 'The model proxy does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model proxy.' + NONE],
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model proxy, then try again.' + NONE],
'model-provider-unavailable': [409, 'The model service does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model setup.' + NONE],
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model setup, then try again.' + NONE],
'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness.' + NONE],
'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies.' + NONE],
'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Model proxy.' + NONE],
'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Routing.' + NONE],
'harness-off': [409, 'This harness is not switched on for the organization. Pick a harness listed under Settings > Routing, or ask the owner to switch it on.' + NONE],
'harness-refused': [409, 'The harness refused this route. Clear Thinking, or pick another model or harness under Settings > Routing.' + NONE],
'template-system-only': [409, 'This role template is for the system, not for an organization. Pick another template.' + NONE],
@@ -100,7 +100,7 @@ const HIRE_START_REFUSALS = {
'credential-scope-exceeded': [409, 'The requested credential scope is wider than the role allows.' + CHECK],
// The fields passed the shape check below, so a malformed answer here is a value the organization
// checks refused: most often a model that is not a launch.models key.
'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Model proxy and a role the organization checks accept.' + EITHER],
'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Routing and a role the organization checks accept.' + EITHER],
};
// A reply the endpoint cannot read as a definite answer: no answer, or the bus server's request
// codes. Anything else that reads as a code is a definite refusal.
+28 -1
View File
@@ -10,10 +10,15 @@ export { createProxyAdmin };
// #1873: one organization's catalogue row for the setup page. A count is shown only when the bus
// answered with a model list; otherwise models is null and the page shows a dash, never a made-up 0.
const RESTART_TO_LAUNCH = 'Restart this organization to start agents on these models.';
export async function orgCatalogue(call) {
try {
const value = await call('routes');
return { status: value?.catalogue?.status ?? 'unknown', models: Array.isArray(value?.catalogue?.models) ? value.catalogue.models.length : null };
const status = value?.catalogue?.status ?? 'unknown';
// settings-p3 (re-check 3 P3-5): a bus that picked the service up after it started reads ready but
// starts agents on these models only after a restart (bus runtime.mjs RESTART_TO_LAUNCH).
const launchRestart = status === 'ready' && Array.isArray(value.catalogue.notices) && value.catalogue.notices.includes(RESTART_TO_LAUNCH);
return { status, models: Array.isArray(value?.catalogue?.models) ? value.catalogue.models.length : null, ...(launchRestart ? { launchRestart: true } : {}) };
} catch { return { status: 'bus-unavailable', models: null }; }
}
@@ -31,7 +36,24 @@ const ROUTES = Object.freeze({
// #1873 ride-default: Ride all, and the confirmed move of one stopped fixture organization.
'/api/proxy/admin/ride-all': ['POST', []],
'/api/proxy/admin/ride-move': ['POST', ['org']],
// #1873 settings-backend A1: reads for Model setup. The list names each read's query keys.
'/api/proxy/admin/log': ['GET', ['lines']],
'/api/proxy/admin/service-key': ['GET', []],
'/api/proxy/admin/history': ['GET', ['limit', 'before']],
});
// The A1 reads take a query; every other route ignores one, as before.
const QUERY_ROUTES = new Set(['/api/proxy/admin/log', '/api/proxy/admin/service-key', '/api/proxy/admin/history']);
// Each query key at most once, only the route's own keys, each a plain decimal number.
function readQuery(req, allowed) {
let params;
try { params = new URL(req.url, 'http://localhost').searchParams; } catch { return null; }
const out = {};
for (const [key, value] of params) {
if (!allowed.includes(key) || Object.hasOwn(out, key) || !/^[0-9]{1,15}$/.test(value)) return null;
out[key] = Number(value);
}
return out;
}
export const PROXY_ADMIN_PATHS = Object.freeze(Object.keys(ROUTES));
const INIT_KEYS = ['generate', 'key', 'confirm', 'port', 'rotateGraceMinutes', 'firstOutputSeconds'];
const json = (res, status, value) => {
@@ -66,6 +88,8 @@ export async function proxyAdminHTTP(req, res, { path, admin, call, named, teste
if (req.headersDistinct.origin?.length !== 1 || req.headers.origin !== origin) return done(403, { error: 'cross-origin request refused' });
if (req.headersDistinct['sec-fetch-site']?.length !== 1 || req.headers['sec-fetch-site'] !== 'same-origin') return done(403, { error: 'cross-site request refused' });
}
let query = {};
if (QUERY_ROUTES.has(path)) { query = readQuery(req, route[1]); if (!query) return refuse('invalid-request'); }
if (!admin) return refuse('not-configured');
let args = {};
if (req.method === 'POST') {
@@ -113,6 +137,9 @@ export async function proxyAdminHTTP(req, res, { path, admin, call, named, teste
case '/api/proxy/admin/ride-move':
if (typeof args.org !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(args.org)) return refuse('invalid-request');
return done(200, await admin.rideMove({ org: args.org, principal }));
case '/api/proxy/admin/log': return done(200, await admin.log(Object.hasOwn(query, 'lines') ? { lines: query.lines } : {}));
case '/api/proxy/admin/service-key': return done(200, await admin.serviceKey());
case '/api/proxy/admin/history': return done(200, await admin.history({ ...(Object.hasOwn(query, 'limit') ? { limit: query.limit } : {}), before: query.before ?? null }));
}
} catch (error) {
const code = ['human-required', 'not-configured', 'invalid-request'].includes(error?.code) ? error.code : proxyCode(error, 'outcome-unknown');
+13 -2
View File
@@ -18,7 +18,10 @@ const codes = ['not-configured', 'human-required', 'provider-not-allowed', 'logi
const json = (res, status, value) => {
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(value));
};
export async function proxyHTTP(req, res, { path, call, named, tester, granted, send, origin, user, log }) {
// `record` is the proxy setup controller's recordAccount (settings-backend A1), or null where this
// Console has no proxy setup: after a write's bus call answers, an account change is added to the
// setup history. A record that fails leaves the bus answer as it is and adds recorded: false.
export async function proxyHTTP(req, res, { path, call, named, tester, granted, send, origin, user, log, record = null }) {
const route = routes[path];
const done = (status, value) => {
// No request body, query, login state, authorization URL or exception text.
@@ -48,11 +51,19 @@ export async function proxyHTTP(req, res, { path, call, named, tester, granted,
} catch { return done(400, { error: 'invalid-request' }); }
}
if (path === '/api/proxy/plugins/set' && (!args.plugins || typeof args.plugins !== 'object' || Array.isArray(args.plugins) || Object.keys(args.plugins).length !== 1 || !['harness', 'model-provider'].includes(Object.keys(args.plugins)[0]) || !Array.isArray(Object.values(args.plugins)[0]) || !Object.values(args.plugins)[0].every(name => typeof name === 'string'))) return done(400, { error: 'invalid-request' });
try { return done(200, await call(route[1], args)); }
let value;
try { value = await call(route[1], args); }
catch (error) {
const code = codes.includes(error.code) || (path === '/api/proxy/plugins/set' && typeof error.code === 'string' && /^[a-z-]{1,64}$/.test(error.code)) ? error.code : 'outcome-unknown';
// proxy-pickup (#1873): a bus with no proxy client names the cause in one plain line.
const reason = code === 'not-configured' && typeof error.reason === 'string' ? { reason: error.reason.slice(0, 300) } : {};
return done(code === 'human-required' ? 403 : ['not-configured', 'proxy-down', 'outcome-unknown'].includes(code) ? 503 : 400, { error: code, ...reason });
}
if (req.method === 'POST' && typeof record === 'function') {
let recorded;
try { recorded = record({ verb: route[1], args, result: value, user: user ?? null }); } catch { recorded = false; }
// All four recorded verbs answer a plain object; any other answer is passed on unmarked.
if (recorded === false && value && typeof value === 'object' && !Array.isArray(value)) value = { ...value, recorded: false };
}
return done(200, value);
}
+3 -1
View File
@@ -183,7 +183,9 @@
function breadcrumbs() {
draw();
// SP1: every page inside an organization says which one, after the dashboard: Dashboard / Acme / ...
const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) ? window.MosaicOrg : null;
// #1873 settings slice 4: an organization's Settings page names it with ?org=, so it says which one too.
const page = /^#\/settings\/([^/?]+)/.exec(location.hash)?.[1], orgSettings = !!page && !!window.MosaicOrg?.orgPage?.(page) && /[?&]org=/.test(location.hash);
const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) || orgSettings ? window.MosaicOrg : null;
if (box && org?.id && !box.querySelector('[data-crumb-org]') && !/^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) box.insertAdjacentHTML('afterbegin', `<a href="#/dashboard">Dashboard</a><span aria-hidden="true">/</span><a href="#/orgs/${encodeURIComponent(org.id)}/organization" data-crumb-org>${escape(org.label)}</a><span aria-hidden="true">/</span>`);
// SP7: a trail with nothing above the page only repeats the page's heading, so the heading names it once.
if (!box) return;
+123 -25
View File
@@ -1306,6 +1306,50 @@
const ROUTE_CELLS=[['harness','Harness'],['model','Model'],['thinking','Thinking'],['fallback.harness','Fallback harness'],['fallback.model','Fallback model'],['fallback.thinking','Fallback thinking']];
const routeCells=r=>({harness:r.harness??'',model:r.model??'',thinking:r.thinking??'','fallback.harness':r.fallback?.harness??'','fallback.model':r.fallback?.model??'','fallback.thinking':r.fallback?.thinking??''});
const sameCells=(a,b)=>ROUTE_CELLS.every(([k])=>a[k]===b[k]);
// #1873 settings slice 1 (D2): an organization that lists the model service but cannot see its
// models. For the instance owner the page reads the model service's state once per visit, so the
// line says which is true: the service is not set up, not running or waiting on a restart after
// a key write (a link to its page), or it runs and this organization still cannot read it. A
// running bus picks the service up at its next catalogue read (proxy-pickup), so a Restart is
// offered only when the state says it helps: the bus names no cause, or names one a fresh start
// clears (MosaicConsole.catalogueCause). With the dev fixture a restart is refused and stops the
// organization, so that cause gets its plain line and Check again. The Restart is never a guess.
let serviceState=null, serviceLoading=false;
function readService(){
if(serviceLoading||serviceState!==null||isTester||!triageOwner||!window.MosaicOrg)return; serviceLoading=true;const epoch=orgEpoch;
fetch('/api/proxy/admin/status',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok||!v||typeof v!=='object')throw Error();
serviceState=v.init?.initialized!==true?'not-set-up':v.fence?.set===true?'fenced':v.unit?.active==='active'&&v.unit?.healthy===true?'running':'not-running';})
.catch(()=>{if(epoch!==orgEpoch)return;serviceState=false;}).finally(()=>{if(epoch!==orgEpoch)return;serviceLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
}
function catalogueLine(proxyOn,catalogue){
const label=window.MosaicOrg?.label||'This organization', org=txt(label), id=window.MosaicOrg?.id, owner=canSend&&!isTester;
const lead=`<b>${org} can't see your models yet.</b>`, thinking='A change to thinking alone still saves.';
// The bus's cause (proxy-pickup). A known cause reads as one plain line with the bus's words
// under Technical details; an unknown one shows the bus's words as they are.
const cause=window.MosaicConsole?.catalogueCause?.(label,catalogue?.notices,catalogue?.reason)??null;
const words=!cause?'':cause.plain?`<details class="routes-cause-detail"><summary>Technical details</summary><p class="small muted">${txt(cause.detail)}</p></details>`:`<p class="small warn">${txt(cause.detail)}</p>`;
const plain=cause?.plain?` ${txt(cause.plain)}`:'';
const setupLink=text=>`<a href="#/settings/model-setup">${text}</a>`;
if(!proxyOn)return `<p class="small warn" id="routes-catalogue">${lead}${plain} ${thinking}</p>${words}`;
if(owner)readService();
const recheck='<button type="button" id="routes-recheck">Check again</button>';
const restart=primary=>window.MosaicConsole?.orgRestartButton?.(id,{name:label,primary})??'';
if(owner&&serviceState==='running'&&cause){
const fix=cause.fix==='service'?` ${setupLink('Open Model setup')}.`:'';
const next=cause.restart?`Restart ${org} to try again. It stops for a moment and starts again.`:cause.code==='fixture-proxy-configured'?'':'Check again once that is fixed.';
return `<div class="banner routes-catalogue" id="routes-catalogue" role="status"><p>${lead} ${cause.plain?`Your model service is running.${plain}${fix}`:`Your model service is running, but ${org} can't use it. ${org} says why:`}</p>${cause.plain?'':words}<p>${next} ${thinking}</p><p class="actions">${cause.restart?restart(true)+' ':''}${recheck}</p>${cause.plain?words:''}</div>`;
}
if(owner&&serviceState==='running')return `<div class="banner routes-catalogue" id="routes-catalogue" role="status"><p>${lead} Your model service is running, but ${org} can't read your models from it. Restart ${org} to connect it again. It stops for a moment and starts again. ${thinking}</p>${restart(true)}</div>`;
if(owner&&serviceState==='not-set-up')return `<p class="small warn" id="routes-catalogue">${lead} Your model service isn't set up yet. ${setupLink('Set up the model service')}. ${thinking}</p>`;
if(owner&&serviceState==='fenced')return `<p class="small warn" id="routes-catalogue">${lead} Your model service is waiting for a restart to finish. ${setupLink('Open Model setup to finish it')}. ${thinking}</p>`;
if(owner&&serviceState==='not-running')return `<p class="small warn" id="routes-catalogue">${lead} The model service is not running. ${setupLink('Open Model setup')}. ${thinking}</p>${words}`;
if(owner&&(serviceLoading||(serviceState===null&&triageOwner)))return `<p class="small warn" id="routes-catalogue">${lead} Checking the model service. ${thinking}</p>`;
if(owner&&serviceState===false)return `<div class="banner routes-catalogue" id="routes-catalogue" role="status"><p>${lead}${plain} The model service's status could not be read. ${thinking}</p>${words}<p class="actions">${recheck}</p></div>`;
return `<p class="small warn" id="routes-catalogue">${lead}${plain} ${thinking}${owner?' A new model needs the model service: ask the instance owner to set it up, or press Stop using the model service when this organization does not need it.':''}</p>${words}`;
}
// Check again rereads Routing; the bus looks for the model service at that read. A draft is kept.
document.addEventListener('click',e=>{if(e.target.id!=='routes-recheck')return;e.target.disabled=true;serviceState=null;routesView=null;last.delete('routes');render(true);});
document.addEventListener('mosaic-org-restarted',e=>{if(e.detail?.id!==window.MosaicOrg?.id)return;serviceState=null;routesView=null;last.delete('routes');const path=routeOf().split('?')[0];if(path==='/settings/routing'||document.querySelector('[data-org-down]'))render(true);});
function routesSection(view,instanceInfo){
const title='<h2 id="routes-title">Routing</h2>';
readHarnesses();
@@ -1334,11 +1378,13 @@
// fixture-only catalogue is ready with no model proxy). Before the setting is read it falls
// back to the catalogue status, as before.
const proxyOn=harnessSettings?(Array.isArray(harnessSettings.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[]).includes('cliproxy'):v.catalogue?.status!=='disabled';
const catalogueInfo=v.catalogue?.status==='ready'?`<p class="small muted">Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.</p>${(v.catalogue.notices??[]).map(n=>`<p class="small warn">${txt(n)}</p>`).join('')}`:v.catalogue?.status==='unavailable'?`<p class="small warn">Model catalogue unavailable. A change to thinking alone still saves.${proxyOn&&canSend&&!isTester?' A new model needs the catalogue: set up the model proxy, or, when this organization has none, press Disable model proxy catalogue.':''}</p>${(v.catalogue.notices??[]).map(n=>`<p class="small warn">${txt(n)}</p>`).join('')}`:'<p class="small muted">Model catalogue not enabled.</p>';
const providerControl=canSend&&!isTester?`<button type="button" id="provider-switch" data-enabled="${proxyOn}">${proxyOn?'Disable':'Enable'} model proxy catalogue</button><p role="status" id="provider-switch-status"></p>`:'';
// settings-p3 (re-check 3 P3-5): a ready catalogue the bus picked up late says agents start on these
// models after a restart; that notice gets the organization's Restart (not primary: Save routes is).
const catalogueInfo=v.catalogue?.status==='ready'?`<p class="small muted">Model catalogue, observed ${txt(window.MosaicLocalTime(v.catalogue.observedAt))}.</p>${(v.catalogue.notices??[]).map(n=>`<p class="small warn">${txt(n)}${n===window.MosaicConsole?.RESTART_TO_LAUNCH&&window.MosaicOrg?.id?` ${window.MosaicConsole.orgRestartButton(window.MosaicOrg.id,{name:window.MosaicOrg.label||window.MosaicOrg.id})}`:''}</p>`).join('')}`:v.catalogue?.status==='unavailable'?catalogueLine(proxyOn,v.catalogue):'<p class="small muted">Model catalogue not enabled.</p>';
const providerControl=canSend&&!isTester?`<button type="button" id="provider-switch" data-enabled="${proxyOn}">${proxyOn?'Stop using the model service':'Use your models'}</button><p role="status" id="provider-switch-status"></p>`:'';
const harnessControl=canSend&&!isTester?`<fieldset class="harness-control"><legend>Harnesses</legend>${harnessSettings ? [...new Set([...harnessSettings.available.harness,...(harnessSettings.plugins.harness??[])])].map(name=>`<label><input type="checkbox" data-harness="${esc(name)}"${(harnessDraft??harnessSettings.plugins.harness??[]).includes(name)?' checked':''}${harnessBusy?' disabled':''}> ${txt(name)}</label>`).join('')+` <button type="button" id="harness-save"${harnessBusy?' disabled':''}>Save harnesses</button>` : '<p>Harnesses unavailable.</p><button type="button" id="harness-read">Read harnesses again</button>'}<p role="status" id="harness-status">${txt(harnessReceipt)}</p></fieldset>`:'';
const off=v.harnesses.length?'':'<p class="small warn">No harness is switched on in the business file\'s plugins.harness, so every launch refuses harness-off and a save that changes a harness refuses too. Switch one on under Harnesses.</p>';
return `<section class="panel routing-panel" aria-labelledby="routes-title"><span class="sr-only">${title}</span>${catalogueInfo}${providerControl}${harnessControl}${off}<form id="routes-form"><div class="table-wrap" tabindex="0" role="region" aria-label="Routes, scroll for all columns"><table id="routes-table"><thead><tr><th scope="col" rowspan="2">Agent</th><th scope="colgroup" colspan="3">Primary</th><th scope="colgroup" colspan="3">Fallback</th></tr><tr>${ROUTE_CELLS.map(([,l])=>`<th scope="col">${l.replace('Fallback ','')}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div><p class="small muted">${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}</p><div class="settings-actions route-actions${routesDraft?' has-draft':''}"><button type="submit"${disabled}>${routesBusy?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save routes'}</button> <button type="button" id="routes-reload"${routesDraft?'':' hidden'}${routesBusy||!routesDraft?' disabled':''}>Discard draft</button><p role="status" id="routes-receipt" class="${routesReceipt.startsWith('Outcome unknown')?'banner ref':routesReceipt.includes('Draft kept')?'banner err':routesReceipt.includes('saved')?'settings-success':''}">${txt(routesReceipt)}</p></div>${routesApplyMarkup()}</form></section>`;
const off=v.harnesses.length?'':'<p class="small warn">No harness is switched on for this organization, so every launch is refused, and so is a save that changes a harness. Switch one on under Harnesses.</p>';
return `<section class="panel routing-panel" aria-labelledby="routes-title"><span class="sr-only">${title}</span>${catalogueInfo}${providerControl}${harnessControl}${off}<form id="routes-form"><div class="table-wrap" tabindex="0" role="region" aria-label="Routes, scroll for all columns"><table id="routes-table"><thead><tr><th scope="col" rowspan="2">Agent</th><th scope="colgroup" colspan="3">Primary</th><th scope="colgroup" colspan="3">Fallback</th></tr><tr>${ROUTE_CELLS.map(([,l])=>`<th scope="col">${l.replace('Fallback ','')}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div><p class="small muted">${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}</p><div class="settings-actions route-actions${routesDraft?' has-draft':''}"><button type="submit"${/ data-primary[ >]/.test(catalogueInfo)?' class="route-save-quiet"':''}${disabled}>${routesBusy?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save routes'}</button> <button type="button" id="routes-reload"${routesDraft?'':' hidden'}${routesBusy||!routesDraft?' disabled':''}>Discard draft</button><p role="status" id="routes-receipt" class="${routesReceipt.startsWith('Outcome unknown')?'banner ref':routesReceipt.includes('Draft kept')?'banner err':routesReceipt.includes('saved')?'settings-success':''}">${txt(routesReceipt)}</p></div>${routesApplyMarkup()}</form></section>`;
}
function routesFields(form){const draft=Object.fromEntries(Object.keys(routesView.instances).map(name=>[name,routeCells(routesView.instances[name])]));for(const el of form.querySelectorAll('[data-route]')){const [name,key]=JSON.parse(el.dataset.route);if(draft[name])draft[name][key]=el.value;}return draft;}
// The changed rows only. A fallback with all three cells empty is cleared; one with some set goes
@@ -1357,13 +1403,13 @@
// A viewer without the switch is sent to the owner.
function catalogueStep(code,routes){
if(!['model-catalogue-unavailable','model-provider-unavailable'].includes(code))return '';
if(!canSend||isTester)return ' Ask the organization\'s owner to set up the model proxy, or to disable the model proxy catalogue when the change needs no proxy.';
if(!canSend||isTester)return ' Ask the organization\'s owner to set up the model service, or to stop using it when the change does not need it.';
const names=Array.isArray(harnessSettings?.plugins?.['model-provider'])?harnessSettings.plugins['model-provider']:[];
if(!names.includes('cliproxy'))return '';
const moved=Object.entries(routes).flatMap(([name,r])=>{const was=routesView?.instances?.[name]??{};
return [[r.harness,r.model,was.harness,was.model],[r.fallback?.harness,r.fallback?.model,was.fallback?.harness,was.fallback?.model]].filter(([h,m,wh,wm])=>m&&(h!==wh||m!==wm)).map(([,m])=>m);});
const module=key=>routesView?.providerModels?.[key]?.module;
return moved.length&&moved.every(key=>module(key)&&module(key)!=='cliproxy'&&names.includes(module(key)))?' This change needs no model proxy: press Disable model proxy catalogue, then save again.':'';
return moved.length&&moved.every(key=>module(key)&&module(key)!=='cliproxy'&&names.includes(module(key)))?' This change does not need the model service: press Stop using the model service, then save again.':'';
}
const routesAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&Array.isArray(r.harnesses)&&Array.isArray(r.models)&&[r.levels,r.instances].every(o=>o&&typeof o==='object'&&!Array.isArray(o));
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('#routes-form');if(!form||!routesView)return;routesDraft=routesFields(form);routesEditVersion++;markSettingsDraft('routing',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('routes-reload');if(discard){discard.hidden=false;discard.disabled=false;}
@@ -1388,7 +1434,7 @@
try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(epoch!==orgEpoch)return;if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.');
const names=Array.isArray(settings.plugins?.['model-provider'])?settings.plugins['model-provider']:[];
// The fresh read decides: a stale label never turns the proxy module on when it meant off.
const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=`${on?'Disable':'Enable'} model proxy catalogue`;button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;}
const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=on?'Stop using the model service':'Use your models';button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;}
const next=on?names.filter(n=>n!=='cliproxy'):[...names,'cliproxy'];
const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'});
if(epoch!==orgEpoch)return;if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true);
@@ -1432,23 +1478,38 @@
});
// Organizations is writable when the server allows org setup, which it does in organization mode where send is off.
const readonlyPage = page => !['appearance','business','console','triage'].includes(page) && !(page === 'organizations' && orgSetup) && !canSend && !isTester;
const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['triage','Triage'],['console','Console'],['about','About']];
function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`), dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);}
const settingsPages = [['appearance','Appearance'],['business',window.MosaicOrg ? 'Organization' : 'Business'],['limits','Launch limits'],['organizations','Organizations'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-setup','Model setup'],['triage','Triage'],['console','Console'],['about','About']];
function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href^="#/settings/${page}"]`), dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);}
// #1873 settings slice 4 (DESIGN.md section 2): four groups. You; Your models; All organizations;
// This organization, whose heading holds the organization picker. An organization's own pages carry
// ?org=<id> so the address base never changes with the organization. Testers keep their short list.
const ORG_SETTINGS = ['routing','agents','limits','tokens','assistant','business','names'];
function settingsShell(page, body, helper='') {
const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages.filter(([id])=>id!=='triage'||triageOwner);
const label=pages.find(([id])=>id===page)?.[1] || 'Appearance';
const org = window.MosaicOrg, orgId = org?.id ?? null, orgName = orgId ? (org.label || orgId) : null;
const scoped = id => ORG_SETTINGS.includes(id);
const href = id => `#/settings/${id}${orgId && scoped(id) ? `?org=${enc(orgId)}` : ''}`;
const labels = isTester ? Object.fromEntries([['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']]) : { appearance:'Appearance', 'model-setup':'Model setup', triage:'Triage', organizations:'Organizations', console:'Console', about:'About', routing: org ? 'Models' : 'Routing', agents:'Agents', limits:'Launch limits', tokens:'Token use', assistant:'Assistant', business: org ? 'Organization file' : 'Business' };
const label = labels[page] || 'Appearance';
const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft()))||(id==='triage'&&window.MosaicTriageRoute?.hasDraft());
const dot='<span class="settings-dot"><span class="sr-only">unsaved changes</span></span>';
const links=pages.map(([id,name],i)=>`${i===0?'<div class="settings-group">Your browser</div>':i===1?'<div class="settings-group">This instance</div>':''}<a href="#/settings/${id}"${id===page?' aria-current="page"':''}>${name}${isDirty(id)?dot:''}</a>`).join('') + (!isTester ? '<div class="settings-group">Members and invites <span class="muted">not built</span></div>' : '');
return `${head('Settings','Your browser and this instance.')}<div class="settings-layout"><div><button type="button" id="settings-disclosure" aria-expanded="false" aria-controls="settings-nav"><small>Section</small><strong>${label}${isDirty(page)?dot:''}</strong><span aria-hidden="true">⌄</span></button><nav id="settings-nav" aria-label="Settings sections">${links}</nav></div><div class="settings-content settings-${page}${readonlyPage(page)?' readonly':''}"><h2 id="settings-page-title" tabindex="-1">${label}</h2><p class="settings-helper">${helper}</p>${readonlyPage(page)?'<p class="settings-readonly">Read only. Saving requires signed-in send mode.</p>':''}${body}</div></div>`;
const a = id => `<a href="${href(id)}"${id===page?' aria-current="page"':''}>${labels[id]}${isDirty(id)?dot:''}</a>`;
const group = (title, ids) => ids.length ? `<div class="settings-group">${title}</div>${ids.map(a).join('')}` : '';
const rows = org ? org.rows() : [];
const picker = org && rows.length ? `<div class="settings-group org-pick"><label for="org-pick">This organization</label><select id="org-pick">${rows.map(r => `<option value="${txt(r.id)}"${r.id === orgId ? ' selected' : ''}>${txt(r.label)}</option>`).join('')}</select></div>` : `<div class="settings-group">${org ? 'This organization' : 'This business'}</div>`;
const links = isTester ? group('Settings', ['appearance','business','routing','agents','names'])
: group('You', ['appearance']) + group('Your models', ['model-setup', ...(triageOwner ? ['triage'] : [])]) + group(org ? 'All organizations' : 'This instance', ['organizations','console','about'])
+ picker + ['routing','agents','limits','tokens','assistant','business'].map(a).join('');
const where = orgName && scoped(page) ? `${txt(orgName)} · ` : '';
const title = org && page === 'routing' && orgName ? `${txt(orgName)}'s models` : label;
return `${head('Settings','Your models, your organizations and this browser.')}<div class="settings-layout"><div><button type="button" id="settings-disclosure" aria-expanded="false" aria-controls="settings-nav"><small>Section</small><strong>${where}${label}${isDirty(page)?dot:''}</strong><span aria-hidden="true">⌄</span></button><nav id="settings-nav" aria-label="Settings sections">${links}</nav></div><div class="settings-content settings-${page}${readonlyPage(page)?' readonly':''}"><h2 id="settings-page-title" tabindex="-1">${title}</h2><p class="settings-helper">${helper}</p>${readonlyPage(page)?'<p class="settings-readonly">Read only. Saving requires signed-in send mode.</p>':''}${body}</div></div>`;
}
async function settingsView(get, page='appearance') {
if (page==='business') return businessView(get);
if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.');
if (page==='organizations') { await configRead; return settingsShell(page,window.MosaicOrgCreate.markup,'Create an organization from the template, edit it, and finish its setup. Each step names the command it equals.'); }
if (page==='model-proxy') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Accounts used by this instance, their priority, and the client keys assigned to agents.'); }
if (page==='model-setup') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Your model service, your accounts and the models they offer. Every organization uses them, including organizations you add later, unless it sets up its own.'); }
// #1873 triage-settings: Settings > Triage (triage-settings.js), the instance owner's only; anyone else gets no page.
if (page==='triage') { await configRead; if (!triageOwner || !window.MosaicTriageRoute) return notFound(); return settingsShell(page,await window.MosaicTriageRoute.section(),'The model, harness and daily token cap Triage uses. Only the instance owner sees this page.'); }
if (page==='triage') { await configRead; if (!triageOwner || !window.MosaicTriageRoute) return notFound(); return settingsShell(page,await window.MosaicTriageRoute.section(),'The model Triage uses, what runs it, and its daily token limit. Only the instance owner sees this page.'); }
// F3: Settings > Console (console-restart.js). The server checks the owner, Origin and trail.
if (page==='console') { await configRead; await window.MosaicConsole?.ready; return settingsShell(page,window.MosaicConsole?.settingsMarkup()??'<section class="panel"><p class="small warn">The Console controls did not load. Reload the page to try again.</p></section>','Restart this Console on the same address and configuration.'); }
const s = await get.api('settings'), n = s.notifier || {};
@@ -1459,15 +1520,26 @@
// #1873 A2: the root and project agent levels (agents.js MosaicAgentLevels), the owner's only.
let agentLevels='';
if (page==='agents' && window.MosaicOrg && window.MosaicAgentLevels && !isTester) agentLevels = await window.MosaicAgentLevels.section().catch(()=>'');
if (page==='routing') { try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } }
if (page==='routing') { await window.MosaicConsole?.ready; try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } }
if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch);
const notify = typeof n.binding==='string' ? `<code>${txt(n.binding)}</code>` : n.refused ? `Could not be read: <code>${txt(n.refused)}</code>` : '<span class="muted">None set</span>';
const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`<section class="panel"><dl class="kv"><dt>Address</dt><dd><code>${txt(s.address)||'unknown'}</code></dd><dt>Release</dt><dd>${txt(s.release)||'unknown'}</dd><dt>Business</dt><dd>${txt(s.business)||none}</dd><dt>Board</dt><dd><code>${txt(s.board)||'unknown'}</code></dd><dt>Notifier binding</dt><dd>${notify}</dd></dl></section>`, 'model-proxy':()=>'<section class="panel"><a href="#/settings/model-proxy">Open model proxy settings</a></section>'};
const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'};
const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`<section class="panel"><dl class="kv"><dt>Address</dt><dd><code>${txt(s.address)||'unknown'}</code></dd><dt>Release</dt><dd>${txt(s.release)||'unknown'}</dd><dt>Business</dt><dd>${txt(s.business)||none}</dd><dt>Board</dt><dd><code>${txt(s.board)||'unknown'}</code></dd><dt>Notifier binding</dt><dd>${notify}</dd></dl></section>`};
const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change. A harness is the program that runs the model. Preflight is the check a launch makes before it starts.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'};
return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`);
}
let settingsFocusDisclosure=false;
document.addEventListener('change', e => { if (e.target.id === 'org-picker') window.MosaicOrg?.switchTo(e.target.value); });
document.addEventListener('change', e => { if (e.target.id === 'org-picker') window.MosaicOrg?.switchTo(e.target.value); else if (e.target.id === 'org-pick') pickSettingsOrg(e.target.value); });
// Slice 4: the picker re-reads the page in place. An organization's page keeps its page with the new
// ?org=.
function pickSettingsOrg(id) {
const org = window.MosaicOrg; if (!org || !id) return;
const [path, query = ''] = routeOf().split('?'), page = path.split('/')[2] || 'appearance';
const rest = query.split('&').filter(p => p && !p.startsWith('org='));
// settings-s4 review F1: from a page that is not an organization's (Model setup, Appearance,
// Organizations) the picker opens that organization's first page, Routing, and keeps the
// single-pane address base; it never builds an #/orgs/<id>/ address.
location.hash = ORG_SETTINGS.includes(page) ? `#/settings/${page}?${[`org=${enc(id)}`, ...rest].join('&')}` : `#/settings/routing?org=${enc(id)}`;
}
document.addEventListener('click', e=>{const b=e.target.closest?.('#settings-disclosure');if(b){b.setAttribute('aria-expanded',String(b.getAttribute('aria-expanded')!=='true'));return;} if(e.target.closest?.('#settings-nav a')) { const b=$('settings-disclosure'); if(b?.getAttribute('aria-expanded')==='true') {b.setAttribute('aria-expanded','false');settingsFocusDisclosure=true;b.focus();} }});
document.addEventListener('keydown', e=>{if(e.key==='Escape' && $('settings-disclosure')?.getAttribute('aria-expanded')==='true'){e.preventDefault();$('settings-disclosure').setAttribute('aria-expanded','false');$('settings-disclosure').focus();}});
@@ -1674,7 +1746,29 @@
const refusal = err => err.status === 403 || ['not-configured', 'no-bus-host', 'queue-refused'].includes(err.code);
// After a refusal nothing read before is shown anywhere: not in a view, the palette or the Inbox count.
function forget() { window.MosaicChat?.forget(); last.clear(); inboxCount = null; messageCount = null; }
const failedView = (err, path) => `${head(path === '/queue' ? 'Queue' : failTitle(err))}<div class="banner ${refusal(err) ? 'ref' : 'err'}" role="alert"><p>${refusal(err) ? `<b>refused: <code>${txt(err.code)}</code>.</b> ` : ''}${why(err, err.code === 'queue-refused')} Console shows nothing rather than a guess. Nothing was written.</p>${retry}</div>${empty('Nothing to show.', refusal(err) ? 'The view stays empty until the problem above is fixed.' : err.module ? 'Read again.' : 'Read again, or come back when the bus answers.')}`;
// One shipped copy of the line every failed read ends with (failedView and settingsFailed).
const NO_GUESS = 'Console shows nothing rather than a guess. Nothing was written.';
const failedView = (err, path) => `${head(path === '/queue' ? 'Queue' : failTitle(err))}<div class="banner ${refusal(err) ? 'ref' : 'err'}" role="alert"><p>${refusal(err) ? `<b>refused: <code>${txt(err.code)}</code>.</b> ` : ''}${why(err, err.code === 'queue-refused')} ${NO_GUESS}</p>${retry}</div>${empty('Nothing to show.', refusal(err) ? 'The view stays empty until the problem above is fixed.' : err.module ? 'Read again.' : 'Read again, or come back when the bus answers.')}`;
// #1873 settings slice 1 (D7): an organization page under Settings that cannot be read keeps the
// Settings nav, so the instance pages (Appearance, Model setup, Triage, Console) stay one link
// away. When the organization's bus is down the page says so in plain words and offers Restart,
// whose refusal stays on screen (console-restart.js keeps it per organization); the header's own
// "Bus unavailable" banner steps aside on this page so there is one Restart, not two.
function settingsFailed(err, path) {
const page = path.split('/')[2] || 'appearance', id = window.MosaicOrg?.id, row = id ? window.MosaicOrg.row?.(id) : null;
const org = txt(window.MosaicOrg?.label || id || ''), name = settingsPages.find(([p]) => p === page)?.[1] || 'this page';
if (id && row?.busHealthy === false && !refusal(err)) {
const state = row.busStopped ? `${org} is stopped` : `${org} isn't running`;
// Why it is down, from the read the dashboard row uses (MosaicConsole.orgDownReason). Only a
// refused start is a reason it stopped; anything else is what the last check saw (P3-9).
const label = window.MosaicOrg.label || id, whyText = v => !v ? '' : v.plain && v.plain !== `${label} did not start.` ? txt(v.plain) : `${v.refused === false ? 'Last check' : 'Why it stopped'}: ${txt(v.detail)}`;
const why = window.MosaicConsole?.orgDownReason?.(id, label, v => { const p = document.querySelector(`[data-org-down="${CSS.escape(id)}"] [data-org-down-why]`); if (p) { p.innerHTML = whyText(v); p.hidden = !p.innerHTML; } }) ?? null;
// settings-p3 (re-check 3 P3-4): after a refusal a restart can't clear, Restart is not the primary.
const restart = window.MosaicConsole?.orgRestartButton?.(id, { name: label, primary: !(window.MosaicConsole?.orgRefusal?.(id)?.restart === false || why?.restart === false) }) || '';
return settingsShell(page, `<section class="panel org-down" data-org-down="${txt(id)}"><div class="banner err" role="alert"><p><b>${state}, so ${txt(name)} can't be read.</b> Start it again to see and change this page. Nothing was written.</p><p data-org-down-why${why ? '' : ' hidden'}>${whyText(why)}</p>${restart ? `<p>${restart}</p>` : '<p class="small">Ask the instance owner to restart it.</p>'}</div><p class="small">This instance's own pages still work: <a href="#/settings/appearance">Appearance</a>, <a href="#/settings/model-setup">Model setup</a>${triageOwner ? ', <a href="#/settings/triage">Triage</a>' : ''} and <a href="#/settings/console">Console</a>.</p></section>`);
}
return settingsShell(page, `<div class="banner ${refusal(err) ? 'ref' : 'err'}" role="alert"><p><b>${txt(failTitle(err))}.</b> ${refusal(err) ? `<code>${txt(err.code)}</code>. ` : ''}${why(err, err.code === 'queue-refused')} ${NO_GUESS}</p>${retry}</div>`);
}
const staleBanner = err => `<div class="banner err s1-stale" role="alert"><p><b>The last read failed.</b> ${why(err)} This is what was read before, ${when(readAt)}. Nothing was changed.</p>${retry}</div>`;
// Freshness line in the command bar for bus pages.
const stamp = iso => { const t = Date.parse(iso); return Number.isFinite(t) ? `${new Date(t).toISOString().slice(11, 19)} UTC` : 'unknown'; };
@@ -1813,7 +1907,7 @@
// On the cross-organization pages a filter or selection changes only the query: that is a
// repaint of the same page, not a navigation (no loading view, focus and scroll kept).
const samePage = drawerPage(path) && typeof shown === 'string' && shown.split('?')[0] === path;
if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;}
if (path !== '/settings/model-setup' && proxyCleanup) {proxyCleanup();proxyCleanup=null;}
if ((navigated || path !== '/settings/organizations') && orgCleanup) {orgCleanup();orgCleanup=null;}
// Leaving a decision discards its confirmation immediately, including a preview in flight.
if (answer && (navigated || path !== (answer.org ? '/inbox' : `/inbox/${answer.id}`))) answer = null;
@@ -1829,6 +1923,8 @@
window.MosaicChat?.leave(chatPath);
if (path === '/business') { location.replace('#/settings/business'); return; }
if (path === '/settings/display') { location.replace('#/settings/appearance'); return; }
// #1873 settings slice 4: the owner's page is Model setup; its old address lands there, query kept.
if (path === '/settings/model-proxy') { location.replace(`#/settings/model-setup${query ? `?${query}` : ''}`); return; }
// #1873 SP6: the Assistant page draws its own thread panes (assistant.js); every other page
// stops their polling. It is a system page: an organization's address for it, and the old
// Side by side address, land on `#/assistant`.
@@ -1911,7 +2007,7 @@
sections(path); schedule();
return;
}
if (path === '/settings/model-proxy' && shown === route && !navigated) return;
if (path === '/settings/model-setup' && shown === route && !navigated) return;
if (path === '/settings/triage' && shown === route && !navigated) return;
if (path === '/settings/organizations' && shown?.split('?')[0] === path && !navigated) return;
if (($('agent-dialog')?.open || document.querySelector('.agent-more[aria-expanded=true]')) && !navigated) { schedule(); return; }
@@ -1919,7 +2015,7 @@
let html, state = 'fresh';
const live = reader(true);
try {
if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/triage','/settings/organizations'].includes(path)) {
if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-setup','/settings/triage','/settings/organizations'].includes(path)) {
try { await live('messages'); }
catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; }
}
@@ -1928,7 +2024,7 @@
if (err.code === 'signed-out') return;
const kept = reader(false);
try { if (refusal(err)) throw err; html = await view(kept, path, new URLSearchParams(query), opts, current); readAt = kept.oldest(); html = staleBanner(err) + html; state = 'stale'; }
catch { html = failedView(err, path) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; }
catch { if (window.MosaicOrg && path.startsWith('/settings/')) { await window.MosaicConsole?.ready; html = settingsFailed(err, path); } else html = failedView(err, path) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; }
if (refusal(err)) forget();
}
if (!current()) return;
@@ -1944,7 +2040,8 @@
syncAppearance(true);
if (path.startsWith('/docs/')) paintDoc();
if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]'));
if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount();
if ($('bus-view').querySelector('[data-org-down]')) { const down = $('bus-down'); if (down) down.hidden = true; }
if (path === '/settings/model-setup') { proxyCleanup?.(); proxyCleanup=window.MosaicProxy.mount(); }
if (path === '/settings/organizations') orgCleanup=window.MosaicOrgCreate.mount();
sections(path);
const h1 = $('bus-view').querySelector('h1');
@@ -2164,6 +2261,7 @@
instanceView = null; instanceDrafts = { add: null, change: null }; instanceReceipt = ''; instanceReceiptOp = null; instanceReceipts = Object.create(null);
routesView = null; routesDraft = null; routesReceipt = ''; routesEditVersion++;
harnessSettings = null; harnessDraft = null; harnessReceipt = '';
serviceState = null; serviceLoading = false;
// A file draft is keyed by project and path only; the page reload that used to drop it is gone.
docKey = null; docStates.clear(); pkAll = []; pkShown = []; pkAt = 0;
configRead = switchRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => applyConfig(c, { quiet: true })).catch(() => {});
+6 -1
View File
@@ -186,7 +186,12 @@
return `<ul class="chat-cites">${list.map(c => `<li>${c.badge ? `<span class="chat-scope chat-scope-${c.badge}">${txt(c.badge)}</span> ` : ''}${c.link ? `<a href="${esc(c.link)}" rel="noopener noreferrer" target="_blank">${txt(c.ref)}</a>` : `<code>${txt(c.ref)}</code>`} <q>${txt(c.quote)}</q>${c.agent ? ` <span class="chat-label chat-agent-written">agent-written: ${txt(c.agent)}</span>` : ''}${c.changed ? ' <span class="chat-label chat-changed">changed since</span>' : ''}</li>`).join('')}</ul>`;
}
function messageBody(m) {
if (m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ')) return `<div class="chat-body">The assistant couldn't reply. Try again, or check Agents.<div class="small">Details: ${txt(m.body.slice('The turn failed: '.length))}</div></div>`;
if (m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ')) {
// #1873 chat-fail: "The turn failed: <plain cause and next step>\nDetails: <technical reason>".
const rest = m.body.slice('The turn failed: '.length), at = rest.indexOf('\nDetails: ');
if (at > 0) return `<div class="chat-body">The assistant couldn't reply: ${txt(rest.slice(0, at))}<div class="small">Details: ${txt(rest.slice(at + '\nDetails: '.length))}</div></div>`;
return `<div class="chat-body">The assistant couldn't reply. Try again, or check Agents.<div class="small">Details: ${txt(rest)}</div></div>`;
}
const r = renderReply?.(m.body, { check: m.check ?? null, name: m.from_role, changed: changedBy(m.check) });
if (r?.kind === 'reply') return `<div class="chat-body">${prose(r.text)}</div>${r.citations.length ? cites(r.citations) : ''}`;
if (r?.kind === 'notice') {
+115 -1
View File
@@ -175,6 +175,8 @@
}
} catch (error) {
busReceipt = error instanceof SyntaxError || error?.name === 'TypeError' ? 'Outcome unknown. Check the bus with mosaic bus status before retrying.' : error.message;
// #1873 D7: the refusal follows the organization onto its Settings pages.
if (!(error instanceof SyntaxError || error?.name === 'TypeError')) orgReceipts.set(id, { ok: false, ...refusalLine(window.MosaicOrg?.label || id, error.message) });
} finally { busBusy = false; paintBus(); }
});
@@ -196,5 +198,117 @@
} finally { busBusy = false; paintBus(); }
}
window.MosaicConsole = Object.freeze({ ready, settingsMarkup, busButton, attachBus, get busRestart() { return busAllowed(); }, get config() { return config; } });
// #1873 settings slice 1 (D2, D3, D7): a Restart button for one named organization, for pages that
// list organizations by id (Routing, Model setup, a stopped organization's Settings). Each
// organization keeps its own receipt, so a refusal stays on screen across repaints until the next
// press. It calls the same POST /api/orgs/<id>/restart/bus as the header's Restart bus.
const orgReceipts = new Map(), orgBusy = new Set();
const orgAllowed = () => config?.orgSetup === true && config?.tester !== true && config?.user !== true;
// The refusal the bus host wrote, with one plain line in front when its code is known.
function refusalLine(name, message) {
const text = String(message || 'The restart was refused. Nothing was retried.');
// settings-p3 (re-check 3 P3-4): a restart is refused the same way again, so `restart: false`
// tells the page not to keep Restart as its primary action.
if (/\bfixture-proxy-configured\b/.test(text)) return { plain: `${name} runs on test models, which can't share this machine with your model service. It did not start.`, detail: text, restart: false };
return { plain: `${name} did not start.`, detail: text };
}
// #1873 review P1-1, P2-2: the cause a running bus gives for a catalogue it cannot read
// (runtime.mjs pickProxy), as one plain line. `restart` says whether a restart can fix it: the
// lock and the organization binding load again at a fresh start; with the dev fixture or a key
// or settings file that does not load, the start is refused too or reads the same file. `fix`
// names the page that fixes it. The bus's own words stay in `detail`; an unknown cause has no
// plain line, so the page shows the bus's words.
function catalogueCause(name, notices, reason) {
// Two different models that slug to one key: the catalogue names it in `reason`, with no notice.
if (reason === 'model-key-collision') return { code: reason, plain: `Two of your models get the same short name, so ${name} can't tell them apart. A restart won't change that. Take one of them out of an API key's Models list on Model setup. If both come from signed-in accounts, this can't be changed from Console yet.`, restart: false, fix: 'service', detail: reason };
const list = (Array.isArray(notices) ? notices : []).filter(n => typeof n === 'string' && n);
if (!list.length) return null;
const detail = list.join(' '), code = /\(([a-z][a-z-]*)\)/.exec(detail)?.[1] ?? (/has not been set up/.test(detail) ? 'proxy-not-set-up' : null);
const known = {
// No existing endpoint removes the fixture provider, so the line names no step to take here.
'fixture-proxy-configured': [`${name} runs on test models, which can't share this machine with your model service. This can't be changed from Console yet.`, false, null],
'proxy-lock-invalid': [`${name} can't open the model service's shared lock. A restart opens it again.`, true, null],
'invalid-host-request': [`${name} isn't linked to this instance's model service. A restart links it again.`, true, null],
'proxy-management-key-invalid': [`${name} can't load the model service's key, so it can't reach the model service.`, false, 'service'],
'proxy-down': [`${name} couldn't check the model service just now. Check again in a moment.`, false, null],
'proxy-not-set-up': ['Your model service isn\'t set up yet.', false, 'service'],
}[code] ?? (/^proxy-/.test(code ?? '') ? [`${name} can't load the model service's settings.`, false, 'service'] : null);
return known ? { code, plain: known[0], restart: known[1], fix: known[2], detail } : { code, plain: null, restart: false, fix: null, detail };
}
function orgRestartButton(id, { name = id, label = `Restart ${name}`, primary = false } = {}) {
if (!orgAllowed() || typeof id !== 'string' || !id) return '';
const busy = orgBusy.has(id), r = orgReceipts.get(id);
const receipt = !r ? '' : r.ok ? esc(r.text) : `<strong>${esc(r.plain)}</strong> <span class="small muted" data-org-restart-detail>${esc(r.detail)}</span>`;
return `<span class="org-restart" data-org-restart-box="${esc(id)}"><button type="button" class="btn${primary ? ' primary' : ''}" data-org-restart="${esc(id)}" data-org-name="${esc(name)}" data-label="${esc(label)}"${primary ? ' data-primary' : ''}${busy ? ' disabled' : ''}>${esc(busy ? 'Restarting…' : label)}</button> <span role="status" data-org-restart-receipt class="${r && !r.ok ? 'org-restart-refused' : ''}">${receipt}</span></span>`;
}
const paintOrg = id => document.querySelectorAll(`[data-org-restart-box="${CSS.escape(id)}"]`).forEach(el => {
const b = el.querySelector('[data-org-restart]'), r = orgReceipts.get(id);
el.outerHTML = orgRestartButton(id, { name: b?.dataset.orgName || id, label: b?.dataset.label, primary: b?.hasAttribute('data-primary') && r?.restart !== false });
});
async function restartOrg(id, name) {
if (orgBusy.has(id) || !orgAllowed()) return null;
orgBusy.add(id); orgReceipts.delete(id); paintOrg(id);
let result;
try {
const response = await nativeFetch(`/api/orgs/${encodeURIComponent(id)}/restart/bus`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}', cache: 'no-store', redirect: 'manual' });
if (response.type === 'opaqueredirect') throw new Error('Sign in again, then retry.');
const body = await response.json();
if (!response.ok || body.outcome !== 'done' || body.step !== 'bus-restart') throw new Error(body.message || 'The restart was refused. Nothing was retried.');
result = { ok: true, healthy: body.healthy === true, text: `${name} ${body.restarted ? 'restarted' : 'started'} at ${clock()}. ${body.healthy ? 'It answers.' : `It has not answered yet. Check it with mosaic bus status ${id}.`}` };
} catch (error) {
result = error instanceof SyntaxError || error?.name === 'TypeError'
? { ok: false, plain: 'Outcome unknown.', detail: `Check it with mosaic bus status ${id} before you press Restart again.` }
: { ok: false, ...refusalLine(name, error.message) };
}
orgBusy.delete(id); orgReceipts.set(id, result); paintOrg(id);
if (id === window.MosaicOrg?.id) { busReceipt = result.ok ? result.text : `${result.plain} ${result.detail}`; paintBus(); }
await Promise.resolve(window.MosaicOrg?.refreshList?.()).catch(() => {});
document.dispatchEvent(new CustomEvent('mosaic-org-restarted', { detail: { id, ok: result.ok, healthy: result.healthy === true } }));
return result;
}
document.addEventListener('click', e => {
const button = e.target.closest?.('[data-org-restart]');
if (!button || button.disabled) return;
restartOrg(button.dataset.orgRestart, button.dataset.orgName || button.dataset.orgRestart);
});
// #1873 review 2 P2-D: why a stopped organization is down. GET /api/workspace carries each
// organization's state and, for a refused start, "the bus refused to start: <message>"
// (workspace-read.mjs). It is the reason the dashboard row shows. One read per organization at a
// time, kept for 15 seconds; until it lands this returns what was read before, or null. A reason
// that only restates "not running" is not a reason.
// settings-p3 (re-check 3 P3-9): only a refused start is a stop reason (`refused: true`); any other
// reason (a slow or failed read, a host that does not answer yet) is what the last check saw.
// P3-11: the raw reason is kept and each caller's line is built with its own name when used, and
// every caller that asked while the read was pending is told when it lands.
const downReasons = new Map();
const downLine = (raw, name) => !raw ? null : raw.refused ? { ...refusalLine(name, raw.text), refused: true } : { plain: null, detail: raw.text, refused: false };
function orgDownReason(id, name = id, onRead = null) {
if (typeof id !== 'string' || !id) return null;
const got = downReasons.get(id);
if (got && (got.pending || Date.now() - got.at < 15000)) {
if (got.pending && typeof onRead === 'function') got.waiters.push([name, onRead]);
return downLine(got.raw, name);
}
const entry = { at: got?.at ?? 0, raw: got?.raw ?? null, pending: true, waiters: typeof onRead === 'function' ? [[name, onRead]] : [] };
downReasons.set(id, entry);
nativeFetch(`/api/workspace?${new URLSearchParams({ org: id, sections: 'tasks' })}`, { cache: 'no-store', redirect: 'manual' })
.then(r => (r.ok ? r.json() : null))
.then(body => {
const row = (Array.isArray(body?.orgs) ? body.orgs : []).find(o => o?.org === id);
const reason = row && row.state !== 'ok' && typeof row.reason === 'string' ? row.reason.trim() : '';
if (!reason || /^the bus is not (running|answering)\.?$/i.test(reason)) return null;
const refused = /^the bus refused to start: ([\s\S]+)$/.exec(reason);
return refused ? { refused: true, text: refused[1] } : { refused: false, text: reason };
})
.catch(() => null)
.then(raw => {
downReasons.set(id, { at: Date.now(), raw, pending: false, waiters: [] });
for (const [who, callback] of entry.waiters) { try { callback(downLine(raw, who)); } catch { /* one caller's repaint does not stop the others */ } }
});
return downLine(got?.raw ?? null, name);
}
// The notice the bus adds to a ready catalogue it picked up after it started (bus runtime.mjs RESTART_TO_LAUNCH).
const RESTART_TO_LAUNCH = 'Restart this organization to start agents on these models.';
window.MosaicConsole = Object.freeze({ RESTART_TO_LAUNCH, ready, settingsMarkup, busButton, attachBus, orgRestartButton, restartOrg, catalogueCause, orgDownReason, orgRefusal: id => orgReceipts.get(id) ?? null, get busRestart() { return busAllowed(); }, get config() { return config; } });
})();
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -14,7 +14,7 @@
const value = await response.json();
if (!response.ok) {
if (response.status === 401) throw new Error('Sign in to the Console again.');
if (value.error === 'not-configured') throw new Error(typeof value.reason === 'string' && value.reason ? value.reason : 'The model proxy is not configured for this instance.');
if (value.error === 'not-configured') throw new Error(typeof value.reason === 'string' && value.reason ? value.reason : 'The model service is not set up on this instance.');
if (value.error === 'login-state-unknown') throw new Error('This sign-in has ended. Start a new sign-in.');
if (value.error === 'apikey-invalid') throw new Error('Enter a nonempty API key, with no spaces or line breaks.');
throw new Error('The operation could not be confirmed. Nothing was retried. Refresh before trying again.');
+73 -4
View File
@@ -98,6 +98,17 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap}
.console-reconnect>span{flex:1 1 220px;min-width:0;overflow-wrap:anywhere}
.bus-restart{display:inline-flex;flex-wrap:wrap;gap:6px 10px;align-items:center;min-width:0}
.bus-restart [role=status]:empty{display:none}
/* #1873 settings slice 1: a Restart for one named organization (console-restart.js orgRestartButton). */
.org-restart{display:inline-flex;flex-wrap:wrap;gap:6px 10px;align-items:center;min-width:0;max-width:100%}
.org-restart [data-org-restart]{min-height:var(--action-target);white-space:normal;text-align:left}
.org-restart [role=status]{min-width:0;overflow-wrap:anywhere}
.org-restart [role=status]:empty{display:none}
.org-restart .org-restart-refused strong,.org-restart-refused strong{color:var(--strong)}
.org-restart [data-org-restart-detail]{display:block}
.routes-catalogue{flex-direction:column;align-items:stretch}
.routes-catalogue>p{flex:none}
.settings-content .org-down .banner p{margin:0 0 8px;flex-basis:100%}
.settings-content .org-down .banner p:last-child{margin-bottom:0}
.routes-apply{margin:12px 0 0;padding-left:18px;display:grid;gap:8px}
.routes-apply li{overflow-wrap:anywhere}
.agent-restart{display:inline-flex;flex-wrap:wrap;gap:6px 10px;align-items:center;min-width:0}
@@ -109,6 +120,22 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap}
.proxy-setup-buttons{display:flex;flex-wrap:wrap;gap:8px}.proxy-setup-buttons button{min-height:44px}
#proxy-setup pre{overflow-x:auto;max-width:100%;font-size:12px}#proxy-setup h3{margin:16px 0 4px}#proxy-setup details{margin:0 0 12px}#proxy-setup summary{min-height:44px;display:flex;align-items:center;cursor:pointer}
#proxy-setup-receipts{padding-left:20px;overflow-wrap:anywhere;font-size:13px}
/* #1873 settings slice 1 (D3, D4): the kept restart list and Technical details. */
.proxy-setup-restart{margin:0 0 12px}
.proxy-setup-restart-list{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:8px}
.proxy-setup-restart-list li{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px;padding:10px 12px;border:1px solid var(--line);border-radius:var(--r);min-width:0}
.proxy-setup-restart-list li>.small{flex:1 1 220px;min-width:0;overflow-wrap:anywhere}
.proxy-setup-restart-name{display:inline-flex;flex-wrap:wrap;align-items:center;gap:6px;min-width:0}
.proxy-setup-restart-list li>details{flex:1 1 100%;min-width:0;overflow-wrap:anywhere}
.routes-cause-detail,.proxy-setup-cause{margin:6px 0 0}
.routes-cause-detail summary,.proxy-setup-cause summary{cursor:pointer}
.settings-content button[type=submit].route-save-quiet{background:var(--surface);color:var(--text);border-color:var(--border)}
.proxy-setup-tech>summary{font-weight:600}
#triage-route-harness-help{display:block;margin-top:4px;max-width:36ch}
#triage-route select{max-width:100%}
.triage-state-fix{margin:0 0 8px}.triage-fix{white-space:normal}
/* #1873 settings slice 1: at phone width a model select takes the whole row, so a long model name is not cut. */
@media(max-width:759px){.routing-panel #routes-table td:nth-of-type(2),.routing-panel #routes-table td:nth-of-type(5){grid-column:1/-1}.routing-panel #routes-table select{width:100%;max-width:100%}}
@media(max-width:479px){.proxy-setup-state{grid-template-columns:1fr}.proxy-setup-state dd{margin-bottom:6px}}
/* Stream S4: which organization this is, in words. Colour (the theme) is never the only cue; the strip appears whenever the theme is not the built-in one. */
.org-cue{margin:0 0 12px;padding:6px 10px;border:1px solid var(--line);border-left:4px solid var(--action);border-radius:var(--r-table);background:var(--raised);color:var(--text);font-size:13px;overflow-wrap:anywhere}.skel-rows{display:grid;gap:10px;padding:14px 12px;border:1px solid var(--line);border-radius:var(--r-table);background:var(--surface)}
@@ -264,7 +291,10 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
.settings-content input:disabled,.settings-content select:disabled,.settings-content textarea:disabled{background:var(--raised);border-color:var(--line);color:var(--muted)}
.settings-content button,.settings-content summary{min-height:44px;min-width:44px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);padding:8px 18px;font:inherit;cursor:pointer}
.settings-content button[type=submit]{background:var(--accent-fill);color:var(--on-accent);border-color:var(--accent-fill)}
.settings-content :is(button,input,select,textarea,a,summary):focus-visible,#settings-nav a:focus-visible,#settings-disclosure:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
/* #1873 settings slice 4: Model setup has at most one primary button, which display.js marks .primary; its other submits read as plain buttons. */
.settings-content .model-setup button[type=submit]:not(.primary){background:var(--surface);color:var(--text);border-color:var(--border)}
#proxy-signin .form-foot{display:flex;flex-wrap:wrap;align-items:center;gap:var(--gap,12px)}
.settings-content :is(button,input,select,textarea,a,summary):focus-visible,#settings-nav a:focus-visible,#settings-nav select:focus-visible,#settings-disclosure:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
.settings-segments{display:inline-flex;max-width:100%;border:1px solid var(--border);border-radius:var(--r);overflow:hidden}
.settings-segments label{position:relative;display:block}
.settings-segments input,.palette-tile input{position:absolute;opacity:0;width:1px;height:1px}
@@ -282,6 +312,45 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
.palette-swatches{display:flex;gap:6px}.palette-swatches i{display:block;width:16px;height:16px;border-radius:50%;background:var(--swatch-canvas);border:1px solid var(--line)}.palette-swatches i:nth-child(2){background:var(--swatch-action);border:0}.palette-swatches i:nth-child(3){background:var(--swatch-accent);border:0}
.settings-browser-status{color:var(--success)!important;margin:0!important}.settings-browser-status:not(:empty){margin-top:10px!important}.settings-browser-status.warning{color:var(--warning)!important}
.settings-readonly{padding:12px 16px;background:var(--raised);border-radius:var(--r)}
/* #1873 settings slice 4: the organization picker in the nav, and Model setup's step cards. */
#settings-nav .org-pick{display:flex;flex-direction:column;gap:6px}
#settings-nav .org-pick label{font:inherit;color:inherit}
#settings-nav .org-pick select{min-height:44px;max-width:100%;font:inherit;font-size:14px;color:var(--text);background:var(--surface);border:1px solid var(--border);border-radius:var(--r);padding:0 10px}
.settings-content .panel.setup-step{display:block;margin:0 0 var(--gap,12px)}
.setup-step>header{display:flex;align-items:center;gap:var(--gap,12px)}
.setup-step>header h3{flex:1;margin:0}
.step-n{flex:none;display:inline-grid;place-items:center;width:28px;height:28px;border-radius:50%;border:1px solid var(--border);font-weight:700;color:var(--muted)}
.setup-step.done .step-n{border-color:var(--success);color:var(--success)}
.setup-step.next .step-n{border-color:var(--action);color:var(--action)}
.setup-step.blocked .step-n{border-color:var(--danger);color:var(--danger)}
.setup-step .summary{margin:6px 0 0 40px}
.setup-step .body{margin:var(--gap,12px) 0 0 40px;min-width:0}
.setup-step.waiting{color:var(--muted)}
.setup-step.waiting h3{color:var(--muted)}
.settings-form{display:grid;gap:var(--pad,16px);max-width:28rem;margin:0}
.settings-form .field{display:flex;flex-direction:column;gap:6px;margin:0;min-width:0}
.settings-form .field>label,.settings-form legend,.settings-form .lbl{font-weight:600;color:var(--strong)}
.settings-form .field :is(input,select){width:100%}
.settings-form .w-num{max-width:12rem}
.settings-form .help{margin:0}
.settings-form .form-foot{display:flex;align-items:center;gap:var(--gap,12px);flex-wrap:wrap}
.settings-form fieldset{border:0;margin:0;padding:0;display:grid;gap:8px;min-width:0}
.rows{margin:var(--gap,12px) 0 0;padding:0;list-style:none}
.rows li{display:grid;grid-template-columns:7rem minmax(0,1fr) auto;gap:6px var(--gap,12px);align-items:center;padding:10px 0;border-top:1px solid var(--line)}
.rows li>span:first-child{font-weight:600;color:var(--strong)}
.rows li>.account-reason{grid-column:2/-1;margin:0}
.progress{list-style:none;margin:var(--gap,12px) 0 0;padding:0;display:grid;gap:6px}
.progress li::before{display:inline-block;width:1.4em;color:var(--muted)}
.progress .ok::before{content:"✓";color:var(--success)}.progress .run::before{content:"●";color:var(--action)}.progress .todo::before{content:"○"}.progress .bad::before{content:"✕";color:var(--danger)}
.mk-note{border-left:3px solid var(--warning);padding-left:10px}
.model-list{display:grid;gap:0;margin:0;padding:0;list-style:none}
.model-list li{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:center;min-height:44px;padding:4px 0;border-top:1px solid var(--line)}
.model-list li .small{margin-left:auto}
.setup-log{font:13px/1.5 var(--mono,monospace);white-space:pre-wrap;overflow-wrap:anywhere;margin:var(--gap,12px) 0 0;padding:10px;border:1px solid var(--line);border-radius:var(--r);background:var(--raised)}
.err-line{color:var(--danger)}
.settings-content details{margin-top:var(--gap,12px)}
.settings-content details>.inside{margin-top:var(--gap,12px)}
@media(max-width:759px){.rows li{grid-template-columns:1fr}.rows li>.badge{justify-self:start}.rows li>.account-reason{grid-column:auto}.setup-step .summary,.setup-step .body{margin-left:0}.settings-form{max-width:none}.settings-form .w-num{max-width:none}}
@media(max-width:959px) and (min-width:760px){.settings-layout{grid-template-columns:180px minmax(0,1fr);gap:24px}}
@media(max-width:759px){.settings-layout{display:block}.settings-layout>div:first-child{margin-bottom:20px}#settings-disclosure{width:100%;min-height:44px;display:flex;align-items:center;gap:12px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);text-align:left}#settings-disclosure small{color:var(--muted)}#settings-disclosure span{margin-left:auto}#settings-disclosure[aria-expanded=false]+#settings-nav{display:none}#settings-nav{padding:12px 0}.settings-content>h2{font-size:21px}.palette-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.palette-content{min-height:64px;padding:7px}.palette-tile input:checked+.palette-content{padding:6px}.settings-segments{display:flex;width:100%}.settings-segments label{flex:1;min-width:0}.settings-segments span,.settings-appearance .panel:last-child .settings-segments span{min-width:0;padding:0 4px}.settings-content .table-wrap{max-width:100%}}
.settings-content [aria-invalid=true]{border:2px solid var(--danger)!important}
@@ -329,7 +398,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
.settings-segments:has(input:focus-visible){outline:2px solid var(--focus);outline-offset:2px}
.settings-segments input:focus-visible+span{outline:none}
#proxy-authorize:not([hidden]){display:inline-flex;align-items:center;min-height:44px}
.settings-content #proxy-accounts .proxy-priority-save{background:var(--surface);color:var(--text);border-color:var(--border)}
.settings-content #proxy-order .proxy-priority-save{background:var(--surface);color:var(--text);border-color:var(--border)}
@media(min-width:760px){#routes-table select{min-width:132px}}
@media(max-width:759px){
#agents-table :is(th,td,code){min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;word-break:break-word}
@@ -345,9 +414,9 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
@media (max-width:759px) {
.table-wrap:has(.s1-agents), .table-wrap:has(.s1-authority), .table-wrap:has(.s1-creds),
.table-wrap:has(#token-usage-table), .table-wrap:has(#token-limits-table),
.table-wrap:has(#proxy-accounts), .table-wrap:has(#proxy-keys) { overflow-x:scroll; max-width:100%; }
.table-wrap:has(#proxy-keys) { overflow-x:scroll; max-width:100%; }
.s1-agents, .s1-authority, .s1-creds, #token-usage-table, #token-limits-table,
.table-wrap:has(#proxy-accounts) table, .table-wrap:has(#proxy-keys) table { min-width:650px; }
.table-wrap:has(#proxy-keys) table { min-width:650px; }
.s1-authority :is(th,td), .s1-creds :is(th,td) { white-space:nowrap; }
/* #1873 A2: the root and project agent level grids scroll inside their card. */
.table-wrap:has(#agent-levels-root-grid), .table-wrap:has(#agent-levels-project-grid) { overflow-x:scroll; max-width:100%; }
+53 -9
View File
@@ -8,6 +8,8 @@
const $ = id => document.getElementById(id);
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const PATH = '/api/triage/route';
// proxy-scope slice 4 (#1873): Repair access and Turn Triage off (triage-route-http.mjs).
const ACCESS_PATH = '/api/triage/access';
// The time zones this browser knows, offered as suggestions only; the server decides.
const zones = (() => { try { return Intl.supportedValuesOf('timeZone'); } catch { return []; } })();
// draft holds the typed fields; base is the revision they were read at, which a save sends, so a
@@ -33,11 +35,12 @@
const models = () => (Array.isArray(data?.choices?.models) ? data.choices.models : []);
const harnessesOf = key => models().find(m => m.key === key)?.harnesses ?? [];
const savedAt = v => (Number.isFinite(Date.parse(v)) ? window.MosaicLocalTime(v) : 'at an unknown time');
function stored() {
const r = data?.route;
if (!r) return `<p id="triage-route-stored"><strong>Not set.</strong> ${esc(data?.routeMessage ?? 'No Triage route is set.')}</p>`;
return `<p id="triage-route-stored">Stored route: <strong>${esc(r.model)}</strong> on <strong>${esc(r.harness)}</strong>, cap ${esc(Number(r.cap).toLocaleString('en-US'))} tokens a day, reset ${esc(r.reset)} ${esc(r.timeZone)}. Revision ${esc(r.revision)}, saved ${esc(r.updatedAt)}.</p>`;
if (!r) return `<p id="triage-route-stored" data-revision="0"><strong>Not set.</strong> Triage has no model chosen yet, so it will not start.</p>`;
return `<p id="triage-route-stored" data-revision="${esc(r.revision)}">Saved route: <strong>${esc(r.model)}</strong>, runs with <strong>${esc(r.harness)}</strong>. Daily token limit ${esc(Number(r.cap).toLocaleString('en-US'))}, resets at ${esc(r.reset)} ${esc(r.timeZone)}. Saved ${esc(savedAt(r.updatedAt))}.</p>`;
}
function form() {
@@ -50,16 +53,16 @@
+ (d.model && !offered ? `<option value="${esc(d.model)}" selected>${esc(d.model)} (not offered now)</option>` : '')
+ list.map(m => `<option value="${esc(m.key)}"${m.key === d.model ? ' selected' : ''}${m.available ? '' : ' disabled'}>${esc(m.label && m.label !== m.key ? `${m.label} (${m.key})` : m.key)}${m.available ? '' : ' (unavailable)'}</option>`).join('');
const hs = harnessesOf(d.model);
const harnessOptions = `<option value=""${d.harness === '' ? ' selected' : ''}>${d.model ? 'Choose a harness' : 'Choose a model first'}</option>`
const harnessOptions = `<option value=""${d.harness === '' ? ' selected' : ''}>${d.model ? 'Choose what runs it' : 'Choose a model first'}</option>`
+ (d.harness && !hs.includes(d.harness) ? `<option value="${esc(d.harness)}" selected>${esc(d.harness)} (not offered for this model)</option>` : '')
+ hs.map(h => `<option value="${esc(h)}"${h === d.harness ? ' selected' : ''}>${esc(h)}</option>`).join('');
const status = data?.choices?.status;
const catalogue = status === 'ready' ? '' : `<p class="small warn" id="triage-route-catalogue">No organization bus offered a model catalogue (${esc(status ?? 'unknown')}), so no route can be saved now.</p>`;
const catalogue = status === 'ready' ? '' : `<p class="small warn" id="triage-route-catalogue" data-status="${esc(status ?? 'unknown')}">No organization can show your models right now, so no route can be saved. <a href="#/settings/model-setup">Open Model setup</a> to see why each organization can't see your models.</p>`;
const conflictButton = conflict ? ' <button type="button" class="btn" id="triage-route-reload">Reload route</button>' : '';
return `${catalogue}<form id="triage-route-form" novalidate><div class="filters">`
+ `<label>Model <select id="triage-route-model"${off}>${modelOptions}</select></label>`
+ `<label>Harness <select id="triage-route-harness"${off}>${harnessOptions}</select></label>`
+ `<label>Daily cap, tokens <input id="triage-route-cap" type="number" min="1" step="1" inputmode="numeric" value="${esc(d.cap)}"${off}></label>`
+ `<label>Runs with <select id="triage-route-harness" aria-describedby="triage-route-harness-help"${off}>${harnessOptions}</select><span class="small muted" id="triage-route-harness-help">The program that runs the model, named as its module is installed. The list shows only the programs this model runs with.</span></label>`
+ `<label>Daily token limit <input id="triage-route-cap" type="number" min="1" step="1" inputmode="numeric" value="${esc(d.cap)}"${off}></label>`
+ `<label>Reset <input id="triage-route-reset" value="00:00" readonly aria-readonly="true"></label>`
+ `<label>Time zone <input id="triage-route-zone" list="triage-route-zones" autocomplete="off" spellcheck="false" placeholder="Region/City" value="${esc(d.timeZone)}"${off}></label>`
+ `</div><datalist id="triage-route-zones">${zones.map(z => `<option value="${esc(z)}"></option>`).join('')}</datalist>`
@@ -67,10 +70,47 @@
+ `</form>${send ? '' : '<p class="small muted" id="triage-route-readonly">This Console is read-only, so the route cannot be saved here.</p>'}`;
}
// proxy-scope slice 4: the key's state, ids and days only, and the two access buttons.
let accessLine = '';
function access() {
const a = data?.access;
if (!a || typeof a !== 'object') return '';
const state = a.key === 'issued' ? `Triage key ${esc(a.keyId)} is issued. It rotates on ${esc(a.rotateBy)}.`
: a.key === 'missing' ? 'No Triage key is issued, so Triage will not start.'
: 'The Triage key file is not safe to use, so Triage will not start.';
const warn = [a.rotation === 'rotation overdue' ? 'Key rotation overdue.' : '', a.code === 'triage-no-riding-bus' ? `${a.message}.` : ''].filter(Boolean).join(' ');
const off = busy || data?.send !== true ? ' disabled' : '';
return `<div id="triage-access" data-key="${esc(a.key)}" data-code="${esc(a.code ?? '')}" data-rotation="${esc(a.rotation ?? '')}"><p class="small">${state}</p>`
+ (warn ? `<p class="small warn" id="triage-access-warn">${esc(warn)}</p>` : '')
+ `<div class="settings-actions"><button type="button" class="btn" id="triage-access-repair"${off}>Repair access</button> <button type="button" class="btn" id="triage-access-off"${off}>Turn Triage off</button> <span role="status" id="triage-access-line" tabindex="-1">${esc(accessLine)}</span></div></div>`;
}
// Each key action in its own plain sentence (proxy.triage.key answers).
const ACTION_LINE = {
issued: 'A Triage key was issued.', replaced: 'A new Triage key replaced one the proxy no longer held.',
held: 'The Triage key is in place.', revoked: 'Triage is off. Its key was removed.', none: 'Triage is off. No key was held.',
};
async function accessOp(op) {
if (busy || data?.send !== true) return;
if (op === 'off' && typeof window.confirm === 'function' && !window.confirm('Turn Triage off? This stops any Triage session and removes its key. Repair access issues a new one.')) return;
busy = true; accessLine = op === 'off' ? 'Turning Triage off…' : 'Repairing access…'; repaint();
let r, a = null;
try { r = await window.fetch(ACCESS_PATH, { cache: 'no-store', redirect: 'manual', method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ op }) }); }
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 (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.';
repaint();
$('triage-access-line')?.focus?.();
}
function markup() {
const body = data === null
? `<p class="small warn">${esc(readLine || 'The Triage route could not be read.')}</p><p role="status" id="triage-route-line" tabindex="-1">${esc(line)}</p>`
: `${stored()}${form()}<p class="small muted" id="triage-route-note">${esc(data.note ?? 'Saving a route does not start Triage. The key and the wiring are separate.')}</p>`;
: `${stored()}${access()}${form()}<p class="small muted" id="triage-route-note">${esc(data.note ?? 'Saving a route does not start Triage. Triage also needs its key.')}</p>`;
return `<section class="panel" id="triage-route" aria-labelledby="triage-route-title"><h3 id="triage-route-title">Triage model route</h3>${body}</section>`;
}
const repaint = () => { const panel = $('triage-route'); if (panel) panel.outerHTML = markup(); };
@@ -92,7 +132,7 @@
if (r.ok && a?.route) {
data = { ...data, route: a.route, revision: a.revision, routeMessage: undefined };
draft = fromRoute(a.route); base = a.revision;
line = `Saved. Revision ${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();
$('triage-route-line')?.focus?.();
return;
@@ -126,7 +166,11 @@
repaint(); $('triage-route-model')?.focus();
});
document.addEventListener('submit', e => { if (e.target?.id !== 'triage-route-form') return; e.preventDefault(); save(); });
document.addEventListener('click', e => { if (e.target?.id === 'triage-route-reload') reload(); });
document.addEventListener('click', e => {
if (e.target?.id === 'triage-route-reload') reload();
if (e.target?.id === 'triage-access-repair') accessOp('repair');
if (e.target?.id === 'triage-access-off') accessOp('off');
});
const hasDraft = () => !!(draft && data && JSON.stringify(draft) !== JSON.stringify(fromRoute(data.route)));
window.MosaicTriageRoute = { section, hasDraft };
+9 -4
View File
@@ -52,7 +52,11 @@
}
const av = (org, size = '') => `<span class="ws-av ws-o${size ? ` ${size}` : ''}" style="${colours(org)}" aria-hidden="true">${esc(initials(org))}</span>`;
const label = org => org.label || org.id;
const state = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : org.busStopped ? ['s-offline', '○', 'bus stopped'] : ['s-offline', '○', 'bus unavailable']);
// #1873 settings slice 4: the instance owner's model marks (display.js MosaicModelDots) sit over the
// bus state. Can't start always shows; needs restart and paused only on a running bus.
const MODEL_MARKS = { cant: ['s-error', '▲', "can't start"], restart: ['s-waiting', '◐', 'needs restart'], paused: ['s-waiting', '◐', 'paused'] };
const busState = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : org.busStopped ? ['s-offline', '○', 'bus stopped'] : ['s-offline', '○', 'bus unavailable']);
const state = org => { const mark = org.invalid ? null : window.MosaicModelDots?.get(org.id); return mark === 'cant' || (mark && org.busHealthy) ? MODEL_MARKS[mark] : busState(org); };
// A status mark: a glyph plus its word, shown or read aloud only.
const dot = (cls, glyph, word, shown = false) => `<span class="ws-dot ${cls}" title="${esc(word)}"><b aria-hidden="true">${glyph}</b>${shown ? esc(word) : `<span class="ws-sr">${esc(word)}</span>`}</span>`;
const orgHref = id => `#/orgs/${enc(id)}`;
@@ -126,7 +130,7 @@
const key = focusKey(root);
if (orgError || !orgs) { root.innerHTML = `<hr class="ws-hr"><p class="ws-line">${orgError ? 'Organizations unavailable' : 'Reading organizations…'}</p>`; return; }
// SP1: a system route (the dashboard) marks no organization; an organization route marks its own.
const here = route(), selected = /^#\/orgs\//.test(location.hash) ? window.MosaicOrg?.id : null;
const here = route(), selected = /^#\/orgs\//.test(location.hash) || /^#\/settings\/[^?]+\?(?:[^#]*&)?org=/.test(location.hash) ? window.MosaicOrg?.id : null;
const rows = orgs.map(org => {
const [cls, glyph, word] = state(org), mine = org.id === selected, current = mine && here === '/organization';
return `<li data-workspace-org="${esc(org.id)}"><a class="ws-nav ws-org-row${mine && !current ? ' sel' : ''}" href="${esc(orgHref(org.id))}/organization" data-focus-key="${esc(`org:${org.id}`)}"${current ? ' aria-current="page"' : ''}>${av(org)}<span class="t">${esc(label(org))}</span>${dot(cls, glyph, word, cls !== 's-working')}</a></li>`;
@@ -157,6 +161,7 @@
});
window.addEventListener('hashchange', () => { if (orgs) paint(); });
document.addEventListener('mosaic-org-list', e => refresh(e.detail?.rows));
document.addEventListener('mosaic-model-dots', () => { if (orgs) paint(); });
// ---------- organization dashboard (sample 03) ----------
const SAFE = /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,159}$/;
@@ -200,7 +205,7 @@
['ledger', 'Launch limits', !s ? unread : s.launch?.refused ? unread : Number.isFinite(total) ? `${plural(total, 'session')} at once` : 'No session limit', 'org file', 'limits'],
['talk', 'Assistant', 'The assistant agent and its seat names', 'org file', 'assistant'],
['ledger', 'Token use', 'Usage and limits per provider and model', 'system', 'tokens'],
['term', 'Model proxy', 'Accounts, priority and client keys', 'system', 'model-proxy'],
['term', 'Model setup', 'Your model service and its accounts', 'system', 'model-setup'],
['restart', 'Console', 'Console restart', 'system', 'console'],
['business', 'Organizations', orgCount === null ? unread : plural(orgCount, 'organization'), 'system', 'organizations'],
['flag', 'About', typeof s?.release === 'string' ? `Release ${s.release}` : 'Address, release and notifier', 'system', 'about'],
@@ -307,7 +312,7 @@
const bus = restart ? (org.busHealthy ? `<span class="ws-busctl" data-dashboard-bus>${restart}</span>` : '') : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button> <button type="button" class="ws-btn" data-bus-stop-off data-focus-key="bus-stop-off" disabled title="${esc(stopTitle)}">Stop bus</button></span>`;
// SP11 (#1873): the line beside the disabled reload says how a change to the organization file loads.
const reload = `<button type="button" class="ws-btn" data-org-reload data-focus-key="org-reload" disabled aria-describedby="${esc(why)}" title="Reloading without a restart is not available yet">${icon('doc')}Reload organization file</button>`;
const [bcls, bglyph] = state(org);
const [bcls, bglyph] = busState(org);
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : org.busStopped ? `bus stopped, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">The bus reads the organization file when it starts. To load a change to the file, restart the bus.</span></p>`;
const projectName = pid => projectRows?.find(p => p.id === pid)?.name || pid;
+2 -1
View File
@@ -1051,7 +1051,8 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user,
principal: currentSession ? { provider: currentSession.provider, iss: currentSession.iss, sub: currentSession.sub } : null, log });
if (path.startsWith('/api/proxy/')) return proxyHTTP(req, res, { path, call: proxyCall, named, tester, granted,
send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log });
send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log,
record: proxyAdmin && typeof proxyAdmin.recordAccount === 'function' ? entry => proxyAdmin.recordAccount({ ...entry, org: orgId }) : null });
}
// #1873 triage-host: the Triage session's two routes answer only the instance owner's own session on
// the public name, with no organization selected. Anyone else falls through to the answer an
+87
View File
@@ -0,0 +1,87 @@
// proxy-scope slice 4 (#1873): the Console's side of the Triage key. The Console never holds the
// proxy management key, so it never issues or removes a Triage key itself: it asks one riding
// organization's bus to, through the bus verb `proxy.triage.key` (op ensure or revoke), as the owner,
// the way Proxy setup's init asks one bus for `proxy.init` (packages/model-proxy/src/admin-control.mjs).
// A riding organization lists cliproxy and is not a fixture organization; its bus decides for itself
// whether it holds the owner's proxy client, and refuses triage-no-riding-bus when it does not.
//
// A bus that is down or not riding did nothing, so it is passed over and the next one is asked. A bus
// whose outcome is unknown (a timeout, or an answer that could not be read) may have done the work, so
// the walk stops there and the caller shows the key file's state. Any other refusal is the answer.
// With no bus left the answer is triage-no-riding-bus.
//
// The key file is read only through packages/bus/src/triage-key-file.mjs, the reader with no proxy
// client and no lock. No answer here holds a key: only ids, days and codes.
import { readKey } from '../../bus/src/triage-key-file.mjs';
export const NO_RIDING_MESSAGE = "Triage needs one organization that uses the owner's models";
// A bus sweep runs every 30 s; a rotation still not done this long after its day began means no
// riding bus could act.
export const OVERDUE_ALLOWANCE_MS = 10 * 60 * 1000;
// A refusal that says only "not this bus": ask the next one.
const NEXT = new Set(['triage-no-riding-bus', 'not-configured', 'no-bus-host', 'unknown-verb', 'bus-unavailable']);
// An outcome the Console cannot know (webui bus.mjs OPEN): stop, and answer outcome-unknown.
const OPEN = new Set(['outcome-unknown', 'invalid-response', 'response-too-large']);
const ACTIONS = new Set(['issued', 'held', 'replaced', 'revoked', 'none']);
const KEY_ID = /^[0-9a-f]{12}$/;
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const ids = v => (Array.isArray(v) ? v.filter(x => typeof x === 'string' && KEY_ID.test(x)) : []);
// The fields the Console keeps from a bus answer, re-checked here: ids and a day, never a key.
const clean = (op, a) => ({
ok: true, op,
action: ACTIONS.has(a?.action) ? a.action : 'unknown',
addedKeyIds: ids(a?.addedKeyIds), removedKeyIds: ids(a?.removedKeyIds),
...(op === 'ensure' && typeof a?.keyId === 'string' && KEY_ID.test(a.keyId) ? { keyId: a.keyId } : {}),
...(op === 'ensure' && typeof a?.rotateBy === 'string' && DAY.test(a.rotateBy) ? { rotateBy: a.rotateBy } : {}),
});
// triageKeyCall({ riders, op }) -> { ok: true, op, action, addedKeyIds, removedKeyIds, keyId?, rotateBy?, org }
// | { ok: false, code, org? }
// riders async () -> [{ id, fixture, cliproxy, call }] (webui cli.mjs rideRiders)
// The organizations whose bus may hold the Triage key: they list cliproxy and are not fixtures. The
// status reads the same list, so it says no riding organization exactly when the walk has none to ask.
export const ridingOrgs = list => (Array.isArray(list) ? list : []).filter(r => r?.cliproxy === true && r.fixture !== true && typeof r.call === 'function');
export async function triageKeyCall({ riders, op }) {
if (op !== 'ensure' && op !== 'revoke') return { ok: false, code: 'invalid-request' };
let list = [];
try { list = await riders(); } catch { list = []; }
for (const r of ridingOrgs(list)) {
let answer;
try { answer = await r.call('proxy.triage.key', { op }); }
catch (e) {
const code = typeof e?.code === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(e.code) ? e.code : 'outcome-unknown';
if (NEXT.has(code)) continue;
return { ok: false, code: OPEN.has(code) ? 'outcome-unknown' : code, org: r.id };
}
return { ...clean(op, answer), org: r.id };
}
return { ok: false, code: 'triage-no-riding-bus' };
}
// The key's state from the file alone, for Settings > Triage: never the key, only whether one is
// held, its id, its rotation day, how many old keys are in grace, and whether the rotation is overdue.
// { key: 'missing' } | { key: 'unsafe' } | { key: 'issued', keyId, rotateBy, retiring, overdue }
export function keyState(configDir, { now = () => Date.now(), keyOptions = {} } = {}) {
let record;
try { record = readKey(configDir, keyOptions); } catch { return { key: 'unsafe' }; }
if (!record) return { key: 'missing' };
const due = Date.parse(`${record.rotateBy}T00:00:00Z`);
return {
key: 'issued', keyId: record.keyId, rotateBy: record.rotateBy, retiring: record.retiring.length,
due: Number.isFinite(due) && now() >= due,
overdue: Number.isFinite(due) && now() > due + OVERDUE_ALLOWANCE_MS,
};
}
// The status Settings > Triage shows: the key state, and the named code when no organization rides
// the owner's models (so no bus can issue, rotate or retire the key). The rotation is overdue when
// its day has begun and no riding bus can act, or when it is still not done well after (a riding
// organization whose bus did not rotate it).
export function accessStatus(state, { riding }) {
const out = { ...state, riding: riding === true };
if (riding !== true) Object.assign(out, { code: 'triage-no-riding-bus', message: NO_RIDING_MESSAGE });
if (state.key === 'issued' && (state.overdue || (state.due && riding !== true))) out.rotation = 'rotation overdue';
return out;
}
+248 -24
View File
@@ -35,12 +35,15 @@
//
// #1873 triage-wiring: the host sets the harness's MOSAIC_ names itself. At each start it calls the
// module's bundle() into the run's bundle/ (Claude Code: settings.json with the tool gate hook and
// mcp.json with the typed tools' server) and its env() with no proxy, and keeps the MOSAIC_ names the
// mcp.json with the typed tools' server) and its env(), and keeps the MOSAIC_ names the
// module declares, with clean string values, never a name the runner sets. Every other name is the
// route's, under the fence above, so no name has two sources. The thinking
// level is the module's "low", or its first level. These join the route's fenced harnessEnv in
// session.json. The key is never among them: env() gets no proxy, and a value that holds the key
// refuses the start. MOSAIC_CLAUDE_BIN, the pinned binary's absolute path, passes from the
// session.json. The key is never among them: #1873 harness-matrix gives bundle() and env() the
// real proxy (pi takes it through models.json), and a MOSAIC_ value or any file under the run's
// bundle/, home/, work/ or tmp/ that holds the key, raw or JSON-decoded, refuses the start, as
// does a URL other than the proxy's in a file the module wrote there, or a change the module made
// to the rest of the run directory (session/). MOSAIC_CLAUDE_BIN, the pinned binary's absolute path, passes from the
// Console's environment as it does for a bus session. An answer the agent sends has the key, and
// anything shaped like it, replaced before it reaches the transcript.
//
@@ -57,7 +60,7 @@
import { spawn } from "node:child_process";
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, chmodSync, writeFileSync } from "node:fs";
import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, readdirSync, openSync, readFileSync, rmSync, chmodSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
@@ -66,7 +69,7 @@ import { BWRAP, REPO, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds }
import { isProviderVariable } from "../../seat/src/session.mjs";
import { configDir as systemConfigDir } from "../../organization/src/organization-config.mjs";
import { typedTools } from "../../harness/src/tools.mjs";
import { builtinTools } from "../../harness/src/bundle.mjs";
import { builtinTools, checkedTransport } from "../../harness/src/bundle.mjs";
import { FOUNDER_ENV } from "../../harness/src/runner.mjs";
import { extractCards, plainText } from "./triage-cards.mjs";
import { SNAPSHOT_FILE, writeSnapshot } from "./triage-snapshot.mjs";
@@ -88,6 +91,12 @@ export const USAGE_NOT_READ = "Triage could not read its token usage or its cap,
// #1873 triage-wiring: two turns in a row whose usage reads unknown end the session (cap fail closed).
export const UNKNOWN_TURNS_MAX = 2;
export const USAGE_UNKNOWN_ENDED = "Triage ended this session: the token usage of two turns in a row could not be read, so the daily cap could not be kept. The next message starts a new session.";
// proxy-scope slice 4 (#1873): a session still running on a key whose grace has ended (its retireAt
// in the key file has passed, or the key is gone from the file) stops with this code, before the bus
// sweep removes the key from the proxy (the sweep waits 30 s past retireAt).
export const KEY_ROTATED_CODE = "triage-key-rotated";
export const KEY_ROTATED = "Triage stopped this session: its key was rotated and the old key's grace ended. The next message starts a new session on the current key.";
export const KEY_POLL_MS = 5000;
// #1873 triage-wiring: the route's refusals (triage-route.mjs), each with the one plain line the
// drawer shows. None carries a path, a key or an env value.
export const ROUTE_REFUSALS = Object.freeze({
@@ -128,7 +137,17 @@ const RUNNER_NAMES = new Set(["MOSAIC_SYSTEM_PROMPT_FILE", "MOSAIC_WORKSPACE", "
export const KEY_REMOVED = "[key removed]";
// The marker, under host/ (never mounted), that the next start gets a fresh session/.
const FRESH_MARKER = "fresh-session";
export const ROUTE_ENV_ALLOW = Object.freeze(["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]);
// #1873 harness-matrix: the names a harness may take the Triage key through. claude-code takes it as
// ANTHROPIC_AUTH_TOKEN; pi as ANTHROPIC_API_KEY, which its models.json names. A route's env holds
// exactly one of them.
export const ROUTE_KEY_NAMES = Object.freeze(["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]);
export const ROUTE_ENV_ALLOW = Object.freeze(["ANTHROPIC_BASE_URL", ...ROUTE_KEY_NAMES]);
// The one key name a route env holds and its value, or null when it holds none or more than one.
export const routeKey = (routeEnv) => {
const held = ROUTE_KEY_NAMES.filter((k) => routeEnv?.[k] !== undefined);
if (held.length !== 1 || typeof routeEnv[held[0]] !== "string" || !routeEnv[held[0]]) return null;
return { name: held[0], value: routeEnv[held[0]] };
};
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
const ENV_VALUE_MAX = 4096;
const HARNESS_ENV_MAX = 64;
@@ -162,7 +181,10 @@ async function repoHarnessModule(name) {
}
export function triageEnv(source, routeEnv = {}, { node = process.execPath } = {}) {
const env = { PATH: `${dirname(node)}:/usr/bin:/bin` };
// #1873 harness-matrix: the repository's node_modules/.bin comes first, as a bus session's PATH has
// it (session.mjs sessionEnv): a harness whose adapter runs its binary from there finds it. It is in
// the sandbox only when the harness's own mounts bind node_modules.
const env = { PATH: `${join(REPO, "node_modules", ".bin")}:${dirname(node)}:/usr/bin:/bin` };
for (const k of SPAWN_ENV_ALLOW) if (k !== "PATH" && typeof source?.[k] === "string" && source[k].length <= 256) env[k] = source[k];
for (const k of SPAWN_PATH_ALLOW) if (typeof source?.[k] === "string" && source[k].startsWith("/") && source[k].length <= 256 && cleanValue(source[k])) env[k] = source[k];
for (const k of ROUTE_ENV_ALLOW) if (typeof routeEnv?.[k] === "string" && routeEnv[k].length <= 4096) env[k] = routeEnv[k];
@@ -307,13 +329,18 @@ export function createRelay({ socket, cap, take, read, onSend, usage = null, sto
// repository's packages/plugins/harness/<name> by default
// home HOME, which no mount may reach outside the stack's own code; the Console user's by default
// usageSource { readTurn({ harness, root }) } the transcript usage-source; the repository's own by default
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null, proxyPort = null, tokenPattern = null, harnessModule = repoHarnessModule, home = homedir(), usageSource = { readTurn } }) {
// keyRecord () -> the Triage key file's record (packages/bus/src/triage-key-file.mjs readKey) or
// null; throws when unsafe. With it, a session on a key past its retireAt, or a key
// gone from the file, stops with triage-key-rotated. Without it, nothing is checked.
// keyPollMs how often a running session's key is checked
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null, proxyPort = null, tokenPattern = null, harnessModule = repoHarnessModule, home = homedir(), usageSource = { readTurn }, keyRecord = null, keyPollMs = KEY_POLL_MS }) {
if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TriageError("triage-no-data-root", "no data root");
const validPort = (p) => Number.isInteger(p) && p > 0 && p <= 65535;
if (proxyPort !== null && typeof proxyPort !== "function" && !validPort(proxyPort)) throw new TypeError("proxyPort must be a port number, null or a function");
if (tokenPattern !== null && !(tokenPattern instanceof RegExp)) throw new TypeError("tokenPattern must be a RegExp or null");
if (typeof harnessModule !== "function") throw new TypeError("harnessModule must be a function");
if (typeof usageSource?.readTurn !== "function") throw new TypeError("usageSource must have readTurn");
if (keyRecord !== null && typeof keyRecord !== "function") throw new TypeError("keyRecord must be a function or null");
const tokenShape = tokenPattern && new RegExp(`^(?:${tokenPattern.source})$`, tokenPattern.flags.replace(/[gmy]/g, ""));
const tokenAnywhere = tokenPattern && new RegExp(tokenPattern.source, tokenPattern.flags.replace(/[gmy]/g, "") + "g");
// What no mount source may lie in or around, besides the run directory and the fixed list. HOME
@@ -339,6 +366,11 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
// host/ too, so a Console restart between the end and the next message keeps it.
let freshSession = false;
const badSeen = new Set();
// proxy-scope slice 4: the key the running session holds (memory only, never written or logged),
// the timer that checks it, and the last stop the host made for a rotated key.
let heldKey = null;
let keyTimer = null;
let lastStop = null;
const ensureDirs = () => {
mkdirSync(dataRoot, { recursive: true, mode: 0o700 });
@@ -385,9 +417,38 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
// #1873 triage-wiring: the module's bundle files and its MOSAIC_ names, which the host sets itself.
const hostHarnessEnv = (mod, { admitted, bundleDir, files, policy, tools, toolSocket }) => {
if (typeof mod?.bundle !== "function" || typeof mod?.env !== "function") return {};
if (typeof mod?.bundle !== "function" || typeof mod?.env !== "function") return { env: {}, files: [] };
// #1873 harness-matrix: the module gets the real proxy and the route's transport, as a bus
// session's bundle does, so a harness that takes the proxy through its own files (pi's
// models.json) writes them here. Claude Code's bundle() takes no proxy. No file it writes, in
// bundle/ or outside it, may hold the key or anything shaped like it.
const routed = routeKey(admitted.env);
const key = routed?.value;
if (!key) throw new Error("no key");
const holdsKey = (v) => typeof v === "string" && (v.includes(key) || Boolean(tokenAnywhere && v.match(tokenAnywhere)));
// A file's text, and when it parses as JSON every key and string in it, decoded: an escaped key
// or URL ("\u0061...", "http:\/\/...") is seen as the harness that parses the file sees it. A
// harness can parse more loosely than JSON.parse (pi takes a byte order mark, comments and
// trailing commas), so a file that does not parse may hold no backslash: its escapes would be
// decoded by the harness and not here.
const decoded = (text) => {
const out = [text];
let doc;
try { doc = JSON.parse(text); } catch {
if (text.includes("\\")) throw new Error("bundle file holds an escape it does not parse");
return out;
}
const stack = [doc];
while (stack.length) {
const v = stack.pop();
if (typeof v === "string") out.push(v);
else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) { out.push(k); stack.push(x); }
}
return out;
};
const write = (name, text) => {
if (typeof name !== "string" || !/^[a-z][a-z0-9.-]{0,63}$/.test(name) || typeof text !== "string") throw new Error("bundle file refused");
if (decoded(text).some(holdsKey)) throw new Error("bundle file holds the key");
writeFileSync(join(bundleDir, name), text, { mode: 0o600, flag: "wx" });
return [name, createHash("sha256").update(text).digest("hex")];
};
@@ -398,18 +459,114 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
let levels = [];
try { levels = typeof mod.levels === "function" ? mod.levels() : []; } catch { levels = []; }
const thinking = Array.isArray(levels) && levels.includes("low") ? "low" : Array.isArray(levels) && typeof levels[0] === "string" ? levels[0] : "";
const session = { model: admitted.model, provider: admitted.provider ?? "", thinking, toolSocket };
const own = mod.bundle({ dir: bundleDir, files: { ...files }, session: { ...session }, write, quote, models: {}, proxy: null, transports: {} });
const given = mod.env({ files: { ...(plainObject(own?.files) ? own.files : {}) }, policy, tools, session: { ...session }, models: {}, proxy: null });
const proxy = { baseUrl: admitted.env.ANTHROPIC_BASE_URL, key };
const session = { model: admitted.model, provider: admitted.provider ?? "", thinking, toolSocket, ...(admitted.transport ? { proxyTransport: { ...admitted.transport } } : {}) };
const models = { triage: { provider: admitted.provider ?? "", model: admitted.model } };
const transports = admitted.transport ? { triage: { ...admitted.transport } } : {};
// The rest of the run directory (session/, kept across starts) is the module's to leave alone:
// what it holds before bundle() must be what it holds after env(). ctime is in the record
// because no user process can set it back, as it can mtime.
const scanned = new Set(["bundle", "home", "work", "tmp"]);
const kept = () => {
const seen = new Map();
for (const name of readdirSync(paths.agent, { recursive: true })) {
const rel = String(name);
if (scanned.has(rel.split("/")[0])) continue;
const st = lstatSync(join(paths.agent, rel));
seen.set(rel, `${st.mode}:${st.ino}:${st.size}:${st.mtimeMs}:${st.ctimeMs}:${st.nlink}`);
}
return seen;
};
const before = kept();
// The host's own bundle files (prompt, policy, tools) must be as the host wrote them.
const hostFiles = new Map(Object.values(files).map((f) => [f, readFileSync(f, "utf8")]));
const own = mod.bundle({ dir: bundleDir, files: { ...files }, session: { ...session }, write, quote, models, proxy: { ...proxy }, transports });
const ownFiles = plainObject(own?.files) ? own.files : {};
const given = mod.env({ files: { ...ownFiles }, policy, tools, session: { ...session }, models, proxy: { ...proxy } });
if (!plainObject(given)) throw new Error("env refused");
const key = admitted.env?.ANTHROPIC_AUTH_TOKEN;
const after = kept();
const changed = [...after].filter(([k, v]) => before.get(k) !== v).map(([k]) => k);
if (changed.length || after.size !== before.size) {
// What the module added or changed goes, and the next start takes a fresh session.
for (const k of changed) rmSync(join(paths.agent, k), { recursive: true, force: true });
freshSession = true;
throw new Error("bundle changed the run directory");
}
// Each host bundle file is still there, a regular file with one link and the same bytes,
// whether or not the scan below reaches it.
for (const [f, text] of hostFiles) {
const st = lstatSync(f, { throwIfNoEntry: false });
if (!st?.isFile() || st.nlink !== 1 || readFileSync(f, "utf8") !== text) throw new Error("bundle changed a host file");
}
// A module can write by its own means too, and name only some of its files. writeBundle makes
// bundle/, home/, work/ and tmp/ fresh just before, so every file in them came from this start:
// each is read again, and each must be a regular file with no key in it, raw or decoded, and,
// past the host's own bundle files, no URL but the proxy's (its root or /v1): a harness reads
// files from its HOME and workspace that it does not declare (pi's ~/.pi/agent/models.json).
// No string in them may be a pi command value: pi runs a config value that starts with "!" as a
// shell command, so no decoded string starts with "!" and no text holds a string that does ('"!').
// These fences see what the module left when env() returns, in the run directory only. They do not stop a module that
// hides the key (base64, split across files) or writes after: harness modules are reviewed
// repo code, and the fences catch their mistakes, not their intent.
const proxyUrl = (u) => u === proxy.baseUrl || u === proxy.baseUrl + "/v1";
const SPECIAL = new Set(["http:", "https:", "ws:", "wss:", "ftp:", "file:"]);
// Every URL a string names, as written ("http://", "http:host", "http:\\host") or as a URL
// parser reads the whole string (it drops tabs and newlines anywhere and controls at the ends).
const urlsIn = (text) => {
const out = [...text.matchAll(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>\\]*/gi), ...text.matchAll(/\b(?:https?|wss?|ftp|file):[^\s"'<>]*/gi)].map(([u]) => u);
if (URL.canParse(text) && SPECIAL.has(new URL(text).protocol)) out.push(text);
return out;
};
const strings = new Map();
for (const d of ["bundle", "home", "work", "tmp"]) {
const root = join(paths.agent, d);
for (const name of readdirSync(root, { recursive: true })) {
const f = join(root, String(name));
const st = lstatSync(f);
if (st.isDirectory()) continue;
if (!st.isFile()) throw new Error("bundle file is not a regular file");
const text = readFileSync(f, "utf8");
if (hostFiles.has(f)) { if (text !== hostFiles.get(f)) throw new Error("bundle changed a host file"); continue; }
const all = decoded(text);
if (all.some(holdsKey)) throw new Error("bundle file holds the key");
if (all.some((t) => urlsIn(t).some((u) => !proxyUrl(u)))) throw new Error("bundle file names another URL");
if (all.some((t) => t.startsWith("!") || t.includes('"!'))) throw new Error("bundle file holds a command value");
strings.set(f, all);
}
}
// The key goes only into the one key name the route answered, as the key itself; the URL, when
// env() names one, is the route's.
for (const [k, v] of Object.entries(given)) {
if (k === routed.name) continue;
if (holdsKey(v)) throw new Error("env holds the key");
if (k === "ANTHROPIC_BASE_URL" && v !== proxy.baseUrl) throw new Error("env names another proxy");
}
if (given[routed.name] !== key) throw new Error("env does not take the key as it is");
// Files the module wrote outside bundle/ (pi's models.json): each a regular file the session's
// HOME holds, read above, with no URL but the proxy's (its root or /v1), raw or decoded, bound read-only
// over the run directory. A harness whose env() names no URL must take it from one of them.
const homeDir = join(paths.agent, "home");
const harnessFiles = [];
let urlInFile = false;
for (const f of Object.values(ownFiles)) {
if (typeof f !== "string" || f.startsWith(bundleDir + "/")) continue;
if (!f.startsWith(homeDir + "/") || f.split("/").includes("..")) throw new Error("bundle file outside the session's HOME");
const st = lstatSync(f);
if (!st.isFile() || st.nlink !== 1) throw new Error("bundle file is not a regular file");
const all = strings.get(f);
if (!all) throw new Error("bundle file was not read");
if (all.some((t) => urlsIn(t).length > 0)) urlInFile = true;
harnessFiles.push(f);
}
if (given.ANTHROPIC_BASE_URL === undefined && !urlInFile) throw new Error("harness takes no proxy URL");
// A name the route's harnessEnv holds that env() also answers must have env()'s value.
for (const [k, v] of Object.entries(admitted.harnessEnv ?? {})) if (Object.hasOwn(given, k) && given[k] !== v) throw new Error("harness env differs");
const out = {};
for (const [k, v] of Object.entries(given)) {
if (!k.startsWith("MOSAIC_") || !mod.envNames.includes(k) || !ENV_NAME.test(k) || RUNNER_NAMES.has(k) || !cleanValue(v)) continue;
if ((typeof key === "string" && key && v.includes(key)) || (tokenAnywhere && v.match(tokenAnywhere))) throw new Error("env holds the key");
out[k] = v;
}
return out;
return { env: out, files: harnessFiles };
};
const writeBundle = (admitted, mod) => {
@@ -434,11 +591,11 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
writeFileSync(bundle.prompt, hostPrompt(contract, { snapshotPath: join(workspace, "health", SNAPSHOT_FILE), steps }), { mode: 0o600, flag: "wx" });
writeFileSync(bundle.policy, JSON.stringify(policy, null, 2) + "\n", { mode: 0o600, flag: "wx" });
writeFileSync(bundle.tools, JSON.stringify(tools, null, 2) + "\n", { mode: 0o600, flag: "wx" });
let hostEnv;
try { hostEnv = hostHarnessEnv(mod, { admitted, bundleDir: join(a, "bundle"), files: bundle, policy, tools, toolSocket: join(a, "tools.sock") }); }
let hostEnv, harnessFiles;
try { ({ env: hostEnv, files: harnessFiles } = hostHarnessEnv(mod, { admitted, bundleDir: join(a, "bundle"), files: bundle, policy, tools, toolSocket: join(a, "tools.sock") })); }
catch {
log("triage host: route refused: harness-bundle");
rmSync(join(a, "bundle"), { recursive: true, force: true });
for (const d of ["bundle", "home", "work", "tmp"]) rmSync(join(a, d), { recursive: true, force: true });
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
}
const run = `triage-${now().toISOString().replace(/[^0-9]/g, "").slice(0, 14)}`;
@@ -450,7 +607,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
...(Number.isInteger(pollInterval) && pollInterval >= 100 ? { pollInterval } : {}),
};
writeFileSync(join(a, "session.json"), JSON.stringify(session, null, 2) + "\n", { mode: 0o600, flag: "wx" });
return run;
return { run, harnessFiles };
};
// The route's answer, checked. It returns a copy taken once, so a getter or a later change to
@@ -475,6 +632,10 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
for (const [k, v] of Object.entries(he)) if (refusedHarnessName(k) || !declared.includes(k) || !cleanValue(v)) refuse("harness-env");
const re = a.env ?? {};
if (!plainObject(re) || Object.entries(re).some(([k, v]) => !ROUTE_ENV_ALLOW.includes(k) || !cleanValue(v))) refuse("route-env");
// #1873 harness-matrix: exactly one key name, and no harnessEnv value holds the key.
const routed = routeKey(re);
if (!routed) refuse("route-env");
for (const v of Object.values(he)) if (v.includes(routed.value) || (tokenAnywhere && v.match(tokenAnywhere))) refuse("harness-env");
const url = LOOPBACK_URL.exec(re.ANTHROPIC_BASE_URL ?? "");
let port = proxyPort;
if (typeof proxyPort === "function") {
@@ -482,7 +643,13 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
if (!validPort(port)) refuse("route-env");
}
if (!url || Number(url[1]) > 65535 || (port !== null && Number(url[1]) !== port)) refuse("route-env");
if (tokenShape && !(typeof re.ANTHROPIC_AUTH_TOKEN === "string" && tokenShape.test(re.ANTHROPIC_AUTH_TOKEN))) refuse("route-env");
if (tokenShape && !tokenShape.test(routed.value)) refuse("route-env");
// The route's transport, when it gives one, held to the bus's own transport check. This checks its
// shape only: the harness rule ran at the route's admit, through the provider module's route().
if (a.transport !== undefined) {
try { checkedTransport({ provider: a.provider ?? "", model: a.model }, a.harness, () => ({ ...(plainObject(a.transport) ? a.transport : {}), provider: a.provider ?? "", model: a.model })); }
catch { refuse("transport"); }
}
let installRoots;
try { installRoots = structuredClone(mod.installRoots({ env })); } catch { refuse("module"); }
try {
@@ -614,11 +781,54 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
return true;
};
// proxy-scope slice 4. Where the held key stands in the key file: "current", the retireAt (ms) of
// the retiring entry that holds it, "gone", or "unknown" (no reader, no key, or an unsafe file:
// nothing is decided on a file that cannot be read; the next admit refuses it).
const keyStanding = (held) => {
if (!keyRecord || typeof held !== "string" || !held) return "unknown";
let r;
try { r = keyRecord(); } catch { return "unknown"; }
if (!r) return "gone";
if (r.key === held) return "current";
const old = Array.isArray(r.retiring) ? r.retiring.find((x) => x?.key === held) : null;
if (!old) return "gone";
const at = Date.parse(old.retireAt);
return Number.isFinite(at) ? at : "gone";
};
const keyDue = (held) => {
const s = keyStanding(held);
return s === "gone" || (typeof s === "number" && s <= now().getTime());
};
// SIGTERM, then SIGKILL after the grace; resolves when the process has exited (or 2 s after SIGKILL).
const endChild = (c, graceMs) => new Promise((resolve) => {
if (!c || c.exitCode !== null || c.signalCode !== null) return resolve();
let kill = null, last = null;
c.once("exit", () => { clearTimeout(kill); clearTimeout(last); resolve(); });
try { process.kill(-c.pid, "SIGTERM"); } catch {}
kill = setTimeout(() => {
try { process.kill(-c.pid, "SIGKILL"); } catch {}
last = setTimeout(resolve, 2000);
}, graceMs);
});
// The session on a rotated key stops: a host line says why, the runner is told its session is gone
// at its next state or receive, and the process group ends. Queued messages get their lines at exit.
let rotating = null;
const stopRotated = (c, { graceMs = 5000 } = {}) => rotating ??= (async () => {
if (!c || child !== c) return;
if (usage) usage.halted = true;
lastStop = { code: KEY_ROTATED_CODE, at: now().toISOString() };
log(`triage host: stopping the session: ${KEY_ROTATED_CODE}`);
try { append({ at: now().toISOString(), from: "host", text: KEY_ROTATED }); }
catch { log("triage host: transcript write failed"); }
await endChild(c, graceMs);
})().finally(() => { rotating = null; });
const clearKeyTimer = () => { if (keyTimer) clearInterval(keyTimer); keyTimer = null; };
const start = async ({ admitted, installRoots, transcriptRoot, mod }) => {
ensureDirs();
const run = writeBundle(admitted, mod);
const { run, harnessFiles } = writeBundle(admitted, mod);
// The key this session holds, and anything shaped like a key, never reaches the transcript.
const key = typeof admitted.env?.ANTHROPIC_AUTH_TOKEN === "string" && admitted.env.ANTHROPIC_AUTH_TOKEN ? admitted.env.ANTHROPIC_AUTH_TOKEN : null;
const key = routeKey(admitted.env)?.value ?? null;
const scrub = (body) => {
let t = typeof body === "string" ? body : "";
if (key) t = t.split(key).join(KEY_REMOVED);
@@ -655,14 +865,14 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
});
let list;
try {
list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, relaySocket: join(paths.agent, "relay.sock"), node, readOnly });
list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, relaySocket: join(paths.agent, "relay.sock"), node, readOnly, harnessFiles });
} catch (e) {
if (e?.code !== "hosted-binds-refused") throw e;
log(`triage host: route refused at the binds: ${e.fence}`);
// Nothing of the refused start stays: the relay, its socket, the bundle and session.json go.
relay?.close();
relay = null;
for (const f of ["relay.sock", "session.json", "bundle"]) rmSync(join(paths.agent, f), { recursive: true, force: true });
for (const f of ["relay.sock", "session.json", "bundle", "home", "work", "tmp"]) rmSync(join(paths.agent, f), { recursive: true, force: true });
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
}
const argv = hostedArgv(list, paths.agent, [node, RUNNER, paths.agent], { bwrap });
@@ -686,6 +896,8 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
if (child !== mine) return;
lastExit = { code: Number.isInteger(code) ? code : null, signal: signal ?? null, at: now().toISOString() };
child = null;
heldKey = null;
clearKeyTimer();
// A turn the session began and never ended (killed, crashed) still spent tokens: it gets its line.
// The open turns are read when this runs, after any usage.end already in the chain.
chainUsage(async () => { for (const k of [...u.baselines.keys()]) await finishTurn(u, k); });
@@ -706,6 +918,13 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
log(`triage host: launcher did not run: ${e.code ?? "error"}`);
throw new TriageError("triage-start-failed", "the Triage session did not start");
}
// proxy-scope slice 4: the key this session holds is checked while it runs.
heldKey = key;
clearKeyTimer();
if (keyRecord && key) {
keyTimer = setInterval(() => { if (child === mine && keyDue(key)) stopRotated(mine).catch(() => {}); }, keyPollMs);
keyTimer.unref?.();
}
};
// The cap is the route's to count. Once it answers over the cap with a time in the next two days,
@@ -757,6 +976,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
resetsAt: unset ? "not set" : c.resetsAt ?? "not read",
running: child !== null,
lastExit,
lastStop,
snapshot: last,
transcript: transcript(),
};
@@ -784,6 +1004,9 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
try { append({ at: now().toISOString(), from: "host", in_reply_to: id, text: e?.code === "triage-route-invalid" ? ROUTE_REFUSED : NOT_STARTED }); } catch {}
throw e instanceof TriageError ? e : new TriageError("triage-route-invalid", "the model route's answer is not usable");
}
// proxy-scope slice 4: a session on a key past its grace stops before this message is queued,
// so the message starts a new session on the key the route answered with.
if (child && keyDue(heldKey)) await stopRotated(child);
queue.push({ id, body: text, at, delivered: false });
if (!child) {
starting ??= start(checked).finally(() => { starting = null; });
@@ -801,6 +1024,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async
return { id, at };
},
async stop({ graceMs = 5000 } = {}) {
clearKeyTimer();
const c = child;
if (c) {
try { process.kill(-c.pid, "SIGTERM"); } catch {}
+80 -3
View File
@@ -19,12 +19,16 @@ import { fileURLToPath } from 'node:url';
import { checkRoutes } from '../../organization/src/launch-settings.mjs';
import { isDailyModelQuota } from '../../plugins/src/model-quota.mjs';
import { readRoute, writeRoute } from './triage-route-store.mjs';
import { NO_RIDING_MESSAGE, accessStatus } from './triage-access.mjs';
export const TRIAGE_ROUTE_PATH = '/api/triage/route';
// proxy-scope slice 4 (#1873): Repair access (ensure) and Turn Triage off (stop, then revoke).
export const TRIAGE_ACCESS_PATH = '/api/triage/access';
export const ACCESS_OPS = Object.freeze(['repair', 'off']);
export const BODY_MAX = 16384;
export const POST_KEYS = Object.freeze(['model', 'harness', 'cap', 'timeZone', 'revision']);
export const NOT_SET_MESSAGE = 'No Triage route is set.';
export const NOT_STARTED_NOTE = 'Saving a route does not start Triage. The key and the wiring are separate.';
export const NOT_STARTED_NOTE = 'Saving a route does not start Triage. Triage also needs its key.';
const HARNESS_ROOT = fileURLToPath(new URL('../../plugins/harness/', import.meta.url));
// The same shapes the store holds (triage-route-store.mjs).
@@ -63,6 +67,7 @@ const STATUS = Object.freeze({
'triage-route-unreadable': 503,
'triage-route-unrecorded': 500,
'outcome-unknown': 503,
'triage-no-riding-bus': 503,
});
// Fixed words for each code. The store's own messages name lock files, so none is forwarded.
const MESSAGES = Object.freeze({
@@ -85,7 +90,16 @@ const MESSAGES = Object.freeze({
'triage-route-unreadable': 'The stored route could not be read.',
'triage-route-unrecorded': 'The route was saved, but its receipt line was not written.',
'outcome-unknown': 'The route service did not answer.',
'triage-no-riding-bus': `${NO_RIDING_MESSAGE}. Start an organization that uses them, then choose Repair access.`,
});
// proxy-scope slice 4: a bus refusal of proxy.triage.key, in fixed words. The code is a bus code
// (lowercase and dashes); nothing from the bus's text is shown.
const keyFailed = code => code === 'triage-no-riding-bus' ? MESSAGES['triage-no-riding-bus']
: `The Triage key was not changed. The organization's bus refused with ${/^[a-z][a-z0-9-]{0,63}$/.test(code ?? '') ? code : 'an unknown code'}.`;
// What a key step answers in a response: ids, action and day, or the code and its fixed words.
const keyView = r => r?.ok === true
? { action: r.action, ...(r.keyId ? { keyId: r.keyId } : {}), ...(r.rotateBy ? { rotateBy: r.rotateBy } : {}) }
: { error: r?.code ?? 'outcome-unknown', message: keyFailed(r?.code) };
const json = (res, status, value) => {
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
@@ -191,7 +205,25 @@ async function readBody(req) {
// Registers both routes. `catalogues` returns each active organization's `routes` catalogue (or a
// status when its bus did not answer); `harnesses` lists the installed harness modules.
export function triageRouteRoutes({ dataRoot, catalogues, harnesses = installedHarnesses, log = () => {} }) {
// proxy-scope slice 4: `access`, when given, is the Triage key's side:
// state() the key file's state (triage-access.mjs keyState), never the key
// riding() async -> true when one organization rides the owner's models
// key(op) async -> triageKeyCall's answer for op ensure or revoke, through one riding bus
// stop() async -> stops a running Triage session (the host's stop)
// A route save with no key held runs ensure once; POST /api/triage/access runs Repair access
// (ensure) or Turn Triage off (stop, then revoke). With no access, neither happens.
export function triageRouteRoutes({ dataRoot, catalogues, harnesses = installedHarnesses, log = () => {}, access = null }) {
const accessNow = async () => {
if (!access) return undefined;
let state;
try { state = access.state(); } catch { state = { key: 'unsafe' }; }
let riding = false;
try { riding = (await access.riding()) === true; } catch { riding = false; }
return accessStatus(state, { riding });
};
const keyStep = async op => {
try { return await access.key(op); } catch { return { ok: false, code: 'outcome-unknown' }; }
};
async function catalogue() {
let list;
try { list = await catalogues(); } catch { list = []; }
@@ -222,9 +254,11 @@ export function triageRouteRoutes({ dataRoot, catalogues, harnesses = installedH
let doc;
try { doc = readRoute(dataRoot); } catch (error) { return refuse(error?.code === 'triage-route-unreadable' ? 'triage-route-unreadable' : 'outcome-unknown'); }
const route = view(doc);
const status = await accessNow();
return done(200, {
route, ...(route ? {} : { routeMessage: NOT_SET_MESSAGE }), revision: route ? route.revision : 0,
choices: choices(await catalogue()), send: context.send === true, note: NOT_STARTED_NOTE,
...(status ? { access: status } : {}),
});
}
if (context.send !== true) return refuse('read-only');
@@ -247,7 +281,17 @@ export function triageRouteRoutes({ dataRoot, catalogues, harnesses = installedH
if (by === null) return refuse('human-required');
try {
const doc = writeRoute(dataRoot, { model, harness, limit: cap, timeZone: zone, by, revision });
return done(200, { route: view(doc), revision: doc.revision, note: NOT_STARTED_NOTE });
// proxy-scope slice 4: the owner's first save (the one that creates the route, at revision 0),
// with no key held, asks a riding bus for one. A later save never does: after Turn Triage off
// only Repair access brings a key back. A key that is not issued leaves the route saved; the
// answer says why.
let key;
if (access && revision === 0) {
let state;
try { state = access.state(); } catch { state = { key: 'unsafe' }; }
if (state.key === 'missing') key = keyView(await keyStep('ensure'));
}
return done(200, { route: view(doc), revision: doc.revision, note: NOT_STARTED_NOTE, ...(key ? { key } : {}) });
} catch (error) {
const code = typeof error?.code === 'string' && Object.hasOwn(MESSAGES, error.code) && error.code.startsWith('triage-route-') ? error.code : 'outcome-unknown';
if (code !== 'triage-route-stale') return refuse(code);
@@ -256,7 +300,40 @@ export function triageRouteRoutes({ dataRoot, catalogues, harnesses = installedH
return refuse(code, { revision: stored ? stored.revision : 0 });
}
}
// POST /api/triage/access { op: 'repair' | 'off' }: the owner's Repair access and Turn Triage off.
async function handleAccess(req, res, context) {
const done = (status, value) => {
log(`${new Date().toISOString()} ${req.method} ${TRIAGE_ACCESS_PATH} ${status}`);
return json(res, status, value);
};
const refuse = code => done(STATUS[code] ?? 503, { error: code, message: MESSAGES[code] ?? MESSAGES['outcome-unknown'] });
if (req.method !== 'POST') return refuse('method-not-allowed');
if (context.owner !== true || !context.session) return refuse('human-required');
if (one(req, 'origin') !== context.origin) return refuse('cross-origin');
if (one(req, 'sec-fetch-site') !== 'same-origin') return refuse('cross-site');
if (context.send !== true) return refuse('read-only');
if (!access) return refuse('outcome-unknown');
let op;
try {
if ((req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase() !== 'application/json') throw Error();
const chunks = []; let size = 0;
for await (const chunk of req) { size += chunk.length; if (size > BODY_MAX) throw Error(); chunks.push(chunk); }
const body = JSON.parse(Buffer.concat(chunks));
if (!plain(body) || Object.keys(body).length !== 1 || !ACCESS_OPS.includes(body.op)) throw Error();
op = body.op;
} catch { return done(400, { error: 'invalid-request', message: 'The request takes op, repair or off.' }); }
if (op === 'off') {
// The session stops first, so nothing runs on a key while it is removed.
try { await access.stop(); } catch { log('triage access: the session stop failed'); }
}
const result = await keyStep(op === 'repair' ? 'ensure' : 'revoke');
const key = keyView(result);
const status = await accessNow();
if (result?.ok === true) return done(200, { op, key, access: status });
return done(STATUS[result?.code] ?? 502, { op, ...key, key, access: status });
}
return registered => {
registered.add('POST', TRIAGE_ACCESS_PATH, handleAccess);
registered.add('GET', TRIAGE_ROUTE_PATH, handle);
registered.add('POST', TRIAGE_ROUTE_PATH, handle);
};
+63 -26
View File
@@ -1,22 +1,27 @@
// #1873 triage-wiring: the Triage host's model route, resolved again at each admit (design report
// reports/triage-route-design.md slice 5). Four sources, each read fresh:
// the route store harness name, model key and cap (triage-route-store.mjs)
// the key file <configDir>/secrets/triage/model (packages/cli/src/triage-key-file.mjs, the
// the key file <configDir>/secrets/triage/model (packages/bus/src/triage-key-file.mjs, the
// key verbs' own reader and checks; never the module that holds the proxy client)
// the model catalogue model and provider for the key, read from each active organization's bus
// `routes` verb and merged (mergeCatalogues), then held to checkRoutes, the
// check an organization's route change runs: offered, available, compatible
// the harness module adapter, turnEnd, mounts and harnessEnv (packages/plugins/harness/<name>)
// proxy.json the proxy's port, read at each admit (proxyPort may be a function)
// The answer's env holds only ANTHROPIC_BASE_URL (the instance proxy on 127.0.0.1) and
// ANTHROPIC_AUTH_TOKEN (the Triage key). harnessEnv holds only the module's own names that the host's
// fence takes (refusedHarnessName): no MOSAIC_* name, which the host sets itself from the module's
// bundle() and env() (triage-host.mjs). A harness runs Triage only when it has bundle() and env() and
// takes the proxy through exactly those two variables: env() given a stand-in proxy must answer the
// stand-in's URL as ANTHROPIC_BASE_URL and its key as ANTHROPIC_AUTH_TOKEN, and put that key nowhere
// else. pi takes its proxy through its own models.json and ANTHROPIC_API_KEY, so it is refused with
// triage-harness-incompatible. The host runs its fences on every answer (triage-host.mjs
// checkAdmitted), so nothing here is trusted on its own.
// the provider module the route's transport for this harness (packages/plugins/model-provider/
// <module>, route()), the check a bus launch runs: a model the provider holds
// off the harness (an OAuth Claude model on pi) is triage-harness-incompatible
// The answer's env holds ANTHROPIC_BASE_URL (the instance proxy on 127.0.0.1) and the Triage key
// under the one name the harness takes it by (ROUTE_KEY_NAMES: claude-code's ANTHROPIC_AUTH_TOKEN,
// pi's ANTHROPIC_API_KEY). harnessEnv holds only the module's own names that the host's fence takes
// (refusedHarnessName): no MOSAIC_* name, which the host sets itself from the module's bundle() and
// env() (triage-host.mjs). #1873 harness-matrix: a harness runs Triage when it has bundle() and env()
// and meets one contract, with no list of harness names: env() given a stand-in proxy puts the
// stand-in's key, unchanged, in exactly one ROUTE_KEY_NAMES name and nowhere else, and names the
// stand-in's URL only as ANTHROPIC_BASE_URL, if at all. A harness that takes the URL through its own
// file (pi's models.json) is held to that at the host, which checks the file bundle() writes. The
// host runs its fences on every answer (triage-host.mjs checkAdmitted), so nothing here is trusted
// on its own.
//
// Each refusal is a code from ROUTE_REFUSALS (triage-host.mjs) with a fixed plain line. No code or line carries a path,
// a key or an env value. Whether the key is in the proxy's list cannot be known without the proxy
@@ -27,13 +32,15 @@ import { lstatSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { checkRoutes } from "../../organization/src/launch-settings.mjs";
import { SECRET, keyPrefix, readKey } from "../../cli/src/triage-key-file.mjs";
import { SECRET, keyPrefix, readKey } from "../../bus/src/triage-key-file.mjs";
import { readRoute } from "./triage-route-store.mjs";
import { ROUTE_REFUSALS, refusedHarnessName } from "./triage-host.mjs";
import { ROUTE_KEY_NAMES, ROUTE_REFUSALS, refusedHarnessName } from "./triage-host.mjs";
import { checkedTransport } from "../../harness/src/bundle.mjs";
export { ROUTE_REFUSALS };
const HARNESS_ROOT = fileURLToPath(new URL("../../plugins/harness/", import.meta.url));
const PROVIDER_ROOT = fileURLToPath(new URL("../../plugins/model-provider/", import.meta.url));
const HARNESS_NAME = /^[a-z][a-z0-9-]{0,31}$/;
const MODEL_KEY = /^[a-z0-9][a-z0-9._-]{0,63}$/;
export const PROBE_TIMEOUT_MS = 1000;
@@ -41,10 +48,17 @@ export const PROBE_TIMEOUT_MS = 1000;
const refuse = (code) => ({ ok: false, code });
// The stand-in proxy env() is asked about. Neither value is a real URL or key.
const PROXY_PROBE = Object.freeze({ baseUrl: "http://127.0.0.1:9", key: "triage-route-probe-key" });
// True when env(), given the stand-in proxy, puts it in the two route variables and nowhere else.
const takesRouteProxy = (given) => plain(given)
&& given.ANTHROPIC_BASE_URL === PROXY_PROBE.baseUrl && given.ANTHROPIC_AUTH_TOKEN === PROXY_PROBE.key
&& Object.entries(given).every(([k, v]) => k === "ANTHROPIC_AUTH_TOKEN" || !String(v).includes(PROXY_PROBE.key));
// The name env(), given the stand-in proxy, takes the key by, or null. The key goes unchanged into
// exactly one ROUTE_KEY_NAMES name and is in no other value; the URL is in no value but
// ANTHROPIC_BASE_URL, which, when present, is the stand-in's URL.
export const routeKeyName = (given) => {
if (!plain(given)) return null;
const holders = Object.entries(given).filter(([, v]) => String(v).includes(PROXY_PROBE.key));
if (holders.length !== 1 || !ROUTE_KEY_NAMES.includes(holders[0][0]) || holders[0][1] !== PROXY_PROBE.key) return null;
if (given.ANTHROPIC_BASE_URL !== undefined && given.ANTHROPIC_BASE_URL !== PROXY_PROBE.baseUrl) return null;
if (Object.entries(given).some(([k, v]) => k !== "ANTHROPIC_BASE_URL" && String(v).includes(PROXY_PROBE.baseUrl))) return null;
return holders[0][0];
};
const validPort = (p) => Number.isInteger(p) && p > 0 && p <= 65535;
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const identity = (m) => JSON.stringify([m.provider, m.model, m.module, m.upstream]);
@@ -69,6 +83,14 @@ export async function repoHarnessModule(name, root = HARNESS_ROOT) {
return import(pathToFileURL(file).href);
}
// The repository's model-provider module of that name, or null.
export async function repoProviderModule(name, root = PROVIDER_ROOT) {
if (!HARNESS_NAME.test(name ?? "")) return null;
const file = join(root, name, "index.mjs");
try { if (!lstatSync(file).isFile()) return null; } catch { return null; }
return import(pathToFileURL(file).href);
}
// Each active organization's catalogue, merged into one. Only ready answers count. A key is offered
// when a ready catalogue lists it, and dropped when two disagree on what it is (provider, model,
// module, upstream). It is available only when every catalogue listing it says so, and its harnesses
@@ -137,17 +159,18 @@ export function checkModel({ model, harness, catalogue, harnesses }) {
}
}
// createTriageRoute({ dataRoot, configDir, proxyPort, catalogues, harnessModule, probe, env, installed })
// createTriageRoute({ dataRoot, configDir, proxyPort, catalogues, harnessModule, providerModule, probe, env, installed })
// proxyPort the instance proxy's port (proxy.json), or null when none is configured; or a
// function that answers it, called at each admit
// catalogues async () -> [catalogue] each active organization's `routes` catalogue
// harnessModule async (name) -> the harness module or null; the repository's by default
// providerModule async (name) -> the model-provider module or null; the repository's by default
// probe async (port) -> true when the proxy accepts a connection
// env the Console's environment, for the module's mounts (MOSAIC_CLAUDE_BIN)
// installed () -> the installed harness names
// Returns { isSet(), admit() }. isSet answers whether a route is stored (an unreadable store counts
// as set, so the read does not hide it; admit refuses it).
export function createTriageRoute({ dataRoot, configDir, proxyPort = null, catalogues = async () => [], harnessModule = repoHarnessModule, probe = probePort, env = process.env, installed = installedHarnesses, keyOptions = {} }) {
export function createTriageRoute({ dataRoot, configDir, proxyPort = null, catalogues = async () => [], harnessModule = repoHarnessModule, providerModule = repoProviderModule, probe = probePort, env = process.env, installed = installedHarnesses, keyOptions = {} }) {
if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TypeError("dataRoot must be an absolute path");
if (typeof configDir !== "string" || !configDir.startsWith("/")) throw new TypeError("configDir must be an absolute path");
if (proxyPort !== null && typeof proxyPort !== "function" && !validPort(proxyPort)) throw new TypeError("proxyPort must be a port number, null or a function");
@@ -180,28 +203,42 @@ export function createTriageRoute({ dataRoot, configDir, proxyPort = null, catal
const failed = checkModel({ model: stored.model, harness: stored.harness, catalogue, harnesses });
if (failed) return refuse(failed);
const offered = catalogue.models.find((m) => m.key === stored.model);
// #1873 harness-matrix: the provider's own route for this harness, as a bus launch asks it, so
// a stale catalogue row that names a harness the provider now holds the model off is refused.
// A provider with no route() gives no transport; a harness that needs one then fails below.
let transport = null;
let provider = null;
try { provider = await providerModule(offered.module); } catch { provider = null; }
if (typeof provider?.route === "function") {
const entry = { provider: offered.provider, model: offered.model, module: offered.module, upstream: offered.upstream };
try { transport = checkedTransport(entry, stored.harness, provider.route); }
catch (e) { return refuse(e?.code === "model-harness-incompatible" ? "triage-harness-incompatible" : "triage-model-not-offered"); }
}
// 5. The harness module's own answers.
let mod = null;
try { mod = await harnessModule(stored.harness); } catch { mod = null; }
if (!mod || typeof mod.adapter !== "function" || typeof mod.turnEnd !== "function" || !Array.isArray(mod.envNames)
|| typeof mod.bundle !== "function" || typeof mod.env !== "function") return refuse("triage-harness-incompatible");
let adapter, turnEnd, harnessMounts, harnessEnv;
let adapter, turnEnd, harnessMounts, harnessEnv, keyName;
try {
adapter = mod.adapter();
turnEnd = mod.turnEnd();
harnessMounts = typeof mod.mounts === "function" ? mod.mounts({ env }) : [];
// The module's env() for this model, less every name the host's fence refuses (MOSAIC_*
// among them: the host sets those) and every name the module does not declare.
const session = { model: offered.model, provider: offered.provider ?? "" };
const given = mod.env({ files: {}, policy: { tools: [] }, tools: [], session, models: {}, proxy: null });
harnessEnv = Object.fromEntries(Object.entries(plain(given) ? given : {})
// The module's env() for this model and the stand-in proxy, held to the contract, less every
// name the host's fence refuses (MOSAIC_* and ANTHROPIC_* among them: the host sets those)
// and every name the module does not declare.
const session = { model: offered.model, provider: offered.provider ?? "", ...(transport ? { proxyTransport: { ...transport } } : {}) };
const given = mod.env({ files: {}, policy: { tools: [] }, tools: [], session, models: {}, proxy: { ...PROXY_PROBE } });
keyName = routeKeyName(given);
if (!keyName) return refuse("triage-harness-incompatible");
harnessEnv = Object.fromEntries(Object.entries(given)
.filter(([k, v]) => mod.envNames.includes(k) && !refusedHarnessName(k) && typeof v === "string"));
if (!takesRouteProxy(mod.env({ files: {}, policy: { tools: [] }, tools: [], session, models: {}, proxy: { ...PROXY_PROBE } }))) return refuse("triage-harness-incompatible");
} catch { return refuse("triage-harness-incompatible"); }
return {
ok: true, harness: stored.harness, adapter, turnEnd, harnessMounts, harnessEnv,
model: offered.model, provider: offered.provider ?? "",
env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`, ANTHROPIC_AUTH_TOKEN: record.key },
...(transport ? { transport } : {}),
env: { ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`, [keyName]: record.key },
};
},
};
@@ -125,7 +125,7 @@ test('both drafts survive a refresh render and the other form\'s save; a draft k
assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#agent-levels-root-form .filters")).display'), 'grid', 'the level forms keep the Settings form layout');
await type(b, 'agent-levels-root-form', { name: 'drafted', vars: 'limits.network=none' });
await type(b, 'agent-levels-project-form', { name: 'helper', form: 'narrow', vars: 'limits.tools=read' });
assert.equal(await b.evaluate('!!document.querySelector("#settings-nav a[href$=\'settings/agents\'] .settings-dot")'), true, 'the nav marks unsaved changes');
assert.equal(await b.evaluate('!!document.querySelector("#settings-nav a[href^=\'#/settings/agents\'] .settings-dot")'), true, 'the nav marks unsaved changes');
// A full Settings render, as the ten-second poll does: the edit box is a new node, the drafts are in it.
await b.evaluate('document.getElementById("agent-levels-edit").dataset.old = "1"; document.getElementById("refresh").click()');
await wait('document.getElementById("agent-levels-edit") && !document.getElementById("agent-levels-edit").dataset.old');
+3 -3
View File
@@ -303,12 +303,12 @@ const startWith=async err=>{
assert.equal(s.calls.length,1,'one bus call, never retried');
return {r,s};
};
test('D4 hire start: model-provider-unavailable keeps its code and names Settings > Model proxy',async()=>{
test('D4 hire start: model-provider-unavailable keeps its code and names Settings > Model setup',async()=>{
const {r,s}=await startWith(new BusReadError('model-provider-unavailable'));
assert.equal(r.status,409,r.text);
const body=r.json();
assert.equal(body.error,'model-provider-unavailable');
assert.match(body.message,/Settings > Model proxy/);
assert.match(body.message,/Settings > Model setup/);
assert.match(body.message,/Nothing was applied/);
assert.equal(r.headers['cache-control'],'no-store');
assert.match(s.lines.at(-1),/step=start error=model-provider-unavailable$/);
@@ -373,7 +373,7 @@ test('E2E6 hire start: an apply-phase decision-stale on a fire does not say noth
});
test('E2E6 hire start: invalid-request from the bus says the values, not the shape, were refused',async()=>{
const {r}=await startWith(new BusReadError('invalid-request'));
assert.equal(r.status,400);assert.equal(r.json().error,'invalid-request');assert.match(r.json().message,/Settings > Model proxy/);
assert.equal(r.status,400);assert.equal(r.json().error,'invalid-request');assert.match(r.json().message,/Settings > Routing/);
});
test('E2E6 hire start: the bus server request codes and organization-uncertain stay outcome-unknown',async()=>{
for(const code of ['revision-conflict-revoked','request-timeout','invalid-envelope','incomplete-request','organization-uncertain'])
@@ -89,7 +89,7 @@ for (const [width, height] of [[1440, 900], [390, 844]]) test(`D4 the org-mode i
await b.evaluate('document.querySelector("#hire-start-form").requestSubmit()');
await wait('document.querySelector("#hire-start-status code")');
assert.equal(await text('#hire-start-status code'), 'model-provider-unavailable');
assert.match(await text('#hire-start-status'), /Settings > Model proxy/);
assert.match(await text('#hire-start-status'), /Settings > Model setup/);
assert.doesNotMatch(await text('#hire-start-status'), /may have reached the bus/);
const start = calls.filter(c => c.verb === 'hire.start.console');
assert.equal(start.length, 1, 'one start, never retried');
@@ -155,7 +155,7 @@ test('D4 a hire answer that arrives during a slow inbox read keeps its status af
release();
await wait('document.querySelector("[data-ws-inbox]") !== window.__marker && document.querySelector("#hire-start-form")');
assert.equal(await b.evaluate('document.querySelector("#hire-start-status code")?.textContent ?? null'), 'model-provider-unavailable');
assert.match(await b.evaluate('document.querySelector("#hire-start-status").innerText'), /Settings > Model proxy/);
assert.match(await b.evaluate('document.querySelector("#hire-start-status").innerText'), /Settings > Model setup/);
assert.equal(calls.filter(c => c.verb === 'hire.start.console').length, 1);
});
@@ -145,7 +145,8 @@ test('sidebar lists organizations and navigating changes the route and header',
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelectorAll('[data-workspace-org]').length===2 && document.querySelector('#settings-page-title'))return;await new Promise(r=>setTimeout(r,30))}throw Error('Organizations did not appear')})()`);
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent==='Alpha')return;await new Promise(r=>setTimeout(r,30))}throw Error('organization crumb missing')})()`);
assert.equal(await b.evaluate(`document.querySelector('#current-organization')`), null, 'the header does not name an organization');
assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization');
// settings slice 4: the page's nav label and title is Organization file.
assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization file');
await b.evaluate('window.__sameDocument = true');
assert.equal(await b.evaluate(`!!document.querySelector('#org-picker')`), false);
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-workspace-org]')].map(o=>o.dataset.workspaceOrg)`), ['alpha', 'beta']);
@@ -194,7 +195,8 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy
await b.evaluate(`document.querySelector('[data-workspace-org=beta] a').click()`);
await wait('!!document.querySelector("dialog[open] [data-stay]")');
await b.evaluate(`document.querySelector('[data-stay]').click()`);
assert.match(await b.evaluate('location.hash'), /^#\/orgs\/alpha\//);
// settings slice 4: an organization's Settings page names it with ?org=.
assert.equal(await b.evaluate('location.hash'), '#/settings/business?org=alpha');
assert.equal(await b.evaluate(`window.MosaicOrg.id`), 'alpha');
await b.evaluate(`location.hash='#/chat/threads/${thread}'`);
await wait('!!document.querySelector("#chat-body")');
@@ -204,7 +206,8 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy
await b.evaluate(`document.querySelector('[data-discard]').click()`).catch(() => {});
let switched = false;
for (let i = 0; i < 150 && !switched; i++) {
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Beta'`); } catch {}
// settings slice 4: the old address lands on the organization's Settings page with ?org=, and its crumb names it.
try { switched = await b.evaluate(`location.hash === '#/settings/business?org=beta' && document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Beta'`); } catch {}
if (!switched) await new Promise(r => setTimeout(r, 30));
}
assert.equal(switched, true);
+185 -3
View File
@@ -3,7 +3,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { request } from 'node:http';
import { mkdtempSync, rmSync } from 'node:fs';
import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startServer } from '../src/serve.mjs';
@@ -20,7 +20,10 @@ const ROUTES = [
['fence/clear', 'POST', {}], ['init-lock/clear', 'POST', {}],
// #1873 ride-default: Ride all, and the move of one stopped fixture organization.
['ride-all', 'POST', {}], ['ride-move', 'POST', { org: 'stand-in' }],
// #1873 settings-backend A1: the model service log, the service key's made-at time, setup history.
['log', 'GET'], ['service-key', 'GET'], ['history', 'GET'],
];
const READS = ROUTES.filter(([p]) => ['log', 'service-key', 'history'].includes(p));
function fakeAdmin() {
const calls = [];
@@ -33,6 +36,10 @@ function fakeAdmin() {
fetchStart: () => { calls.push(['fetchStart']); return { state: 'running' }; },
init: async (call, args) => { calls.push(['init', args]); await call('proxy.init', args); return { settings: { port: 18432 }, receipt: { op: 'init' } }; },
fenceClear: async call => { calls.push(['fenceClear']); return call('proxy.fence.clear', { evidence: {} }); },
log: async args => { calls.push(['log', args]); return { unit: 'mosaic-proxy.service', lines: ['ok'], redacted: 0, dropped: 0 }; },
serviceKey: () => { calls.push(['serviceKey']); return { madeAt: '2026-11-01T08:00:00.000Z', renewedAt: null, renewal: 'not-built', problem: null }; },
history: args => { calls.push(['history', args]); return { entries: [], next: null }; },
recordAccount: entry => { calls.push(['recordAccount', entry]); return true; },
};
}
const send = (port, path, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve, reject) => {
@@ -54,7 +61,7 @@ async function devServer(t, options = {}) {
}
const hit = (f, route, extra = {}) => send(f.port, `/api/proxy/admin/${route[0]}`, { method: route[1], headers: { ...f.headers(), ...extra }, body: route[2] });
test('the route table is exactly the brief: status, render, fetch, init, four unit verbs, fence clear, lock clear, ride all, ride move', () => {
test('the route table is exactly the brief: status, render, fetch, init, four unit verbs, fence clear, lock clear, ride all, ride move, log, service key, history', () => {
assert.deepEqual(PROXY_ADMIN_PATHS, ROUTES.map(([p]) => `/api/proxy/admin/${p}`));
});
@@ -64,7 +71,7 @@ test('the dev local owner reaches every route; init and fence clear go to the bu
const r = await hit(f, route);
assert.equal(r.status, route[0] === 'fetch' ? 202 : 200, route[0]);
}
assert.deepEqual(f.admin.calls.map(c => c[0]), ['status', 'render', 'fetchStart', 'init', 'unitAction', 'unitAction', 'unitAction', 'unitAction', 'fenceClear', 'initLockClear', 'rideAll', 'rideMove']);
assert.deepEqual(f.admin.calls.map(c => c[0]), ['status', 'render', 'fetchStart', 'init', 'unitAction', 'unitAction', 'unitAction', 'unitAction', 'fenceClear', 'initLockClear', 'rideAll', 'rideMove', 'log', 'serviceKey', 'history']);
assert.deepEqual(f.admin.calls.filter(c => c[0] === 'unitAction').map(c => c[1]), ['install', 'start', 'stop', 'restart']);
assert.deepEqual(f.busCalls.map(c => c[0]), ['proxy.init', 'proxy.fence.clear']);
assert.deepEqual(f.busCalls[0][1], { generate: true });
@@ -207,6 +214,18 @@ test('an organization whose bus does not answer shows no model count, not a made
assert.deepEqual(await orgCatalogue(async () => ({ catalogue: { status: 'enabled', models: [] } })), { status: 'enabled', models: 0 });
});
// settings-p3 (re-check 3 P3-5): a ready catalogue the bus picked up after it started carries the bus's
// restart notice; Model setup gets launchRestart so it keeps that organization listed. The notice text is
// copied from packages/bus/src/runtime.mjs (not exported there); the pins below fail if the copies drift.
test('a ready catalogue with the bus restart notice is marked launchRestart, and every copy of the notice matches the bus', async () => {
const notice = 'Restart this organization to start agents on these models.';
assert.deepEqual(await orgCatalogue(async () => ({ catalogue: { status: 'ready', models: [{ id: 'a' }], notices: [notice] } })), { status: 'ready', models: 1, launchRestart: true });
assert.deepEqual(await orgCatalogue(async () => ({ catalogue: { status: 'ready', models: [{ id: 'a' }], notices: ['something else'] } })), { status: 'ready', models: 1 });
assert.deepEqual(await orgCatalogue(async () => ({ catalogue: { status: 'unavailable', models: [], notices: [notice] } })), { status: 'unavailable', models: 0 });
for (const file of ['../../bus/src/runtime.mjs', '../src/proxy-admin.mjs', '../src/public/console-restart.js'])
assert.ok(readFileSync(new URL(file, import.meta.url), 'utf8').includes(`RESTART_TO_LAUNCH = '${notice}'`), file);
});
test('ride move takes one organization id and passes the signed-in owner as the principal', async t => {
const f = await devServer(t);
for (const body of [{}, { org: '' }, { org: '../x' }, { org: 'A' }, { org: 7 }, { org: 'x', extra: 1 }])
@@ -233,3 +252,166 @@ test('a signed-in member who is not the instance owner gets human-required for r
}
assert.deepEqual(member.admin.calls, []);
});
// #1873 settings-backend A1: the three reads. Query keys are each read's own, once each, plain
// decimal numbers; the controller clamps the values.
test('the reads pass their query to the controller and refuse an unknown, repeated or non-number key', async t => {
const f = await devServer(t);
const get = path => send(f.port, path, { headers: f.headers() });
assert.equal((await get('/api/proxy/admin/log')).status, 200);
assert.equal((await get('/api/proxy/admin/log?lines=1000')).status, 200);
assert.equal((await get('/api/proxy/admin/history')).status, 200);
assert.equal((await get('/api/proxy/admin/history?limit=1000&before=4096')).status, 200);
assert.equal((await get('/api/proxy/admin/service-key')).status, 200);
assert.deepEqual(f.admin.calls, [['log', {}], ['log', { lines: 1000 }], ['history', { before: null }], ['history', { limit: 1000, before: 4096 }], ['serviceKey']]);
f.admin.calls.length = 0;
for (const path of ['/api/proxy/admin/log?lines=-1', '/api/proxy/admin/log?lines=1.5', '/api/proxy/admin/log?lines=', '/api/proxy/admin/log?lines=1e3', '/api/proxy/admin/log?lines=5&lines=6',
'/api/proxy/admin/log?limit=5', '/api/proxy/admin/log?unit=sshd.service', '/api/proxy/admin/log?lines=0x10', '/api/proxy/admin/log?lines=1234567890123456',
'/api/proxy/admin/history?before=abc', '/api/proxy/admin/history?lines=5', '/api/proxy/admin/history?limit=5&limit=6', '/api/proxy/admin/service-key?x=1', '/api/proxy/admin/service-key?key']) {
const r = await get(path);
assert.equal(r.status, 400, path); assert.deepEqual(r.json, { error: 'invalid-request' }, path);
}
assert.deepEqual(f.admin.calls, []);
for (const route of READS) assert.equal((await send(f.port, `/api/proxy/admin/${route[0]}`, { method: 'POST', headers: f.headers(), body: {} })).status, 405, route[0]);
});
test('a read the controller cannot answer reaches the page as its code only', async t => {
const f = await devServer(t);
f.admin.log = async () => { throw Object.assign(new Error(`${SENTINEL} journal said /home/owner/x`), { code: 'outcome-unknown' }); };
f.admin.history = () => { throw Object.assign(new Error(SENTINEL), { code: 'invalid-request' }); };
f.admin.serviceKey = () => { throw new Error(SENTINEL); };
assert.deepEqual((await hit(f, ['log', 'GET'])).json, { error: 'outcome-unknown' });
assert.equal((await hit(f, ['log', 'GET'])).status, 503);
assert.deepEqual((await hit(f, ['history', 'GET'])).json, { error: 'invalid-request' });
assert.deepEqual((await hit(f, ['service-key', 'GET'])).json, { error: 'outcome-unknown' });
f.admin.log = async () => { throw Object.assign(new Error('x'), { code: 'not-configured' }); };
assert.deepEqual((await hit(f, ['log', 'GET'])).json, { error: 'not-configured' });
assert.equal(f.logs.join('\n').includes(SENTINEL), false);
});
test('a member, an organization owner and a request on a name that is not the Console\'s get refused on every read', async t => {
const organizations = { list: async () => [], resolve: async id => (id === 'x' ? { busHealthy: true } : null) };
for (const session of [{ name: 'Bob', provider: 'local-dev', iss: 'local-dev', sub: 'bob', rootOwner: false, instanceRole: 'member' },
{ name: 'Olive', provider: 'local-dev', iss: 'local-dev', sub: 'olive', rootOwner: false, instanceRole: 'operator', orgRole: 'owner' }]) {
const f = await devServer(t, { organizations, sso: { ...createDevOwner(), session: () => session } });
for (const route of READS) {
const inOrg = await send(f.port, `/api/orgs/x/proxy/admin/${route[0]}?lines=5`.replace(/\?lines=5$/, ''), { headers: f.headers() });
assert.equal(inOrg.status, 403, `${session.sub} ${route[0]}`); assert.deepEqual(inOrg.json, { error: 'human-required' }, `${session.sub} ${route[0]}`);
const bad = await send(f.port, `/api/orgs/x/proxy/admin/${route[0]}?nope=1`, { headers: f.headers() });
assert.deepEqual(bad.json, { error: 'human-required' }, 'the caller is checked before the query');
const plain = await hit(f, route);
assert.equal(plain.status >= 400 && plain.status < 500, true, `${route[0]} outside an organization is refused`);
}
assert.deepEqual(f.admin.calls, []);
}
const f = await devServer(t);
for (const route of READS) {
const r = await send(f.port, `/api/proxy/admin/${route[0]}`, { headers: { host: 'console.evil.example' } });
assert.equal(r.status, 403, route[0]);
}
assert.deepEqual(f.admin.calls, []);
});
// The real controller over a scratch config and data root with keys planted in proxy.json, the
// management key file, the receipt history and the journal: none reaches an answer.
test('end to end with the real controller, no planted key reaches any read', async t => {
const { createProxyAdmin } = await import('../../model-proxy/src/admin-control.mjs');
const { initFiles, appendReceipt } = await import('../../model-proxy/src/admin.mjs');
const root = mkdtempSync(join(tmpdir(), 'pa-a1-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
const files = initFiles(configDir, dataRoot);
const TAIL = 'Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE';
const planted = ['msk-tag-qwertyu', 'mso-tag-acme-qwerty', 'mst-tag-triage-zxcvb', 'msp-tag-plmokn', `msk-k1a2-${TAIL}`, `mso-k1a2-acme-${TAIL}`, `mst-k1a2-triage-${TAIL}`, `msp-k1a2-${TAIL}`];
const { mkdirSync, writeFileSync } = await import('node:fs');
mkdirSync(join(configDir, 'secrets'), { recursive: true, mode: 0o700 }); mkdirSync(dataRoot, { mode: 0o700 });
writeFileSync(files.settings, JSON.stringify({ port: 18432, note: planted[0] }), { mode: 0o600 });
writeFileSync(files.key, planted[4], { mode: 0o600 });
for (const key of planted) appendReceipt(dataRoot, { time: new Date(0).toISOString(), op: 'init', note: `key ${key}`, [key.replace(/-/g, '_')]: key });
const journalCalls = [];
const unit = {
unit: 'mosaic-proxy-zz.service',
status: async () => ({ unit: 'mosaic-proxy-zz.service', installed: true, active: 'active', healthy: true }),
log: async (lines, options) => {
const { unitLog } = await import('../../model-proxy/src/admin.mjs');
return unitLog({ run: async (command, args) => { journalCalls.push([command, ...args]); return { code: 0, stdout: [...planted.map(k => `refused ${k}`), 'auth plainwordsonly', 'served 3 requests'].join('\n') + '\n' }; }, unit: 'mosaic-proxy-zz.service', lines, secrets: options.secrets });
},
};
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: async () => ({ stopped: true, running: [] }), env: { MOSAIC_PROXY_TOKEN: 'plainwordsonly' } });
const f = await devServer(t, { proxyAdmin: admin });
const answers = [];
for (const path of ['log', 'log?lines=1000', 'service-key', 'history', 'history?limit=2']) {
const r = await send(f.port, `/api/proxy/admin/${path}`, { headers: f.headers() });
assert.equal(r.status, 200, path);
answers.push(r.text);
}
const all = answers.join('\n') + f.logs.join('\n');
for (const bit of [...planted, ...planted.map(k => k.slice(4)), TAIL.slice(0, 10), 'plainwordsonly', root]) assert.equal(all.includes(bit), false, bit);
const log = JSON.parse(answers[0]);
assert.deepEqual(log.lines.slice(-1), ['served 3 requests']);
assert.equal(log.lines.length, planted.length + 1);
assert.equal(log.dropped, 1);
assert.deepEqual(journalCalls[1].slice(4, 6), ['-n', '200']);
const key = JSON.parse(answers[2]);
assert.deepEqual(Object.keys(key), ['madeAt', 'renewedAt', 'renewal', 'problem']);
assert.equal(key.problem, null); assert.equal(key.renewal, 'not-built');
const first = JSON.parse(answers[4]);
assert.equal(first.entries.length, 2);
const rest = await send(f.port, `/api/proxy/admin/history?limit=100&before=${first.next}`, { headers: f.headers() });
assert.equal(rest.json.entries.length, planted.length - 2);
assert.equal(rest.json.next, null);
assert.equal(rest.text.includes('qwerty'), false);
});
// Account changes made outside the setup page join its history. The bus call's answer is unchanged;
// a record that fails adds recorded: false and still answers the bus's result.
test('an account write through /api/proxy/* records a labelled entry; reads and login steps record nothing', async t => {
const f = await devServer(t);
const post = (path, body) => send(f.port, path, { method: 'POST', headers: f.headers(), body });
f.busCalls.length = 0;
const added = await post('/api/proxy/apikey/add', { provider: 'openai', key: SENTINEL });
assert.equal(added.status, 200);
assert.deepEqual(added.json, { cleared: true }, 'the bus answer is passed through as it was');
await post('/api/proxy/login/start', { provider: 'openai' });
await send(f.port, '/api/proxy/accounts', { headers: f.headers() });
const records = f.admin.calls.filter(c => c[0] === 'recordAccount').map(c => c[1]);
assert.deepEqual(records.map(r => r.verb), ['proxy.apikey.add', 'proxy.login.start']);
assert.deepEqual(records[0], { verb: 'proxy.apikey.add', args: { provider: 'openai', key: SENTINEL }, result: { cleared: true }, user: 'Local operator', org: null });
f.admin.recordAccount = () => false;
const unrecorded = await post('/api/proxy/apikey/add', { provider: 'openai', key: SENTINEL });
assert.deepEqual(unrecorded.json, { cleared: true, recorded: false });
f.admin.recordAccount = () => { throw new Error(SENTINEL); };
const thrown = await post('/api/proxy/apikey/add', { provider: 'openai', key: SENTINEL });
assert.deepEqual(thrown.json, { cleared: true, recorded: false });
f.admin.recordAccount = () => null;
assert.deepEqual((await post('/api/proxy/login/cancel', { state: 's' })).json, { cleared: true }, 'not an account change: nothing added');
assert.equal(f.logs.join('\n').includes(SENTINEL), false);
});
test('a refused or failed account write records nothing, and an organization route names its organization', async t => {
const f = await devServer(t, { proxyCall: async () => { throw Object.assign(new Error('x'), { code: 'provider-not-allowed' }); } });
const r = await send(f.port, '/api/proxy/apikey/add', { method: 'POST', headers: f.headers(), body: { provider: 'openai', key: SENTINEL } });
assert.equal(r.status, 400);
assert.deepEqual(f.admin.calls, []);
const organizations = { list: async () => [], resolve: async id => (id === 'acme' ? { busHealthy: true, send: async () => ({}), proxyCall: async () => ({ added: true }) } : null) };
const o = await devServer(t, { organizations });
const inOrg = await send(o.port, '/api/orgs/acme/proxy/apikey/add', { method: 'POST', headers: o.headers(), body: { provider: 'openai', key: SENTINEL } });
assert.deepEqual(inOrg.json, { added: true });
assert.deepEqual(o.admin.calls, [['recordAccount', { verb: 'proxy.apikey.add', args: { provider: 'openai', key: SENTINEL }, result: { added: true }, user: 'Local operator', org: 'acme' }]]);
});
test('a real controller records the account write without the key, and history shows it', async t => {
const { createProxyAdmin } = await import('../../model-proxy/src/admin-control.mjs');
const root = mkdtempSync(join(tmpdir(), 'pa-a1r-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const { mkdirSync } = await import('node:fs');
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
mkdirSync(configDir, { mode: 0o700 }); mkdirSync(dataRoot, { mode: 0o700 });
const admin = createProxyAdmin({ dataRoot, configDir, unit: { unit: 'mosaic-proxy-zz.service', status: async () => ({ installed: false }) }, buses: async () => ({ stopped: true, running: [] }), now: () => new Date(0), env: {} });
const f = await devServer(t, { proxyAdmin: admin, proxyCall: async () => ({ added: true }) });
const r = await send(f.port, '/api/proxy/apikey/add', { method: 'POST', headers: f.headers(), body: { provider: 'openai', key: SENTINEL } });
assert.deepEqual(r.json, { added: true });
const h = await send(f.port, '/api/proxy/admin/history', { headers: f.headers() });
assert.deepEqual(h.json, { entries: [{ time: new Date(0).toISOString(), op: 'account.proxy.apikey.add', provider: 'openai', user: 'Local operator' }], next: null });
assert.equal(readFileSync(join(dataRoot, 'state', 'proxy-admin.jsonl'), 'utf8').includes(SENTINEL), false);
});
+10 -7
View File
@@ -42,7 +42,8 @@ async function setup(t, readonly = false, refusal = null) {
await b.navigate(`http://127.0.0.1:${server.address().port}/#/settings/model-proxy`);
const wait = expression => b.evaluate(`(async()=>{for(let n=0;n<600;n++){if(${expression})return true;await new Promise(r=>setTimeout(r,25));}throw Error('proxy UI condition timed out');})()`);
await wait('window.__stubReady === true && document.readyState === "complete" && document.querySelector("#proxy-message")');
if (!refusal) await wait('document.querySelector("#proxy-message").textContent.includes("loaded")');
// The status line reads "Reading accounts…" until the accounts are painted, then empties.
if (!refusal) await wait('document.querySelector("#proxy-message").textContent==="" && document.querySelector("#proxy-accounts").children.length>0');
return { b, state, wait };
}
test('proxy browser clears write-only key immediately, sends once and renders data as text', { timeout: 60000 }, async t => {
@@ -78,21 +79,21 @@ test('proxy browser OAuth opens safely, callback wait stays pending, status ok c
test('proxy browser read-only disables account changes', { timeout: 60000 }, async t => {
const { b, state } = await setup(t, true);
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-write]")].every(e=>e.disabled)'), true);
assert.equal(await b.evaluate('document.querySelector("#proxy-accounts input").disabled'), true);
assert.equal(await b.evaluate('document.querySelector("#proxy-order input").disabled'), true);
assert.equal(state.routes.some(r => r.endsWith('/apikey/add') || r.endsWith('/login/start')), false);
});
test('proxy read refusal is visible and never reported as loaded', { timeout: 60000 }, async t => {
const { b, wait } = await setup(t, false, '/accounts');
await wait('document.querySelector("#proxy-message").textContent.includes("not configured")');
await wait('document.querySelector("#proxy-message").textContent.includes("not set up")');
assert.equal(await b.evaluate('document.querySelector("#proxy-message").textContent.includes("loaded")'), false);
});
test('proxy write refusal never reports success or exposes the submitted key', { timeout: 60000 }, async t => {
const { b, wait } = await setup(t, false, '/apikey/add');
await b.evaluate('document.querySelector("#proxy-apikey input").value="refused-secret-canary";document.querySelector("#proxy-apikey").requestSubmit();true');
await wait('document.querySelector("#proxy-message").textContent.includes("not configured")');
await wait('document.querySelector("#proxy-message").textContent.includes("not set up")');
assert.equal(await b.evaluate('document.querySelector("#proxy-message").textContent.includes("added")'), false);
assert.equal(await b.evaluate('document.documentElement.outerHTML.includes("refused-secret-canary")'), false);
assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").value'), '');
@@ -106,7 +107,9 @@ test('proxy browser saves the configured model names for a z.ai group', { timeou
assert.equal(state.routes.filter(r => r.endsWith('/group/models/set')).length, 1);
});
test('client key issued time is displayed in local time', { timeout: 60000 }, async t => {
const {b}=await setup(t);
assert.equal(await b.evaluate(`document.querySelector('#proxy-keys tr td:nth-child(4)').textContent`),await b.evaluate(`new Date('2026-11-07T02:24:02.021Z').toLocaleString()`));
test('settings-s4: Model setup shows no client keys table and reads no keys (design section 10)', { timeout: 60000 }, async t => {
const {b,state}=await setup(t);
assert.equal(await b.evaluate(`Boolean(document.querySelector('#proxy-keys, #proxy-refresh'))`),false);
assert.doesNotMatch(await b.evaluate('document.body.innerText'),/Client keys|Accounts and client keys/);
assert.equal(state.routes.some(r=>r.startsWith('/api/proxy/keys')),false);
});
+299 -52
View File
@@ -1,5 +1,7 @@
// #1873 the Proxy setup panel in a real browser: the next step is one button, init sends a
// generated-key request unless the owner pastes a key on loopback, and pasted fields are cleared.
// settings slice 4: the page is four step cards (Model service, Accounts and models, Organizations,
// Triage); one press runs fetch, init, install and start, each posted once.
import test from 'node:test';
import assert from 'node:assert/strict';
import { w15Fixture } from './w15-fixture.mjs';
@@ -22,62 +24,66 @@ const fenced = { ...base, release: fetched.release, init: { initialized: true, p
const unconfigured = { 'GET /api/proxy/accounts': { status: 503, body: { error: 'not-configured' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'not-configured' } } };
const scenario = (status, config = {}) => ({ '/api/config': { send: true, devOwner: true, proxyAdmin: true, proxyAdminSend: true, ...config }, '/api/proxy/admin/status': status, ...unconfigured });
const writes = b => b.evaluate('window.__writes.filter(w=>w.path.startsWith("/api/proxy/admin/")).map(w=>({path:w.path,body:JSON.parse(w.body)}))');
// Step 3's line names the step it holds in data-next.
const STEP3 = '#setup-step-organizations [data-step-summary]';
test('a fresh instance shows the fetch step as one button, the not-built own proxy, and no terminal note', { timeout: 90000 }, async t => {
test('a fresh instance shows Set up model service as one button, the not-built own proxy, and no terminal note', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(base), 'POST /api/proxy/admin/fetch': { status: 202, body: { state: 'running' } } } });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fetch"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup").hidden'), false);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Fetch the pinned release');
assert.match(await b.evaluate('document.querySelector("#proxy-setup-next p").textContent'), /CLIProxyAPI 8\.0\.42/);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Set up model service');
assert.equal(await b.evaluate('document.querySelector("#setup-step-service [data-step-badge]").textContent'), 'Next');
assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /about a minute to set up/);
assert.match(await b.evaluate('document.querySelector("#proxy-setup-state").textContent'), /pinned 8\.0\.42/);
assert.match(await b.evaluate('document.querySelector("#proxy-setup-own").textContent'), /not built/);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-orgs td").textContent'), 'acme');
await wait('document.querySelector("#proxy-message")?.textContent.includes("Follow the next step under Proxy setup")');
await wait('document.querySelector("#proxy-message")?.textContent.includes("Step 1 sets it up")');
assert.equal(await b.evaluate('!!document.querySelector("#proxy-dev-setup")'), false, 'the page replaces the terminal note');
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-init [data-setup-write]:not([disabled])").length'), 0, 'init waits for a verified release');
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/fetch")');
// The status still names the download, so the run stops there: nothing is retried by itself.
await wait('document.querySelector("#setup-step-service").dataset.state==="bad"');
assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/fetch', body: {} }]);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Try again');
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
test('without send the next-step button is disabled and nothing is posted', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: scenario(base, { send: false, proxyAdminSend: false }) });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fetch"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").disabled'), true);
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
assert.deepEqual(await writes(b), []);
});
test('init sends generate by default; a pasted key on loopback is sent with its confirmation and the fields are cleared', { timeout: 90000 }, async t => {
test('init always sends generate; there is no pasted key, and Try again sends generate again', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fetched), 'POST /api/proxy/admin/init': { body: { settings: { port: 18432 }, receipt: { op: 'init', time: T, port: 18432, generated: true } } } } });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init"');
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
await wait('document.querySelector("#proxy-setup-init-box").open===true');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-paste-choice").hidden'), false, 'loopback page offers the paste choice');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-paste").hidden'), true);
await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="18432";f.requestSubmit();})()');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Continue setup');
// The settings sit under Advanced and go with the press.
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts');
// settings-s4 (design section 10, A8 and A2): no "Use my own key", no key fields, no rotation grace.
assert.equal(await b.evaluate('Boolean(document.querySelector("#proxy-setup-paste-choice, #proxy-setup-paste, #proxy-setup-key, #proxy-setup-confirm, #proxy-setup-grace, [name=keySource]"))'), false);
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-init input[type=password], #proxy-setup-advanced input[type=password]").length'), 0);
assert.match(await b.evaluate('document.querySelector("#proxy-setup-init").textContent'), /Mosaic makes the service key on this machine/);
assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup").textContent'), /Use my own key|Key rotation grace/);
await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="18432";document.querySelector("#proxy-setup-go").click();})()');
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/init")');
await wait('document.querySelector("#proxy-setup-message").textContent.includes("with a generated key")');
assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/init', body: { port: 18432, generate: true } }]);
assert.deepEqual(await writes(b), [{ path: '/api/proxy/admin/init', body: { generate: true, port: 18432 } }]);
assert.match(await b.evaluate('document.querySelector("#proxy-setup-receipts").textContent'), /init/);
await wait('!document.querySelector("#proxy-setup-init [data-setup-write]").disabled');
await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.keySource.value="paste";f.querySelector("[value=paste]").dispatchEvent(new Event("change"));f.elements.port.value="";f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0002";f.requestSubmit();})()');
await wait('document.querySelector("#proxy-setup-message").textContent.includes("proxy-key-mismatch")');
assert.equal((await writes(b)).length, 1, 'a mismatch is refused in the page');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").elements.key.value'), '', 'the key field is cleared on submit');
await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.key.value="pa-browser-sentinel-0001";f.elements.confirm.value="pa-browser-sentinel-0001";f.requestSubmit();})()');
// The status still names init, so the run stops there; Try again starts from it.
await wait('document.querySelector("#proxy-setup-go")?.textContent==="Try again" && !document.querySelector("#proxy-setup-init [data-setup-write]").disabled');
await b.evaluate('(()=>{const f=document.querySelector("#proxy-setup-init");f.elements.port.value="";document.querySelector("#proxy-setup-go").click();})()');
await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/init").length===2');
assert.deepEqual((await writes(b))[1], { path: '/api/proxy/admin/init', body: { key: 'pa-browser-sentinel-0001', confirm: 'pa-browser-sentinel-0001' } });
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup-init input[type=password]")].every(i=>i.value==="")'), true);
assert.equal(await b.evaluate('document.body.innerText.includes("pa-browser-sentinel")'), false);
assert.deepEqual((await writes(b))[1], { path: '/api/proxy/admin/init', body: { generate: true } });
});
test('after a confirmed restart the next step clears the fence and shows the receipt', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(fenced), 'POST /api/proxy/admin/fence/clear': { body: { cleared: true, receipt: { op: 'fence.clear', time: T, pid: 4242 } } } } });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="fence-clear"');
assert.match(await b.evaluate('document.querySelector("#proxy-setup-state").textContent'), /new pid 4242/);
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
@@ -91,19 +97,18 @@ test('a stopped proxy hides the account panels with a setup note, and starting t
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'inactive' }, next: ['unit-start'] };
const down = { 'GET /api/proxy/accounts': { status: 503, body: { error: 'proxy-down' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'proxy-down' } } };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(installed), ...down, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit.start', time: T, pid: 4242 } } } } });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-start"');
await wait('document.querySelector("#proxy-message").textContent.includes("not running yet")');
assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-apikey-title]").hidden'), true);
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].every(e=>e.hidden)'), true);
await b.evaluate(`Object.assign(window.__scenario, {
'GET /api/proxy/accounts': { body: { accounts: [] } }, 'GET /api/proxy/keys': { body: { keys: [] } },
'/api/proxy/admin/status': ${JSON.stringify({ ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] })} })`);
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/unit/start")');
await wait('document.querySelector("#proxy-message").textContent.includes("Accounts and client keys loaded")');
assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-apikey-title]").hidden'), false);
assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), false);
await wait('[...document.querySelectorAll("[data-accounts-part]")].length>0 && [...document.querySelectorAll("[data-accounts-part]")].every(e=>!e.hidden)');
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].some(e=>e.hidden)'), false);
});
test('an initialized proxy whose accounts read fails with another code also hides the panels until it answers', { timeout: 90000 }, async t => {
@@ -111,64 +116,72 @@ test('an initialized proxy whose accounts read fails with another code also hide
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'inactive' }, next: ['unit-start'] };
const failing = { 'GET /api/proxy/accounts': { status: 503, body: { error: 'outcome-unknown' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'outcome-unknown' } } };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(installed), ...failing, 'POST /api/proxy/admin/unit/start': { body: { receipt: { op: 'unit.start', time: T, pid: 4242 } } } } });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-start"');
await wait('document.querySelector("#proxy-message").textContent.includes("the account panels return once the proxy answers")');
assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), true);
await wait('document.querySelector("#proxy-message").textContent.includes("your accounts show here once the service answers")');
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].every(e=>e.hidden)'), true);
await b.evaluate(`Object.assign(window.__scenario, {
'GET /api/proxy/accounts': { body: { accounts: [] } }, 'GET /api/proxy/keys': { body: { keys: [] } },
'/api/proxy/admin/status': ${JSON.stringify({ ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] })} })`);
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
await wait('document.querySelector("#proxy-message").textContent.includes("Accounts and client keys loaded")');
assert.equal(await b.evaluate('document.querySelector("[aria-labelledby=proxy-accounts-title]").hidden'), false);
await wait('[...document.querySelectorAll("[data-accounts-part]")].length>0 && [...document.querySelectorAll("[data-accounts-part]")].every(e=>!e.hidden)');
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-accounts-part]")].some(e=>e.hidden)'), false);
});
test('a fence with no readable time names the --proxy-restarted path instead of a page restart', { timeout: 90000 }, async t => {
const timeless = { ...fenced, fence: { set: true, invalid: true }, restart: null, next: ['unit-restart'] };
const { f, b, wait } = await w15Fixture(t, { scenario: scenario(timeless) });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-restart"');
assert.match(await b.evaluate('document.querySelector("#proxy-setup-next p").textContent'), /no readable time.*mosaic proxy fence clear --proxy-restarted/);
const text = await b.evaluate('document.querySelector("#proxy-setup-next > p").textContent');
assert.match(text, /no readable time.*restart the model service, confirm it answers, then clear the fence\./);
assert.doesNotMatch(text, /proxy/i, 'owner text says model service');
// The exact command sits under Technical details, folded, with where to run it.
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next details.proxy-setup-cli").open'), false);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next details.proxy-setup-cli summary").textContent'), 'Technical details');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next details.proxy-setup-cli p").textContent'), 'Run this in a terminal on this machine: mosaic proxy fence clear --proxy-restarted');
});
test('after a reload the receipts come from status, and an initialized proxy folds the init form', { timeout: 90000 }, async t => {
test('after a reload the receipts come from status, and an initialized proxy shows its settings read-only', { timeout: 90000 }, async t => {
const initialized = { ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
receipts: [{ op: 'fetch', time: T, version: '8.0.42' }, { op: 'init', time: T, generated: true, port: 18432 }], next: ['unit-install'] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(initialized), 'POST /api/proxy/admin/unit/install': { body: { receipt: { op: 'unit.install', time: T } } } } });
await b.navigate(f.base + '/#/settings/model-proxy');
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="unit-install"');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-receipts li strong")].map(s=>s.textContent)'), ['init', 'fetch'], 'newest first, from proxy-admin.jsonl');
await b.evaluate('document.querySelector("#proxy-setup-init-box").open = true');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").hidden'), true, 'init is done, so its form is gone');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-settings").textContent'), 'Port18432');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-settings-note").textContent'), 'Changing these after setup is not built yet.');
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/unit/install")');
await wait('document.querySelector("#proxy-setup-init-box").open===false');
});
// #1873 ride-default: the Ride all box. The confirm names the stricter admission, the answer's
// skips and stand-in organizations are painted even while an earlier load still waits on the
// accounts read, and the move confirm says the organization spends real tokens after it.
test('Ride all confirms the stricter admission, paints skips and stand-in organizations while a load waits, and the move warns of real tokens', { timeout: 90000 }, async t => {
const running = { ...fenced, fence: { set: false }, restart: null, next: ['ride-all'],
const running = { ...fenced, fence: { set: false }, restart: null, next: ['accounts', 'ride-all'],
ride: [{ id: 'north', state: 'ready' }, { id: 'south', state: 'ready' }, { id: 'west', state: 'fixture' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running),
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running), ...answering(1), '/api/triage/route': savedRoute,
'POST /api/proxy/admin/ride-all': { body: { added: ['south'], already: [], skipped: [], fixtures: [{ id: 'west' }], receipt: { op: 'ride.all', time: T } } },
'POST /api/proxy/admin/ride-move': { body: { moved: false, reason: 'bus-running' } } } });
// The first accounts and keys reads answer not-configured; every later pair never answers, so a load stays in flight.
// The first accounts and keys reads answer; every later pair never answers, so a load stays in flight.
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { const inner = window.fetch; let n = 0; window.__confirms = [];
window.confirm = text => { window.__confirms.push(text); return true; };
window.fetch = (input, init) => { const url = String(typeof input === 'string' ? input : input.url);
if (url.includes('/api/proxy/accounts') && n++ > 0) return new Promise(() => {});
if (url.includes('/api/proxy/keys') && n > 1) return new Promise(() => {});
return inner(input, init); }; })();` });
await b.navigate(f.base + '/#/settings/model-proxy');
await wait('document.querySelector("#proxy-ride")?.hidden===false && document.querySelector("#proxy-setup-go")?.dataset.next==="ride-all"');
await b.navigate(f.base + '/#/settings/model-setup');
await wait(`document.querySelector("#proxy-ride")?.checkVisibility() && document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="ride-all"`);
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").className'), 'btn primary');
assert.match(await b.evaluate('document.querySelector("#proxy-ride-text").textContent'), /every launch route is checked, direct Anthropic routes too.*2 organizations can ride now/);
assert.match(await b.evaluate('document.querySelector("#proxy-ride-fixtures li").textContent'), /^west uses stand-in models, can be moved to the owner's models\./);
// The first Ride all's own reload paints, then waits on the accounts read for good.
await b.evaluate('document.querySelector("#proxy-ride-go").click()');
await wait('window.__writes.some(w=>w.path==="/api/proxy/admin/ride-all")');
assert.match(await b.evaluate('window.__confirms[0]'), /Admission gets stricter there: every launch route is checked, direct Anthropic routes too, and while the proxy is down or fenced every launch in that organization is refused/);
assert.match(await b.evaluate('window.__confirms[0]'), /Admission gets stricter there: every launch route is checked, direct Anthropic routes too, and while the model service is down or fenced every launch in that organization is refused/);
await wait('document.querySelector("#proxy-ride-message").textContent.includes("Added to 1")');
await wait('document.querySelector("#proxy-ride-go").disabled===false');
// The second answer lands while that load is still in flight.
@@ -177,7 +190,7 @@ test('Ride all confirms the stricter admission, paints skips and stand-in organi
await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/ride-all").length===2');
await wait('document.querySelector("#proxy-ride-message").textContent.includes("skipped 1")');
await wait('document.querySelectorAll("#proxy-ride-skips li").length===1');
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-skips li").textContent'), 'Skipped north: Its bus started before the proxy was set up. Restart its bus, then ride again.');
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-skips li").textContent'), 'Skipped north: Its bus started before the model service was set up. Restart its bus, then ride again.');
assert.match(await b.evaluate('document.querySelector("#proxy-ride-fixtures li").textContent'), /Its bus is running: stop it first\./);
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), false, 'the box is not left busy');
await b.evaluate('document.querySelector("[data-ride-move=west]").click()');
@@ -202,9 +215,243 @@ test('Ride all confirms the stricter admission, paints skips and stand-in organi
await wait('window.__writes.filter(w=>w.path==="/api/proxy/admin/ride-all").length===3');
await wait('document.querySelectorAll("#proxy-ride-skips li").length===3');
assert.deepEqual(JSON.parse(await b.evaluate('JSON.stringify([...document.querySelectorAll("#proxy-ride-skips li")].map(li=>li.textContent))')), [
'Skipped north: The model proxy was on it, or Ride all may have added it, and it is off now. Ride all leaves it off. Add it on its Settings page to use it.',
'Skipped south: The proxy could not record the change first, so it was not made.',
'Skipped north: It used your model service, or Ride all may have added it, and it is off now. Ride all leaves it off. To use it there, choose Use your models on its Models page.',
'Skipped south: Console could not record the change first, so it was not made.',
// Re-check 3 (P3-3): a damaged receipts line stops every add until someone repairs it.
'Skipped east: Its organization file, its change log or the proxy\'s receipts could not be read. A damaged line in the proxy\'s receipts must be repaired by hand before Ride all adds again.']);
'Skipped east: Its organization file, its change log or the model service\'s receipts could not be read. A damaged line in the receipts must be repaired by hand before Ride all adds again.']);
// settings-p3 (rebase re-check P3-4): the Ride all box, its confirms and its lines say model service, not proxy.
assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-ride").innerText + window.__confirms.join(" ")'), /proxy/i);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// #1873 settings slice 1 (DESIGN.md sections 4 and 9, D1, D3, D4). The service runs ("accounts" is the
// server's next step); the steps after it come from what the page reads: accounts, organizations, Triage route.
const running = { ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] };
const account = { accountId: 'a1', displayName: 'Claude work', provider: 'claude', status: 'active', priority: 0 };
const answering = (n = 1) => ({ 'GET /api/proxy/accounts': { body: { accounts: Array.from({ length: n }, () => account) } }, 'GET /api/proxy/keys': { body: { keys: [] } } });
// An organization's own routes read, the one Routing uses: its catalogue and the bus's cause lines.
const routes = (notices = [], status = 'unavailable', reason) => ({ rows: [{ catalogue: { status, models: [], notices, ...(reason ? { reason } : {}) } }] });
const FIXTURE = 'This organization routes launches to the dev fixture, which the host refuses next to a model proxy (fixture-proxy-configured). Remove the fixture or stop using it here.';
const savedRoute = { route: { model: 'm', harness: 'claude-code', cap: 1000, reset: '00:00', timeZone: 'UTC', revision: 1, updatedAt: T } };
const restarted = { body: { outcome: 'done', step: 'bus-restart', restarted: true, healthy: true } };
const visible = sel => `[...document.querySelectorAll(${JSON.stringify(sel)})].filter(e=>e.checkVisibility())`;
test('settings-s1 B2: once the service runs, the organizations that cannot see the models stay listed, each with its own Restart', { timeout: 90000 }, async t => {
const orgs = [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'beta', proxy: 'shared', catalogue: { status: 'bus-unavailable' } },
{ id: 'gamma', proxy: 'shared', catalogue: { status: 'ready', models: 3 } }, { id: 'delta', proxy: 'shared', catalogue: { status: 'disabled' } }];
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, '/api/orgs/acme/bus/routes': routes(), 'POST /api/orgs/acme/restart/bus': restarted } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===2');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-restart").checkVisibility()'), true);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-restart-list li")].map(li=>[li.dataset.restartOrg, li.querySelector(".badge").className, li.querySelector(".badge").textContent, li.querySelector("[data-org-restart]")?.textContent ?? null])'),
[['acme', 'badge badge-attn', "Can't see models", 'Restart acme'], ['beta', 'badge badge-danger', 'Not running', 'Restart beta']]);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null, 'the next step is the list, so no second button');
// acme's bus names no cause, so a restart connects it. beta is not running: it keeps its Restart
// and its refusal, and does not hold the next step.
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart acme\. It has a Restart button under Organizations that can't use your models yet\./);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-restart-title").textContent'), "Organizations that can't use your models yet");
// A restart reads the status again; the organization stays on the list, now ready, so the owner sees it worked.
await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...running, organizations: [{ ...orgs[0], catalogue: { status: 'ready', models: 3 } }, ...orgs.slice(1)] })}`);
await b.evaluate('document.querySelector("[data-org-restart=acme]").focus()');
assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none', 'the focused Restart shows a focus ring');
await b.key('Enter', 'Enter');
await wait('document.querySelector("[data-restart-org=acme] .badge")?.textContent==="Ready"');
assert.deepEqual(await b.evaluate('window.__writes.map(w=>w.method+" "+w.path)'), ['POST /api/orgs/acme/restart/bus']);
assert.equal(await b.evaluate('document.querySelector("[data-restart-org=acme] [data-org-restart]")'), null, 'a ready organization has no Restart');
assert.equal(await b.evaluate('document.querySelector("[data-restart-org=acme] .badge").className'), 'badge badge-ok');
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^The model service is set up\. Some organizations still can't see your models\./);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
test('settings-s1 B2: Restart shows only where the organization\'s own cause allows it; the dev fixture and a model-key collision get their plain lines, and neither holds the next step', { timeout: 90000 }, async t => {
const orgs = [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'lab', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } },
{ id: 'lock', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'odd', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } },
{ id: 'clash', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }];
const lock = 'The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.';
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute,
'/api/orgs/acme/bus/routes': routes(), '/api/orgs/lab/bus/routes': routes([FIXTURE]), '/api/orgs/lock/bus/routes': routes([lock]), 'GET /api/orgs/odd/bus/routes': { status: 500, body: { error: 'x' } },
'/api/orgs/clash/bus/routes': routes([], 'unavailable', 'model-key-collision') } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===5 && !/Checking why/.test(document.querySelector("#proxy-setup-restart-list").textContent)');
const rows = await b.evaluate('Object.fromEntries([...document.querySelectorAll("#proxy-setup-restart-list li")].map(li=>[li.dataset.restartOrg, {badge: li.querySelector(".badge").className, why: li.querySelector(":scope > .small").textContent, restart: li.querySelector("[data-org-restart]")?.textContent ?? null, link: li.querySelector(":scope > .small a")?.getAttribute("href") ?? null, detail: li.querySelector("details summary")?.textContent ?? null}]))');
assert.deepEqual(rows.acme, { badge: 'badge badge-attn', why: "acme can't read your models from the model service yet. A restart connects it.", restart: 'Restart acme', link: null, detail: null });
// Saving routes does not remove the fixture provider, so lab gets no Routing link (review 2, P2-B).
assert.deepEqual(rows.lab, { badge: 'badge badge-attn', why: "lab runs on test models, which can't share this machine with your model service. This can't be changed from Console yet.", restart: null, link: null, detail: 'Technical details' });
assert.deepEqual(rows.lock, { badge: 'badge badge-attn', why: "lock can't open the model service's shared lock. A restart opens it again.", restart: 'Restart lock', link: null, detail: 'Technical details' });
// Two models that slug to one key: a restart reads the same catalogue again (review 2, P2-A).
assert.deepEqual(rows.clash, { badge: 'badge badge-attn', why: "Two of your models get the same short name, so clash can't tell them apart. A restart won't change that. Take one of them out of an API key's Models list on Model setup. If both come from signed-in accounts, this can't be changed from Console yet.", restart: null, link: null, detail: 'Technical details' });
assert.deepEqual(rows.odd, { badge: 'badge badge-attn', why: "odd can't see your models, and its reason could not be read. Open odd's Models page", restart: null, link: '#/settings/routing?org=odd', detail: null });
assert.equal(await b.evaluate('document.querySelector("[data-restart-org=lab] details").textContent.includes("fixture-proxy-configured")'), true, 'the bus line is kept under Technical details');
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart acme and lock\./);
assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup-restart-list").innerText'), /model proxy/i, 'the bus line shows only once Technical details is opened');
// Once acme and lock see the models, only the fixture, the collision and the unread one are left, and none holds a step.
await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...running, organizations: [{ ...orgs[0], catalogue: { status: 'ready', models: 2 } }, orgs[1], { ...orgs[2], catalogue: { status: 'ready', models: 2 } }, orgs[3], orgs[4]] })}`);
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-org-restarted", { detail: { id: "acme" } })); true');
await wait(`/^The model service is set up\\. Some organizations still/.test(document.querySelector(${JSON.stringify(STEP3)}).textContent)`);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null);
assert.deepEqual(await b.evaluate('window.__writes.map(w=>w.method+" "+w.path)'), [], 'nothing restarts by itself');
});
test('settings-s1 B2: a refused restart keeps its reason on the list across the status read that follows', { timeout: 90000 }, async t => {
const orgs = [{ id: 'lab', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }];
const refusal = { status: 409, body: { error: 'bus-start-refused', message: 'bus start refused: fixture-proxy-configured' } };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute, 'POST /api/orgs/lab/restart/bus': refusal } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("[data-org-restart=lab]")');
await b.evaluate('document.querySelector("[data-org-restart=lab]").click()');
await wait('document.querySelector("[data-restart-org=lab] .org-restart-refused")');
await new Promise(r => setTimeout(r, 300));
assert.equal(await b.evaluate('document.querySelector("[data-restart-org=lab] [data-org-restart-receipt] strong").textContent'), "lab runs on test models, which can't share this machine with your model service. It did not start.");
assert.equal(await b.evaluate('document.querySelector("[data-restart-org=lab] .badge").className'), 'badge badge-danger', 'a refused organization is never green');
});
test('settings-s1 B3: a sign-in reads the whole status again and the next step follows accounts, organizations, then the Triage route', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }] }, { orgSetup: true }), ...answering(0), '/api/triage/route': { route: null }, '/api/orgs/acme/bus/routes': routes(),
'POST /api/proxy/login/status': { body: { status: 'error', reason: 'login-timeout' } } } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#setup-step-accounts")?.dataset.state==="next"');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").className'), 'btn primary');
await b.evaluate(`window.open = () => null; window.__scenario['POST /api/proxy/login/start'] = { body: { url: location.origin + '/signin-stub', state: 's1' } }`);
// A sign-in that runs out of time says so plainly.
await b.evaluate('document.querySelector("#proxy-login-start").requestSubmit()');
await wait('document.querySelector("#proxy-login-message").textContent==="Sign-in took too long. Try again."');
// The next sign-in finishes. The status read after it is the one that names acme, so the step proves the reread.
await b.evaluate(`Object.assign(window.__scenario, ${JSON.stringify({ ...answering(1), 'POST /api/proxy/login/status': { body: { status: 'ok' } }, '/api/proxy/admin/status': { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }] } })})`);
await b.evaluate('document.querySelector("#proxy-login-start").requestSubmit()');
await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="restart-orgs"`);
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart acme\./);
assert.equal(await b.evaluate('document.querySelector("#proxy-login-message").textContent'), 'Account signed in.');
// acme restarts and can see the models; the Triage route is not set, so that is the step after.
await b.evaluate(`Object.assign(window.__scenario, ${JSON.stringify({ 'POST /api/orgs/acme/restart/bus': restarted, '/api/proxy/admin/status': { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }] } })})`);
await b.evaluate('document.querySelector("[data-org-restart=acme]").click()');
await wait('document.querySelector("#setup-step-triage")?.dataset.state==="next"');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-setup-triage").textContent, document.querySelector("#proxy-setup-triage").className]'), ['Set up Triage', 'btn primary']);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// Rebase onto ride-default: with an account, Ride all is the step after accounts while an organization can
// ride now, and its box shows outside Technical details. Stand-in organizations alone do not hold the step.
test('settings-s1 B3 with ride-default: Ride all follows accounts while an organization can ride, and only then', { timeout: 90000 }, async t => {
const riding = { ...running, next: ['accounts', 'ride-all'], organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }],
ride: [{ id: 'north', state: 'ready' }, { id: 'west', state: 'fixture' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(riding), ...answering(1), '/api/triage/route': { route: null } } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="ride-all"`);
// settings-s4: the step is Ride all's own button, the page's primary one.
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").className'), 'btn primary');
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-setup button")].filter(e=>e.checkVisibility()&&e.textContent==="Ride all").length'), 1, 'one Ride all button');
assert.equal(await b.evaluate('document.querySelector("#proxy-ride").checkVisibility()'), true, 'the Ride all box is not folded under Technical details');
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), false);
// Ride all adds north. Only a stand-in organization is left: the step moves on to the Triage route, and Move stays offered.
await b.evaluate(`window.confirm = () => true; Object.assign(window.__scenario, ${JSON.stringify({ '/api/proxy/admin/status': { ...riding, ride: [{ id: 'north', state: 'already' }, { id: 'west', state: 'fixture' }] },
'POST /api/proxy/admin/ride-all': { body: { added: ['north'], already: [], skipped: [], fixtures: [{ id: 'west' }], receipt: { op: 'ride.all', time: T } } } })})`);
await b.evaluate('document.querySelector("#proxy-ride-go").click()');
await wait('document.querySelector("#setup-step-triage")?.dataset.state==="next"');
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=west]").checkVisibility()'), true);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// settings-p3 (rebase re-check P3-2): an owner who can't send gets no Ride all step: Ride all is disabled for them.
test('settings-p3: Ride all is not the next step when the owner cannot send', { timeout: 90000 }, async t => {
const riding = { ...running, next: ['accounts', 'ride-all'], organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'north', state: 'ready' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(riding, { proxyAdminSend: false }), ...answering(1), '/api/triage/route': { route: null } } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#setup-step-triage")?.dataset.state==="next"');
assert.equal(await b.evaluate('document.querySelector("#proxy-ride-go").disabled'), true);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// settings-p3 (rebase re-check P3-1): with a stand-in or skipped organization still in the Ride all box,
// the done line does not say every organization can see the models.
test('settings-p3: the done line does not say every organization while the Ride all box still lists one', { timeout: 90000 }, async t => {
const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'west', state: 'fixture' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(done), ...answering(1), '/api/triage/route': savedRoute } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="done"`);
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), 'The model service is set up. Some organizations still need a step under Use your models in every organization.');
assert.equal(await b.evaluate('document.querySelector("#proxy-ride").checkVisibility() && document.querySelector("#proxy-ride h4").textContent'), 'Use your models in every organization');
// Once nothing is listed there, the line says every organization.
await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...done, ride: [{ id: 'acme', state: 'already' }] })}`);
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-org-restarted", { detail: { id: "acme" } })); true');
await wait(`document.querySelector(${JSON.stringify(STEP3)}).textContent==="The model service is set up and every organization can see your models."`);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// settings-p3 review P2-1: an owner who can't send gets no Ride all step, so the done line shows while an
// organization can still ride; it must not say every organization can see the models.
test('settings-p3: the done line does not say every organization while one can still ride and the owner cannot send', { timeout: 90000 }, async t => {
const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'ready' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(done, { proxyAdminSend: false }), ...answering(1), '/api/triage/route': savedRoute } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next==="done"`);
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), 'The model service is set up. Some organizations still need a step under Use your models in every organization.');
assert.match(await b.evaluate('document.querySelector("#proxy-ride-text").textContent'), /1 organization can ride now\./);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// settings-p3 review P3-3: on a single-business Console a stand-in organization has no bus status
// (running null), so the page says moving is not available there and offers no Move button.
test('settings-p3: a stand-in organization with no bus status is not offered a Move', { timeout: 90000 }, async t => {
const state = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'west', state: 'fixture', running: null }, { id: 'east', state: 'fixture' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(state), ...answering(1), '/api/triage/route': savedRoute } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-ride-fixtures li")');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-ride-fixtures li")].map(li => li.firstChild.textContent.trim())'),
['west uses stand-in models. Moving it is not available on this Console.', "east uses stand-in models, can be moved to the owner's models."]);
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=west]")'), null);
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=east]").disabled'), false);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// settings-p3 (re-check 3 P3-5): a ready catalogue the bus picked up late (launchRestart) keeps the
// organization listed with its Restart, holds the next step, and Model setup never says done.
test('settings-p3: an organization whose agents start on the models only after a restart is listed and holds the next step', { timeout: 90000 }, async t => {
const orgs = [{ id: 'late', proxy: 'shared', catalogue: { status: 'ready', models: 2, launchRestart: true } }];
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario({ ...running, organizations: orgs }, { orgSetup: true }), ...answering(), '/api/triage/route': savedRoute } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelectorAll("#proxy-setup-restart-list li").length===1');
assert.deepEqual(await b.evaluate('(li=>[li.querySelector(".badge").className, li.querySelector(".badge").textContent, li.querySelector(":scope > .small").textContent, li.querySelector("[data-org-restart]")?.textContent ?? null])(document.querySelector("[data-restart-org=late]"))'),
['badge badge-attn', 'Restart needed', 'late can see your models. Its agents start on them after a restart.', 'Restart late']);
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart late\./);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// settings-p3 (re-check 3 P3-1, P3-7): the init lock and partial init lines say what to do in plain
// words, never point at "the README" in the text, and keep the README path under Technical details.
test('settings-p3: the init lock and partial init steps say what to do, with the README path under Technical details', { timeout: 90000 }, async t => {
const held = { ...fetched, initLock: { present: true, clearable: false, blockers: ['the bus for acme is running'] }, next: ['init-lock-wait'] };
const { f, b, wait } = await w15Fixture(t, { scenario: scenario(held) });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init-lock-wait"');
const read = 'JSON.stringify({text: document.querySelector("#proxy-setup-next > p").textContent, summary: document.querySelector("#proxy-setup-next details summary")?.textContent, lead: document.querySelector("#proxy-setup-next details p")?.textContent, code: document.querySelector("#proxy-setup-next details code")?.textContent, open: document.querySelector("#proxy-setup-next details")?.open, button: document.querySelector("#proxy-setup-go").textContent})';
assert.deepEqual(JSON.parse(await b.evaluate(read)), {
text: 'An init lock is held and cannot be cleared: the bus for acme is running. Stop the bus, then check again. Model service files that are left must be resolved by hand. Do not delete them to make init run again.',
summary: 'Technical details', lead: 'The hand steps for a stale init lock and a partial init are in packages/model-proxy/README.md', code: 'packages/model-proxy/README.md', open: false, button: 'Check again' });
await b.evaluate(`window.__scenario['/api/proxy/admin/status'] = ${JSON.stringify({ ...fetched, init: { initialized: false, partial: true, files: [{ label: 'proxy settings', present: true }, { label: 'management key', present: false }] }, next: ['init-repair'] })}`);
await b.evaluate('document.querySelector("#proxy-setup-go").click()');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="init-repair"');
const repair = JSON.parse(await b.evaluate(read));
assert.equal(repair.text, 'Setup is partly done. Init never overwrites model service files that already exist, so they must be resolved by hand. Do not delete them to make init run again. Then check again.');
assert.equal(repair.code, 'packages/model-proxy/README.md');
assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup-next").innerText'), /README|proxy/i, 'nothing technical shows until Technical details is opened');
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
test('settings-s1 B4: only the next step has a button; done steps, Fence, Init lock and the service controls sit under Technical details', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { ...scenario(running), ...answering(0), '/api/triage/route': savedRoute } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#setup-step-accounts")?.dataset.state==="next"');
assert.deepEqual(await b.evaluate(`${visible('.settings-content .primary')}.map(e=>e.id||e.textContent)`), ['proxy-login-go'], 'one primary button on the page');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go")'), null, 'step 1 is done, so it has no button');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init").checkVisibility()'), false, 'init is done, so its form is gone');
const tech = await b.evaluate('(()=>{const d=document.querySelector("#proxy-setup-tech");return {summary:d.querySelector("summary").textContent,open:d.open,terms:[...d.querySelectorAll("dt")].map(x=>x.textContent),units:d.querySelectorAll("[data-unit]").length,receipts:!!d.querySelector("#proxy-setup-receipts")}})()');
assert.deepEqual(tech, { summary: 'Technical details: release, service, history', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock'], units: 4, receipts: true });
assert.equal(await b.evaluate(`${visible('#proxy-setup dt, #proxy-setup [data-unit]')}.length`), 0, 'nothing technical shows until it is opened');
// Technical details opens by keyboard and shows the controls.
await b.evaluate('document.querySelector("#proxy-setup-tech summary").focus()');
await b.key('Enter', 'Enter');
await wait('document.querySelector("#proxy-setup-tech").open');
assert.equal(await b.evaluate(`${visible('#proxy-setup [data-unit]')}.length`), 4);
});
+8 -7
View File
@@ -197,7 +197,7 @@ test('Routing switch writes the model-provider setting and keeps other modules',
await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`const original=window.fetch;window.posts=[];window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify({send:true}));if(url==='/api/proxy/plugins')return new Response(JSON.stringify(${JSON.stringify(settings)}));if(url==='/api/proxy/plugins/set'){posts.push(JSON.parse(options.body));return new Promise(r=>window.answer=(status,body)=>r(new Response(JSON.stringify(body),{status})));}return original(url,options);};`});
await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/routing`);
const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed');})()`);
await wait('document.querySelector("#provider-switch")?.textContent.startsWith("Enable")');
await wait('document.querySelector("#provider-switch")?.textContent.startsWith("Use your models")');
await b.evaluate('document.querySelector("#provider-switch").click();true');
await wait('posts.length===1');const payload=await b.evaluate('posts[0]');
assert.deepEqual(payload.plugins,{'model-provider':['cliproxy']});
@@ -271,8 +271,8 @@ test('quick fallback edits survive the harness redraw', {timeout:60000}, async t
// organization's catalogue is ready with no proxy, and its switch reads Enable.
test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disable and removes cliproxy only; a fixture-only org reads Enable', {timeout:90000}, async t => {
for (const [providers, label, line, next] of [
[['fixture','cliproxy'], 'Disable', /Model catalogue unavailable\. A change to thinking alone still saves\. A new model needs the catalogue: set up the model proxy, or, when this organization has none, press Disable model proxy catalogue\./, ['fixture']],
[['fixture'], 'Enable', /^Model catalogue, observed /, ['fixture','cliproxy']],
[['fixture','cliproxy'], 'Stop using the model service', /can't see your models yet\. Your model service isn't set up yet\. A change to thinking alone still saves\. A new model needs the model service: ask the instance owner to set it up, or press Stop using the model service when this organization does not need it\./, ['fixture']],
[['fixture'], 'Use your models', /^Model catalogue, observed /, ['fixture','cliproxy']],
]) {
const root=tmp(t,'d3-switch-'), f=fixture(root,'acme',doc=>{doc.plugins['model-provider']=providers;return doc;});
const dir=join(root,'config'),file=join(dir,'businesses','acme.json');
@@ -290,8 +290,9 @@ test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disab
await wait(`document.querySelector("#provider-switch")?.textContent.startsWith(${JSON.stringify(label)})&&!!document.querySelector('[data-harness]')`);
const [info,...notices]=await b.evaluate('[document.querySelector(".routing-panel > p.small")?.textContent,...[...document.querySelectorAll(".routing-panel > p.small.warn")].slice(1).map(p=>p.textContent)]');
assert.match(info,line,providers.join(','));
// proxy-pickup (#1873): an unavailable catalogue shows the bus's cause line under it.
assert.deepEqual(notices,label==='Disable'?['The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.']:[],providers.join(','));
// proxy-pickup (#1873): the bus's cause reads as a plain line; its own words sit under Technical details.
assert.deepEqual(notices,[],providers.join(','));
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".routing-panel > details.routes-cause-detail p")].map(p=>p.textContent)'),label==='Stop using the model service'?['The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.']:[],providers.join(','));
await b.evaluate('document.querySelector("#provider-switch").click();true');
await wait('posts.length===1');const payload=await b.evaluate('posts[0]');
assert.deepEqual(payload.plugins,{'model-provider':next},providers.join(','));
@@ -308,10 +309,10 @@ test('D3 Routing: with cliproxy listed and no model proxy the switch reads Disab
test('D3 Routing: a catalogue refusal names Disable only when it can make the save apply, and sends a tester to the owner', {timeout:90000}, async t => {
const refusal=code=>({error:code,message:`${code}: the reason. Nothing changed.`,sent:false});
for (const [providers, tester, instance, code, expect] of [
[['fixture','cliproxy'], false, 'coder', 'model-catalogue-unavailable', /Nothing changed\. This change needs no model proxy: press Disable model proxy catalogue, then save again\. Draft kept\.$/],
[['fixture','cliproxy'], false, 'coder', 'model-catalogue-unavailable', /Nothing changed\. This change does not need the model service: press Stop using the model service, then save again\. Draft kept\.$/],
[['fixture','cliproxy'], false, 'reviewer', 'model-catalogue-unavailable', /Nothing changed\. Draft kept\.$/],
[['fixture'], false, 'reviewer', 'model-provider-unavailable', /Nothing changed\. Draft kept\.$/],
[['fixture','cliproxy'], true, 'coder', 'model-catalogue-unavailable', /Nothing changed\. Ask the organization's owner to set up the model proxy, or to disable the model proxy catalogue when the change needs no proxy\. Draft kept\.$/],
[['fixture','cliproxy'], true, 'coder', 'model-catalogue-unavailable', /Nothing changed\. Ask the organization's owner to set up the model service, or to stop using it when the change does not need it\. Draft kept\.$/],
]) {
const label=`${providers.join(',')} tester=${tester} ${instance}`;
const view={business:'acme',revision:'a'.repeat(64),harnesses:['pi','claude-code'],models:['fixture-deterministic','proxy-x'],
@@ -14,8 +14,9 @@ async function open(t, tester=false) {
test('Business moves from sidebar to first instance Settings section',opts,async t=>{
const {b}=await open(t);
assert.equal(await b.evaluate('[...document.querySelectorAll("#sections a")].filter(e=>e.getAttribute("href")==="#/business").length'),0);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim()).slice(0,4)'),['Your browser','Appearance','This instance','Business']);
assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(e=>e.getAttribute("href")==="#/settings/business").nextElementSibling.textContent.trim()'),'Launch limits');
// #1873 settings slice 4 (DESIGN.md section 2): the nav reads in four groups; a single-business Console's own pages sit under "This business", Business last.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim())'),['You','Appearance','Your models','Model setup','This instance','Organizations','Console','About','This business','Routing','Agents','Launch limits','Token use','Assistant','Business']);
assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(e=>e.getAttribute("href")==="#/settings/business").nextElementSibling'),null);
});
test('legacy Business bookmark replaces its history entry and retains its data',opts,async t=>{
@@ -35,11 +36,11 @@ test('legacy Business bookmark replaces its history entry and retains its data',
await b.evaluate('history.back()'); await wait('location.hash==="#/settings/appearance"');
});
test('mobile disclosure lists Business first in This instance',opts,async t=>{
test('mobile disclosure lists Business under This business',opts,async t=>{
const {b}=await open(t); await b.viewport(390,844);
await b.evaluate('document.querySelector("#settings-disclosure").click()');
assert.equal(await b.evaluate('document.querySelector("#settings-disclosure").getAttribute("aria-expanded")'),'true');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim()).slice(0,4)'),['Your browser','Appearance','This instance','Business']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav > *")].map(e=>e.textContent.trim())'),['You','Appearance','Your models','Model setup','This instance','Organizations','Console','About','This business','Routing','Agents','Launch limits','Token use','Assistant','Business']);
assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(e=>e.getAttribute("href")==="#/settings/business").getClientRects().length>0'),true);
});
@@ -77,6 +77,14 @@ test('failed assistant turns explain recovery in conversation and messages',asyn
let text=await b.evaluate(`document.querySelector('.chat-message-agent').textContent`);assert.match(text,/The assistant couldn.t reply\. Try again, or check Agents\./);assert.match(text,/adapter exited 127/);
await b.evaluate(`location.hash='#/messages'`);await wait(`document.querySelector('.s1-message')`);text=await b.evaluate(`document.querySelector('#message-list').textContent`);assert.match(text,/The assistant couldn.t reply\. Try again, or check Agents\./);assert.match(text,/adapter exited 127/);
});
// #1873 chat-fail: a failed turn with a plain cause shows the cause and next step, with the technical reason under it.
test('a failed turn with a plain cause shows it in the conversation with its details under it',async t=>{
const extra=`fixtureMessages[1].body='The turn failed: the model account is out of usage. Check Settings > Model setup.\\nDetails: adapter exited 1 <b>x</b>';`;
const {b,wait}=await setup(t,'/projects/threads/'+T,390,extra);await wait(`document.querySelector('.chat-message-agent .chat-body')`);
const r=await b.evaluate(`(()=>{const e=document.querySelector('.chat-message-agent .chat-body');return {text:e.textContent,small:e.querySelector('.small')?.textContent,bold:!!e.querySelector('b')}})()`);
assert.match(r.text,/^The assistant couldn.t reply: the model account is out of usage\. Check Settings > Model setup\./);
assert.equal(r.small,'Details: adapter exited 1 <b>x</b>');assert.equal(r.bold,false);
});
test('queue refusal redacts the placeholder and shows its code only once',async t=>{
const extra=`const prior=window.fetch;window.fetch=async(u,o)=>String(u)==='/api/queue'?new Response(JSON.stringify({error:'queue-refused',message:'<path> is a linked worktree; the queue runs only in the canonical checkout'}),{status:503,headers:{'content-type':'application/json'}}):prior(u,o);`;
const {b,wait}=await setup(t,'/queue',390,extra);await wait(`document.querySelector('#bus-view .banner')`);const text=await b.evaluate(`document.querySelector('#bus-view .banner').textContent`);assert.doesNotMatch(text,/<path>/);assert.equal((text.match(/queue-refused/g)||[]).length,1);
@@ -7,10 +7,10 @@ test('Settings proxy navigation keeps the root document through Settings and Das
await b.navigate(f.base+'/#/settings');
await wait('!!document.querySelector("#settings-nav")');
assert.equal(await b.evaluate('location.pathname'), '/');
await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(a=>a.textContent.includes("Model proxy")).click()');
await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(a=>a.textContent.includes("Model setup")).click()');
await new Promise(r=>setTimeout(r,500));
assert.equal(await b.evaluate('location.pathname'), '/');
await wait('document.querySelector("#settings-page-title")?.textContent==="Model proxy" && !!document.querySelector("#proxy-accounts")');
await wait('document.querySelector("#settings-page-title")?.textContent==="Model setup" && !!document.querySelector("#proxy-accounts")');
await b.evaluate('[...document.querySelectorAll("#settings-nav a")].find(a=>a.textContent.includes("Appearance")).click()');
await wait('document.querySelector("#settings-page-title")?.textContent==="Appearance" && !!document.querySelector(".settings-appearance")');
assert.equal(await b.evaluate('location.pathname'), '/');
@@ -58,7 +58,7 @@ test('server sections render and a routing draft can be discarded at phone width
const instances={revision,launch:true,instances:{chief:{definition:'chief',launcher:true,launched:false,kept:false,running:[]}},definitions:{chief:{accepted:true,services:[]}},noHire:[],retired:[]};
const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/settings':{launch,notifier:{binding:null}},'/api/bus/routes':{rows:[routes]},'/api/bus/instances':{rows:[instances]},'/api/bus/names':{rows:[]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]}}});
await b.viewport(390,900);
for(const [path,title] of [['limits','Launch limits'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['about','About']]) {
for(const [path,title] of [['limits','Launch limits'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model setup'],['about','About']]) {
await b.navigate(f.base+'/#/settings/'+path); await wait(`document.querySelector('#settings-page-title')?.textContent===${JSON.stringify(title)}`);
assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'),true,path);
const undersized=await b.evaluate(`[...document.querySelectorAll('.settings-content button,.settings-content select,.settings-content input:not([type=checkbox]):not([type=radio]):not([type=hidden]),.settings-content summary')].filter(e=>e.getClientRects().length).filter(e=>{const r=e.getBoundingClientRect();return r.width<44||r.height<44}).map(e=>e.outerHTML.slice(0,150))`);
@@ -119,7 +119,7 @@ test('hiring switches lead names and launch settings inputs align in columns', {
test('an unconfigured proxy is one empty state without forms or a false read-only note', {timeout:90000}, async t => {
const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/config':{send:true,devOwner:true},'GET /api/proxy/accounts':{status:503,body:{error:'not-configured'}},'GET /api/proxy/keys':{status:503,body:{error:'not-configured'}}}});
await b.navigate(f.base+'/#/settings/model-proxy');await wait('document.querySelector("#proxy-message")?.textContent.includes("not configured")');
await b.navigate(f.base+'/#/settings/model-proxy');await wait('document.querySelector("#proxy-message")?.textContent.includes("not set up")');
assert.equal(await b.evaluate('document.querySelector("#proxy-message").classList.contains("empty")'),true);
assert.equal(await b.evaluate('!!document.querySelector(".settings-readonly")'),false);
assert.equal(await b.evaluate('[...document.querySelectorAll(".settings-model-proxy .panel:not(#proxy-dev-setup)")].every(e=>e.hidden)'),true);
@@ -131,7 +131,7 @@ test('an unconfigured proxy is one empty state without forms or a false read-onl
test('an unconfigured proxy without the dev owner shows no setup note', {timeout:90000}, async t => {
const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/config':{send:true},'GET /api/proxy/accounts':{status:503,body:{error:'not-configured'}},'GET /api/proxy/keys':{status:503,body:{error:'not-configured'}}}});
await b.navigate(f.base+'/#/settings/model-proxy');await wait('document.querySelector("#proxy-message")?.textContent.includes("not configured")');
await b.navigate(f.base+'/#/settings/model-proxy');await wait('document.querySelector("#proxy-message")?.textContent.includes("not set up")');
assert.equal(await b.evaluate('!!document.querySelector("#proxy-dev-setup")'),false);
assert.equal(await b.evaluate('[...document.querySelectorAll(".settings-model-proxy .panel")].every(e=>e.hidden)'),true);
});
@@ -11,10 +11,10 @@ async function page(t,section,width=1440,options={}) {
const x=await w15Fixture(t,{scenario}); const {b,f,wait}=x;
if(options.poll)await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{const original=setTimeout;window.setTimeout=(fn,ms,...args)=>{if(ms===10000)window.__pollRefresh=fn;return original(fn,ms,...args)}})()`});
await b.viewport(width,width===390?900:1000);await b.navigate(f.base+'/#/settings/'+section);
await wait(`document.querySelector('#settings-page-title')?.textContent===${JSON.stringify(({agents:'Agents',routing:'Routing',limits:'Launch limits',assistant:'Assistant',appearance:'Appearance','model-proxy':'Model proxy'})[section])}`);
await wait(`document.querySelector('#settings-page-title')?.textContent===${JSON.stringify(({agents:'Agents',routing:'Routing',limits:'Launch limits',assistant:'Assistant',appearance:'Appearance','model-proxy':'Model setup'})[section])}`);
if(section==='agents')await wait('!!document.querySelector(".agent-more")');
if(section==='routing')await wait('!!document.querySelector("[data-route]")');
if(section==='model-proxy')await wait('!!document.querySelector("#proxy-accounts form")');
if(section==='model-proxy')await wait('!!document.querySelector("#proxy-order form")');
return x;
}
async function pointer(b,sel,xpart=.5){const pt=await b.evaluate(`(()=>{let e=document.querySelector(${JSON.stringify(sel)});e.scrollIntoView({block:'center'});let r=e.getBoundingClientRect();return {x:r.left+r.width*${xpart},y:r.top+r.height/2}})()`);for(const type of ['mousePressed','mouseReleased'])await b.call('Input.dispatchMouseEvent',{type,...pt,button:'left',clickCount:1});}
@@ -29,13 +29,13 @@ test('F6 add agent labels left aligned with launch on own row',opts,async t=>{co
test('F7 maximum length agent values wrap at 390',opts,async t=>{const {b}=await page(t,'agents',390);assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);});
test('F8 root proxy route mounts its settings section',opts,async t=>{const {b}=await page(t,'model-proxy');assert.equal(await b.evaluate('location.pathname'),'/');assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts")'),true);});
test('F9 add agent saving and refusal remain local and visible',opts,async t=>{const {b,wait}=await page(t,'agents');await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');await input(b,'#instance-add-form [data-instance-field=instance]','new-coder');await b.evaluate(`document.querySelector('#instance-add-form select').value='coder';window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#instance-add-form').requestSubmit()`);await wait('!!window.__answer && !!document.querySelector("#instance-add-form .settings-spinner")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-change-form select").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("#instances-receipt")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .banner.err")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-add-form .banner.err").getBoundingClientRect().bottom<=document.querySelector("#instance-add-form button[type=submit]").getBoundingClientRect().top'),true);});
test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await pointer(b,'#settings-nav a[href="#/settings/model-proxy"]');await wait('!!document.querySelector("#proxy-accounts form")');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-accounts button")).backgroundColor===getComputedStyle(document.querySelector("#proxy-refresh")).backgroundColor'),true);});
test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await pointer(b,'#settings-nav a[href="#/settings/model-setup"]');await wait('!!document.querySelector("#proxy-order form")');await pointer(b,'#setup-step-accounts .step-toggle');await wait('!document.querySelector("#setup-step-accounts-body").hidden');await pointer(b,'#proxy-add-box summary');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-order .proxy-priority-save")).backgroundColor===getComputedStyle(document.querySelector("#proxy-login-cancel")).backgroundColor'),true);});
test('F11 Vars fields have labels and mobile agent values identify columns',opts,async t=>{const {b,wait}=await page(t,'agents',390);assert.equal(await b.evaluate('document.querySelector("#instance-add-form textarea").labels.length>0'),true);assert.match(await b.evaluate('document.querySelector("#agents-table tbody tr").innerText'),/Definition/);assert.equal(await b.evaluate('document.querySelector("#agents-table tbody td").getAttribute("headers")'), 'agent-col-definition');await b.viewport(1440,1000);await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');assert.equal(await b.evaluate('document.querySelector("#instance-change-form textarea").labels.length>0'),true);});
test('F12 collapsed section announces current draft and clears after discard',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`(()=>{let e=[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking');e.value='xhigh';e.dispatchEvent(new Event('change',{bubbles:true}))})()`);assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),true);assert.match(await b.evaluate('document.querySelector("#settings-disclosure").textContent'),/unsaved changes/);await pointer(b,'#routes-reload');await wait('!document.querySelector("#settings-nav .settings-dot")');assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),false);});
test('F13 each browser save receipt expires independently',opts,async t=>{const {b}=await page(t,'appearance');await b.evaluate('document.querySelector("[name=theme][value=dim]").focus();document.querySelector("[name=theme][value=dim]").click();document.querySelector("[name=palette][value=grove]").focus();document.querySelector("[name=palette][value=grove]").click();document.querySelector("[name=density][value=compact]").focus();document.querySelector("[name=density][value=compact]").click()');await b.evaluate('new Promise(r=>setTimeout(r,4200))');assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".settings-browser-status")].map(e=>e.textContent)'),['','','']);});
test('F14 settings subtitle is 16px and fallback option is None',opts,async t=>{const {b,wait}=await page(t,'appearance');assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#bus-view .page-head p")).fontSize'),'16px');await b.evaluate('location.hash="#/settings/routing"');await wait('!!document.querySelector(".fallback-cell select")');assert.equal(await b.evaluate('document.querySelector(".fallback-cell select option").textContent'),'None');});
test('F9 assistant saving shows spinner and local refusal',opts,async t=>{const {b,wait}=await page(t,'assistant');await input(b,'[data-assistant-field=definition]','changed');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('.assistant-form').requestSubmit()`);await wait('!!window.__answer && !!document.querySelector(".assistant-form .settings-spinner")');assert.equal(await b.evaluate('!!document.querySelector(".assistant-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("[data-assistant-receipt]")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('document.querySelector("[data-assistant-receipt]").classList.contains("err")'),true);});
test('F9 proxy priority disables input and shows saving',opts,async t=>{const {b,wait}=await page(t,'model-proxy');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#proxy-accounts form').requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-accounts input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#proxy-apikey [name=key]").matches(":disabled")'),false);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-accounts form .banner.err")');await b.evaluate(`window.__answer=null;let f=document.querySelector('#proxy-apikey');f.elements.key.value='fixture-key';f.requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-apikey .settings-spinner")'),true);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-apikey-message.banner.err")');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").value'), '');});
test('F9 proxy priority disables input and shows saving',opts,async t=>{const {b,wait}=await page(t,'model-proxy');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#proxy-order form').requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-order input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-order .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#proxy-apikey [name=key]").matches(":disabled")'),false);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-order form .banner.err")');await b.evaluate(`window.__answer=null;let f=document.querySelector('#proxy-apikey');f.elements.key.value='fixture-key';f.requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-apikey .settings-spinner")'),true);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-apikey-message.banner.err")');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").value'), '');});
test('F3 routing refusal remains visible and announced in the phone draft bar',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`__scenario['POST /api/routes']={status:409,body:{message:'Fixture conflict',sent:false}};[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking').focus()`);await b.key('ArrowDown');await wait('!!document.querySelector("#settings-disclosure .settings-dot")');await pointer(b,'#routes-form button[type=submit]');await wait('document.querySelector("#routes-receipt")?.textContent.includes("Fixture conflict")');assert.deepEqual(await b.evaluate(`(()=>{const e=document.querySelector('#routes-receipt'),r=e.getBoundingClientRect();return {visible:r.width>0&&r.height>0,role:e.getAttribute('role'),banner:e.classList.contains('err')}})()`),{visible:true,role:'status',banner:true});});
test('F9 simultaneous assistant card refusals stay with their own drafts',opts,async t=>{const {b,wait}=await page(t,'assistant');await b.evaluate(`window.__answers={};window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answers[u]=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o)`);await input(b,'[data-assistant-field=definition]','changed');await b.evaluate('document.querySelector(".assistant-form").requestSubmit()');await wait('!!window.__answers["/api/settings"] && !!document.querySelector(".assistant-form .settings-spinner")');await input(b,'[data-assistant-field=name]','Wren');await b.key('Enter');await wait('!!window.__answers["/api/name"]');await b.evaluate(`__answers['/api/name'](409,{message:'Name refused',sent:false})`);await wait('document.querySelector("[data-assistant-kind=name]")?.textContent.includes("Name refused")');await b.evaluate(`__answers['/api/settings'](409,{message:'Settings refused',sent:false})`);await wait('document.querySelector("[data-assistant-kind=settings]")?.textContent.includes("Settings refused")');assert.match(await b.evaluate('document.querySelector("[data-assistant-kind=name]").textContent'),/Name refused/);assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").value'),'Wren');assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=definition]").value'),'changed');});
test('S5 routing remains inside its panel and reaches the last fallback control',opts,async t=>{
@@ -46,8 +46,10 @@ test('S5 routing remains inside its panel and reaches the last fallback control'
test('S5 mobile token use, proxy and held roles expose their clipped columns',opts,async t=>{
const {b,wait}=await page(t,'model-proxy',390);
await b.evaluate(`__scenario['/api/bus/usage']={rows:[{total:{input:1,output:2,cacheWrite:3,cacheRead:4,unknownTurns:5}}]};__scenario['/api/bus/agents']={rows:[{role:'assistant',state:'idle',attention:'none',holder:'fixture',at:'2026-11-06T10:25:00Z'}]}`);
for(const [route,selector] of [['/settings/model-proxy','#proxy-accounts'],['/settings/tokens','#token-usage-table'],['/agents','.s1-agents']]){
if(route!=='/settings/model-proxy')await b.evaluate(`location.hash=${JSON.stringify('#'+route)}`);
// settings slice 4: accounts are rows that wrap, not a table, so they fit the phone with nothing clipped.
assert.deepEqual(await b.evaluate('(()=>{const e=document.querySelector("#proxy-accounts");return {fits:e.getBoundingClientRect().right<=document.documentElement.clientWidth,page:document.documentElement.scrollWidth<=innerWidth}})()'),{fits:true,page:true});
for(const [route,selector] of [['/settings/tokens','#token-usage-table'],['/agents','.s1-agents']]){
await b.evaluate(`location.hash=${JSON.stringify('#'+route)}`);
await wait(`document.querySelector(${JSON.stringify(selector)})`);
const r=await b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(selector)}).closest('.table-wrap');return {overflow:getComputedStyle(e).overflowX,scroll:e.scrollWidth,client:e.clientWidth,right:e.getBoundingClientRect().right,viewport:document.documentElement.clientWidth}})()`);
assert.ok(r.right<=r.viewport && r.scroll>r.client && r.overflow==='scroll',route+' '+JSON.stringify(r));
@@ -0,0 +1,376 @@
// #1873 settings slice 1, bullets 1 and 6 (DESIGN.md sections 3.4, 5 and 9; DEFECTS D2 and D7).
// B1: Routing in an organization that lists the model service but cannot see its models says why,
// and offers Restart only when the model service runs and the bus names no cause. A running bus picks
// the service up at its next catalogue read (proxy-pickup); when it still cannot, its cause line shows
// with Check again, because a restart would not fix that cause. B6: a stopped organization's Settings page
// keeps a refused restart's reason on screen and keeps the instance pages one link away.
// Every bus is a fake: acme answers, gamma is stopped. The page's own reads of the routes, the
// plugin list and the model service state are answered by a fetch stub; the rest is the real server.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
import { ReadError } from '../src/reads.mjs';
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
];
const ROLES = { acme: { chief: { definition: 'chief-of-staff' }, coder: { definition: 'coder' } }, gamma: { chief: { definition: 'chief-of-staff' } } };
// The routes acme's bus answers; a test swaps it to show a restart that brought the catalogue up.
const state = { view: null, gamma: null };
async function fixture() {
const { checkRootAgents } = await import('../../organization/src/index.mjs');
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) };
const empty = () => Promise.resolve([]);
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme }, roles: ROLES[org.id], projects: {} },
status: async () => (!org.busHealthy && state.gamma ? state.gamma : org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
options: () => ({ bus: { inbox: empty, agents: empty, 'thread.claims': empty, tasks: empty, usage: () => Promise.resolve({}), limits: () => Promise.resolve({}), decisions: empty }, chat: { threads: empty, projects: empty } }),
});
const organizations = {
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
// As in production, a stopped organization keeps its reads; each one that needs the bus fails.
if (!org.busHealthy) return { busHealthy: false, reads: { settings: async () => { throw new ReadError('bus-unavailable'); } }, bus: {}, chat: { projects: empty, threads: empty } };
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {} }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => state.view, instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) },
chat: { projects: empty, threads: empty },
};
},
};
return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } };
}
const VIEW = {
business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi', 'claude-code'], models: ['fixture-deterministic'],
providerModels: { 'fixture-deterministic': { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic' } },
levels: { pi: ['off', 'low'], 'claude-code': ['off', 'low'] },
instances: { coder: { harness: 'pi', model: 'fixture-deterministic', thinking: 'off', fallback: null } },
catalogue: { status: 'unavailable', models: [], notices: [] },
};
const PLUGINS = { revision: 'b'.repeat(64), plugins: { harness: ['pi', 'claude-code'], 'model-provider': ['fixture', 'cliproxy'] }, available: { harness: ['pi', 'claude-code'] } };
const SERVICE = {
running: { init: { initialized: true }, unit: { active: 'active', healthy: true }, fence: { set: false } },
stopped: { init: { initialized: true }, unit: { active: 'inactive', healthy: false }, fence: { set: false } },
fresh: { init: { initialized: false }, unit: { active: 'inactive', healthy: false }, fence: { set: false } },
fenced: { init: { initialized: true }, unit: { active: 'active', healthy: true }, fence: { set: true } },
};
const DONE = { status: 200, body: { outcome: 'done', step: 'bus-restart', restarted: true, healthy: true } };
const REFUSED = { status: 409, body: { error: 'bus-start-refused', message: 'bus start refused: fixture-proxy-configured' } };
// The stub answers by path suffix, so it serves both the scoped reads (display.js scopes /api/x to
// /api/orgs/<id>/x) and console-restart.js, which binds fetch before that wrapper. The routes come
// from acme's fake bus. /api/config is the
// server's own answer with the instance owner's flags added; the dev owner is not a root owner here.
const stub = ({ service = SERVICE.running, restart = DONE, extra = {} } = {}) => `(() => {
const real = window.fetch.bind(window); window.__writes = [];
window.__s1 = ${JSON.stringify({ plugins: PLUGINS, service, restart, extra })};
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
window.fetch = async (input, init = {}) => {
const url = new URL(typeof input === 'string' ? input : input.url, location.href), path = url.pathname, method = (init.method || 'GET').toUpperCase();
if (method === 'POST' && /^\\/api\\/orgs\\/[^/]+\\/restart\\/bus$/.test(path)) { __writes.push(path); return json(__s1.restart.body, __s1.restart.status); }
if (method !== 'GET') return real(input, init);
for (const [suffix, body] of Object.entries(__s1.extra)) if (path.endsWith(suffix)) return json(body);
if (/\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(path)) { const c = await (await real(input, init)).json(); return json({ ...c, orgSetup: true, proxyAdmin: true, proxyAdminSend: true, ...(/\\/orgs\\//.test(path) ? { settingsSend: true } : {}) }); }
if (path.endsWith('/proxy/plugins')) return json(__s1.plugins);
if (path.endsWith('/proxy/admin/status')) return json(__s1.service);
return real(input, init);
};
})();`;
async function setup(t, { viewport = [1440, 900], path, init, triage = null, view = VIEW, gamma = null }) {
state.view = view; state.gamma = gamma;
const { organizations, agentLevels } = await fixture();
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, triage, send: async () => ({}), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: init });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}${path}`);
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error("wait failed: "+${JSON.stringify(expression)}+" HASH "+location.hash+" BODY "+(document.querySelector("main")?.innerText??document.body.innerText).slice(0,600))})()`);
return { b, base, wait, text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
}
test('settings-s1 B1: with the model service running and no cause from the bus, Routing offers the organization\'s Restart', { timeout: 90000 }, async t => {
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub() });
await wait('document.querySelector("#routes-catalogue [data-org-restart=acme]")');
const line = await text('#routes-catalogue');
assert.match(line, /^Acme Studio can't see your models yet\. Your model service is running, but Acme Studio can't read your models from it\. Restart Acme Studio to connect it again\./);
assert.doesNotMatch(line, /model proxy/i);
const button = await b.evaluate('(() => { const e = document.querySelector("#routes-catalogue [data-org-restart=acme]"); return { text: e.textContent, primary: e.classList.contains("primary") }; })()');
assert.deepEqual(button, { text: 'Restart Acme Studio', primary: true });
// One primary on the page: while the Restart is primary, Save routes is drawn as a plain button.
assert.equal(await b.evaluate('document.querySelector("#routes-save, .routing-panel button[type=submit]")?.classList.contains("route-save-quiet")'), true);
assert.notEqual(await b.evaluate('getComputedStyle(document.querySelector(".routing-panel button[type=submit]")).backgroundColor'), await b.evaluate('getComputedStyle(document.querySelector("#routes-catalogue [data-org-restart=acme]")).backgroundColor'));
// Keyboard: the button takes focus with a visible ring and Enter presses it.
await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart=acme]").focus(); true');
assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none');
state.view = { ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] } };
await b.key('Enter', 'Enter');
await wait('window.__writes.length === 1');
assert.deepEqual(await b.evaluate('window.__writes'), ['/api/orgs/acme/restart/bus']);
// The page reads the routes again after the restart, and a ready catalogue has no Restart line.
await wait('!document.querySelector("#routes-catalogue") && /Model catalogue, observed/.test(document.querySelector(".routing-panel")?.textContent ?? "")');
});
test('settings-s1 B1: when the bus names why it cannot use the running model service, Routing says it in plain words with the bus\'s line under Technical details, and the lock cause offers Restart and Check again', { timeout: 90000 }, async t => {
const cause = 'The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.';
const view = { ...VIEW, catalogue: { status: 'unavailable', reason: 'proxy-not-configured', models: [], notices: [cause] } };
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub(), view });
await wait('document.querySelector("#routes-catalogue #routes-recheck")');
const line = await text('#routes-catalogue');
assert.match(line, /^Acme Studio can't see your models yet\. Your model service is running\. Acme Studio can't open the model service's shared lock\. A restart opens it again\.\n+Restart Acme Studio to try again\./);
assert.doesNotMatch(line, /model proxy|proxy-lock-invalid/i, 'the bus line is folded away');
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue details.routes-cause-detail").open'), false);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue details.routes-cause-detail p").textContent'), cause);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue details summary").textContent'), 'Technical details');
// A fresh start clears the lock cause, so the Restart is the primary action, beside Check again.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#routes-catalogue [data-org-restart]")].map(e => [e.textContent, e.classList.contains("primary")])'), [['Restart Acme Studio', true]]);
// Keyboard: Check again takes focus with a visible ring; Enter rereads, and the bus has the service now.
await b.evaluate('document.querySelector("#routes-recheck").focus(); true');
assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none');
state.view = { ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] } };
await b.key('Enter', 'Enter');
await wait('!document.querySelector("#routes-catalogue") && /Model catalogue, observed/.test(document.querySelector(".routing-panel")?.textContent ?? "")');
assert.deepEqual(await b.evaluate('window.__writes'), [], 'Check again writes nothing');
});
test('settings-s1 B1: a cause a restart cannot fix, such as the dev fixture, offers Check again and no Restart', { timeout: 90000 }, async t => {
const cause = 'This organization routes launches to the dev fixture, which the host refuses next to a model proxy (fixture-proxy-configured). Remove the fixture or stop using it here.';
const view = { ...VIEW, catalogue: { status: 'unavailable', reason: 'proxy-not-configured', models: [], notices: [cause] } };
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub(), view });
await wait('document.querySelector("#routes-catalogue #routes-recheck")');
const line = await text('#routes-catalogue');
// Saving routes does not remove the fixture provider and no endpoint does, so the line asks for nothing.
assert.match(line, /Your model service is running\. Acme Studio runs on test models, which can't share this machine with your model service\. This can't be changed from Console yet\./);
assert.doesNotMatch(line, /model proxy|Choose another model|check again once/i);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue details.routes-cause-detail p").textContent'), cause);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null, 'a restart would be refused and stop the organization');
assert.equal(await b.evaluate('document.querySelector(".routing-panel button[type=submit]")?.classList.contains("route-save-quiet")'), false, 'with no Restart, Save routes stays the primary');
});
test('settings-s1 B1: a model-key-collision catalogue says two models share a name, offers no Restart and links to Model setup', { timeout: 90000 }, async t => {
const view = { ...VIEW, catalogue: { status: 'unavailable', reason: 'model-key-collision', models: [], notices: [] } };
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub(), view });
await wait('document.querySelector("#routes-catalogue a")');
const line = await text('#routes-catalogue');
assert.match(line, /Two of your models get the same short name, so Acme Studio can't tell them apart\. A restart won't change that\./);
assert.doesNotMatch(line, /Restart Acme Studio|model proxy/i);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null, 'a restart comes back to the same state');
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a[href=\'#/settings/model-setup\']")?.textContent'), 'Open Model setup');
});
test('settings-s1 B1: a set fence reads as a restart to finish, not as a stopped service; a status read that fails offers Check again', { timeout: 90000 }, async t => {
{
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub({ service: SERVICE.fenced }) });
await wait('document.querySelector("#routes-catalogue a")');
const line = await text('#routes-catalogue');
assert.match(line, /Your model service is waiting for a restart to finish\. Open Model setup to finish it\./);
assert.doesNotMatch(line, /not running/);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a").getAttribute("href")'), '#/settings/model-setup');
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null);
await b.close();
}
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub({ service: null }) });
await wait('document.querySelector("#routes-catalogue #routes-recheck")');
assert.match(await text('#routes-catalogue'), /The model service's status could not be read\./);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null);
});
test('settings-s1 B1: with the model service not set up or not running, Routing links to its page and offers no Restart', { timeout: 90000 }, async t => {
for (const [service, expect, href] of [
[SERVICE.fresh, /Your model service isn't set up yet\. Set up the model service\./, '#/settings/model-setup'],
[SERVICE.stopped, /The model service is not running\. Open Model setup\./, '#/settings/model-setup'],
]) {
const { b, wait, text } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub({ service }) });
await wait('document.querySelector("#routes-catalogue a")');
assert.match(await text('#routes-catalogue'), expect);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue [data-org-restart]")'), null);
assert.equal(await b.evaluate('document.querySelector("#routes-catalogue a").getAttribute("href")'), href);
await b.close();
}
});
test('settings-s1 B6: a stopped organization keeps its refused restart on screen and keeps the instance pages reachable', { timeout: 90000 }, async t => {
const { b, wait, text } = await setup(t, { path: '/#/orgs/gamma/settings/routing', init: stub({ restart: REFUSED }) });
await wait('document.querySelector("[data-org-down=gamma] [data-org-restart=gamma]")');
assert.match(await text('[data-org-down=gamma] .banner.err'), /^Gamma Home is stopped, so Routing can't be read\./);
// The reason the dashboard already reads (/api/workspace) shows before any restart is pressed.
await wait('document.querySelector("[data-org-down=gamma] [data-org-down-why]:not([hidden])")');
assert.equal(await text('[data-org-down=gamma] [data-org-down-why]'), 'Why it stopped: stopped by the owner');
// One Restart on the page: the header's bus banner steps aside.
assert.equal(await b.evaluate('[...document.querySelectorAll("[data-org-restart], #bus-restart")].filter(e => e.offsetParent).length'), 1);
// settings-p3 (re-check 3 P3-10): the why line sits under the headline, not beside it, at 1440.
assert.equal(await b.evaluate('(([a, w]) => w.getBoundingClientRect().top >= a.getBoundingClientRect().bottom)([...document.querySelectorAll("[data-org-down=gamma] .banner > p")])'), true, 'why line under the headline');
const primary = 'document.querySelector("[data-org-down=gamma] [data-org-restart=gamma]").classList.contains("primary")';
assert.equal(await b.evaluate(primary), true, 'Restart is primary before any refusal');
// The refusal's own repaint (console-restart.js paintOrg) is read when it lands, before the page renders again.
await b.evaluate(`window.__firstPaint = null; new MutationObserver((_, o) => { const d = document.querySelector("[data-org-down=gamma] [data-org-restart-detail]"); if (d) { window.__firstPaint = d.closest("[data-org-restart-box]").querySelector("[data-org-restart]").classList.contains("primary"); o.disconnect(); } }).observe(document.body, { subtree: true, childList: true }); true`);
await b.evaluate('document.querySelector("[data-org-down=gamma] [data-org-restart=gamma]").click(); true');
await wait('window.__writes.length === 1 && document.querySelector("[data-org-down=gamma] [data-org-restart-detail]")');
assert.equal(await b.evaluate('window.__firstPaint'), false, 'the refusal repaint does not keep Restart primary');
// The page renders again after the restart; the refusal stays, with its plain line first.
await new Promise(r => setTimeout(r, 500));
const receipt = await text('[data-org-down=gamma] [data-org-restart-receipt]');
assert.match(receipt, /^Gamma Home runs on test models, which can't share this machine with your model service\. It did not start\./);
assert.match(receipt, /bus start refused: fixture-proxy-configured/);
// settings-p3 (re-check 3 P3-4): a restart is refused the same way again, so Restart stays but is not
// the primary action, both in place and after the page renders again.
assert.equal(await b.evaluate(primary), false, 'Restart is not primary after the fixture refusal');
await b.evaluate('document.querySelector("[data-org-down=gamma]").dataset.old = "1"; location.hash = "#/orgs/gamma/settings/appearance"');
await wait('location.hash.endsWith("appearance") && !document.querySelector("[data-org-down][data-old]")');
await b.evaluate('location.hash = "#/orgs/gamma/settings/routing"'); await wait('document.querySelector("[data-org-down=gamma]:not([data-old]) [data-org-restart=gamma]")');
assert.equal(await b.evaluate(primary), false, 'still not primary after rendering again');
const links = await b.evaluate('[...document.querySelectorAll("[data-org-down=gamma] a")].map(a => [a.textContent, a.getAttribute("href")])');
assert.deepEqual(links, [['Appearance', '#/settings/appearance'], ['Model setup', '#/settings/model-setup'], ['Triage', '#/settings/triage'], ['Console', '#/settings/console']]);
// A link from the stopped page opens an instance page.
await b.evaluate('document.querySelector("[data-org-down=gamma] a[href=\'#/settings/model-setup\']").click(); true');
await wait('document.querySelector("#proxy-setup") || document.querySelector("h1")?.textContent === "Model setup"');
assert.notEqual(await text('h1'), 'Not found');
});
// settings-p3 (re-check 3 P3-5): a ready catalogue the bus picked up after it started carries the bus's
// restart notice (runtime.mjs RESTART_TO_LAUNCH); Routing puts the organization's Restart beside it,
// not primary, since Save routes is. Also (bus.js help): the Routing help names no harness.
test('settings-p3: a ready catalogue with the restart notice offers the organization Restart beside it, and the help names no harness', { timeout: 90000 }, async t => {
const notice = 'Restart this organization to start agents on these models.';
const view = { ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [notice] } };
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/routing', init: stub(), view });
await wait('document.querySelector(".routing-panel p.warn [data-org-restart=acme]")');
assert.deepEqual(await b.evaluate('(p => [p.firstChild.textContent.trim(), p.querySelector("[data-org-restart]").textContent, p.querySelector("[data-org-restart]").classList.contains("primary")])(document.querySelector(".routing-panel p.warn [data-org-restart=acme]").closest("p"))'),
[notice, 'Restart Acme Studio', false]);
assert.equal(await b.evaluate('window.MosaicConsole.RESTART_TO_LAUNCH'), notice);
const help = await b.evaluate('document.querySelector(".settings-helper").textContent');
assert.match(help, /A harness is the program that runs the model\. Preflight/);
assert.doesNotMatch(help, /Claude|such as/);
await b.evaluate('document.querySelector(".routing-panel p.warn [data-org-restart=acme]").focus(); true');
assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none');
});
// settings-p3 (re-check 3 P3-9): a reason that is not a stop (a host that runs but does not answer yet)
// is labeled as the last check, not as why the bus stopped.
test('settings-p3: a stopped page labels a reason that is not a stop as the last check', { timeout: 90000 }, async t => {
const { wait, text } = await setup(t, { path: '/#/orgs/gamma/settings/routing', init: stub(), gamma: { healthy: false, pid: 4343, boot: { ok: true, at: at(5), lastGood: at(5) } } });
await wait('document.querySelector("[data-org-down=gamma] [data-org-down-why]:not([hidden])")');
assert.equal(await text('[data-org-down=gamma] [data-org-down-why]'), 'Last check: the bus host is running but does not answer yet');
});
// settings-p3 (re-check 3 P3-11): two callers that ask while one read is pending are each told when it
// lands, each with a line that names its own organization label.
test('settings-p3: every caller of orgDownReason that asks while the read is pending gets its own line', { timeout: 90000 }, async t => {
const { b, wait } = await setup(t, { path: '/#/settings/appearance', init: stub(), gamma: { healthy: false, boot: { ok: false, at: at(5), lastGood: null, reason: 'bus start refused: fixture-proxy-configured' } } });
await wait('window.MosaicConsole?.orgDownReason');
await b.evaluate('window.__lines = []; MosaicConsole.orgDownReason("gamma", "First", v => __lines.push(["a", v?.plain])); MosaicConsole.orgDownReason("gamma", "Second", v => __lines.push(["b", v?.plain])); true');
await wait('window.__lines.length === 2');
assert.deepEqual(await b.evaluate('window.__lines.sort()'), [
['a', "First runs on test models, which can't share this machine with your model service. It did not start."],
['b', "Second runs on test models, which can't share this machine with your model service. It did not start."]]);
// The cached answer is built for the caller who asks, not kept from the first one.
assert.equal(await b.evaluate('MosaicConsole.orgDownReason("gamma", "Third").plain'), "Third runs on test models, which can't share this machine with your model service. It did not start.");
});
// Shots for the build report, current beside proposed: run with MOSAIC_UX_SHOTS=<dir>, on this tree and on
// the base tree with this file copied in. Each waits only for what both trees draw, then settles. At 390
// every visible select must show its chosen text in full, and no page scrolls sideways.
test('shots', { timeout: 600000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => {
const { mkdir, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const { TriageError, ROUTE_REFUSALS } = await import('../src/triage-host.mjs');
const dir = process.env.MOSAIC_UX_SHOTS; await mkdir(dir, { recursive: true });
const settle = () => new Promise(r => setTimeout(r, 1500));
const T = new Date(Date.now() - 20 * 60000).toISOString();
const status = { release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' },
init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', healthy: true, pid: 4242, port: 18432, listening: true },
fence: { set: false }, initLock: { present: false, clearable: false, blockers: [] }, fetch: { state: 'idle' }, restart: null, busy: null,
organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'unavailable', models: 0 } }, { id: 'gamma', proxy: 'shared', catalogue: { status: 'bus-unavailable' } }],
// settings-p3: the Ride all box below the restart list, with one organization that can ride, one
// skipped because its bus is down and one on stand-in models.
ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'ready' }, { id: 'gamma', state: 'bus-down' }, { id: 'west', state: 'fixture' }],
ownProxy: { available: false, state: 'not built', reason: 'The configuration has one proxy per instance.' }, next: ['accounts'] };
const triageRead = { route: { model: 'sonnet', harness: 'claude-code', cap: 200000, reset: '00:00', timeZone: 'Europe/Berlin', revision: 1, updatedAt: T }, revision: 1, send: true,
choices: { status: 'ready', models: [{ key: 'sonnet', label: 'Sonnet', available: true, harnesses: ['claude-code', 'pi'] }, { key: 'glm-flash', label: 'GLM Flash', available: true, harnesses: ['pi'] }] },
note: 'Saving a route does not start Triage. Triage also needs its key.' };
const extra = { '/proxy/accounts': { accounts: [{ accountId: 'a1', displayName: 'Claude work', provider: 'claude', status: 'active', priority: 0 }] }, '/proxy/keys': { keys: [] }, '/api/triage/route': triageRead };
const snapshot = { snapshotVersion: 1, at: T, console: { state: 'answering', at: T }, proxy: 'not read', systemConfig: { valid: true, exit: 0, code: null },
organizations: { count: 2, list: [{ id: 'acme', bus: { state: 'running', lastStart: { ok: true, at: T } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } },
{ id: 'gamma', bus: { state: 'stopped', lastStart: { ok: false, at: T } }, processing: 'not read', config: { valid: true, exit: 0, code: null } }] } };
const triage = { snapshotAt: () => Date.now(), refresh: async () => null,
state: async () => ({ route: 'set', running: false, lastExit: null, overCapUntil: null, snapshot, transcript: [] }),
message: async () => { throw new TriageError('triage-harness-incompatible', ROUTE_REFUSALS['triage-harness-incompatible']); } };
const PAGES = [
{ name: 'routing', path: '/#/orgs/acme/settings/routing', ready: 'document.querySelector(".routing-panel select")' },
// proxy-pickup: the bus names why it cannot use the running model service.
{ name: 'routing-cause', path: '/#/orgs/acme/settings/routing', ready: 'document.querySelector(".routing-panel select")',
view: { ...VIEW, catalogue: { status: 'unavailable', reason: 'proxy-not-configured', models: [], notices: ['The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.'] } } },
{ name: 'model-service', path: '/#/orgs/acme/settings/model-proxy', ready: 'document.querySelector("#proxy-setup") && !document.querySelector("#proxy-setup").hidden' },
{ name: 'triage-settings', path: '/#/orgs/acme/settings/triage', ready: 'document.querySelector("#triage-route select")' },
// Both trees draw a Restart for the stopped organization; the shot waits for it, presses it, and shows
// what stays on screen after the refusal.
{ name: 'org-down', path: '/#/orgs/gamma/settings/routing', ready: 'document.querySelector("h1") && document.querySelector("[data-org-restart=gamma], [data-bus-restart]")', after: async (b, wait) => {
await b.evaluate('(document.querySelector("[data-org-restart=gamma]") ?? document.querySelector("[data-bus-restart]")).click(); true'); await wait('window.__writes.length > 0');
} },
{ name: 'triage-drawer', path: '/#/dashboard', viewportOnly: true, ready: 'document.querySelector("#triage-open")', after: async (b, wait) => {
await b.evaluate('document.querySelector("#triage-open").click(); true');
await wait('document.querySelector("#triage-text") && !document.querySelector("#triage-text").disabled');
await b.evaluate('document.querySelector("#triage-text").focus(); true'); await b.call('Input.insertText', { text: 'is gamma healthy?' });
await b.evaluate('document.querySelector("#triage-send").click(); true');
await wait('document.querySelector("#triage-send-status")?.textContent.trim()');
} },
];
const report = [];
for (const page of PAGES) {
const f = await setup(t, { path: '/', init: stub({ service: status, restart: REFUSED, extra }), triage, view: page.view ?? VIEW });
// A phone draws its scrollbar over the page; headless Chromium would take 15px of the 390 for it.
await f.b.call('Emulation.setScrollbarsHidden', { hidden: true });
for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) {
await f.b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });
await f.b.viewport(width, width === 390 ? 844 : 900);
await f.b.navigate(`${f.base}/?shot=${page.name}-${scheme}-${width}${page.path.slice(1)}`);
await f.wait(`(${page.ready}) && !!window.MosaicAppearance`);
await f.b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`);
if (page.after) await page.after(f.b, f.wait);
await settle();
const fit = await f.b.evaluate(`(() => {
const out = [], probe = document.createElement('span'); probe.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap'; document.body.append(probe);
for (const s of document.querySelectorAll('select')) { if (!s.checkVisibility()) continue; const cs = getComputedStyle(s), r = s.getBoundingClientRect();
probe.style.font = cs.font; probe.textContent = s.selectedOptions[0]?.textContent ?? '';
const room = s.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
out.push({ label: s.getAttribute('aria-label') || s.id || s.name, text: probe.textContent, need: Math.ceil(probe.getBoundingClientRect().width), room: Math.floor(room), inside: r.left >= 0 && r.right <= innerWidth + 0.5 }); }
probe.remove(); return { selects: out, sideways: document.documentElement.scrollWidth > document.documentElement.clientWidth };
})()`);
const shot = `${page.name}-${width}-${scheme}.png`;
// The drawer is fixed to the window, so its shot is the window; every other page is shot whole.
if (page.viewportOnly) await f.b.screenshot(join(dir, shot));
else {
let metrics = await f.b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize;
// The footer is fixed to the window: grow the window to the page so it does not cover the page.
await f.b.viewport(width, Math.ceil(size.height)); await settle();
metrics = await f.b.call('Page.getLayoutMetrics'); size = metrics.cssContentSize || metrics.contentSize;
const { data } = await f.b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height), scale: 1 } });
await writeFile(join(dir, shot), Buffer.from(data, 'base64'));
}
report.push({ page: page.name, width, scheme, shot, ...fit });
}
await f.b.close();
}
await writeFile(join(dir, 'measure.json'), JSON.stringify(report, null, 1));
// Only the measurement is reported for the base tree; this tree must pass it.
if (!process.env.MOSAIC_UX_SHOTS_BASE) for (const r of report) {
assert.equal(r.sideways, false, `${r.shot} scrolls sideways`);
if (r.width === 390) for (const s of r.selects) { assert.ok(s.inside, `${r.shot}: ${s.label} runs off screen`); assert.ok(s.need <= s.room, `${r.shot}: ${s.label} cuts "${s.text}" (${s.need} > ${s.room})`); }
}
});
@@ -0,0 +1,498 @@
// #1873 settings slice 4 (DESIGN.md sections 2 and 4, CHANGES-R3): the Settings nav in four groups with
// the organization picker, organization pages at #/settings/<page>?org=<id>, the old addresses still
// open their pages, Model setup's four step cards and its one-press chain, the accounts list with
// health badges, Models offered read-only, the sidebar's model marks, and the Ride all done line that
// does not count an organization that turned the model service off.
// Part A runs the real server with fake organization buses (acme and north answer, gamma is stopped).
// Part B is the single-business Console with every API answer explicit (w15-fixture.mjs).
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
import { ReadError } from '../src/reads.mjs';
import { w15Fixture } from './w15-fixture.mjs';
// ---- Part A: organizations -------------------------------------------------------------------
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
{ id: 'north', label: 'North Works', theme: 'cobalt', busHealthy: true },
];
const VIEW = {
business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi'], models: ['fixture-deterministic'],
providerModels: { 'fixture-deterministic': { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic' } },
levels: { pi: ['off', 'low'] }, instances: {}, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] },
};
async function orgFixture() {
const { checkRootAgents } = await import('../../organization/src/index.mjs');
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) };
const empty = () => Promise.resolve([]);
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme }, roles: { chief: { definition: 'chief-of-staff' } }, projects: {} },
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: new Date().toISOString(), lastGood: null, reason: 'stopped by the owner' } }),
options: () => ({ bus: { inbox: empty, agents: empty, 'thread.claims': empty, tasks: empty, usage: () => Promise.resolve({}), limits: () => Promise.resolve({}), decisions: empty }, chat: { threads: empty, projects: empty } }),
});
const organizations = {
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
if (!org.busHealthy) return { busHealthy: false, reads: { settings: async () => { throw new ReadError('bus-unavailable'); } }, bus: {}, chat: { projects: empty, threads: empty } };
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {} }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => ({ ...VIEW, business: id }), instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) },
chat: { projects: empty, threads: empty },
};
},
};
return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } };
}
// The instance owner's flags on /api/config and the model service status, by path suffix (display.js
// scopes some reads under /api/orgs/<id>/). Everything else is the real server.
const SERVICE_UP = { next: ['accounts'], init: { initialized: true, files: [] }, release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] };
const ownerStub = (service = SERVICE_UP, extra = {}) => `(() => {
const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service, accounts: [], routes: null, posts: {}, ...extra })}; window.__writes = [];
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
window.fetch = async (input, init = {}) => {
const url = new URL(typeof input === 'string' ? input : input.url, location.href), path = url.pathname, method = (init.method || 'GET').toUpperCase();
if (method !== 'GET' && /\\/proxy\\//.test(path)) { window.__writes.push(path); const key = Object.keys(__s4.posts).find(k => path.endsWith(k)); const a = key ? __s4.posts[key] : { status: 500, body: { error: 'stub' } };
if (a === 'hang') return new Promise(() => {}); if (a.service) __s4.service = a.service; return json(a.body ?? {}, a.status ?? 200); }
if (method !== 'GET') return real(input, init);
if (__s4.routes && /\\/bus\\/routes$/.test(path)) return json(__s4.routes);
if (/\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(path)) { const c = await (await real(input, init)).json(); return json({ ...c, orgSetup: true, proxyAdmin: true, proxyAdminSend: true, ...(/\\/orgs\\//.test(path) ? { settingsSend: true } : {}) }); }
if (path.endsWith('/proxy/admin/status')) return json(__s4.service);
if (path.endsWith('/proxy/accounts')) return json({ accounts: __s4.accounts });
if (path.endsWith('/proxy/keys')) return json({ keys: [] });
if (path.endsWith('/triage/route')) return json({ route: null });
return real(input, init);
};
})();`;
async function orgSetup(t, { path, viewport = [1440, 900], service, extra } = {}) {
const { organizations, agentLevels } = await orgFixture();
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, triage: null, send: async () => ({}), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: ownerStub(service, extra) });
await b.navigate(`http://127.0.0.1:${server.address().port}${path}`);
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<250;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error("wait failed: "+${JSON.stringify(expression)}+" HASH "+location.hash)})()`);
return { b, wait, base: `http://127.0.0.1:${server.address().port}`, text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`) };
}
test('settings-s4: the nav has four groups, the organization pages carry ?org=, the picker switches organization, and there is no Members row', { timeout: 90000 }, async t => {
const { b, wait, text } = await orgSetup(t, { path: '/#/settings/routing?org=acme' });
await wait('document.querySelector("#org-pick") && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=acme\'][aria-current=page]")');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#settings-nav .settings-group")].map(g => (g.querySelector("label") ?? g).textContent.trim())'),
['You', 'Your models', 'All organizations', 'This organization']);
const links = await b.evaluate('[...document.querySelectorAll("#settings-nav a")].map(a => a.getAttribute("href"))');
assert.deepEqual(links.slice(0, 2), ['#/settings/appearance', '#/settings/model-setup']);
assert.ok(links.includes('#/settings/triage'), 'the instance owner sees Triage under Your models');
for (const page of ['organizations', 'console', 'about']) assert.ok(links.includes(`#/settings/${page}`), page);
const orgLinks = links.filter(h => /\?org=/.test(h));
assert.deepEqual(orgLinks.map(h => h.replace(/^#\/settings\/|\?org=acme$/g, '')), ['routing', 'agents', 'limits', 'tokens', 'assistant', 'business']);
assert.equal(links.some(h => /members/.test(h)), false, 'no Members row');
// The picker lists every organization, the open one selected, and sits above the organization's pages.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#org-pick option")].map(o => [o.value, o.textContent, o.selected])'),
[['acme', 'Acme Studio', true], ['gamma', 'Gamma Home', false], ['north', 'North Works', false]]);
assert.match(await text('#breadcrumbs'), /Acme Studio/);
// Every page is one click from the open nav: all its links are visible at 1440.
assert.equal(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].every(a => a.checkVisibility())'), true);
await b.evaluate('(() => { const s = document.querySelector("#org-pick"); s.value = "north"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()');
await wait('location.hash === "#/settings/routing?org=north" && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=north\']")');
await wait('/North Works/.test(document.querySelector("#breadcrumbs")?.textContent ?? "")');
// Keyboard: the picker takes focus with a visible ring.
await b.evaluate('document.querySelector("#org-pick").focus(); true');
assert.notEqual(await b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none');
});
test('settings-s4: the old addresses still open their pages', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/orgs/acme/settings/routing' });
await wait('location.hash === "#/settings/routing?org=acme"');
await b.evaluate('location.hash = "#/settings/model-proxy"; true');
await wait('location.hash === "#/settings/model-setup" && document.querySelector("#proxy-setup")');
assert.equal(await b.evaluate('document.querySelector("#settings-page-title")?.textContent'), 'Model setup');
await b.evaluate('location.hash = "#/orgs/acme/settings/model-proxy"; true');
await wait('!location.hash.includes("model-proxy") && document.querySelector("#proxy-setup")');
assert.equal(await b.evaluate('document.querySelector("#settings-page-title")?.textContent'), 'Model setup');
await b.evaluate('location.hash = "#/orgs/north/settings/agents"; true');
await wait('location.hash === "#/settings/agents?org=north"');
});
test('settings-s4: at 390 the section button names the organization and the page, and nothing scrolls sideways', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/routing?org=acme', viewport: [390, 844] });
await wait('document.querySelector("#settings-disclosure strong")?.textContent.includes("Models")');
assert.equal(await b.evaluate('document.querySelector("#settings-disclosure strong").textContent.trim()'), 'Acme Studio · Models');
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true);
await b.evaluate('location.hash = "#/settings/model-setup"; true');
await wait('document.querySelector("#setup-step-service")?.dataset.state');
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true);
});
const mark = id => `document.querySelector('[data-workspace-org=${id}] .ws-dot')?.title`;
test('settings-s4: the sidebar marks an organization that needs a restart and one that can\'t start, from the setup status', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready' } }],
ride: [{ id: 'gamma', state: 'fixture', running: false }] };
const { b, wait } = await orgSetup(t, { path: '/#/dashboard', service });
await wait(`${mark('acme')} === 'needs restart' && ${mark('gamma')} === "can't start"`);
assert.equal(await b.evaluate(mark('north')), 'bus running');
assert.equal(await b.evaluate("document.querySelector('[data-workspace-org=acme] .ws-dot b').textContent"), '◐');
assert.equal(await b.evaluate("document.querySelector('[data-workspace-org=gamma] .ws-dot b').textContent"), '▲');
});
test('settings-s4: the sidebar marks an organization paused while the model service is set up but not running', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, next: ['unit-start'], unit: { ...SERVICE_UP.unit, active: 'inactive', listening: false }, ride: [{ id: 'acme', state: 'already' }] };
const { b, wait } = await orgSetup(t, { path: '/#/dashboard', service });
await wait(`${mark('acme')} === 'paused'`);
assert.equal(await b.evaluate(mark('north')), 'bus running', 'an organization that does not use the model service has no mark');
assert.equal(await b.evaluate(mark('gamma')), 'bus stopped');
});
// settings-s4 review F1: the picker on a page that is not an organization's keeps the #/settings/ base.
test('settings-s4 review F1: picking an organization from Model setup opens its Routing page at #/settings/routing?org=', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup' });
// A route change repaints the picker, so the pick waits for the select and changes it in one step.
const pick = id => wait(`(() => { const s = document.querySelector("#org-pick"); if (!s || ![...s.options].some(o => o.value === "${id}")) return false; s.value = "${id}"; s.dispatchEvent(new Event("change", { bubbles: true })); return true; })()`);
await wait('document.querySelector("#org-pick") && document.querySelector("#proxy-setup")');
await pick('north');
await wait('location.hash === "#/settings/routing?org=north" && document.querySelector("#settings-nav a[href=\'#/settings/routing?org=north\'][aria-current=page]")');
await wait('/North Works/.test(document.querySelector("#breadcrumbs")?.textContent ?? "")');
assert.equal(await b.evaluate('location.hash.includes("#/orgs/")'), false);
for (const from of ['appearance', 'organizations']) {
await b.evaluate(`location.hash = "#/settings/${from}"; true`);
await wait(`document.querySelector("#settings-nav a[href='#/settings/${from}'][aria-current=page]") && document.querySelector("#org-pick")`);
await pick('acme');
await wait('location.hash === "#/settings/routing?org=acme" && document.querySelector("#org-pick")?.value === "acme"');
await pick('north');
await wait('location.hash === "#/settings/routing?org=north"');
}
});
// settings-s4 review F2: the organization the sidebar marks "can't start" is named on step 3 in the same words.
test('settings-s4 review F2: a stand-in organization with its bus stopped reads "can\'t start" in the sidebar and on Model setup step 3, with the fix', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }],
ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'already' }, { id: 'gamma', state: 'fixture', running: false }] };
const accounts = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }];
const { b, wait, text } = await orgSetup(t, { path: '/#/settings/model-setup', service, extra: { accounts } });
await wait(`${mark('gamma')} === "can't start"`);
await wait(`/can't start/.test(document.querySelector(${JSON.stringify(STEP3)})?.textContent ?? "")`);
assert.equal(await text(STEP3), "The model service is set up. Gamma Home can't start: it uses stand-in models and its bus is stopped. Move it to your models under Use your models in every organization, then start its bus.");
assert.equal(await b.evaluate('document.querySelector("#setup-step-organizations").dataset.state'), 'bad');
const item = await b.evaluate('document.querySelector("#proxy-ride-fixtures li").firstChild.textContent.trim()');
assert.equal(item, "Gamma Home can't start: it uses stand-in models and its bus is stopped. Move it to the owner's models, then start its bus.");
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=gamma]").textContent'), 'Move Gamma Home');
assert.equal(await b.evaluate('document.querySelector("[data-ride-move=gamma]").checkVisibility()'), true);
// The organizations that need nothing get no mark.
assert.equal(await b.evaluate(mark('acme')), 'bus running');
});
// settings-s4 review N8: a fence to clear while the service runs is not "paused".
test('settings-s4 review N8: no paused mark while the service runs and only a fence is left to clear', { timeout: 90000 }, async t => {
const service = { ...SERVICE_UP, next: ['fence-clear'], fence: { set: true }, ride: [{ id: 'acme', state: 'already' }] };
const { b, wait } = await orgSetup(t, { path: '/#/dashboard', service });
await wait(`${mark('acme')} === 'bus running' && ${mark('north')} === 'bus running'`);
await new Promise(r => setTimeout(r, 1500));
assert.equal(await b.evaluate(mark('acme')), 'bus running');
});
// ---- Part B: Model setup ---------------------------------------------------------------------
const T = '2026-11-11T12:00:00.000Z';
const fresh = {
release: { fetched: false, verified: false, version: '8.0.42', panelVersion: '1.26.7' },
init: { initialized: false, partial: false, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' },
fence: { set: false }, initLock: { present: false, clearable: false, blockers: [] }, fetch: { state: 'idle' }, restart: null, busy: null,
organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }], ownProxy: { available: false, state: 'not built', reason: 'One proxy per instance.' }, next: ['fetch'],
};
const fetched = { ...fresh, release: { ...fresh.release, fetched: true, verified: true }, fetch: { state: 'done', receipt: { op: 'fetch', time: T, version: '8.0.42' } }, next: ['init'] };
const configured = { ...fetched, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, next: ['unit-install'] };
const installed = { ...configured, unit: { ...configured.unit, installed: true }, next: ['unit-start'] };
const running = { ...installed, unit: { ...installed.unit, active: 'active', pid: 4242, port: 18432, listening: true }, next: ['accounts'] };
const config = { send: true, devOwner: true, proxyAdmin: true, proxyAdminSend: true };
const accounts = list => ({ 'GET /api/proxy/accounts': { body: { accounts: list } }, 'GET /api/proxy/keys': { body: { keys: [] } } });
const admin = b => b.evaluate('window.__writes.filter(w => w.path.startsWith("/api/proxy/admin/")).map(w => w.path.slice(17))');
// A primary button is one drawn with the accent fill, whatever its class: a submit is drawn that way too.
const primaries = b => b.evaluate(`(() => { const host = document.querySelector(".model-setup"), probe = document.createElement("button"); probe.className = "btn primary"; host.append(probe);
const fill = getComputedStyle(probe).backgroundColor; probe.remove();
return [...host.querySelectorAll("button, a")].filter(e => e.checkVisibility() && getComputedStyle(e).backgroundColor === fill).map(e => e.id || e.textContent); })()`);
const STEP3 = '#setup-step-organizations [data-step-summary]';
// The status the page reads follows the writes it has made, as the host's would.
const following = stages => `(() => {
const stages = ${JSON.stringify(stages)};
const status = () => { const paths = window.__writes.map(w => w.path); let s = stages[0][1]; for (const [path, next] of stages) if (!path || paths.includes(path)) s = next; return s; };
Object.defineProperty(window.__scenario, '/api/proxy/admin/status', { get: status, enumerable: true, configurable: true });
})();`;
test('settings-s4: one press runs fetch, init, install and start in that order, each once, and step 2 is next', { timeout: 90000 }, async t => {
const receipt = op => ({ body: { receipt: { op, time: T } } });
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, 'POST /api/proxy/admin/fetch': { status: 202, body: { state: 'running' } },
'POST /api/proxy/admin/init': receipt('init'), 'POST /api/proxy/admin/unit/install': receipt('unit-install'), 'POST /api/proxy/admin/unit/start': receipt('unit-start'), ...accounts([]), '/api/triage/route': { route: null } } });
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: following([[null, fresh], ['/api/proxy/admin/fetch', fetched], ['/api/proxy/admin/init', configured], ['/api/proxy/admin/unit/install', installed], ['/api/proxy/admin/unit/start', running]]) });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "fetch"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Set up model service');
assert.deepEqual(await primaries(b), ['proxy-setup-go'], 'one primary button on the page');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".setup-step h3")].map(h => h.textContent)'), ['Model service', 'Accounts and models', 'Organizations', 'Triage']);
assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts").dataset.state'), 'wait');
await b.evaluate('document.querySelector("#proxy-setup-go").click(); true');
await wait('document.querySelector("#setup-step-service").dataset.state === "done"');
assert.deepEqual(await admin(b), ['fetch', 'init', 'unit/install', 'unit/start']);
assert.deepEqual(await b.evaluate('JSON.parse(window.__writes.find(w => w.path === "/api/proxy/admin/init").body)'), { generate: true });
assert.match(await b.evaluate('document.querySelector("#setup-step-service [data-step-summary]").textContent'), /^Running\. Answers on this machine, port 18432\.$/);
await wait('document.querySelector("#setup-step-accounts").dataset.state === "next"');
assert.deepEqual(await primaries(b), ['proxy-login-go'], 'the one primary moves to step 2');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude');
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
test('settings-s4: a step that fails stops the run with Try again, keeps the finished steps, and shows the service\'s last lines', { timeout: 90000 }, async t => {
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, 'POST /api/proxy/admin/init': { body: { receipt: { op: 'init', time: T } } },
'POST /api/proxy/admin/unit/install': { status: 500, body: { error: 'unit-install-failed' } }, 'GET /api/proxy/accounts': { status: 503, body: { error: 'not-configured' } }, 'GET /api/proxy/keys': { status: 503, body: { error: 'not-configured' } } } });
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: following([[null, fetched], ['/api/proxy/admin/init', configured]]) });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "init"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Continue setup');
// Resume: the download is done, the rest is not started.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => [li.dataset.stage, li.className])'), [['fetch', 'ok'], ['init', 'todo'], ['start', 'todo'], ['answer', 'todo']]);
await b.evaluate('document.querySelector("#proxy-setup-go").click(); true');
await wait('document.querySelector("#setup-step-service").dataset.state === "bad" && document.querySelector("#proxy-setup-go")?.textContent === "Try again"');
assert.deepEqual(await admin(b), ['init', 'unit/install'], 'nothing is retried by itself');
assert.equal(await b.evaluate('document.querySelector("#setup-step-service [data-step-badge]").textContent'), 'Setup stopped');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.className)'), ['ok', 'ok', 'bad', 'todo']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-progress li")].map(li => li.firstChild.textContent)'), ['Downloaded and checked', 'Configured', 'Start the service: did not finish', 'Check it answers']);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-lines").checkVisibility() && document.querySelector("#proxy-setup-lines summary").textContent'), "The service's last lines");
assert.deepEqual(await primaries(b), ['proxy-setup-go']);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-advanced summary").textContent'), 'Advanced: programs, port, timeouts');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-tech summary").textContent'), 'Technical details: release, service, history');
});
test('settings-s4: ?step= opens a done card; without it a done card folds to its line', { timeout: 90000 }, async t => {
const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }];
for (const [hash, shown] of [['#/settings/model-setup?step=accounts', true], ['#/settings/model-setup', false]]) {
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null } } });
await b.navigate(f.base + '/' + hash);
await wait('document.querySelector("#setup-step-accounts")?.dataset.state === "done"');
assert.equal(await b.evaluate('!document.querySelector("#setup-step-accounts-body").hidden'), shown, hash);
assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts .step-toggle").textContent'), shown ? 'Hide' : 'Show');
await b.close();
}
});
test('settings-s4: accounts read as rows with kind and health, the provider picks sign-in or a key, and a sign-in can be cancelled', { timeout: 90000 }, async t => {
const list = [
{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 2 },
{ accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'error', priority: 1 },
{ accountId: 'a3', provider: 'z.ai', displayName: 'z.ai key', status: 'disabled', priority: 0, models: ['glm-4.6'] },
{ accountId: 'a4', provider: 'claude', displayName: 'Claude old', status: 'mystery', priority: 0 },
];
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null },
'POST /api/proxy/login/start': { body: { url: 'https://claude.ai/oauth/authorize?state=s4', state: 's4' } }, 'POST /api/proxy/login/status': { body: { status: 'wait' } }, 'POST /api/proxy/login/cancel': { body: { status: 'cancelled' } }, 'POST /api/proxy/login/submit': { body: { status: 'wait' } } } });
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.open = () => null;' });
await b.navigate(f.base + '/#/settings/model-setup');
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li")].map(li => [...li.children].map(c => c.innerText.replace(/\\s+/g, " ").trim()))'), [
['Claude', 'Subscription Claude work', 'Ready'], ['ChatGPT / Codex', 'Subscription Codex home', 'Not working'], ['z.ai', 'API key z.ai key', 'Off'], ['Claude', 'Subscription Claude old', 'Unknown']]);
assert.equal(await b.evaluate('document.querySelector("#setup-step-accounts").dataset.state'), 'bad', 'an account that is not working needs the owner');
assert.match(await b.evaluate('document.querySelector("#setup-step-accounts [data-step-summary]").textContent'), /ChatGPT \/ Codex \(subscription\): not working/);
assert.match(await b.evaluate('document.querySelector("#setup-step-accounts").textContent'), /Removing an account is not built yet\./);
// The provider picks how to add: a sign-in for a subscription, Check and add for an API key.
await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-login-go").checkVisibility(), document.querySelector("#proxy-apikey").checkVisibility(), document.querySelector("#proxy-apikey button[type=submit]").textContent]'), [false, true, 'Check and add']);
assert.ok((await primaries(b)).length <= 1, 'one primary button with the key form open');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "codex"; s.dispatchEvent(new Event("change")); return true; })()');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to ChatGPT / Codex');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "claude"; s.dispatchEvent(new Event("change")); document.querySelector("#proxy-login-start").requestSubmit(); return true; })()');
await wait('!document.querySelector("#proxy-signin").hidden');
assert.ok((await primaries(b)).length <= 1, 'one primary button while signing in');
assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-login-submit button[type=submit]")).backgroundColor === getComputedStyle(document.querySelector("#proxy-login-cancel")).backgroundColor'), true, 'Finish sign-in is a plain button');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-return summary").textContent'), 'The sign-in tab did not come back');
assert.equal(await b.evaluate('document.querySelector("#proxy-login-cancel").disabled'), false);
// Paste-back: the address from a tab that did not come back goes to login/submit and the box is cleared.
await b.evaluate('(() => { const f = document.querySelector("#proxy-login-submit"); f.elements.redirect_url.value = "http://localhost:54545/callback?code=c&state=s4"; f.requestSubmit(); return true; })()');
await wait('window.__writes.some(w => w.path === "/api/proxy/login/submit") && /Address submitted/.test(document.querySelector("#proxy-login-message").textContent)');
assert.deepEqual(await b.evaluate('JSON.parse(window.__writes.find(w => w.path === "/api/proxy/login/submit").body)'), { redirect_url: 'http://localhost:54545/callback?code=c&state=s4' });
assert.equal(await b.evaluate('document.querySelector("#proxy-login-submit").elements.redirect_url.value'), '');
await b.evaluate('document.querySelector("#proxy-login-cancel").click(); true');
await wait('document.querySelector("#proxy-signin").hidden && document.querySelector("#proxy-login-message").textContent === "Sign-in cancelled."');
assert.deepEqual(await b.evaluate('window.__writes.map(w => w.path)').then(p => p.filter(x => /login\/(start|cancel)/.test(x))), ['/api/proxy/login/start', '/api/proxy/login/cancel']);
});
test('settings-s4 chat-fail F3: an account row shows the accounts read\'s reason beside its state, as text, and nothing when the field is absent or empty', { timeout: 90000 }, async t => {
const out = 'The account is out of usage. It resets at 2099-03-04 05:06 UTC. Wait until then, or add another account.';
const signin = 'The account needs to sign in again. Sign in again, or add another account. <img src=x onerror=window.__xss=1>';
const list = [
{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'unavailable', priority: 2, reason: out },
{ accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'error', priority: 1, reason: signin },
{ accountId: 'a3', provider: 'claude', displayName: 'Claude spare', status: 'error', priority: 0, reason: '' },
{ accountId: 'a4', provider: 'codex', displayName: 'Codex work', status: 'active', priority: 0 },
];
for (const width of [1440, 390]) {
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': running, ...accounts(list), '/api/triage/route': { route: null } } });
await b.viewport(width, width === 390 ? 844 : 900);
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 4');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li")].map(li => [...li.children].map(c => c.textContent.replace(/\\s+/g, " ").trim()))'), [
['Claude', 'SubscriptionClaude work', 'Not available', out], ['ChatGPT / Codex', 'SubscriptionCodex home', 'Not working', signin],
['Claude', 'SubscriptionClaude spare', 'Not working'], ['ChatGPT / Codex', 'SubscriptionCodex work', 'Ready']], `${width}: the reason follows the state; absent or empty shows nothing`);
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-accounts img").length + (window.__xss ?? 0)'), 0, 'the reason is text, never markup');
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-accounts .account-reason")].every(p => p.checkVisibility() && p.getBoundingClientRect().right <= document.documentElement.clientWidth)'), true);
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, `${width}: nothing scrolls sideways`);
await b.close();
}
});
test('settings-s4: Models offered lists each provider\'s models read-only with a count, a search past eight, and Coming later', { timeout: 90000 }, async t => {
const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }, { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'active', priority: 0 }];
const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-model-${i}`, available: true }))
.concat([{ module: 'cliproxy', upstream: 'codex', model: 'gpt-x', available: true }, { module: 'cliproxy', upstream: 'codex', model: 'gpt-gone', available: false }, { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic', available: true }]);
const status = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 11 } }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': status, ...accounts(list), '/api/triage/route': { route: null },
'/api/orgs/acme/bus/routes': { rows: [{ catalogue: { status: 'ready', models } }] } } });
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 2');
await b.evaluate('document.querySelector("#proxy-offered").open = true; true');
await wait('document.querySelectorAll("#proxy-offered-list details[data-offered]").length === 2');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list details[data-offered] > summary")].map(s => s.textContent)'), ['Claude models offered: 10', 'ChatGPT / Codex models offered: 1']);
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list input[type=checkbox]")].every(c => c.disabled)'), true, 'read-only');
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list li")].every(li => li.lastElementChild.textContent === "Coming later")'), true);
assert.equal(await b.evaluate('!!document.querySelector("#proxy-offered-list details[data-offered=claude] input[type=search]")'), true, 'more than eight: a search box');
assert.equal(await b.evaluate('!!document.querySelector("#proxy-offered-list details[data-offered=codex] input[type=search]")'), false, 'one model: no search box');
await b.evaluate('(() => { document.querySelector("#proxy-offered-list details[data-offered=claude]").open = true; const i = document.querySelector("#proxy-offered-list details[data-offered=claude] input[type=search]"); i.value = "model-7"; i.dispatchEvent(new Event("input")); return true; })()');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list details[data-offered=claude] li")].filter(li => !li.hidden).map(li => li.dataset.model)'), ['claude-model-7']);
assert.deepEqual(await b.evaluate('window.__writes'), [], 'reading the models writes nothing');
});
test('settings-s4 review N9: before setup, every control under Advanced takes focus with a visible ring', { timeout: 90000 }, async t => {
const fresh = { ...SERVICE_UP, release: { ...SERVICE_UP.release, fetched: false, verified: false }, init: { initialized: false, partial: false, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' }, organizations: [], next: ['fetch'] };
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: fresh });
await wait('document.querySelector("#proxy-setup-go")?.dataset.next === "fetch" && !document.querySelector("#proxy-setup-advanced").hidden');
await b.evaluate('(() => { const d = document.querySelector("#proxy-setup-advanced"); d.open = true; d.querySelector("summary").focus(); return true; })()');
await wait('document.querySelector("#proxy-setup-advanced").open && document.activeElement?.closest("#proxy-setup-advanced")');
const visited = [], noRing = [];
for (let i = 0; i < 20; i++) {
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
const r = await b.evaluate(`(() => { const e = document.activeElement; if (!e || !e.closest("#proxy-setup-advanced")) return null; const cs = getComputedStyle(e);
return { key: e.id || e.name || e.tagName, ring: (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none') }; })()`);
if (!r) break; visited.push(r.key); if (!r.ring) noRing.push(r.key);
}
assert.ok(visited.includes('proxy-setup-port') && visited.includes('proxy-setup-first'), JSON.stringify(visited));
assert.deepEqual(noRing, []);
});
test('settings-s4 P3: the done line names an organization that turned the model service off and does not count it as waiting', { timeout: 90000 }, async t => {
const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }];
const done = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 2 } }], ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'removed' }] };
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': done, ...accounts(list), '/api/triage/route': { route: { model: 'm' } } } });
await b.navigate(f.base + '/#/settings/model-setup');
await wait(`document.querySelector(${JSON.stringify(STEP3)})?.dataset.next === "done"`);
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), 'The model service is set up and every organization that uses it can see your models. north turned it off, and Ride all leaves it off.');
assert.equal(await b.evaluate('document.querySelector("#setup-step-organizations").dataset.state'), 'done');
assert.deepEqual(await primaries(b), [], 'nothing left to do: no primary button');
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
// Shots for the build report, beside the mockups: run with MOSAIC_UX_SHOTS=<dir>. Each page is shot whole
// at 390 and 1440, light and dark. Every page is measured: nothing scrolls sideways, every visible select
// shows its chosen text, and every visible control shows a focus ring when it takes keyboard focus.
test('shots', { timeout: 900000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => {
const { mkdir, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const dir = process.env.MOSAIC_UX_SHOTS; await mkdir(dir, { recursive: true });
const settle = () => new Promise(r => setTimeout(r, 1200));
const fresh = { ...SERVICE_UP, release: { ...SERVICE_UP.release, fetched: false, verified: false }, init: { initialized: false, partial: false, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' }, fetch: { state: 'idle' }, organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }, { id: 'north', proxy: 'shared', catalogue: null }], next: ['fetch'] };
const fetched = { ...fresh, release: { ...fresh.release, fetched: true, verified: true }, next: ['init'] };
const configured = { ...fetched, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, next: ['unit-install'] };
const ready = [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }];
const up = { ...SERVICE_UP, organizations: ready, ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'already' }, { id: 'gamma', state: 'bus-down' }] };
const accounts = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }, { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'active', priority: 0 }];
const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-sonnet-4-${i}`, available: true }))
.concat(['gpt-5.1', 'gpt-5.1-codex'].map(model => ({ module: 'cliproxy', upstream: 'codex', model, available: true })));
const routes = { rows: [{ ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models, notices: [] } }] };
const go = 'document.querySelector("#proxy-setup-go").click(); true';
const PAGES = [
{ name: 'nav-open', path: '/#/settings/routing?org=acme', ready: 'document.querySelector("#org-pick")', after: async (b, wait, width) => {
if (width === 390) { await b.evaluate('document.querySelector("#settings-disclosure").click(); true'); await wait('document.querySelector("#settings-nav a").checkVisibility()'); } } },
{ name: 'models-nothing', path: '/#/settings/model-setup', service: fresh, ready: 'document.querySelector("#proxy-setup-go")?.dataset.next === "fetch"' },
{ name: 'models-setting-up', path: '/#/settings/model-setup', service: fetched, extra: { posts: { '/admin/init': { body: { receipt: { op: 'init' } }, service: configured }, '/admin/unit/install': 'hang' } },
ready: 'document.querySelector("#proxy-setup-go")?.dataset.next === "init"', after: async (b, wait) => { await b.evaluate(go); await wait('document.querySelector("#proxy-setup-progress li.run")'); } },
{ name: 'models-setup-failed', path: '/#/settings/model-setup', service: fetched, extra: { posts: { '/admin/init': { body: { receipt: { op: 'init' } }, service: configured }, '/admin/unit/install': { status: 500, body: { error: 'unit-install-failed' } } } },
ready: 'document.querySelector("#proxy-setup-go")?.dataset.next === "init"', after: async (b, wait) => { await b.evaluate(go); await wait('document.querySelector("#proxy-setup-go").textContent === "Try again"'); } },
{ name: 'models-running', path: '/#/settings/model-setup', service: { ...SERVICE_UP, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 0 } }] }, ready: 'document.querySelector("#setup-step-accounts")?.dataset.state === "next"' },
{ name: 'models-accounts', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2' },
{ name: 'models-accounts-signin', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes, posts: { '/login/start': { body: { url: 'https://claude.ai/oauth/authorize?state=shot', state: 'shot' } }, '/login/status': { body: { status: 'wait' } } } },
ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async (b, wait) => {
await b.evaluate('window.open = () => null; document.querySelector("#proxy-add-box").open = true; document.querySelector("#proxy-login-start").requestSubmit(); true'); await wait('!document.querySelector("#proxy-signin").hidden'); } },
{ name: 'models-accounts-key', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async b => {
await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()'); } },
{ name: 'models-offered', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async (b, wait) => {
await b.evaluate('document.querySelector("#proxy-offered").open = true; true'); await wait('document.querySelector("#proxy-offered-list details[data-offered=claude]")');
await b.evaluate('document.querySelector("#proxy-offered-list details[data-offered=claude]").open = true; true'); } },
{ name: 'models-problems', path: '/#/settings/model-setup', service: { ...up, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }],
ride: [{ id: 'acme', state: 'already' }, { id: 'north', state: 'already' }, { id: 'gamma', state: 'fixture', running: false }] }, extra: { accounts: [accounts[0], { ...accounts[1], status: 'error' }], routes },
ready: 'document.querySelector("#setup-step-accounts")?.dataset.state === "bad"' },
{ name: 'models-advanced', path: '/#/settings/model-setup', service: up, extra: { accounts, routes }, ready: 'document.querySelector("#setup-step-service")?.dataset.state === "done"', after: async b => {
await b.evaluate('document.querySelector("#proxy-setup-advanced").open = true; document.querySelector("#proxy-setup-tech").open = true; true'); } },
{ name: 'org-models', path: '/#/settings/routing?org=acme', service: up, ready: 'document.querySelector(".routing-panel select, .routing-panel")' },
{ name: 'sidebar-marks', path: '/#/dashboard', service: { ...up, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }], ride: [{ id: 'gamma', state: 'fixture', running: false }] },
ready: `${mark('acme')} === 'needs restart'`, viewportOnly: true },
];
const report = [];
for (const page of PAGES) for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) {
const f = await orgSetup(t, { path: '/', service: page.service ?? up, extra: page.extra, viewport: [width, width === 390 ? 844 : 900] });
await f.b.call('Emulation.setScrollbarsHidden', { hidden: true });
await f.b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });
await f.b.navigate(`${f.base}/?shot=${page.name}-${scheme}-${width}${page.path.slice(1)}`);
await f.wait(`(${page.ready}) && !!window.MosaicAppearance`);
await f.b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`);
if (page.after) await page.after(f.b, f.wait, width);
await settle();
const fit = await f.b.evaluate(`(() => {
const out = [], probe = document.createElement('span'); probe.style.cssText = 'position:absolute;visibility:hidden;white-space:nowrap'; document.body.append(probe);
for (const s of document.querySelectorAll('select')) { if (!s.checkVisibility()) continue; const cs = getComputedStyle(s), r = s.getBoundingClientRect();
probe.style.font = cs.font; probe.textContent = s.selectedOptions[0]?.textContent ?? '';
out.push({ label: s.id || s.name, text: probe.textContent, need: Math.ceil(probe.getBoundingClientRect().width), room: Math.floor(s.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight)), inside: r.left >= 0 && r.right <= innerWidth + 0.5 }); }
probe.remove(); return { selects: out, sideways: document.documentElement.scrollWidth > document.documentElement.clientWidth };
})()`);
// Keyboard focus: Tab through the page and note any control whose ring is not visible.
const noRing = [], seen = new Set();
for (let i = 0; i < 120; i++) {
await f.b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
await f.b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
const r = await f.b.evaluate(`(() => { const e = document.activeElement; if (!e || e === document.body) return null; const cs = getComputedStyle(e);
const ring = (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none');
return { key: e.id || e.getAttribute('href') || e.tagName + ':' + (e.textContent || '').trim().slice(0, 30), ring }; })()`);
if (!r || seen.has(r.key)) break; seen.add(r.key);
if (!r.ring) noRing.push(r.key);
}
await f.b.evaluate('document.activeElement?.blur(); window.scrollTo(0, 0); true'); await settle();
const shot = `${page.name}-${width}-${scheme}.png`;
if (page.viewportOnly) await f.b.screenshot(join(dir, shot));
else {
let metrics = await f.b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize;
await f.b.viewport(width, Math.ceil(size.height)); await settle();
metrics = await f.b.call('Page.getLayoutMetrics'); size = metrics.cssContentSize || metrics.contentSize;
const { data } = await f.b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height), scale: 1 } });
await writeFile(join(dir, shot), Buffer.from(data, 'base64'));
}
report.push({ page: page.name, width, scheme, shot, ...fit, noRing });
await f.b.close();
}
await writeFile(join(dir, 'measure.json'), JSON.stringify(report, null, 1));
for (const r of report) {
assert.equal(r.sideways, false, `${r.shot} scrolls sideways`);
assert.deepEqual(r.noRing, [], `${r.shot}: controls with no visible focus ring`);
if (r.width === 390) for (const s of r.selects) { assert.ok(s.inside, `${r.shot}: ${s.label} runs off screen`); assert.ok(s.need <= s.room, `${r.shot}: ${s.label} cuts "${s.text}" (${s.need} > ${s.room})`); }
}
});
+3 -1
View File
@@ -50,7 +50,9 @@ test('shipped strings are unchanged, and the web keeps its write boundary', () =
['bus.js', 'No page at this address.'], ['app.js', 'Nothing is waiting on you.'], ['bus.js', 'Nothing is waiting on you.'],
['bus.js', 'No tasks in this business yet.'], ['bus.js', 'Tasks appear after the PM creates them or the poller reads them from Vikunja.'],
['bus.js', 'No open tasks.'], ['bus.js', 'No role is held right now.'], ['bus.js', 'Nothing of this kind in the trail.'],
['bus.js', 'Console shows nothing rather than a guess. Nothing was written.'],
// settings-p3 (re-check 3 P3-8): the line is declared once as NO_GUESS and used by the failed view and
// the failed Settings read; counting the uses catches dropping it from either page.
['bus.js', 'Console shows nothing rather than a guess. Nothing was written.'], ['bus.js', '${NO_GUESS}', 2],
]) assert.equal(plain[file].split(s).length - 1, n, `${file}: ${s}`);
// Row 252 (#1753, mos-1321): the one decision control is the Console's grant Approve and Deny, one
// fetch(url, ...) in decidePost, called only for a decision's confirmation and its resolve. Its labels
@@ -211,8 +211,8 @@ test('a switch stops following an agent request: no poll reaches the next organi
await wait('window.__reads.length >= 1');
assert.deepEqual(await b.evaluate('window.__posts'), ['/api/orgs/acme/agent/launch']);
assert.match(await b.evaluate('window.__reads[0]'), /^\/api\/orgs\/acme\/agent\/request\?id=/);
await b.evaluate('location.hash = "#/orgs/beta/settings/agents"');
await wait('location.hash === "#/orgs/beta/settings/agents" && document.querySelector("#agents-section [data-agent-name=chief]") && !document.querySelector("#agents-section [data-agent-name=reviewer]")');
await b.evaluate('location.hash = "#/settings/agents?org=beta"');
await wait('location.hash === "#/settings/agents?org=beta" && document.querySelector("#agents-section [data-agent-name=chief]") && !document.querySelector("#agents-section [data-agent-name=reviewer]")');
const seen = await b.evaluate('window.__reads.length');
// Two poll periods pass on beta's page.
await new Promise(r => setTimeout(r, 4500));
@@ -239,13 +239,13 @@ test('a save still in flight at a switch: its answer is not drawn on the next or
await b.evaluate(`(() => { const i = document.querySelector(${JSON.stringify(total)}); i.value = "5"; i.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector(${JSON.stringify(submit)}).click(); })()`);
await wait('typeof window.__release === "function"');
assert.equal(await b.evaluate('window.__posts[0]?.revision'), 'a'.repeat(64));
await b.evaluate('location.hash = "#/orgs/beta/settings/limits"');
await wait(`location.hash === "#/orgs/beta/settings/limits" && document.querySelector(${JSON.stringify(total)})?.value === "7"`);
await b.evaluate('location.hash = "#/settings/limits?org=beta"');
await wait(`location.hash === "#/settings/limits?org=beta" && document.querySelector(${JSON.stringify(total)})?.value === "7"`);
// beta's Save is its own: not held by acme's write.
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false);
await b.evaluate('window.__release()');
await new Promise(r => setTimeout(r, 700));
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits');
assert.equal(await b.evaluate('location.hash'), '#/settings/limits?org=beta');
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value`), '7');
assert.equal(await b.evaluate('document.getElementById("launch-settings-receipt")?.textContent.trim() ?? ""'), '');
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false);
@@ -420,15 +420,15 @@ test('a read still in flight at a switch: its answer is not kept for the next or
// A fresh read of acme's settings starts and is held.
await b.evaluate('window.__holdAcme = true; location.hash = "#/orgs/acme/settings/tokens"');
await wait('window.__acme.length >= 1');
await b.evaluate('window.__holdBeta = true; location.hash = "#/orgs/beta/settings/limits"');
await wait('location.hash === "#/orgs/beta/settings/limits" && window.__beta.length >= 1');
await b.evaluate('window.__holdBeta = true; location.hash = "#/settings/limits?org=beta"');
await wait('location.hash === "#/settings/limits?org=beta" && window.__beta.length >= 1');
// acme answers after the switch; then beta's read fails.
await b.evaluate('window.__acme.forEach(r => r())');
await new Promise(r => setTimeout(r, 400));
await b.evaluate('window.__beta.forEach(r => r())');
await wait('document.querySelector("#bus-view .banner")');
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits');
assert.equal(await b.evaluate('location.hash'), '#/settings/limits?org=beta');
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value ?? null`), null, 'acme\'s held answer was drawn on beta');
assert.equal(await b.evaluate('!!document.querySelector("#bus-view .s1-stale")'), false);
assert.match(await b.evaluate('document.getElementById("bus-view").innerText'), /beta settings read failed/);
@@ -27,7 +27,7 @@ function boardOrgs({ refuse = null, tasksFail = [] } = {}) {
forge: [{ id: 'api-gateway', repo: 'gateway', name: 'API gateway', at: '2026-11-09T10:00:00.000Z' }, { id: 'billing', repo: 'billing', name: 'Billing', at: '2026-11-08T10:00:00.000Z' }],
};
const store = [
{ n: 41, title: 'Rate limit the public API', state: 'todo', group: 'api-gateway', assignees: ['coder'], priority: 4, due: '2026-11-20T00:00:00.000Z' },
{ n: 41, title: 'Rate limit the public API', state: 'todo', group: 'api-gateway', assignees: ['coder'], priority: 4, due: '2099-11-20T00:00:00.000Z' },
{ n: 42, title: 'Invoice export', state: 'in-progress', group: 'billing', assignees: [], priority: 0, due: null },
{ n: 43, title: 'Retire the v1 gateway', state: 'done', group: 'api-gateway', assignees: ['reviewer'], priority: 2, due: null },
].map(t => ({ ...t, rev: 0 }));
@@ -90,7 +90,7 @@ test('the board merges every organization\'s tasks, tags each with its org, and
[['ddigital', 'V-112', true, 'Vikunja'], ['ddigital', 'V-118', true, 'Vikunja'], ['forge', '#41', true, 'built-in'], ['forge', '#42', true, 'built-in'], ['forge', '#43', true, 'built-in']]);
// Columns: the store's states, plus one for the Vikunja task whose bucket the bus does not name.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".tb-col h3")].map(h => h.textContent)'), ['To do', 'In progress', 'Review', 'Blocked', 'Done', 'State not read']);
assert.deepEqual(await b.evaluate('[...document.querySelector("[data-tb-col=todo] [data-tb-task=\'forge|task:41\'] .bot").children].map(e => e.textContent.trim())'), ['API gateway', 'coder', 'P4', 'due 20 Nov']);
assert.deepEqual(await b.evaluate('[...document.querySelector("[data-tb-col=todo] [data-tb-task=\'forge|task:41\'] .bot").children].map(e => e.textContent.trim())'), ['API gateway', 'coder', 'P4', 'due 20 Nov 2099']);
// Only built-in store cards can be dragged; a Vikunja card is read only.
assert.equal(await b.evaluate('document.querySelector("[data-tb-task=\'forge|task:41\']").draggable'), true);
assert.equal(await b.evaluate('document.querySelector("[data-tb-task=\'ddigital|vikunja:3/112\']").draggable'), false);
+316
View File
@@ -0,0 +1,316 @@
// proxy-scope slice 4 (#1873): the Console's side of the Triage key. The Console asks one riding
// organization's bus for proxy.triage.key (it never holds the management key); a bus that is down or
// not riding is passed over; with none left the status is triage-no-riding-bus with its named
// message. Settings > Triage shows "rotation overdue" when the day has passed and no riding bus can
// act. The owner's first save with no key held runs ensure; Repair access runs ensure; Turn Triage
// off stops the session, then runs revoke. No answer, response or log line holds a key.
import test from 'node:test';
import assert from 'node:assert/strict';
import { request } from 'node:http';
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { keyIdOf, keyPrefix } from '../../bus/src/triage-key-file.mjs';
import { NO_RIDING_MESSAGE, OVERDUE_ALLOWANCE_MS, accessStatus, keyState, ridingOrgs, triageKeyCall } from '../src/triage-access.mjs';
import { ACCESS_OPS, TRIAGE_ACCESS_PATH, TRIAGE_ROUTE_PATH, triageRouteRoutes } from '../src/triage-route-http.mjs';
const scratch = prefix => mkdtempSync(join(process.env.TMPDIR, prefix));
const T = '2026-11-18T12:00:00.000Z';
const SECRET = 'S'.repeat(20) + 'e_-' + 'c'.repeat(20);
const KEY = `mst-0123456789ab-triage-${SECRET}`;
const busError = code => Object.assign(new Error(`bus said ${code} ${KEY}`), { code });
// A rider as webui cli.mjs rideRiders lists them; `answer` is what its bus does with the call.
const rider = (id, answer, over = {}) => {
const r = { id, fixture: false, cliproxy: true, calls: [], call: async (verb, args) => { r.calls.push([verb, args]); return answer(args); }, ...over };
return r;
};
const ISSUED = () => ({ op: 'ensure', action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-18', addedKeyIds: ['0123456789ab'], removedKeyIds: [], key: KEY, retiring: [{ key: KEY }] });
test('triageKeyCall asks the first riding bus as the owner, passes over a bus that is down or not riding, and skips fixture and non-cliproxy organizations', async () => {
const fixtureOrg = rider('fix', ISSUED, { fixture: true });
const ownProxy = rider('own', ISSUED, { cliproxy: false });
const down = rider('down', () => { throw busError('no-bus-host'); });
const notRiding = rider('other', () => { throw busError('triage-no-riding-bus'); });
const good = rider('alpha', ISSUED);
const after = rider('beta', ISSUED);
const r = await triageKeyCall({ riders: async () => [fixtureOrg, ownProxy, down, notRiding, good, after], op: 'ensure' });
assert.deepEqual(r, { ok: true, op: 'ensure', action: 'issued', addedKeyIds: ['0123456789ab'], removedKeyIds: [], keyId: '0123456789ab', rotateBy: '2026-12-18', org: 'alpha' });
assert.deepEqual(good.calls, [['proxy.triage.key', { op: 'ensure' }]]);
for (const x of [fixtureOrg, ownProxy, after]) assert.deepEqual(x.calls, [], x.id);
for (const x of [down, notRiding]) assert.equal(x.calls.length, 1, x.id);
assert.equal(JSON.stringify(r).includes(SECRET), false, 'no key in the answer');
});
test('triageKeyCall: a bus whose outcome is unknown (a timeout, an unreadable or oversized answer) may have done the work, so the walk stops there and asks no other bus', async () => {
for (const c of ['outcome-unknown', 'invalid-response', 'response-too-large']) {
const slow = rider('slow', () => { throw busError(c); });
const next = rider('beta', ISSUED);
for (const op of ['ensure', 'revoke'])
assert.deepEqual(await triageKeyCall({ riders: async () => [slow, next], op }), { ok: false, code: 'outcome-unknown', org: 'slow' }, `${c} ${op}`);
assert.deepEqual(next.calls, [], c);
}
// ridingOrgs is the list the walk asks, and the status reads the same list.
const list = [rider('fix', ISSUED, { fixture: true }), rider('own', ISSUED, { cliproxy: false }), rider('alpha', ISSUED), { id: 'nocall', cliproxy: true }, null];
assert.deepEqual(ridingOrgs(list).map(r => r.id), ['alpha']);
assert.deepEqual(ridingOrgs('x'), []);
});
test('triageKeyCall: with no riding bus left the answer is triage-no-riding-bus; any other refusal is the answer and stops the walk', async () => {
for (const list of [[], [rider('own', ISSUED, { cliproxy: false })], [rider('fix', ISSUED, { fixture: true })], [rider('a', () => { throw busError('triage-no-riding-bus'); }), rider('b', () => { throw busError('bus-unavailable'); })]])
assert.deepEqual(await triageKeyCall({ riders: async () => list, op: 'revoke' }), { ok: false, code: 'triage-no-riding-bus' });
assert.deepEqual(await triageKeyCall({ riders: async () => { throw new Error('x'); }, op: 'ensure' }), { ok: false, code: 'triage-no-riding-bus' });
const refused = rider('alpha', () => { throw busError('human-required'); });
const next = rider('beta', ISSUED);
assert.deepEqual(await triageKeyCall({ riders: async () => [refused, next], op: 'ensure' }), { ok: false, code: 'human-required', org: 'alpha' });
assert.deepEqual(next.calls, []);
// A code that is not a bus code is outcome-unknown, which stops the walk.
const odd = rider('odd', () => { throw busError(`rm -rf ${KEY}`); });
assert.deepEqual(await triageKeyCall({ riders: async () => [odd, next], op: 'ensure' }), { ok: false, code: 'outcome-unknown', org: 'odd' });
for (const op of ['rotate', undefined, 'ENSURE']) assert.deepEqual(await triageKeyCall({ riders: async () => [next], op }), { ok: false, code: 'invalid-request' });
assert.deepEqual(next.calls, []);
});
test('triageKeyCall keeps ids and a day only: a key, a key-shaped id or an unknown action from a bus is dropped', async () => {
const leaky = rider('alpha', () => ({ action: 'replaced', keyId: KEY, rotateBy: `${KEY}`, addedKeyIds: [KEY, '0123456789ab'], removedKeyIds: ['ba9876543210', { key: KEY }], key: KEY }));
const r = await triageKeyCall({ riders: async () => [leaky], op: 'ensure' });
assert.deepEqual(r, { ok: true, op: 'ensure', action: 'replaced', addedKeyIds: ['0123456789ab'], removedKeyIds: ['ba9876543210'], org: 'alpha' });
const strange = rider('alpha', () => ({ action: KEY, keyId: '0123456789ab', addedKeyIds: 'x' }));
assert.deepEqual(await triageKeyCall({ riders: async () => [strange], op: 'revoke' }), { ok: true, op: 'revoke', action: 'unknown', addedKeyIds: [], removedKeyIds: [], org: 'alpha' });
});
// A key file as the bus writes it (triage-key.mjs), in a temp config directory.
function keyFile(configDir, { rotateBy = '2026-12-18', mode = 0o600 } = {}) {
const dir = join(configDir, 'secrets', 'triage');
mkdirSync(dir, { recursive: true, mode: 0o700 });
chmodSync(join(configDir, 'secrets'), 0o700);
chmodSync(dir, 0o700);
const key = `${keyPrefix(configDir)}${SECRET}`;
writeFileSync(join(dir, 'model'), JSON.stringify({ version: 1, key, keyId: keyIdOf(key), issuedAt: T, rotateBy, retiring: [] }), { mode });
chmodSync(join(dir, 'model'), mode);
return key;
}
test('keyState reads the file through the reader alone: missing, issued with its id and day, due and overdue, or unsafe; never the key', t => {
const root = scratch('ta-ks-');
t.after(() => rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config');
mkdirSync(configDir, { mode: 0o700 });
assert.deepEqual(keyState(configDir), { key: 'missing' });
const key = keyFile(configDir);
const at = s => () => Date.parse(s);
const before = keyState(configDir, { now: at('2026-12-17T23:59:59Z') });
assert.deepEqual(before, { key: 'issued', keyId: keyIdOf(key), rotateBy: '2026-12-18', retiring: 0, due: false, overdue: false });
assert.equal(JSON.stringify(before).includes(SECRET), false);
assert.deepEqual(keyState(configDir, { now: at('2026-12-18T00:00:00Z') }), { ...before, due: true });
assert.equal(OVERDUE_ALLOWANCE_MS, 600000);
assert.deepEqual(keyState(configDir, { now: at('2026-12-18T00:10:00Z') }), { ...before, due: true });
assert.deepEqual(keyState(configDir, { now: at('2026-12-18T00:10:01Z') }), { ...before, due: true, overdue: true });
chmodSync(join(configDir, 'secrets', 'triage', 'model'), 0o644);
assert.deepEqual(keyState(configDir), { key: 'unsafe' });
rmSync(join(configDir, 'secrets', 'triage', 'model'));
symlinkSync('/dev/null', join(configDir, 'secrets', 'triage', 'model'));
assert.deepEqual(keyState(configDir), { key: 'unsafe' });
});
test('accessStatus: no riding organization names triage-no-riding-bus and its message; rotation overdue shows when the day has passed and no riding bus can act', () => {
const issued = { key: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-18', retiring: 0, due: false, overdue: false };
assert.deepEqual(accessStatus(issued, { riding: true }), { ...issued, riding: true });
assert.deepEqual(accessStatus(issued, { riding: false }), { ...issued, riding: false, code: 'triage-no-riding-bus', message: NO_RIDING_MESSAGE });
assert.equal(NO_RIDING_MESSAGE, "Triage needs one organization that uses the owner's models");
assert.equal(accessStatus({ ...issued, due: true }, { riding: false }).rotation, 'rotation overdue');
assert.equal(accessStatus({ ...issued, due: true }, { riding: true }).rotation, undefined, 'a riding bus has its sweep to act');
assert.equal(accessStatus({ ...issued, due: true, overdue: true }, { riding: true }).rotation, 'rotation overdue', 'still not done well after the day began');
assert.deepEqual(accessStatus({ key: 'missing' }, { riding: false }), { key: 'missing', riding: false, code: 'triage-no-riding-bus', message: NO_RIDING_MESSAGE });
assert.equal(accessStatus({ key: 'missing' }, { riding: 'yes' }).riding, false);
});
// --- Over HTTP ---------------------------------------------------------------------------------
const MODEL = { key: 'sonnet', module: 'anthropic', upstream: 'cliproxy', provider: 'anthropic', model: 'claude-sonnet', label: 'SONNET', available: true, reason: null, harnesses: ['claude-code', 'pi'] };
const READY = () => ({ status: 'ready', observedAt: T, notices: [], models: [MODEL] });
const BODY = { model: 'sonnet', harness: 'claude-code', cap: 200000, timeZone: 'Europe/Berlin', revision: 0 };
const send = (port, path, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve, reject) => {
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
let text = ''; res.on('data', c => { text += c; }); res.on('end', () => resolve({ status: res.statusCode, text, json: (() => { try { return JSON.parse(text); } catch { return null; } })() }));
});
req.on('error', reject); req.end(body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body));
});
// A dev-owner Console with the access side wired as cli.mjs wires it: the real keyState over a temp
// config directory and the real triageKeyCall over stand-in riders. A rider's ensure writes the key
// file, as the bus does; its revoke removes it.
async function console_(t, { riders: make = null, serve = {} } = {}) {
const root = scratch('ta-http-');
t.after(() => rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
mkdirSync(configDir, { mode: 0o700 });
mkdirSync(dataRoot, { mode: 0o700 });
const order = [];
const busAnswer = ({ op }) => {
order.push(`bus ${op}`);
if (op === 'ensure') { keyFile(configDir); return ISSUED(); }
rmSync(join(configDir, 'secrets', 'triage', 'model'), { force: true });
return { op: 'revoke', action: 'revoked', addedKeyIds: [], removedKeyIds: ['0123456789ab'], key: KEY };
};
const list = make ? make(busAnswer) : [rider('alpha', busAnswer)];
const logs = [], routeLogs = [];
const access = {
state: () => keyState(configDir, { now: () => Date.parse(T) }),
// As cli.mjs: the same list the walk asks (the proxy is set up in this harness).
riding: async () => ridingOrgs(list).length > 0,
key: op => triageKeyCall({ riders: async () => list, op }),
stop: async () => { order.push('stop'); },
};
const s = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso: createDevOwner(), send: async () => ({}), log: l => logs.push(l),
routes: [triageRouteRoutes({ dataRoot, catalogues: async () => [READY()], harnesses: () => ['claude-code', 'pi'], log: l => routeLogs.push(l), access })], ...serve });
t.after(() => new Promise(r => s.close(r)));
const port = s.address().port;
const read = { host: `127.0.0.1:${port}`, 'sec-fetch-site': 'same-origin' };
const write = { ...read, origin: `http://127.0.0.1:${port}`, 'content-type': 'application/json' };
return {
port, configDir, list, order, logs, routeLogs, write,
get: () => send(port, TRIAGE_ROUTE_PATH, { headers: read }),
save: (body = BODY) => send(port, TRIAGE_ROUTE_PATH, { method: 'POST', headers: write, body }),
op: (op, headers = write) => send(port, TRIAGE_ACCESS_PATH, { method: 'POST', headers, body: { op } }),
};
}
test('the first save with no key held asks one riding bus for ensure; a later save, with the key held, does not', async t => {
const f = await console_(t);
const before = await f.get();
assert.deepEqual(before.json.access, { key: 'missing', riding: true });
const first = await f.save();
assert.equal(first.status, 200, first.text);
assert.deepEqual(first.json.key, { action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-18' });
assert.deepEqual(f.list[0].calls, [['proxy.triage.key', { op: 'ensure' }]]);
const second = await f.save({ ...BODY, revision: 1, cap: 300000 });
assert.equal(second.status, 200, second.text);
assert.equal(Object.hasOwn(second.json, 'key'), false);
assert.equal(f.list[0].calls.length, 1, 'ensure runs once');
assert.equal((await f.get()).json.access.key, 'issued');
});
test('with no riding organization, a save keeps the route and says why; the status names triage-no-riding-bus and its message; Repair answers 503 with it', async t => {
const f = await console_(t, { riders: answer => [rider('own', answer, { cliproxy: false }), rider('fix', answer, { fixture: true })] });
const r = await f.get();
assert.deepEqual(r.json.access, { key: 'missing', riding: false, code: 'triage-no-riding-bus', message: NO_RIDING_MESSAGE });
const saved = await f.save();
assert.equal(saved.status, 200);
assert.equal(saved.json.route.model, 'sonnet', 'the route is saved');
assert.equal(saved.json.key.error, 'triage-no-riding-bus');
assert.match(saved.json.key.message, /^Triage needs one organization that uses the owner's models\./);
const repair = await f.op('repair');
assert.equal(repair.status, 503);
assert.equal(repair.json.error, 'triage-no-riding-bus');
assert.equal(repair.json.access.code, 'triage-no-riding-bus');
for (const x of f.list) assert.deepEqual(x.calls, [], x.id);
});
test('rotation overdue shows when the key day has passed and no organization rides the owner models', async t => {
const f = await console_(t, { riders: answer => [rider('own', answer, { cliproxy: false })] });
keyFile(f.configDir, { rotateBy: '2026-11-17' });
const r = await f.get();
assert.equal(r.json.access.rotation, 'rotation overdue');
assert.equal(r.json.access.code, 'triage-no-riding-bus');
assert.equal(r.json.access.key, 'issued');
});
test('Repair access runs ensure; Turn Triage off stops the session first, then runs revoke', async t => {
const f = await console_(t);
assert.deepEqual(ACCESS_OPS, ['repair', 'off']);
const repair = await f.op('repair');
assert.equal(repair.status, 200, repair.text);
assert.deepEqual(repair.json, { op: 'repair', key: { action: 'issued', keyId: '0123456789ab', rotateBy: '2026-12-18' }, access: { key: 'issued', keyId: repair.json.access.keyId, rotateBy: '2026-12-18', retiring: 0, due: false, overdue: false, riding: true } });
const off = await f.op('off');
assert.equal(off.status, 200, off.text);
assert.deepEqual(off.json, { op: 'off', key: { action: 'revoked' }, access: { key: 'missing', riding: true } });
assert.deepEqual(f.order, ['bus ensure', 'stop', 'bus revoke']);
assert.deepEqual(f.list[0].calls.map(c => c[1].op), ['ensure', 'revoke']);
});
test('after Turn Triage off, a later save does not issue the key again; only Repair access brings it back', async t => {
const f = await console_(t);
assert.equal((await f.save()).json.key.action, 'issued');
assert.equal((await f.op('off')).status, 200);
const again = await f.save({ ...BODY, revision: 1, cap: 300000 });
assert.equal(again.status, 200, again.text);
assert.equal(Object.hasOwn(again.json, 'key'), false);
assert.equal((await f.get()).json.access.key, 'missing');
assert.deepEqual(f.order, ['bus ensure', 'stop', 'bus revoke']);
assert.equal((await f.op('repair')).json.key.action, 'issued');
assert.deepEqual(f.order, ['bus ensure', 'stop', 'bus revoke', 'bus ensure']);
});
test('a bus refusal on Off leaves the key and says why with a fixed line; the session was still stopped', async t => {
const f = await console_(t, { riders: () => [rider('alpha', () => { throw busError('storage-unavailable'); })] });
const off = await f.op('off');
assert.equal(off.status, 502);
assert.equal(off.json.error, 'storage-unavailable');
assert.equal(off.json.message, 'The Triage key was not changed. The organization\'s bus refused with storage-unavailable.');
assert.deepEqual(f.order, ['stop']);
assert.equal(off.text.includes(SECRET), false);
});
test('the access path holds the owner, same-origin and read-only gates, takes op only, and the tester listener cannot reach it', async t => {
const f = await console_(t);
const { origin, ...noOrigin } = f.write;
assert.equal((await f.op('repair', noOrigin)).status, 403);
assert.equal((await f.op('repair', { ...f.write, origin: 'http://evil.example' })).status, 403);
assert.equal((await f.op('repair', { ...f.write, 'sec-fetch-site': 'cross-site' })).status, 403);
const { 'sec-fetch-site': _, ...noSite } = f.write;
assert.equal((await f.op('repair', noSite)).status, 403);
for (const body of [{}, { op: 'ensure' }, { op: 'revoke' }, { op: 'repair', key: KEY }, { op: ['repair'] }, 'repair'])
assert.equal((await send(f.port, TRIAGE_ACCESS_PATH, { method: 'POST', headers: f.write, body })).status, 400, JSON.stringify(body));
assert.equal((await send(f.port, TRIAGE_ACCESS_PATH, { method: 'POST', headers: { ...f.write, 'content-type': 'text/plain' }, body: { op: 'repair' } })).status, 400);
assert.notEqual((await send(f.port, TRIAGE_ACCESS_PATH, { headers: f.write })).status, 200, 'a GET is not an op');
assert.deepEqual(f.list[0].calls, [], 'no refused request reached a bus');
assert.deepEqual(f.order, []);
// The handler's own owner and same-origin lines, behind the serve gate: a caller who is not the
// instance owner, or a doubled Origin or Sec-Fetch-Site, is refused before any bus is asked.
let handler, unitAsked = 0;
const unitAccess = { state: () => ({ key: 'missing' }), riding: async () => true, key: async () => { unitAsked++; return { ok: true }; }, stop: async () => { unitAsked++; } };
triageRouteRoutes({ dataRoot: f.configDir, catalogues: async () => [READY()], harnesses: () => ['claude-code', 'pi'], access: unitAccess })({ add: (method, path, fn) => { if (path === TRIAGE_ACCESS_PATH) handler = fn; } });
const o = 'https://console.example';
const call = (headersDistinct, extra = {}) => new Promise(resolve => {
const res = { writeHead(status) { this.status = status; }, end(text) { resolve({ status: this.status, json: JSON.parse(text) }); } };
const req = { method: 'POST', headersDistinct, headers: { 'content-type': 'application/json' }, async *[Symbol.asyncIterator]() { yield Buffer.from('{"op":"off"}'); } };
handler(req, res, { owner: true, session: { provider: 'local-dev', sub: 'local-dev-owner' }, origin: o, send: true, ...extra });
});
const same = { origin: [o], 'sec-fetch-site': ['same-origin'] };
assert.equal((await call(same, { owner: false })).json.error, 'human-required');
assert.equal((await call(same, { session: null })).json.error, 'human-required');
assert.equal((await call({ ...same, origin: [o, o] })).json.error, 'cross-origin');
assert.equal((await call({ ...same, 'sec-fetch-site': ['same-origin', 'same-origin'] })).json.error, 'cross-site');
assert.equal((await call(same, { send: false })).json.error, 'read-only');
assert.equal(unitAsked, 0);
assert.equal((await call(same)).status, 200);
assert.equal(unitAsked, 2, 'the owner\'s own call stops and revokes');
const ro = await console_(t, { serve: { send: null } });
const r = await ro.op('off');
assert.equal(r.status, 403);
assert.equal(r.json.error, 'read-only');
assert.deepEqual(ro.order, []);
const { startTesterSocket } = await import('../src/tester-socket.mjs');
const { testerRequest } = await import('../../cli/src/tester-http.mjs');
const root = scratch('ta-tester-');
t.after(() => rmSync(root, { recursive: true, force: true }));
let asked = 0;
const access = { state: () => ({ key: 'missing' }), riding: async () => true, key: async () => { asked++; return { ok: true }; }, stop: async () => { asked++; } };
const s = await startTesterSocket({ dataRoot: root, log: () => {}, routes: [triageRouteRoutes({ dataRoot: root, catalogues: async () => [READY()], harnesses: () => ['claude-code', 'pi'], access })] });
t.after(() => new Promise(r2 => s.close(r2)));
for (const op of ['repair', 'off']) assert.equal((await testerRequest({ dataRoot: root, path: TRIAGE_ACCESS_PATH, method: 'POST', body: { op } })).status, 403, op);
assert.equal(asked, 0);
});
test('no response or log line holds a key, even when a bus answers with one', async t => {
const f = await console_(t);
const texts = [];
for (const r of [await f.get(), await f.save(), await f.op('repair'), await f.op('off'), await f.get()]) texts.push(r.text);
const all = texts.join('\n') + f.logs.join('\n') + f.routeLogs.join('\n');
assert.equal(all.includes(SECRET), false);
assert.equal(all.includes(f.configDir), false, 'no config path');
});
@@ -9,7 +9,6 @@ import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { TriageError, NOT_STARTED } from '../src/triage-host.mjs';
import { capMessage, NO_ROUTE_MESSAGE } from '../src/triage-http.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
@@ -77,9 +76,10 @@ function fakeHost(over = {}) {
return { h, triage };
}
async function setup(t, { host = fakeHost(), triage = host.triage, send = true, sso = createDevOwner(), viewport = [1440, 900], path = '/#/dashboard', init = null } = {}) {
// proxyAdmin: a stand-in model service admin, so /api/config says proxyAdmin and Settings > Triage exists.
async function setup(t, { host = fakeHost(), triage = host.triage, send = true, sso = createDevOwner(), viewport = [1440, 900], path = '/#/dashboard', init = null, proxyAdmin = null } = {}) {
const { organizations, agentLevels } = await orgFixture();
const server = await startServer({ port: 0, sso, organizations, agentLevels, triage, send: send ? async () => ({}) : null, log: () => {} });
const server = await startServer({ port: 0, sso, organizations, agentLevels, triage, proxyAdmin, send: send ? async () => ({}) : null, log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
@@ -157,12 +157,13 @@ test('item 1: at 390 wide the entry stays visible and one click opens the drawer
});
test('item 2 and 3: route not set says so, and the message box is off with the reason', async t => {
const f = await setup(t, { host: fakeHost({ route: 'not set' }) });
const f = await setup(t, { host: fakeHost({ route: 'not set' }), proxyAdmin: {} });
await open(f);
assert.match(await f.text('#triage-state'), new RegExp(NO_ROUTE_MESSAGE.slice(0, 40)));
assert.equal(await f.text('#triage-state'), 'Triage has no model chosen yet, so it will not start.');
assert.equal(await f.b.evaluate('document.querySelector("#triage-state-fix a")?.getAttribute("href")'), '#/settings/triage');
assert.equal(await f.b.evaluate('document.querySelector("#triage-text")?.disabled'), true);
assert.equal(await f.b.evaluate('document.querySelector("#triage-send")?.disabled'), true);
assert.match(await f.text('#triage-send-off'), /no model route is set/i);
assert.match(await f.text('#triage-send-off'), /no model chosen yet/i);
});
test('item 2: over cap shows the cap message and the time it takes messages again', async t => {
@@ -170,10 +171,10 @@ test('item 2: over cap shows the cap message and the time it takes messages agai
const f = await setup(t, { host: fakeHost({ overCapUntil: until }) });
await open(f);
const state = await f.text('#triage-state');
assert.ok(state.includes(capMessage(until)), state);
const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(until)})`);
assert.ok(state.includes(`Local time: ${local}.`), state);
assert.match(await f.text('#triage-send-off'), /daily token cap/i);
assert.equal(state, `Triage used its daily token limit. It takes messages again at ${local}.`);
assert.equal(await f.b.evaluate('document.querySelector("#triage-state-fix").hidden'), true, 'a set route shows no fix link');
assert.match(await f.text('#triage-send-off'), /daily token limit/i);
});
test('item 2: running, last exit, and the health snapshot with "not read" shown as that', async t => {
@@ -183,9 +184,9 @@ test('item 2: running, last exit, and the health snapshot with "not read" shown
assert.match(await f.text('#triage-state'), /^Running/);
const health = await f.text('#triage-health');
assert.match(health, /Console: answering/);
assert.match(health, /Proxy: not read/);
assert.match(health, /Model service: not read/);
assert.match(health, /System config: valid/);
assert.match(health, /acme: bus running, processing on, config valid/);
assert.match(health, /Acme Studio: bus running, processing on, config valid/);
assert.match(health, /gamma: bus not read, processing not read, config not valid \(org-config-invalid\)/);
assert.doesNotMatch(health.split('\n').find(l => l.startsWith('gamma')), /healthy|running/);
// The next poll picks up a stopped session and its last exit, and a snapshot that read nothing.
@@ -194,7 +195,7 @@ test('item 2: running, last exit, and the health snapshot with "not read" shown
await f.wait('/Last exit/.test(document.querySelector("#triage-state").textContent)', 300);
assert.match(await f.text('#triage-state'), /Not running\. Last exit: code 1/);
const after = await f.text('#triage-health');
assert.match(after, /Proxy: healthy/);
assert.match(after, /Model service: healthy/);
assert.match(after, /System config: not read/);
assert.match(after, /Organizations: not read/);
// No snapshot at all.
@@ -240,8 +241,8 @@ test('item 3: each send answer has plain words, a refused send keeps the draft,
assert.equal(await draft(), 'is acme healthy?', `${label}: the draft stays`);
};
await type(f, 'is acme healthy?');
await refused(() => { host.h.next = new TriageError('triage-no-route', 'x'); }, /Not sent.*no model route is set/i, '409');
await refused(() => { const e = new TriageError('triage-over-cap', 'x'); e.until = until; host.h.next = e; }, new RegExp(`Not sent.*daily token cap.*${until.slice(0, 16)}`), '429');
await refused(() => { host.h.next = new TriageError('triage-no-route', 'x'); }, /Not sent.*no model chosen yet/i, '409');
await refused(() => { const e = new TriageError('triage-over-cap', 'x'); e.until = until; host.h.next = e; }, new RegExp(`Not sent.*daily token limit.*${until.slice(0, 16)}`), '429');
await refused(() => { host.h.next = new TriageError('triage-message-too-long', 'x'); }, /Not sent.*too long/i, '400');
await refused(() => f.b.evaluate('window.__force403 = true'), /Not sent.*read-only/i, '403');
await f.b.evaluate('window.__force403 = false');
@@ -444,7 +445,7 @@ test('triage-followups: with no drawer open the first render still focuses the h
test('triage-cap: one usage line from the read: not set, the count against the cap with the reset, not read, and markup as text', async t => {
const f = await setup(t, { host: fakeHost({ usageToday: 'not set', cap: 'not set', resetsAt: 'not set' }) });
await open(f);
assert.equal(await f.text('#triage-usage'), 'Daily token cap: not set.');
assert.equal(await f.text('#triage-usage'), 'Daily token limit: not set.');
assert.equal(await f.b.evaluate('document.querySelector("#triage-usage").hidden'), false);
const resetsAt = new Date(Date.now() + 5 * 3600000).toISOString();
const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(resetsAt)})`);
@@ -470,3 +471,110 @@ test('triage-cap: a read without the usage fields shows no usage line', async t
await open(f);
assert.equal(await f.b.evaluate('document.querySelector("#triage-usage").hidden'), true);
});
// The Triage route read this test server does not mount: the route names its harness as the module is installed.
const ROUTE_READ = `(()=>{const prev=window.fetch;window.fetch=(i,init)=>{if(new URL(typeof i==="string"?i:i.url,location.href).pathname==="/api/triage/route")return Promise.resolve(new Response(JSON.stringify({route:{model:"sonnet",harness:"claude-code",cap:150000,reset:"00:00",timeZone:"UTC",revision:1,updatedAt:"2026-11-18T12:00:00.000Z"},revision:1,choices:{status:"ready",models:[]},send:true,note:""}),{status:200,headers:{"content-type":"application/json"}}));return prev(i,init);};})()`;
// #1873 settings slice 1, bullet 5 (DESIGN.md section 5): a route refusal is a plain line that says what is
// missing, with a link to the Settings page that fixes it. The harness refusal names the route's harness as
// its module declares it, read from the route; no harness name is written into the page. The key refusal has
// no fix page in slice 1, so it ends at what is missing and offers no link.
test('settings-s1 B5: route refusals read as plain lines with the fix link; the harness line names the route\'s harness', async t => {
const host = fakeHost({ running: false });
const f = await setup(t, { host, proxyAdmin: {}, init: ROUTE_READ });
await open(f);
await type(f, 'is acme healthy?');
const { ROUTE_REFUSALS } = await import('../src/triage-host.mjs');
const cases = [
['triage-harness-incompatible', /^Not sent\. The model Triage uses doesn't run with claude-code, the program its route says runs it\. Choose a model that runs with claude-code, or another program, in Triage settings\. Open Triage settings$/, '#/settings/triage'],
['triage-proxy-down', /^Not sent\. The model service isn't running, so Triage can't start\. Open Model setup$/, '#/settings/model-setup'],
['triage-model-not-offered', /^Not sent\. The model Triage uses is no longer offered\./, '#/settings/triage'],
['triage-key-missing', /^Not sent\. Triage isn't turned on yet: it needs a Triage key, and none is issued on this instance\.$/, null],
];
let status = '';
for (const [code, pattern, href] of cases) {
host.h.next = new TriageError(code, ROUTE_REFUSALS[code]);
status = await sendAndWait(f, status);
assert.match(status, pattern, code);
assert.doesNotMatch(status, /harness|proxy/i, `${code}: no internal word`);
assert.equal(await f.b.evaluate('document.querySelector("#triage-send-status a")?.getAttribute("href") ?? null'), href, `${code}: fix link`);
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'is acme healthy?', `${code}: the draft stays`);
}
// The fix link is reachable by keyboard and goes to its page, closing the drawer.
host.h.next = new TriageError('triage-harness-incompatible', ROUTE_REFUSALS['triage-harness-incompatible']);
status = await sendAndWait(f, status);
await f.b.evaluate('document.querySelector("#triage-send-status a").focus()');
assert.equal(await f.b.evaluate('document.activeElement?.textContent'), 'Open Triage settings');
assert.notEqual(await f.b.evaluate('getComputedStyle(document.activeElement).outlineStyle'), 'none', 'the focused link shows a focus ring');
await f.b.key('Enter', 'Enter');
// The Settings pages live inside the open organization, so the shell scopes the address to it.
await f.wait('/^#(\\/orgs\\/acme)?\\/settings\\/triage$/.test(location.hash) && document.querySelector("#triage-drawer").hidden && document.querySelector("#triage-route")');
assert.notEqual(await f.text('h1'), 'Not found');
});
// When the route read gives no harness (here the server does not mount it), the line stays plain without a name.
test('settings-s1 B5: the harness refusal without a readable route keeps a plain line and its fix link', async t => {
const host = fakeHost({ running: false });
const f = await setup(t, { host, proxyAdmin: {} });
await open(f);
await type(f, 'is acme healthy?');
const { ROUTE_REFUSALS } = await import('../src/triage-host.mjs');
host.h.next = new TriageError('triage-harness-incompatible', ROUTE_REFUSALS['triage-harness-incompatible']);
const status = await sendAndWait(f, '');
assert.equal(status, "Not sent. The model Triage uses doesn't run with the program its route says runs it. Choose a model and a program that run together in Triage settings. Open Triage settings");
assert.equal(await f.b.evaluate('document.querySelector("#triage-send-status a")?.getAttribute("href") ?? null'), '#/settings/triage');
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'is acme healthy?', 'the draft stays');
});
// Settings > Triage exists only where /api/config says proxyAdmin, so without it no line links there.
test('settings-s1 B5: without the Triage settings page the refusal keeps its line and offers no link to it', async t => {
const host = fakeHost({ route: 'not set' });
const f = await setup(t, { host });
await open(f);
assert.equal(await f.text('#triage-state'), 'Triage has no model chosen yet, so it will not start.');
assert.equal(await f.b.evaluate('document.querySelector("#triage-state-fix").hidden && !document.querySelector("#triage-state-fix a")'), true);
assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer a[href=\'#/settings/triage\']")'), null);
});
// #1873 settings slice 1, bullet 6 (D7): an organization whose last start was refused reads as not
// running in the Health list, never as running. The snapshot carries the time of the refused start but
// not its reason (triage-snapshot.mjs keeps lastStart {ok, at} only). The reason comes from the read the
// dashboard row uses (GET /api/workspace); when that read names none, the line says where to see why.
test('settings-s1 B6: a refused last start reads as not running in Health, with the time and where to see why', async t => {
const snapshot = SNAPSHOT();
const failedAt = at(30);
snapshot.organizations.list[0] = { id: 'acme', bus: { state: 'stopped', lastStart: { ok: false, at: failedAt } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } };
const f = await setup(t, { host: fakeHost({ running: true, snapshot }) });
await open(f);
const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(failedAt)})`);
const line = (await f.text('#triage-health')).split('\n').find(l => l.startsWith('Acme Studio'));
assert.equal(line, `Acme Studio: not running: its last start failed at ${local} (bus stopped). Restart it on the dashboard to see why, processing on, config valid`);
});
// Review 2, P2-D: the workspace read carries the refusal, so Health shows it, through the plain line
// for a known cause and word for word for any other.
const WORKSPACE_REASON = reason => `(() => { const f = window.fetch; window.fetch = (u, o) => String(u?.url ?? u).includes('/api/workspace?org=acme&sections=tasks')
? Promise.resolve(new Response(JSON.stringify({ orgs: [{ org: 'acme', state: 'down', reason: ${JSON.stringify(reason)} }] }), { headers: { 'content-type': 'application/json' } })) : f(u, o); })()`;
test('settings-s1 B6: a refused last start shows the reason the workspace read carries', async t => {
const failedAt = at(30);
for (const [reason, expect] of [
// The fixture case is a synthetic pair: lastStart.ok false with a fixture refusal reason. The host
// does not write it. The fixture refusal is thrown after recordBootOk (cli.mjs), so boot status stays
// ok and the workspace read says "the bus is not running". The case pins the line the page would show
// once a later bus lane records that refusal.
['the bus refused to start: bus start refused: fixture-proxy-configured', ' Acme Studio runs on test models, which can\'t share this machine with your model service. It did not start.'],
['the bus refused to start: stopped by the owner', ' Why it stopped: stopped by the owner.'],
// settings-p3 (re-check 3 P3-9): a reason that is not a stop is labeled as the last check.
['the bus state was not read within 2000 ms', ' Last check: the bus state was not read within 2000 ms.'],
]) {
const snapshot = SNAPSHOT();
snapshot.organizations.list[0] = { id: 'acme', bus: { state: 'stopped', lastStart: { ok: false, at: failedAt } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } };
const f = await setup(t, { host: fakeHost({ running: true, snapshot }), init: WORKSPACE_REASON(reason) });
await open(f);
const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(failedAt)})`);
await f.wait(`/Acme Studio: .*config valid\\./.test(document.querySelector('#triage-health')?.innerText ?? '')`);
const line = (await f.text('#triage-health')).split('\n').find(l => l.startsWith('Acme Studio'));
assert.equal(line, `Acme Studio: not running: its last start failed at ${local} (bus stopped), processing on, config valid.${expect}`);
await f.b.close();
}
});
+111 -16
View File
@@ -12,7 +12,7 @@ import { REPO, RUNNER_FILES, checkHostedRoute, sandboxProblem } from "../../seat
import { isProviderVariable } from "../../seat/src/session.mjs";
import {
NOT_STARTED, NOT_TAKEN, RELAY_REFUSED, ROUTE_ENV_ALLOW, ROUTE_REFUSED, SPAWN_ENV_ALLOW, SPAWN_PATH_ALLOW, UNANSWERED, createRelay, createTriageHost, hostPrompt,
USAGE_NOT_READ, USAGE_UNKNOWN_ENDED, UNKNOWN_TURNS_MAX, overCapNotTaken, refusedHarnessName, triageEnv,
USAGE_NOT_READ, USAGE_UNKNOWN_ENDED, UNKNOWN_TURNS_MAX, KEY_ROTATED, KEY_ROTATED_CODE, overCapNotTaken, refusedHarnessName, triageEnv,
} from "../src/triage-host.mjs";
import { writeRoute } from "../src/triage-route-store.mjs";
import { appendUsage, readUsage, usagePath } from "../src/triage-usage.mjs";
@@ -22,6 +22,9 @@ const FIXTURE = new URL("./fixtures/triage-adapter.mjs", import.meta.url).pathna
const skip = sandboxProblem() ?? false;
const scratch = () => mkdtempSync(join(process.env.TMPDIR, "th-"));
const CAP = "a".repeat(64);
// #1873 harness-matrix: a route env holds exactly one key name; the fixture routes give this key.
const FIXTURE_KEY = "triage-fixture-key";
const KEYED = { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: FIXTURE_KEY };
const SNAPSHOT = {
snapshotVersion: 1, at: "2026-11-16T12:00:00.000Z", console: { state: "answering", at: "2026-11-16T12:00:00.000Z" },
proxy: "not read", systemConfig: { valid: true, exit: 0, code: null },
@@ -46,10 +49,13 @@ const raw = (socket, line) => new Promise((resolve, reject) => {
test("triageEnv keeps the fixed names and the route's proxy variables, and nothing else", () => {
const env = triageEnv(CONSOLE_ENV, { ANTHROPIC_BASE_URL: "http://127.0.0.1:1", ANTHROPIC_AUTH_TOKEN: "k", MOSAIC_CONFIG: "/y", OTHER: "z" }, { node: "/opt/node/bin/node" });
assert.deepEqual(Object.keys(env).sort(), ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "LANG", "PATH", "TZ"]);
assert.equal(env.PATH, "/opt/node/bin:/usr/bin:/bin");
// #1873 harness-matrix: the repository's node_modules/.bin first, as a bus session's PATH has it.
assert.equal(env.PATH, `${join(REPO, "node_modules", ".bin")}:/opt/node/bin:/usr/bin:/bin`);
assert.deepEqual(SPAWN_ENV_ALLOW, ["PATH", "LANG", "LC_ALL", "TZ", "TERM"]);
assert.deepEqual(ROUTE_ENV_ALLOW, ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]);
assert.equal(triageEnv(CONSOLE_ENV, { ANTHROPIC_API_KEY: "from-the-route" }).ANTHROPIC_API_KEY, undefined, "the session gets no key, only the proxy's token");
// #1873 harness-matrix: the route's key goes under the one name its harness takes it by: claude-code
// ANTHROPIC_AUTH_TOKEN, pi ANTHROPIC_API_KEY. The host admits a route env with exactly one of them.
assert.deepEqual(ROUTE_ENV_ALLOW, ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]);
assert.equal(triageEnv(CONSOLE_ENV, { ANTHROPIC_API_KEY: "from-the-route" }).ANTHROPIC_API_KEY, "from-the-route", "the route's key under the name its harness takes");
assert.equal(triageEnv(CONSOLE_ENV).ANTHROPIC_API_KEY, undefined, "a key in the Console's environment is not the route's");
// #1873 triage-wiring: the pinned harness binary passes as an absolute path, as a bus session's does.
assert.deepEqual(SPAWN_PATH_ALLOW, ["MOSAIC_CLAUDE_BIN"]);
@@ -141,7 +147,7 @@ function spy(root) {
}
const answer = (root, over = {}) => ({
ok: true, adapter: join(root, "install", "adapter.sh"), harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit",
model: "m", provider: "p", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" }, ...over,
model: "m", provider: "p", env: { ...KEYED }, ...over,
});
// One route answer through a fresh host: refused before anything is written or spawned, with the
// one code, the owner-readable line, and a log line that names the fence.
@@ -284,23 +290,28 @@ test("fence 1: the bundle holds the copy the host checked; no MOSAIC_ name reach
await refusedRoute(t, "function", (root) => ({ harnessEnv: { FAKE_OK: "x" }, extra: () => 1 }));
});
test("fence 2: route env holds only the proxy's two names, the base URL is http on 127.0.0.1 with a port, and the host's port and token shape hold when given", async (t) => {
test("fence 2: route env holds only the proxy's names, exactly one key name, the base URL is http on 127.0.0.1 with a port, and the host's port and token shape hold when given", async (t) => {
const bad = [
undefined, "", "http://localhost:9", "http://[::1]:9", "https://127.0.0.1:9", "http://127.0.0.1", "http://127.0.0.1:", "http://127.0.0.1:9/",
"http://127.0.0.1:9/v1", "http://127.0.0.1:09", "http://127.0.0.1:0", "http://127.0.0.1:65536", "http://127.0.0.1:99999", "http://127.0.0.2:9",
"http://[email protected]:9", "HTTP://127.0.0.1:9", "http://127.0.0.1:9\n", "http://127.0.0.1:9 ", "http://127.1:9", "http://2130706433:9",
"http://127.0.0.1:9#x", "http://127.0.0.1:9?x", "http://10.0.0.1:9", 9,
];
for (const url of bad) await refusedRoute(t, `url ${JSON.stringify(url)}`, () => ({ env: url === undefined ? {} : { ANTHROPIC_BASE_URL: url } }));
for (const url of bad) await refusedRoute(t, `url ${JSON.stringify(url)}`, () => ({ env: url === undefined ? { ANTHROPIC_AUTH_TOKEN: FIXTURE_KEY } : { ANTHROPIC_BASE_URL: url, ANTHROPIC_AUTH_TOKEN: FIXTURE_KEY } }));
for (const extra of ["OTHER", "MOSAIC_CONFIG", "ANTHROPIC_API_KEY", "PATH", "anthropic_base_url"]) {
await refusedRoute(t, `env ${extra}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", [extra]: "x" } }));
await refusedRoute(t, `env ${extra}`, () => ({ env: { ...KEYED, [extra]: "x" } }));
}
// #1873 harness-matrix: no key name, or both, is refused; the key as ANTHROPIC_API_KEY alone is admitted.
await refusedRoute(t, "no key name", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }));
await refusedRoute(t, "both key names", () => ({ env: { ...KEYED, ANTHROPIC_API_KEY: FIXTURE_KEY } }));
await refusedRoute(t, "empty key", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_API_KEY: "" } }));
await admittedRoute(t, "key as ANTHROPIC_API_KEY", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_API_KEY: FIXTURE_KEY } }));
for (const token of ["a\nb", "a\u2028b", "a\u0000b", "a\u007fb"]) await refusedRoute(t, `token ${JSON.stringify(token)}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: token } }));
await refusedRoute(t, "env array", () => ({ env: ["ANTHROPIC_BASE_URL"] }));
await admittedRoute(t, "port 65535", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:65535" } }));
await admittedRoute(t, "port 65535", () => ({ env: { ...KEYED, ANTHROPIC_BASE_URL: "http://127.0.0.1:65535" } }));
// The host's port.
await refusedRoute(t, "other port", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }), { proxyPort: 9001 });
await admittedRoute(t, "its port", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9001" } }), { proxyPort: 9001 });
await refusedRoute(t, "other port", () => ({ env: { ...KEYED } }), { proxyPort: 9001 });
await admittedRoute(t, "its port", () => ({ env: { ...KEYED, ANTHROPIC_BASE_URL: "http://127.0.0.1:9001" } }), { proxyPort: 9001 });
// The host's token shape: the whole token, never a part of it.
const tokenPattern = /mst-[0-9a-f]{8}/g;
for (const token of [undefined, "xmst-deadbeef", "mst-deadbeefx", "mst-DEADBEEF", "", "mst-deadbee"]) {
@@ -418,7 +429,9 @@ test("a host whose HOME holds the repository starts the shipped pi harness's own
const pi = await import(new URL("../../plugins/harness/pi/index.mjs", import.meta.url).href);
const home = dirname(REPO);
const opts = { home, harnessModule: async (name) => (name === "pi" ? pi : null) };
const piRoute = (root) => answer(root, { harness: "pi", adapter: pi.adapter(), harnessMounts: pi.mounts({ env: {} }), harnessEnv: { PI_MODEL: "m", PI_OFFLINE: "1" } });
// #1873 harness-matrix: pi takes the key as ANTHROPIC_API_KEY and the proxy through its models.json.
const transport = { routeId: "other", endpoint: "root", api: "anthropic-messages", piProvider: "mosaic-proxy-other", compat: null };
const piRoute = (root) => answer(root, { harness: "pi", adapter: pi.adapter(), harnessMounts: pi.mounts({ env: {} }), harnessEnv: { PI_MODEL: "m", PI_OFFLINE: "1" }, env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_API_KEY: FIXTURE_KEY }, transport });
const s = await admittedRoute(t, "pi under HOME", (root) => () => piRoute(root), opts);
assert.equal(s.adapter, pi.adapter());
// The route's names, and the MOSAIC_ names the host sets itself from the module's env() (#1873
@@ -459,7 +472,7 @@ test("a route that changes after the first check is refused at the binds: nothin
assert.ok(logs.includes("triage host: route refused at the binds: adapter"), logs.join(" | "));
assert.equal(existsSync(join(root, "spawned")), false);
assert.equal(h.running, false);
for (const f of ["session.json", "relay.sock", "bundle"]) assert.equal(existsSync(join(agent, f)), false, f);
for (const f of ["session.json", "relay.sock", "bundle", "home", "work", "tmp"]) assert.equal(existsSync(join(agent, f)), false, f);
const [owner, note, ...rest] = (await h.state()).transcript;
assert.deepEqual([owner.from, note.from, note.in_reply_to, note.text, rest.length], ["owner", "host", owner.id, ROUTE_REFUSED, 0]);
rmSync(join(root, "install", "adapter.sh"));
@@ -525,7 +538,7 @@ test("end to end under the sandbox: the first message starts the session, which
join(dataRoot, "triage", "health", "snapshot.json"), join(dataRoot, "triage", "agent", "work", "health", "snapshot.json"),
];
let admits = 0;
const route = { admit: async () => { admits += 1; return { ok: true, adapter, harness: "fake", harnessEnv: { TRIAGE_PROBE: JSON.stringify(probe) }, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }; } };
const route = { admit: async () => { admits += 1; return { ok: true, adapter, harness: "fake", harnessEnv: { TRIAGE_PROBE: JSON.stringify(probe) }, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ...KEYED } }; } };
// Each read shows one more spend, so every turn reads as known and the session keeps going: two
// turns in a row with unknown usage (a stub turn spends nothing) end it.
let reads = 0;
@@ -543,7 +556,7 @@ test("end to end under the sandbox: the first message starts the session, which
assert.equal(h.running, true);
const probed = JSON.parse((await replies(1))[0].text.replace(/\n\n.*$/s, ""));
const allowed = new Set([
"PATH", "LANG", "TZ", "HOME", "TMPDIR", "ANTHROPIC_BASE_URL", "TRIAGE_PROBE", "PWD", "SHLVL", "_", "OLDPWD",
"PATH", "LANG", "TZ", "HOME", "TMPDIR", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "TRIAGE_PROBE", "PWD", "SHLVL", "_", "OLDPWD",
"MOSAIC_REQUEST", "MOSAIC_SYSTEM_PROMPT_FILE", "MOSAIC_WORKSPACE", "MOSAIC_SESSION_DIR", "MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE",
"MOSAIC_TOOL_SOCKET", "MOSAIC_TURN_MARKER", "MOSAIC_PROVIDER", "MOSAIC_MODEL", "MOSAIC_MODEL_ACTIVITY_DIR", "MOSAIC_UNSLOP_LOG",
]);
@@ -593,7 +606,7 @@ function stubRoute(root) {
mkdirSync(join(root, "install"), { recursive: true });
const adapter = join(root, "install", "adapter.sh");
writeFileSync(adapter, `exec '${process.execPath}' '${FIXTURE}'\n`, { mode: 0o644 });
return { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }) };
return { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ...KEYED } }) };
}
const repliesOf = (h, n, from = "triage") => waitFor(async () => {
const list = (await h.state()).transcript.filter((e) => e.from === from);
@@ -1323,3 +1336,85 @@ test("cap fail closed: a Console restart between the unknown end and the next me
assert.deepEqual(readdirSync(join(second.dataRoot, "triage", "agent", "session")), [], "a fresh session directory");
assert.equal(existsSync(marker), false, "the marker is used once");
});
// proxy-scope slice 4 (#1873): a Triage session still running on a key whose grace has ended stops
// with triage-key-rotated: the host line says why, the state names the code, the process ends, and
// no line, log or state holds the key. The key file is read through the keyRecord the Console hands
// the host (packages/bus/src/triage-key-file.mjs readKey); here a stand-in record.
const OLD_KEY = `mst-0123456789ab-triage-${"o".repeat(43)}`;
const NEW_KEY = `mst-0123456789ab-triage-${"n".repeat(43)}`;
const keyed = (root, key) => ({ asked: 0, key, admit: async function () { this.asked++; return answer(root, { env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: this.key } }); } });
const recordOf = (key, retiring = []) => ({ version: 1, key, keyId: "000000000000", issuedAt: "2026-11-18T00:00:00.000Z", rotateBy: "2026-12-18", retiring });
test("key rotation: a session on the old key runs through its grace and stops at its retireAt with triage-key-rotated", { timeout: 30000 }, async (t) => {
const root = scratch();
const logs = [];
let clock = Date.parse("2026-11-18T12:00:00.000Z");
let record = recordOf(OLD_KEY);
const { h, dataRoot } = host(t, root, { route: keyed(root, OLD_KEY), bwrap: standIn(root), usageSource: spendSource, now: () => new Date(clock), log: (l) => logs.push(l), keyRecord: () => record, keyPollMs: 50 });
assert.equal(KEY_ROTATED_CODE, "triage-key-rotated");
await h.message("one");
await runnerClient(root, dataRoot);
const pid = h.pid;
// The bus rotates: the old key is retiring until 12:10. Through the grace the session keeps running.
record = recordOf(NEW_KEY, [{ key: OLD_KEY, keyId: "111111111111", issuedAt: "2026-10-18T00:00:00.000Z", retireAt: "2026-11-18T12:10:00.000Z" }]);
clock = Date.parse("2026-11-18T12:09:59.000Z");
await new Promise((r) => setTimeout(r, 300));
assert.equal(h.running, true, "inside the grace the session runs");
assert.equal((await h.state()).lastStop, null);
// At the retireAt it stops, before the sweep (30 s later) removes the key from the proxy.
clock = Date.parse("2026-11-18T12:10:00.000Z");
await waitFor(() => !h.running, 10000);
assert.throws(() => process.kill(pid, 0), "the process is gone");
const s = await h.state();
assert.deepEqual(s.lastStop, { code: "triage-key-rotated", at: "2026-11-18T12:10:00.000Z" });
assert.equal(s.transcript.filter((e) => e.from === "host" && e.text === KEY_ROTATED).length, 1, "one host line says why");
assert.ok(logs.includes("triage host: stopping the session: triage-key-rotated"), logs.join(" | "));
const text = JSON.stringify(s) + logs.join("\n");
for (const k of [OLD_KEY, NEW_KEY]) assert.equal(text.includes(k.slice(-43)), false, "no key in the state or the logs");
});
test("key rotation: a message to a session whose key left the file stops it first, and the message starts a new session on the current key", { timeout: 30000 }, async (t) => {
const root = scratch();
let record = recordOf(OLD_KEY);
const route = keyed(root, OLD_KEY);
// The poll is slow here, so only the message path can stop the session.
const { h, dataRoot } = host(t, root, { route, bwrap: standIn(root), usageSource: spendSource, now: () => new Date("2026-11-18T12:00:00.000Z"), keyRecord: () => record, keyPollMs: 600000 });
await h.message("one");
await runnerClient(root, dataRoot);
const first = h.pid;
// The owner turned Triage off and on: the old key is gone; the route now answers the new key.
record = recordOf(NEW_KEY);
route.key = NEW_KEY;
rmSync(join(root, "stdin.json"));
await h.message("two");
// The stop happens inside message(), before the message is queued: assert it now, so a missing
// stop fails here rather than at the test timeout below.
assert.equal((await h.state()).lastStop?.code, "triage-key-rotated", "message() stops the session on the gone key");
await runnerClient(root, dataRoot);
assert.notEqual(h.pid, first, "a new session");
assert.throws(() => process.kill(first, 0), "the old process is gone");
const s = await h.state();
assert.equal(s.lastStop.code, "triage-key-rotated");
assert.equal(s.transcript.filter((e) => e.from === "host" && e.text === KEY_ROTATED).length, 1);
assert.equal(s.transcript.filter((e) => e.from === "owner").length, 2, "the second message is kept and delivered");
// The new session holds the current key: a message to it does not stop it.
await h.message("three");
assert.equal(h.pid !== first && h.running, true);
assert.equal((await h.state()).transcript.filter((e) => e.text === KEY_ROTATED).length, 1);
});
test("key rotation: with no key reader, or a key file that cannot be read, a running session is not stopped", { timeout: 30000 }, async (t) => {
for (const keyRecord of [null, () => { throw Object.assign(new Error("unsafe"), { code: "triage-key-unsafe" }); }]) {
const root = scratch();
const { h, dataRoot } = host(t, root, { route: keyed(root, OLD_KEY), bwrap: standIn(root), usageSource: spendSource, now: () => new Date("2026-11-18T12:00:00.000Z"), keyRecord, keyPollMs: 50 });
await h.message("one");
await runnerClient(root, dataRoot);
await new Promise((r) => setTimeout(r, 300));
await h.message("two");
assert.equal(h.running, true, String(keyRecord));
assert.equal((await h.state()).lastStop, null);
await h.stop();
}
assert.throws(() => createTriageHost({ dataRoot: "/x", keyRecord: "path" }), /keyRecord/);
});
@@ -7,7 +7,7 @@ import assert from 'node:assert/strict';
import { w15Fixture } from './w15-fixture.mjs';
const T = '2026-11-18T12:00:00.000Z';
const NOTE = 'Saving a route does not start Triage. The key and the wiring are separate.';
const NOTE = 'Saving a route does not start Triage. Triage also needs its key.';
const choices = { status: 'ready', models: [
{ key: 'down', label: 'Down', available: false, harnesses: ['claude-code'] },
{ key: 'glm-flash', label: 'GLM Flash', available: true, harnesses: ['pi'] },
@@ -40,12 +40,14 @@ test('the owner sees Triage in Settings, "not set" before a first save, the cata
await wait('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\')');
await b.evaluate('document.querySelector(\'#settings-nav a[href="#/settings/triage"]\').click()');
await wait('document.getElementById("triage-route-stored")');
assert.match(await text(b, 'triage-route-stored'), /^Not set\. No Triage route is set\.$/);
assert.match(await text(b, 'triage-route-stored'), /^Not set\. Triage has no model chosen yet, so it will not start\.$/);
assert.ok(await reads(b) >= 1, 'the owner page reads the route (the counter works)');
assert.equal(await text(b, 'triage-route-note'), NOTE);
assert.equal(await text(b, 'settings-page-title'), 'Triage');
assert.deepEqual(await options(b, 'triage-route-model'), [['', 'Choose a model', false], ['down', 'Down (down) (unavailable)', true], ['glm-flash', 'GLM Flash (glm-flash)', false], ['sonnet', 'Sonnet (sonnet)', false]]);
assert.deepEqual(await options(b, 'triage-route-harness'), [['', 'Choose a model first', false]]);
// The help line names no harness: the list carries each harness's id as its module is installed.
assert.equal(await text(b, 'triage-route-harness-help'), 'The program that runs the model, named as its module is installed. The list shows only the programs this model runs with.');
assert.equal(await value(b, 'triage-route-cap'), '', 'no default cap');
assert.equal(await value(b, 'triage-route-zone'), '', 'no default time zone');
assert.equal(await value(b, 'triage-route-reset'), '00:00');
@@ -54,7 +56,7 @@ test('the owner sees Triage in Settings, "not set" before a first save, the cata
assert.equal(await b.evaluate('document.getElementById("triage-route-catalogue")'), null);
// The harness list follows the model; a model with one harness picks it.
await pick(b, 'triage-route-model', 'glm-flash');
assert.deepEqual(await options(b, 'triage-route-harness'), [['', 'Choose a harness', false], ['pi', 'pi', false]]);
assert.deepEqual(await options(b, 'triage-route-harness'), [['', 'Choose what runs it', false], ['pi', 'pi', false]]);
assert.equal(await value(b, 'triage-route-harness'), 'pi');
await pick(b, 'triage-route-model', 'sonnet');
assert.deepEqual((await options(b, 'triage-route-harness')).map(o => o[0]), ['', 'claude-code', 'pi']);
@@ -73,10 +75,10 @@ test('Save posts the fields and the read revision once, then shows the stored ro
await wait('document.getElementById("triage-route-model")');
await fill(b, { zone: ' America/Chicago ' });
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('document.getElementById("triage-route-line")?.textContent==="Saved. Revision 1."');
await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="1"');
assert.equal(await b.evaluate('document.activeElement?.id'), 'triage-route-line', 'focus lands on the saved line, not the page body');
assert.deepEqual(await writes(b), [{ method: 'POST', body: { model: 'sonnet', harness: 'claude-code', cap: 150000, timeZone: 'America/Chicago', revision: 0 } }]);
assert.match(await text(b, 'triage-route-stored'), /Stored route: sonnet on claude-code, cap 150,000 tokens a day, reset 00:00 America\/Chicago\. Revision 1/);
assert.match(await text(b, 'triage-route-stored'), /^Saved route: sonnet, runs with claude-code\. Daily token limit 150,000, resets at 00:00 America\/Chicago\. Saved .+\.$/);
assert.equal(await value(b, 'triage-route-cap'), '150000');
// The next save carries the new revision.
await type(b, 'triage-route-cap', '9000');
@@ -93,7 +95,8 @@ test('a stored route fills the fields; each refusal is one plain line and keeps
assert.equal(await value(b, 'triage-route-harness'), 'pi');
assert.equal(await value(b, 'triage-route-cap'), '200000');
assert.equal(await value(b, 'triage-route-zone'), 'Europe/Berlin');
assert.match(await text(b, 'triage-route-stored'), /^Stored route: sonnet on pi, cap 200,000 tokens a day, reset 00:00 Europe\/Berlin\. Revision 1, saved 2026-11-18T12:00:00\.000Z\.$/);
assert.equal(await text(b, 'triage-route-stored'), `Saved route: sonnet, runs with pi. Daily token limit 200,000, resets at 00:00 Europe/Berlin. Saved ${await b.evaluate('window.MosaicLocalTime("2026-11-18T12:00:00.000Z")')}.`);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '1');
for (const [error, message, status] of [['triage-zone-unknown', 'The time zone is not one this Console knows.', 400], ['model-harness-incompatible', 'That harness does not run this model.', 400], ['model-provider-unavailable', 'The model provider is not available now.', 503]]) {
await b.evaluate(`Object.assign(window.__scenario, {'POST /api/triage/route': {status: ${status}, body: {error: ${JSON.stringify(error)}, message: ${JSON.stringify(message)}}}})`);
await fill(b, { zone: 'Mars/Olympus', cap: '777' });
@@ -106,7 +109,7 @@ test('a stored route fills the fields; each refusal is one plain line and keeps
assert.equal(await b.evaluate('document.getElementById("triage-route-reload")'), null, 'only a conflict offers a re-read');
assert.equal(await b.evaluate('document.getElementById("triage-route-save").disabled'), false);
}
assert.match(await text(b, 'triage-route-stored'), /Revision 1/, 'a refusal leaves the stored line alone');
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '1', 'a refusal leaves the stored line alone');
// A refusal with no readable answer still says one line.
await b.evaluate(`Object.assign(window.__scenario, {'POST /api/triage/route': {status: 500, body: {}}})`);
await b.evaluate('document.getElementById("triage-route-save").click()');
@@ -119,7 +122,7 @@ test('a stored route fills the fields; each refusal is one plain line and keeps
await wait('document.getElementById("triage-route-cap")');
assert.equal(await value(b, 'triage-route-cap'), '777');
assert.equal(await value(b, 'triage-route-zone'), 'Mars/Olympus');
assert.match(await text(b, 'triage-route-stored'), /Revision 1/);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '1');
});
test('a stale revision says so, keeps the fields, and Reload route reads the stored route again', { timeout: 90000 }, async t => {
@@ -136,11 +139,11 @@ test('a stale revision says so, keeps the fields, and Reload route reads the sto
await b.evaluate('document.getElementById("triage-route-reload").click()');
await wait('document.getElementById("triage-route-model")?.value==="glm-flash"');
assert.equal(await value(b, 'triage-route-cap'), '42');
assert.match(await text(b, 'triage-route-stored'), /Revision 2/);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '2');
assert.equal(await b.evaluate('document.getElementById("triage-route-reload")'), null);
await b.evaluate(`window.__scenario['POST /api/triage/route'] = {body: {route: ${JSON.stringify(route({ revision: 3, model: 'glm-flash', cap: 42 }))}, revision: 3, note: ${JSON.stringify(NOTE)}}}`);
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait('document.getElementById("triage-route-line")?.textContent==="Saved. Revision 3."');
await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="3"');
assert.equal((await writes(b)).at(-1).body.revision, 2, 'the save after a re-read carries the stored revision');
});
@@ -162,7 +165,7 @@ test('an untouched page follows the store; typed fields keep the revision they w
await away();
assert.equal(await value(b, 'triage-route-model'), 'glm-flash');
assert.equal(await value(b, 'triage-route-cap'), '42');
assert.match(await text(b, 'triage-route-stored'), /Revision 2/);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '2');
assert.equal(await b.evaluate(dot), false);
// Typed at revision 2, then saved elsewhere again: the typed fields stay and the save sends revision 2.
await type(b, 'triage-route-cap', '9000');
@@ -170,7 +173,7 @@ test('an untouched page follows the store; typed fields keep the revision they w
await away();
assert.equal(await value(b, 'triage-route-model'), 'glm-flash');
assert.equal(await value(b, 'triage-route-cap'), '9000');
assert.match(await text(b, 'triage-route-stored'), /Revision 3/);
assert.equal(await b.evaluate('document.getElementById("triage-route-stored").dataset.revision'), '3');
assert.equal(await b.evaluate(dot), true, 'the typed fields are marked unsaved');
await b.evaluate('document.getElementById("triage-route-save").click()');
await wait(`document.getElementById("triage-route-line")?.textContent===${JSON.stringify(message)}`);
@@ -198,7 +201,7 @@ test('a second Save while one runs does nothing', { timeout: 90000 }, async t =>
assert.equal(await b.evaluate('window.__writes.filter(w=>w.path==="/api/triage/route").length'), 0, 'the held POST is not recorded yet');
assert.equal(await b.evaluate('window.__posts'), 1, 'no second POST left the page');
await b.evaluate('window.__release()');
await wait('document.getElementById("triage-route-line")?.textContent==="Saved. Revision 1."');
await wait('/^Saved .+\\.$/.test(document.getElementById("triage-route-line")?.textContent) && document.getElementById("triage-route-stored")?.dataset.revision==="1"');
assert.equal((await writes(b)).length, 1);
});
@@ -217,7 +220,9 @@ test('a catalogue that is not ready says so and offers no model', { timeout: 900
const { f, b, wait } = await w15Fixture(t, { scenario: scenario({ ...unset, choices: { status: 'bus-unavailable', models: [] } }) });
await b.navigate(f.base + '/#/settings/triage');
await wait('document.getElementById("triage-route-catalogue")');
assert.match(await text(b, 'triage-route-catalogue'), /No organization bus offered a model catalogue \(bus-unavailable\)/);
assert.match(await text(b, 'triage-route-catalogue'), /No organization can show your models right now, so no route can be saved\. Open Model setup to see why each organization can.t see your models\./);
assert.equal(await b.evaluate('document.getElementById("triage-route-catalogue").dataset.status'), 'bus-unavailable');
assert.equal(await b.evaluate('document.querySelector("#triage-route-catalogue a").getAttribute("href")'), '#/settings/model-setup');
assert.deepEqual(await options(b, 'triage-route-model'), [['', 'Choose a model', false]]);
});
+295 -14
View File
@@ -8,10 +8,10 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:net";
import { request } from "node:http";
import { createServer as createHttpServer, request } from "node:http";
import { execFileSync, spawnSync } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client } from "../../bus/src/client.mjs";
@@ -23,7 +23,7 @@ import { readUsage, usagePath } from "../src/triage-usage.mjs";
import { startServer } from "../src/serve.mjs";
import { createDevOwner } from "../src/dev-owner.mjs";
import { NO_ROUTE_MESSAGE, capMessage } from "../src/triage-http.mjs";
import { keyIdOf, keyPrefix } from "../../cli/src/triage-key-file.mjs";
import { keyIdOf, keyPrefix } from "../../bus/src/triage-key-file.mjs";
const FIXTURE = fileURLToPath(new URL("./fixtures/triage-adapter.mjs", import.meta.url));
const SRC = fileURLToPath(new URL("../src/", import.meta.url));
@@ -361,15 +361,26 @@ test("refusal: the harness cannot run the model, or its module is missing or bro
await refusal(t, "module lacks bundle", { setup, code: "triage-harness-incompatible", opts: { module: { bundle: undefined } } });
await refusal(t, "module lacks env", { setup, code: "triage-harness-incompatible", opts: { module: { env: undefined } } });
await refusal(t, "env ignores the proxy", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true } } });
const viaApiKey = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_BASE_URL: proxy.baseUrl, ANTHROPIC_API_KEY: proxy.key } : {}) });
await refusal(t, "env puts the key in another variable", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, env: viaApiKey } } });
// #1873 harness-matrix: the key goes into exactly one of the route's key names (ROUTE_KEY_NAMES).
const viaOther = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_BASE_URL: proxy.baseUrl, FAKE_KEY: proxy.key } : {}) });
await refusal(t, "env puts the key in a name the route does not take", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, envNames: ["FAKE_OK", "FAKE_KEY"], env: viaOther } } });
const bothNames = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_AUTH_TOKEN: proxy.key, ANTHROPIC_API_KEY: proxy.key } : {}) });
await refusal(t, "env puts the key in both route key names", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, env: bothNames } } });
const changed = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_API_KEY: `Bearer ${proxy.key}` } : {}) });
await refusal(t, "env changes the key", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, env: changed } } });
const urlElsewhere = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key, FAKE_URL: proxy.baseUrl } : {}) });
await refusal(t, "env names the proxy URL in another variable", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, envNames: ["FAKE_OK", "FAKE_URL"], env: urlElsewhere } } });
const twice = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_BASE_URL: proxy.baseUrl, ANTHROPIC_AUTH_TOKEN: proxy.key, FAKE_COPY: `k=${proxy.key}` } : {}) });
await refusal(t, "env puts the key in a second variable too", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, envNames: ["FAKE_OK", "FAKE_COPY"], env: twice } } });
const otherUrl = ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_BASE_URL: "http://127.0.0.1:1", ANTHROPIC_AUTH_TOKEN: proxy.key } : {}) });
await refusal(t, "env names another proxy URL", { setup, code: "triage-harness-incompatible", opts: { module: { envRaw: true, env: otherUrl } } });
});
test("refusal: pi, which takes its proxy through its own models.json and ANTHROPIC_API_KEY, is refused as not compatible", { timeout: 30000 }, async (t) => {
// #1873 harness-matrix: pi takes the proxy through its own models.json, which the host writes, and
// the key as ANTHROPIC_API_KEY. The route admits it when the provider gives a transport for pi, and
// refuses a Claude model on pi even when a stale catalogue row still names pi.
const piOffer = (over = {}) => offer({ key: "glm-5", provider: "other", model: "fixture-triage-model", module: "cliproxy", upstream: "other", harnesses: ["claude-code", "pi"], ...over });
async function piRoute(t, { offered = piOffer(), harness = "pi" } = {}) {
const root = scratch();
const dataRoot = join(root, "data");
const configDir = join(root, "cfg");
@@ -377,15 +388,50 @@ test("refusal: pi, which takes its proxy through its own models.json and ANTHROP
const proxyServer = createServer((s) => s.destroy());
const proxyPort = await listen(proxyServer);
t.after(() => closed(proxyServer));
const route = createTriageRoute({ dataRoot, configDir, proxyPort, catalogues: async () => [catalogue([offer({ harnesses: ["claude-code", "pi"] })])], env: {} });
const route = createTriageRoute({ dataRoot, configDir, proxyPort, catalogues: async () => [catalogue([offered])], env: {} });
mkdirSync(join(dataRoot, "triage"), { recursive: true, mode: 0o700 });
chmodSync(dataRoot, 0o700);
writeRoute(dataRoot, { model: "glm-5", harness: "pi", limit: 1000, timeZone: "UTC", by: "owner" });
writeRoute(dataRoot, { model: "glm-5", harness, limit: 1000, timeZone: "UTC", by: "owner" });
issue(configDir);
assert.deepEqual(await route.admit(), { ok: false, code: "triage-harness-incompatible" });
// The same store with claude-code is admitted, so the refusal is pi's own.
writeRoute(dataRoot, { model: "glm-5", harness: "claude-code", limit: 1000, timeZone: "UTC", by: "owner", revision: 1 });
assert.equal((await route.admit()).ok, true);
return { route, proxyPort, dataRoot };
}
test("#1873 pi is admitted through the proxy: the key as ANTHROPIC_API_KEY, the provider's transport, pi's own names", { timeout: 30000 }, async (t) => {
for (const [provider, upstream, model, piProvider] of [["other", "other", "fixture-triage-model", "mosaic-proxy-other"], ["zai", "zai", "glm-fixture", "mosaic-proxy-glm"], ["codex", "codex", "gpt-fixture", "mosaic-proxy-codex"]]) {
const { route, proxyPort } = await piRoute(t, { offered: piOffer({ provider, upstream, model }) });
const a = await route.admit();
assert.equal(a.ok, true, `${provider}: ${a.code}`);
assert.deepEqual(Object.keys(a.env).sort(), ["ANTHROPIC_API_KEY", "ANTHROPIC_BASE_URL"], provider);
assert.equal(a.env.ANTHROPIC_BASE_URL, `http://127.0.0.1:${proxyPort}`);
assert.equal(a.transport.piProvider, piProvider, provider);
assert.deepEqual([a.harness, a.model, a.turnEnd, a.harnessEnv.PI_PROVIDER, a.harnessEnv.PI_MODEL, a.harnessEnv.PI_OFFLINE], ["pi", model, "marker", piProvider, model, "1"], provider);
assert.equal(Object.keys(a.harnessEnv).some((k) => k.startsWith("ANTHROPIC") || k.startsWith("MOSAIC_")), false, provider);
}
});
test("#1873 an OAuth Claude model on pi is refused at the Triage route, even with a stale catalogue row that names pi", { timeout: 30000 }, async (t) => {
for (const offered of [
piOffer({ provider: "anthropic", upstream: "claude", model: "claude-opus-5-5" }),
// An API-key group model whose name an OAuth Claude account offers: the catalogue holds it to claude-code.
piOffer({ provider: "other", upstream: "other", model: "anthropic/claude-sonnet-5-5", harnesses: ["claude-code"] }),
]) {
const { route } = await piRoute(t, { offered });
assert.deepEqual(await route.admit(), { ok: false, code: "triage-harness-incompatible" }, offered.model);
}
// Jason 2026-11-19: a Claude model from an API key runs on any harness, so the same name on an
// API-key row that names pi is admitted on pi.
const api = await piRoute(t, { offered: piOffer({ provider: "other", upstream: "other", model: "anthropic/claude-sonnet-5-5" }) });
const b = await api.route.admit();
assert.equal(b.ok, true, b.code);
assert.equal(b.transport.piProvider, "mosaic-proxy-other");
// The same Claude row on claude-code is admitted, so the refusal is the harness rule's.
const { route } = await piRoute(t, { offered: piOffer({ provider: "anthropic", upstream: "claude", model: "claude-opus-5-5" }), harness: "claude-code" });
const a = await route.admit();
assert.equal(a.ok, true, a.code);
assert.deepEqual(Object.keys(a.env).sort(), ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"]);
// A provider with no route() gives pi no transport, so pi cannot take the proxy and is refused.
const none = await piRoute(t, { offered: offer({ harnesses: ["claude-code", "pi"] }) });
assert.deepEqual(await none.route.admit(), { ok: false, code: "triage-harness-incompatible" });
});
test("the proxy port is read at each admit: a proxy set up after the Console started counts, and the host's fence asks the same function", { timeout: 30000 }, async (t) => {
@@ -496,6 +542,170 @@ test("fence: a resolved route that fails the host's fences launches nothing and
}
});
// #1873 harness-matrix: a harness that takes the key as ANTHROPIC_API_KEY and the URL through its own
// file, as pi does, meets every host fence: one key name, the key in no harnessEnv value or file, the
// key's shape, a valid transport, the URL from the route only, the file inside the session's HOME.
const piLike = (over = {}) => ({
envRaw: true,
env: ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key } : {}) }),
bundle: ({ dir, proxy }) => {
const file = join(dir, "..", "home", "harness.json");
writeFileSync(file, JSON.stringify({ baseUrl: proxy.baseUrl, apiKey: "$ANTHROPIC_API_KEY" }), { mode: 0o600, flag: "wx" });
return { files: { harness: join(dir.slice(0, -"/bundle".length), "home", "harness.json") } };
},
...over,
});
test("#1873 fence: a pi-shaped answer passes the host's fences, and each fence still fires on it", { timeout: 60000 }, async (t) => {
// The pi-shaped harness is admitted, writes its file under HOME and launches.
const root0 = scratch();
const ok = await rig(t, { bwrap: spy(root0), module: piLike() });
ok.setRoute();
const key = issue(ok.configDir);
const a = await ok.route.admit();
assert.deepEqual(Object.keys(a.env).sort(), ["ANTHROPIC_API_KEY", "ANTHROPIC_BASE_URL"]);
await ok.h.message("hello");
await waitFor(() => existsSync(join(root0, "spawned")));
const argv = readFileSync(join(root0, "spawn-argv"), "utf8").split("\n");
const file = join(ok.dataRoot, "triage", "agent", "home", "harness.json");
const at = argv.findIndex((v, i) => v === "--ro-bind" && argv[i + 1] === file && argv[i + 2] === file);
const rw = argv.findIndex((v, i) => v === "--bind" && argv[i + 1] === join(ok.dataRoot, "triage", "agent"));
assert.ok(at > rw && rw >= 0, "the harness file is bound read-only over the writable run directory");
const spawnEnv = readFileSync(join(root0, "spawn-env"), "utf8");
assert.ok(spawnEnv.split("\n").some((l) => l === `ANTHROPIC_API_KEY=${key}`), "the key goes to the spawn as ANTHROPIC_API_KEY");
assert.equal(spawnEnv.includes("ANTHROPIC_AUTH_TOKEN="), false);
await ok.h.stop();
const fence = async (label, { module, patch = (x) => x, fenceName, tokenDir = null, seed = null }) => {
const rootN = scratch();
const r = await rig(t, { bwrap: spy(rootN), module, ...(tokenDir ? { tokenDir } : {}) });
r.setRoute();
seed?.(r);
const k = issue(r.configDir);
const admit = r.route.admit.bind(r.route);
r.route.admit = async () => { const x = await admit(); return x.ok ? patch(x, k) : x; };
await assert.rejects(r.h.message("hello"), (e) => e.code === "triage-route-invalid", label);
assert.ok(r.logs.includes(`triage host: route refused: ${fenceName}`), `${label}: ${r.logs.join(" | ")}`);
assert.equal(existsSync(join(rootN, "spawned")), false, `${label}: nothing launched`);
assert.equal(existsSync(join(r.dataRoot, "triage", "agent", "home", "harness.json")), false, `${label}: the harness file is removed`);
// Nothing the refused start wrote keeps the key: not the log, not a file under the run directory.
assertNoKey(k, [["host log", r.logs.join("\n")], ...filesUnder(join(r.dataRoot, "triage", "agent"))]);
};
await fence("both key names", { module: piLike(), patch: (x) => ({ ...x, env: { ...x.env, ANTHROPIC_AUTH_TOKEN: x.env.ANTHROPIC_API_KEY } }), fenceName: "route-env" });
await fence("no key name", { module: piLike(), patch: (x) => ({ ...x, env: { ANTHROPIC_BASE_URL: x.env.ANTHROPIC_BASE_URL } }), fenceName: "route-env" });
await fence("the key in harnessEnv", { module: piLike(), patch: (x, k) => ({ ...x, harnessEnv: { FAKE_OK: `k=${k}` } }), fenceName: "harness-env" });
await fence("a transport the bus would refuse", { module: piLike(), patch: (x) => ({ ...x, transport: { routeId: "x", endpoint: "elsewhere", api: "anthropic-messages", piProvider: "p", compat: null } }), fenceName: "transport" });
await fence("a key of another instance's shape", { module: piLike(), fenceName: "route-env", tokenDir: "/another/instance" });
await fence("env copies the real key at the host", { module: piLike({ env: ({ proxy }) => ({ FAKE_OK: proxy && !proxy.key.startsWith("triage-route-probe") ? `k=${proxy.key}` : "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key } : {}) }) }), fenceName: "harness-bundle" });
await fence("env names another proxy at the host", { module: piLike({ env: ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key, ...(proxy.key.startsWith("triage-route-probe") ? {} : { ANTHROPIC_BASE_URL: "http://127.0.0.1:1" }) } : {}) }) }), fenceName: "harness-bundle" });
await fence("no proxy URL in env or a file", { module: piLike({ bundle: () => ({ files: {} }) }), fenceName: "harness-bundle" });
await fence("a harness file outside HOME", { module: piLike({ bundle: ({ dir, proxy }) => { const f = join(dir, "..", "work", "x.json"); writeFileSync(f, proxy.baseUrl, { flag: "wx" }); return { files: { x: join(dir.slice(0, -"/bundle".length), "work", "x.json") } }; } }), fenceName: "harness-bundle" });
await fence("a harness file holding the key", { module: piLike({ bundle: ({ dir, proxy }) => { const f = join(dir.slice(0, -"/bundle".length), "home", "harness.json"); writeFileSync(f, `${proxy.baseUrl} ${proxy.key}`, { flag: "wx" }); return { files: { harness: f } }; } }), fenceName: "harness-bundle" });
await fence("a harness file that is a link", { module: piLike({ bundle: ({ dir, proxy }) => { const base = dir.slice(0, -"/bundle".length); writeFileSync(join(base, "work", "real.json"), proxy.baseUrl); const f = join(base, "home", "harness.json"); symlinkSync(join(base, "work", "real.json"), f); return { files: { harness: f } }; } }), fenceName: "harness-bundle" });
// The host gives bundle() the real key, so no file it writes in bundle/, by write() or by its own
// means, may hold the key; a harness file names no URL but the proxy's.
const piWith = (extra) => piLike({ bundle: (o) => { extra(o); return piLike().bundle(o); } });
// write() refuses before the file exists, so the key never rests on disk, not even until the scan.
let keyOnDisk = null;
await fence("a bundle file written through write() holding the key", { module: piWith(({ write, dir, proxy }) => {
try { write("auth.json", JSON.stringify({ apiKey: proxy.key })); } finally { keyOnDisk = existsSync(join(dir, "auth.json")); }
}), fenceName: "harness-bundle" });
assert.equal(keyOnDisk, false, "write() wrote no file that holds the key");
await fence("a bundle file written directly holding the key", { module: piWith(({ dir, proxy }) => writeFileSync(join(dir, "auth.json"), proxy.key, { flag: "wx" })), fenceName: "harness-bundle" });
await fence("a bundle file in a subdirectory holding the key", { module: piWith(({ dir, proxy }) => { mkdirSync(join(dir, "sub")); writeFileSync(join(dir, "sub", "auth.json"), proxy.key, { flag: "wx" }); }), fenceName: "harness-bundle" });
await fence("a harness file that names a second URL", { module: piLike({ bundle: ({ dir, proxy }) => { const f = join(dir.slice(0, -"/bundle".length), "home", "harness.json"); writeFileSync(f, JSON.stringify({ a: proxy.baseUrl, b: "https://api.example.invalid/v1" }), { flag: "wx" }); return { files: { harness: f } }; } }), fenceName: "harness-bundle" });
// Review round 2: the fences read decoded JSON and every file this start made, named or not.
const agentOf = (dir) => dir.slice(0, -"/bundle".length);
const escapedKey = (key) => `\\u${key.charCodeAt(0).toString(16).padStart(4, "0")}${key.slice(1)}`;
const harnessFile = (text) => piLike({ bundle: ({ dir, proxy }) => { const f = join(agentOf(dir), "home", "harness.json"); writeFileSync(f, text(proxy), { flag: "wx" }); return { files: { harness: f } }; } });
await fence("a harness file that names a second URL, JSON-escaped", { module: harnessFile((proxy) => `{"a":${JSON.stringify(proxy.baseUrl)},"baseUrl":"http:\\/\\/api.example.invalid\\/v1"}`), fenceName: "harness-bundle" });
await fence("a harness file that holds the key, JSON-escaped", { module: harnessFile((proxy) => `{"a":${JSON.stringify(proxy.baseUrl)},"apiKey":"${escapedKey(proxy.key)}"}`), fenceName: "harness-bundle" });
await fence("a harness file that holds the key as a JSON key, escaped", { module: harnessFile((proxy) => `{"a":${JSON.stringify(proxy.baseUrl)},"${escapedKey(proxy.key)}":1}`), fenceName: "harness-bundle" });
keyOnDisk = null;
await fence("a bundle file written through write() that holds the key, JSON-escaped", { module: piWith(({ write, dir, proxy }) => {
try { write("auth.json", `{"apiKey":"${escapedKey(proxy.key)}"}`); } finally { keyOnDisk = existsSync(join(dir, "auth.json")); }
}), fenceName: "harness-bundle" });
assert.equal(keyOnDisk, false, "write() wrote no file that holds the key, escaped");
await fence("an unnamed file under home/ that holds the key", { module: piWith(({ dir, proxy }) => writeFileSync(join(agentOf(dir), "home", "auth.json"), proxy.key, { flag: "wx" })), fenceName: "harness-bundle" });
await fence("an unnamed file under work/ that holds the key", { module: piWith(({ dir, proxy }) => writeFileSync(join(agentOf(dir), "work", "stash.txt"), proxy.key, { flag: "wx" })), fenceName: "harness-bundle" });
await fence("an unnamed file under tmp/ that holds the key", { module: piWith(({ dir, proxy }) => writeFileSync(join(agentOf(dir), "tmp", "stash.txt"), proxy.key, { flag: "wx" })), fenceName: "harness-bundle" });
await fence("a harness file with a second hard link", { module: piLike({ bundle: ({ dir, proxy }) => {
const f = join(agentOf(dir), "home", "harness.json");
writeFileSync(f, JSON.stringify({ baseUrl: proxy.baseUrl }), { flag: "wx" });
linkSync(f, join(agentOf(dir), "tmp", "harness.json"));
return { files: { harness: f } };
} }), fenceName: "harness-bundle" });
await fence("a link under home/", { module: piWith(({ dir }) => symlinkSync("/etc/hostname", join(agentOf(dir), "home", "link"))), fenceName: "harness-bundle" });
// A URL a harness reads without "//", or that a URL parser reads once it drops a newline.
const withUrl = (url) => harnessFile((proxy) => JSON.stringify({ a: proxy.baseUrl, baseUrl: url }));
await fence("a harness file that names a URL with no slashes", { module: withUrl("http:api.example.invalid/v1"), fenceName: "harness-bundle" });
await fence("a harness file that names a URL with backslashes", { module: withUrl("http:\\\\api.example.invalid/v1"), fenceName: "harness-bundle" });
await fence("a harness file that names a URL with a newline in its scheme", { module: withUrl("h\nttp:api.example.invalid/v1"), fenceName: "harness-bundle" });
// A file the module does not name, which the harness reads from HOME all the same (pi's
// ~/.pi/agent/models.json), while env() names the proxy.
const undeclared = (url) => piLike({
env: ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key, ANTHROPIC_BASE_URL: proxy.baseUrl } : {}) }),
bundle: ({ dir, proxy }) => {
mkdirSync(join(agentOf(dir), "home", ".pi", "agent"), { recursive: true });
writeFileSync(join(agentOf(dir), "home", ".pi", "agent", "models.json"), JSON.stringify({ providers: { x: { baseUrl: url(proxy) } } }), { flag: "wx" });
return { files: {} };
},
});
await fence("an unnamed file under home/ that names another URL", { module: undeclared(() => "https://api.example.invalid/v1"), fenceName: "harness-bundle" });
// A file JSON.parse refuses but a looser parser takes (pi: a byte order mark, comments, trailing
// commas) may hold no escape the host cannot decode.
const escapedUrl = (proxy) => `{"a":${JSON.stringify(proxy.baseUrl)},"baseUrl":"http:\\/\\/api.example.invalid\\/v1"}`;
await fence("a harness file with a byte order mark and an escaped URL", { module: harnessFile((proxy) => `\uFEFF${escapedUrl(proxy)}`), fenceName: "harness-bundle" });
await fence("a harness file with a comment and an escaped URL", { module: harnessFile((proxy) => `// models\n${escapedUrl(proxy)}`), fenceName: "harness-bundle" });
await fence("a harness file with a trailing comma and an escaped key", { module: harnessFile((proxy) => `{"a":${JSON.stringify(proxy.baseUrl)},"apiKey":"${escapedKey(proxy.key)}",}`), fenceName: "harness-bundle" });
keyOnDisk = null;
await fence("a bundle file written through write() with a byte order mark and an escaped key", { module: piWith(({ write, dir, proxy }) => {
try { write("auth.json", `\uFEFF{"apiKey":"${escapedKey(proxy.key)}"}`); } finally { keyOnDisk = existsSync(join(dir, "auth.json")); }
}), fenceName: "harness-bundle" });
assert.equal(keyOnDisk, false, "write() refuses a loose file with an escape before it exists");
// session/, kept across starts, is not the module's to write: what it adds goes, and the next
// start takes a fresh session.
await fence("a file written under session/", { module: piWith(({ dir, proxy }) => writeFileSync(join(agentOf(dir), "session", "auth.txt"), proxy.key, { flag: "wx" })), fenceName: "harness-bundle" });
// A URL with no slashes inside a longer line, which no URL parser reads whole.
await fence("a plain-text harness file that names a URL with no slashes in a line", { module: harnessFile((proxy) => `${proxy.baseUrl}\nbaseUrl=http:api.example.invalid/v1\n`), fenceName: "harness-bundle" });
// The host's own bundle files are the host's: a module that rewrites one is refused.
await fence("a module that rewrites the host's policy file", { module: piWith(({ dir, proxy }) => writeFileSync(join(dir, "policy.json"), `{"k":"${escapedKey(proxy.key)}"}`)), fenceName: "harness-bundle" });
// Review round 4. pi runs a config value that starts with "!" as a shell command, in a parsed
// file or one only pi's looser parser takes.
await fence("a harness file with a command value", { module: harnessFile((proxy) => JSON.stringify({ a: proxy.baseUrl, apiKey: "!env" })), fenceName: "harness-bundle" });
await fence("a harness file with a command header and a comment", { module: harnessFile((proxy) => `// models\n{"a":${JSON.stringify(proxy.baseUrl)},"headers":{"x":"!env"}}`), fenceName: "harness-bundle" });
await fence("an unnamed file under home/ with a command value", { module: undeclared(() => "!env"), fenceName: "harness-bundle" });
await fence("a harness file with a JSON-escaped command value", { module: harnessFile((proxy) => `{"a":${JSON.stringify(proxy.baseUrl)},"apiKey":"\\u0021env"}`), fenceName: "harness-bundle" });
// A host bundle file the module deletes or replaces is refused, though the scan never reaches it.
await fence("a module that deletes the host's prompt", { module: piWith(({ dir }) => rmSync(join(dir, "prompt.md"))), fenceName: "harness-bundle" });
await fence("a module that hard-links the host's prompt", { module: piWith(({ dir }) => linkSync(join(dir, "prompt.md"), join(agentOf(dir), "tmp", "prompt.md"))), fenceName: "harness-bundle" });
// A FIFO there has one link, and a read of it with no writer would block: the host must see it is
// not a regular file before it reads.
await fence("a module that replaces the host's prompt with a FIFO", { module: piWith(({ dir }) => { rmSync(join(dir, "prompt.md")); execFileSync("mkfifo", [join(dir, "prompt.md")]); }), fenceName: "harness-bundle" });
await fence("a module that replaces the host's policy with a directory", { module: piWith(({ dir }) => { rmSync(join(dir, "policy.json")); mkdirSync(join(dir, "policy.json")); }), fenceName: "harness-bundle" });
// A session/ file rewritten in place at the same size, with its times set back, still shows: its
// ctime moved.
const seeded = (r) => { const d = join(r.dataRoot, "triage", "agent", "session"); mkdirSync(d, { recursive: true, mode: 0o700 }); writeFileSync(join(d, "history.jsonl"), "x".repeat(512), { mode: 0o600 }); };
await fence("a session/ file rewritten with its times set back", { seed: seeded, module: piWith(({ dir, proxy }) => {
const f = join(agentOf(dir), "session", "history.jsonl");
const st = statSync(f);
writeFileSync(f, (proxy.key + "x".repeat(512)).slice(0, 512));
utimesSync(f, st.atimeMs / 1000, st.mtimeMs / 1000);
}), fenceName: "harness-bundle" });
// The unnamed models.json with only the proxy's URL launches.
{
const rootN = scratch();
const p = await rig(t, { bwrap: spy(rootN), module: undeclared((proxy) => `${proxy.baseUrl}/v1`) });
p.setRoute();
issue(p.configDir);
await p.h.message("hello");
await waitFor(() => existsSync(join(rootN, "spawned")));
await p.h.stop();
}
await fence("env changes the key at the host", { module: piLike({ env: ({ proxy }) => ({ FAKE_OK: "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key.startsWith("triage-route-probe") ? proxy.key : `Bearer ${proxy.key}` } : {}) }) }), fenceName: "harness-bundle" });
await fence("env drops the key at the host", { module: piLike({ env: ({ proxy }) => ({ FAKE_OK: "1", ...(proxy?.key.startsWith("triage-route-probe") ? { ANTHROPIC_API_KEY: proxy.key } : {}) }) }), fenceName: "harness-bundle" });
await fence("env answers another value at the host", { module: piLike({ env: ({ proxy }) => ({ FAKE_OK: proxy && !proxy.key.startsWith("triage-route-probe") ? "2" : "1", ...(proxy ? { ANTHROPIC_API_KEY: proxy.key } : {}) }) }), fenceName: "harness-bundle" });
});
test("fence: every admit runs the fences, a running session or not: a message whose route fails is not queued", { timeout: 30000 }, async (t) => {
const root0 = scratch();
const r = await rig(t, { bwrap: standIn(root0) });
@@ -578,6 +788,77 @@ printf '%s\\n' '{"type":"result","subtype":"success","is_error":false,"result":"
assertNoKey(key, [...filesUnder(dataRoot), ["host log", logs.join("\n")], ["state", JSON.stringify(await h.state())]]);
});
// #1873 harness-matrix: the pi harness the repository ships, end to end under the real sandbox and
// the real pi, against a stand-in proxy on the route's port that answers the Anthropic messages API.
// The route admits pi with the provider's transport; the host writes pi's models.json under the
// session's HOME, binds it read-only, and gives pi the key as ANTHROPIC_API_KEY. No model is called.
function anthropicStandIn(text) {
const seen = [];
const server = createHttpServer((req, res) => {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
let body = {};
try { body = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { body = {}; }
const keyHeader = req.headers["x-api-key"] ?? String(req.headers.authorization ?? "").replace(/^Bearer /, "");
seen.push({ method: req.method, url: req.url, model: body.model, keySha: sha(keyHeader), stream: body.stream });
if (req.method !== "POST" || !/^\/v1\/messages(\?|$)/.test(req.url ?? "")) { res.writeHead(404); return res.end(); }
const message = { id: "msg_stand_in", type: "message", role: "assistant", model: body.model, stop_sequence: null };
res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
const event = (type, data) => res.write(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`);
event("message_start", { message: { ...message, content: [], stop_reason: null, usage: { input_tokens: 1, output_tokens: 0 } } });
event("content_block_start", { index: 0, content_block: { type: "text", text: "" } });
event("content_block_delta", { index: 0, delta: { type: "text_delta", text } });
event("content_block_stop", { index: 0 });
event("message_delta", { delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 1 } });
event("message_stop", {});
res.end();
});
});
return { server, seen };
}
test("#1873 the pi harness answers through the proxy: the route's model, the Triage key as ANTHROPIC_API_KEY, pi's models.json read-only, no key in any file", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const dataRoot = join(root, "data");
const configDir = join(root, "cfg");
mkdirSync(configDir, { mode: 0o700 });
const { server, seen } = anthropicStandIn("pi stand-in answer");
const proxyPort = await listen(server);
t.after(() => { server.closeAllConnections?.(); return closed(server); });
const logs = [];
const route = createTriageRoute({ dataRoot, configDir, proxyPort, catalogues: async () => [catalogue([piOffer()])], env: {} });
const h = createTriageHost({ dataRoot, route, proxyPort, tokenPattern: triageTokenPattern(configDir), readSnapshot: async () => SNAPSHOT, env: CONSOLE_ENV, usageSource: spendSource, now: () => new Date(NOW), log: (l) => logs.push(l) });
t.after(() => h.stop());
mkdirSync(join(dataRoot, "triage"), { recursive: true, mode: 0o700 });
chmodSync(dataRoot, 0o700);
writeRoute(dataRoot, { model: "glm-5", harness: "pi", limit: 100000, timeZone: "UTC", by: "owner" });
const key = issue(configDir);
await h.message("hello");
const replies = await triageReplies(h, 1);
assert.equal(replies[0].text, "pi stand-in answer", JSON.stringify({ transcript: (await h.state()).transcript, logs }));
// What the stand-in proxy saw: the Anthropic messages route, the route's model, the Triage key.
const calls = seen.filter((c) => c.method === "POST");
assert.ok(calls.length >= 1, JSON.stringify(seen));
for (const c of calls) {
assert.match(c.url, /^\/v1\/messages/);
assert.equal(c.model, "fixture-triage-model");
assert.equal(c.keySha, sha(key), "pi sends the Triage key");
}
// pi's models.json: the route's provider and model at the proxy's URL, the key only by name.
const agent = join(dataRoot, "triage", "agent");
const models = JSON.parse(readFileSync(join(agent, "home", ".pi", "agent", "models.json"), "utf8"));
assert.deepEqual(Object.keys(models.providers), ["mosaic-proxy-other"]);
const p = models.providers["mosaic-proxy-other"];
assert.deepEqual([p.baseUrl, p.api, p.apiKey, p.models.map((m) => m.id)], [`http://127.0.0.1:${proxyPort}`, "anthropic-messages", "$ANTHROPIC_API_KEY", ["fixture-triage-model"]]);
const session = JSON.parse(readFileSync(join(agent, "session.json"), "utf8"));
assert.deepEqual([session.harness, session.turnEnd, session.harnessEnv.PI_PROVIDER, session.harnessEnv.PI_MODEL, session.harnessEnv.MOSAIC_THINKING], ["pi", "marker", "mosaic-proxy-other", "fixture-triage-model", "low"]);
assert.equal(Object.keys(session.harnessEnv).some((k) => k.startsWith("ANTHROPIC")), false);
await h.stop();
assertNoKey(key, [...filesUnder(dataRoot), ["host log", logs.join("\n")], ["state", JSON.stringify(await h.state())]]);
});
test("the key scrub: an answer that carries the session's key, or anything shaped like a key, reaches the transcript and the read with the key removed", { skip, timeout: 60000 }, async (t) => {
const r = await rig(t);
r.setRoute();
@@ -635,8 +916,8 @@ function loaded(t, args) {
return readFileSync(out, "utf8").split("\n").filter(Boolean).map((u) => (u.startsWith("file:") ? fileURLToPath(u) : u));
}
const CLIENT = join(REPO_ROOT, "packages", "model-proxy", "src", "client.mjs");
const KEY_VERBS = join(REPO_ROOT, "packages", "cli", "src", "triage-key.mjs");
const KEY_FILE = join(REPO_ROOT, "packages", "cli", "src", "triage-key-file.mjs");
const KEY_VERBS = join(REPO_ROOT, "packages", "bus", "src", "triage-key.mjs");
const KEY_FILE = join(REPO_ROOT, "packages", "bus", "src", "triage-key-file.mjs");
test("the Console process never imports the proxy management client or the key verbs' module", { timeout: 120000 }, (t) => {
// The control: the hook sees them when a module that uses them loads.
@@ -56,10 +56,10 @@ function workspaceOrgs({ failThreads = false, seen = null, send = false, copies
}
// No bus or setup work runs in these tests: every restart below is refused before the admin is used.
const refusingAdmin = () => createOrgAdmin({ service: {}, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
const SETTINGS = ['Identity', 'Appearance', 'Projects', 'Agents and roles', 'Models and routing', 'Arbiters', 'Task tracker', 'Channels', 'Launch limits', 'Assistant', 'Token use', 'Model proxy', 'Console', 'Organizations', 'About', 'Members and invites', 'Bus', 'Archive or delete'];
const SETTINGS = ['Identity', 'Appearance', 'Projects', 'Agents and roles', 'Models and routing', 'Arbiters', 'Task tracker', 'Channels', 'Launch limits', 'Assistant', 'Token use', 'Model setup', 'Console', 'Organizations', 'About', 'Members and invites', 'Bus', 'Archive or delete'];
const TAGS = ['org file', 'override', 'system', 'root', 'not built', 'danger'];
// Every page the Settings view has for the owner (bus.js settingsPages).
const SETTINGS_PAGES = ['appearance', 'business', 'limits', 'organizations', 'routing', 'agents', 'assistant', 'tokens', 'model-proxy', 'console', 'about'];
const SETTINGS_PAGES = ['appearance', 'business', 'limits', 'organizations', 'routing', 'agents', 'assistant', 'tokens', 'model-setup', 'console', 'about'];
test('workspace navigation exposes all organizations and remembers project grouping', async t => {
const organizations = {
+2 -1
View File
@@ -186,7 +186,8 @@ test('Queue, Business and Settings in their five states, with no move button', {
// The owner's model proxy is reached from Settings, never from the Console tree.
await go('#/settings', 'Settings');
assert.equal(await count('nav.tree a[href="/proxy"]'), 0);
assert.equal(await count('#settings-nav a[href="#/settings/model-proxy"]'), 1);
// Slice 4 names the page Model setup; the old #/settings/model-proxy address still opens it.
assert.equal(await count('#settings-nav a[href="#/settings/model-setup"]'), 1);
// About holds the notifier and instance facts; browser appearance saves immediately.
await go('#/settings/about', 'Settings');