From 2fd0f0c8bb10d8e4d4900906f2ca34461e724409 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:02:58 +0000 Subject: [PATCH 01/10] Send Bot rows' Needs you, Failed, last reply and preview from aiden serve With durable Bot sessions on, the headless server builds the same live Bot summary the desktop uses (conversation, state, queued inputs and whether an approval waits on the person). It feeds the host feed's Bot rows (needsYou, failed, lastReplyAt, preview), so a paired desktop's Bots list and Inbox show this server's Bots as they show a Mac's, and the router's botNeedsYou, so the server offers bot:needs-you to phones. The feed refreshes when a Bot's turn starts or ends, on a pause, and when an approval opens or settles. Without durable sessions nothing changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .memory/bot-chat-activity.md | 4 +-- docs/aiden-on-the-go-remote-access.md | 2 +- docs/aiden-remote-api-v1.md | 4 +-- packages/cli/src/remote-bots.ts | 43 ++++++++++++++++++++++++++- packages/cli/src/remote.ts | 14 ++++++--- packages/cli/tests/parity.test.mjs | 33 ++++++++++++++++++++ 6 files changed, 90 insertions(+), 10 deletions(-) diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index 618310c1f8..abc55415f2 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -107,6 +107,6 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev - PR 3 (desktop only, no revision): the desktop asks for `bot:cards`, `bot:access-requests` and `bot:plans` (each `own_call`, only when the host lists them) and answers them through new peer ops `botRespondRoutineProposal`, `botAnswerAccessRequest`, `botRespondPlan`. `remote-bot-session.ts` maps plan/access frames onto `snapshot.plan`/`accessRequest` (plan items get place ids; `revision` = the frame's seq) and memory/routine entries onto local rows. `RemoteBotChatView` puts access and pending plan cards in the Needs-you slot, an active plan in the body, echoes sends at once (shared `BotPendingSend` helpers from bot-chat-pane) and shows a re-pair hint group for old pairings (`remoteBotGroups`). Host: `AidenRemoteBotService.list()` leaves out a Bot whose summary fails the contract instead of failing the whole list (and the host feed). - PR 3 follow-up: `peerBotSessionCompat` dropped `accessRequest` and `plan` from session reads, so a reload lost the card; both are now kept (an unreadable one becomes null). - PR 3b (Remote revision 67, provisional; re-claim at merge): `GET /bots/{botId}/session/entries?before=&limit=` (projector `olderEntries`, same audience as the snapshot; unknown `before` = 409 operation_stale) and `POST /bots/{botId}/queued/{submissionId}/withdraw` (needs `bot:activity`; routine/intro inputs read `gone`; runtime gained `withdraw`). No feature tokens: the server feature list is at its 32-token cap, so the desktop treats a 404 as an older host. Peer ops `botSessionEntries`, `botWithdrawQueued`; the follower's `loadOlder` + `carryOlderRemoteBotEntries` keep loaded pages across same-epoch snapshots. "Every waiting approval" was dropped: the next approval already follows each answer, and a count would need a new opt-in because phone approval decoders are strict. -- PR 4 (2026-11-24, provisional revision 68, `bot:needs-you`): `GET /bots` summaries carry `needsYou: true` only for devices holding the opt-in (Android's Bot decoder rejects unknown keys). Router dependency `botNeedsYou(botIds)` reads `botLiveProjection().needsYou` (no transcript read); a failed read sends the list without it. iOS and Android ask for it alone; home rows read "Waiting for you" and stop showing as working, an approval the phone sees keeps "Needs your OK"; iOS inbox counts it. `aiden serve` doesn't wire it yet (PR 5). -- Still to come: PR 5 (headless server sends the same Bot signals). Not planned yet: a model picker for a remote Bot with a model problem (no remote route sets a Bot's model). +- PR 4 (2026-11-24, provisional revision 68, `bot:needs-you`): `GET /bots` summaries carry `needsYou: true` only for devices holding the opt-in (Android's Bot decoder rejects unknown keys). Router dependency `botNeedsYou(botIds)` reads `botLiveProjection().needsYou` (no transcript read); a failed read sends the list without it. iOS and Android ask for it alone; home rows read "Waiting for you" and stop showing as working, an approval the phone sees keeps "Needs your OK"; iOS inbox counts it. +- PR 5 (2026-11-24): `aiden serve` with durable Bots builds a `BotLiveProjection` (`createCliBotSignals` in `packages/cli/src/remote-bots.ts`: conversation, state, quietInputs, `approvalPending` from the CLI approvals bridge). It feeds host-feed `botSignals` (needsYou, failed, lastReplyAt, preview) and the router's `botNeedsYou`, so the server offers `bot:needs-you`. The feed refreshes on the durable runtime's state changes and `approvals.onChange`. CLI Bots ask no questions or hand-offs, so an approval is the only wait. Without durable sessions nothing changes. Not planned yet: a model picker for a remote Bot with a model problem (no remote route sets a Bot's model). diff --git a/docs/aiden-on-the-go-remote-access.md b/docs/aiden-on-the-go-remote-access.md index 7222dc6276..3bee271c4b 100644 --- a/docs/aiden-on-the-go-remote-access.md +++ b/docs/aiden-on-the-go-remote-access.md @@ -126,7 +126,7 @@ When the paired Mac offers it (contract revision 42, `bot:issues`), a Bot's **Ne ## Bots waiting on you on the phone -When the paired Mac offers it (contract revision 68, `bot:needs-you`, provisional), a Bot that waits on you there (an approval, a question, a hand-off, an access request, a plan to OK or a Needs you card) reads **Waiting for you** on the Bots list of Aiden On The Go for iPhone and Android, instead of looking busy. An approval the phone can already see in that Bot's chat keeps its own line, such as "Needs your OK". On iPhone the Inbox also lists that Bot under **Needs you**. The phone picks this up whenever it reads the Bots list again. An `aiden serve` host, or a Mac on an older Aiden, doesn't offer it yet, and the list looks as before. +When the paired Mac offers it (contract revision 68, `bot:needs-you`, provisional), a Bot that waits on you there (an approval, a question, a hand-off, an access request, a plan to OK or a Needs you card) reads **Waiting for you** on the Bots list of Aiden On The Go for iPhone and Android, instead of looking busy. An approval the phone can already see in that Bot's chat keeps its own line, such as "Needs your OK". On iPhone the Inbox also lists that Bot under **Needs you**. The phone picks this up whenever it reads the Bots list again. An `aiden serve` server with durable Bot sessions offers it too, for a Bot waiting on an approval. A Mac on an older Aiden doesn't, and the list looks as before. ## Bot messaging on the phone diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 3baf5e906e..bdc651fd49 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1140,7 +1140,7 @@ A desktop that wrote triage keeps its own answer until the host reports a `triag - Run control stops runs and answers approvals, including approvals raised by a phone's turn. Only a one-time decision applies: an approval answer with any `scope` other than `once` is refused with `400 invalid_request`, because the CLI keeps no remembered approvals. The CLI's runs ask no questions and take no mid-run input: an answer is refused, and input is refused as `run_not_active`. The server does not advertise `chat-run-input-v1` or `chat-question-prompts-v1`, so a paired desktop shows Stop and approvals on its runs, but no Steer and no question answers. - Phones paired to the CLI hear `phone-run-control-v1`, `chat-read-state-v1` and `chat-triage-v1`, as on a Mac. They may negotiate `runs:observe` and `runs:control`, then watch, stop and answer approvals on runs another device started, and share read markers and unread state. They are still refused `GET /host/events`. Phones offer no Steer or Queue on a run they did not start, and show a question card only when a run asks one, which a CLI run never does. - Revoking a device (`aiden remote revoke `) ends its host feed, run streams and Bot session streams. It never cancels a run. -- Host-feed Bot rows carry no `needsYou`, `failed` or `lastReplyAt`, and a Bot edit reaches the feed only with its next other change (a chat, workspace, run, read marker or triage change). +- With durable Bot sessions on (`aiden bots enable-durable`), host-feed Bot rows carry `needsYou` (an approval waiting on the person; CLI Bots ask no questions and take no hand-offs), `failed`, `lastReplyAt` and the revision-66 `preview`, from the same live summary the desktop uses. A Bot's turn starting or ending, a pause and an approval opening or settling refresh the feed. Without durable sessions the rows carry none of them. A Bot edit (its name or avatar) still reaches the feed only with its next other change (a chat, workspace, run, read marker or triage change). - A snooze is re-checked at least once a minute while `aiden serve` runs. The host does not re-check it when the computer wakes or unlocks. ## New worktree from a phone, revision 53 (`chat:new-worktree`, provisional) @@ -1522,7 +1522,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 Revision 68 is provisional: it was written when `main` was at 65 and revisions 66 and 67 were still open, and the host keeps it in one constant (`AIDEN_REMOTE_BOT_NEEDS_YOU_CONTRACT_REVISION`), so claiming the next free number at merge changes only that constant. -**Negotiation.** The host lists `bot:needs-you` in `serverCapabilities` to a device that may hold Bot opt-ins, whenever it can tell which Bots wait on the person. A device asks for it with `POST /device/capabilities {accepts: ["bot:needs-you"]}` in a call of its **own**: a host older than revision 68 refuses the unknown name with `400 invalid_request`, and a host that cannot tell answers `404 not_found`. Pairing never issues it, and there is no `/server` feature token (the list is at its 32-token limit). +**Negotiation.** The host lists `bot:needs-you` in `serverCapabilities` to a device that may hold Bot opt-ins, whenever it can tell which Bots wait on the person: the desktop app, and `aiden serve` with durable Bot sessions on (there an approval is the only wait, since its Bots ask no questions and take no hand-offs). A device asks for it with `POST /device/capabilities {accepts: ["bot:needs-you"]}` in a call of its **own**: a host older than revision 68 refuses the unknown name with `400 invalid_request`, and a host that cannot tell answers `404 not_found`. Pairing never issues it, and there is no `/server` feature token (the list is at its 32-token limit). **Audience-gated `needsYou`.** `GET /bots` summaries (`BotSummary`) carry `needsYou: true` only for a device holding `bot:needs-you`, and only for a Bot the person owes an answer: an open approval, question, hand-off, access request, pending plan or issue. That is the same signal the host's own Bots list, the host feed's revision-52 `needsYou` and the Dock badge use, read without the Bot's transcript. It is never sent as `false`, and other devices never see the key: Android's Bot decoder rejects unknown keys. If the host cannot read the signal for a list, it sends the list without it rather than failing. diff --git a/packages/cli/src/remote-bots.ts b/packages/cli/src/remote-bots.ts index 2ae3cf90ee..7178f00b5f 100644 --- a/packages/cli/src/remote-bots.ts +++ b/packages/cli/src/remote-bots.ts @@ -12,6 +12,45 @@ import type { AidenIdempotencyLedger, AidenIdempotencySnapshot } from "../../../ import { CLI_BOT_OWNER_AUDIENCE_ID, type createCliBots } from "./bots.ts"; import type { createCliRemoteChats } from "./remote-chats.ts"; import type { createDaemonChats } from "./daemon-chats.ts"; +import { createBotLiveProjection, type BotLiveProjection } from "../../../main/services/bot-runtime/live-projection.js"; +import { hostFeedBotSignals, type AidenRemoteHostFeedBotSignals } from "../../../main/services/aiden-remote-host-feed.js"; + +/** Four at a time, like the desktop: each read may open a Bot's transcript. */ +async function eachBot(ids: readonly string[], read: (id: string) => Promise): Promise> { + const out: Array = []; + for (let start = 0; start < ids.length; start += 4) { + out.push(...await Promise.all(ids.slice(start, start + 4).map(async (id) => [id, await read(id)] as const))); + } + return out; +} + +/** + * The summary this host's Bot rows come from, as on the desktop: what waits on + * the person (an approval), the run state, the newest reply and its line. A + * Bot's transcript is read again only after its newest entry changes. + */ +export function createCliBotSignals(durable: NonNullable>["durable"]>) { + const live: BotLiveProjection = createBotLiveProjection({ + conversation: (botId) => durable.runtime.conversation(botId), + state: (botId) => durable.runtime.state(botId), + quietInputs: (botId, ids) => durable.runtime.quietInputs(botId, ids), + approvalPending: (botId) => durable.approvals.pending(botId).length > 0, + }); + return { + /** Host feed Bot rows (revisions 52 and 66): Needs you, Failed, last reply and its line. */ + botSignals: async (bots: readonly { id: string }[]): Promise> => + new Map(await eachBot(bots.map((bot) => bot.id), async (id) => hostFeedBotSignals(await live.summary(id).catch(() => undefined)))), + /** Revision 68 (`bot:needs-you`): which Bots wait on the person, without reading transcripts. */ + botNeedsYou: async (botIds: readonly string[]): Promise> => + new Set((await eachBot(botIds, (id) => live.needsYou(id).catch(() => false))).filter(([, waiting]) => waiting).map(([id]) => id)), + /** A Bot's row changed: its state (a turn started or ended, a pause) or an approval. */ + onChange(listener: () => void): () => void { + const detach = [durable.stateChanges(() => listener()), durable.approvals.onChange(() => listener())]; + return () => { for (const off of detach) off(); }; + }, + close: () => live.close(), + }; +} export function createCliRemoteBots(agentDir: string, instanceId: string, runtime: Awaited>, daemon: ReturnType, chatApi: Awaited>, idempotency: AidenIdempotencyLedger, persistIdempotency: (value: AidenIdempotencySnapshot) => Promise) { @@ -48,5 +87,7 @@ export function createCliRemoteBots(agentDir: string, instanceId: string, runtim // A pause or unpause from `aiden bots` changes only the state; open phone streams hear it here. stateChanges: runtime.durable.stateChanges, }) : undefined; - return { bots, botFiles, ...(botSessions ? { botSessions } : {}) }; + const signals = runtime.durable ? createCliBotSignals(runtime.durable) : undefined; + // `signals` is for the host feed; the rest are Remote routes. + return { bots, botFiles, ...(botSessions ? { botSessions } : {}), ...(signals ? { botNeedsYou: signals.botNeedsYou, signals } : {}) }; } diff --git a/packages/cli/src/remote.ts b/packages/cli/src/remote.ts index 1e25798082..695fc6bde1 100644 --- a/packages/cli/src/remote.ts +++ b/packages/cli/src/remote.ts @@ -196,6 +196,7 @@ export async function createCliRemote(agentDir: string, chats: ReturnType scheduledSettingsPatch(input, validateTimezone), notifyChanged: () => {}, }); let botSessions: import("../../../main/services/aiden-remote-bot-session.js").AidenRemoteBotSessionService | undefined; + let botSignals: ReturnType | undefined; let chatApi: Awaited> | undefined; // One chat runtime for Remote and the MCP server, whichever asks first. let chatApiLoad: Promise>> | undefined; @@ -217,8 +218,10 @@ export async function createCliRemote(agentDir: string, chats: ReturnType chats.llmClient.cancelRun(runId), @@ -236,9 +239,10 @@ export async function createCliRemote(agentDir: string, chats: ReturnType { const run = chats.runs.summary(runId); return run ? liveRunAttention(run.chatId, chats.runs)?.summary : undefined; }, liveRuns: () => chats.runs.list(), - // No live Bot summaries on this host, so Bot rows carry no Needs you, Failed or last reply. + // Bot rows carry Needs you, Failed, the last reply and its line from the same live summary the desktop uses. source: createAidenRemoteHostFeedSource({ chats: api.chats, listWorkspaces: () => workspaces.application.list(), - repositoryIdentity: git.gitCachedRepositoryIdentity, listBots: () => botApi.bots.list() }), + repositoryIdentity: git.gitCachedRepositoryIdentity, listBots: () => botApi.bots.list(), + ...(signals ? { botSignals: signals.botSignals } : {}) }), }); hostFeed = feed; const detachers = [ @@ -247,6 +251,8 @@ export async function createCliRemote(agentDir: string, chats: ReturnType feed.invalidate()), workspaces.configStore.onWorkspacesChanged(() => feed.invalidate()), chats.runs.onChange((summary, removed) => feed.noteRun(summary, removed)), + // A turn started or ended (a new reply), a pause, or an approval opened or settled. + ...(signals ? [signals.onChange(() => feed.invalidate())] : []), ]; detachHostFeed = () => { for (const detach of detachers) detach(); }; return { @@ -300,7 +306,7 @@ export async function createCliRemote(agentDir: string, chats: ReturnType cliAppsCommand(mcp, args), // The MCP listener closes first, so no outside app starts a turn while the rest stops. - async stop() { await mcp.stop(); closeHostFeed(); chatApi?.stopInbox(); await botSessions?.close(); await chats.stop(); await service.stopAndSettle(); await speech.stop(); await scheduledMcp.close(); if (!options.bots) await bots.stop(); }, + async stop() { await mcp.stop(); closeHostFeed(); chatApi?.stopInbox(); await botSessions?.close(); await botSignals?.close(); await chats.stop(); await service.stopAndSettle(); await speech.stop(); await scheduledMcp.close(); if (!options.bots) await bots.stop(); }, async command(args: string[]) { const [action = "status", value] = args; switch (action) { diff --git a/packages/cli/tests/parity.test.mjs b/packages/cli/tests/parity.test.mjs index 12644662b9..1569414b67 100644 --- a/packages/cli/tests/parity.test.mjs +++ b/packages/cli/tests/parity.test.mjs @@ -2396,6 +2396,17 @@ test("durable CLI Bots can message each other", async (t) => { assert.equal(capabilities.status, 200); assert.equal(capabilities.data.serverCapabilities.includes("bot:allowed"), false, "CLI never advertises desktop remembered approvals"); assert.equal((await request(modern, `/bots/${bots[0].id}/allowed`)).status, 404, "CLI supplies no remembered-approval endpoint"); + // Revision 68: this server says which Bots wait on the person, only to a device that asked. + assert.ok(capabilities.data.serverCapabilities.includes("bot:needs-you"), "the server offers bot:needs-you"); + const askedNeedsYou = await request(modern, "/device/capabilities", "POST", { accepts: ["bot:needs-you"] }); + assert.equal(askedNeedsYou.status, 200, JSON.stringify(askedNeedsYou)); + const pendingApprovals = host.durable.approvals.pending; + host.durable.approvals.pending = (id) => id === bots[0].id ? [{ botId: id }] : []; + try { + const waiting = await request(modern, "/bots"); + assert.deepEqual(waiting.data.bots.filter((row) => row.needsYou).map((row) => row.id), [bots[0].id]); + assert.equal((await request(older, "/bots")).data.bots.some((row) => "needsYou" in row), false, "a device that didn't ask never sees the key"); + } finally { host.durable.approvals.pending = pendingApprovals; } const list = await request(modern, "/bots"); assert.equal(list.status, 200); assert.deepEqual(list.data.messaging, { enabled: true }); assert.equal((await request(older, "/bots")).data.messaging, undefined); @@ -2537,6 +2548,28 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f const imageData = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aX1sAAAAASUVORK5CYII="; const sent = await host.durable.runtime.send(bot.id, { text: "Hello", requestId: "migration-first", attachments: [{ type: "image", mimeType: "image/png", data: imageData }] }); assert.deepEqual(await host.durable.runtime.awaitReply(bot.id, sent.submissionId, new AbortController().signal), { kind: "completed", text: "Durable answer" }); + // A paired desktop's Bot row and a phone's Bots list read what this server's own Bot did, as from a Mac. + const { signals } = api.createCliRemoteBots(dir, "test-instance", host, daemon, {}, ledger, async () => {}); + try { + const row = (await signals.botSignals([{ id: bot.id }])).get(bot.id); + assert.equal(row.preview, "Durable answer"); + assert.ok(Date.parse(row.lastReplyAt) > 0, JSON.stringify(row)); + assert.equal(row.needsYou, undefined); + assert.equal(row.failed, undefined); + assert.deepEqual([...await signals.botNeedsYou([bot.id])], []); + let changes = 0; + const off = signals.onChange(() => { changes += 1; }); + const pending = host.durable.approvals.pending; + host.durable.approvals.pending = (id) => id === bot.id ? [{ botId: bot.id }] : []; + try { + assert.deepEqual([...await signals.botNeedsYou([bot.id])], [bot.id], "an approval waiting on the person"); + assert.equal((await signals.botSignals([{ id: bot.id }])).get(bot.id).needsYou, true); + } finally { host.durable.approvals.pending = pending; } + await host.command(["pause", bot.id]); + await host.command(["unpause", bot.id]); + assert.ok(changes > 0, "a pause reaches the host feed"); + off(); + } finally { await signals.close(); } const durableEntries = (await (await host.durable.runtime.conversation(bot.id)).context(api.BACKGROUND_CONTEXT)).entries; const callContext = api.cliDurableBotToolContext([...durableEntries].reverse(), { chatId: legacy.id, botId: bot.id }); const forkSnapshot = await callContext.loadChat(); From ef11fd6ddd9a16d820bde559ff79c65389436bea Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:03:07 +0000 Subject: [PATCH 02/10] Say in the server README that its Bot rows now carry Needs you, Failed and the last reply Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- packages/cli/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index a1408a5cbb..d837a30ce5 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -112,7 +112,7 @@ Phones and Macs paired with the server see its workspaces, chats, Bots, schedule - **Inline visuals.** In a workspace chat, `render_artifact` checks the HTML exactly as the desktop does, saves an offline export page in `/artifacts`, and then draws the visual once as a still picture (PNG at twice the pixel density, 720 px wide or 1024 px for `layout: "wide"`) that paired phones and desktops show in the reply, as they show a Mac's visual snapshot. The server draws with an installed Chrome or Chromium found only at fixed paths: `/Applications/Google Chrome.app` or `/Applications/Chromium.app` on macOS, and `/usr/bin/google-chrome-stable`, `/usr/bin/google-chrome`, `/usr/bin/chromium` or `/usr/bin/chromium-browser` on Linux. It never searches `PATH`, reads no variable to find one, and downloads nothing; the Docker image ships no browser. The browser is looked for only when a visual is drawn, runs headless with its sandbox on, a new temporary profile (deleted afterwards), every network request refused and a 15-second limit, and draws one visual at a time. The visual's sandboxed frame stays in the page's own process (Chrome's `IsolateSandboxedIframes` is off): with it on, Chrome 158 crashes when the page is set, and the extra process slowed drawing on small machines. A server running as root does not draw visuals, since Chrome would need its sandbox off there. Without a browser, or when drawing fails, the person sees no visual and Aiden is told so and asked to give the facts as text. `render_ui` visuals reach the phone as their text rendering, with each chart's, heatmap's and sparkline's data written out and each table row as one plain line of labelled values (`Customer: Acme · Revenue: $1.2M`), since the server has no component renderer; a Mac paired to the server shows the same text. Every tool result says exactly which of these the person sees. A visual is never interactive on the server: phones are not offered the visual viewer. - **Forks.** Paired phones fork server chats with the Remote `chat-fork-v1` feature; the fork's journal is seeded from the copied visible messages, so tool results before the cut are not carried. The server does not offer Fork with summary (`chat-fork-summary-v1`). -- **Paired desktops.** A Mac or Linux desktop paired to the server lists its chats in the sidebar and the Inbox. The server serves the host feed (`GET /host/events`), live-run observation and run control (Stop and approvals), shared read markers (`POST /chats/{id}/read`), and the Inbox's Pin, Done and Snooze (`POST /chats/{id}/triage`), with the same `inbox-signals-v1` row times, last assistant message ID and Inbox bucket as the desktop. Mark read acknowledges the reply displayed on the paired device. Read markers and triage are kept in `chat-read-markers.json` and `chat-triage.json` in the server's data directory, and snoozes end on a timer that runs with `aiden serve`. A desktop paired before this server version doesn't need to pair again: it picks up the host grants on its next connection after Aiden starts (relaunch Aiden if it was already connected). Approvals from a paired device apply once; the server keeps no "always allow" approvals and refuses one. A paired device that negotiates `approval:cards` (contract revision 61) gets the same typed approval card the desktop sends and can allow only what that card offers; the approval mode and rules routes, Bot settings changes, suggestions and Templates are desktop-only. The server's runs don't take questions or mid-run input, so a paired desktop shows Stop and approvals on them but no Steer. The server's Bot rows carry no Needs you, Failed or last-reply signals, so its Bots appear in a desktop's Inbox only while they are open. +- **Paired desktops.** A Mac or Linux desktop paired to the server lists its chats in the sidebar and the Inbox. The server serves the host feed (`GET /host/events`), live-run observation and run control (Stop and approvals), shared read markers (`POST /chats/{id}/read`), and the Inbox's Pin, Done and Snooze (`POST /chats/{id}/triage`), with the same `inbox-signals-v1` row times, last assistant message ID and Inbox bucket as the desktop. Mark read acknowledges the reply displayed on the paired device. Read markers and triage are kept in `chat-read-markers.json` and `chat-triage.json` in the server's data directory, and snoozes end on a timer that runs with `aiden serve`. A desktop paired before this server version doesn't need to pair again: it picks up the host grants on its next connection after Aiden starts (relaunch Aiden if it was already connected). Approvals from a paired device apply once; the server keeps no "always allow" approvals and refuses one. A paired device that negotiates `approval:cards` (contract revision 61) gets the same typed approval card the desktop sends and can allow only what that card offers; the approval mode and rules routes, Bot settings changes, suggestions and Templates are desktop-only. The server's runs don't take questions or mid-run input, so a paired desktop shows Stop and approvals on them but no Steer. With durable Bot sessions on, the server's Bot rows carry Needs you (an approval waiting), Failed, the last reply time and the last message, as a Mac's do, so a paired desktop shows them in its Bots list and Inbox, and phones that ask for `bot:needs-you` show "Waiting for you". Without durable sessions the rows carry none of them, and its Bots appear in a desktop's Inbox only while they are open. - **Joining a running chat.** Revision 58 clients can request a bounded snapshot of the server’s public reply, reasoning and activity when they attach or reconnect. Saved messages are available through the usual chat history. - **Phones and other runs.** A paired phone can watch, stop and answer approvals on a run another device started (`phone-run-control-v1`), shares read markers and unread state with paired desktops, and marks chats Done or snoozes them from its Inbox (`chat-triage-v1`, under the `chat:write` it was paired with). It doesn't read the host feed, and it offers no Steer on a run it didn't start. - **Project transfer.** The server does not advertise the desktop's `workspace-clone-v1` project transfer (Add this project to another machine); its Remote API keeps the existing workspace creation modes. From ad2cec8ed09be7cd256989e581dd31cd1105a345 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:16:42 +0000 Subject: [PATCH 03/10] Refresh aiden serve's host feed when a Bot turn ends Follow a running Bot in the live projection, as the desktop does, so the end of every turn (reply or failure) invalidates the feed with its final row. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- packages/cli/src/bot-durable.ts | 9 +++++---- packages/cli/src/remote-bots.ts | 30 +++++++++++++++++++++++++----- packages/cli/tests/parity.test.mjs | 26 ++++++++++++++++++++++++-- 3 files changed, 54 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/bot-durable.ts b/packages/cli/src/bot-durable.ts index 7977eb1e3e..7a9282966a 100644 --- a/packages/cli/src/bot-durable.ts +++ b/packages/cli/src/bot-durable.ts @@ -1,4 +1,5 @@ import { createBotMessageLedger } from "../../../main/services/bot-messages/ledger.js"; +import type { BotSessionState } from "../../../main/services/bot-runtime/bot-session-service.js"; import { createBotMessageCourier } from "../../../main/services/bot-messages/courier.js"; import { createBotMessageLifecycle } from "../../../main/services/bot-messages/lifecycle.js"; import { projectBotMessageRoster } from "../../../main/services/bot-messages/roster.js"; @@ -86,9 +87,9 @@ export async function createCliDurableBots(profileDir: string, ports: CliDurable const imageInputs = new Map(); const approvals = createBotApprovals({ publish: () => {} }); const memory = createBotMemoryService({ store: createBotMemoryStore({ profileDir }) }); - const stateListeners = new Set<(botId: string) => void>(); + const stateListeners = new Set<(botId: string, state: BotSessionState) => void>(); /** Pause changes commit no entry; open phone streams hear them here. */ - const stateChanges = (listener: (botId: string) => void) => { stateListeners.add(listener); return () => { stateListeners.delete(listener); }; }; + const stateChanges = (listener: (botId: string, state: BotSessionState) => void) => { stateListeners.add(listener); return () => { stateListeners.delete(listener); }; }; const spending = createCliBotSpending(profileDir); const spendingRefusal = async (botId: string) => spending.refusal(botId, (await ports.botStore.get(botId))?.name); const roster = async () => projectBotMessageRoster(await ports.botStore.list(), { @@ -227,9 +228,9 @@ export async function createCliDurableBots(profileDir: string, ports: CliDurable }, }, onSessionOpen: (botId) => memory.beginSession(botId), - onStateChange: (botId) => { + onStateChange: (botId, state) => { for (const listener of stateListeners) { - try { listener(botId); } catch (error) { process.stderr.write(`Bot ${botId} state listener failed: ${error instanceof Error ? error.message : String(error)}\n`); } + try { listener(botId, state); } catch (error) { process.stderr.write(`Bot ${botId} state listener failed: ${error instanceof Error ? error.message : String(error)}\n`); } } }, deleteEffects: [(botId) => messages.forgetBot(botId), ports.deleteRoutines, async (botId) => { try { await spending.forgetBot(botId); } catch (error) { process.stderr.write(`Bot ${botId} spending cleanup: ${String(error)}\n`); } }, async (botId) => { memory.forgetBot(botId); models.forget(botId); imageInputs.delete(botId); }, async (botId) => { await ports.pauses.forgetBot(botId); }, async (botId) => { await ports.application.deleteBot({ botId }); }], diff --git a/packages/cli/src/remote-bots.ts b/packages/cli/src/remote-bots.ts index 7178f00b5f..02d2843c93 100644 --- a/packages/cli/src/remote-bots.ts +++ b/packages/cli/src/remote-bots.ts @@ -27,15 +27,31 @@ async function eachBot(ids: readonly string[], read: (id: string) => Promise< /** * The summary this host's Bot rows come from, as on the desktop: what waits on * the person (an approval), the run state, the newest reply and its line. A - * Bot's transcript is read again only after its newest entry changes. + * Bot's transcript is read again only after its newest entry changes. As on + * the desktop, a running Bot's feed stays open until its run settles, so the + * end of every turn (a reply, a failure) reaches the host feed with its row. */ export function createCliBotSignals(durable: NonNullable>["durable"]>) { + const listeners = new Set<() => void>(); + const changed = () => { + for (const listener of [...listeners]) { + try { listener(); } catch (error) { process.stderr.write(`aiden: Bot row listener failed: ${error instanceof Error ? error.message : String(error)}\n`); } + } + }; const live: BotLiveProjection = createBotLiveProjection({ conversation: (botId) => durable.runtime.conversation(botId), state: (botId) => durable.runtime.state(botId), quietInputs: (botId, ids) => durable.runtime.quietInputs(botId, ids), approvalPending: (botId) => durable.approvals.pending(botId).length > 0, + // A run ended: its reply, or why it failed, is now readable. + onRunSettled: () => changed(), + onError: (botId, error) => process.stderr.write(`aiden: Bot ${botId} row: ${error instanceof Error ? error.message : String(error)}\n`), }); + // A turn started or ended, or a pause: the feed follows a running Bot to its end. + const detach = [ + durable.stateChanges((botId, state) => { live.notifyState(botId, state); changed(); }), + durable.approvals.onChange(() => changed()), + ]; return { /** Host feed Bot rows (revisions 52 and 66): Needs you, Failed, last reply and its line. */ botSignals: async (bots: readonly { id: string }[]): Promise> => @@ -43,12 +59,16 @@ export function createCliBotSignals(durable: NonNullable> => new Set((await eachBot(botIds, (id) => live.needsYou(id).catch(() => false))).filter(([, waiting]) => waiting).map(([id]) => id)), - /** A Bot's row changed: its state (a turn started or ended, a pause) or an approval. */ + /** A Bot's row changed: a turn started or ended, a pause, or an approval. */ onChange(listener: () => void): () => void { - const detach = [durable.stateChanges(() => listener()), durable.approvals.onChange(() => listener())]; - return () => { for (const off of detach) off(); }; + listeners.add(listener); + return () => { listeners.delete(listener); }; + }, + close: () => { + for (const off of detach) off(); + listeners.clear(); + return live.close(); }, - close: () => live.close(), }; } diff --git a/packages/cli/tests/parity.test.mjs b/packages/cli/tests/parity.test.mjs index 1569414b67..0ffe4d4bc0 100644 --- a/packages/cli/tests/parity.test.mjs +++ b/packages/cli/tests/parity.test.mjs @@ -2472,9 +2472,10 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f const oldEntry = process.env.AIDEN_CLI_ENTRY; process.env.AIDEN_CLI_ENTRY = join(pkg, "dist/app/cli.js"); t.after(() => { if (oldEntry === undefined) delete process.env.AIDEN_CLI_ENTRY; else process.env.AIDEN_CLI_ENTRY = oldEntry; }); - let calls = 0, hold = false, scriptResult, scriptTools; + let calls = 0, hold = false, gate = null, scriptResult, scriptTools; const server = createServer(async (request, response) => { let body = ""; for await (const chunk of request) body += chunk; + if (gate) await gate.promise; const parsed = JSON.parse(body); const write = JSON.stringify(parsed.messages).includes("Write durable file") && !parsed.messages.some((message) => message.role === "tool"); const last = parsed.messages.at(-1); @@ -2537,6 +2538,7 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f assert.equal(remoteBots.botSessions.supportsAttachments, false); assert.equal(remoteBots.botSessions.supportsActivity, false); await remoteBots.botSessions.close(); + remoteBots.signals.close(); const routine = await host.routines.create({ botId: bot.id, name: "Read update", prompt: "Give a brief update", schedule: { kind: "daily", time: "12:00" }, timezone: "UTC" }); const routineRun = await scheduler.service.runNow(routine.id, { runId: "stable-routine-fire" }); assert.equal(routineRun.result, "success"); @@ -2581,8 +2583,28 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f forkSnapshot.messages.find((message) => message.role === "user").content = "caller mutated snapshot"; assert.equal((await callContext.loadChat()).messages.find((message) => message.role === "user").content, "Hello", "call snapshot cannot be mutated by another consumer"); + // A paired desktop's feed re-reads its rows on each change: a turn's end alone brings the row its reply. + const { signals: replySignals } = api.createCliRemoteBots(dir, "test-instance", host, daemon, {}, ledger, async () => {}); + const before = Date.parse((await replySignals.botSignals([{ id: bot.id }])).get(bot.id).lastReplyAt); + const seen = []; + const offReply = replySignals.onChange(() => { seen.push(replySignals.botSignals([{ id: bot.id }]).then((rows) => rows.get(bot.id))); }); + let release; + gate = { promise: new Promise((resolve) => { release = resolve; }) }; const writeTurn = await host.durable.runtime.send(bot.id, { text: "Write durable file", requestId: "durable-write-once" }); - assert.equal((await host.durable.runtime.awaitReply(bot.id, writeTurn.submissionId, new AbortController().signal)).kind, "completed"); + try { + await Promise.all(seen); + const whileRunning = seen.length; + gate = null; + release(); + assert.equal((await host.durable.runtime.awaitReply(bot.id, writeTurn.submissionId, new AbortController().signal)).kind, "completed"); + let settledRow; + for (let attempt = 0; attempt < 100 && !settledRow; attempt += 1) { + settledRow = (await Promise.all(seen.slice(whileRunning))).find((value) => value?.lastReplyAt && Date.parse(value.lastReplyAt) > before); + if (!settledRow) await new Promise((resolve) => setTimeout(resolve, 20)); + } + assert.ok(settledRow, "the finished turn alone reaches the host feed, with its reply"); + assert.equal(settledRow.preview, "Durable answer"); + } finally { gate = null; release(); offReply(); replySignals.close(); } assert.equal(readFileSync(join((await host.managedWorkspace.resolve(bot.id)).homePath, "durable.txt"), "utf8"), "Written by the durable Bot"); // Codemode runs in the bundle: the script's read is a nested call through the Bot's own checks. const scriptTurn = await host.durable.runtime.send(bot.id, { text: "Script durable file", requestId: "durable-script-once" }); From 175a7f6d035aba395ca1ea308da9378b5d6a7a1a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:32:06 +0000 Subject: [PATCH 04/10] Report a Bot run that ends while its live feed opens as settled A running notice whose feed opened after the run ended set the feed back to running and never reported the end, so the host feed missed the reply. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .../bot-runtime/live-projection.test.ts | 36 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 12 ++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index a3710520fb..dc763d640b 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -323,6 +323,42 @@ test("a routine turn shows as its label, and a [SILENT] answer hides the whole t } }); +test("a run that ends while its feed is still opening is reported settled, and never reads running again", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("Done already.")]); + let release: (() => void) | undefined; + let held = true; + const opened = new Promise((resolve) => (release = resolve)); + const settled: Array<{ botId: string; kind: string }> = []; + let service: BotSessionRuntime | undefined; + const live = await start(fauxModels, { + projection: { + // Opening the feed waits until the turn is over. + conversation: async (botId) => { + if (held) await opened; + return service!.conversation(botId); + }, + onRunSettled: (botId, state) => settled.push({ botId, kind: state.kind }), + }, + }); + service = live.service; + try { + const sent = await live.service.send("bot:a", { text: "Quick one", requestId: "desk-1" }); + const outcome = await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + assert.equal(outcome.kind, "completed"); + assert.deepEqual(settled, [], "nothing is reported before the feed opens"); + held = false; + release!(); + await waitFor(() => settled.length > 0, { what: "the settled run to be reported" }); + assert.deepEqual(settled, [{ botId: "bot:a", kind: "idle" }]); + const view = await live.projection.subscribe("bot:a", recorder().sink); + view.unsubscribe(); + assert.equal(view.snapshot.state.kind, "idle", "the stale running notice was not applied"); + assert.deepEqual(visibleText(view.snapshot).slice(-1), ["assistant:Done already."]); + } finally { + await live.close(); + } +}); + test("a failed reply is a typed failed turn, and Retry as a new submission answers after it", async () => { const failure = fauxAssistantMessage("", { stopReason: "error", errorMessage: "provider is down" }); const fauxModels = createFauxModels([failure, fauxAssistantMessage("Here it is.")]); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index b2a1ceef79..17f9637903 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1616,7 +1616,17 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro const wanted = state.kind === "running" || (subscribers.get(botId)?.size ?? 0) > 0; if (!wanted || state.kind === "unavailable") return; void openFeed(botId).then( - (opened) => enqueueWork(opened, async () => setState(opened, state)), + (opened) => + enqueueWork(opened, async () => { + // The feed read the state as it opened, after this notice: a run that + // ended while it opened is reported settled, never set running again. + if (state.kind === "running" && opened.state.kind !== "running" && !opened.runActive) { + deps.onRunSettled?.(opened.botId, opened.state); + void closeIfUnwatched(opened); + return; + } + setState(opened, state); + }), (error) => report(botId, error), ); }, From e9a3c9eb84ae09ff587a842fd56991aab117b909 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:42:16 +0000 Subject: [PATCH 05/10] Never apply a running notice over the state a Bot's live feed opened with The feed reads the state as it opens, after the notice, so a pause or interruption in between kept reading running; report it settled instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .../bot-runtime/live-projection.test.ts | 32 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 9 +++--- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index dc763d640b..6390650345 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -359,6 +359,38 @@ test("a run that ends while its feed is still opening is reported settled, and n } }); +test("a Bot paused while its feed is still opening reads paused, not running", async () => { + const fauxModels = createFauxModels([slowAnswer()], { tokensPerSecond: 20 }); + let release: (() => void) | undefined; + let held = true; + const opened = new Promise((resolve) => (release = resolve)); + const settled: string[] = []; + let service: BotSessionRuntime | undefined; + const live = await start(fauxModels, { + projection: { + conversation: async (botId) => { + if (held) await opened; + return service!.conversation(botId); + }, + onRunSettled: (_botId, state) => settled.push(state.kind), + }, + }); + service = live.service; + try { + await live.service.send("bot:a", { text: "Take your time", requestId: "desk-1" }); + assert.equal((await live.service.pause("bot:a", "mac")).kind, "paused"); + held = false; + release!(); + await waitFor(() => settled.length > 0, { what: "the paused run to be reported" }); + assert.deepEqual(settled, ["paused"]); + const view = await live.projection.subscribe("bot:a", recorder().sink); + view.unsubscribe(); + assert.equal(view.snapshot.state.kind, "paused", "the earlier running notice was not applied"); + } finally { + await live.close(); + } +}); + test("a failed reply is a typed failed turn, and Retry as a new submission answers after it", async () => { const failure = fauxAssistantMessage("", { stopReason: "error", errorMessage: "provider is down" }); const fauxModels = createFauxModels([failure, fauxAssistantMessage("Here it is.")]); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 17f9637903..5fef3fb165 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1618,14 +1618,13 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro void openFeed(botId).then( (opened) => enqueueWork(opened, async () => { - // The feed read the state as it opened, after this notice: a run that - // ended while it opened is reported settled, never set running again. - if (state.kind === "running" && opened.state.kind !== "running" && !opened.runActive) { + // The feed read the state as it opened, after this notice, so the + // notice is never applied over it. A run that ended (or paused, or + // was interrupted) while it opened is reported settled. + if (state.kind === "running" && opened.state.kind !== "running") { deps.onRunSettled?.(opened.botId, opened.state); void closeIfUnwatched(opened); - return; } - setState(opened, state); }), (error) => report(botId, error), ); From 6f71a426b1ce54fa5d7e2fee747e96abb7048662 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:58:18 +0000 Subject: [PATCH 06/10] Read a Bot's state again once its live feed opens A notice that arrives while the feed opens may be older or newer than the state it read, so the state is read again inside the feed queue. A feed whose conversation closed while it opened (a pause can do that) is no longer kept with its stale state, and a run that ended meanwhile is still reported settled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .../bot-runtime/live-projection.test.ts | 37 ++++++++++++++++ main/services/bot-runtime/live-projection.ts | 43 ++++++++++++++----- 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 6390650345..78011e7ef7 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -391,6 +391,43 @@ test("a Bot paused while its feed is still opening reads paused, not running", a } }); +test("a Bot paused after its opening feed read the state is still reported paused", async () => { + const fauxModels = createFauxModels([slowAnswer()], { tokensPerSecond: 20 }); + let release: (() => void) | undefined; + let held = true; + const planRead = new Promise((resolve) => (release = resolve)); + let reachedPlan: (() => void) | undefined; + const atPlan = new Promise((resolve) => (reachedPlan = resolve)); + const settled: string[] = []; + const live = await start(fauxModels, { + projection: { + // The plan is read after the state, so holding it holds the feed open past its state read. + plan: async () => { + if (held) { + reachedPlan!(); + await planRead; + } + return null; + }, + onRunSettled: (_botId, state) => settled.push(state.kind), + }, + }); + try { + await live.service.send("bot:a", { text: "Take your time", requestId: "desk-1" }); + await atPlan; + assert.equal((await live.service.pause("bot:a", "mac")).kind, "paused"); + held = false; + release!(); + await waitFor(() => settled.length > 0, { what: "the paused run to be reported" }); + assert.deepEqual(settled, ["paused"]); + const view = await live.projection.subscribe("bot:a", recorder().sink); + view.unsubscribe(); + assert.equal(view.snapshot.state.kind, "paused", "the feed shows the pause, not the running state read before it"); + } finally { + await live.close(); + } +}); + test("a failed reply is a typed failed turn, and Retry as a new submission answers after it", async () => { const failure = fauxAssistantMessage("", { stopReason: "error", errorMessage: "provider is down" }); const fauxModels = createFauxModels([failure, fauxAssistantMessage("Here it is.")]); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 5fef3fb165..ada1071410 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1471,12 +1471,21 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro else runStarts.ended(botId); feed.activity = computeActivity(feed); feed.queued = await queuedFor(feed, initial.docs); - feeds.set(botId, feed); - watch.start((value) => enqueueWork(feed, () => onFrame(feed, value.entries, value.docs))); - void watch.closed.then(() => { + const end = () => { feed.ended = true; if (feeds.get(botId) === feed) feeds.delete(botId); - }); + }; + feeds.set(botId, feed); + void watch.closed.then(end); + try { + watch.start((value) => enqueueWork(feed, () => onFrame(feed, value.entries, value.docs))); + } catch (error) { + // The conversation closed while the feed opened (a pause can): this feed + // never follows it, so it isn't kept with the state it read. + end(); + feed.cancel(); + throw error; + } return feed; })(); opening.set(botId, promise); @@ -1618,15 +1627,29 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro void openFeed(botId).then( (opened) => enqueueWork(opened, async () => { - // The feed read the state as it opened, after this notice, so the - // notice is never applied over it. A run that ended (or paused, or - // was interrupted) while it opened is reported settled. - if (state.kind === "running" && opened.state.kind !== "running") { - deps.onRunSettled?.(opened.botId, opened.state); + // A notice that arrived while the feed opened may be older or newer + // than the state it read, so neither is trusted: the state is read + // again now, after every notice so far. A run that ended (or paused, + // or was interrupted) while it opened is reported settled. + const latest = await deps.state(botId).catch(() => opened.state); + setState(opened, latest); + if (state.kind === "running" && latest.kind !== "running") { + deps.onRunSettled?.(opened.botId, latest); void closeIfUnwatched(opened); } }), - (error) => report(botId, error), + (error) => { + report(botId, error); + // A pause can stop the conversation's watch while the feed opens, so + // the feed never opens; a run that ended meanwhile is still reported. + if (state.kind !== "running") return; + void deps.state(botId).then( + (latest) => { + if (latest.kind !== "running") deps.onRunSettled?.(botId, latest); + }, + (stateError) => report(botId, stateError), + ); + }, ); }, From 450a2d7ea600ca9dcb3c8ccf1c3c06d03a20d207 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 09:12:16 +0000 Subject: [PATCH 07/10] Report each Bot run's end once The opening reconciliation and a run's last frame could both report the same run as settled. A feed now remembers that its run's end was reported and clears that when a new run starts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .../bot-runtime/live-projection.test.ts | 37 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 22 +++++++++-- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 78011e7ef7..c652a19965 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -359,6 +359,43 @@ test("a run that ends while its feed is still opening is reported settled, and n } }); +test("a run that ends after its opening feed read the state is reported settled once", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("Done already.")]); + let release: (() => void) | undefined; + let held = true; + const planRead = new Promise((resolve) => (release = resolve)); + let reachedPlan: (() => void) | undefined; + const atPlan = new Promise((resolve) => (reachedPlan = resolve)); + const settled: string[] = []; + const live = await start(fauxModels, { + projection: { + // The plan is read after the state and the transcript, so the run's last frame is still to come. + plan: async () => { + if (held) { + reachedPlan!(); + await planRead; + } + return null; + }, + onRunSettled: (_botId, state) => settled.push(state.kind), + }, + }); + try { + const sent = await live.service.send("bot:a", { text: "Quick one", requestId: "desk-1" }); + await atPlan; + const outcome = await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + assert.equal(outcome.kind, "completed"); + held = false; + release!(); + await waitFor(() => settled.length > 0, { what: "the settled run to be reported" }); + // Give a second report, if any, time to arrive. + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.deepEqual(settled, ["idle"], "one run, one report"); + } finally { + await live.close(); + } +}); + test("a Bot paused while its feed is still opening reads paused, not running", async () => { const fauxModels = createFauxModels([slowAnswer()], { tokensPerSecond: 20 }); let release: (() => void) | undefined; diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index ada1071410..59564e2bfb 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1128,6 +1128,11 @@ interface Feed { */ projectedFrom: readonly EntryRecord[] | undefined; runActive: boolean; + /** + * Whether the current run's end was already reported (`onRunSettled`), so a + * frame and the opening reconciliation don't both report it. A new run clears it. + */ + settled: boolean; /** Identity of the current run; a follow-up turn replaces the run without a gap. */ runKey: string | null; watch: ActiveConversationWatch; @@ -1383,6 +1388,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro return; } feed.runActive = runActive; + if (runActive) feed.settled = false; // The run's end is reported with its new state, so the line never flashes a phase after the reply. const state = await deps.state(feed.botId).catch(() => feed.state); setState(feed, state); @@ -1391,7 +1397,10 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro feed.stopping = false; feed.resuming = false; resumingBots.delete(feed.botId); - deps.onRunSettled?.(feed.botId, state); + if (!feed.settled) { + feed.settled = true; + deps.onRunSettled?.(feed.botId, state); + } void closeIfUnwatched(feed); } } @@ -1400,7 +1409,10 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro if (JSON.stringify(state) === JSON.stringify(feed.state)) return; const wasRunning = feed.state.kind === "running"; feed.state = state; - if (state.kind === "running" && !wasRunning) startRun(feed); + if (state.kind === "running" && !wasRunning) { + feed.settled = false; + startRun(feed); + } if (state.kind !== "running") { feed.stopping = false; feed.resuming = false; @@ -1460,6 +1472,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro frame: { entries: initial.entries, docs: initial.docs }, projectedFrom: projected.stable ? initial.entries : undefined, runActive: liveRunActive(initial.docs), + settled: false, runKey: liveRunKey(initial.docs), watch, cancel: () => cancel(new Error("Bot live feed closed.")), @@ -1633,7 +1646,10 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro // or was interrupted) while it opened is reported settled. const latest = await deps.state(botId).catch(() => opened.state); setState(opened, latest); - if (state.kind === "running" && latest.kind !== "running") { + // A run whose last frame is still to come is reported by that frame + // or here, whichever is first; a paused run's frame may never come. + if (state.kind === "running" && latest.kind !== "running" && !opened.settled) { + opened.settled = true; deps.onRunSettled?.(opened.botId, latest); void closeIfUnwatched(opened); } From 65b30802f630ad9eb1a5d36be0c73070807b1ddd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 09:26:28 +0000 Subject: [PATCH 08/10] Settle a failed Bot feed opening once for every notice that joined it Notices that join the same opening see the same error; the failure is now reported, and the run settled, once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- main/services/bot-runtime/live-projection.test.ts | 6 +++++- main/services/bot-runtime/live-projection.ts | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index c652a19965..a6d9623a39 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -452,11 +452,15 @@ test("a Bot paused after its opening feed read the state is still reported pause try { await live.service.send("bot:a", { text: "Take your time", requestId: "desk-1" }); await atPlan; + // A second running notice (a follow-up accepted mid-run) joins the same opening. + live.projection.notifyState("bot:a", await live.service.state("bot:a")); assert.equal((await live.service.pause("bot:a", "mac")).kind, "paused"); held = false; release!(); await waitFor(() => settled.length > 0, { what: "the paused run to be reported" }); - assert.deepEqual(settled, ["paused"]); + // Give a second report, if any, time to arrive. + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.deepEqual(settled, ["paused"], "one opening, one report"); const view = await live.projection.subscribe("bot:a", recorder().sink); view.unsubscribe(); assert.equal(view.snapshot.state.kind, "paused", "the feed shows the pause, not the running state read before it"); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 59564e2bfb..cf9802f0fe 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1193,6 +1193,8 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro const lastSeq = new Map(); const report = (botId: string, error: unknown) => deps.onError?.(botId, error); + /** Errors of feed openings already handled, so notices that joined one act on it once. */ + const failedOpenings = new WeakSet(); const classifyRetryMs = deps.classifyRetryMs ?? 1_000; function snapshotOf(feed: Feed): BotLiveSnapshot { @@ -1655,6 +1657,12 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro } }), (error) => { + // Every notice that joined the same opening sees the same error: + // the failed opening is reported, and settled, once. + if (typeof error === "object" && error !== null) { + if (failedOpenings.has(error)) return; + failedOpenings.add(error); + } report(botId, error); // A pause can stop the conversation's watch while the feed opens, so // the feed never opens; a run that ended meanwhile is still reported. From dcb2afbe62295c7e69b463fe885106f9d2b9539f Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 11:35:45 -0500 Subject: [PATCH 09/10] Settle a run for a running notice that joins a failed feed opening behind one that wasn't running, and close the parity test's Bot sessions --- .../bot-runtime/live-projection.test.ts | 73 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 25 ++++--- packages/cli/tests/parity.test.mjs | 8 +- 3 files changed, 93 insertions(+), 13 deletions(-) diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index a6d9623a39..326f35c880 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -7,6 +7,7 @@ import * as os from "node:os"; import * as path from "node:path"; import { after, test } from "node:test"; import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; +import type { WatchEnd } from "@earendil-works/chord/watch"; import { fauxAssistantMessage, fauxText, fauxThinking, fauxToolCall } from "@earendil-works/pi-ai/providers/faux"; import { applyBotLiveEvent, @@ -469,6 +470,78 @@ test("a Bot paused after its opening feed read the state is still reported pause } }); +test("a running notice that joins a failed opening behind a notice that wasn't running still reports its run settled", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("unused")]); + let endFirstWatch: (() => void) | undefined; + const firstWatchEnded = new Promise((resolve) => (endFirstWatch = () => resolve({ kind: "ended" }))); + let failing = false; + let failedOpens = 0; + let failOpening: (() => void) | undefined; + const openingFailed = new Promise((resolve) => (failOpening = resolve)); + const failure = new Error("the conversation closed while the feed opened"); + const settled: string[] = []; + let reports = 0; + let service: BotSessionRuntime | undefined; + const live = await start(fauxModels, { + // The test sends every state notice itself. + service: { onStateChange: () => undefined }, + projection: { + conversation: async (botId) => { + if (failing) { + failedOpens += 1; + await openingFailed; + throw failure; + } + // The first feed follows the real conversation until the test ends its watch. + const real = await service!.conversation(botId); + return new Proxy(real, { + get(target, property) { + if (property === "watch") { + return async (context: Parameters[0]) => { + const watch = await target.watch(context); + return new Proxy(watch, { + get(inner, key) { + if (key === "closed") return Promise.race([inner.closed, firstWatchEnded]); + const value = Reflect.get(inner, key, inner) as unknown; + return typeof value === "function" ? value.bind(inner) : value; + }, + }); + }; + } + const value = Reflect.get(target, property, target) as unknown; + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }, + onRunSettled: (_botId, state) => settled.push(state.kind), + onError: () => { + reports += 1; + }, + }, + }); + service = live.service; + try { + // A window keeps watching the Bot while its feed ends underneath it. + const watching = await live.projection.subscribe("bot:a", recorder().sink); + endFirstWatch!(); + await new Promise((resolve) => setTimeout(resolve, 20)); + // An idle notice reopens the feed for that window; a running notice joins the same opening. + failing = true; + live.projection.notifyState("bot:a", { kind: "idle" }); + live.projection.notifyState("bot:a", { kind: "running", submissionId: "sub-joined" }); + assert.equal(failedOpens, 1, "both notices share one opening"); + failOpening!(); + await waitFor(() => settled.length > 0, { what: "the joined running notice's run to be reported" }); + // Give a second report, if any, time to arrive. + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.deepEqual(settled, ["idle"], "the run the running notice named is reported settled, once"); + assert.equal(reports, 1, "the failed opening is reported once"); + watching.unsubscribe(); + } finally { + await live.close(); + } +}); + test("a failed reply is a typed failed turn, and Retry as a new submission answers after it", async () => { const failure = fauxAssistantMessage("", { stopReason: "error", errorMessage: "provider is down" }); const fauxModels = createFauxModels([failure, fauxAssistantMessage("Here it is.")]); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index cf9802f0fe..4f5a372317 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1193,8 +1193,12 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro const lastSeq = new Map(); const report = (botId: string, error: unknown) => deps.onError?.(botId, error); - /** Errors of feed openings already handled, so notices that joined one act on it once. */ - const failedOpenings = new WeakSet(); + /** + * Feed openings that failed, by their error (every notice that joined one sees + * the same error): reported once, and the run settled once for whichever + * joined notice was a running one, whatever order the notices came in. + */ + const failedOpenings = new WeakMap(); const classifyRetryMs = deps.classifyRetryMs ?? 1_000; function snapshotOf(feed: Feed): BotLiveSnapshot { @@ -1657,16 +1661,19 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro } }), (error) => { - // Every notice that joined the same opening sees the same error: - // the failed opening is reported, and settled, once. - if (typeof error === "object" && error !== null) { - if (failedOpenings.has(error)) return; - failedOpenings.add(error); + // Every notice that joined the same opening sees the same error: the + // failure is reported once, and a run is settled once if any of them + // was a running notice, even one that joined behind an idle or paused one. + let failed = typeof error === "object" && error !== null ? failedOpenings.get(error) : undefined; + if (!failed) { + failed = { settling: false }; + if (typeof error === "object" && error !== null) failedOpenings.set(error, failed); + report(botId, error); } - report(botId, error); // A pause can stop the conversation's watch while the feed opens, so // the feed never opens; a run that ended meanwhile is still reported. - if (state.kind !== "running") return; + if (state.kind !== "running" || failed.settling) return; + failed.settling = true; void deps.state(botId).then( (latest) => { if (latest.kind !== "running") deps.onRunSettled?.(botId, latest); diff --git a/packages/cli/tests/parity.test.mjs b/packages/cli/tests/parity.test.mjs index 0ffe4d4bc0..51deae4df7 100644 --- a/packages/cli/tests/parity.test.mjs +++ b/packages/cli/tests/parity.test.mjs @@ -2551,7 +2551,7 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f const sent = await host.durable.runtime.send(bot.id, { text: "Hello", requestId: "migration-first", attachments: [{ type: "image", mimeType: "image/png", data: imageData }] }); assert.deepEqual(await host.durable.runtime.awaitReply(bot.id, sent.submissionId, new AbortController().signal), { kind: "completed", text: "Durable answer" }); // A paired desktop's Bot row and a phone's Bots list read what this server's own Bot did, as from a Mac. - const { signals } = api.createCliRemoteBots(dir, "test-instance", host, daemon, {}, ledger, async () => {}); + const { signals, botSessions } = api.createCliRemoteBots(dir, "test-instance", host, daemon, {}, ledger, async () => {}); try { const row = (await signals.botSignals([{ id: bot.id }])).get(bot.id); assert.equal(row.preview, "Durable answer"); @@ -2571,7 +2571,7 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f await host.command(["unpause", bot.id]); assert.ok(changes > 0, "a pause reaches the host feed"); off(); - } finally { await signals.close(); } + } finally { await botSessions?.close(); await signals.close(); } const durableEntries = (await (await host.durable.runtime.conversation(bot.id)).context(api.BACKGROUND_CONTEXT)).entries; const callContext = api.cliDurableBotToolContext([...durableEntries].reverse(), { chatId: legacy.id, botId: bot.id }); const forkSnapshot = await callContext.loadChat(); @@ -2584,7 +2584,7 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f assert.equal((await callContext.loadChat()).messages.find((message) => message.role === "user").content, "Hello", "call snapshot cannot be mutated by another consumer"); // A paired desktop's feed re-reads its rows on each change: a turn's end alone brings the row its reply. - const { signals: replySignals } = api.createCliRemoteBots(dir, "test-instance", host, daemon, {}, ledger, async () => {}); + const { signals: replySignals, botSessions: replySessions } = api.createCliRemoteBots(dir, "test-instance", host, daemon, {}, ledger, async () => {}); const before = Date.parse((await replySignals.botSignals([{ id: bot.id }])).get(bot.id).lastReplyAt); const seen = []; const offReply = replySignals.onChange(() => { seen.push(replySignals.botSignals([{ id: bot.id }]).then((rows) => rows.get(bot.id))); }); @@ -2604,7 +2604,7 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f } assert.ok(settledRow, "the finished turn alone reaches the host feed, with its reply"); assert.equal(settledRow.preview, "Durable answer"); - } finally { gate = null; release(); offReply(); replySignals.close(); } + } finally { gate = null; release(); offReply(); await replySessions?.close(); await replySignals.close(); } assert.equal(readFileSync(join((await host.managedWorkspace.resolve(bot.id)).homePath, "durable.txt"), "utf8"), "Written by the durable Bot"); // Codemode runs in the bundle: the script's read is a nested call through the Bot's own checks. const scriptTurn = await host.durable.runtime.send(bot.id, { text: "Script durable file", requestId: "durable-script-once" }); From ff21e3b2c6b289f18deacfa38d95ac1c38ce5319 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:43:14 +0000 Subject: [PATCH 10/10] Check that aiden serve marks its host feed Bot rows summarized Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- packages/cli/tests/parity.test.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/cli/tests/parity.test.mjs b/packages/cli/tests/parity.test.mjs index 51deae4df7..b5fcf708c2 100644 --- a/packages/cli/tests/parity.test.mjs +++ b/packages/cli/tests/parity.test.mjs @@ -2556,6 +2556,7 @@ test("durable CLI Bot migration preserves history, dedupes across restart, and f const row = (await signals.botSignals([{ id: bot.id }])).get(bot.id); assert.equal(row.preview, "Durable answer"); assert.ok(Date.parse(row.lastReplyAt) > 0, JSON.stringify(row)); + assert.equal(row.summarized, true, "a paired Mac can tell this server reports every Bot's reply"); assert.equal(row.needsYou, undefined); assert.equal(row.failed, undefined); assert.deepEqual([...await signals.botNeedsYou([bot.id])], []);