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
47 changed files with 3600 additions and 417 deletions

No files matched your search

+24 -1
View File
@@ -708,6 +708,7 @@ export class Broker {
#credentialVerbs;
#proxyInit;
#proxyFenceClear;
#proxyTriageKey;
#proxyPage;
#project;
#library;
@@ -772,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');
@@ -802,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;
@@ -6220,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;
+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",
+84 -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;
@@ -1905,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);
@@ -1913,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();
@@ -1930,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" } };
});
}
+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\./);
});
+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 -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";
+34 -1
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 });
@@ -254,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);
});
+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)] : [];
+22
View File
@@ -36,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) => {
@@ -71,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') {
@@ -118,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;
+43 -15
View File
@@ -1329,7 +1329,7 @@
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-proxy">${text}</a>`;
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>';
@@ -1478,21 +1478,36 @@
});
// 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 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);}
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,'Your model service, the accounts it uses and their priority, and the keys agents use to reach it.'); }
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 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.
@@ -1508,12 +1523,23 @@
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 setup</a></section>'};
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();}});
@@ -1739,7 +1765,7 @@
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-proxy">Model setup</a>${triageOwner ? ', <a href="#/settings/triage">Triage</a>' : ''} and <a href="#/settings/console">Console</a>.</p></section>`);
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>`);
}
@@ -1881,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;
@@ -1897,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`.
@@ -1979,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; }
@@ -1987,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; }
}
@@ -2013,7 +2041,7 @@
if (path.startsWith('/docs/')) paintDoc();
if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]'));
if ($('bus-view').querySelector('[data-org-down]')) { const down = $('bus-down'); if (down) down.hidden = true; }
if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount();
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');
File diff suppressed because it is too large. Load diff
+46 -4
View File
@@ -291,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}
@@ -309,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}
@@ -356,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}
@@ -372,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%; }
+47 -4
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
@@ -55,7 +57,7 @@
+ (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" data-status="${esc(status ?? 'unknown')}">No organization can show your models right now, so no route can be saved. <a href="#/settings/model-proxy">Open Model setup</a> to see why each organization can't see your models.</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>`
@@ -68,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. Triage also needs its key.')}</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(); };
@@ -93,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 ${savedAt(a.route.updatedAt)}.`;
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;
@@ -127,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 setup', 'Your model service and its accounts', '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;
}
+74 -1
View File
@@ -91,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({
@@ -323,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
@@ -355,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 });
@@ -765,6 +781,49 @@ 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, harnessFiles } = writeBundle(admitted, mod);
@@ -837,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); });
@@ -857,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,
@@ -908,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(),
};
@@ -935,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; });
@@ -952,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 {}
+79 -2
View File
@@ -19,8 +19,12 @@ 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.';
@@ -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);
};
+2 -2
View File
@@ -1,7 +1,7 @@
// #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
@@ -32,7 +32,7 @@ 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_KEY_NAMES, ROUTE_REFUSALS, refusedHarnessName } from "./triage-host.mjs";
import { checkedTransport } from "../../harness/src/bundle.mjs";
@@ -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');
@@ -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);
+172 -2
View File
@@ -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 });
@@ -245,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);
});
+8 -5
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,7 +79,7 @@ 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);
});
@@ -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);
});
@@ -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 Set up the model service")');
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,23 +116,23 @@ 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 service 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"');
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\./);
@@ -138,37 +143,39 @@ test('a fence with no readable time names the --proxy-restarted path instead of
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.
@@ -208,7 +215,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===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: 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 Routing page.',
'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 model service\'s receipts could not be read. A damaged line in the receipts must be repaired by hand before Ride all adds again.']);
@@ -234,7 +241,7 @@ test('settings-s1 B2: once the service runs, the organizations that cannot see 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-proxy');
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])'),
@@ -242,7 +249,7 @@ test('settings-s1 B2: once the service runs, the organizations that cannot see t
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("#proxy-setup-next").textContent'), /^Next: restart acme\. It has a Restart button under Organizations that can't use your models yet\./);
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)] })}`);
@@ -253,7 +260,7 @@ test('settings-s1 B2: once the service runs, the organizations that cannot see t
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("#proxy-setup-next").textContent'), /^The model service is set up\. Some organizations still can't see your models\./);
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'), []);
});
@@ -265,7 +272,7 @@ test('settings-s1 B2: Restart shows only where the organization\'s own cause all
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-proxy');
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 });
@@ -274,14 +281,14 @@ test('settings-s1 B2: Restart shows only where the organization\'s own cause all
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 Routing", restart: null, link: '#/orgs/odd/settings/routing', detail: null });
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("#proxy-setup-next").textContent'), /^Next: restart acme and lock\./);
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("#proxy-setup-next").textContent)');
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');
});
@@ -290,7 +297,7 @@ test('settings-s1 B2: a refused restart keeps its reason on the list across the
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-proxy');
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")');
@@ -302,9 +309,10 @@ test('settings-s1 B2: a refused restart keeps its reason on the list across the
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-proxy');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="accounts"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Add an account');
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()');
@@ -312,15 +320,14 @@ test('settings-s1 B3: a sign-in reads the whole status again and the next step f
// 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("#proxy-setup-next [data-next]")?.dataset.next==="restart-orgs"');
assert.match(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), /^Next: restart acme\./);
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("#proxy-setup-go")?.dataset.next==="triage-route"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Open Triage settings');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").disabled'), false);
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'), []);
});
@@ -330,10 +337,10 @@ test('settings-s1 B3 with ride-default: Ride all follows accounts while an organ
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-proxy');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="ride-all"');
// settings-p3 (rebase re-check P3-3): the step button is not a second "Ride all"; it goes to the box's own button.
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-go").textContent'), 'Go to Ride all');
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);
@@ -341,7 +348,7 @@ test('settings-s1 B3 with ride-default: Ride all follows accounts while an organ
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("#proxy-setup-go")?.dataset.next==="triage-route"');
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'), []);
});
@@ -350,8 +357,8 @@ test('settings-s1 B3 with ride-default: Ride all follows accounts while an organ
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-proxy');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="triage-route"');
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'), []);
});
@@ -361,14 +368,14 @@ test('settings-p3: Ride all is not the next step when the owner cannot send', {
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-proxy');
await wait('document.querySelector("#proxy-setup-next [data-next]")?.dataset.next==="done"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next").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 h3").textContent'), 'Use your models in every organization');
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("#proxy-setup-next").textContent==="The model service is set up and every organization can see your models."');
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'), []);
});
@@ -377,9 +384,9 @@ test('settings-p3: the done line does not say every organization while the Ride
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-proxy');
await wait('document.querySelector("#proxy-setup-next [data-next]")?.dataset.next==="done"');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-next").textContent'), 'The model service is set up. Some organizations still need a step under Use your models in every organization.');
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'), []);
});
@@ -389,7 +396,7 @@ test('settings-p3: the done line does not say every organization while one can s
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-proxy');
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."]);
@@ -403,11 +410,11 @@ test('settings-p3: a stand-in organization with no bus status is not offered a M
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-proxy');
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("#proxy-setup-next").textContent'), /^Next: restart late\./);
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(STEP3)}).textContent`), /^Next: restart late\./);
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
@@ -416,7 +423,7 @@ test('settings-p3: an organization whose agents start on the models only after a
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-proxy');
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)), {
@@ -434,12 +441,13 @@ test('settings-p3: the init lock and partial init steps say what to do, with the
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-proxy');
await wait('document.querySelector("#proxy-setup-go")?.dataset.next==="accounts"');
assert.deepEqual(await b.evaluate(`${visible('#proxy-setup button')}.map(e=>e.id||e.textContent)`), ['proxy-setup-go'], 'one visible button in the setup panel');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-init-box").checkVisibility()'), false, 'init is done, so its form is gone');
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', open: false, terms: ['Release', 'Initialized', 'Service', 'Fence', 'Init lock'], units: 4, receipts: true });
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()');
@@ -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);
});
@@ -14,7 +14,7 @@ async function page(t,section,width=1440,options={}) {
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));
@@ -170,7 +170,7 @@ test('settings-s1 B1: a model-key-collision catalogue says two models share a na
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-proxy\']")?.textContent'), 'Open Model setup');
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 => {
@@ -180,7 +180,7 @@ test('settings-s1 B1: a set fence reads as a restart to finish, not as a stopped
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-proxy');
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();
}
@@ -192,8 +192,8 @@ test('settings-s1 B1: a set fence reads as a restart to finish, not as a stopped
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-proxy'],
[SERVICE.stopped, /The model service is not running\. Open Model setup\./, '#/settings/model-proxy'],
[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")');
@@ -235,9 +235,9 @@ test('settings-s1 B6: a stopped organization keeps its refused restart on screen
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-proxy'], ['Triage', '#/settings/triage'], ['Console', '#/settings/console']]);
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-proxy\']").click(); true');
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');
});
@@ -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})`); }
}
});
@@ -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/);
+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');
});
@@ -487,7 +487,7 @@ test('settings-s1 B5: route refusals read as plain lines with the fix link; the
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-proxy'],
['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],
];
+83 -1
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";
@@ -1336,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/);
});
@@ -222,7 +222,7 @@ test('a catalogue that is not ready says so and offers no model', { timeout: 900
await wait('document.getElementById("triage-route-catalogue")');
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-proxy');
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]]);
});
+3 -3
View File
@@ -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));
@@ -916,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.
@@ -59,7 +59,7 @@ const refusingAdmin = () => createOrgAdmin({ service: {}, context: async () => (
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');