From a284774f05730ad74c9e886b3004027106c1000a Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 17:00:54 +0000 Subject: [PATCH 001/129] test(hosts): drive daemon channel tests with pi --mode rpc frames The fake child now answers the daemon's startup get_state instead of a runner hello, and commands, replies and events use pi's flat frames. Runner-only checks (channel protocol version, delta/full event filter switching) are removed. Update fixtures also name the tau repository. --- lib/hosts/daemon-channels.test.mjs | 148 +++++++++++++---------------- lib/hosts/updates.test.mjs | 25 ++--- lib/self-update.test.mjs | 4 +- 3 files changed, 82 insertions(+), 95 deletions(-) diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index 09d0f393..0e68a9ec 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -13,16 +13,20 @@ const MOVED = "22222222-2222-4222-8222-222222222222"; const launch = { cwd: "/tmp", recordedCwd: null, sessionFile: "/tmp/s.jsonl", advisor: false }; /** Commands the daemon sends on its own: the fake child answers them, never a link's. */ const DAEMON_OPS = new Set(["set_event_filter", "set_subagent_subscription", "set_host_tools", "set_host_uri_schemes"]); -const cmd = (id, op, args = {}) => JSON.stringify({ t: "cmd", id, op, args }); -const ev = (child, event) => child.emit({ t: "event", event }); +/** Lines the daemon forwards to the child that answer a request rather than issue a command. */ +const REPLIES = new Set(["ui_response", "extension_ui_response", "host_tool_result", "host_uri_result"]); +const cmd = (id, op, args = {}) => JSON.stringify({ ...args, type: op, id }); +const ev = (child, event) => child.emit(event); +const res = (id, data, extra = {}) => ({ type: "response", id, success: true, ...(data === undefined ? {} : { data }), ...extra }); /** The commands links sent, as the child received them (ids remapped by the daemon). */ -const own = child => child.writes.filter(frame => frame.t === "cmd" && !DAEMON_OPS.has(frame.op) && frame.args?.message !== RESUME_PROMPT); +/** The daemon's own startup `get_state` is the first line it writes; anything else a link sent. */ +const own = child => child.writes.filter(frame => !REPLIES.has(frame.type) && frame !== child.writes[0] && !DAEMON_OPS.has(frame.type) && frame.message !== RESUME_PROMPT); const stdoutFrames = (h, linkId) => h.output.filter(item => item.body.type === "stdout" && (linkId === undefined || item.id === linkId)).map(item => JSON.parse(item.body.line)); -/** `hello`: fields the child's first line overrides (a wrong `proto`). */ -function harness(launchAdvisor = false, hello = {}) { +/** `state`: fields the child's startup `get_state` answer overrides. */ +function harness(launchAdvisor = false, state = {}) { const children = [], output = [], changed = [], logs = []; - // What a spawned child does first; a test may replace it (exit during startup, for one). - const hooks = { startup: (child, request) => child.emit({ t: "hello", proto: 1, pid: 1, sessionId: request.sessionFile ? SAVED : randomUUID(), sessionFile: request.sessionFile, cwd: request.cwd, ...hello }) }; + // How a spawned child answers the daemon's startup `get_state`; a test may replace it (exit during startup, for one). + const hooks = { startup: (child, request, probe) => child.emit(res(probe.id, { sessionId: request.sessionFile ? SAVED : randomUUID(), sessionFile: request.sessionFile, cwd: request.cwd, ...state }, { command: "get_state" })) }; const links = ["l1", "l2"].map(id => ({ id, version: LINK_PROTOCOL_VERSION, isUp: () => true, queue(body, key) { output.push({ id, body, key }); return 1; }, output(body) { output.push({ id, body }); }, discard() {} })); async function spawn(request) { @@ -30,8 +34,9 @@ function harness(launchAdvisor = false, hello = {}) { const transport = { write(line, callback) { const frame = JSON.parse(line); writes.push(frame); callback?.(null); - if (frame.t === "cmd" && !hooks.holdDaemonReplies && (DAEMON_OPS.has(frame.op) || frame.args?.message === RESUME_PROMPT)) { - queueMicrotask(() => listeners.line?.(JSON.stringify({ t: "res", id: frame.id, ok: true, data: {} }))); + if (writes.length === 1 && frame.type === "get_state") setTimeout(() => hooks.startup(child, request, frame), 0); + else if (!REPLIES.has(frame.type) && !hooks.holdDaemonReplies && (DAEMON_OPS.has(frame.type) || frame.message === RESUME_PROMPT)) { + queueMicrotask(() => listeners.line?.(JSON.stringify(res(frame.id, {})))); } }, killTree(force) { child.kills.push(force); if (!child.holdExit) child.exit(force); }, @@ -40,7 +45,6 @@ function harness(launchAdvisor = false, hello = {}) { }; const child = { request, transport, writes, kills: [], holdExit: false, exit(force = false) { for (const exit of exits) exit(0, force ? "SIGKILL" : null); }, emit(frame) { listeners.line?.(JSON.stringify(frame)); }, stderr(chunk) { listeners.stderr?.(chunk); } }; children.push(child); - setTimeout(() => hooks.startup(child, request), 0); return { transport, cwd: request.cwd, fellBack: false, launchAdvisor }; } const table = new ChannelTable({ sessionId: () => SAVED, prepareLaunch: x => x, log: message => logs.push(message), channelsChanged: ch => changed.push(ch), spawn }); @@ -54,9 +58,9 @@ test("concurrent opens spawn once; command order and replies stay source-owned", // Both links number their commands 1: the daemon gives each its own id toward the child and restores the link's on the reply. h.table.stdin(h.a, a.ch, cmd(1, "get_messages", { who: "a" })); h.table.stdin(h.b, a.ch, cmd(1, "get_messages", { who: "b" })); const sent = own(h.children[0]); - assert.deepEqual(sent.map(frame => frame.args.who), ["a", "b"]); + assert.deepEqual(sent.map(frame => frame.who), ["a", "b"]); assert.notEqual(sent[0].id, sent[1].id); - for (const frame of sent) h.children[0].emit({ t: "res", id: frame.id, ok: true, data: { who: frame.args.who } }); + for (const frame of sent) h.children[0].emit(res(frame.id, { who: frame.who })); assert.deepEqual(stdoutFrames(h).map(frame => [frame.id, frame.data.who]), [[1, "a"], [1, "b"]]); assert.deepEqual(h.output.map(item => item.id), ["l1", "l2"]); assert.throws(() => h.table.stdin({ ...h.a, id: "guessed" }, a.ch, cmd(1, "get_messages"))); @@ -85,10 +89,10 @@ test("an idle advisor replacement fences opens and correlates late stdin refusal assert.deepEqual(old.kills, [false]); h.table.stdin(h.a, first.ch, cmd("late-prompt", "prompt", { message: "must not disappear" })); const refused = stdoutFrames(h).find(frame => frame.id === "late-prompt"); - assert.equal(refused.t, "res"); - assert.equal(refused.ok, false); + assert.equal(refused.type, "response"); + assert.equal(refused.success, false); assert.equal(refused.code, "session_restarting"); - assert.equal(old.writes.some(frame => frame.args?.message === "must not disappear"), false); + assert.equal(old.writes.some(frame => frame.message === "must not disappear"), false); let joined = false; const joining = h.table.open(h.a, { sessionId: SAVED, launch }).then(result => { joined = true; return result; }); await new Promise(resolve => setTimeout(resolve, 0)); @@ -111,10 +115,10 @@ test("advisor changes never replace a peer command, unsettled background work, d h.table.release(h.a, first.ch); const child = h.children[0]; if (phase === "command" || phase === "acknowledged") h.table.stdin(h.a, first.ch, cmd("peer-prompt", "prompt", { message: "work" })); - if (phase === "acknowledged") child.emit({ t: "res", id: own(child)[0].id, ok: true, data: { agentInvoked: true } }); + if (phase === "acknowledged") child.emit(res(own(child)[0].id, { agentInvoked: true })); if (phase === "running" || phase === "unsettled") ev(child, { type: "agent_start" }); if (phase === "unsettled") ev(child, { type: "agent_end", isTerminal: true }); - if (phase === "dialog") child.emit({ t: "ui_request", id: 1, method: "ask", args: {} }); + if (phase === "dialog") child.emit({ type: "ui_request", id: 1, method: "ask", args: {} }); if (phase === "preparing") h.table.setInterest(h.a, first.ch, false, true); const joined = await h.table.open(h.b, { sessionId: SAVED, launch: { ...launch, advisor: true }, replaceAdvisor: true }); assert.equal(joined.ch, first.ch, phase); @@ -127,15 +131,15 @@ test("advisor changes never replace a peer command, unsettled background work, d test("join captures full stream and dialogs before later deltas; first answer closes the other UI", async () => { const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); const child = h.children[0]; ev(child, { type: "message_start", messageId: "m", message: { role: "assistant", content: [{ type: "text", text: "one" }] } }); - child.emit({ t: "ui_request", id: 1, method: "ask", args: {} }); + child.emit({ type: "ui_request", id: 1, method: "ask", args: {} }); const b = await h.table.open(h.b, { sessionId: SAVED, launch }); - assert.equal(JSON.parse(b.streaming).event.message.content[0].text, "one"); assert.equal(JSON.parse(b.pending[0]).id, 1); + assert.equal(JSON.parse(b.streaming).message.content[0].text, "one"); assert.equal(JSON.parse(b.pending[0]).id, 1); ev(child, { type: "message_update", messageId: "m", message: { role: "assistant" }, assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "two" } }); assert.equal(h.output.filter(x => x.id === "l2").length, 0); h.table.release(h.b, b.ch); assert.equal(h.output.filter(x => x.id === "l2").length, 1); - h.table.stdin(h.b, b.ch, JSON.stringify({ t: "ui_response", id: 1, value: "x" })); h.table.stdin(h.a, a.ch, JSON.stringify({ t: "ui_response", id: 1, value: "y" })); - assert.equal(child.writes.filter(frame => frame.t === "ui_response").length, 1); - assert.ok(h.output.some(x => x.id === "l1" && x.body.type === "stdout" && JSON.parse(x.body.line).t === "ui_end" && JSON.parse(x.body.line).id === 1)); + h.table.stdin(h.b, b.ch, JSON.stringify({ type: "ui_response", id: 1, value: "x" })); h.table.stdin(h.a, a.ch, JSON.stringify({ type: "ui_response", id: 1, value: "y" })); + assert.equal(child.writes.filter(frame => frame.type === "ui_response").length, 1); + assert.ok(h.output.some(x => x.id === "l1" && x.body.type === "stdout" && JSON.parse(x.body.line).type === "ui_end" && JSON.parse(x.body.line).id === 1)); await h.table.stop(); }); @@ -145,25 +149,23 @@ test("a private res is never broadcast; a session frame after a persistence noti ev(h.children[0], { type: "notice", source: "session-persistence", level: "info" }); h.output.length = 0; h.table.stdin(h.a, a.ch, cmd("a", "get_state_probe")); - h.children[0].emit({ t: "res", id: own(h.children[0])[0].id, ok: true, data: { pad: "x".repeat(1100000) } }); + h.children[0].emit(res(own(h.children[0])[0].id, { pad: "x".repeat(1100000) })); assert.equal(h.output.filter(x => x.id === "l2").length, 0); assert.deepEqual(h.output.filter(x => x.id === "l1").map(x => JSON.parse(x.body.line).id), ["a"]); - h.children[0].emit({ t: "session", sessionId: MOVED, sessionFile: "/tmp/moved.jsonl" }); + h.children[0].emit({ type: "session", sessionId: MOVED, sessionFile: "/tmp/moved.jsonl" }); assert.equal((await h.table.open(h.b, { sessionId: SAVED, launch })).ch, a.ch); assert.equal((await h.table.open(h.b, { sessionId: MOVED, launch: { ...launch, sessionFile: "/tmp/moved.jsonl" } })).ch, a.ch); assert.equal(h.table.listing(h.a)[0].sessionId, MOVED); assert.equal(h.children.length, 1); await h.table.stop(); }); -test("startup sets global settings once for two members; links may not send daemon-owned ops", async () => { +test("startup reads the state once for two members; links may not send daemon-owned ops", async () => { const h = harness(); const a = await h.table.open(h.a, { sessionId: SAVED, launch }); await h.table.open(h.b, { sessionId: SAVED, launch }); - assert.deepEqual(h.children[0].writes.map(frame => [frame.t, frame.op]), [["cmd", "set_event_filter"], ["cmd", "set_subagent_subscription"]]); - assert.deepEqual(h.children[0].writes[0].args, { events: null, messageUpdates: "delta" }); - assert.deepEqual(h.children[0].writes[1].args, { level: "events" }); + assert.deepEqual(h.children[0].writes.map(frame => frame.type), ["get_state"]); for (const op of DAEMON_OPS) assert.throws(() => h.table.stdin(h.a, a.ch, cmd(1, op)), { code: "invalid_request" }); - assert.equal(h.children[0].writes.length, 2); + assert.equal(h.children[0].writes.length, 1); assert.deepEqual(h.output, []); h.table.release(h.a, a.ch); await h.table.stop(); }); @@ -182,44 +184,26 @@ test("only a rejoining member that lost no output is told its stream is continuo await h.table.stop(); }); -test("open never waits on a runner that answers startup commands late; replies nobody owns never reach a member", async () => { - const h = harness(); h.hooks.holdDaemonReplies = true; +test("replies nobody owns never reach a member", async () => { + const h = harness(); const a = await h.table.open(h.a, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); const child = h.children[0]; h.table.stdin(h.a, a.ch, cmd(1, "get_state")); - // Late answers to timed-out startup commands: ids the daemon no longer owns. - child.emit({ t: "res", id: 1, ok: true }); child.emit({ t: "res", id: 2, ok: true }); child.emit({ t: "res", id: 99, ok: true }); + // A repeated answer to the daemon's own startup get_state, and an id nobody sent. + child.emit(res(child.writes[0].id)); child.emit(res("99")); assert.deepEqual(stdoutFrames(h), []); - child.emit({ t: "res", id: own(child)[0].id, ok: true, data: { state: true } }); + child.emit(res(own(child)[0].id, { state: true })); assert.deepEqual(stdoutFrames(h).map(frame => [frame.id, frame.data]), [[1, { state: true }]]); await h.table.stop(); }); -test("a child that speaks another channel protocol fails startup and is killed", async () => { - const h = harness(false, { proto: 2 }); - await assert.rejects(h.table.open(h.a, { sessionId: SAVED, launch }), { code: "host_process_exited" }); - assert.deepEqual(h.children[0].kills, [true]); - assert.deepEqual(h.children[0].writes, [], "no setting is sent to a child of an unknown protocol"); - assert.equal(h.table.size, 0); - await h.table.stop(); -}); - -test("a message_update the snapshot cannot apply moves the child to full updates once", async () => { - const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); - const orphan = { type: "message_update", messageId: "m", message: { role: "assistant" }, assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "x" } }; - ev(h.children[0], orphan); ev(h.children[0], orphan); - await new Promise(resolve => setTimeout(resolve, 0)); - assert.deepEqual(h.children[0].writes.filter(frame => frame.op === "set_event_filter").map(frame => frame.args.messageUpdates), ["delta", "full"]); - await h.table.stop(); -}); - test("closing one membership neither kills the child nor broadcasts its late reply", async () => { const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); await h.table.open(h.b, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); h.table.release(h.b, a.ch); h.table.stdin(h.a, a.ch, cmd("old", "get_messages")); h.table.stdin(h.b, a.ch, cmd("old", "get_messages")); // The other link's own numbering never collides. const [first] = own(h.children[0]); - h.table.close(h.a, a.ch); h.children[0].emit({ t: "res", id: first.id, ok: true, data: {} }); + h.table.close(h.a, a.ch); h.children[0].emit(res(first.id, {})); assert.deepEqual(h.output, []); assert.equal(h.table.size, 1); assert.equal((await h.table.open(h.a, { sessionId: SAVED, launch })).joined, true); await h.table.stop(); @@ -242,8 +226,8 @@ test("recovery and two server opens share one spawn and one daemon-owned resume h.table.open(h.b, { sessionId: SAVED, launch }), ]); assert.equal(h.children.length, 1); - const prompts = h.children[0].writes.filter(frame => frame.op === "prompt"); - assert.equal(prompts.length, 1); assert.equal(prompts[0].args.message, RESUME_PROMPT); assert.deepEqual(h.output, []); + const prompts = h.children[0].writes.filter(frame => frame.type === "prompt"); + assert.equal(prompts.length, 1); assert.equal(prompts[0].message, RESUME_PROMPT); assert.deepEqual(h.output, []); await h.table.stop(); }); @@ -253,14 +237,14 @@ test("only the chosen callback executor receives the request but both members re for (const link of [h.a, h.b]) h.table.setTools(link, a.ch, [{ name: "open_url" }], []); await new Promise(resolve => setImmediate(resolve)); // omp answers set_host_tools before it can call the tool h.table.stdin(h.b, a.ch, cmd("p", "prompt", { message: "open" })); - h.children[0].emit({ t: "host_tool_call", id: 7, toolName: "open_url", arguments: {} }); + h.children[0].emit({ type: "host_tool_call", id: 7, toolName: "open_url", arguments: {} }); // The non-prompting member sees only the daemon's peer-admission marker, never the callback. - assert.deepEqual(h.output.map(item => [item.id, JSON.parse(item.body.line).t]), [["l1", "peer_message_command"], ["l2", "host_tool_call"]]); - h.table.stdin(h.a, a.ch, JSON.stringify({ t: "host_tool_result", id: 7, result: "no" })); - h.table.stdin(h.b, a.ch, JSON.stringify({ t: "host_tool_result", id: 7, result: "yes" })); - assert.deepEqual(h.children[0].writes.filter(frame => frame.t === "host_tool_result").map(({ id, result }) => ({ id, result })), [{ id: 7, result: "yes" }]); + assert.deepEqual(h.output.map(item => [item.id, JSON.parse(item.body.line).type]), [["l1", "peer_message_command"], ["l2", "host_tool_call"]]); + h.table.stdin(h.a, a.ch, JSON.stringify({ type: "host_tool_result", id: 7, result: "no" })); + h.table.stdin(h.b, a.ch, JSON.stringify({ type: "host_tool_result", id: 7, result: "yes" })); + assert.deepEqual(h.children[0].writes.filter(frame => frame.type === "host_tool_result").map(({ id, result }) => ({ id, result })), [{ id: 7, result: "yes" }]); ev(h.children[0], { type: "tool_execution_end", toolCallId: 7, toolName: "open_url", result: "yes" }); - assert.deepEqual(h.output.filter(item => JSON.parse(item.body.line).event?.type === "tool_execution_end").map(item => item.id), ["l1", "l2"]); + assert.deepEqual(h.output.filter(item => JSON.parse(item.body.line).type === "tool_execution_end").map(item => item.id), ["l1", "l2"]); await h.table.stop(); }); @@ -270,10 +254,10 @@ test("a prompt_result returns under the sending link's own id, to that link only h.table.stdin(h.a, a.ch, cmd(1000, "prompt", { message: "hi" })); const [sent] = own(h.children[0]); assert.notEqual(sent.id, 1000); - h.children[0].emit({ t: "res", id: sent.id, ok: true, data: { agentInvoked: true } }); - h.children[0].emit({ t: "prompt_result", id: sent.id, text: "done" }); - const results = h.output.filter(item => item.body.type === "stdout" && ["res", "prompt_result"].includes(JSON.parse(item.body.line).t)); - assert.deepEqual(results.map(item => [item.id, JSON.parse(item.body.line).t, JSON.parse(item.body.line).id]), [["l1", "res", 1000], ["l1", "prompt_result", 1000]]); + h.children[0].emit(res(sent.id, { agentInvoked: true })); + h.children[0].emit({ type: "prompt_result", id: sent.id, text: "done" }); + const results = h.output.filter(item => item.body.type === "stdout" && ["response", "prompt_result"].includes(JSON.parse(item.body.line).type)); + assert.deepEqual(results.map(item => [item.id, JSON.parse(item.body.line).type, JSON.parse(item.body.line).id]), [["l1", "response", 1000], ["l1", "prompt_result", 1000]]); await h.table.stop(); }); @@ -282,13 +266,13 @@ test("a prompt's outcome reaches the other members uncorrelated, so the elected await h.table.open(h.b, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); h.table.release(h.b, a.ch); h.table.stdin(h.a, a.ch, cmd(1000, "prompt", { message: "hi" })); h.table.stdin(h.a, a.ch, cmd(1001, "prompt", { message: "again" })); const [first, second] = own(h.children[0]); - h.children[0].emit({ t: "prompt_result", id: first.id, agentInvoked: true, status: "error", error: { message: "boom" } }); - h.children[0].emit({ t: "prompt_error", id: second.id, command: "prompt", error: "No API key" }); - const outcomes = frames => frames.filter(frame => ["prompt_result", "prompt_error", "peer_prompt_outcome"].includes(frame.t)); - assert.deepEqual(outcomes(stdoutFrames(h, "l1")).map(frame => [frame.t, frame.id]), [["prompt_result", 1000], ["prompt_error", 1001]]); + h.children[0].emit({ type: "prompt_result", id: first.id, agentInvoked: true, status: "error", error: { message: "boom" } }); + h.children[0].emit({ type: "prompt_error", id: second.id, command: "prompt", error: "No API key" }); + const outcomes = frames => frames.filter(frame => ["prompt_result", "prompt_error", "peer_prompt_outcome"].includes(frame.type)); + assert.deepEqual(outcomes(stdoutFrames(h, "l1")).map(frame => [frame.type, frame.id]), [["prompt_result", 1000], ["prompt_error", 1001]]); assert.deepEqual(outcomes(stdoutFrames(h, "l2")), [ - { t: "peer_prompt_outcome", outcome: { t: "prompt_result", agentInvoked: true, status: "error", error: { message: "boom" } } }, - { t: "peer_prompt_outcome", outcome: { t: "prompt_error", command: "prompt", error: "No API key" } }, + { type: "peer_prompt_outcome", outcome: { type: "prompt_result", agentInvoked: true, status: "error", error: { message: "boom" } } }, + { type: "peer_prompt_outcome", outcome: { type: "prompt_error", command: "prompt", error: "No API key" } }, ]); await h.table.stop(); }); @@ -346,7 +330,7 @@ for (const operation of ["open", "delete"]) { const h = harness(); try { const original = await h.table.open(h.a, { sessionId: SAVED, launch: { ...launch, sessionFile: parent } }); - h.children[0].emit({ t: "session", sessionId: MOVED, sessionFile: fork }); + h.children[0].emit({ type: "session", sessionId: MOVED, sessionFile: fork }); if (operation === "open") { const reopened = await h.table.open(h.b, { sessionId: SAVED, launch: { ...launch, sessionFile: parent } }); assert.notEqual(reopened.ch, original.ch); @@ -372,7 +356,7 @@ test("a native copy-on-write move retains aliases even while the original file s try { const opened = await h.table.open(h.a, { sessionId: SAVED, launch: { ...launch, sessionFile: parent } }); ev(h.children[0], { type: "notice", source: "session-persistence", level: "info", message: "Session moved" }); - h.children[0].emit({ t: "session", sessionId: MOVED, sessionFile: moved }); + h.children[0].emit({ type: "session", sessionId: MOVED, sessionFile: moved }); assert.equal((await h.table.open(h.b, { sessionId: SAVED, launch: { ...launch, sessionFile: parent } })).ch, opened.ch); assert.equal((await h.table.open(h.b, { sessionId: MOVED, launch: { ...launch, sessionFile: moved } })).ch, opened.ch); assert.equal(h.children.length, 1); @@ -414,7 +398,7 @@ test("destructive operations on an old copy-on-write file never retarget its liv try { await h.table.open(h.a, { sessionId: SAVED, launch: { ...launch, sessionFile: original } }); ev(h.children[0], { type: "notice", source: "session-persistence", level: "info", message: "Session moved" }); - h.children[0].emit({ t: "session", sessionId: MOVED, sessionFile: moved }); + h.children[0].emit({ type: "session", sessionId: MOVED, sessionFile: moved }); let requested; await h.table.mutateSession(SAVED, async id => { requested = id; }); assert.equal(requested, SAVED); @@ -448,7 +432,7 @@ test("a recovering run is protected from a competing advisor open before its res assert.equal(h.children.length, 1); assert.equal(joined.advisorSpawned, false); assert.deepEqual(h.children[0].kills, []); - assert.equal(h.children[0].writes.filter(frame => frame.op === "prompt").length, 1); + assert.equal(h.children[0].writes.filter(frame => frame.type === "prompt").length, 1); await h.table.stop(); }); @@ -460,7 +444,7 @@ test("a session frame updates the listing even in the middle of a run", async () const child = h.children[0]; ev(child, { type: "agent_start" }); ev(child, { type: "notice", source: "session-persistence", level: "info", message: "Session moved" }); - child.emit({ t: "session", sessionId: MOVED, sessionFile: "/tmp/moved-mid-run.jsonl" }); + child.emit({ type: "session", sessionId: MOVED, sessionFile: "/tmp/moved-mid-run.jsonl" }); assert.equal(h.table.listing(h.a)[0].sessionId, MOVED); assert.equal(h.children.length, 1); } finally { await h.table.stop(); } @@ -469,7 +453,7 @@ test("a session frame updates the listing even in the middle of a run", async () test("a history-edit lease refuses a competing editor and other links' mutations until released, dropped or closed", async () => { const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); await h.table.open(h.b, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); h.table.release(h.b, a.ch); - const prompts = () => h.children[0].writes.filter(frame => frame.op === "prompt").map(frame => frame.args.message); + const prompts = () => h.children[0].writes.filter(frame => frame.type === "prompt").map(frame => frame.message); h.table.editLease(h.a, a.ch, true); assert.throws(() => h.table.editLease(h.b, a.ch, true), { status: 409, code: "session_busy" }, "a competing editor fails before its preflight"); h.table.editLease(h.b, a.ch, false); // Releasing a lease it does not hold changes nothing. @@ -477,7 +461,7 @@ test("a history-edit lease refuses a competing editor and other links' mutations h.table.stdin(h.b, a.ch, cmd("read", "get_messages")); h.table.stdin(h.a, a.ch, cmd("edit", "prompt", { message: "edit" })); assert.deepEqual(prompts(), ["edit"]); - assert.ok(h.children[0].writes.some(frame => frame.op === "get_messages"), "reads are never fenced"); + assert.ok(h.children[0].writes.some(frame => frame.type === "get_messages"), "reads are never fenced"); const refused = stdoutFrames(h, "l2").find(frame => frame.id === "peer"); assert.equal(refused?.code, "session_busy"); h.table.editLease(h.a, a.ch, false); @@ -503,7 +487,7 @@ test("an exit between join and the open result's release still reaches the joini test("a reopen keeps this link's queued command replies and drops output its snapshot supersedes", async () => { const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); h.table.stdin(h.a, a.ch, cmd("q", "get_messages")); - h.children[0].emit({ t: "res", id: own(h.children[0])[0].id, ok: true, data: {} }); + h.children[0].emit(res(own(h.children[0])[0].id, {})); ev(h.children[0], { type: "notice", message: "stale" }); await h.table.open(h.a, { sessionId: SAVED, launch, expectedChannel: a.ch }); h.table.release(h.a, a.ch); h.table.release(h.a, a.ch); @@ -610,8 +594,8 @@ test("a session-file move keeps the credentials server in the recorded launch", h.a.version = 9; h.a.login = { url: "https://a.example", token: "a" }; const opened = await h.table.open(h.a, { sessionId: SAVED, launch: { ...launch, shareCredentials: true } }); h.table.release(h.a, opened.ch); - h.children[0].emit({ t: "session", sessionId: MOVED, sessionFile: "/tmp/moved.jsonl", cwd: "/tmp" }); - h.children[0].emit({ t: "event", event: { type: "agent_start" } }); + h.children[0].emit({ type: "session", sessionId: MOVED, sessionFile: "/tmp/moved.jsonl", cwd: "/tmp" }); + h.children[0].emit({ type: "agent_start" }); await new Promise(resolve => setTimeout(resolve, 0)); assert.deepEqual(h.table.running().map(({ sessionId, launch: recorded }) => [sessionId, recorded.sessionFile, recorded.credentialsServer]), [[MOVED, "/tmp/moved.jsonl", "https://a.example"]]); @@ -644,7 +628,7 @@ test("an omp that exits during startup logs the last 500 bytes of its stderr to test("stderr is dropped once startup settles and never logged on a later exit", async (t) => { const h = harness(); t.after(() => h.table.stop()); - h.hooks.startup = (child, request) => { child.stderr("early text"); child.emit({ t: "hello", proto: 1, pid: 1, sessionId: SAVED, sessionFile: request.sessionFile, cwd: request.cwd }); }; + h.hooks.startup = (child, request, probe) => { child.stderr("early text"); child.emit(res(probe.id, { sessionId: SAVED, sessionFile: request.sessionFile, cwd: request.cwd }, { command: "get_state" })); }; const opened = await h.table.open(h.a, { sessionId: SAVED, launch }); h.table.release(h.a, opened.ch); h.children[0].stderr("late text"); diff --git a/lib/hosts/updates.test.mjs b/lib/hosts/updates.test.mjs index 53929579..2ab8a83c 100644 --- a/lib/hosts/updates.test.mjs +++ b/lib/hosts/updates.test.mjs @@ -17,7 +17,7 @@ let failedNpm = false; let api; let worker; const STAMPED = "18.20.0-int.202611130355.gd2c2eff"; -const approvedPin = (digest = "a".repeat(64), version = "99.0.0") => ({ version, releaseRepo: "ompweb-dev/ompweb", assets: { "ompweb-linux-x64.tar.gz": digest } }); +const approvedPin = (digest = "a".repeat(64), version = "99.0.0") => ({ version, releaseRepo: "ompweb-dev/tau", assets: { "ompweb-linux-x64.tar.gz": digest } }); const resetState = () => rmSync(stateRoot, { recursive: true, force: true }); const ownedDirectory = (path) => { mkdirSync(path, { recursive: true, mode: 0o700 }); }; async function deadPid() { @@ -40,7 +40,7 @@ before(async () => { process.env.OMP_WEB_OMP_BIN = bin; globalThis.fetch = async (url) => { if (String(url).startsWith("https://registry.npmjs.org/")) return new Response(failedNpm ? "broken" : JSON.stringify({ version: latest }), { status: failedNpm ? 503 : 200 }); - assert.match(String(url), /^https:\/\/raw\.githubusercontent\.com\/ompweb-dev\/ompweb\/v[^/]+\/lib\/hosts\/link-protocol\.ts$/); + assert.match(String(url), /^https:\/\/raw\.githubusercontent\.com\/ompweb-dev\/tau\/v[^/]+\/lib\/hosts\/link-protocol\.ts$/); if (protocol === null) throw new Error("fixture offline"); return new Response(protocol); }; @@ -64,7 +64,7 @@ test("candidate protocol outside server range is visible but cannot execute", as assert.equal(info.ompweb.canUpdate, false); assert.match(info.ompweb.blockedReason, /server first/i); await assert.rejects(api.startHostUpdate("ompweb", "99.0.0", { min: 1, max: 2 }), /server first/i); - assert.deepEqual(info.omp, { currentVersion: STAMPED }, "omp updates with ompweb: its row carries only the version"); + assert.equal(info.omp.currentVersion, STAMPED); assert.ok(worker.HOST_VERSION_PATTERN.test(STAMPED)); }); @@ -88,20 +88,23 @@ test("npm discovery failure stays explicit instead of claiming up to date", asyn failedNpm = false; }); -test("omp, version syntax and a stale candidate are rejected before execution", async () => { - await assert.rejects(api.startHostUpdate("omp", "2.0.0", { min: 1, max: 10 }), (error) => error.code === "invalid_target"); +test("invalid target, version syntax and a stale candidate are rejected before execution", async () => { + await assert.rejects(api.startHostUpdate("unknown", "2.0.0", { min: 1, max: 10 }), (error) => error.code === "invalid_target"); await assert.rejects(api.startHostUpdate("ompweb", "2.0.0; touch /tmp/unwanted", { min: 1, max: 10 }), /version/i); await assert.rejects(api.startHostUpdate("ompweb", "1.9.0", { min: 1, max: 10 }), /changed|candidate|available/i); }); test("disable policy blocks checks and starts", async () => { process.env.OMP_WEB_DISABLE_AUTOUPDATE = "1"; - const info = await api.checkHostUpdates({ min: 1, max: 10 }, true); - assert.equal(info.ompweb.canUpdate, false); - assert.match(info.ompweb.blockedReason, /disabled/i); - await assert.rejects(api.startHostUpdate("ompweb", "2.0.0", { min: 1, max: 10 }), /disabled/i); - assert.deepEqual(info.omp, { currentVersion: STAMPED }); - delete process.env.OMP_WEB_DISABLE_AUTOUPDATE; + try { + const info = await api.checkHostUpdates({ min: 1, max: 10 }, true); + assert.equal(info.ompweb.canUpdate, false); + assert.match(info.ompweb.blockedReason, /disabled/i); + await assert.rejects(api.startHostUpdate("ompweb", "2.0.0", { min: 1, max: 10 }), /disabled/i); + assert.equal(info.omp.currentVersion, STAMPED); + } finally { + delete process.env.OMP_WEB_DISABLE_AUTOUPDATE; + } }); test("an approved pin evaluates its immutable version after latest moves", async () => { diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs index 510906a7..2af54b81 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -67,9 +67,9 @@ const { acknowledgeSelfUpdate, acknowledgeSelfUpdateBoot, commitSelfUpdate, getS function pinFor(version = NEW) { return { - version, releaseRepo: "ompweb-dev/ompweb", + version, releaseRepo: "ompweb-dev/tau", assets: { [`ompweb-${process.platform === "win32" ? "windows" : process.platform}-${process.arch}${process.platform === "win32" ? ".zip" : ".tar.gz"}`]: "a".repeat(64) }, - npm: { tarball: `https://registry.npmjs.org/@kahme247/ompweb/-/ompweb-${version}.tgz`, integrity: `sha512-${Buffer.alloc(64).toString("base64")}` }, + npm: { tarball: `https://registry.npmjs.org/@ompweb-dev/tau/-/tau-${version}.tgz`, integrity: `sha512-${Buffer.alloc(64).toString("base64")}` }, }; } function planFor(id, targetVersion = NEW, fromVersion = OLD, local = { recovery: "local", sessionProcesses: 0, activeTurns: 0 }) { From d5d31d3e21775a2e431345712cd00d4ae45d3822 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 17:16:41 +0000 Subject: [PATCH 002/129] test: port remaining runner-protocol tests to pi --mode rpc Fake children and link fixtures answer the startup get_state, take flat {type, id, ...args} commands and reply with response frames; events travel unwrapped. Runner-only checks (channel protocol version, subagent subscription, --advisor/--profile argv, use-omp-build) are removed, word-prediction commands are swapped for surviving ones, and update pins name the tau repository and npm package. --- components/HostsConfig.test.mjs | 10 +-- components/SettingsConfig.updates.test.mjs | 9 +- lib/agent-command.test.mjs | 22 +++-- lib/agent-tools.test.mjs | 29 +++---- lib/api-contract.test.mjs | 10 +-- lib/browser-link.test.mjs | 2 +- lib/hosts/daemon-runtime.test.mjs | 15 ++-- lib/hosts/daemon-update-safety.test.mjs | 2 +- lib/hosts/daemon.test.mjs | 82 +++++++++---------- lib/hosts/files-owner.integration.test.mjs | 9 +- lib/hosts/hub-v7.test.mjs | 40 ++++----- lib/hosts/hub.test.mjs | 4 +- lib/hosts/legacy-recovery.test.mjs | 7 +- lib/hosts/link-driver.test-helper.mjs | 8 +- lib/hosts/link-integration.test.mjs | 59 ++++++------- lib/hosts/local-host-profile.test.mjs | 4 +- .../maintenance-daemon.integration.test.mjs | 10 +-- lib/hosts/multi-server.integration.test.mjs | 2 +- lib/hosts/pool-starts.test.mjs | 41 ++++------ lib/hosts/preflight.test.mjs | 20 ++--- lib/hosts/recovery.test.mjs | 4 +- lib/hosts/session-index.test.mjs | 11 ++- lib/hosts/stream-snapshot.test.mjs | 6 +- lib/instrumentation-crash-policy.test.mjs | 10 +-- lib/message-outbox-review.test.mjs | 20 ++--- lib/omp/win32-spawn.test.mjs | 67 ++++++++------- lib/outbox-handoff.test.mjs | 7 +- lib/server-update-worker.test.mjs | 4 +- lib/session-resume.test.mjs | 1 - lib/transport-stats.test.ts | 2 +- lib/upgrade-plan-coordinator.test.mjs | 4 +- lib/user-level-config-routes.test.mjs | 19 +++-- scripts/use-omp-build.test.mjs | 42 ---------- tests/fixtures/multi-server-omp.mjs | 16 ++-- 34 files changed, 268 insertions(+), 330 deletions(-) delete mode 100644 scripts/use-omp-build.test.mjs diff --git a/components/HostsConfig.test.mjs b/components/HostsConfig.test.mjs index 662f3d79..426e90e7 100644 --- a/components/HostsConfig.test.mjs +++ b/components/HostsConfig.test.mjs @@ -162,9 +162,9 @@ test("local host shows both installed versions and a blocked candidate with its const row = screen.getByRole("button", { name: "Rename This machine" }).closest("li"); await within(row).findByText(/Update the web server first: protocol 4 is not supported\./); assert.ok(within(row).getByRole("button", { name: "Update ompweb host" }).disabled); - // omp is read-only: it updates with ompweb. + // omp is its own target: with no candidate it offers no update, and it no longer says it updates with ompweb. assert.equal(within(row).queryByRole("button", { name: "Update omp runtime" }), null); - within(row).getByText("Updated with ompweb"); + assert.equal(within(row).queryByText("Updated with ompweb"), null); assert.match(row.textContent, /Current: 1\.0\.0/); assert.match(row.textContent, /Current: 2\.0\.0/); assert.match(row.textContent, /Available: 1\.1\.0/); @@ -368,12 +368,12 @@ test("a registry version that is not newer is not shown as an available candidat await showHosts([hostRow()]); await screen.findByText("Current: 18.14.0"); screen.getByText("Current: 20.1.0-beta.1"); - screen.getByText("Up to date"); + assert.equal(screen.getAllByText("Up to date").length, 2); assert.equal(screen.queryByText(/^Available:/), null); assert.equal(screen.queryByRole("button", { name: /^Update (ompweb host|omp runtime)$/ }), null); }); -test("resident-session blocking stays readable with a disabled daemon update; the omp row stays read-only", async (t) => { +test("resident-session blocking stays readable with a disabled daemon update; the omp row offers no update without a candidate", async (t) => { mockHostRequests(t, async () => Response.json(updateInfo({ ompweb: software({ canUpdate: false, blockedReason: "Close all sessions on Laptop before updating the host daemon.", installMethod: "npm", protocolVersion: 3 }), }))); @@ -381,7 +381,7 @@ test("resident-session blocking stays readable with a disabled daemon update; th await screen.findByText(/Close all sessions on Laptop before updating the host daemon/); assert.ok(screen.getByRole("button", { name: "Update ompweb host" }).disabled); assert.equal(screen.queryByRole("button", { name: "Update omp runtime" }), null); - screen.getByText("Updated with ompweb"); + assert.equal(screen.queryByText("Updated with ompweb"), null); }); test("sharing credentials is confirmed before it is turned on, and turned off at once", async (t) => { diff --git a/components/SettingsConfig.updates.test.mjs b/components/SettingsConfig.updates.test.mjs index d93dfc20..80ab7dba 100644 --- a/components/SettingsConfig.updates.test.mjs +++ b/components/SettingsConfig.updates.test.mjs @@ -87,12 +87,12 @@ test("a supported binary install gets the in-app Update action, not a download l assert.ok(!requests.some((url) => url.includes("app-update")), "the Settings click must not prepare or commit anything itself"); }); -test("a host's omp row shows the omp its ompweb shipped and offers no update of its own", async (t) => { +test("a host's omp row is its own update target: its version, its candidate and its own Update button", async (t) => { const { HostUpdates } = await import("./HostUpdates"); const originalFetch = globalThis.fetch; globalThis.fetch = async () => Response.json({ ompweb: { currentVersion: "0.6.0", availableVersion: "0.7.0", updateAvailable: true, canUpdate: true, blockedReason: null, updateCommand: "npm install -g @kahme247/ompweb", installMethod: "npm", protocolVersion: 10 }, - omp: { currentVersion: "18.20.0-int.202611130355.gd2c2eff" }, + omp: { currentVersion: "18.20.0-int.202611130355.gd2c2eff", availableVersion: "18.21.0", updateAvailable: true, canUpdate: true, blockedReason: null, updateCommand: "npm install -g @earendil-works/pi-coding-agent" }, operation: null, }); const container = document.createElement("div"); @@ -108,6 +108,7 @@ test("a host's omp row shows the omp its ompweb shipped and offers no update of }); await act(() => new Promise((resolve) => setTimeout(resolve, 20))); assert.ok(container.textContent.includes("18.20.0-int.202611130355.gd2c2eff"), container.textContent); - assert.ok(container.textContent.includes("Updated with ompweb"), container.textContent); - assert.deepEqual(buttonLabels(container).filter((label) => label === "Update"), ["Update"], "only ompweb has an update button"); + assert.ok(container.textContent.includes("Available: 18.21.0"), container.textContent); + assert.ok(!container.textContent.includes("Updated with ompweb"), container.textContent); + assert.deepEqual(buttonLabels(container).filter((label) => label === "Update"), ["Update", "Update"], "ompweb and omp each have an update button"); }); diff --git a/lib/agent-command.test.mjs b/lib/agent-command.test.mjs index 0b7bca1f..4c639222 100644 --- a/lib/agent-command.test.mjs +++ b/lib/agent-command.test.mjs @@ -32,22 +32,22 @@ const daemon = await linkLocalHost(); async function respond(message, link = daemon) { if (message.type !== "stdin") return; - const { t, op, args, ...rest } = JSON.parse(message.line); - const command = t === "cmd" ? { ...args, ...rest, type: op } : { ...rest, type: t }; + const command = JSON.parse(message.line); stdin.push(command); - if (t !== "cmd") return; - let reply = { ok: true, data: {} }; + // Replies to dialogs and host calls are frames, not commands: pi answers nothing. + if (command.id === undefined || /^(ui_response|extension_ui_response|host_tool_result|host_uri_result)$/.test(command.type)) return; + let reply = { success: true, data: {} }; if (command.type === "get_state") { reply = { - ok: true, + success: true, data: { sessionId: SAVED_ID, sessionFile: `/remote/sessions/${SAVED_ID}.jsonl`, isStreaming: false, isCompacting: false, ...child.state }, }; } else if (command.type === "set_model") { reply = child.setModelFails - ? { ok: false, error: "Model not found" } - : { ok: true, data: { id: command.modelId, provider: command.provider } }; + ? { success: false, error: "Model not found" } + : { success: true, data: { id: command.modelId, provider: command.provider } }; } - await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "res", id: command.id, ...reply }) }); + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, ...reply }) }); } let channels = 0; @@ -148,9 +148,9 @@ test("a missing type is 400 command_type_required; a no-spawn command without a assert.equal(missing.status, 400); assert.equal((await missing.json()).code, "command_type_required"); - const canned = await runAgentCommand("nobody", { type: "predict_word" }, false); + const canned = await runAgentCommand("nobody", { type: "get_btw_history" }, false); assert.equal(canned.status, 200); - assert.deepEqual(await canned.json(), { success: true, data: { suffix: null } }); + assert.deepEqual(await canned.json(), { success: true, data: { records: [] } }); }); test("client-message status rejects an oversized selector before any native admission", async (t) => { @@ -225,8 +225,6 @@ test("x-omp-received-at is stamped once the body is in, like a socket's ack afte // Background commands never spawn or replace an omp child: every SSE open // fires get_btw_history, so a regression here starts omp on each reconnect. const CANNED = [ - [{ type: "predict_word" }, { suffix: null }], - [{ type: "predict_word_feedback" }, null], [{ type: "get_btw_history" }, { records: [] }], [{ type: "btw_cancel" }, { cancelled: false }], ]; diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index 6867941a..aeb9c4cc 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -519,24 +519,21 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold const ch = `ch-${identities.size + 1}`; identities.set(ch, id); spawns.push({ hostId: link.id, sessionId: id, ch, ...launch }); - const hello = JSON.stringify({ t: "hello", proto: 1, pid: 1, sessionId: id, sessionFile: `/remote/sessions/${id}.jsonl`, cwd: launch.cwd }); - return { ch, joined: false, pending: [hello], streaming: null, cwd: launch.cwd, fellBack: false, launchAdvisor: false, advisorSpawned: false, autoApproveExtension: false }; + return { ch, joined: false, pending: [], streaming: null, cwd: launch.cwd, fellBack: false, launchAdvisor: false, advisorSpawned: false, autoApproveExtension: false }; }, }, async (message) => { if (message.type === "kill") return link.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }); if (message.type !== "stdin") return; - const frame = JSON.parse(message.line); - const { t, op, args, ...rest } = frame; - const command = t === "cmd" ? { type: op, id: frame.id, ...args } : { type: t, ...rest }; + const command = JSON.parse(message.line); commands.push({ hostId: link.id, ch: message.ch, ...command }); if (command.type === "host_tool_result") { results.push(command); return; } - if (t !== "cmd") return; + if (command.id === undefined || /^(ui_response|extension_ui_response|host_uri_result)$/.test(command.type)) return; if (link !== source && command.type === holdInitialization) { reachedInitialization.resolve(); return; } const data = command.type === "get_state" ? { sessionId: identities.get(message.ch), sessionFile: `/remote/sessions/${identities.get(message.ch)}.jsonl`, isStreaming: false, isCompacting: false, isSettled: true, queuedMessageCount: 0 } : {}; - await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "res", id: command.id, ok: true, data }) }); + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }) }); }); } const sample = { effectiveCpus: 4, load1: 0, busyFraction: 0, stealFraction: 0, availableMemoryBytes: 3 * 1024 ** 3, activeSessions: 0 }; @@ -552,7 +549,7 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold }); async function call(args, requestId = randomUUID(), toolName = "new_session") { const before = results.length; - await source.post({ type: "stdout", ch: sourceChannel, line: JSON.stringify({ t: "host_tool_call", id: requestId, toolName, arguments: args }) }); + await source.post({ type: "stdout", ch: sourceChannel, line: JSON.stringify({ type: "host_tool_call", id: requestId, toolName, arguments: args }) }); await until(() => results.slice(before).some((result) => result.id === requestId), `${toolName} result`); return results.slice(before).find((result) => result.id === requestId); } @@ -605,20 +602,20 @@ test("independent pooled agent creation reserves a real owner and initializes on const transport={ write(line,callback){ const frame=JSON.parse(line); frames.push(frame); callback(null); - if(frame.t!=="cmd")return; - const data=frame.op==="get_state"?{sessionId:${JSON.stringify(f.sourceId)},sessionFile:${JSON.stringify(f.sourceRow.path)},isStreaming:false,isCompacting:false}:{}; - queueMicrotask(()=>transport.emit(JSON.stringify({t:"res",id:frame.id,ok:true,data}))); + if(frame.type==="host_tool_result")return; + const data=frame.type==="get_state"?{sessionId:${JSON.stringify(f.sourceId)},sessionFile:${JSON.stringify(f.sourceRow.path)},isStreaming:false,isCompacting:false}:{}; + queueMicrotask(()=>transport.emit(JSON.stringify({type:"response",id:frame.id,command:frame.type,success:true,data}))); }, onLine(listener){transport.emit=listener},onStderr(){},onExit(listener){transport.exit=listener}, endInput(){queueMicrotask(()=>transport.exit?.(0,null))},killTree(){queueMicrotask(()=>transport.exit?.(null,"SIGTERM"))} }; const calls=[ - {t:"host_tool_call",id:${JSON.stringify(requestId)},toolName:"new_session",arguments:${JSON.stringify(args)}}, - {t:"host_tool_call",id:"other-mutating-tool",toolName:"send_to_session",arguments:{sessionId:"other",message:"do not replay"}} + {type:"host_tool_call",id:${JSON.stringify(requestId)},toolName:"new_session",arguments:${JSON.stringify(args)}}, + {type:"host_tool_call",id:"other-mutating-tool",toolName:"send_to_session",arguments:{sessionId:"other",message:"do not replay"}} ]; const session=await adoptRpcSession({host:hub.getHost(source.id),transport,sessionId:${JSON.stringify(f.sourceId)},cwd:${JSON.stringify(f.sourceCwd)},replay:calls.map(call=>JSON.stringify(call))}); - await until(()=>frames.filter(frame=>frame.t==="host_tool_result").length===2,"native request replay"); - const answers=frames.filter(frame=>frame.t==="host_tool_result"); + await until(()=>frames.filter(frame=>frame.type==="host_tool_result").length===2,"native request replay"); + const answers=frames.filter(frame=>frame.type==="host_tool_result"); const creation=answers.find(frame=>frame.id===${JSON.stringify(requestId)}); assert.equal(creation.isError,false,creation.result.content[0].text); assert.deepEqual(JSON.parse(creation.result.content[0].text),${JSON.stringify(created)}); @@ -689,7 +686,7 @@ test("native pooled creation exposes its retained identity and unknown delivery const requestId = "uncertain-native-creation"; t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); try { - await f.source.post({ type: "stdout", ch: f.sourceChannel, line: JSON.stringify({ t: "host_tool_call", id: requestId, toolName: "new_session", arguments: args }) }); + await f.source.post({ type: "stdout", ch: f.sourceChannel, line: JSON.stringify({ type: "host_tool_call", id: requestId, toolName: "new_session", arguments: args }) }); await f.reachedInitialization; // Keep both source and selected worker online; only the native acknowledgement is missing. for (let step = 0; step < 6; step++) { diff --git a/lib/api-contract.test.mjs b/lib/api-contract.test.mjs index 45fe615b..c0887d51 100644 --- a/lib/api-contract.test.mjs +++ b/lib/api-contract.test.mjs @@ -262,8 +262,7 @@ async function pooledNewRouteFixture(t, onCommand = async () => undefined) { validateCwd: ({ path }) => ({ ok: true, value: { cwd: path, projectRoot: "/worker/project" } }), open({ launch }) { spawns.push(launch); - const hello = JSON.stringify({ t: "hello", proto: 1, pid: 1, sessionId, sessionFile: `/remote/sessions/${sessionId}.jsonl`, cwd: launch.cwd }); - return { ch: `ch-${spawns.length}`, joined: false, pending: [hello], streaming: null, cwd: launch.cwd, fellBack: false, launchAdvisor: false, advisorSpawned: false, autoApproveExtension: false }; + return { ch: `ch-${spawns.length}`, joined: false, pending: [], streaming: null, cwd: launch.cwd, fellBack: false, launchAdvisor: false, advisorSpawned: false, autoApproveExtension: false }; }, sessionFileExists: () => false, invalidateSessionLists: () => null, @@ -271,14 +270,13 @@ async function pooledNewRouteFixture(t, onCommand = async () => undefined) { }, async (message) => { if (message.type === "kill") return link.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }); if (message.type !== "stdin") return; - const frame = JSON.parse(message.line); - if (frame.t !== "cmd") return; - const command = { type: frame.op, id: frame.id, ...frame.args }; + const command = JSON.parse(message.line); + if (command.id === undefined || /^(ui_response|extension_ui_response|host_tool_result|host_uri_result)$/.test(command.type)) return; commands.push(command); if (await onCommand(command, { link, sessionId, dir }) === "hold") return; const data = command.type === "get_state" ? { sessionId, sessionFile: `/remote/sessions/${sessionId}.jsonl`, isStreaming: false, isCompacting: false } : command.type === "set_model" ? { provider: command.provider, id: command.modelId, name: command.modelId, reasoning: true, input: ["text"], contextWindow: 200000, maxTokens: 8192, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } : {}; - await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "res", id: command.id, ok: true, data }) }); + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }) }); }); await link.post({ type: "capacity", sample: { effectiveCpus: 4, load1: 0, busyFraction: 0, stealFraction: 0, availableMemoryBytes: 16 * 1024 ** 3, activeSessions: 0 } }); t.after(async () => { diff --git a/lib/browser-link.test.mjs b/lib/browser-link.test.mjs index 9fae7ee0..a2084d60 100644 --- a/lib/browser-link.test.mjs +++ b/lib/browser-link.test.mjs @@ -722,7 +722,7 @@ test("read-only commands are not remembered: the same rid runs again and takes n withSession(t, "sess-read", wrapper); const peer = browser(); peer.connect(t); - for (const type of ["get_state", "get_state", "predict_word"]) peer.send({ type: "cmd", rid: "r-read", session: "sess-read", advisor: false, command: { type } }); + for (const type of ["get_state", "get_state", "get_messages"]) peer.send({ type: "cmd", rid: "r-read", session: "sess-read", advisor: false, command: { type } }); await settled(peer, () => peer.replies().length === 3, "three replies"); assert.deepEqual(peer.replies().map((reply) => reply.deduped), [false, false, false]); assert.equal(wrapper.sent.length, 3); diff --git a/lib/hosts/daemon-runtime.test.mjs b/lib/hosts/daemon-runtime.test.mjs index 0142ceef..1ae2debc 100644 --- a/lib/hosts/daemon-runtime.test.mjs +++ b/lib/hosts/daemon-runtime.test.mjs @@ -24,15 +24,16 @@ fs.appendFileSync(${JSON.stringify(spawns)}, process.pid + "\\n"); const rules = (() => { try { return fs.readFileSync(${JSON.stringify(join(scratch, "agent", "AGENTS.md"))}, "utf8"); } catch { return null; } })(); fs.appendFileSync(${JSON.stringify(envs)}, JSON.stringify({ url: process.env.OMP_AUTH_BROKER_URL ?? null, token: !!process.env.OMP_AUTH_BROKER_TOKEN, leaked: JSON.stringify([process.env, process.argv]).includes(${JSON.stringify(LINK_TOKEN)}), rules }) + "\\n"); -const file = process.argv[process.argv.indexOf("--resume") + 1]; +const file = process.argv[process.argv.indexOf("--session") + 1]; const id = JSON.parse(fs.readFileSync(file, "utf8").split("\\n")[0]).id; const emit = frame => process.stdout.write(JSON.stringify(frame) + "\\n"); require("node:readline").createInterface({input:process.stdin}).on("line", line => { const command = JSON.parse(line); - if (command.t === "cmd") emit({t:"res",id:command.id,ok:true,data:{}}); - if (command.t === "cmd" && command.op === "prompt") emit({t:"event",event:{type:"agent_start"}}); + // The daemon's startup get_state names the session; every other command gets an empty success. + const data = command.type === "get_state" ? {sessionId:id,sessionFile:file,cwd:process.cwd()} : {}; + emit({type:"response",id:command.id,command:command.type,success:true,data}); + if (command.type === "prompt") emit({type:"agent_start"}); }); -setImmediate(() => emit({t:"hello",proto:1,pid:process.pid,sessionId:id,sessionFile:file,cwd:process.cwd()})); `; // Rewriting the binary changes its fingerprint, so the daemon probes the new version. function writeFakeOmp(version) { @@ -160,8 +161,8 @@ test("configuration reload, source ops/uploads and peer-only deletion preserve o assert.throws(() => daemon.control("drain"), { code: "host_busy" }, "another link's native child still prevents maintenance"); c.send({ type: "req", id: "join-c", op: "open", args: { sessionId: id, launch } }); await until(() => c.result("join-c")); assert.equal(c.result("join-c").result.ch, ch); assert.equal(c.result("join-c").result.joined, true); - c.send({ type: "stdin", ch, line: JSON.stringify({ t: "cmd", id: 4242, op: "get_messages", args: {} }) + "\n" }); - await until(() => c.messages.some(message => message.type === "stdout" && JSON.parse(message.line).t === "res" && JSON.parse(message.line).id === 4242)); + c.send({ type: "stdin", ch, line: JSON.stringify({ type: "get_messages", id: "4242" }) + "\n" }); + await until(() => c.messages.some(message => message.type === "stdout" && JSON.parse(message.line).type === "response" && JSON.parse(message.line).id === "4242")); assert.equal(readFileSync(spawns, "utf8").trim().split("\n").length, 2, "only the explicitly deleted session was respawned"); c.close(1000); assert.equal(await daemon.done, 1); }); @@ -336,7 +337,7 @@ test("an open with a version the member lacks applies it before omp starts; host assert.ok(config.auth.length > 1 && config.auth.every(header => header === `Bearer ${LINK_TOKEN}`), "every fetch carried the link's token"); await until(() => a.states.some(state => state.version === version && state.files === "current")); const ch = a.result("apply-open").result.ch; - a.send({ type: "stdin", ch, line: JSON.stringify({ t: "cmd", id: 1, op: "prompt", args: { message: "go" } }) + "\n" }); + a.send({ type: "stdin", ch, line: JSON.stringify({ type: "prompt", id: "1", message: "go" }) + "\n" }); const running = join(process.env.PI_CODING_AGENT_DIR, "omp-web", "host-running.json"); await until(() => existsSync(running) && readFileSync(running, "utf8").includes(id)); const recorded = JSON.parse(readFileSync(running, "utf8")).find(entry => entry.sessionId === id); diff --git a/lib/hosts/daemon-update-safety.test.mjs b/lib/hosts/daemon-update-safety.test.mjs index ed67c605..162a9768 100644 --- a/lib/hosts/daemon-update-safety.test.mjs +++ b/lib/hosts/daemon-update-safety.test.mjs @@ -11,7 +11,7 @@ process.env.PI_CODING_AGENT_DIR = join(scratch, "agent"); const root = join(scratch, "agent", "omp-web", "host-update"); mkdirSync(root, { recursive: true, mode: 0o700 }); const binary = join(scratch, process.platform === "win32" ? "omp.cmd" : "omp"); -const script = `if(process.argv.includes('--version')){console.log('18.0.0');process.exit(0)};if(process.argv.includes('--check')){console.log('Current version: 18.0.0');process.exit(0)};const emit=(f)=>process.stdout.write(JSON.stringify(f)+'\\n');require('node:readline').createInterface({input:process.stdin}).on('line',(l)=>{const c=JSON.parse(l);if(c.t==='cmd')emit({t:'res',id:c.id,ok:true,data:{}})});setImmediate(()=>emit({t:'hello',proto:1,pid:process.pid,sessionId:require('node:crypto').randomUUID(),cwd:process.cwd()}));`; +const script = `if(process.argv.includes('--version')){console.log('18.0.0');process.exit(0)};if(process.argv.includes('--check')){console.log('Current version: 18.0.0');process.exit(0)};const emit=(f)=>process.stdout.write(JSON.stringify(f)+'\\n');const sessionId=require('node:crypto').randomUUID();require('node:readline').createInterface({input:process.stdin}).on('line',(l)=>{const c=JSON.parse(l);emit({type:'response',id:c.id,command:c.type,success:true,data:c.type==='get_state'?{sessionId,cwd:process.cwd()}:{}})});`; if (process.platform === "win32") { writeFileSync(binary + ".cjs", script); writeFileSync(binary, `@"${process.execPath}" "${binary}.cjs" %*\r\n`); diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index b6734c19..3edc1f20 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -62,26 +62,23 @@ require("node:fs").appendFileSync(${JSON.stringify(childrenFile)}, JSON.stringif const emit = (frame) => process.stdout.write(JSON.stringify(frame) + "\\n"); require("node:readline").createInterface({ input: process.stdin }).on("line", (line) => { const command = JSON.parse(line); - // The runner channel protocol: a command is {t: "cmd", id, op, args}; the daemon's own set-up commands get a reply, the test ops none. - const { op, args = {} } = command; - if (command.t !== "cmd") return; - if (op === "set_event_filter" || op === "set_subagent_subscription") return emit({ t: "res", id: command.id, ok: true, data: {} }); - if (op === "state") emit({ t: "session", sessionId: args.sessionId }); - if (op === "flood") for (let i = 0; i < ${FLOOD_LINES}; i++) emit({ t: "x", i, pad: "y".repeat(${FLOOD_PAD}) }); - if (op === "many") for (let i = 0; i < 25000; i++) process.stdout.write('{"t":"n"}\\n'); - if (op === "parts") for (let i = 0; i < args.n; i++) emit({ t: "p", i, pad: "q".repeat(400_000) }); - if (op === "cjk") for (let i = 0; i < 100; i++) emit({ t: "c", i, text: "漢".repeat(10_000) }); - if (op === "huge") emit({ t: "x", pad: "y".repeat(9 * 1024 * 1024) }); - if (op === "echo") emit({ t: "echoed" }); - if (op === "identify") emit({ t: "identity", pid: process.pid }); + // pi --mode rpc: a command is {type, id, ...args}; the daemon's startup get_state gets a reply, the test ops none. + const { type: op, ...args } = command; + if (op === "get_state") return emit({ type: "response", id: command.id, command: "get_state", success: true, data: { cwd: process.cwd() } }); + if (op === "state") emit({ type: "session", sessionId: args.sessionId }); + if (op === "flood") for (let i = 0; i < ${FLOOD_LINES}; i++) emit({ type: "x", i, pad: "y".repeat(${FLOOD_PAD}) }); + if (op === "many") for (let i = 0; i < 25000; i++) process.stdout.write('{"type":"n"}\\n'); + if (op === "parts") for (let i = 0; i < args.n; i++) emit({ type: "p", i, pad: "q".repeat(400_000) }); + if (op === "cjk") for (let i = 0; i < 100; i++) emit({ type: "c", i, text: "漢".repeat(10_000) }); + if (op === "huge") emit({ type: "x", pad: "y".repeat(9 * 1024 * 1024) }); + if (op === "echo") emit({ type: "echoed" }); + if (op === "identify") emit({ type: "identity", pid: process.pid }); if (op === "exit") process.exit(0); - if (op === "frame") emit({ t: "event", event: args.big ? { ...args.frame, pad: "x".repeat(1024 * 1024) } : args.frame }); - // Two ~6.5 MB event lines, as omp echoes an image prompt (message_start, message_end). - if (op === "echoes") for (const id of ["start", "end"]) emit({ t: "event", event: { type: "message_" + id, pad: "z".repeat(${ECHO_PAD}) } }); - if (op === "ask") emit({ t: "ui_request", id: 7, method: "ask", args: [[]] }); + if (op === "frame") emit(args.big ? { ...args.frame, pad: "x".repeat(1024 * 1024) } : args.frame); + // Two ~6.5 MB event lines, as pi echoes an image prompt (message_start, message_end). + if (op === "echoes") for (const id of ["start", "end"]) emit({ type: "message_" + id, pad: "z".repeat(${ECHO_PAD}) }); + if (op === "ask") emit({ type: "extension_ui_request", id: "7", method: "select", title: "Pick", options: [] }); }); -// The runner's hello: the daemon waits for it before it opens the channel. -emit({ t: "hello", proto: 1, pid: process.pid, cwd: process.cwd() }); `); /** The daemon's WebSocket with a send buffer the test controls, as a slow link has one: unless the link is @@ -244,8 +241,8 @@ function scriptedServer({ refuse = () => null, validToken = null, version = LINK /** The daemon's channel id for each name `spawnChannel` opened. */ server.chs = {}; let cmdSeq = 0; - /** A test op for channel `name` in the runner protocol; the daemon renumbers the command id. */ - server.stdin = (name, op, args = {}) => server.send({ type: "stdin", ch: server.chs[name], line: JSON.stringify({ t: "cmd", id: ++cmdSeq, op, args }) + "\n" }); + /** A test op for channel `name` as a pi RPC command; the daemon renumbers the command id. */ + server.stdin = (name, op, args = {}) => server.send({ type: "stdin", ch: server.chs[name], line: JSON.stringify({ ...args, type: op, id: String(++cmdSeq) }) + "\n" }); server.stop = () => http.stop(true); servers.push(server); return server; @@ -460,7 +457,7 @@ test("capacity follows real turns, reconnects with fresh unsequenced samples, an server.stdin(ch, "frame", { frame, big }); // A following plain echo is a barrier after the entire big frame was read. server.stdin(ch, "echo"); - await waitFor(() => server.up.filter((m) => m.type === "stdout" && m.ch === server.chs[ch]).slice(before).some((m) => m.line === '{"t":"echoed"}'), "the emitted turn frame"); + await waitFor(() => server.up.filter((m) => m.type === "stdout" && m.ch === server.chs[ch]).slice(before).some((m) => m.line === '{"type":"echoed"}'), "the emitted turn frame"); }; try { await waitFor(() => server.hellos.length === 1, "the hello"); @@ -560,9 +557,9 @@ test("a running host deletes expired staged uploads every hour, not only when it test("the hello reports this host's extension auto-approve", async () => { const log = captureLog(); - const config = join(process.env.PI_CODING_AGENT_DIR, "config.yml"); + const config = join(process.env.PI_CODING_AGENT_DIR, "settings.json"); mkdirSync(dirname(config), { recursive: true }); - writeFileSync(config, "tools:\n approval:\n extension: allow\n"); + writeFileSync(config, JSON.stringify({ tools: { approval: { extension: "allow" } } })); const server = scriptedServer(); const daemon = start(server); try { @@ -1000,7 +997,7 @@ test("each uplink frame starts with the ack of the applied downlink, and the nex const log = captureLog(); const server = scriptedServer(); const daemon = start(server); - const echoes = () => server.up.filter((m) => m.type === "stdout" && m.line === '{"t":"echoed"}').length; + const echoes = () => server.up.filter((m) => m.type === "stdout" && m.line === '{"type":"echoed"}').length; try { await waitFor(() => server.hellos.length === 1, "the hello"); await spawnChannel(server, "c1"); @@ -1250,7 +1247,8 @@ test("application version rejection keeps the daemon alive for maintenance and r } }); -test("a refused upgrade is diagnosed with one plain GET: 401 stops every omp child, 503 and others redial", async () => { +// The 503 and 426 redials back off for about 6 s in all. +test("a refused upgrade is diagnosed with one plain GET: 401 stops every omp child, 503 and others redial", { timeout: 15_000 }, async () => { const log = captureLog(); try { rmSync(pidFile, { force: true }); @@ -1308,9 +1306,9 @@ test("output beyond the channel buffer while the uplink is down is dropped, then assert.ok(floodLines < 100, `dropped output must not arrive (${floodLines} lines did)`); // Output flows again after the resync. server.stdin("c1", "echo"); - await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line === '{"t":"echoed"}'), "output after resync"); + await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line === '{"type":"echoed"}'), "output after resync"); const resyncAt = server.up.findIndex((m) => m.type === "resync"); - const echoAt = server.up.findIndex((m) => m.line === '{"t":"echoed"}'); + const echoAt = server.up.findIndex((m) => m.line === '{"type":"echoed"}'); assert.ok(resyncAt < echoAt); } finally { await daemon.stop(); @@ -1320,7 +1318,7 @@ test("output beyond the channel buffer while the uplink is down is dropped, then /** What a channel's up messages carried: each event's type, and where a resync fell. */ function framesUp(messages) { - return messages.flatMap((m) => (m.type === "resync" ? ["resync"] : m.type === "stdout" ? [JSON.parse(m.line).event.type] : [])); + return messages.flatMap((m) => (m.type === "resync" ? ["resync"] : m.type === "stdout" ? [JSON.parse(m.line).type] : [])); } /** The channel's messages main gets for the two echoes (~17 MB), written while the uplink is stalled. `log`: the @@ -1342,7 +1340,7 @@ async function echoesWhileStalled(ch, log) { const last = server.up.findLast((m) => m.ch === server.chs[ch]); if (last?.type === "resync") return true; const record = last?.type === "stdout" ? JSON.parse(last.line) : null; - return record?.event?.type === "message_end"; + return record?.type === "message_end"; }, "the echoes or a resync"); return server.up.filter((m) => m.ch === server.chs[ch]); } finally { @@ -1358,7 +1356,7 @@ test("an overflow drops the backlog of whole lines and sends a resync", async () try { const messages = await echoesWhileStalled("drop", log); assert.ok(messages.some((m) => m.type === "resync"), "the overflow sent a resync"); - assert.ok(messages.every((m) => m.type !== "stdout" || JSON.parse(m.line).t === "event"), "what went up is whole lines"); + assert.ok(messages.every((m) => m.type !== "stdout" || JSON.parse(m.line).type.startsWith("message_")), "what went up is whole lines"); } finally { LINK_LIMITS.channelBufferBytes = saved; log.restore(); @@ -1384,7 +1382,7 @@ test("a stdout line over the link limit is dropped for a resync", async () => { server.stdin("big", "huge"); await waitFor(() => server.up.some((m) => m.type === "resync" && m.ch === server.chs.big), "resync"); server.stdin("big", "echo"); - await waitFor(() => server.up.some((m) => m.ch === server.chs.big && m.line === '{"t":"echoed"}'), "output after the oversize line"); + await waitFor(() => server.up.some((m) => m.ch === server.chs.big && m.line === '{"type":"echoed"}'), "output after the oversize line"); assert.equal(server.up.some((m) => m.ch === server.chs.big && m.type === "stdout" && m.line.length > 1_000), false, "the oversize line never goes up"); } finally { await daemon.stop(); @@ -1400,16 +1398,16 @@ test("after a link drop the next hello carries each channel's open blocking requ await waitFor(() => server.hellos.length === 1, "the hello"); await spawnChannel(server, "c1"); server.stdin("c1", "ask"); - await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line.includes('"ui_request"')), "the ask request"); - const request = server.up.find((m) => m.type === "stdout" && m.line.includes('"ui_request"')).line; + await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line.includes('"extension_ui_request"')), "the ask request"); + const request = server.up.find((m) => m.type === "stdout" && m.line.includes('"extension_ui_request"')).line; assert.deepEqual(server.hellos[0].channels, []); server.drop(); await waitFor(() => server.hellos.length === 2, "the relink"); assert.deepEqual(server.hellos[1].channels, [{ ch: server.chs.c1, sessionId: null, cwd: scratch, pending: [request] }]); // The answer goes down to omp: the request is no longer open. The echo orders it before the drop. - server.send({ type: "stdin", ch: server.chs.c1, line: '{"t":"ui_response","id":7,"value":"x"}\n' }); + server.send({ type: "stdin", ch: server.chs.c1, line: '{"type":"extension_ui_response","id":"7","value":"x"}\n' }); server.stdin("c1", "echo"); - await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line === '{"t":"echoed"}'), "the echo"); + await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line === '{"type":"echoed"}'), "the echo"); server.drop(); await waitFor(() => server.hellos.length === 3, "the second relink"); assert.deepEqual(server.hellos[2].channels, [{ ch: server.chs.c1, sessionId: null, cwd: scratch, pending: [] }]); @@ -1659,7 +1657,7 @@ for (const hideBuffer of [false, true]) { server.raw({ type: "ping" }); await waitFor(() => server.res("big"), "the result"); const lastPiece = server.frames.findLastIndex((frame) => frame.blob === "big"); - const echoAt = server.frames.findIndex((frame) => Array.isArray(frame) && frame.some((m) => m.line === '{"t":"echoed"}')); + const echoAt = server.frames.findIndex((frame) => Array.isArray(frame) && frame.some((m) => m.line === '{"type":"echoed"}')); const pongAt = server.frames.findIndex((frame) => Array.isArray(frame) && frame.some((m) => m.type === "pong")); assert.ok(echoAt !== -1 && echoAt < lastPiece, `echo in frame ${echoAt}, the result's last piece in frame ${lastPiece}`); assert.ok(pongAt !== -1 && pongAt < lastPiece, `pong in frame ${pongAt}, the result's last piece in frame ${lastPiece}`); @@ -1688,7 +1686,7 @@ test("a redial with about 20,000 unacked lines resends them well within offlineM const log = captureLog(); const server = scriptedServer(); const daemon = start(server); - const ones = () => new Set(server.up.filter((m) => m.ch === server.chs.c1 && m.line === '{"t":"n"}').map((m) => m.seq)).size; + const ones = () => new Set(server.up.filter((m) => m.ch === server.chs.c1 && m.line === '{"type":"n"}').map((m) => m.seq)).size; try { await waitFor(() => server.hellos.length === 1, "the hello"); await spawnChannel(server, "c1"); @@ -1809,7 +1807,7 @@ test("downlink parts join into one stdin line, also when the line is torn across try { await waitFor(() => server.hellos.length === 1, "the hello"); await spawnChannel(server, "c1"); - const inner = JSON.stringify({ type: "stdin", seq: 0, ch: server.chs.c1, line: `${JSON.stringify({ t: "cmd", id: 1, op: "echo", args: { pad: "q".repeat(600_000) } })}\n` }); + const inner = JSON.stringify({ type: "stdin", seq: 0, ch: server.chs.c1, line: `${JSON.stringify({ type: "echo", id: "1", pad: "q".repeat(600_000) })}\n` }); const first = server.send({ type: "part", at: 0, end: false, data: inner.slice(0, 300_000) }); // The daemon acks the part with its next frame, a pong. server.raw({ type: "ping" }); @@ -1820,9 +1818,9 @@ test("downlink parts join into one stdin line, also when the line is torn across // Resent though applied (dropped by seq), then the rest of the line. server.raw({ type: "part", seq: first, at: 0, end: false, data: inner.slice(0, 300_000) }); server.send({ type: "part", at: 300_000, end: true, data: inner.slice(300_000) }); - await waitFor(() => server.up.some((m) => m.ch === server.chs.c1 && m.line === '{"t":"echoed"}'), "the joined line reaching omp"); + await waitFor(() => server.up.some((m) => m.ch === server.chs.c1 && m.line === '{"type":"echoed"}'), "the joined line reaching omp"); await sleep(100); - assert.equal(server.up.filter((m) => m.line === '{"t":"echoed"}').length, 1); + assert.equal(server.up.filter((m) => m.line === '{"type":"echoed"}').length, 1); } finally { await daemon.stop(); log.restore(); @@ -1859,7 +1857,7 @@ async function stalledRedial(server, { afterWelcome = () => [], stalled = async await spawnChannel(server, "c1"); server.holdAcks = true; const heldFrom = server.textFrameBytes.length; - const ones = () => server.up.filter((m) => m.ch === server.chs.c1 && m.line === '{"t":"n"}'); + const ones = () => server.up.filter((m) => m.ch === server.chs.c1 && m.line === '{"type":"n"}'); server.stdin("c1", "many"); // The daemon stops at a full unacked window, and every frame since the hold is unacked: nothing more goes up. await waitFor(() => server.textFrameBytes.slice(heldFrom).reduce((sum, bytes) => sum + bytes, 0) >= LINK_LIMITS.unackedBytes, @@ -1880,7 +1878,7 @@ async function stalledRedial(server, { afterWelcome = () => [], stalled = async uplink.paused = false; // The resend is done once a message sequenced after the old lines arrives: new lines come after the snapshot. await waitFor(() => server.up.slice(server.upAtHello[1]).some((m) => m.seq > maxSeq), "the resend to finish"); - const resent = server.up.slice(server.upAtHello[1]).filter((m) => m.ch === server.chs.c1 && m.line === '{"t":"n"}' && m.seq <= maxSeq).length; + const resent = server.up.slice(server.upAtHello[1]).filter((m) => m.ch === server.chs.c1 && m.line === '{"type":"n"}' && m.seq <= maxSeq).length; return { resent, unacked }; } finally { LINK_LIMITS.unackedBytes = savedWindow; diff --git a/lib/hosts/files-owner.integration.test.mjs b/lib/hosts/files-owner.integration.test.mjs index 3d21db2e..f6c24040 100644 --- a/lib/hosts/files-owner.integration.test.mjs +++ b/lib/hosts/files-owner.integration.test.mjs @@ -97,12 +97,11 @@ const path=require('node:path'); const sessionId=require('node:crypto').randomUUID(); const sessionFile=path.join(process.env.PI_CODING_AGENT_DIR,'sessions',sessionId+'.jsonl'); const out=(value)=>process.stdout.write(JSON.stringify(value)+'\\n'); -out({t:'hello',proto:1,pid:process.pid,sessionId,sessionFile,cwd:process.cwd()}); require('node:readline').createInterface({input:process.stdin}).on('line',(line)=>{ const command=JSON.parse(line); - if(command.t!=='cmd')return; - const data=command.op==='get_state'?{sessionId,sessionFile,isStreaming:false,isCompacting:false}:{}; - out({t:'res',id:command.id,ok:true,data}); + if(command.id===undefined)return; + const data=command.type==='get_state'?{sessionId,sessionFile,isStreaming:false,isCompacting:false}:{}; + out({type:'response',id:command.id,command:command.type,success:true,data}); }); process.stdin.on('end',()=>process.exit(0));`; if (process.platform === "win32") { @@ -172,7 +171,7 @@ async function until(predicate, what, timeout = 10000) { } } async function startDaemon(machine, token) { - const env = { ...process.env, HOME: machine.home, USERPROFILE: machine.home, PI_CONFIG_DIR: ".omp", PI_CODING_AGENT_DIR: machine.agent, OMP_WEB_OMP_BIN: fakeOmp, OMP_WEB_DISABLE_AUTOUPDATE: "1" }; + const env = { ...process.env, HOME: machine.home, USERPROFILE: machine.home, PI_CONFIG_DIR: ".omp", PI_CODING_AGENT_DIR: machine.agent, TAU_PI_BIN: fakeOmp, OMP_WEB_DISABLE_AUTOUPDATE: "1" }; const url = `http://127.0.0.1:${server.port}`; const login = spawnSync("node", [hostBin, "login", "--url", url], { env, input: `${token}\n`, encoding: "utf8" }); assert.equal(login.status, 0, login.stderr); diff --git a/lib/hosts/hub-v7.test.mjs b/lib/hosts/hub-v7.test.mjs index 965ff9d8..46b33f1b 100644 --- a/lib/hosts/hub-v7.test.mjs +++ b/lib/hosts/hub-v7.test.mjs @@ -33,7 +33,7 @@ test.after(() => { let serial = 0; const sessionId = () => `11111111-2222-4333-8444-${String(++serial).padStart(12, "0")}`; const launch = (id) => ({ cwd: "/w", recordedCwd: "/w", sessionFile: `/sessions/${id}.jsonl`, advisor: false }); -const ev = (event) => JSON.stringify({ t: "event", event }); +const ev = (event) => JSON.stringify(event); const snapshot = (text = "before") => ev({ type: "message_update", messageId: "m", message: { role: "assistant", content: [{ type: "text", text }] } }); const result = (ch, extras = {}) => ({ ch, joined: true, pending: [], streaming: null, cwd: "/w", fellBack: false, launchAdvisor: false, advisorSpawned: false, autoApproveExtension: false, ...extras }); @@ -98,9 +98,9 @@ test("shell exclusion is forwarded on every bash command, including after reload await session.send(command); await session.send({ type: "reload" }); await session.send(command); - const executions = messages.filter((m) => m.type === "stdin").map((m) => JSON.parse(m.line)).filter((m) => m.op === "bash"); + const executions = messages.filter((m) => m.type === "stdin").map((m) => JSON.parse(m.line)).filter((m) => m.type === "bash"); assert.equal(executions.length, 2); - assert.ok(executions.every((m) => m.args.excludeFromContext === true)); + assert.ok(executions.every((m) => m.excludeFromContext === true)); }); // A promise continuation is too late: the following stdout is applied in the same WebSocket frame. @@ -112,11 +112,11 @@ test("v7 open installs the returned channel and snapshot before same-frame live const req = await link.next(); assert.equal(req.op, "open"); assert.deepEqual(req.args, { sessionId: id, launch: launch(id) }); - const dialog = JSON.stringify({ t: "ui_request", id: 5, method: "askDialog", args: [[]] }); + const dialog = JSON.stringify({ type: "ui_request", id: 5, method: "askDialog", args: [[]] }); await link.post( { type: "channels_changed", channels: [{ ch: "canonical", sessionId: id, cwd: "/w", pending: [] }] }, { type: "res", id: req.id, ok: true, result: result("canonical", { pending: [dialog], streaming: snapshot() }) }, - { type: "stdout", ch: "canonical", line: JSON.stringify({ t: "notice", message: "later" }) }, + { type: "stdout", ch: "canonical", line: JSON.stringify({ type: "notice", message: "later" }) }, ); const spawned = await opening; const frames = []; @@ -125,7 +125,7 @@ test("v7 open installs the returned channel and snapshot before same-frame live assert.equal(spawned.transport.id, "canonical"); proc.replay([...spawned.pending, spawned.streaming]); proc.release(); - assert.deepEqual(frames, [{ type: "ui_request", id: 5, method: "askDialog", args: [[]] }, JSON.parse(snapshot()).event, { type: "notice", message: "later" }]); + assert.deepEqual(frames, [{ type: "ui_request", id: 5, method: "askDialog", args: [[]] }, JSON.parse(snapshot()), { type: "notice", message: "later" }]); spawned.transport.setInterest(true); spawned.transport.setPreparing(true); spawned.transport.setPreparing(false); @@ -499,14 +499,14 @@ test("v7 joined wrappers skip child-global startup, report interest and preserve detach(); await until(() => messages.filter(m => m.type === "interest").at(-1)?.on === false, "interest released"); const startup = new Set(["set_event_filter", "set_subagent_subscription", "set_host_tools", "set_host_uri_schemes"]); - assert.deepEqual(messages.filter(m => m.type === "stdin" && startup.has(JSON.parse(m.line).op)), []); + assert.deepEqual(messages.filter(m => m.type === "stdin" && startup.has(JSON.parse(m.line).type)), []); await session.destroyAndWait(); assert.equal(messages.some(m => m.type === "kill"), false); }); test("v7 hello eagerly joins background runs and resync restores the daemon snapshot without changing filters", async (t) => { const id = sessionId(); - const dialog = JSON.stringify({ t: "ui_request", id: 9, method: "askDialog", args: [[]] }); + const dialog = JSON.stringify({ type: "ui_request", id: 9, method: "askDialog", args: [[]] }); const { link, ch, messages, opens } = await sharedLink(t, id, { listed: true, pending: [dialog], streaming: snapshot("whole"), state: { isStreaming: true } }); await until(() => getRpcSession(id)?.isAlive(), "background adoption"); const wrapper = getRpcSession(id); @@ -516,12 +516,12 @@ test("v7 hello eagerly joins background runs and resync restores the daemon snap assert.equal(opens.length, 1); await link.post({ type: "resync", ch }); await until(() => opens.length === 2, "snapshot reopen"); - await until(() => messages.filter(m => m.type === "stdin" && JSON.parse(m.line).op === "get_state").length >= 2, "resync state"); + await until(() => messages.filter(m => m.type === "stdin" && JSON.parse(m.line).type === "get_state").length >= 2, "resync state"); assert.equal(wrapper.getStreamSnapshot().streamingMessage.content[0].text, "whole"); await link.post({ type: "stdout", ch, line: ev({ type: "message_update", messageId: "m", message: { role: "assistant" }, assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: " plus" } }) }); assert.equal(wrapper.getStreamSnapshot().streamingMessage.content[0].text, "whole plus"); assert.equal(opens.length, 2, "a daemon snapshot is a valid delta base"); - assert.equal(messages.some(m => m.type === "stdin" && JSON.parse(m.line).op === "set_event_filter"), false); + assert.equal(messages.some(m => m.type === "stdin" && JSON.parse(m.line).type === "set_event_filter"), false); const events = []; const detach = wrapper.onEvent(event => events.push(event)); assert.ok(events.some(event => event.type === "ui_request" && event.id === 9)); @@ -656,7 +656,7 @@ test("shared callback snapshots cannot execute a browser action twice", async (t const events = []; const detach = session.onEvent(event => events.push(event)); t.after(detach); - const call = { t: "host_tool_call", id: "one-action", toolName: "open_url", arguments: { url: "https://example.test" } }; + const call = { type: "host_tool_call", id: "one-action", toolName: "open_url", arguments: { url: "https://example.test" } }; await link.post({ type: "stdout", ch, line: JSON.stringify(call) }); pending.push(JSON.stringify(call)); await link.post({ type: "resync", ch }); @@ -666,11 +666,11 @@ test("shared callback snapshots cannot execute a browser action twice", async (t test("adopted shared web callbacks report unknown outcome instead of blindly repeating an action", async (t) => { const id = sessionId(); - const call = JSON.stringify({ t: "host_tool_call", id: "before-restart", toolName: "open_url", arguments: { url: "https://example.test" } }); + const call = JSON.stringify({ type: "host_tool_call", id: "before-restart", toolName: "open_url", arguments: { url: "https://example.test" } }); const { messages } = await sharedLink(t, id, { listed: true, pending: [call] }); await until(() => getRpcSession(id)?.isAlive(), "adopted callback owner"); - await until(() => messages.some(message => message.type === "stdin" && JSON.parse(message.line).t === "host_tool_result"), "ambiguous callback result"); - const reply = messages.filter(message => message.type === "stdin").map(message => JSON.parse(message.line)).find(frame => frame.t === "host_tool_result"); + await until(() => messages.some(message => message.type === "stdin" && JSON.parse(message.line).type === "host_tool_result"), "ambiguous callback result"); + const reply = messages.filter(message => message.type === "stdin").map(message => JSON.parse(message.line)).find(frame => frame.type === "host_tool_result"); assert.equal(reply.id, "before-restart"); assert.equal(reply.isError, true); assert.match(reply.result.content[0].text, /outcome is unknown/); @@ -703,7 +703,7 @@ test("explicit v7 reload kills once, restores registrations and leaves startup s await until(() => messages.filter(message => message.type === "host_tools").length >= 3, "restored tool registration"); assert.deepEqual(messages.filter(message => message.type === "host_tools").at(-1).schemes, [{ scheme: "browser", writable: true }]); const forbidden = new Set(["set_event_filter", "set_subagent_subscription", "set_host_tools", "set_host_uri_schemes"]); - assert.deepEqual(messages.filter(message => message.type === "stdin" && forbidden.has(JSON.parse(message.line).op)), []); + assert.deepEqual(messages.filter(message => message.type === "stdin" && forbidden.has(JSON.parse(message.line).type)), []); }); test("joined and eagerly adopted shared wrappers retain the actual native advisor mode", async (t) => { @@ -746,8 +746,8 @@ for (const desired of [true, false]) { assert.equal(opens.at(-1).replaceAdvisor, true); assert.equal(opens.at(-1).preparing, true); assert.equal(opens.at(-1).launch.advisor, desired); - await until(() => messages.some(message => message.type === "stdin" && JSON.parse(message.line).op === "prompt"), "prompt on the renewed channel"); - assert.equal(messages.filter(message => message.type === "stdin" && JSON.parse(message.line).op === "prompt").length, 1); + await until(() => messages.some(message => message.type === "stdin" && JSON.parse(message.line).type === "prompt"), "prompt on the renewed channel"); + assert.equal(messages.filter(message => message.type === "stdin" && JSON.parse(message.line).type === "prompt").length, 1); assert.equal(messages.some(message => message.type === "kill"), false, "replacement is guarded on the daemon"); }); } @@ -900,7 +900,7 @@ test("a peer server's identical echo never confirms this server's own message ad assert.deepEqual(await owned, {}, "an uncontended echo proves the admission"); own.stop(); const contended = watch(), outcome = contended.handOff(); - await fixture.link.post({ type: "stdout", ch: fixture.ch, line: JSON.stringify({ t: "peer_message_command" }) }, ...echo(2)); + await fixture.link.post({ type: "stdout", ch: fixture.ch, line: JSON.stringify({ type: "peer_message_command" }) }, ...echo(2)); assert.equal((await outcome).mayHaveBeenSent, true, "a peer's admission makes the echo ambiguous"); contended.stop(); }); @@ -921,7 +921,7 @@ test("an edit another web app holds the lease for fails session_busy before any const id = sessionId(); const fixture = await sharedLink(t, id, { leaseBusy: true }); const { session } = await startRpcSession(id, launch(id).sessionFile, "/w", undefined, false, "/w", undefined, hub.getHost(fixture.link.id)); - const reads = () => fixture.messages.filter(message => message.type === "stdin" && JSON.parse(message.line).op === "get_state").length; + const reads = () => fixture.messages.filter(message => message.type === "stdin" && JSON.parse(message.line).type === "get_state").length; const before = reads(); await assert.rejects(session.send({ type: "edit_message", entryId: "u1" }), { code: "session_busy" }); assert.equal(reads(), before, "no preflight ran without the lease"); @@ -935,7 +935,7 @@ test("a pre-release v7 daemon without editLease still lets the edit run", async const { session } = await startRpcSession(id, launch(id).sessionFile, "/w", undefined, false, "/w", undefined, hub.getHost(fixture.link.id)); session.proc.transport.setEditing = async () => { throw new HostOpError(501, "unknown_op", "Unknown host op: editLease"); }; const editing = session.send({ type: "edit_message", entryId: "u1" }); - await until(() => fixture.messages.some(message => message.type === "stdin" && JSON.parse(message.line).op === "get_state" && session.isEditingHistory()), "preflight ran"); + await until(() => fixture.messages.some(message => message.type === "stdin" && JSON.parse(message.line).type === "get_state" && session.isEditingHistory()), "preflight ran"); await editing.catch(() => {}); }); diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 7c79371c..f7d75467 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -679,7 +679,7 @@ test("a start while the adoption re-syncs joins it: no kill, no second child", a kills.push(message.ch); return link.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }); } - if (message.type === "stdin" && JSON.parse(message.line).op === "get_state" && !holding) { + if (message.type === "stdin" && JSON.parse(message.line).type === "get_state" && !holding) { holding = true; await release.promise; } @@ -1228,7 +1228,7 @@ test("each downlink line the daemon acks becomes a down sample: its size, the un const { req, ch, spawning, result, post } = await spawnOverLink(link); const session = "11111111-2222-4333-8444-5555555555aa"; // The child names its session in a `session` frame (a new session's first one, a switch, a fork). - const state = { t: "session", sessionId: session, sessionFile: `/remote/sessions/${session}.jsonl` }; + const state = { type: "session", sessionId: session, sessionFile: `/remote/sessions/${session}.jsonl` }; await post([{ type: "res", seq: 1, id: req.id, ok: true, result }, { type: "stdout", seq: 2, ch, line: JSON.stringify(state) }]); const { transport } = await spawning; transport.write(`${"x".repeat(100_000)}\n`, () => {}); diff --git a/lib/hosts/legacy-recovery.test.mjs b/lib/hosts/legacy-recovery.test.mjs index d609486b..32f119c9 100644 --- a/lib/hosts/legacy-recovery.test.mjs +++ b/lib/hosts/legacy-recovery.test.mjs @@ -168,9 +168,10 @@ test("the two historical envelopes carry one command and each dialect's parser r const runner = JSON.parse(runnerLine); assert.deepEqual(rpc, { id: "7", type: "bash", command, excludeFromContext: true }); assert.deepEqual(runner, { t: "cmd", id: 7, op: "bash", args: { command, excludeFromContext: true } }); - // A runner-form daemon's DaemonChannels.stdin parses with parseWire: no `t`, no command. - assert.equal(parseWire(rpcLine), null); - assert.deepEqual(parseWire(runnerLine)?.args, runner.args); + // An RPC-form daemon's stdin parses with parseWire (pi's `type` dialect): the runner line has no `type`, no command. + // The runner-form parser (`{t}` frames) left with the runner, so its half is checked by shape below. + assert.equal(parseWire(runnerLine), null); + assert.deepEqual(parseWire(rpcLine), rpc); // An RPC-form daemon's stdin (v10 prerelease 546a945df0) needs a string `type` and refuses ids it reserves with "d:". assert.equal(runner.type, undefined); assert.equal(rpc.t, undefined); diff --git a/lib/hosts/link-driver.test-helper.mjs b/lib/hosts/link-driver.test-helper.mjs index b5fe6a0e..ac908b0e 100644 --- a/lib/hosts/link-driver.test-helper.mjs +++ b/lib/hosts/link-driver.test-helper.mjs @@ -146,10 +146,10 @@ export function ompChild(link, sessionId, { state = {}, fail = null } = {}) { return async (message) => { if (message.type !== "stdin") return; const command = JSON.parse(message.line); - if (command.t !== "cmd") return; - const data = command.op === "get_state" ? { sessionId, sessionFile: `/remote/sessions/${sessionId}.jsonl`, isStreaming: false, isCompacting: false, ...state } : {}; - const outcome = command.op === fail ? { ok: false, error: `${fail} failed` } : { ok: true, data }; - await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "res", id: command.id, ...outcome }) }); + if (command.id === undefined || /^(ui_response|extension_ui_response|host_tool_result|host_uri_result)$/.test(command.type)) return; + const data = command.type === "get_state" ? { sessionId, sessionFile: `/remote/sessions/${sessionId}.jsonl`, isStreaming: false, isCompacting: false, ...state } : {}; + const outcome = command.type === fail ? { success: false, error: `${fail} failed` } : { success: true, data }; + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, ...outcome }) }); }; } diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 37f4db11..acf18046 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -64,7 +64,7 @@ const out = (frame) => { log({ kind: "out", line }); process.stdout.write(line + "\\n"); }; -const resumeAt = process.argv.indexOf("--resume"); +const resumeAt = process.argv.indexOf("--session"); const resumed = resumeAt === -1 ? null : process.argv[resumeAt + 1]; // As omp does, a new session's file is written only once its first assistant message ends. const sessionId = resumed ? JSON.parse(fs.readFileSync(resumed, "utf8").split("\\n")[0]).id : require("node:crypto").randomUUID(); @@ -74,7 +74,7 @@ let streaming = false; let text = ""; const update = (next) => { text = String(next); - out({ t: "event", event: { type: "message_update", message: { role: "assistant", content: [{ type: "text", text }] } } }); + out({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text }] } }); }; const end = () => { streaming = false; @@ -87,36 +87,34 @@ const end = () => { ]; fs.writeFileSync(sessionFile, lines.map((line) => JSON.stringify(line)).join("\\n") + "\\n"); } - out({ t: "event", event: { type: "agent_end", isTerminal: true, messages: [] } }); + out({ type: "agent_end", isTerminal: true, messages: [] }); }; log({ kind: "start", sessionId }); -out({ t: "hello", proto: 1, pid: process.pid, sessionId, sessionFile, cwd: process.cwd() }); require("node:readline").createInterface({ input: process.stdin }).on("line", (line) => { const command = JSON.parse(line); // Bulk stdin (the backpressure test): logged without its padding. - if (command.op === "pad") return log({ kind: "pad", n: command.args.n }); + if (command.type === "pad") return log({ kind: "pad", n: command.n }); log({ kind: "stdin", command }); - const reply = (data) => out({ t: "res", id: command.id, ok: true, data }); - // A dialog answer and a host tool result are frames: omp sends no res to them. - if (command.t === "ui_response") { + const reply = (data) => out({ type: "response", id: command.id, command: command.type, success: true, data }); + // A dialog answer and a host tool result are frames: pi sends no response to them. + if (command.type === "ui_response") { update("answered " + command.value.results[0].selectedOptions[0]); return end(); } - if (command.t === "host_tool_result") { + if (command.type === "host_tool_result") { update("tool " + command.result.content[0].text); return end(); } - if (command.t !== "cmd") return; - if (command.op === "get_state") return reply({ sessionId, sessionFile, isStreaming: streaming, isCompacting: false }); - if (command.op !== "prompt") return reply({}); + if (command.type === "get_state") return reply({ sessionId, sessionFile, isStreaming: streaming, isCompacting: false }); + if (command.type !== "prompt") return reply({}); reply({ agentInvoked: true }); - prompt = command.args.message; + prompt = command.message; streaming = true; - out({ t: "event", event: { type: "agent_start" } }); - if (command.args.message === "ask") return out({ t: "ui_request", id: 1, method: "askDialog", args: [[{ id: "q", question: "Pick", options: [{ label: "A" }] }]] }); - if (command.args.message === "tool") { + out({ type: "agent_start" }); + if (command.message === "ask") return out({ type: "ui_request", id: 1, method: "askDialog", args: [[{ id: "q", question: "Pick", options: [{ label: "A" }] }]] }); + if (command.message === "tool") { // A host tool call, then one more frame once the test creates the go file. - out({ t: "host_tool_call", id: "h1", toolCallId: "c1", toolName: "browser_open", arguments: { url: "https://a.test" } }); + out({ type: "host_tool_call", id: "h1", toolCallId: "c1", toolName: "browser_open", arguments: { url: "https://a.test" } }); const timer = setInterval(() => { if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; clearInterval(timer); @@ -124,17 +122,17 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l }, 25); return; } - if (command.args.message === "late") { + if (command.message === "late") { // An ask and an agent tool call, once the test creates the go file. const timer = setInterval(() => { if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; clearInterval(timer); - out({ t: "ui_request", id: 2, method: "askDialog", args: [[{ id: "q", question: "Late", options: [{ label: "B" }] }]] }); - out({ t: "host_tool_call", id: "h2", toolCallId: "c2", toolName: "send_to_session", arguments: { sessionId: ${JSON.stringify("11111111-2222-4333-8444-000000000001")}, message: "hi" } }); + out({ type: "ui_request", id: 2, method: "askDialog", args: [[{ id: "q", question: "Late", options: [{ label: "B" }] }]] }); + out({ type: "host_tool_call", id: "h2", toolCallId: "c2", toolName: "send_to_session", arguments: { sessionId: ${JSON.stringify("11111111-2222-4333-8444-000000000001")}, message: "hi" } }); }, 25); return; } - if (command.args.message === "slow") { + if (command.message === "slow") { for (let i = 1; i <= ${SLOW_HALF}; i++) update(i); let sent = ${SLOW_HALF}; const timer = setInterval(() => { @@ -413,8 +411,8 @@ test("a restarted web server adopts its running omp children, resumed or new: ea saveWebServerSettings({ autoResumeSessions: false }); }); const remote = hub.getHost(hostId); - // A resumed session, and a new one (no --resume) in its first reply: it names itself only in - // its hello, and no session list has it until that reply ends and omp writes its file. + // A resumed session, and a new one (no --session) in its first reply: it names itself only in + // its get_state answer, and no session list has it until that reply ends and pi writes its file. const runs = [ await startRpcSession(SMALL_ID, smallFile, projectDir, undefined, false, projectDir, undefined, remote), await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote), @@ -462,11 +460,8 @@ test("a restarted web server adopts its running omp children, resumed or new: ea for (const id of ids) { const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === id); assert.equal(starts.length, 1, `no second child was spawned for ${id}`); - // The daemon subscribes once when it starts the child; an adopting server joins it and never subscribes again. - const handshakes = log.filter((entry) => entry.pid === starts[0].pid && entry.command?.op === "set_subagent_subscription"); - assert.equal(handshakes.length, 1, `the daemon alone set up the same child of ${id}`); } - assert.equal(log.some((entry) => entry.command?.args?.message === RESUME_PROMPT), false, "no resume prompt"); + assert.equal(log.some((entry) => entry.command?.message === RESUME_PROMPT), false, "no resume prompt"); }); test("a run waiting on an ask shows the dialog again after a web restart, and the answer reaches the same omp child", async () => { @@ -493,7 +488,7 @@ test("a run waiting on an ask shows the dialog again after a web restart, and th const log = ompLog(); const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === ASK_ID); assert.equal(starts.length, 1, "no second child was spawned"); - assert.ok(log.some((entry) => entry.pid === starts[0].pid && entry.command?.t === "ui_response" && entry.command.id === 1)); + assert.ok(log.some((entry) => entry.pid === starts[0].pid && entry.command?.type === "ui_response" && entry.command.id === 1)); assert.deepEqual(seen.kills.slice(killsBefore).filter((ch) => ch === getRpcSession(ASK_ID).proc.transport.ch), [], "no kill reached the asking child"); }); @@ -526,7 +521,7 @@ test("a stopping web server sends nothing more and takes nothing in: a closing t await waitFor(() => ompSaid("while stopping") && seen.refusedUpgrades > refusedBefore, "output while stopping, and a redial refused"); }, }); - assert.equal(ompLog().some((entry) => entry.command?.t === "host_tool_result"), false, "no rejection reached omp"); + assert.equal(ompLog().some((entry) => entry.command?.type === "host_tool_result"), false, "no rejection reached omp"); assert.equal(before.some((event) => event.type === "message_update"), false, "the stopping server applied none of it"); await waitFor(() => getRpcSession(TOOL_ID), "the adoption"); @@ -541,7 +536,7 @@ test("a stopping web server sends nothing more and takes nothing in: a closing t await waitFor(() => events.some((event) => event.type === "agent_end"), "the run to end"); assert.ok(events.some((event) => event.type === "message_update" && /outcome is unknown/.test(event.message.content[0].text))); assert.equal(stopping().length, 1, "delivered once"); - const results = ompLog().filter((entry) => entry.command?.t === "host_tool_result").map((entry) => entry.command); + const results = ompLog().filter((entry) => entry.command?.type === "host_tool_result").map((entry) => entry.command); assert.equal(results.length, 1); assert.equal(results[0].id, "h1"); assert.equal(results[0].isError, true); @@ -582,7 +577,7 @@ test("a request omp opens while the web server stops reaches the next server onc await waitFor(() => getRpcSession(LATE_ID), "the adoption"); const events = adopted.get(getRpcSession(LATE_ID)); - const results = () => ompLog().filter((entry) => entry.command?.t === "host_tool_result" && entry.command.id === "h2"); + const results = () => ompLog().filter((entry) => entry.command?.type === "host_tool_result" && entry.command.id === "h2"); await waitFor(() => results().length > 0, "the agent tool result"); // Room for a second delivery to show up. await sleep(300); @@ -599,7 +594,7 @@ test("a daemon that stops reading is paced, not closed: the hub sends its outbox const pad = "x".repeat(6 * 1024 * 1024); daemon.kill("SIGSTOP"); try { - for (let n = 1; n <= count; n++) session.proc.transport.write(`${JSON.stringify({ t: "cmd", id: n, op: "pad", args: { n, pad } })}\n`, assert.ifError); + for (let n = 1; n <= count; n++) session.proc.transport.write(`${JSON.stringify({ type: "pad", id: String(n), n, pad })}\n`, assert.ifError); // Room for a close at the limit to show up. await sleep(300); assert.deepEqual([...sockets], [socket], "the socket stays open while the daemon reads nothing"); diff --git a/lib/hosts/local-host-profile.test.mjs b/lib/hosts/local-host-profile.test.mjs index e1d3417b..7cc77740 100644 --- a/lib/hosts/local-host-profile.test.mjs +++ b/lib/hosts/local-host-profile.test.mjs @@ -32,6 +32,7 @@ test("the owning host refuses legacy configuration before starting omp", async ( [{ extraArgs: ["--profile=work"] }, "stored_reserved_launch_arg"], [{ extraArgs: ["--cwd", "/elsewhere"] }, "stored_reserved_launch_arg"], [{ extraArgs: ["--resume=/tmp/other"] }, "stored_reserved_launch_arg"], + [{ extraArgs: ["--session=/tmp/other"] }, "stored_reserved_launch_arg"], [{ extraArgs: ["--mode", "rpc-ui"] }, "stored_reserved_launch_arg"], [{ extraArgs: ["rpc-ui"] }, "stored_reserved_launch_arg"], ]) { @@ -44,7 +45,8 @@ test("the owning host refuses legacy configuration before starting omp", async ( }); assert.equal(existsSync(marker), false); } - assert.deepEqual(buildSessionSpawnArgs("", undefined, false, { profile: "work", extraArgs: ["--verbose"] }), ["--profile", "work", "--verbose"]); + // pi has no profiles: a valid stored profile is accepted but not passed on. + assert.deepEqual(buildSessionSpawnArgs("", undefined, false, { profile: "work", extraArgs: ["--verbose"] }), ["--verbose"]); }); test("spawnRpc's env reaches the child and wins over the agentEnv setting", async (t) => { diff --git a/lib/hosts/maintenance-daemon.integration.test.mjs b/lib/hosts/maintenance-daemon.integration.test.mjs index 83f2b16a..ffd19803 100644 --- a/lib/hosts/maintenance-daemon.integration.test.mjs +++ b/lib/hosts/maintenance-daemon.integration.test.mjs @@ -90,10 +90,10 @@ test("maintenance reports a live prompt as active without inspecting its applica const emit = frame => process.stdout.write(JSON.stringify(frame) + "\\n"); require("node:readline").createInterface({input:process.stdin}).on("line", line => { const command = JSON.parse(line); - if (command.t === "cmd") emit({t:"res",id:command.id,ok:true,data:{}}); - if (command.op === "prompt") emit({t:"event",event:{type:"agent_start"}}); + const data = command.type === "get_state" ? {sessionId:${JSON.stringify(id)},cwd:${JSON.stringify(root)},sessionFile:${JSON.stringify(file)},isStreaming:false} : {}; + emit({type:"response",id:command.id,command:command.type,success:true,data}); + if (command.type === "prompt") emit({type:"agent_start"}); }); -emit({t:"hello",proto:1,pid:process.pid,sessionId:${JSON.stringify(id)},cwd:${JSON.stringify(root)},sessionFile:${JSON.stringify(file)}}); `; if (process.platform === "win32") { writeFileSync(fakeOmp + ".cjs", source); @@ -133,8 +133,8 @@ emit({t:"hello",proto:1,pid:process.pid,sessionId:${JSON.stringify(id)},cwd:${JS await until(() => messages.some(frame => frame.type === "res" && frame.id === "open-active"), "the real daemon to start its child"); const opened = messages.find(frame => frame.type === "res" && frame.id === "open-active"); assert.equal(opened.ok, true, JSON.stringify(opened)); - socket.send(JSON.stringify({ type: "stdin", seq: ++seq, ch: opened.result.ch, line: JSON.stringify({ t: "cmd", id: 1, op: "prompt", args: { message: "work" } }) + "\n" })); - await until(() => messages.some(frame => frame.type === "stdout" && JSON.parse(frame.line).event?.type === "agent_start"), "the prompt to become active"); + socket.send(JSON.stringify({ type: "stdin", seq: ++seq, ch: opened.result.ch, line: JSON.stringify({ type: "prompt", id: "1", message: "work" }) + "\n" })); + await until(() => messages.some(frame => frame.type === "stdout" && JSON.parse(frame.line).type === "agent_start"), "the prompt to become active"); const status = await maintenance.requestMaintenance(host.id, "status", {}); assert.equal(status.sessionProcesses, 1); assert.equal(status.sessions.find(session => session.id === id)?.active, true); diff --git a/lib/hosts/multi-server.integration.test.mjs b/lib/hosts/multi-server.integration.test.mjs index 2dad2c63..f703d025 100644 --- a/lib/hosts/multi-server.integration.test.mjs +++ b/lib/hosts/multi-server.integration.test.mjs @@ -183,5 +183,5 @@ test("two real web servers share one host process and one live conversation", { assert.ok(echo, "both real server links preserve the exact native outbox echo ID"); assert.equal(echo.message.clientMessageId, undefined, "native correlation stays outside the provider message"); } - assert.equal(starts().find((entry) => entry.type === "stdin" && entry.command.args?.message === "outbox from B")?.command.args.clientMessageId, "peer-delivered-message"); + assert.equal(starts().find((entry) => entry.type === "stdin" && entry.command.message === "outbox from B")?.command.clientMessageId, "peer-delivered-message"); }); diff --git a/lib/hosts/pool-starts.test.mjs b/lib/hosts/pool-starts.test.mjs index 4bfd5e1d..bcb4817b 100644 --- a/lib/hosts/pool-starts.test.mjs +++ b/lib/hosts/pool-starts.test.mjs @@ -390,26 +390,27 @@ const file = path.join(${JSON.stringify(workerDir)}, "sessions", "fixture", id + const log = (entry) => fs.appendFileSync(${JSON.stringify(logFile)}, JSON.stringify({pid:process.pid, sessionId:id, ...entry}) + "\\n"); const out = (frame) => process.stdout.write(JSON.stringify(frame) + "\\n"); log({kind:"start", cwd:process.cwd(), argv:process.argv.slice(2)}); -out({t:"hello", proto:1, pid:process.pid, sessionId:id, sessionFile:file, cwd:process.cwd()}); -if(fs.existsSync(${JSON.stringify(join(dir, "open-ask"))}))out({t:"ui_request",id:1,method:"askDialog",args:[[{id:"q",question:"Recover this question",options:[{label:"A"}]}]]}); +// The daemon's startup get_state is the handshake; a dialog opened by then is pending for the adopting server. +let answered=false; +const openAsk=()=>{if(!answered&&fs.existsSync(${JSON.stringify(join(dir, "open-ask"))}))out({type:"ui_request",id:1,method:"askDialog",args:[[{id:"q",question:"Recover this question",options:[{label:"A"}]}]]});answered=true;}; require("node:readline").createInterface({input:process.stdin}).on("line", (line) => { const command=JSON.parse(line); log({kind:"command", command}); - if(command.t!=="cmd") return; - const reply=(data)=>out({t:"res", id:command.id, ok:true, data}); - if(command.op==="get_state") { - const answer=()=>{reply({sessionId:id, sessionFile:file, isStreaming:false, isCompacting:false, isSettled:true, queuedMessageCount:0});if(fs.existsSync(${JSON.stringify(join(dir, "emit-live"))}))out({t:"event",event:{type:"message_update",message:{role:"assistant",content:[{type:"text",text:"live after adoption"}]}}});}; + if(["ui_response","extension_ui_response","host_tool_result","host_uri_result"].includes(command.type)) return; + const reply=(data)=>out({type:"response", id:command.id, command:command.type, success:true, data}); + if(command.type==="get_state") { + const answer=()=>{reply({sessionId:id, sessionFile:file, isStreaming:false, isCompacting:false, isSettled:true, queuedMessageCount:0});openAsk();if(fs.existsSync(${JSON.stringify(join(dir, "emit-live"))}))out({type:"message_update",message:{role:"assistant",content:[{type:"text",text:"live after adoption"}]}});}; if(!fs.existsSync(${JSON.stringify(join(dir, "hold-handshake"))})) return answer(); const timer=setInterval(()=>{if(!fs.existsSync(${JSON.stringify(join(dir, "hold-handshake"))})){clearInterval(timer);answer();}},10); return; } - if(command.op==="get_subagents"&&fs.existsSync(${JSON.stringify(join(dir, "hold-adoption"))})){ - out({t:"event",event:{type:"message_update",message:{role:"assistant",content:[{type:"text",text:"held during adoption"}]}}}); + if(command.type==="get_subagents"&&fs.existsSync(${JSON.stringify(join(dir, "hold-adoption"))})){ + out({type:"message_update",message:{role:"assistant",content:[{type:"text",text:"held during adoption"}]}}); return; } - if(command.op==="prompt") { + if(command.type==="prompt") { fs.mkdirSync(path.dirname(file),{recursive:true}); - fs.writeFileSync(file,JSON.stringify({type:"session",version:3,id,cwd:process.cwd(),timestamp:"2026-01-01T00:00:00.000Z"})+"\\n"+JSON.stringify({type:"message",id:"m1",parentId:null,timestamp:"2026-01-01T00:00:01.000Z",message:{role:"user",content:command.args.message}})+"\\n"); + fs.writeFileSync(file,JSON.stringify({type:"session",version:3,id,cwd:process.cwd(),timestamp:"2026-01-01T00:00:00.000Z"})+"\\n"+JSON.stringify({type:"message",id:"m1",parentId:null,timestamp:"2026-01-01T00:00:01.000Z",message:{role:"user",content:command.message}})+"\\n"); if(fs.existsSync(${JSON.stringify(join(dir, "hold-prompt"))})) return; } reply({}); @@ -539,9 +540,7 @@ test("lost spawn acknowledgement and API restart reconcile a sessionless journal return f.log().some((entry) => entry.kind === "start"); }, "initial child was not spawned"); const child = f.log().find((entry) => entry.kind === "start"); - assert.ok(child.argv.includes("central-profile"), "logical project launch config must reach the worker's actual process"); - assert.ok(child.argv.includes("--verbose")); - assert.ok(child.argv.includes("--advisor")); + assert.ok(child.argv.includes("--verbose"), "logical project launch config must reach the worker's actual process"); writeFileSync(join(child.cwd, "private.txt"), "unpublished work survives API restart\n"); const file = join(f.mainDir, "omp-web", "pool-starts.json"); const durable = readFileSync(file); @@ -568,7 +567,7 @@ test("lost spawn acknowledgement and API restart reconcile a sessionless journal assert.equal(body.cwd, child.cwd); assert.equal(readFileSync(join(child.cwd, "private.txt"), "utf8"), "unpublished work survives API restart\n"); assert.equal(f.log().filter((entry) => entry.kind === "start").length, 1); - assert.equal(f.log().filter((entry) => entry.command?.op === "prompt").length, 1); + assert.equal(f.log().filter((entry) => entry.command?.type === "prompt").length, 1); assert.equal(f.kills(), ""); }); @@ -578,7 +577,7 @@ test("API process restart after a delivered initial prompt returns durable uncer const first = f.post().then((response) => { early = response; return response; }).catch(() => null); await f.waitFor(async () => { if (early) assert.fail(`creation returned ${early.status} before prompt dispatch: ${await early.text()}`); - return f.log().some((entry) => entry.command?.op === "prompt"); + return f.log().some((entry) => entry.command?.type === "prompt"); }, "initial prompt was not delivered"); const child = f.log().find((entry) => entry.kind === "start"); assert.ok(readFileSync(join(f.mainDir, "omp-web", "pool-starts.json"), "utf8").includes(child.sessionId)); @@ -594,7 +593,7 @@ test("API process restart after a delivered initial prompt returns durable uncer assert.equal(body.delivery, "unknown"); } assert.equal(f.log().filter((entry) => entry.kind === "start").length, 1); - assert.equal(f.log().filter((entry) => entry.command?.op === "prompt").length, 1); + assert.equal(f.log().filter((entry) => entry.command?.type === "prompt").length, 1); assert.equal(f.kills(), ""); assert.doesNotThrow(() => process.kill(child.pid, 0)); }); @@ -619,16 +618,10 @@ test("logical launch config reaches the worker and clearing it removes stale spa assert.equal(second.status, 200, await second.clone().text()); const children = f.log().filter((entry) => entry.kind === "start"); assert.equal(children.length, 2); - assert.ok(children[0].argv.includes("--profile")); - assert.ok(children[0].argv.includes("central-profile")); assert.ok(children[0].argv.includes("--verbose")); - assert.ok(children[0].argv.includes("--advisor")); - assert.equal(children[1].argv.includes("--profile"), false); - assert.equal(children[1].argv.includes("central-profile"), false); assert.equal(children[1].argv.includes("--verbose"), false); - assert.equal(children[1].argv.includes("--advisor"), false); assert.notEqual(children[0].cwd, children[1].cwd); - assert.equal(f.log().filter((entry) => entry.command?.op === "prompt").length, 2); + assert.equal(f.log().filter((entry) => entry.command?.type === "prompt").length, 2); }); test("the journal retains identity and bounded replay metadata without copying the initial API payload", async (t) => { @@ -668,7 +661,7 @@ test("a partially adopted pooled child retries its native adoption, pending repl await f.startApi(); await f.online(); await f.waitFor(() => f.apiLog().includes("retained creation") && f.apiLog().includes("get_subagents"), "adoption did not fail after the child reported its real ID"); - assert.ok(f.log().some((entry) => entry.command?.op === "get_state")); + assert.ok(f.log().some((entry) => entry.command?.type === "get_state")); rmSync(join(f.dir, "hold-adoption")); const retry = await f.post(); assert.equal(retry.status, 200, await retry.clone().text()); diff --git a/lib/hosts/preflight.test.mjs b/lib/hosts/preflight.test.mjs index 34ec0e32..37e11fd4 100644 --- a/lib/hosts/preflight.test.mjs +++ b/lib/hosts/preflight.test.mjs @@ -33,12 +33,12 @@ async function preflight(script, timeoutMs) { } test("an omp that reads stdin and never says hello fails with the binary, the reason and its stderr", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { - // The incident: an omp without --headless sat reading the piped stdin. - const result = await preflight("#!/bin/sh\necho 'unknown flag --headless' >&2\nexec cat >/dev/null\n", 1000); + // The incident: an omp without the expected flags sat reading the piped stdin. + const result = await preflight("#!/bin/sh\necho 'unknown flag --mode' >&2\nexec cat >/dev/null\n", 1000); assert.equal(result.code, 1); assert.deepEqual(result.out, []); assert.equal(result.err.length, 1); - assert.match(result.err[0], new RegExp(`^preflight failed: ${omp}: no hello within 1 s: unknown flag --headless$`)); + assert.match(result.err[0], new RegExp(`^preflight failed: ${omp}: no hello within 1 s: unknown flag --mode$`)); }); test("an omp that exits names its exit code", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { @@ -48,7 +48,7 @@ test("an omp that exits names its exit code", { skip: process.platform === "win3 }); test("an omp without the execute bit fails before any start", { skip: process.platform === "win32" && "no execute bit on Windows" }, async () => { - writeFileSync(omp, "#!/bin/sh\necho '{\"t\":\"hello\",\"proto\":1}'\nexec cat >/dev/null\n"); + writeFileSync(omp, "#!/bin/sh\nread line\necho '{\"type\":\"response\",\"id\":\"preflight\",\"command\":\"get_state\",\"success\":true}'\nexec cat >/dev/null\n"); chmodSync(omp, 0o644); const err = []; const { error } = console; @@ -57,21 +57,21 @@ test("an omp without the execute bit fails before any start", { skip: process.pl assert.deepEqual(err, [`preflight failed: ${omp}: not executable`]); }); -test("a session omp that says hello passes with its version", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { - const result = await preflight(`#!/bin/sh\nif [ "$1" = "--version" ]; then echo 18.99.0; exit 0; fi\ncase "$*" in *"--headless --cwd "*"--no-session"*) echo '{"t":"hello","proto":1}'; exec cat >/dev/null;; esac\nexit 9\n`, 5000); +test("a session pi that answers get_state passes with its version", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { + const result = await preflight(`#!/bin/sh\nif [ "$1" = "--version" ]; then echo 18.99.0; exit 0; fi\ncase "$*" in *"--mode rpc "*"--no-session"*) read line; echo '{"type":"response","id":"preflight","command":"get_state","success":true,"data":{}}'; exec cat >/dev/null;; esac\nexit 9\n`, 5000); assert.deepEqual(result, { code: 0, out: [`preflight ok: ${omp} 18.99.0`], err: [] }); }); -test("an omp on another channel protocol fails: the daemon would refuse it", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { - const result = await preflight(`#!/bin/sh\necho '{"t":"hello","proto":2}'\nexec cat >/dev/null\n`, 5000); +test("a pi whose get_state fails fails the check with its error", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { + const result = await preflight(`#!/bin/sh\nread line\necho '{"type":"response","id":"preflight","command":"get_state","success":false,"error":"boom"}'\nexec cat >/dev/null\n`, 5000); assert.equal(result.code, 1); - assert.match(result.err[0], new RegExp(`^preflight failed: ${omp}: speaks channel protocol 2, not 1$`)); + assert.match(result.err[0], new RegExp(`^preflight failed: ${omp}: get_state failed: boom$`)); }); test("nothing omp started outlives the check", { skip: process.platform === "win32" && "a POSIX shell omp" }, async () => { const pidFile = join(base, "grandchild.pid"); // A grandchild (LSP, extension) that ignores omp's stdin closing. - const result = await preflight(`#!/bin/sh\nif [ "$1" = "--version" ]; then echo 18.99.0; exit 0; fi\nsleep 300 &\necho $! > "${pidFile}"\necho '{"t":"hello","proto":1}'\nexec cat >/dev/null\n`, 5000); + const result = await preflight(`#!/bin/sh\nif [ "$1" = "--version" ]; then echo 18.99.0; exit 0; fi\nsleep 300 &\necho $! > "${pidFile}"\nread line\necho '{"type":"response","id":"preflight","command":"get_state","success":true,"data":{}}'\nexec cat >/dev/null\n`, 5000); assert.equal(result.code, 0, result.err.join("\n")); const pid = Number(readFileSync(pidFile, "utf8")); const gone = () => { try { process.kill(pid, 0); return false; } catch { return true; } }; diff --git a/lib/hosts/recovery.test.mjs b/lib/hosts/recovery.test.mjs index 826e586b..109fc339 100644 --- a/lib/hosts/recovery.test.mjs +++ b/lib/hosts/recovery.test.mjs @@ -103,7 +103,7 @@ const phasePin = (digest = "a".repeat(64)) => ({ version: "0.8.0", releaseRepo: recovery.hostRecoveryDependencies.repo(), assets: { "ompweb-linux-x64.tar.gz": digest }, - npm: { tarball: "https://registry.npmjs.org/@kahme247/ompweb/-/ompweb-0.8.0.tgz", integrity: `sha512-${Buffer.alloc(64).toString("base64")}` }, + npm: { tarball: "https://registry.npmjs.org/@ompweb-dev/tau/-/tau-0.8.0.tgz", integrity: `sha512-${Buffer.alloc(64).toString("base64")}` }, }); const refusal = (state, code) => (error) => error instanceof recovery.HostRecoveryRefusal && error.state === state && error.code === code; const status = () => JSON.parse(readFileSync(join(stateRoot, "status.json"), "utf8")); @@ -178,7 +178,7 @@ test("recovery phases require an existing exactly matching prepared operation", assert.equal(JSON.parse(readFileSync(join(stateRoot, OPERATION, "decision.json"), "utf8")).decision, "commit"); for (const [label, changed] of [ ["force", { force: true }], - ["version", { version: "0.9.0", releasePin: { ...releasePin, version: "0.9.0", npm: { ...releasePin.npm, tarball: "https://registry.npmjs.org/@kahme247/ompweb/-/ompweb-0.9.0.tgz" } } }], + ["version", { version: "0.9.0", releasePin: { ...releasePin, version: "0.9.0", npm: { ...releasePin.npm, tarball: "https://registry.npmjs.org/@ompweb-dev/tau/-/tau-0.9.0.tgz" } } }], ["compatibility", { compatibility: { min: 12, max: 13 } }], ["pin", { releasePin: phasePin("b".repeat(64)) }], ]) await assert.rejects(recovery.startHostRecovery({ ...commit, ...changed }, deps), refusal("failed", "operation_conflict"), label); diff --git a/lib/hosts/session-index.test.mjs b/lib/hosts/session-index.test.mjs index 61305efc..cf56dc4e 100644 --- a/lib/hosts/session-index.test.mjs +++ b/lib/hosts/session-index.test.mjs @@ -5,7 +5,6 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { linkHost, linkLocalHost, ompChild, until } from "./link-driver.test-helper.mjs"; - const hub = await import("./hub.ts"); const index = await import("./session-index.ts"); const { HostOpError } = await import("./link-protocol.ts"); @@ -79,18 +78,18 @@ function serveQueuedSession(remote, listSessions, ops = {}) { listSessions, sessionFileExists: () => true, invalidateSessionLists: () => null, - // A v10 host opens a channel already past the runner's hello; a rejoin (`expectedChannel`) keeps its channel. + // A v10 host opens a channel already past its startup get_state; a rejoin (`expectedChannel`) keeps its channel. open: (args) => ({ ch: args.expectedChannel ?? "queued-ch", joined: args.expectedChannel !== undefined, pending: [], streaming: null, cwd: args.launch.cwd ?? "/remote/project", fellBack: false, launchAdvisor: false, advisorSpawned: false, autoApproveExtension: false }), }, async (message) => { if (message.type === "kill") return remote.post({ type: "exit", ch: message.ch, code: 0, signal: null }); if (message.type === "stdin") { const command = JSON.parse(message.line); - if (command.t === "cmd" && command.op === "follow_up") { + if (command.type === "follow_up") { commands.push(command); - queued.push(command.args.message); + queued.push(command.message); await native(message); - const event = { type: "queue_update", steering: [], followUp: [...queued], clientMessageIds: { steering: [], followUp: commands.map((command) => command.args.clientMessageId ?? null) } }; - return remote.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "event", event }) }); + const event = { type: "queue_update", steering: [], followUp: [...queued], clientMessageIds: { steering: [], followUp: commands.map((command) => command.clientMessageId ?? null) } }; + return remote.post({ type: "stdout", ch: message.ch, line: JSON.stringify(event) }); } } return native(message); diff --git a/lib/hosts/stream-snapshot.test.mjs b/lib/hosts/stream-snapshot.test.mjs index 1e2aa104..e503681f 100644 --- a/lib/hosts/stream-snapshot.test.mjs +++ b/lib/hosts/stream-snapshot.test.mjs @@ -11,9 +11,7 @@ test("a joining server gets rebuilt text and streamed tool arguments, never gues { type: "toolcall_start", contentIndex: 1, block: { type: "toolCall", id: "t", name: "write", arguments: {} } }, { type: "toolcall_delta", contentIndex: 1, delta: '{"path":"a"' }, ]) s.note({ type: "message_update", messageId: "m", message: { role: "assistant" }, assistantMessageEvent }); - const line = JSON.parse(s.whole()); - assert.equal(line.t, "event"); - const whole = line.event; + const whole = JSON.parse(s.whole()); assert.equal(whole.type, "message_update"); assert.equal(whole.message.content[0].text, "hello"); assert.deepEqual(whole.message.content[1].arguments, { path: "a" }); @@ -34,5 +32,5 @@ test("a queued user echo cannot clear an assistant message still streaming", () const snapshot = new StreamSnapshot(); snapshot.note({ type: "message_start", messageId: "assistant", message: { role: "assistant", content: [{ type: "text", text: "working" }] } }); snapshot.note({ type: "message_end", messageId: "user", message: { role: "user", content: "next" } }); - assert.equal(JSON.parse(snapshot.whole()).event.message.content[0].text, "working"); + assert.equal(JSON.parse(snapshot.whole()).message.content[0].text, "working"); }); diff --git a/lib/instrumentation-crash-policy.test.mjs b/lib/instrumentation-crash-policy.test.mjs index cf00ed17..11647851 100644 --- a/lib/instrumentation-crash-policy.test.mjs +++ b/lib/instrumentation-crash-policy.test.mjs @@ -17,7 +17,7 @@ const readOrEmpty = (file) => { }; // Runs instrumentation.node.ts's register() in a child, then `then`. Returns -// the exit status plus the journals under the agent dir and under ~/.omp (the +// the exit status plus the journals under the agent dir and under ~/.pi (the // default, un-isolated location). function runAfterRegister(then, { agentDir = "agent" } = {}) { const home = mkdtempSync(join(tmpdir(), "omp-web-crash-policy-")); @@ -34,7 +34,7 @@ function runAfterRegister(then, { agentDir = "agent" } = {}) { HOME: home, USERPROFILE: home, PI_CODING_AGENT_DIR: join(home, agentDir), - OMP_WEB_OMP_BIN: join(home, "missing-omp"), + TAU_PI_BIN: join(home, "missing-pi"), }, encoding: "utf8", timeout: 60_000, @@ -43,7 +43,7 @@ function runAfterRegister(then, { agentDir = "agent" } = {}) { status: result.status, stderr: result.stderr, journal: readOrEmpty(join(home, agentDir, "omp-web", "diagnostics.log")), - homeJournal: readOrEmpty(join(home, ".omp", "omp-web", "diagnostics.log")), + homeJournal: readOrEmpty(join(home, ".pi", "omp-web", "diagnostics.log")), }; } finally { rmSync(home, { recursive: true, force: true }); @@ -77,12 +77,12 @@ test("a client disconnect surfacing as uncaught `aborted` is journaled without e assert.doesNotMatch(journal, /\[crash\]/); }); -test("the journal follows an isolated agent dir and keeps ~/.omp/omp-web by default", () => { +test("the journal follows an isolated agent dir and keeps ~/.pi/omp-web by default", () => { const isolated = throwAfterRegister(`new Error("boom")`); assert.match(isolated.journal, /\[crash\] uncaughtException Error: boom/); assert.equal(isolated.homeJournal, "", "an isolated run must not write the real journal"); - const byDefault = throwAfterRegister(`new Error("boom")`, { agentDir: join(".omp", "agent") }); + const byDefault = throwAfterRegister(`new Error("boom")`, { agentDir: join(".pi", "agent") }); assert.match(byDefault.homeJournal, /\[crash\] uncaughtException Error: boom/); }); diff --git a/lib/message-outbox-review.test.mjs b/lib/message-outbox-review.test.mjs index 15ebea0f..28e9bfa6 100644 --- a/lib/message-outbox-review.test.mjs +++ b/lib/message-outbox-review.test.mjs @@ -41,17 +41,9 @@ async function add(sessionId, id, message = "held", mode = "prompt") { return outbox.runOutboxCommand(sessionId, { type: "outbox_add", scope: outbox.outboxScope(), id, message, mode }, false, "owner"); } -// The fixture speaks ompweb's frame shapes; this encodes each as the omp runner channel puts it on stdout. -function wire({ type, ...rest }, sessionId) { - if (type === "ready") return { t: "hello", proto: 1, pid: 1, sessionId, sessionFile: `/nonexistent/${sessionId}.jsonl`, cwd: "/" }; - if (type === "response") return { t: "res", id: rest.id, ok: rest.success, ...(rest.success ? { data: rest.data } : { error: rest.error }) }; - if (type.startsWith("host_") || ["prompt_result", "prompt_error", "notice"].includes(type)) return { t: type, ...rest }; - return { t: "event", event: { type, ...rest } }; -} -/** A channel stdin frame back in ompweb's command shape: `cmd` as `{type: op, id, ...args}`, others as `{type: t, ...}`. */ +/** A stdin frame tau wrote to the fake pi, parsed as a flat `{type, id, ...}` command. */ function unwire(line) { - const { t, op, args, ...rest } = JSON.parse(line); - return t === "cmd" ? { type: op, id: rest.id, ...args } : { type: t, ...rest }; + return JSON.parse(line); } // Only the external child is simulated: registry, wrapper admission, RpcProcess writes and SQLite are real. @@ -73,7 +65,7 @@ async function liveSession(sessionId, { fresh = false, supportsClientMessageIds if (event.type === "agent_start") transport.streaming = true; else if (event.type === "agent_end" && event.isTerminal !== false) transport.streaming = false; else if (event.type === "queue_update") transport.queue = { steering: event.steering, followUp: event.followUp, ...(event.clientMessageIds ? { clientMessageIds: event.clientMessageIds } : {}) }; - transport.line(JSON.stringify(wire(event, transport.sessionId))); + transport.line(JSON.stringify(event)); // `pi --mode rpc` frames are flat JSON lines. }, emitFor(command, event, key = command.type === "steer" || command.streamingBehavior === "steer" ? "steering" : "followUp") { assert.ok(command, "the native event must name its command"); @@ -100,7 +92,7 @@ async function liveSession(sessionId, { fresh = false, supportsClientMessageIds } : {})); callback(null); }, - onLine(listener) { transport.line = listener; queueMicrotask(() => transport.emit({ type: "ready" })); }, + onLine(listener) { transport.line = listener; }, onStderr() {}, onExit(listener) { transport.exit = listener; }, onResync(listener) { transport.resync = listener; }, @@ -475,7 +467,7 @@ test("another pending native control reply keeps the taint, and the settle read let stateReads = 0; transport.write = (line, callback) => { const command = unwire(line); - if (command.type === "get_available_commands") { + if (command.type === "get_commands") { transport.commands.push(command); heldControl = command; callback(null); @@ -814,7 +806,7 @@ test("an open ask holds a steer until it is answered and turns an agent-tool ste const sid = "open-ask-target"; const target = await liveSession(sid); const source = await liveSession("open-ask-source"); - target.transport.line(JSON.stringify({ t: "ui_request", id: 7, method: "formDialog", args: ["
"] })); + target.transport.line(JSON.stringify({ type: "ui_request", id: 7, method: "formDialog", args: ["
"] })); await until(() => target.session.isAwaitingAsk(), "the open ask"); await add(sid, "ask-steer", "after the answer", "steer"); await sleep(200); diff --git a/lib/omp/win32-spawn.test.mjs b/lib/omp/win32-spawn.test.mjs index b887958b..a079d570 100644 --- a/lib/omp/win32-spawn.test.mjs +++ b/lib/omp/win32-spawn.test.mjs @@ -9,7 +9,10 @@ import { PassThrough } from "node:stream"; // Each test that mocks child_process imports omp-cli fresh so it binds the fake. let freshImport = 0; -const { RpcProcess } = await import("./rpc-process.ts"); +const { RpcProcess, resolveTauExtensionPath } = await import("./rpc-process.ts"); +// pi takes its cwd from the spawn options, not an argument. +const extension = resolveTauExtensionPath(); +const PI_ARGS = ["--mode", "rpc", ...(extension ? ["--extension", extension] : [])]; /** Replace process.platform for the duration of one test (helper reads it at call time). */ function withPlatform(t, platform) { @@ -53,40 +56,40 @@ test("RpcProcess routes .cmd launchers through cmd.exe on win32", (t) => { const { harness } = startProcess("C:\\tools\\omp-work.cmd", CWD); assert.equal(harness.spawnCalls.length, 1); assert.equal(harness.spawnCalls[0].file, "cmd.exe"); - assert.deepEqual(harness.spawnCalls[0].args, ["/c", "C:\\tools\\omp-work.cmd", "--headless", "--cwd", CWD]); + assert.deepEqual(harness.spawnCalls[0].args, ["/c", "C:\\tools\\omp-work.cmd", ...PI_ARGS]); }); test("RpcProcess routes .bat launchers through cmd.exe on win32", (t) => { withPlatform(t, "win32"); const { harness } = startProcess("C:\\tools\\omp-work.bat", CWD); assert.equal(harness.spawnCalls[0].file, "cmd.exe"); - assert.deepEqual(harness.spawnCalls[0].args, ["/c", "C:\\tools\\omp-work.bat", "--headless", "--cwd", CWD]); + assert.deepEqual(harness.spawnCalls[0].args, ["/c", "C:\\tools\\omp-work.bat", ...PI_ARGS]); }); test("RpcProcess matches script extensions case-insensitively", (t) => { withPlatform(t, "win32"); const { harness } = startProcess("C:\\tools\\OMP-WORK.CMD", CWD); assert.equal(harness.spawnCalls[0].file, "cmd.exe"); - assert.deepEqual(harness.spawnCalls[0].args, ["/c", "C:\\tools\\OMP-WORK.CMD", "--headless", "--cwd", CWD]); + assert.deepEqual(harness.spawnCalls[0].args, ["/c", "C:\\tools\\OMP-WORK.CMD", ...PI_ARGS]); }); test("RpcProcess leaves .exe binaries untouched", () => { const { harness } = startProcess("C:\\tools\\omp.exe", CWD); assert.equal(harness.spawnCalls[0].file, "C:\\tools\\omp.exe"); - assert.deepEqual(harness.spawnCalls[0].args, ["--headless", "--cwd", CWD]); + assert.deepEqual(harness.spawnCalls[0].args, [...PI_ARGS]); }); test("RpcProcess leaves extensionless binaries untouched", () => { const { harness } = startProcess("omp", CWD); assert.equal(harness.spawnCalls[0].file, "omp"); - assert.deepEqual(harness.spawnCalls[0].args, ["--headless", "--cwd", CWD]); + assert.deepEqual(harness.spawnCalls[0].args, [...PI_ARGS]); }); test("RpcProcess never wraps .cmd on non-win32 platforms", (t) => { withPlatform(t, "linux"); const { harness } = startProcess("/usr/local/bin/omp-work.cmd", CWD); assert.equal(harness.spawnCalls[0].file, "/usr/local/bin/omp-work.cmd"); - assert.deepEqual(harness.spawnCalls[0].args, ["--headless", "--cwd", CWD]); + assert.deepEqual(harness.spawnCalls[0].args, [...PI_ARGS]); }); test("production launcher produces the exact Phase 5.3 spawn shape with options unchanged", (t) => { @@ -95,7 +98,7 @@ test("production launcher produces the exact Phase 5.3 spawn shape with options const { harness } = startProcess(launcher, CWD); const call = harness.spawnCalls[0]; assert.equal(call.file, "cmd.exe"); - assert.deepEqual(call.args, ["/c", launcher, "--headless", "--cwd", CWD]); + assert.deepEqual(call.args, ["/c", launcher, ...PI_ARGS]); // Everything except (file, args) must be byte-for-byte what the unwrapped // spawn produced before the patch. assert.equal(call.opts.cwd, CWD); @@ -110,11 +113,11 @@ test("probeOmpVersion routes .cmd launchers through cmd.exe on win32", async (t) const dir = mkdtempSync(join(tmpdir(), "omp-winspawn-probe-")); const bin = join(dir, "omp-work.cmd"); writeFileSync(bin, "stub\n"); - const previousBin = process.env.OMP_WEB_OMP_BIN; - process.env.OMP_WEB_OMP_BIN = bin; + const previousBin = process.env.TAU_PI_BIN; + process.env.TAU_PI_BIN = bin; t.after(() => { - if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; - else process.env.OMP_WEB_OMP_BIN = previousBin; + if (previousBin === undefined) delete process.env.TAU_PI_BIN; + else process.env.TAU_PI_BIN = previousBin; rmSync(dir, { recursive: true, force: true }); }); let captured = null; @@ -133,11 +136,11 @@ test("probeOmpVersion leaves .exe binaries untouched", async (t) => { const dir = mkdtempSync(join(tmpdir(), "omp-winspawn-probe-")); const bin = join(dir, "omp.exe"); writeFileSync(bin, "stub\n"); - const previousBin = process.env.OMP_WEB_OMP_BIN; - process.env.OMP_WEB_OMP_BIN = bin; + const previousBin = process.env.TAU_PI_BIN; + process.env.TAU_PI_BIN = bin; t.after(() => { - if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; - else process.env.OMP_WEB_OMP_BIN = previousBin; + if (previousBin === undefined) delete process.env.TAU_PI_BIN; + else process.env.TAU_PI_BIN = previousBin; rmSync(dir, { recursive: true, force: true }); }); let captured = null; @@ -156,11 +159,11 @@ test("probeOmpVersion never wraps .cmd on non-win32 platforms", async (t) => { const dir = mkdtempSync(join(tmpdir(), "omp-winspawn-probe-")); const bin = join(dir, "omp-work.cmd"); writeFileSync(bin, "stub\n"); - const previousBin = process.env.OMP_WEB_OMP_BIN; - process.env.OMP_WEB_OMP_BIN = bin; + const previousBin = process.env.TAU_PI_BIN; + process.env.TAU_PI_BIN = bin; t.after(() => { - if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; - else process.env.OMP_WEB_OMP_BIN = previousBin; + if (previousBin === undefined) delete process.env.TAU_PI_BIN; + else process.env.TAU_PI_BIN = previousBin; rmSync(dir, { recursive: true, force: true }); }); let captured = null; @@ -180,21 +183,29 @@ test("real .cmd launcher through the real spawn path receives spaced arguments i const bin = join(dir, "fake-omp.cmd"); const argsFile = join(dir, "args.txt"); // The engine stub announces readiness like omp, then records its raw argument - // tail so the test can pin cmd.exe quoting of the spaced --cwd argument. + // tail so the test can pin cmd.exe quoting of the spaced --session argument. writeFileSync(bin, [ "@echo off", "echo {\"t\":\"hello\",\"proto\":1}", "> \"%~dp0args.txt\" echo %*", "", ].join("\r\n")); - // The spawn cwd itself contains a literal space — the exact production shape - // of a project directory passed as --cwd. + // The spawn cwd contains a literal space, so the --session file path the + // launcher passes does too. const spacedCwd = join(dir, "temp dir x"); mkdirSync(spacedCwd); + const previousExtension = process.env.TAU_NO_EXTENSION; + process.env.TAU_NO_EXTENSION = "1"; + t.after(() => { + if (previousExtension === undefined) delete process.env.TAU_NO_EXTENSION; + else process.env.TAU_NO_EXTENSION = previousExtension; + }); + const sessionFile = join(spacedCwd, "s.jsonl"); const { promise: exited, resolve: resolveExit } = Promise.withResolvers(); new RpcProcess({ cwd: spacedCwd, + extraArgs: ["--session", sessionFile], dependencies: { resolveOmpBin: () => bin }, // real child_process.spawn — no seam onExit: (info) => resolveExit(info), }); @@ -204,7 +215,7 @@ test("real .cmd launcher through the real spawn path receives spaced arguments i const info = await exited; assert.equal(info.code, 0); const rawTail = readFileSync(argsFile, "utf8").replace(/\r\n/g, "\n").trim(); - assert.equal(rawTail, `--headless --cwd "${spacedCwd}"`); + assert.equal(rawTail, `--mode rpc --session "${sessionFile}"`); }); test("real .cmd launcher through the real version probe returns its stdout", { skip: process.platform !== "win32", timeout: 30000 }, async (t) => { @@ -218,11 +229,11 @@ test("real .cmd launcher through the real version probe returns its stdout", { s "echo omp/99.9.9-win", "", ].join("\r\n")); - const previousBin = process.env.OMP_WEB_OMP_BIN; - process.env.OMP_WEB_OMP_BIN = bin; + const previousBin = process.env.TAU_PI_BIN; + process.env.TAU_PI_BIN = bin; t.after(() => { - if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; - else process.env.OMP_WEB_OMP_BIN = previousBin; + if (previousBin === undefined) delete process.env.TAU_PI_BIN; + else process.env.TAU_PI_BIN = previousBin; }); const { getOmpVersion } = await import(`./omp-cli.ts?fresh=${freshImport++}`); assert.equal(await getOmpVersion(), "omp/99.9.9-win"); diff --git a/lib/outbox-handoff.test.mjs b/lib/outbox-handoff.test.mjs index 1df1df63..9654d9aa 100644 --- a/lib/outbox-handoff.test.mjs +++ b/lib/outbox-handoff.test.mjs @@ -4,7 +4,6 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test, { after } from "node:test"; import { linkLocalHost, listedSession, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; - const SESSION = "01a0e6b0-d916-7610-8343-f4a766ba0052"; const agentDir = mkdtempSync(join(tmpdir(), "omp-web-outbox-handoff-")); const previousAgentDir = process.env.PI_CODING_AGENT_DIR; @@ -310,10 +309,10 @@ test("a child another server started is awaited while this server adopts it, the daemon.serve(daemonOps, async (message) => { if (message.type !== "stdin") return; const command = JSON.parse(message.line); - if (command.op === "get_state") await adopting; - if (command.op !== "get_client_message_status") return omp(message); + if (command.type === "get_state") await adopting; + if (command.type !== "get_client_message_status") return omp(message); asked.push(command); - await daemon.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "res", id: command.id, ok: true, data: nativeReply() }) }); + await daemon.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data: nativeReply() }) }); }); t.after(async () => { const disposing = getRpcSession(SESSION)?.destroyAndWait(); diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index d730f7f4..a0b3030d 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -17,9 +17,9 @@ const OLD = "0.1.0"; const NEW = "9.9.9"; const FAST = { bootTimeoutMs: 800, hostTimeoutMs: 800, pollMs: 5, settleMs: 5 }; const releasePin = { - version: NEW, releaseRepo: "ompweb-dev/ompweb", + version: NEW, releaseRepo: "ompweb-dev/tau", assets: { [`ompweb-${process.platform === "win32" ? "windows" : process.platform}-${process.arch}${process.platform === "win32" ? ".zip" : ".tar.gz"}`]: "a".repeat(64) }, - npm: { tarball: `https://registry.npmjs.org/@kahme247/ompweb/-/ompweb-${NEW}.tgz`, integrity: `sha512-${Buffer.alloc(64).toString("base64")}` }, + npm: { tarball: `https://registry.npmjs.org/@ompweb-dev/tau/-/tau-${NEW}.tgz`, integrity: `sha512-${Buffer.alloc(64).toString("base64")}` }, }; /** A release tree the worker accepts: `version.txt` is what a started "server" or "host" reads to say which release it runs. */ diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index aa3ede83..71a47f25 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -6,7 +6,6 @@ import { join } from "node:path"; import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { LinkDriver, linkLocalHost, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; - /** A new omp-web process: fresh tracker, same agent dir. */ function restart() { globalThis.__ompResumeTracker = undefined; diff --git a/lib/transport-stats.test.ts b/lib/transport-stats.test.ts index bbb1126c..769d3728 100644 --- a/lib/transport-stats.test.ts +++ b/lib/transport-stats.test.ts @@ -62,7 +62,7 @@ test("diagnostics exclude unconfirmed deliveries and failed commands from succes test("commands the web app may answer without omp count as transport only, never as omp time", () => { const ok = { metric: "action", transport: "ws", outcome: "ok", sentAt: 0, gotAt: 10, recvAt: 2, repliedAt: 3 }; - const rows = diagnosticStats([{ ...ok, type: "predict_word" }, { ...ok, type: "get_btw_history" }]); + const rows = diagnosticStats([{ ...ok, type: "get_btw_history" }, { ...ok, type: "btw_cancel" }]); assert.deepEqual(rows.map((row) => [row.metric, row.count]), [["transportMs", 2]]); }); diff --git a/lib/upgrade-plan-coordinator.test.mjs b/lib/upgrade-plan-coordinator.test.mjs index ce0ac349..17dd6ad9 100644 --- a/lib/upgrade-plan-coordinator.test.mjs +++ b/lib/upgrade-plan-coordinator.test.mjs @@ -33,8 +33,8 @@ const { buildUpgradePlan, getUpgradePlan, upgradePlanPath, upgradePlannedHosts, const state = await import("./self-update-state.ts"); const id = "12345678-1234-4234-8234-123456789012"; const target = "0.8.0"; -const approvedPin = { version: target, releaseRepo: "ompweb-dev/ompweb", assets: { "ompweb-linux-x64.tar.gz": "a".repeat(64) }, - npm: { tarball: `https://registry.npmjs.org/@kahme247/ompweb/-/ompweb-${target}.tgz`, integrity: `sha512-${Buffer.alloc(64).toString("base64")}` } }; +const approvedPin = { version: target, releaseRepo: "ompweb-dev/tau", assets: { "ompweb-linux-x64.tar.gz": "a".repeat(64) }, + npm: { tarball: `https://registry.npmjs.org/@ompweb-dev/tau/-/tau-${target}.tgz`, integrity: `sha512-${Buffer.alloc(64).toString("base64")}` } }; let metadataDigest = "a".repeat(64); let metadataNpm = approvedPin.npm; let npmRequests = 0; diff --git a/lib/user-level-config-routes.test.mjs b/lib/user-level-config-routes.test.mjs index fef7cbae..3c322a20 100644 --- a/lib/user-level-config-routes.test.mjs +++ b/lib/user-level-config-routes.test.mjs @@ -19,28 +19,29 @@ writeFileSync(join(scratch, "skills.json"), JSON.stringify({ ], warnings: [], })); -writeFileSync(join(scratch, "plugins.json"), JSON.stringify({ - npm: [{ name: "global-npm", version: "1.0.0", path: join(scratch, "missing"), enabled: true }], - marketplace: [{ id: "here@market", scope: "project", entries: [{ scope: "project" }] }, { id: "mine@market", scope: "user", entries: [{ scope: "user" }] }], -})); +// `pi list` prints each package's source, then its installed path. +writeFileSync(join(scratch, "plugins.txt"), [ + "User packages:", " global-npm", ` ${join(scratch, "missing")}`, " mine@market", ` ${join(scratch, "mine")}`, + "", "Project packages:", " here@market", ` ${join(scratch, "here")}`, "", +].join("\n")); const bin = join(scratch, "omp"); writeFileSync(bin, `#!/bin/sh echo "$(pwd) $*" >> '${log}' case "$1 $2" in "skill list") cat '${join(scratch, "skills.json")}' ;; - "plugin list") cat '${join(scratch, "plugins.json")}' ;; + "list ") cat '${join(scratch, "plugins.txt")}' ;; *) echo '{}' ;; esac `, { mode: 0o755 }); // Nothing of the real home is read: omp-web's own lookups (skill locks, MCP files) go under the scratch home. Bun's // os.homedir() ignores a HOME set at run time, so it is replaced too. -const ENV_KEYS = ["OMP_WEB_OMP_BIN", "PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "CLAUDE_CONFIG_DIR"]; +const ENV_KEYS = ["TAU_PI_BIN", "OMP_WEB_OMP_BIN", "PI_CODING_AGENT_DIR", "PI_CONFIG_DIR", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "CLAUDE_CONFIG_DIR"]; const saved = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); for (const key of ENV_KEYS) delete process.env[key]; const home = join(scratch, "home"); mkdirSync(home); -process.env.OMP_WEB_OMP_BIN = bin; +process.env.TAU_PI_BIN = bin; process.env.PI_CODING_AGENT_DIR = agentDir; process.env.HOME = process.env.USERPROFILE = home; const scratchOs = { ...os, homedir: () => home }; @@ -98,7 +99,7 @@ test("plugins without a cwd: the user's only, and only global changes", { skip } const installed = await post(plugins, { action: "install", source: "npm:demo", scope: "global" }); assert.equal(installed.status, 200); assert.deepEqual((await installed.json()).packages.map((pkg) => pkg.source), ["global-npm", "mine@market"]); - assert.deepEqual(calls(), [`${agentDir} plugin list --json`, `${agentDir} plugin install npm:demo --json`, `${agentDir} plugin list --json`]); + assert.deepEqual(calls(), [`${agentDir} list`, `${agentDir} install npm:demo`, `${agentDir} list`]); const project = await post(plugins, { action: "install", source: "npm:demo", scope: "project" }); assert.equal(project.status, 400); @@ -115,7 +116,7 @@ test("a missing agent directory is created owner-only before omp runs there, not const body = await listed.json(); assert.deepEqual([body.packages.map((pkg) => pkg.source), body.diagnostics], [["global-npm", "mine@market"], []]); assert.equal(statSync(fresh).mode & 0o777, 0o700); - assert.deepEqual(calls(), [`${fresh} plugin list --json`]); + assert.deepEqual(calls(), [`${fresh} list`]); rmSync(join(scratch, "fresh"), { recursive: true }); const installed = await post(plugins, { action: "install", source: "npm:demo", scope: "global" }); diff --git a/scripts/use-omp-build.test.mjs b/scripts/use-omp-build.test.mjs deleted file mode 100644 index 915183c7..00000000 --- a/scripts/use-omp-build.test.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import assert from "node:assert/strict"; -import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { delimiter, join } from "node:path"; -import test from "node:test"; - -// A ZIP containing index.json and fixture.tgz, readable by both unzip and Windows' bundled bsdtar. -const archive = Buffer.from("UEsDBBQAAAAAAAAAIVyswTZ6JAAAACQAAAAKAAAAaW5kZXguanNvbnsiQG9oLW15LXBpL2ZpeHR1cmUiOiJmaXh0dXJlLnRneiJ9ClBLAwQUAAAAAAAAACFczMCKaRAAAAAQAAAACwAAAGZpeHR1cmUudGd6Zml4dHVyZSBwYWNrYWdlClBLAQIUAxQAAAAAAAAAIVyswTZ6JAAAACQAAAAKAAAAAAAAAAAAAACkgQAAAABpbmRleC5qc29uUEsBAhQDFAAAAAAAAAAhXMzAimkQAAAAEAAAAAsAAAAAAAAAAAAAAKSBTAAAAGZpeHR1cmUudGd6UEsFBgAAAAACAAIAcQAAAIUAAAAAAA==", "base64"); - -test("runner packages extract with the native ZIP tool despite a shadowing tar, and failed extraction keeps the old vendor", async (t) => { - const root = mkdtempSync(join(tmpdir(), "omp-build-extract-")); - t.after(() => rmSync(root, { recursive: true, force: true })); - const scripts = join(root, "scripts"); - const vendor = join(root, "vendor"); - const shadow = join(root, "shadow-path"); - for (const dir of [scripts, vendor, shadow]) mkdirSync(dir); - const script = join(scripts, "use-omp-build.ts"); - copyFileSync(new URL("../runner/scripts/use-omp-build.ts", import.meta.url), script); - writeFileSync(join(root, "omp-build.json"), JSON.stringify({ repo: "fixture/omp", tag: "v1.0.0-int.202601010000.g1234567" })); - writeFileSync(join(vendor, "old-package.tgz"), "previous vendor"); - // Selecting tar from PATH must fail rather than accidentally pass with a ZIP-capable tar. - writeFileSync(join(shadow, process.platform === "win32" ? "tar.exe" : "tar"), "not an executable", { mode: 0o700 }); - let body = Buffer.from("not a ZIP"); - const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(body) }); - t.after(() => server.stop(true)); - const env = { ...process.env, OMP_BUILD_RELEASES: server.url.origin, PATH: `${shadow}${delimiter}${process.env.PATH ?? ""}` }; - const run = async () => { - const child = Bun.spawn([process.execPath, script], { cwd: root, env, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); - const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); - return { code, output: stdout + stderr }; - }; - const failed = await run(); - assert.notEqual(failed.code, 0, failed.output); - assert.equal(readFileSync(join(vendor, "old-package.tgz"), "utf8"), "previous vendor"); - body = archive; - const installed = await run(); - assert.equal(installed.code, 0, installed.output); - assert.deepEqual(JSON.parse(readFileSync(join(vendor, "index.json"), "utf8")), { "@oh-my-pi/fixture": "fixture.tgz" }); - assert.equal(readFileSync(join(vendor, "fixture.tgz"), "utf8"), "fixture package\n"); - assert.equal(existsSync(join(vendor, "old-package.tgz")), false); - assert.equal(existsSync(`${vendor}.new`), false); -}); diff --git a/tests/fixtures/multi-server-omp.mjs b/tests/fixtures/multi-server-omp.mjs index 83cf6837..c25e9eb6 100644 --- a/tests/fixtures/multi-server-omp.mjs +++ b/tests/fixtures/multi-server-omp.mjs @@ -9,8 +9,8 @@ const sessionId = process.env.OMP_MULTI_SESSION_ID; const sessionFile = process.env.OMP_MULTI_SESSION_FILE; const record = (entry) => fs.appendFileSync(process.env.OMP_MULTI_LOG, `${JSON.stringify({ pid: process.pid, ...entry })}\n`); const send = (frame) => process.stdout.write(`${JSON.stringify(frame)}\n`); -const out = (event) => send({ t: "event", event }); -const resumed = process.argv.includes("--resume"); +const out = (event) => send(event); +const resumed = process.argv.includes("--session"); record({ type: "start", resumed }); let streaming = false; let messages = []; @@ -30,19 +30,17 @@ const end = () => { out({ type: "agent_end", isTerminal: true, messages: [] }); out({ type: "session_settled" }); }; -send({ t: "hello", proto: 1, pid: process.pid, sessionId, sessionFile, cwd: process.cwd() }); readline.createInterface({ input: process.stdin }).on("line", (line) => { const command = JSON.parse(line); record({ type: "stdin", command }); - if (command.t === "ui_response") { + if (command.type === "ui_response") { // ompweb names the dialog by its wire id as a string. record({ type: "answer", id: String(command.id) }); return end(); } - if (command.t !== "cmd") return; - const { args } = command; - const reply = (data = {}) => send({ t: "res", id: command.id, ok: true, data }); - switch (command.op) { + const args = command; + const reply = (data = {}) => send({ type: "response", id: command.id, command: command.type, success: true, data }); + switch (command.type) { case "get_state": return reply({ sessionId, sessionFile, cwd: process.cwd(), supportsClientMessageIds: true, isStreaming: streaming, isSettled: !streaming, isCompacting: false, queuedMessages: [], messages }); case "get_subagents": return reply({ subagents: [] }); case "get_btw_history": return reply({ records: [] }); @@ -62,7 +60,7 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => { persist(user, args.clientMessageId); out({ type: "message_end", messageId: `u${n}`, message: user, ...correlation }); if (args.message === "ask") { - send({ t: "ui_request", id: n, method: "askDialog", args: [[{ id: "pick", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }]] }); + send({ type: "ui_request", id: n, method: "askDialog", args: [[{ id: "pick", question: "Pick one", options: [{ label: "A" }, { label: "B" }] }]] }); return; } const assistant = { role: "assistant", content: [{ type: "text", text: "" }], timestamp: Date.now() }; From 2a5f91e906565f1969bc6827c6542193f03f55be Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 17:24:54 +0000 Subject: [PATCH 003/129] refactor(hosts): drop the TUI host socket and its adopted channels Only the fork's omp runner dialed the daemon's host socket; pi never does, so the listener, ChannelTable.adopt and the adopted-channel branches are dead. The startup get_state now waits channelReadyMs, as the hub does for an open, instead of the 15 s command timeout. The v10/v11 upgrade test exercised published ompweb updaters that install @kahme247/ompweb, a path tau hosts never take. --- lib/hosts/daemon-channels.test.mjs | 22 -- lib/hosts/daemon-channels.ts | 46 +-- lib/hosts/daemon.ts | 16 +- lib/hosts/host-cli.ts | 5 +- lib/hosts/omp-socket.test.mjs | 124 ------- lib/hosts/omp-socket.ts | 143 -------- lib/hosts/v10-upgrade.integration.test.mjs | 367 --------------------- 7 files changed, 18 insertions(+), 705 deletions(-) delete mode 100644 lib/hosts/omp-socket.test.mjs delete mode 100644 lib/hosts/omp-socket.ts delete mode 100644 lib/hosts/v10-upgrade.integration.test.mjs diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index 0e68a9ec..d7546a81 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -277,28 +277,6 @@ test("a prompt's outcome reaches the other members uncorrelated, so the elected await h.table.stop(); }); -test("an adopted channel has no idle stop and is never recorded as running", async () => { - const saved = process.env.OMP_WEB_DISCONNECT_DESTROY_MS; - process.env.OMP_WEB_DISCONNECT_DESTROY_MS = "1"; // an unattended spawned child stops after 1 ms - try { - const control = harness(), first = await control.table.open(control.a, { sessionId: SAVED, launch }); - assert.ok(first.ch); - const h = harness(), spawned = await h.spawn(launch); - const ch = await h.table.adopt(spawned, launch); - assert.deepEqual(h.changed, [ch]); - await new Promise(resolve => setTimeout(resolve, 30)); - assert.deepEqual(control.children[0].kills, [false], "the same unattended child is stopped when the daemon spawned it"); - assert.deepEqual(h.children[0].kills, [], "a lifecycle stop never kills a TUI's runner"); - assert.equal(h.table.size, 1); - ev(h.children[0], { type: "agent_start" }); - assert.equal(h.table.activeTurns, 1); - assert.deepEqual(h.table.running(), []); - await control.table.stop(); await h.table.stop(); - } finally { - if (saved === undefined) delete process.env.OMP_WEB_DISCONNECT_DESTROY_MS; else process.env.OMP_WEB_DISCONNECT_DESTROY_MS = saved; - } -}); - test("shared removal never kills; permanent removal during spawn cannot attach a dead shared member", async () => { const removed = harness(); await removed.table.open(removed.a, { sessionId: SAVED, launch }); removed.table.linkGone(removed.a); assert.equal(removed.table.size, 1); await removed.table.stop(); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 450d4f13..0a15b8dc 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -24,10 +24,7 @@ type Channel = { commands: Map; /** `onReply`: runs as pi's successful reply is read, before the next stdout line. */ internal: Map; - ready: Promise; noteReady(frame: WireFrame | null): void; readyTimer: NodeJS.Timeout; startup: Promise; exited: boolean; opened: boolean; fullFallback: boolean; forceTimer?: NodeJS.Timeout; - /** omp the daemon did not start (a TUI's runner on the host socket): no idle stop, never recovered. */ - adopted?: boolean; sessionMovePending?: boolean; replacing?: boolean; /** The link holding the history-edit lease: other links' history mutations are refused. */ @@ -47,7 +44,6 @@ type ChannelDeps = { sessionsChanged?(): void; channelsChanged?(ch: string): void; }; -const collision = () => new HostOpError(409, "session_running_elsewhere", "This session is already running on another link"); const invalid = (message = "Invalid channel request") => new HostOpError(400, "invalid_request", message); /** A process start's launch, from what its opener asked: the wire never names the credentials server (it is the opening * link's own, and only when the hub asks), and a configuration version passes only in its one valid form. */ @@ -242,34 +238,19 @@ export class ChannelTable { } } - /** A channel whose omp the daemon did not start (a TUI's runner on the host socket); resolves with its id once hello is read. - * Refuses (409) a session that already has a channel: two omps must never write one session file. */ - async adopt(spawned: SpawnResult, launch: SpawnRequest, sessionId?: string): Promise { - const prepared = this.deps.prepareLaunch(launch); - const identity = (prepared.sessionFile ? this.identity(prepared) : null) ?? (sessionId && isValidSessionId(sessionId) ? sessionId : null); - const key = identity ?? (prepared.sessionFile || null); - if (this.find(identity, prepared.sessionFile) || (key !== null && this.spawning.has(key))) throw collision(); - const channel = await this.create(prepared, identity, undefined, spawned); - channel.opened = true; - this.deps.channelsChanged?.(channel.ch); - return channel.ch; - } - - private async create(launch: SpawnRequest, identity: string | null, preparingLinkId?: string, adopted?: SpawnResult): Promise { + private async create(launch: SpawnRequest, identity: string | null, preparingLinkId?: string): Promise { this.spawningCount++; try { - if (this.stopped) { adopted?.transport.killTree(true); throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); } - const spawned = adopted ?? await this.deps.spawn(launch); + if (this.stopped) throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); + const spawned = await this.deps.spawn(launch); if (this.stopped) { spawned.transport.killTree(true); throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); } - const { promise: ready, resolve: noteReady } = Promise.withResolvers(); - const readyTimer = setTimeout(() => noteReady(null), LINK_LIMITS.channelReadyMs); readyTimer.unref?.(); const ch = randomUUID(); const channel: Channel = { ...spawned, ch, launch, pending: new PendingRequests(LINK_LIMITS.pendingBytes, identity), snapshot: new StreamSnapshot(), members: new Map(), aliases: new Set(identity ? [identity] : []), files: new Set(launch.sessionFile ? [launch.sessionFile] : []), - commands: new Map(), internal: new Map(), ready, noteReady, readyTimer, - startup: Promise.resolve(), exited: false, opened: false, fullFallback: false, adopted: adopted !== undefined }; + commands: new Map(), internal: new Map(), + startup: Promise.resolve(), exited: false, opened: false, fullFallback: false }; this.channels.set(ch, channel); - channel.lifecycle = new ChannelLifecycle({ stop: reason => { if (channel.adopted) return; this.deps.log(`channel ${ch}: stopping (${reason})`); this.stopChannel(channel, reason); }, onRunning: () => this.deps.runningChanged?.() }); + channel.lifecycle = new ChannelLifecycle({ stop: reason => { this.deps.log(`channel ${ch}: stopping (${reason})`); this.stopChannel(channel, reason); }, onRunning: () => this.deps.runningChanged?.() }); if (preparingLinkId) channel.lifecycle.setPreparing(preparingLinkId, true); channel.shared = new SharedRequests({ members: () => [...channel.members.keys()], isUp: id => channel.members.get(id)?.link.isUp() ?? false, deliver: (id, lines) => { const member = channel.members.get(id); if (member) for (const line of lines) this.deliver(channel, member, { type: "stdout", ch, line }); }, @@ -283,7 +264,7 @@ export class ChannelTable { }); spawned.transport.onExit((code, signal) => { if (startupStderr) this.deps.log(`channel ${ch}: omp exited during startup (code ${code ?? "null"}, signal ${signal ?? "none"}): ${JSON.stringify(startupStderr.toString("utf8"))}`); - channel.exited = true; clearTimeout(channel.readyTimer); channel.noteReady(null); clearTimeout(channel.forceTimer); + channel.exited = true; clearTimeout(channel.forceTimer); channel.lifecycle?.dispose(); channel.snapshot.clear(); for (const pending of channel.internal.values()) { clearTimeout(pending.timer); pending.reject(new Error("omp exited")); } channel.internal.clear(); channel.commands.clear(); this.channels.delete(ch); @@ -305,25 +286,24 @@ export class ChannelTable { private async configure(channel: Channel): Promise { if (channel.exited) return; try { - const res = await this.command(channel, "get_state", {}); - clearTimeout(channel.readyTimer); + // Readiness: pi answers once its extensions have loaded, which may take as long as the hub waits for an open. + const res = await this.command(channel, "get_state", {}, undefined, LINK_LIMITS.channelReadyMs); if (isRecord(res.data)) { this.noteIdentity(channel, res.data as WireFrame); } } catch (error) { - clearTimeout(channel.readyTimer); if (channel.exited) return; - if (!channel.adopted) channel.transport.killTree(true); + channel.transport.killTree(true); throw new HostOpError(502, "host_process_exited", error instanceof Error ? error.message : "pi did not answer get_state"); } } - private command(channel: Channel, op: string, args: Record, onReply?: () => void): Promise { + private command(channel: Channel, op: string, args: Record, onReply?: () => void, timeoutMs = 15000): Promise { if (channel.exited) return Promise.reject(new Error("pi exited")); const id = String(++this.commandId); const command = { ...args, type: op, id }; const { promise, resolve, reject } = Promise.withResolvers(); - const timer = setTimeout(() => { channel.internal.delete(id); channel.lifecycle?.forgetCommand(id); reject(new Error(`pi ${op} timed out`)); }, 15000); timer.unref?.(); + const timer = setTimeout(() => { channel.internal.delete(id); channel.lifecycle?.forgetCommand(id); reject(new Error(`pi ${op} timed out`)); }, timeoutMs); timer.unref?.(); channel.internal.set(id, { resolve, reject, timer, onReply }); channel.lifecycle?.noteStdin(command); channel.transport.write(JSON.stringify(command) + "\n", error => { if (error) { const pending = channel.internal.get(id); if (!pending) return; clearTimeout(pending.timer); channel.internal.delete(id); channel.lifecycle?.forgetCommand(id, true); reject(error); } @@ -528,7 +508,7 @@ export class ChannelTable { } running(): HostResumeEntry[] { // A recovered session starts on the version already applied: the resume manifest never names one. - return [...this.channels.values()].filter(channel => !channel.adopted && (channel.lifecycle?.isRunning || channel.resuming) && channel.pending.sessionId && channel.launch.sessionFile && !channel.sessionMovePending) + return [...this.channels.values()].filter(channel => (channel.lifecycle?.isRunning || channel.resuming) && channel.pending.sessionId && channel.launch.sessionFile && !channel.sessionMovePending) .map(channel => { const launch = { ...channel.launch }; delete launch.configVersion; return { sessionId: channel.pending.sessionId!, launch }; }); } /** Resumes each entry once; returns the entries whose resume failed. */ diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index ffd4f67e..308b9b9c 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -20,7 +20,6 @@ import { runOmpCli } from "../omp/plugins-cli"; import { HostResumeTracker, type HostResumeEntry } from "./host-resume"; import { CONFIG_VERSION_RE, CREATION_ID_RE, encodeLine, HostOpError, isHostOp, LINK_LIMITS, LINK_PROTOCOL_VERSION, SESSION_OP_PARAMS, type DownMessage, type OpenChannelRequest, type UnknownMessage } from "./link-protocol"; import { localHost, resolveSpawnCwdResult } from "./local-host"; -import { listenHostSocket, type HostSocket } from "./omp-socket"; import { sessionOps } from "./session-ops"; import packageJson from "../../package.json"; import { acknowledgeHostUpdateReceipt, checkHostUpdates, configureHostUpdateSafety, getHostUpdateOperation, hostUpdateBlocksNewWork, HostUpdateError, startHostUpdate } from "./updates"; @@ -96,8 +95,7 @@ export interface HostDaemon { started: Promise; control(command: HostControlCommand): HostControlStatus; } -/** `hostSocket`: where omps started from a TUI attach (`hostSocketPath()`); unset, none can. */ -type DaemonOptions = { allowHttp: boolean; url?: string; token?: string; links?: HostLink[]; hostSocket?: string }; +type DaemonOptions = { allowHttp: boolean; url?: string; token?: string; links?: HostLink[] }; export function runHostDaemon(options: DaemonOptions): HostDaemon { const explicit = options.url !== undefined && options.token !== undefined ? [{ url: options.url, token: options.token }] : options.links; const initial = explicit ?? readHostLinks(); @@ -178,14 +176,6 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { sessionsChanged, channelsChanged, }); - const hostSocket: Promise = options.hostSocket === undefined ? Promise.resolve(undefined) : listenHostSocket(options.hostSocket, { - adopt: async (spawned, launch, sessionId) => { - if (stopped) throw new HostOpError(503, "host_stopping", "This host is stopping"); - if (drained) throw new HostOpError(409, "host_drained", "This host is locally drained for maintenance"); - return channels.adopt(spawned, launch, sessionId); - }, - log, - }).catch(error => { log("omps started from a TUI cannot attach: " + reason(error)); return undefined; }); configureHostUpdateSafety(() => drained ? "This host is locally drained for maintenance." : busyReason(), { drained: () => drained, sessions: () => channels.size }); const uploads = new StagedUploads(ack => { const link = uploadAttempts.get(ack.id + ":" + ack.attempt); @@ -516,7 +506,7 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { resume.freeze(); // The configuration first: its requests to a server are aborted at once, so no start waiting on them holds the stop. const configStopped = config.stop(); - stopping = (async () => { await Promise.all([...links.values()].map(link => link.stop())); await Promise.all([...maintenanceLinks.values()].map(link => link.stop())); await Promise.all([...stops, ...[...services.values()].map(service => service.stop())]); await (await hostSocket)?.close(); await channels.stop(); await configStopped; await forwarder.stop(); resume.dispose(); finish(code); })(); + stopping = (async () => { await Promise.all([...links.values()].map(link => link.stop())); await Promise.all([...maintenanceLinks.values()].map(link => link.stop())); await Promise.all([...stops, ...[...services.values()].map(service => service.stop())]); await channels.stop(); await configStopped; await forwarder.stop(); resume.dispose(); finish(code); })(); return stopping; } // Links first: a recovered sharing session needs its link to start. @@ -549,6 +539,6 @@ export function runHostDaemon(options: DaemonOptions): HostDaemon { operationsInFlight--; if (!stopped) for (const link of links.values()) link.start(); }); - const started = Promise.all([startupSweep, startupRecovery, versionRead, hostSocket]).then(() => {}); + const started = Promise.all([startupSweep, startupRecovery, versionRead]).then(() => {}); return { stop: () => shutdown(0), done, control, started }; } diff --git a/lib/hosts/host-cli.ts b/lib/hosts/host-cli.ts index b5e8b26d..5a5e7c50 100644 --- a/lib/hosts/host-cli.ts +++ b/lib/hosts/host-cli.ts @@ -69,15 +69,14 @@ async function main(argv: string[]): Promise { return 1; } // Login/logout need none of the daemon, which jiti would otherwise transpile on every run. - const [{ runHostDaemon }, { hostSocketPath }] = await Promise.all([import("./daemon"), import("./omp-socket")]); + const { runHostDaemon } = await import("./daemon"); let daemon: HostDaemon | undefined; const endpoint = await createHostControlServer((command) => { if (!daemon) throw new Error("The host daemon is starting"); return daemon.control(command); }); try { - // Windows has no host socket yet (a current-user named pipe is open in the runner spec). - daemon = runHostDaemon({ allowHttp: argv.includes("--allow-http"), hostSocket: process.platform === "win32" ? undefined : hostSocketPath() }); + daemon = runHostDaemon({ allowHttp: argv.includes("--allow-http") }); // Worker cutover starts fail-closed; ordinary hosts have no maintenance environment. if (process.env.OMP_WEB_HOST_DRAINED === "1") daemon.control("drain"); const stop = () => void daemon!.stop(); diff --git a/lib/hosts/omp-socket.test.mjs b/lib/hosts/omp-socket.test.mjs deleted file mode 100644 index 51b14d43..00000000 --- a/lib/hosts/omp-socket.test.mjs +++ /dev/null @@ -1,124 +0,0 @@ -import assert from "node:assert/strict"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs"; -import { createConnection } from "node:net"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { createInterface } from "node:readline"; -import test, { after } from "node:test"; -import { ChannelTable } from "./daemon-channels.ts"; -import { CHANNEL_PROTO, hostSocketPath, listenHostSocket } from "./omp-socket.ts"; -import * as runner from "../../runner/src/channel.ts"; - -const SESSION = "33333333-3333-4333-8333-333333333333"; -const scratch = mkdtempSync(join(tmpdir(), "omp-socket-test-")); -after(() => rmSync(scratch, { recursive: true, force: true })); - -async function until(predicate, what) { - for (const started = Date.now(); !predicate(); await new Promise(resolve => setTimeout(resolve, 10))) { - if (Date.now() - started > 5000) throw new Error(`timed out waiting for ${what}`); - } -} - -test("a runner that says hello on the host socket is announced as a channel with its session id", { skip: process.platform === "win32" }, async () => { - const path = join(scratch, "runtime", "ompweb", "host.sock"); - const announced = []; - const link = { id: "l1", version: 7, isUp: () => true, queue() { return 1; }, output() {}, discard() {} }; - const table = new ChannelTable({ sessionId: () => SESSION, prepareLaunch: launch => launch, log() {}, channelsChanged: ch => announced.push(ch), - spawn: () => { throw new Error("an attached omp is never spawned"); } }); - // The umask is process-wide: omp children spawned while listen() is pending (restored sessions at startup) inherit it. - const narrowed = []; - const umask = process.umask; - process.umask = (...args) => { if (args.length) narrowed.push(args[0]); return umask.apply(process, args); }; - let socket; - try { socket = await listenHostSocket(path, { adopt: (spawned, launch) => table.adopt(spawned, launch), log() {} }); } - finally { process.umask = umask; } - assert.deepEqual(narrowed, [], "the host socket never changes the process umask"); - assert.equal(statSync(path).mode & 0o777, 0o600); - assert.equal(statSync(join(scratch, "runtime", "ompweb")).mode & 0o777, 0o700); - - // The fake runner answers every daemon command, as the real one does. - const runner = createConnection(path); - createInterface({ input: runner }).on("line", line => { - const frame = JSON.parse(line); - if (frame.t === "cmd") runner.write(JSON.stringify({ t: "res", id: frame.id, ok: true }) + "\n"); - }).on("error", () => {}); // socket.close() below hangs up on the runner: a res still in flight gets EPIPE. - const closed = new Promise(resolve => runner.once("close", resolve)); - runner.write(JSON.stringify({ t: "hello", proto: 1, pid: 4242, sessionId: SESSION, sessionFile: join(scratch, "s.jsonl"), cwd: scratch }) + "\n"); - - await until(() => announced.length > 0, "the channel announcement"); - const [listed] = table.listing(link); - assert.equal(listed.ch, announced[0]); - assert.equal(listed.sessionId, SESSION); - assert.equal(listed.cwd, scratch); - - await socket.close(); - await closed; - assert.equal(existsSync(path), false); - await until(() => table.size === 0, "the channel's exit on disconnect"); - await table.stop(); -}); - -test("the host socket refuses a directory others can write", { skip: process.platform === "win32" }, async () => { - const dir = join(scratch, "open"); - mkdirSync(dir); - chmodSync(dir, 0o777); - await assert.rejects(listenHostSocket(join(dir, "host.sock"), { adopt: async () => {}, log() {} }), /group or world writable/); - assert.equal(existsSync(join(dir, "host.sock")), false); -}); - -test("an existing directory others can read is narrowed to 0700 before the socket listens", { skip: process.platform === "win32" }, async () => { - const dir = join(scratch, "readable"); - mkdirSync(dir); - chmodSync(dir, 0o755); - const socket = await listenHostSocket(join(dir, "host.sock"), { adopt: async () => {}, log() {} }); - assert.equal(statSync(dir).mode & 0o777, 0o700); - await socket.close(); -}); - -test("the host and the runner agree on the socket path and the channel protocol for the same env", () => { - assert.equal(CHANNEL_PROTO, runner.CHANNEL_PROTO); - const saved = { OMPWEB_HOST_SOCKET: process.env.OMPWEB_HOST_SOCKET, XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }; - try { - for (const env of [{}, { XDG_RUNTIME_DIR: "/run/user/1" }, { OMPWEB_HOST_SOCKET: "/x/h.sock", XDG_RUNTIME_DIR: "/run/user/1" }]) { - delete process.env.OMPWEB_HOST_SOCKET; delete process.env.XDG_RUNTIME_DIR; - Object.assign(process.env, env); - assert.equal(hostSocketPath(), runner.hostSocketPath(), JSON.stringify(env)); - } - } finally { - for (const [key, value] of Object.entries(saved)) if (value === undefined) delete process.env[key]; else process.env[key] = value; - } -}); - -test("a second runner on a session that already has a channel is refused with a frame and gets no channel", { skip: process.platform === "win32" }, async () => { - const path = join(scratch, "dup", "host.sock"); - const table = new ChannelTable({ sessionId: () => null, prepareLaunch: launch => launch, log() {}, spawn: () => { throw new Error("never spawned"); } }); - const socket = await listenHostSocket(path, { adopt: (spawned, launch, sessionId) => table.adopt(spawned, launch, sessionId), log() {} }); - const dial = () => { - const conn = createConnection(path), lines = []; - createInterface({ input: conn }).on("line", line => { - const frame = JSON.parse(line); lines.push(frame); - if (frame.t === "cmd") conn.write(JSON.stringify({ t: "res", id: frame.id, ok: true }) + "\n"); - }); - // A new session: no file yet, so only the hello's session id names it. - conn.write(JSON.stringify({ t: "hello", proto: 1, pid: 1, sessionId: SESSION, sessionFile: null, cwd: scratch }) + "\n"); - return { conn, lines, closed: new Promise(resolve => conn.once("close", resolve)) }; - }; - const first = dial(); - await until(() => table.size === 1, "the first channel"); - const second = dial(); - await second.closed; - assert.deepEqual(second.lines, [{ t: "refused", reason: "This session is already running on another link" }]); - assert.equal(table.size, 1); - await socket.close(); await first.closed; await table.stop(); -}); - -test("the socket is 0600 even under umask 0", { skip: process.platform === "win32" }, async () => { - const path = join(scratch, "umask", "host.sock"); - const old = process.umask(0); - try { - const socket = await listenHostSocket(path, { adopt: async () => {}, log() {} }); - assert.equal(statSync(path).mode & 0o777, 0o600); - assert.equal(process.umask(), 0, "the caller's umask is restored"); - await socket.close(); - } finally { process.umask(old); } -}); diff --git a/lib/hosts/omp-socket.ts b/lib/hosts/omp-socket.ts deleted file mode 100644 index 803200ce..00000000 --- a/lib/hosts/omp-socket.ts +++ /dev/null @@ -1,143 +0,0 @@ -// The host socket an omp started from a TUI dials (runner/src/channel.ts): each connection becomes a daemon channel, -// its lines the child's stdout, the server's lines written back, its close the child's exit. Unix only, never TCP. -import { chmodSync, lstatSync, mkdirSync, unlinkSync } from "node:fs"; -import { createConnection, createServer, type Socket } from "node:net"; -import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; -import { createInterface, type Interface } from "node:readline"; -import type { RpcTransport } from "../omp/rpc-transport"; -import { isRecord } from "../type-guards"; -import type { SpawnRequest, SpawnResult } from "./host"; - -const HELLO_TIMEOUT_MS = 10_000; -const errno = (error: unknown) => (error as NodeJS.ErrnoException)?.code; - -/** Must match `CHANNEL_PROTO` in runner/src/channel.ts (omp-socket.test.mjs checks). */ -export const CHANNEL_PROTO = 1; - -/** Must match `hostSocketPath()` in runner/src/channel.ts (omp-socket.test.mjs checks). */ -export function hostSocketPath(): string { - return process.env.OMPWEB_HOST_SOCKET || join(process.env.XDG_RUNTIME_DIR || tmpdir(), "ompweb", "host.sock"); -} - -/** Creates `dir` 0700 or narrows an existing one to 0700; refuses one another user owns or others could already write. */ -function privateDir(dir: string): void { - mkdirSync(dir, { recursive: true, mode: 0o700 }); - const stat = lstatSync(dir); - if (stat.isSymbolicLink() || !stat.isDirectory() || stat.uid !== process.getuid!()) throw new Error(`Unsafe host socket directory ${dir}: not a directory this user owns`); - if (stat.mode & 0o022) throw new Error(`Unsafe host socket directory ${dir}: group or world writable`); - // mkdirSync's mode does not apply to a directory that already exists: others must not even reach the socket. - if (stat.mode & 0o077) chmodSync(dir, 0o700); -} - -/** Removes a socket file nothing answers on; refuses a live one or anything that is not a socket. */ -async function removeStale(path: string): Promise { - try { if (!lstatSync(path).isSocket()) throw new Error(`${path} exists and is not a socket`); } - catch (error) { if (errno(error) === "ENOENT") return; throw error; } - const probed = Promise.withResolvers(); - const probe = createConnection(path); - probe.once("connect", () => { probe.destroy(); probed.reject(new Error(`Another ompweb host is listening on ${path}`)); }); - probe.once("error", error => errno(error) === "ECONNREFUSED" ? probed.resolve() : probed.reject(error)); - await probed.promise; - unlinkSync(path); -} - -/** The socket as the byte pipe of a child the daemon did not start. `first` (the hello) and later lines are held for - * the first subscriber. */ -function socketTransport(socket: Socket, lines: Interface, first: string, pid: number): RpcTransport { - const lineListeners: ((line: string) => void)[] = []; - const exitListeners: ((code: number | null, signal: NodeJS.Signals | null) => void)[] = []; - const pending = [first]; - let exit: [number | null, null] | null = null; - lines.on("line", line => { - if (lineListeners.length === 0) pending.push(line); - for (const listener of lineListeners) listener(line); - }); - // A TUI quitting ends the socket cleanly: report it as a normal exit, not a crash. - socket.once("close", hadError => { - exit = [hadError ? null : 0, null]; - for (const listener of exitListeners) listener(exit[0], null); - }); - return { - id: String(pid), - write(line, callback) { - if (!socket.writable) { callback(new Error("omp disconnected from the host")); return; } - socket.write(line, error => callback(error ?? null)); - }, - onLine(listener) { lineListeners.push(listener); for (const line of pending.splice(0)) listener(line); }, - onStderr() {}, - onExit(listener) { - exitListeners.push(listener); - const info = exit; - if (info) queueMicrotask(() => listener(info[0], null)); - }, - endInput() { socket.end(); }, - // The TUI owns this omp: stopping the channel only disconnects it, the omp keeps running. - killTree() { socket.destroy(); }, - }; -} - -/** `hello`'s identity as the launch a spawned child would have had; null for a malformed hello. */ -function helloLaunch(line: string): { pid: number; launch: SpawnRequest; sessionId?: string } | null { - let hello: unknown; - try { hello = JSON.parse(line); } catch { return null; } - if (!isRecord(hello) || hello.t !== "hello" || typeof hello.cwd !== "string" || !hello.cwd || !Number.isSafeInteger(hello.pid) - || !(hello.sessionFile === undefined || hello.sessionFile === null || typeof hello.sessionFile === "string")) return null; - return { pid: hello.pid as number, launch: { cwd: hello.cwd, recordedCwd: hello.cwd, sessionFile: hello.sessionFile ?? "", advisor: false }, - ...(typeof hello.sessionId === "string" ? { sessionId: hello.sessionId } : {}) }; -} - -/** Tells the runner not to redial (runner/src/channel.ts), then closes. */ -function refuse(socket: Socket, reason: string): void { - socket.end(JSON.stringify({ t: "refused", reason }) + "\n"); -} - -export type HostSocket = { path: string; close(): Promise }; - -/** Listens on `path` (0600 in a private directory); `adopt` turns each runner that says `hello` into a channel. */ -export async function listenHostSocket(path: string, options: { - adopt(spawned: SpawnResult, launch: SpawnRequest, sessionId?: string): Promise; - log(message: string): void; -}): Promise { - privateDir(dirname(path)); - await removeStale(path); - const sockets = new Set(); - const server = createServer(socket => { - sockets.add(socket); - socket.once("close", () => sockets.delete(socket)); - socket.on("error", () => {}); - socket.setTimeout(HELLO_TIMEOUT_MS, () => socket.destroy()); - const lines = createInterface({ input: socket, crlfDelay: Infinity }); - lines.once("line", first => { - const hello = helloLaunch(first); - if (!hello) { options.log("refused a TUI omp: its first line is not a valid hello"); refuse(socket, "invalid hello"); return; } - socket.setTimeout(0); - const transport = socketTransport(socket, lines, first, hello.pid); - options.adopt({ transport, cwd: hello.launch.cwd, fellBack: false, launchAdvisor: false }, hello.launch, hello.sessionId).catch((error: unknown) => { - const reason = error instanceof Error ? error.message : String(error); - options.log(`refused TUI omp ${hello.pid}: ${reason}`); - refuse(socket, reason); - }); - }); - }); - const listening = Promise.withResolvers(); - server.once("error", listening.reject); - // No process.umask(): it is process-wide, and omp children spawned while listen() is pending would inherit it. - // privateDir() left the directory 0700, so nobody else reaches the socket before this chmod narrows the file itself. - server.listen(path, listening.resolve); - await listening.promise; - try { chmodSync(path, 0o600); } catch (error) { server.close(); throw error; } - server.on("error", error => options.log("host socket: " + String(error))); - let closing: Promise | undefined; - return { - path, - close: () => { - if (closing) return closing; - const closed = Promise.withResolvers(); - // libuv unlinks the socket file on close; the TUIs' omps keep running and only lose the host. - server.close(() => closed.resolve()); - for (const socket of sockets) socket.destroy(); - return closing = closed.promise; - }, - }; -} diff --git a/lib/hosts/v10-upgrade.integration.test.mjs b/lib/hosts/v10-upgrade.integration.test.mjs deleted file mode 100644 index b8ec02f4..00000000 --- a/lib/hosts/v10-upgrade.integration.test.mjs +++ /dev/null @@ -1,367 +0,0 @@ -// Real pre-cutover daemons (link protocol 10 and 11) upgrading to this checkout through this checkout's hub. -// -// Nothing of the old side is imitated. The daemon is the published source, extracted from git at a pinned commit into -// a disposable npm-layout install and started as `node bin/omp-web-host.js`; its welcome check, its `checkUpdates` / -// `updateSoftware` handlers and its updater engine (candidate protocol check, install, swap, restart, health) all run -// unchanged. Only delivery is disposable: a fetch preload answers the npm registry and the raw-GitHub link-protocol.ts -// (the worktree's real file, parsed by the OLD updater's own regex), and a fake `npm` "installs" a copy of this -// checkout as the release. The hub is the real hub behind the real /api/hosts/link route. No user service is touched. -// -// Pinned sources (both reachable from main; the test skips, naming the commit, when a shallow clone lacks it): -// v10 546a945df0d1716a7a135d6e3221ba885b00171e package 0.6.0, link 10. The last commit before 8ec9208d (runner -// channels); published as prerelease 20261113T113829Z-546a945df0. v10 first appeared at a53494c4. Its updater -// takes target "ompweb" or "omp" and has no preflight. -// v11 3a56e79b217a3949f7180069e6769bc3fa031167 package 0.7.0, link 11: the commit tag v0.7.0 points at. -// -// Run: bun test --timeout 240000 lib/hosts/v10-upgrade.integration.test.mjs -// Needs: full git history (`git cat-file -e `), `tar` and `git` on PATH, node >= 24 on PATH, `npm ci` done in this -// checkout (daemon dependencies are symlinked from its node_modules), a POSIX machine (Linux or macOS). -// Disposable stand-ins besides delivery: one POSIX `omp` script (OMP_WEB_OMP_BIN) that answers `--version`, `--check` and -// the session start with the runner's channel hello, so the v11 updater's real `fetch-omp` and `preflight` of the candidate -// pass without the runner binary (no `bun runner/scripts/build-binary.ts` needed) or any network. -// Not covered: compiled-binary installs, systemd/launchd-supervised hosts, Windows, a daemon with live sessions (a legacy -// link carries none; the old busy checks are its own unchanged code). The server side serves only /api/hosts/link, so the -// upgraded daemon's maintenance connection is refused there; its application link and health acknowledgement are real. -// Cleanup: each scenario kills every process whose command line names its directory (daemons, detached workers, the -// stand-in sharing the install) and the file kills the rest; the run fails if any survives. A crash of the test runner -// itself can leave detached daemons running under the system temp directory (v10-upgrade-it-*): kill them by that path. -import assert from "node:assert/strict"; -import test, { after } from "node:test"; -import { execFileSync, spawn, spawnSync } from "node:child_process"; -import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { delimiter, dirname, join } from "node:path"; -import { pathToFileURL } from "node:url"; -import { nodeBinary, repo, repoVersion, spawnNodeOutsideService } from "./update-fixture.test-helper.mjs"; - -const LEGACY = { - v10: { name: "v10", link: 10, version: "0.6.0", commit: "546a945df0d1716a7a135d6e3221ba885b00171e" }, - v11: { name: "v11", link: 11, version: "0.7.0", commit: "3a56e79b217a3949f7180069e6769bc3fa031167" }, -}; -/** The application link version this release speaks, and the only target compatibility an old updater may be given. */ -const APPLICATION = 12; - -const base = realpathSync(mkdtempSync(join(tmpdir(), "v10-upgrade-it-"))); -const previousAgentDir = process.env.PI_CODING_AGENT_DIR; -process.env.PI_CODING_AGENT_DIR = join(base, "main-agent"); - -const linkRoute = await import("../../app/api/hosts/link/route.ts"); -const hub = await import("./hub.ts"); -const { createHost } = await import("./registry.ts"); -const { closeNotificationStore } = await import("../notification-store.ts"); -const { CHANNEL_PROTO } = await import("./omp-socket.ts"); - -const wait = (ms) => new Promise((done) => setTimeout(done, ms)); -const read = (path) => JSON.parse(readFileSync(path, "utf8")); -function alive(pid) { - try { process.kill(pid, 0); return true; } catch (error) { return error.code === "EPERM"; } -} - -// Every line the hub sends each host, in order, so the old daemon's whole view of the server can be asserted. -const down = new Map(); -const wrappers = new WeakMap(); -/** The hub keys its state on socket identity: one stable wrapper per socket, recording what it sends. */ -function wrap(ws) { - let wrapper = wrappers.get(ws); - if (wrapper) return wrapper; - const send = (frame, ...rest) => { - if (typeof frame === "string") { - for (const line of frame.split("\n")) if (line) down.set(ws.data.hostId, [...(down.get(ws.data.hostId) ?? []), JSON.parse(line)]); - } - return ws.send(frame, ...rest); - }; - wrapper = new Proxy(ws, { get: (target, name) => name === "send" ? send : typeof target[name] === "function" ? target[name].bind(target) : target[name] }); - wrappers.set(ws, wrapper); - return wrapper; -} -const server = Bun.serve({ - port: 0, - hostname: "127.0.0.1", - routes: { - "/api/hosts/link": { - GET: (req) => linkRoute.GET(req, { upgrade: (data) => server.upgrade(req, { data }) }), - POST: (req) => linkRoute.POST(req), - }, - }, - websocket: { - ...hub.hostLinkSocket, - message: (ws, data) => hub.hostLinkSocket.message(wrap(ws), data), - drain: (ws) => hub.hostLinkSocket.drain(wrap(ws)), - close: (ws) => hub.hostLinkSocket.close(wrap(ws)), - }, -}); - -/** Pids of every process whose command line names `dir`: daemons, workers and stand-ins all run files from inside it. */ -function processesUnder(dir) { - let lines; - if (process.platform === "linux") { - lines = readdirSync("/proc").filter((name) => /^\d+$/.test(name)).flatMap((name) => { - try { return [[Number(name), readFileSync(`/proc/${name}/cmdline`, "utf8").replaceAll("\0", " ")]]; } catch { return []; } - }); - } else { - const result = spawnSync("ps", ["-axo", "pid=,command="], { encoding: "utf8" }); - if (result.error || result.status !== 0 || typeof result.stdout !== "string") throw new Error("Cannot inspect test-owned processes; temporary installs retained", { cause: result.error }); - lines = result.stdout.split("\n").flatMap((line) => { - const match = /^\s*(\d+)\s+(.*)$/.exec(line); - return match ? [[Number(match[1]), match[2]]] : []; - }); - } - return lines.filter(([pid, command]) => pid !== process.pid && command.includes(dir)).map(([pid]) => pid); -} -async function stopAll(dir) { - for (const signal of ["SIGTERM", "SIGKILL"]) { - for (const pid of processesUnder(dir)) { try { process.kill(pid, signal); } catch { /* already gone */ } } - for (const deadline = Date.now() + 10_000; processesUnder(dir).length > 0 && Date.now() < deadline;) await wait(100); - } - assert.deepEqual(processesUnder(dir), [], "every process this test started must exit before its directory is removed"); -} - -after(async () => { - if (process.platform !== "win32") await stopAll(base); - await server.stop(true); - closeNotificationStore(); - hub.flushLinkSamples(); - if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; - else process.env.PI_CODING_AGENT_DIR = previousAgentDir; - for (let tries = 0; ; tries++) { - try { return rmSync(base, { recursive: true, force: true }); } catch (error) { - if (tries === 50 || !["EBUSY", "ENOTEMPTY", "EPERM"].includes(error.code)) throw error; - await wait(100); - } - } -}); - -const haveCommit = (commit) => spawnSync("git", ["-C", repo, "cat-file", "-e", `${commit}^{commit}`]).status === 0; - -const sources = new Map(); -/** `bin`, `lib` and package.json of the pinned commit: everything `omp-web-host.js` loads. */ -function legacySource(legacy) { - if (sources.has(legacy.commit)) return sources.get(legacy.commit); - const dir = join(base, `source-${legacy.name}`); - mkdirSync(dir); - const archive = `${dir}.tar`; - // umask 0022: the updater refuses an install directory that is group-writable. - execFileSync("git", ["-C", repo, "-c", "tar.umask=0022", "archive", "--format=tar", "-o", archive, legacy.commit, "bin", "lib", "package.json"]); - execFileSync("tar", ["-xf", archive, "-C", dir, "--no-same-owner"]); - // The pin must be the daemon this test claims to run. - assert.equal(read(join(dir, "package.json")).version, legacy.version); - assert.match(readFileSync(join(dir, "lib", "hosts", "link-protocol.ts"), "utf8"), new RegExp(`^export const LINK_PROTOCOL_VERSION = ${legacy.link};$`, "m")); - sources.set(legacy.commit, dir); - return dir; -} - -let releaseDir; -/** This checkout as the release the fake npm delivers: what `npm install @kahme247/ompweb@` would unpack. */ -function release() { - if (releaseDir) return releaseDir; - releaseDir = join(base, "release"); - mkdirSync(releaseDir); - cpSync(join(repo, "bin"), join(releaseDir, "bin"), { recursive: true }); - cpSync(join(repo, "lib"), join(releaseDir, "lib"), { recursive: true, filter: (src) => !/\.test(-helper)?\.(mjs|ts|tsx)$/.test(src) }); - cpSync(join(repo, "package.json"), join(releaseDir, "package.json")); - return releaseDir; -} - -const preload = join(base, "release-delivery.mjs"); -// The only network the old updater sees: the npm registry's latest version and the target tag's raw link-protocol.ts. -writeFileSync(preload, `import { appendFileSync, existsSync, readFileSync } from "node:fs"; -const real = globalThis.fetch; -const dir = process.env.UPGRADE_FIXTURE_DIR; -globalThis.fetch = async (input, init) => { - const url = String(input instanceof Request ? input.url : input); - appendFileSync(dir + "/fetch.log", url + "\\n"); - if (url.startsWith("https://registry.npmjs.org/")) return Response.json({ version: process.env.UPGRADE_FIXTURE_VERSION }); - if (/^https:\\/\\/raw\\.githubusercontent\\.com\\/[^/]+\\/[^/]+\\/v[^/]+\\/lib\\/hosts\\/link-protocol\\.ts$/.test(url)) { - const override = dir + "/link-protocol.override"; - return new Response(readFileSync(existsSync(override) ? override : process.env.UPGRADE_FIXTURE_PROTOCOL_SOURCE)); - } - if (/^http:\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\])[:/]/.test(url)) return real(input, init); - throw new Error("upgrade fixture: no network access to " + url); -}; -`); - -/** Installs the pinned daemon as a real npm-layout host, logs it into the hub and starts it. Null when no scope is available. */ -async function startLegacy(legacy, layout) { - const work = join(base, `${legacy.name}-${layout}`); - const modules = join(work, "node_modules"); - const install = join(modules, "@kahme247", "ompweb"); - const home = join(work, "home"); - const agent = join(home, ".omp", "agent"); - mkdirSync(join(work, "bin"), { recursive: true }); - mkdirSync(modules, { recursive: true }); - mkdirSync(agent, { recursive: true }); - // The daemon's dependencies, resolved from the node_modules above the install as for any hoisted global install. - for (const name of readdirSync(join(repo, "node_modules"))) { - if (!name.startsWith(".")) symlinkSync(realpathSync(join(repo, "node_modules", name)), join(modules, name), "dir"); - } - cpSync(legacySource(legacy), install, { recursive: true }); - for (let dir = install; dir !== dirname(work); dir = dirname(dir)) chmodSync(dir, 0o755); - const fakeOmp = join(work, "fake-omp"); - // One stand-in for both omp roles an update touches: the version/update probes of the old daemon, and the session omp - // that the candidate's `ompweb preflight` (run by the v11 updater before its switch) must see say hello. - writeFileSync(fakeOmp, `#!/bin/sh -if [ "$1" = "--version" ]; then echo 14.0.0-fake; exit 0; fi -case "$*" in *--check*) echo "Current version: 14.0.0-fake"; exit 0;; esac -case "$*" in *"--headless --cwd "*"--no-session"*) echo '{"t":"hello","proto":${CHANNEL_PROTO}}'; exec cat >/dev/null;; esac -exit 0 -`, { mode: 0o755 }); - writeFileSync(join(work, "idle.js"), "setInterval(() => {}, 1000);\n"); - writeFileSync(join(work, "bin", "npm"), `#!/usr/bin/env node -const fs = require("node:fs"), path = require("node:path"); -const args = process.argv.slice(2); -fs.appendFileSync(${JSON.stringify(join(work, "npm.log"))}, JSON.stringify(args) + "\\n"); -if (!args.includes(${JSON.stringify(`@kahme247/ompweb@${repoVersion}`)})) process.exit(8); -fs.cpSync(${JSON.stringify(release())}, path.join(args[args.indexOf("--prefix") + 1], "node_modules", "@kahme247", "ompweb"), { recursive: true }); -`, { mode: 0o700 }); - - const { host, token } = createHost(`${legacy.name} ${layout}`); - const env = { - ...process.env, HOME: home, USERPROFILE: home, PI_CODING_AGENT_DIR: agent, OMP_WEB_OMP_BIN: fakeOmp, OMP_WEB_PACKAGE_DIR: install, - PATH: join(work, "bin") + delimiter + process.env.PATH, - NODE_OPTIONS: [process.env.NODE_OPTIONS, `--import ${pathToFileURL(preload).href}`].filter(Boolean).join(" "), - UPGRADE_FIXTURE_DIR: work, UPGRADE_FIXTURE_VERSION: repoVersion, UPGRADE_FIXTURE_PROTOCOL_SOURCE: join(repo, "lib", "hosts", "link-protocol.ts"), - }; - delete env.OMP_WEB_DISABLE_AUTOUPDATE; - delete env.OMP_WEB_HOST_DRAINED; - const entry = join(install, "bin", "omp-web-host.js"); - const login = spawnSync(nodeBinary(), [entry, "login", "--url", `http://127.0.0.1:${server.port}`], { env, cwd: work, input: `${token}\n`, encoding: "utf8" }); - assert.equal(login.status, 0, login.stderr); - - const child = await spawnNodeOutsideService(entry, env); - if (!child) return null; - let log = ""; - child.stdout.on("data", (data) => { log += data; }); - child.stderr.on("data", (data) => { log += data; }); - const lines = (name) => existsSync(join(work, name)) ? readFileSync(join(work, name), "utf8").split("\n").filter(Boolean) : []; - return { - legacy, layout, work, install, child, hostId: host.id, stateRoot: join(agent, "omp-web", "host-update"), - log: () => log, - npmCalls: () => lines("npm.log").map((line) => JSON.parse(line)), - fetched: () => lines("fetch.log"), - status: () => read(join(agent, "omp-web", "host-update", "status.json")), - }; -} - -async function waitFor(predicate, what, run, timeoutMs = 120_000) { - for (const deadline = Date.now() + timeoutMs; ; await wait(100)) { - if (predicate()) return; - if (Date.now() > deadline) { - const status = existsSync(join(run.stateRoot, "status.json")) ? JSON.stringify(run.status()) : "none"; - assert.fail(`timed out waiting for ${what}\nupdate status: ${status}\nnpm calls: ${JSON.stringify(run.npmCalls())}\nold daemon log:\n${run.log()}`); - } - } -} - -/** checkUpdates through the hub. The daemon's own startup upload sweep briefly reports "Wait for ..."; any other block is the answer. */ -async function checkUpdates(run) { - for (const deadline = Date.now() + 30_000; ; await wait(500)) { - const info = await hub.getHostSoftwareUpdates(run.hostId, true); - if (!/^Wait for/.test(info.ompweb.blockedReason ?? "") || Date.now() > deadline) return info; - } -} - -async function upgrade(run) { - const { legacy, layout, hostId } = run; - const row = () => hub.listHosts().find((host) => host.id === hostId); - const sent = () => down.get(hostId) ?? []; - - // The real old daemon is welcomed with the version it said (it throws on any other) and linked for upgrading only. - await waitFor(() => row()?.status === "needs-upgrade" && row().upgradeOnly === true && /linked to /.test(run.log()), `the ${legacy.name} daemon to be welcomed upgrade-only`, run); - assert.equal(row().hostVersion, legacy.link); - assert.equal(row().ompwebVersion, legacy.version); - assert.deepEqual([...new Set(sent().filter((message) => message.type === "welcome").map((message) => message.v))], [legacy.link]); - - if (layout === "separate") { - // A candidate on another protocol is refused by what the old updater was told, not by a fixture shortcut. - writeFileSync(join(run.work, "link-protocol.override"), `export const LINK_PROTOCOL_VERSION = ${APPLICATION - 1};\n`); - const wrong = await checkUpdates(run); - assert.equal(wrong.ompweb.protocolVersion, APPLICATION - 1); - assert.equal(wrong.ompweb.canUpdate, false); - rmSync(join(run.work, "link-protocol.override")); - } - - let installBefore; - let web; - if (layout === "shared") { - // The web package shares this installation, and has not replaced it yet: nothing may be installed over it. - web = spawn(nodeBinary(), [join(run.work, "idle.js"), join(run.install, "package.json")], { stdio: "ignore", cwd: run.work }); - const stale = await checkUpdates(run); - assert.equal(stale.ompweb.canUpdate, false); - assert.match(stale.ompweb.blockedReason, /installation is shared/); - await assert.rejects(hub.updateHostSoftware(hostId, "ompweb", repoVersion)); - assert.deepEqual(run.npmCalls(), []); - // `npm i -g` of the web package: the shared installation now holds the candidate while the old daemon keeps running. - for (const name of readdirSync(run.install)) rmSync(join(run.install, name), { recursive: true, force: true }); - cpSync(release(), run.install, { recursive: true }); - chmodSync(run.install, 0o755); - installBefore = { directory: statSync(run.install).ino, manifest: statSync(join(run.install, "package.json")) }; - } - - const info = await checkUpdates(run); - assert.equal(info.ompweb.currentVersion, legacy.version); - assert.equal(info.ompweb.availableVersion, repoVersion); - assert.equal(info.ompweb.updateAvailable, true); - assert.equal(info.ompweb.protocolVersion, APPLICATION); - assert.equal(info.ompweb.canUpdate, true, info.ompweb.blockedReason); - - const accepted = await hub.updateHostSoftware(hostId, "ompweb", repoVersion); - assert.deepEqual({ target: accepted.operation.target, version: accepted.operation.version }, { target: "ompweb", version: repoVersion }); - await waitFor(() => existsSync(join(run.stateRoot, "status.json")) && run.status().operation.state !== "running", "the old updater to finish", run); - const { operation, daemonPid } = run.status(); - assert.equal(operation.state, "succeeded", operation.error); - await waitFor(() => row()?.status === "online" && row().hostVersion === APPLICATION && row().ompwebVersion === repoVersion, "the upgraded daemon to link at the application version", run); - assert.equal(row().upgradeOnly, undefined); - assert.equal(hub.getHostLinkProtocol(hostId), APPLICATION); - await waitFor(() => run.child.exitCode !== null || run.child.signalCode !== null, "the old daemon to stop", run); - const health = read(join(run.stateRoot, operation.id, "health.json")); - assert.equal(health.version, repoVersion); - assert.notEqual(health.pid, daemonPid); - assert.ok(alive(health.pid), "the new daemon keeps running"); - assert.equal(read(join(run.install, "package.json")).version, repoVersion); - - const backups = readdirSync(dirname(run.install)).filter((name) => name.startsWith(".ompweb-backup-")); - if (layout === "separate") { - assert.equal(run.npmCalls().length, 1); - assert.ok(run.npmCalls()[0].includes(`@kahme247/ompweb@${repoVersion}`)); - assert.deepEqual(backups, [`.ompweb-backup-${operation.id}`]); - assert.equal(read(join(dirname(run.install), backups[0], "package.json")).version, legacy.version); - } else { - // A shared install is restarted, never reinstalled: no package manager, no swap, no backup, and the other process lives. - assert.deepEqual(run.npmCalls(), []); - assert.deepEqual(backups, []); - assert.equal(read(join(run.stateRoot, operation.id, "descriptor.json")).restartOnly, true); - assert.equal(statSync(run.install).ino, installBefore.directory); - const manifest = statSync(join(run.install, "package.json")); - assert.deepEqual([manifest.ino, manifest.mtimeMs], [installBefore.manifest.ino, installBefore.manifest.mtimeMs]); - assert.ok(alive(web.pid), "the process sharing the installation is untouched"); - } - const candidateSource = new RegExp(`^https://raw\\.githubusercontent\\.com/[^/]+/[^/]+/v${repoVersion.replaceAll(".", "\\.")}/lib/hosts/link-protocol\\.ts$`); - assert.ok(run.fetched().some((url) => candidateSource.test(url)), "the old updater read the target release's link protocol"); - - // Everything the legacy connection ever received: transport and the two update requests, each with the one - // compatibility an application-12 release may be reached through. The v12 welcome ends it. - const frames = sent(); - const upgraded = frames.findIndex((message) => message.type === "welcome" && message.v === APPLICATION); - assert.ok(upgraded > 0, "the upgraded daemon is welcomed at the application version"); - const legacyFrames = frames.slice(0, upgraded); - assert.deepEqual([...new Set(legacyFrames.map((message) => message.type))].filter((type) => !["welcome", "ack", "ping", "pong", "req"].includes(type)), []); - const requests = legacyFrames.filter((message) => message.type === "req"); - assert.deepEqual([...new Set(requests.map((message) => message.op))].sort(), ["checkUpdates", "updateSoftware"]); - for (const request of requests) assert.deepEqual(request.args.compatibility, { min: APPLICATION, max: APPLICATION }); - assert.deepEqual(requests.filter((message) => message.op === "updateSoftware").map((message) => [message.args.target, message.args.version]), [["ompweb", repoVersion]]); -} - -const skipWindows = process.platform === "win32" && "this proof needs git archive, symlinked dependencies and a POSIX process table"; -const skipScope = "systemd-run cannot create the scope that keeps this test outside the service running the suite"; -async function scenario(t, legacy, layout) { - if (skipWindows) return t.skip(skipWindows); - if (!haveCommit(legacy.commit)) return t.skip(`commit ${legacy.commit} (${legacy.name} daemon) is not in this clone; fetch full history`); - const run = await startLegacy(legacy, layout); - if (!run) return t.skip(skipScope); - try { await upgrade(run); } finally { await stopAll(run.work); } -} - -test("v10 daemon (546a945d) is welcomed as v10 and upgraded by its own updater to a separate v12 install", { timeout: 240_000 }, (t) => scenario(t, LEGACY.v10, "separate")); -test("v10 daemon (546a945d) on an installation the web package already replaced is restarted, not reinstalled", { timeout: 240_000 }, (t) => scenario(t, LEGACY.v10, "shared")); -test("v11 daemon (v0.7.0) is welcomed as v11 and upgraded by its own updater to a separate v12 install", { timeout: 240_000 }, (t) => scenario(t, LEGACY.v11, "separate")); -test("v11 daemon (v0.7.0) on an installation the web package already replaced is restarted, not reinstalled", { timeout: 240_000 }, (t) => scenario(t, LEGACY.v11, "shared")); From 711d48b0a5230b48c692e872a71de43fca30972f Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 17:28:44 +0000 Subject: [PATCH 004/129] fix(updates): install and verify the @ompweb-dev/tau package Update and recovery checks still required @kahme247/ompweb, so a tau install was refused as not an installed package and a staged tau release failed the name check. Package names, install directories, npm metadata checks and update commands now use @ompweb-dev/tau. --- .github/workflows/verify-pr.yml | 8 ++++---- bin/bun-runtime.js | 2 +- bin/generate-release-notes.js | 2 +- bin/generate-release-notes.test.mjs | 2 +- bin/omp-web-launchd.js | 4 ++-- bin/omp-web-launchd.test.mjs | 4 ++-- bin/omp-web-systemd.js | 2 +- bin/omp-web.js | 4 ++-- components/AppShell.tsx | 2 +- components/AppUpdateDialog.tsx | 2 +- components/HostUpdates.test.mjs | 2 +- components/SettingsConfig.tsx | 4 ++-- components/SettingsConfig.updates.test.mjs | 6 +++--- components/UpdateToast.test.mjs | 4 ++-- lib/app-update-route.test.mjs | 2 +- lib/github-release-notes.ts | 2 +- lib/hosts/daemon-update-safety.test.mjs | 4 ++-- lib/hosts/daemon.test.mjs | 4 ++-- lib/hosts/host-update-e2e.test.mjs | 2 +- lib/hosts/host-updates-route.test.mjs | 8 ++++---- lib/hosts/recovery.test.mjs | 8 ++++---- lib/hosts/recovery.ts | 2 +- lib/hosts/release-pin-routing.test.mjs | 2 +- lib/hosts/update-fixture.test-helper.mjs | 6 +++--- lib/hosts/update-worker.test.mjs | 14 +++++++------- lib/hosts/update-worker.ts | 12 ++++++------ lib/hosts/updates.test.mjs | 8 ++++---- lib/hosts/updates.ts | 2 +- lib/hosts/upgrade-shim.test.mjs | 2 +- lib/i18n/locales/en.json | 2 +- lib/i18n/locales/ja.json | 2 +- lib/i18n/locales/zh-CN.json | 2 +- lib/i18n/locales/zh-TW.json | 2 +- lib/npm-update.test.mjs | 8 ++++---- lib/self-update.test.mjs | 8 ++++---- lib/self-update.ts | 4 ++-- lib/server-update-worker.test.mjs | 2 +- lib/server-update-worker.ts | 2 +- lib/upgrade-plan-coordinator.test.mjs | 2 +- lib/upgrade-plan.ts | 4 ++-- package-lock.json | 4 ++-- scripts/macos-launchd.mts | 8 ++++---- 42 files changed, 88 insertions(+), 88 deletions(-) diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 168ac2c7..80238f82 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -134,15 +134,15 @@ jobs: shell: bash run: | npm pack --ignore-scripts - npm install -g --prefix "$RUNNER_TEMP/ompweb-prefix" ./kahme247-ompweb-*.tgz - npm run smoke -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@kahme247/ompweb" + npm install -g --prefix "$RUNNER_TEMP/ompweb-prefix" ./ompweb-dev-tau-*.tgz + npm run smoke -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@ompweb-dev/tau" # Bun's postinstall does not run here: the launcher must fall back to @oven/bun-- (spec R1). - name: Packed install smoke test (install scripts disabled) shell: bash run: | - npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts" ./kahme247-ompweb-*.tgz - npm run smoke -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@kahme247/ompweb" + npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts" ./ompweb-dev-tau-*.tgz + npm run smoke -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@ompweb-dev/tau" - name: Parse Windows PowerShell scripts (Windows only) if: runner.os == 'Windows' diff --git a/bin/bun-runtime.js b/bin/bun-runtime.js index 1434e850..b97f4367 100644 --- a/bin/bun-runtime.js +++ b/bin/bun-runtime.js @@ -8,7 +8,7 @@ const path = process.getBuiltinModule("node:path"); const MIN_BUN_VERSION = "1.4.4"; // The postinstall replaces bin/bun.exe (a 450-byte placeholder) with the real ~100 MB binary. const PLACEHOLDER_LIMIT = 1024 * 1024; -const REINSTALL = "npm install -g @kahme247/ompweb"; +const REINSTALL = "npm install -g @ompweb-dev/tau"; // bun@1.4.4's optionalDependencies, by `${process.platform}-${process.arch}` (Android uses the linux-*-android builds). const PLATFORM_PACKAGES = { "darwin-arm64": ["@oven/bun-darwin-aarch64"], diff --git a/bin/generate-release-notes.js b/bin/generate-release-notes.js index 336ee288..f2433b5f 100644 --- a/bin/generate-release-notes.js +++ b/bin/generate-release-notes.js @@ -213,7 +213,7 @@ function formatReleaseNotes({ if (!lines.join("\n").includes("## Upgrade")) { lines.push("\n## Upgrade\n"); lines.push("```bash"); - lines.push(`npm install -g @kahme247/ompweb@${version}`); + lines.push(`npm install -g @ompweb-dev/tau@${version}`); lines.push("```"); } diff --git a/bin/generate-release-notes.test.mjs b/bin/generate-release-notes.test.mjs index f173a8fa..2c5caaa8 100644 --- a/bin/generate-release-notes.test.mjs +++ b/bin/generate-release-notes.test.mjs @@ -107,6 +107,6 @@ Older release notes. assert.match(notes, /## Contributors/); assert.match(notes, /@alice/); assert.match(notes, /@bob/); - assert.match(notes, /npm install -g @kahme247\/ompweb@0\.4\.0/); + assert.match(notes, /npm install -g @ompweb-dev\/tau@0\.4\.0/); }); }); diff --git a/bin/omp-web-launchd.js b/bin/omp-web-launchd.js index 79cecd8e..04b3688b 100644 --- a/bin/omp-web-launchd.js +++ b/bin/omp-web-launchd.js @@ -8,7 +8,7 @@ require("./node-version").exitIfUnsupportedNode(); // // Usage (installed as the `ompweb-launchd` bin, or run via npx / node directly): // ompweb-launchd [install [package-spec]|uninstall|status] -// npx -p @kahme247/ompweb@latest ompweb-launchd install +// npx -p @ompweb-dev/tau@latest ompweb-launchd install // eslint-disable-next-line @typescript-eslint/no-require-imports const { spawnSync } = require("node:child_process"); @@ -117,7 +117,7 @@ function install(pkgArg) { } } - const pkg = pkgArg ?? process.env.OMP_WEB_PKG ?? "@kahme247/ompweb@latest"; + const pkg = pkgArg ?? process.env.OMP_WEB_PKG ?? "@ompweb-dev/tau@latest"; const port = process.env.PORT ?? "30177"; const hostname = process.env.OMP_WEB_HOSTNAME ?? "127.0.0.1"; const noOpen = process.env.OMP_WEB_NO_OPEN ?? "1"; diff --git a/bin/omp-web-launchd.test.mjs b/bin/omp-web-launchd.test.mjs index f780eeee..e0b96096 100644 --- a/bin/omp-web-launchd.test.mjs +++ b/bin/omp-web-launchd.test.mjs @@ -10,14 +10,14 @@ const env = { PATH: "/usr/bin", PI_CODING_AGENT_DIR: "/Users/u/agent" }; test("the host daemon plist runs `ompweb host`, restarts with KeepAlive, and is throttled", () => { const plist = buildPlist({ label: HOST_LABEL, - args: ["/usr/local/bin/npx", "--yes", "@kahme247/ompweb@latest", "host"], + args: ["/usr/local/bin/npx", "--yes", "@ompweb-dev/tau@latest", "host"], env, logName: "ompweb-host", throttleInterval: 10, }); assert.equal(HOST_LABEL, "com.kahme247.ompweb-host"); assert.match(plist, /Label<\/key>com\.kahme247\.ompweb-host<\/string>/); - assert.match(plist, /@kahme247\/ompweb@latest<\/string>\n host<\/string>\n <\/array>/); + assert.match(plist, /@ompweb-dev\/tau@latest<\/string>\n host<\/string>\n <\/array>/); assert.match(plist, /KeepAlive<\/key>/); assert.match(plist, /ThrottleInterval<\/key>10<\/integer>/); assert.match(plist, /PI_CODING_AGENT_DIR<\/key>\/Users\/u\/agent<\/string>/); diff --git a/bin/omp-web-systemd.js b/bin/omp-web-systemd.js index 7f7afd79..b89c82b8 100644 --- a/bin/omp-web-systemd.js +++ b/bin/omp-web-systemd.js @@ -8,7 +8,7 @@ require("./node-version").exitIfUnsupportedNode(); // // Usage: // ompweb-systemd [install|uninstall|start|stop|restart|status|open] -// npx --yes --package=@kahme247/ompweb@latest ompweb-systemd install +// npx --yes --package=@ompweb-dev/tau@latest ompweb-systemd install // // `install` creates ~/.omp/agent/web-service.env. The file is deliberately // separate from the unit so port, hostname, password, and omp path can be diff --git a/bin/omp-web.js b/bin/omp-web.js index 155c43d3..2e3c79fc 100755 --- a/bin/omp-web.js +++ b/bin/omp-web.js @@ -5,8 +5,8 @@ require("./node-version").exitIfUnsupportedNode(); // Forward service subcommands from the main bin. This makes both -// `npx @kahme247/ompweb@latest ompweb-launchd ...` and -// `npx @kahme247/ompweb@latest ompweb-systemd ...` work without requiring +// `npx @ompweb-dev/tau@latest ompweb-launchd ...` and +// `npx @ompweb-dev/tau@latest ompweb-systemd ...` work without requiring // callers to know the path of the secondary executable. const forwardedServiceScripts = { launchd: "omp-web-launchd.js", diff --git a/components/AppShell.tsx b/components/AppShell.tsx index 85795fb8..f5e70363 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -420,7 +420,7 @@ export function AppShell({ appName }: { appName: string }) { {appUpdate.updateCommand} ) : (
- {appUpdate.updateCommand || "npm install -g @kahme247/ompweb"} + {appUpdate.updateCommand || "npm install -g @ompweb-dev/tau"}
) : (
@@ -3077,6 +3051,7 @@ export const ChatInput = memo(forwardRef(function ChatIn )}
+ {queueActions}
))}
diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index a97353ec..5f8d5360 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -462,7 +462,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio handleSend, handleAbort, handleFork, handleEdit, handleModelChange, retrySession, handleSteer, handleFollowUp, handleAbortCompaction, handleCompact, heldMessages, deleteHeldMessage, retryHeldMessage, - removeQueuedMessage, promoteQueuedToSteer, + clearQueuedMessages, handleBuiltinSlashCommand, togglePreCompactionHistory, handleThinkingLevelChange, handleFastModeChange, handleSlowModeChange, handleCycleModel, handleCycleThinkingLevel, handleAbortRetry, loadSlashCommands, handleToolPresetChange, @@ -1054,8 +1054,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio sessionStats={sessionStats} modelCapacity={modelCapacity} generationSpeed={generationSpeed} - onRemoveQueuedMessage={removeQueuedMessage} - onPromoteQueuedToSteer={promoteQueuedToSteer} + onClearQueuedMessages={clearQueuedMessages} slashCommands={slashCommands} slashCommandsLoading={slashCommandsLoading} onLoadSlashCommands={loadSlashCommands} diff --git a/hooks/useAgentSession-stream.ts b/hooks/useAgentSession-stream.ts index 73f8ed96..766c0dea 100644 --- a/hooks/useAgentSession-stream.ts +++ b/hooks/useAgentSession-stream.ts @@ -253,8 +253,6 @@ export const PROMPT_SETTLE_INITIAL_DELAY_MS = 800; export const PROMPT_SETTLE_POLL_MS = 600; export const PROMPT_SETTLE_MAX_MS = 20_000; export const AGENT_STATE_RECONCILE_MS = 15_000; -// Stop waits at most this long to take queued messages back before aborting. -export const WITHDRAW_BEFORE_ABORT_MS = 1_500; export const BASH_STATE_RECONCILE_MS = 1_000; // Cadence for re-reading a session that some OTHER `omp` process is running. // omp-web owns no wrapper for those, so /api/agent//events 409s and nothing diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index efce900b..3ce62c75 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -300,13 +300,10 @@ async function fetchStub(url, init = {}) { if (body?.type === "get_btw_history") { return jsonResponse(200, { success: true, data: { records: world.btwHistory.get(sid) ?? [] } }); } - // omp before abort_and_restore_queue rejects it (its real wording), which keeps the - // per-entry withdrawal tests on their fallback path; tests of the atomic - // path set what omp hands back. + // The server answers abort_and_restore_queue with what pi's clear_queue withdrew + // (nothing unless a test sets it). if (body?.type === "abort_and_restore_queue") { - return world.abortRestoreQueue - ? jsonResponse(200, { success: true, data: world.abortRestoreQueue }) - : jsonResponse(400, { error: "Unknown command: abort_and_restore_queue", code: "rpc_command_failed" }); + return jsonResponse(200, { success: true, data: world.abortRestoreQueue ?? { steering: [], followUp: [] } }); } return jsonResponse(200, { success: true, data: {} }); } @@ -430,6 +427,7 @@ async function confirmEdit(view, button) { // Harness // --------------------------------------------------------------------------- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const isAtomicStop = (method, _url, body) => method === "POST" && body?.type === "abort_and_restore_queue"; /** Run pending timers/microtasks inside act so state updates are flushed. */ async function settle(ms = 120) { @@ -745,13 +743,13 @@ test("editing and resending a queued bang-prefixed prompt never runs its inline world.agents.set(sid, { running: true, state: { queuedMessages: { steering: [], followUp: [message] } } }); world.outboxHold = true; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: async () => ({ value: { success: true, data: { removed: true } } }), + match: (method, _url, body) => method === "POST" && body?.type === "clear_queue", + produce: async () => ({ value: { success: true, data: { steering: [], followUp: [message] } } }), }); const view = ownRoot(render(React.createElement(ChatWindow, { session: sessionInfo(sid), newSessionCwd: null }), { wrapper: TestRoot })); await settle(); - await act(async () => { fireEvent.click(view.getByTitle("Edit this queued message")); }); - await until(() => view.getByRole("textbox").value === message, "the removed queue entry must return to the composer"); + await act(async () => { fireEvent.click(view.getByTitle(translate("chatInput.queuedEditTitle"))); }); + await until(() => view.getByRole("textbox").value === message, "the withdrawn queue must return to the composer"); await act(async () => { fireEvent.keyDown(view.getByRole("textbox"), { key: "Enter" }); }); await until(() => world.outbox.length === 1 || world.calls.some((call) => call.body?.type === "bash"), "the recovered message must be dispatched"); assert.deepEqual(world.calls.filter((call) => call.body?.type === "bash"), [], "queue recovery must preserve prompt intent"); @@ -766,30 +764,6 @@ test("editing and resending a queued bang-prefixed prompt never runs its inline assert.deepEqual(world.calls.filter((call) => call.body?.type === "bash").map((call) => call.body.command), ["printf example"]); }); -test("removing the last recovered image clears prompt-only mode for fresh shell input", async (t) => { - resetWorld(); - const { clearDraft } = await import("@/lib/draft-store"); - const sid = "cleared-image-prompt"; - t.after(() => clearDraft(sid)); - primeSession(sid, [userMsg("u0", "before")]); - world.agents.set(sid, { running: true, state: { queuedMessages: { steering: [], followUp: ["[Image]"] } } }); - world.outboxHold = true; - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: async () => ({ value: { success: true, data: { removed: true, images: [{ data: "AAAA", mimeType: "image/png" }] } } }), - }); - const view = ownRoot(render(React.createElement(ChatWindow, { session: sessionInfo(sid), newSessionCwd: null }), { wrapper: TestRoot })); - await settle(); - await act(async () => { fireEvent.click(view.getByTitle("Edit this queued message")); }); - await until(() => view.queryAllByRole("button", { name: /remove image/i }).length === 1, "the image-only prompt must be recovered"); - await act(async () => { fireEvent.click(view.getByRole("button", { name: /remove image/i })); }); - await act(async () => { fireEvent.change(view.getByRole("textbox"), { target: { value: "!!printf example" } }); }); - await act(async () => { fireEvent.keyDown(view.getByRole("textbox"), { key: "Enter" }); }); - await until(() => world.outbox.length === 1 || world.calls.some((call) => call.body?.type === "bash"), "fresh input must be dispatched"); - assert.deepEqual(world.calls.filter((call) => call.body?.type === "bash").map((call) => call.body.command), ["printf example"]); - assert.deepEqual(world.outbox, [], "clearing the recovered image must not leave fresh shell input in prompt mode"); -}); - test("a shell-queued outbox prompt and steer use queue_update without a phantom turn or reply notice", async () => { resetWorld(); primeSession("bash-queue", [userMsg("u0", "q")]); @@ -823,260 +797,119 @@ test("a shell-queued outbox prompt and steer use queue_update without a phantom assert.deepEqual(w.latest.notices, []); }); -test("queued cancellation reports omp's answer and leaves the chip to the snapshot", async (t) => { +test("clearing the queue resolves to pi's withdrawn texts, writes no draft, and leaves the chips to the snapshot", async (t) => { + const { getDraft, clearDraft } = await import("@/lib/draft-store"); for (const outcome of [ { - name: "removed", - response: { value: { success: true, data: { removed: true, images: [{ type: "image", data: "AAAA", mimeType: "image/png" }, { bogus: true }] } } }, - result: [{ data: "AAAA", mimeType: "image/png" }], - notices: [], + name: "cleared", + response: { value: { success: true, data: { steering: ["steer first"], followUp: ["target", "", 7, "target"] } } }, + result: ["steer first", "target", "target"], notices: [], }, - { name: "not pending", response: { value: { success: true, data: { removed: false } } }, result: false, notices: ["warning"] }, - { name: "unsupported", response: { status: 400, value: { error: "Unknown RPC command: remove_queued_message" } }, result: false, notices: ["error"] }, + { name: "failed", response: { status: 500, value: { error: "pi refused" } }, result: false, notices: ["error"] }, ]) { await t.test(outcome.name, async () => { resetWorld(); - const sid = `cancel-${outcome.name.replace(" ", "-")}`; + const sid = `clear-queue-${outcome.name}`; + clearDraft(sid); primeSession(sid, [userMsg("u0", "q")]); const { w, es } = await startRun(sid, "run"); - await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["target", "target"] })); + await act(() => es.emit({ type: "queue_update", steering: ["steer first"], followUp: ["target", "target"] })); let release; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", + match: (method, _url, body) => method === "POST" && body?.type === "clear_queue", produce: () => new Promise((resolve) => { release = resolve; }), }); let first; let second; await act(async () => { - first = w.latest.removeQueuedMessage("target", "followUp"); - second = w.latest.removeQueuedMessage("target", "followUp"); + first = w.latest.clearQueuedMessages(); + second = w.latest.clearQueuedMessages(); }); - assert.equal(await second, false, "an overlapping click cannot cancel the duplicate"); - assert.deepEqual(world.calls.filter((c) => c.body?.type === "remove_queued_message").map((c) => c.body), [ - { type: "remove_queued_message", message: "target", queue: "followUp" }, - ]); + assert.equal(await second, false, "an overlapping click cannot clear the queue twice"); + assert.deepEqual(world.calls.filter((c) => c.body?.type === "clear_queue").map((c) => c.body), [{ type: "clear_queue" }]); await act(async () => { release(outcome.response); - assert.deepEqual(await first, outcome.result); + assert.deepEqual(await first, outcome.result, "steering first, then follow-ups; non-empty strings only"); }); - assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: ["target", "target"] }); + assert.equal(getDraft(sid), null, "the composer, not the hook, owns recovery"); + assert.deepEqual(w.latest.queuedMessages, { steering: ["steer first"], followUp: ["target", "target"] }); assert.deepEqual(w.latest.notices.map((n) => n.type), outcome.notices); }); } }); -test("Steer promotes through omp once and reports a refusal", async (t) => { - for (const outcome of [ - { name: "promoted", response: { value: { success: true, data: { promoted: true } } }, notices: [] }, - { name: "not pending", response: { value: { success: true, data: { promoted: false } } }, notices: ["warning"] }, - ]) { - await t.test(outcome.name, async () => { - resetWorld(); - const sid = `promote-${outcome.name.replace(" ", "-")}`; - primeSession(sid, [userMsg("u0", "q")]); - const { w, es } = await startRun(sid, "run"); - await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["target", "target"] })); - let release; - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", - produce: () => new Promise((resolve) => { release = resolve; }), - }); - const callsBefore = world.calls.length; - let first; - await act(async () => { - first = w.latest.promoteQueuedToSteer("target"); - await w.latest.promoteQueuedToSteer("target"); - }); - assert.deepEqual(world.calls.slice(callsBefore).map((c) => c.body), [{ type: "promote_queued_message", message: "target" }], - "one promotion, never a separate steer"); - await act(async () => { - release(outcome.response); - await first; - }); - assert.deepEqual(w.latest.notices.map((n) => n.type), outcome.notices); - }); - } -}); - -test("a promotion answered after navigation does not notify the new session", async () => { +test("a queue clear failing after navigation does not notify the new session", async () => { resetWorld(); - primeSession("old-promotion", [userMsg("u0", "old")]); - primeSession("new-promotion", [userMsg("u1", "new")]); - const { w: old, es } = await startRun("old-promotion", "run"); + primeSession("old-clear", [userMsg("u0", "old")]); + primeSession("new-clear", [userMsg("u1", "new")]); + const { w: old, es } = await startRun("old-clear", "run"); await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["target"] })); let release; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "promote_queued_message", + match: (method, _url, body) => method === "POST" && body?.type === "clear_queue", produce: () => new Promise((resolve) => { release = resolve; }), }); - let promotion; - await act(async () => { promotion = old.latest.promoteQueuedToSteer("target"); }); + let clearing; + await act(async () => { clearing = old.latest.clearQueuedMessages(); }); old.unmount(); - const current = await mountSession("new-promotion"); + const current = await mountSession("new-clear"); await act(async () => { - release({ status: 400, value: { error: "Native promotion failed" } }); - await promotion; + release({ status: 400, value: { error: "Native clear failed" } }); + await clearing; }); assert.deepEqual(current.latest.notices, []); }); -// Stop must neither lose a queued message nor let omp run it: omp starts a -// queued steer as soon as an abort lands (#130 saw follow-ups replay after the -// next reply). Withdraw first, like the TUI's Esc, and hand the text back. -test("Stop withdraws pending queued messages into the session draft before aborting", async () => { +test("a queue clear pi answers after unmount still resolves to the withdrawn texts so Edit can recover them", async () => { const { getDraft, clearDraft } = await import("@/lib/draft-store"); resetWorld(); - clearDraft("abort-withdraw"); - primeSession("abort-withdraw", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-withdraw", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["my steer", "already taken"], followUp: ["my follow-up"] })); - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message" && body.message === "already taken", - produce: async () => ({ value: { success: true, data: { removed: false } } }), - }); - for (const message of ["my steer", "my follow-up"]) { - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message" && body.message === message, - produce: async () => ({ value: { success: true, data: { removed: true } } }), - }); - } - await act(async () => { await w.latest.handleAbort(); }); - const commands = world.calls.map((c) => c.body?.type).filter(Boolean); - assert.ok(commands.lastIndexOf("remove_queued_message") < commands.indexOf("abort"), "the queue is withdrawn before the abort lands"); - assert.equal(getDraft("abort-withdraw")?.value, "my steer\n\nmy follow-up", "a message the model already took stays out of the draft"); - assert.deepEqual(w.latest.notices, []); - clearDraft("abort-withdraw"); -}); - -test("a slow withdrawal does not hold Stop, and its late answer still recovers the text", async () => { - const { getDraft, clearDraft } = await import("@/lib/draft-store"); - resetWorld(); - clearDraft("abort-slow"); - primeSession("abort-slow", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-slow", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["slow steer"], followUp: [] })); - let release; - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: () => new Promise((resolve) => { release = resolve; }), - }); - let stop; - await act(async () => { stop = w.latest.handleAbort(); }); - await sleep(1700); - assert.equal(world.calls.some((c) => c.body?.type === "abort"), true, "abort goes out while the removal is still pending"); - await act(async () => { - release({ value: { success: true, data: { removed: true } } }); - await stop; - }); - assert.equal(getDraft("abort-slow")?.value, "slow steer"); - clearDraft("abort-slow"); -}); - -test("Stop saves confirmed text early and still restores the queue in order", async () => { - const { getDraft, clearDraft } = await import("@/lib/draft-store"); - resetWorld(); - clearDraft("abort-mixed"); - primeSession("abort-mixed", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-mixed", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["first", "second"], followUp: [] })); - let release; - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message" && body.message === "first", - produce: () => new Promise((resolve) => { release = resolve; }), - }); - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message" && body.message === "second", - produce: async () => ({ value: { success: true, data: { removed: true } } }), - }); - let stop; - await act(async () => { stop = w.latest.handleAbort(); }); - await sleep(1700); - assert.equal(getDraft("abort-mixed")?.value, "second", "confirmed text is saved before the stalled request settles"); - await act(async () => { - release({ value: { success: true, data: { removed: true } } }); - await stop; - }); - assert.equal(getDraft("abort-mixed")?.value, "first\n\nsecond", "a late confirmation keeps queue order"); - clearDraft("abort-mixed"); -}); - -test("Stop withdraws a follow-up that a concurrent promotion already moved to steering", async () => { - const { getDraft, clearDraft } = await import("@/lib/draft-store"); - resetWorld(); - clearDraft("abort-promoted"); - primeSession("abort-promoted", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-promoted", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["promoted"] })); - for (const [queue, removed] of [["followUp", false], ["steering", true]]) { - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message" && body.queue === queue, - produce: async () => ({ value: { success: true, data: { removed } } }), - }); - } - await act(async () => { await w.latest.handleAbort(); }); - const commands = world.calls.map((c) => c.body?.type).filter(Boolean); - assert.ok(commands.lastIndexOf("remove_queued_message") < commands.indexOf("abort")); - assert.equal(getDraft("abort-promoted")?.value, "promoted"); - assert.deepEqual(world.calls.filter((c) => c.body?.type === "remove_queued_message").map((c) => c.body.queue), ["followUp", "steering"]); - clearDraft("abort-promoted"); -}); - -test("a steering message the model already took is not looked for among follow-ups", async () => { - resetWorld(); - primeSession("abort-taken", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-taken", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["taken"], followUp: [] })); - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: async () => ({ value: { success: true, data: { removed: false } } }), - }); - await act(async () => { await w.latest.handleAbort(); }); - assert.deepEqual(world.calls.filter((c) => c.body?.type === "remove_queued_message").map((c) => c.body.queue), ["steering"]); -}); - -test("a cancellation omp confirms after unmount still reports success so Edit can recover the text", async () => { - resetWorld(); - primeSession("cancel-unmount", [userMsg("u0", "q")]); - const { w, es } = await startRun("cancel-unmount", "run"); + clearDraft("clear-unmount"); + primeSession("clear-unmount", [userMsg("u0", "q")]); + const { w, es } = await startRun("clear-unmount", "run"); await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["target"] })); let release; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", + match: (method, _url, body) => method === "POST" && body?.type === "clear_queue", produce: () => new Promise((resolve) => { release = resolve; }), }); - let cancellation; - await act(async () => { cancellation = w.latest.removeQueuedMessage("target", "followUp"); }); + let clearing; + await act(async () => { clearing = w.latest.clearQueuedMessages(); }); w.unmount(); - release({ value: { success: true, data: { removed: true } } }); - assert.deepEqual(await cancellation, [], "an omp that returns no images still confirms the removal"); + release({ value: { success: true, data: { steering: [], followUp: ["target"] } } }); + assert.deepEqual(await clearing, ["target"]); + assert.equal(getDraft("clear-unmount"), null, "the hook writes no draft"); }); -test("a Stop whose run ended during the withdrawal does not abort the next prompt", async () => { +// End to end through ChatWindow: the composer recovers a queue Edit into its +// confirmed owner, following confirmed identity moves (retargetPendingRecovery). +test("a queue Edit pi answers after a confirmed Edit identity move recovers into the moved conversation", async (t) => { resetWorld(); - primeSession("abort-fenced", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-fenced", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["late steer"], followUp: [] })); + const { getDraft, clearDraft } = await import("@/lib/draft-store"); + const sid = "queue-edit-move", target = `${sid}-owned`; + t.after(() => { clearDraft(sid); clearDraft(target); }); + const native = primeEditableHistory(sid); + native.moveTo = target; + await attachEditableWrapper(t, native); + const w = await mountMovableChat(sid); + await act(async () => { lastEs().emit({ type: "queue_update", steering: [], followUp: ["queued question"] }); }); let release; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: () => new Promise((resolve) => { release = resolve; }), - }); - let stop; - await act(async () => { stop = w.latest.handleAbort(); }); - await act(async () => { - es.emit({ type: "message_end", message: assistantMsg("a1", "answer") }); - es.emit({ type: "agent_end", isTerminal: true }); + match: (method, _url, body) => method === "POST" && body?.type === "clear_queue", + produce: () => new Promise((resolve) => { + release = () => resolve({ value: { success: true, data: { steering: [], followUp: ["queued question"] } } }); + }), }); + await act(async () => { fireEvent.click(w.view.getByTitle(translate("chatInput.queuedEditTitle"))); }); + assert.equal(typeof release, "function", "pi has the clear_queue; its answer is still on the way"); + // pi's queue is empty now, so a history Edit is legal before the answer lands. + await act(async () => { lastEs().emit({ type: "queue_update", steering: [], followUp: [] }); }); + await confirmEdit(w.view, w.editButton()); + await until(() => w.selectedId === target, "the Edit confirms the new identity before the queue answer"); + await act(async () => { release(); }); await settle(); - let sending; - await act(async () => { sending = w.latest.handleSend("next prompt"); await sleep(30); }); - await act(async () => { lastEs().open(); await sending; }); - await act(async () => { - release({ value: { success: true, data: { removed: true } } }); - await stop; - }); - assert.equal(world.calls.some((c) => c.body?.type === "prompt" && c.body?.message === "next prompt"), true); - assert.equal(world.calls.some((c) => c.body?.type === "abort"), false, "the new prompt keeps running"); + assert.match(getDraft(target)?.value ?? "", /queued question/, "the withdrawn text lands in the conversation's current draft"); + assert.match(w.view.getByRole("textbox").value, /queued question/); + assert.equal(getDraft(sid), null, "recovery must not resurrect the abandoned owner"); }); test("a delayed Stop does not abort a run another device started after the targeted run ended", async () => { @@ -1086,7 +919,7 @@ test("a delayed Stop does not abort a run another device started after the targe await act(() => es.emit({ type: "queue_update", steering: ["late steer"], followUp: [] })); let release; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", + match: isAtomicStop, produce: () => new Promise((resolve) => { release = resolve; }), }); let stop; @@ -1099,9 +932,10 @@ test("a delayed Stop does not abort a run another device started after the targe await act(async () => { es.emit({ type: "agent_start" }); }); // another device's prompt await settle(); await act(async () => { - release({ value: { success: true, data: { removed: true } } }); + release({ status: 502, value: { error: "Bad Gateway" } }); await stop; }); + assert.equal(world.calls.filter((c) => c.body?.type === "abort_and_restore_queue").length, 1, "the failed Stop is not retried into the other device's run"); assert.equal(world.calls.some((c) => c.body?.type === "abort"), false, "the other device's run keeps going"); }); @@ -1112,7 +946,7 @@ test("a delayed Stop spares another device's run even when the targeted run ende await act(() => es.emit({ type: "queue_update", steering: ["late steer"], followUp: [] })); let release; world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", + match: isAtomicStop, produce: () => new Promise((resolve) => { release = resolve; }), }); // The empty-completion recovery reload stalls, so the hook never renders idle. @@ -1127,9 +961,10 @@ test("a delayed Stop spares another device's run even when the targeted run ende es.emit({ type: "agent_start" }); // another device's prompt }); await act(async () => { - release({ value: { success: true, data: { removed: true } } }); + release({ status: 502, value: { error: "Bad Gateway" } }); await stop; }); + assert.equal(world.calls.filter((c) => c.body?.type === "abort_and_restore_queue").length, 1, "the failed Stop is not retried into the other device's run"); assert.equal(world.calls.some((c) => c.body?.type === "abort"), false, "the other device's run keeps going"); }); @@ -1176,71 +1011,6 @@ test("an older state response cannot overwrite a newer snapshot that arrived fir assert.deepEqual(w.latest.queuedMessages, { steering: ["pending"], followUp: [] }, "the older response must not clear the chip"); }); -test("overlapping Stops share one withdrawal and one abort", async () => { - resetWorld(); - primeSession("abort-twice", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-twice", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["A", "B"], followUp: [] })); - await act(async () => { await Promise.all([w.latest.handleAbort(), w.latest.handleAbort()]); }); - assert.deepEqual(world.calls.filter((c) => c.body?.type === "remove_queued_message").map((c) => c.body.message), ["A", "B"]); - assert.equal(world.calls.filter((c) => c.body?.type === "abort").length, 1); -}); - -test("a stalled withdrawal from an earlier Stop does not swallow the next run's Stop", async () => { - resetWorld(); - primeSession("abort-next", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-next", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: ["stalled"], followUp: [] })); - let release; - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: () => new Promise((resolve) => { release = resolve; }), - }); - let first; - await act(async () => { first = w.latest.handleAbort(); }); - await sleep(1700); // deadline passed, first abort sent, removal still pending - await act(async () => { - es.emit({ type: "message_end", message: assistantMsg("a1", "answer") }); - es.emit({ type: "agent_end", isTerminal: true }); - es.emit({ type: "queue_update", steering: [], followUp: [] }); - }); - await settle(); - let sending; - await act(async () => { sending = w.latest.handleSend("next prompt"); await sleep(30); }); - await act(async () => { lastEs().open(); await sending; }); - await act(async () => { await w.latest.handleAbort(); }); - assert.equal(world.calls.filter((c) => c.body?.type === "abort").length, 2, "the new run's Stop sends its own abort"); - await act(async () => { - release({ value: { success: true, data: { removed: true } } }); - await first; - }); -}); - -test("a late follow-up refusal does not remove a same-text steer from a newer run", async () => { - resetWorld(); - primeSession("abort-late-refusal", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-late-refusal", "hello agent"); - await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["same"] })); - let refuse; - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message" && body.queue === "followUp", - produce: () => new Promise((resolve) => { refuse = resolve; }), - }); - let stop; - await act(async () => { stop = w.latest.handleAbort(); }); - await sleep(1700); - await act(async () => { - es.emit({ type: "message_end", message: assistantMsg("a1", "answer") }); - es.emit({ type: "agent_end", isTerminal: true }); - es.emit({ type: "agent_start" }); // new run that queues its own "same" steer - }); - await act(async () => { - refuse({ value: { success: true, data: { removed: false } } }); - await stop; - }); - assert.equal(world.calls.some((c) => c.body?.type === "remove_queued_message" && c.body.queue === "steering"), false); -}); - test("a state snapshot older than a queue_update is dropped, and opening the stream re-reads the queue", async () => { resetWorld(); primeSession("queue-order", [userMsg("u0", "q")]); @@ -1264,34 +1034,16 @@ test("a state snapshot older than a queue_update is dropped, and opening the str assert.deepEqual(w.latest.queuedMessages, { steering: ["queued while disconnected"], followUp: [] }); }); -test("a settled cancellation releases the guard for the next one", async () => { +test("a settled queue clear releases the guard for the next one", async () => { resetWorld(); - primeSession("cancel-twice", [userMsg("u0", "q")]); - const { w, es } = await startRun("cancel-twice", "run"); + primeSession("clear-twice", [userMsg("u0", "q")]); + const { w, es } = await startRun("clear-twice", "run"); await act(() => es.emit({ type: "queue_update", steering: [], followUp: ["one", "two"] })); await act(async () => { - await w.latest.removeQueuedMessage("one", "followUp"); - await w.latest.removeQueuedMessage("two", "followUp"); + assert.deepEqual(await w.latest.clearQueuedMessages(), []); + assert.deepEqual(await w.latest.clearQueuedMessages(), []); }); - assert.deepEqual(world.calls.filter((c) => c.body?.type === "remove_queued_message").map((c) => c.body.message), ["one", "two"]); -}); - -test("Stop with an empty queue sends no removal; a failed withdrawal still stops and warns", async () => { - resetWorld(); - primeSession("abort-empty", [userMsg("u0", "loaded question")]); - const { w, es } = await startRun("abort-empty", "hello agent"); - await act(async () => { await w.latest.handleAbort(); }); - assert.equal(world.calls.some((c) => c.body?.type === "remove_queued_message"), false); - assert.deepEqual(w.latest.notices, []); - - await act(() => es.emit({ type: "queue_update", steering: ["my steer"], followUp: [] })); - world.holds.push({ - match: (method, _url, body) => method === "POST" && body?.type === "remove_queued_message", - produce: async () => ({ status: 400, value: { error: "Unknown RPC command: remove_queued_message" } }), - }); - await act(async () => { await w.latest.handleAbort(); }); - assert.equal(world.calls.filter((c) => c.body?.type === "abort").length, 2); - assert.deepEqual(w.latest.notices.map((n) => n.type), ["warning"]); + assert.equal(world.calls.filter((c) => c.body?.type === "clear_queue").length, 2); }); test("an answered dialog handoff cannot clear the next unanswered request", async () => { @@ -1392,17 +1144,6 @@ test("ui_end closes another tab's dialog; presentation ui frames drive notices, assert.equal(w.latest.extensionCustomUi, null); }); -test("a stale local queue action reports that its target is unavailable", async () => { - resetWorld(); - primeSession("missing-local-target", [userMsg("u0", "q")]); - const w = await mountSession("missing-local-target"); - await act(async () => { - assert.equal(await w.latest.removeQueuedMessage("already delivered", "followUp"), false); - }); - assert.deepEqual(w.latest.queuedMessages, { steering: [], followUp: [] }); - assert.equal(w.latest.notices.at(-1)?.type, "warning"); -}); - // ISSUE #167: omp reports 47 runnable builtins over RPC; `/guided-goal`, // `/vibe`, `/budget` and `/goal` are TUI-only and absent from that list, so the // client has to name them instead of letting them land as silent prompt text. @@ -6135,22 +5876,19 @@ test("a vanished session's permanent outbox refusal remains a failed held bubble assert.deepEqual(w.latest.notices, [], "the held bubble owns permanent delivery errors"); }); -// The incident behind abort_and_restore_queue: a promoted steer was still in -// omp when Stop landed but missing from this client's snapshot, so nothing -// withdrew it and omp ran it as a new turn after the abort. omp's atomic Esc -// takes back everything it holds, listed here or not. -test("Stop takes queued input back through omp in one step, including a steer the snapshot missed", async () => { +// The incident behind abort_and_restore_queue: a steer was still in the agent +// when Stop landed but missing from this client's snapshot, so nothing withdrew +// it and it ran as a new turn after the abort. The server's clear_queue + abort +// takes back everything pi holds, listed here or not, in delivery order. +test("Stop takes queued input back in one step, including a steer the snapshot missed", async () => { const { getDraft, clearDraft } = await import("@/lib/draft-store"); resetWorld(); clearDraft("abort-atomic"); primeSession("abort-atomic", [userMsg("u0", "loaded question")]); const { w } = await startRun("abort-atomic", "hello agent"); world.abortRestoreQueue = { - steering: [{ text: "steer the snapshot missed" }, { text: "[Image]" }], - followUp: [ - { text: "later follow-up", images: [{ type: "image", data: "x", mimeType: "image/png" }] }, - { text: "[Image]", images: [{ type: "image", data: "y", mimeType: "image/webp" }] }, - ], + steering: [{ text: "steer the snapshot missed" }, { text: "second steer" }], + followUp: [{ text: "later follow-up" }, { text: "" }, { text: 7 }], }; await act(async () => { await w.latest.handleAbort(); }); @@ -6158,15 +5896,13 @@ test("Stop takes queued input back through omp in one step, including a steer th const commands = world.calls.map((c) => c.body?.type).filter(Boolean); assert.equal(commands.filter((type) => type === "abort_and_restore_queue").length, 1); assert.equal(commands.includes("abort"), false, "omp's own abort already stopped the run"); - assert.equal(commands.includes("remove_queued_message"), false); - assert.equal(getDraft("abort-atomic")?.value, "steer the snapshot missed\n\n[Image]\n\nlater follow-up", "only an image-only message's label is dropped"); - assert.deepEqual(getDraft("abort-atomic")?.images, [{ data: "x", mimeType: "image/png" }, { data: "y", mimeType: "image/webp" }]); + assert.equal(commands.includes("clear_queue"), false, "the server withdraws as part of the Stop"); + assert.equal(getDraft("abort-atomic")?.value, "steer the snapshot missed\n\nsecond steer\n\nlater follow-up", "steering first, then follow-ups"); + assert.equal(getDraft("abort-atomic")?.promptOnly, true); assert.deepEqual(w.latest.notices, []); clearDraft("abort-atomic"); }); -const isAtomicStop = (method, _url, body) => method === "POST" && body?.type === "abort_and_restore_queue"; - test("a failed atomic Stop is retried once and restores what omp still held", async () => { const { getDraft, clearDraft } = await import("@/lib/draft-store"); resetWorld(); @@ -6180,8 +5916,7 @@ test("a failed atomic Stop is retried once and restores what omp still held", as const commands = world.calls.map((c) => c.body?.type).filter(Boolean); assert.equal(commands.filter((type) => type === "abort_and_restore_queue").length, 2); - assert.equal(commands.includes("abort"), false, "a failure is not mistaken for an omp without the command"); - assert.equal(commands.includes("remove_queued_message"), false); + assert.equal(commands.includes("abort"), false, "a failure is retried, never replaced by a plain abort"); assert.equal(getDraft("abort-atomic-retry")?.value, "retry me"); assert.deepEqual(w.latest.notices, []); clearDraft("abort-atomic-retry"); @@ -6228,21 +5963,19 @@ test("a failed atomic Stop never retries into a run started after the click", as assert.equal(world.calls.some((c) => c.body?.type === "abort"), false, "nor a fallback abort"); }); -test("overlapping Stops share one atomic withdrawal; an image-only entry does not come back as text", async () => { +test("overlapping Stops share one atomic withdrawal and restore its texts once", async () => { const { getDraft, clearDraft } = await import("@/lib/draft-store"); resetWorld(); clearDraft("abort-atomic-twice"); primeSession("abort-atomic-twice", [userMsg("u0", "loaded question")]); const { w } = await startRun("abort-atomic-twice", "hello agent"); - world.abortRestoreQueue = { - steering: [{ text: "[Image]", images: [{ type: "image", data: "x", mimeType: "image/png" }] }], - followUp: [{ text: "words" }], - }; + world.abortRestoreQueue = { steering: [{ text: "A" }], followUp: [{ text: "words" }] }; await act(async () => { await Promise.all([w.latest.handleAbort(), w.latest.handleAbort()]); }); assert.equal(world.calls.filter((c) => c.body?.type === "abort_and_restore_queue").length, 1); - assert.equal(getDraft("abort-atomic-twice")?.value, "words"); + assert.equal(world.calls.some((c) => c.body?.type === "abort"), false); + assert.equal(getDraft("abort-atomic-twice")?.value, "A\n\nwords"); clearDraft("abort-atomic-twice"); }); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0d3a9ed8..5ea80a84 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -27,7 +27,7 @@ import { HostOfflineError, TransportLostError, getOutboxScope, rememberOutboxSco import type { HostStatus } from "@/lib/hosts/host"; import type { WorkspaceFileSource } from "@/lib/workspace-types"; import { newChatDraftKey, remoteHostId } from "@/lib/project-ordering"; -import { clearDraft, getDraft, mergeRecoveredText, recoverDraft, setDraft, toDraftImages, type ChatDraft, type ChatDraftImage } from "@/lib/draft-store"; +import { clearDraft, getDraft, mergeRecoveredText, recoverDraft, setDraft, type ChatDraft } from "@/lib/draft-store"; import { formatExitedSessionNotice, translate } from "@/lib/i18n"; import { formatApiError } from "@/lib/i18n/api-error"; import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion"; @@ -79,7 +79,6 @@ import { import type { NoticeType } from "./useAgentSession-notices"; import { AGENT_STATE_RECONCILE_MS, - WITHDRAW_BEFORE_ABORT_MS, BASH_STATE_RECONCILE_MS, EVENT_STREAM_CONNECT_TIMEOUT_MS, EVENT_STREAM_RETRY_MAX_MS, @@ -2431,29 +2430,19 @@ export function useAgentSession(opts: UseAgentSessionOptions) { }, [agentRunning]); - /** Cancel one pending message in omp. The chip itself leaves through omp's - * queue snapshot; resolves to the removed message's images (empty when it - * had none or omp does not return them) only when omp confirms the - * removal, else false. */ - const removeQueuedMessage = useCallback(async (text: string, queue: "steering" | "followUp"): Promise => { + /** Take every queued message back from pi, which clears its queue only whole + * (texts, never images); the chips leave through pi's queue snapshot. + * Resolves to the texts in delivery order, or false when pi did not clear. */ + const clearQueuedMessages = useCallback(async (): Promise => { const sid = sessionIdRef.current; - if (!hookAliveRef.current || !sid || !text) return false; - if (!queuedMessagesRef.current[queue].includes(text)) { - addNotice({ type: "warning", message: translate("agentSession.queuedRemovalUnavailable") }); - return false; - } + if (!hookAliveRef.current || !sid) return false; if (queuedRemovalRef.current?.sessionId === sid) return false; const removal = { sessionId: sid }; queuedRemovalRef.current = removal; try { - const result = await sendAgentCommand<{ removed: boolean; images?: unknown }>(sid, { - type: "remove_queued_message", message: text, queue, - }); - if (result?.removed === true) return toDraftImages(result.images); - if (hookAliveRef.current && sessionIdRef.current === sid) { - addNotice({ type: "warning", message: translate("agentSession.queuedRemovalUnavailable") }); - } - return false; + const result = await sendAgentCommand<{ steering?: unknown; followUp?: unknown }>(sid, { type: "clear_queue" }); + return [result?.steering, result?.followUp].flatMap((queue) => (Array.isArray(queue) ? queue : [])) + .filter((text): text is string => typeof text === "string" && text.length > 0); } catch (error) { if (hookAliveRef.current && sessionIdRef.current === sid) { addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); @@ -2464,30 +2453,6 @@ export function useAgentSession(opts: UseAgentSessionOptions) { } }, [addNotice]); - /** Move the first matching follow-up into omp's steering queue; the chip - * relabels through omp's queue snapshot. Never enqueue a copy via steer. */ - const promoteQueuedToSteer = useCallback(async (text: string) => { - const sid = sessionIdRef.current; - if (!hookAliveRef.current || !sid || !text || !queuedMessagesRef.current.followUp.includes(text)) return; - if (queuedRemovalRef.current?.sessionId === sid) return; - const promotion = { sessionId: sid }; - queuedRemovalRef.current = promotion; - try { - const result = await sendAgentCommand<{ promoted: boolean }>(sid, { - type: "promote_queued_message", - message: text, - }); - if (result?.promoted !== true && hookAliveRef.current && sessionIdRef.current === sid) { - addNotice({ type: "warning", message: translate("agentSession.queuedPromotionUnavailable") }); - } - } catch (error) { - if (!hookAliveRef.current || sessionIdRef.current !== sid) return; - addNotice({ type: "error", message: error instanceof Error ? error.message : String(error) }); - } finally { - if (queuedRemovalRef.current === promotion) queuedRemovalRef.current = null; - } - }, [addNotice]); - const handleAgentEvent = useCallback((event: AgentEvent) => { if ((event.type === "message_start" || event.type === "message_end") && typeof event.clientMessageId === "string" && event.message) { const message = event.message as AgentMessage; @@ -3661,132 +3626,44 @@ export function useAgentSession(opts: UseAgentSessionOptions) { }, [addNotice, ensureNewSession, loadSession, opts.chatInputRef, promoteNewSession, session]); executeBashRef.current = executeBash; - const withdrawAndAbort = useCallback(async (sid: string, onAbortSent: () => void) => { - // Captured at the click: no abort below may reach a run that started + const withdrawAndAbort = useCallback(async (sid: string) => { + // Captured at the click: a retry must not reach a run that started // since (this client's next prompt or another device's). const runId = promptRunIdRef.current; const runsEnded = runsEndedRef.current; const sameRun = () => promptRunIdRef.current === runId && runsEndedRef.current === runsEnded; - // Like the TUI's Esc, omp takes every pending user message back and then - // aborts, in one step: it also catches a steer this client's queue - // snapshot does not list yet, or one the run already claimed but never - // recorded, which a removal by text cannot reach and which omp would - // otherwise run as a new turn right after the abort. The texts and images - // return to this session's draft (omp drops the images from a response - // over its transport limit). Known window: they exist only in the - // response until the abort finishes, so a reload during a slow abort + // Like the TUI's Esc, the server takes every pending user message back + // (pi's clear_queue) and then aborts: pi would otherwise run a queued + // message as soon as the abort lands. The texts return to this session's + // draft; pi keeps no images for them. Known window: they exist only in + // the response until the abort finishes, so a reload during a slow abort // loses them. - type RestoredQueue = { steering?: Array<{ text?: unknown; images?: unknown[] }>; followUp?: Array<{ text?: unknown; images?: unknown[] }> }; + type RestoredQueue = { steering?: Array<{ text?: unknown }>; followUp?: Array<{ text?: unknown }> }; let restoredQueue: RestoredQueue | null | undefined; - let unsupported = false; let failures = 0; - // A failure after omp already withdrew would lose the texts on the - // per-entry path (the queue is empty by then). Retrying the same command - // is safe instead: omp returns whatever is still queued. - for (let attempt = 0; attempt < 2 && restoredQueue === undefined && !unsupported && (attempt === 0 || sameRun()); attempt++) { + // Retrying the same command is safe: it returns whatever is still queued. + for (let attempt = 0; attempt < 2 && restoredQueue === undefined && (attempt === 0 || sameRun()); attempt++) { try { restoredQueue = (await sendAgentCommand(sid, { type: "abort_and_restore_queue" })) ?? null; - } catch (error) { - unsupported = error instanceof Error && error.message.includes("Unknown command"); - if (!unsupported) failures += 1; - } - } - if (!unsupported) { - const steering = Array.isArray(restoredQueue?.steering) ? restoredQueue.steering : []; - const followUp = Array.isArray(restoredQueue?.followUp) ? restoredQueue.followUp : []; - const entries = [...steering, ...followUp]; - const texts = entries - // An image-only message comes back as omp's "[Image]" chip label, - // which is not text to put back; a literal "[Image]" without images is. - .filter((entry) => !(entry.text === "[Image]" && Array.isArray(entry.images) && entry.images.length > 0)) - .map((entry) => entry.text) - .filter((text): text is string => typeof text === "string" && text.length > 0); - const images = entries.flatMap((entry) => toDraftImages(entry.images)); - if (texts.length > 0 || images.length > 0) recoverDraft(sid, { text: texts.join("\n\n"), images, promptOnly: true }); - // A failed attempt may have withdrawn messages whose texts were in the - // lost response; say so unless the retry brought texts back. - if (failures > 0 && texts.length === 0 && hookAliveRef.current && sessionIdRef.current === sid) { - addNotice({ type: "warning", message: translate("agentSession.queueRestoreUncertain") }); - } - return; - } - // omp before abort_and_restore_queue: take pending messages back out of - // omp BEFORE the abort: omp runs a queued steer as soon as an abort lands - // (and keeps a follow-up for after the next reply, #130). A message the - // model already took (removed: false) lands in the transcript instead. A - // steer whose send has not reached omp's queue snapshot yet is not withdrawn. - const pending = queuedMessagesRef.current; - const entries = [ - ...pending.steering.map((text) => ({ text, queue: "steering" as const })), - ...pending.followUp.map((text) => ({ text, queue: "followUp" as const })), - ]; - const removed: boolean[] = []; - const restored: boolean[] = []; - let recoveredBlock = ""; - let failed = false; - // Recover confirmed withdrawals in queue order. A later batch rewrites the - // earlier block in order while the draft still starts with it. - const recoverWithdrawn = () => { - const fresh = entries.filter((_, i) => removed[i] && !restored[i]).map((entry) => entry.text); - if (fresh.length === 0) return; - entries.forEach((_, i) => { if (removed[i]) restored[i] = true; }); - const block = entries.filter((_, i) => restored[i]).map((entry) => entry.text).join("\n\n"); - recoverDraft(sid, { text: block, replace: recoveredBlock ? { lead: recoveredBlock, fallback: fresh.join("\n\n") } : undefined, promptOnly: true }); - recoveredBlock = block; - }; - const removals = Promise.all(entries.map(async (entry, i) => { - // A promotion that landed after this snapshot moved the message into - // steering (removal from steering never moves it back): try both. - const queues = entry.queue === "followUp" ? ["followUp", "steering"] as const : ["steering"] as const; - try { - for (const queue of queues) { - // A late refusal must not reach into a newer run's steering queue. - if (queue === "steering" && entry.queue === "followUp" - && (promptRunIdRef.current !== runId || runsEndedRef.current !== runsEnded)) return; - const result = await sendAgentCommand<{ removed: boolean }>(sid, { type: "remove_queued_message", message: entry.text, queue }); - if (result?.removed === true) { - removed[i] = true; - return; - } - } - } catch (error) { - console.error("Failed to withdraw queued message:", error); - failed = true; - } - })); - // A slow removal must not hold Stop hostage; late answers still recover - // text. (Executor form: Promise.withResolvers is missing in Safari < 17.4.) - let clearDeadline = () => {}; - await Promise.race([removals, new Promise((resolve) => { - const timer = setTimeout(resolve, WITHDRAW_BEFORE_ABORT_MS); - clearDeadline = () => clearTimeout(timer); - })]); - clearDeadline(); - // Text omp already gave back must survive a reload while a slower - // removal is still pending. - recoverWithdrawn(); - // The targeted run may have ended during the wait and another prompt - // (this client's or another device's) started: this Stop is not for it. - if (sameRun()) { - try { - await sendAgentCommand(sid, { type: "abort" }); - } catch (e) { - console.error("Failed to abort:", e); + } catch { + failures += 1; } } - // From here only late recovery remains: a new run's Stop must not wait on it. - onAbortSent(); - await removals; - recoverWithdrawn(); - if (failed && hookAliveRef.current && sessionIdRef.current === sid) { - addNotice({ type: "warning", message: translate("agentSession.queueDiscardFailed") }); + const steering = Array.isArray(restoredQueue?.steering) ? restoredQueue.steering : []; + const followUp = Array.isArray(restoredQueue?.followUp) ? restoredQueue.followUp : []; + const texts = [...steering, ...followUp] + .map((entry) => entry.text) + .filter((text): text is string => typeof text === "string" && text.length > 0); + if (texts.length > 0) recoverDraft(sid, { text: texts.join("\n\n"), promptOnly: true }); + // A failed attempt may have withdrawn messages whose texts were in the + // lost response; say so unless the retry brought texts back. + if (failures > 0 && texts.length === 0 && hookAliveRef.current && sessionIdRef.current === sid) { + addNotice({ type: "warning", message: translate("agentSession.queueRestoreUncertain") }); } }, [addNotice]); // Button, Esc, and the global shortcut can all fire while a withdrawal is // in flight: one Stop at a time, or two recoveries interleave their text. - // The guard covers withdrawal and abort only; late recovery of a stalled - // removal must not swallow the Stop of a run that starts afterwards. const stopInFlightRef = useRef | null>(null); const handleAbort = useCallback(async () => { const sid = sessionIdRef.current; @@ -3803,7 +3680,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { if (stopInFlightRef.current) return stopInFlightRef.current; // An older Stop never clears a newer one's guard. const release = () => { if (stopInFlightRef.current === stop) stopInFlightRef.current = null; }; - const stop: Promise = withdrawAndAbort(sid, release).finally(release); + const stop: Promise = withdrawAndAbort(sid).finally(release); stopInFlightRef.current = stop; return stop; }, [withdrawAndAbort]); @@ -4935,7 +4812,7 @@ export function useAgentSession(opts: UseAgentSessionOptions) { handleCompact, handleHandoff, handleSteer, handleFollowUp, handleAbortCompaction, heldMessages, deleteHeldMessage, retryHeldMessage, handleBuiltinSlashCommand, togglePreCompactionHistory, - handleToolPresetChange, handleThinkingLevelChange, loadSlashCommands, removeQueuedMessage, promoteQueuedToSteer, setActiveLeafId, setData, setMessages, + handleToolPresetChange, handleThinkingLevelChange, loadSlashCommands, clearQueuedMessages, setActiveLeafId, setData, setMessages, dispatch, setAgentRunning, setForkingEntryId, resolveUploadHost, btw, askBtw, diff --git a/lib/hosts/channel-lifecycle.test.mjs b/lib/hosts/channel-lifecycle.test.mjs index 8534af19..980a6872 100644 --- a/lib/hosts/channel-lifecycle.test.mjs +++ b/lib/hosts/channel-lifecycle.test.mjs @@ -85,9 +85,9 @@ test("authoritative queue withdrawal releases queued guards but a pre-ACK empty l.noteStdout({ type: "queue_update", steering: [], followUp: ["later"] }); l.noteStdout({ type: "response", id: "queued", command: "follow_up", success: true, data: { queued: true } }); assert.equal(l.isIdle, false); - l.noteStdin({ type: "remove_queued_message", id: "withdraw", messageId: "queued" }); + l.noteStdin({ type: "clear_queue", id: "withdraw" }); l.noteStdout({ type: "queue_update", steering: [], followUp: [] }); - l.noteStdout({ type: "response", id: "withdraw", command: "remove_queued_message", success: true, data: {} }); + l.noteStdout({ type: "response", id: "withdraw", command: "clear_queue", success: true, data: { steering: [], followUp: ["later"] } }); assert.equal(l.isIdle, true); l.noteStdin({ type: "follow_up", id: "starting", message: "now" }); l.noteStdout({ type: "queue_update", steering: [], followUp: [] }); diff --git a/lib/hosts/channel-lifecycle.ts b/lib/hosts/channel-lifecycle.ts index 6a728c5a..47024bbb 100644 --- a/lib/hosts/channel-lifecycle.ts +++ b/lib/hosts/channel-lifecycle.ts @@ -96,7 +96,7 @@ export class ChannelLifecycle { if (queued) this.awaitingQueue.set(id, false); else this.awaitingStart.add(id); } - if (op === "remove_queued_message" || op === "abort_and_restore_queue" || op === "clear_queue") this.queueWithdrawals.set(id, this.queueRevision); + if (op === "clear_queue") this.queueWithdrawals.set(id, this.queueRevision); } this.changed(); } diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 49ec8133..c1a8f2fc 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -67,7 +67,7 @@ export const LINK_CLOSE = { goingAway: 1001, invalidData: 1007, policy: 1008, to /** Native commands that append to, replace or resume the active history: a history edit fences them on every link. */ export const HISTORY_MUTATING_COMMANDS = new Set([ "edit_message", "prompt", "steer", "follow_up", "followUp", "abort", "abort_and_prompt", - "abort_and_restore_queue", "remove_queued_message", "promote_queued_message", + "abort_and_restore_queue", "clear_queue", "fork", "branch", "new_session", "switch_session", "compact", "abort_compaction", "reload", "bash", "abort_bash", "handoff", "set_todos", "set_session_name", "set_model", "cycle_model", "set_thinking_level", "cycle_thinking_level", diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 5f2c4b32..d19bb06a 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -30,10 +30,7 @@ "agentSession.uploadOwnerUnavailable": "The session owner could not be determined. No file was uploaded.", "agentSession.sessionRenamed": "Session renamed to {name}", "agentSession.shellSessionFailed": "Unable to create a session for the shell command", - "agentSession.queuedPromotionUnavailable": "The queued follow-up is no longer available to steer.", "agentSession.queuedWhileShellRunning": "A shell command is still running, so the message was queued and runs when it finishes.", - "agentSession.queuedRemovalUnavailable": "This message is no longer pending in that queue and could not be cancelled.", - "agentSession.queueDiscardFailed": "The run was stopped, but some queued messages could not be taken back. The agent may still deliver them.", "agentSession.queueRestoreUncertain": "The run was stopped, but the queued messages may not have come back to the composer. Check the queue and the chat before resending.", "agentSession.startingAgent": "Starting omp… the first launch of a session can take a while.", "agentSession.toolPresetNotice": "Tool presets apply when a session starts; this session keeps its current tools.", @@ -448,15 +445,13 @@ "chatInput.slowMode.wrapUpReset": "limit reached · wrapping up · resets {time}", "chatInput.slowMode.wrapUpExtraUsage": "limit reached · wrap-up, then extra usage", "chatInput.queuedDelete": "Delete", - "chatInput.queuedDeleteTitle": "Remove this queued message", - "chatInput.queuedDeleteConfirmBody": "Cancel this queued message? Once cancellation is confirmed, it will be removed from the agent's queue. A message already delivered to the agent cannot be cancelled.", + "chatInput.queuedDeleteTitle": "Discard all queued messages", + "chatInput.queuedDeleteConfirmBody": "Discard all queued messages? The agent's queue is cleared as a whole. A message already delivered to the agent cannot be discarded.", "chatInput.cancel": "Cancel", "chatInput.queuedEdit": "Edit", - "chatInput.queuedEditTitle": "Edit this queued message", + "chatInput.queuedEditTitle": "Move all queued messages back into the composer", "chatInput.queuedFollowUp": "Queued follow-up", "chatInput.queuedSteer": "Queued steer", - "chatInput.queuedSteerAction": "Steer", - "chatInput.queuedSteerTitle": "Deliver this message as a steer", "chatInput.queuedPrompts": "Queued prompts", "chatInput.expandQueued": "Show all queued prompts", "chatInput.collapseQueued": "Collapse queued prompts", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 4519431b..3ca902df 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -30,10 +30,7 @@ "agentSession.uploadOwnerUnavailable": "セッションの所有ホストを特定できませんでした。ファイルはアップロードされていません。", "agentSession.sessionRenamed": "セッション名を {name} に変更しました", "agentSession.shellSessionFailed": "シェルコマンド用のセッションを作成できませんでした", - "agentSession.queuedPromotionUnavailable": "このフォローアップはキューに存在しないため、ステアリングに変更できません。", "agentSession.queuedWhileShellRunning": "シェルコマンドの実行中です。メッセージはキューに追加され、コマンドの終了後に実行されます。", - "agentSession.queuedRemovalUnavailable": "このメッセージはそのキューに存在しないため、キャンセルできませんでした。", - "agentSession.queueDiscardFailed": "実行は停止しましたが、キュー内の一部のメッセージを取り戻せませんでした。エージェントがそれらを配信する可能性があります。", "agentSession.queueRestoreUncertain": "実行は停止しましたが、キュー内のメッセージが入力欄に戻っていない可能性があります。再送信する前にキューとチャットを確認してください。", "agentSession.startingAgent": "omp を起動しています… セッションの初回起動には時間がかかる場合があります。", "agentSession.toolPresetNotice": "ツールプリセットはセッション開始時に適用されます。このセッションは現在のツールを維持します。", @@ -432,15 +429,13 @@ "chatInput.slowMode.wrapUpReset": "上限到達 · まとめ処理中 · {time} にリセット", "chatInput.slowMode.wrapUpExtraUsage": "上限到達 · まとめ処理後に追加使用量へ移行", "chatInput.queuedDelete": "削除", - "chatInput.queuedDeleteTitle": "このキューされたメッセージを削除", - "chatInput.queuedDeleteConfirmBody": "このキューされたメッセージをキャンセルしますか?キャンセルが確認されると、エージェントのキューから削除されます。すでにエージェントに配信されたメッセージはキャンセルできません。", + "chatInput.queuedDeleteTitle": "キューされたメッセージをすべて破棄", + "chatInput.queuedDeleteConfirmBody": "キューされたメッセージをすべて破棄しますか?エージェントのキューはまとめてクリアされます。すでにエージェントに配信されたメッセージは破棄できません。", "chatInput.cancel": "キャンセル", "chatInput.queuedEdit": "編集", - "chatInput.queuedEditTitle": "このキューされたメッセージを編集", + "chatInput.queuedEditTitle": "キューされたメッセージをすべて入力欄に戻す", "chatInput.queuedFollowUp": "キューされたフォローアップ", "chatInput.queuedSteer": "キューされたステア", - "chatInput.queuedSteerAction": "ステア", - "chatInput.queuedSteerTitle": "このメッセージをステアとして送信", "chatInput.queuedPrompts": "キュー内のプロンプト", "chatInput.expandQueued": "すべてのキューを表示", "chatInput.collapseQueued": "キューを折りたたむ", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 6e5d6c27..69f39deb 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -30,10 +30,7 @@ "agentSession.uploadOwnerUnavailable": "无法确定会话的所属主机。未上传任何文件。", "agentSession.sessionRenamed": "会话已重命名为 {name}", "agentSession.shellSessionFailed": "无法为 shell 命令创建会话", - "agentSession.queuedPromotionUnavailable": "该后续消息已不在队列中,无法转为引导消息。", "agentSession.queuedWhileShellRunning": "仍有 Shell 命令正在运行,消息已加入队列,将在该命令结束后执行。", - "agentSession.queuedRemovalUnavailable": "该消息已不在此队列中,无法取消。", - "agentSession.queueDiscardFailed": "运行已停止,但部分排队消息未能取回。智能体仍可能发送它们。", "agentSession.queueRestoreUncertain": "已停止运行,但队列中的消息可能没有回到输入框。重新发送前请检查队列和聊天记录。", "agentSession.startingAgent": "正在启动 omp……会话首次启动可能需要一些时间。", "agentSession.toolPresetNotice": "工具预设在会话启动时生效;当前会话将保留现有工具。", @@ -432,15 +429,13 @@ "chatInput.slowMode.wrapUpReset": "已达限额 · 正在收尾 · {time} 重置", "chatInput.slowMode.wrapUpExtraUsage": "已达限额 · 收尾后使用额外用量", "chatInput.queuedDelete": "删除", - "chatInput.queuedDeleteTitle": "移除这条已排队消息", - "chatInput.queuedDeleteConfirmBody": "要取消这条已排队消息吗?取消成功后,它将从智能体的队列中移除。已发送给智能体的消息无法取消。", + "chatInput.queuedDeleteTitle": "丢弃所有已排队消息", + "chatInput.queuedDeleteConfirmBody": "要丢弃所有已排队消息吗?智能体的队列会整体清空。已发送给智能体的消息无法丢弃。", "chatInput.cancel": "取消", "chatInput.queuedEdit": "编辑", - "chatInput.queuedEditTitle": "编辑这条已排队消息", + "chatInput.queuedEditTitle": "将所有已排队消息移回输入框", "chatInput.queuedFollowUp": "已排队的后续消息", "chatInput.queuedSteer": "已排队的引导消息", - "chatInput.queuedSteerAction": "引导", - "chatInput.queuedSteerTitle": "将此消息作为引导发送", "chatInput.queuedPrompts": "排队的提示词", "chatInput.expandQueued": "展开所有排队提示词", "chatInput.collapseQueued": "折叠排队提示词", diff --git a/lib/i18n/locales/zh-TW.json b/lib/i18n/locales/zh-TW.json index d858e849..f2d0c553 100644 --- a/lib/i18n/locales/zh-TW.json +++ b/lib/i18n/locales/zh-TW.json @@ -30,10 +30,7 @@ "agentSession.uploadOwnerUnavailable": "無法判定此對話所屬的主機。未上傳任何檔案。", "agentSession.sessionRenamed": "對話已重新命名為 {name}", "agentSession.shellSessionFailed": "無法為 Shell 指令建立對話", - "agentSession.queuedPromotionUnavailable": "佇列中的後續訊息已無法調整為引導指令。", "agentSession.queuedWhileShellRunning": "Shell 指令仍在執行中,訊息已排入佇列,將在指令完成後執行。", - "agentSession.queuedRemovalUnavailable": "此訊息已不在佇列的待處理清單中,無法取消。", - "agentSession.queueDiscardFailed": "執行已停止,但部分佇列中的訊息無法收回。代理仍可能會傳送這些訊息。", "agentSession.queueRestoreUncertain": "執行已停止,但佇列中的訊息可能未退回至訊息輸入框。重新傳送前請先確認佇列與對話內容。", "agentSession.startingAgent": "正在啟動 omp… 對話首次啟動可能需要一些時間。", "agentSession.toolPresetNotice": "工具組合會在對話啟動時套用;此對話將保留其目前工具。", @@ -448,15 +445,13 @@ "chatInput.slowMode.wrapUpReset": "已達額度上限 · 正在收尾 · {time} 重設", "chatInput.slowMode.wrapUpExtraUsage": "已達額度上限 · 收尾後使用額外用量", "chatInput.queuedDelete": "刪除", - "chatInput.queuedDeleteTitle": "移除此佇列訊息", - "chatInput.queuedDeleteConfirmBody": "確定要取消此佇列訊息嗎?確認取消後,該訊息將從代理的佇列中移除。已傳遞給代理的訊息無法取消。", + "chatInput.queuedDeleteTitle": "捨棄所有佇列訊息", + "chatInput.queuedDeleteConfirmBody": "確定要捨棄所有佇列訊息嗎?代理的佇列會整體清空。已傳遞給代理的訊息無法捨棄。", "chatInput.cancel": "取消", "chatInput.queuedEdit": "編輯", - "chatInput.queuedEditTitle": "編輯此佇列訊息", + "chatInput.queuedEditTitle": "將所有佇列訊息移回輸入框", "chatInput.queuedFollowUp": "佇列中的後續訊息", "chatInput.queuedSteer": "佇列中的引導訊息", - "chatInput.queuedSteerAction": "引導", - "chatInput.queuedSteerTitle": "將此訊息作為引導指令傳遞", "chatInput.queuedPrompts": "佇列中的提示詞", "chatInput.expandQueued": "顯示所有佇列中的提示詞", "chatInput.collapseQueued": "收合佇列中的提示詞", diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index ee05b64d..11330840 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -241,7 +241,7 @@ test("RpcProcess times out commands with RpcCommandTimeoutError and drops late r await proc.dispose(0); }); -for (const type of ["remove_queued_message", "promote_queued_message"]) { +for (const type of ["clear_queue"]) { test(`${type} times out without replaying, misrouting late ACKs, or interrupting long commands`, async (t) => { const transport = makeTransport(); const proc = startProcess(transport); @@ -255,7 +255,7 @@ for (const type of ["remove_queued_message", "promote_queued_message"]) { const login = wrapper.send({ type: "login", provider: "test" }); void login.then(() => { loginSettled = true; }, () => { loginSettled = true; }); let mutationError; - const mutation = wrapper.send({ type, messageId: "queued-first" }); + const mutation = wrapper.send({ type }); void mutation.catch((error) => { mutationError = error; }); await tick(); const first = transport.commands.find((command) => command.type === type); @@ -269,18 +269,18 @@ for (const type of ["remove_queued_message", "promote_queued_message"]) { assert.equal(loginSettled, false); let nextSettled = false; - const next = wrapper.send({ type, messageId: "queued-next" }); + const next = wrapper.send({ type }); void next.then(() => { nextSettled = true; }, () => { nextSettled = true; }); await tick(); const mutations = transport.commands.filter((command) => command.type === type); assert.equal(mutations.length, 2, "the timed-out mutation must not be automatically replayed"); const second = mutations[1]; - transport.send({ id: first.id, type: "response", command: type, success: true, data: { messageId: "queued-first" } }); + transport.send({ id: first.id, type: "response", command: type, success: true, data: { steering: [], followUp: ["queued-first"] } }); await tick(); assert.equal(nextSettled, false, "a late ACK must not settle a subsequent queue mutation"); - transport.send({ id: second.id, type: "response", command: type, success: true, data: { messageId: "queued-next" } }); - assert.deepEqual(await next, { messageId: "queued-next" }); + transport.send({ id: second.id, type: "response", command: type, success: true, data: { steering: [], followUp: ["queued-next"] } }); + assert.deepEqual(await next, { steering: [], followUp: ["queued-next"] }); t.mock.timers.tick(60_000); await tick(); assert.equal(loginSettled, false, "long unrelated commands retain their unlimited transport wait"); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index f711aa27..7646962f 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -1977,23 +1977,38 @@ test("auto-titling stops after a few turns omp declines to title", async (t) => assert.equal(sent.filter((type) => type === "generate_title").length, 3); }); -test("abort_and_restore_queue returns omp's withdrawn messages and clears the run like abort", async (t) => { - const restored = { steering: [{ text: "steer" }], followUp: [{ text: "later" }] }; +test("abort_and_restore_queue takes pi's queue back with clear_queue, then aborts, and clears the run like abort", async (t) => { const sent = []; const { wrapper, emit } = snapshotSession(t, async (command) => { sent.push(command.type); - if (command.type === "abort_and_restore_queue") return restored; + if (command.type === "clear_queue") return { steering: ["steer"], followUp: ["later", 7] }; if (command.type === "get_state") return { sessionId: "abort-restore", isStreaming: false, isCompacting: false }; return { ignored: true }; }); emit({ type: "agent_start" }); emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "partial" }] } }); - assert.deepEqual(await wrapper.send({ type: "abort_and_restore_queue" }), restored); + assert.deepEqual(await wrapper.send({ type: "abort_and_restore_queue" }), { steering: [{ text: "steer" }], followUp: [{ text: "later" }] }); assert.equal(wrapper.getStreamSnapshot().streamingMessage, null); assert.equal(wrapper.getStreamSnapshot().isPromptRunning, false); assert.equal(await wrapper.send({ type: "abort" }), null, "plain abort still answers nothing"); - assert.deepEqual(sent.filter((type) => type.startsWith("abort")), ["abort_and_restore_queue", "abort"]); + assert.deepEqual(sent.filter((type) => type !== "get_state"), ["clear_queue", "abort", "abort"], "clear_queue goes before abort; plain abort clears nothing"); +}); + +test("abort_and_restore_queue still returns the withdrawn texts when the abort after clear_queue fails; plain abort rethrows", async (t) => { + const sent = []; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command.type); + if (command.type === "clear_queue") return { steering: [], followUp: ["later"] }; + if (command.type === "abort") throw new Error("abort refused"); + if (command.type === "get_state") return { sessionId: "abort-restore-fail", isStreaming: false, isCompacting: false }; + return {}; + }); + const warn = t.mock.method(console, "warn", () => {}); + assert.deepEqual(await wrapper.send({ type: "abort_and_restore_queue" }), { steering: [], followUp: [{ text: "later" }] }); + assert.equal(warn.mock.callCount(), 1, "the failed abort is logged"); + await assert.rejects(wrapper.send({ type: "abort" }), /abort refused/); + assert.deepEqual(sent.filter((type) => type !== "get_state"), ["clear_queue", "abort", "abort"]); }); test("MCP toggles run native commands, serialize prompts, and reload only after success", async (t) => { @@ -2323,7 +2338,7 @@ test("an edit fences prompts and history changes from every client until its cor { type: "compact" }, { type: "reload" }, { type: "bash", command: "echo hi" }, { type: "abort_and_prompt", message: "replace" }, { type: "abort" }, { type: "set_session_name", name: "rename" }, { type: "set_model", provider: "x", modelId: "y" }, - { type: "remove_queued_message", messageId: "queued" }, + { type: "clear_queue" }, { type: "abort_and_restore_queue" }, ]; const sentBefore = session.commands.length; for (const command of fenced) await assert.rejects(session.wrapper.send(command), { code: "session_busy" }); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 5d0759e1..7f4a1bfa 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -190,7 +190,6 @@ const IMAGE_BEARING_COMMANDS = new Set(["prompt", "steer", "follow_up", "abort_a // pi-web commands with no omp RPC equivalent. The UI tolerates these failing. const UNSUPPORTED_COMMANDS: Record = { navigate_tree: "Branch navigation is not supported over the omp RPC protocol", - clear_queue: "Recalling queued messages is not supported over the omp RPC protocol", get_tools: "Per-session tool listing is not supported over the omp RPC protocol", set_tools: "Changing tools on a running session is not supported over the omp RPC protocol; tool presets apply to new sessions", }; @@ -2702,22 +2701,31 @@ export class AgentSessionWrapper { return null; } - case "remove_queued_message": - case "promote_queued_message": { - // Queue mutations are synchronous control operations, like get_state. - // Expiry must not abort unrelated work or replay a possibly applied mutation. - const result = await this.proc.sendCommand(command as { type: string }, GET_STATE_TIMEOUT_MS); + // pi takes the queue back only whole: clear_queue returns every queued text (never images). + // Like a control read, expiry must not abort unrelated work or replay a possibly applied mutation. + case "clear_queue": { + const result = await this.proc.sendCommand({ type: "clear_queue" }, GET_STATE_TIMEOUT_MS); return result ?? null; } - // abort_and_restore_queue is omp's Esc: it takes queued user input back - // atomically, then aborts, and returns the withdrawn messages. + // abort_and_restore_queue is the TUI's Esc: clear_queue before abort (pi runs a queued + // message as soon as an abort lands), then report the withdrawn texts as entries. case "abort": case "abort_and_restore_queue": { this.responseObserved = false; this.responseRunActive = false; const result = await this.withFinalRunningNotification(async () => { - const response: unknown = await this.proc.sendCommand({ type }); + const withdrawn = type === "abort" ? null + : await this.proc.sendCommand<{ steering?: unknown; followUp?: unknown }>({ type: "clear_queue" }, GET_STATE_TIMEOUT_MS); + try { + await this.proc.sendCommand({ type: "abort" }); + } catch (error) { + // The withdrawn texts exist only in this answer: return them, and let state reconciliation show the run. + if (!withdrawn) throw error; + console.warn(`[omp-web] abort after clear_queue failed for ${this._sessionId}: ${error instanceof Error ? error.message : String(error)}`); + } + const entries = (texts: unknown) => (Array.isArray(texts) ? texts : []).filter((text) => typeof text === "string").map((text) => ({ text })); + const response = withdrawn && { steering: entries(withdrawn.steering), followUp: entries(withdrawn.followUp) }; // If the prompt was aborted before the agent loop started, no // agent_end will arrive to clear the flag; the streaming flag still // tracks a live turn that ends with its own agent_end. diff --git a/tests/fixtures/multi-server-omp.mjs b/tests/fixtures/multi-server-omp.mjs index c25e9eb6..0d7f9c63 100644 --- a/tests/fixtures/multi-server-omp.mjs +++ b/tests/fixtures/multi-server-omp.mjs @@ -44,9 +44,9 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => { case "get_state": return reply({ sessionId, sessionFile, cwd: process.cwd(), supportsClientMessageIds: true, isStreaming: streaming, isSettled: !streaming, isCompacting: false, queuedMessages: [], messages }); case "get_subagents": return reply({ subagents: [] }); case "get_btw_history": return reply({ records: [] }); + case "clear_queue": return reply({ steering: [], followUp: [] }); case "abort": - case "abort_and_restore_queue": - reply({ messages: [] }); + reply(); return end(); case "prompt": { reply({ agentInvoked: true }); From 2e419e10d991a331a118ac56c01462572c559e58 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 18:22:47 +0000 Subject: [PATCH 007/129] feat(hosts): register server host tools in pi and route their calls The companion extension registered a fixed tool list, so browser tools other than open_file and the agent tools (new_session, send_to_session, list_sessions) never reached pi, and the Agent tools setting could not hide anything. The daemon now sends its set_host_tools union as /tau_host_tools, which the extension registers and activates, turning off tools no longer listed. The daemon also routes the extension's __tau_host_tool__ dialog as a host_tool_call, so one member executes each call instead of every linked server, and returns the result as the dialog's answer. Companion-extension commands are kept out of run tracking: pi's reply never says that no run started. --- lib/hosts/daemon-channels.test.mjs | 21 ++++-- lib/hosts/daemon-channels.ts | 36 +++++++-- lib/hosts/link-integration.test.mjs | 19 +++-- lib/pi/tau-extension.ts | 110 +++++++--------------------- 4 files changed, 84 insertions(+), 102 deletions(-) diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index d7546a81..a5c22374 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -20,7 +20,9 @@ const ev = (child, event) => child.emit(event); const res = (id, data, extra = {}) => ({ type: "response", id, success: true, ...(data === undefined ? {} : { data }), ...extra }); /** The commands links sent, as the child received them (ids remapped by the daemon). */ /** The daemon's own startup `get_state` is the first line it writes; anything else a link sent. */ -const own = child => child.writes.filter(frame => !REPLIES.has(frame.type) && frame !== child.writes[0] && !DAEMON_OPS.has(frame.type) && frame.message !== RESUME_PROMPT); +/** A daemon-owned companion-extension command (`/tau_host_tools`, the port of set_host_tools). */ +const extensionCommand = frame => frame.type === "prompt" && typeof frame.message === "string" && frame.message.startsWith("/tau_"); +const own = child => child.writes.filter(frame => !REPLIES.has(frame.type) && frame !== child.writes[0] && !DAEMON_OPS.has(frame.type) && !extensionCommand(frame) && frame.message !== RESUME_PROMPT); const stdoutFrames = (h, linkId) => h.output.filter(item => item.body.type === "stdout" && (linkId === undefined || item.id === linkId)).map(item => JSON.parse(item.body.line)); /** `state`: fields the child's startup `get_state` answer overrides. */ function harness(launchAdvisor = false, state = {}) { @@ -35,7 +37,7 @@ function harness(launchAdvisor = false, state = {}) { write(line, callback) { const frame = JSON.parse(line); writes.push(frame); callback?.(null); if (writes.length === 1 && frame.type === "get_state") setTimeout(() => hooks.startup(child, request, frame), 0); - else if (!REPLIES.has(frame.type) && !hooks.holdDaemonReplies && (DAEMON_OPS.has(frame.type) || frame.message === RESUME_PROMPT)) { + else if (!REPLIES.has(frame.type) && !hooks.holdDaemonReplies && (DAEMON_OPS.has(frame.type) || extensionCommand(frame) || frame.message === RESUME_PROMPT)) { queueMicrotask(() => listeners.line?.(JSON.stringify(res(frame.id, {})))); } }, @@ -235,14 +237,19 @@ test("only the chosen callback executor receives the request but both members re const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); await h.table.open(h.b, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); h.table.release(h.b, a.ch); for (const link of [h.a, h.b]) h.table.setTools(link, a.ch, [{ name: "open_url" }], []); - await new Promise(resolve => setImmediate(resolve)); // omp answers set_host_tools before it can call the tool + await new Promise(resolve => setImmediate(resolve)); // pi registers the tools before it can call one + assert.deepEqual(h.children[0].writes.filter(extensionCommand).map(frame => frame.message), [`/tau_host_tools ${JSON.stringify([{ name: "open_url" }])}`], + "the union goes to the companion extension once"); h.table.stdin(h.b, a.ch, cmd("p", "prompt", { message: "open" })); - h.children[0].emit({ type: "host_tool_call", id: 7, toolName: "open_url", arguments: {} }); + // The extension asks for the tool as an input dialog; the daemon routes it as the host_tool_call it stands for. + h.children[0].emit({ type: "extension_ui_request", id: "7", method: "input", title: "__tau_host_tool__", placeholder: JSON.stringify({ toolCallId: "t", toolName: "open_url", args: { url: "u" } }) }); // The non-prompting member sees only the daemon's peer-admission marker, never the callback. assert.deepEqual(h.output.map(item => [item.id, JSON.parse(item.body.line).type]), [["l1", "peer_message_command"], ["l2", "host_tool_call"]]); - h.table.stdin(h.a, a.ch, JSON.stringify({ type: "host_tool_result", id: 7, result: "no" })); - h.table.stdin(h.b, a.ch, JSON.stringify({ type: "host_tool_result", id: 7, result: "yes" })); - assert.deepEqual(h.children[0].writes.filter(frame => frame.type === "host_tool_result").map(({ id, result }) => ({ id, result })), [{ id: 7, result: "yes" }]); + assert.deepEqual(JSON.parse(h.output[1].body.line), { type: "host_tool_call", id: "7", toolName: "open_url", arguments: { url: "u" } }); + h.table.stdin(h.a, a.ch, JSON.stringify({ type: "host_tool_result", id: "7", result: "no" })); + h.table.stdin(h.b, a.ch, JSON.stringify({ type: "host_tool_result", id: "7", result: { content: [{ type: "text", text: "yes" }] }, isError: false })); + assert.deepEqual(h.children[0].writes.filter(frame => frame.type === "extension_ui_response"), + [{ type: "extension_ui_response", id: "7", value: JSON.stringify({ content: [{ type: "text", text: "yes" }], isError: false }) }]); ev(h.children[0], { type: "tool_execution_end", toolCallId: 7, toolName: "open_url", result: "yes" }); assert.deepEqual(h.output.filter(item => JSON.parse(item.body.line).type === "tool_execution_end").map(item => item.id), ["l1", "l2"]); await h.table.stop(); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 0a15b8dc..54ffecd1 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -44,6 +44,22 @@ type ChannelDeps = { sessionsChanged?(): void; channelsChanged?(ch: string): void; }; +/** pi's companion extension asks for a host tool as an `input` dialog titled `__tau_host_tool__` (lib/pi/tau-extension.ts): + * the daemon routes it as the `host_tool_call` it stands for, so one member executes it. */ +function bridgedToolCall(frame: WireFrame): WireFrame | null { + if (frame.type !== "extension_ui_request" || frame.method !== "input" || frame.title !== "__tau_host_tool__" || typeof frame.id !== "string" || typeof frame.placeholder !== "string") return null; + try { + const payload: unknown = JSON.parse(frame.placeholder); + return isRecord(payload) && typeof payload.toolName === "string" ? { type: "host_tool_call", id: frame.id, toolName: payload.toolName, arguments: payload.args ?? {} } : null; + } catch { + return null; + } +} +/** The extension's answer to a bridged call: the tool result as the dialog's value. */ +function bridgedToolResult(frame: WireFrame): WireFrame { + const result = isRecord(frame.result) ? frame.result : { content: [{ type: "text", text: String(frame.result ?? "") }] }; + return { type: "extension_ui_response", id: frame.id, value: JSON.stringify({ ...result, ...(frame.isError !== undefined ? { isError: Boolean(frame.isError) } : {}) }) }; +} const invalid = (message = "Invalid channel request") => new HostOpError(400, "invalid_request", message); /** A process start's launch, from what its opener asked: the wire never names the credentials server (it is the opening * link's own, and only when the hub asks), and a configuration version passes only in its one valid form. */ @@ -254,7 +270,12 @@ export class ChannelTable { if (preparingLinkId) channel.lifecycle.setPreparing(preparingLinkId, true); channel.shared = new SharedRequests({ members: () => [...channel.members.keys()], isUp: id => channel.members.get(id)?.link.isUp() ?? false, deliver: (id, lines) => { const member = channel.members.get(id); if (member) for (const line of lines) this.deliver(channel, member, { type: "stdout", ch, line }); }, - write: (op, args, onReply) => { void this.command(channel, op, args, onReply).catch(error => this.deps.log(`channel ${ch}: ${String(error)}`)); } }); + write: (op, args, onReply) => { + // pi has neither command: the companion extension registers the tools it is sent; host URI schemes have no pi counterpart. + if (op === "set_host_uri_schemes") return; + const [command, commandArgs] = op === "set_host_tools" ? ["prompt", { message: `/tau_host_tools ${JSON.stringify(args.tools)}` }] : [op, args]; + void this.command(channel, command, commandArgs, onReply).catch(error => this.deps.log(`channel ${ch}: ${String(error)}`)); + } }); spawned.transport.onLine(line => this.stdout(channel, line)); // The last 500 bytes omp writes before startup settles, for the daemon's own log if it exits meanwhile; never sent on. let startupStderr: Buffer | null = Buffer.alloc(0); @@ -304,7 +325,9 @@ export class ChannelTable { const command = { ...args, type: op, id }; const { promise, resolve, reject } = Promise.withResolvers(); const timer = setTimeout(() => { channel.internal.delete(id); channel.lifecycle?.forgetCommand(id); reject(new Error(`pi ${op} timed out`)); }, timeoutMs); timer.unref?.(); - channel.internal.set(id, { resolve, reject, timer, onReply }); channel.lifecycle?.noteStdin(command); + channel.internal.set(id, { resolve, reject, timer, onReply }); + // A companion-extension command (`/tau_*`) starts no run, and pi's reply never says so (no agentInvoked). + if (!(op === "prompt" && typeof args.message === "string" && args.message.startsWith("/tau_"))) channel.lifecycle?.noteStdin(command); channel.transport.write(JSON.stringify(command) + "\n", error => { if (error) { const pending = channel.internal.get(id); if (!pending) return; clearTimeout(pending.timer); channel.internal.delete(id); channel.lifecycle?.forgetCommand(id, true); reject(error); } }); @@ -325,12 +348,14 @@ export class ChannelTable { this.deps.runningChanged?.(); } - private stdout(channel: Channel, line: string): void { - const frame = parseWire(line); - if (!frame) { + private stdout(channel: Channel, rawLine: string): void { + const parsed = parseWire(rawLine); + if (!parsed) { for (const member of channel.members.values()) member.link.queue({ type: "resync", ch: channel.ch }, channel.ch); return; } + const call = bridgedToolCall(parsed); + const frame = call ?? parsed, line = call ? JSON.stringify(call) : rawLine; if (frame.type === "session") this.noteIdentity(channel, frame); if (channel.shared?.isCompleted(frame)) return; channel.lifecycle?.noteStdout(frame); @@ -448,6 +473,7 @@ export class ChannelTable { let out = frame, id: string | null = null; if (isReply) { if (!channel.shared?.answer(link.id, frame)) return; + if (frame.type === "host_tool_result") out = bridgedToolResult(frame); } else if (op !== null) { if (idOf(frame.id) === null) throw invalid("Invalid channel command id"); id = String(++this.commandId); diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index acf18046..05d93468 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -101,12 +101,15 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l update("answered " + command.value.results[0].selectedOptions[0]); return end(); } - if (command.type === "host_tool_result") { - update("tool " + command.result.content[0].text); + // A host tool's answer, as the companion extension's input dialog receives it. + if (command.type === "extension_ui_response") { + update("tool " + JSON.parse(command.value).content[0].text); return end(); } if (command.type === "get_state") return reply({ sessionId, sessionFile, isStreaming: streaming, isCompacting: false }); if (command.type !== "prompt") return reply({}); + // A companion-extension command (the daemon's /tau_host_tools): handled at once, no run. + if (command.message.startsWith("/tau_")) return reply(); reply({ agentInvoked: true }); prompt = command.message; streaming = true; @@ -114,7 +117,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l if (command.message === "ask") return out({ type: "ui_request", id: 1, method: "askDialog", args: [[{ id: "q", question: "Pick", options: [{ label: "A" }] }]] }); if (command.message === "tool") { // A host tool call, then one more frame once the test creates the go file. - out({ type: "host_tool_call", id: "h1", toolCallId: "c1", toolName: "browser_open", arguments: { url: "https://a.test" } }); + out({ type: "extension_ui_request", id: "h1", method: "input", title: "__tau_host_tool__", placeholder: JSON.stringify({ toolCallId: "c1", toolName: "browser_open", args: { url: "https://a.test" } }) }); const timer = setInterval(() => { if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; clearInterval(timer); @@ -128,7 +131,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; clearInterval(timer); out({ type: "ui_request", id: 2, method: "askDialog", args: [[{ id: "q", question: "Late", options: [{ label: "B" }] }]] }); - out({ type: "host_tool_call", id: "h2", toolCallId: "c2", toolName: "send_to_session", arguments: { sessionId: ${JSON.stringify("11111111-2222-4333-8444-000000000001")}, message: "hi" } }); + out({ type: "extension_ui_request", id: "h2", method: "input", title: "__tau_host_tool__", placeholder: JSON.stringify({ toolCallId: "c2", toolName: "send_to_session", args: { sessionId: ${JSON.stringify("11111111-2222-4333-8444-000000000001")}, message: "hi" } }) }); }, 25); return; } @@ -521,7 +524,7 @@ test("a stopping web server sends nothing more and takes nothing in: a closing t await waitFor(() => ompSaid("while stopping") && seen.refusedUpgrades > refusedBefore, "output while stopping, and a redial refused"); }, }); - assert.equal(ompLog().some((entry) => entry.command?.type === "host_tool_result"), false, "no rejection reached omp"); + assert.equal(ompLog().some((entry) => entry.command?.type === "extension_ui_response"), false, "no rejection reached pi"); assert.equal(before.some((event) => event.type === "message_update"), false, "the stopping server applied none of it"); await waitFor(() => getRpcSession(TOOL_ID), "the adoption"); @@ -536,11 +539,11 @@ test("a stopping web server sends nothing more and takes nothing in: a closing t await waitFor(() => events.some((event) => event.type === "agent_end"), "the run to end"); assert.ok(events.some((event) => event.type === "message_update" && /outcome is unknown/.test(event.message.content[0].text))); assert.equal(stopping().length, 1, "delivered once"); - const results = ompLog().filter((entry) => entry.command?.type === "host_tool_result").map((entry) => entry.command); + const results = ompLog().filter((entry) => entry.command?.type === "extension_ui_response").map((entry) => ({ id: entry.command.id, ...JSON.parse(entry.command.value) })); assert.equal(results.length, 1); assert.equal(results[0].id, "h1"); assert.equal(results[0].isError, true); - assert.match(results[0].result.content[0].text, /outcome is unknown/); + assert.match(results[0].content[0].text, /outcome is unknown/); }); test("a request omp opens while the web server stops reaches the next server once: one dialog, one agent tool result", async (t) => { @@ -577,7 +580,7 @@ test("a request omp opens while the web server stops reaches the next server onc await waitFor(() => getRpcSession(LATE_ID), "the adoption"); const events = adopted.get(getRpcSession(LATE_ID)); - const results = () => ompLog().filter((entry) => entry.command?.type === "host_tool_result" && entry.command.id === "h2"); + const results = () => ompLog().filter((entry) => entry.command?.type === "extension_ui_response" && entry.command.id === "h2"); await waitFor(() => results().length > 0, "the agent tool result"); // Room for a second delivery to show up. await sleep(300); diff --git a/lib/pi/tau-extension.ts b/lib/pi/tau-extension.ts index f83c73e0..3b5eff04 100644 --- a/lib/pi/tau-extension.ts +++ b/lib/pi/tau-extension.ts @@ -2,7 +2,7 @@ * Companion pi extension for tau (loaded via `pi --mode rpc --extension ...`). * * Bridges tau-specific capabilities over pi's standard RPC + Extension UI protocol: - * 1. Host tools (`open_file`, `github_*`) via `ctx.ui.input("__tau_host_tool__", ...)` + * 1. Host tools the server registers (`/tau_host_tools`), called via `ctx.ui.input("__tau_host_tool__", ...)` * 2. Interactive `ask` tool via `ctx.ui.input("__tau_ask__", ...)` * 3. `clientMessageId` / `origin` tracking via `/tau_meta` + `input` / `message_start` * 4. `/btw` side-question bridge (`/btw`, `/tau_btw`) @@ -46,6 +46,8 @@ interface PiExtensionAPI { }, ): void; on(event: string, handler: (event: Record, ctx: PiContext) => unknown): void; + getActiveTools(): string[]; + setActiveTools(names: string[]): void; appendEntry(customType: string, data?: unknown): void; events: { on(event: string, handler: (data: unknown) => void): () => void; @@ -114,88 +116,32 @@ function registerHostTool( } export default function tauExtension(pi: PiExtensionAPI): void { - // 1. Host tools: open_file + GitHub watch/action tools - registerHostTool( - pi, - "open_file", - "Open File", - "Open a file in the tau web UI file viewer (supports local:// URIs and workspace paths).", - { - type: "object", - properties: { - path: { type: "string", description: "File path or local:// URI to open in the viewer." }, - line: { type: "number", description: "Optional 1-based line number to jump to." }, - endLine: { type: "number", description: "Optional 1-based end line number to highlight." }, - }, - required: ["path"], - }, - ); - - const githubTarget = { - type: "string", - description: "OWNER/REPO#N, or a https://github.com/OWNER/REPO/pull/N, /issues/N or /actions/runs/ID URL.", - }; - - registerHostTool(pi, "watch_github", "Watch GitHub", "Watch a GitHub PR, issue, or Actions workflow run for updates.", { - type: "object", - properties: { target: githubTarget }, - required: ["target"], - }); - registerHostTool(pi, "unwatch_github", "Unwatch GitHub", "Stop watching a GitHub PR, issue, or workflow run.", { - type: "object", - properties: { target: githubTarget }, - required: ["target"], - }); - registerHostTool(pi, "github_read", "Read GitHub", "Read metadata, comments, reviews, threads, checks, files, or diff for a GitHub target.", { - type: "object", - properties: { - target: githubTarget, - include: { type: "array", items: { type: "string" }, description: "Parts to include (summary, comments, reviews, threads, checks, files, diff)." }, - ids: { type: "array", items: { type: "string" }, description: "Optional item IDs to fetch." }, - }, - required: ["target"], - }); - registerHostTool(pi, "github_comment", "GitHub Comment", "Post a comment on a GitHub PR or issue.", { - type: "object", - properties: { - target: githubTarget, - body: { type: "string", description: "Comment body in Markdown." }, - replyToId: { type: "string", description: "Optional review comment ID to reply to." }, - }, - required: ["target", "body"], - }); - registerHostTool(pi, "github_resolve_thread", "Resolve GitHub Thread", "Resolve or unresolve a PR review thread.", { - type: "object", - properties: { - target: githubTarget, - threadId: { type: "string", description: "GraphQL thread ID." }, - resolved: { type: "boolean", description: "True to resolve, false to unresolve." }, - }, - required: ["target", "threadId"], - }); - registerHostTool(pi, "github_run_list", "List GitHub Runs", "List recent GitHub Actions workflow runs.", { - type: "object", - properties: { - repo: { type: "string", description: "OWNER/REPO" }, - branch: { type: "string" }, - workflow: { type: "string" }, - status: { type: "string" }, - limit: { type: "number" }, - }, - required: ["repo"], - }); - registerHostTool(pi, "github_run_rerun", "Rerun GitHub Workflow", "Rerun a GitHub Actions workflow run.", { - type: "object", - properties: { - target: githubTarget, - failedOnly: { type: "boolean" }, + // 1. Host tools: the ones tau's server registers for this session (browser tools such as open_file, and the + // agent and GitHub tools while Settings allows them). The host daemon turns its `set_host_tools` union into + // `/tau_host_tools `; tools it no longer lists are deactivated, as pi cannot unregister one. + const hostTools = new Set(); + pi.registerCommand("tau_host_tools", { + description: "Register the host tools tau's server names for this session", + handler(args) { + let tools: unknown; + try { + tools = JSON.parse(args); + } catch { + return; + } + if (!Array.isArray(tools)) return; + const listed = new Set(); + for (const tool of tools) { + if (typeof tool !== "object" || tool === null || typeof (tool as { name?: unknown }).name !== "string") continue; + const { name, description, parameters } = tool as { name: string; description?: unknown; parameters?: unknown }; + listed.add(name); + registerHostTool(pi, name, name, typeof description === "string" ? description : "", + typeof parameters === "object" && parameters !== null ? parameters as Record : { type: "object", properties: {} }); + hostTools.add(name); + } + const active = pi.getActiveTools().filter((name) => !hostTools.has(name) || listed.has(name)); + pi.setActiveTools([...new Set([...active, ...listed])]); }, - required: ["target"], - }); - registerHostTool(pi, "github_run_cancel", "Cancel GitHub Workflow", "Cancel a running GitHub Actions workflow run.", { - type: "object", - properties: { target: githubTarget }, - required: ["target"], }); // 2. Interactive `ask` tool From 268e5d4c06aa643931fca9cbef5e1866769b6285 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 18:22:48 +0000 Subject: [PATCH 008/129] fix(plugins): list configured pi packages that are not installed pi list prints a package's path only when it is installed; the parser dropped every package without one and kept a filter mark in the source. --- lib/omp/plugins-cli.test.mjs | 11 +++++++++++ lib/omp/plugins-cli.ts | 15 ++++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/lib/omp/plugins-cli.test.mjs b/lib/omp/plugins-cli.test.mjs index e58f515c..58891178 100644 --- a/lib/omp/plugins-cli.test.mjs +++ b/lib/omp/plugins-cli.test.mjs @@ -168,3 +168,14 @@ test("an aborted signal ends a running omp", async (t) => { test("a missing pi rejects", async () => { await assert.rejects(runOmpCli(["list"], 5_000), /pi binary not found\. Install @earendil-works\/pi-coding-agent or set TAU_PI_BIN/); }); + +test("pi list: a configured package that is not installed is listed with no path, and a filter mark is not its source", async () => { + const { parsePiListOutput } = await import("./plugins-cli.ts"); + const out = "\x1b[1mUser packages:\x1b[22m\n npm:installed\n\x1b[2m /home/u/.pi/agent/npm/node_modules/installed\x1b[22m\n npm:missing\n git:github.com/a/b (filtered)\n /home/u/.pi/agent/git/b\n\n\x1b[1mProject packages:\x1b[22m\n ./local\n"; + assert.deepEqual(parsePiListOutput(out), [ + { source: "npm:installed", path: "/home/u/.pi/agent/npm/node_modules/installed", scope: "global" }, + { source: "npm:missing", path: "", scope: "global" }, + { source: "git:github.com/a/b", path: "/home/u/.pi/agent/git/b", scope: "global" }, + { source: "./local", path: "", scope: "project" }, + ]); +}); diff --git a/lib/omp/plugins-cli.ts b/lib/omp/plugins-cli.ts index d5b20f54..29017b4d 100644 --- a/lib/omp/plugins-cli.ts +++ b/lib/omp/plugins-cli.ts @@ -75,18 +75,19 @@ export function parsePiListOutput(stdout: string): PiPackageEntry[] { const cleaned = stdout.replace(ANSI_RE, ""); const entries: PiPackageEntry[] = []; let scope: "global" | "project" | null = null; - let currentSource: string | null = null; + // pi prints a package's installed path on the next, deeper line only when it is installed. + let last: PiPackageEntry | null = null; for (const rawLine of cleaned.split(/\r?\n/)) { const trimmed = rawLine.trim(); if (!trimmed) continue; - if (trimmed === "User packages:") { scope = "global"; currentSource = null; continue; } - if (trimmed === "Project packages:") { scope = "project"; currentSource = null; continue; } + if (trimmed === "User packages:") { scope = "global"; last = null; continue; } + if (trimmed === "Project packages:") { scope = "project"; last = null; continue; } if (!scope) continue; - if (/^\s{4}/.test(rawLine) && currentSource) { - entries.push({ source: currentSource, path: trimmed, scope }); - currentSource = null; + if (/^\s{4}/.test(rawLine)) { + if (last && !last.path) last.path = trimmed; } else if (/^\s{2}/.test(rawLine)) { - currentSource = trimmed; + last = { source: trimmed.replace(/ \(filtered\)$/, ""), path: "", scope }; + entries.push(last); } } return entries; From 760fc33c3de00d2b1319a97bd344abacd05189a8 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 18:22:48 +0000 Subject: [PATCH 009/129] ci: build, test and release without the omp runner The runner and its fork pin are gone: workflows install the pinned pi (@earendil-works/pi-coding-agent 0.85.1) instead, smoke tests and preflight use the pi on PATH, release binaries ship no runner and the release attaches only the binaries. --- .github/workflows/omp-runner.yml | 97 ------------------------------- .github/workflows/prerelease.yml | 23 ++------ .github/workflows/publish.yml | 43 +++----------- .github/workflows/verify-pr.yml | 26 ++++----- scripts/build-binary.ts | 23 ++------ scripts/build-release-binaries.sh | 8 +-- scripts/smoke.ts | 16 ++--- 7 files changed, 41 insertions(+), 195 deletions(-) delete mode 100644 .github/workflows/omp-runner.yml diff --git a/.github/workflows/omp-runner.yml b/.github/workflows/omp-runner.yml deleted file mode 100644 index 56c17e66..00000000 --- a/.github/workflows/omp-runner.yml +++ /dev/null @@ -1,97 +0,0 @@ -name: omp runner binaries - -on: - push: - branches: - - main - pull_request: - paths: - - "runner/**" - - ".github/workflows/omp-runner.yml" - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -jobs: - test: - name: Typecheck and test - runs-on: ubuntu-latest - defaults: - run: - working-directory: runner - steps: - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - - - name: Fetch the pinned omp packages - run: bun scripts/use-omp-build.ts - - - name: Install dependencies - run: bun install --frozen-lockfile - - - name: Typecheck - run: bunx tsc -p . - - - name: Test - run: bun test - - build: - name: Build (${{ matrix.target }}) - # Bun cross-compiles every target from Linux, as omp's own release does. - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - { target: linux-x64, os: linux, cpu: x64, binary: ompweb-omp-linux-x64 } - - { target: linux-arm64, os: linux, cpu: arm64, binary: ompweb-omp-linux-arm64 } - - { target: darwin-x64, os: darwin, cpu: x64, binary: ompweb-omp-darwin-x64 } - - { target: darwin-arm64, os: darwin, cpu: arm64, binary: ompweb-omp-darwin-arm64 } - - { target: windows-x64, os: win32, cpu: x64, binary: ompweb-omp-windows-x64.exe } - defaults: - run: - working-directory: runner - - steps: - - name: Checkout repository - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - - - name: Setup Bun - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.4 - - - name: Fetch the pinned omp packages - run: bun scripts/use-omp-build.ts - - # The host's own addon package is not needed; the target's is what gets embedded. - - name: Install dependencies - run: bun install --frozen-lockfile --os=${{ matrix.os }} --cpu=${{ matrix.cpu }} - - - name: Build binary - run: bun scripts/build-binary.ts ${{ matrix.target }} - - - name: Smoke test - if: matrix.target == 'linux-x64' - run: | - set -euo pipefail - runtime_dir="$(mktemp -d)" - HOME="$runtime_dir/home" XDG_DATA_HOME="$runtime_dir/xdg" release/${{ matrix.binary }} --version - HOME="$runtime_dir/home" XDG_DATA_HOME="$runtime_dir/xdg" release/${{ matrix.binary }} --smoke-test - - - name: Upload binary - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.binary }} - path: runner/release/${{ matrix.binary }} - if-no-files-found: error diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 13b2a4ab..755e8b2e 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -26,6 +26,7 @@ jobs: runs-on: ubuntu-latest env: SHA: ${{ github.event.workflow_run.head_sha || github.sha }} + PI_VERSION: 0.85.1 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: @@ -40,24 +41,8 @@ jobs: - run: npm ci - run: npm run build - # The omp the runners compile against: the fork's newest integration build, not runner/omp-build.json's pin - # (not committed back). No such release or a runner that fails tsc against it fails the release. - - name: Find the newest omp integration build - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - sha=$(gh api repos/ompweb-dev/oh-my-pi/commits/integration-release --jq .sha) - tag=$(gh api --paginate 'repos/ompweb-dev/oh-my-pi/releases?per_page=100' --jq '.[].tag_name' \ - | grep -E "^v[0-9]+\.[0-9]+\.[0-9]+-int\.[0-9]{12}\.g${sha:0:7}\$" | head -n 1 || true) - if [ -z "$tag" ]; then - echo "::error::ompweb-dev/oh-my-pi has no integration release for integration-release ($sha)" - exit 1 - fi - echo "OMP_TAG=$tag" >> "$GITHUB_ENV" - # Without GH_TOKEN: bun install runs the omp packages' scripts. - - name: Pin the runner to it - run: npx bun runner/scripts/use-omp-build.ts "$OMP_TAG" && (cd runner && npx bun x tsc -p .) + - name: Install pi + run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" - name: Pin the binary release identity run: | now=$(date -u +%s) @@ -79,5 +64,5 @@ jobs: # A draft first, so a failed upload never leaves a published prerelease missing archives. gh release create "$tag" release/ompweb-*.tar.gz release/ompweb-*.zip \ --repo "$GITHUB_REPOSITORY" --target "$SHA" --draft --prerelease --title "$title" \ - --notes "Binaries built from $GITHUB_REPOSITORY@$SHA ($subject), omp: ompweb-dev/oh-my-pi $OMP_TAG. Not a release: no npm package, no update notice." + --notes "Binaries built from $GITHUB_REPOSITORY@$SHA ($subject), tested with pi $PI_VERSION. Not a release: no npm package, no update notice." gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --draft=false diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1fb840be..7abe7bfc 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,6 +7,7 @@ on: env: TAG: ${{ github.ref_name }} + PI_VERSION: 0.85.1 permissions: contents: write @@ -34,25 +35,9 @@ jobs: - run: npm install --global npm@^11.5.1 - run: npm ci - # The omp the runners compile against: the fork's newest integration build, not runner/omp-build.json's pin - # (not committed back). No such release or a runner that fails tsc against it fails the release. Pinned before - # the tests: they import the runner (lib/hosts/omp-socket.test.mjs), and must run against the omp that ships. - - name: Find the newest omp integration build - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - sha=$(gh api repos/ompweb-dev/oh-my-pi/commits/integration-release --jq .sha) - tag=$(gh api --paginate 'repos/ompweb-dev/oh-my-pi/releases?per_page=100' --jq '.[].tag_name' \ - | grep -E "^v[0-9]+\.[0-9]+\.[0-9]+-int\.[0-9]{12}\.g${sha:0:7}\$" | head -n 1 || true) - if [ -z "$tag" ]; then - echo "::error::ompweb-dev/oh-my-pi has no integration release for integration-release ($sha)" - exit 1 - fi - echo "OMP_TAG=$tag" >> "$GITHUB_ENV" - # Without GH_TOKEN: bun install runs the omp packages' scripts. - - name: Pin the runner to it - run: npx bun runner/scripts/use-omp-build.ts "$OMP_TAG" && (cd runner && npx bun x tsc -p .) + # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. + - name: Install pi + run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" # Match Verify PR: allow isolated fixtures, never control of the runner's service. - name: Allow isolated native fixture scopes run: | @@ -61,13 +46,10 @@ jobs: systemd-run --scope --quiet --collect --no-ask-password true - run: npm test - run: npm run build - # Builds the omp runners too, which the source smoke spawns from runner/release/. The archives leave them out: - # every install fetches its runner from this release (lib/omp/runner-fetch.ts), attached below. - name: Build the release binaries - run: sh scripts/build-release-binaries.sh --no-runner + run: sh scripts/build-release-binaries.sh - run: npm run smoke - # --omp: the draft release cannot serve the runner to the binary yet. - - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb --omp runner/release/ompweb-omp-linux-x64 + - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb - name: Create draft GitHub Release env: @@ -75,22 +57,15 @@ jobs: run: | if ! gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then node bin/generate-release-notes.js --tag "$TAG" --output release-notes.md - printf '\nomp: ompweb-dev/oh-my-pi %s\n' "$OMP_TAG" >> release-notes.md + printf '\nTested with pi %s (@earendil-works/pi-coding-agent).\n' "$PI_VERSION" >> release-notes.md gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" --notes-file release-notes.md --draft fi - # The runners, by the names and checksum listing lib/omp/runner-fetch.ts fetches (OMP_RUNNER_ASSET, - # OMP_RUNNER_CHECKSUMS), for binary and npm installs alike. - - name: Attach the binaries and the omp runners to the draft release + - name: Attach the binaries to the draft release env: GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - runners=(ompweb-omp-linux-x64 ompweb-omp-linux-arm64 ompweb-omp-darwin-x64 ompweb-omp-darwin-arm64 ompweb-omp-windows-x64.exe) - (cd runner/release && sha256sum "${runners[@]}" > ompweb-omp.sha256) - gh release upload "$TAG" release/ompweb-*.tar.gz release/ompweb-*.zip "${runners[@]/#/runner/release/}" runner/release/ompweb-omp.sha256 --repo "$GITHUB_REPOSITORY" --clobber + run: gh release upload "$TAG" release/ompweb-*.tar.gz release/ompweb-*.zip --repo "$GITHUB_REPOSITORY" --clobber - # Before npm: an npm install fetches its runner from this release, which a draft does not serve. - name: Publish GitHub Release env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 80238f82..0ce87435 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -18,6 +18,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +env: + PI_VERSION: 0.85.1 + permissions: contents: read pull-requests: read @@ -46,12 +49,12 @@ jobs: node-version-file: .nvmrc cache: npm - # The runner's own deps too: lib/hosts/omp-socket.test.mjs checks the host against runner/src/channel.ts. - name: Install dependencies - run: | - npm ci - npx bun runner/scripts/use-omp-build.ts - npx bun install --cwd runner --frozen-lockfile + run: npm ci + + # The pi tau drives (`pi --mode rpc`), on PATH for the tests' live sessions, the smoke tests and preflight. + - name: Install pi + run: npm install --global "@earendil-works/pi-coding-agent@$PI_VERSION" - name: TypeScript typecheck run: npm run typecheck @@ -86,9 +89,6 @@ jobs: - name: Verify production build run: npm run build - - name: Build the omp runner - run: npx bun runner/scripts/build-binary.ts - - name: Smoke test run: npm run smoke @@ -117,7 +117,7 @@ jobs: npx bun scripts/check-host-release-archive.ts "$archive" npm run smoke -- --binary "$bin" # What the host updater checks on a new release before it switches (lib/hosts/update-worker.ts): the marker - # it finds the command by, then the command itself against the bundled ompweb-omp. + # it finds the command by, then the command itself against the pi on PATH. grep -qa ompweb-preflight-scratch- "$bin" node -e 'require("node:child_process").execFileSync(process.argv[1], ["preflight"], {stdio:"inherit",timeout:120000})' "$bin" @@ -126,23 +126,21 @@ jobs: shell: bash env: OMPWEB_COMPILED_UPGRADE_E2E: "1" - run: | - export OMPWEB_UPGRADE_E2E_RUNNER="$(node -p "require('node:path').resolve('runner', 'release', 'ompweb-omp-' + (process.platform === 'win32' ? 'windows' : process.platform) + '-' + process.arch + (process.platform === 'win32' ? '.exe' : ''))")" - npx bun test --parallel --timeout 900000 lib/compiled-upgrade.integration.test.mjs + run: npx bun test --parallel --timeout 900000 lib/compiled-upgrade.integration.test.mjs - name: Packed install smoke test shell: bash run: | npm pack --ignore-scripts npm install -g --prefix "$RUNNER_TEMP/ompweb-prefix" ./ompweb-dev-tau-*.tgz - npm run smoke -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@ompweb-dev/tau" + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@ompweb-dev/tau" # Bun's postinstall does not run here: the launcher must fall back to @oven/bun-- (spec R1). - name: Packed install smoke test (install scripts disabled) shell: bash run: | npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts" ./ompweb-dev-tau-*.tgz - npm run smoke -- --omp "$(ls runner/release/ompweb-omp-*)" --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@ompweb-dev/tau" + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@ompweb-dev/tau" - name: Parse Windows PowerShell scripts (Windows only) if: runner.os == 'Windows' diff --git a/scripts/build-binary.ts b/scripts/build-binary.ts index 8a92a072..5d0f742c 100644 --- a/scripts/build-binary.ts +++ b/scripts/build-binary.ts @@ -1,8 +1,7 @@ -// `npm run build:binary [-- --target bun--]` (after the client build and the runner build, -// `bun runner/scripts/build-binary.ts -`): compiles server/binary.ts into release/ompweb--/ompweb -// (ompweb.exe for Windows) next to the files it serves, the omp runner it spawns (ompweb-omp; not with --no-runner, -// where ompweb fetches it from its release, lib/omp/runner-fetch.ts) and the licenses of what it redistributes, then -// archives that directory as release/ompweb--.tar.gz (.zip for Windows). Default target: this machine. +// `npm run build:binary [-- --target bun--]` (after the client build): compiles server/binary.ts into +// release/ompweb--/ompweb (ompweb.exe for Windows) next to the files it serves and the licenses of what it +// redistributes, then archives that directory as release/ompweb--.tar.gz (.zip for Windows). Default +// target: this machine. import { cpSync, existsSync, readFileSync, writeFileSync, rmSync } from "node:fs"; import path from "node:path"; import { parseArgs } from "node:util"; @@ -10,7 +9,7 @@ import { bundledPackageDirs, writeLicenses } from "./licenses"; import packageJson from "../package.json"; const root = path.join(import.meta.dir, ".."); -const { values } = parseArgs({ args: Bun.argv.slice(2), options: { target: { type: "string" }, "no-runner": { type: "boolean" } } }); +const { values } = parseArgs({ args: Bun.argv.slice(2), options: { target: { type: "string" } } }); const target = (values.target ?? `bun-${process.platform === "win32" ? "windows" : process.platform}-${process.arch}`) as Bun.Build.CompileTarget; const windows = target.startsWith("bun-windows-"); // A -baseline target (x64 without AVX2, what releases ship) keeps the plain name, which the README and the update notice use. @@ -46,8 +45,7 @@ for (const log of result.logs) console.log(log); if (!result.success) process.exit(1); // The static root (server/binary.ts): the client, the public files, the KaTeX CSS and fonts (where the server -// resolves the katex package), and the licenses of what ships. Beside the binary, unless --no-runner: the omp runner -// it spawns (`ompweb-omp`, lib/omp/omp-cli.ts), built first by runner/scripts/build-binary.ts. +// resolves the katex package), and the licenses of what ships. pi is not shipped: the binary spawns the one on PATH. const copy = (from: string, to: string) => cpSync(from, path.join(out, to), { recursive: true }); for (const file of ["dist", "public", "LICENSE"]) copy(path.join(root, file), file); const releaseTag = process.env.OMP_WEB_RELEASE_TAG || (process.env.GITHUB_REF_TYPE === "tag" ? process.env.GITHUB_REF_NAME : undefined); @@ -55,15 +53,6 @@ if (releaseTag) { if (!/^(?:v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?|\d{8}T\d{6}Z-[a-f0-9]{7,40})$/.test(releaseTag)) throw new Error("Invalid binary release tag"); writeFileSync(path.join(out, "build-info.json"), JSON.stringify({ version: packageJson.version, releaseTag }) + "\n"); } -if (!values["no-runner"]) { - const runnerTarget = name.slice("ompweb-".length); - const runner = path.join(root, "runner", "release", `ompweb-omp-${runnerTarget}${windows ? ".exe" : ""}`); - if (!existsSync(runner)) { - console.error(`No ${path.relative(root, runner)}: run \`bun runner/scripts/build-binary.ts ${runnerTarget}\` first.`); - process.exit(1); - } - copy(runner, windows ? "ompweb-omp.exe" : "ompweb-omp"); -} for (const file of new Bun.Glob("app/fonts/*-{OFL.txt,LICENSE.*}").scanSync(root)) copy(path.join(root, file), file); const katex = path.dirname(Bun.resolveSync("katex/package.json", root)); for (const file of ["package.json", "LICENSE", "dist/katex.min.css", "dist/fonts"]) copy(path.join(katex, file), `node_modules/katex/${file}`); diff --git a/scripts/build-release-binaries.sh b/scripts/build-release-binaries.sh index ac5794cb..784162b9 100755 --- a/scripts/build-release-binaries.sh +++ b/scripts/build-release-binaries.sh @@ -1,15 +1,11 @@ #!/bin/sh # The five binaries every release and prerelease ships (after `npm run build`), into release/: -# release/ompweb--.tar.gz, .zip for Windows, and the five omp runners, runner/release/ompweb-omp--. -# A prerelease archive holds its runner as ompweb-omp beside ompweb; with --no-runner (releases) it does not, and -# ompweb fetches it from the release instead, which attaches each runner (lib/omp/runner-fetch.ts). Bun -# cross-compiles all of them from one machine. +# release/ompweb--.tar.gz, .zip for Windows. They spawn the pi on PATH (`pi --mode rpc`), which they do +# not ship. Bun cross-compiles all of them from one machine. # The x64 targets name -baseline (no AVX2 needed): in Bun 1.4.4 that is the default x64 runtime too (the # same bytes), and naming it keeps a later Bun from shipping a -modern one. They keep the plain # ompweb--x64 names. set -eu -# The pinned omp packages, then every platform's native addon package, which the runner embeds per target. -(cd runner && npx bun scripts/use-omp-build.ts && npx bun install --frozen-lockfile --os='*' --cpu='*' && npx bun scripts/build-binary.ts linux-x64 linux-arm64 darwin-x64 darwin-arm64 windows-x64) for target in bun-linux-x64-baseline bun-linux-arm64 bun-darwin-x64-baseline bun-darwin-arm64 bun-windows-x64-baseline; do npx bun scripts/build-binary.ts --target "$target" "$@" done diff --git a/scripts/smoke.ts b/scripts/smoke.ts index 5e5f6fd9..e76b107a 100644 --- a/scripts/smoke.ts +++ b/scripts/smoke.ts @@ -1,10 +1,10 @@ // `npm run smoke [-- --package | --binary ]`: starts ompweb (`node /bin/omp-web.js`, or the compiled // binary) on a free port with a throwaway HOME, waits for its automatic local host, and checks the shipped -// bundle, the SPA, a hashed asset, the API, a session listed through the daemon, a live session started through the -// omp runner (no model call) and the SSE stream, then stops both. -// : the repo root (after `npm run build` and `bun runner/scripts/build-binary.ts`) or a packed install; -// : release/ompweb--/ompweb, whose directory holds the static files and the runner (ompweb-omp) unless -// built --no-runner. Prints one `ok ` / `FAIL : ` line per step. +// bundle, the SPA, a hashed asset, the API, a session listed through the daemon, a live session started through +// `pi --mode rpc` (no model call) and the SSE stream, then stops both. pi comes from PATH unless --omp names one. +// : the repo root (after `npm run build`) or a packed install; +// : release/ompweb--/ompweb, whose directory holds the static files. +// Prints one `ok ` / `FAIL : ` line per step. import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; @@ -223,11 +223,11 @@ try { }); } - // No model call: the spawn, the runner's hello and the get_state that follows it. - await step("a live session starts through the omp runner", async () => { + // No model call: the spawn and pi's answer to get_state. + await step("a live session starts through pi", async () => { const response = await fetch(`${base}/api/agent/${SESSION_ID}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ type: "get_state" }) }); const text = await response.text(); - assert(response.status === 200 && text.includes(SESSION_ID), `get_state: status ${response.status} ${text} (no runner? build it with \`bun runner/scripts/build-binary.ts\`)`); + assert(response.status === 200 && text.includes(SESSION_ID), `get_state: status ${response.status} ${text} (is pi on PATH?)`); const state = await (await fetch(`${base}/api/agent/${SESSION_ID}`)).json() as { running?: boolean }; assert(state.running === true, `GET /api/agent: ${JSON.stringify(state)}`); }); From e166bc9a9bcc3abacd58fc4c2653c60c1b39dc7a Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 19:08:38 +0000 Subject: [PATCH 010/129] fix(rpc): split pi's stdout at LF only readline also ends a line at U+2028 and U+2029, which are valid inside JSON strings, so model text containing one broke its frame in two and forced a resync. pi's framing is strict JSONL: split at LF, strip a trailing CR, and decode UTF-8 across chunk boundaries. --- lib/omp/rpc-process-runtime.test.mjs | 16 ++++++++++++++++ lib/omp/rpc-transport.ts | 21 +++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 11330840..5af44e82 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -131,6 +131,22 @@ test("agent_settled reaches listeners as session_settled; get_state gains the qu await proc.dispose(0); }); +test("stdout splits frames at LF only: U+2028 inside a string and a character split across chunks stay one frame", async () => { + const transport = makeTransport(); + const proc = startProcess(transport); + await proc.waitReady(); + const notices = []; + proc.onFrame((frame) => { if (frame.type === "notice") notices.push(frame.message); }); + const bytes = Buffer.from(`${JSON.stringify({ type: "notice", message: "a\u2028b\u2029c é" })}\r\n`, "utf8"); + const cut = bytes.indexOf(Buffer.from("é", "utf8")) + 1; // inside the two-byte é + transport.child.stdout.write(bytes.subarray(0, cut)); + await tick(); + transport.child.stdout.write(bytes.subarray(cut)); + await until(() => notices.length > 0); + assert.deepEqual(notices, ["a\u2028b\u2029c é"]); + await proc.dispose(0); +}); + test("a failed response rejects with RpcCommandError", async () => { const transport = makeTransport(); transport.onLine = (frame) => frame.id && transport.send({ id: frame.id, type: "response", command: frame.type, success: false, error: "busy" }); diff --git a/lib/omp/rpc-transport.ts b/lib/omp/rpc-transport.ts index badb2202..f2ad49f5 100644 --- a/lib/omp/rpc-transport.ts +++ b/lib/omp/rpc-transport.ts @@ -1,5 +1,5 @@ import { type ChildProcessWithoutNullStreams, spawn } from "child_process"; -import { createInterface } from "readline"; +import { StringDecoder } from "string_decoder"; import { wrapWindowsScript } from "./omp-cli"; /** @@ -84,9 +84,26 @@ export function spawnLocalRpcTransport(options: { for (const listener of stderrListeners) listener(chunk); }; - createInterface({ input: child.stdout }).on("line", (line) => { + const emitLine = (line: string) => { if (lineListeners.length === 0) pendingLines.push(line); for (const listener of lineListeners) listener(line); + }; + // pi frames end at LF only: readline also splits on U+2028/U+2029, which are valid inside JSON strings. + const decoder = new StringDecoder("utf8"); + let partial = ""; + const split = (text: string) => { + partial += text; + for (let end = partial.indexOf("\n"); end !== -1; end = partial.indexOf("\n")) { + const line = partial.slice(0, end); + partial = partial.slice(end + 1); + emitLine(line.endsWith("\r") ? line.slice(0, -1) : line); + } + }; + child.stdout.on("data", (chunk: Buffer) => split(decoder.write(chunk))); + child.stdout.on("end", () => { + split(decoder.end()); + if (partial) emitLine(partial); + partial = ""; }); child.stderr.on("data", (chunk: Buffer) => emitStderr(chunk.toString("utf8"))); child.on("exit", emitExit); From a0879d8ba0154e16c0f649ff801beaf94b23ba9e Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 19:08:38 +0000 Subject: [PATCH 011/129] fix(hosts): a prompt pi handled without a run releases its guard pi 0.99+ answers a prompt that an extension command or input handler consumed with disposition "handled" and starts no run; the daemon kept waiting for that run's agent_start, which held off the idle stop. --- lib/hosts/channel-lifecycle.test.mjs | 4 ++-- lib/hosts/channel-lifecycle.ts | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/hosts/channel-lifecycle.test.mjs b/lib/hosts/channel-lifecycle.test.mjs index 980a6872..da1d6198 100644 --- a/lib/hosts/channel-lifecycle.test.mjs +++ b/lib/hosts/channel-lifecycle.test.mjs @@ -66,8 +66,8 @@ test("an accepted prompt stays protected between its ACK and authoritative start l.dispose(); }); -test("failed and non-invoking prompt replies release the submitted-message guard", () => { - for (const reply of [{ success: false, error: "rejected" }, { success: true, data: { agentInvoked: false } }]) { +test("failed, non-invoking and handled prompt replies release the submitted-message guard", () => { + for (const reply of [{ success: false, error: "rejected" }, { success: true, data: { agentInvoked: false } }, { success: true, data: { disposition: "handled" } }]) { const h = harness(), l = h.lifecycle; l.setStartup(false); l.setInterest("a", true); l.noteStdin({ type: "prompt", id: "slash", message: "/local" }); diff --git a/lib/hosts/channel-lifecycle.ts b/lib/hosts/channel-lifecycle.ts index 47024bbb..cfc18023 100644 --- a/lib/hosts/channel-lifecycle.ts +++ b/lib/hosts/channel-lifecycle.ts @@ -132,7 +132,8 @@ export class ChannelLifecycle { const id = frame.type === "response" ? idOf(frame.id) : null; if (id !== null) { this.commands.delete(id); - if (frame.success === false || (isRecord(frame.data) && frame.data.agentInvoked === false)) { + // pi (0.99+) reports `disposition: "handled"` for a prompt an extension command or input handler consumed: no run. + if (frame.success === false || (isRecord(frame.data) && (frame.data.agentInvoked === false || frame.data.disposition === "handled"))) { this.awaitingStart.delete(id); this.awaitingQueue.delete(id); } else if (this.awaitingQueue.has(id) && (this.queuePresent || (isRecord(frame.data) && frame.data.queued === true))) { this.awaitingQueue.set(id, true); From 144a1e6228d850f57d0faa8c97b5e57c006bad26 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 19:08:38 +0000 Subject: [PATCH 012/129] ci: test and release against pi 1.5.2 --- .github/workflows/prerelease.yml | 2 +- .github/workflows/publish.yml | 2 +- .github/workflows/verify-pr.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 755e8b2e..b5158c36 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -26,7 +26,7 @@ jobs: runs-on: ubuntu-latest env: SHA: ${{ github.event.workflow_run.head_sha || github.sha }} - PI_VERSION: 0.85.1 + PI_VERSION: 1.5.2 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7abe7bfc..a1655743 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -7,7 +7,7 @@ on: env: TAG: ${{ github.ref_name }} - PI_VERSION: 0.85.1 + PI_VERSION: 1.5.2 permissions: contents: write diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index 0ce87435..d0647c10 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -19,7 +19,7 @@ concurrency: cancel-in-progress: true env: - PI_VERSION: 0.85.1 + PI_VERSION: 1.5.2 permissions: contents: read From d085a72ba9b5fd58a1aa91f076f97bbc45fb5b71 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 19:34:14 +0000 Subject: [PATCH 013/129] feat(btw): answer side questions in pi's companion extension pi has no /btw, and the extension's stand-in recorded the question without answering it. The extension now answers from the active branch's conversation with the session's model (streamSimple), streams btw_delta and btw_record frames, cancels, takes follow-ups, and keeps each record as a custom session entry, which pi leaves out of the model context; a record saved while running is interrupted on reload. The server reaches it through RpcProcess.callExtension: a /tau_btw prompt that the extension answers with a tau_reply frame naming the call's id. The daemon treats such /tau_* commands as no user message: no peer marker, no history-edit fence, and their reply ends them. --- lib/agent-command.test.mjs | 8 +- lib/hosts/daemon-channels.test.mjs | 13 ++ lib/hosts/daemon-channels.ts | 15 ++- lib/omp/rpc-process-runtime.test.mjs | 32 +++++ lib/omp/rpc-process.ts | 44 +++++++ lib/pi/tau-extension.ts | 185 ++++++++++++++++++--------- lib/rpc-manager.ts | 16 ++- 7 files changed, 247 insertions(+), 66 deletions(-) diff --git a/lib/agent-command.test.mjs b/lib/agent-command.test.mjs index 4c639222..a644e3d2 100644 --- a/lib/agent-command.test.mjs +++ b/lib/agent-command.test.mjs @@ -37,7 +37,13 @@ async function respond(message, link = daemon) { // Replies to dialogs and host calls are frames, not commands: pi answers nothing. if (command.id === undefined || /^(ui_response|extension_ui_response|host_tool_result|host_uri_result)$/.test(command.type)) return; let reply = { success: true, data: {} }; - if (command.type === "get_state") { + if (command.type === "prompt" && command.message.startsWith("/tau_btw ")) { + // The companion extension answers a side-question call with a tau_reply frame, then pi's handled prompt reply. + const { replyId } = JSON.parse(command.message.slice("/tau_btw ".length)); + const frame = { type: "tau_reply", replyId, data: { records: [] } }; + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau-btw", widgetLines: [JSON.stringify(frame)] }) }); + reply = { success: true, data: { disposition: "handled" } }; + } else if (command.type === "get_state") { reply = { success: true, data: { sessionId: SAVED_ID, sessionFile: `/remote/sessions/${SAVED_ID}.jsonl`, isStreaming: false, isCompacting: false, ...child.state }, diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index a5c22374..7d9759c6 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -255,6 +255,19 @@ test("only the chosen callback executor receives the request but both members re await h.table.stop(); }); +test("a companion-extension command is no user message: no peer marker, no edit fence, and its reply ends it", async () => { + const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); + await h.table.open(h.b, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); h.table.release(h.b, a.ch); + h.table.stdin(h.a, a.ch, cmd("x", "prompt", { message: "/tau_btw {\"action\":\"history\"}" })); + assert.equal(h.output.some(item => JSON.parse(item.body.line).type === "peer_message_command"), false); + const [sent] = h.children[0].writes.filter(frame => frame.type === "prompt"); + h.children[0].emit(res(sent.id, { disposition: "handled" }, { command: "prompt" })); + h.children[0].emit(res(sent.id, {}, { command: "prompt" })); + assert.equal(stdoutFrames(h, "l1").filter(frame => frame.id === "x").length, 1, "the owner is dropped with its reply"); + assert.throws(() => h.table.stdin(h.b, a.ch, cmd("y", "prompt", { message: "/tau_host_tools []" })), { code: "invalid_request" }); + await h.table.stop(); +}); + test("a prompt_result returns under the sending link's own id, to that link only", async () => { const h = harness(), a = await h.table.open(h.a, { sessionId: SAVED, launch }); await h.table.open(h.b, { sessionId: SAVED, launch }); h.table.release(h.a, a.ch); h.table.release(h.b, a.ch); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 54ffecd1..6f6dc45e 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -55,6 +55,8 @@ function bridgedToolCall(frame: WireFrame): WireFrame | null { return null; } } +/** A companion-extension command (`/tau_*`, sent as a prompt): pi runs no turn for it, so it is no user message. */ +const isExtensionCommand = (frame: Record) => frame.type === "prompt" && typeof frame.message === "string" && frame.message.startsWith("/tau_"); /** The extension's answer to a bridged call: the tool result as the dialog's value. */ function bridgedToolResult(frame: WireFrame): WireFrame { const result = isRecord(frame.result) ? frame.result : { content: [{ type: "text", text: String(frame.result ?? "") }] }; @@ -326,8 +328,8 @@ export class ChannelTable { const { promise, resolve, reject } = Promise.withResolvers(); const timer = setTimeout(() => { channel.internal.delete(id); channel.lifecycle?.forgetCommand(id); reject(new Error(`pi ${op} timed out`)); }, timeoutMs); timer.unref?.(); channel.internal.set(id, { resolve, reject, timer, onReply }); - // A companion-extension command (`/tau_*`) starts no run, and pi's reply never says so (no agentInvoked). - if (!(op === "prompt" && typeof args.message === "string" && args.message.startsWith("/tau_"))) channel.lifecycle?.noteStdin(command); + // A companion-extension command starts no run (older pi's reply never says so). + if (!isExtensionCommand(command)) channel.lifecycle?.noteStdin(command); channel.transport.write(JSON.stringify(command) + "\n", error => { if (error) { const pending = channel.internal.get(id); if (!pending) return; clearTimeout(pending.timer); channel.internal.delete(id); channel.lifecycle?.forgetCommand(id, true); reject(error); } }); @@ -461,15 +463,17 @@ export class ChannelTable { const member = channel.members.get(link.id)!; const isReply = ["extension_ui_response", "ui_response", "host_tool_result", "host_uri_result"].includes(frame.type); const op = isReply ? null : frame.type; + const extension = isExtensionCommand(frame); const refuse = (code: string, error: string) => { if (op !== null) this.deliver(channel, member, { type: "stdout", ch, line: JSON.stringify({ type: "response", id: frame.id, command: op, success: false, code, error }) }, true); }; if (channel.replacing) return refuse("session_restarting", "This session is restarting to apply advisor mode; retry once it is ready"); - if (op !== null && channel.editor !== undefined && channel.editor !== link.id && HISTORY_MUTATING_COMMANDS.has(op)) { + if (op !== null && !extension && channel.editor !== undefined && channel.editor !== link.id && HISTORY_MUTATING_COMMANDS.has(op)) { return refuse("session_busy", "Another web app is editing this session's history; retry once it finishes"); } if (op === "branch" || op === "new_session" || op === "switch_session") channel.sessionMovePending = false; if (op !== null && ["set_event_filter", "set_subagent_subscription", "set_host_tools", "set_host_uri_schemes"].includes(op)) throw invalid("This command is owned by the host daemon"); + if (extension && /^\/tau_host_tools\b/.test(frame.message as string)) throw invalid("This command is owned by the host daemon"); let out = frame, id: string | null = null; if (isReply) { if (!channel.shared?.answer(link.id, frame)) return; @@ -477,10 +481,11 @@ export class ChannelTable { } else if (op !== null) { if (idOf(frame.id) === null) throw invalid("Invalid channel command id"); id = String(++this.commandId); - channel.commands.set(id, { link, id: frame.id, op }); + // An extension command's reply ends it: never kept for a prompt_result like a message command. + channel.commands.set(id, { link, id: frame.id, op: extension ? "extension_command" : op }); out = { ...frame, id }; } - if (op !== null && MESSAGE_COMMANDS.has(op)) { + if (op !== null && !extension && MESSAGE_COMMANDS.has(op)) { channel.shared?.prompt(link.id); const marker = JSON.stringify({ type: PEER_MESSAGE_FRAME }); for (const [other, peer] of channel.members) if (other !== link.id) this.deliver(channel, peer, { type: "stdout", ch, line: marker }); diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 5af44e82..f862745b 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -147,6 +147,38 @@ test("stdout splits frames at LF only: U+2028 inside a string and a character sp await proc.dispose(0); }); +test("callExtension sends / and settles on its tau_reply frame, which listeners never see", async () => { + const transport = makeTransport(); + const proc = startProcess(transport); + await proc.waitReady(); + const frames = []; + proc.onFrame((frame) => frames.push(frame.type)); + const widget = (frame) => transport.send({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau-btw", widgetLines: [JSON.stringify(frame)] }); + const call = proc.callExtension("tau_btw", { action: "history" }); + await until(() => transport.commands.length > 0); + const [prompt] = transport.commands; + assert.equal(prompt.type, "prompt"); + const sent = JSON.parse(prompt.message.slice("/tau_btw ".length)); + assert.equal(sent.action, "history"); + widget({ type: "tau_reply", replyId: "another server's call", data: { records: ["wrong"] } }); + widget({ type: "btw_record", record: { id: "r" } }); + widget({ type: "tau_reply", replyId: sent.replyId, data: { records: [] } }); + transport.send({ id: prompt.id, type: "response", command: "prompt", success: true, data: { disposition: "handled" } }); + assert.deepEqual(await call, { records: [] }); + assert.deepEqual(frames, ["btw_record"], "replies are consumed; other frames pass"); + + const failing = proc.callExtension("tau_btw", { action: "ask" }); + await until(() => transport.commands.length > 1); + const second = JSON.parse(transport.commands[1].message.slice("/tau_btw ".length)); + widget({ type: "tau_reply", replyId: second.replyId, error: "No model is selected for this session" }); + await assert.rejects(failing, (error) => error instanceof RpcCommandError && error.message === "No model is selected for this session"); + + const orphan = proc.callExtension("tau_btw", { action: "history" }); + await until(() => transport.commands.length > 2); + await proc.dispose(0); + await assert.rejects(orphan, /exited/); +}); + test("a failed response rejects with RpcCommandError", async () => { const transport = makeTransport(); transport.onLine = (frame) => frame.id && transport.send({ id: frame.id, type: "response", command: frame.type, success: false, error: "busy" }); diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index 6af608d4..edab6d53 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -1,4 +1,5 @@ import type { spawn } from "child_process"; +import { randomUUID } from "crypto"; import { existsSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath } from "url"; @@ -165,6 +166,8 @@ export class RpcProcess { /** Standard pi extension dialog methods awaiting `ui_response` -> `extension_ui_response`. */ private readonly extensionDialogMethods = new Map(); private nextId = 1; + /** Companion-extension calls awaiting their `tau_reply` frame (see `callExtension`). */ + private readonly extensionReplies = new Map(); /** Whether pi has settled since its last `agent_start` (`agent_settled`); null for an adopted child whose history is unknown. */ private settled: boolean | null; /** The last `queue_update`: pi's `get_state` reports only `pendingMessageCount`. */ @@ -217,6 +220,11 @@ export class RpcProcess { entry.reject(exitError); } this.pending.clear(); + for (const [, entry] of this.extensionReplies) { + clearTimeout(entry.timer); + entry.reject(exitError); + } + this.extensionReplies.clear(); exitDeferred.resolve(); options.onExit?.({ code, signal, stderrTail: this.stderrTail }); }); @@ -364,6 +372,17 @@ export class RpcProcess { if (method === "setWidget" && req.widgetKey === "tau-btw" && Array.isArray(req.widgetLines) && typeof req.widgetLines[0] === "string") { try { const btw = JSON.parse(req.widgetLines[0]) as RpcFrame; + if (btw && btw.type === "tau_reply") { + // Answers one of this process's extension calls; another server's calls name ids it never made. + const entry = typeof btw.replyId === "string" ? this.extensionReplies.get(btw.replyId) : undefined; + if (entry) { + this.extensionReplies.delete(btw.replyId as string); + clearTimeout(entry.timer); + if (typeof btw.error === "string") entry.reject(new RpcCommandError(entry.command, btw.error)); + else entry.resolve(btw.data); + } + return null; + } if (btw && typeof btw.type === "string") return btw; } catch { // Ignore malformed widget payload. @@ -429,6 +448,31 @@ export class RpcProcess { }); } + /** + * Calls a companion-extension command (`/ `, lib/pi/tau-extension.ts). pi starts no run for it and its + * prompt reply carries no data, so the extension answers with a `tau_reply` frame naming `replyId`. + */ + callExtension(command: string, args: Record, timeoutMs = 30_000): Promise { + const replyId = randomUUID(); + const reply = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.extensionReplies.delete(replyId); + reject(new RpcCommandTimeoutError(command, timeoutMs)); + }, timeoutMs); + timer.unref?.(); + this.extensionReplies.set(replyId, { command, resolve: resolve as (data: unknown) => void, reject, timer }); + }); + // The reply may come before or after pi's own prompt reply; only a refused prompt settles the call by itself. + this.sendCommand({ type: "prompt", message: `/${command} ${JSON.stringify({ ...args, replyId })}` }, timeoutMs).catch((error: Error) => { + const entry = this.extensionReplies.get(replyId); + if (!entry) return; + clearTimeout(entry.timer); + this.extensionReplies.delete(replyId); + entry.reject(error); + }); + return reply; + } + /** Fire-and-forget frame (`extension_ui_response`, etc.). */ sendFrame(frame: { type: string; [key: string]: unknown }): void { if (this.exited) return; diff --git a/lib/pi/tau-extension.ts b/lib/pi/tau-extension.ts index 3b5eff04..a8b3d4b4 100644 --- a/lib/pi/tau-extension.ts +++ b/lib/pi/tau-extension.ts @@ -16,11 +16,24 @@ interface PiUI { setWidget(key: string, lines: string[] | undefined, options?: { placement?: "aboveEditor" | "belowEditor" }): void; } +interface SessionEntry { type?: string; customType?: string; data?: unknown; message?: { role?: string; content?: unknown } } + +/** The subset of pi's AssistantMessageEventStream the side questions read. */ +interface ModelStream extends AsyncIterable<{ type: string; delta?: string }> { + result(): Promise<{ stopReason?: string; errorMessage?: string }>; +} + interface PiContext { ui: PiUI; cwd: string; + model?: unknown; + modelRegistry?: { + streamSimple(model: unknown, context: { systemPrompt?: string; messages: unknown[] }, options?: { signal?: AbortSignal }): ModelStream; + }; sessionManager?: { - getEntries?: () => Array<{ type?: string; customType?: string; data?: unknown }>; + getEntries?: () => SessionEntry[]; + getBranch?: () => SessionEntry[]; + getLeafId?: () => string | null; }; } @@ -60,12 +73,25 @@ interface MessageMeta { origin?: string; } -interface BtwEntry { - id: string; - question: string; - status: "running" | "done" | "error" | "cancelled"; - answer?: string; - createdAt: number; +/** tau's side-question record (lib/btw.ts): the first turn, then any follow-ups. */ +type BtwStatus = "running" | "complete" | "cancelled" | "error" | "interrupted"; +interface BtwTurn { question: string; answer: string; status: BtwStatus; createdAt: number; updatedAt: number; error?: string } +interface BtwRecord extends BtwTurn { id: string; leafId: string | null; followUps?: BtwTurn[] } + +/** Conversation text a side question is asked about: user and assistant text of the active branch, newest kept. */ +const BTW_CONTEXT_CHARS = 200_000; +function conversationText(entries: SessionEntry[]): string { + const parts: string[] = []; + for (const entry of entries) { + const role = entry.type === "message" ? entry.message?.role : undefined; + if (role !== "user" && role !== "assistant") continue; + const content = entry.message?.content; + const text = typeof content === "string" ? content + : Array.isArray(content) ? content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n") : ""; + if (text.trim()) parts.push(`${role === "user" ? "User" : "Assistant"}: ${text.trim()}`); + } + // shortcut: a fixed character budget, not the model's context window; size it from ctx.model when that matters. + return parts.join("\n\n").slice(-BTW_CONTEXT_CHARS); } function parseHostToolResponse(raw: string | undefined): { @@ -204,63 +230,108 @@ export default function tauExtension(pi: PiExtensionAPI): void { ctx.ui.setStatus("tau-meta", JSON.stringify(meta)); }); - // 4. /btw side-question bridge - const btwHistory: BtwEntry[] = []; + // 4. /btw side questions: answered from the conversation so far with the session's model, never added to it. + // tau calls `/tau_btw {action, replyId, ...}` and gets a `tau_reply` frame back; answers stream as `btw_delta` + // and `btw_record` frames (all through the `tau-btw` widget, which tau's RpcProcess decodes). + const btwRecords = new Map(); + const btwRunning = new Map(); + const latestTurn = (record: BtwRecord): BtwTurn => record.followUps?.at(-1) ?? record; + const withLatest = (record: BtwRecord, patch: Partial): BtwRecord => { + const followUps = record.followUps; + if (!followUps?.length) return { ...record, ...patch }; + return { ...record, followUps: [...followUps.slice(0, -1), { ...followUps[followUps.length - 1], ...patch }] }; + }; + const emitBtw = (ctx: PiContext, frame: Record) => ctx.ui.setWidget("tau-btw", [JSON.stringify(frame)]); + + pi.on("session_start", (_event, ctx) => { + btwRecords.clear(); + for (const entry of ctx.sessionManager?.getEntries?.() ?? []) { + const record = entry.type === "custom" && entry.customType === "tau_btw" ? entry.data as BtwRecord : null; + if (record && typeof record.id === "string") btwRecords.set(record.id, record); + } + // A record saved while running belonged to a process that is gone. + for (const [id, record] of btwRecords) if (latestTurn(record).status === "running") btwRecords.set(id, withLatest(record, { status: "interrupted" })); + }); + + const finishBtw = (ctx: PiContext, id: string, patch: Partial) => { + btwRunning.delete(id); + const record = btwRecords.get(id); + if (!record) return; + const done = withLatest(record, { ...patch, updatedAt: Date.now() }); + btwRecords.set(id, done); + pi.appendEntry("tau_btw", done); + emitBtw(ctx, { type: "btw_record", record: done }); + }; + + async function answerBtw(ctx: PiContext, id: string, signal: AbortSignal): Promise { + const record = btwRecords.get(id)!; + const earlier = (record.followUps?.length ? [record, ...record.followUps.slice(0, -1)] : []) + .map((turn) => `Side question: ${turn.question}\nYour answer: ${turn.answer}`).join("\n\n"); + const prompt = [ + "", conversationText(ctx.sessionManager?.getBranch?.() ?? []), "", + ...(earlier ? ["", earlier] : []), + "", `Side question: ${latestTurn(record).question}`, + ].join("\n"); + let answer = ""; + try { + const stream = ctx.modelRegistry!.streamSimple(ctx.model, { + systemPrompt: "You answer a side question about the conversation shown. The conversation goes on without your answer: do not act or call tools, just answer briefly.", + messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }], + }, { signal }); + for await (const event of stream) { + if (event.type !== "text_delta" || !event.delta) continue; + answer += event.delta; + const current = btwRecords.get(id); + if (current) btwRecords.set(id, withLatest(current, { answer })); + emitBtw(ctx, { type: "btw_delta", recordId: id, delta: event.delta }); + } + const result = await stream.result(); + if (signal.aborted || result.stopReason === "aborted") finishBtw(ctx, id, { answer, status: "cancelled" }); + else if (result.stopReason === "error") finishBtw(ctx, id, { answer, status: "error", error: result.errorMessage ?? "The model failed" }); + else finishBtw(ctx, id, { answer, status: "complete" }); + } catch (error) { + finishBtw(ctx, id, signal.aborted ? { answer, status: "cancelled" } : { answer, status: "error", error: error instanceof Error ? error.message : String(error) }); + } + } pi.registerCommand("tau_btw", { - description: "Handle tau /btw side-question commands", + description: "tau's side questions (ask, cancel, history)", handler(args, ctx) { - const trimmed = args.trim(); - if (!trimmed) return; + let cmd: { action?: unknown; replyId?: unknown; question?: unknown; recordId?: unknown }; try { - const cmd = JSON.parse(trimmed) as { action?: string; id?: string; question?: string }; - if (cmd.action === "history") { - ctx.ui.setWidget("tau-btw", [JSON.stringify({ type: "btw_history", entries: btwHistory })]); - return; - } - if (cmd.action === "cancel" && cmd.id) { - const entry = btwHistory.find((e) => e.id === cmd.id); - if (entry && entry.status === "running") { - entry.status = "cancelled"; - ctx.ui.setWidget("tau-btw", [JSON.stringify({ type: "btw_cancelled", id: entry.id })]); - } - return; - } - if (cmd.question) { - const entry: BtwEntry = { - id: cmd.id || `btw-${Date.now()}`, - question: cmd.question, - status: "done", - answer: "", - createdAt: Date.now(), - }; - btwHistory.push(entry); - pi.appendEntry("tau_btw", entry); - ctx.ui.setWidget("tau-btw", [JSON.stringify({ type: "btw_entry", entry })]); - } + cmd = JSON.parse(args); } catch { - // Plain text fallback - } - }, - }); - - pi.registerCommand("btw", { - description: "Ask a side question without modifying the main conversation", - handler(args, ctx) { - const question = args.trim(); - if (!question) { - ctx.ui.notify("Usage: /btw ", "warning"); return; } - const entry: BtwEntry = { - id: `btw-${Date.now()}`, - question, - status: "done", - createdAt: Date.now(), - }; - btwHistory.push(entry); - pi.appendEntry("tau_btw", entry); - ctx.ui.setWidget("tau-btw", [JSON.stringify({ type: "btw_entry", entry })]); + const reply = (data: unknown) => emitBtw(ctx, { type: "tau_reply", replyId: cmd.replyId, data }); + const fail = (error: string) => emitBtw(ctx, { type: "tau_reply", replyId: cmd.replyId, error }); + if (cmd.action === "history") return reply({ records: [...btwRecords.values()] }); + if (cmd.action === "cancel") { + const running = typeof cmd.recordId === "string" ? btwRunning.get(cmd.recordId) : undefined; + running?.abort(); + return reply({ cancelled: running !== undefined }); + } + if (cmd.action !== "ask") return fail("Unknown side-question action"); + const question = typeof cmd.question === "string" ? cmd.question.trim() : ""; + if (!question) return fail("A side question needs text"); + if (!ctx.model || !ctx.modelRegistry) return fail("No model is selected for this session"); + const now = Date.now(); + const turn: BtwTurn = { question, answer: "", status: "running", createdAt: now, updatedAt: now }; + let record: BtwRecord; + if (typeof cmd.recordId === "string") { + const existing = btwRecords.get(cmd.recordId); + if (!existing) return fail("That side question is gone"); + if (btwRunning.has(existing.id)) return fail("That side question is still being answered"); + record = { ...existing, followUps: [...(existing.followUps ?? []), turn] }; + } else { + record = { id: `btw-${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`, leafId: ctx.sessionManager?.getLeafId?.() ?? null, ...turn }; + } + btwRecords.set(record.id, record); + const controller = new AbortController(); + btwRunning.set(record.id, controller); + reply({ record }); + emitBtw(ctx, { type: "btw_record", record }); + void answerBtw(ctx, record.id, controller.signal); }, }); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 7f4a1bfa..6270993d 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -176,9 +176,6 @@ const PASSTHROUGH_COMMANDS = new Set([ "set_subagent_subscription", "get_login_providers", "login", - "btw", - "btw_cancel", - "get_btw_history", "get_client_message_status", ]); @@ -3012,6 +3009,19 @@ export class AgentSessionWrapper { return null; } + // pi has no side questions: the companion extension answers them (`/tau_btw`, lib/pi/tau-extension.ts) and + // streams btw_record / btw_delta frames. + case "btw": + return await this.proc.callExtension("tau_btw", { + action: "ask", + question: command.question, + ...(typeof command.recordId === "string" ? { recordId: command.recordId } : {}), + }); + case "btw_cancel": + return await this.proc.callExtension("tau_btw", { action: "cancel", recordId: command.recordId }); + case "get_btw_history": + return await this.proc.callExtension("tau_btw", { action: "history" }, GET_STATE_TIMEOUT_MS); + default: { if (PASSTHROUGH_COMMANDS.has(type)) { if (type === "abort_and_prompt") { From dbdcabec32f4ccc28285e3466412bb116d62abd2 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 20:04:25 +0000 Subject: [PATCH 014/129] feat(edit): run history Edit through pi's navigateTree pi has no edit_message command and moves the leaf only from an extension command, so the wrapper calls /tau_edit: the companion extension checks the target is a user message, runs navigateTree(entryId, { summarize: false }), which keeps the old branch and moves the leaf to the message's parent, and answers { sessionId, cancelled, leafId }. Its reply frames now use the widget key tau, as they carry more than /btw. --- hooks/useAgentSession.rpc.test.mjs | 2 ++ lib/agent-command.test.mjs | 2 +- lib/hosts/hub-v7.test.mjs | 3 ++- lib/omp/rpc-process-runtime.test.mjs | 2 +- lib/omp/rpc-process.ts | 2 +- lib/pi/tau-extension.ts | 32 +++++++++++++++++++++++++--- lib/rpc-manager.test.mjs | 6 +++++- lib/rpc-manager.ts | 3 ++- lib/session-routes.test.mjs | 2 ++ 9 files changed, 45 insertions(+), 9 deletions(-) diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 3ce62c75..a196c17d 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -3992,6 +3992,8 @@ async function attachEditableWrapper(t, native, { holdHistory = false } = {}) { if (command.type === "prompt") { await native.command(command); return { agentInvoked: true }; } return {}; }, + // History Edit's companion-extension call (`/tau_edit`) reaches the fake as the edit it stands for. + callExtension(command, args) { return this.sendCommand(command === "tau_edit" ? { type: "edit_message", entryId: args.entryId } : { type: command, ...args }); }, sendFrame() {}, async dispose() { listeners.clear(); }, }, process.cwd(), null, false, "", undefined, onlineHost); diff --git a/lib/agent-command.test.mjs b/lib/agent-command.test.mjs index a644e3d2..30a7e8c1 100644 --- a/lib/agent-command.test.mjs +++ b/lib/agent-command.test.mjs @@ -41,7 +41,7 @@ async function respond(message, link = daemon) { // The companion extension answers a side-question call with a tau_reply frame, then pi's handled prompt reply. const { replyId } = JSON.parse(command.message.slice("/tau_btw ".length)); const frame = { type: "tau_reply", replyId, data: { records: [] } }; - await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau-btw", widgetLines: [JSON.stringify(frame)] }) }); + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau", widgetLines: [JSON.stringify(frame)] }) }); reply = { success: true, data: { disposition: "handled" } }; } else if (command.type === "get_state") { reply = { diff --git a/lib/hosts/hub-v7.test.mjs b/lib/hosts/hub-v7.test.mjs index 46b33f1b..17c672d6 100644 --- a/lib/hosts/hub-v7.test.mjs +++ b/lib/hosts/hub-v7.test.mjs @@ -936,7 +936,8 @@ test("a pre-release v7 daemon without editLease still lets the edit run", async session.proc.transport.setEditing = async () => { throw new HostOpError(501, "unknown_op", "Unknown host op: editLease"); }; const editing = session.send({ type: "edit_message", entryId: "u1" }); await until(() => fixture.messages.some(message => message.type === "stdin" && JSON.parse(message.line).type === "get_state" && session.isEditingHistory()), "preflight ran"); - await editing.catch(() => {}); + // The fake child never answers /tau_edit: the edit itself is not this test's concern. + editing.catch(() => {}); }); test("a host's planned stop closes the wrapper quietly; a crash is still reported", async (t) => { diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index f862745b..bcab9be8 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -153,7 +153,7 @@ test("callExtension sends / and settles on its tau_reply frame, await proc.waitReady(); const frames = []; proc.onFrame((frame) => frames.push(frame.type)); - const widget = (frame) => transport.send({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau-btw", widgetLines: [JSON.stringify(frame)] }); + const widget = (frame) => transport.send({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau", widgetLines: [JSON.stringify(frame)] }); const call = proc.callExtension("tau_btw", { action: "history" }); await until(() => transport.commands.length > 0); const [prompt] = transport.commands; diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index edab6d53..03d33c50 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -369,7 +369,7 @@ export class RpcProcess { if (method === "notify") { return { type: "notice", level: typeof req.notifyType === "string" ? req.notifyType : "info", message: String(req.message ?? "") }; } - if (method === "setWidget" && req.widgetKey === "tau-btw" && Array.isArray(req.widgetLines) && typeof req.widgetLines[0] === "string") { + if (method === "setWidget" && req.widgetKey === "tau" && Array.isArray(req.widgetLines) && typeof req.widgetLines[0] === "string") { try { const btw = JSON.parse(req.widgetLines[0]) as RpcFrame; if (btw && btw.type === "tau_reply") { diff --git a/lib/pi/tau-extension.ts b/lib/pi/tau-extension.ts index a8b3d4b4..9f820314 100644 --- a/lib/pi/tau-extension.ts +++ b/lib/pi/tau-extension.ts @@ -34,7 +34,11 @@ interface PiContext { getEntries?: () => SessionEntry[]; getBranch?: () => SessionEntry[]; getLeafId?: () => string | null; + getSessionId?: () => string; + getEntry?: (id: string) => SessionEntry | undefined; }; + /** Command handlers only (ExtensionCommandContext). */ + navigateTree?: (targetId: string, options?: { summarize?: boolean }) => Promise<{ cancelled: boolean }>; } interface PiExtensionAPI { @@ -232,7 +236,7 @@ export default function tauExtension(pi: PiExtensionAPI): void { // 4. /btw side questions: answered from the conversation so far with the session's model, never added to it. // tau calls `/tau_btw {action, replyId, ...}` and gets a `tau_reply` frame back; answers stream as `btw_delta` - // and `btw_record` frames (all through the `tau-btw` widget, which tau's RpcProcess decodes). + // and `btw_record` frames (all through the `tau` widget, which tau's RpcProcess decodes). const btwRecords = new Map(); const btwRunning = new Map(); const latestTurn = (record: BtwRecord): BtwTurn => record.followUps?.at(-1) ?? record; @@ -241,7 +245,7 @@ export default function tauExtension(pi: PiExtensionAPI): void { if (!followUps?.length) return { ...record, ...patch }; return { ...record, followUps: [...followUps.slice(0, -1), { ...followUps[followUps.length - 1], ...patch }] }; }; - const emitBtw = (ctx: PiContext, frame: Record) => ctx.ui.setWidget("tau-btw", [JSON.stringify(frame)]); + const emitBtw = (ctx: PiContext, frame: Record) => ctx.ui.setWidget("tau", [JSON.stringify(frame)]); pi.on("session_start", (_event, ctx) => { btwRecords.clear(); @@ -335,7 +339,29 @@ export default function tauExtension(pi: PiExtensionAPI): void { }, }); - // 5. pi-subagents event bridge + // 5. History Edit: move the leaf to just before a user message, keeping the old branch (tau's edit_message). + pi.registerCommand("tau_edit", { + description: "tau's history Edit", + async handler(args, ctx) { + let cmd: { replyId?: unknown; entryId?: unknown }; + try { + cmd = JSON.parse(args); + } catch { + return; + } + const reply = (frame: Record) => ctx.ui.setWidget("tau", [JSON.stringify({ type: "tau_reply", replyId: cmd.replyId, ...frame })]); + const entry = typeof cmd.entryId === "string" ? ctx.sessionManager?.getEntry?.(cmd.entryId) : undefined; + if (entry?.type !== "message" || entry.message?.role !== "user") return reply({ error: "The edit target must be a user message" }); + try { + const { cancelled } = await ctx.navigateTree!(cmd.entryId as string, { summarize: false }); + reply({ data: { sessionId: ctx.sessionManager?.getSessionId?.(), cancelled, leafId: ctx.sessionManager?.getLeafId?.() ?? null } }); + } catch (error) { + reply({ error: error instanceof Error ? error.message : String(error) }); + } + }, + }); + + // 6. pi-subagents event bridge const subagentEvents = [ "subagent:start", "subagent:update", diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 7646962f..9bb08443 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -63,6 +63,10 @@ function snapshotSession(t, sendCommand = async () => ({}), Wrapper = SnapshotWr return result; }, sendFrame(frame) { sentFrames.push(frame); }, + // The companion-extension call History Edit makes (`/tau_edit`) reaches the fake as the edit it stands for. + callExtension(command, args, timeoutMs) { + return this.sendCommand(command === "tau_edit" ? { type: "edit_message", entryId: args.entryId } : { type: command, ...args }, timeoutMs); + }, dispose: async () => {}, }, process.cwd(), null, false, sessionId, disconnectDestroyMs, host); wrapper.start(); @@ -3308,7 +3312,7 @@ test("an edit that times out with no uplink since dispatch answers host_offline const omp = async (message) => { if (message.type === "kill") kills.push(message); // The link drops right after the edit preflight: the edit command is never answered. - if (message.type === "stdin" && readCommand(message.line).type === "edit_message") return editAsked.resolve(); + if (message.type === "stdin" && readCommand(message.line).message?.startsWith("/tau_edit ")) return editAsked.resolve(); await answer(message); }; link.serve(openOverLink(), omp); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 6270993d..a7ea7883 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2275,7 +2275,8 @@ export class AgentSessionWrapper { throw new WebRpcError("Wait for the current run to finish before editing", "session_busy"); } - const result = await proc.sendCommand({ type: "edit_message", entryId }, EDIT_TIMEOUT_MS); + // pi moves the leaf only from an extension command (`/tau_edit`, lib/pi/tau-extension.ts): navigateTree. + const result = await proc.callExtension("tau_edit", { entryId }, EDIT_TIMEOUT_MS); if (!isRecord(result) || typeof result.sessionId !== "string" || !result.sessionId.trim() || typeof result.cancelled !== "boolean" || (result.leafId !== null && typeof result.leafId !== "string")) { throw new Error("OMP returned an invalid history edit result"); diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 80e75c16..2f42e598 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -1607,6 +1607,8 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn throw new Error(`Unexpected native command: ${command.type}`); }, sendFrame() {}, + // History Edit's companion-extension call (`/tau_edit`) reaches the fake as the edit it stands for. + callExtension(command, args) { return this.sendCommand(command === "tau_edit" ? { type: "edit_message", entryId: args.entryId } : { type: command, ...args }); }, async dispose() {}, }, dir); wrapper.start(); From f0a66c791f12f4db6c8a7bd7bc3d563a3a0ee897 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 20:23:31 +0000 Subject: [PATCH 015/129] feat(subagents): follow pi-subagents' children in the roster The extension listened for guessed pi-subagents event names, so no subagent ever reached tau. pi-subagents already reports to RPC hosts: foreground children as AgentProgress rows on its subagent tool call, background runs as PI_SUBAGENT_ASYNC_JSON snapshots on its subagent-async widget. RpcProcess now runs both through SubagentBridge, which emits the subagent_lifecycle and subagent_progress frames tau's roster reads (lifecycle before a new child's progress, progress before its end; a child still running when its call ends ends with it), and the wrapper answers get_subagents with the children still running. --- lib/omp/rpc-process.ts | 9 ++ lib/omp/subagent-bridge.test.mjs | 52 +++++++++++ lib/omp/subagent-bridge.ts | 156 +++++++++++++++++++++++++++++++ lib/pi/tau-extension.ts | 25 +---- lib/rpc-manager.ts | 5 +- 5 files changed, 224 insertions(+), 23 deletions(-) create mode 100644 lib/omp/subagent-bridge.test.mjs create mode 100644 lib/omp/subagent-bridge.ts diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index 03d33c50..eb8c328b 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -8,6 +8,7 @@ import { isRecord } from "../type-guards"; import { OMP_NOT_FOUND, resolveOmpBin } from "./omp-cli"; import { type RpcTransport, spawnLocalRpcTransport } from "./rpc-transport"; import { LINK_LIMITS } from "../hosts/link-protocol"; +import { SubagentBridge } from "./subagent-bridge"; /** * Process + protocol layer for `pi --mode rpc` (NDJSON over stdio). @@ -166,6 +167,8 @@ export class RpcProcess { /** Standard pi extension dialog methods awaiting `ui_response` -> `extension_ui_response`. */ private readonly extensionDialogMethods = new Map(); private nextId = 1; + /** pi-subagents' reports as tau's subagent frames; its running children answer get_subagents. */ + readonly subagents = new SubagentBridge(); /** Companion-extension calls awaiting their `tau_reply` frame (see `callExtension`). */ private readonly extensionReplies = new Map(); /** Whether pi has settled since its last `agent_start` (`agent_settled`); null for an adopted child whose history is unknown. */ @@ -312,6 +315,12 @@ export class RpcProcess { this.resolveReady({ ...parsed, type: "ready" }); return; } + const bridged = this.subagents.translate(parsed as RpcFrame); + if (bridged) { + if (!bridged.consume) this.dispatch(parsed as RpcFrame, replayed); + for (const frame of bridged.frames) this.dispatch(frame, replayed); + return; + } if (parsed.type === "extension_ui_request" && typeof parsed.method === "string") { const translated = this.translateExtensionUiRequest(parsed); if (translated) this.dispatch(translated, replayed); diff --git a/lib/omp/subagent-bridge.test.mjs b/lib/omp/subagent-bridge.test.mjs new file mode 100644 index 00000000..e55fd229 --- /dev/null +++ b/lib/omp/subagent-bridge.test.mjs @@ -0,0 +1,52 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { SubagentBridge } from "./subagent-bridge.ts"; +import { parseSubagentLifecycle, parseSubagentProgress, parseSubagentSnapshot } from "../subagent-types.ts"; + +const row = (status, extra = {}) => ({ index: 0, agent: "reviewer", status, task: "Review the diff", sessionFile: "/s/child.jsonl", recentTools: [], recentOutput: [], toolCount: 2, tokens: 10, currentTool: "read", model: "anthropic/claude", ...extra }); +const update = (toolCallId, rows) => ({ type: "tool_execution_update", toolCallId, toolName: "subagent", partialResult: { content: [], details: { progress: rows } } }); +const end = (toolCallId, rows, isError = false) => ({ type: "tool_execution_end", toolCallId, toolName: "subagent", isError, result: { content: [], details: { progress: rows } } }); +const kinds = (result) => result.frames.map((frame) => `${frame.type}:${frame.payload.status ?? frame.payload.progress?.status}`); + +test("a foreground subagent call becomes a started child, its progress, and its end; the call frame still passes", () => { + const bridge = new SubagentBridge(); + const first = bridge.translate(update("call|1", [row("running")])); + assert.equal(first.consume, false); + assert.deepEqual(kinds(first), ["subagent_lifecycle:started", "subagent_progress:running"], "lifecycle first: the roster ignores progress for a child it lacks"); + const info = parseSubagentLifecycle(first.frames[0].payload); + assert.equal(info.id, "call_1.0", "an id tau can name a transcript file by"); + assert.equal(info.parentToolCallId, "call|1"); + assert.equal(info.sessionFile, "/s/child.jsonl"); + const progress = parseSubagentProgress(first.frames[1].payload.progress); + assert.equal(progress.currentTool, "read"); + assert.equal(progress.resolvedModel, "anthropic/claude"); + assert.deepEqual(bridge.running().map((child) => child.id), ["call_1.0"]); + + assert.deepEqual(bridge.translate(update("call|1", [row("running")])).frames, [], "an unchanged report adds nothing"); + assert.deepEqual(kinds(bridge.translate(update("call|1", [row("running", { toolCount: 3 })]))), ["subagent_progress:running"]); + assert.deepEqual(kinds(bridge.translate(end("call|1", [row("running", { toolCount: 3 })]))), ["subagent_progress:completed", "subagent_lifecycle:completed"], "a child still running when the call ends ends with it"); + assert.deepEqual(bridge.running(), []); + assert.deepEqual(bridge.translate(update("call|1", [row("running")])).frames, [], "an ended child never comes back"); +}); + +test("a failed call fails the children it left running", () => { + const bridge = new SubagentBridge(); + bridge.translate(update("c", [row("running"), row("completed", { index: 1 })])); + assert.deepEqual(kinds(bridge.translate(end("c", [row("running"), row("completed", { index: 1 })], true))), ["subagent_progress:failed", "subagent_lifecycle:failed"]); +}); + +test("background runs come from the subagent-async widget, which tau consumes", () => { + const bridge = new SubagentBridge(); + const widget = (runs) => ({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "subagent-async", widgetLines: [`PI_SUBAGENT_ASYNC_JSON:${JSON.stringify({ kind: "pi-subagents.async-status-snapshot", version: 1, runs })}`] }); + const run = (state, children = []) => ({ id: "run-1", kind: "workflow", label: "sweep", state, startedAt: 1000, updatedAt: 3000, children }); + const step = (state) => ({ id: "step:0", kind: "step", label: "lint", state, agent: "linter", model: "m", activity: { currentTool: "bash", toolCount: 4 } }); + const first = bridge.translate(widget([run("running", [step("running")])])); + assert.equal(first.consume, true); + assert.deepEqual(kinds(first), ["subagent_lifecycle:started", "subagent_progress:running", "subagent_lifecycle:started", "subagent_progress:running"]); + const child = parseSubagentLifecycle(first.frames[2].payload); + assert.deepEqual([child.id, child.agent, child.detached], ["async.step_0", "linter", true]); + assert.deepEqual(bridge.running().map((entry) => parseSubagentSnapshot(entry)?.id), ["async.run-1", "async.step_0"]); + assert.deepEqual(kinds(bridge.translate(widget([run("failed", [step("stopped")])]))), ["subagent_progress:failed", "subagent_lifecycle:failed", "subagent_progress:aborted", "subagent_lifecycle:aborted"]); + assert.deepEqual(bridge.translate({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "subagent-async" }), { frames: [], consume: true }, "a cleared widget"); + assert.equal(bridge.translate({ type: "agent_start" }), null); +}); diff --git a/lib/omp/subagent-bridge.ts b/lib/omp/subagent-bridge.ts new file mode 100644 index 00000000..dff8942e --- /dev/null +++ b/lib/omp/subagent-bridge.ts @@ -0,0 +1,156 @@ +import { isRecord } from "../type-guards"; + +/** + * pi-subagents (the pi package that runs subagents) reports its children two ways an RPC host can read: foreground + * runs as progress on its `subagent` tool call (`details.progress[]`, AgentProgress rows), and background runs as + * `PI_SUBAGENT_ASYNC_JSON:` snapshots on its `subagent-async` widget. SubagentBridge turns both into the + * `subagent_lifecycle` / `subagent_progress` frames tau's roster reads, and keeps the running children for + * `get_subagents`. + */ + +type Frame = { type: string; [key: string]: unknown }; +type Status = "started" | "completed" | "failed" | "aborted"; +type ProgressStatus = "pending" | "running" | "completed" | "failed" | "aborted"; + +interface Entry { + id: string; + index: number; + agent: string; + status: Status; + detached: boolean; + description?: string; + task?: string; + sessionFile?: string; + parentToolCallId?: string; + progress: Record; + lastUpdate: number; +} + +const ASYNC_WIDGET = "subagent-async"; +const ASYNC_PREFIX = "PI_SUBAGENT_ASYNC_JSON:"; +/** tau addresses a subagent by an id it can put in a file name (SUBAGENT_ID_RE). */ +const idPart = (value: unknown) => String(value).replace(/[^A-Za-z0-9_-]/g, "_"); +const text = (value: unknown) => (typeof value === "string" && value ? value : undefined); +const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : undefined); +const terminal = (status: Status) => status !== "started"; + +function defined(record: Record): Record { + return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined)); +} + +/** A foreground AgentProgress row as tau's SubagentProgress. */ +function rowProgress(id: string, row: Record, status: ProgressStatus): Record { + const started = number(row.startedAt), ended = number(row.endedAt) ?? number(row.lastActivityAt); + return defined({ + id, index: number(row.index), agent: text(row.agent), status, task: text(row.task) ?? text(row.progressText), + currentTool: text(row.currentTool), currentToolArgs: text(row.currentToolArgs), currentToolStartMs: number(row.currentToolStartedAt), + recentTools: Array.isArray(row.recentTools) ? row.recentTools : undefined, + recentOutput: Array.isArray(row.recentOutput) ? row.recentOutput : undefined, + toolCount: number(row.toolCount), tokens: number(row.tokens), contextTokens: number(row.window), resolvedModel: text(row.model), + durationMs: number(row.durationMs) ?? (started !== undefined && ended !== undefined ? ended - started : undefined), + }); +} + +const ROW_STATUS: Record = { + pending: ["started", "pending"], running: ["started", "running"], detached: ["started", "running"], + completed: ["completed", "completed"], failed: ["failed", "failed"], +}; +const NODE_STATUS: Record = { + queued: ["started", "pending"], running: ["started", "running"], paused: ["started", "running"], + complete: ["completed", "completed"], failed: ["failed", "failed"], partial: ["failed", "failed"], rejected: ["failed", "failed"], + stopped: ["aborted", "aborted"], +}; + +export class SubagentBridge { + private readonly entries = new Map(); + + /** The frames one pi frame stands for, or null when it reports no subagent. `consume`: the raw frame is only transport. */ + translate(frame: Frame): { frames: Frame[]; consume: boolean } | null { + if ((frame.type === "tool_execution_update" || frame.type === "tool_execution_end") && frame.toolName === "subagent") { + return { frames: this.foreground(frame), consume: false }; + } + if (frame.type === "extension_ui_request" && frame.method === "setWidget" && frame.widgetKey === ASYNC_WIDGET) { + const line = Array.isArray(frame.widgetLines) ? frame.widgetLines[0] : undefined; + if (typeof line !== "string" || !line.startsWith(ASYNC_PREFIX)) return { frames: [], consume: true }; + try { + return { frames: this.background(JSON.parse(line.slice(ASYNC_PREFIX.length))), consume: true }; + } catch { + return { frames: [], consume: true }; + } + } + return null; + } + + /** The children still running, as get_subagents answers them. */ + running(): Array> { + return [...this.entries.values()].filter((entry) => !terminal(entry.status)).map((entry) => defined({ ...entry })); + } + + private foreground(frame: Frame): Frame[] { + const toolCallId = text(frame.toolCallId); + const result = frame.type === "tool_execution_end" ? frame.result : frame.partialResult; + const rows = isRecord(result) && isRecord(result.details) && Array.isArray(result.details.progress) ? result.details.progress : []; + if (!toolCallId) return []; + const frames: Frame[] = []; + rows.forEach((row: unknown, position: number) => { + if (!isRecord(row)) return; + const index = number(row.index) ?? position; + const id = `${idPart(toolCallId)}.${index}`; + let [status, progressStatus] = ROW_STATUS[String(row.status)] ?? ["started", "running"]; + // The call ended: a child it still lists as running ended with it. + if (frame.type === "tool_execution_end" && !terminal(status)) [status, progressStatus] = frame.isError === true ? ["failed", "failed"] : ["completed", "completed"]; + frames.push(...this.update({ + id, index, agent: text(row.agent) ?? "subagent", status, detached: row.status === "detached", + description: text(row.sessionName), task: text(row.task), sessionFile: text(row.sessionFile), parentToolCallId: toolCallId, + progress: rowProgress(id, row, progressStatus), lastUpdate: Date.now(), + })); + }); + return frames; + } + + private background(snapshot: unknown): Frame[] { + if (!isRecord(snapshot) || !Array.isArray(snapshot.runs)) return []; + const frames: Frame[] = []; + const visit = (node: unknown, index: number) => { + if (!isRecord(node) || typeof node.id !== "string" || node.kind === "host-step") return; + const id = `async.${idPart(node.id)}`; + const [status, progressStatus] = NODE_STATUS[String(node.state)] ?? ["started", "running"]; + const activity = isRecord(node.activity) ? node.activity : {}; + const started = number(node.startedAt), ended = number(node.endedAt) ?? number(node.updatedAt); + const agent = text(node.agent) ?? text(node.label) ?? "subagent"; + frames.push(...this.update({ + id, index, agent, status, detached: true, description: text(node.label), task: text(node.progressText), + progress: defined({ + id, index, agent, status: progressStatus, task: text(node.progressText), currentTool: text(activity.currentTool), + currentToolStartMs: number(activity.currentToolStartedAt), toolCount: number(activity.toolCount), resolvedModel: text(node.model), + durationMs: started !== undefined && ended !== undefined ? ended - started : undefined, + }), + lastUpdate: Date.now(), + })); + if (Array.isArray(node.children)) node.children.forEach(visit); + }; + snapshot.runs.forEach(visit); + return frames; + } + + /** Lifecycle before progress for a new child (the roster drops progress for one it lacks), progress before its end. */ + private update(next: Entry): Frame[] { + const previous = this.entries.get(next.id); + if (previous && terminal(previous.status)) return []; + this.entries.set(next.id, next); + const lifecycle: Frame = { + type: "subagent_lifecycle", + payload: defined({ id: next.id, agent: next.agent, status: next.status, index: next.index, description: next.description, + sessionFile: next.sessionFile, parentToolCallId: next.parentToolCallId, detached: next.detached }), + }; + const progress: Frame = { + type: "subagent_progress", + payload: defined({ index: next.index, agent: next.agent, task: next.task, sessionFile: next.sessionFile, + parentToolCallId: next.parentToolCallId, detached: next.detached, progress: next.progress }), + }; + const progressed = JSON.stringify(previous?.progress) !== JSON.stringify(next.progress); + if (!previous) return [lifecycle, progress]; + if (previous.status !== next.status) return progressed ? [progress, lifecycle] : [lifecycle]; + return progressed ? [progress] : []; + } +} diff --git a/lib/pi/tau-extension.ts b/lib/pi/tau-extension.ts index 9f820314..5f291e62 100644 --- a/lib/pi/tau-extension.ts +++ b/lib/pi/tau-extension.ts @@ -5,8 +5,9 @@ * 1. Host tools the server registers (`/tau_host_tools`), called via `ctx.ui.input("__tau_host_tool__", ...)` * 2. Interactive `ask` tool via `ctx.ui.input("__tau_ask__", ...)` * 3. `clientMessageId` / `origin` tracking via `/tau_meta` + `input` / `message_start` - * 4. `/btw` side-question bridge (`/btw`, `/tau_btw`) - * 5. `pi-subagents` event bridge (`pi.events`) + * 4. `/btw` side questions (`/tau_btw`) + * 5. History Edit (`/tau_edit`) + * pi-subagents needs no bridge here: tau reads its tool progress and `subagent-async` widget (lib/omp/subagent-bridge.ts). */ interface PiUI { @@ -360,24 +361,4 @@ export default function tauExtension(pi: PiExtensionAPI): void { } }, }); - - // 6. pi-subagents event bridge - const subagentEvents = [ - "subagent:start", - "subagent:update", - "subagent:end", - "subagent_start", - "subagent_update", - "subagent_end", - "pi-subagents:event", - ]; - let lastCtx: PiContext | null = null; - pi.on("session_start", (_event, ctx) => { - lastCtx = ctx; - }); - for (const eventName of subagentEvents) { - pi.events.on(eventName, (data) => { - lastCtx?.ui.setStatus("tau-subagent", JSON.stringify({ event: eventName, data })); - }); - } } diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index a7ea7883..519a3b60 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -171,7 +171,6 @@ const PASSTHROUGH_COMMANDS = new Set([ "get_messages_page", "export_html", "handoff", - "get_subagents", "get_subagent_messages", "set_subagent_subscription", "get_login_providers", @@ -3010,6 +3009,10 @@ export class AgentSessionWrapper { return null; } + // pi-subagents' running children, as RpcProcess's bridge last saw them (pi has no such command). + case "get_subagents": + return { subagents: this.proc.subagents?.running() ?? [] }; + // pi has no side questions: the companion extension answers them (`/tau_btw`, lib/pi/tau-extension.ts) and // streams btw_record / btw_delta frames. case "btw": From 1768d367135c597377e9fb0257c01e61abc4315b Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 20:47:59 +0000 Subject: [PATCH 016/129] fix(rpc): start the utility pi without omp's --no-lsp pi rejects --no-lsp (Unknown option), so the utility process behind logins and model lists exited on start. It skips MCP instead, pi's startup work the utility never needs. --- lib/omp/rpc-utility.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/omp/rpc-utility.ts b/lib/omp/rpc-utility.ts index b7d33aae..e94c42cd 100644 --- a/lib/omp/rpc-utility.ts +++ b/lib/omp/rpc-utility.ts @@ -17,7 +17,8 @@ import { RpcProcess } from "./rpc-process"; // omitting them made the web UI's model/provider lists disagree with the CLI's. // Measured against a real install (omp/17.1.3): ready-frame latency is the same // either way (~3.6s with vs ~4.0s without over 4 runs each). -const UTILITY_EXTRA_ARGS = ["--no-session", "--no-skills", "--no-lsp"]; +// pi has no language servers to skip; MCP is its startup work the utility never needs. +const UTILITY_EXTRA_ARGS = ["--no-session", "--no-skills", "--no-mcp"]; const READY_TIMEOUT_MS = 60_000; // Longer than the 60s models-cache TTL on purpose: with idle-kill == TTL every // pause past a minute paid a cold multi-second respawn on top of the stale From 2c4896b33c1c89dc5bca88973dcd641e990408d2 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 21:04:18 +0000 Subject: [PATCH 017/129] feat(messages): give pi's messages tau's client ids and origins pi keeps no client message ids, so delivery fell back to matching text and origin cards (session and GitHub sources) disappeared. The session wrapper now names each message before sending it (/tau_meta). The companion extension binds the name in its input handler to the message pi admits, follows pi's steering and follow-up queues in delivery order, announces the id just before pi's own message_start, and journals it as tau's client-message-entry (with its origin) once pi has stored the message, which the session reader joins for origin cards. A withdrawn queue is journaled as client-message-resolution, and get_client_message_status reads the journal through the extension. RpcProcess puts the announced id and origin on the user message's events, the extension's names on queue snapshots, and reports supportsClientMessageIds once the extension has spoken (tau_hello at start, or any reply from an adopted process). --- lib/message-outbox-review.test.mjs | 16 +++- lib/omp/rpc-process-runtime.test.mjs | 39 ++++++++ lib/omp/rpc-process.ts | 43 ++++++++- lib/outbox-handoff.test.mjs | 8 +- lib/pi/tau-extension.ts | 133 ++++++++++++++++++++++----- lib/rpc-manager.ts | 18 +++- 6 files changed, 226 insertions(+), 31 deletions(-) diff --git a/lib/message-outbox-review.test.mjs b/lib/message-outbox-review.test.mjs index 28e9bfa6..c8ceb184 100644 --- a/lib/message-outbox-review.test.mjs +++ b/lib/message-outbox-review.test.mjs @@ -80,7 +80,15 @@ async function liveSession(sessionId, { fresh = false, supportsClientMessageIds write(line, callback) { const command = unwire(line); transport.commands.push(command); - if (["prompt", "follow_up", "steer", "abort_and_prompt"].includes(command.type)) transport.pendingMessages.push(command); + if (command.type === "prompt" && command.message.startsWith("/tau_meta ")) { + // The companion extension's status answer: a tau_reply frame, then pi's handled prompt reply. + const { replyId, action } = JSON.parse(command.message.slice("/tau_meta ".length)); + const data = action === "status" ? transport.replies.get_client_message_status ?? null : { named: true }; + queueMicrotask(() => { + transport.emit({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau", widgetLines: [JSON.stringify({ type: "tau_reply", replyId, data })] }); + transport.answer(command, { disposition: "handled" }); + }); + } else if (["prompt", "follow_up", "steer", "abort_and_prompt"].includes(command.type)) transport.pendingMessages.push(command); else queueMicrotask(() => transport.answer(command, command.type in transport.replies ? transport.replies[command.type] : command.type === "get_state" ? { sessionId: transport.sessionId, sessionFile: `/nonexistent/${transport.sessionId}.jsonl`, isStreaming: transport.streaming, isCompacting: false, sessionName: "Review fixture", @@ -1599,8 +1607,10 @@ test("a handoff status read reaches the live child through the real wrapper and const response = await runAgentCommand(sid, { type: "get_client_message_status", clientMessageIds: ["seen", "queued", "missing"] }, false, "owner"); assert.equal(response.status, 200, JSON.stringify(await response.clone().json())); const sent = transport.commands.slice(writes); - assert.deepEqual(sent.map((command) => [command.type, command.clientMessageIds]), - [["get_client_message_status", ["seen", "queued", "missing"]]], "the read is forwarded verbatim, once"); + assert.deepEqual(sent.map((command) => { + const { action, clientMessageIds } = JSON.parse(command.message.slice("/tau_meta ".length)); + return [action, clientMessageIds]; + }), [["status", ["seen", "queued", "missing"]]], "the read goes to the companion extension verbatim, once"); const { data } = await response.json(); assert.deepEqual(data.messages, reply.messages); assert.deepEqual(data.queuedMessages.clientMessageIds, reply.queuedMessages.clientMessageIds); diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index bcab9be8..73e448c3 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -179,6 +179,45 @@ test("callExtension sends / and settles on its tau_reply frame, await assert.rejects(orphan, /exited/); }); +test("the companion extension's names reach user messages, queue snapshots and get_state", async () => { + const transport = makeTransport(); + const proc = startProcess(transport); + await proc.waitReady(); + const frames = []; + proc.onFrame((frame) => frames.push(frame)); + const tau = (frame) => transport.send({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau", widgetLines: [JSON.stringify(frame)] }); + const state = async () => { + const sent = transport.commands.length; + const reply = proc.sendCommand({ type: "get_state" }); + await until(() => transport.commands.length > sent); + transport.send({ id: transport.commands.at(-1).id, type: "response", command: "get_state", success: true, data: { isStreaming: true, pendingMessageCount: 1 } }); + return reply; + }; + assert.equal((await state()).supportsClientMessageIds, undefined, "no names before the extension speaks"); + tau({ type: "tau_hello" }); + await until(() => proc.tauExtension); + const origin = { v: 1, kind: "github", sentAt: "2026-11-18T00:00:00.000Z" }; + tau({ type: "tau_queue", steering: [], followUp: [{ clientMessageId: "cm-q", origin }] }); + transport.send({ type: "queue_update", steering: [], followUp: ["later"] }); + await until(() => frames.some((frame) => frame.type === "queue_update")); + assert.deepEqual(frames.at(-1).clientMessageIds, { steering: [], followUp: ["cm-q"] }); + assert.deepEqual(frames.at(-1).messageOrigins, { steering: [], followUp: [origin] }); + const named = await state(); + assert.equal(named.supportsClientMessageIds, true); + assert.deepEqual(named.queuedMessages.clientMessageIds, { steering: [], followUp: ["cm-q"] }); + + tau({ type: "tau_message_identity", clientMessageId: "cm-1", origin }); + transport.send({ type: "message_start", message: { role: "user", content: "hi" } }); + transport.send({ type: "message_end", message: { role: "user", content: "hi" } }); + transport.send({ type: "message_start", message: { role: "user", content: "unnamed" } }); + await until(() => frames.filter((frame) => frame.type === "message_start").length === 2); + const users = frames.filter((frame) => frame.type === "message_start" || frame.type === "message_end"); + assert.deepEqual(users.map((frame) => frame.clientMessageId ?? null), ["cm-1", "cm-1", null], "a name covers one message"); + assert.deepEqual(users[0].origin, origin); + assert.equal(frames.some((frame) => frame.type.startsWith("tau_")), false, "extension frames are consumed"); + await proc.dispose(0); +}); + test("a failed response rejects with RpcCommandError", async () => { const transport = makeTransport(); transport.onLine = (frame) => frame.id && transport.send({ id: frame.id, type: "response", command: frame.type, success: false, error: "busy" }); diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index eb8c328b..c7ee4e41 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -175,6 +175,12 @@ export class RpcProcess { private settled: boolean | null; /** The last `queue_update`: pi's `get_state` reports only `pendingMessageCount`. */ private lastQueue: { steering: unknown[]; followUp: unknown[] } | null = null; + /** Whether tau's companion extension answers (any `tau` widget frame seen): then messages carry client ids. */ + tauExtension = false; + /** The extension's names for the queued messages (`tau_queue`), in pi's queue order. */ + private queueIds: Record<"steering" | "followUp", Array<{ clientMessageId?: unknown; origin?: unknown }>> | null = null; + /** The name the extension announced for the user message pi starts next (`tau_message_identity`). */ + private identity: { clientMessageId: unknown; origin?: unknown } | null = null; private stderrTail = ""; private exited = false; private exitInfo: { code: number | null; signal: NodeJS.Signals | null } | null = null; @@ -329,6 +335,14 @@ export class RpcProcess { if (parsed.type === "agent_start") this.settled = false; if (parsed.type === "queue_update") { this.lastQueue = { steering: Array.isArray(parsed.steering) ? parsed.steering : [], followUp: Array.isArray(parsed.followUp) ? parsed.followUp : [] }; + this.dispatch({ ...parsed, ...this.queueNames(this.lastQueue) } as RpcFrame, replayed); + return; + } + if ((parsed.type === "message_start" || parsed.type === "message_end") && this.identity && isRecord(parsed.message) && parsed.message.role === "user") { + const { clientMessageId, origin } = this.identity; + if (parsed.type === "message_end") this.identity = null; + this.dispatch({ ...parsed, type: parsed.type, clientMessageId, ...(origin !== undefined ? { origin } : {}) }, replayed); + return; } if (parsed.type === "agent_settled") { this.settled = true; @@ -381,6 +395,19 @@ export class RpcProcess { if (method === "setWidget" && req.widgetKey === "tau" && Array.isArray(req.widgetLines) && typeof req.widgetLines[0] === "string") { try { const btw = JSON.parse(req.widgetLines[0]) as RpcFrame; + this.tauExtension = true; + if (btw?.type === "tau_hello") return null; + if (btw?.type === "tau_message_identity") { + this.identity = { clientMessageId: btw.clientMessageId, ...(btw.origin !== undefined ? { origin: btw.origin } : {}) }; + return null; + } + if (btw?.type === "tau_queue") { + const list = (value: unknown) => (Array.isArray(value) ? value.filter(isRecord) : []); + this.queueIds = { steering: list(btw.steering), followUp: list(btw.followUp) }; + // pi may have reported this queue before the extension named it: report it again, named. + const named = this.lastQueue && this.queueNames(this.lastQueue); + return named && Object.keys(named).length ? { type: "queue_update", ...this.lastQueue, ...named } : null; + } if (btw && btw.type === "tau_reply") { // Answers one of this process's extension calls; another server's calls name ids it never made. const entry = typeof btw.replyId === "string" ? this.extensionReplies.get(btw.replyId) : undefined; @@ -542,12 +569,26 @@ export class RpcProcess { } /** A `response`; one for no pending command (timed out, or another server's) is dropped. */ + /** The extension's ids and origins for `queue`, when they line up with it; none otherwise. */ + private queueNames(queue: { steering: unknown[]; followUp: unknown[] }): Record { + const names = this.queueIds; + if (!names || names.steering.length !== queue.steering.length || names.followUp.length !== queue.followUp.length) return {}; + const field = (key: "clientMessageId" | "origin") => ({ + steering: names.steering.map((item) => item[key] ?? null), followUp: names.followUp.map((item) => item[key] ?? null), + }); + return { clientMessageIds: field("clientMessageId"), messageOrigins: field("origin") }; + } + /** Fills the `get_state` fields tau reads that pi does not report: the queue, its size and settlement. */ private withQueueAndSettlement(state: Record): Record { const pending = typeof state.pendingMessageCount === "number" ? state.pendingMessageCount : undefined; const out = { ...state }; if (out.queuedMessageCount === undefined && pending !== undefined) out.queuedMessageCount = pending; - if (out.queuedMessages === undefined && (this.lastQueue || pending === 0)) out.queuedMessages = this.lastQueue ?? { steering: [], followUp: [] }; + if (out.queuedMessages === undefined && (this.lastQueue || pending === 0)) { + const queue = this.lastQueue ?? { steering: [], followUp: [] }; + out.queuedMessages = { ...queue, ...this.queueNames(queue) }; + } + if (out.supportsClientMessageIds === undefined && this.tauExtension) out.supportsClientMessageIds = true; if (out.isSettled === undefined && this.settled !== null && pending !== undefined) { out.isSettled = this.settled && state.isStreaming !== true && state.isCompacting !== true && pending === 0; } diff --git a/lib/outbox-handoff.test.mjs b/lib/outbox-handoff.test.mjs index 9654d9aa..fbbd1ee6 100644 --- a/lib/outbox-handoff.test.mjs +++ b/lib/outbox-handoff.test.mjs @@ -310,9 +310,13 @@ test("a child another server started is awaited while this server adopts it, the if (message.type !== "stdin") return; const command = JSON.parse(message.line); if (command.type === "get_state") await adopting; - if (command.type !== "get_client_message_status") return omp(message); + // A status read is a companion-extension call: its tau_reply frame, then pi's handled prompt reply. + if (command.type !== "prompt" || !command.message?.startsWith("/tau_meta ")) return omp(message); asked.push(command); - await daemon.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data: nativeReply() }) }); + const { replyId } = JSON.parse(command.message.slice("/tau_meta ".length)); + const reply = { type: "tau_reply", replyId, data: nativeReply() }; + await daemon.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "extension_ui_request", id: "w", method: "setWidget", widgetKey: "tau", widgetLines: [JSON.stringify(reply)] }) }); + await daemon.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: "prompt", success: true, data: { disposition: "handled" } }) }); }); t.after(async () => { const disposing = getRpcSession(SESSION)?.destroyAndWait(); diff --git a/lib/pi/tau-extension.ts b/lib/pi/tau-extension.ts index 5f291e62..c66298d4 100644 --- a/lib/pi/tau-extension.ts +++ b/lib/pi/tau-extension.ts @@ -4,7 +4,7 @@ * Bridges tau-specific capabilities over pi's standard RPC + Extension UI protocol: * 1. Host tools the server registers (`/tau_host_tools`), called via `ctx.ui.input("__tau_host_tool__", ...)` * 2. Interactive `ask` tool via `ctx.ui.input("__tau_ask__", ...)` - * 3. `clientMessageId` / `origin` tracking via `/tau_meta` + `input` / `message_start` + * 3. Message identity and origin (`/tau_meta`, `input`, `message_start`/`message_end`) * 4. `/btw` side questions (`/tau_btw`) * 5. History Edit (`/tau_edit`) * pi-subagents needs no bridge here: tau reads its tool progress and `subagent-async` widget (lib/omp/subagent-bridge.ts). @@ -17,7 +17,7 @@ interface PiUI { setWidget(key: string, lines: string[] | undefined, options?: { placement?: "aboveEditor" | "belowEditor" }): void; } -interface SessionEntry { type?: string; customType?: string; data?: unknown; message?: { role?: string; content?: unknown } } +interface SessionEntry { id?: string; type?: string; customType?: string; data?: unknown; message?: { role?: string; content?: unknown } } /** The subset of pi's AssistantMessageEventStream the side questions read. */ interface ModelStream extends AsyncIterable<{ type: string; delta?: string }> { @@ -73,11 +73,6 @@ interface PiExtensionAPI { }; } -interface MessageMeta { - clientMessageId?: string; - origin?: string; -} - /** tau's side-question record (lib/btw.ts): the first turn, then any follow-ups. */ type BtwStatus = "running" | "complete" | "cancelled" | "error" | "interrupted"; interface BtwTurn { question: string; answer: string; status: BtwStatus; createdAt: number; updatedAt: number; error?: string } @@ -207,32 +202,122 @@ export default function tauExtension(pi: PiExtensionAPI): void { }, }); - // 3. clientMessageId / origin tracking - const pendingMeta: MessageMeta[] = []; + // 3. Message identity. pi keeps no client ids, so tau names each message just before sending it + // (`/tau_meta {action: "name", clientMessageId, origin, text}`). The input handler binds the name to the message + // pi admits with that text, tracking pi's steering and follow-up queues in their delivery order; message_start + // announces it (`tau_message_identity`, ahead of pi's own event) and message_end journals it as tau's + // `client-message-entry`, which the session reader joins to show origin cards. + interface Named { clientMessageId: string; text: string; origin?: unknown } + const named: Named[] = []; + let starting: Named | null = null; + let current: Named | null = null; + const queued: Record<"steering" | "followUp", Named[]> = { steering: [], followUp: [] }; + const emitTau = (ctx: PiContext, frame: Record) => ctx.ui.setWidget("tau", [JSON.stringify(frame)]); + const emitQueue = (ctx: PiContext) => emitTau(ctx, { + type: "tau_queue", + steering: queued.steering.map(({ clientMessageId, origin }) => ({ clientMessageId, origin })), + followUp: queued.followUp.map(({ clientMessageId, origin }) => ({ clientMessageId, origin })), + }); + const textOf = (content: unknown) => typeof content === "string" ? content + : Array.isArray(content) ? content.filter((block) => block?.type === "text").map((block) => block.text).join("") : ""; + /** The queued message pi starts: steering goes first; text tells the queues apart unless a skill or template expanded it. */ + const takeQueued = (text: string): Named | null => { + for (const queue of [queued.steering, queued.followUp]) if (queue[0]?.text === text) return queue.shift()!; + for (const queue of [queued.steering, queued.followUp]) if (queue[0]?.text.startsWith("/")) return queue.shift()!; + return queued.steering.shift() ?? queued.followUp.shift() ?? null; + }; + const journaled = (ctx: PiContext) => { + const ids = new Map(), resolved = new Set(); + for (const entry of ctx.sessionManager?.getBranch?.() ?? []) { + const data = entry.data as { clientMessageId?: unknown; entryId?: unknown; clientMessageIds?: unknown } | undefined; + if (entry.type === "custom" && entry.customType === "client-message-entry" && typeof data?.clientMessageId === "string" && typeof data.entryId === "string") ids.set(data.clientMessageId, data.entryId); + if (entry.type === "custom" && entry.customType === "client-message-resolution" && Array.isArray(data?.clientMessageIds)) for (const id of data.clientMessageIds) resolved.add(String(id)); + } + return { ids, resolved }; + }; + + // Announced at start, so tau names the very first message (an adopted process proves itself by any reply). + pi.on("session_start", (_event, ctx) => emitTau(ctx, { type: "tau_hello" })); pi.registerCommand("tau_meta", { - description: "Attach clientMessageId/origin metadata to the next user message", - handler(args) { + description: "tau's message identity (name, status, clear)", + handler(args, ctx) { + let cmd: { action?: unknown; replyId?: unknown; clientMessageId?: unknown; text?: unknown; origin?: unknown; clientMessageIds?: unknown }; try { - const parsed = JSON.parse(args) as MessageMeta; - if (parsed && (parsed.clientMessageId || parsed.origin)) { - pendingMeta.push({ - ...(parsed.clientMessageId ? { clientMessageId: String(parsed.clientMessageId) } : {}), - ...(parsed.origin ? { origin: String(parsed.origin) } : {}), - }); - } + cmd = JSON.parse(args); } catch { - // Ignore malformed metadata payloads. + return; + } + const reply = (data: unknown) => emitTau(ctx, { type: "tau_reply", replyId: cmd.replyId, data }); + if (cmd.action === "name" && typeof cmd.clientMessageId === "string" && typeof cmd.text === "string") { + named.push({ clientMessageId: cmd.clientMessageId, text: cmd.text, ...(cmd.origin !== undefined ? { origin: cmd.origin } : {}) }); + return reply({ named: true }); + } + if (cmd.action === "clear") { + // tau took pi's queue back (clear_queue): those messages will never start. + const withdrawn = [...queued.steering, ...queued.followUp].map((item) => item.clientMessageId); + queued.steering = []; queued.followUp = []; + if (withdrawn.length) pi.appendEntry("client-message-resolution", { clientMessageIds: withdrawn }); + emitQueue(ctx); + return reply({ withdrawn }); + } + if (cmd.action === "status" && Array.isArray(cmd.clientMessageIds)) { + const asked = cmd.clientMessageIds.filter((id): id is string => typeof id === "string"); + const { ids, resolved } = journaled(ctx); + const pending = new Set([...named, ...queued.steering, ...queued.followUp, ...(starting ? [starting] : []), ...(current ? [current] : [])].map((item) => item.clientMessageId)); + const messages = asked.flatMap((clientMessageId) => { + const entry = ids.has(clientMessageId) ? ctx.sessionManager?.getEntry?.(ids.get(clientMessageId)!) : undefined; + return entry?.message ? [{ clientMessageId, message: entry.message }] : []; + }); + return reply({ + messages, + queuedMessages: { + steering: queued.steering.map((item) => item.text), followUp: queued.followUp.map((item) => item.text), + clientMessageIds: { steering: queued.steering.map((item) => item.clientMessageId), followUp: queued.followUp.map((item) => item.clientMessageId) }, + }, + persistedClientMessageIds: asked.filter((id) => ids.has(id)), + resolvedClientMessageIds: asked.filter((id) => resolved.has(id)), + unresolvedClientMessageIds: asked.filter((id) => pending.has(id) && !ids.has(id) && !resolved.has(id)), + }); } + reply(null); }, }); + pi.on("input", (event, ctx) => { + const index = named.findIndex((item) => item.text === event.text); + if (index === -1) return; + const item = named.splice(index, 1)[0]; + if (event.streamingBehavior === "steer") queued.steering.push(item); + else if (event.streamingBehavior === "followUp") queued.followUp.push(item); + else starting = item; + if (event.streamingBehavior) emitQueue(ctx); + }); + pi.on("message_start", (event, ctx) => { - const msg = event.message as { role?: string } | undefined; - if (msg?.role !== "user" || pendingMeta.length === 0) return; - const meta = pendingMeta.shift()!; - pi.appendEntry("tau_message_meta", meta); - ctx.ui.setStatus("tau-meta", JSON.stringify(meta)); + const message = event.message as { role?: string; content?: unknown } | undefined; + if (message?.role !== "user") return; + const wasQueued = !starting; + current = starting ?? takeQueued(textOf(message.content)); + starting = null; + if (!current) return; + emitTau(ctx, { type: "tau_message_identity", clientMessageId: current.clientMessageId, ...(current.origin !== undefined ? { origin: current.origin } : {}) }); + if (wasQueued) emitQueue(ctx); + }); + + pi.on("message_end", (event, ctx) => { + const message = event.message as { role?: string; timestamp?: unknown } | undefined; + if (message?.role !== "user" || !current) return; + const named = current; + current = null; + // pi stores the message after its message_end handlers: journal it once its entry exists (found by timestamp). + const journal = (attempt: number) => { + const entry = (ctx.sessionManager?.getBranch?.() ?? []).findLast((item) => item.type === "message" && item.message?.role === "user" + && (item.message as { timestamp?: unknown }).timestamp === message.timestamp) as (SessionEntry & { id?: string }) | undefined; + if (entry?.id) pi.appendEntry("client-message-entry", { clientMessageId: named.clientMessageId, entryId: entry.id, ...(named.origin !== undefined ? { origin: named.origin } : {}) }); + else if (attempt < 50) setTimeout(() => journal(attempt + 1), 20); + }; + setTimeout(() => journal(0), 0); }); // 4. /btw side questions: answered from the conversation so far with the session's model, never added to it. diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 519a3b60..d8ae4d3c 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -175,7 +175,6 @@ const PASSTHROUGH_COMMANDS = new Set([ "set_subagent_subscription", "get_login_providers", "login", - "get_client_message_status", ]); // Commands that can carry user-attached images to the model. All of them must @@ -2536,6 +2535,11 @@ export class AgentSessionWrapper { } /** `correlationKey`: the command a caller submitted through `send`; marked once its native message write begins. */ + /** pi's queue was taken back: the extension's names for it will never start (best effort; it journals them withdrawn). */ + private forgetQueuedNames(): void { + if (this.proc.tauExtension) void this.proc.callExtension("tau_meta", { action: "clear" }, GET_STATE_TIMEOUT_MS).catch(() => {}); + } + private async sendNativeMessageCommand(command: { type: string; [key: string]: unknown }, timeoutMs?: number, correlationKey?: object): Promise { const message = IMAGE_BEARING_COMMANDS.has(command.type); const proof = message && !this.messageReplacement && !this.hasPendingMessageCommands() @@ -2549,6 +2553,12 @@ export class AgentSessionWrapper { } const generation = this.messageCommandGeneration; try { + // pi keeps no client ids: the companion extension binds this name to the message pi admits next with this text. + if (message && this.proc.tauExtension && isClientMessageId(command.clientMessageId) && typeof command.message === "string") { + await this.proc.callExtension("tau_meta", { + action: "name", clientMessageId: command.clientMessageId, text: command.message, ...(isRecord(command.origin) ? { origin: command.origin } : {}), + }, GET_STATE_TIMEOUT_MS).catch(() => {}); + } const replacement = proof ?? this.messageReplacement; const result = await this.proc.sendCommand(command, timeoutMs, message && replacement ? (_ok, id) => replacement.replied(proof ? command : correlationKey ?? command, id) @@ -2702,9 +2712,14 @@ export class AgentSessionWrapper { // Like a control read, expiry must not abort unrelated work or replay a possibly applied mutation. case "clear_queue": { const result = await this.proc.sendCommand({ type: "clear_queue" }, GET_STATE_TIMEOUT_MS); + this.forgetQueuedNames(); return result ?? null; } + // The extension journals which messages pi persisted, queued or withdrew (`/tau_meta` status). + case "get_client_message_status": + return await this.proc.callExtension("tau_meta", { action: "status", clientMessageIds: command.clientMessageIds }, GET_STATE_TIMEOUT_MS); + // abort_and_restore_queue is the TUI's Esc: clear_queue before abort (pi runs a queued // message as soon as an abort lands), then report the withdrawn texts as entries. case "abort": @@ -2714,6 +2729,7 @@ export class AgentSessionWrapper { const result = await this.withFinalRunningNotification(async () => { const withdrawn = type === "abort" ? null : await this.proc.sendCommand<{ steering?: unknown; followUp?: unknown }>({ type: "clear_queue" }, GET_STATE_TIMEOUT_MS); + if (withdrawn) this.forgetQueuedNames(); try { await this.proc.sendCommand({ type: "abort" }); } catch (error) { From c8206a5a1442b61f50e9c4f09ad1dbef9e753ddf Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 23:08:05 +0000 Subject: [PATCH 018/129] test: give every test process its own temp directory A test body still running after its environment was restored (a timeout under --parallel, a late timer) wrote the self-update state into the machine's real /ompweb-self-update-, which blocked a real server's host daemon start; update-policy.test.mjs wrote mutation.sqlite there on every run. --- bunfig.toml | 3 +++ tests/isolate-tmp.mjs | 14 ++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 tests/isolate-tmp.mjs diff --git a/bunfig.toml b/bunfig.toml index 3caa0370..63d1bb4f 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -2,3 +2,6 @@ [serve.static] plugins = ["./scripts/tailwind-plugin.ts"] env = "OMP_WEB_PUBLIC_*" + +[test] +preload = ["./tests/isolate-tmp.mjs"] diff --git a/tests/isolate-tmp.mjs b/tests/isolate-tmp.mjs new file mode 100644 index 00000000..cac81f29 --- /dev/null +++ b/tests/isolate-tmp.mjs @@ -0,0 +1,14 @@ +// Preloaded by every test process (bunfig.toml [test]): os.tmpdir() points into a directory of this process's own, so +// state a test writes after it restored the environment (a body still running past its timeout, a late timer) lands +// there and not in the machine's real temp directory, where a running server would read it (the self-update root +// `/ompweb-self-update-`). Removed once the file's tests end. +import { afterAll } from "bun:test"; +import { chmodSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const root = mkdtempSync(join(tmpdir(), "t-")); +// Like /tmp: tests that drop to another user (file-access.permissions) still need to reach their fixtures. +chmodSync(root, 0o1777); +for (const name of ["TMPDIR", "TEMP", "TMP"]) process.env[name] = root; +afterAll(() => rmSync(root, { recursive: true, force: true })); From 6d3eb88c3f0cc5a39e1ff42559797ed36af44e83 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 23:45:56 +0000 Subject: [PATCH 019/129] refactor(self-update): name the temporary update root tau-self-update --- lib/self-update-state.ts | 2 +- tests/isolate-tmp.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/self-update-state.ts b/lib/self-update-state.ts index 137df9fa..0077b748 100644 --- a/lib/self-update-state.ts +++ b/lib/self-update-state.ts @@ -45,7 +45,7 @@ export function resolveSelfUpdateTempRoot( ): string { const pathApi = platform === "win32" ? win32 : posix; const suffix = platform === "win32" ? "" : `-${uid ?? "user"}`; - return pathApi.join(temporary, `ompweb-self-update${suffix}`); + return pathApi.join(temporary, `tau-self-update${suffix}`); } export const rootDir = (): string => resolveSelfUpdateTempRoot(); diff --git a/tests/isolate-tmp.mjs b/tests/isolate-tmp.mjs index cac81f29..4b6c0f22 100644 --- a/tests/isolate-tmp.mjs +++ b/tests/isolate-tmp.mjs @@ -1,7 +1,7 @@ // Preloaded by every test process (bunfig.toml [test]): os.tmpdir() points into a directory of this process's own, so // state a test writes after it restored the environment (a body still running past its timeout, a late timer) lands // there and not in the machine's real temp directory, where a running server would read it (the self-update root -// `/ompweb-self-update-`). Removed once the file's tests end. +// `/tau-self-update-`). Removed once the file's tests end. import { afterAll } from "bun:test"; import { chmodSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; From dcb912967a1e01b0fe9d9675781a32b4abad6f77 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 23:58:38 +0000 Subject: [PATCH 020/129] refactor: rename ompweb names to tau Rename the remaining omp-web/ompweb product names in code, tests, scripts and CI: bin files and the tau CLI, TAU_* environment variables, the tau state directory and file names, browser storage keys, cookies and headers, service labels (dev.ompweb.tau, dev.ompweb.tau-host, tau.service, tau-host.service), and the default ports 30187 (production) and 30188 (dev). --- .github/workflows/prerelease.yml | 6 +- .github/workflows/publish.yml | 10 +- .github/workflows/verify-pr.yml | 38 ++-- .serena/project.yml | 2 +- app/api/auth/all-providers/route.ts | 2 +- app/api/auth/api-key/[provider]/route.ts | 6 +- app/api/hosts/[id]/cluster/route.ts | 6 +- app/api/hosts/[id]/updates/route.ts | 2 +- app/api/hosts/broker/[...path]/route.ts | 2 +- app/api/hosts/link/route.ts | 2 +- app/api/hosts/maintenance/route.ts | 2 +- app/api/hosts/route.ts | 6 +- app/api/manifest/route.ts | 4 +- app/api/models-config/catalog/route.ts | 6 +- app/api/models-config/route.ts | 2 +- app/api/models-config/test/route.ts | 6 +- app/api/omp-update/route.ts | 2 +- app/api/omp-version/route.ts | 2 +- app/api/plugins/route.ts | 2 +- app/api/sessions/[id]/route.ts | 4 +- app/api/stt/[jobId]/route.ts | 2 +- app/api/stt/route.ts | 2 +- app/api/transport-metrics/route.ts | 2 +- app/api/web-auth/session/route.ts | 8 +- app/api/web-settings/route.ts | 2 +- app/globals.css | 6 +- app/index.html | 2 +- bin/bun-runtime.js | 2 +- bin/generate-release-notes.js | 2 +- bin/linux-tray.js | 124 +++++------ bin/linux-tray.test.mjs | 50 ++--- bin/network-addresses.js | 8 +- bin/node-version-gate.test.mjs | 2 +- bin/node-version.js | 2 +- bin/service-env.js | 2 +- ...-hash-password.js => tau-hash-password.js} | 14 +- ...rd.test.mjs => tau-hash-password.test.mjs} | 4 +- bin/{omp-web-host.js => tau-host.js} | 10 +- ...mp-web-host.test.mjs => tau-host.test.mjs} | 38 ++-- bin/{omp-web-launchd.js => tau-launchd.js} | 66 +++--- ...-launchd.test.mjs => tau-launchd.test.mjs} | 16 +- bin/{omp-web-options.js => tau-options.js} | 74 +++---- ...-password-hash.js => tau-password-hash.js} | 4 +- ...ecurity.test.mjs => tau-security.test.mjs} | 22 +- bin/{omp-web-systemd.js => tau-systemd.js} | 114 +++++----- ...-systemd.test.mjs => tau-systemd.test.mjs} | 198 ++++++++--------- bin/{omp-web-tray.exe => tau-tray.exe} | Bin bin/{omp-web-tray.js => tau-tray.js} | 16 +- ...mp-web-tray.test.mjs => tau-tray.test.mjs} | 4 +- bin/{omp-web.js => tau.js} | 52 ++--- bunfig.toml | 2 +- components/AppShell-app-update.ts | 4 +- components/AppShell-layout.tsx | 4 +- components/AppShell.tsx | 20 +- components/ChatInput.btw.test.mjs | 4 +- .../ChatInput.queue-attachments.test.mjs | 4 +- components/ChatInput.uploads.test.mjs | 8 +- components/ChatWindow.tsx | 10 +- components/ComposerPanels.tsx | 4 +- components/ConnectionDiagnostics.test.mjs | 4 +- components/ExtensionDialog.form.test.mjs | 4 +- components/ExtensionDialog.test.mjs | 6 +- components/FileViewer.markdown-links.test.mjs | 2 +- components/FileViewer.tsx | 2 +- components/HostUpdates.test.mjs | 34 +-- components/HostUpdates.tsx | 6 +- components/HostsConfig.cluster.test.mjs | 26 +-- components/HostsConfig.test.mjs | 68 +++--- components/HostsConfig.tsx | 2 +- components/LocalDaemonBanner.test.mjs | 8 +- components/LocalDaemonBanner.tsx | 6 +- components/MarkdownBody.tsx | 2 +- components/MessageView.test.mjs | 4 +- components/MessageView.tsx | 2 +- components/ModelsConfig-panels.tsx | 2 +- components/NotificationList.test.mjs | 2 +- components/OriginMessageView.tsx | 2 +- components/ProviderUsageBar.tsx | 4 +- components/SessionSidebar-chrome.tsx | 14 +- components/SessionSidebar-helpers.ts | 6 +- components/SessionSidebar.tsx | 8 +- components/SettingsConfig.cluster.test.mjs | 2 +- components/SettingsConfig.tsx | 18 +- components/SettingsConfig.updates.test.mjs | 10 +- components/{OmpWebLogo.tsx => TauLogo.tsx} | 2 +- components/host-status.ts | 6 +- hooks/useAgentSession-queue.ts | 2 +- hooks/useAgentSession-stream.ts | 8 +- hooks/useAgentSession.rpc.test.mjs | 22 +- hooks/useAgentSession.ts | 20 +- hooks/useChatSearchHighlights.ts | 4 +- hooks/useDictation.migration.test.mjs | 8 +- hooks/useDictation.ts | 4 +- hooks/useSidebarHistory.ts | 2 +- hooks/useTheme.test.mjs | 12 +- hooks/useTheme.ts | 2 +- instrumentation.node.ts | 32 +-- lib/agent-client.test.mjs | 8 +- lib/agent-client.ts | 4 +- lib/agent-command.test.mjs | 4 +- lib/agent-command.ts | 4 +- lib/agent-links.ts | 2 +- lib/agent-tools.test.mjs | 14 +- lib/agent-tools.ts | 14 +- lib/api-contract.test.mjs | 16 +- lib/app-update-route.test.mjs | 6 +- lib/archive-restore-lock.test.mjs | 28 +-- lib/archive-restore-lock.ts | 2 +- lib/auth-login-route.test.mjs | 2 +- lib/bash-output.test.mjs | 6 +- lib/browser-link.integration.test.mjs | 2 +- lib/browser-link.test.mjs | 18 +- lib/browser-link.ts | 6 +- lib/chat-attachments.ts | 2 +- lib/chat-transcript-plan.test.mjs | 2 +- lib/chat-transcript-plan.ts | 2 +- lib/child-process-env.test.mjs | 12 +- lib/compiled-upgrade.integration.test.mjs | 48 ++--- lib/composer-prefs.test.mjs | 2 +- lib/composer-prefs.ts | 4 +- lib/connection-diagnostics-prefs.ts | 6 +- lib/directory-browser.test.mjs | 4 +- lib/event-stream-hub.test.mjs | 12 +- lib/event-stream-hub.ts | 2 +- lib/event-stream-worker.test.mjs | 10 +- lib/event-stream-worker.ts | 10 +- lib/event-stream.test.mjs | 18 +- lib/event-stream.ts | 18 +- lib/file-access.permissions.test.mjs | 4 +- lib/file-access.test.mjs | 26 +-- lib/file-dirent.test.mjs | 4 +- lib/file-index-route.test.mjs | 12 +- lib/file-types.ts | 2 +- lib/file-upload.test.mjs | 4 +- lib/github/action-receipts.ts | 2 +- lib/github/action-tools.ts | 4 +- lib/github/events.test.mjs | 2 +- lib/github/events.ts | 4 +- lib/github/gh.test.mjs | 4 +- lib/github/gh.ts | 4 +- lib/github/tools.test.mjs | 10 +- lib/github/tools.ts | 2 +- lib/github/watch-store.test.mjs | 12 +- lib/github/watch-store.ts | 12 +- lib/github/watcher.test.mjs | 24 +-- lib/github/watcher.ts | 10 +- lib/hosts/broker-route.test.mjs | 26 +-- lib/hosts/channel-lifecycle.ts | 2 +- lib/hosts/cluster-config-route.test.mjs | 14 +- lib/hosts/cluster-config-server.ts | 6 +- lib/hosts/cluster-config.test.mjs | 2 +- lib/hosts/cluster-route.test.mjs | 14 +- lib/hosts/cluster.test.mjs | 4 +- lib/hosts/cluster.ts | 2 +- lib/hosts/daemon-broker.test.mjs | 12 +- lib/hosts/daemon-channels.ts | 4 +- lib/hosts/daemon-cluster-config.test.mjs | 14 +- lib/hosts/daemon-cluster-config.ts | 2 +- lib/hosts/daemon-link.ts | 10 +- lib/hosts/daemon-runtime.test.mjs | 22 +- lib/hosts/daemon-update-safety.test.mjs | 38 ++-- lib/hosts/daemon.test.mjs | 52 ++--- lib/hosts/daemon.ts | 20 +- lib/hosts/files-owner.integration.test.mjs | 16 +- lib/hosts/host-cli.ts | 14 +- lib/hosts/host-control.test.mjs | 10 +- lib/hosts/host-control.ts | 8 +- lib/hosts/host-login.test.mjs | 6 +- lib/hosts/host-login.ts | 4 +- lib/hosts/host-resume.ts | 2 +- lib/hosts/host-update-e2e.test.mjs | 18 +- lib/hosts/host-updates-route.test.mjs | 52 ++--- lib/hosts/hosts-route.test.mjs | 14 +- lib/hosts/hub-v7.test.mjs | 10 +- lib/hosts/hub.test.mjs | 12 +- lib/hosts/hub.ts | 92 ++++---- lib/hosts/legacy-recovery.test.mjs | 56 ++--- lib/hosts/legacy-recovery.ts | 58 ++--- lib/hosts/legacy-upgrades.test.mjs | 60 +++--- lib/hosts/legacy-upgrades.ts | 10 +- lib/hosts/link-driver.test-helper.mjs | 6 +- lib/hosts/link-integration.test.mjs | 14 +- lib/hosts/link-protocol.ts | 6 +- lib/hosts/local-bootstrap.test.mjs | 38 ++-- lib/hosts/local-bootstrap.ts | 8 +- lib/hosts/local-daemon-start.test.mjs | 24 +-- lib/hosts/local-daemon-start.ts | 8 +- lib/hosts/local-daemon-supervisor.test.mjs | 130 +++++------ lib/hosts/local-daemon-supervisor.ts | 18 +- lib/hosts/local-host-profile.test.mjs | 14 +- .../maintenance-daemon.integration.test.mjs | 14 +- lib/hosts/maintenance-hub.test.mjs | 12 +- lib/hosts/maintenance-hub.ts | 16 +- lib/hosts/maintenance-protocol.test.mjs | 4 +- lib/hosts/maintenance-protocol.ts | 8 +- lib/hosts/maintenance-transport.test.mjs | 4 +- lib/hosts/multi-server.integration.test.mjs | 14 +- lib/hosts/pool-selection.test.mjs | 4 +- lib/hosts/pool-starts.test.mjs | 14 +- lib/hosts/pool-starts.ts | 4 +- lib/hosts/pools.ts | 4 +- lib/hosts/preflight.test.mjs | 4 +- lib/hosts/preflight.ts | 8 +- lib/hosts/recovery.test.mjs | 38 ++-- lib/hosts/recovery.ts | 26 +-- lib/hosts/registry.test.mjs | 4 +- lib/hosts/registry.ts | 6 +- lib/hosts/release-pin-routing.test.mjs | 30 +-- lib/hosts/session-index.test.mjs | 12 +- lib/hosts/session-ops-archive.test.mjs | 10 +- lib/hosts/session-ops.test.mjs | 2 +- lib/hosts/session-ops.ts | 4 +- lib/hosts/update-decision.test.mjs | 4 +- lib/hosts/update-fixture.test-helper.mjs | 22 +- lib/hosts/update-types.ts | 6 +- lib/hosts/update-worker.test.mjs | 94 ++++---- lib/hosts/update-worker.ts | 66 +++--- lib/hosts/updates.test.mjs | 204 +++++++++--------- lib/hosts/updates.ts | 42 ++-- lib/hosts/upgrade-shim.test.mjs | 14 +- lib/hosts/upload-retention-sync.test.mjs | 2 +- lib/hosts/upload-retention-sync.ts | 2 +- lib/hosts/upload-retention.test.mjs | 10 +- lib/hosts/upload-retention.ts | 8 +- lib/hosts/uploads.test.mjs | 2 +- lib/hosts/uploads.ts | 10 +- lib/hosts/workspace-test-helper.mjs | 8 +- lib/i18n/locales/en.json | 98 ++++----- lib/i18n/locales/ja.json | 98 ++++----- lib/i18n/locales/zh-CN.json | 98 ++++----- lib/i18n/locales/zh-TW.json | 98 ++++----- lib/install-name.test.mjs | 30 +-- lib/install-name.ts | 6 +- lib/instrumentation-crash-policy.test.mjs | 8 +- lib/local-uri.test.mjs | 2 +- lib/local-uri.ts | 2 +- lib/manifest-route.test.mjs | 14 +- lib/manifest-theme.ts | 2 +- lib/media-cache.ts | 10 +- lib/media-route.test.mjs | 8 +- lib/message-origin.test.mjs | 4 +- lib/message-origin.ts | 4 +- lib/message-outbox-review.test.mjs | 6 +- lib/message-outbox.test.mjs | 28 +-- lib/message-outbox.ts | 32 +-- lib/model-catalog.ts | 2 +- lib/navigation-history.ts | 2 +- lib/network-addresses.test.mjs | 12 +- lib/notification-events.test.mjs | 2 +- lib/notification-events.ts | 8 +- lib/notification-history-route.test.mjs | 2 +- lib/notification-hub.test.mjs | 8 +- lib/notification-hub.ts | 2 +- lib/notification-store.test.mjs | 24 +-- lib/notification-store.ts | 8 +- lib/notification-sw.test.mjs | 10 +- lib/npm-update.test.mjs | 4 +- lib/npm-update.ts | 2 +- lib/omp/agent-env-policy.ts | 12 +- lib/omp/agent-env.test.mjs | 20 +- lib/omp/agent-env.ts | 4 +- lib/omp/archive.test.mjs | 24 +-- lib/omp/archive.ts | 2 +- lib/omp/auth-broker.test.mjs | 6 +- lib/omp/mcp-config.test.mjs | 2 +- lib/omp/mcp-config.ts | 4 +- lib/omp/models-config.test.mjs | 2 +- lib/omp/models-config.ts | 2 +- lib/omp/omp-cli.test.mjs | 16 +- lib/omp/omp-cli.ts | 4 +- lib/omp/paths.ts | 6 +- lib/omp/plugins-cli.test.mjs | 14 +- lib/omp/rpc-process.ts | 2 +- lib/omp/session-archive.test.mjs | 4 +- lib/omp/session-files.ts | 12 +- lib/omp/settings-config.test.mjs | 2 +- lib/outbox-handoff.test.mjs | 2 +- lib/pi-types.ts | 8 +- lib/pooled-projects.ts | 2 +- lib/project-clone.ts | 2 +- lib/project-command-env.test.mjs | 70 +++--- lib/project-command-env.ts | 36 ++-- lib/project-registry.test.mjs | 12 +- lib/provider-usage.test.mjs | 10 +- lib/provider-usage.ts | 2 +- lib/recent-runs.ts | 2 +- lib/recovery-release.test.mjs | 10 +- lib/recovery-release.ts | 4 +- lib/release-repo.ts | 2 +- lib/request-security.test.mjs | 6 +- lib/request-security.ts | 2 +- lib/rpc-manager.test.mjs | 98 ++++----- lib/rpc-manager.ts | 70 +++--- lib/self-update.test.mjs | 56 ++--- lib/self-update.ts | 22 +- lib/server-update-worker.test.mjs | 30 +-- lib/server-update-worker.ts | 20 +- lib/session-local-files.test.mjs | 2 +- lib/session-reader.test.mjs | 52 ++--- lib/session-reader.ts | 4 +- lib/session-resume.test.mjs | 18 +- lib/session-resume.ts | 14 +- lib/session-routes.test.mjs | 32 +-- lib/session-search-matches.test.mjs | 2 +- lib/session-search.test.mjs | 10 +- lib/session-watcher.ts | 2 +- lib/skill-updates.ts | 4 +- lib/skills-service.test.mjs | 14 +- lib/skills-service.ts | 4 +- lib/stt-jobs.ts | 6 +- lib/stt-route.test.mjs | 52 ++--- lib/subagent-history.test.mjs | 18 +- lib/subagent-history.ts | 2 +- ...-options.test.mjs => tau-options.test.mjs} | 38 ++-- lib/tool-preset-preference.test.mjs | 2 +- lib/tool-preset-preference.ts | 2 +- lib/transport-metrics.test.mjs | 4 +- lib/transport-metrics.ts | 2 +- lib/types.ts | 6 +- lib/update-policy.test.mjs | 2 +- lib/update-policy.ts | 2 +- lib/upgrade-directory.windows.test.mjs | 6 +- lib/upgrade-plan-coordinator.test.mjs | 48 ++--- lib/upgrade-plan.test.mjs | 4 +- lib/upgrade-plan.ts | 44 ++-- lib/upgrade-process.launchd.test.mjs | 2 +- lib/upgrade-process.test.mjs | 18 +- lib/upgrade-process.ts | 18 +- lib/upgrade-process.windows-service.test.mjs | 26 +-- lib/uploads.test.mjs | 36 ++-- lib/usage-db.test.mjs | 2 +- lib/usage-service.test.mjs | 2 +- lib/usage-service.ts | 2 +- lib/user-level-config-routes.test.mjs | 6 +- lib/web-auth-secret.ts | 4 +- lib/web-auth.test.mjs | 120 +++++------ lib/web-auth.ts | 36 ++-- lib/web-password-hash.test.mjs | 2 +- lib/web-password-hash.ts | 10 +- lib/web-settings.test.mjs | 56 ++--- lib/web-settings.ts | 16 +- lib/web-slash-commands.ts | 2 +- lib/windows-service.test.mjs | 38 ++-- lib/windows-service.ts | 54 ++--- lib/workspace-memory.ts | 2 +- lib/worktree.test.mjs | 6 +- native/tray/Program.cs | 58 ++--- native/tray/tray.csproj | 4 +- nix/package.nix | 2 +- package-lock.json | 10 +- package.json | 34 +-- proxy.ts | 10 +- public/icon.svg | 4 +- public/sw.js | 12 +- public/{omp-web-logo.svg => tau-logo.svg} | 4 +- public/{omp-web.ico => tau.ico} | Bin scripts/build-binary.ts | 12 +- scripts/build-release-binaries.sh | 6 +- scripts/check-host-release-archive.ts | 4 +- scripts/licenses.ts | 4 +- scripts/link-hol-probe.ts | 14 +- scripts/macos-launchd.mts | 64 +++--- scripts/smoke.ts | 26 +-- scripts/transport-metrics.test.ts | 2 +- scripts/windows/install-tray.ps1 | 46 ++-- scripts/windows/launch-tray.vbs | 2 +- .../{omp-web-host.ps1 => tau-host.ps1} | 16 +- .../{omp-web-service.ps1 => tau-service.ps1} | 44 ++-- .../{omp-web-tray.ps1 => tau-tray.ps1} | 78 +++---- scripts/windows/uninstall-tray.ps1 | 30 +-- server/app.test.ts | 66 +++--- server/app.ts | 12 +- server/binary.ts | 28 +-- server/client-env.test.ts | 54 ++--- server/client-env.ts | 8 +- server/dev.test.ts | 14 +- server/dev.ts | 18 +- server/http.test.ts | 20 +- server/main.ts | 4 +- tests/compiled-upgrade-fixture.mjs | 4 +- tests/fixtures/multi-server-omp.mjs | 2 +- 381 files changed, 3157 insertions(+), 3157 deletions(-) rename bin/{omp-web-hash-password.js => tau-hash-password.js} (89%) rename bin/{omp-web-hash-password.test.mjs => tau-hash-password.test.mjs} (90%) rename bin/{omp-web-host.js => tau-host.js} (53%) rename bin/{omp-web-host.test.mjs => tau-host.test.mjs} (88%) rename bin/{omp-web-launchd.js => tau-launchd.js} (76%) rename bin/{omp-web-launchd.test.mjs => tau-launchd.test.mjs} (73%) rename bin/{omp-web-options.js => tau-options.js} (67%) rename bin/{omp-web-password-hash.js => tau-password-hash.js} (96%) rename bin/{omp-web-security.test.mjs => tau-security.test.mjs} (72%) rename bin/{omp-web-systemd.js => tau-systemd.js} (83%) rename bin/{omp-web-systemd.test.mjs => tau-systemd.test.mjs} (67%) rename bin/{omp-web-tray.exe => tau-tray.exe} (100%) rename bin/{omp-web-tray.js => tau-tray.js} (95%) rename bin/{omp-web-tray.test.mjs => tau-tray.test.mjs} (93%) rename bin/{omp-web.js => tau.js} (82%) rename components/{OmpWebLogo.tsx => TauLogo.tsx} (96%) rename lib/{omp-web-options.test.mjs => tau-options.test.mjs} (73%) rename public/{omp-web-logo.svg => tau-logo.svg} (73%) rename public/{omp-web.ico => tau.ico} (100%) rename scripts/windows/{omp-web-host.ps1 => tau-host.ps1} (79%) rename scripts/windows/{omp-web-service.ps1 => tau-service.ps1} (86%) rename scripts/windows/{omp-web-tray.ps1 => tau-tray.ps1} (90%) diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index b5158c36..d8d99d1e 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -50,9 +50,9 @@ jobs: echo "RELEASE_TAG=$(date -u -d "@$now" +%Y%m%dT%H%M%SZ)-$(git rev-parse --short=10 "$SHA")" >> "$GITHUB_ENV" - name: Build the release binaries env: - OMP_WEB_RELEASE_TAG: ${{ env.RELEASE_TAG }} + TAU_RELEASE_TAG: ${{ env.RELEASE_TAG }} run: sh scripts/build-release-binaries.sh - - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb + - run: npm run smoke -- --binary release/tau-linux-x64/tau - name: Publish the prerelease env: @@ -62,7 +62,7 @@ jobs: tag="$RELEASE_TAG" subject=$(git log -1 --format=%s "$SHA") # A draft first, so a failed upload never leaves a published prerelease missing archives. - gh release create "$tag" release/ompweb-*.tar.gz release/ompweb-*.zip \ + gh release create "$tag" release/tau-*.tar.gz release/tau-*.zip \ --repo "$GITHUB_REPOSITORY" --target "$SHA" --draft --prerelease --title "$title" \ --notes "Binaries built from $GITHUB_REPOSITORY@$SHA ($subject), tested with pi $PI_VERSION. Not a release: no npm package, no update notice." gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --draft=false diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a1655743..cdca70f2 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -42,14 +42,14 @@ jobs: - name: Allow isolated native fixture scopes run: | rule="polkit.addRule(function(action, subject) { if (action.id === 'org.freedesktop.systemd1.manage-units' && subject.user === '$(id -un)' && /\\.scope$/.test(action.lookup('unit') || '')) { return polkit.Result.YES; } });" - printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-ompweb-fixture-scopes.rules >/dev/null + printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-tau-fixture-scopes.rules >/dev/null systemd-run --scope --quiet --collect --no-ask-password true - run: npm test - run: npm run build - name: Build the release binaries run: sh scripts/build-release-binaries.sh - run: npm run smoke - - run: npm run smoke -- --binary release/ompweb-linux-x64/ompweb + - run: npm run smoke -- --binary release/tau-linux-x64/tau - name: Create draft GitHub Release env: @@ -64,7 +64,7 @@ jobs: - name: Attach the binaries to the draft release env: GH_TOKEN: ${{ github.token }} - run: gh release upload "$TAG" release/ompweb-*.tar.gz release/ompweb-*.zip --repo "$GITHUB_REPOSITORY" --clobber + run: gh release upload "$TAG" release/tau-*.tar.gz release/tau-*.zip --repo "$GITHUB_REPOSITORY" --clobber - name: Publish GitHub Release env: @@ -100,10 +100,10 @@ jobs: jq -n \ --arg body "$(jq -r '.body' <<<"$RELEASE_JSON")" \ - --arg title "OMPWEB $TAG" \ + --arg title "tau $TAG" \ --arg url "$(jq -r '.url' <<<"$RELEASE_JSON")" \ '{ - username: "OMPWEB Releases", + username: "tau Releases", embeds: [{ title: $title, url: $url, diff --git a/.github/workflows/verify-pr.yml b/.github/workflows/verify-pr.yml index d0647c10..52fc8642 100644 --- a/.github/workflows/verify-pr.yml +++ b/.github/workflows/verify-pr.yml @@ -67,7 +67,7 @@ jobs: if: runner.os == 'Linux' run: | rule="polkit.addRule(function(action, subject) { if (action.id === 'org.freedesktop.systemd1.manage-units' && subject.user === '$(id -un)' && /\\.scope$/.test(action.lookup('unit') || '')) { return polkit.Result.YES; } });" - printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-ompweb-fixture-scopes.rules >/dev/null + printf '%s\n' "$rule" | sudo tee /etc/polkit-1/rules.d/49-tau-fixture-scopes.rules >/dev/null systemd-run --scope --quiet --collect --no-ask-password true # Do not pass pwsh's Core module search path to Windows PowerShell children used by the native tests. @@ -93,60 +93,60 @@ jobs: run: npm run smoke # The release binary for this runner (the -baseline x64 build releases ship), from the client built above, with its - # own `ompweb host` daemon (scripts/build-binary.ts). + # own `tau host` daemon (scripts/build-binary.ts). - name: Binary smoke test shell: bash run: | if [ "$RUNNER_OS" = Windows ]; then npx bun scripts/build-binary.ts --target bun-windows-x64-baseline - bin=release/ompweb-windows-x64/ompweb.exe - archive=release/ompweb-windows-x64.zip + bin=release/tau-windows-x64/tau.exe + archive=release/tau-windows-x64.zip elif [ "$RUNNER_OS" = macOS ]; then arch=$(node -p process.arch) target="bun-darwin-$arch" if [ "$arch" = x64 ]; then target="$target-baseline"; fi npx bun scripts/build-binary.ts --target "$target" - bin="release/ompweb-darwin-$arch/ompweb" - archive="release/ompweb-darwin-$arch.tar.gz" + bin="release/tau-darwin-$arch/tau" + archive="release/tau-darwin-$arch.tar.gz" else npx bun scripts/build-binary.ts --target bun-linux-x64-baseline - bin=release/ompweb-linux-x64/ompweb - archive=release/ompweb-linux-x64.tar.gz + bin=release/tau-linux-x64/tau + archive=release/tau-linux-x64.tar.gz fi # The archive a host downloads must pass the updater's own size limits and checks. npx bun scripts/check-host-release-archive.ts "$archive" npm run smoke -- --binary "$bin" # What the host updater checks on a new release before it switches (lib/hosts/update-worker.ts): the marker # it finds the command by, then the command itself against the pi on PATH. - grep -qa ompweb-preflight-scratch- "$bin" + grep -qa tau-preflight-scratch- "$bin" node -e 'require("node:child_process").execFileSync(process.argv[1], ["preflight"], {stdio:"inherit",timeout:120000})' "$bin" # Required on every supported runner, including macOS foreground. A skip fails the job. - name: Native compiled coordinated upgrade and rollback shell: bash env: - OMPWEB_COMPILED_UPGRADE_E2E: "1" + TAU_COMPILED_UPGRADE_E2E: "1" run: npx bun test --parallel --timeout 900000 lib/compiled-upgrade.integration.test.mjs - name: Packed install smoke test shell: bash run: | npm pack --ignore-scripts - npm install -g --prefix "$RUNNER_TEMP/ompweb-prefix" ./ompweb-dev-tau-*.tgz - npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix")/@ompweb-dev/tau" + npm install -g --prefix "$RUNNER_TEMP/tau-prefix" ./ompweb-dev-tau-*.tgz + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/tau-prefix")/@ompweb-dev/tau" # Bun's postinstall does not run here: the launcher must fall back to @oven/bun-- (spec R1). - name: Packed install smoke test (install scripts disabled) shell: bash run: | - npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts" ./ompweb-dev-tau-*.tgz - npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/ompweb-prefix-no-scripts")/@ompweb-dev/tau" + npm install -g --ignore-scripts --prefix "$RUNNER_TEMP/tau-prefix-no-scripts" ./ompweb-dev-tau-*.tgz + npm run smoke -- --package "$(npm root -g --prefix "$RUNNER_TEMP/tau-prefix-no-scripts")/@ompweb-dev/tau" - name: Parse Windows PowerShell scripts (Windows only) if: runner.os == 'Windows' shell: pwsh run: | - foreach ($f in 'scripts/windows/omp-web-service.ps1', 'scripts/windows/omp-web-tray.ps1') { + foreach ($f in 'scripts/windows/tau-service.ps1', 'scripts/windows/tau-tray.ps1') { $e = $null [System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path $f).Path, [ref]$null, [ref]$e) | Out-Null if ($e) { $e; exit 1 } @@ -155,10 +155,10 @@ jobs: - name: Verify Windows System Tray & Shortcuts (Windows only) if: runner.os == 'Windows' run: | - node bin/omp-web-tray.js --status - node bin/omp-web-tray.js --install - node bin/omp-web-tray.js --status - node bin/omp-web-tray.js --uninstall + node bin/tau-tray.js --status + node bin/tau-tray.js --install + node bin/tau-tray.js --status + node bin/tau-tray.js --uninstall pr-rules: name: PR Rules & Quality Gates diff --git a/.serena/project.yml b/.serena/project.yml index b0471a36..705fe87d 100644 --- a/.serena/project.yml +++ b/.serena/project.yml @@ -1,5 +1,5 @@ # the name by which the project can be referenced within Serena/when chatting with the LLM. -project_name: "ompweb" +project_name: "tau" # list of language servers to start when using the LSP backend; choose from: # ada al angular ansible astro diff --git a/app/api/auth/all-providers/route.ts b/app/api/auth/all-providers/route.ts index 166e399f..0efa182d 100644 --- a/app/api/auth/all-providers/route.ts +++ b/app/api/auth/all-providers/route.ts @@ -2,7 +2,7 @@ import { readModelsConfig } from "@/lib/omp/models-config"; import { type OmpLoginProvider, type OmpModel, runUtilityCommand } from "@/lib/omp/rpc-utility"; // omp exposes no "all known providers" query over RPC, and API keys live in -// its SQLite credential store which omp-web must not touch. What we CAN see is +// its SQLite credential store which tau must not touch. What we CAN see is // which providers currently resolve models (env keys, stored keys, models.yml) // via get_available_models — so this endpoint lists configured providers only. // Unconfigured API-key providers cannot be set up from the web UI (see the diff --git a/app/api/auth/api-key/[provider]/route.ts b/app/api/auth/api-key/[provider]/route.ts index f786d56e..ee87d966 100644 --- a/app/api/auth/api-key/[provider]/route.ts +++ b/app/api/auth/api-key/[provider]/route.ts @@ -4,7 +4,7 @@ import { type OmpLoginProvider, type OmpModel, runUtilityCommand } from "@/lib/o type Params = { params: Promise<{ provider: string }> }; // omp stores API keys in its encrypted SQLite credential store (agent.db), -// which omp-web must never write from Node, and the omp RPC login command only +// which tau must never write from Node, and the omp RPC login command only // bridges browser-based flows (providers that prompt for a key before opening // a URL are rejected by omp's RPC mode). Keys therefore cannot be stored or // removed from the web UI. @@ -42,7 +42,7 @@ export async function GET(_req: Request, { params }: Params) { export async function POST(_req: Request, { params }: Params) { const { provider } = await params; return Response.json( - { error: `Cannot store an API key for "${provider}" from omp-web. ${API_KEY_WRITE_GUIDANCE}`, code: "api_key_store_unsupported" }, + { error: `Cannot store an API key for "${provider}" from tau. ${API_KEY_WRITE_GUIDANCE}`, code: "api_key_store_unsupported" }, { status: 501 }, ); } @@ -51,7 +51,7 @@ export async function POST(_req: Request, { params }: Params) { export async function DELETE(_req: Request, { params }: Params) { const { provider } = await params; return Response.json( - { error: `Cannot remove the API key for "${provider}" from omp-web. ${API_KEY_WRITE_GUIDANCE}`, code: "api_key_remove_unsupported" }, + { error: `Cannot remove the API key for "${provider}" from tau. ${API_KEY_WRITE_GUIDANCE}`, code: "api_key_remove_unsupported" }, { status: 501 }, ); } diff --git a/app/api/hosts/[id]/cluster/route.ts b/app/api/hosts/[id]/cluster/route.ts index fb7efe06..dffad7e6 100644 --- a/app/api/hosts/[id]/cluster/route.ts +++ b/app/api/hosts/[id]/cluster/route.ts @@ -21,7 +21,7 @@ const MAX_ORIGIN_PATHS = 500; const MAX_ORIGIN_PATH_LENGTH = 4096; const noStore = { "cache-control": "no-store" }; const fail = (error: string, code: string, status: number) => Response.json({ error, code }, { status, headers: noStore }); -const storageFailure = () => fail("The pool registry (omp-web/pools.json) cannot be read or written; fix it before changing the cluster", "pool_storage_unavailable", 503); +const storageFailure = () => fail("The pool registry (tau/pools.json) cannot be read or written; fix it before changing the cluster", "pool_storage_unavailable", 503); function errorResponse(error: unknown): Response { if (error instanceof HostOpError) return fail(error.message, error.code, error.status); if (error instanceof ClusterError) return fail(error.message, error.code, 409); @@ -53,8 +53,8 @@ function requireReady(host: Host): void { if (block === "omp-old") throw new HostOpError(409, "host_omp_too_old", `Update omp on ${host.label} to ${MIN_SHARED_CREDENTIALS_OMP} or newer first`); if (block !== "upgrade") throw new HostOpError(409, "host_offline", `${host.label} is offline`); throw host.id === LOCAL_HOST_ID - ? new HostOpError(409, "host_restart_required", "Restart this machine's ompweb host daemon to join the cluster") - : new HostOpError(409, "host_upgrade_required", `Update ompweb on ${host.label} to join the cluster`); + ? new HostOpError(409, "host_restart_required", "Restart this machine's tau host daemon to join the cluster") + : new HostOpError(409, "host_upgrade_required", `Update tau on ${host.label} to join the cluster`); } /** The host's projects in its own order (mergeProjects: the order the user sees), then its hidden registry entries, which move too. */ diff --git a/app/api/hosts/[id]/updates/route.ts b/app/api/hosts/[id]/updates/route.ts index 0d6f7429..df1f4081 100644 --- a/app/api/hosts/[id]/updates/route.ts +++ b/app/api/hosts/[id]/updates/route.ts @@ -28,7 +28,7 @@ export async function POST(request: Request, { params }: Context) { if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") return fail("Content-Type must be application/json", "unsupported_media_type", 415); try { const body = await parseJsonWithinLimit(request, 4096); - if (!isRecord(body) || Object.keys(body).some((key) => !["target", "version", "force"].includes(key)) || body.target !== "ompweb" + if (!isRecord(body) || Object.keys(body).some((key) => !["target", "version", "force"].includes(key)) || body.target !== "tau" || (body.force !== undefined && typeof body.force !== "boolean") || typeof body.version !== "string" || body.version.length > 100 || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(body.version)) { return fail("target and a release version are required", "invalid_host_update", 400); diff --git a/app/api/hosts/broker/[...path]/route.ts b/app/api/hosts/broker/[...path]/route.ts index 7ad99e90..efa39f03 100644 --- a/app/api/hosts/broker/[...path]/route.ts +++ b/app/api/hosts/broker/[...path]/route.ts @@ -26,7 +26,7 @@ const PLAIN_PATH = /^\/v1\/[A-Za-z0-9/_-]*$/; /** Never a token, a query, a body or an error message: a broker failure names only its class. */ function log(hostId: string, method: string, path: string, status: number, reason?: string) { - console.log(`[omp-web] broker ${hostId} ${method} ${path} ${status}${reason ? ` ${reason}` : ""}`); + console.log(`[tau] broker ${hostId} ${method} ${path} ${status}${reason ? ` ${reason}` : ""}`); } function only(source: Headers, names: readonly string[]): Headers { diff --git a/app/api/hosts/link/route.ts b/app/api/hosts/link/route.ts index 09a94a79..73b64654 100644 --- a/app/api/hosts/link/route.ts +++ b/app/api/hosts/link/route.ts @@ -1,6 +1,6 @@ import { handleLinkUpgrade, handleOutdatedLinkPost, type LinkSocketData } from "@/lib/hosts/hub"; -// The `ompweb host` daemon's link (lib/hosts/hub.ts). proxy.ts does not run +// The `tau host` daemon's link (lib/hosts/hub.ts). proxy.ts does not run // for this path: the hub checks the host's bearer token before it upgrades. // GET /api/hosts/link — the link's WebSocket; undefined once upgraded (server/app.ts). diff --git a/app/api/hosts/maintenance/route.ts b/app/api/hosts/maintenance/route.ts index b3174f4b..03649f4f 100644 --- a/app/api/hosts/maintenance/route.ts +++ b/app/api/hosts/maintenance/route.ts @@ -4,5 +4,5 @@ import packageJson from "@/package.json"; /** API v1 discovery and its independent host-token-authenticated WebSocket. */ export function GET(request: Request, { upgrade }: { upgrade: (data: MaintenanceSocketData) => boolean }) { - return handleMaintenanceUpgrade(request, upgrade, { protocolVersion: LINK_PROTOCOL_VERSION, ompwebVersion: packageJson.version }); + return handleMaintenanceUpgrade(request, upgrade, { protocolVersion: LINK_PROTOCOL_VERSION, tauVersion: packageJson.version }); } diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index 64ad1d07..7cd2a824 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -9,7 +9,7 @@ const MAX_LABEL_LENGTH = 100; const noStore = { "cache-control": "no-store" }; const fail = (error: string, status: number) => Response.json({ error }, { status, headers: noStore }); -const poolStorageFailure = () => fail("The pool registry (omp-web/pools.json) cannot be read or written; fix it before changing pools", 503); +const poolStorageFailure = () => fail("The pool registry (tau/pools.json) cannot be read or written; fix it before changing pools", 503); function hasOnlyKeys(value: unknown, keys: readonly string[]): value is Record { return isRecord(value) && Object.keys(value).every((key) => keys.includes(key)); @@ -17,7 +17,7 @@ function hasOnlyKeys(value: unknown, keys: readonly string[]): value is Record h.id === host.id), token, - command: `ompweb host login --url ${requestOrigin(req)}`, + command: `tau host login --url ${requestOrigin(req)}`, }, { headers: noStore }, ); diff --git a/app/api/manifest/route.ts b/app/api/manifest/route.ts index 59bfbc42..ce3e68f2 100644 --- a/app/api/manifest/route.ts +++ b/app/api/manifest/route.ts @@ -6,10 +6,10 @@ import { parseThemeColor } from "@/lib/manifest-theme"; // Packaged public assets are read/encoded once per server module, from the // package directory the launcher names (the working directory is wherever -// ompweb was started). Native installers fetch HTTP icons without cookies, +// tau was started). Native installers fetch HTTP icons without cookies, // even with a credentialed manifest. const pngDataUrl = (filename: string) => - `data:image/png;base64,${readFileSync(join(process.env.OMP_WEB_PACKAGE_DIR ?? process.cwd(), "public", filename)).toString("base64")}`; + `data:image/png;base64,${readFileSync(join(process.env.TAU_PACKAGE_DIR ?? process.cwd(), "public", filename)).toString("base64")}`; const manifest = { description: "Web UI for the pi coding agent", diff --git a/app/api/models-config/catalog/route.ts b/app/api/models-config/catalog/route.ts index a4448731..696f3016 100644 --- a/app/api/models-config/catalog/route.ts +++ b/app/api/models-config/catalog/route.ts @@ -16,7 +16,7 @@ interface CatalogCache { } declare global { - var __ompWebModelsDevCatalogCache: CatalogCache | undefined; + var __tauModelsDevCatalogCache: CatalogCache | undefined; } async function fetchCatalog(): Promise { @@ -32,9 +32,9 @@ async function fetchCatalog(): Promise { } async function loadCatalog(): Promise { - let cache = globalThis.__ompWebModelsDevCatalogCache; + let cache = globalThis.__tauModelsDevCatalogCache; if (!cache) { - cache = globalThis.__ompWebModelsDevCatalogCache = { entries: [], expiresAt: 0 }; + cache = globalThis.__tauModelsDevCatalogCache = { entries: [], expiresAt: 0 }; } if (cache.entries.length > 0 && cache.expiresAt > Date.now()) return cache.entries; if (!cache.inFlight) { diff --git a/app/api/models-config/route.ts b/app/api/models-config/route.ts index a9ecb4b3..f6f86658 100644 --- a/app/api/models-config/route.ts +++ b/app/api/models-config/route.ts @@ -40,7 +40,7 @@ export async function PUT(req: Request) { } catch (error) { if (error instanceof ModelsConfigParseError) { return Response.json( - { error: `${error.message} — fix it by hand; omp-web will not overwrite it`, code: "models_config_unparseable" }, + { error: `${error.message} — fix it by hand; tau will not overwrite it`, code: "models_config_unparseable" }, { status: 409 }, ); } diff --git a/app/api/models-config/test/route.ts b/app/api/models-config/test/route.ts index e576c109..ce1038ce 100644 --- a/app/api/models-config/test/route.ts +++ b/app/api/models-config/test/route.ts @@ -11,7 +11,7 @@ import { type OmpModel, runIsolatedUtilityCommand } from "@/lib/omp/rpc-utility" import { isRecord } from "@/lib/type-guards"; // Registry resolution (spawn + model discovery), not a completion round-trip: -// omp-web cannot send test prompts without going through a full agent session. +// tau cannot send test prompts without going through a full agent session. const TEST_TIMEOUT_MS = 60_000; function errorMessage(error: unknown): string { @@ -48,8 +48,8 @@ export async function POST(req: Request) { // Isolated throwaway agent dir: the spawned omp sees only this candidate // config (no stored credentials, no models.db cache) and never touches // ~/.omp. Profile/XDG overrides are cleared so the redirect always wins - // (the omp child still honors profiles even though omp-web ignores them). - tempDir = mkdtempSync(join(tmpdir(), "omp-web-model-test-")); + // (the omp child still honors profiles even though tau ignores them). + tempDir = mkdtempSync(join(tmpdir(), "tau-model-test-")); writeFileSync(join(tempDir, "models.yml"), serializeModelsConfig(config), "utf8"); const startedAt = Date.now(); diff --git a/app/api/omp-update/route.ts b/app/api/omp-update/route.ts index 055518e8..4568b690 100644 --- a/app/api/omp-update/route.ts +++ b/app/api/omp-update/route.ts @@ -2,7 +2,7 @@ import { isApiRequestOriginAllowed, shouldCheckApiRequestOrigin } from "@/lib/re import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { restartAllRpcSessions } from "@/lib/rpc-manager"; -/** Restarts every running omp session. omp itself updates with ompweb: its release ships the runner. */ +/** Restarts every running omp session. omp itself updates with tau: its release ships the runner. */ export async function POST(request: Request) { if (shouldCheckApiRequestOrigin(request) && !isApiRequestOriginAllowed(request)) { return Response.json({ error: "Cross-origin API requests are not allowed", code: "cross_origin_forbidden" }, { status: 403 }); diff --git a/app/api/omp-version/route.ts b/app/api/omp-version/route.ts index 976e8051..197ac6f7 100644 --- a/app/api/omp-version/route.ts +++ b/app/api/omp-version/route.ts @@ -1,7 +1,7 @@ import { getOmpVersion } from "@/lib/omp/omp-cli"; /** Runtime probe of the installed omp binary ("omp/17.1.3"), separate from the - * build-time omp-web version — the two can legitimately drift. */ + * build-time tau version — the two can legitimately drift. */ export async function GET() { const version = await getOmpVersion(); return Response.json({ version }); diff --git a/app/api/plugins/route.ts b/app/api/plugins/route.ts index c869eaa6..7c6c6048 100644 --- a/app/api/plugins/route.ts +++ b/app/api/plugins/route.ts @@ -16,7 +16,7 @@ import type { } from "@/lib/api-types"; // Plugin management is delegated to the user's omp binary (`omp plugin ...`); -// omp-web never embeds the Bun-only SDK. `--json` output shapes are mirrored +// tau never embeds the Bun-only SDK. `--json` output shapes are mirrored // from oh-my-pi coding-agent src/cli/plugin-cli.ts + extensibility/plugins. type PluginAction = "install" | "remove" | "update" | "disable" | "enable"; diff --git a/app/api/sessions/[id]/route.ts b/app/api/sessions/[id]/route.ts index d3099a23..a16262ca 100644 --- a/app/api/sessions/[id]/route.ts +++ b/app/api/sessions/[id]/route.ts @@ -140,7 +140,7 @@ export async function DELETE( try { forgetSessionReplacementMappings(id); } catch (error) { - console.warn(`[omp-web] could not clear deleted-session retry metadata: ${error instanceof Error ? error.message : String(error)}`); + console.warn(`[tau] could not clear deleted-session retry metadata: ${error instanceof Error ? error.message : String(error)}`); } invalidateHostSessionList(resolved.host.id); clearExitedRpcSession(id); @@ -148,7 +148,7 @@ export async function DELETE( removeSessionWatches(id); } catch (error) { // The delete succeeded; a watch left behind ends at the outbox's 404 for this session. - console.warn(`[omp-web] GitHub watches of ${id} were not removed: ${error instanceof Error ? error.message : String(error)}`); + console.warn(`[tau] GitHub watches of ${id} were not removed: ${error instanceof Error ? error.message : String(error)}`); } return Response.json({ ok: true, ...result.value }); } catch (error) { diff --git a/app/api/stt/[jobId]/route.ts b/app/api/stt/[jobId]/route.ts index 605029c9..4a927c38 100644 --- a/app/api/stt/[jobId]/route.ts +++ b/app/api/stt/[jobId]/route.ts @@ -21,7 +21,7 @@ export async function GET(_req: Request, { params }: Params) { export async function POST(req: Request, { params }: Params) { const config = readSttConfig(); if (!config) { - return Response.json({ error: "STT not configured. Set OMP_WEB_STT_ENDPOINT or OMP_WEB_STT_MODEL." }, { status: 501 }); + return Response.json({ error: "STT not configured. Set TAU_STT_ENDPOINT or TAU_STT_MODEL." }, { status: 501 }); } const owner = new URL(req.url).searchParams.get("owner")?.slice(0, 128) || undefined; const job = retrySttJob(config, (await params).jobId, owner); diff --git a/app/api/stt/route.ts b/app/api/stt/route.ts index caae0883..ea6ad375 100644 --- a/app/api/stt/route.ts +++ b/app/api/stt/route.ts @@ -23,7 +23,7 @@ export async function POST(request: Request) { const config = readSttConfig(); if (!config) { return Response.json( - { error: "STT not configured. Set OMP_WEB_STT_ENDPOINT." }, + { error: "STT not configured. Set TAU_STT_ENDPOINT." }, { status: 501 } ); } diff --git a/app/api/transport-metrics/route.ts b/app/api/transport-metrics/route.ts index 753d4775..dc32baf1 100644 --- a/app/api/transport-metrics/route.ts +++ b/app/api/transport-metrics/route.ts @@ -10,7 +10,7 @@ export function GET() { return Response.json({ now: Date.now() }, { headers: { "cache-control": "no-store" } }); } -// POST /api/transport-metrics { samples } — appended to /omp-web/transport-metrics.jsonl. +// POST /api/transport-metrics { samples } — appended to /tau/transport-metrics.jsonl. export async function POST(req: Request) { let body: unknown; try { diff --git a/app/api/web-auth/session/route.ts b/app/api/web-auth/session/route.ts index a9faa96a..3fd05d7f 100644 --- a/app/api/web-auth/session/route.ts +++ b/app/api/web-auth/session/route.ts @@ -4,8 +4,8 @@ import { createWebSession, isValidWebPassword, isWebPasswordEnabled, - OMP_WEB_SESSION_COOKIE, - OMP_WEB_SESSION_MAX_AGE_SECONDS, + TAU_SESSION_COOKIE, + TAU_SESSION_MAX_AGE_SECONDS, } from "@/lib/web-auth"; const MAX_PASSWORD_REQUEST_BYTES = 8 * 1024; @@ -27,11 +27,11 @@ export async function POST(request: Request) { } const secure = requestProtocol(request) === "https:"; - const cookie = new Bun.Cookie(OMP_WEB_SESSION_COOKIE, createWebSession(), { + const cookie = new Bun.Cookie(TAU_SESSION_COOKIE, createWebSession(), { httpOnly: true, secure, sameSite: "lax", - maxAge: OMP_WEB_SESSION_MAX_AGE_SECONDS, + maxAge: TAU_SESSION_MAX_AGE_SECONDS, path: "/", }); return Response.json({ ok: true }, { headers: { "set-cookie": cookie.serialize() } }); diff --git a/app/api/web-settings/route.ts b/app/api/web-settings/route.ts index daec0072..1b1ebca8 100644 --- a/app/api/web-settings/route.ts +++ b/app/api/web-settings/route.ts @@ -7,7 +7,7 @@ import { browserTransportState, loadWebServerSettings, readWebServerSettingsFrom import { isRecord } from "@/lib/type-guards"; import { isUploadRetentionDays } from "@/lib/upload-limits"; -/** GET/PUT /api/web-settings - omp-web's own server-side settings. */ +/** GET/PUT /api/web-settings - tau's own server-side settings. */ export async function GET() { try { return Response.json(readSettings()); diff --git a/app/globals.css b/app/globals.css index 2b734e31..3b9cb6c4 100644 --- a/app/globals.css +++ b/app/globals.css @@ -1,4 +1,4 @@ -/* Keep Tailwind's content scan inside the omp-web package. This is important +/* Keep Tailwind's content scan inside the tau package. This is important on Windows, where a parent user-profile package can make the scanner walk protected junctions such as "My Documents" during production builds. */ @import "tailwindcss" source(none); @@ -5151,12 +5151,12 @@ html[data-touch-targets="accessible"] :is(.extension-choice, .extension-field) { /* Sidebar search hits in the chat (CSS Custom Highlight API, set by useChatSearchHighlights) and in the sidebar's match list. */ -::highlight(omp-search), +::highlight(tau-search), .session-search-match-hit { background-color: color-mix(in srgb, var(--status-warning) 32%, transparent); color: inherit; } -::highlight(omp-search-current) { +::highlight(tau-search-current) { background-color: var(--status-warning); color: var(--bg); } diff --git a/app/index.html b/app/index.html index 1e006ffe..5da65aa7 100644 --- a/app/index.html +++ b/app/index.html @@ -13,7 +13,7 @@ - + diff --git a/bin/bun-runtime.js b/bin/bun-runtime.js index b97f4367..188bed4e 100644 --- a/bin/bun-runtime.js +++ b/bin/bun-runtime.js @@ -71,7 +71,7 @@ function resolveBunBinary(packageDir, env = process.env) { if (onPath && versionAtLeast(onPath, MIN_BUN_VERSION)) return "bun"; const found = onPath ? ` (bun ${onPath} on PATH is older than ${MIN_BUN_VERSION})` : ""; - throw new Error(`Bun runtime not found${found}. Reinstall ompweb with: ${REINSTALL}`); + throw new Error(`Bun runtime not found${found}. Reinstall tau with: ${REINSTALL}`); } module.exports = { MIN_BUN_VERSION, PLATFORM_PACKAGES, resolveBunBinary }; diff --git a/bin/generate-release-notes.js b/bin/generate-release-notes.js index f2433b5f..b4f0caaf 100644 --- a/bin/generate-release-notes.js +++ b/bin/generate-release-notes.js @@ -161,7 +161,7 @@ function formatReleaseNotes({ for (const c of commits) { const s = c.subject.trim(); - if (/^(?:chore: )?release( ompweb)? v?[0-9]/i.test(s) || /^v?[0-9]+\.[0-9]+\.[0-9]+$/i.test(s)) { + if (/^(?:chore: )?release( tau)? v?[0-9]/i.test(s) || /^v?[0-9]+\.[0-9]+\.[0-9]+$/i.test(s)) { continue; } diff --git a/bin/linux-tray.js b/bin/linux-tray.js index 2d44cb1f..0061176f 100644 --- a/bin/linux-tray.js +++ b/bin/linux-tray.js @@ -3,19 +3,19 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); -// Linux system tray for ompweb (KDE Plasma and any StatusNotifierItem host). +// Linux system tray for tau (KDE Plasma and any StatusNotifierItem host). // // Registers a StatusNotifierItem on the session bus with a DBusMenu context // menu mirroring the Windows tray: open, copy URL, start/stop/restart the // systemd user service, view logs, autostart toggle, quit. // // CLI: -// ompweb-tray --install [--no-autostart] install icons/autostart, start tray -// ompweb-tray --uninstall remove autostart and stop the tray -// ompweb-tray --start run the tray (foreground) -// ompweb-tray --stop | --restart stop/restart a running tray -// ompweb-tray --status [--json] tray + service status -// ompweb-tray --open open the web UI in the browser +// tau-tray --install [--no-autostart] install icons/autostart, start tray +// tau-tray --uninstall remove autostart and stop the tray +// tau-tray --start run the tray (foreground) +// tau-tray --stop | --restart stop/restart a running tray +// tau-tray --status [--json] tray + service status +// tau-tray --open open the web UI in the browser // -p, --port / -H, --hostname override status endpoint // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -36,9 +36,9 @@ const path = require("node:path"); const { readServiceEnv, writeServiceEnv } = require("./service-env");// eslint-disable-next-line @typescript-eslint/no-require-imports const { getAccessibleAddresses, isLoopbackHost } = require("./network-addresses"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { hashPassword } = require("./omp-web-password-hash"); +const { hashPassword } = require("./tau-password-hash"); -// dbus-next is intentionally NOT a dependency of ompweb (see #268): it +// dbus-next is intentionally NOT a dependency of tau (see #268): it // pulled in usocket/node-gyp@7 and ten deprecated packages on every // install, while only the Linux tray uses it. It is loaded on demand // below, and the tray installs it (or tells the user how to) at setup @@ -46,9 +46,9 @@ const { hashPassword } = require("./omp-web-password-hash"); // via FallbackVariant, which only needs the .value the tests and the // menu code read; the real D-Bus path always uses the real Variant. const DBUS_MISSING_MESSAGE = - "The Linux tray requires dbus-next, which is not bundled with ompweb. " + + "The Linux tray requires dbus-next, which is not bundled with tau. " + "Install it with: npm install dbus-next@^0.10.2 " + - "(in the ompweb install directory, or globally with npm install -g dbus-next@^0.10.2), " + + "(in the tau install directory, or globally with npm install -g dbus-next@^0.10.2), " + "then run the tray command again."; class FallbackVariant { @@ -111,7 +111,7 @@ function getDbusClasses() { return [ "", this.state.running ? buildIconPixmap(true) : buildIconPixmap(false), - "ompweb", + "tau", this.state.running ? `Running — ${this.state.serviceUrl}` : "Service stopped", ]; } @@ -169,8 +169,8 @@ function getDbusClasses() { }); StatusNotifierItem.prototype.Category = "ApplicationStatus"; - StatusNotifierItem.prototype.Id = "ompweb"; - StatusNotifierItem.prototype.Title = "ompweb"; + StatusNotifierItem.prototype.Id = "tau"; + StatusNotifierItem.prototype.Title = "tau"; // Status, IconName, IconPixmap, and ToolTip stay as class getters (dynamic). StatusNotifierItem.prototype.WindowId = 0; StatusNotifierItem.prototype.AttentionIconName = ""; @@ -247,7 +247,7 @@ function getDbusClasses() { class TrayControl extends Interface { constructor(state) { - super("org.kde.ompweb.Tray"); + super("org.kde.tau.Tray"); this.state = state; } @@ -267,13 +267,13 @@ function getDbusClasses() { const execFileAsync = promisify(execFile); -const BUS_NAME = "org.kde.ompweb.tray"; +const BUS_NAME = "org.kde.tau.tray"; const ITEM_PATH = "/StatusNotifierItem"; const MENU_PATH = "/MenuBar"; -const TRAY_PATH = "/ompweb/tray"; -const SERVICE_UNIT = "ompweb.service"; -const DAEMON_UNIT = "ompweb-host.service"; -const AUTOSTART_FILE = path.join(os.homedir(), ".config", "autostart", "ompweb-tray.desktop"); +const TRAY_PATH = "/tau/tray"; +const SERVICE_UNIT = "tau.service"; +const DAEMON_UNIT = "tau-host.service"; +const AUTOSTART_FILE = path.join(os.homedir(), ".config", "autostart", "tau-tray.desktop"); const ICON_DIR = path.join(os.homedir(), ".local", "share", "icons", "hicolor", "scalable", "apps"); const POLL_INTERVAL_MS = 5000; @@ -385,9 +385,9 @@ function buildIconPixmap(running) { } function printHelp() { - console.log(`Usage: ompweb-tray [command] [options] + console.log(`Usage: tau-tray [command] [options] -Linux system tray icon (StatusNotifierItem) for the ompweb web service. +Linux system tray icon (StatusNotifierItem) for the tau web service. Commands: --install, install Install icons + autostart entry, then start the tray @@ -421,7 +421,7 @@ function readPackageVersion() { // Pure helpers (unit-tested) // --------------------------------------------------------------------------- -function sanitizePort(val, fallback = 30177) { +function sanitizePort(val, fallback = 30187) { const port = parseInt(val, 10); return Number.isInteger(port) && port >= 0 && port <= 65535 ? port : fallback; } @@ -445,16 +445,16 @@ function readTrayConfig(overrides = {}, env = process.env, home = os.homedir()) jsonConfig = {}; } const port = overrides.port ?? sanitizePort(serviceEnv.PORT ?? jsonConfig.port); - const hostname = overrides.hostname ?? sanitizeHostname(serviceEnv.OMP_WEB_HOSTNAME ?? jsonConfig.hostname); + const hostname = overrides.hostname ?? sanitizeHostname(serviceEnv.TAU_HOSTNAME ?? jsonConfig.hostname); return { port, hostname, configFile, serviceUrl: `http://${hostname}:${port}` }; } // Menu item table. `separator` items render as dividers; `checkmark` items // carry a toggle state; `disabled` items are inert status rows. -// `daemon` is "running", "stopped" or "not installed" (the ompweb-host unit). +// `daemon` is "running", "stopped" or "not installed" (the tau-host unit). function buildMenuItems({ running, version, autostart, hasService, exposed, hasDialogTool, daemon = "not installed" }) { return [ - { id: 1, label: `ompweb (v${version})`, enabled: false }, + { id: 1, label: `tau (v${version})`, enabled: false }, { id: 2, label: running ? " Status: Running" : " Status: Stopped", enabled: false }, { id: 19, label: ` Daemon: ${daemon[0].toUpperCase()}${daemon.slice(1)}`, enabled: false }, { id: 3, separator: true }, @@ -528,11 +528,11 @@ function buildAutostartDesktop(execLine) { return [ "[Desktop Entry]", "Type=Application", - "Name=ompweb Tray", - "GenericName=ompweb tray icon", - "Comment=ompweb web service tray icon and controls", + "Name=tau Tray", + "GenericName=tau tray icon", + "Comment=tau web service tray icon and controls", `Exec=${execLine}`, - "Icon=ompweb", + "Icon=tau", "Terminal=false", "Categories=Network;", "X-GNOME-Autostart-enabled=true", @@ -552,7 +552,7 @@ function buildAutostartExec() { // Terminal used to open logs; ordered candidates, first hit wins. function terminalCandidates(env = process.env) { return [ - ...(env.OMP_WEB_TERMINAL ? [env.OMP_WEB_TERMINAL] : []), + ...(env.TAU_TERMINAL ? [env.TAU_TERMINAL] : []), ...(env.TERMINAL ? [env.TERMINAL] : []), "konsole", "alacritty", @@ -603,7 +603,7 @@ function dialogCandidates() { } function resolveDialogTool(env = process.env) { - const override = env.OMP_WEB_DIALOG; + const override = env.TAU_DIALOG; if (override) { return override.includes(path.sep) ? (isExecutable(override) ? override : null) : which(override); } @@ -704,7 +704,7 @@ function viewLogs() { const resolved = candidateBinPath(terminal); if (!resolved) return false; const prefix = terminalPrefix(terminal).slice(1); - const child = spawn(resolved, [...prefix, `journalctl --user -u ompweb -u ompweb-host -f`], { + const child = spawn(resolved, [...prefix, `journalctl --user -u tau -u tau-host -f`], { stdio: "ignore", detached: true, env: process.env, @@ -779,12 +779,12 @@ function createTrayState(config, { log = console.log } = {}) { try { writeServiceEnv(merged); } catch (err) { - state.notify("ompweb", `Config write failed: ${err.message}`); + state.notify("tau", `Config write failed: ${err.message}`); return false; } const result = systemctlUser(["restart", SERVICE_UNIT]); if (!result.ok) { - state.notify("ompweb", `Service restart failed: ${result.stderr || result.stdout || "unknown error"}`); + state.notify("tau", `Service restart failed: ${result.stderr || result.stdout || "unknown error"}`); return false; } state.reloadConfig(); @@ -801,7 +801,7 @@ function createTrayState(config, { log = console.log } = {}) { getDbusClasses().Interface.emitPropertiesChanged(state.sni, { IconName: "", IconPixmap: buildIconPixmap(state.running), - ToolTip: ["", buildIconPixmap(state.running), "ompweb", state.running ? `Running — ${state.serviceUrl}` : "Service stopped"], + ToolTip: ["", buildIconPixmap(state.running), "tau", state.running ? `Running — ${state.serviceUrl}` : "Service stopped"], }); state.sni.NewIcon(); state.sni.NewToolTip(); @@ -816,7 +816,7 @@ function createTrayState(config, { log = console.log } = {}) { openUrl(state.serviceUrl); break; case "copy": - if (!copyToClipboard(state.serviceUrl)) state.notify("ompweb", "No clipboard tool found (install wl-clipboard)"); + if (!copyToClipboard(state.serviceUrl)) state.notify("tau", "No clipboard tool found (install wl-clipboard)"); break; case "toggle": systemctlUser([state.running ? "stop" : "start", SERVICE_UNIT]); @@ -825,33 +825,33 @@ function createTrayState(config, { log = console.log } = {}) { systemctlUser(["restart", SERVICE_UNIT]); break; case "logs": - if (!viewLogs()) state.notify("ompweb", "No terminal emulator found for logs"); + if (!viewLogs()) state.notify("tau", "No terminal emulator found for logs"); break; case "autostart": state.setAutostart(!state.autostart); break; case "expose": { const exposing = !state.exposed; - const updates = { OMP_WEB_HOSTNAME: exposing ? "0.0.0.0" : "127.0.0.1" }; - if (exposing && !readServiceEnv().OMP_WEB_PASSWORD_HASH) { + const updates = { TAU_HOSTNAME: exposing ? "0.0.0.0" : "127.0.0.1" }; + if (exposing && !readServiceEnv().TAU_PASSWORD_HASH) { const password = await dialogPrompt({ tool: state.dialogTool, - title: "ompweb", + title: "tau", text: "A password is required to expose the web UI.\nWeb sign-in password:", password: true, }); if (!password) { - state.notify("ompweb", "Expose cancelled: a password is required to leave loopback"); + state.notify("tau", "Expose cancelled: a password is required to leave loopback"); break; } - updates.OMP_WEB_PASSWORD_HASH = hashPassword(password); + updates.TAU_PASSWORD_HASH = hashPassword(password); } if (state.applyServiceEnv(updates)) { const urls = getAccessibleAddresses({ hostname: state.hostname, port: state.port }).entries .filter((entry) => entry.label !== "Local") .map((entry) => entry.url); state.notify( - "ompweb", + "tau", exposing ? `Exposed to the network: ${urls[0] ?? `http://0.0.0.0:${state.port}`}` : `Restricted to loopback (${state.serviceUrl})`, @@ -862,38 +862,38 @@ function createTrayState(config, { log = console.log } = {}) { case "port": { const input = await dialogPrompt({ tool: state.dialogTool, - title: "ompweb", + title: "tau", text: `Server port (current: ${state.port}):`, value: String(state.port), }); if (input === null) break; const port = parseInt(input.trim(), 10); if (!Number.isInteger(port) || port < 1 || port > 65535) { - state.notify("ompweb", `Invalid port: ${input.trim()}`); + state.notify("tau", `Invalid port: ${input.trim()}`); break; } if (state.applyServiceEnv({ PORT: String(port) })) { - state.notify("ompweb", `Port updated: ${state.serviceUrl}`); + state.notify("tau", `Port updated: ${state.serviceUrl}`); } break; } case "password": { const password = await dialogPrompt({ tool: state.dialogTool, - title: "ompweb", + title: "tau", text: "Web sign-in password (empty disables auth):", password: true, }); if (password === null) break; const updates = {}; if (password) { - updates.OMP_WEB_PASSWORD_HASH = hashPassword(password); + updates.TAU_PASSWORD_HASH = hashPassword(password); } else { - updates.OMP_WEB_PASSWORD_HASH = null; - if (!isLoopbackHost(state.hostname)) updates.OMP_WEB_HOSTNAME = "127.0.0.1"; + updates.TAU_PASSWORD_HASH = null; + if (!isLoopbackHost(state.hostname)) updates.TAU_HOSTNAME = "127.0.0.1"; } if (state.applyServiceEnv(updates)) { - state.notify("ompweb", password ? "Password updated" : "Password disabled (loopback only)"); + state.notify("tau", password ? "Password updated" : "Password disabled (loopback only)"); } break; } @@ -916,7 +916,7 @@ function createTrayState(config, { log = console.log } = {}) { state.autostart = enable; state.refreshMenu(); } catch (err) { - state.notify("ompweb", `Autostart update failed: ${err.message}`); + state.notify("tau", `Autostart update failed: ${err.message}`); } }; @@ -925,7 +925,7 @@ function createTrayState(config, { log = console.log } = {}) { try { const obj = await state.bus.getProxyObject("org.freedesktop.Notifications", "/org/freedesktop/Notifications"); const iface = obj.getInterface("org.freedesktop.Notifications"); - await iface.Notify("ompweb", 0, "ompweb", summary, body, [], {}, 5000); + await iface.Notify("tau", 0, "tau", summary, body, [], {}, 5000); } catch { // Notifications are best-effort. } @@ -1005,7 +1005,7 @@ async function startTray(config, { log = console.log, error = console.error } = } // 1 = primary owner, 4 = already ours; anything else means another tray runs. if (nameReply !== 1 && nameReply !== 4) { - log("ompweb tray is already running"); + log("tau tray is already running"); return state; } @@ -1025,15 +1025,15 @@ async function startTray(config, { log = console.log, error = console.error } = await state.registerWithWatcher(); state.registerTimer = setInterval(() => state.registerWithWatcher(), 60000); state.pollTimer = setInterval(() => state.poll(), POLL_INTERVAL_MS); - log(`ompweb tray started (${state.serviceUrl})`); + log(`tau tray started (${state.serviceUrl})`); return state; } function installIcons({ log = console.log } = {}) { try { fs.mkdirSync(ICON_DIR, { recursive: true }); - fs.writeFileSync(path.join(ICON_DIR, "ompweb.svg"), ICON_RUNNING, { mode: 0o644 }); - fs.writeFileSync(path.join(ICON_DIR, "ompweb-off.svg"), ICON_STOPPED, { mode: 0o644 }); + fs.writeFileSync(path.join(ICON_DIR, "tau.svg"), ICON_RUNNING, { mode: 0o644 }); + fs.writeFileSync(path.join(ICON_DIR, "tau-off.svg"), ICON_STOPPED, { mode: 0o644 }); } catch (err) { log(`warning: could not install tray icons: ${err.message}`); } @@ -1079,7 +1079,7 @@ async function quitRunningTray() { } try { const obj = await bus.getProxyObject(BUS_NAME, TRAY_PATH); - const iface = obj.getInterface("org.kde.ompweb.Tray"); + const iface = obj.getInterface("org.kde.tau.Tray"); await iface.Quit(); return true; } catch { @@ -1124,7 +1124,7 @@ async function readStatus(overrides) { // Best-effort on-demand install of dbus-next, used only by --install: // the user explicitly opted into tray setup, so installing the tray's -// own dependency into the ompweb install directory is in scope there. +// own dependency into the tau install directory is in scope there. // --start/--restart never auto-install (they can run unattended from // autostart); they fail with DBUS_MISSING_MESSAGE instead. function defaultNpmInstallDbus() { @@ -1192,7 +1192,7 @@ async function runCli(argv = process.argv.slice(2)) { }); if (process.platform !== "linux") { - console.error("error: the Linux tray is only supported on Linux (see omp-web-tray for Windows)"); + console.error("error: the Linux tray is only supported on Linux (see tau-tray for Windows)"); return { exitCode: 1 }; } @@ -1283,7 +1283,7 @@ async function runCli(argv = process.argv.slice(2)) { if (cliArgs.json) { console.log(JSON.stringify(status, null, 2)); } else { - console.log(`=== ompweb Linux tray status ===`); + console.log(`=== tau Linux tray status ===`); console.log(` Tray running : ${status.trayRunning ? "Yes" : "No"}`); console.log(` Service unit : ${status.serviceInstalled ? "installed" : "not installed"} (${status.serviceRunning ? "active" : "inactive"})`); console.log(` Host daemon : ${status.daemon}`); diff --git a/bin/linux-tray.test.mjs b/bin/linux-tray.test.mjs index a02bac13..65699d47 100644 --- a/bin/linux-tray.test.mjs +++ b/bin/linux-tray.test.mjs @@ -39,10 +39,10 @@ const { } = require("./service-env.js"); test("sanitizePort accepts valid ports and falls back otherwise", () => { - assert.equal(sanitizePort("30177"), 30177); + assert.equal(sanitizePort("30187"), 30187); assert.equal(sanitizePort(8080), 8080); - assert.equal(sanitizePort("nope"), 30177); - assert.equal(sanitizePort("70000"), 30177); + assert.equal(sanitizePort("nope"), 30187); + assert.equal(sanitizePort("70000"), 30187); assert.equal(sanitizePort(undefined, 4000), 4000); }); @@ -53,7 +53,7 @@ test("sanitizeHostname trims strings and rejects empties", () => { }); test("readTrayConfig prefers CLI overrides over the service config file", () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-")); try { const agentDir = path.join(home, ".omp", "agent"); mkdirSync(agentDir, { recursive: true }); @@ -73,10 +73,10 @@ test("readTrayConfig prefers CLI overrides over the service config file", () => }); test("readTrayConfig falls back to defaults without a config file", () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-")); try { const config = readTrayConfig({}, {}, home); - assert.equal(config.port, 30177); + assert.equal(config.port, 30187); assert.equal(config.hostname, "127.0.0.1"); } finally { rmSync(home, { recursive: true, force: true }); @@ -108,7 +108,7 @@ test("buildMenuItems reflects running state and service availability", () => { assert.equal(itemById(noDialog, 13).enabled, false); assert.equal(itemById(noDialog, 14).enabled, false); - // The ompweb-host daemon state sits under the web status. + // The tau-host daemon state sits under the web status. assert.equal(itemById(running, 19).label, " Daemon: Not installed"); assert.equal(itemById(running, 19).enabled, false); const withDaemon = buildMenuItems({ running: true, version: "0.4.2", autostart: false, hasService: true, exposed: false, hasDialogTool: true, daemon: "running" }); @@ -152,9 +152,9 @@ test("buildLayout nests all items under the root with the given revision", () => }); test("autostart desktop file references the tray script", () => { - const desktop = buildAutostartDesktop("/usr/bin/node /opt/ompweb/bin/linux-tray.js --start"); + const desktop = buildAutostartDesktop("/usr/bin/node /opt/tau/bin/linux-tray.js --start"); assert.match(desktop, /^\[Desktop Entry\]/); - assert.match(desktop, /^Exec=\/usr\/bin\/node \/opt\/ompweb\/bin\/linux-tray\.js --start$/m); + assert.match(desktop, /^Exec=\/usr\/bin\/node \/opt\/tau\/bin\/linux-tray\.js --start$/m); assert.match(desktop, /^Terminal=false$/m); assert.match(desktop, /^X-KDE-autostart-after=panel$/m); }); @@ -169,7 +169,7 @@ test("buildAutostartExec quotes paths containing spaces", () => { }); test("terminal candidates honor explicit env overrides first", () => { - const candidates = terminalCandidates({ OMP_WEB_TERMINAL: "foot", TERMINAL: "wezterm" }); + const candidates = terminalCandidates({ TAU_TERMINAL: "foot", TERMINAL: "wezterm" }); assert.deepEqual(candidates.slice(0, 2), ["foot", "wezterm"]); assert.ok(candidates.includes("konsole")); }); @@ -223,10 +223,10 @@ test("buildIconPixmap returns sized structs with matching byte counts", () => { test("service env file round-trips quoted and escaped values", () => { const entries = { - PORT: "30177", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: 'pa"ss\\word', - OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp", + PORT: "30187", + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: 'pa"ss\\word', + TAU_OMP_BIN: "/home/u/.bun/bin/omp", }; const parsed = parseServiceEnv(serializeServiceEnv(entries)); assert.deepEqual(parsed, entries); @@ -238,24 +238,24 @@ test("parseServiceEnv tolerates comments, blanks, and unquoted values", () => { ; also a comment PORT=40001 -OMP_WEB_HOSTNAME="0.0.0.0" +TAU_HOSTNAME="0.0.0.0" broken line without equals 1BAD=skipped `); - assert.deepEqual(parsed, { PORT: "40001", OMP_WEB_HOSTNAME: "0.0.0.0" }); + assert.deepEqual(parsed, { PORT: "40001", TAU_HOSTNAME: "0.0.0.0" }); }); test("writeServiceEnv writes atomically with mode 600 and readServiceEnv round-trips", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-env-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-env-")); try { const file = path.join(dir, "web-service.env"); - writeServiceEnv({ PORT: "40100", OMP_WEB_PASSWORD: "s3cret" }, file); + writeServiceEnv({ PORT: "40100", TAU_PASSWORD: "s3cret" }, file); // Windows has no Unix permission bits (chmod is best-effort there), so // the mode assertion only applies elsewhere. if (process.platform !== "win32") { assert.equal(statSync(file).mode & 0o777, 0o600); } - assert.deepEqual(readServiceEnv(file), { PORT: "40100", OMP_WEB_PASSWORD: "s3cret" }); + assert.deepEqual(readServiceEnv(file), { PORT: "40100", TAU_PASSWORD: "s3cret" }); assert.ok(escapeEnvValue("a\nb").includes(" ")); } finally { rmSync(dir, { recursive: true, force: true }); @@ -263,12 +263,12 @@ test("writeServiceEnv writes atomically with mode 600 and readServiceEnv round-t }); test("readTrayConfig prefers the env file over the JSON config", () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-")); try { const agentDir = path.join(home, ".omp", "agent"); mkdirSync(agentDir, { recursive: true }); writeFileSync(path.join(agentDir, "web-service.json"), JSON.stringify({ port: 40001, hostname: "0.0.0.0" })); - writeFileSync(path.join(agentDir, "web-service.env"), serializeServiceEnv({ PORT: "40200", OMP_WEB_HOSTNAME: "127.0.0.1" })); + writeFileSync(path.join(agentDir, "web-service.env"), serializeServiceEnv({ PORT: "40200", TAU_HOSTNAME: "127.0.0.1" })); const config = readTrayConfig({}, {}, home); assert.equal(config.port, 40200); @@ -281,7 +281,7 @@ test("readTrayConfig prefers the env file over the JSON config", () => { test("dialog candidates put kdialog first and resolve via override", () => { assert.deepEqual(dialogCandidates(), ["kdialog", "zenity"]); - assert.equal(resolveDialogTool({ OMP_WEB_DIALOG: "definitely-not-on-path-xyz" }), null); + assert.equal(resolveDialogTool({ TAU_DIALOG: "definitely-not-on-path-xyz" }), null); }); test("dialogPrompt returns null on cancel and text on success", async () => { @@ -289,10 +289,10 @@ test("dialogPrompt returns null on cancel and text on success", async () => { if (args.includes("--password")) { throw new Error("cancelled"); } - return { stdout: "30178\n" }; + return { stdout: "30188\n" }; }; const tool = "/usr/bin/kdialog"; - assert.equal(await dialogPrompt({ tool, title: "t", text: "port", value: "1" }, fakeRun), "30178"); + assert.equal(await dialogPrompt({ tool, title: "t", text: "port", value: "1" }, fakeRun), "30188"); assert.equal(await dialogPrompt({ tool, title: "t", text: "pw", password: true }, fakeRun), null); assert.equal(await dialogPrompt({ tool: null, title: "t", text: "x" }, fakeRun), null); }); @@ -318,7 +318,7 @@ test("ensureDbusInstalled reports failure without throwing when the installer fa }); test("tray --start fails gracefully with an install hint when dbus-next is absent (#268)", { skip: dbusIsInstalled() || process.platform !== "linux" }, () => { - const home = mkdtempSync(path.join(tmpdir(), "ompweb-tray-nodbus-")); + const home = mkdtempSync(path.join(tmpdir(), "tau-tray-nodbus-")); try { const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "linux-tray.js"); const res = spawnSync("node", [script, "--start"], { diff --git a/bin/network-addresses.js b/bin/network-addresses.js index 62805f5e..0da3a754 100644 --- a/bin/network-addresses.js +++ b/bin/network-addresses.js @@ -172,7 +172,7 @@ function formatAddressBanner({ const lines = []; lines.push(""); - lines.push(` ${bold("ompweb")} ${dim(`v${version}`)} ${green("is ready")}`); + lines.push(` ${bold("tau")} ${dim(`v${version}`)} ${green("is ready")}`); lines.push(""); const maxLabelLen = Math.max(...entries.map((e) => e.label.length), hint ? 7 : 5); @@ -188,12 +188,12 @@ function formatAddressBanner({ if (passwordEnabled) { lines.push(""); - lines.push(` ${dim("🔒 Password protection enabled (OMP_WEB_PASSWORD_HASH)")}`); + lines.push(` ${dim("🔒 Password protection enabled (TAU_PASSWORD_HASH)")}`); } - if (process.platform === "win32" && !process.env.OMP_WEB_SERVICE) { + if (process.platform === "win32" && !process.env.TAU_SERVICE) { lines.push(""); - lines.push(` ${dim("💡 Windows Tray: Run 'ompweb --install-tray' to enable background startup & Desktop shortcut.")}`); + lines.push(` ${dim("💡 Windows Tray: Run 'tau --install-tray' to enable background startup & Desktop shortcut.")}`); } lines.push(""); diff --git a/bin/node-version-gate.test.mjs b/bin/node-version-gate.test.mjs index 4df38be3..b6871871 100644 --- a/bin/node-version-gate.test.mjs +++ b/bin/node-version-gate.test.mjs @@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("..", import.meta.url)); const { bin } = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); // Pretend to be Node 22 before the entry point runs. -const preload = join(mkdtempSync(join(tmpdir(), "ompweb-node-gate-")), "old-node.cjs"); +const preload = join(mkdtempSync(join(tmpdir(), "tau-node-gate-")), "old-node.cjs"); writeFileSync(preload, `Object.defineProperty(process, "versions", { value: { ...process.versions, node: "22.19.0" } });\n`); for (const [name, script] of Object.entries(bin)) { diff --git a/bin/node-version.js b/bin/node-version.js index 8674edcd..a60321df 100644 --- a/bin/node-version.js +++ b/bin/node-version.js @@ -22,7 +22,7 @@ function isNodeVersionSupported(version) { function getUnsupportedNodeVersionMessage(version) { return [ - `ompweb requires Node.js ${MIN_NODE_VERSION} or newer.`, + `tau requires Node.js ${MIN_NODE_VERSION} or newer.`, `Current Node.js version: ${version}.`, "Upgrade Node.js and try again: https://nodejs.org/", ].join("\n"); diff --git a/bin/service-env.js b/bin/service-env.js index dc0ddfd5..f2183f12 100644 --- a/bin/service-env.js +++ b/bin/service-env.js @@ -1,6 +1,6 @@ "use strict"; -// Shared systemd EnvironmentFile helpers for the ompweb Linux service. +// Shared systemd EnvironmentFile helpers for the tau Linux service. // Runtime settings live in ~/.omp/agent/web-service.env so changing the // port, bind address, or password does not require regenerating the unit. diff --git a/bin/omp-web-hash-password.js b/bin/tau-hash-password.js similarity index 89% rename from bin/omp-web-hash-password.js rename to bin/tau-hash-password.js index 842028f7..29107c4d 100644 --- a/bin/omp-web-hash-password.js +++ b/bin/tau-hash-password.js @@ -1,11 +1,11 @@ "use strict"; -// `ompweb hash-password` plus the password prompt the launcher and the service +// `tau hash-password` plus the password prompt the launcher and the service // installers use. The password is read from stdin, never from argv, so it // stays out of shell history and out of `ps` output (issue #239). // eslint-disable-next-line @typescript-eslint/no-require-imports -const { hashPassword, isPasswordHash } = require("./omp-web-password-hash"); +const { hashPassword, isPasswordHash } = require("./tau-password-hash"); /** Key sent when the user presses Ctrl+C at a prompt. */ const INTERRUPT_KEY = Buffer.from([0x03]); @@ -109,7 +109,7 @@ async function promptPassword(options = {}) { } /** - * `ompweb hash-password`: print the `OMP_WEB_PASSWORD_HASH` value for the + * `tau hash-password`: print the `TAU_PASSWORD_HASH` value for the * password read from stdin. * @returns {Promise} process exit code */ @@ -136,21 +136,21 @@ async function runHashPasswordCommand(options = {}) { /** * Resolve the password hash an installer should write: an existing - * `OMP_WEB_PASSWORD_HASH`, or a plaintext `OMP_WEB_PASSWORD` hashed here. + * `TAU_PASSWORD_HASH`, or a plaintext `TAU_PASSWORD` hashed here. * Reading a plaintext password is allowed on this side only — the hash is what * gets stored, and the plaintext never reaches a service definition or a child * process. Returns null when neither is configured, and throws when a hash was * given but is unusable (silently dropping it would disable auth). */ function resolvePasswordHash(env = process.env) { - const existing = typeof env.OMP_WEB_PASSWORD_HASH === "string" ? env.OMP_WEB_PASSWORD_HASH.trim() : ""; + const existing = typeof env.TAU_PASSWORD_HASH === "string" ? env.TAU_PASSWORD_HASH.trim() : ""; if (existing) { if (!isPasswordHash(existing)) { - throw new Error("OMP_WEB_PASSWORD_HASH is not a valid password hash; generate one with: ompweb hash-password"); + throw new Error("TAU_PASSWORD_HASH is not a valid password hash; generate one with: tau hash-password"); } return existing; } - const plaintext = env.OMP_WEB_PASSWORD; + const plaintext = env.TAU_PASSWORD; return typeof plaintext === "string" && plaintext.length > 0 ? hashPassword(plaintext) : null; } diff --git a/bin/omp-web-hash-password.test.mjs b/bin/tau-hash-password.test.mjs similarity index 90% rename from bin/omp-web-hash-password.test.mjs rename to bin/tau-hash-password.test.mjs index 32a86b60..e0a7b9ae 100644 --- a/bin/omp-web-hash-password.test.mjs +++ b/bin/tau-hash-password.test.mjs @@ -5,8 +5,8 @@ import { fileURLToPath } from "node:url"; import test from "node:test"; const require = createRequire(import.meta.url); -const { verifyPassword } = require("./omp-web-password-hash.js"); -const launcher = fileURLToPath(new URL("./omp-web.js", import.meta.url)); +const { verifyPassword } = require("./tau-password-hash.js"); +const launcher = fileURLToPath(new URL("./tau.js", import.meta.url)); // util-linux `script` gives the command a real terminal, so the prompt runs in raw mode. const hasScript = process.platform === "linux" && spawnSync("script", ["--version"]).status === 0; diff --git a/bin/omp-web-host.js b/bin/tau-host.js similarity index 53% rename from bin/omp-web-host.js rename to bin/tau-host.js index 25c7f8e5..ef1ca908 100755 --- a/bin/omp-web-host.js +++ b/bin/tau-host.js @@ -1,21 +1,21 @@ #!/usr/bin/env node "use strict"; -// `ompweb host`: link this machine to a main omp-web so sessions can run here (lib/hosts/host-cli.ts). -// ompweb host login --url reads the host token from stdin -// ompweb host [--allow-http] dials the saved server and keeps the link up (http:// is accepted without the flag for loopback) +// `tau host`: link this machine to a main tau so sessions can run here (lib/hosts/host-cli.ts). +// tau host login --url reads the host token from stdin +// tau host [--allow-http] dials the saved server and keeps the link up (http:// is accepted without the flag for loopback) // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); // The daemon finds its runner from here (lib/omp/omp-cli.ts), not from whatever cwd it was started in. -process.env.OMP_WEB_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); +process.env.TAU_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); // eslint-disable-next-line @typescript-eslint/no-require-imports const jiti = require("jiti").createJiti(__filename); jiti.import("../lib/hosts/host-cli.ts").then( ({ runHostCli }) => runHostCli(process.argv.slice(2)).then((code) => process.exit(code)), (error) => { - console.error(`ompweb host: ${error instanceof Error ? error.message : String(error)}`); + console.error(`tau host: ${error instanceof Error ? error.message : String(error)}`); process.exit(1); }, ); diff --git a/bin/omp-web-host.test.mjs b/bin/tau-host.test.mjs similarity index 88% rename from bin/omp-web-host.test.mjs rename to bin/tau-host.test.mjs index 799369b0..dcd384f4 100644 --- a/bin/omp-web-host.test.mjs +++ b/bin/tau-host.test.mjs @@ -7,15 +7,15 @@ import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { fileURLToPath } from "node:url"; -const bin = fileURLToPath(new URL("./omp-web.js", import.meta.url)); +const bin = fileURLToPath(new URL("./tau.js", import.meta.url)); // Windows has no signals: child.kill("SIGTERM") terminates the process outright, so the daemon's handler never runs. -test("SIGTERM to `ompweb host` stops the daemon itself, leaving no orphan", { skip: process.platform === "win32" && "Windows kills on SIGTERM without running handlers" }, async (t) => { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-cli-")); +test("SIGTERM to `tau host` stops the daemon itself, leaving no orphan", { skip: process.platform === "win32" && "Windows kills on SIGTERM without running handlers" }, async (t) => { + const scratch = mkdtempSync(join(tmpdir(), "tau-host-cli-")); const agentDir = join(scratch, "agent"); - mkdirSync(join(agentDir, "omp-web"), { recursive: true }); + mkdirSync(join(agentDir, "tau"), { recursive: true }); // Nothing listens on this loopback port: the daemon redials until it is stopped. - writeFileSync(join(agentDir, "omp-web", "host.json"), JSON.stringify({ url: "http://127.0.0.1:9", token: "t" }), { mode: 0o600 }); + writeFileSync(join(agentDir, "tau", "host.json"), JSON.stringify({ url: "http://127.0.0.1:9", token: "t" }), { mode: 0o600 }); const child = spawn("node", [bin, "host"], { env: { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: agentDir }, stdio: ["ignore", "pipe", "pipe"], @@ -43,9 +43,9 @@ test("SIGTERM to `ompweb host` stops the daemon itself, leaving no orphan", { sk assert.deepEqual(stopped, { code: 0, signal: null }, "the daemon's own stop handled the signal"); }); -/** Run `ompweb host login` with `input` on stdin (left open unless `end`). */ +/** Run `tau host login` with `input` on stdin (left open unless `end`). */ async function login(t, input, { end = true } = {}) { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-login-")); + const scratch = mkdtempSync(join(tmpdir(), "tau-host-login-")); const agentDir = join(scratch, "agent"); t.after(() => rmSync(scratch, { recursive: true, force: true })); const child = spawn("node", [bin, "host", "login", "--url", "http://127.0.0.1:9"], { @@ -59,17 +59,17 @@ async function login(t, input, { end = true } = {}) { child.stdin.write(input); if (end) child.stdin.end(); const code = await Promise.race([closed, sleep(10_000, "timeout", { ref: false })]); - const file = join(agentDir, "omp-web", "host.json"); + const file = join(agentDir, "tau", "host.json"); return { code, stderr, saved: existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null }; } -test("`ompweb host login` saves the first stdin line as the token", async (t) => { +test("`tau host login` saves the first stdin line as the token", async (t) => { const { code, saved } = await login(t, " tok-123 \nignored\n"); assert.equal(code, 0); assert.equal(saved?.token, "tok-123"); }); -test("`ompweb host login` refuses a token line over 4096 bytes without waiting for more input", async (t) => { +test("`tau host login` refuses a token line over 4096 bytes without waiting for more input", async (t) => { const { code, stderr, saved } = await login(t, "a".repeat(5000), { end: false }); assert.equal(code, 1); assert.match(stderr, /4096 bytes/); @@ -90,7 +90,7 @@ async function hostCommand(env, ...args) { } function controlFixture(t, { url, longRoot = false } = {}) { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-control-cli-")); + const scratch = mkdtempSync(join(tmpdir(), "tau-host-control-cli-")); const agentDir = join(scratch, ...(longRoot ? ["long-agent-directory-".repeat(10), "agent"] : ["agent"])); const omp = join(scratch, "fixture-omp"); writeFileSync(omp, `#!${process.execPath}\nconsole.log("18.0.0-cli-fixture");\n`, { mode: 0o700 }); @@ -98,10 +98,10 @@ function controlFixture(t, { url, longRoot = false } = {}) { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: agentDir, XDG_CONFIG_HOME: join(scratch, "config"), XDG_DATA_HOME: join(scratch, "data"), XDG_STATE_HOME: join(scratch, "state"), XDG_CACHE_HOME: join(scratch, "cache"), - OMP_WEB_OMP_BIN: omp, OMP_WEB_DISABLE_AUTOUPDATE: "1", + TAU_OMP_BIN: omp, TAU_DISABLE_AUTOUPDATE: "1", }; - mkdirSync(join(agentDir, "omp-web"), { recursive: true, mode: 0o700 }); - writeFileSync(join(agentDir, "omp-web", "host.json"), JSON.stringify({ url: url ?? "http://127.0.0.1:9", token: "private-cli-fixture-token" }), { mode: 0o600 }); + mkdirSync(join(agentDir, "tau"), { recursive: true, mode: 0o700 }); + writeFileSync(join(agentDir, "tau", "host.json"), JSON.stringify({ url: url ?? "http://127.0.0.1:9", token: "private-cli-fixture-token" }), { mode: 0o600 }); t.after(() => rmSync(scratch, { recursive: true, force: true })); return { scratch, agentDir, env }; } @@ -220,7 +220,7 @@ test("Windows: status/drain/resume reach the real daemon over its pipe; a duplic test("worker maintenance startup is drained before linking and can be explicitly resumed", async (t) => { const f = controlFixture(t); - const daemon = launchHost(t, { ...f.env, OMP_WEB_HOST_DRAINED: "1" }); + const daemon = launchHost(t, { ...f.env, TAU_HOST_DRAINED: "1" }); if (process.platform !== "win32") { const { hostControlPath } = await import("../lib/hosts/host-control.ts"); t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true })); @@ -233,11 +233,11 @@ test("worker maintenance startup is drained before linking and can be explicitly assert.equal(JSON.parse(resumed.stdout).drained, false); }); -test("`ompweb host login --add` and logout change only the selected URL without argv tokens", async (t) => { - const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-multi-login-")); +test("`tau host login --add` and logout change only the selected URL without argv tokens", async (t) => { + const scratch = mkdtempSync(join(tmpdir(), "tau-host-multi-login-")); const agentDir = join(scratch, "agent"); - const file = join(agentDir, "omp-web", "host.json"); - mkdirSync(join(agentDir, "omp-web"), { recursive: true }); + const file = join(agentDir, "tau", "host.json"); + mkdirSync(join(agentDir, "tau"), { recursive: true }); const primary = { url: "https://production.example", token: "production-secret" }; const staging = { url: "http://127.0.0.1:40000", token: "staging-secret" }; writeFileSync(file, JSON.stringify(primary)); diff --git a/bin/omp-web-launchd.js b/bin/tau-launchd.js similarity index 76% rename from bin/omp-web-launchd.js rename to bin/tau-launchd.js index 04b3688b..be77e112 100644 --- a/bin/omp-web-launchd.js +++ b/bin/tau-launchd.js @@ -4,11 +4,11 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); -// Install ompweb as a macOS launchd user agent (starts at login, restarts on crash). +// Install tau as a macOS launchd user agent (starts at login, restarts on crash). // -// Usage (installed as the `ompweb-launchd` bin, or run via npx / node directly): -// ompweb-launchd [install [package-spec]|uninstall|status] -// npx -p @ompweb-dev/tau@latest ompweb-launchd install +// Usage (installed as the `tau-launchd` bin, or run via npx / node directly): +// tau-launchd [install [package-spec]|uninstall|status] +// npx -p @ompweb-dev/tau@latest tau-launchd install // eslint-disable-next-line @typescript-eslint/no-require-imports const { spawnSync } = require("node:child_process"); @@ -19,15 +19,15 @@ const os = require("node:os"); // eslint-disable-next-line @typescript-eslint/no-require-imports const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { resolvePasswordHash } = require("./omp-web-hash-password"); +const { resolvePasswordHash } = require("./tau-hash-password"); -const LABEL = "com.kahme247.ompweb"; -// The host daemon links this machine to an omp-web (`ompweb host`); it runs next to the web agent. -const HOST_LABEL = "com.kahme247.ompweb-host"; +const LABEL = "dev.ompweb.tau"; +// The host daemon links this machine to an tau (`tau host`); it runs next to the web agent. +const HOST_LABEL = "dev.ompweb.tau-host"; const HOME = os.homedir(); const PLIST = path.join(HOME, "Library", "LaunchAgents", `${LABEL}.plist`); const HOST_PLIST = path.join(HOME, "Library", "LaunchAgents", `${HOST_LABEL}.plist`); -const LOG_DIR = path.join(HOME, "Library", "Logs", "ompweb"); +const LOG_DIR = path.join(HOME, "Library", "Logs", "tau"); const DOMAIN = `gui/${process.getuid?.() ?? 0}`; function fail(message) { @@ -97,7 +97,7 @@ ${envXml} function buildHostEnv({ svcPath, ompBin, agentDir }) { return { PATH: svcPath, - ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + ...(ompBin ? { TAU_OMP_BIN: ompBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; } @@ -107,31 +107,31 @@ function install(pkgArg) { const siblingNpx = path.join(path.dirname(nodeBin), "npx"); const npxBin = isExecutableFile(siblingNpx) ? siblingNpx : (which("npx") ?? fail("npx not found on PATH")); - // Only an explicit override: ompweb runs its own omp (ompweb-omp). A stock omp on PATH cannot run its sessions. - const ompBin = process.env.OMP_WEB_OMP_BIN || null; + // Only an explicit override: tau runs its own omp (tau-omp). A stock omp on PATH cannot run its sessions. + const ompBin = process.env.TAU_OMP_BIN || null; if (ompBin) { try { fs.accessSync(ompBin, fs.constants.X_OK); } catch { - fail(`OMP_WEB_OMP_BIN=${ompBin} is not executable`); + fail(`TAU_OMP_BIN=${ompBin} is not executable`); } } - const pkg = pkgArg ?? process.env.OMP_WEB_PKG ?? "@ompweb-dev/tau@latest"; - const port = process.env.PORT ?? "30177"; - const hostname = process.env.OMP_WEB_HOSTNAME ?? "127.0.0.1"; - const noOpen = process.env.OMP_WEB_NO_OPEN ?? "1"; - const disableAutoUpdate = process.env.OMP_WEB_DISABLE_AUTOUPDATE; - const installName = process.env.OMP_WEB_NAME; - // Only a hash is stored in the plist: omp-web never forwards a plaintext - // password, and `OMP_WEB_PASSWORD` set for this install is hashed here. + const pkg = pkgArg ?? process.env.TAU_PKG ?? "@ompweb-dev/tau@latest"; + const port = process.env.PORT ?? "30187"; + const hostname = process.env.TAU_HOSTNAME ?? "127.0.0.1"; + const noOpen = process.env.TAU_NO_OPEN ?? "1"; + const disableAutoUpdate = process.env.TAU_DISABLE_AUTOUPDATE; + const installName = process.env.TAU_NAME; + // Only a hash is stored in the plist: tau never forwards a plaintext + // password, and `TAU_PASSWORD` set for this install is hashed here. let passwordHash; try { passwordHash = resolvePasswordHash(); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } - const trustedHeaderDigest = process.env.OMP_WEB_TRUSTED_HEADER_SHA256; + const trustedHeaderDigest = process.env.TAU_TRUSTED_HEADER_SHA256; const agentDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, HOME); const asdfBin = which("asdf"); @@ -149,21 +149,21 @@ function install(pkgArg) { const env = { PATH: svcPath, PORT: port, - OMP_WEB_HOSTNAME: hostname, - OMP_WEB_NO_OPEN: noOpen, - ...(disableAutoUpdate ? { OMP_WEB_DISABLE_AUTOUPDATE: disableAutoUpdate } : {}), - ...(installName ? { OMP_WEB_NAME: installName } : {}), - ...(passwordHash ? { OMP_WEB_PASSWORD_HASH: passwordHash } : {}), - ...(trustedHeaderDigest ? { OMP_WEB_TRUSTED_HEADER_SHA256: trustedHeaderDigest } : {}), - ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + TAU_HOSTNAME: hostname, + TAU_NO_OPEN: noOpen, + ...(disableAutoUpdate ? { TAU_DISABLE_AUTOUPDATE: disableAutoUpdate } : {}), + ...(installName ? { TAU_NAME: installName } : {}), + ...(passwordHash ? { TAU_PASSWORD_HASH: passwordHash } : {}), + ...(trustedHeaderDigest ? { TAU_TRUSTED_HEADER_SHA256: trustedHeaderDigest } : {}), + ...(ompBin ? { TAU_OMP_BIN: ompBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; - const web = buildPlist({ label: LABEL, args: [npxBin, "--yes", pkg], env, logName: "ompweb" }); + const web = buildPlist({ label: LABEL, args: [npxBin, "--yes", pkg], env, logName: "tau" }); const host = buildPlist({ label: HOST_LABEL, args: [npxBin, "--yes", pkg, "host"], env: buildHostEnv({ svcPath, ompBin, agentDir }), - logName: "ompweb-host", + logName: "tau-host", // host.json does not exist until the web server first starts; the daemon exits until then. throttleInterval: 10, }); @@ -184,7 +184,7 @@ function install(pkgArg) { console.log(`installed: ${HOST_PLIST}`); console.log(`package: ${pkg} (via npx --yes)`); console.log(`url: http://${hostname}:${port}`); - console.log(`logs: ${path.join(LOG_DIR, "ompweb.log")}, ${path.join(LOG_DIR, "ompweb-host.log")}`); + console.log(`logs: ${path.join(LOG_DIR, "tau.log")}, ${path.join(LOG_DIR, "tau-host.log")}`); if (passwordHash) console.log("note: the password hash is stored in the plist (mode 600)"); } @@ -220,7 +220,7 @@ function main() { else if (command === "uninstall") uninstall(); else if (command === "status") status(); else { - console.error("usage: ompweb-launchd [install [package-spec]|uninstall|status]"); + console.error("usage: tau-launchd [install [package-spec]|uninstall|status]"); process.exit(2); } } diff --git a/bin/omp-web-launchd.test.mjs b/bin/tau-launchd.test.mjs similarity index 73% rename from bin/omp-web-launchd.test.mjs rename to bin/tau-launchd.test.mjs index e0b96096..324e33dd 100644 --- a/bin/omp-web-launchd.test.mjs +++ b/bin/tau-launchd.test.mjs @@ -3,29 +3,29 @@ import { createRequire } from "node:module"; import test from "node:test"; const require = createRequire(import.meta.url); -const { HOST_LABEL, LABEL, buildHostEnv, buildPlist } = require("./omp-web-launchd.js"); +const { HOST_LABEL, LABEL, buildHostEnv, buildPlist } = require("./tau-launchd.js"); const env = { PATH: "/usr/bin", PI_CODING_AGENT_DIR: "/Users/u/agent" }; -test("the host daemon plist runs `ompweb host`, restarts with KeepAlive, and is throttled", () => { +test("the host daemon plist runs `tau host`, restarts with KeepAlive, and is throttled", () => { const plist = buildPlist({ label: HOST_LABEL, args: ["/usr/local/bin/npx", "--yes", "@ompweb-dev/tau@latest", "host"], env, - logName: "ompweb-host", + logName: "tau-host", throttleInterval: 10, }); - assert.equal(HOST_LABEL, "com.kahme247.ompweb-host"); - assert.match(plist, /Label<\/key>com\.kahme247\.ompweb-host<\/string>/); + assert.equal(HOST_LABEL, "dev.ompweb.tau-host"); + assert.match(plist, /Label<\/key>dev\.ompweb\.tau-host<\/string>/); assert.match(plist, /@ompweb-dev\/tau@latest<\/string>\n host<\/string>\n <\/array>/); assert.match(plist, /KeepAlive<\/key>/); assert.match(plist, /ThrottleInterval<\/key>10<\/integer>/); assert.match(plist, /PI_CODING_AGENT_DIR<\/key>\/Users\/u\/agent<\/string>/); - assert.match(plist, /ompweb-host\.log<\/string>/); + assert.match(plist, /tau-host\.log<\/string>/); }); test("the web plist keeps its arguments and has no throttle", () => { - const plist = buildPlist({ label: LABEL, args: ["/usr/local/bin/npx", "--yes", "pkg & co"], env, logName: "ompweb" }); + const plist = buildPlist({ label: LABEL, args: ["/usr/local/bin/npx", "--yes", "pkg & co"], env, logName: "tau" }); assert.match(plist, /pkg & co<\/string>\n <\/array>/); assert.match(plist, /KeepAlive<\/key>/); assert.doesNotMatch(plist, /ThrottleInterval/); @@ -34,6 +34,6 @@ test("the web plist keeps its arguments and has no throttle", () => { test("the host env carries PATH, the omp binary and the agent dir, but no web settings", () => { const all = buildHostEnv({ svcPath: "/usr/bin", ompBin: "/opt/omp/bin/omp", agentDir: "/Users/u/agent" }); - assert.deepEqual(all, { PATH: "/usr/bin", OMP_WEB_OMP_BIN: "/opt/omp/bin/omp", PI_CODING_AGENT_DIR: "/Users/u/agent" }); + assert.deepEqual(all, { PATH: "/usr/bin", TAU_OMP_BIN: "/opt/omp/bin/omp", PI_CODING_AGENT_DIR: "/Users/u/agent" }); assert.deepEqual(buildHostEnv({ svcPath: "/usr/bin" }), { PATH: "/usr/bin" }); }); diff --git a/bin/omp-web-options.js b/bin/tau-options.js similarity index 67% rename from bin/omp-web-options.js rename to bin/tau-options.js index af13f322..c6c7438f 100644 --- a/bin/omp-web-options.js +++ b/bin/tau-options.js @@ -3,7 +3,7 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports const { parseArgs } = require("util"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { hashPassword, isPasswordHash } = require("./omp-web-password-hash"); +const { hashPassword, isPasswordHash } = require("./tau-password-hash"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { isLoopbackHost } = require("./network-addresses"); // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -15,7 +15,7 @@ function isEnabled(value) { return typeof value === "string" && TRUE_VALUES.has(value.trim().toLowerCase()); } -/** Legacy plaintext credential: detected so `ompweb` can migrate (env) or refuse (flag) it. */ +/** Legacy plaintext credential: detected so `tau` can migrate (env) or refuse (flag) it. */ function legacyPassword(args, env) { const flagIndex = args.findIndex((arg) => arg === "--password" || arg.startsWith("--password=")); if (flagIndex !== -1) { @@ -24,17 +24,17 @@ function legacyPassword(args, env) { const value = inline !== undefined ? inline : (args[flagIndex + 1] ?? ""); return { value, source: "flag" }; } - const fromEnv = env.OMP_WEB_PASSWORD; + const fromEnv = env.TAU_PASSWORD; if (typeof fromEnv === "string" && fromEnv.length > 0) return { value: fromEnv, source: "env" }; return undefined; } function printHelp() { - console.log(`Usage: ompweb [options] + console.log(`Usage: tau [options] Options: - -p, --port Server port (default 30177, env PORT) - -H, --hostname Bind hostname (default 127.0.0.1, env OMP_WEB_HOSTNAME) + -p, --port Server port (default 30187, env PORT) + -H, --hostname Bind hostname (default 127.0.0.1, env TAU_HOSTNAME) --no-open Do not open the browser automatically --install-tray Install system tray service & shortcuts (Windows tray / Linux SNI tray) --uninstall-tray Uninstall system tray service & shortcuts @@ -44,16 +44,16 @@ Options: Commands: hash-password Read a password from stdin and print the value for - OMP_WEB_PASSWORD_HASH + TAU_PASSWORD_HASH Password: - ompweb hash-password # prompts, input hidden - echo "a-long-random-password" | ompweb hash-password - OMP_WEB_PASSWORD_HASH='scrypt$15$8$1$...' ompweb + tau hash-password # prompts, input hidden + echo "a-long-random-password" | tau hash-password + TAU_PASSWORD_HASH='scrypt$15$8$1$...' tau - ompweb never passes a plaintext password on: --password is rejected, and an - OMP_WEB_PASSWORD is hashed at startup with a warning that prints its hash - (set alongside OMP_WEB_PASSWORD_HASH, it is rejected), because every omp + tau never passes a plaintext password on: --password is rejected, and an + TAU_PASSWORD is hashed at startup with a warning that prints its hash + (set alongside TAU_PASSWORD_HASH, it is rejected), because every omp session inherits the environment and an agent could print the password into its transcript. @@ -85,17 +85,17 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { strict: false, }); - const passwordHash = typeof env.OMP_WEB_PASSWORD_HASH === "string" ? env.OMP_WEB_PASSWORD_HASH.trim() : undefined; + const passwordHash = typeof env.TAU_PASSWORD_HASH === "string" ? env.TAU_PASSWORD_HASH.trim() : undefined; const legacy = legacyPassword(args, env); - const port = String(cliArgs.port ?? env.PORT ?? "30177"); + const port = String(cliArgs.port ?? env.PORT ?? "30187"); const shared = { port, - hostname: cliArgs.hostname ?? env.OMP_WEB_HOSTNAME ?? "127.0.0.1", + hostname: cliArgs.hostname ?? env.TAU_HOSTNAME ?? "127.0.0.1", passwordHash, legacyPassword: legacy?.value, legacyPasswordSource: legacy?.source, - openBrowser: !cliArgs["no-open"] && !isEnabled(env.OMP_WEB_NO_OPEN), + openBrowser: !cliArgs["no-open"] && !isEnabled(env.TAU_NO_OPEN), installTray: Boolean(cliArgs["install-tray"] || cliArgs["install-service"]), uninstallTray: Boolean(cliArgs["uninstall-tray"]), tray: Boolean(cliArgs.tray), @@ -110,7 +110,7 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { } catch { console.log("0.0.0"); } return { ...shared, version: true }; } - // Expose help flag without exiting here — caller (bin/omp-web.js) decides + // Expose help flag without exiting here — caller (bin/tau.js) decides // whether to exit, keeping parseLaunchOptions testable. Print here so // --help works even when the caller is a test. if (cliArgs.help) { @@ -121,8 +121,8 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { } /** - * The password and bind checks before a server starts (bin/omp-web.js, server/binary.ts). Only a password hash reaches - * the server (issue #239): a plaintext OMP_WEB_PASSWORD alone is migrated, hashed into OMP_WEB_PASSWORD_HASH and + * The password and bind checks before a server starts (bin/tau.js, server/binary.ts). Only a password hash reaches + * the server (issue #239): a plaintext TAU_PASSWORD alone is migrated, hashed into TAU_PASSWORD_HASH and * removed from process.env before any child can inherit it. The removed --password flag, a plaintext set next to a * hash, an invalid hash, or a non-loopback bind without a password print why and exit 1. * @returns {string | undefined} the password hash, if any @@ -130,59 +130,59 @@ function parseLaunchOptions(args = process.argv.slice(2), env = process.env) { function checkLaunchSecurity(launchOptions) { let passwordHash = launchOptions.passwordHash; if (launchOptions.legacyPasswordSource === "env" && !passwordHash) { - passwordHash = hashPassword(process.env.OMP_WEB_PASSWORD); - process.env.OMP_WEB_PASSWORD_HASH = passwordHash; - delete process.env.OMP_WEB_PASSWORD; + passwordHash = hashPassword(process.env.TAU_PASSWORD); + process.env.TAU_PASSWORD_HASH = passwordHash; + delete process.env.TAU_PASSWORD; console.warn([ - "Warning: OMP_WEB_PASSWORD holds a plaintext password. This option has been deprecated and is marked for removal.", + "Warning: TAU_PASSWORD holds a plaintext password. This option has been deprecated and is marked for removal.", "", - "Every omp session inherits omp-web's environment, so an agent could print", - "the password into its transcript. ompweb hashed it and kept it out of the", + "Every omp session inherits tau's environment, so an agent could print", + "the password into its transcript. tau hashed it and kept it out of the", "server's environment, but agents can still read it from this launcher", "process, and a new hash is made on every start, which signs every browser", "out on each restart.", "", - "Remove OMP_WEB_PASSWORD and set this instead:", + "Remove TAU_PASSWORD and set this instead:", "", - ` OMP_WEB_PASSWORD_HASH='${passwordHash}'`, + ` TAU_PASSWORD_HASH='${passwordHash}'`, ].join("\n")); } else if (launchOptions.legacyPasswordSource === "env") { - console.error("OMP_WEB_PASSWORD_HASH and the plaintext OMP_WEB_PASSWORD are both set. Remove OMP_WEB_PASSWORD."); + console.error("TAU_PASSWORD_HASH and the plaintext TAU_PASSWORD are both set. Remove TAU_PASSWORD."); process.exit(1); } else if (launchOptions.legacyPassword !== undefined) { console.error([ - "ompweb no longer accepts a plaintext password: the --password flag was removed.", + "tau no longer accepts a plaintext password: the --password flag was removed.", "Every omp session inherits this process's environment, so an agent could", "print the password into its transcript.", "", "Create a hash and use that instead:", "", - " ompweb hash-password", - " OMP_WEB_PASSWORD_HASH='scrypt$...' ompweb", + " tau hash-password", + " TAU_PASSWORD_HASH='scrypt$...' tau", ].join("\n")); process.exit(1); } if (passwordHash !== undefined && !isPasswordHash(passwordHash)) { - console.error(`OMP_WEB_PASSWORD_HASH is not a valid password hash.\n\nGenerate one with: ompweb hash-password`); + console.error(`TAU_PASSWORD_HASH is not a valid password hash.\n\nGenerate one with: tau hash-password`); process.exit(1); } const { hostname } = launchOptions; if (!isLoopbackHost(hostname)) { if (passwordHash === undefined) { - console.error(`Refusing to listen on ${hostname} without a password hash. Run: ompweb hash-password, then set OMP_WEB_PASSWORD_HASH. Or bind to 127.0.0.1.`); + console.error(`Refusing to listen on ${hostname} without a password hash. Run: tau hash-password, then set TAU_PASSWORD_HASH. Or bind to 127.0.0.1.`); process.exit(1); } - console.warn(`Warning: ompweb is listening on ${hostname} over HTTP. Use HTTPS or a trusted VPN to protect the password and session cookie in transit.`); + console.warn(`Warning: tau is listening on ${hostname} over HTTP. Use HTTPS or a trusted VPN to protect the password and session cookie in transit.`); } return passwordHash; } // The server must not start inside the installation: on Windows a live process whose working // directory is the package blocks the rename an in-place update performs -// (ERROR_SHARING_VIOLATION). The entry point and OMP_WEB_PACKAGE_DIR are absolute, so the +// (ERROR_SHARING_VIOLATION). The entry point and TAU_PACKAGE_DIR are absolute, so the // server does not need the installation as its directory. function serverWorkingDirectory(home = os.homedir()) { - if (!home) throw new Error("Cannot start ompweb: the home directory is empty, and the server must not run inside its installation."); + if (!home) throw new Error("Cannot start tau: the home directory is empty, and the server must not run inside its installation."); return home; } diff --git a/bin/omp-web-password-hash.js b/bin/tau-password-hash.js similarity index 96% rename from bin/omp-web-password-hash.js rename to bin/tau-password-hash.js index 54a18048..ab0b1ec0 100644 --- a/bin/omp-web-password-hash.js +++ b/bin/tau-password-hash.js @@ -1,8 +1,8 @@ "use strict"; -// The `OMP_WEB_PASSWORD_HASH` format, in one place. This file must stay plain +// The `TAU_PASSWORD_HASH` format, in one place. This file must stay plain // CJS JS with no dependencies beyond node:crypto: the packaged launcher -// (bin/omp-web.js) validates and hashes before the server exists, lib/web-password-hash.ts +// (bin/tau.js) validates and hashes before the server exists, lib/web-password-hash.ts // is the typed view of it for the server, and the service installers hash the // password they write. See issue #239. diff --git a/bin/omp-web-security.test.mjs b/bin/tau-security.test.mjs similarity index 72% rename from bin/omp-web-security.test.mjs rename to bin/tau-security.test.mjs index 8c623ed1..24eed356 100644 --- a/bin/omp-web-security.test.mjs +++ b/bin/tau-security.test.mjs @@ -8,12 +8,12 @@ import { fileURLToPath } from "node:url"; import test from "node:test"; const require = createRequire(import.meta.url); -const { verifyPassword } = require("./omp-web-password-hash.js"); +const { verifyPassword } = require("./tau-password-hash.js"); const binDir = fileURLToPath(new URL(".", import.meta.url)); /** Run the launcher against a stub `server/main.ts` that records the environment it was started with. */ async function launch(env, args = []) { - const pkg = await mkdtemp(join(tmpdir(), "ompweb-launch-")); + const pkg = await mkdtemp(join(tmpdir(), "tau-launch-")); try { await mkdir(join(pkg, "bin")); for (const name of await readdir(binDir)) { @@ -26,7 +26,7 @@ async function launch(env, args = []) { // The package has no bun dependency, so the launcher runs this under the Bun on PATH: this test's own, // as on Windows npm puts only a bun.cmd shim there, which a spawn without a shell cannot run. await writeFile(join(pkg, "server", "main.ts"), `require("fs").writeFileSync(${JSON.stringify(dump)}, JSON.stringify(process.env));`); - const result = spawnSync("node", [join(pkg, "bin", "omp-web.js"), "--no-open", "-p", "0", ...args], { + const result = spawnSync("node", [join(pkg, "bin", "tau.js"), "--no-open", "-p", "0", ...args], { env: { PATH: [dirname(process.execPath), process.env.PATH].join(delimiter), HOME: pkg, ...env }, encoding: "utf8", timeout: 20_000, @@ -45,19 +45,19 @@ test("launcher refuses unauthenticated non-loopback binds", async () => { assert.equal(serverEnv, null); }); -test("launcher hands the server a hash of a plaintext OMP_WEB_PASSWORD, never the plaintext", async () => { - const { stderr, serverEnv } = await launch({ OMP_WEB_PASSWORD: "s3cret pw" }); +test("launcher hands the server a hash of a plaintext TAU_PASSWORD, never the plaintext", async () => { + const { stderr, serverEnv } = await launch({ TAU_PASSWORD: "s3cret pw" }); assert.ok(serverEnv, stderr); - assert.equal(serverEnv.OMP_WEB_PASSWORD, undefined); - const hash = serverEnv.OMP_WEB_PASSWORD_HASH; + assert.equal(serverEnv.TAU_PASSWORD, undefined); + const hash = serverEnv.TAU_PASSWORD_HASH; assert.equal(verifyPassword("s3cret pw", hash), true); - assert.ok(stderr.includes(`OMP_WEB_PASSWORD_HASH='${hash}'`), stderr); + assert.ok(stderr.includes(`TAU_PASSWORD_HASH='${hash}'`), stderr); assert.ok(!stderr.includes("s3cret pw"), stderr); }); -test("launcher refuses a plaintext OMP_WEB_PASSWORD next to a hash", async () => { - const { hashPassword } = require("./omp-web-password-hash.js"); - const { status, serverEnv } = await launch({ OMP_WEB_PASSWORD: "s3cret pw", OMP_WEB_PASSWORD_HASH: hashPassword("other") }); +test("launcher refuses a plaintext TAU_PASSWORD next to a hash", async () => { + const { hashPassword } = require("./tau-password-hash.js"); + const { status, serverEnv } = await launch({ TAU_PASSWORD: "s3cret pw", TAU_PASSWORD_HASH: hashPassword("other") }); assert.equal(status, 1); assert.equal(serverEnv, null); }); diff --git a/bin/omp-web-systemd.js b/bin/tau-systemd.js similarity index 83% rename from bin/omp-web-systemd.js rename to bin/tau-systemd.js index b89c82b8..01d01084 100644 --- a/bin/omp-web-systemd.js +++ b/bin/tau-systemd.js @@ -4,11 +4,11 @@ // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); -// Install ompweb as a Linux systemd user service. +// Install tau as a Linux systemd user service. // // Usage: -// ompweb-systemd [install|uninstall|start|stop|restart|status|open] -// npx --yes --package=@ompweb-dev/tau@latest ompweb-systemd install +// tau-systemd [install|uninstall|start|stop|restart|status|open] +// npx --yes --package=@ompweb-dev/tau@latest tau-systemd install // // `install` creates ~/.omp/agent/web-service.env. The file is deliberately // separate from the unit so port, hostname, password, and omp path can be @@ -27,24 +27,24 @@ const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { getServiceEnvPath, readServiceEnv, writeServiceEnv } = require("./service-env"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { resolvePasswordHash } = require("./omp-web-hash-password"); +const { resolvePasswordHash } = require("./tau-hash-password"); -const UNIT_NAME = "ompweb"; +const UNIT_NAME = "tau"; const UNIT = `${UNIT_NAME}.service`; const HOME = os.homedir(); const UNIT_DIR = path.join(HOME, ".config", "systemd", "user"); const UNIT_PATH = path.join(UNIT_DIR, UNIT); -// The host daemon links this machine to an omp-web (`ompweb host`); it runs next to the web unit. -const HOST_UNIT_NAME = "ompweb-host"; +// The host daemon links this machine to an tau (`tau host`); it runs next to the web unit. +const HOST_UNIT_NAME = "tau-host"; const HOST_UNIT = `${HOST_UNIT_NAME}.service`; const HOST_UNIT_PATH = path.join(UNIT_DIR, HOST_UNIT); const UNITS = [UNIT, HOST_UNIT]; const ENV_PATH = getServiceEnvPath(); -const DEFAULT_PORT = "30177"; +const DEFAULT_PORT = "30187"; const DEFAULT_HOSTNAME = "127.0.0.1"; function printHelp() { - console.log(`Usage: ompweb-systemd [command] [options] + console.log(`Usage: tau-systemd [command] [options] Commands: install Install the web and host-daemon user services, create the env file, and enable them @@ -58,7 +58,7 @@ Commands: Options: -p, --port Server port (default ${DEFAULT_PORT}, env PORT) - -H, --hostname Bind address (default ${DEFAULT_HOSTNAME}, env OMP_WEB_HOSTNAME) + -H, --hostname Bind address (default ${DEFAULT_HOSTNAME}, env TAU_HOSTNAME) --no-autostart Install and start, but do not enable at login --clean-config Also remove web-service.env on uninstall --json Output status as JSON @@ -66,7 +66,7 @@ Options: -v, --version Show version For LAN access, install with: - OMP_WEB_HOSTNAME=0.0.0.0 OMP_WEB_PASSWORD='change-me' ompweb-systemd install + TAU_HOSTNAME=0.0.0.0 TAU_PASSWORD='change-me' tau-systemd install (the plaintext password is hashed before it is written to the env file) `); } @@ -198,21 +198,21 @@ function formatExecStart(value) { return /\s/.test(String(value)) ? `"${escaped}"` : escaped; } -// Resolve the ompweb binary the unit will run. An explicit override wins, +// Resolve the tau binary the unit will run. An explicit override wins, // followed by the sibling of node (npm/bun global installs), then PATH. -function resolveOmpwebBin(env = process.env) { - const override = env.OMP_WEB_SYSTEMD_BIN; +function resolveTauBin(env = process.env) { + const override = env.TAU_SYSTEMD_BIN; if (override) { - if (!isExecutableFile(override)) throw new Error(`OMP_WEB_SYSTEMD_BIN=${override} is not executable`); + if (!isExecutableFile(override)) throw new Error(`TAU_SYSTEMD_BIN=${override} is not executable`); return override; } - const sibling = path.join(path.dirname(process.execPath), "ompweb"); + const sibling = path.join(path.dirname(process.execPath), "tau"); if (isExecutableFile(sibling)) return sibling; - const onPath = which("ompweb", env); + const onPath = which("tau", env); if (onPath) return onPath; - throw new Error("ompweb binary not found (next to node or on PATH); set OMP_WEB_SYSTEMD_BIN"); + throw new Error("tau binary not found (next to node or on PATH); set TAU_SYSTEMD_BIN"); } function validatePort(value) { const port = Number(value); @@ -231,9 +231,9 @@ function validateHostname(value) { // Build the unit file text. Runtime settings belong in EnvironmentFile so the // tray or an editor can change them without reinstalling the unit. The web and // host units share the env file: same user, same HOME and PI_CODING_AGENT_DIR, -// so both read the same /omp-web/host.json. -function buildUnitText({ description, execArgs, restart, ompwebBin, env: extraEnv, home, envPath }) { - const ompBin = extraEnv.OMP_WEB_OMP_BIN ?? null; +// so both read the same /tau/host.json. +function buildUnitText({ description, execArgs, restart, tauBin, env: extraEnv, home, envPath }) { + const ompBin = extraEnv.TAU_OMP_BIN ?? null; const interpreterDir = ompBin ? launcherInterpreterDir(ompBin) : null; const pathDirs = [ ...(ompBin ? [path.dirname(ompBin)] : []), @@ -241,7 +241,7 @@ function buildUnitText({ description, execArgs, restart, ompwebBin, env: extraEn // interpreter resolved via `env`; without its directory the service // fails with exit 127 even though the binary itself is on PATH (#116). ...(interpreterDir ? [interpreterDir] : []), - path.dirname(ompwebBin), + path.dirname(tauBin), path.dirname(process.execPath), path.join(home, ".local", "bin"), "/usr/local/bin", @@ -249,7 +249,7 @@ function buildUnitText({ description, execArgs, restart, ompwebBin, env: extraEn "/bin", ].filter((dir, index, all) => all.indexOf(dir) === index); - return `# Generated by ompweb-systemd — edits are overwritten on reinstall. + return `# Generated by tau-systemd — edits are overwritten on reinstall. [Unit] Description=${description} Documentation=${readPackageHomepage()} @@ -259,7 +259,7 @@ ${restart.startLimit} [Service] Type=simple WorkingDirectory=%h -ExecStart=${formatExecStart(ompwebBin)}${execArgs} +ExecStart=${formatExecStart(tauBin)}${execArgs} Environment=${environmentLine([["PATH", pathDirs.join(path.delimiter)]])} EnvironmentFile=${escapeUnitPath(envPath)} Restart=${restart.policy} @@ -270,12 +270,12 @@ WantedBy=default.target `; } -function buildUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { +function buildUnit({ tauBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { return buildUnitText({ - description: "ompweb web service (oh-my-pi web UI)", + description: "tau web service (oh-my-pi web UI)", execArgs: "", restart: { policy: "on-failure", delay: 3, startLimit: "StartLimitIntervalSec=60\nStartLimitBurst=5\n" }, - ompwebBin, env, home, envPath, + tauBin, env, home, envPath, }); } @@ -283,12 +283,12 @@ function buildUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPa // server writes it at startup) and when the server revokes or outdates its // token. Restart=always with a 10 s delay covers all of those, and // StartLimitIntervalSec=0 keeps systemd from giving up while it waits. -function buildHostUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { +function buildHostUnit({ tauBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { return buildUnitText({ - description: "ompweb host daemon (links this machine to an ompweb server)", + description: "tau host daemon (links this machine to an tau server)", execArgs: " host", restart: { policy: "always", delay: 10, startLimit: "StartLimitIntervalSec=0\n" }, - ompwebBin, env, home, envPath, + tauBin, env, home, envPath, }); } @@ -313,16 +313,16 @@ function systemdQuery(args) { } function install(options = {}) { - let ompwebBin; + let tauBin; try { - ompwebBin = resolveOmpwebBin(); + tauBin = resolveTauBin(); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } - // Only an explicit override: ompweb runs its own omp (ompweb-omp). A stock omp on PATH cannot run its sessions. - const ompBin = process.env.OMP_WEB_OMP_BIN || null; - if (ompBin && !isExecutableFile(ompBin)) fail(`OMP_WEB_OMP_BIN=${ompBin} is not executable`); + // Only an explicit override: tau runs its own omp (tau-omp). A stock omp on PATH cannot run its sessions. + const ompBin = process.env.TAU_OMP_BIN || null; + if (ompBin && !isExecutableFile(ompBin)) fail(`TAU_OMP_BIN=${ompBin} is not executable`); // Note: the missing-interpreter check lives in runCli (before the Linux // gate) so it fails loudly on every platform; install() only reuses the // resolved ompBin for the unit + env file. @@ -331,13 +331,13 @@ function install(options = {}) { let hostname; try { port = validatePort(options.port ?? process.env.PORT ?? DEFAULT_PORT); - hostname = validateHostname(options.hostname ?? process.env.OMP_WEB_HOSTNAME ?? DEFAULT_HOSTNAME); + hostname = validateHostname(options.hostname ?? process.env.TAU_HOSTNAME ?? DEFAULT_HOSTNAME); } catch (error) { fail(error instanceof Error ? error.message : String(error)); } - // Only the hash reaches the env file: omp-web never forwards a plaintext - // password, and `OMP_WEB_PASSWORD` set for this install is hashed here. + // Only the hash reaches the env file: tau never forwards a plaintext + // password, and `TAU_PASSWORD` set for this install is hashed here. let passwordHash; try { passwordHash = resolvePasswordHash(); @@ -347,8 +347,8 @@ function install(options = {}) { const agentDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, HOME); const envPath = getServiceEnvPath(); const unitOptions = { - ompwebBin, - env: ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}, + tauBin, + env: ompBin ? { TAU_OMP_BIN: ompBin } : {}, home: HOME, envPath, }; @@ -357,13 +357,13 @@ function install(options = {}) { // read by systemd on every start/restart, and is safe to edit by hand. writeServiceEnv({ PORT: port, - OMP_WEB_HOSTNAME: hostname, - OMP_WEB_NO_OPEN: process.env.OMP_WEB_NO_OPEN ?? "1", - ...(process.env.OMP_WEB_DISABLE_AUTOUPDATE ? { OMP_WEB_DISABLE_AUTOUPDATE: process.env.OMP_WEB_DISABLE_AUTOUPDATE } : {}), - ...(process.env.OMP_WEB_NAME ? { OMP_WEB_NAME: process.env.OMP_WEB_NAME } : {}), - ...(passwordHash ? { OMP_WEB_PASSWORD_HASH: passwordHash } : {}), - ...(process.env.OMP_WEB_TRUSTED_HEADER_SHA256 ? { OMP_WEB_TRUSTED_HEADER_SHA256: process.env.OMP_WEB_TRUSTED_HEADER_SHA256 } : {}), - ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + TAU_HOSTNAME: hostname, + TAU_NO_OPEN: process.env.TAU_NO_OPEN ?? "1", + ...(process.env.TAU_DISABLE_AUTOUPDATE ? { TAU_DISABLE_AUTOUPDATE: process.env.TAU_DISABLE_AUTOUPDATE } : {}), + ...(process.env.TAU_NAME ? { TAU_NAME: process.env.TAU_NAME } : {}), + ...(passwordHash ? { TAU_PASSWORD_HASH: passwordHash } : {}), + ...(process.env.TAU_TRUSTED_HEADER_SHA256 ? { TAU_TRUSTED_HEADER_SHA256: process.env.TAU_TRUSTED_HEADER_SHA256 } : {}), + ...(ompBin ? { TAU_OMP_BIN: ompBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }, envPath); @@ -385,7 +385,7 @@ function install(options = {}) { console.log(`installed: ${UNIT_PATH}`); console.log(`installed: ${HOST_UNIT_PATH}`); - console.log(`binary: ${ompwebBin}`); + console.log(`binary: ${tauBin}`); console.log(`config: ${envPath} (port/hostname/password — no reinstall needed)`); console.log(`url: http://${hostname}:${port}`); console.log(`logs: journalctl --user -u ${UNIT_NAME} -u ${HOST_UNIT_NAME} -f`); @@ -461,7 +461,7 @@ function readStatus() { const envConfig = readServiceEnv(); const configuredPort = Number.parseInt(envConfig.PORT ?? process.env.PORT ?? DEFAULT_PORT, 10); const port = Number.isInteger(configuredPort) ? configuredPort : Number(DEFAULT_PORT); - const hostname = envConfig.OMP_WEB_HOSTNAME ?? process.env.OMP_WEB_HOSTNAME ?? DEFAULT_HOSTNAME; + const hostname = envConfig.TAU_HOSTNAME ?? process.env.TAU_HOSTNAME ?? DEFAULT_HOSTNAME; return { isLinux: process.platform === "linux", ...web, @@ -480,7 +480,7 @@ function printStatus(asJson) { console.log(JSON.stringify(status, null, 2)); return status; } - console.log(`=== ompweb systemd service status (${process.platform}) ===`); + console.log(`=== tau systemd service status (${process.platform}) ===`); console.log(` Unit : ${status.unit} (${status.isInstalled ? status.unitPath : "not installed"})`); console.log(` Version : v${readPackageVersion()}`); console.log(` Active : ${status.isActive ? `Yes (pid ${status.pid})` : "No"}`); @@ -496,7 +496,7 @@ function printStatus(asJson) { function openInBrowser() { const status = readStatus(); - const openBin = process.env.OMP_WEB_OPEN ?? which("xdg-open") ?? "xdg-open"; + const openBin = process.env.TAU_OPEN ?? which("xdg-open") ?? "xdg-open"; const child = spawnSync(openBin, [status.serviceUrl], { stdio: "ignore", detached: true }); if (child.error) console.error(`Failed to open browser: ${child.error.message}`); else console.log(`Opening ${status.serviceUrl}...`); @@ -536,23 +536,23 @@ async function runCli(argv = process.argv.slice(2)) { // Validate the install inputs before the platform gate so misconfigured // launchers fail loudly on any platform (and stay testable on Windows). - // An OMP_WEB_OMP_BIN launcher script whose interpreter is nowhere on PATH + // An TAU_OMP_BIN launcher script whose interpreter is nowhere on PATH // would install a unit that can only fail later with exit 127 (issue #116) — fail now. if (command === "install") { - const ompBin = process.env.OMP_WEB_OMP_BIN || null; + const ompBin = process.env.TAU_OMP_BIN || null; if (ompBin && !isExecutableFile(ompBin)) { - fail(`OMP_WEB_OMP_BIN=${ompBin} is not executable`); + fail(`TAU_OMP_BIN=${ompBin} is not executable`); } else if (ompBin && readLauncherInterpreter(ompBin) && !launcherInterpreterDir(ompBin)) { fail( `omp at ${ompBin} is a launcher script whose interpreter ` + `(${readLauncherInterpreter(ompBin)}) was not found on PATH; ` + - `install that runtime (or point OMP_WEB_OMP_BIN at a standalone binary) and reinstall`, + `install that runtime (or point TAU_OMP_BIN at a standalone binary) and reinstall`, ); } } if (process.platform !== "linux") { - fail("systemd services are Linux-only (use ompweb-launchd on macOS or ompweb --install-tray on Windows)"); + fail("systemd services are Linux-only (use tau-launchd on macOS or tau --install-tray on Windows)"); } const installOptions = { @@ -615,7 +615,7 @@ module.exports = { launcherInterpreterDir, readLauncherInterpreter, readStatus, - resolveOmpwebBin, + resolveTauBin, runCli, validateHostname, validatePort, diff --git a/bin/omp-web-systemd.test.mjs b/bin/tau-systemd.test.mjs similarity index 67% rename from bin/omp-web-systemd.test.mjs rename to bin/tau-systemd.test.mjs index ceb2ae8b..c347f98a 100644 --- a/bin/omp-web-systemd.test.mjs +++ b/bin/tau-systemd.test.mjs @@ -17,41 +17,41 @@ const { formatExecStart, launcherInterpreterDir, readLauncherInterpreter, - resolveOmpwebBin, + resolveTauBin, runCli, validateHostname, validatePort, -} = require("./omp-web-systemd.js"); +} = require("./tau-systemd.js"); const { parseServiceEnv, serializeServiceEnv, writeServiceEnv, } = require("./service-env.js"); -const { hashPassword, verifyPassword } = require("./omp-web-password-hash.js"); +const { hashPassword, verifyPassword } = require("./tau-password-hash.js"); test("service env files round-trip quoted values", () => { const serialized = serializeServiceEnv({ - PORT: "30177", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: 'secret\\with"quotes', + PORT: "30187", + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: 'secret\\with"quotes', }); - assert.match(serialized, /OMP_WEB_PASSWORD="secret\\\\with\\"quotes"/); + assert.match(serialized, /TAU_PASSWORD="secret\\\\with\\"quotes"/); assert.deepEqual(parseServiceEnv(serialized), { - PORT: "30177", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: 'secret\\with"quotes', + PORT: "30187", + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: 'secret\\with"quotes', }); }); test("writeServiceEnv creates the parent directory and a private file", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-service-env-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-service-env-")); try { const envPath = path.join(dir, "nested", "web-service.env"); - writeServiceEnv({ PORT: "40100", OMP_WEB_HOSTNAME: "127.0.0.1" }, envPath); + writeServiceEnv({ PORT: "40100", TAU_HOSTNAME: "127.0.0.1" }, envPath); assert.deepEqual(parseServiceEnv(readFileSync(envPath, "utf8")), { PORT: "40100", - OMP_WEB_HOSTNAME: "127.0.0.1", + TAU_HOSTNAME: "127.0.0.1", }); if (process.platform !== "win32") assert.equal(statSync(envPath).mode & 0o777, 0o600); } finally { @@ -61,18 +61,18 @@ test("writeServiceEnv creates the parent directory and a private file", () => { test("buildUnit points at the generated env file and keeps runtime settings out of the unit", () => { const unit = buildUnit({ - ompwebBin: "/usr/local/bin/ompweb", - env: { OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp" }, + tauBin: "/usr/local/bin/tau", + env: { TAU_OMP_BIN: "/home/u/.bun/bin/omp" }, home: "/home/u", envPath: "/home/u/.omp/agent/web-service.env", }); - assert.match(unit, /ExecStart=\/usr\/local\/bin\/ompweb\n/); + assert.match(unit, /ExecStart=\/usr\/local\/bin\/tau\n/); assert.match(unit, /WorkingDirectory=%h/); assert.match(unit, /EnvironmentFile=\/home\/u\/\.omp\/agent\/web-service\.env/); assert.doesNotMatch(unit, /PORT=/); - assert.doesNotMatch(unit, /OMP_WEB_PASSWORD_HASH/); - assert.doesNotMatch(unit, /OMP_WEB_PASSWORD=/); + assert.doesNotMatch(unit, /TAU_PASSWORD_HASH/); + assert.doesNotMatch(unit, /TAU_PASSWORD=/); assert.match(unit, /Restart=on-failure/); assert.match(unit, /StartLimitIntervalSec=60/); assert.match(unit, /StartLimitBurst=5/); @@ -82,16 +82,16 @@ test("buildUnit points at the generated env file and keeps runtime settings out } }); -test("buildHostUnit runs `ompweb host` with the web unit's env file and never gives up restarting", () => { +test("buildHostUnit runs `tau host` with the web unit's env file and never gives up restarting", () => { const options = { - ompwebBin: "/usr/local/bin/ompweb", - env: { OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp" }, + tauBin: "/usr/local/bin/tau", + env: { TAU_OMP_BIN: "/home/u/.bun/bin/omp" }, home: "/home/u", envPath: "/home/u/.omp/agent/web-service.env", }; const unit = buildHostUnit(options); - assert.match(unit, /^ExecStart=\/usr\/local\/bin\/ompweb host$/m); + assert.match(unit, /^ExecStart=\/usr\/local\/bin\/tau host$/m); assert.match(unit, /EnvironmentFile=\/home\/u\/\.omp\/agent\/web-service\.env/); assert.match(unit, /^Restart=always$/m); assert.match(unit, /^RestartSec=10$/m); @@ -102,11 +102,11 @@ test("buildHostUnit runs `ompweb host` with the web unit's env file and never gi // Same PATH as the web unit, so omp resolves the same way in both. const envLine = (text) => text.match(/^Environment=.*$/m)[0]; assert.equal(envLine(unit), envLine(buildUnit(options))); - assert.equal(buildHostUnit({ ...options, ompwebBin: "/opt/my tools/ompweb" }).match(/^ExecStart=(.*)$/m)[1], '"/opt/my tools/ompweb" host'); + assert.equal(buildHostUnit({ ...options, tauBin: "/opt/my tools/tau" }).match(/^ExecStart=(.*)$/m)[1], '"/opt/my tools/tau" host'); }); test("buildUnit adds the launcher interpreter dir for Bun/npm installs of omp", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-bun-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-bun-")); try { const fakeBinDir = path.join(dir, "local", "bin"); const fakeBunDir = path.join(dir, "mise", "shims"); @@ -125,8 +125,8 @@ test("buildUnit adds the launcher interpreter dir for Bun/npm installs of omp", assert.equal(launcherInterpreterDir(path.join(fakeBinDir, "omp"), { PATH: "/usr/bin" }), null); const unit = buildUnit({ - ompwebBin: "/usr/local/bin/ompweb", - env: { OMP_WEB_OMP_BIN: path.join(fakeBinDir, "omp") }, + tauBin: "/usr/local/bin/tau", + env: { TAU_OMP_BIN: path.join(fakeBinDir, "omp") }, home: "/home/u", envPath: "/home/u/.omp/agent/web-service.env", }); @@ -146,23 +146,23 @@ test("unit helpers escape systemd values and paths", () => { assert.equal(escapeUnitValue('quo"te\\'), 'quo\\"te\\\\'); assert.equal(escapeUnitPath("/home/user name/web-service.env"), "/home/user\\x20name/web-service.env"); assert.equal(escapeUnitPath("/home/100%name/web-service.env"), "/home/100%%name/web-service.env"); - assert.equal(formatExecStart("/usr/local/bin/ompweb"), "/usr/local/bin/ompweb"); - assert.equal(formatExecStart("/home/user name/ompweb"), '"/home/user name/ompweb"'); + assert.equal(formatExecStart("/usr/local/bin/tau"), "/usr/local/bin/tau"); + assert.equal(formatExecStart("/home/user name/tau"), '"/home/user name/tau"'); }); -test("resolveOmpwebBin honors an executable override", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-")); +test("resolveTauBin honors an executable override", () => { + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-")); try { - const fake = path.join(dir, "ompweb"); + const fake = path.join(dir, "tau"); writeFileSync(fake, "#!/bin/sh\n", { mode: 0o755 }); - assert.equal(resolveOmpwebBin({ OMP_WEB_SYSTEMD_BIN: fake }), fake); + assert.equal(resolveTauBin({ TAU_SYSTEMD_BIN: fake }), fake); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("port and hostname validation rejects unsafe values", () => { - assert.equal(validatePort("30177"), "30177"); + assert.equal(validatePort("30187"), "30187"); assert.equal(validateHostname("0.0.0.0"), "0.0.0.0"); assert.throws(() => validatePort("0"), /invalid port/); assert.throws(() => validatePort("65536"), /invalid port/); @@ -171,63 +171,63 @@ test("port and hostname validation rejects unsafe values", () => { }); test("install creates the env file and unit with LAN settings", { skip: process.platform !== "linux" }, () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-install-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-install-")); try { const home = path.join(dir, "home"); const binDir = path.join(dir, "bin"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); const fakeSystemctl = path.join(binDir, "systemctl"); mkdirSync(home, { recursive: true }); mkdirSync(binDir, { recursive: true }); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); writeFileSync(fakeSystemctl, "#!/bin/sh\ncase \"$*\" in *is-active*) exit 3 ;; *) exit 0 ;; esac\n", { mode: 0o755 }); - // A stock omp on PATH: pinning the services to it would replace ompweb's own omp, which its sessions need. + // A stock omp on PATH: pinning the services to it would replace tau's own omp, which its sessions need. writeFileSync(path.join(binDir, "omp"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); const childEnv = { ...process.env, HOME: home, PATH: binDir, - OMP_WEB_SYSTEMD_BIN: fakeOmpweb, - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_PASSWORD: "test-password", - OMP_WEB_NO_OPEN: "0", - OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), - OMP_WEB_DISABLE_AUTOUPDATE: "1", - OMP_WEB_NAME: "My Box", + TAU_SYSTEMD_BIN: fakeTau, + TAU_HOSTNAME: "0.0.0.0", + TAU_PASSWORD: "test-password", + TAU_NO_OPEN: "0", + TAU_TRUSTED_HEADER_SHA256: "a".repeat(64), + TAU_DISABLE_AUTOUPDATE: "1", + TAU_NAME: "My Box", PORT: "40123", }; delete childEnv.PI_CODING_AGENT_DIR; - delete childEnv.OMP_WEB_OMP_BIN; + delete childEnv.TAU_OMP_BIN; - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { env: childEnv, encoding: "utf8", }); assert.equal(result.status, 0, result.stderr); const envPath = path.join(home, ".omp", "agent", "web-service.env"); - const unitPath = path.join(home, ".config", "systemd", "user", "ompweb.service"); + const unitPath = path.join(home, ".config", "systemd", "user", "tau.service"); const written = parseServiceEnv(readFileSync(envPath, "utf8")); - // The installer hashes OMP_WEB_PASSWORD: only the hash may reach the env - // file, and omp-web refuses to start on a plaintext password (issue #239). - assert.match(written.OMP_WEB_PASSWORD_HASH, /^scrypt\$15\$8\$1\$[A-Za-z0-9_-]{22}\$[A-Za-z0-9_-]{43}$/); - assert.equal(written.OMP_WEB_PASSWORD, undefined); - assert.equal(verifyPassword("test-password", written.OMP_WEB_PASSWORD_HASH), true); - assert.equal(verifyPassword("not-the-password", written.OMP_WEB_PASSWORD_HASH), false); - delete written.OMP_WEB_PASSWORD_HASH; + // The installer hashes TAU_PASSWORD: only the hash may reach the env + // file, and tau refuses to start on a plaintext password (issue #239). + assert.match(written.TAU_PASSWORD_HASH, /^scrypt\$15\$8\$1\$[A-Za-z0-9_-]{22}\$[A-Za-z0-9_-]{43}$/); + assert.equal(written.TAU_PASSWORD, undefined); + assert.equal(verifyPassword("test-password", written.TAU_PASSWORD_HASH), true); + assert.equal(verifyPassword("not-the-password", written.TAU_PASSWORD_HASH), false); + delete written.TAU_PASSWORD_HASH; assert.deepEqual(written, { PORT: "40123", - OMP_WEB_HOSTNAME: "0.0.0.0", - OMP_WEB_NO_OPEN: "0", - OMP_WEB_DISABLE_AUTOUPDATE: "1", - OMP_WEB_NAME: "My Box", - OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), + TAU_HOSTNAME: "0.0.0.0", + TAU_NO_OPEN: "0", + TAU_DISABLE_AUTOUPDATE: "1", + TAU_NAME: "My Box", + TAU_TRUSTED_HEADER_SHA256: "a".repeat(64), }); assert.match(readFileSync(unitPath, "utf8"), /EnvironmentFile=.*web-service\.env/); - assert.doesNotMatch(readFileSync(unitPath, "utf8"), /OMP_WEB_OMP_BIN/); - const hostUnit = readFileSync(path.join(path.dirname(unitPath), "ompweb-host.service"), "utf8"); - assert.match(hostUnit, /^ExecStart=.*\/ompweb host$/m); + assert.doesNotMatch(readFileSync(unitPath, "utf8"), /TAU_OMP_BIN/); + const hostUnit = readFileSync(path.join(path.dirname(unitPath), "tau-host.service"), "utf8"); + assert.match(hostUnit, /^ExecStart=.*\/tau host$/m); assert.match(hostUnit, /EnvironmentFile=.*web-service\.env/); assert.match(result.stdout, /config:.*web-service\.env/); } finally { @@ -236,40 +236,40 @@ test("install creates the env file and unit with LAN settings", { skip: process. }); test("install writes a pre-hashed password unchanged and rejects a broken one", { skip: process.platform !== "linux" }, () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-hash-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-hash-")); try { const home = path.join(dir, "home"); const binDir = path.join(dir, "bin"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); const fakeSystemctl = path.join(binDir, "systemctl"); mkdirSync(home, { recursive: true }); mkdirSync(binDir, { recursive: true }); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); writeFileSync(fakeSystemctl, "#!/bin/sh\ncase \"$*\" in *is-active*) exit 3 ;; *) exit 0 ;; esac\n", { mode: 0o755 }); const base = { ...process.env, HOME: home, PATH: binDir, - OMP_WEB_SYSTEMD_BIN: fakeOmpweb, - OMP_WEB_HOSTNAME: "0.0.0.0", + TAU_SYSTEMD_BIN: fakeTau, + TAU_HOSTNAME: "0.0.0.0", }; delete base.PI_CODING_AGENT_DIR; - delete base.OMP_WEB_OMP_BIN; - delete base.OMP_WEB_PASSWORD; + delete base.TAU_OMP_BIN; + delete base.TAU_PASSWORD; const provided = hashPassword("preset-password"); - const ok = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { - env: { ...base, OMP_WEB_PASSWORD_HASH: provided }, + const ok = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { + env: { ...base, TAU_PASSWORD_HASH: provided }, encoding: "utf8", }); assert.equal(ok.status, 0, ok.stderr); assert.equal( - parseServiceEnv(readFileSync(path.join(home, ".omp", "agent", "web-service.env"), "utf8")).OMP_WEB_PASSWORD_HASH, + parseServiceEnv(readFileSync(path.join(home, ".omp", "agent", "web-service.env"), "utf8")).TAU_PASSWORD_HASH, provided, ); - const broken = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { - env: { ...base, OMP_WEB_PASSWORD_HASH: "definitely-not-a-hash" }, + const broken = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { + env: { ...base, TAU_PASSWORD_HASH: "definitely-not-a-hash" }, encoding: "utf8", }); assert.notEqual(broken.status, 0); @@ -280,12 +280,12 @@ test("install writes a pre-hashed password unchanged and rejects a broken one", }); test("install fails loudly when the omp launcher interpreter is missing", () => { - const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-missing-interp-")); + const dir = mkdtempSync(path.join(tmpdir(), "tau-systemd-missing-interp-")); try { const binDir = path.join(dir, "bin"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); mkdirSync(binDir, { recursive: true }); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); // Launcher script needing an interpreter that is nowhere on PATH. writeFileSync(path.join(binDir, "omp"), "#!/usr/bin/env bun\n", { mode: 0o755 }); @@ -294,11 +294,11 @@ test("install fails loudly when the omp launcher interpreter is missing", () => // No node dir: the spawn uses an absolute process.execPath, and adding // it breaks the premise when node and bun share a directory. PATH: binDir, - OMP_WEB_SYSTEMD_BIN: fakeOmpweb, - OMP_WEB_OMP_BIN: path.join(binDir, "omp"), + TAU_SYSTEMD_BIN: fakeTau, + TAU_OMP_BIN: path.join(binDir, "omp"), PORT: "40123", }; - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), "install", "--no-autostart"], { + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), "install", "--no-autostart"], { env: childEnv, encoding: "utf8", }); @@ -310,8 +310,8 @@ test("install fails loudly when the omp launcher interpreter is missing", () => } }); -test("main ompweb bin forwards the systemd subcommand", () => { - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web.js"), "systemd", "--version"], { +test("main tau bin forwards the systemd subcommand", () => { + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau.js"), "systemd", "--version"], { encoding: "utf8", }); assert.equal(result.status, 0, result.stderr); @@ -325,27 +325,27 @@ test("runCli handles help and unknown commands without systemd", async () => { // Runs the CLI against a fake systemctl that logs its arguments; `hostUnit: false` mimics an install from before the daemon. function runWithFakeSystemctl(command, { hostUnit = true, active = false, dir: sharedDir, hostFails = !hostUnit } = {}) { - // A shared dir keeps HOME and the fake ompweb path, so a repeated install generates identical units. - const dir = sharedDir ?? mkdtempSync(path.join(tmpdir(), "ompweb-systemd-cmd-")); + // A shared dir keeps HOME and the fake tau path, so a repeated install generates identical units. + const dir = sharedDir ?? mkdtempSync(path.join(tmpdir(), "tau-systemd-cmd-")); const home = path.join(dir, "home"); const binDir = path.join(dir, "bin"); const log = path.join(dir, "systemctl.log"); - const fakeOmpweb = path.join(binDir, "ompweb"); + const fakeTau = path.join(binDir, "tau"); mkdirSync(binDir, { recursive: true }); const unitDir = path.join(home, ".config", "systemd", "user"); mkdirSync(unitDir, { recursive: true }); - writeFileSync(path.join(unitDir, "ompweb.service"), "[Service]\n"); - if (hostUnit && !existsSync(path.join(unitDir, "ompweb-host.service"))) writeFileSync(path.join(unitDir, "ompweb-host.service"), "[Service]\n"); - writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + writeFileSync(path.join(unitDir, "tau.service"), "[Service]\n"); + if (hostUnit && !existsSync(path.join(unitDir, "tau-host.service"))) writeFileSync(path.join(unitDir, "tau-host.service"), "[Service]\n"); + writeFileSync(fakeTau, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); // A missing host unit makes systemctl fail, as the real one does. writeFileSync( path.join(binDir, "systemctl"), - `#!/bin/sh\necho "$*" >> "${log}"\n${hostFails ? 'case "$*" in *ompweb-host*) exit 5 ;; esac\n' : ""}case "$*" in *is-active*) exit ${active ? 0 : 3} ;; *) exit 0 ;; esac\n`, + `#!/bin/sh\necho "$*" >> "${log}"\n${hostFails ? 'case "$*" in *tau-host*) exit 5 ;; esac\n' : ""}case "$*" in *is-active*) exit ${active ? 0 : 3} ;; *) exit 0 ;; esac\n`, { mode: 0o755 }, ); - const env = { ...process.env, HOME: home, PATH: binDir, OMP_WEB_SYSTEMD_BIN: fakeOmpweb, OMP_WEB_DISABLE_AUTOUPDATE: "1" }; - for (const key of ["PI_CODING_AGENT_DIR", "OMP_WEB_OMP_BIN", "OMP_WEB_PASSWORD"]) delete env[key]; - const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), command], { env, encoding: "utf8" }); + const env = { ...process.env, HOME: home, PATH: binDir, TAU_SYSTEMD_BIN: fakeTau, TAU_DISABLE_AUTOUPDATE: "1" }; + for (const key of ["PI_CODING_AGENT_DIR", "TAU_OMP_BIN", "TAU_PASSWORD"]) delete env[key]; + const result = spawnSync(NODE, [path.join(process.cwd(), "bin", "tau-systemd.js"), command], { env, encoding: "utf8" }); const calls = existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []; rmSync(log, { force: true }); return { result, calls, dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) }; @@ -355,7 +355,7 @@ test("restart restarts the web unit only: restarting the daemon would end every const { result, calls, cleanup } = runWithFakeSystemctl("restart"); try { assert.equal(result.status, 0, result.stderr); - assert.deepEqual(calls, ["--user restart ompweb.service"]); + assert.deepEqual(calls, ["--user restart tau.service"]); } finally { cleanup(); } @@ -366,7 +366,7 @@ test("start and stop cover both units when the host unit exists", { skip: proces const { result, calls, cleanup } = runWithFakeSystemctl(command); try { assert.equal(result.status, 0, result.stderr); - assert.deepEqual(calls, [`--user ${command} ompweb.service ompweb-host.service`]); + assert.deepEqual(calls, [`--user ${command} tau.service tau-host.service`]); } finally { cleanup(); } @@ -378,7 +378,7 @@ test("start, stop and restart work on an install without the host unit", { skip: const { result, calls, cleanup } = runWithFakeSystemctl(command, { hostUnit: false }); try { assert.equal(result.status, 0, result.stderr); - assert.deepEqual(calls, [`--user ${command} ompweb.service`]); + assert.deepEqual(calls, [`--user ${command} tau.service`]); } finally { cleanup(); } @@ -390,13 +390,13 @@ test("install restarts a running host unit only when its unit text changed", { s const first = runWithFakeSystemctl("install", { hostUnit: false, hostFails: false, active: true }); try { assert.equal(first.result.status, 0, first.result.stderr); - assert.ok(first.calls.includes("--user restart ompweb.service")); - assert.ok(first.calls.includes("--user restart ompweb-host.service")); + assert.ok(first.calls.includes("--user restart tau.service")); + assert.ok(first.calls.includes("--user restart tau-host.service")); // Same install again: identical unit text, so only the web unit restarts. const second = runWithFakeSystemctl("install", { active: true, dir: first.dir }); assert.equal(second.result.status, 0, second.result.stderr); - assert.ok(second.calls.includes("--user restart ompweb.service")); - assert.ok(!second.calls.includes("--user restart ompweb-host.service"), second.calls.join("\n")); + assert.ok(second.calls.includes("--user restart tau.service")); + assert.ok(!second.calls.includes("--user restart tau-host.service"), second.calls.join("\n")); } finally { first.cleanup(); } diff --git a/bin/omp-web-tray.exe b/bin/tau-tray.exe similarity index 100% rename from bin/omp-web-tray.exe rename to bin/tau-tray.exe diff --git a/bin/omp-web-tray.js b/bin/tau-tray.js similarity index 95% rename from bin/omp-web-tray.js rename to bin/tau-tray.js index 58e7fab9..430959da 100644 --- a/bin/omp-web-tray.js +++ b/bin/tau-tray.js @@ -14,12 +14,12 @@ const fs = require("fs"); const path = require("path"); function printHelp() { - console.log(`Usage: node bin/omp-web-tray.js [command] [options] - ompweb-tray [command] [options] + console.log(`Usage: node bin/tau-tray.js [command] [options] + tau-tray [command] [options] Platform notes: Windows System Tray shortcuts and background service - Linux StatusNotifierItem tray (KDE Plasma and compatible) — see ompweb-systemd + Linux StatusNotifierItem tray (KDE Plasma and compatible) — see tau-systemd for the systemd user service this tray manages Commands: @@ -32,7 +32,7 @@ Commands: --open, open Open the background web service in default browser Options: - -p, --port Server port for background service (default 30177) + -p, --port Server port for background service (default 30187) -H, --hostname Bind address (default 127.0.0.1) -m, --mode Execution mode: "start" or "dev" (default "start", Windows only) --no-autostart Disable automatic startup on logon @@ -144,7 +144,7 @@ async function runCli(argv = process.argv.slice(2)) { } if (isStart) { - console.log("Starting omp-web background system tray service..."); + console.log("Starting tau background system tray service..."); const res = await windowsService.startTrayService({ openBrowser: cliArgs.open }); if (res.success) { console.log("Tray service launched in background."); @@ -156,7 +156,7 @@ async function runCli(argv = process.argv.slice(2)) { } if (isStop) { - console.log("Stopping omp-web background system tray service..."); + console.log("Stopping tau background system tray service..."); const res = await windowsService.stopTrayService(); if (res.success) { console.log("Background system tray service stopped."); @@ -168,7 +168,7 @@ async function runCli(argv = process.argv.slice(2)) { } if (isRestart) { - console.log("Restarting omp-web background system tray service..."); + console.log("Restarting tau background system tray service..."); const res = await windowsService.restartTrayService(); if (res.success) { console.log("Background system tray service restarted."); @@ -201,7 +201,7 @@ async function runCli(argv = process.argv.slice(2)) { if (cliArgs.json) { console.log(JSON.stringify(status, null, 2)); } else { - console.log("=== omp-web Windows Service Status ==="); + console.log("=== tau Windows Service Status ==="); console.log(` Platform : ${process.platform === "win32" ? "Windows" : process.platform}`); console.log(` Version : v${status.version}`); console.log(` Installed : ${status.isInstalled ? "Yes" : "No"}`); diff --git a/bin/omp-web-tray.test.mjs b/bin/tau-tray.test.mjs similarity index 93% rename from bin/omp-web-tray.test.mjs rename to bin/tau-tray.test.mjs index 3af5b9ca..0439276c 100644 --- a/bin/omp-web-tray.test.mjs +++ b/bin/tau-tray.test.mjs @@ -3,8 +3,8 @@ import { createRequire } from "node:module"; import test from "node:test"; const require = createRequire(import.meta.url); -const { parseLaunchOptions } = require("./omp-web-options.js"); -const { runCli } = require("./omp-web-tray.js"); +const { parseLaunchOptions } = require("./tau-options.js"); +const { runCli } = require("./tau-tray.js"); test("parseLaunchOptions parses --install-tray and --install-service flags", () => { const opts1 = parseLaunchOptions(["--install-tray"], {}); diff --git a/bin/omp-web.js b/bin/tau.js similarity index 82% rename from bin/omp-web.js rename to bin/tau.js index 2e3c79fc..930b380a 100755 --- a/bin/omp-web.js +++ b/bin/tau.js @@ -5,24 +5,24 @@ require("./node-version").exitIfUnsupportedNode(); // Forward service subcommands from the main bin. This makes both -// `npx @ompweb-dev/tau@latest ompweb-launchd ...` and -// `npx @ompweb-dev/tau@latest ompweb-systemd ...` work without requiring +// `npx @ompweb-dev/tau@latest tau-launchd ...` and +// `npx @ompweb-dev/tau@latest tau-systemd ...` work without requiring // callers to know the path of the secondary executable. const forwardedServiceScripts = { - launchd: "omp-web-launchd.js", - "tau-launchd": "omp-web-launchd.js", - "ompweb-launchd": "omp-web-launchd.js", - systemd: "omp-web-systemd.js", - "tau-systemd": "omp-web-systemd.js", - "ompweb-systemd": "omp-web-systemd.js", + launchd: "tau-launchd.js", + "tau-launchd": "tau-launchd.js", + "tau-launchd": "tau-launchd.js", + systemd: "tau-systemd.js", + "tau-systemd": "tau-systemd.js", + "tau-systemd": "tau-systemd.js", }; -// `ompweb hash-password` reads the password on stdin and prints the value for -// OMP_WEB_PASSWORD_HASH. Handled first so it works with no build artifacts, no +// `tau hash-password` reads the password on stdin and prints the value for +// TAU_PASSWORD_HASH. Handled first so it works with no build artifacts, no // port, and no agent directory. if (process.argv[2] === "hash-password" || process.argv[2] === "hash_password") { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { runHashPasswordCommand } = require("./omp-web-hash-password"); + const { runHashPasswordCommand } = require("./tau-hash-password"); runHashPasswordCommand() .then((exitCode) => { process.exit(exitCode); }) .catch((error) => { @@ -34,9 +34,9 @@ if (process.argv[2] === "hash-password" || process.argv[2] === "hash_password") } function startLauncher() { -// `ompweb preflight` (lib/hosts/preflight.ts): what an updater runs on a candidate release; it prints "preflight ok: ". +// `tau preflight` (lib/hosts/preflight.ts): what an updater runs on a candidate release; it prints "preflight ok: ". if (process.argv[2] === "preflight") { - process.env.OMP_WEB_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); + process.env.TAU_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); module.require("jiti").createJiti(__filename).import("../lib/hosts/preflight.ts").then( ({ runPreflight }) => runPreflight().then((code) => process.exit(code)), (error) => { @@ -47,7 +47,7 @@ if (process.argv[2] === "preflight") { return; } if (process.argv[2] === "recover-host") { - process.env.OMP_WEB_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); + process.env.TAU_PACKAGE_DIR ??= module.require("node:path").join(__dirname, ".."); module.require("jiti").createJiti(__filename).import("../lib/hosts/recovery.ts").then( ({ runHostRecoveryCli }) => runHostRecoveryCli(process.argv.slice(3)).then((code) => process.exit(code)), (error) => { @@ -57,11 +57,11 @@ if (process.argv[2] === "recover-host") { ); return; } -// `ompweb host` runs in this process: a supervisor's SIGTERM must reach the daemon, not a wrapper. +// `tau host` runs in this process: a supervisor's SIGTERM must reach the daemon, not a wrapper. if (process.argv[2] === "host") { process.argv.splice(2, 1); // eslint-disable-next-line @typescript-eslint/no-require-imports - require("./omp-web-host.js"); + require("./tau-host.js"); return; } const forwardedServiceScript = forwardedServiceScripts[process.argv[2]]; @@ -85,7 +85,7 @@ const path = require("node:path"); // eslint-disable-next-line @typescript-eslint/no-require-imports const fs = require("node:fs"); // eslint-disable-next-line @typescript-eslint/no-require-imports -const { checkLaunchSecurity, parseLaunchOptions, serverWorkingDirectory } = require("./omp-web-options"); +const { checkLaunchSecurity, parseLaunchOptions, serverWorkingDirectory } = require("./tau-options"); // eslint-disable-next-line @typescript-eslint/no-require-imports const { isPortAvailable } = require("./port-availability"); // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -108,7 +108,7 @@ if (launchOptions.error) { if (launchOptions.installTray || launchOptions.uninstallTray || launchOptions.tray) { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { runCli } = require("./omp-web-tray"); + const { runCli } = require("./tau-tray"); const trayArgs = []; if (launchOptions.installTray) { trayArgs.push("--install"); @@ -178,16 +178,16 @@ function attachOutput(child) { function serverEnvironment() { return { ...process.env, - OMP_WEB_PACKAGE_DIR: pkgDir, - OMP_WEB_LAUNCHER_PID: String(process.pid), - OMP_WEB_NODE_BIN: process.execPath, - OMP_WEB_PORT: port, - OMP_WEB_HOSTNAME: hostname, + TAU_PACKAGE_DIR: pkgDir, + TAU_LAUNCHER_PID: String(process.pid), + TAU_NODE_BIN: process.execPath, + TAU_PORT: port, + TAU_HOSTNAME: hostname, }; } function trackServer(child) { - child.once("error", (error) => console.error(`Could not start ompweb: ${error.message}`)); + child.once("error", (error) => console.error(`Could not start tau: ${error.message}`)); attachOutput(child); wireChildProcessLifecycle(child, process); return child; @@ -197,7 +197,7 @@ function spawnServer(command) { return trackServer(spawn(command[0], command.slice(1), { // Never the installation: on Windows a working directory there blocks the rename an // in-place update performs, and the server needs no relative path (the entry point and - // OMP_WEB_PACKAGE_DIR below are absolute). + // TAU_PACKAGE_DIR below are absolute). cwd: serverWorkingDirectory(), stdio: ["inherit", "pipe", "inherit"], env: serverEnvironment(), @@ -212,7 +212,7 @@ async function main() { } if (!await isPortAvailable(port, hostname)) { console.error(`Port ${port} on ${hostname} is already in use.`); - console.error(`If ompweb is already running, open ${browserUrl}. Otherwise, stop the process using it or run: ompweb --port ${Number(port) + 1}`); + console.error(`If tau is already running, open ${browserUrl}. Otherwise, stop the process using it or run: tau --port ${Number(port) + 1}`); process.exitCode = 1; return; } diff --git a/bunfig.toml b/bunfig.toml index 63d1bb4f..ae5067dc 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -1,7 +1,7 @@ # Bun's dev server (server/dev.ts HTML import) bundles the SPA with these; scripts/build-client.ts passes its own. [serve.static] plugins = ["./scripts/tailwind-plugin.ts"] -env = "OMP_WEB_PUBLIC_*" +env = "TAU_PUBLIC_*" [test] preload = ["./tests/isolate-tmp.mjs"] diff --git a/components/AppShell-app-update.ts b/components/AppShell-app-update.ts index f1f5ad15..30b2ddf7 100644 --- a/components/AppShell-app-update.ts +++ b/components/AppShell-app-update.ts @@ -1,8 +1,8 @@ import type { UpgradeApproval, UpgradePlan } from "@/lib/upgrade-types"; import type { AppUpdateInfo } from "./AppUpdateDialog"; -export const DISMISSED_APP_UPDATE_KEY = "omp-web:dismissed-app-update"; -export const COMPLETED_APP_UPDATE_KEY = "omp-web:completed-app-update"; +export const DISMISSED_APP_UPDATE_KEY = "tau:dismissed-app-update"; +export const COMPLETED_APP_UPDATE_KEY = "tau:completed-app-update"; export const APP_UPDATE_POLL_MS = 500; export const APP_UPDATE_STOPPING_POLL_MS = 200; // Longer than the backend's 30-minute coordinator lease, so the browser never gives up before the server does. diff --git a/components/AppShell-layout.tsx b/components/AppShell-layout.tsx index a01acf4d..39e39993 100644 --- a/components/AppShell-layout.tsx +++ b/components/AppShell-layout.tsx @@ -12,7 +12,7 @@ export function projectLabel(projectPath: string): string { // Resizable desktop sidebar: the width is stored on the container as the // --sidebar-width CSS variable (globals.css) and persisted between sessions. -export const SIDEBAR_WIDTH_STORAGE_KEY = "omp-web:sidebar-width"; +export const SIDEBAR_WIDTH_STORAGE_KEY = "tau:sidebar-width"; export const SIDEBAR_MIN_WIDTH = 200; export const SIDEBAR_MAX_WIDTH = 520; export const SIDEBAR_DEFAULT_WIDTH = 260; @@ -35,7 +35,7 @@ export function loadSidebarWidth(): number { // Resizable right (file) panel: null means the fluid 42% default; a number is // a user-chosen pixel width persisted between sessions (same drag pattern as // the left sidebar, mirrored — the handle sits on the panel's left edge). -export const RIGHT_PANEL_WIDTH_STORAGE_KEY = "omp-web:right-panel-width"; +export const RIGHT_PANEL_WIDTH_STORAGE_KEY = "tau:right-panel-width"; export const RIGHT_PANEL_MIN_WIDTH = 300; export const RIGHT_PANEL_MAX_WIDTH = 900; diff --git a/components/AppShell.tsx b/components/AppShell.tsx index f5e70363..438edc8f 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -111,15 +111,15 @@ const RightPanel = dynamic(() => import("./RightPanel").then((m) => m.RightPanel loading: () => null, }); -const TOOL_CALLS_COLLAPSED_STORAGE_KEY = "omp-web:tool-calls-collapsed"; -const HIDE_TOOL_ACTIVITY_STORAGE_KEY = "omp-web:hide-tool-activity"; -const NEVER_FOLD_ACTIVITY_STORAGE_KEY = "omp-web:never-fold-activity"; -const SHOW_TOOL_CALLS_UNFOLDED_STORAGE_KEY = "omp-web:show-tool-calls-unfolded"; +const TOOL_CALLS_COLLAPSED_STORAGE_KEY = "tau:tool-calls-collapsed"; +const HIDE_TOOL_ACTIVITY_STORAGE_KEY = "tau:hide-tool-activity"; +const NEVER_FOLD_ACTIVITY_STORAGE_KEY = "tau:never-fold-activity"; +const SHOW_TOOL_CALLS_UNFOLDED_STORAGE_KEY = "tau:show-tool-calls-unfolded"; // Off by default, so the transcript keeps collapsing reasoning until asked. -const EXPAND_THINKING_STORAGE_KEY = "omp-web:expand-thinking"; -const PROVIDER_USAGE_VISIBLE_STORAGE_KEY = "omp-web:provider-usage-visible"; -const NATIVE_SELECT_ALL_STORAGE_KEY = "omp-web:scope-native-select-all"; -const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "omp-web:open-url-automatically"; +const EXPAND_THINKING_STORAGE_KEY = "tau:expand-thinking"; +const PROVIDER_USAGE_VISIBLE_STORAGE_KEY = "tau:provider-usage-visible"; +const NATIVE_SELECT_ALL_STORAGE_KEY = "tau:scope-native-select-all"; +const OPEN_URL_AUTOMATICALLY_STORAGE_KEY = "tau:open-url-automatically"; type AutoNameStatus = @@ -1719,7 +1719,7 @@ export function AppShell({ appName }: { appName: string }) { } setPendingOpens((queue) => [...queue, { kind: "url", target: url, name: url, sessionId, crossSession }]); return crossSession - ? `Asked the user to confirm opening ${url}; they are viewing another omp-web session.` + ? `Asked the user to confirm opening ${url}; they are viewing another tau session.` : `Asked the user to confirm opening ${url}.`; }, [openUrlAutomatically]); const handleSessionOpenUrl = useCallback((url: string) => requestOpenUrl(url, selectedSession?.id ?? "", false), [requestOpenUrl, selectedSession?.id]); @@ -1739,7 +1739,7 @@ export function AppShell({ appName }: { appName: string }) { const source = owner ? { ...call, sessionId: owner } : call; if (viewing()) return handleOpenFile(path, name, source); setPendingOpens((queue) => [...queue, { kind: "file", target: path, name, sessionId: call.sessionId, source, crossSession: true }]); - return `Asked the user to confirm opening ${path}; they are viewing another omp-web session.`; + return `Asked the user to confirm opening ${path}; they are viewing another tau session.`; }, }, call.sessionId, controller.signal); if (controller.signal.aborted) return; diff --git a/components/ChatInput.btw.test.mjs b/components/ChatInput.btw.test.mjs index b4bf9612..4df8735a 100644 --- a/components/ChatInput.btw.test.mjs +++ b/components/ChatInput.btw.test.mjs @@ -52,7 +52,7 @@ for (const isStreaming of [false, true]) { for (const behavior of ["queue", "steer"]) { test(`/btw offers Send during a run regardless of the ${behavior} preference`, async () => { - localStorage.setItem("omp-web:submit-during-run", behavior); + localStorage.setItem("tau:submit-during-run", behavior); const user = userEvent.setup(); const { calls } = renderComposer({ isStreaming: true }); await user.type(screen.getByRole("textbox"), "/btw what is 2+2"); @@ -63,7 +63,7 @@ for (const behavior of ["queue", "steer"]) { } test("without builtin dispatch, /btw during a run keeps the Queue button and queues as ordinary text", async () => { - localStorage.setItem("omp-web:submit-during-run", "queue"); + localStorage.setItem("tau:submit-during-run", "queue"); const user = userEvent.setup(); const { calls } = renderComposer({ isStreaming: true, onBuiltinCommand: undefined }); await user.type(screen.getByRole("textbox"), "/btw what is 2+2"); diff --git a/components/ChatInput.queue-attachments.test.mjs b/components/ChatInput.queue-attachments.test.mjs index 34328c8c..2bc56db5 100644 --- a/components/ChatInput.queue-attachments.test.mjs +++ b/components/ChatInput.queue-attachments.test.mjs @@ -123,7 +123,7 @@ test("Enter during a run queues a follow-up with the attached image and text fil }); test("a stored Steer preference still steers Enter during a run", async () => { - localStorage.setItem("omp-web:submit-during-run", "steer"); + localStorage.setItem("tau:submit-during-run", "steer"); const user = userEvent.setup(); const calls = await renderRunningWithAttachments(); await user.type(screen.getByRole("textbox"), "look at this"); @@ -142,7 +142,7 @@ test("attachments alone turn Stop into Queue, which queues them as a follow-up", }); test("a stored Steer preference turns the primary button into Steer, which steers like Enter", async () => { - localStorage.setItem("omp-web:submit-during-run", "steer"); + localStorage.setItem("tau:submit-during-run", "steer"); const user = userEvent.setup(); const calls = await renderRunningWithAttachments(); await user.type(screen.getByRole("textbox"), "look at this"); diff --git a/components/ChatInput.uploads.test.mjs b/components/ChatInput.uploads.test.mjs index f156e2f5..06a74fb7 100644 --- a/components/ChatInput.uploads.test.mjs +++ b/components/ChatInput.uploads.test.mjs @@ -150,9 +150,9 @@ const pressEnter = () => act(async () => { fireEvent.keyDown(screen.getByRole("t /** Reuse the uploads server suite's loopback daemon fixture so ID-bound PUTs reach real staged files. */ async function uploadOwner(t) { const scratch = mkdtempSync(join(tmpdir(), "omp-composer-owner-")); - const previous = { agentDir: process.env.PI_CODING_AGENT_DIR, ompBin: process.env.OMP_WEB_OMP_BIN }; + const previous = { agentDir: process.env.PI_CODING_AGENT_DIR, ompBin: process.env.TAU_OMP_BIN }; process.env.PI_CODING_AGENT_DIR = join(scratch, "agent"); - process.env.OMP_WEB_OMP_BIN = join(scratch, "no-omp"); + process.env.TAU_OMP_BIN = join(scratch, "no-omp"); const linkRoute = await import("../app/api/hosts/link/route.ts"); const uploadsRoute = await import("../app/api/uploads/route.ts"); const uploadRoute = await import("../app/api/uploads/[id]/route.ts"); @@ -179,7 +179,7 @@ async function uploadOwner(t) { hub.flushLinkSamples(); closeNotificationStore(); closeOutboxStore(); - for (const [key, value] of [["PI_CODING_AGENT_DIR", previous.agentDir], ["OMP_WEB_OMP_BIN", previous.ompBin]]) { + for (const [key, value] of [["PI_CODING_AGENT_DIR", previous.agentDir], ["TAU_OMP_BIN", previous.ompBin]]) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } @@ -195,7 +195,7 @@ async function uploadOwner(t) { uploadRequests.push(response); return response; }; - return { hostId: host.id, staged: (id) => readFileSync(join(scratch, "agent", "omp-web", "uploads", `${id}.part`)) }; + return { hostId: host.id, staged: (id) => readFileSync(join(scratch, "agent", "tau", "uploads", `${id}.part`)) }; } test("a .zip becomes a file chip, uploads on attach, and its id goes with the prompt", async () => { diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 5f8d5360..139cc124 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -16,7 +16,7 @@ import { SubagentTranscriptDialog } from "./SubagentTranscriptDialog"; import { ChatMinimap, useMessageRefs } from "./ChatMinimap"; import { ComposerPanels } from "./ComposerPanels"; import { BtwHistoryDialog, type BtwPanelProps } from "./BtwPanel"; -import OmpWebLogo from "./OmpWebLogo"; +import TauLogo from "./TauLogo"; import { CHAT_COLUMN_MAX_WIDTH, MINIMAP_WIDTH } from "@/lib/chat-layout"; import { WorkspaceState } from "./AppShell-layout"; import { useAgentSession, type AgentPhase, type NoticeItem, type SubagentInfo } from "@/hooks/useAgentSession"; @@ -345,7 +345,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ // With "Hide tool activity while working" on (the default) the running turn // folds like a finished one; off restores the flat tail. if (hideToolActivity) return false; - // `sessionBusy` only goes true for a run omp-web owns, so a session driven + // `sessionBusy` only goes true for a run tau owns, so a session driven // by another `omp` process would never get a live tail; the transcript-tail // heuristic supplies that missing case. return (sessionBusy || externalRunActive || isStreaming) && row.endIndex === messages.length && row.userIndex === lastAnchorIdx; @@ -1184,12 +1184,12 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, newSessio }} >
- - omp web + + tau
- web v{process.env.OMP_WEB_PUBLIC_APP_VERSION ?? "0.0.0"} + web v{process.env.TAU_PUBLIC_APP_VERSION ?? "0.0.0"}
diff --git a/components/ComposerPanels.tsx b/components/ComposerPanels.tsx index 05473937..72fdfb1d 100644 --- a/components/ComposerPanels.tsx +++ b/components/ComposerPanels.tsx @@ -17,8 +17,8 @@ import { SubagentStatusIcon } from "./SubagentStatusIcon"; import { BtwPanel, type BtwPanelProps } from "./BtwPanel"; // Panels unmount when their inputs are empty and remount when they fill -const TODO_COLLAPSED_STORAGE_KEY = "omp-web:composer-todo-collapsed"; -const SUBAGENTS_COLLAPSED_STORAGE_KEY = "omp-web:composer-subagents-collapsed"; +const TODO_COLLAPSED_STORAGE_KEY = "tau:composer-todo-collapsed"; +const SUBAGENTS_COLLAPSED_STORAGE_KEY = "tau:composer-subagents-collapsed"; function loadCollapsed(key: string, defaultExpanded: boolean): boolean { if (typeof window === "undefined") return !defaultExpanded; diff --git a/components/ConnectionDiagnostics.test.mjs b/components/ConnectionDiagnostics.test.mjs index d657eb6d..748b5bda 100644 --- a/components/ConnectionDiagnostics.test.mjs +++ b/components/ConnectionDiagnostics.test.mjs @@ -253,8 +253,8 @@ test("turning the setting on in another tab adds the Connection tab here", async render(createElement(Harness)); assert.equal(screen.queryByRole("tab", { name: "Connection" }), null); act(() => { - localStorage.setItem("omp-web:connection-diagnostics", "on"); - window.dispatchEvent(Object.assign(new Event("storage"), { key: "omp-web:connection-diagnostics" })); + localStorage.setItem("tau:connection-diagnostics", "on"); + window.dispatchEvent(Object.assign(new Event("storage"), { key: "tau:connection-diagnostics" })); }); assert.ok(await screen.findByRole("tab", { name: "Connection" })); }); diff --git a/components/ExtensionDialog.form.test.mjs b/components/ExtensionDialog.form.test.mjs index 8a8bbad0..80b25756 100644 --- a/components/ExtensionDialog.form.test.mjs +++ b/components/ExtensionDialog.form.test.mjs @@ -126,7 +126,7 @@ test("controls named like HTMLFormElement members still submit", async () => { test("a choice's label keeps its text and inline markup in one block beside the control", () => { // The row is a flex container: without the wrapper every text run and became its own column. renderForm(`
Get omp - +
`); const label = screen.getByRole("radio", { name: /Download the matching/ }).closest("label"); @@ -135,5 +135,5 @@ test("a choice's label keeps its text and inline markup in one block beside the assert.equal(rest.length, 0, "the label has exactly two flex items: the control and one text block"); assert.equal(text.className, "extension-choice-text"); assert.ok(text.querySelector("code"), "inline markup stays inside the text block"); - assert.equal(text.textContent.trim(), "Download the matching ompweb-omp and check its sha256."); + assert.equal(text.textContent.trim(), "Download the matching tau-omp and check its sha256."); }); diff --git a/components/ExtensionDialog.test.mjs b/components/ExtensionDialog.test.mjs index dcb7b51d..4f4a6af8 100644 --- a/components/ExtensionDialog.test.mjs +++ b/components/ExtensionDialog.test.mjs @@ -64,7 +64,7 @@ test("question selection survives request replay but is cleared for the next que }); test("confirm answers true, and cancel answers with no value", async () => { - const request = { type: "ui_request", id: "omp-web:abc", method: "confirm", args: ["Delete it?", "This cannot be undone."] }; + const request = { type: "ui_request", id: "tau:abc", method: "confirm", args: ["Delete it?", "This cannot be undone."] }; const responses = []; const onRespond = (current, value) => responses.push({ id: current.id, value }); const view = render(React.createElement(ExtensionDialog, { request, onRespond, attached: true })); @@ -72,7 +72,7 @@ test("confirm answers true, and cancel answers with no value", async () => { screen.getByText("This cannot be undone."); fireEvent.click(screen.getByRole("button", { name: "Confirm" })); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); - assert.deepEqual(responses, [{ id: "omp-web:abc", value: true }, { id: "omp-web:abc", value: undefined }]); + assert.deepEqual(responses, [{ id: "tau:abc", value: true }, { id: "tau:abc", value: undefined }]); } finally { view.unmount(); } @@ -81,7 +81,7 @@ test("confirm answers true, and cancel answers with no value", async () => { test("server-owned send confirmation shows named endpoints and escaped message text", () => { const request = { type: "ui_request", - id: "omp-web:send", + id: "tau:send", method: "confirm", args: ["Allow this session to send a message?", ""], serverPayload: { diff --git a/components/FileViewer.markdown-links.test.mjs b/components/FileViewer.markdown-links.test.mjs index df918d83..379dc96b 100644 --- a/components/FileViewer.markdown-links.test.mjs +++ b/components/FileViewer.markdown-links.test.mjs @@ -48,7 +48,7 @@ async function renderPreview(filePath, opened) { return view; } -test("preview links never navigate omp-web away, and unservable images show their alt text", async () => { +test("preview links never navigate tau away, and unservable images show their alt text", async () => { const opened = []; const { container, getByText } = await renderPreview("/var/tmp/out/docs/guide.md", opened); diff --git a/components/FileViewer.tsx b/components/FileViewer.tsx index ed15792f..9be2bafb 100644 --- a/components/FileViewer.tsx +++ b/components/FileViewer.tsx @@ -1225,7 +1225,7 @@ function TextFileViewer({ filePath, hostId, cwd, sourceSessionId, onOpenFile, on ? resolveLocalFileHref(href, markdownDirectory, cwd ?? markdownDirectory) : null; if (!linkedFile || !onOpenFile) { - // Never let a preview link replace omp-web itself: in-page anchors stay, + // Never let a preview link replace tau itself: in-page anchors stay, // web links open a new tab, and a path the panel cannot open (such as a // relative link in a Markdown file outside the workspace) is plain text. if (href?.startsWith("#")) return {children}; diff --git a/components/HostUpdates.test.mjs b/components/HostUpdates.test.mjs index a607d66c..684ca0c4 100644 --- a/components/HostUpdates.test.mjs +++ b/components/HostUpdates.test.mjs @@ -7,19 +7,19 @@ import { HostUpdates } from "./HostUpdates"; const endpoint = "/api/hosts/box/updates"; const info = { - ompweb: { currentVersion: "0.7.0", availableVersion: "0.7.1", updateAvailable: true, canUpdate: true, blockedReason: null, updateCommand: "npm install -g @ompweb-dev/tau", installMethod: "npm", protocolVersion: 12 }, + tau: { currentVersion: "0.7.0", availableVersion: "0.7.1", updateAvailable: true, canUpdate: true, blockedReason: null, updateCommand: "npm install -g @ompweb-dev/tau", installMethod: "npm", protocolVersion: 12 }, omp: { currentVersion: "18.20.0" }, operation: null, }; /** Render the real host row and record every request it sends. */ -async function renderHost(t, host, ompweb = {}, operation = null) { +async function renderHost(t, host, tau = {}, operation = null) { const requests = []; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, init) => { requests.push({ url: String(url), method: init?.method ?? "GET", body: init?.body }); - if (init?.method === "POST") return Response.json({ accepted: true, operation: { state: "running", target: "ompweb", version: "0.7.1" } }); - return Response.json({ ...info, operation, ompweb: { ...info.ompweb, ...ompweb } }); + if (init?.method === "POST") return Response.json({ accepted: true, operation: { state: "running", target: "tau", version: "0.7.1" } }); + return Response.json({ ...info, operation, tau: { ...info.tau, ...tau } }); }; const container = document.createElement("div"); document.body.append(container); @@ -38,8 +38,8 @@ async function renderHost(t, host, ompweb = {}, operation = null) { const button = (root, label) => [...root.querySelectorAll("button")].find((candidate) => candidate.textContent.trim() === label); -test("an upgrade-only legacy host can check for and submit an ompweb update", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", upgradeOnly: true, ompVersion: "omp/18.20.0", ompwebVersion: "0.7.0" }); +test("an upgrade-only legacy host can check for and submit an tau update", async (t) => { + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", upgradeOnly: true, ompVersion: "omp/18.20.0", tauVersion: "0.7.0" }); assert.equal(requests[0]?.url, endpoint, "the status is read on mount"); assert.equal(button(container, "Check updates").disabled, false); @@ -54,18 +54,18 @@ test("an upgrade-only legacy host can check for and submit an ompweb update", as await act(() => new Promise((resolve) => setTimeout(resolve, 20))); const post = requests.find((request) => request.method === "POST"); assert.ok(post, "the update was not submitted"); - assert.deepEqual(JSON.parse(post.body), { target: "ompweb", version: "0.7.1" }); + assert.deepEqual(JSON.parse(post.body), { target: "tau", version: "0.7.1" }); }); test("a connected maintenance API can update a compatible host while its application connection is offline", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", apiVersion: 1, hostVersion: 12, ompwebVersion: "0.7.0" }); + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", apiVersion: 1, hostVersion: 12, tauVersion: "0.7.0" }); assert.equal(requests[0]?.url, endpoint); assert.equal(button(container, "Check updates").disabled, false); assert.ok(button(container, "Update")); }); test("an ordinary incompatible host cannot be checked or updated", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", ompVersion: "omp/18.20.0", ompwebVersion: "0.6.0" }); + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "needs-upgrade", ompVersion: "omp/18.20.0", tauVersion: "0.6.0" }); assert.deepEqual(requests, [], "an unavailable host must not be read"); const check = button(container, "Check updates"); assert.equal(check.disabled, true); @@ -76,13 +76,13 @@ test("an ordinary incompatible host cannot be checked or updated", async (t) => }); test("an offline host stays unavailable", async (t) => { - const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", ompVersion: "omp/18.20.0", ompwebVersion: "0.7.0" }); + const { container, requests } = await renderHost(t, { id: "box", label: "Box", status: "offline", ompVersion: "omp/18.20.0", tauVersion: "0.7.0" }); assert.deepEqual(requests, []); assert.equal(button(container, "Check updates").disabled, true); assert.ok(container.textContent.includes("Updates unavailable while this host is offline."), container.textContent); }); -const modern = { id: "box", label: "Box", status: "online", apiVersion: 1, hostVersion: 12, ompwebVersion: "0.7.0" }; +const modern = { id: "box", label: "Box", status: "online", apiVersion: 1, hostVersion: 12, tauVersion: "0.7.0" }; const blocked = { canUpdate: false, canForceUpdate: true, blockedReason: "Sessions are running on this host" }; const posts = (requests) => requests.filter((request) => request.method === "POST"); // A closing dialog may linger briefly; the newest one is the one on screen. @@ -105,7 +105,7 @@ test("a normally blocked host offers a distinct Force update that posts nothing await act(async () => dialogButton("Terminate sessions and update").click()); await act(() => new Promise((resolve) => setTimeout(resolve, 20))); assert.equal(posts(requests).length, 1); - assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "ompweb", version: "0.7.1", force: true }); + assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "tau", version: "0.7.1", force: true }); }); test("force is never inferred from a blocker's wording", async (t) => { @@ -120,7 +120,7 @@ test("a host that can be updated normally offers no force and the normal payload act(() => button(container, "Update").click()); await act(async () => dialogButton("Update").click()); await act(() => new Promise((resolve) => setTimeout(resolve, 20))); - assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "ompweb", version: "0.7.1" }); + assert.deepEqual(JSON.parse(posts(requests)[0].body), { target: "tau", version: "0.7.1" }); }); test("a forced update outlives the old 5-minute wait, and giving up later only asks for a status check", async (t) => { @@ -129,12 +129,12 @@ test("a forced update outlives the old 5-minute wait, and giving up later only a Date.now = () => realNow() + skewMs; const requests = []; let posted = false; - const running = { id: "op", target: "ompweb", version: "0.7.1", state: "running", force: true }; + const running = { id: "op", target: "tau", version: "0.7.1", state: "running", force: true }; const originalFetch = globalThis.fetch; globalThis.fetch = async (url, init) => { requests.push({ url: String(url), method: init?.method ?? "GET", body: init?.body }); if (init?.method === "POST") { posted = true; return Response.json({ accepted: true, operation: running }); } - return Response.json({ ...info, ompweb: { ...info.ompweb, ...blocked }, operation: posted ? running : null }); + return Response.json({ ...info, tau: { ...info.tau, ...blocked }, operation: posted ? running : null }); }; const container = document.createElement("div"); document.body.append(container); @@ -156,7 +156,7 @@ test("a forced update outlives the old 5-minute wait, and giving up later only a skewMs = 6 * 60_000; // past the old 5-minute limit, inside the 15-minute lease await settle(1200); - assert.ok(container.textContent.includes("Updating ompweb host to 0.7.1"), container.textContent); + assert.ok(container.textContent.includes("Updating tau host to 0.7.1"), container.textContent); assert.ok(!container.textContent.includes("Stopped waiting"), "gave up inside the backend lease"); skewMs = 21 * 60_000; // beyond the wait @@ -169,7 +169,7 @@ test("a forced update outlives the old 5-minute wait, and giving up later only a }); test("uncertain shutdown recovery shows its durable error instead of polling Updating forever", async (t) => { - const operation = { id: "pending-stop", target: "ompweb", version: "0.7.1", state: "running", committing: true, recoveryRequired: true, error: "Recovery required: the daemon's shutdown could not be reconciled" }; + const operation = { id: "pending-stop", target: "tau", version: "0.7.1", state: "running", committing: true, recoveryRequired: true, error: "Recovery required: the daemon's shutdown could not be reconciled" }; const { container, requests } = await renderHost(t, modern, blocked, operation); assert.ok(container.querySelector('[role="alert"]').textContent.includes(operation.error)); assert.equal(button(container, "Check updates").disabled, false); diff --git a/components/HostUpdates.tsx b/components/HostUpdates.tsx index d084d9b8..246e3f14 100644 --- a/components/HostUpdates.tsx +++ b/components/HostUpdates.tsx @@ -83,7 +83,7 @@ export function HostUpdates({ host }: { host: HostRow }) { } if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`); // A successful status read, not POST acceptance, establishes the result. - if (!data.ompweb || !data.omp) throw new Error(t("hostUpdates.invalidResponse")); + if (!data.tau || !data.omp) throw new Error(t("hostUpdates.invalidResponse")); const next = data as HostUpdateInfo; setInfo(next); setError(null); @@ -179,10 +179,10 @@ export function HostUpdates({ host }: { host: HostRow }) {