diff --git a/AGENTS.md b/AGENTS.md index 020d304a..a86a07e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -559,7 +559,7 @@ The todo plan (`TodoList`) and subagent roster sit pinned above the input, each `hooks/useAudio.ts` stores the toggle (`tau-sound-enabled`) and reuses one `AudioContext`, unlocked from a user gesture in `ChatInput`; `ChatWindow` plays the tone from `onAgentEnd`. ### Notifications (`lib/notification-*.ts`, `public/sw.js`, Settings → Notifications) -- Detection runs on the server in `AgentSessionWrapper.handleFrame` (and `handleProcessExit`), so unwatched sessions notify. `createNotificationDetector()` inspects top-level frames only (subagent frames never notify). "Completed" fires on `session_settled`; a failed or aborted last prompt suppresses it. Other servers on a shared channel get the prompt's outcome as `peer_prompt_outcome`. Failures arrive as `prompt_error` and `process_exit`; one failure per run. A crash notifies "Run failed" while a run or its background work is unsettled. +- Detection runs on the server in `AgentSessionWrapper.handleFrame` (and `handleProcessExit`), so unwatched sessions notify. `createNotificationDetector()` inspects top-level frames only (subagent frames never notify). "Completed" fires on `session_settled`; a failed or aborted last prompt suppresses it. A refused message command reaches only the server that sent it (pi answers it only in that command's `response`). Failures arrive as `prompt_error` and `process_exit`; one failure per run. A crash notifies "Run failed" while a run or its background work is unsettled. - **Presence vs streams.** Tabs report `{clientId, deviceId, visible, sessionId, seq}` to `/api/notifications/presence` (on change, input after idling, every 30 s; expires 60 s after receipt; `visible` = visible and input within 3 min; `sessionId` null while Settings hides the chat; an older `seq` is dropped). Streams are the tab's open `notifications` subscriptions. Prefs PUTs run one at a time. - **Routing** (`routeNotification`): a visible tab on the session drops the event everywhere; else, with a visible connected tab, `whenActive: "toast"` devices get a toast on their active tabs; else push (subscribed devices) or in-page `showNotification`. The server decides before pushing (iOS revokes permission for silent pushes; `sw.js` always shows what it receives). - Prefs and subscriptions are per device (`localStorage`, mirrored to the SQLite store in `/tau/`, 0600, WAL; it holds the VAPID key and the history). Push text is rendered server-side in the device's locale. diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index 24cfa372..08aa5a8d 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -223,32 +223,29 @@ test("a companion-extension command is no user message: no peer marker, no edit await h.table.stop(); }); -test("a prompt_result returns under the sending link's own id, to that link only", async () => { +test("a prompt's response 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); 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(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]]); + const results = h.output.filter(item => item.body.type === "stdout" && JSON.parse(item.body.line).type === "response"); + assert.deepEqual(results.map(item => [item.id, JSON.parse(item.body.line).id]), [["l1", 1000]]); await h.table.stop(); }); -test("a prompt's outcome reaches the other members uncorrelated, so the elected notifier sees a peer's failure", async () => { +test("a refused prompt reaches only its sender: the owner reports it, and peers hear a run's failure from its broadcast events", 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(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({ 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")), [ - { 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" } }, - ]); + // pi answers a message command with a response only, accepted or refused. + h.children[0].emit({ type: "response", id: first.id, command: "prompt", success: true, data: {} }); + h.children[0].emit({ type: "response", id: second.id, command: "prompt", success: false, error: "No API key" }); + const outcomes = frames => frames.filter(frame => frame.type === "response"); + assert.deepEqual(outcomes(stdoutFrames(h, "l1")).map(frame => [frame.type, frame.id, frame.success]), [["response", 1000, true], ["response", 1001, false]]); + assert.deepEqual(outcomes(stdoutFrames(h, "l2")), []); await h.table.stop(); }); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 72d06d29..3ec40f3a 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -5,7 +5,7 @@ import { readSessionHeaderSync } from "../pi/session-files"; import { isValidSessionId } from "../session-file-references-core"; import { isRecord } from "../type-guards"; import type { DaemonLink } from "./daemon-link"; -import { CONFIG_VERSION_RE, CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, LINK_LIMITS, MESSAGE_COMMANDS, PEER_MESSAGE_FRAME, PEER_PROMPT_OUTCOME_FRAME, type HelloChannel, type OpenChannelRequest, type OpenChannelResult, type Unsequenced, type UpMessage } from "./link-protocol"; +import { CONFIG_VERSION_RE, CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, LINK_LIMITS, MESSAGE_COMMANDS, PEER_MESSAGE_FRAME, type HelloChannel, type OpenChannelRequest, type OpenChannelResult, type Unsequenced, type UpMessage } from "./link-protocol"; import { idOf, parseWire, PendingRequests, wireEvent, type WireFrame } from "./pending-requests"; import { StreamSnapshot } from "./stream-snapshot"; import { ChannelLifecycle } from "./channel-lifecycle"; @@ -356,25 +356,18 @@ export class ChannelTable { } const owner = channel.commands.get(fid); if (owner) { - if (!MESSAGE_COMMANDS.has(owner.op)) channel.commands.delete(fid); + channel.commands.delete(fid); const member = owner.link && channel.members.get(owner.link.id); if (member) this.deliver(channel, member, { type: "stdout", ch: channel.ch, line: JSON.stringify({ ...frame, id: owner.id }) }, true); return; } return; } - if ((frame.type === "prompt_result" || frame.type === "prompt_error" || frame.type === "bash_output" || frame.type === "bash_execution_update") && (typeof frame.id === "string" || typeof frame.id === "number")) { - const fid = String(frame.id); - const owner = channel.commands.get(fid); + if ((frame.type === "bash_output" || frame.type === "bash_execution_update") && (typeof frame.id === "string" || typeof frame.id === "number")) { + const owner = channel.commands.get(String(frame.id)); if (owner) { - if (frame.type === "prompt_result" || frame.type === "prompt_error") channel.commands.delete(fid); const member = owner.link && channel.members.get(owner.link.id); if (member) this.deliver(channel, member, { type: "stdout", ch: channel.ch, line: JSON.stringify({ ...frame, id: owner.id }) }); - if (frame.type === "prompt_result" || frame.type === "prompt_error") { - const outcome: WireFrame = { ...frame }; delete outcome.id; - const peer = JSON.stringify({ type: PEER_PROMPT_OUTCOME_FRAME, outcome }); - for (const other of channel.members.values()) if (other !== member) this.deliver(channel, other, { type: "stdout", ch: channel.ch, line: peer }); - } return; } } diff --git a/lib/hosts/daemon-runtime.test.mjs b/lib/hosts/daemon-runtime.test.mjs index e0fcee51..bb4df092 100644 --- a/lib/hosts/daemon-runtime.test.mjs +++ b/lib/hosts/daemon-runtime.test.mjs @@ -1,16 +1,21 @@ import assert from "node:assert/strict"; import test from "node:test"; +import { mock } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { tmpdir } from "node:os"; +import * as os from "node:os"; import { encodeBlobFrame, encodeLine, LINK_LIMITS, LINK_PROTOCOL_VERSION, PartJoiner } from "./link-protocol.ts"; -const scratch = mkdtempSync(join(tmpdir(), "daemon-multi-runtime-")); +const scratch = mkdtempSync(join(os.tmpdir(), "daemon-multi-runtime-")); const old = { agent: process.env.PI_CODING_AGENT_DIR, bin: process.env.TAU_PI_BIN, home: process.env.HOME, profile: process.env.USERPROFILE }; process.env.PI_CODING_AGENT_DIR = join(scratch, "agent"); // A member applies the master's configuration under its home directory too (`~/.agents/skills`). -process.env.HOME = process.env.USERPROFILE = join(scratch, "home"); -mkdirSync(process.env.HOME, { recursive: true }); +const home = join(scratch, "home"); +process.env.HOME = process.env.USERPROFILE = home; +mkdirSync(home, { recursive: true }); +// Bun's os.homedir() keeps the HOME it started with, so the daemon would apply into the real ~/.agents. +// This file runs in its own process (`bun test --parallel`), so the mock needs no restore. +mock.module("node:os", () => ({ ...os, default: { ...os.default, homedir: () => home }, homedir: () => home })); const fakePi = join(scratch, process.platform === "win32" ? "omp.cmd" : "omp"); const spawns = join(scratch, "spawns"); const envs = join(scratch, "envs"); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 697e636d..5d9c864b 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -1347,7 +1347,7 @@ export class RemoteRpcTransport implements RpcTransport { deliverLine(line: string): void { if (this.closed) return; - if (line.includes('"command":"get_state"') || line.includes('"type":"session"') || line.includes('"t":"hello"') || line.includes('"t":"session"')) this.noteSession(line); + if (line.includes('"command":"get_state"') || line.includes('"type":"session"')) this.noteSession(line); if (this.lineListeners.length > 0) return notify(this.lineListeners, line); const bytes = this.holdable(line); if (bytes === null) return; @@ -1388,7 +1388,7 @@ export class RemoteRpcTransport implements RpcTransport { if (!isRecord(frame)) return; const sessionId = frame.type === "response" && frame.command === "get_state" && frame.success === true && isRecord(frame.data) ? frame.data.sessionId - : (frame.type === "session" || frame.t === "hello" || frame.t === "session") ? frame.sessionId : undefined; + : frame.type === "session" ? frame.sessionId : undefined; if (typeof sessionId === "string" && isValidSessionId(sessionId)) { this.session = sessionId; } diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index fae547bc..2ce370cb 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -66,9 +66,6 @@ export const HISTORY_MUTATING_COMMANDS = new Set([ export const MESSAGE_COMMANDS = new Set(["prompt", "steer", "follow_up", "followUp"]); /** Shared-channel marker a daemon puts in the other members' output when one link writes a message command. */ export const PEER_MESSAGE_FRAME = "peer_message_command"; -/** Shared-channel frame `{t, outcome}` a daemon puts in the other members' output for one link's `prompt_result` or - * `prompt_error` (its command id dropped): the elected notifier must hear a run failed whichever server prompted it. */ -export const PEER_PROMPT_OUTCOME_FRAME = "peer_prompt_outcome"; /** Named `req.args` keys for each session op, in parameter order. Named, not * positional, so an omitted optional argument never turns into `null`. */ diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index cd2ad152..a994d34a 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -920,16 +920,6 @@ test("an asynchronous prompt failure (prompt_error) notifies the user", async (t assert.deepEqual(delivered, [["error", "No API key for provider"]]); }); -test("a peer server's failed prompt suppresses completion and notifies its failure", async (t) => { - const { feed, delivered } = await notifyingSession(t); - feed({ type: "agent_start" }); - feed({ type: "agent_end", isTerminal: true, messages: [] }); - feed({ type: "peer_prompt_outcome", outcome: { t: "prompt_result", agentInvoked: true, status: "error", error: { message: "boom" } } }); - feed({ type: "session_settled" }); - feed({ type: "peer_prompt_outcome", outcome: { t: "prompt_error", command: "prompt", error: "No API key" } }); - assert.deepEqual(delivered, [["error", "boom"], ["error", "No API key"]]); -}); - test("a crash of an idle session does not notify", async (t) => { const { wrapper, delivered } = await notifyingSession(t); wrapper.handleProcessExit({ code: 1, signal: null, stderrTail: "out of memory" }); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index a83d4c1d..0ca70405 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -42,7 +42,7 @@ import type { import type { AgentConfirmPayload, AgentMessage, CrossSessionHostToolCall, CrossSessionHostToolEvent, ExitedRpcSession, ExtensionWidgetItem } from "./types"; import { isLinkUp, type Host, type HostStatus, type SpawnRequest } from "./hosts/host"; import { freezeHostLinks, getHost, hostOwnsLifecycle, isNotifier, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; -import { CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, PEER_MESSAGE_FRAME, PEER_PROMPT_OUTCOME_FRAME } from "./hosts/link-protocol"; +import { CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, PEER_MESSAGE_FRAME } from "./hosts/link-protocol"; import { LOCAL_HOST_ID } from "./hosts/registry"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId, invalidateHostSessionList, listSessionsAllHosts, sessionSpawnTarget } from "./hosts/session-index"; @@ -911,13 +911,6 @@ export class AgentSessionWrapper { this.peerMessageCommands += 1; return; } - if (event.type === PEER_PROMPT_OUTCOME_FRAME) { - // Another server's prompt ended: only the notification detector reads it (that server owns the prompt's state). - const { t: type, ...outcome } = isRecord(event.outcome) ? event.outcome : {}; - if (type === "prompt_result") this.publishNotifications({ ...outcome, type }); - else if (type === "prompt_error") this.publishNotifications({ ...outcome, type, errorMessage: typeof outcome.error === "string" ? outcome.error : "Prompt failed" }); - return; - } if (this.hostOwnedLifecycle && event.type === "host_tool_call" && typeof event.id === "string") { const key = `${event.type}:${event.id}`; if (this.deliveredCallbacks.has(key)) return;