From 86a6a1aefd07b2492e9900cb968fcc64822117e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 06:09:11 +0000 Subject: [PATCH 1/7] Show a paired Mac's Bot's last message, photo and unread dot Host feed Bot rows (Remote revision 66, provisional) carry a one-line preview and always come from the Bot list's cached summary, so every row has its last reply time. A new peer binary operation reads a Bot's photo avatar. The Bots sidebar shows the preview under the name, the photo, and a dot for a reply this Mac hasn't shown yet; the remote chat title shows the photo too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .memory/bot-chat-activity.md | 5 + .memory/inbox-sidebar.md | 1 + .../AidenOnTheGo/AidenBackgroundJobsTest.kt | 2 +- .../AidenBotAccessRequestsContractTest.kt | 2 +- .../AidenOnTheGo/AidenBotPlanContractTest.kt | 2 +- .../AidenOnTheGo/AidenRemoteClientTest.kt | 2 +- docs/aiden-on-the-go-remote-access.md | 2 +- docs/aiden-remote-api-v1.md | 12 +- docs/plans/inbox-sidebar-plan.md | 1 + .../AidenBackgroundJobsTests.swift | 2 +- ios/AidenOnTheGoTests/AidenBotPlanTests.swift | 2 +- .../AidenBotSessionTests.swift | 2 +- .../AidenRemotePhase0Tests.swift | 4 +- main/handlers/bot-live.test.ts | 1 - .../services/aiden-remote-host-feed-source.ts | 2 +- main/services/aiden-remote-host-feed.test.ts | 20 +++ main/services/aiden-remote-host-feed.ts | 19 ++- main/services/aiden-remote-protocol.test.ts | 45 +++++- main/services/aiden-remote-protocol.ts | 45 +++++- main/services/aiden-remote-service-main.ts | 7 +- .../bot-runtime/live-projection.test.ts | 12 +- main/services/bot-runtime/live-projection.ts | 12 -- main/services/peer-operation.test.ts | 9 +- main/services/peer-operation.ts | 5 +- main/services/peer-response.ts | 1 + package.json | 2 +- .../aiden-remote/v1/fixtures/contract.json | 39 ++++- protocol/aiden-remote/v1/openapi.json | 110 ++++++++++++- renderer/components/bot-avatar.tsx | 10 +- renderer/components/bot-unread-dot.tsx | 6 + renderer/components/remote-bots-section.tsx | 153 ++++++++++++------ renderer/lib/hosts/new-chat-targets.ts | 18 +++ renderer/lib/hosts/remote-bot-photo-asset.ts | 20 +++ renderer/lib/hosts/remote-images.ts | 34 +++- renderer/lib/remote-bot-seen.test.ts | 35 ++++ renderer/lib/remote-bot-seen.ts | 122 ++++++++++++++ renderer/main/bots/bot-sidebar.test.tsx | 76 ++++++++- renderer/main/bots/bot-sidebar.tsx | 11 +- renderer/main/remote-bot-chat-view.tsx | 13 +- renderer/main/remote-new-chat-view.test.tsx | 23 ++- renderer/shared/chat-pending-attention.ts | 14 +- renderer/shared/peer-operation.ts | 6 +- 42 files changed, 766 insertions(+), 143 deletions(-) create mode 100644 renderer/components/bot-unread-dot.tsx create mode 100644 renderer/lib/hosts/remote-bot-photo-asset.ts create mode 100644 renderer/lib/remote-bot-seen.test.ts create mode 100644 renderer/lib/remote-bot-seen.ts diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index 7f9014a642..f8bf89c9b4 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -101,3 +101,8 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev - Still open: a manual VoiceOver/TalkBack pass and an end-to-end run against a real Mac on this branch. - Overlapping Stops where one fails briefly clear "Stopping" (cosmetic). No Remove for queued messages on phones (no Remote withdraw route). Chat activity picks have no durable queue. +### Bots across Macs (2026-11-24) +- PR 1 (#895, desktop only): paired Mac's Bot rows show the feed's avatar, Needs you over Thinking over stop status, never the description; `ChatSidebar` owns `usePeerHostSidebar` so feeds stay live on the Bots page; remote Bot chat only treats 404/403 as gone. +- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`), compared only against the host's own `lastReplyAt`. +- Still to come: PR 3 (plan, access-request and memory cards in remote Bot chats, load older), PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). + diff --git a/.memory/inbox-sidebar.md b/.memory/inbox-sidebar.md index a0b3078342..4d60d6cce2 100644 --- a/.memory/inbox-sidebar.md +++ b/.memory/inbox-sidebar.md @@ -276,6 +276,7 @@ Related: [[chat-row-states]], [[sidebar-chat-row-context]], [[multi-host-control ### Follow-up review: admitted details, transcript-free feeds and phone inverses (2026-11-02) - iOS local summary edits retain the generation of a whole detail/view admission across later triage/read/activity writes. A stale refresh cannot replace its newer title/reply/read state; a newer page reply still wins. Both completion orders are exercised in real Home/cache tests. - Host-feed Bot signals use `BotLiveProjection.inboxSignals`: runtime state/attention and an already-open feed's reply timestamp only. Closed feeds never open conversation entries or context. The full Bot list summary still has its separate preview cache. Native clients do not consume the desktop host feed. + - Superseded by Remote revision 66 (2026-11-24, Bots across Macs PR 2): `inboxSignals` is gone and host-feed Bot rows come from `BotLiveProjection.summary`, the same cached summary the Bot list uses. A closed Bot's transcript is read again only when its newest entry changes, and every row now carries `lastReplyAt` plus a one-line `preview` (140 characters). See `.memory/bot-chat-activity.md`. - Both phones offer Mark not done and Unsnooze as persistent swipe/accessibility actions on searched held rows, under the existing capability and active-run guards. Undo of Mark not done restores the historical Done timestamp using guarded `restoreDoneAt`, matching desktop. Offer/binding, request-body, optimistic placement and Android rendered-action coverage exercise the behavior. - Validation: iOS 33 focused simulator tests pass; disabling the whole-admission reconciliation reproduces stale title in the new Home regression. Android 54 focused JVM tests and all 8 rendered Inbox tests pass on API 36.1; the inverse-action screenshot was inspected. The existing aged-Undo UI test now posts after fixture composition, so startup cannot consume its remaining second. Bot projection/host feed 75 tests, handler/peer Inbox 7 tests, TypeScript, scoped ESLint and CLI build pass. diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBackgroundJobsTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBackgroundJobsTest.kt index 2ef73d5a1e..9132edec1c 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBackgroundJobsTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBackgroundJobsTest.kt @@ -156,7 +156,7 @@ class AidenBackgroundJobsTest { * person stopped, or a reason this version does not know, reads as plain Stopped. */ @Test fun aJobStoppedAfterTheChatWentQuietSaysSo() { - assertEquals(65, contract.getValue("contractRevision").jsonPrimitive.int) + assertEquals(66, contract.getValue("contractRevision").jsonPrimitive.int) val list = contract.getValue("backgroundJobsChatSettled").jsonObject.getValue("list") val decoded = AidenBackgroundJobs.decode(list.toString()) val labels = decoded.jobs.associate { it.id to AidenBackgroundJobCopy.status(it, start) } diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotAccessRequestsContractTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotAccessRequestsContractTest.kt index ee468ccb68..e242325aa1 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotAccessRequestsContractTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotAccessRequestsContractTest.kt @@ -30,7 +30,7 @@ class AidenBotAccessRequestsContractTest { private fun frame(element: JsonElement) = AidenBotSessionEventStream.decodeFrame(element.toString().toByteArray(), "bot_fixture_01") @Test fun canonicalCardsSessionFramesIssuesAndLegacySettlement() { - assertEquals(65, root.getValue("contractRevision").jsonPrimitive.int) + assertEquals(66, root.getValue("contractRevision").jsonPrimitive.int) assertEquals("bot:access-requests", fixture.getValue("capability").jsonPrimitive.content) val folder = AidenBotAccessRequest.parse(fixture.getValue("folder")) val mac = AidenBotAccessRequest.parse(fixture.getValue("wholeMac")) diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotPlanContractTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotPlanContractTest.kt index 749fbac328..ff5873c9c2 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotPlanContractTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBotPlanContractTest.kt @@ -47,7 +47,7 @@ class AidenBotPlanContractTest { assertNull(plan.items.first().used); assertNull(plan.items.first().max) } @Test fun canonicalSnapshotAndOrderedPlanFramesDecode() { - assertEquals(65, root.getValue("contractRevision").jsonPrimitive.int) + assertEquals(66, root.getValue("contractRevision").jsonPrimitive.int) val session = wire.decodeFromJsonElement(AidenBotSession.serializer(), fixture.getValue("session")) assertEquals(0L, session.seq) assertHostFolderReview(requireNotNull(session.plan)) diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenRemoteClientTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenRemoteClientTest.kt index 3ef1037ebf..50c42e8612 100644 --- a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenRemoteClientTest.kt +++ b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenRemoteClientTest.kt @@ -1618,7 +1618,7 @@ class AidenRemoteClientTest { @Test fun streamSnapshotReasonsDecodeSharedFixtureRejectInvalidReasonsAndNegotiateSolo() = runBlocking { val fixture = contractFixture() - assertEquals(65, fixture.getValue("contractRevision").jsonPrimitive.int) + assertEquals(66, fixture.getValue("contractRevision").jsonPrimitive.int) val section = fixture.getValue("streamRecovery").jsonObject assertEquals("stream:snapshot-reasons", section.getValue("capability").jsonPrimitive.content) diff --git a/docs/aiden-on-the-go-remote-access.md b/docs/aiden-on-the-go-remote-access.md index 694415fef0..9fba82eaf9 100644 --- a/docs/aiden-on-the-go-remote-access.md +++ b/docs/aiden-on-the-go-remote-access.md @@ -69,7 +69,7 @@ Pairing a computer gives it full control of this computer's chats: it can read t - **Visuals.** A visual the other computer pictured shows as that picture. A native visual it did not picture (any `render_ui` visual from `aiden serve`) shows as its text, line by line, where its tool call ran, with **Copy as text** and nothing inside to tap or change. An HTML visual (`render_artifact`) the other computer did not picture, for example because `aiden serve` found no Chrome, shows nothing here; the reply's text still says what it held. - **Not here.** Read-aloud is not offered for a remote chat. - **New chats.** On a new chat, choose the computer in the composer's machine picker, then one of its workspaces and models. Attachments upload to that computer. Pictures in a format the other computer does not take (WebP, GIF, BMP) are converted first, to PNG (or JPEG when that is what fits), and shrunk step by step until each is within 8 MB and the message's attachments together are within 16 MB. An animated GIF sends its first frame. HEIC photos can't be sent to another computer yet: the composer asks you to export one as a JPEG first. A picture this Mac cannot open is not sent either, and the composer says to save it as a PNG or JPEG. When the other computer runs contract revision 50 or newer, pictures go as their own bytes instead of base64 text, about a quarter less to send. -- **Bots.** Paired computers' Bots appear in the Bots area below this Mac's own, under "On ", with the avatar shape and colour they have there (a custom photo still shows the stock Bot icon). A row stays current on any page, including the Bots pages. Like this Mac's own rows, it shows **Needs you** and "Waiting for you" while the Bot waits on an approval, question, hand-off or issue there, "Thinking…" while a turn runs (only while that computer is online), and otherwise why it stopped (Paused, Interrupted, Needs an AI model). A Bot's description is never shown as its line; search still matches it. Opening one row leaves the others clickable. The open chat's title shows the Bot's avatar. A chat that loses its connection reconnects on its own; it says the Bot is gone only when that computer answers that the Bot was deleted or this Mac may no longer read it, and a message sent while it reconnects shows as soon as that computer has it. Opening one shows the same single conversation its own computer, phones and Telegram show: the Bot runs there, and this Mac sends messages, Stop, Resume, Dismiss, question answers and tool approvals to it. A tool that only its own computer may allow (Computer Use) can only be denied from here. Connect cards ask the Bot's computer to finish the connection there. When the app is already connected on that computer but the Bot's Custom access leaves it out, the card still reads **Finish on **, and that opens the Bot's chat there, where its card's **Connect** adds the app to that Bot. Phones work the same way with **Finish on your Mac**. If that computer runs an older Aiden, update it; an older Mac sending to a newer computer's Bot is told to update. When the Bot's computer offers hand-offs (contract revision 37), a step the Bot hands back ("Your turn: …") can be answered from here too, in two steps: **Take control** first (it opens the page the step names, if any), then **I'm done** (with a note typed in the composer if you like), **Skip**, or **Open again** for that page. A step on the Bot's own screen over there puts **Finish on ** first, which brings it forward on that computer, then offers **Skip** and **I'm done**. A sign-in in the Bot's own browser there also starts with **Finish on **; it is answered on that computer, so here it then offers **Skip** alone. Images the Bot shares appear in its chat as pictures, read from the Bot's computer while its chat is connected (contract revision 45). The chat's **···** menu offers **Pause Bot** and **Resume Bot**, and a paused Bot shows a Resume card and holds the composer until it is resumed. Custom Bots can also ask for a folder or temporary whole-Mac file access. Current iOS and Android clients can answer those cards. A Mac viewing a paired computer’s Bot sees a notice to answer on that computer; it does not grant access itself. See [Bot access requests](bot-access-requests.md). The Assistant stays on its own computer. +- **Bots.** Paired computers' Bots appear in the Bots area below this Mac's own, under "On ", with the avatar they have there: its shape and colour, or its photo. A row stays current on any page, including the Bots pages. Like this Mac's own rows, it shows **Needs you** and "Waiting for you" while the Bot waits on an approval, question, hand-off or issue there, "Thinking…" while a turn runs (only while that computer is online), otherwise why it stopped (Paused, Interrupted, Needs an AI model), and otherwise its last message. A new reply since the Bot's chat was last open on this Mac shows an unread dot. The last message and the dot need that computer on contract revision 66; with an older one the line stays empty. A Bot's description is never shown as its line; search still matches it. Opening one row leaves the others clickable. The open chat's title shows the Bot's avatar or photo. A chat that loses its connection reconnects on its own; it says the Bot is gone only when that computer answers that the Bot was deleted or this Mac may no longer read it, and a message sent while it reconnects shows as soon as that computer has it. Opening one shows the same single conversation its own computer, phones and Telegram show: the Bot runs there, and this Mac sends messages, Stop, Resume, Dismiss, question answers and tool approvals to it. A tool that only its own computer may allow (Computer Use) can only be denied from here. Connect cards ask the Bot's computer to finish the connection there. When the app is already connected on that computer but the Bot's Custom access leaves it out, the card still reads **Finish on **, and that opens the Bot's chat there, where its card's **Connect** adds the app to that Bot. Phones work the same way with **Finish on your Mac**. If that computer runs an older Aiden, update it; an older Mac sending to a newer computer's Bot is told to update. When the Bot's computer offers hand-offs (contract revision 37), a step the Bot hands back ("Your turn: …") can be answered from here too, in two steps: **Take control** first (it opens the page the step names, if any), then **I'm done** (with a note typed in the composer if you like), **Skip**, or **Open again** for that page. A step on the Bot's own screen over there puts **Finish on ** first, which brings it forward on that computer, then offers **Skip** and **I'm done**. A sign-in in the Bot's own browser there also starts with **Finish on **; it is answered on that computer, so here it then offers **Skip** alone. Images the Bot shares appear in its chat as pictures, read from the Bot's computer while its chat is connected (contract revision 45). The chat's **···** menu offers **Pause Bot** and **Resume Bot**, and a paused Bot shows a Resume card and holds the composer until it is resumed. Custom Bots can also ask for a folder or temporary whole-Mac file access. Current iOS and Android clients can answer those cards. A Mac viewing a paired computer’s Bot sees a notice to answer on that computer; it does not grant access itself. See [Bot access requests](bot-access-requests.md). The Assistant stays on its own computer. - **Not available remotely.** Terminal, the Environment browser, computer use and open-in-editor work only on the computer you are sitting at. ### Offline and identity changes diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 4ace8ac552..d14ee42e46 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1127,7 +1127,7 @@ A desktop that wrote triage keeps its own answer until the host reports a `triag - A detached or interrupted local prompt, which only the host's own window can retry, does not affect the bucket. - A client ignores a bucket without a sort time, a sort time without a bucket, or a value it doesn't know, and places the row itself. The desktop parser drops such a pair, including a malformed `inboxSortAt`, and reads the rest of the row. -**Host feed.** `run.state` may carry `attentionSummary`: the waiting approval's or question's one-line ask, whitespace collapsed, trimmed and at most 200 characters (cut with "…"). Only devices holding `runs:observe` receive it, and only while `state` is `needs_approval` or `needs_input`; other devices receive the same event without it, including on replay. A snapshot carries no runs, so right after a `runs:observe` device's snapshot the host sends that device a `run.state` for each run still waiting, with its `attentionSummary`; a run that was already waiting when the device connected still shows its ask. Those events take sequences that every other device skips, like the Bot-only entries a device without `bot:read` never sees. They share the one host journal, so each pass is capped at half its retention (half of 1,000 events and of 8 MiB): one observer's resnapshot never expires a cursor another device took at the same moment, but a burst of reconnecting observers with many waiting runs uses up retention faster, and a device whose cursor ages out gets a fresh snapshot as usual. A client drops a malformed one and keeps the event. Bot rows (`snapshot.bots`, `bot.upsert`) may carry `needsYou: true` (an approval, a question, a hand-off or an open issue waits on the person), `failed: true` (the Bot's last turn was cut short or its model cannot be used) and `lastReplyAt` (when its newest reply with visible text arrived, only while a live feed already holds its transcript). State and attention read runtime signals; building the host feed never opens a Bot transcript. Each field is absent unless it holds. +**Host feed.** `run.state` may carry `attentionSummary`: the waiting approval's or question's one-line ask, whitespace collapsed, trimmed and at most 200 characters (cut with "…"). Only devices holding `runs:observe` receive it, and only while `state` is `needs_approval` or `needs_input`; other devices receive the same event without it, including on replay. A snapshot carries no runs, so right after a `runs:observe` device's snapshot the host sends that device a `run.state` for each run still waiting, with its `attentionSummary`; a run that was already waiting when the device connected still shows its ask. Those events take sequences that every other device skips, like the Bot-only entries a device without `bot:read` never sees. They share the one host journal, so each pass is capped at half its retention (half of 1,000 events and of 8 MiB): one observer's resnapshot never expires a cursor another device took at the same moment, but a burst of reconnecting observers with many waiting runs uses up retention faster, and a device whose cursor ages out gets a fresh snapshot as usual. A client drops a malformed one and keeps the event. Bot rows (`snapshot.bots`, `bot.upsert`) may carry `needsYou: true` (an approval, a question, a hand-off or an open issue waits on the person), `failed: true` (the Bot's last turn was cut short or its model cannot be used) and `lastReplyAt` (when its newest reply with visible text arrived). Before revision 66 a host sent `lastReplyAt` only while a live feed already held the Bot's transcript; since revision 66 it sends it for every Bot, with `preview` (see "Bot row previews, revision 66"). Each field is absent unless it holds. **Clients.** A paired desktop's Inbox lists a host's chats with these times and that host's Pin, Done and Snooze, and lists the host's Bots that need you, failed, or are open. It places them with its own rules from those signals and does not read `inboxBucket`, which is for clients without the placement code (phones, from Phase 3b). Aiden On The Go for iOS (from Phase 3b) offers an Inbox (Beta) sidebar view, chosen per device, that places each row in the host's `inboxBucket` ordered by `inboxSortAt`. It rechecks three things on the phone's own clock: the chat open on the phone stays out of Updates and the failed Needs you tier, a `snoozed` row past its `snoozedUntil` shows where it would be awake, and an Earlier row older than seven days drops out. A row without a usable pair (an older host, an unknown bucket, a sort time alone or a malformed value) is placed by the phone's port of the desktop rules from the same signals, and the rest of the summary reads as before. Swipe actions write through the host: Mark read with `chat-read-state-v1`, and Done and Snooze with `chat-triage-v1` and `chat:write`, sent as `POST /chats/{chatId}/triage` with an `Idempotency-Key` and the row's `triageRevision` as `ifRevision`. A swipe's `409 revision_conflict` whose `details.currentRevision` names the host's revision is sent once more from that revision under a new `Idempotency-Key`; a write that lands on that retry shows no confirmation or Undo (the desktop never retries), and a second conflict, or one without it, puts the row back and reloads the list. Undo is never retried: its `ifRevision` is the revision its own swipe's write left, kept with the confirmation, not the row's current `triageRevision` (a list reload may have brought in a newer one), so a conflict means another device changed the chat since. The phone puts the row back, reloads the list and says "That chat changed since, so Undo left it as it is.", as the desktop does. Mark read is offered on any unread row when the host lists `chat-read-state-v1`. Done and Snooze are offered only on a row that is not waiting on approval or input and not running, with Mark not done or Unsnooze instead when search finds a row that already holds it (a newer reply ends a Done hold), once the host lists `chat-triage-v1` (Macs and `aiden serve` from this revision) and grants `chat:write`; an older host gets Mark read only. As on the desktop, Done or Snooze on unseen failed output (not the chat open on the phone) also marks it read, so without `chat-read-state-v1` neither is offered on that row. The row moves at once; a refused write puts back only the fields it changed that still hold its value, and Undo writes back what the row held before (an earlier snooze still running, else a wake; Done only if it held Done, restoring its original timestamp under the Undo revision guard so newer replies still wake it). A refusal never brings back the unread dot of a chat viewed while the write was out, and the read marker sent with Done or Snooze goes to the host the write went to, even after a switch. A landed write drops the row's `inboxBucket` and `inboxSortAt` until the next list, so the phone places it from its new signals. Aiden On The Go for Android (from Phase 3b) offers the same Inbox (Beta) view with the same rechecks, local fallback and writes: each field is decoded on its own, so a malformed one, an unknown bucket or a sort time alone drops only that field or the pair and keeps the row, and the Mark read, Done and Snooze swipes are also custom TalkBack actions. @@ -1494,3 +1494,13 @@ Revision 65 was claimed on 2026-11-18, when `main` was at 64. The host keeps it **Clients.** Aiden On The Go for iOS and Android negotiate `stream:snapshot-reasons` alone when offered, handle `snapshot` before generic sequence-gap detection so a recovery boundary triggers one authoritative transcript read instead of two, drop buffered/revealed live text and reasoning on both Workspace and Bot chats when any `snapshot` arrives, and latch gap-recovery replay on `reason: "gap"` (and conservatively on legacy reason-less snapshots) so replayed `text_delta`, `reasoning_delta` and historical `reset` frames never duplicate an answer already present in the fetched transcript while terminal settlement still completes cleanly without resending the turn. A contiguous live `snapshot` with `reason: "reset"` clears the stale draft and continues streaming the replacement reply normally. **Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` holds `streamRecovery`: `capability`, `gapEvents`, `legacyGapSnapshot` and `resetEvents`. + +## Bot row previews, revision 66 (provisional) + +Revision 66 is provisional: it was written when `main` was at 65, and the host keeps it in one constant (`AIDEN_REMOTE_BOT_FEED_PREVIEW_CONTRACT_REVISION`), so claiming the next free number at merge changes only that constant. It needs no capability or feature token. + +**Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads; for a Bot whose chat is closed the host keeps that summary in memory and reads the Bot's transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. + +**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. + +**Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt` and `preview`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou` and `failed` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). diff --git a/docs/plans/inbox-sidebar-plan.md b/docs/plans/inbox-sidebar-plan.md index c68d3d455f..acf3f43fd7 100644 --- a/docs/plans/inbox-sidebar-plan.md +++ b/docs/plans/inbox-sidebar-plan.md @@ -537,5 +537,6 @@ Inbox reads carry the displayed reply ID, including reads sent after Done and Sn - An iOS detail/view admission keeps its whole-row generation across a later triage edit, so an older in-flight refresh cannot erase the viewed reply or restore its unread marker. A genuinely newer page reply still wins. - Phone search offers Mark not done and Unsnooze on held rows through the same swipe and accessibility actions. Undo restores the original Done timestamp with its revision guard. - Host-feed Bot attention/state reads remain transcript-free; reply times come only from an already-open live feed, never by opening a closed conversation. + - Update (2026-11-24, Remote revision 66): host-feed Bot rows now come from the Bot list's cached summary, so each row carries its last reply time and a one-line preview. A closed Bot's transcript is re-read only when its newest entry changes. See `docs/aiden-remote-api-v1.md`, "Bot row previews". - Detail-versus-page precedence uses the same identity-aware reply boundary as Mark read: two different reply IDs at the same millisecond do not let an admitted read row replace the incoming unseen reply. Native refresh/cache tests cover tied IDs, strictly newer pages and stale pages. diff --git a/ios/AidenOnTheGoTests/AidenBackgroundJobsTests.swift b/ios/AidenOnTheGoTests/AidenBackgroundJobsTests.swift index aa735bffac..515be08a3b 100644 --- a/ios/AidenOnTheGoTests/AidenBackgroundJobsTests.swift +++ b/ios/AidenOnTheGoTests/AidenBackgroundJobsTests.swift @@ -57,7 +57,7 @@ final class AidenBackgroundJobsTests: XCTestCase { func testAJobStoppedAfterTheChatWentQuietSaysSo() throws { let fixtureURL = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "contract", withExtension: "json")) let root = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(contentsOf: fixtureURL)) as? [String: Any]) - XCTAssertEqual(root["contractRevision"] as? Int, 65) + XCTAssertEqual(root["contractRevision"] as? Int, 66) let section = try XCTUnwrap(root["backgroundJobsChatSettled"] as? [String: Any]) let data = try JSONSerialization.data(withJSONObject: try XCTUnwrap(section["list"])) let list = try AidenRemoteJSONDecoder.decode(AidenBackgroundJobs.self, from: data) diff --git a/ios/AidenOnTheGoTests/AidenBotPlanTests.swift b/ios/AidenOnTheGoTests/AidenBotPlanTests.swift index 9b5081565a..9705c78469 100644 --- a/ios/AidenOnTheGoTests/AidenBotPlanTests.swift +++ b/ios/AidenOnTheGoTests/AidenBotPlanTests.swift @@ -7,7 +7,7 @@ final class AidenBotPlanTests: XCTestCase { func section() throws -> [String: Any] { let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "contract", withExtension: "json")) let root = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) - XCTAssertEqual(root["contractRevision"] as? Int, 65) + XCTAssertEqual(root["contractRevision"] as? Int, 66) return try XCTUnwrap(root["botPlans"] as? [String: Any]) } func decode(_ type: T.Type, _ value: Any) throws -> T { diff --git a/ios/AidenOnTheGoTests/AidenBotSessionTests.swift b/ios/AidenOnTheGoTests/AidenBotSessionTests.swift index af05348780..b672f6dfd1 100644 --- a/ios/AidenOnTheGoTests/AidenBotSessionTests.swift +++ b/ios/AidenOnTheGoTests/AidenBotSessionTests.swift @@ -5895,7 +5895,7 @@ final class AidenBotAccessRequestsTests: XCTestCase { private func section() throws -> [String: Any] { let url = try XCTUnwrap(Bundle(for: Self.self).url(forResource: "contract", withExtension: "json")) let root = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) - XCTAssertEqual(root["contractRevision"] as? Int, 65) + XCTAssertEqual(root["contractRevision"] as? Int, 66) return try XCTUnwrap(root["botAccessRequests"] as? [String: Any]) } private func decode(_ type: T.Type, _ object: Any) throws -> T { diff --git a/ios/AidenOnTheGoTests/AidenRemotePhase0Tests.swift b/ios/AidenOnTheGoTests/AidenRemotePhase0Tests.swift index d88de59e3a..fa6fef1bed 100644 --- a/ios/AidenOnTheGoTests/AidenRemotePhase0Tests.swift +++ b/ios/AidenOnTheGoTests/AidenRemotePhase0Tests.swift @@ -171,7 +171,7 @@ final class AidenRemotePhase0Tests: XCTestCase { from: data ) - XCTAssertEqual(fixture.contractRevision, 65) + XCTAssertEqual(fixture.contractRevision, 66) XCTAssertEqual(fixture.streamRecovery?.capability, .streamSnapshotReasons) XCTAssertEqual(fixture.streamRecovery?.gapEvents.first?.payload?.reason, .gap) XCTAssertNil(fixture.streamRecovery?.legacyGapSnapshot.payload?.reason) @@ -2017,7 +2017,7 @@ final class AidenRemotePhase0Tests: XCTestCase { let url = try XCTUnwrap(sharedContractFixtureURL) let data = try Data(contentsOf: url) let fixture = try AidenRemoteJSONDecoder.decode(AidenRemoteContractFixture.self, from: data) - XCTAssertEqual(fixture.contractRevision, 65) + XCTAssertEqual(fixture.contractRevision, 66) let recovery = try XCTUnwrap(fixture.streamRecovery) XCTAssertEqual(recovery.capability, .streamSnapshotReasons) XCTAssertEqual(recovery.gapEvents.map(\.sequence), [4097, 4098, 4099]) diff --git a/main/handlers/bot-live.test.ts b/main/handlers/bot-live.test.ts index 2fde5127fd..da11b8ff82 100644 --- a/main/handlers/bot-live.test.ts +++ b/main/handlers/bot-live.test.ts @@ -58,7 +58,6 @@ function fakeProjection() { cancelStopping: () => undefined, refreshActivity: async () => undefined, needsYou: async () => true, - inboxSignals: async () => ({ state: { kind: "idle" }, needsYou: true, lastReplyAt: null }), summary: async (botId) => ({ botId, preview: "hi", diff --git a/main/services/aiden-remote-host-feed-source.ts b/main/services/aiden-remote-host-feed-source.ts index 3cb58dff4e..dba82adeef 100644 --- a/main/services/aiden-remote-host-feed-source.ts +++ b/main/services/aiden-remote-host-feed-source.ts @@ -1,4 +1,4 @@ -// The `/host/events` feed's one transcript-free read, shared by the desktop +// The `/host/events` feed's one read (no chat transcripts), shared by the desktop // host and `aiden serve`: chat summaries, workspaces (with their cached // repository identity) and Bot rows in both audience shapes. Each host passes // what it owns; a host without live Bot summaries passes no `botSignals`. diff --git a/main/services/aiden-remote-host-feed.test.ts b/main/services/aiden-remote-host-feed.test.ts index 76f51d8ab1..77de2c239d 100644 --- a/main/services/aiden-remote-host-feed.test.ts +++ b/main/services/aiden-remote-host-feed.test.ts @@ -734,3 +734,23 @@ test("a Bot row's Inbox signals hold only what its live summary says", () => { assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: -1 }), {}, "a negative time is unknown"); assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: 1.5 }), {}, "a fractional time is unknown"); }); + +test("a Bot row's preview is the host's own row line, as one plain line a paired Mac can trust", async () => { + const { parseAidenRemoteHostFeedBot } = await import("./aiden-remote-protocol.js"); + const idle = { state: { kind: "idle" } as BotSessionState, needsYou: false, lastReplyAt: null as number | null }; + assert.deepEqual(hostFeedBotSignals({ ...idle, preview: null }), {}, "no preview, no key"); + assert.deepEqual(hostFeedBotSignals({ ...idle, preview: " \n " }), {}, "a blank preview sends no key"); + assert.equal(hostFeedBotSignals({ ...idle, preview: "Release moved\nto Friday" }).preview, "Release moved to Friday"); + const long = hostFeedBotSignals({ ...idle, preview: `${"word ".repeat(60)}\u202Eend` }).preview!; + assert.equal(Array.from(long).length, 140); + assert.ok(long.endsWith("…")); + // Whatever the transcript held, the row it makes passes the contract's own check. + const row = { + id: "bot_1", name: "Scout", purpose: "", health: "ready", revision: "r1", + avatar: { semantic: { version: 1, shape: "orb", color: "rose" } }, + createdAt: "2026-11-01T00:00:00.000Z", updatedAt: "2026-11-01T00:00:00.000Z", + }; + for (const preview of ["\u0000\u0007bell", "tab\there", `${"😀".repeat(200)}`, "\u2028para\u2029graph", "\u200Bzero width"]) { + assert.doesNotThrow(() => parseAidenRemoteHostFeedBot({ ...row, ...hostFeedBotSignals({ ...idle, preview }) }), JSON.stringify(preview)); + } +}); diff --git a/main/services/aiden-remote-host-feed.ts b/main/services/aiden-remote-host-feed.ts index c2927634d5..34db5c16b6 100644 --- a/main/services/aiden-remote-host-feed.ts +++ b/main/services/aiden-remote-host-feed.ts @@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto"; import { AIDEN_REMOTE_HOST_FEED_MAX_BYTES, AIDEN_REMOTE_HOST_FEED_MAX_EVENTS, + AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX, AIDEN_REMOTE_HOST_FEED_SNAPSHOT_CHUNK_BYTES, AIDEN_REMOTE_PROTOCOL_VERSION, type AidenRemoteCapability, @@ -34,7 +35,7 @@ export interface AidenRemoteHostFeedBot { [key: string]: unknown; } -/** A Bot row's revision-50 Inbox signals; each is present only when it holds. */ +/** A Bot row's revision-50 Inbox signals and revision-66 preview; each is present only when it holds. */ export interface AidenRemoteHostFeedBotSignals { /** An approval, a question, a hand-off or an open issue waits on the person. */ needsYou?: true; @@ -42,25 +43,33 @@ export interface AidenRemoteHostFeedBotSignals { failed?: true; /** When the Bot's newest reply with visible text arrived, RFC 3339. */ lastReplyAt?: string; + /** + * Revision 66: the line the host's own Bots list shows under the Bot's name + * (its newest reply, else the person's newest message), one plain line of at + * most `AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX` characters. + */ + preview?: string; } -/** The Inbox signals of one Bot from its live summary; none when the summary is unknown. */ +/** The Inbox signals and preview of one Bot from its live summary; none when the summary is unknown. */ export function hostFeedBotSignals( - live: Pick | undefined, + live: (Pick & Partial>) | undefined, ): AidenRemoteHostFeedBotSignals { if (!live) return {}; const failed = isFailedBotSession(live.state); const replied = live.lastReplyAt !== null && Number.isSafeInteger(live.lastReplyAt) && live.lastReplyAt >= 0 ? new Date(live.lastReplyAt) : undefined; + const preview = clipPendingAttentionSummary(live.preview, AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX); return { ...(live.needsYou ? { needsYou: true as const } : {}), ...(failed ? { failed: true as const } : {}), ...(replied && Number.isFinite(replied.getTime()) ? { lastReplyAt: replied.toISOString() } : {}), + ...(preview ? { preview } : {}), }; } -/** One transcript-free read of everything the feed projects. */ +/** One read of everything the feed projects; it opens no chat transcript (Bot previews come from cached summaries). */ export interface AidenRemoteHostFeedState { /** Non-Bot chat summaries, exactly as `/chat-summaries` projects them. */ summaries: readonly AidenRemoteChatSummaryProjection[]; @@ -167,7 +176,7 @@ const DEFAULT_DEBOUNCE_MS = 50; /** * Host-wide change feed for paired desktop controllers. It never scans - * transcripts: every refresh is one transcript-free `source.read()` diffed + * chat transcripts: every refresh is one `source.read()` diffed * against the previous read, and run states come from HostRunRegistry * change notifications. The journal is the only queue; a reader that falls * behind retention, or presents a cursor from another epoch, gets a fresh diff --git a/main/services/aiden-remote-protocol.test.ts b/main/services/aiden-remote-protocol.test.ts index bc0de3d8c4..666d189cbe 100644 --- a/main/services/aiden-remote-protocol.test.ts +++ b/main/services/aiden-remote-protocol.test.ts @@ -3618,7 +3618,7 @@ test("revision 56 plans decode strictly, preserve absent versus null, and exclud const section = protocol.parseAidenRemoteContractFixture(raw).botPlans!; assert.deepEqual(section, raw.botPlans); assert.equal(protocol.AIDEN_REMOTE_BOT_PLANS_CONTRACT_REVISION, 56); - assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 65); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 66); assert.equal(section.pending.status, "pending"); assert.equal(section.active.steps[0].status, "done"); const parse = protocol.parseAidenRemoteBotPlan; @@ -3705,7 +3705,7 @@ test("revision 57 allowed fixture is strict and exposes only bounded public list const raw = await json("fixtures/contract.json") as Record; const section = protocol.parseAidenRemoteContractFixture(raw).botAllowed!; assert.deepEqual(section, raw.botAllowed); - assert.equal(protocol.AIDEN_REMOTE_BOT_ALLOWED_CONTRACT_REVISION, 57); assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 65); + assert.equal(protocol.AIDEN_REMOTE_BOT_ALLOWED_CONTRACT_REVISION, 57); assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 66); const all = [...section.paginated.firstPage.entries, ...section.paginated.nextPage.entries]; assert.equal(all.length, 53); assert.equal(all.filter(e => e.kind === "rule").length, 50); assert.equal(all.filter(e => e.kind === "folder").length, 3); assert.equal(new Set(all.map(e => e.id)).size, 53); @@ -3814,7 +3814,7 @@ test("revision 62 reads only the steps Stop cancelled as stopped, and every othe const protocol = await import("./aiden-remote-protocol.js"); const raw = await json("fixtures/contract.json") as Record; assert.equal(protocol.AIDEN_REMOTE_STOPPED_BY_USER_CONTRACT_REVISION, 62); - assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 65); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 66); const fixture = protocol.parseAidenRemoteContractFixture(raw).stoppedSteps; assert.ok(fixture); assert.deepEqual(fixture.stoppedStepIds, ["tool-3"]); @@ -3922,7 +3922,7 @@ test("revision 65 distinguishes gap recovery snapshots from provider resets and const protocol = await import("./aiden-remote-protocol.js"); const raw = await json("fixtures/contract.json") as Record; assert.equal(protocol.AIDEN_REMOTE_STREAM_SNAPSHOT_REASONS_CONTRACT_REVISION, 65); - assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 65); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 66); const parsedFixture = protocol.parseAidenRemoteContractFixture(raw); const section = parsedFixture.streamRecovery; assert.ok(section); @@ -3999,3 +3999,40 @@ test("revision 65 distinguishes gap recovery snapshots from provider resets and false, ); }); + +test("revision 66 host feed Bot rows carry a one-line preview and refuse anything else", async () => { + const protocol = await import("./aiden-remote-protocol.js"); + const raw = await json("fixtures/contract.json") as Record; + assert.equal(protocol.AIDEN_REMOTE_BOT_FEED_PREVIEW_CONTRACT_REVISION, 66); + const fixture = protocol.parseAidenRemoteContractFixture(raw); + const upsert = fixture.hostFeedEvents?.find((event) => event.type === "bot.upsert"); + assert.ok(upsert, "the fixture sends a Bot row"); + assert.equal(typeof upsert.payload.preview, "string"); + assert.equal(upsert.payload.needsYou, true); + + const row = (raw.hostFeedEvents as { type: string; payload: Record }[]) + .find((event) => event.type === "bot.upsert")!.payload; + const parse = (change: Record) => () => protocol.parseAidenRemoteHostFeedBot({ ...row, ...change }); + assert.doesNotThrow(parse({ preview: "😀".repeat(140) }), "the limit counts characters, not UTF-16 units"); + assert.throws(parse({ preview: "x".repeat(141) })); + assert.throws(parse({ preview: "" })); + assert.throws(parse({ preview: " leading space" }), /one trimmed plain line/u); + assert.throws(parse({ preview: "two\nlines" }), /one trimmed plain line/u); + assert.throws(parse({ preview: "hidden\u202Eoverride" }), /one trimmed plain line/u); + assert.doesNotThrow(parse({ preview: "family 👨\u200D👩\u200D👧" }), "emoji joiners stay"); + assert.throws(parse({ needsYou: false }), /needsYou/u); + assert.throws(parse({ failed: "yes" }), /failed/u); + assert.throws(parse({ lastReplyAt: "yesterday" })); + assert.throws(parse({ issueCount: 2 }), /issueCount/u); + assert.throws(parse({ secret: "x" }), /unsupported field/u); + + // The OpenAPI contract describes the same row. + const { default: Ajv2020 } = await import("ajv/dist/2020.js"); + const { default: addFormats } = await import("ajv-formats"); + const spec = await json("openapi.json") as { components: object }; + const ajv = new Ajv2020({ strict: false }); + addFormats(ajv); + const feedBot = ajv.compile({ $ref: "#/components/schemas/HostFeedBot", components: spec.components }); + assert.equal(feedBot(row), true, JSON.stringify(feedBot.errors)); + assert.equal(feedBot({ ...row, preview: "x".repeat(141) }), false); +}); diff --git a/main/services/aiden-remote-protocol.ts b/main/services/aiden-remote-protocol.ts index 95eeb8d097..25b0e8c135 100644 --- a/main/services/aiden-remote-protocol.ts +++ b/main/services/aiden-remote-protocol.ts @@ -371,7 +371,17 @@ export const AIDEN_REMOTE_CONTINUE_IN_NEW_CHAT_CONTRACT_REVISION = 64 as const; * payload so closed decoders on revision <= 64 stay valid. */ export const AIDEN_REMOTE_STREAM_SNAPSHOT_REASONS_CONTRACT_REVISION = 65 as const; -export const AIDEN_REMOTE_CONTRACT_REVISION = AIDEN_REMOTE_STREAM_SNAPSHOT_REASONS_CONTRACT_REVISION; +/** + * Contract revision 66 (provisional; re-claim the next revision after + * `main`'s at merge by changing only this constant): host feed Bot rows may + * carry `preview`, the one plain line the host's own Bots list shows under the + * Bot's name (at most 140 characters), and a host now sends `lastReplyAt` for + * every Bot rather than only Bots whose chat is open there. Display-only, no + * capability or feature token; older desktops ignore the key, and phones don't + * read the host feed. + */ +export const AIDEN_REMOTE_BOT_FEED_PREVIEW_CONTRACT_REVISION = 66 as const; +export const AIDEN_REMOTE_CONTRACT_REVISION = AIDEN_REMOTE_BOT_FEED_PREVIEW_CONTRACT_REVISION; export const AIDEN_REMOTE_BASE_PATH = "/api/aiden/v1" as const; export const AIDEN_REMOTE_MAX_SSE_FRAME_BYTES = 1_048_576; export const AIDEN_REMOTE_MAX_JSON_RESPONSE_BYTES = 1_048_576; @@ -3453,6 +3463,36 @@ function parseBotSummaryFields(value: unknown): AidenRemoteBotSummary { }; } +/** The longest `preview` a host feed Bot row carries (revision 66). */ +export const AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX = 140; + +/** + * A host feed Bot row: a Bot summary without `issueCount` (a phone shape), + * plus revision 52's `needsYou`, `failed` and `lastReplyAt` and revision 66's + * `preview`, one trimmed plain line. + */ +export function parseAidenRemoteHostFeedBot(value: unknown, label = "Host feed Bot"): Record { + if (!isRecord(value)) throw new Error(`${label} must be an object.`); + if (hasOwn(value, "issueCount")) throw new Error(`${label} carries no issueCount.`); + const { needsYou, failed, lastReplyAt, preview, ...summary } = value; + parseAidenRemoteBotSummary(summary); + assertExactKeys( + summary, + ["id", "name", "purpose", "avatar", "health", "createdAt", "updatedAt", "revision", "sessionState", "paused"], + label, + ); + if (needsYou !== undefined && needsYou !== true) throw new Error(`${label} needsYou must be true when present.`); + if (failed !== undefined && failed !== true) throw new Error(`${label} failed must be true when present.`); + if (lastReplyAt !== undefined) dateTimeValue(lastReplyAt, `${label} lastReplyAt`); + if (preview !== undefined) { + const text = boundedText(preview, `${label} preview`, AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX); + if (text.trim() !== text || /[\p{Cc}\p{Cf}\u2028\u2029]/u.test(text.replace(/[\u200C\u200D]/gu, ""))) { + throw new Error(`${label} preview must be one trimmed plain line.`); + } + } + return value; +} + export function parseAidenRemoteBotList(value: unknown): AidenRemoteBotList { if (!isRecord(value) || !Array.isArray(value.bots)) { throw new Error("Bot list must contain a bots array."); @@ -9935,8 +9975,11 @@ function parseRevision19Fixture( throw new Error("Host feed snapshot lists must be arrays."); } event.payload.workspaces.forEach((workspace) => parseHostFeedWorkspaceRepository(workspace, "Host feed workspace")); + event.payload.bots.forEach((bot) => parseAidenRemoteHostFeedBot(bot)); } else if (event.type === "workspace.upsert") { parseHostFeedWorkspaceRepository(event.payload, "Host feed workspace"); + } else if (event.type === "bot.upsert") { + parseAidenRemoteHostFeedBot(event.payload); } else if (event.type === "run.state") { assertExactKeys( event.payload, diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index e1fd8ed4c1..1647c53faf 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -1235,13 +1235,14 @@ async function createRuntime(): Promise { approvalMode: async () => effectiveApprovalMode(await configStore.getSettings(), true), repositoryIdentity: gitCachedRepositoryIdentity, ...(bots ? { listBots: () => bots.list() } : {}), - // Read runtime signals without opening conversation entries or context. - // Reply times are available only from an already-open live feed. + // The same summary this Mac's own Bots list reads (revision 66): a closed + // Bot's preview and last reply come from the projection's cache, which + // reads the transcript again only after its newest entry changes. botSignals: async (botRows) => { const { botLiveProjection } = await import("./bot-runtime/bot-session-main.js"); const live = botLiveProjection(); return new Map(await mapWithConcurrency(botRows, 4, async (bot) => - [bot.id, hostFeedBotSignals(await live.inboxSignals(bot.id).catch(() => undefined))] as const, + [bot.id, hostFeedBotSignals(await live.summary(bot.id).catch(() => undefined))] as const, )); }, }), diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 508abe706a..a3710520fb 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -959,13 +959,8 @@ test("needsYou agrees with the summary, with or without an open feed, and never const needsYou = await live.projection.needsYou("bot:a"); assert.equal(transcriptReads, before, `the cheap read opens no transcript (${label})`); assert.equal(needsYou, expected, label); - const signals = await live.projection.inboxSignals("bot:a"); - assert.equal(transcriptReads, before, "host-feed signals never open a transcript"); - assert.equal(signals.needsYou, expected); const summary = await live.projection.summary("bot:a"); - assert.deepEqual(signals.state, summary.state, `host-feed state agrees (${label})`); assert.equal(summary.needsYou, expected, `the summary agrees (${label})`); - if (label.startsWith("no feed") || label.startsWith("feed closed")) assert.equal(signals.lastReplyAt, null); }; const states = [ [false, false], @@ -998,9 +993,8 @@ test("needsYou agrees with the summary, with or without an open feed, and never await live.service.send("bot:a", { text: "hello", requestId: "feed-signals" }); await waitFor(() => visibleText(tape.view).includes("assistant:Hello."), { what: "the existing live feed's reply" }); const before = transcriptReads; - assert.equal((await live.projection.inboxSignals("bot:a")).lastReplyAt, - (await live.projection.summary("bot:a")).lastReplyAt); - assert.equal(transcriptReads, before, "an open feed reuses its admitted entries too"); + assert.notEqual((await live.projection.summary("bot:a")).lastReplyAt, null); + assert.equal(transcriptReads, before, "an open feed reuses its admitted entries"); watching.unsubscribe(); issueOpen = true; unavailable = true; @@ -2322,7 +2316,6 @@ test("a waiting access request reaches subscribers, needs-you and late joiners; const card = requests.pending()[0]!; await waitFor(() => tape.view?.accessRequest?.waitId === card.waitId, { what: "the public access event" }); assert.equal((await live.projection.summary("bot:a")).needsYou, true); - assert.equal((await live.projection.inboxSignals("bot:a")).needsYou, true); assert.deepEqual(Object.keys(tape.view!.accessRequest!).sort(), ["botId", "waitId", "toolCallId", "target", "label", "place", "why", "choices"].sort()); await assert.rejects(requests.answer("bot:a", card.waitId, "always", async () => { throw new Error("Access changed"); }), /Access changed/u); await live.projection.refreshAccessRequest("bot:a"); @@ -2410,7 +2403,6 @@ test("pending plans need the person offscreen and subscribe catches unannounced for (const status of ["pending", "active", "finished", "stopped", "expired"] as const) { plan = planView({ status }); assert.equal(await live.projection.needsYou("bot:a"), status === "pending"); - assert.equal((await live.projection.inboxSignals("bot:a")).needsYou, status === "pending"); assert.equal((await live.projection.summary("bot:a")).needsYou, status === "pending"); } plan = planView(); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 4ec319968d..b2a1ceef79 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -1079,8 +1079,6 @@ export interface BotLiveProjection { refreshActivity(botId: string): Promise; /** Preview, time and state for a list row. */ summary(botId: string): Promise; - /** Host-feed signals from runtime state and an already-open feed only. */ - inboxSignals(botId: string): Promise>; /** * The summary's `needsYou` alone, without reading the transcript: an open * question, hand-off, access request, pending plan, approval or issue, and never for an unavailable Bot @@ -1690,16 +1688,6 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro return needsYouNow(botId); }, - async inboxSignals(botId) { - const feed = feeds.get(botId); - const state = feed && !feed.ended ? feed.state : await deps.state(botId); - return { - state, - needsYou: state.kind !== "unavailable" && await needsYouNow(botId), - lastReplyAt: feed && !feed.ended ? botLastReplyAt(feed.entries) : null, - }; - }, - async summary(botId) { // Read right before each return, so a slow summary never reports a stale wait. It uses the // same sources as the chat, so a row agrees with it whether or not a chat is open. diff --git a/main/services/peer-operation.test.ts b/main/services/peer-operation.test.ts index 76e65d68c0..d20bbead56 100644 --- a/main/services/peer-operation.test.ts +++ b/main/services/peer-operation.test.ts @@ -60,6 +60,7 @@ test("expanded peer operations resolve to the contract's routes, not arbitrary U [{ operation: "runInputs", resourceId: "run_1", idempotencyKey: KEY }, "submitRunInput"], [{ operation: "createBotChat", resourceId: "bot_1", idempotencyKey: KEY }, "createBotChat"], [{ operation: "botSessionImage", resourceId: "bot_1", itemId: "entry_7" }, "getBotSessionImage"], + [{ operation: "botAvatar", resourceId: "bot_1", itemId: `avatar_revision_${"a".repeat(32)}` }, "getBotAvatarContent"], [{ operation: "uploadAttachment", resourceId: "chat_1", body: { name: "a.txt" } }, "uploadChatAttachment"], [{ operation: "removeAttachment", resourceId: "chat_1", itemId: `att_${"A".repeat(43)}` }, "removeChatAttachment"], [{ operation: "botSession", resourceId: "bot_1" }, "getBotSession"], @@ -262,7 +263,13 @@ test("expanded peer reads reject malformed DTOs and attachment bytes stay bounde { mimeType: "image/jpeg", data: png }, )) as { mimeType: string; bytes: Uint8Array }; assert.deepEqual([shared.mimeType, [...shared.bytes]], ["image/jpeg", [...png]]); - for (const operation of ["attachmentContent", "botSessionImage"]) + // A Bot's photo avatar too. + const photo = (await peerOperationResult( + { operation: "botAvatar" }, + { mimeType: "image/png", data: png }, + )) as { mimeType: string; bytes: Uint8Array }; + assert.deepEqual([photo.mimeType, [...photo.bytes]], ["image/png", [...png]]); + for (const operation of ["attachmentContent", "botSessionImage", "botAvatar"]) for (const invalid of [ { mimeType: "text/html", data: png }, { mimeType: "image/png", data: Buffer.alloc(0) }, diff --git a/main/services/peer-operation.ts b/main/services/peer-operation.ts index f98e8b6cb3..e8bc11aa00 100644 --- a/main/services/peer-operation.ts +++ b/main/services/peer-operation.ts @@ -58,7 +58,7 @@ const STAGED_ATTACHMENT_ID = /^att_[A-Za-z0-9_-]{43}$/u; const BOT_WAIT_ID = /^[A-Za-z0-9-]{1,64}$/u; /** Operations whose answer is bounded image bytes, not JSON. */ -export const PEER_BINARY_OPERATIONS: ReadonlySet = new Set(["attachmentContent", "botSessionImage"]); +export const PEER_BINARY_OPERATIONS: ReadonlySet = new Set(["attachmentContent", "botSessionImage", "botAvatar"]); /** Run-control operations reconcile from the host feed's run state. */ export const PEER_RUN_OPERATIONS: ReadonlySet = new Set([ @@ -383,6 +383,9 @@ export function peerOperationRequest( case "botSessionImage": path = `/bots/${id()}/session/images/${item()}`; break; + case "botAvatar": + path = `/bots/${id()}/avatar/${item()}`; + break; case "createChat": path = "/chats"; method = "POST"; diff --git a/main/services/peer-response.ts b/main/services/peer-response.ts index 4ee4758dd4..cbc99f6496 100644 --- a/main/services/peer-response.ts +++ b/main/services/peer-response.ts @@ -53,6 +53,7 @@ const operationIds: Record = { forkSummaryCancel: "chatForkSummaryAction", botSession: "getBotSession", botSessionImage: "getBotSessionImage", + botAvatar: "getBotAvatarContent", botSend: "sendBotMessage", botResume: "resumeBotSession", botDismiss: "dismissBotSession", diff --git a/package.json b/package.json index d34675ba95..856d4da295 100644 --- a/package.json +++ b/package.json @@ -140,7 +140,7 @@ "pretest:bots": "npm run build:lease-flock && npm run build:subagent-file-mutator && npm run build:bot-inbox-writer && node scripts/build-bot-inbox-writer.mjs --test && node --test scripts/bot-inbox-writer.test.mjs && tsx --test main/services/bot-share-image-tool.test.ts main/services/bot-inbound-attachment-inbox.test.ts main/services/vision-analysis-tool.test.ts", "pretest:bot-runtime": "npm run build:lease-flock", "test:telegram": "tsx --test main/services/telegram/bot-reply-outbox.test.ts main/services/telegram/telegram-profile-mutation-fence.test.ts main/services/telegram/telegram-controls.test.ts main/services/telegram/telegram-inbound.test.ts main/services/telegram/telegram-outbound.test.ts main/services/telegram/telegram-queue.test.ts main/services/telegram/telegram-markdown.test.ts main/services/telegram/telegram-bot-api.test.ts main/services/telegram/telegram-turn.test.ts main/services/telegram/telegram-session.test.ts main/services/telegram/telegram-service-core.test.ts main/services/telegram/telegram-workspace-core.test.ts main/services/telegram/telegram-activity.test.ts main/services/telegram/telegram-profile-config.test.ts main/services/telegram/telegram-extension-registry.test.ts main/services/telegram/telegram-thread-store.test.ts main/services/telegram/telegram-ownership.test.ts main/services/telegram/telegram-agent-tools.test.ts main/services/telegram/telegram-bot-binding-store.test.ts main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts renderer/lib/telegram-workspace-options.test.ts", - "test:bots": "tsx --test main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts main/services/bot-avatar-store.test.ts main/services/bot-store-core.test.ts main/services/bot-chat-store.test.ts main/services/bot-mutation-gate.test.ts main/services/bot-inbox-projection.test.ts main/services/bot-system-prompt.test.ts main/services/bot-generation-preparation.test.ts main/services/bot-inbound-attachment-home.test.ts main/services/bot-file-tool-router.test.ts main/services/bot-tool-authority.test.ts main/services/bot-capability-store-core.test.ts main/services/bot-capability-store.test.ts main/services/bot-capability-state-checkpoint.test.ts main/services/bot-capability-keychain-anchor.test.ts main/services/bot-capability-secret-service-anchor.test.ts main/services/bot-capability-lease.test.ts main/services/bot-runtime-inventory-lease.test.ts main/services/bot-runtime-inventory-publication.test.ts main/services/bot-runtime-authority.test.ts main/services/bot-capability-catalog-core.test.ts main/services/bot-capability-bindings.test.ts main/services/bot-capability-key-store.test.ts main/services/bot-capability-migration-seal.test.ts main/services/bot-capability-incarnation-store.test.ts main/services/bot-capability-inventory-ports.test.ts main/services/bot-capability-production-shape.test.ts main/services/bot-mcp-inventory.test.ts main/services/bot-skill-inventory.test.ts main/services/bot-skill-content-watcher.test.ts main/services/bot-managed-workspace-core.test.ts main/services/bot-lifecycle-journal-core.test.ts main/services/bot-application-service.test.ts main/handlers/bot-params.test.ts main/handlers/bot-renderer-errors.test.ts main/handlers/bots.contract.test.ts main/handlers/bot-access.test.ts main/handlers/bot-telegram.test.ts renderer/main/bots-view.test.tsx renderer/main/bots/bot-character-card.test.tsx renderer/main/bots/bot-chat-header.test.tsx renderer/main/bots/bot-chat-mode.test.tsx renderer/main/bots/bot-delete-dialog.test.tsx renderer/main/bots/bots-home.test.tsx renderer/main/bots/bot-create-flow.test.tsx renderer/main/bots/bot-advanced.test.tsx renderer/main/bots/bot-access-draft.test.ts renderer/main/bots/bot-profile-photo.test.tsx renderer/lib/model-picker-data.test.ts renderer/lib/command-system-core.test.ts renderer/shared/bot-capabilities.test.ts renderer/shared/computer-noun.test.ts renderer/shared/bot-presets.test.ts renderer/shared/bot-connections.test.ts renderer/components/bots/bot-connection-ui.test.tsx main/services/bot-runtime-tools/suggest-connection.test.ts main/services/bot-connection-dismissals.test.ts main/handlers/bot-live.test.ts main/handlers/bot-questions.test.ts renderer/main/bots/bot-chat-pane.test.tsx renderer/main/bots/bot-status-slot.test.ts renderer/main/bots/bot-routines.test.tsx renderer/lib/bot-notifications-sync.test.ts main/services/bot-connection-setup-core.test.ts main/handlers/bot-files.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-memory-page.test.tsx main/services/bot-routine-notes.test.ts main/services/bot-routine-proposals.test.ts main/services/bot-routine-notifications.test.ts renderer/main/bots/bot-model-choice.test.ts renderer/main/bots/bot-model-picker.test.tsx renderer/shared/bot-activity.test.ts renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-activity-recap.test.tsx renderer/lib/bot-routes.test.ts renderer/lib/bot-sidebar-preferences.test.ts renderer/lib/search-fold.test.ts renderer/main/bots/use-bot-sidebar-preferences.test.tsx renderer/main/bots/bot-panel.test.tsx renderer/main/bots/bot-activity-log.test.ts renderer/main/bots/bot-sidebar.test.tsx main/services/bot-wake-ups/wake-ups.test.ts renderer/components/bots/wake-up-chip.test.tsx renderer/main/bots/bot-wake-ups.test.tsx", + "test:bots": "tsx --test main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts main/services/bot-avatar-store.test.ts main/services/bot-store-core.test.ts main/services/bot-chat-store.test.ts main/services/bot-mutation-gate.test.ts main/services/bot-inbox-projection.test.ts main/services/bot-system-prompt.test.ts main/services/bot-generation-preparation.test.ts main/services/bot-inbound-attachment-home.test.ts main/services/bot-file-tool-router.test.ts main/services/bot-tool-authority.test.ts main/services/bot-capability-store-core.test.ts main/services/bot-capability-store.test.ts main/services/bot-capability-state-checkpoint.test.ts main/services/bot-capability-keychain-anchor.test.ts main/services/bot-capability-secret-service-anchor.test.ts main/services/bot-capability-lease.test.ts main/services/bot-runtime-inventory-lease.test.ts main/services/bot-runtime-inventory-publication.test.ts main/services/bot-runtime-authority.test.ts main/services/bot-capability-catalog-core.test.ts main/services/bot-capability-bindings.test.ts main/services/bot-capability-key-store.test.ts main/services/bot-capability-migration-seal.test.ts main/services/bot-capability-incarnation-store.test.ts main/services/bot-capability-inventory-ports.test.ts main/services/bot-capability-production-shape.test.ts main/services/bot-mcp-inventory.test.ts main/services/bot-skill-inventory.test.ts main/services/bot-skill-content-watcher.test.ts main/services/bot-managed-workspace-core.test.ts main/services/bot-lifecycle-journal-core.test.ts main/services/bot-application-service.test.ts main/handlers/bot-params.test.ts main/handlers/bot-renderer-errors.test.ts main/handlers/bots.contract.test.ts main/handlers/bot-access.test.ts main/handlers/bot-telegram.test.ts renderer/main/bots-view.test.tsx renderer/main/bots/bot-character-card.test.tsx renderer/main/bots/bot-chat-header.test.tsx renderer/main/bots/bot-chat-mode.test.tsx renderer/main/bots/bot-delete-dialog.test.tsx renderer/main/bots/bots-home.test.tsx renderer/main/bots/bot-create-flow.test.tsx renderer/main/bots/bot-advanced.test.tsx renderer/main/bots/bot-access-draft.test.ts renderer/main/bots/bot-profile-photo.test.tsx renderer/lib/model-picker-data.test.ts renderer/lib/command-system-core.test.ts renderer/shared/bot-capabilities.test.ts renderer/shared/computer-noun.test.ts renderer/shared/bot-presets.test.ts renderer/shared/bot-connections.test.ts renderer/components/bots/bot-connection-ui.test.tsx main/services/bot-runtime-tools/suggest-connection.test.ts main/services/bot-connection-dismissals.test.ts main/handlers/bot-live.test.ts main/handlers/bot-questions.test.ts renderer/main/bots/bot-chat-pane.test.tsx renderer/main/bots/bot-status-slot.test.ts renderer/main/bots/bot-routines.test.tsx renderer/lib/bot-notifications-sync.test.ts main/services/bot-connection-setup-core.test.ts main/handlers/bot-files.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-memory-page.test.tsx main/services/bot-routine-notes.test.ts main/services/bot-routine-proposals.test.ts main/services/bot-routine-notifications.test.ts renderer/main/bots/bot-model-choice.test.ts renderer/main/bots/bot-model-picker.test.tsx renderer/shared/bot-activity.test.ts renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-activity-recap.test.tsx renderer/lib/bot-routes.test.ts renderer/lib/bot-sidebar-preferences.test.ts renderer/lib/remote-bot-seen.test.ts renderer/lib/search-fold.test.ts renderer/main/bots/use-bot-sidebar-preferences.test.tsx renderer/main/bots/bot-panel.test.tsx renderer/main/bots/bot-activity-log.test.ts renderer/main/bots/bot-sidebar.test.tsx main/services/bot-wake-ups/wake-ups.test.ts renderer/components/bots/wake-up-chip.test.tsx renderer/main/bots/bot-wake-ups.test.tsx", "test:bot-runtime": "tsx --test main/services/bot-runtime/bot-claim-check.test.ts main/services/bot-runtime/bot-run-watchdog.test.ts main/services/bot-runtime/bot-execution-issues.test.ts main/services/bot-runtime/bot-reply-silence.test.ts main/services/bot-runtime/bot-suggestion-budget.test.ts main/services/bot-runtime/profile-lock.test.ts main/services/bot-runtime/harness-host.test.ts main/services/bot-runtime/tool-adapter.test.ts main/services/bot-runtime/bot-extension.test.ts main/services/bot-runtime/bot-session-service.test.ts main/services/bot-runtime/bot-tool-assembly.test.ts main/services/bot-runtime/bot-approval-judge.test.ts main/services/bot-runtime/bot-owner-request.test.ts main/services/bot-runtime/bot-delete.test.ts main/services/bot-runtime/live-projection.test.ts main/services/bot-runtime/active-transcript-watch.test.ts main/services/bot-runtime/bot-attention.test.ts main/services/bot-runtime/bot-starter.test.ts main/services/bot-settings-changes/service.test.ts main/services/bot-settings-changes/ports.test.ts main/services/bot-settings-changes/tool.test.ts main/services/bot-runtime/bot-question-tool.test.ts main/services/bot-runtime/bot-questions.test.ts main/services/bot-memory/store.test.ts main/services/bot-memory/scan.test.ts main/services/bot-memory/tool.test.ts main/services/bot-memory/compaction.test.ts main/services/bot-memory/review.test.ts main/services/bot-memory/recall.test.ts main/handlers/bot-memory.test.ts main/services/bot-runtime/bot-activity-detail.test.ts main/services/bot-runtime/bot-computer-tools.test.ts main/services/bot-runtime/bot-computer-candidates.test.ts main/services/bot-runtime/bot-file-candidates.test.ts", "pretest:bot-health": "npm run build:lease-flock", "pretest:bot-learning": "npm run build:lease-flock", diff --git a/protocol/aiden-remote/v1/fixtures/contract.json b/protocol/aiden-remote/v1/fixtures/contract.json index 40ec8764bb..2917b72d06 100644 --- a/protocol/aiden-remote/v1/fixtures/contract.json +++ b/protocol/aiden-remote/v1/fixtures/contract.json @@ -1,5 +1,5 @@ { - "contractRevision": 65, + "contractRevision": 66, "peerRouteAdvertisement": { "feature": "peer-routes-v1", "routes": [ @@ -2299,7 +2299,7 @@ "instanceId": "instance_fixture_01", "displayName": "Fixture Aiden", "platform": "mac", - "contractRevision": 65, + "contractRevision": 66, "pairingRequests": true }, "hostFeedEvents": [ @@ -2377,6 +2377,41 @@ "payload": { "id": "workspace_fixture_02" } + }, + { + "protocolVersion": 1, + "streamId": "host", + "sequence": 3, + "timestamp": "2026-08-18T19:02:03.000Z", + "type": "bot.upsert", + "terminal": false, + "payload": { + "id": "bot_fixture_01", + "name": "Scout", + "purpose": "Finds the signal in a busy week", + "avatar": { + "semantic": { + "version": 1, + "shape": "orb", + "color": "rose" + }, + "asset": { + "assetRevision": "avatar_revision_3", + "mimeType": "image/png", + "width": 512, + "height": 512, + "byteSize": 1024 + } + }, + "health": "ready", + "sessionState": "idle", + "createdAt": "2026-08-18T17:00:00.000Z", + "updatedAt": "2026-08-18T18:45:00.000Z", + "revision": "bot_revision_7", + "needsYou": true, + "lastReplyAt": "2026-08-18T19:01:30.000Z", + "preview": "Three things changed this week: the release moved to Friday, and two reviews are waiting on you." + } } ], "runEvents": [ diff --git a/protocol/aiden-remote/v1/openapi.json b/protocol/aiden-remote/v1/openapi.json index b415975262..0edf3c3f39 100644 --- a/protocol/aiden-remote/v1/openapi.json +++ b/protocol/aiden-remote/v1/openapi.json @@ -5561,7 +5561,7 @@ "name": "since", "in": "query", "required": false, - "description": "Epoch-milliseconds cursor; runs finished at or after it are returned (inclusive — clients dedupe by run id).", + "description": "Epoch-milliseconds cursor; runs finished at or after it are returned (inclusive \u2014 clients dedupe by run id).", "schema": { "type": "integer", "minimum": 0 @@ -5588,7 +5588,7 @@ }, "now": { "type": "integer", - "description": "Server epoch-milliseconds clock — clients baseline first-poll cursors to this rather than the device clock." + "description": "Server epoch-milliseconds clock \u2014 clients baseline first-poll cursors to this rather than the device clock." } }, "additionalProperties": false @@ -6545,7 +6545,10 @@ "name": "Aiden-Run-Checkpoint", "in": "header", "description": "Revision 58. Set to 1 to accept a bounded snapshot of an active run at its current sequence. Older hosts ignore this header.", - "schema": { "type": "string", "const": "1" } + "schema": { + "type": "string", + "const": "1" + } }, { "$ref": "#/components/parameters/ChatId" @@ -6587,7 +6590,10 @@ "name": "Aiden-Run-Checkpoint", "in": "header", "description": "Revision 58. Set to 1 to accept a bounded snapshot of an active run at its current sequence. Older hosts ignore this header.", - "schema": { "type": "string", "const": "1" } + "schema": { + "type": "string", + "const": "1" + } }, { "name": "runId", @@ -12548,7 +12554,9 @@ }, "inputSource": { "type": "string", - "enum": ["voice"], + "enum": [ + "voice" + ], "description": "Additive in contract revision 60, user messages only: Aiden Live sent this message for the person on the Mac. Clients show a small \"By voice\" label; they ignore the key on assistant messages and any value they do not know." }, "createdAt": { @@ -18179,6 +18187,92 @@ }, "additionalProperties": false }, + "HostFeedBot": { + "type": "object", + "description": "A host feed Bot row: a BotSummary (without issueCount, which only phones read) plus the Inbox signals of contract revision 52 and the preview of revision 66. Each optional field is present only when it holds.", + "x-aiden-updated-at-not-before-created-at": true, + "required": [ + "id", + "name", + "purpose", + "avatar", + "health", + "createdAt", + "updatedAt", + "revision" + ], + "properties": { + "id": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9._:-]+$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "purpose": { + "type": "string", + "maxLength": 280 + }, + "avatar": { + "$ref": "#/components/schemas/BotAvatarView" + }, + "health": { + "$ref": "#/components/schemas/BotHealth" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "revision": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "sessionState": { + "description": "Contract revision 37: paused reaches only devices holding bot:handoffs; every other device sees a paused Bot as unavailable.", + "enum": [ + "idle", + "running", + "interrupted", + "needs_model", + "unavailable", + "paused" + ] + }, + "paused": { + "description": "Contract revision 37, only for devices holding bot:handoffs and only while the person paused the Bot (sessionState is then paused).", + "const": true + }, + "needsYou": { + "description": "Contract revision 52: an approval, a question, a hand-off or an open issue waits on the person.", + "const": true + }, + "failed": { + "description": "Contract revision 52: the Bot's last turn was cut short, or its model cannot be used.", + "const": true + }, + "lastReplyAt": { + "description": "Contract revision 52: when the Bot's newest reply with visible text arrived. Since revision 66 a host sends it for every Bot, not only Bots whose chat is open there.", + "type": "string", + "format": "date-time" + }, + "preview": { + "description": "Contract revision 66: the one plain line the host's own Bots list shows under the Bot's name (its newest reply, else the person's newest message). No line breaks or control characters.", + "type": "string", + "minLength": 1, + "maxLength": 140 + } + }, + "additionalProperties": false + }, "HostFeedSnapshot": { "type": "object", "required": [ @@ -18214,7 +18308,7 @@ "type": "array", "description": "Empty for devices without bot:read.", "items": { - "$ref": "#/components/schemas/BotSummary" + "$ref": "#/components/schemas/HostFeedBot" } }, "partial": { @@ -18381,7 +18475,7 @@ "then": { "properties": { "payload": { - "$ref": "#/components/schemas/BotSummary" + "$ref": "#/components/schemas/HostFeedBot" } } } @@ -19190,7 +19284,7 @@ "type": "string", "minLength": 1, "maxLength": 120, - "description": "When the routine runs, ready to show: a schedule with its timezone (\"Every day at 9:00 AM · Pacific Time\"), or what starts an event routine (\"When this routine's link is called\"). A card the Bot replaced with a revised one is omitted; the revised card follows as a new entry." + "description": "When the routine runs, ready to show: a schedule with its timezone (\"Every day at 9:00 AM \u00b7 Pacific Time\"), or what starts an event routine (\"When this routine's link is called\"). A card the Bot replaced with a revised one is omitted; the revised card follows as a new entry." }, "status": { "enum": [ diff --git a/renderer/components/bot-avatar.tsx b/renderer/components/bot-avatar.tsx index 66f4ca53eb..5a962bf64c 100644 --- a/renderer/components/bot-avatar.tsx +++ b/renderer/components/bot-avatar.tsx @@ -111,12 +111,15 @@ export function BotAvatar({ botId, name, photoLoading = "none", + photoUrl, size = "medium", working = false, }: { avatar: BotAvatarValue; botId?: string; name: string; + /** A photo read elsewhere (a paired Mac's Bot), drawn over the shape like this Mac's own Bots' photos. */ + photoUrl?: string; photoLoading?: "none" | "visible" | "immediate"; size?: "small" | "medium" | "large" | "preview"; /** The Bot is in a running turn: its face glances (a photo shows a small activity badge instead). */ @@ -151,7 +154,8 @@ export function BotAvatar({ photoLoading === "immediate" ? "selected" : "visible", ); const [failedRevision, setFailedRevision] = React.useState(); - const showPhoto = photo && failedRevision !== photo.assetRevision; + const shown = photoUrl ? { dataUrl: photoUrl, assetRevision: photoUrl } : photo; + const showPhoto = shown && failedRevision !== shown.assetRevision; React.useEffect(() => { const node = avatarRef.current; if (!working || !node) return; @@ -179,8 +183,8 @@ export function BotAvatar({ alt="" className="absolute inset-0 size-full object-cover" draggable={false} - src={photo.dataUrl} - onError={() => setFailedRevision(photo.assetRevision)} + src={shown.dataUrl} + onError={() => setFailedRevision(shown.assetRevision)} /> ) : null} {showPhoto && working ? ( diff --git a/renderer/components/bot-unread-dot.tsx b/renderer/components/bot-unread-dot.tsx new file mode 100644 index 0000000000..3e038b2fae --- /dev/null +++ b/renderer/components/bot-unread-dot.tsx @@ -0,0 +1,6 @@ +/** A Bot row's unread dot, inline after the name: it takes room only when it is there. */ +export function BotUnreadDot() { + return ( + + ); +} diff --git a/renderer/components/remote-bots-section.tsx b/renderer/components/remote-bots-section.tsx index 0b05369509..0648faea31 100644 --- a/renderer/components/remote-bots-section.tsx +++ b/renderer/components/remote-bots-section.tsx @@ -1,5 +1,8 @@ +import * as React from "react"; import { Bot, Loader2 } from "lucide-react"; -import type { RemoteBotChoice, RemoteBotGroup } from "../lib/hosts/new-chat-targets"; +import type { NewChatMachine, RemoteBotChoice, RemoteBotGroup } from "../lib/hosts/new-chat-targets"; +import { useRemoteBotPhoto } from "../lib/hosts/remote-images"; +import { isRemoteBotUnread, markRemoteBotSeen, useRemoteBotSeen } from "../lib/remote-bot-seen"; import { matchesSearch } from "../lib/search-fold"; import { RemoteHostMarker } from "./sidebar-remote"; import { cn } from "../lib/ui-utils"; @@ -13,8 +16,9 @@ import { Text } from "./ui"; import { pauseWhenUnseen } from "../lib/offscreen-pause"; import { BotAvatar } from "./bot-avatar"; import { BotNeedsYouBadge } from "./bot-needs-you-badge"; +import { BotUnreadDot } from "./bot-unread-dot"; -type RemoteBotLine = { kind: "waiting" | "working" | "status"; text: string; spoken: string }; +type RemoteBotLine = { kind: "waiting" | "working" | "status" | "preview"; text: string; spoken: string }; const STATUS_LINES = { paused: { text: BOT_PAUSED_ROW_LABEL, spoken: "paused" }, @@ -24,13 +28,16 @@ const STATUS_LINES = { /** * A paired Mac's Bot's one line, in the order this Mac's own Bot rows use: - * waiting on the person, then a running turn, then why it stopped. The Bot's - * description is never the line; it is searchable and read as the row's description. + * waiting on the person, then a running turn, then why it stopped, then the + * last message (revision 66 hosts send it). The Bot's description is never + * the line; it is searchable and read as the row's description when there is + * no message. */ export function remoteBotLine(bot: RemoteBotChoice): RemoteBotLine | null { if (bot.needsYou) return { kind: "waiting", text: BOT_WAITING_LINE, spoken: "needs you" }; if (bot.working) return { kind: "working", text: BOT_WORKING_LINE, spoken: "working" }; if (bot.status) return { kind: "status", ...STATUS_LINES[bot.status] }; + if (bot.preview) return { kind: "preview", text: bot.preview, spoken: bot.preview }; return null; } @@ -60,6 +67,12 @@ export function RemoteBotsSection({ selected?: string | null; onOpen(hostId: string, botId: string): void; }) { + const seen = useRemoteBotSeen(); + // The open Bot's newest reply is on screen, so it is not unread when the person leaves. + const open = selected ? groups.flatMap(({ host, bots }) => bots.filter((bot) => `${host.id}/${bot.id}` === selected))[0] : undefined; + React.useEffect(() => { + if (selected && open?.lastReplyAt !== undefined) markRemoteBotSeen(selected, open.lastReplyAt); + }, [selected, open?.lastReplyAt]); if (groups.length === 0) return null; return (
@@ -78,58 +91,18 @@ export function RemoteBotsSection({ ) : null}
    {bots.map((bot) => { - const line = remoteBotLine(bot); const key = `${host.id}/${bot.id}`; - const busy = opening === key; const current = selected === key; - const unavailable = Boolean(host.disabledReason); return ( -
  • - -
  • + ); })}
@@ -138,3 +111,77 @@ export function RemoteBotsSection({
); } + +function RemoteBotRow({ + host, + bot, + busy, + current, + unread, + onOpen, +}: { + host: NewChatMachine; + bot: RemoteBotChoice; + busy: boolean; + current: boolean; + unread: boolean; + onOpen(hostId: string, botId: string): void; +}) { + const line = remoteBotLine(bot); + const key = `${host.id}/${bot.id}`; + const unavailable = Boolean(host.disabledReason); + const photoUrl = useRemoteBotPhoto(host.id, bot.id, bot.photo, !unavailable); + const working = Boolean(bot.working) && !bot.needsYou; + return ( +
  • + +
  • + ); +} diff --git a/renderer/lib/hosts/new-chat-targets.ts b/renderer/lib/hosts/new-chat-targets.ts index 8775bed55e..1b593d9d35 100644 --- a/renderer/lib/hosts/new-chat-targets.ts +++ b/renderer/lib/hosts/new-chat-targets.ts @@ -5,6 +5,8 @@ import { hostControlRefusal, remoteHostCapabilities } from "./remote-host-adapte import { localComputerNoun } from "../../shared/computer-noun"; import { isBotAvatarAppearance, type BotAvatar } from "../../shared/bots"; import { peerFeedBotAttention } from "../../shared/peer-feed-inbox"; +import { clipPendingAttentionSummary } from "../../shared/chat-pending-attention"; +import { remoteBotPhotoAsset, type RemoteBotPhotoAsset } from "./remote-bot-photo-asset"; /** * Where new work can start: this Mac or a paired host, the projects each host @@ -138,8 +140,17 @@ export interface RemoteBotChoice { * resumed, or the Bot's AI model cannot be used. */ status?: "paused" | "interrupted" | "needs_model"; + /** The line the host's own Bots list shows under the name (revision 66), one plain line. */ + preview?: string; + /** When the Bot's newest reply arrived, by the host's clock; the row's unread dot compares it with what this Mac showed. */ + lastReplyAt?: number; + /** The Bot's photo, as the host lists it; read on demand. */ + photo?: RemoteBotPhotoAsset; } +/** The longest preview a remote Bot row shows; a host sends at most this (revision 66). */ +export const REMOTE_BOT_PREVIEW_MAX = 140; + export interface RemoteBotGroup { host: NewChatMachine; bots: RemoteBotChoice[]; @@ -167,6 +178,10 @@ export function remoteBotGroups( const purpose = text(row, "purpose"); const semantic = (row.avatar as { semantic?: unknown } | null | undefined)?.semantic; const { needsYou } = peerFeedBotAttention(row); + // The host already sends one plain line; it is still another computer's text. + const preview = clipPendingAttentionSummary(row.preview, REMOTE_BOT_PREVIEW_MAX); + const lastReplyAt = typeof row.lastReplyAt === "string" ? Date.parse(row.lastReplyAt) : Number.NaN; + const photo = remoteBotPhotoAsset(row); return { id: row.id, name: text(row, "name") ?? "Untitled Bot", @@ -177,6 +192,9 @@ export function remoteBotGroups( ...(row.sessionState === "paused" || row.sessionState === "interrupted" || row.sessionState === "needs_model" ? { status: row.sessionState as "paused" | "interrupted" | "needs_model" } : {}), + ...(preview ? { preview } : {}), + ...(Number.isFinite(lastReplyAt) && lastReplyAt > 0 ? { lastReplyAt } : {}), + ...(photo ? { photo } : {}), }; }); if (bots.length === 0) continue; diff --git a/renderer/lib/hosts/remote-bot-photo-asset.ts b/renderer/lib/hosts/remote-bot-photo-asset.ts new file mode 100644 index 0000000000..311ab4bf3f --- /dev/null +++ b/renderer/lib/hosts/remote-bot-photo-asset.ts @@ -0,0 +1,20 @@ +import { MAX_INLINE_IMAGE_BYTES } from "../../shared/attachment-contract"; + +/** A paired host's Bot photo as its feed row lists it (`avatar.asset`). */ +export interface RemoteBotPhotoAsset { + assetRevision: string; + byteSize: number; +} + +const ASSET_REVISION = /^[A-Za-z0-9._:-]{1,128}$/u; + +/** The photo a host feed Bot row lists, or undefined when it lists none or a malformed one. */ +export function remoteBotPhotoAsset(row: object): RemoteBotPhotoAsset | undefined { + const avatar = (row as { avatar?: unknown }).avatar; + const asset = avatar && typeof avatar === "object" ? (avatar as { asset?: unknown }).asset : undefined; + if (!asset || typeof asset !== "object") return undefined; + const { assetRevision, byteSize, mimeType } = asset as Record; + if (typeof assetRevision !== "string" || !ASSET_REVISION.test(assetRevision) || mimeType !== "image/png") return undefined; + if (typeof byteSize !== "number" || !Number.isSafeInteger(byteSize) || byteSize <= 0 || byteSize > MAX_INLINE_IMAGE_BYTES) return undefined; + return { assetRevision, byteSize }; +} diff --git a/renderer/lib/hosts/remote-images.ts b/renderer/lib/hosts/remote-images.ts index 996e0fe771..08e78b3dd3 100644 --- a/renderer/lib/hosts/remote-images.ts +++ b/renderer/lib/hosts/remote-images.ts @@ -1,5 +1,5 @@ import * as React from "react"; -import { useQueries } from "@tanstack/react-query"; +import { skipToken, useQueries, useQuery } from "@tanstack/react-query"; import type { BotTranscriptEntry } from "../../shared/bot-live"; import { MAX_INLINE_IMAGE_BYTES } from "../../shared/attachment-contract"; import type { PeerAttachmentContent } from "../../shared/peer-operation"; @@ -7,6 +7,7 @@ import { peerHostsApi } from "../ipc"; import { bytesToBase64 } from "../live-pcm-capture"; import type { Attachment, ChatMessage } from "../types"; import type { HostChatAdapter, HostChatError, HostChatResult } from "./host-chat-adapter"; +import type { RemoteBotPhotoAsset } from "./remote-bot-photo-asset"; export type { PeerAttachmentContent }; @@ -269,3 +270,34 @@ export function useRemoteBotImages( [entries, loaded, gone], ); } + +/** + * A paired host's Bot's photo, as a data URL once read, read once per asset + * revision (a new photo has a new revision). Undefined while reading, and for + * good when the host can't hand it over: the avatar's shape stays. + */ +export function useRemoteBotPhoto( + hostId: string, + botId: string, + asset: RemoteBotPhotoAsset | undefined, + enabled = true, +): string | undefined { + const query = useQuery({ + queryKey: ["host", hostId, "bot", botId, "photo", asset?.assetRevision ?? "", asset?.byteSize ?? 0], + queryFn: asset + ? () => + limited(hostId, async () => { + const result = await peerHostsApi.call(hostId, { operation: "botAvatar", resourceId: botId, itemId: asset.assetRevision }); + if (!result.ok) throw imageGone(result.error) ? new RemoteImageGone(result.error.message) : new Error(result.error.message); + const data = acceptRemoteImage({ mimeType: "image/png", size: asset.byteSize }, peerAttachmentContent(result.value)); + if (data === null) throw new RemoteImageGone("The other computer sent a different photo."); + return `data:image/png;base64,${data}`; + }) + : skipToken, + enabled, + retry: (failures: number, error: Error) => !(error instanceof RemoteImageGone) && failures < 2, + // A revision's bytes never change. + staleTime: Infinity, + }); + return asset ? query.data : undefined; +} diff --git a/renderer/lib/remote-bot-seen.test.ts b/renderer/lib/remote-bot-seen.test.ts new file mode 100644 index 0000000000..b50ecd3d03 --- /dev/null +++ b/renderer/lib/remote-bot-seen.test.ts @@ -0,0 +1,35 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + REMOTE_BOT_SEEN_LIMIT, + isRemoteBotUnread, + parseRemoteBotSeen, + serializeRemoteBotSeen, + withRemoteBotSeen, +} from "./remote-bot-seen"; + +test("a paired Mac's Bot reads unread only for a reply newer than the last one shown here, or than the record's start", () => { + const seen = parseRemoteBotSeen(null, 1_000); + assert.equal(isRemoteBotUnread(seen, "host/bot", undefined), false, "no reply time, no dot"); + assert.equal(isRemoteBotUnread(seen, "host/bot", 900), false, "a reply from before the record began is not new"); + assert.equal(isRemoteBotUnread(seen, "host/bot", 1_500), true); + const shown = withRemoteBotSeen(seen, "host/bot", 1_500); + assert.equal(isRemoteBotUnread(shown, "host/bot", 1_500), false); + assert.equal(isRemoteBotUnread(shown, "host/bot", 1_600), true); + assert.equal(isRemoteBotUnread(shown, "other/bot", 1_500), true, "each host's Bot is its own"); + assert.equal(withRemoteBotSeen(shown, "host/bot", 1_200), shown, "the seen time never moves back"); +}); + +test("the record survives a reload and refuses what it can't trust", () => { + const shown = withRemoteBotSeen(parseRemoteBotSeen(null, 1_000), "host/bot", 1_500); + assert.deepEqual(parseRemoteBotSeen(serializeRemoteBotSeen(shown), 5_000), shown); + for (const raw of ["not json", "[]", JSON.stringify({ version: 2, since: 10, seenReplyAt: {} })]) { + assert.deepEqual(parseRemoteBotSeen(raw, 5_000), { since: 5_000, seenReplyAt: {} }, raw); + } + const odd = parseRemoteBotSeen(JSON.stringify({ version: 1, since: 9_000, seenReplyAt: { a: -1, b: "x", c: 7 } }), 5_000); + assert.deepEqual(odd, { since: 5_000, seenReplyAt: { c: 7 } }, "a start in the future would hide replies, so it is clamped"); + let many = parseRemoteBotSeen(null, 1); + for (let index = 1; index <= REMOTE_BOT_SEEN_LIMIT + 5; index++) many = withRemoteBotSeen(many, `h/${index}`, index + 10); + assert.equal(Object.keys(many.seenReplyAt).length, REMOTE_BOT_SEEN_LIMIT, "only the newest are kept"); + assert.equal(many.seenReplyAt["h/1"], undefined); +}); diff --git a/renderer/lib/remote-bot-seen.ts b/renderer/lib/remote-bot-seen.ts new file mode 100644 index 0000000000..e157469d8f --- /dev/null +++ b/renderer/lib/remote-bot-seen.ts @@ -0,0 +1,122 @@ +// The newest reply of each paired Mac's Bot this Mac has shown, so a newer +// one reads as unread (the dot on its row). Kept per device in local storage, +// keyed `hostId/botId`, apart from this Mac's own Bots' preferences, which +// drop any Bot this Mac doesn't have. Times are the host's (`lastReplyAt` on +// its feed rows, revision 52), compared only with each other. `since` is when +// the record began, so a paired Mac's Bots are not all unread the first time. + +import * as React from "react"; + +export const REMOTE_BOT_SEEN_KEY = "aiden-agent.remote-bots-seen.v1"; +export const REMOTE_BOT_SEEN_LIMIT = 200; + +export interface RemoteBotSeen { + since: number; + /** The newest reply each remote Bot's chat showed here, by `hostId/botId`. */ + seenReplyAt: Readonly>; +} + +const validTime = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value) && value > 0; + +function newest(times: Record): Record { + const entries = Object.entries(times); + if (entries.length <= REMOTE_BOT_SEEN_LIMIT) return times; + return Object.fromEntries(entries.sort((left, right) => right[1] - left[1]).slice(0, REMOTE_BOT_SEEN_LIMIT)); +} + +export function parseRemoteBotSeen(raw: string | null, now: number = Date.now()): RemoteBotSeen { + const fresh = { since: now, seenReplyAt: {} }; + if (raw === null) return fresh; + let value: unknown; + try { + value = JSON.parse(raw); + } catch { + return fresh; + } + if (!value || typeof value !== "object" || Array.isArray(value)) return fresh; + const record = value as Record; + if (record.version !== 1) return fresh; + const seenReplyAt: Record = {}; + if (record.seenReplyAt && typeof record.seenReplyAt === "object" && !Array.isArray(record.seenReplyAt)) { + for (const [key, at] of Object.entries(record.seenReplyAt as Record)) { + if (key && validTime(at)) seenReplyAt[key] = at; + } + } + return { since: validTime(record.since) ? Math.min(record.since, now) : now, seenReplyAt: newest(seenReplyAt) }; +} + +export function serializeRemoteBotSeen(seen: RemoteBotSeen): string { + return JSON.stringify({ version: 1, since: seen.since, seenReplyAt: seen.seenReplyAt }); +} + +/** The remote Bot's chat showed the reply at `replyAt`; the seen time only moves forward. */ +export function withRemoteBotSeen(seen: RemoteBotSeen, key: string, replyAt: number | undefined): RemoteBotSeen { + if (replyAt === undefined || !validTime(replyAt) || replyAt <= (seen.seenReplyAt[key] ?? 0)) return seen; + return { ...seen, seenReplyAt: newest({ ...seen.seenReplyAt, [key]: replyAt }) }; +} + +/** A reply newer than the newest one its chat showed here, or than the record's start when it never showed one. */ +export function isRemoteBotUnread(seen: RemoteBotSeen, key: string, lastReplyAt: number | undefined): boolean { + return lastReplyAt !== undefined && lastReplyAt > (seen.seenReplyAt[key] ?? seen.since); +} + +// One record per window, shared by every row and chat view and kept in step +// with other windows through `storage` events. +let current: RemoteBotSeen | null = null; +const listeners = new Set<() => void>(); + +function read(): RemoteBotSeen { + if (current) return current; + let raw: string | null = null; + try { + raw = window.localStorage.getItem(REMOTE_BOT_SEEN_KEY); + } catch { + raw = null; + } + current = parseRemoteBotSeen(raw); + // Save the start time, so a reload doesn't move it and hide replies that came in between. + if (raw === null) write(current); + return current; +} + +function write(next: RemoteBotSeen): void { + current = next; + try { + window.localStorage.setItem(REMOTE_BOT_SEEN_KEY, serializeRemoteBotSeen(next)); + } catch { + // Storage is full or off: the dot still works for this window. + } + for (const listener of listeners) listener(); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + const onStorage = (event: StorageEvent) => { + if (event.key !== REMOTE_BOT_SEEN_KEY) return; + current = parseRemoteBotSeen(event.newValue); + listener(); + }; + window.addEventListener("storage", onStorage); + return () => { + listeners.delete(listener); + window.removeEventListener("storage", onStorage); + }; +} + +/** This window's record of what each paired Mac's Bot has shown. */ +export function useRemoteBotSeen(): RemoteBotSeen { + return React.useSyncExternalStore(subscribe, read, read); +} + +/** Records that the remote Bot's chat shows its reply at `replyAt`. */ +export function markRemoteBotSeen(key: string, replyAt: number | undefined): void { + const before = read(); + const next = withRemoteBotSeen(before, key, replyAt); + if (next !== before) write(next); +} + +/** Tests start each case from an empty record. */ +export function resetRemoteBotSeenForTests(): void { + current = null; +} diff --git a/renderer/main/bots/bot-sidebar.test.tsx b/renderer/main/bots/bot-sidebar.test.tsx index 2f17ddc1e9..4c2b036792 100644 --- a/renderer/main/bots/bot-sidebar.test.tsx +++ b/renderer/main/bots/bot-sidebar.test.tsx @@ -10,6 +10,7 @@ import { useCommandSystem } from "../../lib/command-system"; import type { CommandId } from "../../shared/keybindings"; import { useBotNotificationsSync } from "../../lib/bot-notifications-sync"; import { hostQueryKeys } from "../../lib/hosts/host-query-keys"; +import { resetRemoteBotSeenForTests } from "../../lib/remote-bot-seen"; import { BOT_SIDEBAR_PREFERENCES_KEY, parseBotSidebarPreferences, @@ -24,7 +25,10 @@ import { AppCapabilitiesProvider, DISABLED_APP_CAPABILITIES } from "../../lib/ap import { createBotTestQueryClient, mountWithBotRouter } from "./test-providers"; import { botFixture } from "./test-fixtures"; -beforeEach(() => localStorage.clear()); +beforeEach(() => { + localStorage.clear(); + resetRemoteBotSeenForTests(); +}); afterEach(cleanup); const PLANNER = botFixture({ id: "bot-1", name: "Planner", description: "Plans trips" }); @@ -624,6 +628,76 @@ test("a paired Mac's Bot shows when it is working there, and marks the one whose assert.ok(!working.querySelector(".bot-avatar"), "a row with no avatar keeps the stock icon"); }); +test("a paired Mac's Bot shows its last message and photo, and a new reply shows a dot until its chat is opened", async () => { + const queryClient = createBotTestQueryClient(); + queryClient.setQueryData(hostQueryKeys.list(), [ + { id: "host-b", name: "Studio", enabled: true, state: "connected", features: ["bot-durable-session-v1"], capabilities: ["chat:read", "chat:write", "bot:read", "bot:write"] }, + ]); + queryClient.setQueryData(hostQueryKeys.statuses(), [ + { hostId: "host-b", generation: 1, state: { kind: "connected", since: 1 }, feed: "live", stale: false }, + ]); + const revision = `avatar_revision_${"a".repeat(32)}`; + const feed = (lastReplyAt: string) => ({ + hostId: "host-b", + epoch: "e1", + sequence: 1, + stale: false, + summaries: [], + workspaces: [], + bots: [ + { + id: "remote-1", + name: "Scout", + purpose: "You find flights.", + avatar: { + semantic: { version: 1, shape: "orb", color: "rose" }, + asset: { assetRevision: revision, mimeType: "image/png", width: 512, height: 512, byteSize: 4 }, + }, + sessionState: "idle", + lastReplyAt, + // Another computer's text: the row shows it as one plain line. + preview: "Flights to Lisbon\nare cheaper on Tuesday", + }, + ], + runs: [], + }); + const inAMinute = () => new Date(Date.now() + 60_000).toISOString(); + queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed(inAMinute())); + const photoReads: unknown[] = []; + sidebarIpc([], {}, { + "bots:list": () => [], + "remote:peerCall": (_hostId, raw) => { + const call = raw as { operation: string; resourceId?: string; itemId?: string }; + if (call.operation !== "botAvatar") return { ok: false, error: { code: "not_found", message: "Not in this test." } }; + photoReads.push(call); + return { ok: true, value: { mimeType: "image/png", bytes: new Uint8Array([1, 2, 3, 4]) } }; + }, + }); + const { router } = await mountSidebar("/bots", queryClient); + const row = await screen.findByRole("button", { name: "Scout, on Studio, unread" }); + assert.ok(within(row).getByText("Flights to Lisbon are cheaper on Tuesday")); + assert.ok(within(row).getByRole("img", { name: "Unread", hidden: true })); + assert.equal(row.getAttribute("aria-description"), "Flights to Lisbon are cheaper on Tuesday"); + await waitFor(() => assert.equal(row.querySelector("img")?.getAttribute("src"), "data:image/png;base64,AQIDBA==")); + assert.deepEqual(photoReads, [{ operation: "botAvatar", resourceId: "remote-1", itemId: revision }]); + + await act(async () => { + await router.navigate({ to: "/host/$hostId/bots/$botId/chat", params: { hostId: "host-b", botId: "remote-1" } }); + }); + await act(async () => { + await router.navigate({ to: "/bots" }); + }); + await screen.findByRole("button", { name: "Scout, on Studio" }); + assert.ok(!within(screen.getByRole("button", { name: "Scout, on Studio" })).queryByRole("img", { name: "Unread", hidden: true })); + + // The next reply is new again. + await act(async () => { + queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed(new Date(Date.now() + 120_000).toISOString())); + }); + await screen.findByRole("button", { name: "Scout, on Studio, unread" }); + assert.equal(photoReads.length, 1, "the same photo is read once"); +}); + test("on a Bots page, a paired Mac's Bots keep up with what that Mac sends", async () => { const host = { id: "host-b", diff --git a/renderer/main/bots/bot-sidebar.tsx b/renderer/main/bots/bot-sidebar.tsx index 9860f9d086..be22a8fc6c 100644 --- a/renderer/main/bots/bot-sidebar.tsx +++ b/renderer/main/bots/bot-sidebar.tsx @@ -25,6 +25,7 @@ import { useProfile } from "../../lib/queries"; import { cn } from "../../lib/ui-utils"; import type { BotDefinition } from "../../shared/bots"; import { RemoteBotsSection, remoteBotGroupsMatching } from "../../components/remote-bots-section"; +import { BotUnreadDot } from "../../components/bot-unread-dot"; import { useRemoteBots } from "../remote-bots"; import { BotCreateMenu, useBotCreateDialogs } from "./bot-create-menu"; import { BotDeleteDialog } from "./bot-delete-dialog"; @@ -86,12 +87,6 @@ function sameRowProps(previous: RowProps, next: RowProps): boolean { ); } -/** The unread dot, inline after the name: it takes room only when it is there. */ -function UnreadDot() { - return ( - - ); -} /** The row's ⌘ number while ⌘ is held, where its ••• button sits. */ function ShortcutHint({ binding, className }: { binding: string; className: string }) { @@ -160,7 +155,7 @@ const BotRow = React.memo(function BotRow({ {row.bot.name} {/* "Needs you" outranks the dot; the row still says "Unread" to a screen reader. */} - {unread && !row.needsYou ? : null} + {unread && !row.needsYou ? : null} {line || row.needsYou ? ( @@ -245,7 +240,7 @@ const PinnedBot = React.memo(function PinnedBot({ {row.bot.name} - {row.needsYou ? : unread ? : null} + {row.needsYou ? : unread ? : null} {row.needsYou && unread ? Unread : null} {description ? ( diff --git a/renderer/main/remote-bot-chat-view.tsx b/renderer/main/remote-bot-chat-view.tsx index 643ab78101..ae3fc5d896 100644 --- a/renderer/main/remote-bot-chat-view.tsx +++ b/renderer/main/remote-bot-chat-view.tsx @@ -30,6 +30,8 @@ import { useAppCapabilities } from "../lib/app-capabilities"; import { botListLocation } from "../lib/bot-routes"; import { insertTextIntoTextarea } from "../lib/composer-type-focus"; import { hostQueryKeys } from "../lib/hosts/host-query-keys"; +import { remoteBotPhotoAsset } from "../lib/hosts/remote-bot-photo-asset"; +import { markRemoteBotSeen } from "../lib/remote-bot-seen"; import { hostServesBotHandoffs, hostSharesBotSessions } from "../lib/hosts/remote-bot-session"; import { useRemoteBotSession } from "../lib/hosts/use-remote-bot-session"; import { browserApi, peerHostsApi } from "../lib/ipc"; @@ -52,7 +54,7 @@ import { botReplyQuote } from "./bots/bot-message-actions"; import { BotPausedNotice, botPausedText } from "./bots/bot-paused-card"; import { BotStatusLine } from "./bots/bot-status-line"; import { useChatFind } from "../components/chat-find-bar"; -import { useRemoteBotImages } from "../lib/hosts/remote-images"; +import { useRemoteBotImages, useRemoteBotPhoto } from "../lib/hosts/remote-images"; /** Text files ride along in the message, as in a local Bot chat. */ function attachmentText(attachments: readonly Attachment[]): string { @@ -137,6 +139,13 @@ export function RemoteBotChatView({ hostId, botId }: { hostId: string; botId: st const toolActivitySetting = useAppearancePreference("showToolActivity"); const localBots = useBots(false, toolActivitySetting === undefined); const avatar = botAvatar(feed.data, botId); + const row = feed.data?.bots.find((bot) => bot.id === botId); + const photoUrl = useRemoteBotPhoto(hostId, botId, row ? remoteBotPhotoAsset(row) : undefined); + // The newest reply is on screen here, so it is not unread when the person leaves (revision 66 hosts send its time). + const lastReplyAt = typeof row?.lastReplyAt === "string" ? Date.parse(row.lastReplyAt) : Number.NaN; + React.useEffect(() => { + if (Number.isFinite(lastReplyAt)) markRemoteBotSeen(`${hostId}/${botId}`, lastReplyAt); + }, [hostId, botId, lastReplyAt]); // A host too old to share the conversation is told so below, without asking it. const shared = !host || hostSharesBotSessions(host); const live = useRemoteBotSession(hostId, botId, shared); @@ -217,7 +226,7 @@ export function RemoteBotChatView({ hostId, botId }: { hostId: string; botId: st title={ {name} diff --git a/renderer/main/remote-new-chat-view.test.tsx b/renderer/main/remote-new-chat-view.test.tsx index 93ebda0919..237bbc5ae7 100644 --- a/renderer/main/remote-new-chat-view.test.tsx +++ b/renderer/main/remote-new-chat-view.test.tsx @@ -4,7 +4,11 @@ import type * as React from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { DOMParser } from "@xmldom/xmldom"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { RemoteBotsSection, remoteBotGroupsMatching } from "../components/remote-bots-section"; +import { RemoteBotsSection, remoteBotGroupsMatching, remoteBotLine } from "../components/remote-bots-section"; + +/** The rows read photos through React Query, as under the app's provider. */ +const renderSection = (element: React.ReactElement) => + renderToStaticMarkup({element}); import { SCRATCH_PROJECT } from "../components/remote-new-chat-pickers"; import { CommandSystemProvider } from "../lib/command-system"; import type { HostChatCapability } from "../lib/hosts/host-chat-adapter"; @@ -270,7 +274,7 @@ test("the folder browser lists a host's shared roots, then a folder's subfolders test("Bots on paired Macs are grouped by Mac, and a Mac that cannot open them says why", () => { const render = (props: Partial>) => dom( - renderToStaticMarkup( + renderSection( ), ""); + assert.equal(renderSection(), ""); }); test("a paired Mac's paused, interrupted or model-less Bot says so, never its purpose", () => { const view = dom( - renderToStaticMarkup( + renderSection( - renderToStaticMarkup(); + renderSection(); const searched = dom(shown("pull requests")); assert.equal(searched.button(/^Reviewer, on Studio$/u) !== undefined, true); assert.equal(searched.button(/^Scribe, on Studio$/u) === undefined, true); assert.doesNotMatch(searched.text, /On Laptop/u); assert.equal(shown("zebra"), ""); }); + +test("a paired Mac's Bot's last message is its line only when nothing more pressing is", () => { + const bot = { id: "b1", name: "Scout", preview: "Flights are cheaper on Tuesday" }; + assert.deepEqual(remoteBotLine(bot), { kind: "preview", text: bot.preview, spoken: bot.preview }); + assert.equal(remoteBotLine({ ...bot, status: "paused" })?.kind, "status"); + assert.equal(remoteBotLine({ ...bot, working: true })?.kind, "working"); + assert.equal(remoteBotLine({ ...bot, working: true, needsYou: true })?.kind, "waiting"); + assert.equal(remoteBotLine({ id: "b2", name: "Quiet" }), null); +}); diff --git a/renderer/shared/chat-pending-attention.ts b/renderer/shared/chat-pending-attention.ts index e5015e2ad0..ba5bf7b95d 100644 --- a/renderer/shared/chat-pending-attention.ts +++ b/renderer/shared/chat-pending-attention.ts @@ -43,19 +43,19 @@ function stripFormatCharacters(text: string): string { } /** - * One line, at most 200 characters, ending in an ellipsis when cut. Line - * breaks become spaces; other control and invisible formatting characters - * (bidi overrides, zero-width spaces, stray tag characters) are dropped so a - * tooltip shows the text as it reads. + * One line, at most `max` characters (200 by default), ending in an ellipsis + * when cut. Line breaks become spaces; other control and invisible formatting + * characters (bidi overrides, zero-width spaces, stray tag characters) are + * dropped so a tooltip or a row shows the text as it reads. */ -export function clipPendingAttentionSummary(text: unknown): string { +export function clipPendingAttentionSummary(text: unknown, max: number = CHAT_PENDING_ATTENTION_SUMMARY_MAX): string { if (typeof text !== "string") return ""; const oneLine = stripFormatCharacters(text.replace(/\s+/gu, " ")) .replace(/ {2,}/gu, " ") .trim(); const characters = Array.from(oneLine); - return characters.length <= CHAT_PENDING_ATTENTION_SUMMARY_MAX + return characters.length <= max ? characters.join("") // A cut through a flag leaves its tag characters stray; strip them again. - : `${stripFormatCharacters(characters.slice(0, CHAT_PENDING_ATTENTION_SUMMARY_MAX - 1).join(""))}…`; + : `${stripFormatCharacters(characters.slice(0, max - 1).join(""))}…`; } diff --git a/renderer/shared/peer-operation.ts b/renderer/shared/peer-operation.ts index 0a27de4a1a..0367735139 100644 --- a/renderer/shared/peer-operation.ts +++ b/renderer/shared/peer-operation.ts @@ -26,7 +26,9 @@ export type PeerReadOperation = /** A Bot's one durable conversation (`GET /bots/{botId}/session`). */ | "botSession" /** Contract revision 45 (`bot:images`): one shared image's bytes; `itemId` is its entry. */ - | "botSessionImage"; + | "botSessionImage" + /** A Bot's photo avatar bytes (`GET /bots/{botId}/avatar/{assetRevision}`); `itemId` is the asset revision. */ + | "botAvatar"; export type PeerWriteOperation = | "createChat" | "send" @@ -99,7 +101,7 @@ export interface PeerOperation { revision?: string; } -/** `attachmentContent` and `botSessionImage` resolve to bounded image bytes instead of JSON. */ +/** `attachmentContent`, `botSessionImage` and `botAvatar` resolve to bounded image bytes instead of JSON. */ export interface PeerAttachmentContent { mimeType: "image/png" | "image/jpeg"; bytes: Uint8Array; From 393c322a0e816346b86e4cb0b163d6ce2a24d49b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:16:32 +0000 Subject: [PATCH 2/7] Keep remote Bot unread dots in the host's clock and clear them only when the chat shows the reply - A host's existing replies start read from its own newest reply time when this Mac first lists its Bots, instead of this Mac's clock, so a host whose clock is ahead or behind gets the right dots. - A reply counts as seen only once the remote chat's session view shows it, not when its row is selected or the feed alone reports it. - Register remote-bot-seen.test.ts in the CI test registry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .memory/bot-chat-activity.md | 2 +- docs/aiden-on-the-go-remote-access.md | 2 +- docs/aiden-remote-api-v1.md | 2 +- package.json | 2 +- renderer/components/remote-bots-section.tsx | 12 +-- renderer/lib/remote-bot-seen.test.ts | 72 +++++++++++---- renderer/lib/remote-bot-seen.ts | 99 ++++++++++++++++----- renderer/main/bots/bot-sidebar.test.tsx | 26 +++--- renderer/main/remote-bot-chat-view.test.tsx | 53 +++++++++++ renderer/main/remote-bot-chat-view.tsx | 17 ++-- scripts/ci-test-registry.json | 1 + 11 files changed, 222 insertions(+), 66 deletions(-) diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index f8bf89c9b4..63ec728e16 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -103,6 +103,6 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev ### Bots across Macs (2026-11-24) - PR 1 (#895, desktop only): paired Mac's Bot rows show the feed's avatar, Needs you over Thinking over stop status, never the description; `ChatSidebar` owns `usePeerHostSidebar` so feeds stay live on the Bots page; remote Bot chat only treats 404/403 as gone. -- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`), compared only against the host's own `lastReplyAt`. +- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. - Still to come: PR 3 (plan, access-request and memory cards in remote Bot chats, load older), PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). diff --git a/docs/aiden-on-the-go-remote-access.md b/docs/aiden-on-the-go-remote-access.md index 9fba82eaf9..a1dfd092a4 100644 --- a/docs/aiden-on-the-go-remote-access.md +++ b/docs/aiden-on-the-go-remote-access.md @@ -69,7 +69,7 @@ Pairing a computer gives it full control of this computer's chats: it can read t - **Visuals.** A visual the other computer pictured shows as that picture. A native visual it did not picture (any `render_ui` visual from `aiden serve`) shows as its text, line by line, where its tool call ran, with **Copy as text** and nothing inside to tap or change. An HTML visual (`render_artifact`) the other computer did not picture, for example because `aiden serve` found no Chrome, shows nothing here; the reply's text still says what it held. - **Not here.** Read-aloud is not offered for a remote chat. - **New chats.** On a new chat, choose the computer in the composer's machine picker, then one of its workspaces and models. Attachments upload to that computer. Pictures in a format the other computer does not take (WebP, GIF, BMP) are converted first, to PNG (or JPEG when that is what fits), and shrunk step by step until each is within 8 MB and the message's attachments together are within 16 MB. An animated GIF sends its first frame. HEIC photos can't be sent to another computer yet: the composer asks you to export one as a JPEG first. A picture this Mac cannot open is not sent either, and the composer says to save it as a PNG or JPEG. When the other computer runs contract revision 50 or newer, pictures go as their own bytes instead of base64 text, about a quarter less to send. -- **Bots.** Paired computers' Bots appear in the Bots area below this Mac's own, under "On ", with the avatar they have there: its shape and colour, or its photo. A row stays current on any page, including the Bots pages. Like this Mac's own rows, it shows **Needs you** and "Waiting for you" while the Bot waits on an approval, question, hand-off or issue there, "Thinking…" while a turn runs (only while that computer is online), otherwise why it stopped (Paused, Interrupted, Needs an AI model), and otherwise its last message. A new reply since the Bot's chat was last open on this Mac shows an unread dot. The last message and the dot need that computer on contract revision 66; with an older one the line stays empty. A Bot's description is never shown as its line; search still matches it. Opening one row leaves the others clickable. The open chat's title shows the Bot's avatar or photo. A chat that loses its connection reconnects on its own; it says the Bot is gone only when that computer answers that the Bot was deleted or this Mac may no longer read it, and a message sent while it reconnects shows as soon as that computer has it. Opening one shows the same single conversation its own computer, phones and Telegram show: the Bot runs there, and this Mac sends messages, Stop, Resume, Dismiss, question answers and tool approvals to it. A tool that only its own computer may allow (Computer Use) can only be denied from here. Connect cards ask the Bot's computer to finish the connection there. When the app is already connected on that computer but the Bot's Custom access leaves it out, the card still reads **Finish on **, and that opens the Bot's chat there, where its card's **Connect** adds the app to that Bot. Phones work the same way with **Finish on your Mac**. If that computer runs an older Aiden, update it; an older Mac sending to a newer computer's Bot is told to update. When the Bot's computer offers hand-offs (contract revision 37), a step the Bot hands back ("Your turn: …") can be answered from here too, in two steps: **Take control** first (it opens the page the step names, if any), then **I'm done** (with a note typed in the composer if you like), **Skip**, or **Open again** for that page. A step on the Bot's own screen over there puts **Finish on ** first, which brings it forward on that computer, then offers **Skip** and **I'm done**. A sign-in in the Bot's own browser there also starts with **Finish on **; it is answered on that computer, so here it then offers **Skip** alone. Images the Bot shares appear in its chat as pictures, read from the Bot's computer while its chat is connected (contract revision 45). The chat's **···** menu offers **Pause Bot** and **Resume Bot**, and a paused Bot shows a Resume card and holds the composer until it is resumed. Custom Bots can also ask for a folder or temporary whole-Mac file access. Current iOS and Android clients can answer those cards. A Mac viewing a paired computer’s Bot sees a notice to answer on that computer; it does not grant access itself. See [Bot access requests](bot-access-requests.md). The Assistant stays on its own computer. +- **Bots.** Paired computers' Bots appear in the Bots area below this Mac's own, under "On ", with the avatar they have there: its shape and colour, or its photo. A row stays current on any page, including the Bots pages. Like this Mac's own rows, it shows **Needs you** and "Waiting for you" while the Bot waits on an approval, question, hand-off or issue there, "Thinking…" while a turn runs (only while that computer is online), otherwise why it stopped (Paused, Interrupted, Needs an AI model), and otherwise its last message. A reply that arrives after this Mac first lists the Bot, and that its chat here hasn't shown yet, shows an unread dot. The last message and the dot need that computer on contract revision 66; with an older one the line stays empty. A Bot's description is never shown as its line; search still matches it. Opening one row leaves the others clickable. The open chat's title shows the Bot's avatar or photo. A chat that loses its connection reconnects on its own; it says the Bot is gone only when that computer answers that the Bot was deleted or this Mac may no longer read it, and a message sent while it reconnects shows as soon as that computer has it. Opening one shows the same single conversation its own computer, phones and Telegram show: the Bot runs there, and this Mac sends messages, Stop, Resume, Dismiss, question answers and tool approvals to it. A tool that only its own computer may allow (Computer Use) can only be denied from here. Connect cards ask the Bot's computer to finish the connection there. When the app is already connected on that computer but the Bot's Custom access leaves it out, the card still reads **Finish on **, and that opens the Bot's chat there, where its card's **Connect** adds the app to that Bot. Phones work the same way with **Finish on your Mac**. If that computer runs an older Aiden, update it; an older Mac sending to a newer computer's Bot is told to update. When the Bot's computer offers hand-offs (contract revision 37), a step the Bot hands back ("Your turn: …") can be answered from here too, in two steps: **Take control** first (it opens the page the step names, if any), then **I'm done** (with a note typed in the composer if you like), **Skip**, or **Open again** for that page. A step on the Bot's own screen over there puts **Finish on ** first, which brings it forward on that computer, then offers **Skip** and **I'm done**. A sign-in in the Bot's own browser there also starts with **Finish on **; it is answered on that computer, so here it then offers **Skip** alone. Images the Bot shares appear in its chat as pictures, read from the Bot's computer while its chat is connected (contract revision 45). The chat's **···** menu offers **Pause Bot** and **Resume Bot**, and a paused Bot shows a Resume card and holds the composer until it is resumed. Custom Bots can also ask for a folder or temporary whole-Mac file access. Current iOS and Android clients can answer those cards. A Mac viewing a paired computer’s Bot sees a notice to answer on that computer; it does not grant access itself. See [Bot access requests](bot-access-requests.md). The Assistant stays on its own computer. - **Not available remotely.** Terminal, the Environment browser, computer use and open-in-editor work only on the computer you are sitting at. ### Offline and identity changes diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index d14ee42e46..548f2f20e0 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1501,6 +1501,6 @@ Revision 66 is provisional: it was written when `main` was at 65, and the host k **Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads; for a Bot whose chat is closed the host keeps that summary in memory and reads the Bot's transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. -**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. +**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. **Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt` and `preview`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou` and `failed` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). diff --git a/package.json b/package.json index 856d4da295..1785437fa3 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,7 @@ "test:preflight": "npm run test:mcp && npm run test:artificial-analysis && npm run test:model-pad && tsx --test main/services/appearance-preview-core.test.ts main/services/dock-icon.test.ts main/services/generation-timeline.test.ts main/services/local-runtime-status.test.ts main/services/mcp-tool-result.test.ts main/services/pi-thinking-disclosure.integration.test.ts renderer/components/activity-feed.test.tsx renderer/components/context-meter.test.tsx renderer/components/chat-sidebar.test.tsx renderer/components/composer.test.tsx renderer/components/composer-slash-palette.test.tsx renderer/components/settings/providers-settings.test.tsx renderer/main/chat-transition.test.tsx renderer/components/reasoning-block.test.tsx renderer/components/reasoning-visibility-control.test.tsx renderer/components/thinking-control.test.tsx renderer/lib/agent-steps.test.ts renderer/lib/button-appearance-contract.test.ts renderer/lib/dialog-motion-contract.test.ts renderer/lib/scrollbar-gutter-contract.test.ts renderer/lib/scroll-follow.test.ts renderer/lib/text-entry-focus-contract.test.ts renderer/lib/pill-appearance.test.ts renderer/lib/reasoning-disclosure.test.ts renderer/lib/streaming-motion-contract.test.ts renderer/lib/streaming-reveal.test.ts renderer/components/streaming-markdown-reveal.test.tsx renderer/lib/voice-recorder-core.test.ts renderer/lib/media-recorder-stop.test.ts renderer/lib/dictation-vad.test.ts renderer/lib/dictation-sounds.test.ts renderer/pill-preload-channels.test.ts renderer/shared/anthropic-thinking.test.ts renderer/shared/app-update.test.ts renderer/shared/claim-check.test.ts renderer/shared/codex-thinking.test.ts renderer/shared/context-pressure.test.ts renderer/shared/google-thinking.test.ts renderer/shared/provider-deployment.test.ts renderer/shared/assistant-turn-stats.test.ts renderer/lib/sticky-section.test.ts", "test:chat-row-states": "tsx --test renderer/shared/chat-row-state.test.ts renderer/components/chat-row-status.test.tsx renderer/components/sidebar/chat-row.test.tsx renderer/components/sidebar/sidebar-overflow-menu.test.ts renderer/components/chat-row-context.test.tsx renderer/lib/chat-row-context.test.ts renderer/lib/use-mark-chat-read.test.ts main/services/chat-read-markers.test.ts main/handlers/chat-pending-attention.test.ts", "test:sidebar": "tsx --test renderer/components/chat-sidebar.test.tsx renderer/lib/sidebar-workspace-groups.test.ts renderer/lib/sidebar-chat-shortcuts.test.ts renderer/lib/held-modifier-reveal.test.ts renderer/lib/sidebar-organization.test.ts renderer/lib/sidebar-inbox.test.ts renderer/lib/sidebar-inbox-view.test.ts renderer/lib/inbox-triage.test.ts renderer/lib/use-inbox-triage.test.tsx main/services/chat-triage.test.ts main/services/inbox-dock-badge.test.ts renderer/components/sidebar/inbox-view.test.tsx renderer/lib/use-sidebar-view.test.tsx renderer/components/sidebar-organize-menu.test.tsx renderer/components/sidebar-remote.test.tsx renderer/lib/sidebar-remote-groups.test.ts renderer/lib/hosts/peer-host-feed-state.test.ts renderer/lib/hosts/use-peer-host-sidebar.test.tsx renderer/lib/roving-rows.test.tsx renderer/lib/range-selection.test.ts renderer/lib/focus-recovery.test.ts renderer/components/sidebar/chat-list-selection.test.tsx renderer/lib/approval-shortcuts.test.ts", - "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-queue-fence.test.ts renderer/lib/hosts/remote-turn-selection.test.ts renderer/lib/hosts/remote-bot-session.test.ts renderer/main/remote-bot-chat-view.test.tsx renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts renderer/lib/hosts/observed-local-run.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx renderer/main/remote-chat-images.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts main/services/peer-remote-chat-context.test.ts", + "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-queue-fence.test.ts renderer/lib/hosts/remote-turn-selection.test.ts renderer/lib/hosts/remote-bot-session.test.ts renderer/lib/remote-bot-seen.test.ts renderer/main/remote-bot-chat-view.test.tsx renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts renderer/lib/hosts/observed-local-run.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx renderer/main/remote-chat-images.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts main/services/peer-remote-chat-context.test.ts", "test:peer-hosts": "tsx --test main/services/peer-intent-store.test.ts main/handlers/peer-intents.test.ts main/services/peer-host-registry.test.ts main/services/peer-transport.test.ts main/services/peer-operation.test.ts main/services/peer-host-feed-cache.test.ts main/services/peer-run-subscriptions.test.ts main/services/peer-host-manager.test.ts main/handlers/peer-host-live.test.ts main/services/peer-bootstrap-transport.test.ts main/services/peer-host-pairing.test.ts main/services/peer-pairing-client.test.ts main/services/peer-discovery.test.ts main/handlers/peer-pairing.test.ts main/services/peer-lan-addresses.test.ts main/services/peer-multi-host-acceptance.test.ts main/services/peer-bot-sessions.test.ts main/services/peer-project-source.test.ts main/services/peer-project-file-io.test.ts main/handlers/peer-project-clone.test.ts renderer/shared/peer-project-clone.test.ts renderer/main/peer-project-clone-dialog.test.tsx", "pretest:aiden-remote": "npm run build:worktree-file-io", "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-durable-operation.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-bot-handoffs.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/visual-viewer-document.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-mcp-server.test.ts main/services/chat-orchestration/run-core.test.ts renderer/shared/aiden-mcp-token-env.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-lan-hostname.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/aiden-remote-approval-schedule.test.ts main/handlers/local-runs.test.ts main/services/repository-identity.test.ts renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx main/services/aiden-remote-new-worktree.test.ts main/services/aiden-remote-bot-watches.test.ts main/services/aiden-remote-bot-allowed.test.ts main/services/aiden-remote-bot-ux.test.ts main/handlers/aiden-mcp.test.ts renderer/components/settings/aiden-mcp-settings.test.tsx && node --test scripts/aiden-remote-lan-transport-spike.test.mjs", diff --git a/renderer/components/remote-bots-section.tsx b/renderer/components/remote-bots-section.tsx index 0648faea31..8ed3db6acc 100644 --- a/renderer/components/remote-bots-section.tsx +++ b/renderer/components/remote-bots-section.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import { Bot, Loader2 } from "lucide-react"; import type { NewChatMachine, RemoteBotChoice, RemoteBotGroup } from "../lib/hosts/new-chat-targets"; import { useRemoteBotPhoto } from "../lib/hosts/remote-images"; -import { isRemoteBotUnread, markRemoteBotSeen, useRemoteBotSeen } from "../lib/remote-bot-seen"; +import { isRemoteBotUnread, markRemoteBotHostListed, useRemoteBotSeen } from "../lib/remote-bot-seen"; import { matchesSearch } from "../lib/search-fold"; import { RemoteHostMarker } from "./sidebar-remote"; import { cn } from "../lib/ui-utils"; @@ -68,11 +68,11 @@ export function RemoteBotsSection({ onOpen(hostId: string, botId: string): void; }) { const seen = useRemoteBotSeen(); - // The open Bot's newest reply is on screen, so it is not unread when the person leaves. - const open = selected ? groups.flatMap(({ host, bots }) => bots.filter((bot) => `${host.id}/${bot.id}` === selected))[0] : undefined; + // The replies a host's Bots had when this Mac first lists them start read. + // The open Bot's chat records what it shows itself (`RemoteBotChatView`). React.useEffect(() => { - if (selected && open?.lastReplyAt !== undefined) markRemoteBotSeen(selected, open.lastReplyAt); - }, [selected, open?.lastReplyAt]); + for (const { host, bots } of groups) markRemoteBotHostListed(host.id, bots.map((bot) => bot.lastReplyAt)); + }, [groups]); if (groups.length === 0) return null; return (
    @@ -100,7 +100,7 @@ export function RemoteBotsSection({ bot={bot} busy={opening === key} current={current} - unread={!current && isRemoteBotUnread(seen, key, bot.lastReplyAt)} + unread={!current && isRemoteBotUnread(seen, host.id, bot.id, bot.lastReplyAt)} onOpen={onOpen} /> ); diff --git a/renderer/lib/remote-bot-seen.test.ts b/renderer/lib/remote-bot-seen.test.ts index b50ecd3d03..0c18334735 100644 --- a/renderer/lib/remote-bot-seen.test.ts +++ b/renderer/lib/remote-bot-seen.test.ts @@ -1,34 +1,72 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import type { BotTranscriptEntry } from "../shared/bot-live"; import { REMOTE_BOT_SEEN_LIMIT, isRemoteBotUnread, parseRemoteBotSeen, + remoteBotShownReplyAt, serializeRemoteBotSeen, + withRemoteBotHostListed, withRemoteBotSeen, } from "./remote-bot-seen"; -test("a paired Mac's Bot reads unread only for a reply newer than the last one shown here, or than the record's start", () => { - const seen = parseRemoteBotSeen(null, 1_000); - assert.equal(isRemoteBotUnread(seen, "host/bot", undefined), false, "no reply time, no dot"); - assert.equal(isRemoteBotUnread(seen, "host/bot", 900), false, "a reply from before the record began is not new"); - assert.equal(isRemoteBotUnread(seen, "host/bot", 1_500), true); - const shown = withRemoteBotSeen(seen, "host/bot", 1_500); - assert.equal(isRemoteBotUnread(shown, "host/bot", 1_500), false); - assert.equal(isRemoteBotUnread(shown, "host/bot", 1_600), true); - assert.equal(isRemoteBotUnread(shown, "other/bot", 1_500), true, "each host's Bot is its own"); - assert.equal(withRemoteBotSeen(shown, "host/bot", 1_200), shown, "the seen time never moves back"); +const HOUR = 3_600_000; +const NOW = Date.UTC(2026, 10, 24, 9); + +test("a paired Mac's Bot reads unread only for a reply newer than the last one shown here, or than its host's first listing", () => { + let seen = parseRemoteBotSeen(null); + assert.equal(isRemoteBotUnread(seen, "host", "bot", NOW), false, "nothing to compare with before the host is listed"); + seen = withRemoteBotHostListed(seen, "host", [NOW - 5_000, undefined, NOW]); + assert.equal(isRemoteBotUnread(seen, "host", "bot", undefined), false, "no reply time, no dot"); + assert.equal(isRemoteBotUnread(seen, "host", "bot", NOW - 5_000), false, "a reply from before the first listing is not new"); + assert.equal(isRemoteBotUnread(seen, "host", "bot", NOW + 500), true); + assert.equal(withRemoteBotHostListed(seen, "host", [NOW + 9_000]), seen, "a host's baseline is set once"); + const shown = withRemoteBotSeen(seen, "host/bot", NOW + 500); + assert.equal(isRemoteBotUnread(shown, "host", "bot", NOW + 500), false); + assert.equal(isRemoteBotUnread(shown, "host", "bot", NOW + 600), true); + assert.equal(isRemoteBotUnread(shown, "other", "bot", NOW + 500), false, "each host has its own baseline"); + assert.equal(withRemoteBotSeen(shown, "host/bot", NOW + 200), shown, "the seen time never moves back"); + assert.equal(withRemoteBotHostListed(seen, "quiet", [undefined]), seen, "a host with no reply times sets no baseline"); +}); + +test("a host whose clock is an hour ahead or behind this Mac still starts read and shows its next reply", () => { + for (const skew of [HOUR, -HOUR]) { + const hostNow = NOW + skew; + const listed = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [hostNow - 60_000, hostNow - 120_000]); + assert.equal(isRemoteBotUnread(listed, "host", "scout", hostNow - 60_000), false, `skew ${skew}: the reply already there is read`); + assert.equal(isRemoteBotUnread(listed, "host", "planner", hostNow - 120_000), false, `skew ${skew}: so is an older one`); + assert.equal(isRemoteBotUnread(listed, "host", "scout", hostNow + 1_000), true, `skew ${skew}: the next reply shows a dot`); + assert.equal(isRemoteBotUnread(listed, "host", "newbot", hostNow + 1_000), true, `skew ${skew}: so does a new Bot's first reply`); + } +}); + +test("only a reply the remote chat shows counts as seen", () => { + const user = (id: string, at: number): BotTranscriptEntry => ({ id, type: "user", text: "Hi", imageCount: 0, at }); + const reply = (id: string, at: number): BotTranscriptEntry => ({ id, type: "assistant", text: "Hello", toolCalls: [], stopReason: "stop", at }); + assert.equal(remoteBotShownReplyAt(undefined, NOW), null, "nothing read yet, nothing seen"); + assert.equal(remoteBotShownReplyAt([], NOW), null); + const older = [user("u1", NOW - 3_000), reply("a1", NOW - 2_000)]; + assert.equal(remoteBotShownReplyAt(older, NOW), NOW - 2_000, "an older snapshot shows only its own newest reply"); + assert.equal(remoteBotShownReplyAt([...older, reply("a2", NOW)], NOW), NOW, "the feed's reply once the chat shows it"); + assert.equal( + remoteBotShownReplyAt([...older, reply("a2", NOW), user("u2", NOW + 10)], NOW), + NOW, + "a later message does not claim more than the feed's reply", + ); + assert.equal(remoteBotShownReplyAt([user("u1", NOW)], undefined), null, "no reply shown, none seen"); }); test("the record survives a reload and refuses what it can't trust", () => { - const shown = withRemoteBotSeen(parseRemoteBotSeen(null, 1_000), "host/bot", 1_500); - assert.deepEqual(parseRemoteBotSeen(serializeRemoteBotSeen(shown), 5_000), shown); - for (const raw of ["not json", "[]", JSON.stringify({ version: 2, since: 10, seenReplyAt: {} })]) { - assert.deepEqual(parseRemoteBotSeen(raw, 5_000), { since: 5_000, seenReplyAt: {} }, raw); + const listed = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [NOW]); + const shown = withRemoteBotSeen(listed, "host/bot", NOW + 1); + assert.deepEqual(parseRemoteBotSeen(serializeRemoteBotSeen(shown)), shown); + for (const raw of ["not json", "[]", JSON.stringify({ version: 1, since: 10, seenReplyAt: { "host/bot": 5 } })]) { + assert.deepEqual(parseRemoteBotSeen(raw), { hostSince: {}, seenReplyAt: {} }, raw); } - const odd = parseRemoteBotSeen(JSON.stringify({ version: 1, since: 9_000, seenReplyAt: { a: -1, b: "x", c: 7 } }), 5_000); - assert.deepEqual(odd, { since: 5_000, seenReplyAt: { c: 7 } }, "a start in the future would hide replies, so it is clamped"); - let many = parseRemoteBotSeen(null, 1); + const odd = parseRemoteBotSeen(JSON.stringify({ version: 2, hostSince: { h: "x", g: 4 }, seenReplyAt: { a: -1, b: "x", c: 7 } })); + assert.deepEqual(odd, { hostSince: { g: 4 }, seenReplyAt: { c: 7 } }); + let many = parseRemoteBotSeen(null); for (let index = 1; index <= REMOTE_BOT_SEEN_LIMIT + 5; index++) many = withRemoteBotSeen(many, `h/${index}`, index + 10); assert.equal(Object.keys(many.seenReplyAt).length, REMOTE_BOT_SEEN_LIMIT, "only the newest are kept"); assert.equal(many.seenReplyAt["h/1"], undefined); diff --git a/renderer/lib/remote-bot-seen.ts b/renderer/lib/remote-bot-seen.ts index e157469d8f..cd1ff48e94 100644 --- a/renderer/lib/remote-bot-seen.ts +++ b/renderer/lib/remote-bot-seen.ts @@ -1,17 +1,22 @@ // The newest reply of each paired Mac's Bot this Mac has shown, so a newer // one reads as unread (the dot on its row). Kept per device in local storage, // keyed `hostId/botId`, apart from this Mac's own Bots' preferences, which -// drop any Bot this Mac doesn't have. Times are the host's (`lastReplyAt` on -// its feed rows, revision 52), compared only with each other. `since` is when -// the record began, so a paired Mac's Bots are not all unread the first time. +// drop any Bot this Mac doesn't have. Every time here is the host's +// (`lastReplyAt` on its feed rows, revision 52, and its session entries' +// `createdAt`), never this Mac's clock, so a host whose clock is ahead or +// behind still gets the right dots. `hostSince` is the newest reply a host's +// Bots had when this Mac first listed them: those replies start read. import * as React from "react"; +import { botLastReplyAt } from "../shared/bot-live"; +import type { BotTranscriptEntry } from "../shared/bot-live"; export const REMOTE_BOT_SEEN_KEY = "aiden-agent.remote-bots-seen.v1"; export const REMOTE_BOT_SEEN_LIMIT = 200; export interface RemoteBotSeen { - since: number; + /** Each host's newest reply when this Mac first listed its Bots, by host id. */ + hostSince: Readonly>; /** The newest reply each remote Bot's chat showed here, by `hostId/botId`. */ seenReplyAt: Readonly>; } @@ -25,8 +30,17 @@ function newest(times: Record): Record { return Object.fromEntries(entries.sort((left, right) => right[1] - left[1]).slice(0, REMOTE_BOT_SEEN_LIMIT)); } -export function parseRemoteBotSeen(raw: string | null, now: number = Date.now()): RemoteBotSeen { - const fresh = { since: now, seenReplyAt: {} }; +function times(value: unknown): Record { + const out: Record = {}; + if (!value || typeof value !== "object" || Array.isArray(value)) return out; + for (const [key, at] of Object.entries(value as Record)) { + if (key && validTime(at)) out[key] = at; + } + return newest(out); +} + +export function parseRemoteBotSeen(raw: string | null): RemoteBotSeen { + const fresh = { hostSince: {}, seenReplyAt: {} }; if (raw === null) return fresh; let value: unknown; try { @@ -36,18 +50,28 @@ export function parseRemoteBotSeen(raw: string | null, now: number = Date.now()) } if (!value || typeof value !== "object" || Array.isArray(value)) return fresh; const record = value as Record; - if (record.version !== 1) return fresh; - const seenReplyAt: Record = {}; - if (record.seenReplyAt && typeof record.seenReplyAt === "object" && !Array.isArray(record.seenReplyAt)) { - for (const [key, at] of Object.entries(record.seenReplyAt as Record)) { - if (key && validTime(at)) seenReplyAt[key] = at; - } - } - return { since: validTime(record.since) ? Math.min(record.since, now) : now, seenReplyAt: newest(seenReplyAt) }; + if (record.version !== 2) return fresh; + return { hostSince: times(record.hostSince), seenReplyAt: times(record.seenReplyAt) }; } export function serializeRemoteBotSeen(seen: RemoteBotSeen): string { - return JSON.stringify({ version: 1, since: seen.since, seenReplyAt: seen.seenReplyAt }); + return JSON.stringify({ version: 2, hostSince: seen.hostSince, seenReplyAt: seen.seenReplyAt }); +} + +/** + * The first time this Mac lists a host's Bots, their replies so far start + * read: the host's newest reply becomes its baseline. A host whose Bots have + * no reply times yet gets none, and its Bots show no dot until one is set. + */ +export function withRemoteBotHostListed( + seen: RemoteBotSeen, + hostId: string, + replyTimes: readonly (number | undefined)[], +): RemoteBotSeen { + if (seen.hostSince[hostId] !== undefined) return seen; + const known = replyTimes.filter(validTime); + if (known.length === 0) return seen; + return { ...seen, hostSince: newest({ ...seen.hostSince, [hostId]: Math.max(...known) }) }; } /** The remote Bot's chat showed the reply at `replyAt`; the seen time only moves forward. */ @@ -56,9 +80,35 @@ export function withRemoteBotSeen(seen: RemoteBotSeen, key: string, replyAt: num return { ...seen, seenReplyAt: newest({ ...seen.seenReplyAt, [key]: replyAt }) }; } -/** A reply newer than the newest one its chat showed here, or than the record's start when it never showed one. */ -export function isRemoteBotUnread(seen: RemoteBotSeen, key: string, lastReplyAt: number | undefined): boolean { - return lastReplyAt !== undefined && lastReplyAt > (seen.seenReplyAt[key] ?? seen.since); +/** A reply newer than the newest one its chat showed here, or than its host's baseline when it never showed one. */ +export function isRemoteBotUnread( + seen: RemoteBotSeen, + hostId: string, + botId: string, + lastReplyAt: number | undefined, +): boolean { + const baseline = seen.seenReplyAt[`${hostId}/${botId}`] ?? seen.hostSince[hostId]; + return lastReplyAt !== undefined && baseline !== undefined && lastReplyAt > baseline; +} + +/** + * The newest reply a remote Bot's chat shows, in the host's clock: the feed's + * `lastReplyAt` once the shown session reaches it, otherwise the newest reply + * among the shown entries. Null while nothing is shown, so a slow or failed + * read never clears a dot for a reply the person hasn't seen. + */ +export function remoteBotShownReplyAt( + entries: readonly BotTranscriptEntry[] | undefined, + feedLastReplyAt: number | undefined, +): number | null { + if (!entries || entries.length === 0) return null; + let reached = -Infinity; + for (const entry of entries) { + const at = (entry as { at?: number }).at; + if (at !== undefined && at > reached) reached = at; + } + if (feedLastReplyAt !== undefined && validTime(feedLastReplyAt) && reached >= feedLastReplyAt) return feedLastReplyAt; + return botLastReplyAt(entries); } // One record per window, shared by every row and chat view and kept in step @@ -75,8 +125,6 @@ function read(): RemoteBotSeen { raw = null; } current = parseRemoteBotSeen(raw); - // Save the start time, so a reload doesn't move it and hide replies that came in between. - if (raw === null) write(current); return current; } @@ -109,10 +157,17 @@ export function useRemoteBotSeen(): RemoteBotSeen { return React.useSyncExternalStore(subscribe, read, read); } +/** Sets a host's baseline the first time its Bots are listed here (`withRemoteBotHostListed`). */ +export function markRemoteBotHostListed(hostId: string, replyTimes: readonly (number | undefined)[]): void { + const before = read(); + const next = withRemoteBotHostListed(before, hostId, replyTimes); + if (next !== before) write(next); +} + /** Records that the remote Bot's chat shows its reply at `replyAt`. */ -export function markRemoteBotSeen(key: string, replyAt: number | undefined): void { +export function markRemoteBotSeen(key: string, replyAt: number | null | undefined): void { const before = read(); - const next = withRemoteBotSeen(before, key, replyAt); + const next = withRemoteBotSeen(before, key, replyAt ?? undefined); if (next !== before) write(next); } diff --git a/renderer/main/bots/bot-sidebar.test.tsx b/renderer/main/bots/bot-sidebar.test.tsx index 4c2b036792..73363f8ca9 100644 --- a/renderer/main/bots/bot-sidebar.test.tsx +++ b/renderer/main/bots/bot-sidebar.test.tsx @@ -628,7 +628,7 @@ test("a paired Mac's Bot shows when it is working there, and marks the one whose assert.ok(!working.querySelector(".bot-avatar"), "a row with no avatar keeps the stock icon"); }); -test("a paired Mac's Bot shows its last message and photo, and a new reply shows a dot until its chat is opened", async () => { +test("a paired Mac's Bot shows its last message and photo, and only a reply after it was first listed shows a dot", async () => { const queryClient = createBotTestQueryClient(); queryClient.setQueryData(hostQueryKeys.list(), [ { id: "host-b", name: "Studio", enabled: true, state: "connected", features: ["bot-durable-session-v1"], capabilities: ["chat:read", "chat:write", "bot:read", "bot:write"] }, @@ -661,8 +661,9 @@ test("a paired Mac's Bot shows its last message and photo, and a new reply shows ], runs: [], }); - const inAMinute = () => new Date(Date.now() + 60_000).toISOString(); - queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed(inAMinute())); + // The host's clock is a day ahead of this Mac's: only its own times are compared. + const hostTime = (offset: number) => new Date(Date.now() + 86_400_000 + offset).toISOString(); + queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed(hostTime(0))); const photoReads: unknown[] = []; sidebarIpc([], {}, { "bots:list": () => [], @@ -674,25 +675,28 @@ test("a paired Mac's Bot shows its last message and photo, and a new reply shows }, }); const { router } = await mountSidebar("/bots", queryClient); - const row = await screen.findByRole("button", { name: "Scout, on Studio, unread" }); + // The reply already there when this Mac first lists the Bot starts read. + const row = await screen.findByRole("button", { name: "Scout, on Studio" }); assert.ok(within(row).getByText("Flights to Lisbon are cheaper on Tuesday")); - assert.ok(within(row).getByRole("img", { name: "Unread", hidden: true })); + assert.ok(!within(row).queryByRole("img", { name: "Unread", hidden: true })); assert.equal(row.getAttribute("aria-description"), "Flights to Lisbon are cheaper on Tuesday"); await waitFor(() => assert.equal(row.querySelector("img")?.getAttribute("src"), "data:image/png;base64,AQIDBA==")); assert.deepEqual(photoReads, [{ operation: "botAvatar", resourceId: "remote-1", itemId: revision }]); + // The next reply is new. await act(async () => { - await router.navigate({ to: "/host/$hostId/bots/$botId/chat", params: { hostId: "host-b", botId: "remote-1" } }); + queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed(hostTime(60_000))); }); + const unread = await screen.findByRole("button", { name: "Scout, on Studio, unread" }); + assert.ok(within(unread).getByRole("img", { name: "Unread", hidden: true })); + + // The open Bot shows no dot, but choosing it is not seeing the reply: only its chat showing it is. await act(async () => { - await router.navigate({ to: "/bots" }); + await router.navigate({ to: "/host/$hostId/bots/$botId/chat", params: { hostId: "host-b", botId: "remote-1" } }); }); await screen.findByRole("button", { name: "Scout, on Studio" }); - assert.ok(!within(screen.getByRole("button", { name: "Scout, on Studio" })).queryByRole("img", { name: "Unread", hidden: true })); - - // The next reply is new again. await act(async () => { - queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed(new Date(Date.now() + 120_000).toISOString())); + await router.navigate({ to: "/bots" }); }); await screen.findByRole("button", { name: "Scout, on Studio, unread" }); assert.equal(photoReads.length, 1, "the same photo is read once"); diff --git a/renderer/main/remote-bot-chat-view.test.tsx b/renderer/main/remote-bot-chat-view.test.tsx index 81f3b5b683..c3cab6856f 100644 --- a/renderer/main/remote-bot-chat-view.test.tsx +++ b/renderer/main/remote-bot-chat-view.test.tsx @@ -9,6 +9,8 @@ import type { PeerHostView } from "../shared/peer-host"; import type { PeerOperation } from "../shared/peer-operation"; import { RemoteBotChatView } from "./remote-bot-chat-view"; import { clearHandoffTaken } from "../components/bots/handoff-taken"; +import { RemoteBotsSection } from "../components/remote-bots-section"; +import { REMOTE_BOT_SEEN_KEY, resetRemoteBotSeenForTests } from "../lib/remote-bot-seen"; import { AIDEN_CONTENT_REGIONS_SOURCE, type AidenContentRegionFacts, @@ -574,3 +576,54 @@ test("a shared image whose bytes cannot be read from the other computer says wha assert.ok(await screen.findByText(/I shared an image: dentist-map\.png\. Open this chat on its computer to see it\./)); assert.ok(!screen.queryByRole("img", { name: "dentist-map.png" }), "no image drawn"); }); + +test("a paired Mac's Bot's dot clears only once its chat shows the new reply", async () => { + const before = Date.parse("2026-11-24T08:00:00.000Z"); + const replyAt = "2026-11-24T09:00:00.000Z"; + for (const shows of [false, true]) { + cleanup(); + localStorage.clear(); + resetRemoteBotSeenForTests(); + // This Mac first listed the host's Bots before the reply came. + localStorage.setItem(REMOTE_BOT_SEEN_KEY, JSON.stringify({ version: 2, hostSince: { host_a: before }, seenReplyAt: {} })); + const entries = [ + { type: "message", id: "m1", role: "user", text: "What is on today?", createdAt: "2026-11-24T07:59:00.000Z" }, + { type: "message", id: "m2", role: "assistant", text: "Two meetings and a dentist.", createdAt: "2026-11-24T08:00:00.000Z" }, + ...(shows ? [{ type: "message", id: "m3", role: "assistant", text: "The dentist moved to Friday.", createdAt: replyAt }] : []), + ]; + installBotTestIpc({ + "remote:peerBotSessionSubscribe": () => ({ subscriptionId: "bot_sub_1", state: "streaming" }), + "remote:peerBotSessionUnsubscribe": () => true, + "remote:peerCall": (_hostId, operation) => + (operation as PeerOperation).operation === "botSession" + ? { ok: true, value: { ...SESSION, entries } } + : { ok: false, error: { code: "failed", message: "Not in this test." } }, + }); + const queryClient = createBotTestQueryClient(); + queryClient.setQueryData(hostQueryKeys.list(), [HOST]); + queryClient.setQueryData(hostQueryKeys.feed("host_a"), { + bots: [{ id: "bot_1", name: "Planner", lastReplyAt: replyAt }], + chats: [], + runs: [], + }); + const groups = [ + { + host: { id: "host_a", label: "Studio", availability: "online" as const }, + bots: [{ id: "bot_1", name: "Planner", lastReplyAt: Date.parse(replyAt) }], + }, + ]; + await mountWithBotRouter(, { + initialPath: "/bots", + queryClient, + sidebar: undefined} />, + }); + await screen.findByText("Two meetings and a dentist."); + if (shows) { + await screen.findByText("The dentist moved to Friday."); + await screen.findByRole("button", { name: "Planner, on Studio" }); + } else { + // An older snapshot of the chat: the reply it doesn't show stays unread. + assert.ok(screen.getByRole("button", { name: "Planner, on Studio, unread" })); + } + } +}); diff --git a/renderer/main/remote-bot-chat-view.tsx b/renderer/main/remote-bot-chat-view.tsx index ae3fc5d896..980f79828e 100644 --- a/renderer/main/remote-bot-chat-view.tsx +++ b/renderer/main/remote-bot-chat-view.tsx @@ -31,7 +31,7 @@ import { botListLocation } from "../lib/bot-routes"; import { insertTextIntoTextarea } from "../lib/composer-type-focus"; import { hostQueryKeys } from "../lib/hosts/host-query-keys"; import { remoteBotPhotoAsset } from "../lib/hosts/remote-bot-photo-asset"; -import { markRemoteBotSeen } from "../lib/remote-bot-seen"; +import { markRemoteBotSeen, remoteBotShownReplyAt } from "../lib/remote-bot-seen"; import { hostServesBotHandoffs, hostSharesBotSessions } from "../lib/hosts/remote-bot-session"; import { useRemoteBotSession } from "../lib/hosts/use-remote-bot-session"; import { browserApi, peerHostsApi } from "../lib/ipc"; @@ -141,14 +141,19 @@ export function RemoteBotChatView({ hostId, botId }: { hostId: string; botId: st const avatar = botAvatar(feed.data, botId); const row = feed.data?.bots.find((bot) => bot.id === botId); const photoUrl = useRemoteBotPhoto(hostId, botId, row ? remoteBotPhotoAsset(row) : undefined); - // The newest reply is on screen here, so it is not unread when the person leaves (revision 66 hosts send its time). - const lastReplyAt = typeof row?.lastReplyAt === "string" ? Date.parse(row.lastReplyAt) : Number.NaN; - React.useEffect(() => { - if (Number.isFinite(lastReplyAt)) markRemoteBotSeen(`${hostId}/${botId}`, lastReplyAt); - }, [hostId, botId, lastReplyAt]); // A host too old to share the conversation is told so below, without asking it. const shared = !host || hostSharesBotSessions(host); const live = useRemoteBotSession(hostId, botId, shared); + // The newest reply the chat shows is not unread when the person leaves. Only + // what the session shows counts, never the feed alone (revision 52 hosts send `lastReplyAt`). + const feedReplyAt = typeof row?.lastReplyAt === "string" ? Date.parse(row.lastReplyAt) : Number.NaN; + const shownReplyAt = remoteBotShownReplyAt( + live.view?.snapshot.entries, + Number.isFinite(feedReplyAt) ? feedReplyAt : undefined, + ); + React.useEffect(() => { + markRemoteBotSeen(`${hostId}/${botId}`, shownReplyAt); + }, [hostId, botId, shownReplyAt]); const { busy, run } = useBusyOperations(); const composerRef = React.useRef(null); const findBar = useChatFind(`${hostId}/${botId}`); diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index 9a25e68400..af8c7278f3 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -1307,6 +1307,7 @@ "renderer/lib/profile-share-data.test.ts", "renderer/lib/query-client.test.ts", "renderer/lib/remote-approval.test.ts", + "renderer/lib/remote-bot-seen.test.ts", "renderer/lib/remote-connection-status.test.ts", "renderer/lib/remote-pairing-lifecycle.test.ts", "renderer/lib/remote-settings-polling.test.ts", From 2ae5adb4b8062b9eb5025445dc673120b7c2e0c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:46:39 +0000 Subject: [PATCH 3/7] Show a dot for the first reply of a paired Mac's Bots that hadn't replied yet A host first listed with Bots but no reply times set no baseline, so the next listing took the first real reply as the baseline and it never read as unread. Such a host now gets a baseline of 0, kept across reloads. An empty list still sets nothing, since the host's Bots may not have arrived. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- renderer/lib/remote-bot-seen.test.ts | 16 +++++++++++++--- renderer/lib/remote-bot-seen.ts | 23 ++++++++++++++--------- 3 files changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 548f2f20e0..7fad445c21 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1501,6 +1501,6 @@ Revision 66 is provisional: it was written when `main` was at 65, and the host k **Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads; for a Bot whose chat is closed the host keeps that summary in memory and reads the Bot's transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. -**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. +**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. **Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt` and `preview`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou` and `failed` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). diff --git a/renderer/lib/remote-bot-seen.test.ts b/renderer/lib/remote-bot-seen.test.ts index 0c18334735..7c20ad7b7b 100644 --- a/renderer/lib/remote-bot-seen.test.ts +++ b/renderer/lib/remote-bot-seen.test.ts @@ -27,7 +27,17 @@ test("a paired Mac's Bot reads unread only for a reply newer than the last one s assert.equal(isRemoteBotUnread(shown, "host", "bot", NOW + 600), true); assert.equal(isRemoteBotUnread(shown, "other", "bot", NOW + 500), false, "each host has its own baseline"); assert.equal(withRemoteBotSeen(shown, "host/bot", NOW + 200), shown, "the seen time never moves back"); - assert.equal(withRemoteBotHostListed(seen, "quiet", [undefined]), seen, "a host with no reply times sets no baseline"); + assert.equal(withRemoteBotHostListed(seen, "quiet", []), seen, "a host with no Bots listed yet sets no baseline"); +}); + +test("a host whose Bots hadn't replied when first listed shows a dot for their first reply, also after a reload", () => { + let seen = withRemoteBotHostListed(parseRemoteBotSeen(null), "quiet", [undefined, undefined]); + // The next feed update brings the first reply; listing again must not swallow it. + seen = withRemoteBotHostListed(seen, "quiet", [NOW]); + assert.equal(isRemoteBotUnread(seen, "quiet", "bot", NOW), true); + const reloaded = parseRemoteBotSeen(serializeRemoteBotSeen(seen)); + assert.equal(isRemoteBotUnread(withRemoteBotHostListed(reloaded, "quiet", [NOW]), "quiet", "bot", NOW), true); + assert.equal(isRemoteBotUnread(withRemoteBotSeen(reloaded, "quiet/bot", NOW), "quiet", "bot", NOW), false); }); test("a host whose clock is an hour ahead or behind this Mac still starts read and shows its next reply", () => { @@ -64,8 +74,8 @@ test("the record survives a reload and refuses what it can't trust", () => { for (const raw of ["not json", "[]", JSON.stringify({ version: 1, since: 10, seenReplyAt: { "host/bot": 5 } })]) { assert.deepEqual(parseRemoteBotSeen(raw), { hostSince: {}, seenReplyAt: {} }, raw); } - const odd = parseRemoteBotSeen(JSON.stringify({ version: 2, hostSince: { h: "x", g: 4 }, seenReplyAt: { a: -1, b: "x", c: 7 } })); - assert.deepEqual(odd, { hostSince: { g: 4 }, seenReplyAt: { c: 7 } }); + const odd = parseRemoteBotSeen(JSON.stringify({ version: 2, hostSince: { h: "x", g: 4, z: 0, n: -1 }, seenReplyAt: { a: -1, b: "x", c: 7, d: 0 } })); + assert.deepEqual(odd, { hostSince: { g: 4, z: 0 }, seenReplyAt: { c: 7 } }); let many = parseRemoteBotSeen(null); for (let index = 1; index <= REMOTE_BOT_SEEN_LIMIT + 5; index++) many = withRemoteBotSeen(many, `h/${index}`, index + 10); assert.equal(Object.keys(many.seenReplyAt).length, REMOTE_BOT_SEEN_LIMIT, "only the newest are kept"); diff --git a/renderer/lib/remote-bot-seen.ts b/renderer/lib/remote-bot-seen.ts index cd1ff48e94..187bc1ed0a 100644 --- a/renderer/lib/remote-bot-seen.ts +++ b/renderer/lib/remote-bot-seen.ts @@ -5,7 +5,8 @@ // (`lastReplyAt` on its feed rows, revision 52, and its session entries' // `createdAt`), never this Mac's clock, so a host whose clock is ahead or // behind still gets the right dots. `hostSince` is the newest reply a host's -// Bots had when this Mac first listed them: those replies start read. +// Bots had when this Mac first listed them: those replies start read. A host +// first listed with Bots but no replies gets 0, so its first reply is unread. import * as React from "react"; import { botLastReplyAt } from "../shared/bot-live"; @@ -15,7 +16,7 @@ export const REMOTE_BOT_SEEN_KEY = "aiden-agent.remote-bots-seen.v1"; export const REMOTE_BOT_SEEN_LIMIT = 200; export interface RemoteBotSeen { - /** Each host's newest reply when this Mac first listed its Bots, by host id. */ + /** Each host's newest reply when this Mac first listed its Bots (0 when none had replied), by host id. */ hostSince: Readonly>; /** The newest reply each remote Bot's chat showed here, by `hostId/botId`. */ seenReplyAt: Readonly>; @@ -30,11 +31,13 @@ function newest(times: Record): Record { return Object.fromEntries(entries.sort((left, right) => right[1] - left[1]).slice(0, REMOTE_BOT_SEEN_LIMIT)); } -function times(value: unknown): Record { +const validBaseline = (value: unknown): value is number => value === 0 || validTime(value); + +function times(value: unknown, valid: (at: unknown) => at is number = validTime): Record { const out: Record = {}; if (!value || typeof value !== "object" || Array.isArray(value)) return out; for (const [key, at] of Object.entries(value as Record)) { - if (key && validTime(at)) out[key] = at; + if (key && valid(at)) out[key] = at; } return newest(out); } @@ -51,7 +54,7 @@ export function parseRemoteBotSeen(raw: string | null): RemoteBotSeen { if (!value || typeof value !== "object" || Array.isArray(value)) return fresh; const record = value as Record; if (record.version !== 2) return fresh; - return { hostSince: times(record.hostSince), seenReplyAt: times(record.seenReplyAt) }; + return { hostSince: times(record.hostSince, validBaseline), seenReplyAt: times(record.seenReplyAt) }; } export function serializeRemoteBotSeen(seen: RemoteBotSeen): string { @@ -60,8 +63,9 @@ export function serializeRemoteBotSeen(seen: RemoteBotSeen): string { /** * The first time this Mac lists a host's Bots, their replies so far start - * read: the host's newest reply becomes its baseline. A host whose Bots have - * no reply times yet gets none, and its Bots show no dot until one is set. + * read: the host's newest reply becomes its baseline. Bots with no reply yet + * get a baseline of 0, so the first reply that arrives later is unread. An + * empty list sets nothing: the host's Bots may not have arrived yet. */ export function withRemoteBotHostListed( seen: RemoteBotSeen, @@ -69,9 +73,10 @@ export function withRemoteBotHostListed( replyTimes: readonly (number | undefined)[], ): RemoteBotSeen { if (seen.hostSince[hostId] !== undefined) return seen; + if (replyTimes.length === 0) return seen; const known = replyTimes.filter(validTime); - if (known.length === 0) return seen; - return { ...seen, hostSince: newest({ ...seen.hostSince, [hostId]: Math.max(...known) }) }; + const since = known.length === 0 ? 0 : Math.max(...known); + return { ...seen, hostSince: newest({ ...seen.hostSince, [hostId]: since }) }; } /** The remote Bot's chat showed the reply at `replyAt`; the seen time only moves forward. */ From 1e8e00e17057c4f081b6c4b37385dd94e6fdfea2 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 11:17:15 -0500 Subject: [PATCH 4/7] Keep each paired Bot's host-feed signals until that Bot changes, and wait for a revision 66 listing before setting a host's unread baseline --- .memory/bot-chat-activity.md | 2 +- docs/aiden-remote-api-v1.md | 4 +- main/platform.ts | 17 +++-- main/services/aiden-remote-host-feed.test.ts | 53 +++++++++++++++ main/services/aiden-remote-host-feed.ts | 71 ++++++++++++++++++++ main/services/aiden-remote-service-main.ts | 25 +++---- renderer/components/remote-bots-section.tsx | 2 +- renderer/lib/remote-bot-seen.test.ts | 45 +++++++++---- renderer/lib/remote-bot-seen.ts | 29 ++++++-- 9 files changed, 209 insertions(+), 39 deletions(-) diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index 63ec728e16..a8150498b8 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -103,6 +103,6 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev ### Bots across Macs (2026-11-24) - PR 1 (#895, desktop only): paired Mac's Bot rows show the feed's avatar, Needs you over Thinking over stop status, never the description; `ChatSidebar` owns `usePeerHostSidebar` so feeds stay live on the Bots page; remote Bot chat only treats 404/403 as gone. -- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. +- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. The host baseline is taken only from a listing with a `preview` (proof of revision 66), since an older host sends `lastReplyAt` only for open feeds. Host feed Bot signals are cached per Bot (`createHostFeedBotSignalsCache` in `aiden-remote-host-feed.ts`) and invalidated by that Bot's `bots:changed` / `bots:attention`; `onBroadcast` forwards only the `botId` of a `bots:*` payload. - Still to come: PR 3 (plan, access-request and memory cards in remote Bot chats, load older), PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 7fad445c21..5573b0bb31 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1499,8 +1499,8 @@ Revision 65 was claimed on 2026-11-18, when `main` was at 64. The host keeps it Revision 66 is provisional: it was written when `main` was at 65, and the host keeps it in one constant (`AIDEN_REMOTE_BOT_FEED_PREVIEW_CONTRACT_REVISION`), so claiming the next free number at merge changes only that constant. It needs no capability or feature token. -**Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads; for a Bot whose chat is closed the host keeps that summary in memory and reads the Bot's transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. +**Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads. The feed keeps each Bot's summary until that Bot itself changes (a state change, a wait beginning or ending, or an edit: the same events the host's own Bots list re-reads a row on), so a chat or workspace change re-reads no Bot, and for a Bot whose chat is closed the host reads the transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. -**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. +**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). It takes that baseline only from a listing with a `preview`, which shows the host is on revision 66 and reports every Bot's reply: an older host would give too low a baseline, so its earlier replies would read as new once it upgrades. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. **Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt` and `preview`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou` and `failed` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). diff --git a/main/platform.ts b/main/platform.ts index 63b3b7db72..90dfb2bbbe 100644 --- a/main/platform.ts +++ b/main/platform.ts @@ -66,14 +66,16 @@ export const logger = { error: (scope: string, ...values: LogValue[]) => writeLog("error", scope, values), }; -const broadcastObservers = new Set<(channel: NotificationChannel) => void>(); +type BroadcastObserver = (channel: NotificationChannel, botId?: string) => void; +const broadcastObservers = new Set(); /** * Observe renderer notifications in the main process (the Remote host feed * uses this to learn that chats, workspaces or Bots changed). Payloads are - * deliberately not forwarded. + * deliberately not forwarded; a `bots:*` notice passes only the id of the Bot + * it names, so an observer can re-read that one Bot. */ -export function onBroadcast(observer: (channel: NotificationChannel) => void): () => void { +export function onBroadcast(observer: BroadcastObserver): () => void { broadcastObservers.add(observer); return () => broadcastObservers.delete(observer); } @@ -104,10 +106,17 @@ export function registerBroadcastReceiver( window.once("closed", () => broadcastReceivers.unregister(window)); } +function broadcastBotId(channel: NotificationChannel, payload: unknown): string | undefined { + if (!channel.startsWith("bots:") || typeof payload !== "object" || payload === null) return undefined; + const botId = (payload as { botId?: unknown }).botId; + return typeof botId === "string" ? botId : undefined; +} + function broadcast(channel: NotificationChannel, payload: unknown): void { + const botId = broadcastBotId(channel, payload); for (const observer of [...broadcastObservers]) { try { - observer(channel); + observer(channel, botId); } catch (error) { logger.warn("ipc", `A ${channel} observer failed.`, error); } diff --git a/main/services/aiden-remote-host-feed.test.ts b/main/services/aiden-remote-host-feed.test.ts index 77de2c239d..1efaa62c13 100644 --- a/main/services/aiden-remote-host-feed.test.ts +++ b/main/services/aiden-remote-host-feed.test.ts @@ -4,6 +4,7 @@ import type { ServerResponse } from "node:http"; import test from "node:test"; import { AidenRemoteHostFeedService, + createHostFeedBotSignalsCache, hostFeedBotSignals, type AidenRemoteHostFeedState, } from "./aiden-remote-host-feed.js"; @@ -735,6 +736,58 @@ test("a Bot row's Inbox signals hold only what its live summary says", () => { assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: 1.5 }), {}, "a fractional time is unknown"); }); +test("a refresh reads again only the Bots whose own change arrived, and never keeps a failed or overtaken read", async () => { + const reads = new Map(); + const replies = new Map([["a", 1_000], ["b", 2_000]]); + let failNext: string | undefined; + let hold: { botId: string; release: () => void } | undefined; + const cache = createHostFeedBotSignalsCache({ + summary: async (botId) => { + reads.set(botId, (reads.get(botId) ?? 0) + 1); + if (failNext === botId) { + failNext = undefined; + throw Object.assign(new Error("busy"), { code: "EBUSY" }); + } + const lastReplyAt = replies.get(botId) ?? null; + if (hold?.botId === botId) await new Promise((resolve) => { hold!.release = resolve; }); + return { state: { kind: "idle" } as BotSessionState, needsYou: false, lastReplyAt }; + }, + }); + const bots = [{ id: "a" }, { id: "b" }]; + const replyOf = async (botId: string) => (await cache.signals(bots)).get(botId)?.lastReplyAt; + + assert.equal(await replyOf("a"), new Date(1_000).toISOString()); + await cache.signals(bots); + await cache.signals(bots); + assert.deepEqual(Object.fromEntries(reads), { a: 1, b: 1 }, "unchanged Bots are not read again"); + + replies.set("a", 5_000); + assert.equal(await replyOf("a"), new Date(1_000).toISOString(), "kept until the Bot itself changes"); + cache.invalidate("a"); + assert.equal(await replyOf("a"), new Date(5_000).toISOString()); + assert.deepEqual(Object.fromEntries(reads), { a: 2, b: 1 }, "only the changed Bot is read again"); + + cache.invalidate(); + await cache.signals(bots); + assert.deepEqual(Object.fromEntries(reads), { a: 3, b: 2 }, "a change naming no Bot reads every Bot"); + + cache.invalidate("b"); + failNext = "b"; + assert.deepEqual((await cache.signals(bots)).get("b"), {}, "a failed read sends the row without signals"); + assert.equal(await replyOf("b"), new Date(2_000).toISOString(), "and is read again next refresh"); + + cache.invalidate("a"); + hold = { botId: "a", release: () => undefined }; + const overtaken = cache.signals(bots); + await new Promise((resolve) => setImmediate(resolve)); + replies.set("a", 9_000); + cache.invalidate("a"); + hold.release(); + hold = undefined; + assert.equal((await overtaken).get("a")?.lastReplyAt, new Date(5_000).toISOString()); + assert.equal(await replyOf("a"), new Date(9_000).toISOString(), "a read a change overtook is not kept"); +}); + test("a Bot row's preview is the host's own row line, as one plain line a paired Mac can trust", async () => { const { parseAidenRemoteHostFeedBot } = await import("./aiden-remote-protocol.js"); const idle = { state: { kind: "idle" } as BotSessionState, needsYou: false, lastReplyAt: null as number | null }; diff --git a/main/services/aiden-remote-host-feed.ts b/main/services/aiden-remote-host-feed.ts index 34db5c16b6..60fc96a012 100644 --- a/main/services/aiden-remote-host-feed.ts +++ b/main/services/aiden-remote-host-feed.ts @@ -69,6 +69,77 @@ export function hostFeedBotSignals( }; } +export interface HostFeedBotSignalsCache { + /** Each listed Bot's signals: kept ones as they are, the rest read again. */ + signals(bots: readonly { id: string }[]): Promise>; + /** That Bot changed (`bots:changed`, `bots:attention`); with no Bot, every Bot did. */ + invalidate(botId?: string): void; +} + +/** + * Each Bot's host-feed signals, kept until that Bot itself changes. A closed + * Bot's live summary opens its conversation, and the feed refreshes on every + * chat, workspace or Bot change, so a refresh reads again only the Bots whose + * own change arrived since: the same events this Mac's Bots list re-reads a + * row on. A failed read is not kept, and a read a change overtook is not kept. + */ +export function createHostFeedBotSignalsCache(deps: { + summary(botId: string): Promise[0]>; + /** At most this many summaries read at once (default 4). */ + concurrency?: number; +}): HostFeedBotSignalsCache { + const concurrency = Math.max(1, deps.concurrency ?? 4); + const kept = new Map(); + // Change counts only rise, so a read a change overtook never matches again. + let changes = 0; + let everyBot = 0; + const generations = new Map(); + const generationOf = (botId: string) => `${everyBot}:${generations.get(botId) ?? 0}`; + + async function read(botId: string): Promise { + const hit = kept.get(botId); + if (hit) return hit; + const generation = generationOf(botId); + let live: Parameters[0]; + try { + live = await deps.summary(botId); + } catch { + return {}; + } + const signals = hostFeedBotSignals(live); + if (generationOf(botId) === generation) kept.set(botId, signals); + return signals; + } + + return { + async signals(bots) { + const listed = new Set(bots.map((bot) => bot.id)); + for (const botId of [...kept.keys()]) if (!listed.has(botId)) kept.delete(botId); + for (const botId of [...generations.keys()]) if (!listed.has(botId)) generations.delete(botId); + const results = new Map(); + const ids = [...listed]; + let next = 0; + await Promise.all(Array.from({ length: Math.min(concurrency, ids.length) }, async () => { + while (next < ids.length) { + const botId = ids[next++]!; + results.set(botId, await read(botId)); + } + })); + return results; + }, + invalidate(botId) { + changes += 1; + if (botId === undefined) { + everyBot = changes; + kept.clear(); + return; + } + generations.set(botId, changes); + kept.delete(botId); + }, + }; +} + /** One read of everything the feed projects; it opens no chat transcript (Bot previews come from cached summaries). */ export interface AidenRemoteHostFeedState { /** Non-Bot chat summaries, exactly as `/chat-summaries` projects them. */ diff --git a/main/services/aiden-remote-service-main.ts b/main/services/aiden-remote-service-main.ts index 1647c53faf..808f7ed8ac 100644 --- a/main/services/aiden-remote-service-main.ts +++ b/main/services/aiden-remote-service-main.ts @@ -212,7 +212,7 @@ import { import { hostPlatformCapabilities } from "./host-platform-capabilities.js"; import { electronConnectorWatchRemotePorts } from "./bot-routine-events/connector-watch-startup.js"; import { AidenRemoteHostRunService } from "./aiden-remote-host-runs.js"; -import { AidenRemoteHostFeedService, hostFeedBotSignals } from "./aiden-remote-host-feed.js"; +import { AidenRemoteHostFeedService, createHostFeedBotSignalsCache } from "./aiden-remote-host-feed.js"; import { createAidenRemoteHostFeedSource } from "./aiden-remote-host-feed-source.js"; import { hostRunRegistry } from "./host-runs-main.js"; import { liveRunAttention } from "./chat-pending-attention.js"; @@ -1222,6 +1222,12 @@ async function createRuntime(): Promise { await workspaceApplicationService.list(), () => chatStore.list(), ); + const botSignalsCache = createHostFeedBotSignalsCache({ + summary: async (botId) => { + const { botLiveProjection } = await import("./bot-runtime/bot-session-main.js"); + return botLiveProjection().summary(botId); + }, + }); const hostFeed = new AidenRemoteHostFeedService({ now: Date.now, attentionSummary: (runId) => { @@ -1235,16 +1241,10 @@ async function createRuntime(): Promise { approvalMode: async () => effectiveApprovalMode(await configStore.getSettings(), true), repositoryIdentity: gitCachedRepositoryIdentity, ...(bots ? { listBots: () => bots.list() } : {}), - // The same summary this Mac's own Bots list reads (revision 66): a closed - // Bot's preview and last reply come from the projection's cache, which - // reads the transcript again only after its newest entry changes. - botSignals: async (botRows) => { - const { botLiveProjection } = await import("./bot-runtime/bot-session-main.js"); - const live = botLiveProjection(); - return new Map(await mapWithConcurrency(botRows, 4, async (bot) => - [bot.id, hostFeedBotSignals(await live.summary(bot.id).catch(() => undefined))] as const, - )); - }, + // The same summary this Mac's own Bots list reads (revision 66), kept per + // Bot until that Bot's own `bots:changed` or `bots:attention` arrives, so + // a chat or workspace change opens no Bot conversation. + botSignals: (botRows) => botSignalsCache.signals(botRows), }), }); activeHostFeed = hostFeed; @@ -1261,7 +1261,8 @@ async function createRuntime(): Promise { "bots:attention", ]); const detachers = [ - onBroadcast((channel) => { + onBroadcast((channel, botId) => { + if (channel === "bots:changed" || channel === "bots:attention") botSignalsCache.invalidate(botId); if (hostFeedChannels.has(channel)) hostFeed.invalidate(); }), chatStore.onIndexChanged(() => hostFeed.invalidate()), diff --git a/renderer/components/remote-bots-section.tsx b/renderer/components/remote-bots-section.tsx index 8ed3db6acc..f92e18c867 100644 --- a/renderer/components/remote-bots-section.tsx +++ b/renderer/components/remote-bots-section.tsx @@ -71,7 +71,7 @@ export function RemoteBotsSection({ // The replies a host's Bots had when this Mac first lists them start read. // The open Bot's chat records what it shows itself (`RemoteBotChatView`). React.useEffect(() => { - for (const { host, bots } of groups) markRemoteBotHostListed(host.id, bots.map((bot) => bot.lastReplyAt)); + for (const { host, bots } of groups) markRemoteBotHostListed(host.id, bots); }, [groups]); if (groups.length === 0) return null; return ( diff --git a/renderer/lib/remote-bot-seen.test.ts b/renderer/lib/remote-bot-seen.test.ts index 7c20ad7b7b..7118566a19 100644 --- a/renderer/lib/remote-bot-seen.test.ts +++ b/renderer/lib/remote-bot-seen.test.ts @@ -14,14 +14,18 @@ import { const HOUR = 3_600_000; const NOW = Date.UTC(2026, 10, 24, 9); +/** Rows as a revision 66 host lists them: every Bot with a message has a preview. */ +const listed = (...replies: (number | undefined)[]) => + replies.map((lastReplyAt) => ({ preview: "Release moved to Friday", ...(lastReplyAt === undefined ? {} : { lastReplyAt }) })); + test("a paired Mac's Bot reads unread only for a reply newer than the last one shown here, or than its host's first listing", () => { let seen = parseRemoteBotSeen(null); assert.equal(isRemoteBotUnread(seen, "host", "bot", NOW), false, "nothing to compare with before the host is listed"); - seen = withRemoteBotHostListed(seen, "host", [NOW - 5_000, undefined, NOW]); + seen = withRemoteBotHostListed(seen, "host", listed(NOW - 5_000, undefined, NOW)); assert.equal(isRemoteBotUnread(seen, "host", "bot", undefined), false, "no reply time, no dot"); assert.equal(isRemoteBotUnread(seen, "host", "bot", NOW - 5_000), false, "a reply from before the first listing is not new"); assert.equal(isRemoteBotUnread(seen, "host", "bot", NOW + 500), true); - assert.equal(withRemoteBotHostListed(seen, "host", [NOW + 9_000]), seen, "a host's baseline is set once"); + assert.equal(withRemoteBotHostListed(seen, "host", listed(NOW + 9_000)), seen, "a host's baseline is set once"); const shown = withRemoteBotSeen(seen, "host/bot", NOW + 500); assert.equal(isRemoteBotUnread(shown, "host", "bot", NOW + 500), false); assert.equal(isRemoteBotUnread(shown, "host", "bot", NOW + 600), true); @@ -31,23 +35,40 @@ test("a paired Mac's Bot reads unread only for a reply newer than the last one s }); test("a host whose Bots hadn't replied when first listed shows a dot for their first reply, also after a reload", () => { - let seen = withRemoteBotHostListed(parseRemoteBotSeen(null), "quiet", [undefined, undefined]); + const silent = withRemoteBotHostListed(parseRemoteBotSeen(null), "quiet", [{}, {}]); + assert.deepEqual(silent.hostSince, {}, "Bots with no message yet don't show the host's revision; nothing is set"); + // The person's first message is the preview; the reply hasn't come yet. + let seen = withRemoteBotHostListed(silent, "quiet", listed(undefined, undefined)); + assert.equal(seen.hostSince.quiet, 0); // The next feed update brings the first reply; listing again must not swallow it. - seen = withRemoteBotHostListed(seen, "quiet", [NOW]); + seen = withRemoteBotHostListed(seen, "quiet", listed(NOW)); assert.equal(isRemoteBotUnread(seen, "quiet", "bot", NOW), true); const reloaded = parseRemoteBotSeen(serializeRemoteBotSeen(seen)); - assert.equal(isRemoteBotUnread(withRemoteBotHostListed(reloaded, "quiet", [NOW]), "quiet", "bot", NOW), true); + assert.equal(isRemoteBotUnread(withRemoteBotHostListed(reloaded, "quiet", listed(NOW)), "quiet", "bot", NOW), true); assert.equal(isRemoteBotUnread(withRemoteBotSeen(reloaded, "quiet/bot", NOW), "quiet", "bot", NOW), false); }); +test("a host older than revision 66 sets no baseline, so its earlier replies start read once it upgrades", () => { + // An older host sends no preview, and reply times only for Bots whose chat is open there. + const old = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [{ lastReplyAt: NOW - 9 * HOUR }, {}, {}]); + assert.deepEqual(old.hostSince, {}); + assert.equal(isRemoteBotUnread(old, "host", "closed", NOW - HOUR), false); + // After the upgrade every Bot's newest reply arrives at once; none of them is new. + const upgraded = withRemoteBotHostListed(old, "host", listed(NOW - 9 * HOUR, NOW - HOUR, NOW - 2 * HOUR)); + for (const [botId, at] of [["open", NOW - 9 * HOUR], ["closed", NOW - HOUR], ["other", NOW - 2 * HOUR]] as const) { + assert.equal(isRemoteBotUnread(upgraded, "host", botId, at), false, botId); + } + assert.equal(isRemoteBotUnread(upgraded, "host", "closed", NOW), true, "the next reply shows a dot"); +}); + test("a host whose clock is an hour ahead or behind this Mac still starts read and shows its next reply", () => { for (const skew of [HOUR, -HOUR]) { const hostNow = NOW + skew; - const listed = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [hostNow - 60_000, hostNow - 120_000]); - assert.equal(isRemoteBotUnread(listed, "host", "scout", hostNow - 60_000), false, `skew ${skew}: the reply already there is read`); - assert.equal(isRemoteBotUnread(listed, "host", "planner", hostNow - 120_000), false, `skew ${skew}: so is an older one`); - assert.equal(isRemoteBotUnread(listed, "host", "scout", hostNow + 1_000), true, `skew ${skew}: the next reply shows a dot`); - assert.equal(isRemoteBotUnread(listed, "host", "newbot", hostNow + 1_000), true, `skew ${skew}: so does a new Bot's first reply`); + const first = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", listed(hostNow - 60_000, hostNow - 120_000)); + assert.equal(isRemoteBotUnread(first, "host", "scout", hostNow - 60_000), false, `skew ${skew}: the reply already there is read`); + assert.equal(isRemoteBotUnread(first, "host", "planner", hostNow - 120_000), false, `skew ${skew}: so is an older one`); + assert.equal(isRemoteBotUnread(first, "host", "scout", hostNow + 1_000), true, `skew ${skew}: the next reply shows a dot`); + assert.equal(isRemoteBotUnread(first, "host", "newbot", hostNow + 1_000), true, `skew ${skew}: so does a new Bot's first reply`); } }); @@ -68,8 +89,8 @@ test("only a reply the remote chat shows counts as seen", () => { }); test("the record survives a reload and refuses what it can't trust", () => { - const listed = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [NOW]); - const shown = withRemoteBotSeen(listed, "host/bot", NOW + 1); + const first = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", listed(NOW)); + const shown = withRemoteBotSeen(first, "host/bot", NOW + 1); assert.deepEqual(parseRemoteBotSeen(serializeRemoteBotSeen(shown)), shown); for (const raw of ["not json", "[]", JSON.stringify({ version: 1, since: 10, seenReplyAt: { "host/bot": 5 } })]) { assert.deepEqual(parseRemoteBotSeen(raw), { hostSince: {}, seenReplyAt: {} }, raw); diff --git a/renderer/lib/remote-bot-seen.ts b/renderer/lib/remote-bot-seen.ts index 187bc1ed0a..f0a1ce3650 100644 --- a/renderer/lib/remote-bot-seen.ts +++ b/renderer/lib/remote-bot-seen.ts @@ -7,6 +7,8 @@ // behind still gets the right dots. `hostSince` is the newest reply a host's // Bots had when this Mac first listed them: those replies start read. A host // first listed with Bots but no replies gets 0, so its first reply is unread. +// Only a revision 66 host reports every Bot's reply, so the baseline waits for +// a listing that shows it is one. import * as React from "react"; import { botLastReplyAt } from "../shared/bot-live"; @@ -61,20 +63,33 @@ export function serializeRemoteBotSeen(seen: RemoteBotSeen): string { return JSON.stringify({ version: 2, hostSince: seen.hostSince, seenReplyAt: seen.seenReplyAt }); } +/** What a listed remote Bot row says about its messages (`RemoteBotChoice`). */ +export interface RemoteBotListedRow { + lastReplyAt?: number; + preview?: string; +} + /** * The first time this Mac lists a host's Bots, their replies so far start * read: the host's newest reply becomes its baseline. Bots with no reply yet - * get a baseline of 0, so the first reply that arrives later is unread. An - * empty list sets nothing: the host's Bots may not have arrived yet. + * get a baseline of 0, so the first reply that arrives later is unread. + * + * Nothing is set until the listing shows the host reports every Bot's reply + * (revision 66, which also sends each Bot's `preview`; a Bot with a reply + * always has one). An older host sends reply times only for Bots whose chat + * is open there, so a baseline taken from it would be too low and every + * earlier reply would read as new once the host upgrades. An empty list, or + * one whose Bots have no messages yet, sets nothing either: the first listing + * with a message decides. */ export function withRemoteBotHostListed( seen: RemoteBotSeen, hostId: string, - replyTimes: readonly (number | undefined)[], + rows: readonly RemoteBotListedRow[], ): RemoteBotSeen { if (seen.hostSince[hostId] !== undefined) return seen; - if (replyTimes.length === 0) return seen; - const known = replyTimes.filter(validTime); + if (!rows.some((row) => typeof row.preview === "string" && row.preview.length > 0)) return seen; + const known = rows.map((row) => row.lastReplyAt).filter(validTime); const since = known.length === 0 ? 0 : Math.max(...known); return { ...seen, hostSince: newest({ ...seen.hostSince, [hostId]: since }) }; } @@ -163,9 +178,9 @@ export function useRemoteBotSeen(): RemoteBotSeen { } /** Sets a host's baseline the first time its Bots are listed here (`withRemoteBotHostListed`). */ -export function markRemoteBotHostListed(hostId: string, replyTimes: readonly (number | undefined)[]): void { +export function markRemoteBotHostListed(hostId: string, rows: readonly RemoteBotListedRow[]): void { const before = read(); - const next = withRemoteBotHostListed(before, hostId, replyTimes); + const next = withRemoteBotHostListed(before, hostId, rows); if (next !== before) write(next); } From ed42d28d1da5043e6e1b023ffc8b795bc9ae7ca6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:38:38 +0000 Subject: [PATCH 5/7] Mark host feed Bot rows whose summary the host read, so a paired Mac whose Bots had no message yet still sets its unread baseline A revision 66 host now sends `summarized: true` on every Bot row whose summary it read. The paired Mac takes a host's unread baseline from a listing with a summarized row (or a preview), so a host whose Bots are all still empty gets baseline 0 and their first reply shows a dot again. An older host marks nothing, so its baseline still waits for revision 66. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .memory/bot-chat-activity.md | 2 +- docs/aiden-remote-api-v1.md | 6 ++-- main/services/aiden-remote-host-feed.test.ts | 17 ++++++----- main/services/aiden-remote-host-feed.ts | 7 +++++ main/services/aiden-remote-protocol.test.ts | 3 ++ main/services/aiden-remote-protocol.ts | 8 +++-- .../aiden-remote/v1/fixtures/contract.json | 3 +- protocol/aiden-remote/v1/openapi.json | 4 +++ renderer/lib/hosts/new-chat-targets.ts | 3 ++ renderer/lib/remote-bot-seen.test.ts | 23 ++++++++++----- renderer/lib/remote-bot-seen.ts | 21 ++++++++------ renderer/main/bots/bot-sidebar.test.tsx | 29 +++++++++++++++++++ 12 files changed, 94 insertions(+), 32 deletions(-) diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index a8150498b8..8e82c0bd81 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -103,6 +103,6 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev ### Bots across Macs (2026-11-24) - PR 1 (#895, desktop only): paired Mac's Bot rows show the feed's avatar, Needs you over Thinking over stop status, never the description; `ChatSidebar` owns `usePeerHostSidebar` so feeds stay live on the Bots page; remote Bot chat only treats 404/403 as gone. -- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. The host baseline is taken only from a listing with a `preview` (proof of revision 66), since an older host sends `lastReplyAt` only for open feeds. Host feed Bot signals are cached per Bot (`createHostFeedBotSignalsCache` in `aiden-remote-host-feed.ts`) and invalidated by that Bot's `bots:changed` / `bots:attention`; `onBroadcast` forwards only the `botId` of a `bots:*` payload. +- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. The host baseline is taken only from a listing with a `summarized: true` row or a `preview` (proof of revision 66; `summarized` marks every row whose summary the host read, so a host whose Bots are all still empty gets baseline 0 and their first reply shows a dot), since an older host sends `lastReplyAt` only for open feeds. Host feed Bot signals are cached per Bot (`createHostFeedBotSignalsCache` in `aiden-remote-host-feed.ts`) and invalidated by that Bot's `bots:changed` / `bots:attention`; `onBroadcast` forwards only the `botId` of a `bots:*` payload. - Still to come: PR 3 (plan, access-request and memory cards in remote Bot chats, load older), PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 5573b0bb31..d8578cceb1 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1499,8 +1499,8 @@ Revision 65 was claimed on 2026-11-18, when `main` was at 64. The host keeps it Revision 66 is provisional: it was written when `main` was at 65, and the host keeps it in one constant (`AIDEN_REMOTE_BOT_FEED_PREVIEW_CONTRACT_REVISION`), so claiming the next free number at merge changes only that constant. It needs no capability or feature token. -**Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads. The feed keeps each Bot's summary until that Bot itself changes (a state change, a wait beginning or ending, or an edit: the same events the host's own Bots list re-reads a row on), so a chat or workspace change re-reads no Bot, and for a Bot whose chat is closed the host reads the transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. +**Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads, and a row whose summary the host read carries `summarized: true`, so a summarized row without `preview` or `lastReplyAt` is a Bot with none yet. A row whose summary read failed carries none of the three. The feed keeps each Bot's summary until that Bot itself changes (a state change, a wait beginning or ending, or an edit: the same events the host's own Bots list re-reads a row on), so a chat or workspace change re-reads no Bot, and for a Bot whose chat is closed the host reads the transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. -**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). It takes that baseline only from a listing with a `preview`, which shows the host is on revision 66 and reports every Bot's reply: an older host would give too low a baseline, so its earlier replies would read as new once it upgrades. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. +**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). It takes that baseline only from a listing with a `summarized` row (or a `preview`), which shows the host is on revision 66 and reports every Bot's reply, even when none of its Bots has a message yet: an older host would give too low a baseline, so its earlier replies would read as new once it upgrades. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. -**Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt` and `preview`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou` and `failed` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). +**Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt`, `preview` and `summarized`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou`, `failed` and `summarized` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). diff --git a/main/services/aiden-remote-host-feed.test.ts b/main/services/aiden-remote-host-feed.test.ts index 1efaa62c13..9ee62ad80a 100644 --- a/main/services/aiden-remote-host-feed.test.ts +++ b/main/services/aiden-remote-host-feed.test.ts @@ -723,17 +723,18 @@ test("an observer's waiting-run announcements never push a cursor taken at the s test("a Bot row's Inbox signals hold only what its live summary says", () => { const idle = { state: { kind: "idle" } as BotSessionState, needsYou: false, lastReplyAt: null as number | null }; - assert.deepEqual(hostFeedBotSignals(undefined), {}); - assert.deepEqual(hostFeedBotSignals(idle), {}); + const read = { summarized: true }; + assert.deepEqual(hostFeedBotSignals(undefined), {}, "an unread summary says nothing, not even that the Bot is empty"); + assert.deepEqual(hostFeedBotSignals(idle), read, "a Bot with no message yet is still marked summarized"); assert.deepEqual( hostFeedBotSignals({ ...idle, needsYou: true, lastReplyAt: 3_000 }), - { needsYou: true, lastReplyAt: new Date(3_000).toISOString() }, + { needsYou: true, lastReplyAt: new Date(3_000).toISOString(), ...read }, ); for (const kind of ["interrupted", "model_error"]) { - assert.deepEqual(hostFeedBotSignals({ ...idle, state: { kind } as BotSessionState }), { failed: true }, kind); + assert.deepEqual(hostFeedBotSignals({ ...idle, state: { kind } as BotSessionState }), { failed: true, ...read }, kind); } - assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: -1 }), {}, "a negative time is unknown"); - assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: 1.5 }), {}, "a fractional time is unknown"); + assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: -1 }), read, "a negative time is unknown"); + assert.deepEqual(hostFeedBotSignals({ ...idle, lastReplyAt: 1.5 }), read, "a fractional time is unknown"); }); test("a refresh reads again only the Bots whose own change arrived, and never keeps a failed or overtaken read", async () => { @@ -791,8 +792,8 @@ test("a refresh reads again only the Bots whose own change arrived, and never ke test("a Bot row's preview is the host's own row line, as one plain line a paired Mac can trust", async () => { const { parseAidenRemoteHostFeedBot } = await import("./aiden-remote-protocol.js"); const idle = { state: { kind: "idle" } as BotSessionState, needsYou: false, lastReplyAt: null as number | null }; - assert.deepEqual(hostFeedBotSignals({ ...idle, preview: null }), {}, "no preview, no key"); - assert.deepEqual(hostFeedBotSignals({ ...idle, preview: " \n " }), {}, "a blank preview sends no key"); + assert.deepEqual(hostFeedBotSignals({ ...idle, preview: null }), { summarized: true }, "no preview, no key"); + assert.deepEqual(hostFeedBotSignals({ ...idle, preview: " \n " }), { summarized: true }, "a blank preview sends no key"); assert.equal(hostFeedBotSignals({ ...idle, preview: "Release moved\nto Friday" }).preview, "Release moved to Friday"); const long = hostFeedBotSignals({ ...idle, preview: `${"word ".repeat(60)}\u202Eend` }).preview!; assert.equal(Array.from(long).length, 140); diff --git a/main/services/aiden-remote-host-feed.ts b/main/services/aiden-remote-host-feed.ts index 60fc96a012..4599ec5644 100644 --- a/main/services/aiden-remote-host-feed.ts +++ b/main/services/aiden-remote-host-feed.ts @@ -49,6 +49,12 @@ export interface AidenRemoteHostFeedBotSignals { * most `AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX` characters. */ preview?: string; + /** + * Revision 66: `preview` and `lastReplyAt` come from the Bot's summary, so + * their absence means the Bot has none. A paired Mac waits for it before + * setting a host's unread baseline (`withRemoteBotHostListed`). + */ + summarized?: true; } /** The Inbox signals and preview of one Bot from its live summary; none when the summary is unknown. */ @@ -66,6 +72,7 @@ export function hostFeedBotSignals( ...(failed ? { failed: true as const } : {}), ...(replied && Number.isFinite(replied.getTime()) ? { lastReplyAt: replied.toISOString() } : {}), ...(preview ? { preview } : {}), + summarized: true, }; } diff --git a/main/services/aiden-remote-protocol.test.ts b/main/services/aiden-remote-protocol.test.ts index 666d189cbe..69d7099055 100644 --- a/main/services/aiden-remote-protocol.test.ts +++ b/main/services/aiden-remote-protocol.test.ts @@ -4009,6 +4009,7 @@ test("revision 66 host feed Bot rows carry a one-line preview and refuse anythin assert.ok(upsert, "the fixture sends a Bot row"); assert.equal(typeof upsert.payload.preview, "string"); assert.equal(upsert.payload.needsYou, true); + assert.equal(upsert.payload.summarized, true); const row = (raw.hostFeedEvents as { type: string; payload: Record }[]) .find((event) => event.type === "bot.upsert")!.payload; @@ -4022,6 +4023,7 @@ test("revision 66 host feed Bot rows carry a one-line preview and refuse anythin assert.doesNotThrow(parse({ preview: "family 👨\u200D👩\u200D👧" }), "emoji joiners stay"); assert.throws(parse({ needsYou: false }), /needsYou/u); assert.throws(parse({ failed: "yes" }), /failed/u); + assert.throws(parse({ summarized: false }), /summarized/u); assert.throws(parse({ lastReplyAt: "yesterday" })); assert.throws(parse({ issueCount: 2 }), /issueCount/u); assert.throws(parse({ secret: "x" }), /unsupported field/u); @@ -4035,4 +4037,5 @@ test("revision 66 host feed Bot rows carry a one-line preview and refuse anythin const feedBot = ajv.compile({ $ref: "#/components/schemas/HostFeedBot", components: spec.components }); assert.equal(feedBot(row), true, JSON.stringify(feedBot.errors)); assert.equal(feedBot({ ...row, preview: "x".repeat(141) }), false); + assert.equal(feedBot({ ...row, summarized: false }), false); }); diff --git a/main/services/aiden-remote-protocol.ts b/main/services/aiden-remote-protocol.ts index 25b0e8c135..a833930371 100644 --- a/main/services/aiden-remote-protocol.ts +++ b/main/services/aiden-remote-protocol.ts @@ -376,7 +376,8 @@ export const AIDEN_REMOTE_STREAM_SNAPSHOT_REASONS_CONTRACT_REVISION = 65 as cons * `main`'s at merge by changing only this constant): host feed Bot rows may * carry `preview`, the one plain line the host's own Bots list shows under the * Bot's name (at most 140 characters), and a host now sends `lastReplyAt` for - * every Bot rather than only Bots whose chat is open there. Display-only, no + * every Bot rather than only Bots whose chat is open there, marking each row + * whose summary it read `summarized: true`. Display-only, no * capability or feature token; older desktops ignore the key, and phones don't * read the host feed. */ @@ -3469,12 +3470,12 @@ export const AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX = 140; /** * A host feed Bot row: a Bot summary without `issueCount` (a phone shape), * plus revision 52's `needsYou`, `failed` and `lastReplyAt` and revision 66's - * `preview`, one trimmed plain line. + * `preview`, one trimmed plain line, and `summarized`. */ export function parseAidenRemoteHostFeedBot(value: unknown, label = "Host feed Bot"): Record { if (!isRecord(value)) throw new Error(`${label} must be an object.`); if (hasOwn(value, "issueCount")) throw new Error(`${label} carries no issueCount.`); - const { needsYou, failed, lastReplyAt, preview, ...summary } = value; + const { needsYou, failed, lastReplyAt, preview, summarized, ...summary } = value; parseAidenRemoteBotSummary(summary); assertExactKeys( summary, @@ -3483,6 +3484,7 @@ export function parseAidenRemoteHostFeedBot(value: unknown, label = "Host feed B ); if (needsYou !== undefined && needsYou !== true) throw new Error(`${label} needsYou must be true when present.`); if (failed !== undefined && failed !== true) throw new Error(`${label} failed must be true when present.`); + if (summarized !== undefined && summarized !== true) throw new Error(`${label} summarized must be true when present.`); if (lastReplyAt !== undefined) dateTimeValue(lastReplyAt, `${label} lastReplyAt`); if (preview !== undefined) { const text = boundedText(preview, `${label} preview`, AIDEN_REMOTE_HOST_FEED_BOT_PREVIEW_MAX); diff --git a/protocol/aiden-remote/v1/fixtures/contract.json b/protocol/aiden-remote/v1/fixtures/contract.json index 2917b72d06..7ed24dde82 100644 --- a/protocol/aiden-remote/v1/fixtures/contract.json +++ b/protocol/aiden-remote/v1/fixtures/contract.json @@ -2410,7 +2410,8 @@ "revision": "bot_revision_7", "needsYou": true, "lastReplyAt": "2026-08-18T19:01:30.000Z", - "preview": "Three things changed this week: the release moved to Friday, and two reviews are waiting on you." + "preview": "Three things changed this week: the release moved to Friday, and two reviews are waiting on you.", + "summarized": true } } ], diff --git a/protocol/aiden-remote/v1/openapi.json b/protocol/aiden-remote/v1/openapi.json index 0edf3c3f39..a0f32ff872 100644 --- a/protocol/aiden-remote/v1/openapi.json +++ b/protocol/aiden-remote/v1/openapi.json @@ -18269,6 +18269,10 @@ "type": "string", "minLength": 1, "maxLength": 140 + }, + "summarized": { + "description": "Contract revision 66: the row's preview and lastReplyAt come from the Bot's summary, so a row with this and neither of them is a Bot with no message yet. Absent when the host could not read the summary, and on hosts before revision 66.", + "const": true } }, "additionalProperties": false diff --git a/renderer/lib/hosts/new-chat-targets.ts b/renderer/lib/hosts/new-chat-targets.ts index 1b593d9d35..57ec9bf689 100644 --- a/renderer/lib/hosts/new-chat-targets.ts +++ b/renderer/lib/hosts/new-chat-targets.ts @@ -146,6 +146,8 @@ export interface RemoteBotChoice { lastReplyAt?: number; /** The Bot's photo, as the host lists it; read on demand. */ photo?: RemoteBotPhotoAsset; + /** The host read this Bot's summary (revision 66): no `preview` or `lastReplyAt` means it has none. */ + summarized?: true; } /** The longest preview a remote Bot row shows; a host sends at most this (revision 66). */ @@ -195,6 +197,7 @@ export function remoteBotGroups( ...(preview ? { preview } : {}), ...(Number.isFinite(lastReplyAt) && lastReplyAt > 0 ? { lastReplyAt } : {}), ...(photo ? { photo } : {}), + ...(row.summarized === true ? { summarized: true as const } : {}), }; }); if (bots.length === 0) continue; diff --git a/renderer/lib/remote-bot-seen.test.ts b/renderer/lib/remote-bot-seen.test.ts index 7118566a19..996661980d 100644 --- a/renderer/lib/remote-bot-seen.test.ts +++ b/renderer/lib/remote-bot-seen.test.ts @@ -14,9 +14,15 @@ import { const HOUR = 3_600_000; const NOW = Date.UTC(2026, 10, 24, 9); -/** Rows as a revision 66 host lists them: every Bot with a message has a preview. */ +/** Rows as a revision 66 host lists them: every Bot is summarized, and one with a message has a preview. */ const listed = (...replies: (number | undefined)[]) => - replies.map((lastReplyAt) => ({ preview: "Release moved to Friday", ...(lastReplyAt === undefined ? {} : { lastReplyAt }) })); + replies.map((lastReplyAt) => ({ + summarized: true as const, + preview: "Release moved to Friday", + ...(lastReplyAt === undefined ? {} : { lastReplyAt }), + })); +/** A revision 66 host's Bots that have no message yet. */ +const empty = (count: number) => Array.from({ length: count }, () => ({ summarized: true as const })); test("a paired Mac's Bot reads unread only for a reply newer than the last one shown here, or than its host's first listing", () => { let seen = parseRemoteBotSeen(null); @@ -35,23 +41,26 @@ test("a paired Mac's Bot reads unread only for a reply newer than the last one s }); test("a host whose Bots hadn't replied when first listed shows a dot for their first reply, also after a reload", () => { - const silent = withRemoteBotHostListed(parseRemoteBotSeen(null), "quiet", [{}, {}]); - assert.deepEqual(silent.hostSince, {}, "Bots with no message yet don't show the host's revision; nothing is set"); - // The person's first message is the preview; the reply hasn't come yet. - let seen = withRemoteBotHostListed(silent, "quiet", listed(undefined, undefined)); + // Bots with no message at all: the host still says it read their summaries. + let seen = withRemoteBotHostListed(parseRemoteBotSeen(null), "quiet", empty(2)); assert.equal(seen.hostSince.quiet, 0); // The next feed update brings the first reply; listing again must not swallow it. seen = withRemoteBotHostListed(seen, "quiet", listed(NOW)); assert.equal(isRemoteBotUnread(seen, "quiet", "bot", NOW), true); + // Also when the person's first message came before the reply. + const asked = withRemoteBotHostListed(parseRemoteBotSeen(null), "quiet", listed(undefined, undefined)); + assert.equal(isRemoteBotUnread(withRemoteBotHostListed(asked, "quiet", listed(NOW)), "quiet", "bot", NOW), true); const reloaded = parseRemoteBotSeen(serializeRemoteBotSeen(seen)); assert.equal(isRemoteBotUnread(withRemoteBotHostListed(reloaded, "quiet", listed(NOW)), "quiet", "bot", NOW), true); assert.equal(isRemoteBotUnread(withRemoteBotSeen(reloaded, "quiet/bot", NOW), "quiet", "bot", NOW), false); }); test("a host older than revision 66 sets no baseline, so its earlier replies start read once it upgrades", () => { - // An older host sends no preview, and reply times only for Bots whose chat is open there. + // An older host marks no row summarized, sends no preview, and sends reply + // times only for Bots whose chat is open there. const old = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [{ lastReplyAt: NOW - 9 * HOUR }, {}, {}]); assert.deepEqual(old.hostSince, {}); + assert.deepEqual(withRemoteBotHostListed(old, "host", [{}, {}]).hostSince, {}, "nor do its Bots with no reply"); assert.equal(isRemoteBotUnread(old, "host", "closed", NOW - HOUR), false); // After the upgrade every Bot's newest reply arrives at once; none of them is new. const upgraded = withRemoteBotHostListed(old, "host", listed(NOW - 9 * HOUR, NOW - HOUR, NOW - 2 * HOUR)); diff --git a/renderer/lib/remote-bot-seen.ts b/renderer/lib/remote-bot-seen.ts index f0a1ce3650..ae012c6b23 100644 --- a/renderer/lib/remote-bot-seen.ts +++ b/renderer/lib/remote-bot-seen.ts @@ -8,7 +8,7 @@ // Bots had when this Mac first listed them: those replies start read. A host // first listed with Bots but no replies gets 0, so its first reply is unread. // Only a revision 66 host reports every Bot's reply, so the baseline waits for -// a listing that shows it is one. +// a listing that shows it is one (a row marked `summarized`). import * as React from "react"; import { botLastReplyAt } from "../shared/bot-live"; @@ -67,6 +67,8 @@ export function serializeRemoteBotSeen(seen: RemoteBotSeen): string { export interface RemoteBotListedRow { lastReplyAt?: number; preview?: string; + /** The host read the Bot's summary (revision 66), so no `lastReplyAt` means no reply yet. */ + summarized?: true; } /** @@ -74,13 +76,12 @@ export interface RemoteBotListedRow { * read: the host's newest reply becomes its baseline. Bots with no reply yet * get a baseline of 0, so the first reply that arrives later is unread. * - * Nothing is set until the listing shows the host reports every Bot's reply - * (revision 66, which also sends each Bot's `preview`; a Bot with a reply - * always has one). An older host sends reply times only for Bots whose chat - * is open there, so a baseline taken from it would be too low and every - * earlier reply would read as new once the host upgrades. An empty list, or - * one whose Bots have no messages yet, sets nothing either: the first listing - * with a message decides. + * Nothing is set until the listing shows the host reports every Bot's reply: + * a revision 66 host marks each Bot whose summary it read `summarized` (and + * sends its `preview`, which only such a host has). An older host sends reply + * times only for Bots whose chat is open there, so a baseline taken from it + * would be too low and every earlier reply would read as new once the host + * upgrades. An empty list sets nothing either. */ export function withRemoteBotHostListed( seen: RemoteBotSeen, @@ -88,7 +89,9 @@ export function withRemoteBotHostListed( rows: readonly RemoteBotListedRow[], ): RemoteBotSeen { if (seen.hostSince[hostId] !== undefined) return seen; - if (!rows.some((row) => typeof row.preview === "string" && row.preview.length > 0)) return seen; + if (!rows.some((row) => row.summarized === true || (typeof row.preview === "string" && row.preview.length > 0))) { + return seen; + } const known = rows.map((row) => row.lastReplyAt).filter(validTime); const since = known.length === 0 ? 0 : Math.max(...known); return { ...seen, hostSince: newest({ ...seen.hostSince, [hostId]: since }) }; diff --git a/renderer/main/bots/bot-sidebar.test.tsx b/renderer/main/bots/bot-sidebar.test.tsx index 73363f8ca9..9e7d4e76b3 100644 --- a/renderer/main/bots/bot-sidebar.test.tsx +++ b/renderer/main/bots/bot-sidebar.test.tsx @@ -702,6 +702,35 @@ test("a paired Mac's Bot shows its last message and photo, and only a reply afte assert.equal(photoReads.length, 1, "the same photo is read once"); }); +test("a paired Mac whose Bot had no message when first listed shows a dot for that Bot's first reply", async () => { + const queryClient = createBotTestQueryClient(); + queryClient.setQueryData(hostQueryKeys.list(), [ + { id: "host-b", name: "Studio", enabled: true, state: "connected", features: ["bot-durable-session-v1"], capabilities: ["chat:read", "chat:write", "bot:read", "bot:write"] }, + ]); + queryClient.setQueryData(hostQueryKeys.statuses(), [ + { hostId: "host-b", generation: 1, state: { kind: "connected", since: 1 }, feed: "live", stale: false }, + ]); + const scout = { id: "remote-1", name: "Scout", purpose: "", avatar: { semantic: { version: 1, shape: "orb", color: "rose" } }, sessionState: "idle" }; + const feed = (bot: Record) => ({ + hostId: "host-b", epoch: "e1", sequence: 1, stale: false, summaries: [], workspaces: [], bots: [bot], runs: [], + }); + // A new Bot: the host read its summary and found nothing to show. + queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed({ ...scout, summarized: true })); + sidebarIpc([], {}, { "bots:list": () => [] }); + await mountSidebar("/bots", queryClient); + await screen.findByRole("button", { name: "Scout, on Studio" }); + await act(async () => { + queryClient.setQueryData(hostQueryKeys.feed("host-b"), feed({ + ...scout, + summarized: true, + lastReplyAt: new Date(Date.now() - 86_400_000).toISOString(), + preview: "Found three flights", + })); + }); + const unread = await screen.findByRole("button", { name: "Scout, on Studio, unread" }); + assert.ok(within(unread).getByRole("img", { name: "Unread", hidden: true })); +}); + test("on a Bots page, a paired Mac's Bots keep up with what that Mac sends", async () => { const host = { id: "host-b", From 0ede27de775ec0a28b1c6e9deb57ae5470ffd710 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:49:19 +0000 Subject: [PATCH 6/7] Set a paired host's unread baseline only from a listing whose every Bot is summarized A Bot whose summary read failed is unmarked, so its earlier reply would be left out of a baseline taken from the rest and read as new once the next refresh reads it. The baseline now waits for a listing where every row is summarized. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .memory/bot-chat-activity.md | 2 +- docs/aiden-remote-api-v1.md | 2 +- renderer/lib/remote-bot-seen.test.ts | 16 ++++++++++++++++ renderer/lib/remote-bot-seen.ts | 19 +++++++++---------- renderer/main/bots/bot-sidebar.test.tsx | 1 + 5 files changed, 28 insertions(+), 12 deletions(-) diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index 8e82c0bd81..791e6b63cf 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -103,6 +103,6 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev ### Bots across Macs (2026-11-24) - PR 1 (#895, desktop only): paired Mac's Bot rows show the feed's avatar, Needs you over Thinking over stop status, never the description; `ChatSidebar` owns `usePeerHostSidebar` so feeds stay live on the Bots page; remote Bot chat only treats 404/403 as gone. -- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. The host baseline is taken only from a listing with a `summarized: true` row or a `preview` (proof of revision 66; `summarized` marks every row whose summary the host read, so a host whose Bots are all still empty gets baseline 0 and their first reply shows a dot), since an older host sends `lastReplyAt` only for open feeds. Host feed Bot signals are cached per Bot (`createHostFeedBotSignalsCache` in `aiden-remote-host-feed.ts`) and invalidated by that Bot's `bots:changed` / `bots:attention`; `onBroadcast` forwards only the `botId` of a `bots:*` payload. +- PR 2 (Remote revision 66, provisional; re-claim at merge): host-feed Bot rows (`HostFeedBot` in openapi.json, `parseAidenRemoteHostFeedBot`) carry an optional one-line `preview` (140 characters, no control or format characters) and always come from `BotLiveProjection.summary` (`inboxSignals` was removed). New peer binary operation `botAvatar` (`GET /bots/{botId}/avatar/{assetRevision}`) fetches photo avatars for the row and chat title. Unread dots for remote Bots are a per-device record in local storage (`renderer/lib/remote-bot-seen.ts`, key `aiden-agent.remote-bots-seen.v1`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. The host baseline is taken only from a listing whose every row is `summarized: true` (proof of revision 66, and no Bot whose summary read failed is left out; `summarized` marks every row whose summary the host read, so a host whose Bots are all still empty gets baseline 0 and their first reply shows a dot), since an older host sends `lastReplyAt` only for open feeds. Host feed Bot signals are cached per Bot (`createHostFeedBotSignalsCache` in `aiden-remote-host-feed.ts`) and invalidated by that Bot's `bots:changed` / `bots:attention`; `onBroadcast` forwards only the `botId` of a `bots:*` payload. - Still to come: PR 3 (plan, access-request and memory cards in remote Bot chats, load older), PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index d8578cceb1..d41e0174be 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1501,6 +1501,6 @@ Revision 66 is provisional: it was written when `main` was at 65, and the host k **Host feed.** Host feed Bot rows (`snapshot.bots`, `bot.upsert`, schema `HostFeedBot`) may carry `preview`: the line the host's own Bots list shows under the Bot's name. That is its newest reply, else the person's newest message ("Photo" for a picture alone), a routine's name or a hand-off's answer. It is one plain line: whitespace collapsed, control and invisible formatting characters dropped (emoji joiners stay), trimmed, and at most 140 characters, cut with "…". A Bot with nothing to show sends no key. The host now also sends `lastReplyAt` for every Bot, not only Bots whose chat is open there. Both come from the same summary the host's own Bots list reads, and a row whose summary the host read carries `summarized: true`, so a summarized row without `preview` or `lastReplyAt` is a Bot with none yet. A row whose summary read failed carries none of the three. The feed keeps each Bot's summary until that Bot itself changes (a state change, a wait beginning or ending, or an edit: the same events the host's own Bots list re-reads a row on), so a chat or workspace change re-reads no Bot, and for a Bot whose chat is closed the host reads the transcript again only after its newest entry changes. A Bot's state change at the end of a turn already refreshes the feed, so a new reply reaches paired desktops with it. The schema also lists revision 52's `needsYou`, `failed` and `lastReplyAt`, which the host has sent since then. -**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). It takes that baseline only from a listing with a `summarized` row (or a `preview`), which shows the host is on revision 66 and reports every Bot's reply, even when none of its Bots has a message yet: an older host would give too low a baseline, so its earlier replies would read as new once it upgrades. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. +**Desktop clients.** A paired Mac shows `preview` as the Bot row's line when nothing more pressing applies (Needs you, a running turn and a stopped state come first), clipping it again as untrusted text. It draws a Bot's photo from `avatar.asset` by reading `GET /bots/{botId}/avatar/{assetRevision}` once per asset revision, and shows an unread dot when `lastReplyAt` is newer than the newest reply that Bot's chat showed on this Mac, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). It takes that baseline only from a listing whose every row is `summarized`, which shows the host is on revision 66 and reported every listed Bot's reply, even when none of its Bots has a message yet; a listing where one Bot's summary read failed waits for the next refresh, so that Bot's earlier reply isn't left out of the baseline. An older host marks no row: a baseline from it would be too low, so its earlier replies would read as new once it upgrades. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. **Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt`, `preview` and `summarized`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou`, `failed` and `summarized` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). diff --git a/renderer/lib/remote-bot-seen.test.ts b/renderer/lib/remote-bot-seen.test.ts index 996661980d..ac87eda9aa 100644 --- a/renderer/lib/remote-bot-seen.test.ts +++ b/renderer/lib/remote-bot-seen.test.ts @@ -61,6 +61,11 @@ test("a host older than revision 66 sets no baseline, so its earlier replies sta const old = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [{ lastReplyAt: NOW - 9 * HOUR }, {}, {}]); assert.deepEqual(old.hostSince, {}); assert.deepEqual(withRemoteBotHostListed(old, "host", [{}, {}]).hostSince, {}, "nor do its Bots with no reply"); + assert.deepEqual( + withRemoteBotHostListed(old, "host", [{ preview: "Hi", lastReplyAt: NOW }]).hostSince, + {}, + "a preview alone is not a summarized row", + ); assert.equal(isRemoteBotUnread(old, "host", "closed", NOW - HOUR), false); // After the upgrade every Bot's newest reply arrives at once; none of them is new. const upgraded = withRemoteBotHostListed(old, "host", listed(NOW - 9 * HOUR, NOW - HOUR, NOW - 2 * HOUR)); @@ -70,6 +75,17 @@ test("a host older than revision 66 sets no baseline, so its earlier replies sta assert.equal(isRemoteBotUnread(upgraded, "host", "closed", NOW), true, "the next reply shows a dot"); }); +test("a listing where one Bot's summary failed sets no baseline, so that Bot's earlier reply starts read once it is read", () => { + // The host read Scout's summary but not Planner's; Planner replied an hour ago. + const partial = withRemoteBotHostListed(parseRemoteBotSeen(null), "host", [...listed(NOW - 2 * HOUR), {}]); + assert.deepEqual(partial.hostSince, {}); + // The next refresh reads Planner too. + const complete = withRemoteBotHostListed(partial, "host", listed(NOW - 2 * HOUR, NOW - HOUR)); + assert.equal(complete.hostSince.host, NOW - HOUR); + assert.equal(isRemoteBotUnread(complete, "host", "planner", NOW - HOUR), false, "Planner's earlier reply is not new"); + assert.equal(isRemoteBotUnread(complete, "host", "planner", NOW), true, "its next reply is"); +}); + test("a host whose clock is an hour ahead or behind this Mac still starts read and shows its next reply", () => { for (const skew of [HOUR, -HOUR]) { const hostNow = NOW + skew; diff --git a/renderer/lib/remote-bot-seen.ts b/renderer/lib/remote-bot-seen.ts index ae012c6b23..8984e4601b 100644 --- a/renderer/lib/remote-bot-seen.ts +++ b/renderer/lib/remote-bot-seen.ts @@ -8,7 +8,7 @@ // Bots had when this Mac first listed them: those replies start read. A host // first listed with Bots but no replies gets 0, so its first reply is unread. // Only a revision 66 host reports every Bot's reply, so the baseline waits for -// a listing that shows it is one (a row marked `summarized`). +// a listing whose every row it marked `summarized`. import * as React from "react"; import { botLastReplyAt } from "../shared/bot-live"; @@ -76,12 +76,13 @@ export interface RemoteBotListedRow { * read: the host's newest reply becomes its baseline. Bots with no reply yet * get a baseline of 0, so the first reply that arrives later is unread. * - * Nothing is set until the listing shows the host reports every Bot's reply: - * a revision 66 host marks each Bot whose summary it read `summarized` (and - * sends its `preview`, which only such a host has). An older host sends reply - * times only for Bots whose chat is open there, so a baseline taken from it - * would be too low and every earlier reply would read as new once the host - * upgrades. An empty list sets nothing either. + * Nothing is set until a listing reports every Bot's reply: a revision 66 + * host marks each Bot whose summary it read `summarized`, and the baseline + * waits until every listed Bot is. An older host marks none and sends reply + * times only for Bots whose chat is open there, and a Bot whose summary read + * failed this time is unmarked; a baseline taken without them would be too low + * and their earlier replies would read as new later. An empty list sets + * nothing either. */ export function withRemoteBotHostListed( seen: RemoteBotSeen, @@ -89,9 +90,7 @@ export function withRemoteBotHostListed( rows: readonly RemoteBotListedRow[], ): RemoteBotSeen { if (seen.hostSince[hostId] !== undefined) return seen; - if (!rows.some((row) => row.summarized === true || (typeof row.preview === "string" && row.preview.length > 0))) { - return seen; - } + if (rows.length === 0 || !rows.every((row) => row.summarized === true)) return seen; const known = rows.map((row) => row.lastReplyAt).filter(validTime); const since = known.length === 0 ? 0 : Math.max(...known); return { ...seen, hostSince: newest({ ...seen.hostSince, [hostId]: since }) }; diff --git a/renderer/main/bots/bot-sidebar.test.tsx b/renderer/main/bots/bot-sidebar.test.tsx index 9e7d4e76b3..2eec5d54d9 100644 --- a/renderer/main/bots/bot-sidebar.test.tsx +++ b/renderer/main/bots/bot-sidebar.test.tsx @@ -654,6 +654,7 @@ test("a paired Mac's Bot shows its last message and photo, and only a reply afte asset: { assetRevision: revision, mimeType: "image/png", width: 512, height: 512, byteSize: 4 }, }, sessionState: "idle", + summarized: true, lastReplyAt, // Another computer's text: the row shows it as one plain line. preview: "Flights to Lisbon\nare cheaper on Tuesday", From 0fe8b0fd6e86c61f13c3efc9c26a47644f58a6dc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 16:57:14 +0000 Subject: [PATCH 7/7] Take a paired host's unread baseline from all its Bots, not the ones a search shows The Bots sidebar passes its search-narrowed groups to RemoteBotsSection. A host first listed during a search set its baseline from the matching Bots only, so a hidden Bot's earlier reply read as new once the search cleared. The section now takes the baseline from every listed Bot. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- renderer/components/remote-bots-section.tsx | 13 ++++++--- renderer/main/bots/bot-sidebar.test.tsx | 30 +++++++++++++++++++++ renderer/main/bots/bot-sidebar.tsx | 1 + 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/renderer/components/remote-bots-section.tsx b/renderer/components/remote-bots-section.tsx index f92e18c867..e39b20ff16 100644 --- a/renderer/components/remote-bots-section.tsx +++ b/renderer/components/remote-bots-section.tsx @@ -52,15 +52,22 @@ export function remoteBotGroupsMatching(groups: readonly RemoteBotGroup[], query * Bots that live on paired Macs, grouped by Mac, as rows in the Bots sidebar. * Opening one opens its chat on that Mac; nothing about a remote Bot is stored * or run on this one. The sidebar narrows `groups` with its search first - * (`remoteBotGroupsMatching`). + * (`remoteBotGroupsMatching`) and passes every Bot as `listed`. */ export function RemoteBotsSection({ groups, + listed = groups, opening, selected = null, onOpen, }: { groups: readonly RemoteBotGroup[]; + /** + * Every paired Mac's Bots before search narrows `groups`. A host's unread + * baseline is taken from these, since a search that hides some of a host's + * Bots would leave their replies out of it. + */ + listed?: readonly RemoteBotGroup[]; /** `hostId/botId` of the Bot whose chat is being opened; a click on any row waits for it. */ opening: string | null; /** `hostId/botId` of the Bot whose chat is open. */ @@ -71,8 +78,8 @@ export function RemoteBotsSection({ // The replies a host's Bots had when this Mac first lists them start read. // The open Bot's chat records what it shows itself (`RemoteBotChatView`). React.useEffect(() => { - for (const { host, bots } of groups) markRemoteBotHostListed(host.id, bots); - }, [groups]); + for (const { host, bots } of listed) markRemoteBotHostListed(host.id, bots); + }, [listed]); if (groups.length === 0) return null; return (
    diff --git a/renderer/main/bots/bot-sidebar.test.tsx b/renderer/main/bots/bot-sidebar.test.tsx index 2eec5d54d9..9036b912bc 100644 --- a/renderer/main/bots/bot-sidebar.test.tsx +++ b/renderer/main/bots/bot-sidebar.test.tsx @@ -732,6 +732,36 @@ test("a paired Mac whose Bot had no message when first listed shows a dot for th assert.ok(within(unread).getByRole("img", { name: "Unread", hidden: true })); }); +test("a paired Mac first listed during a search counts every Bot's reply, also the ones the search hides", async () => { + const queryClient = createBotTestQueryClient(); + queryClient.setQueryData(hostQueryKeys.list(), [ + { id: "host-b", name: "Studio", enabled: true, state: "connected", features: ["bot-durable-session-v1"], capabilities: ["chat:read", "chat:write", "bot:read", "bot:write"] }, + ]); + queryClient.setQueryData(hostQueryKeys.statuses(), [ + { hostId: "host-b", generation: 1, state: { kind: "connected", since: 1 }, feed: "live", stale: false }, + ]); + const at = (offset: number) => new Date(Date.now() - 86_400_000 + offset).toISOString(); + const bot = (id: string, name: string, lastReplyAt: string) => ({ + id, name, purpose: "", avatar: { semantic: { version: 1, shape: "orb", color: "rose" } }, sessionState: "idle", + summarized: true, lastReplyAt, preview: `${name} replied`, + }); + sidebarIpc([], {}, { "bots:list": () => [] }); + await mountSidebar("/bots", queryClient); + fireEvent.click(screen.getByRole("button", { name: "Search Bots" })); + fireEvent.change(screen.getByRole("searchbox", { name: "Search Bots" }), { target: { value: "scout" } }); + // The host's Bots arrive while the search shows only Scout; Planner replied later. + await act(async () => { + queryClient.setQueryData(hostQueryKeys.feed("host-b"), { + hostId: "host-b", epoch: "e1", sequence: 1, stale: false, summaries: [], workspaces: [], runs: [], + bots: [bot("remote-1", "Scout", at(0)), bot("remote-2", "Planner", at(60_000))], + }); + }); + await screen.findByRole("button", { name: "Scout, on Studio" }); + assert.equal(screen.queryByRole("button", { name: /^Planner/u }), null); + fireEvent.change(screen.getByRole("searchbox", { name: "Search Bots" }), { target: { value: "" } }); + assert.ok(await screen.findByRole("button", { name: "Planner, on Studio" }), "Planner's reply was already there"); +}); + test("on a Bots page, a paired Mac's Bots keep up with what that Mac sends", async () => { const host = { id: "host-b", diff --git a/renderer/main/bots/bot-sidebar.tsx b/renderer/main/bots/bot-sidebar.tsx index be22a8fc6c..c711acb8c7 100644 --- a/renderer/main/bots/bot-sidebar.tsx +++ b/renderer/main/bots/bot-sidebar.tsx @@ -558,6 +558,7 @@ export function BotSidebar() { {list}