Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d531d7181d | ||
|
|
67e1ff193d | ||
|
|
9a3004cba4 | ||
|
|
4b833d23e9 | ||
|
|
05be6c62bd |
No files matched your search
@@ -1452,3 +1452,73 @@ the model key against a catalogue yet.
|
||||
|
||||
The Console does not read this file: the Triage host keeps `route: null` until
|
||||
the wiring slice.
|
||||
|
||||
## Triage key (#1873)
|
||||
|
||||
`mosaic triage key issue|rotate|retire|status` manage Triage's own model
|
||||
proxy client key. Every verb refuses inside an agent run before anything is
|
||||
read (exit 3), and takes no options.
|
||||
|
||||
The key is `mst-<tag>-triage-<43 base64url>`, where `<tag>` is the first 12
|
||||
hex of sha256 of the config directory, the tag on the instance's own `msk-`
|
||||
sentinel. An org bus reconciles only its `mso-<tag>-<org>-key-` names and a
|
||||
no-org bus only its `msk-<tag>-` names, so neither removes it. The file is
|
||||
`<configDir>/secrets/triage/model`: `{version, key, keyId, issuedAt,
|
||||
rotateBy, retiring}`. The directory is 0700 and the file 0600, owned by the
|
||||
running user. A link, a non-file, a second hard link, a wrong mode or owner, a
|
||||
file over 64 KiB, or a record that does not match the shape refuses every verb
|
||||
with `triage-key-unreadable` (exit 3).
|
||||
|
||||
- `issue` adds one key and writes the file. It refuses `triage-key-issued`
|
||||
when a key is already issued; that is `rotate`.
|
||||
- `rotate` adds a new key and moves the old one to `retiring`, with a retire
|
||||
time of now plus `rotateGraceMinutes` from proxy.json, where the bus reads
|
||||
it (default 120). `rotateBy` is 30 days on, as for an org key. An old key
|
||||
the proxy no longer holds is dropped at once.
|
||||
- `retire` removes retiring keys whose grace has passed or that the proxy no
|
||||
longer holds. It changes nothing before then.
|
||||
|
||||
Nothing runs on a timer. The retire time is the earliest a retiring key may
|
||||
go; the key stays live in the proxy until someone runs `retire` (or a later
|
||||
`rotate` or `issue`) after it. `rotateBy` works the same way: `status` marks
|
||||
it due, and only `rotate` replaces the key.
|
||||
- `status` prints whether a key is issued, its key id, its age, its rotate-by
|
||||
day, each retiring key, what the proxy list holds, a set fence, any key in
|
||||
the Triage namespace the file does not hold, and the next command. It takes
|
||||
no lock and writes nothing.
|
||||
|
||||
`issue`, `rotate` and `retire` hold the instance proxy lock that org buses
|
||||
take (`<dataRoot>/proxy`). Each reads the list, refuses without this
|
||||
instance's sentinel (`triage-key-proxy-open`), reads it again and refuses if
|
||||
it moved (`triage-key-raced`), sets the fence, writes, reads back and clears
|
||||
the fence. The proxy changes first and the file second. Each run that
|
||||
changes something appends one line of key ids, never keys, to
|
||||
`<dataRoot>/proxy/mosaic-keys.receipts.jsonl`. That file is checked under the
|
||||
lock before anything changes; an unsafe one refuses
|
||||
`triage-key-receipts-unsafe`. A receipt line that still fails after the change
|
||||
refuses `triage-key-unrecorded`. No output, error or receipt holds a key.
|
||||
|
||||
The file is written to a 0600 temp file in the same directory, synced, renamed
|
||||
into place, and the directory is synced. A failed directory sync after the
|
||||
rename refuses `triage-key-unsynced`: the file is in place but may not survive
|
||||
a power loss. `proxy-lock-busy` means another proxy writer holds the lock; if
|
||||
none is running, `mosaic proxy fence status` shows the lock state.
|
||||
|
||||
After a crash:
|
||||
|
||||
- Killed after the proxy write and before the read-back: the fence stays set
|
||||
and every proxy writer on the instance refuses `proxy-uncertain`. `status`
|
||||
shows the fence. Restart the proxy, run `mosaic proxy fence clear
|
||||
--proxy-restarted`, then run the verb again.
|
||||
- Killed after the read-back and before the file write: the proxy holds a key
|
||||
the file does not. `status` names it; the next `issue`, `rotate` or `retire`
|
||||
removes it. A file that could not be written refuses
|
||||
`triage-key-unwritten` and says to run the verb again.
|
||||
- Killed after the temp file is written and before its rename: a
|
||||
`.model.<pid>.<hex>.tmp` file that may hold a key stays in the triage
|
||||
directory. `status` counts it; the next `issue`, `rotate` or `retire`
|
||||
removes it under the lock.
|
||||
- A `retire` killed after the proxy write leaves a retiring key the proxy no
|
||||
longer holds. `status` marks it; the next `retire` drops it from the file.
|
||||
|
||||
Nothing gives the key to the Triage host yet; that is the wiring slice.
|
||||
@@ -0,0 +1,392 @@
|
||||
// #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).
|
||||
//
|
||||
// <configDir>/secrets/triage/model (directory 0700, file 0600, the running user's)
|
||||
// { version, key, keyId, issuedAt, rotateBy, retiring: [{ key, keyId, issuedAt, retireAt }] }
|
||||
//
|
||||
// The key is `mst-<instance tag>-triage-<43 base64url>`, where the tag is the first 12 hex of
|
||||
// sha256(configDir), the tag the instance's own `msk-` sentinel carries. An org bus reconciles only
|
||||
// its own `mso-<tag>-<org>-key-` names and a no-org bus only `msk-<tag>-`, so neither touches it.
|
||||
//
|
||||
// Every proxy write runs under the instance proxy lock (packages/bus/src/proxy-lock.mjs), the lock
|
||||
// org buses take: read the list, check this instance's sentinel, fence, PUT, read back, confirm.
|
||||
// The proxy changes first and the file second, as the bus does for an agent key. A crash between
|
||||
// leaves a key in the Triage namespace that the file does not hold; the next issue, rotate or retire
|
||||
// removes it, and status names it. A crash after the PUT and before the read-back leaves the lock's
|
||||
// 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.
|
||||
//
|
||||
// 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.
|
||||
// Nothing wires the key into the Triage host or the Console; that is a later slice.
|
||||
import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { createProxyLock } from "../../bus/src/proxy-lock.mjs";
|
||||
import { loadManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
|
||||
export const KEY_VERSION = 1;
|
||||
// The org key lifetime and the rotate grace default. The bus holds both as literals
|
||||
// (packages/bus/src/model-keys.mjs #issue: 30 days to rotateBy; packages/bus/src/runtime.mjs:
|
||||
// `proxy.rotateGraceMinutes ?? 120`) and exports neither, and this lane may not change the bus.
|
||||
// packages/cli/tests/triage-key.test.mjs drives the bus's own ModelKeys with the same clock and
|
||||
// proves these give the same rotateBy and retireAt, so a change on either side goes red there.
|
||||
// The grace itself is read from proxy.json first, where the bus reads it.
|
||||
export const KEY_LIFETIME_DAYS = 30;
|
||||
export const DEFAULT_ROTATE_GRACE_MINUTES = 120;
|
||||
const FIELDS = Object.freeze(["version", "key", "keyId", "issuedAt", "rotateBy", "retiring"]);
|
||||
const RETIRING_FIELDS = Object.freeze(["key", "keyId", "issuedAt", "retireAt"]);
|
||||
const MAX_BYTES = 64 * 1024;
|
||||
const MAX_RETIRING = 16;
|
||||
const SECRET = /^[A-Za-z0-9_-]{43}$/;
|
||||
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export class TriageKeyError extends Error {
|
||||
constructor(code, message, exitCode = 3) {
|
||||
super(message);
|
||||
this.name = "TriageKeyError";
|
||||
this.code = code;
|
||||
this.exitCode = exitCode;
|
||||
}
|
||||
}
|
||||
const unreadable = (why) => new TriageKeyError("triage-key-unreadable", `the Triage key store is unreadable: ${why}`);
|
||||
|
||||
export const keyIdOf = (key) => createHash("sha256").update(key).digest("hex").slice(0, 12);
|
||||
export const instanceTag = (configDir) => createHash("sha256").update(configDir).digest("hex").slice(0, 12);
|
||||
export const keyPrefix = (configDir) => `mst-${instanceTag(configDir)}-triage-`;
|
||||
const sentinelPrefix = (configDir) => `msk-${instanceTag(configDir)}-sentinel-`;
|
||||
const ownKey = (configDir) => (k) => typeof k === "string" && k.startsWith(keyPrefix(configDir)) && SECRET.test(k.slice(keyPrefix(configDir).length));
|
||||
// Any name under the prefix is Triage's to remove, well formed or not, as the bus treats its own
|
||||
// `msk-<tag>-` names. Only a well-formed key may be stored in the file.
|
||||
const inNamespace = (configDir) => (k) => typeof k === "string" && k.startsWith(keyPrefix(configDir));
|
||||
|
||||
export function keyPaths(configDir) {
|
||||
const secrets = join(configDir, "secrets");
|
||||
const dir = join(secrets, "triage");
|
||||
return { secrets, dir, file: join(dir, "model") };
|
||||
}
|
||||
|
||||
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
|
||||
const exactKeys = (v, keys) => plain(v) && Object.keys(v).length === keys.length && keys.every((k) => Object.hasOwn(v, k));
|
||||
const canonicalTime = (s) => typeof s === "string" && ISO.test(s) && !Number.isNaN(Date.parse(s)) && new Date(s).toISOString() === s;
|
||||
const canonicalDay = (s) => typeof s === "string" && DAY.test(s) && !Number.isNaN(Date.parse(`${s}T00:00:00Z`)) && new Date(`${s}T00:00:00Z`).toISOString().slice(0, 10) === s;
|
||||
|
||||
export function validRecord(doc, configDir) {
|
||||
const own = ownKey(configDir);
|
||||
return exactKeys(doc, FIELDS)
|
||||
&& doc.version === KEY_VERSION
|
||||
&& own(doc.key) && doc.keyId === keyIdOf(doc.key)
|
||||
&& canonicalTime(doc.issuedAt) && canonicalDay(doc.rotateBy)
|
||||
&& Array.isArray(doc.retiring) && doc.retiring.length <= MAX_RETIRING
|
||||
&& doc.retiring.every((r) => exactKeys(r, RETIRING_FIELDS) && own(r.key) && r.key !== doc.key && r.keyId === keyIdOf(r.key)
|
||||
&& canonicalTime(r.issuedAt) && canonicalTime(r.retireAt))
|
||||
&& new Set(doc.retiring.map((r) => r.key)).size === doc.retiring.length;
|
||||
}
|
||||
|
||||
const uidOf = (opts) => opts.uid ?? process.getuid();
|
||||
|
||||
// A real directory, the running user's, mode 0700. Missing: false, or made when `create` is on.
|
||||
function checkDir(dir, uid, what, { create }) {
|
||||
let st;
|
||||
try { st = lstatSync(dir); }
|
||||
catch (e) {
|
||||
if (e.code !== "ENOENT") throw unreadable(`${what} cannot be read`);
|
||||
if (!create) return false;
|
||||
try { mkdirSync(dir, { mode: 0o700 }); } catch { throw unreadable(`${what} cannot be made`); }
|
||||
try {
|
||||
const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
try { fchmodSync(fd, 0o700); } finally { closeSync(fd); }
|
||||
} catch { throw unreadable(`${what} cannot be made`); }
|
||||
st = lstatSync(dir);
|
||||
}
|
||||
if (st.isSymbolicLink()) throw unreadable(`${what} is a link`);
|
||||
if (!st.isDirectory()) throw unreadable(`${what} is not a directory`);
|
||||
if (st.uid !== uid) throw unreadable(`${what} is not owned by this user`);
|
||||
if ((st.mode & 0o777) !== 0o700) throw unreadable(`${what} mode is not 0700`);
|
||||
return true;
|
||||
}
|
||||
|
||||
function checkFile(fd, uid, what, fail = unreadable) {
|
||||
const st = fstatSync(fd);
|
||||
if (!st.isFile()) throw fail(`${what} is not a regular file`);
|
||||
if (st.nlink !== 1) throw fail(`${what} has more than one link`);
|
||||
if (st.uid !== uid) throw fail(`${what} is not owned by this user`);
|
||||
if ((st.mode & 0o777) !== 0o600) throw fail(`${what} mode is not 0600`);
|
||||
return st;
|
||||
}
|
||||
|
||||
// The stored record, or null when no key is issued. Throws triage-key-unreadable on anything unsafe.
|
||||
// opts.uid (both directories and the file) and opts.fileUid (the file only) are test seams for the
|
||||
// owner checks.
|
||||
export function readKey(configDir, opts = {}) {
|
||||
const { secrets, dir, file } = keyPaths(configDir);
|
||||
const uid = uidOf(opts);
|
||||
if (!checkDir(secrets, uid, "the secrets directory", { create: false })) return null;
|
||||
if (!checkDir(dir, uid, "the triage secrets directory", { create: false })) return null;
|
||||
let fd;
|
||||
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
||||
catch (e) {
|
||||
if (e.code === "ENOENT") return null;
|
||||
if (e.code === "ELOOP") throw unreadable("the key file is a link");
|
||||
throw unreadable("the key file cannot be opened");
|
||||
}
|
||||
try {
|
||||
const st = checkFile(fd, opts.fileUid ?? uid, "the key file");
|
||||
if (st.size > MAX_BYTES) throw unreadable("the key file is too large");
|
||||
let doc;
|
||||
try { doc = JSON.parse(readFileSync(fd, "utf8")); } catch { throw unreadable("the key file is not JSON"); }
|
||||
if (!validRecord(doc, configDir)) throw unreadable("the key file does not match the key shape");
|
||||
return doc;
|
||||
} finally { closeSync(fd); }
|
||||
}
|
||||
|
||||
// Both directories, checked (and the triage one made) before any proxy write, so a store that cannot
|
||||
// be written refuses while the proxy is still untouched.
|
||||
function prepareDirs(configDir, uid) {
|
||||
const { secrets, dir } = keyPaths(configDir);
|
||||
if (!checkDir(secrets, uid, "the secrets directory", { create: false })) throw unreadable("the secrets directory is missing");
|
||||
checkDir(dir, uid, "the triage secrets directory", { create: true });
|
||||
}
|
||||
|
||||
// A temp file writeKey left when it was killed before its rename. It may hold a key.
|
||||
const TEMP = /^\.model\.\d+\.[0-9a-f]{12}\.tmp$/;
|
||||
const tempsIn = (dir) => { try { return readdirSync(dir).filter((n) => TEMP.test(n)); } catch { return []; } };
|
||||
// Under the lock no other Triage writer runs, so every temp file left in the directory is dead.
|
||||
function removeTemps(configDir) {
|
||||
const { dir } = keyPaths(configDir);
|
||||
for (const name of tempsIn(dir)) {
|
||||
try { if (!lstatSync(join(dir, name)).isDirectory()) unlinkSync(join(dir, name)); }
|
||||
catch { throw unreadable("a leftover temp file in the triage secrets directory cannot be removed"); }
|
||||
}
|
||||
}
|
||||
|
||||
// A directory sync that failed after the rename: the file is in place but may not be durable.
|
||||
class NotSynced extends Error {}
|
||||
|
||||
// Atomic: a 0600 temp file in the same directory, fsync, rename, fsync of the directory.
|
||||
function writeKey(configDir, record, uid, hook = () => {}) {
|
||||
const { dir, file } = keyPaths(configDir);
|
||||
prepareDirs(configDir, uid);
|
||||
const temp = join(dir, `.model.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
||||
let fd;
|
||||
try { fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
||||
catch { throw unreadable("the key file cannot be written"); }
|
||||
try {
|
||||
try { fchmodSync(fd, 0o600); writeSync(fd, `${JSON.stringify(record, null, 2)}\n`); fsyncSync(fd); }
|
||||
finally { closeSync(fd); }
|
||||
hook("rename");
|
||||
renameSync(temp, file);
|
||||
} catch { try { unlinkSync(temp); } catch {} throw unreadable("the key file cannot be written"); }
|
||||
try {
|
||||
hook("sync");
|
||||
const dfd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try { fsyncSync(dfd); } finally { closeSync(dfd); }
|
||||
} catch { throw new NotSynced(); }
|
||||
}
|
||||
|
||||
// One line per write in the proxy lock's receipts file, ids only. `receiptsReady` runs under the
|
||||
// lock before any change, so an unsafe receipts file refuses while nothing has changed yet.
|
||||
const RECEIPTS_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK;
|
||||
const receiptsUnsafe = (why) => new TriageKeyError("triage-key-receipts-unsafe", `${why}; nothing was changed`);
|
||||
function receiptsReady(stateDir, uid) {
|
||||
let fd;
|
||||
try { fd = openSync(join(stateDir, "mosaic-keys.receipts.jsonl"), RECEIPTS_FLAGS, 0o600); }
|
||||
catch { throw receiptsUnsafe("the proxy receipts file cannot be opened"); }
|
||||
try { checkFile(fd, uid, "the proxy receipts file", receiptsUnsafe); } finally { closeSync(fd); }
|
||||
}
|
||||
function receipt(stateDir, uid, entry) {
|
||||
const unrecorded = new TriageKeyError("triage-key-unrecorded", "the change was made but its receipt line was not written; run mosaic triage key status");
|
||||
let fd;
|
||||
try { fd = openSync(join(stateDir, "mosaic-keys.receipts.jsonl"), RECEIPTS_FLAGS, 0o600); } catch { throw unrecorded; }
|
||||
try {
|
||||
checkFile(fd, uid, "the proxy receipts file", () => unrecorded);
|
||||
writeSync(fd, `${JSON.stringify(entry)}\n`);
|
||||
fsyncSync(fd);
|
||||
} catch { throw unrecorded; }
|
||||
finally { closeSync(fd); }
|
||||
}
|
||||
|
||||
// The grace the bus uses: proxy.json's rotateGraceMinutes, or the bus default.
|
||||
export const graceMinutes = (proxy) => proxy?.rotateGraceMinutes ?? DEFAULT_ROTATE_GRACE_MINUTES;
|
||||
export const rotateByFor = (nowMs) => new Date(nowMs + KEY_LIFETIME_DAYS * 86400_000).toISOString().slice(0, 10);
|
||||
export const retireAtFor = (nowMs, proxy) => new Date(nowMs + graceMinutes(proxy) * 60_000).toISOString();
|
||||
|
||||
const proxyFailure = (code) => {
|
||||
const words = {
|
||||
"proxy-lock-busy": "another proxy writer holds the instance proxy lock; try again when it ends, and if no writer is running, see mosaic proxy fence status",
|
||||
"proxy-lock-uncertain": "the instance proxy lock is in a state this verb will not guess about; check <dataRoot>/proxy by hand",
|
||||
"proxy-lock-invalid": "the instance proxy lock directory is missing or unsafe, or names another proxy",
|
||||
"proxy-uncertain": "an earlier proxy write has an uncertain outcome; see mosaic proxy fence status",
|
||||
"proxy-management-key-invalid": "the proxy management key file is missing or unsafe",
|
||||
"proxy-client-invalid": "the proxy settings are not usable",
|
||||
"proxy-client-down": "the proxy did not answer",
|
||||
"proxy-client-refused": "the proxy refused the management request",
|
||||
"proxy-client-redirect": "the proxy answered with a redirect",
|
||||
"proxy-client-response": "the proxy gave an answer this verb cannot use",
|
||||
};
|
||||
return new TriageKeyError(code, words[code] ?? "the proxy write failed");
|
||||
};
|
||||
|
||||
// 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 }) {
|
||||
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 ?? (() => {}),
|
||||
};
|
||||
}
|
||||
|
||||
function lockFor(c) {
|
||||
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) {
|
||||
try { return await loadManagementClient({ configDir: c.configDir, proxy: c.proxy }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-management-key-invalid"); }
|
||||
}
|
||||
|
||||
function checkSentinel(c, keys) {
|
||||
const prefix = sentinelPrefix(c.configDir);
|
||||
if (!keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length)))) {
|
||||
throw new TriageKeyError("triage-key-proxy-open", "the proxy's key list has no sentinel for this instance, so it may be another proxy");
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const lock = lockFor(c);
|
||||
const client = await clientFor(c);
|
||||
try {
|
||||
return await lock.run(async () => {
|
||||
const before = await client.getKeys();
|
||||
checkSentinel(c, before);
|
||||
const current = readKey(c.configDir, { uid: c.uid, fileUid: c.fileUid });
|
||||
const result = plan(before, current);
|
||||
if (result.record) prepareDirs(c.configDir, c.uid);
|
||||
removeTemps(c.configDir);
|
||||
receiptsReady(c.stateDir, c.uid);
|
||||
const after = result.after;
|
||||
const removed = before.filter((k) => !after.includes(k));
|
||||
const added = after.filter((k) => !before.includes(k));
|
||||
// A key in another namespace never leaves the list.
|
||||
if (removed.some((k) => !inNamespace(c.configDir)(k))) throw new TriageKeyError("triage-key-failed", "the change would remove a key outside the Triage namespace");
|
||||
if (added.length || removed.length) {
|
||||
// As the bus does: a list that moved since the first read is not overwritten.
|
||||
if (!isDeepStrictEqual(await client.getKeys(), before)) throw new TriageKeyError("triage-key-raced", "the proxy's key list changed while this verb ran; run it again");
|
||||
lock.fence({ org: null, op: `triage.${op}` });
|
||||
await client.putKeys(after);
|
||||
c.hook("put");
|
||||
const confirmed = await client.getKeys();
|
||||
if (!confirmed.some((k) => k.startsWith(sentinelPrefix(c.configDir))) || added.some((k) => !confirmed.includes(k)) || removed.some((k) => confirmed.includes(k))) {
|
||||
throw new TriageKeyError("triage-key-unconfirmed", "the proxy did not confirm the change; the instance proxy fence stays set, see mosaic proxy fence status");
|
||||
}
|
||||
lock.confirm();
|
||||
}
|
||||
c.hook("write");
|
||||
let unsynced = false;
|
||||
if (result.record) {
|
||||
try { 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`);
|
||||
}
|
||||
}
|
||||
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) });
|
||||
// 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) };
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof TriageKeyError) throw e;
|
||||
throw proxyFailure(typeof e?.code === "string" && /^proxy-[a-z-]+$/.test(e.code) ? e.code : "triage-key-failed");
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// file write, or by a file that was removed by hand.
|
||||
const orphansOf = (configDir, keys, record) => {
|
||||
const held = record ? [record.key, ...record.retiring.map((r) => r.key)] : [];
|
||||
return keys.filter((k) => inNamespace(configDir)(k) && !held.includes(k));
|
||||
};
|
||||
|
||||
export async function issueKey(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "issue", (before, current) => {
|
||||
if (current) throw new TriageKeyError("triage-key-issued", "a Triage key is already issued; use mosaic triage key rotate");
|
||||
const orphans = orphansOf(c.configDir, before, null);
|
||||
const key = newKey(c.configDir), nowMs = c.now();
|
||||
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring: [] };
|
||||
return { after: [...before.filter((k) => !orphans.includes(k)), key], record, done: { keyId: record.keyId, rotateBy: record.rotateBy } };
|
||||
});
|
||||
}
|
||||
|
||||
// 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));
|
||||
|
||||
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 } },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function retireKeys(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "retire", (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) } };
|
||||
});
|
||||
}
|
||||
|
||||
// Read only: the file, and when the proxy is set up, what its list holds. No lock, no write.
|
||||
// The fence is checked by name only, so status writes nothing, not even the lock's identity file.
|
||||
export async function keyStatus(opts) {
|
||||
const { configDir, system, uid, fileUid } = opts;
|
||||
const record = readKey(configDir, { uid, fileUid });
|
||||
const proxy = { state: "not-set-up", fence: false, leftoverTemps: tempsIn(keyPaths(configDir).dir).length };
|
||||
if (system?.proxy && Number.isInteger(system.proxy.port)) {
|
||||
try { lstatSync(join(system.dataRoot, "proxy", "mosaic-keys.uncertain")); proxy.fence = true; }
|
||||
catch (e) { if (e.code !== "ENOENT") proxy.fence = true; }
|
||||
try {
|
||||
const client = await loadManagementClient({ configDir, proxy: system.proxy });
|
||||
const keys = await client.getKeys();
|
||||
const prefix = sentinelPrefix(configDir);
|
||||
proxy.state = keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length))) ? "read" : "no-sentinel";
|
||||
proxy.holdsKey = record ? keys.includes(record.key) : null;
|
||||
proxy.retiringHeld = record ? record.retiring.map((r) => keys.includes(r.key)) : [];
|
||||
proxy.orphanKeyIds = orphansOf(configDir, keys, record).map(keyIdOf);
|
||||
} catch (e) { proxy.state = "unreadable"; proxy.code = typeof e?.code === "string" && /^proxy-[a-z-]+$/.test(e.code) ? e.code : "proxy-client-response"; }
|
||||
}
|
||||
return { record, proxy };
|
||||
}
|
||||
@@ -13,15 +13,23 @@
|
||||
// Nothing here wires the route into the Triage host: the Console keeps `route: null` until the
|
||||
// wiring slice. `set` checks the harness against the repository's harness modules; it does not
|
||||
// check the model key against a catalogue, since none exists outside an organization's bus yet.
|
||||
//
|
||||
// mosaic triage key issue | rotate | retire | status
|
||||
//
|
||||
// Triage's own model proxy client key (packages/cli/src/triage-key.mjs). 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";
|
||||
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 { CliError } from "./errors.mjs";
|
||||
import { refuseInsideAgent } from "./transport.mjs";
|
||||
|
||||
export const TRIAGE_USAGE = "mosaic triage route show | set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N]";
|
||||
export const TRIAGE_USAGE = "mosaic triage route show | set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N] | key issue | rotate | retire | status";
|
||||
const KEY_VERBS = ["issue", "rotate", "retire", "status"];
|
||||
const HARNESS_ROOT = fileURLToPath(new URL("../../plugins/harness/", import.meta.url));
|
||||
const VALUES = ["--model", "--harness", "--cap", "--time-zone", "--revision"];
|
||||
const WHOLE = /^(0|[1-9][0-9]*)$/;
|
||||
@@ -73,10 +81,89 @@ function show(route) {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// A key error prints its code and fixed words. Anything else becomes one fixed line, so no value
|
||||
// that an unexpected error might carry reaches the terminal.
|
||||
function keyError(error) {
|
||||
if (error instanceof CliError) return error;
|
||||
if (error instanceof TriageKeyError) return new CliError(`${error.code}: ${error.message}`, error.exitCode);
|
||||
return new CliError("triage-key-failed: the key verb stopped on an unexpected error; run mosaic triage key status", 3);
|
||||
}
|
||||
|
||||
const age = (ms) => {
|
||||
const m = Math.max(0, Math.floor(ms / 60_000));
|
||||
return `${Math.floor(m / 1440)}d ${Math.floor((m % 1440) / 60)}h ${m % 60}m`;
|
||||
};
|
||||
const ids = (list) => (list.length ? list.join(", ") : "none");
|
||||
|
||||
function statusText({ record, proxy }, nowMs, file) {
|
||||
const lines = [`triage key: ${record ? "issued" : "not issued"}`, `file: ${file}`];
|
||||
const rotateDue = record && Date.parse(`${record.rotateBy}T00:00:00Z`) <= nowMs;
|
||||
const retireDue = record ? record.retiring.filter((r) => Date.parse(r.retireAt) <= nowMs) : [];
|
||||
if (record) {
|
||||
lines.push(`key id: ${record.keyId}`, `issued: ${record.issuedAt} (age ${age(nowMs - Date.parse(record.issuedAt))})`, `rotate by: ${record.rotateBy}${rotateDue ? " (due)" : ""}`);
|
||||
record.retiring.forEach((r, i) => {
|
||||
const held = proxy.retiringHeld?.[i];
|
||||
lines.push(`retiring: ${r.keyId}, live until a retire after ${r.retireAt}${Date.parse(r.retireAt) <= nowMs ? " (due)" : ""}${held === false ? " (not in the proxy list)" : ""}`);
|
||||
});
|
||||
}
|
||||
const state = {
|
||||
"not-set-up": "not set up for this instance (no proxy.json)",
|
||||
"no-sentinel": "its key list has no sentinel for this instance",
|
||||
unreadable: `not read (${proxy.code})`,
|
||||
read: record ? (proxy.holdsKey ? "holds the key" : "does not hold the key") : "read",
|
||||
}[proxy.state];
|
||||
lines.push(`proxy: ${state}`);
|
||||
if (proxy.fence) lines.push("proxy fence: set, an earlier proxy write has an uncertain outcome");
|
||||
if (proxy.leftoverTemps) lines.push(`leftover temp files in the triage secrets directory: ${proxy.leftoverTemps} (the next issue, rotate or retire removes them)`);
|
||||
if (proxy.orphanKeyIds?.length) lines.push(`keys in the Triage namespace the file does not hold: ${ids(proxy.orphanKeyIds)}`);
|
||||
let next;
|
||||
if (proxy.fence) next = "restart the proxy, then mosaic proxy fence clear --proxy-restarted";
|
||||
else if (proxy.state !== "read") next = proxy.state === "not-set-up" ? "set up the model proxy first (mosaic proxy init)" : "check the proxy with mosaic proxy status";
|
||||
else if (!record) next = "mosaic triage key issue";
|
||||
else if (!proxy.holdsKey || rotateDue) next = "mosaic triage key rotate";
|
||||
else if (retireDue.length || proxy.leftoverTemps || proxy.orphanKeyIds?.length || proxy.retiringHeld?.includes(false)) next = "mosaic triage key retire";
|
||||
else next = "nothing";
|
||||
lines.push(`next: ${next}`, "");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function keyCommand(sub, args, io, deps) {
|
||||
if (!KEY_VERBS.includes(sub)) throw usage("unknown triage key command");
|
||||
if (args.length) throw usage(args[0].startsWith("--") ? "unknown option" : "unexpected argument");
|
||||
try {
|
||||
const system = deps.system ?? loadSystem({ env: io.env });
|
||||
const dir = configDir(io.env);
|
||||
const now = deps.now ? () => deps.now().getTime() : Date.now;
|
||||
const opts = { configDir: dir, system, now, uid: deps.triageKeyUid, fileUid: deps.triageKeyFileUid, hook: deps.triageKeyHook };
|
||||
if (sub === "status") {
|
||||
io.stdout.write(statusText(await keyStatus(opts), now(), keyPaths(dir).file));
|
||||
return;
|
||||
}
|
||||
if (sub === "issue") {
|
||||
const r = await issueKey(opts);
|
||||
io.stdout.write(`triage key issued: ${r.keyId}, rotate by ${r.rotateBy}\nfile: ${keyPaths(dir).file}\n`);
|
||||
if (r.removedKeyIds.length) io.stdout.write(`removed keys this file did not hold: ${ids(r.removedKeyIds)}\n`);
|
||||
return;
|
||||
}
|
||||
if (sub === "rotate") {
|
||||
const r = await rotateKey(opts);
|
||||
io.stdout.write(`triage key rotated: ${r.keyId}, rotate by ${r.rotateBy}\n`);
|
||||
io.stdout.write(r.old.lost
|
||||
? `old key ${r.old.keyId} was not in the proxy list; nothing to retire\n`
|
||||
: `old key ${r.old.keyId} stays live until mosaic triage key retire runs at or after ${r.old.retireAt}\n`);
|
||||
if (r.removedKeyIds.length) io.stdout.write(`removed: ${ids(r.removedKeyIds)}\n`);
|
||||
return;
|
||||
}
|
||||
const r = await retireKeys(opts);
|
||||
io.stdout.write(r.removedKeyIds.length ? `triage key retire: removed ${ids(r.removedKeyIds)}\n` : "triage key retire: nothing to remove\n");
|
||||
} catch (e) { throw keyError(e); }
|
||||
}
|
||||
|
||||
export function triageCommand(rest, io, deps = {}) {
|
||||
refuseInsideAgent(process.env);
|
||||
refuseInsideAgent(io.env);
|
||||
const [noun, sub, ...args] = rest;
|
||||
if (noun === "key" && sub !== undefined) return keyCommand(sub, args, io, deps);
|
||||
if (noun !== "route" || !["show", "set"].includes(sub)) throw usage("unknown triage command");
|
||||
const { values, positional } = parse(args);
|
||||
if (positional.length) throw usage("unexpected argument");
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
// #1873 triage-key: `mosaic triage key issue|rotate|retire|status`, Triage's own model proxy key.
|
||||
// A stand-in management server on loopback and a temporary config directory only; nothing here
|
||||
// reads a real config, proxy or secret. Every stdout, stderr, receipt and file the verbs leave is
|
||||
// scanned for every key the stand-in ever saw, at the end of each test and once more at the end.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
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 { 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 { ModelKeys } from "../../bus/src/model-keys.mjs";
|
||||
import { ManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
import { startBroker } from "../../bus/src/runtime.mjs";
|
||||
import { busOrganization } from "../../bus/src/organization-context.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";
|
||||
import { humanEnv, io } from "./helpers.mjs";
|
||||
|
||||
const REPO = new URL("../../../", import.meta.url).pathname;
|
||||
const NOW = Date.parse("2026-11-18T12:00:00.000Z");
|
||||
const MIN = 60_000, HOUR = 60 * MIN, DAY = 24 * HOUR;
|
||||
const MANAGE = "fx1873-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 iso = (ms) => new Date(ms).toISOString();
|
||||
|
||||
// Every output any verb produced in this file, and every Triage key the stand-in ever held.
|
||||
const OUTPUTS = [];
|
||||
const SEEN = new Set();
|
||||
const VERBS = ["issue", "rotate", "retire", "status"];
|
||||
|
||||
function leaks(text, keys = SEEN) {
|
||||
for (const key of keys) {
|
||||
const secret = key.slice(-43);
|
||||
if (text.includes(key) || text.includes(secret)) return true;
|
||||
for (let i = 0; i + 8 <= secret.length; i++) if (text.includes(secret.slice(i, i + 8))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function walk(dir, skip, out = []) {
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const p = join(dir, name), st = fs.lstatSync(p);
|
||||
if (st.isDirectory()) walk(p, skip, out);
|
||||
else if (st.isFile() && !skip.includes(p)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function fixture(t, { sentinel = true } = {}) {
|
||||
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "tk-")));
|
||||
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 prefix = `mst-${tag(configDir)}-triage-`;
|
||||
const state = {
|
||||
keys: [...(sentinel ? [`msk-${tag(configDir)}-sentinel-${b64()}`] : []), "foreign-client-key", `mso-${tag(configDir)}-demo-key-${b64()}`],
|
||||
gets: 0, puts: [], ignorePut: false, dropSentinelOnPut: false, onGet: null,
|
||||
};
|
||||
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") { state.gets++; const body = JSON.stringify(state.keys); state.onGet?.(state.gets); res.end(body); 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 (state.dropSentinelOnPut) state.keys = next.filter((k) => !k.startsWith("msk-") || !k.includes("-sentinel-"));
|
||||
else if (!state.ignorePut) 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) await close();
|
||||
server.closeAllConnections(); await new Promise((resolve) => server.close(resolve));
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
const f = {
|
||||
root, configDir, prefix, state, server, port, closers, now: NOW,
|
||||
system: { dataRoot: root, proxy: { port, binary: "/fixture-unused" } },
|
||||
file: keyPaths(configDir).file, dir: keyPaths(configDir).dir,
|
||||
env: (extra = {}) => humanEnv({ MOSAIC_CONFIG: join(configDir, "config.json"), ...extra }),
|
||||
async cli(argv, { env, deps = {}, system = f.system } = {}) {
|
||||
const s = io(env ?? f.env());
|
||||
const code = await run(argv, s, { system, now: () => new Date(f.now), ...deps });
|
||||
const out = { code, stdout: s.out.text, stderr: s.err.text };
|
||||
OUTPUTS.push(out.stdout, out.stderr);
|
||||
return out;
|
||||
},
|
||||
// The same verb in a child process that SIGKILLs itself at `stage`.
|
||||
crash(argv, stage) {
|
||||
const script = `
|
||||
import { run } from ${JSON.stringify(new URL("../src/cli.mjs", import.meta.url).href)};
|
||||
import { io } from ${JSON.stringify(new URL("./helpers.mjs", import.meta.url).href)};
|
||||
const p = JSON.parse(process.env.TK_CRASH);
|
||||
const s = io(process.env);
|
||||
const code = await run(p.argv, s, { system: p.system, now: () => new Date(p.now),
|
||||
triageKeyHook: (stage) => { if (stage === p.stage) process.kill(process.pid, "SIGKILL"); } });
|
||||
process.stdout.write(s.out.text); process.stderr.write(s.err.text); process.exitCode = code;`;
|
||||
const env = f.env({ TK_CRASH: JSON.stringify({ argv, stage, system: f.system, now: f.now }) });
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, ["--input-type=module", "-e", script], { env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "", stderr = "";
|
||||
child.stdout.on("data", (d) => { stdout += d; });
|
||||
child.stderr.on("data", (d) => { stderr += d; });
|
||||
child.on("exit", (code, signal) => { OUTPUTS.push(stdout, stderr); resolve({ code, signal, stdout, stderr }); });
|
||||
});
|
||||
},
|
||||
record: () => JSON.parse(fs.readFileSync(f.file, "utf8")),
|
||||
triageKeys: () => state.keys.filter((k) => k.startsWith(prefix)),
|
||||
receipts: () => {
|
||||
const file = join(root, "proxy", "mosaic-keys.receipts.jsonl");
|
||||
return fs.existsSync(file) ? fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
|
||||
},
|
||||
fenced: () => fs.existsSync(join(root, "proxy", "mosaic-keys.uncertain")),
|
||||
// No file under the fixture but the key file itself holds a key; neither does any output.
|
||||
scan(alsoKeyFiles = []) {
|
||||
for (const k of state.keys) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
|
||||
for (const p of walk(root, [f.file, join(configDir, "secrets", "proxy-management.key"), ...alsoKeyFiles])) {
|
||||
assert.equal(leaks(fs.readFileSync(p, "latin1")), false, `a key is in ${p}`);
|
||||
}
|
||||
for (const text of OUTPUTS) assert.equal(leaks(text), false, "a key is in an output");
|
||||
},
|
||||
};
|
||||
return f;
|
||||
}
|
||||
|
||||
const ok = (r) => assert.equal(r.code, 0, r.stderr);
|
||||
const refusal = (r, code, words) => {
|
||||
assert.equal(r.code, 3, r.stderr);
|
||||
assert.equal(r.stdout, "");
|
||||
assert.match(r.stderr, new RegExp(`^mosaic: ${code}: ${words ?? ""}`));
|
||||
};
|
||||
|
||||
test("issue adds one key under the lock, writes the 0600 file, and records ids only", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const before = [...f.state.keys];
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
const rec = f.record();
|
||||
assert.deepEqual(Object.keys(rec), ["version", "key", "keyId", "issuedAt", "rotateBy", "retiring"]);
|
||||
assert.match(rec.key, new RegExp(`^${f.prefix}[A-Za-z0-9_-]{43}$`));
|
||||
assert.equal(rec.keyId, id(rec.key));
|
||||
assert.equal(rec.issuedAt, iso(NOW));
|
||||
assert.equal(rec.rotateBy, "2026-12-18");
|
||||
assert.deepEqual(rec.retiring, []);
|
||||
assert.equal(r.stdout, `triage key issued: ${rec.keyId}, rotate by 2026-12-18\nfile: ${f.file}\n`);
|
||||
assert.deepEqual(f.state.keys, [...before, rec.key]);
|
||||
assert.equal(f.state.puts.length, 1);
|
||||
const file = fs.lstatSync(f.file), dir = fs.lstatSync(f.dir);
|
||||
assert.equal(file.mode & 0o777, 0o600); assert.equal(dir.mode & 0o777, 0o700);
|
||||
assert.equal(file.uid, process.getuid()); assert.equal(dir.uid, process.getuid());
|
||||
assert.deepEqual(f.receipts(), [{ op: "triage.key.issue", time: iso(NOW), addedKeyIds: [rec.keyId], removedKeyIds: [] }]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.readFileSync(join(f.root, "proxy", "keys.generation"), "utf8"), "1\n");
|
||||
// A second issue refuses and changes nothing; rotate is the verb for that.
|
||||
const again = await f.cli(["triage", "key", "issue"]);
|
||||
refusal(again, "triage-key-issued", "a Triage key is already issued; use mosaic triage key rotate\n$");
|
||||
assert.equal(f.state.puts.length, 1);
|
||||
assert.deepEqual(f.record(), rec);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("status reads the file and the list and writes nothing", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const none = await f.cli(["triage", "key", "status"]);
|
||||
ok(none);
|
||||
assert.equal(none.stdout, `triage key: not issued\nfile: ${f.file}\nproxy: read\nnext: mosaic triage key issue\n`);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const rec = f.record(), puts = f.state.puts.length, receipts = f.receipts().length;
|
||||
f.now = NOW + 3 * DAY + 4 * HOUR + 5 * MIN;
|
||||
const shown = await f.cli(["triage", "key", "status"]);
|
||||
ok(shown);
|
||||
assert.equal(shown.stdout, [
|
||||
"triage key: issued", `file: ${f.file}`, `key id: ${rec.keyId}`, `issued: ${iso(NOW)} (age 3d 4h 5m)`,
|
||||
"rotate by: 2026-12-18", "proxy: holds the key", "next: nothing", "",
|
||||
].join("\n"));
|
||||
f.now = Date.parse("2026-12-18T00:00:00.000Z");
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /rotate by: 2026-12-18 \(due\)\n[^]*next: mosaic triage key rotate\n$/);
|
||||
f.now = NOW + HOUR;
|
||||
f.state.keys = f.state.keys.filter((k) => k !== rec.key);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: does not hold the key\nnext: mosaic triage key rotate\n$/);
|
||||
assert.equal(f.state.puts.length, puts);
|
||||
assert.equal(f.receipts().length, receipts);
|
||||
assert.equal(fs.readdirSync(join(f.root, "proxy")).includes("mosaic-keys.lock"), false);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("rotate adds a new key and keeps the old one for the bus grace; retire removes it once due", async (t) => {
|
||||
const f = await fixture(t);
|
||||
refusal(await f.cli(["triage", "key", "rotate"]), "triage-key-not-issued", "no Triage key is issued; use mosaic triage key issue\n$");
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
f.now = NOW + HOUR;
|
||||
const r = await f.cli(["triage", "key", "rotate"]);
|
||||
ok(r);
|
||||
const second = f.record();
|
||||
const retireAt = iso(NOW + HOUR + 120 * MIN);
|
||||
assert.notEqual(second.key, first.key);
|
||||
assert.equal(second.issuedAt, iso(NOW + HOUR));
|
||||
assert.deepEqual(second.retiring, [{ key: first.key, keyId: first.keyId, issuedAt: first.issuedAt, retireAt }]);
|
||||
assert.equal(r.stdout, `triage key rotated: ${second.keyId}, rotate by 2026-12-18\nold key ${first.keyId} stays live until mosaic triage key retire runs at or after ${retireAt}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [first.key, second.key]);
|
||||
f.now = NOW + HOUR + 119 * MIN;
|
||||
const early = await f.cli(["triage", "key", "retire"]);
|
||||
ok(early);
|
||||
assert.equal(early.stdout, "triage key retire: nothing to remove\n");
|
||||
assert.equal(f.state.puts.length, 2);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after ${retireAt}\\n[^]*next: nothing\\n$`));
|
||||
f.now = NOW + HOUR + 120 * MIN;
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after ${retireAt} \\(due\\)\\n[^]*next: mosaic triage key retire\\n$`));
|
||||
const done = await f.cli(["triage", "key", "retire"]);
|
||||
ok(done);
|
||||
assert.equal(done.stdout, `triage key retire: removed ${first.keyId}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [second.key]);
|
||||
assert.deepEqual(f.record(), { ...second, retiring: [] });
|
||||
assert.deepEqual(f.receipts().map((e) => e.op), ["triage.key.issue", "triage.key.rotate", "triage.key.retire"]);
|
||||
assert.deepEqual(f.receipts()[2].removedKeyIds, [first.keyId]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("rotate takes the grace from proxy.json, where the bus reads it, and drops an old key the proxy lost", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.system = { ...f.system, proxy: { ...f.system.proxy, rotateGraceMinutes: 30 } };
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const second = f.record();
|
||||
assert.equal(second.retiring[0].retireAt, iso(NOW + 30 * MIN));
|
||||
// The proxy lost the current key: rotate drops it at once, as the bus does for an agent key.
|
||||
f.state.keys = f.state.keys.filter((k) => k !== second.key);
|
||||
const r = await f.cli(["triage", "key", "rotate"]);
|
||||
ok(r);
|
||||
assert.match(r.stdout, new RegExp(`old key ${second.keyId} was not in the proxy list; nothing to retire\\n$`));
|
||||
assert.deepEqual(f.record().retiring.map((e) => e.keyId), [first.keyId]);
|
||||
// A retiring key past its time, or no longer in the list, leaves on the next rotate.
|
||||
f.now = NOW + 31 * MIN;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const last = f.record();
|
||||
assert.deepEqual(last.retiring.map((e) => e.keyId), [id(f.triageKeys()[0])]);
|
||||
assert.equal(f.triageKeys().includes(first.key), false);
|
||||
assert.equal(f.triageKeys().length, 2);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("lifetime and grace match the bus's own ModelKeys for the same clock and proxy settings", async (t) => {
|
||||
const runtime = fs.readFileSync(join(REPO, "packages/bus/src/runtime.mjs"), "utf8");
|
||||
const literal = runtime.match(/rotateGraceMinutes: proxy\.rotateGraceMinutes \?\? (\d+)/);
|
||||
assert.ok(literal, "the bus no longer reads rotateGraceMinutes as this test expects");
|
||||
assert.equal(Number(literal[1]), DEFAULT_ROTATE_GRACE_MINUTES);
|
||||
for (const grace of [undefined, 45]) {
|
||||
const f = await fixture(t);
|
||||
if (grace !== undefined) f.system = { ...f.system, proxy: { ...f.system.proxy, rotateGraceMinutes: grace } };
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
f.now = NOW + 3 * HOUR;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const ours = f.record();
|
||||
// The bus, driven the way runtime.mjs drives it, on its own in-memory list.
|
||||
let keys = [`msk-${tag(f.configDir)}-sentinel-${b64()}`], record = null, now = NOW;
|
||||
const credentials = { registerModel() {}, modelRecord: () => record, writeModel: (_, r) => { record = r; }, status: () => [] };
|
||||
const client = { getKeys: async () => [...keys], putKeys: async (k) => { keys = [...k]; return { ok: true }; } };
|
||||
const bus = new ModelKeys({ credentials, client, configDir: f.configDir, baseUrl: "http://127.0.0.1:1", now: () => now,
|
||||
...(grace === undefined ? {} : { rotateGraceMinutes: f.system.proxy.rotateGraceMinutes ?? Number(literal[1]) }) });
|
||||
await bus.reconcile();
|
||||
await bus.ensure("demo/x");
|
||||
assert.equal(record.rotateBy, rotateByFor(NOW));
|
||||
now = NOW + 3 * HOUR;
|
||||
await bus.rotate("demo/x");
|
||||
assert.equal(ours.rotateBy, record.rotateBy);
|
||||
assert.equal(ours.retiring[0].retireAt, record.retiring[0].retireAt);
|
||||
assert.equal(ours.retiring[0].retireAt, retireAtFor(now, f.system.proxy));
|
||||
f.scan();
|
||||
}
|
||||
});
|
||||
|
||||
test("an agent caller is refused before anything is read, for every key verb", async (t) => {
|
||||
const f = await fixture(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { env: { ...f.env(), [marker]: "1" } });
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.equal(r.stderr, `mosaic: refused: this runs only from a human shell, outside any agent run (found ${marker} in the environment)\n`);
|
||||
}
|
||||
const saved = process.env[marker];
|
||||
process.env[marker] = "1";
|
||||
try {
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb]);
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.match(r.stderr, new RegExp(`found ${marker} in the environment`));
|
||||
}
|
||||
} finally { if (saved === undefined) delete process.env[marker]; else process.env[marker] = saved; }
|
||||
}
|
||||
assert.equal(f.state.gets, 0);
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
assert.equal(fs.existsSync(f.dir), false);
|
||||
assert.deepEqual(fs.readdirSync(join(f.root, "proxy")), []);
|
||||
});
|
||||
|
||||
test("usage: unknown key verbs, options and arguments exit 4 and echo no value", async (t) => {
|
||||
const f = await fixture(t);
|
||||
for (const argv of [["triage", "key"], ["triage", "key", "nope"], ["triage", "key", "issue", "extra"], ["triage", "key", "status", "--json"]]) {
|
||||
const r = await f.cli(argv);
|
||||
assert.equal(r.code, 4, argv.join(" "));
|
||||
assert.equal(r.stdout, "");
|
||||
assert.match(r.stderr, /\nusage: mosaic triage route show [^\n]*\| key issue \| rotate \| retire \| status\n$/);
|
||||
}
|
||||
const r = await f.cli(["triage", "key", "rotate", "--key", "secret-value"]);
|
||||
assert.equal(r.code, 4);
|
||||
assert.match(r.stderr, /^mosaic: unknown option\n/);
|
||||
assert.doesNotMatch(r.stderr, /secret-value/);
|
||||
assert.equal(f.state.gets, 0);
|
||||
});
|
||||
|
||||
test("an unsafe key store refuses every verb before any proxy write", async (t) => {
|
||||
const uid = process.getuid();
|
||||
const cases = [
|
||||
["file mode", (f) => fs.chmodSync(f.file, 0o644), {}, "the key file mode is not 0600"],
|
||||
["file owner", () => {}, { triageKeyFileUid: uid + 1 }, "the key file is not owned by this user"],
|
||||
["file link", (f) => { fs.renameSync(f.file, join(f.dir, "real")); fs.symlinkSync(join(f.dir, "real"), f.file); }, {}, "the key file is a link"],
|
||||
["file is a directory", (f) => { fs.rmSync(f.file); fs.mkdirSync(f.file, { mode: 0o700 }); }, {}, "the key file is not a regular file"],
|
||||
["file is a FIFO", (f) => { fs.rmSync(f.file); assert.equal(spawnSync("mkfifo", ["-m", "600", f.file]).status, 0); }, {}, "the key file is not a regular file"],
|
||||
["hard link", (f) => fs.linkSync(f.file, join(f.dir, "second")), {}, "the key file has more than one link"],
|
||||
["not JSON", (f) => fs.writeFileSync(f.file, "{"), {}, "the key file is not JSON"],
|
||||
["extra field", (f) => fs.writeFileSync(f.file, JSON.stringify({ ...f.record(), extra: 1 })), {}, "the key file does not match the key shape"],
|
||||
["another instance's key", (f) => { const r = f.record(); const key = `mst-${tag("/elsewhere")}-triage-${b64()}`; fs.writeFileSync(f.file, JSON.stringify({ ...r, key, keyId: id(key) })); }, {}, "the key file does not match the key shape"],
|
||||
["wrong key id", (f) => fs.writeFileSync(f.file, JSON.stringify({ ...f.record(), keyId: "000000000000" })), {}, "the key file does not match the key shape"],
|
||||
["too large", (f) => fs.writeFileSync(f.file, " ".repeat(64 * 1024 + 1)), {}, "the key file is too large"],
|
||||
["triage directory mode", (f) => fs.chmodSync(f.dir, 0o755), {}, "the triage secrets directory mode is not 0700"],
|
||||
["triage directory link", (f) => { fs.renameSync(f.dir, join(f.configDir, "secrets", "moved")); fs.symlinkSync(join(f.configDir, "secrets", "moved"), f.dir); }, {}, "the triage secrets directory is a link"],
|
||||
["triage directory is a file", (f) => { fs.rmSync(f.dir, { recursive: true }); fs.writeFileSync(f.dir, "", { mode: 0o600 }); }, {}, "the triage secrets directory is not a directory"],
|
||||
["secrets mode", (f) => fs.chmodSync(join(f.configDir, "secrets"), 0o750), {}, "the secrets directory mode is not 0700"],
|
||||
["owner", () => {}, { triageKeyUid: uid + 1 }, "the secrets directory is not owned by this user"],
|
||||
];
|
||||
for (const [name, spoil, deps, words] of cases) {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
spoil(f);
|
||||
const keys = [...f.state.keys], puts = f.state.puts.length;
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { deps });
|
||||
refusal(r, "triage-key-unreadable", `the Triage key store is unreadable: ${words.replace(/[.()]/g, "\\$&")}\n$`);
|
||||
assert.equal(f.state.puts.length, puts, `${name}: ${verb}`);
|
||||
}
|
||||
assert.deepEqual(f.state.keys, keys);
|
||||
// The spoils above move or link the key file itself; those copies are the key file.
|
||||
f.scan([join(f.dir, "real"), join(f.dir, "second"), join(f.configDir, "secrets", "moved", "model")]);
|
||||
}
|
||||
// No secrets directory at all: status says not issued; issue refuses before the proxy changes.
|
||||
const f = await fixture(t);
|
||||
fs.rmSync(join(f.configDir, "secrets"), { recursive: true });
|
||||
fs.mkdirSync(join(f.configDir, "secrets"), { mode: 0o700 });
|
||||
fs.writeFileSync(join(f.configDir, "secrets", "proxy-management.key"), MANAGE, { mode: 0o600 });
|
||||
fs.chmodSync(join(f.configDir, "secrets"), 0o755);
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-unreadable", "the Triage key store is unreadable: the secrets directory mode is not 0700\n$");
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
});
|
||||
|
||||
test("the instance proxy lock, the fence, the sentinel and the proxy itself each refuse plainly", async (t) => {
|
||||
// Lock held by a live process: busy after the lock's wait, and nothing changes.
|
||||
const f = await fixture(t);
|
||||
const lockFile = join(f.root, "proxy", "mosaic-keys.lock");
|
||||
ok(await f.cli(["triage", "key", "status"]));
|
||||
fs.writeFileSync(lockFile, `${JSON.stringify({ pid: process.pid, token: "a".repeat(32) })}\n`, { mode: 0o600 });
|
||||
const busy = await f.cli(["triage", "key", "issue"]);
|
||||
refusal(busy, "proxy-lock-busy", "another proxy writer holds the instance proxy lock; try again when it ends, and if no writer is running, see mosaic proxy fence status\n$");
|
||||
assert.equal(f.state.gets, 1);
|
||||
// A lock left by a process that is gone is reaped, and the verb goes ahead.
|
||||
const dead = spawnSync(process.execPath, ["-e", ""]).pid;
|
||||
fs.writeFileSync(lockFile, `${JSON.stringify({ pid: dead, token: "b".repeat(32) })}\n`, { mode: 0o600 });
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.equal(fs.existsSync(lockFile), false);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
fs.rmSync(f.file);
|
||||
f.state.keys = f.state.keys.filter((k) => !k.startsWith(f.prefix));
|
||||
// A set fence: every write refuses, status names it and the way out.
|
||||
const putsBefore = f.state.puts.length;
|
||||
fs.writeFileSync(join(f.root, "proxy", "mosaic-keys.uncertain"), "{}\n", { mode: 0o600 });
|
||||
for (const verb of ["issue", "rotate", "retire"]) refusal(await f.cli(["triage", "key", verb]), "proxy-uncertain");
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy fence: set, an earlier proxy write has an uncertain outcome\nnext: restart the proxy, then mosaic proxy fence clear --proxy-restarted\n$/);
|
||||
assert.equal(f.state.puts.length, putsBefore);
|
||||
// No sentinel for this instance (another instance's does not count).
|
||||
const g = await fixture(t, { sentinel: false });
|
||||
g.state.keys.push(`msk-${tag("/elsewhere")}-sentinel-${b64()}`);
|
||||
refusal(await g.cli(["triage", "key", "issue"]), "triage-key-proxy-open");
|
||||
assert.match((await g.cli(["triage", "key", "status"])).stdout, /proxy: its key list has no sentinel for this instance\nnext: check the proxy with mosaic proxy status\n$/);
|
||||
assert.equal(g.state.puts.length, 0);
|
||||
// No proxy set up, no management key, proxy down.
|
||||
const h = await fixture(t);
|
||||
const bare = { dataRoot: h.root };
|
||||
refusal(await h.cli(["triage", "key", "issue"], { system: bare }), "triage-key-no-proxy");
|
||||
assert.equal((await h.cli(["triage", "key", "status"], { system: bare })).stdout,
|
||||
`triage key: not issued\nfile: ${h.file}\nproxy: not set up for this instance (no proxy.json)\nnext: set up the model proxy first (mosaic proxy init)\n`);
|
||||
fs.chmodSync(join(h.configDir, "secrets", "proxy-management.key"), 0o644);
|
||||
refusal(await h.cli(["triage", "key", "issue"]), "proxy-management-key-invalid");
|
||||
fs.chmodSync(join(h.configDir, "secrets", "proxy-management.key"), 0o600);
|
||||
h.server.closeAllConnections(); await new Promise((resolve) => h.server.close(resolve));
|
||||
h.server.close = (cb) => cb();
|
||||
refusal(await h.cli(["triage", "key", "issue"]), "proxy-client-down");
|
||||
assert.match((await h.cli(["triage", "key", "status"])).stdout, /proxy: not read \(proxy-client-down\)\n/);
|
||||
assert.equal(fs.existsSync(h.file), false);
|
||||
f.scan(); g.scan(); h.scan();
|
||||
});
|
||||
|
||||
test("a write the proxy does not confirm keeps the fence; a list that moves mid-verb is not overwritten", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.state.ignorePut = true;
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-unconfirmed");
|
||||
assert.equal(f.fenced(), true);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
// The store's directory was made and checked before the proxy changed, not after.
|
||||
assert.equal(fs.lstatSync(f.dir).mode & 0o777, 0o700);
|
||||
assert.deepEqual(f.receipts(), []);
|
||||
// A PUT the proxy takes but whose read-back has lost this instance's sentinel is not confirmed.
|
||||
const s = await fixture(t);
|
||||
s.state.dropSentinelOnPut = true;
|
||||
refusal(await s.cli(["triage", "key", "issue"]), "triage-key-unconfirmed");
|
||||
assert.equal(s.fenced(), true);
|
||||
assert.equal(fs.existsSync(s.file), false);
|
||||
s.scan();
|
||||
const g = await fixture(t);
|
||||
g.state.onGet = (n) => { if (n === 1) g.state.keys = [...g.state.keys, "late-foreign-key"]; };
|
||||
refusal(await g.cli(["triage", "key", "issue"]), "triage-key-raced");
|
||||
assert.equal(g.state.puts.length, 0);
|
||||
assert.equal(g.fenced(), false);
|
||||
f.scan(); g.scan();
|
||||
});
|
||||
|
||||
test("keys outside the Triage namespace are never touched; Triage keys the file does not hold are removed", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const agent = `msk-${tag(f.configDir)}-${b64()}`, other = `mst-${tag("/elsewhere")}-triage-${b64()}`;
|
||||
const orphan = `${f.prefix}${b64()}`, odd = `${f.prefix}short`;
|
||||
f.state.keys.push(agent, other, orphan, odd);
|
||||
const foreign = f.state.keys.filter((k) => k !== orphan && k !== odd);
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
// A malformed name under the Triage prefix is still Triage's, as the bus treats its own prefix.
|
||||
assert.match(r.stdout, new RegExp(`removed keys this file did not hold: ${id(orphan)}, ${id(odd)}\\n$`));
|
||||
for (const verb of ["rotate", "retire"]) { f.now += 3 * HOUR; ok(await f.cli(["triage", "key", verb])); }
|
||||
for (const k of foreign) assert.ok(f.state.keys.includes(k), "a key outside the namespace left the list");
|
||||
assert.equal(f.state.keys.includes(orphan), false);
|
||||
assert.equal(f.state.keys.includes(odd), false);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the PUT, before the read-back: the fence holds; status says so; clear, then issue recovers", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const crashed = await f.crash(["triage", "key", "issue"], "put");
|
||||
assert.equal(crashed.signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), true);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const status = await f.cli(["triage", "key", "status"]);
|
||||
ok(status);
|
||||
assert.match(status.stdout, new RegExp(`proxy fence: set[^\\n]*\\nkeys in the Triage namespace the file does not hold: ${id(f.triageKeys()[0])}\\nnext: restart the proxy, then mosaic proxy fence clear --proxy-restarted\\n$`));
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "proxy-uncertain");
|
||||
ok(await f.cli(["proxy", "fence", "clear", "--proxy-restarted"]));
|
||||
assert.equal(f.fenced(), false);
|
||||
const stray = f.triageKeys()[0];
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
assert.match(r.stdout, new RegExp(`removed keys this file did not hold: ${id(stray)}\\n$`));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the read-back, before the file write: no fence; status names the stray key; issue removes it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.crash(["triage", "key", "issue"], "write")).signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const [stray] = f.triageKeys();
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout,
|
||||
new RegExp(`^triage key: not issued\\n[^]*keys in the Triage namespace the file does not hold: ${id(stray)}\\nnext: mosaic triage key issue\\n$`));
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
// The same crash in rotate: the file keeps the old key, the stray new one is named, retire removes it.
|
||||
const held = f.record();
|
||||
assert.equal((await f.crash(["triage", "key", "rotate"], "write")).signal, "SIGKILL");
|
||||
assert.deepEqual(f.record(), held);
|
||||
const strayNew = f.triageKeys().find((k) => k !== held.key);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout,
|
||||
new RegExp(`proxy: holds the key\\nkeys in the Triage namespace the file does not hold: ${id(strayNew)}\\nnext: mosaic triage key retire\\n$`));
|
||||
const retired = await f.cli(["triage", "key", "retire"]);
|
||||
ok(retired);
|
||||
assert.equal(retired.stdout, `triage key retire: removed ${id(strayNew)}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [held.key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("file written but the old key not yet retired: status shows it due; a crash inside retire recovers on the next retire", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
f.now = NOW + 121 * MIN;
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after [^\\n]* \\(due\\)\\n[^]*next: mosaic triage key retire\\n$`));
|
||||
// retire dies after the proxy dropped the key but before the file was rewritten.
|
||||
assert.equal((await f.crash(["triage", "key", "retire"], "write")).signal, "SIGKILL");
|
||||
assert.equal(f.state.keys.includes(first.key), false);
|
||||
assert.equal(f.record().retiring.length, 1);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /\(due\) \(not in the proxy list\)\n[^]*next: mosaic triage key retire\n$/);
|
||||
const puts = f.state.puts.length;
|
||||
const r = await f.cli(["triage", "key", "retire"]);
|
||||
ok(r);
|
||||
assert.equal(f.state.puts.length, puts);
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
// And a retire killed after its PUT leaves the fence, like any other write.
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
f.now += 121 * MIN;
|
||||
assert.equal((await f.crash(["triage", "key", "retire"], "put")).signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), true);
|
||||
refusal(await f.cli(["triage", "key", "retire"]), "proxy-uncertain");
|
||||
ok(await f.cli(["proxy", "fence", "clear", "--proxy-restarted"]));
|
||||
ok(await f.cli(["triage", "key", "retire"]));
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("a file that cannot be written after the proxy changed is reported with its recovery", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "status"]));
|
||||
fs.mkdirSync(f.dir, { mode: 0o700 });
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "write") fs.chmodSync(f.dir, 0o755); } } });
|
||||
refusal(r, "triage-key-unwritten", "the proxy list changed but ");
|
||||
assert.match(r.stderr, /run mosaic triage key issue again, which clears what this run left\n$/);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
fs.chmodSync(f.dir, 0o700);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the temp file, before its rename: status counts it; the next verb removes it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.crash(["triage", "key", "issue"], "rename")).signal, "SIGKILL");
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const temps = fs.readdirSync(f.dir).filter((n) => n.endsWith(".tmp"));
|
||||
assert.equal(temps.length, 1);
|
||||
assert.match(temps[0], /^\.model\.\d+\.[0-9a-f]{12}\.tmp$/);
|
||||
// The temp file holds the key the proxy now has; that is why it must go.
|
||||
const [stray] = f.triageKeys();
|
||||
assert.ok(fs.readFileSync(join(f.dir, temps[0]), "utf8").includes(stray));
|
||||
const status = await f.cli(["triage", "key", "status"]);
|
||||
ok(status);
|
||||
assert.match(status.stdout, new RegExp(`leftover temp files in the triage secrets directory: 1 \\(the next issue, rotate or retire removes them\\)\\nkeys in the Triage namespace the file does not hold: ${id(stray)}\\nnext: mosaic triage key issue\\n$`));
|
||||
// Something else in the directory is not a leftover and stays.
|
||||
fs.writeFileSync(join(f.dir, "notes.tmp"), "", { mode: 0o600 });
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(fs.readdirSync(f.dir).sort(), ["model", "notes.tmp"]);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
// Retire, with nothing else to do, still removes a leftover.
|
||||
assert.equal((await f.crash(["triage", "key", "rotate"], "rename")).signal, "SIGKILL");
|
||||
ok(await f.cli(["triage", "key", "retire"]));
|
||||
assert.deepEqual(fs.readdirSync(f.dir).sort(), ["model", "notes.tmp"]);
|
||||
assert.doesNotMatch((await f.cli(["triage", "key", "status"])).stdout, /leftover/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("the receipts file is checked before the proxy changes; a receipt that fails after is named", async (t) => {
|
||||
const receipts = (f) => join(f.root, "proxy", "mosaic-keys.receipts.jsonl");
|
||||
const spoils = [
|
||||
["mode", (f) => { fs.writeFileSync(receipts(f), "", { mode: 0o644 }); fs.chmodSync(receipts(f), 0o644); }, "the proxy receipts file mode is not 0600"],
|
||||
["link", (f) => { fs.writeFileSync(join(f.root, "elsewhere"), "", { mode: 0o600 }); fs.symlinkSync(join(f.root, "elsewhere"), receipts(f)); }, "the proxy receipts file cannot be opened"],
|
||||
["FIFO", (f) => assert.equal(spawnSync("mkfifo", ["-m", "600", receipts(f)]).status, 0), "the proxy receipts file cannot be opened"],
|
||||
];
|
||||
for (const [name, spoil, words] of spoils) {
|
||||
const f = await fixture(t);
|
||||
spoil(f);
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-receipts-unsafe", `${words}; nothing was changed\n$`);
|
||||
assert.equal(f.state.puts.length, 0, name);
|
||||
assert.equal(f.fenced(), false, name);
|
||||
assert.equal(fs.existsSync(f.file), false, name);
|
||||
f.scan();
|
||||
}
|
||||
// Safe before the change, unsafe at the receipt: the change stands and the refusal says so.
|
||||
const f = await fixture(t);
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "receipt") fs.chmodSync(receipts(f), 0o644); } } });
|
||||
refusal(r, "triage-key-unrecorded", "the change was made but its receipt line was not written; run mosaic triage key status\n$");
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.readFileSync(receipts(f), "utf8"), "");
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("a directory sync that fails after the rename is named, and the receipt is still written", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "sync") throw new Error("EIO"); } } });
|
||||
refusal(r, "triage-key-unsynced", `${f.file.replace(/[.]/g, "\\.")} was written but its directory could not be synced, so it may not survive a power loss; run mosaic triage key status\n$`);
|
||||
const rec = f.record();
|
||||
assert.deepEqual(f.triageKeys(), [rec.key]);
|
||||
assert.deepEqual(f.receipts().map((e) => e.addedKeyIds), [[rec.keyId]]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: holds the key\nnext: nothing\n$/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("an unexpected error prints fixed words, never the error's own text", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const secret = `mst-${tag(f.configDir)}-triage-${b64()}`;
|
||||
SEEN.add(secret);
|
||||
// Outside the proxy write: the verb's own fallback line.
|
||||
const broken = { dataRoot: f.root, get proxy() { throw new Error(`boom ${secret}`); } };
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { system: broken });
|
||||
assert.equal(r.code, 3, verb);
|
||||
assert.equal(r.stderr, "mosaic: triage-key-failed: the key verb stopped on an unexpected error; run mosaic triage key status\n");
|
||||
}
|
||||
// Inside the proxy write: the write's own fixed line, and the fence stays for a human.
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "put") throw new Error(`boom ${secret}`); } } });
|
||||
refusal(r, "triage-key-failed", "the proxy write failed\n$");
|
||||
assert.equal(f.fenced(), true);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
// The org bus reconciles its own `mso-` namespace at start and a no-org bus its `msk-` one; a
|
||||
// Triage key sits in neither, so both leave it. Stray keys in each namespace show the reconcile ran.
|
||||
test("an org bus that starts and reconciles, and a no-org reconcile, both leave the Triage key alone", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const triage = f.record().key;
|
||||
const strayOrg = `mso-${tag(f.configDir)}-demo-key-${b64()}`;
|
||||
f.state.keys.push(strayOrg);
|
||||
const rolesDir = rolesCopy(f.root), system = systemFor(f.root), doc = businessDoc(f.root, "demo");
|
||||
doc.plugins = { ...doc.plugins, harness: ["pi"] };
|
||||
const file = writeJson(join(f.configDir, "businesses", "demo.json"), doc);
|
||||
assert.ok(file);
|
||||
const business = loadBusiness("demo", { dir: f.configDir, rolesDir }), resolved = {};
|
||||
for (const instance of Object.keys(business.roles)) resolved[instance] = resolveInstance({ system, business, instance });
|
||||
fs.mkdirSync(join(f.root, "data"), { mode: 0o700 });
|
||||
new Registry(join(f.root, "data"));
|
||||
const bus = await startBroker({ dataRoot: join(f.root, "data"), businesses: { demo: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir, system }, proxy: { port: f.port, binary: "/fixture-unused" },
|
||||
org: { id: "demo" }, instanceDataRoot: f.root, instanceConfigDir: f.configDir });
|
||||
f.closers.push(() => bus.close());
|
||||
const orgKey = (await bus.modelPreflight({ business: "demo", role: "chief" })).key;
|
||||
assert.ok(orgKey.startsWith(`mso-${tag(f.configDir)}-demo-key-`));
|
||||
assert.equal(f.state.keys.includes(strayOrg), false, "the org reconcile did not run");
|
||||
assert.ok(f.state.keys.includes(triage), "the org bus removed the Triage key");
|
||||
// A no-org reconcile on the same instance.
|
||||
const strayAgent = `msk-${tag(f.configDir)}-${b64()}`;
|
||||
f.state.keys.push(strayAgent);
|
||||
const client = new ManagementClient({ baseUrl: `http://127.0.0.1:${f.port}`, key: MANAGE });
|
||||
const keys = new ModelKeys({ credentials: { status: () => [], modelRecord: () => null }, client, configDir: f.configDir, baseUrl: `http://127.0.0.1:${f.port}` });
|
||||
await keys.reconcile();
|
||||
assert.equal(f.state.keys.includes(strayAgent), false, "the no-org reconcile did not run");
|
||||
assert.ok(f.state.keys.includes(triage), "the no-org reconcile removed the Triage key");
|
||||
// Triage still works under the shared lock while the org bus runs, and leaves the org key.
|
||||
f.now += HOUR;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
assert.ok(f.state.keys.includes(orgKey));
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: holds the key\n/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("scripts/mosaic routes triage key status with the instance's own config directory", (t) => {
|
||||
const home = fs.mkdtempSync(join(tmpdir(), "tkm-"));
|
||||
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||
const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, ".config/mosaic-tktest/config.json") });
|
||||
const setup = spawnSync(join(REPO, "scripts/bootstrap.sh"), ["--instance", "tktest"], { env, encoding: "utf8" });
|
||||
assert.equal(setup.status, 0, setup.stderr);
|
||||
const r = spawnSync(join(REPO, "scripts/mosaic"), ["triage", "key", "status"], { env, encoding: "utf8", timeout: 60000 });
|
||||
OUTPUTS.push(r.stdout, r.stderr);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, `triage key: not issued\nfile: ${join(home, ".config/mosaic-tktest/secrets/triage/model")}\nproxy: not set up for this instance (no proxy.json)\nnext: set up the model proxy first (mosaic proxy init)\n`);
|
||||
const refused = spawnSync(join(REPO, "scripts/mosaic"), ["triage", "key", "issue"], { env: { ...env, CLAUDECODE: "1" }, encoding: "utf8", timeout: 60000 });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.match(refused.stderr, /found CLAUDECODE in the environment/);
|
||||
});
|
||||
|
||||
test("no output of any verb in this file holds any key the stand-in saw", () => {
|
||||
assert.ok(SEEN.size >= 20, `only ${SEEN.size} keys were seen`);
|
||||
assert.ok(OUTPUTS.length >= 100);
|
||||
for (const text of OUTPUTS) assert.equal(leaks(text), false);
|
||||
});
|
||||
@@ -193,7 +193,7 @@
|
||||
catch { return { unknown: true }; }
|
||||
if (res.type === 'opaqueredirect') return { signedOut: true };
|
||||
try { result = await res.json(); } catch { return { unknown: true }; }
|
||||
return { ok: res.ok, result };
|
||||
return { ok: res.ok, status: res.status, result };
|
||||
}
|
||||
// The request's closing read, or a reason the chain stops.
|
||||
async function closing(request, org) {
|
||||
@@ -215,31 +215,39 @@
|
||||
return e ? (Array.isArray(e.running) ? e.running.length : 0) : 0;
|
||||
} catch { return null; }
|
||||
}
|
||||
async function restartAgent(name, thread) {
|
||||
const org = window.MosaicOrg?.id ?? null;
|
||||
const r = restarts[name] = { busy: true, text: `Terminating ${name}…` };
|
||||
const paint = () => paintRestart(name, org);
|
||||
const stop = text => { r.busy = false; r.text = text; paint(); };
|
||||
paint();
|
||||
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason: 'route change' });
|
||||
if (asked.signedOut) return stop('Sign in again, then retry.');
|
||||
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return stop(asked.ok || asked.unknown ? UNKNOWN : refused(asked.result));
|
||||
// SP19 (#1873): the agent drawer's Restart runs this same chain. `org` is the agent's own organization
|
||||
// (on #/agents the page has none), `reason` goes with the terminate, `text(step, detail)` may give the
|
||||
// words for a step (nothing keeps the route-change words below), and `onStatus({ step, busy, text })`
|
||||
// takes each line in place of the Routing receipt's button. The chain never regenerates.
|
||||
async function restartAgent(name, thread, { org = window.MosaicOrg?.id ?? null, reason = 'route change', text, onStatus } = {}) {
|
||||
const r = { busy: true, text: '' };
|
||||
if (!onStatus) restarts[name] = r;
|
||||
const paint = step => onStatus ? onStatus({ step, busy: r.busy, text: r.text }) : paintRestart(name, org);
|
||||
const words = (step, detail, own) => (typeof text === 'function' ? text(step, detail) : undefined) ?? own;
|
||||
const say = (step, detail, own) => { r.text = words(step, detail, own); paint(step); };
|
||||
const stop = (step, detail, own) => { r.busy = false; say(step, detail, own); };
|
||||
say('ending', {}, `Terminating ${name}…`);
|
||||
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason });
|
||||
if (asked.signedOut) return stop('signedOut', {}, 'Sign in again, then retry.');
|
||||
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return asked.ok || asked.unknown ? stop('endUnknown', {}, UNKNOWN) : stop('endRefused', { status: asked.status, result: asked.result }, refused(asked.result));
|
||||
const ended = await closing(asked.result.request, org);
|
||||
if (ended.stop) return stop(ended.stop);
|
||||
if (ended.done.reason) return stop(`${name}: ${ended.done.reason}. It was not restarted.`);
|
||||
r.text = `Terminated ${name}. Waiting for its session to end…`; paint();
|
||||
if (ended.stop) return stop('endOpen', { stop: ended.stop }, ended.stop);
|
||||
if (ended.done.reason) return stop('endClosed', { reason: ended.done.reason }, `${name}: ${ended.done.reason}. It was not restarted.`);
|
||||
say('ended', {}, `Terminated ${name}. Waiting for its session to end…`);
|
||||
let left = false;
|
||||
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name, org)) === 0; }
|
||||
if (!left) return stop(`${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
|
||||
if (thread) return stop(`Terminated ${name} at ${new Date().toLocaleTimeString()}. Its next message starts it on the new route.`);
|
||||
r.text = `Launching ${name}…`; paint();
|
||||
if (!left) return stop('stillRunning', {}, `${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
|
||||
const time = new Date().toLocaleTimeString();
|
||||
if (thread) return stop('threadEnded', { time }, `Terminated ${name} at ${time}. Its next message starts it on the new route.`);
|
||||
say('launching', {}, `Launching ${name}…`);
|
||||
const launch = await send(pin(org, '/api/agent/launch'), { instance: name });
|
||||
if (launch.signedOut) return stop('Sign in again. It was terminated and not launched.');
|
||||
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return stop(launch.ok || launch.unknown ? `${UNKNOWN} It was terminated.` : `${refused(launch.result)} It was terminated and not launched.`);
|
||||
if (launch.signedOut) return stop('launchSignedOut', {}, 'Sign in again. It was terminated and not launched.');
|
||||
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return launch.ok || launch.unknown ? stop('launchUnknown', {}, `${UNKNOWN} It was terminated.`) : stop('launchRefused', { status: launch.status, result: launch.result }, `${refused(launch.result)} It was terminated and not launched.`);
|
||||
const started = await closing(launch.result.request, org);
|
||||
if (started.stop) return stop(started.stop);
|
||||
if (started.done.reason) return stop(`${name}: ${started.done.reason}. It was terminated and not launched.`);
|
||||
return stop(`Restarted ${name} on the new route${started.done.done?.run ? ` (run ${started.done.done.run})` : ''}.`);
|
||||
if (started.stop) return stop('launchOpen', { stop: started.stop }, started.stop);
|
||||
if (started.done.reason) return stop('launchClosed', { reason: started.done.reason }, `${name}: ${started.done.reason}. It was terminated and not launched.`);
|
||||
const run = started.done.done?.run ?? null;
|
||||
return stop('restarted', { run }, `Restarted ${name} on the new route${run ? ` (run ${run})` : ''}.`);
|
||||
}
|
||||
document.addEventListener('click', e => {
|
||||
const b = e.target.closest?.('[data-agent-restart]');
|
||||
@@ -247,7 +255,7 @@
|
||||
restartAgent(b.dataset.agentRestart, b.dataset.agentThread === 'yes');
|
||||
});
|
||||
|
||||
window.MosaicAgents = Object.freeze({ section, restartMarkup, isThread: definition => threadDefinitions.has(definition) });
|
||||
window.MosaicAgents = Object.freeze({ section, restartMarkup, restart: restartAgent, isThread: definition => threadDefinitions.has(definition) });
|
||||
})();
|
||||
|
||||
/* #1873 A2: Settings > Agents, the root and project agent levels. bus.js awaits section() for the
|
||||
|
||||
@@ -1118,8 +1118,16 @@
|
||||
const DRAWER_LIMIT = 5, STOP_REASON = 'Stopped from the agent drawer.';
|
||||
const STOP_UNKNOWN = 'Outcome unknown. Read the agents again before trying; nothing was retried.';
|
||||
// The Stop state of the drawer's agent survives repaints: `confirm` while it asks, `busy` while the
|
||||
// request is open, then the result in words beside the button.
|
||||
let stopState = null; // { id, confirm, busy, text }
|
||||
// request is open, then the result in words beside the button. SP19: `kind` says whether Stop or
|
||||
// Restart asks (no kind is Stop). While either asks or runs, both buttons wait.
|
||||
let stopState = null; // { id, kind, confirm, busy, text }
|
||||
// SP19: each drawer agent's restart, kept per agent so several can run at once and none loses its
|
||||
// line when another drawer asks or stops: `busy` while it runs, then its outcome in words. An entry
|
||||
// goes when a new question starts on that agent, or when the drawer closes after it finished.
|
||||
const restarts = new Map(); // id -> { busy, text }
|
||||
// The state a drawer draws: its own question or Stop first, else its restart.
|
||||
const actState = id => stopState?.id === id ? stopState : restarts.has(id) ? { id, kind: 'restart', ...restarts.get(id) } : null;
|
||||
const RESTART_REASON = 'restart from the agent drawer';
|
||||
let drawerFocus = false, drawerShown = null;
|
||||
// The drawer holds at most one history entry. A row opened from the page without a drawer pushes one
|
||||
// entry marked in history.state; switching rows replaces it. Close goes Back only from that marked
|
||||
@@ -1132,11 +1140,16 @@
|
||||
const sansAgent = () => { const n = queryOf(); n.delete('agent'); const s = n.toString(); return `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`; };
|
||||
// The row's name as a link that opens the drawer: a native link, so Tab reaches it and Enter opens it.
|
||||
const drawerLink = (q, a) => `<a class="ws-drawer-open" href="${esc(drawerHref(q, `${a.org}:${a.key}`))}" data-ws-drawer-open="${esc(`${a.org}:${a.key}`)}" data-focus-key="${esc(`agent:${a.org}:${a.key}`)}">${esc(a.name)}</a>`;
|
||||
const stopConfirm = (name, who) => `<span class="ws-drawer-confirm" data-drawer-stop-confirm>Stop ${esc(who)}? <button type="button" class="ws-btn danger" data-drawer-stop-yes data-focus-key="drawer-stop-yes">Stop ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-stop-no data-focus-key="drawer-stop-no">Cancel</button></span>`;
|
||||
function stopActions(pick, a, orgName) {
|
||||
const st = stopState?.id === pick.id ? stopState : null;
|
||||
const who = `${a.name} in ${orgName}`;
|
||||
return `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${st?.busy || st?.confirm ? ' disabled' : ''}>${st?.busy ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm ? stopConfirm(a.name, who) : ''}`;
|
||||
// SP19: Stop and Restart ask in the same confirm step, each under its own data attributes.
|
||||
const actConfirm = (kind, name, question) => `<span class="ws-drawer-confirm" data-drawer-${kind}-confirm>${esc(question)} <button type="button" class="ws-btn danger" data-drawer-${kind}-yes data-focus-key="drawer-${kind}-yes">${kind === 'stop' ? 'Stop' : 'Restart'} ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-${kind}-no data-focus-key="drawer-${kind}-no">Cancel</button></span>`;
|
||||
const stopConfirm = (name, who) => actConfirm('stop', name, `Stop ${who}?`);
|
||||
const restartConfirm = (name, who, thread) => actConfirm('restart', name, `Restart ${who}? ${thread ? 'It ends its session; its next message starts it again.' : 'It ends its session and launches it again.'}`);
|
||||
function stopActions(pick, a, orgName, thread) {
|
||||
const st = actState(pick.id), kind = st?.kind || 'stop';
|
||||
const who = `${a.name} in ${orgName}`, hold = st?.busy || st?.confirm ? ' disabled' : '';
|
||||
const stop = `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${hold}>${st?.busy && kind === 'stop' ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm && kind === 'stop' ? stopConfirm(a.name, who) : ''}`;
|
||||
if (!window.MosaicAgents?.restart) return stop;
|
||||
return `${stop} <button type="button" class="ws-btn" data-drawer-restart data-drawer-thread="${thread ? 'yes' : 'no'}" data-focus-key="drawer-restart"${hold}>${st?.busy && kind === 'restart' ? 'Restarting…' : 'Restart'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm && kind === 'restart' ? restartConfirm(a.name, who, thread) : ''}`;
|
||||
}
|
||||
// SP13 (#1873): the drawer's instances read gives the agent's state. The drawer does not hold the
|
||||
// page for it: once the page's own reads have answered (`opts.page`), a drawer whose instances read
|
||||
@@ -1335,7 +1348,8 @@
|
||||
: a.level !== 'org' ? 'No Message: a copy is not messaged from here.'
|
||||
: 'No Message: this Console messages only conversation agents, such as the Assistant.'}</p>`);
|
||||
else if (change) acts.push(`<p class="note" data-drawer-nomessage>No Message: this Console does not send chat in ${esc(orgName)}.</p>`);
|
||||
if (change && a.level === 'org' && !a.keep && running(item) > 0) acts.push(stopActions(pick, a, orgName));
|
||||
// SP19: a restart that is running keeps its buttons even when a repaint reads no run between its end and its launch.
|
||||
if (change && a.level === 'org' && !a.keep && (running(item) > 0 || restarts.get(id)?.busy)) acts.push(stopActions(pick, a, orgName, !!window.MosaicAgents?.isThread?.(def)));
|
||||
// Why Stop is not offered, in words, where this Console could otherwise change the organization's agents.
|
||||
// SP13: "not running" is a reason only once the instances read has given the agent's runs.
|
||||
else if (change) acts.push(`<p class="note" data-drawer-nostop>${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.'
|
||||
@@ -1343,7 +1357,7 @@
|
||||
: a.level !== 'org' ? 'A copy is not stopped from here.'
|
||||
: a.keep ? `${esc(a.name)} is one of ${esc(orgName)}’s protected agents, so it is not stopped from here.`
|
||||
: 'It is not running, so there is nothing to stop.'}</p>`);
|
||||
const st = stopState?.id === id ? stopState : null;
|
||||
const st = actState(id);
|
||||
const actions = chat || change
|
||||
? `<div class="ws-drawer-acts" data-drawer-actions>${acts.join(' ')}<p class="ws-drawer-status" id="ws-drawer-status" role="status" data-drawer-status>${esc(st?.text || '')}</p></div>`
|
||||
: `<p class="note" data-drawer-readonly>This Console only reads ${esc(orgName)}. It can not message or stop its agents.</p>`;
|
||||
@@ -1383,6 +1397,7 @@
|
||||
// `agent` from the address in place. Either way the page repaints without it and focus returns to the row.
|
||||
function closeDrawer() {
|
||||
if (!stopState?.busy) stopState = null;
|
||||
for (const [k, r] of restarts) if (!r.busy) restarts.delete(k);
|
||||
if (stateOf()?.[DRAWER_MARK] && queryOf().has('agent')) { history.back(); return; }
|
||||
history.replaceState(unmarked(), '', sansAgent());
|
||||
document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
@@ -1420,7 +1435,7 @@
|
||||
const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
|
||||
stopState = { id, busy: true, text: `Stopping ${name}…` };
|
||||
const repaint = () => document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!stopState.busy; b.firstChild.textContent = stopState.busy ? 'Stopping…' : 'Stop'; } now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
|
||||
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!stopState.busy; b.firstChild.textContent = stopState.busy ? 'Stopping…' : 'Stop'; } const rb = now.querySelector('[data-drawer-restart]'); if (rb) rb.disabled = !!stopState.busy; now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
|
||||
const finish = text => { stopState = { id, text }; paint(); const b = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-stop]`); b?.focus({ preventScroll: true }); };
|
||||
paint();
|
||||
let res, body = null;
|
||||
@@ -1448,6 +1463,72 @@
|
||||
}
|
||||
finish(`Request ${request} is still open. Read the agents again later.`);
|
||||
}
|
||||
// SP19: the drawer's Restart. The agents.js chain ends the agent through its own organization's routes
|
||||
// (the drawer's, which on #/agents is not the page's), waits for the request to close and its runs to
|
||||
// reach 0, then launches it; a conversation agent is not launched. It never regenerates. Each step is
|
||||
// painted in place; a refusal before the end leaves both buttons usable and focus on Restart.
|
||||
const refusedWhy = (d, orgName) => {
|
||||
const e = d?.result?.error, m = d?.result?.message;
|
||||
if (d?.status === 403 && e === 'read-only') return `this Console only reads agents in ${orgName} (read-only).`;
|
||||
if (d?.status === 403 && (e === 'unavailable' || e === 'owner-only')) return `this Console is not the owner of ${orgName}, so it does not restart its agents.`;
|
||||
if (e === 'no-bus-host') return `the bus of ${orgName} is not running. Nothing changed.`;
|
||||
if (e === 'org-archived') return `${orgName} is archived, so its agents are not changed. Nothing changed.`;
|
||||
if (e === 'org-unavailable') return `${orgName} is not available to this Console. Nothing changed.`;
|
||||
if (d?.result?.sent === false && typeof m === 'string' && m) return m;
|
||||
if (d?.result?.sent === false && typeof e === 'string') return `the bus refused (${e}).`;
|
||||
return STOP_UNKNOWN;
|
||||
};
|
||||
const restartWords = (name, orgName) => (step, d) => ({
|
||||
ending: `Restarting ${name}: asking it to end…`,
|
||||
signedOut: 'Not restarted: sign in again, then read the agents.',
|
||||
endUnknown: `Not restarted: ${STOP_UNKNOWN}`,
|
||||
endRefused: `Not restarted: ${refusedWhy(d, orgName)}`,
|
||||
endOpen: `Not restarted: ${d?.stop}`,
|
||||
endClosed: `Not restarted: ${name} was not ended (${d?.reason}).`,
|
||||
ended: `${name} was asked to end. Waiting for its session to end…`,
|
||||
stillRunning: `Not restarted: ${name} was asked to end, but its session is still running. Read the agents again before trying.`,
|
||||
threadEnded: `Ended ${name} at ${d?.time}. Its next message starts it.`,
|
||||
launching: `${name} has ended. Launching it…`,
|
||||
launchSignedOut: `${name} was ended and not launched: sign in again, then read the agents.`,
|
||||
launchUnknown: `${name} was ended. The launch outcome is unknown; read the agents again before trying. Nothing was retried.`,
|
||||
launchRefused: `${name} was ended and not launched: ${refusedWhy(d, orgName)}`,
|
||||
launchOpen: `${name} was ended. ${d?.stop}`,
|
||||
launchClosed: `${name} was ended and not launched: ${d?.reason}.`,
|
||||
restarted: `Restarted ${name}${d?.run ? ` (run ${d.run})` : ''}.`,
|
||||
})[step];
|
||||
async function restartAgent(d) {
|
||||
const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
|
||||
const thread = d.querySelector('[data-drawer-restart]')?.dataset.drawerThread === 'yes';
|
||||
if (restarts.get(id)?.busy) return;
|
||||
// The question is answered: from now on this agent's drawer draws its restart.
|
||||
if (stopState?.id === id) stopState = null;
|
||||
restarts.set(id, { busy: true, text: '' });
|
||||
// Paint this agent's drawer in place, when it is on screen and no question of its own holds it.
|
||||
const paint = () => {
|
||||
const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`), r = restarts.get(id); if (!now || !r || stopState?.id === id) return;
|
||||
const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = r.text;
|
||||
const rb = now.querySelector('[data-drawer-restart]'), sb = now.querySelector('[data-drawer-stop]');
|
||||
if (rb) { rb.disabled = r.busy; rb.firstChild.textContent = r.busy ? 'Restarting…' : 'Restart'; }
|
||||
if (sb) sb.disabled = r.busy;
|
||||
now.querySelector('.ws-drawer-confirm')?.remove();
|
||||
};
|
||||
// The finished line stays in the entry. A refusal before the end changed nothing, so focus goes back
|
||||
// to Restart. Once the agent was ended its runs changed: the repaint reads the instances again, so the
|
||||
// buttons follow them (after a refused launch it has none, so Stop and Restart go), and focus goes to
|
||||
// the drawer's heading, which every repaint keeps.
|
||||
const after = new Set(['restarted', 'threadEnded', 'launchSignedOut', 'launchUnknown', 'launchRefused', 'launchOpen', 'launchClosed']);
|
||||
const done = step => {
|
||||
document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`)?.querySelector(after.has(step) ? '[data-focus-key="drawer-h"]' : '[data-drawer-restart]')?.focus({ preventScroll: true });
|
||||
if (after.has(step)) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
};
|
||||
const onStatus = ({ step, busy, text }) => {
|
||||
restarts.set(id, { busy: !!busy, text });
|
||||
paint();
|
||||
if (!busy) done(step);
|
||||
};
|
||||
try { await window.MosaicAgents.restart(name, thread, { org, reason: RESTART_REASON, text: restartWords(name, orgName), onStatus }); }
|
||||
catch { restarts.set(id, { busy: false, text: `Not restarted: ${STOP_UNKNOWN}` }); paint(); done('endUnknown'); }
|
||||
}
|
||||
document.addEventListener('click', e => {
|
||||
const link = e.target.closest?.('[data-ws-drawer-open]');
|
||||
if (link) {
|
||||
@@ -1466,33 +1547,41 @@
|
||||
if (!d) return;
|
||||
if (e.target.closest('[data-drawer-close]')) { closeDrawer(); return; }
|
||||
const id = d.dataset.wsDrawer;
|
||||
if (e.target.closest('[data-drawer-stop]') && !(stopState?.id === id && stopState.busy)) {
|
||||
const b = d.querySelector('[data-drawer-stop]'), name = d.dataset.drawerName;
|
||||
stopState = { id, confirm: true, text: '' };
|
||||
d.querySelector('[data-drawer-stop-confirm]')?.remove();
|
||||
b.insertAdjacentHTML('afterend', stopConfirm(name, `${name} in ${d.dataset.drawerOrgName}`));
|
||||
b.disabled = true;
|
||||
// SP19: nothing starts while this agent's Stop or Restart runs.
|
||||
const held = (stopState?.id === id && stopState.busy) || !!restarts.get(id)?.busy;
|
||||
const ask = e.target.closest('[data-drawer-stop]') ? 'stop' : e.target.closest('[data-drawer-restart]') ? 'restart' : null;
|
||||
if (ask && !held) {
|
||||
const b = d.querySelector(`[data-drawer-${ask}]`), name = d.dataset.drawerName, who = `${name} in ${d.dataset.drawerOrgName}`;
|
||||
stopState = { id, kind: ask, confirm: true, text: '' }; restarts.delete(id);
|
||||
d.querySelector('.ws-drawer-confirm')?.remove();
|
||||
b.insertAdjacentHTML('afterend', ask === 'stop' ? stopConfirm(name, who) : restartConfirm(name, who, b.dataset.drawerThread === 'yes'));
|
||||
for (const x of d.querySelectorAll('[data-drawer-stop], [data-drawer-restart]')) x.disabled = true;
|
||||
const s = d.querySelector('[data-drawer-status]'); if (s) s.textContent = '';
|
||||
d.querySelector('[data-drawer-stop-no]')?.focus({ preventScroll: true });
|
||||
d.querySelector(`[data-drawer-${ask}-no]`)?.focus({ preventScroll: true });
|
||||
return;
|
||||
}
|
||||
if (e.target.closest('[data-drawer-stop-no]')) { cancelStop(d); return; }
|
||||
if (ask) return;
|
||||
if (e.target.closest('[data-drawer-stop-no], [data-drawer-restart-no]')) { cancelStop(d); return; }
|
||||
if (held) return;
|
||||
if (e.target.closest('[data-drawer-stop-yes]')) stopAgent(d);
|
||||
else if (e.target.closest('[data-drawer-restart-yes]')) restartAgent(d);
|
||||
});
|
||||
// Cancel the Stop question: nothing sent, Stop enabled again and focused.
|
||||
// Cancel the Stop or Restart question: nothing sent, both buttons enabled again, focus on the one that asked.
|
||||
function cancelStop(d) {
|
||||
const kind = d.querySelector('[data-drawer-restart-confirm]') ? 'restart' : 'stop';
|
||||
stopState = null;
|
||||
d.querySelector('[data-drawer-stop-confirm]')?.remove();
|
||||
const b = d.querySelector('[data-drawer-stop]'); if (b) { b.disabled = false; b.focus({ preventScroll: true }); }
|
||||
d.querySelector('.ws-drawer-confirm')?.remove();
|
||||
for (const x of d.querySelectorAll('[data-drawer-stop], [data-drawer-restart]')) x.disabled = false;
|
||||
d.querySelector(`[data-drawer-${kind}]`)?.focus({ preventScroll: true });
|
||||
}
|
||||
// Escape cancels the Stop question while it asks, else closes the drawer, unless a dialog is open
|
||||
// Escape cancels the Stop or Restart question while it asks, else closes the drawer, unless a dialog is open
|
||||
// or something else took the key.
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key !== 'Escape' || e.defaultPrevented || document.querySelector('dialog[open]')) return;
|
||||
const d = document.querySelector('#bus-view [data-ws-drawer]');
|
||||
if (!d) return;
|
||||
e.preventDefault();
|
||||
if (d.querySelector('[data-drawer-stop-confirm]')) cancelStop(d); else closeDrawer();
|
||||
if (d.querySelector('.ws-drawer-confirm')) cancelStop(d); else closeDrawer();
|
||||
});
|
||||
|
||||
// ---- controls: filters write the hash query and repaint in place ----
|
||||
|
||||
@@ -108,10 +108,20 @@ const STUB = `(() => {
|
||||
if (window.__packsBody) return new Response(window.__packsBody, { status: 200, headers: { 'content-type': 'text/html' } });
|
||||
return answer(200, { writable: false, applied: [{ id: 'coding', origin: 'shipped', project: null, hired: ['research-2'], open: [] }], packs: packs[1] === 'beta' ? [{ id: 'coding', origin: 'shipped', pack: { id: 'coding', label: 'Coding', version: 2, hires: [{ name: 'research-2', definition: 'researcher', reason: 'Research.' }], definitions: { researcher: { template: 'researcher', sha256: '${'a'.repeat(64)}' } } } }] : [] });
|
||||
}
|
||||
// SP19: a test may set __runs[org][name] to the runs the instances read lists for that agent.
|
||||
const inst = u.match(/^\\/api\\/orgs\\/([^/]+)\\/bus\\/instances$/);
|
||||
if (inst && window.__runs?.[inst[1]]) {
|
||||
const got = await real(url, init), v = await got.json();
|
||||
for (const [n, runs] of Object.entries(window.__runs[inst[1]])) if (v?.rows?.[0]?.instances?.[n]) v.rows[0].instances[n].running = runs;
|
||||
return answer(got.status, v);
|
||||
}
|
||||
if (!/\\/agent\\//.test(u) || (init.method || 'GET') === 'GET' && !u.includes('/agent/request')) return real(url, init);
|
||||
window.__posts.push({ url: u, method: init.method || 'GET', body: init.body ?? null });
|
||||
const a = window.__answers.shift();
|
||||
if (!a) throw new TypeError('no answer queued');
|
||||
// SP19: an answer may wait on a promise (\`hold\`) and run a step once it is given (\`then\`).
|
||||
if (a.hold) await a.hold;
|
||||
a.then?.();
|
||||
return answer(a.status ?? 200, a.body);
|
||||
};
|
||||
})();`;
|
||||
@@ -711,3 +721,192 @@ test('triage-followups: a drawer opened before the first render ends keeps focus
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
assert.equal(await b.evaluate(`${drawer('acme:coder')}.contains(document.activeElement)`), true, `focus stays in the drawer, not on ${await b.evaluate('document.activeElement?.tagName')}`);
|
||||
});
|
||||
|
||||
// SP19 (#1873): Restart in the drawer, offered only where Stop is. It reuses Stop's confirm step and
|
||||
// status line, ends the agent through its own organization's /agent/terminate, waits for the request to
|
||||
// close and for its runs to reach 0, then launches it through /agent/launch. It never regenerates. A
|
||||
// conversation agent is ended and not launched. The page's 2 s poll steps run every 20 ms here.
|
||||
const FAST = `(() => { const st = window.setTimeout.bind(window); window.setTimeout = (f, ms, ...a) => st(f, ms === 2000 ? 20 : ms, ...a); })()`;
|
||||
const END = '5e000000-0000-4000-8000-0000000000e1', LAUNCH = '5e000000-0000-4000-8000-0000000000a1';
|
||||
const closed = (request, action, extra = {}) => ({ request, instance: 'coder', action, state: 'closed', done: { run: null, transaction: null, refusal: null }, cancelled: null, ...extra });
|
||||
// Every distinct state of the drawer's actions, from now on: [status, Restart's label, Restart disabled, Stop disabled].
|
||||
const WATCH = id => `(() => { window.__seen = []; const snap = () => { const d = document.querySelector('[data-ws-drawer="${id}"]'); if (!d) return; const r = d.querySelector('[data-drawer-restart]'), s = d.querySelector('[data-drawer-stop]'); const v = [d.querySelector('[data-drawer-status]')?.textContent ?? '', r ? r.firstChild.textContent : null, !!r?.disabled, !!s?.disabled]; const l = window.__seen.at(-1); if (!l || l.join('|') !== v.join('|')) window.__seen.push(v); }; snap(); new MutationObserver(snap).observe(document.getElementById('bus-view'), { subtree: true, childList: true, characterData: true, attributes: true }); return true; })()`;
|
||||
const status = d => `(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`;
|
||||
const usable = d => `document.querySelector('${d} [data-drawer-restart]')?.disabled === false && document.querySelector('${d} [data-drawer-stop]')?.disabled === false && !document.querySelector('${d} .ws-drawer-confirm')`;
|
||||
|
||||
test('SP19: Restart asks first, then ends and launches the agent in its own organization, and never regenerates', async t => {
|
||||
// The reader was last on Beta Works, so the Console's chosen organization is beta. #/agents shows every
|
||||
// organization's agents; the drawer's own organization is used, not the chosen one.
|
||||
const { b, wait, text } = await setup(t, { hash: '#/orgs/beta/organization', scripts: [FAST] });
|
||||
await wait(`window.MosaicOrg?.id === 'beta' && document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 0`);
|
||||
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
assert.equal(await b.evaluate('window.MosaicOrg?.id ?? null'), 'beta');
|
||||
// Beside Stop, in the same action group as the status line.
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').closest('[data-drawer-actions]') === document.querySelector('${d} [data-drawer-stop]').closest('[data-drawer-actions]')`), true);
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').textContent`), 'Restart coder in Acme Studio');
|
||||
// It asks first, in Stop's confirm step. Cancel sends nothing and puts focus back on Restart.
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
|
||||
assert.match(await text(`${d} [data-drawer-restart-confirm]`), /^Restart coder in Acme Studio\? It ends its session and launches it again\. Restart coder Cancel$/);
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart-confirm]').classList.contains('ws-drawer-confirm')`), true);
|
||||
assert.deepEqual(await b.evaluate(`[document.querySelector('${d} [data-drawer-restart]').disabled, document.querySelector('${d} [data-drawer-stop]').disabled]`), [true, true]);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-no]').click()`);
|
||||
await wait(`document.activeElement === document.querySelector('${d} [data-drawer-restart]') && ${usable(d)}`);
|
||||
// Escape cancels the question too, and the drawer stays.
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-no]') === document.activeElement`);
|
||||
await b.key('Escape');
|
||||
await wait(`document.activeElement === document.querySelector('${d} [data-drawer-restart]') && ${usable(d)}`);
|
||||
assert.equal(await b.evaluate(agentParam), 'acme:coder');
|
||||
assert.deepEqual(await b.evaluate('window.__posts'), []);
|
||||
// Yes: one terminate, its request followed until it closes, the runs read until none is left, one launch.
|
||||
await b.evaluate(`window.__answers.push(
|
||||
{ body: { request: '${END}', runs: ['run-1'], cancelled: [], taken: [] }, then: () => { window.__runs = { acme: { coder: [] } }; } },
|
||||
{ body: ${JSON.stringify(closed(END, 'end'))} },
|
||||
{ body: { request: '${LAUNCH}' }, then: () => { window.__runs = { acme: { coder: ['run-2'] } }; } },
|
||||
{ body: ${JSON.stringify(closed(LAUNCH, 'launch', { done: { run: 'run-2', transaction: null, refusal: null } }))} })`);
|
||||
await b.evaluate(WATCH('acme:coder'));
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
|
||||
await wait(`/^Restarted coder \\(run run-2\\)\\.$/.test(${status(d)}) && ${usable(d)}`);
|
||||
const posts = await b.evaluate('window.__posts');
|
||||
assert.deepEqual(posts.map(p => [p.url, p.method]), [
|
||||
['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${END}`, 'GET'],
|
||||
['/api/orgs/acme/agent/launch', 'POST'], [`/api/orgs/acme/agent/request?id=${LAUNCH}`, 'GET'],
|
||||
]);
|
||||
assert.deepEqual(JSON.parse(posts[0].body), { instance: 'coder', reason: 'restart from the agent drawer' });
|
||||
assert.deepEqual(JSON.parse(posts[2].body), { instance: 'coder' });
|
||||
assert.equal(posts.some(p => /regenerate/.test(p.url)), false, 'Restart never regenerates');
|
||||
// The status line names each step; while it runs, Restart reads Restarting… and both buttons wait.
|
||||
const seen = await b.evaluate('window.__seen');
|
||||
const steps = seen.map(s => s[0]).filter((s, i, all) => s && s !== all[i - 1]);
|
||||
assert.deepEqual(steps, ['Restarting coder: asking it to end…', 'coder was asked to end. Waiting for its session to end…', 'coder has ended. Launching it…', 'Restarted coder (run run-2).']);
|
||||
for (const [s, label, rd, sd] of seen.filter(s => steps.slice(0, 3).includes(s[0]))) assert.deepEqual([label, rd, sd], ['Restarting…', true, true], s);
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').firstChild.textContent`), 'Restart');
|
||||
});
|
||||
|
||||
// The Assistant is a protected agent, so it has no Stop and no Restart; ideas is a conversation agent that is not.
|
||||
test('SP19: a conversation agent is ended and not launched; its next message starts it', async t => {
|
||||
const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
|
||||
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Aideas', scripts: [FAST], data });
|
||||
const d = '[data-ws-drawer="acme:ideas"]';
|
||||
await wait(`${open('acme:ideas')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').dataset.drawerThread`), 'yes');
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
|
||||
assert.match(await b.evaluate(`document.querySelector('${d} [data-drawer-restart-confirm]').textContent`), /^Restart ideas in Acme Studio\? It ends its session; its next message starts it again\./);
|
||||
await b.evaluate(`window.__answers.push(
|
||||
{ body: { request: '${END}', runs: ['run-4'], cancelled: [], taken: [] }, then: () => { window.__runs = { acme: { ideas: [] } }; } },
|
||||
{ body: ${JSON.stringify({ ...closed(END, 'end'), instance: 'ideas' })} })`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
|
||||
await wait(`/^Ended ideas at .+\\. Its next message starts it\\.$/.test(${status(d)})`);
|
||||
const posts = await b.evaluate('window.__posts');
|
||||
assert.deepEqual(posts.map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${END}`, 'GET']]);
|
||||
assert.deepEqual(JSON.parse(posts[0].body), { instance: 'ideas', reason: 'restart from the agent drawer' });
|
||||
});
|
||||
|
||||
test('SP19: a second click while a restart runs does nothing', async t => {
|
||||
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] });
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
// The terminate's answer is held, so the restart is still running while the page is clicked again.
|
||||
await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), status: 403, body: { error: 'unavailable', sent: false } })`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
|
||||
await wait(`window.__posts.length === 1 && document.querySelector('${d} [data-drawer-restart]').disabled`);
|
||||
// Even a Restart button made clickable again starts nothing: no second question, no second request.
|
||||
await b.evaluate(`(() => { const r = document.querySelector('${d} [data-drawer-restart]'), s = document.querySelector('${d} [data-drawer-stop]'); r.disabled = false; s.disabled = false; r.click(); s.click(); return true; })()`);
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 300))');
|
||||
assert.equal(await b.evaluate(`!!document.querySelector('${d} .ws-drawer-confirm')`), false);
|
||||
assert.equal(await b.evaluate('window.__posts.length'), 1);
|
||||
await b.evaluate('window.__release()');
|
||||
await wait(`/^Not restarted:/.test(${status(d)}) && ${usable(d)}`);
|
||||
assert.equal(await b.evaluate('window.__posts.length'), 1);
|
||||
});
|
||||
|
||||
// SP19 review: a restart keeps its own state, so another drawer's question or Stop does not lose its
|
||||
// line, and its drawer still shows it running when the reader comes back.
|
||||
test('SP19: a restart keeps its line and its running state across another drawer\'s Stop', async t => {
|
||||
const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
|
||||
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST], data });
|
||||
const d = '[data-ws-drawer="acme:coder"]', i = '[data-ws-drawer="acme:ideas"]';
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), status: 403, body: { error: 'unavailable', sent: false } })`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
|
||||
await wait(`window.__posts.length === 1`);
|
||||
// Ideas asks to stop and is cancelled; back on coder, its restart still shows as running.
|
||||
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
|
||||
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
|
||||
await b.evaluate(`document.querySelector('${i} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${i} [data-drawer-stop-no]')`);
|
||||
await b.evaluate(`document.querySelector('${i} [data-drawer-stop-no]').click()`);
|
||||
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
assert.deepEqual(await b.evaluate(`[${status(d)}, document.querySelector('${d} [data-drawer-restart]').firstChild.textContent, document.querySelector('${d} [data-drawer-restart]').disabled, document.querySelector('${d} [data-drawer-stop]').disabled]`),
|
||||
['Restarting coder: asking it to end…', 'Restarting…', true, true]);
|
||||
// Ideas' Stop question is open when coder's restart is refused; coder's drawer still says so after.
|
||||
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
|
||||
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
|
||||
await b.evaluate(`document.querySelector('${i} [data-drawer-stop]').click()`);
|
||||
await wait(`document.querySelector('${i} [data-drawer-stop-no]')`);
|
||||
await b.evaluate('window.__release()');
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 300))');
|
||||
assert.equal(await b.evaluate(`!!document.querySelector('${i} [data-drawer-stop-confirm]')`), true, 'the other drawer keeps its question');
|
||||
await b.evaluate(`document.querySelector('${i} [data-drawer-stop-no]').click()`);
|
||||
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
await wait(`${status(d)} === 'Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents.' && ${usable(d)}`);
|
||||
assert.equal(await b.evaluate('window.__posts.length'), 1);
|
||||
});
|
||||
|
||||
// Each refusal the two routes can give says so in one plain line. Where the agent still runs, both
|
||||
// buttons are usable again and focus is on Restart; after a refused launch it has no run, so the
|
||||
// repaint drops Stop and Restart, keeps the line and puts focus on the drawer's heading.
|
||||
const ENDED = [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] }, runs: [] }, { body: closed(END, 'end') }];
|
||||
for (const [label, answers, line] of [
|
||||
['not the owner', [{ status: 403, body: { error: 'unavailable', sent: false } }],
|
||||
/^Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents\.$/],
|
||||
['the organization is archived', [{ status: 409, body: { error: 'org-archived', message: 'organization is archived' } }],
|
||||
/^Not restarted: Acme Studio is archived, so its agents are not changed\. Nothing changed\.$/],
|
||||
['the bus is stopped', [{ status: 503, body: { error: 'no-bus-host', message: 'no-bus-host: no-bus-host. Nothing changed.', sent: false } }],
|
||||
/^Not restarted: the bus of Acme Studio is not running\. Nothing changed\.$/],
|
||||
['the end is refused', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: { ...closed(END, 'end', { done: { run: null, transaction: null, refusal: 'instance-kept' } }), reason: 'the instance is kept; unkeep it first' } }],
|
||||
/^Not restarted: coder was not ended \(the instance is kept; unkeep it first\)\.$/],
|
||||
['the launch is refused', [...ENDED, { status: 409, body: { error: 'capacity-full', message: 'capacity-full: a launch limit is reached. Nothing changed.', sent: false } }],
|
||||
/^coder was ended and not launched: capacity-full: a launch limit is reached\. Nothing changed\.$/],
|
||||
['the launch request closes refused', [...ENDED, { body: { request: LAUNCH } }, { body: { ...closed(LAUNCH, 'launch', { done: { run: null, transaction: null, refusal: 'no-route' } }), reason: 'the instance has no harness, model and thinking yet; set its route first' } }],
|
||||
/^coder was ended and not launched: the instance has no harness, model and thinking yet; set its route first\.$/],
|
||||
['its runs never reach 0', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: closed(END, 'end') }],
|
||||
/^Not restarted: coder was asked to end, but its session is still running\. Read the agents again before trying\.$/],
|
||||
]) test(`SP19: a refusal says so in the drawer: ${label}`, async t => {
|
||||
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] });
|
||||
const d = '[data-ws-drawer="acme:coder"]';
|
||||
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
|
||||
const queued = JSON.stringify(answers);
|
||||
await b.evaluate(`window.__answers.push(...${queued}.map(a => a.runs ? { ...a, then: () => { window.__runs = { acme: { coder: a.runs } }; } } : a))`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
|
||||
await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
|
||||
await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
|
||||
const launched = label.startsWith('the launch');
|
||||
await wait(launched ? `/ was ended and not launched: /.test(${status(d)}) && !document.querySelector('${d} [data-drawer-restart]')`
|
||||
: `/^Not restarted: /.test(${status(d)}) && document.querySelector('${d} [data-drawer-restart]')?.disabled === false`);
|
||||
await b.evaluate('new Promise(r => setTimeout(r, 300))');
|
||||
assert.match(await b.evaluate(status(d)), line);
|
||||
if (launched) {
|
||||
assert.deepEqual(await b.evaluate(`[!!document.querySelector('${d} [data-drawer-stop]'), document.querySelector('${d} [data-drawer-nostop]')?.textContent]`), [false, 'It is not running, so there is nothing to stop.']);
|
||||
assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} h2')`), true, `focus is on the drawer heading, not ${await b.evaluate('document.activeElement?.outerHTML.slice(0, 80)')}`);
|
||||
} else {
|
||||
assert.equal(await b.evaluate(usable(d)), true, 'both buttons are usable again');
|
||||
assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} [data-drawer-restart]')`), true, 'focus is back on Restart');
|
||||
}
|
||||
const posts = await b.evaluate('window.__posts');
|
||||
assert.equal(posts.some(p => /regenerate/.test(p.url)), false);
|
||||
assert.equal(posts.filter(p => p.url.endsWith('/agent/launch')).length, launched ? 1 : 0);
|
||||
assert.equal(await b.evaluate('window.__answers.length'), 0, 'every queued answer was asked for');
|
||||
});
|
||||
@@ -218,8 +218,9 @@ test('row 194 N5: agents.js is served as JavaScript and index.html loads it once
|
||||
const s = await setup(t);
|
||||
const js = await get(s, '/agents.js');
|
||||
assert.equal(js.status, 200); assert.match(js.type, /^text\/javascript/);
|
||||
// F3 adds the agent restart receipt and the thread test that Settings > Routing uses.
|
||||
assert.match(js.text, /window\.MosaicAgents = Object\.freeze\(\{ section, restartMarkup, isThread: definition => threadDefinitions\.has\(definition\) \}\)/);
|
||||
// F3 adds the agent restart receipt and the thread test that Settings > Routing uses; SP19 the
|
||||
// restart chain the agent drawer calls.
|
||||
assert.match(js.text, /window\.MosaicAgents = Object\.freeze\(\{ section, restartMarkup, restart: restartAgent, isThread: definition => threadDefinitions\.has\(definition\) \}\)/);
|
||||
assert.match(js.text, /Agent actions are unavailable here\. Use mosaic org instance from the instance CLI\./);
|
||||
const html = await get(s, '/');
|
||||
assert.equal(html.text.match(/<script src="\/agents\.js" defer><\/script>/g)?.length, 1);
|
||||
|
||||
@@ -20,7 +20,8 @@ const END = '10000000-0000-4000-8000-0000000000e1', LAUNCH = '10000000-0000-4000
|
||||
const DEV = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner', name: 'Local operator' };
|
||||
const route = thinking => ({ harness: 'claude', model: 'opus', thinking, fallback: null });
|
||||
|
||||
test('F3 Settings > Routing: a save lists how the change reaches each agent, and Restart now moves a running one', { timeout: 120000 }, async t => {
|
||||
// A real server with the stub bus, on Settings > Routing. `refusal` closes coder's end request with that code.
|
||||
async function stage(t, { refusal = null } = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'f3r-')); t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const entry = (definition, extra) => ({ definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running: [], alive: [], ...extra });
|
||||
const instances = {
|
||||
@@ -52,7 +53,7 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
|
||||
if (verb === 'instance.launch') { requests.set(LAUNCH, { instance: args.instance, action: 'launch' }); instances[args.instance].running = ['run-2']; return { request: LAUNCH }; }
|
||||
if (verb === 'instance.request') {
|
||||
const r = requests.get(args.request);
|
||||
return { request: args.request, instance: r.instance, action: r.action, state: 'closed', done: { run: r.action === 'launch' ? 'run-2' : null, transaction: null, refusal: null }, cancelled: null };
|
||||
return { request: args.request, instance: r.instance, action: r.action, state: 'closed', done: { run: r.action === 'launch' ? 'run-2' : null, transaction: null, refusal: r.action === 'end' && r.instance === 'coder' ? refusal : null }, cancelled: null };
|
||||
}
|
||||
throw Error(`unexpected ${verb}`);
|
||||
};
|
||||
@@ -72,6 +73,11 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
|
||||
for (const name of ['chief', 'coder', 'assistant', 'reviewer']) await b.evaluate(`(()=>{const s=${cell(name, 'thinking')};s.value='low';s.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`);
|
||||
await b.evaluate(`document.getElementById('routes-form').requestSubmit();true`);
|
||||
await wait(`document.querySelector('.routes-apply')`);
|
||||
return { b, wait, asked, items, dir };
|
||||
}
|
||||
|
||||
test('F3 Settings > Routing: a save lists how the change reaches each agent, and Restart now moves a running one', { timeout: 120000 }, async t => {
|
||||
const { b, wait, asked, items, dir } = await stage(t);
|
||||
assert.deepEqual(asked, [['routes.set', { revision: REV, routes: { chief: route('low'), coder: route('low'), assistant: route('low'), reviewer: route('low') } }]]);
|
||||
assert.equal(await b.evaluate(`document.getElementById('routes-receipt').textContent`), 'Routes saved for chief, coder, assistant, reviewer. The next launch of each uses the new route.');
|
||||
assert.deepEqual(await items(), [
|
||||
@@ -103,3 +109,29 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
|
||||
await b.viewport(390, 844);
|
||||
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=390`), true, 'no sideways scroll at phone width');
|
||||
});
|
||||
|
||||
// SP19 (#1873): the drawer's Restart shares this chain. The route-change flow keeps its reason, its
|
||||
// unprefixed routes and every line it shows, step by step, and its refusal line.
|
||||
const WATCH = name => `(()=>{window.__seen=[];const snap=()=>{const s=document.querySelector('[data-agent-restart-status="${name}"]')?.textContent??'';if(s&&s!==window.__seen.at(-1))window.__seen.push(s);};new MutationObserver(snap).observe(document.body,{subtree:true,childList:true,characterData:true});return true;})()`;
|
||||
test('SP19: Restart now keeps its reason and its words', { timeout: 120000 }, async t => {
|
||||
const { b, wait, asked } = await stage(t);
|
||||
const posts = [];
|
||||
await b.evaluate(`(()=>{const f=window.fetch;window.__urls=[];window.fetch=(u,o)=>{window.__urls.push(String(u));return f(u,o);};return true;})()`);
|
||||
await b.evaluate(WATCH('coder'));
|
||||
await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').click();true`);
|
||||
await wait(`document.querySelector('[data-agent-restart-status="coder"]')?.textContent==='Restarted coder on the new route (run run-2).'`, 30000);
|
||||
assert.deepEqual(await b.evaluate('window.__seen'), ['Terminating coder…', 'Terminated coder. Waiting for its session to end…', 'Launching coder…', 'Restarted coder on the new route (run run-2).']);
|
||||
assert.deepEqual(asked.filter(([v]) => v === 'instance.end'), [['instance.end', { instance: 'coder', reason: 'route change' }]]);
|
||||
posts.push(...(await b.evaluate('window.__urls')).filter(u => /\/api\/agent\/(terminate|launch|regenerate)/.test(u)));
|
||||
assert.deepEqual(posts, ['/api/agent/terminate', '/api/agent/launch']);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').textContent`), 'Restart coder now');
|
||||
});
|
||||
|
||||
test('SP19: Restart now says when the end is refused, in its own words', { timeout: 120000 }, async t => {
|
||||
const { b, wait, asked } = await stage(t, { refusal: 'instance-kept' });
|
||||
await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').click();true`);
|
||||
await wait(`/It was not restarted/.test(document.querySelector('[data-agent-restart-status="coder"]')?.textContent??'')`, 30000);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart-status="coder"]').textContent`), 'coder: the instance is kept; unkeep it first. It was not restarted.');
|
||||
assert.equal(asked.filter(([v]) => v === 'instance.launch').length, 0);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').disabled`), false);
|
||||
});
|
||||
Reference in new issue
Block a user