diff --git a/packages/cli/tests/harness-watch-host.test.mjs b/packages/cli/tests/harness-watch-host.test.mjs index c51af3444..a92858fb1 100644 --- a/packages/cli/tests/harness-watch-host.test.mjs +++ b/packages/cli/tests/harness-watch-host.test.mjs @@ -12,6 +12,7 @@ import { startHost } from "../src/host.mjs"; import { makeDeployment } from "../../discord/tests/helpers.mjs"; import { fixture, tmp } from "./helpers.mjs"; import { requestWatch } from "../../plugins/src/watch-request.mjs"; +import { pluginPaths } from "../../plugins/src/pinned.mjs"; import * as claude from "../../plugins/harness/claude-code/index.mjs"; function scratch(t) { @@ -462,3 +463,26 @@ test("W3 startHost gives the watch the instance root as its plugin root when the assert.equal(await host.close(0), 0); closed = true; }); + +test("W3 host watch: the default stat key reads the plugin root's plugins, and a record naming the plugin root is not written", async (t) => { + const dataRoot = scratch(t); + const pluginRoot = scratch(t); + const clock = fakeClock(); + const logs = []; + let line = "ok"; + const stub = stubWatch(() => ({ records: [record({ line })], transitions: [], refused: [], gone: [] })); + const handle = startHarnessWatch({ dataRoot, pluginRoot, clock, env: {}, log: (l) => logs.push(l), watch: stub.watch, processing: () => ({ halted: false }), scratchRoot: () => scratch(t) }); + t.after(() => handle.stop()); + await handle.settled(); + assert.equal(stub.calls.length, 1); + clock.fire(); await handle.settled(); + assert.equal(stub.calls.length, 1, "no change, no full pass"); + // A plugin lock that can't be read changes the plugin root's key (the loader refuses it): a full pass. + writeFileSync(pluginPaths(pluginRoot).lock, "{", { mode: 0o600 }); + line = `${pluginRoot}/plugins/pi`; + clock.fire(); await handle.settled(); + assert.equal(stub.calls.length, 2, "the key read the plugin root, so its change ran a full pass"); + assert.match(logs.join("\n"), /a state line held a host path or an env value/, "and the record that names the plugin root was not written"); + assert.ok(!logs.join("\n").includes(pluginRoot)); + assert.ok(!readFileSync(watchFile(dataRoot), "utf8").includes(pluginRoot)); +}); diff --git a/packages/plugins/src/harness-watch.mjs b/packages/plugins/src/harness-watch.mjs index a27ea9735..ab10cfb05 100644 --- a/packages/plugins/src/harness-watch.mjs +++ b/packages/plugins/src/harness-watch.mjs @@ -287,6 +287,9 @@ const STATE_MAX = 1024 * 1024; const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/; const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/; const FAILED_MAX = 32; +// At most this many entries, and records read: a file the host wrote holds one per harness module. +const ENTRIES_MAX = 64; +const RECORDS_MAX = 256; // One entry per harness: each name in names (the harnesses the loader gives, in its order), then // each other harness the file holds a record for. An entry is { name, state, version, checkedAt, @@ -294,31 +297,38 @@ const FAILED_MAX = 32; // file is missing, unreadable, larger than STATE_MAX, not JSON or not version 1's shape, or holds no // usable record for that harness. Never throws. The text fields are redacted again here, with this // process's environment, env and the paths given (the data roots): the file's writer redacted them -// once, and a file someone else wrote is not trusted to have. +// once, and a file someone else wrote is not trusted to have. A name the loader does not give that is +// an env value is dropped. At most ENTRIES_MAX entries, from the first RECORDS_MAX records. export function readWatchView({ dataRoot, names = [], env = process.env, paths = [] } = {}) { - const records = readState(dataRoot); - const order = []; - for (const n of Array.isArray(names) ? names : []) if (typeof n === "string" && NAME.test(n) && !order.includes(n)) order.push(n); + const records = readState(dataRoot).slice(0, RECORDS_MAX); + const order = new Set(); + for (const n of Array.isArray(names) ? names : []) if (typeof n === "string" && NAME.test(n) && order.size < ENTRIES_MAX) order.add(n); + const values = envValues(env); const byName = new Map(); for (const r of records) { if (!r || typeof r !== "object" || Array.isArray(r) || typeof r.harness !== "string" || !NAME.test(r.harness) || byName.has(r.harness)) continue; + if (!order.has(r.harness) && (values.has(r.harness) || order.size >= ENTRIES_MAX)) continue; byName.set(r.harness, r); - if (!order.includes(r.harness)) order.push(r.harness); + order.add(r.harness); } - let redact = null, values = null; + let redact = null; const view = (name) => { const r = byName.get(name); if (!r || !STATES.includes(r.state)) return unchecked(name); redact ??= redactor(env, null, [dataRoot, ...paths]); - values ??= envValues(env); const failed = Array.isArray(r.failed) ? [...new Set(r.failed.slice(0, FAILED_MAX).filter((id) => typeof id === "string" && RULE.test(id) && !values.has(id)))] : []; return { name, state: r.state, version: text(r.version, LABEL_MAX, redact), checkedAt: when(r.checkedAt), changedAt: when(r.changedAt), failed, line: text(r.line, LINE_MAX, redact) }; }; - return order.map(view); + return [...order].map(view); } const unchecked = (name) => ({ name, state: "unchecked", version: null, checkedAt: null, changedAt: null, failed: [], line: NOT_CHECKED }); -const when = (v) => (typeof v === "string" && ISO.test(v) && Number.isFinite(Date.parse(v)) ? v : null); +// A time is kept only when it is a real one: 2026-02-30 is not. +const when = (v) => { + if (typeof v !== "string" || !ISO.test(v)) return null; + const t = Date.parse(v); + return Number.isFinite(t) && new Date(t).toISOString().slice(0, 19) === v.slice(0, 19) ? v : null; +}; // The records of the state file, or [] for any problem. A link, a FIFO or a file over STATE_MAX is // not read. diff --git a/packages/plugins/tests/harness-watch-view.test.mjs b/packages/plugins/tests/harness-watch-view.test.mjs index b2bc38d9b..a7000282f 100644 --- a/packages/plugins/tests/harness-watch-view.test.mjs +++ b/packages/plugins/tests/harness-watch-view.test.mjs @@ -107,3 +107,15 @@ test("W3 readWatchView redacts again: the data roots, the home directory, PATH e assert.deepEqual(e.failed, ["--tools"]); assert.match(e.line, //); }); + +test("W3 readWatchView: a name that is an env value is dropped unless the loader gives it, entries are capped, and an impossible date is not a time", (t) => { + const dir = root(t); + const env = { W3_NAME: "w3-secret-name" }; + const many = Array.from({ length: 300 }, (_, i) => rec(`w3-h${i}`)); + put(dir, { version: 1, harnesses: [rec("w3-secret-name"), rec("pi", { checkedAt: "2026-02-30T00:00:00Z", changedAt: "2026-11-20T10:00:00Z" }), ...many] }); + const view = readWatchView({ dataRoot: dir, names: ["pi"], env }); + assert.ok(!view.some((e) => e.name === "w3-secret-name"), "a file-only name equal to an env value does not reach the answer"); + assert.equal(view.length, 64, "at most 64 entries"); + assert.deepEqual([view[0].checkedAt, view[0].changedAt], [null, "2026-11-20T10:00:00Z"], "2026-02-30 is not a time; a real one is kept"); + assert.equal(readWatchView({ dataRoot: dir, names: ["w3-secret-name"], env })[0].state, "fit", "a name the loader gives is kept"); +}); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 79b14bf3d..8ad5202dd 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1314,7 +1314,8 @@ fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{if(epoch!==orgEpoch)return;harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{if(epoch!==orgEpoch)return;harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);}); } // #1873 W3: one line per harness, from what the bus host's harness watch last wrote (the plugins - // answer's harnessWatch, read only). Red and missing read as a problem; a harness the watch has + // answer's harnessWatch, read only). Red and missing read as a problem, in the danger colour r3 + // gives "can't start" (new launches on them refuse); a harness the watch has // not checked reads "not checked yet", never fit. A bus that gives no harnessWatch gets one line. const WATCH_WORD={fit:'fit',changed:'fit',red:'red',unknown:'unknown',missing:'missing'}; function harnessWatchLine(e){ @@ -1325,7 +1326,7 @@ parts.push(WATCH_WORD[e.state]); if(['red','missing','unknown'].includes(e.state)&&typeof e.line==='string'&&e.line)parts.push(txt(e.line)); if(e.state==='red')parts.push('new launches refuse'); - return `
  • ${parts.join(' · ')}
  • `; + return `
  • ${parts.join(' · ')}
  • `; } const harnessWatchLines=v=>{const list=Array.isArray(v.harnessWatch)?v.harnessWatch.filter(e=>e&&typeof e==='object'&&typeof e.name==='string'&&e.name):null; return list===null?'

    What the harness check found could not be read.

    ':list.length?``:'';}; diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index f766f4209..e858a1fc8 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -390,7 +390,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .settings-content fieldset.harness-control>:is(button,p){flex-basis:100%} .settings-content fieldset.harness-control>ul.harness-watch{flex-basis:100%;margin:0;padding:0;list-style:none;display:grid;gap:4px} .settings-content fieldset.harness-control>ul.harness-watch>li{margin:0;overflow-wrap:anywhere} -.settings-content fieldset.harness-control>ul.harness-watch>li.warn{color:var(--warning);font-weight:600} +.settings-content fieldset.harness-control>ul.harness-watch>li.danger{color:var(--danger);font-weight:600} /* #1873 settings slice 5: an organization's one choice (mockup org-models). A choice not built yet is dashed and disabled. */ /* settings-s5 review P3-4: the choice cards sit in the form column, as .settings-form does. */ .settings-content fieldset.models-source{display:grid;gap:8px;max-width:28rem} diff --git a/packages/webui/tests/routes-harness-watch-browser.test.mjs b/packages/webui/tests/routes-harness-watch-browser.test.mjs index 4b41c7323..4ecddd3c6 100644 --- a/packages/webui/tests/routes-harness-watch-browser.test.mjs +++ b/packages/webui/tests/routes-harness-watch-browser.test.mjs @@ -21,20 +21,21 @@ const watch = [ ]; const settings = (extra) => ({ business: 'acme', revision: initial.revision, plugins: { harness: ['pi'] }, available: { harness: ['pi', 'claude-code'] }, ...extra }); -async function routing(view, shot) { +async function routing(view, shot, act = null) { const web = await startServer({ port: 0, board: 'http://127.0.0.1:9', bus: { messages: async () => ({ messages: [], unread: 0 }), usage: async () => { throw Error('fixture'); }, routes: async () => initial }, reads: { settings: () => ({ business: 'acme', release: 'fixture', notifier: {} }) }, log() {} }); let b; try { b = await browser(); const errors = []; b.on('Runtime.exceptionThrown', x => errors.push(x.exceptionDetails?.exception?.description ?? x.exceptionDetails?.text)); - await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.routeView=${JSON.stringify(initial)};window.harnessView=${JSON.stringify(view)};const original=window.fetch;window.fetch=async(u,o={})=>{if(u==='/api/config')return new Response(JSON.stringify({send:true}));if(u==='/api/proxy/plugins')return new Response(JSON.stringify(harnessView));if(u==='/api/bus/routes')return new Response(JSON.stringify({rows:[routeView],at:new Date().toISOString()}));return original(u,o);};` }); + await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.routeView=${JSON.stringify(initial)};window.harnessView=${JSON.stringify(view)};const original=window.fetch;window.fetch=async(u,o={})=>{if(u==='/api/config')return new Response(JSON.stringify({send:true}));if(u==='/api/proxy/plugins')return new Response(JSON.stringify(harnessView));if(u==='/api/bus/routes')return new Response(JSON.stringify({rows:[routeView],at:new Date().toISOString()}));if(u==='/api/proxy/plugins/set')return new Response(JSON.stringify(window.saveAnswer));return original(u,o);};` }); const wait = expr => b.evaluate(`(async()=>{for(let n=0;n<500;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,20));}throw Error('wait: '+${JSON.stringify(expr)});})()`); if (shot) await b.viewport(1440, 900); await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/routing`); await wait('!!document.querySelector("#harness-save")'); + if (act) await act(b, wait); const page = await b.evaluate(`(()=>{const f=document.querySelector("fieldset.harness-control");return { - lines:[...f.querySelectorAll("ul.harness-watch>li")].map(li=>({state:li.dataset.watchState,text:li.textContent,warn:li.classList.contains("warn"),muted:li.classList.contains("muted"),color:getComputedStyle(li).color})), + lines:[...f.querySelectorAll("ul.harness-watch>li")].map(li=>({state:li.dataset.watchState,text:li.textContent,danger:li.classList.contains("danger"),muted:li.classList.contains("muted"),color:getComputedStyle(li).color})), none:f.querySelector(".harness-watch-none")?.textContent??null, label:f.querySelector("ul.harness-watch")?.getAttribute("aria-label")??null, text:f.textContent, @@ -62,8 +63,8 @@ test('W3 Routing shows one line per harness for each watch state, red and missin assert.equal(unknown.text, 'w3-unknown 0.9.0 · checked 4 min ago · unknown · the fit check could not run'); assert.equal(unchecked.text, 'w3-new · not checked yet'); assert.equal(odd.text, 'w3-odd · not checked yet', 'a state the page does not know is not checked yet, not its line and not fit'); - for (const l of [red, missing]) assert.ok(l.warn && !l.muted, `${l.state} reads as a problem`); - for (const l of [fit, changed, unknown, unchecked, odd]) assert.ok(!l.warn && l.muted, `${l.state} is not a problem line`); + for (const l of [red, missing]) assert.ok(l.danger && !l.muted, `${l.state} reads as a problem`); + for (const l of [fit, changed, unknown, unchecked, odd]) assert.ok(!l.danger && l.muted, `${l.state} is not a problem line`); assert.notEqual(red.color, page.muted, 'a problem line is not drawn in the muted colour'); for (const l of [unknown, unchecked, odd]) assert.doesNotMatch(l.text, /· fit\b/, `${l.state} never reads as fit`); }); @@ -86,3 +87,16 @@ test('W3 Routing: a bus-authored line or version is shown as text, never as mark assert.match(page.lines[0].text, /1<\/b>/); assert.match(page.lines[0].text, / { + const save = (answer) => async (b, wait) => { + await b.evaluate(`window.saveAnswer=${JSON.stringify(answer)};document.querySelector("[data-harness=claude-code]").click();document.querySelector("#harness-save").click();true`); + await wait('document.querySelector("#harness-status")?.textContent.includes("Harnesses saved")'); + }; + const saved = { business: 'acme', revision: 'c'.repeat(64), plugins: { harness: ['pi', 'claude-code'] }, transaction: 'fixture' }; + const kept = await routing(settings({ harnessWatch: watch.slice(0, 3) }), null, save(saved)); + assert.equal(kept.none, null, 'a save answer with no harnessWatch keeps the lines read before'); + assert.deepEqual(kept.lines.map(l => l.state), ['fit', 'changed', 'red']); + const fresh = await routing(settings({ harnessWatch: watch.slice(0, 3) }), null, save({ ...saved, harnessWatch: [watch[3]] })); + assert.deepEqual(fresh.lines.map(l => l.state), ['missing'], 'a save answer with harnessWatch shows its lines'); +});