From 79586155bb2589cc56e941d96a88bea2d1891d00 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:01:00 +0000 Subject: [PATCH 01/16] Load older messages and take back a queued message in a paired Mac's Bot chat Remote revision 67 (provisional) adds two Bot session routes: a page of entries older than one the device holds, projected like its session, and a withdraw for one of the person's queued messages (bot:activity holders; a routine's input or the self-intro reads as gone). No feature tokens, as the server list is full: the desktop treats a 404 as an older host. The remote Bot chat shows Load older messages while the session has older entries, keeps loaded pages across a reconnect of the same epoch, and gives queued rows the same Remove as a local chat. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .memory/bot-chat-activity.md | 6 +- .../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 | 13 ++ .../AidenBackgroundJobsTests.swift | 2 +- ios/AidenOnTheGoTests/AidenBotPlanTests.swift | 2 +- .../AidenBotSessionTests.swift | 2 +- .../AidenRemotePhase0Tests.swift | 4 +- .../services/aiden-remote-bot-session.test.ts | 105 ++++++++++ main/services/aiden-remote-bot-session.ts | 91 ++++++++- main/services/aiden-remote-protocol.test.ts | 43 ++++- main/services/aiden-remote-protocol.ts | 80 +++++++- main/services/aiden-remote-router.test.ts | 68 +++++++ main/services/aiden-remote-router.ts | 70 +++++++ main/services/peer-bot-session-compat.ts | 6 + main/services/peer-operation.test.ts | 30 +++ main/services/peer-operation.ts | 29 ++- main/services/peer-response.ts | 2 + .../aiden-remote/v1/fixtures/contract.json | 4 +- protocol/aiden-remote/v1/openapi.json | 180 ++++++++++++++++++ .../lib/hosts/remote-bot-session-follower.ts | 75 +++++++- renderer/lib/hosts/remote-bot-session.test.ts | 49 +++++ renderer/lib/hosts/remote-bot-session.ts | 50 +++++ renderer/lib/hosts/use-remote-bot-session.ts | 17 +- renderer/main/remote-bot-chat-view.test.tsx | 53 ++++++ renderer/main/remote-bot-chat-view.tsx | 70 ++++++- renderer/shared/peer-operation.ts | 8 +- 30 files changed, 1037 insertions(+), 32 deletions(-) diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index 9c1cdee516..aa05ea8b2b 100644 --- a/.memory/bot-chat-activity.md +++ b/.memory/bot-chat-activity.md @@ -99,11 +99,13 @@ If `main` has moved past 29, change every `30` D introduced to the next free rev ### Parked (full list in spec §17) - Pre-merge bug sweep (PR #479 review and follow-ups), done: Remote — `model_error` is a 409 state refusal (bbd13274e); snapshot and every frame fit the 1 MiB SSE limit by priority allocation (f78443bae, 7aebccfe5). iOS — Chat activity picks stay with their pairing (25574c1ae); a send before the outbox restore never replaces the last launch's file (cc7ae5c6b); Try Again replays the frozen Create through a catalog change (9a2feca96); outbox diagnostics through the typed wrapper (65e00968b); a restore landing after an access-loss purge is dropped (7744dd31b); a New Bot cut off by a relaunch comes back with Try Again (9685204a9, 89b91a071); Files sheet skeletons (7eddc5be8); bounded test waits (d4d63580d); Chat activity reports after leaving and keeps a pick made during a timed-out save (4030c06a5, 978caa670). Android — a restore after an access-loss purge is dropped (e0202df7a); unconfirmed edits never reach the Bot cache's disk (6352bfbad); null literals refused (ea29ffe2f); optimistic New Bot with a Creating… row and same-key Try again, surviving process death (c47d018f6, 212f69254, e348b0131); scheme-derived error text at ≥4.5:1 (4de4bf33f). Test harness — the core-git EPIPE race (3d3cbc959). - 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. +- Overlapping Stops where one fails briefly clear "Stopping" (cosmetic). No Remove for queued messages on phones yet (revision 67 added the route; only the desktop uses it). 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`. - PR 3 (desktop only, no revision): the desktop asks for `bot:cards`, `bot:access-requests` and `bot:plans` (each `own_call`, only when the host lists them) and answers them through new peer ops `botRespondRoutineProposal`, `botAnswerAccessRequest`, `botRespondPlan`. `remote-bot-session.ts` maps plan/access frames onto `snapshot.plan`/`accessRequest` (plan items get place ids; `revision` = the frame's seq) and memory/routine entries onto local rows. `RemoteBotChatView` puts access and pending plan cards in the Needs-you slot, an active plan in the body, echoes sends at once (shared `BotPendingSend` helpers from bot-chat-pane) and shows a re-pair hint group for old pairings (`remoteBotGroups`). Host: `AidenRemoteBotService.list()` leaves out a Bot whose summary fails the contract instead of failing the whole list (and the host feed). -- Still to come: PR 3b (load older, remove a queued message, every waiting approval; next revision), PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). Not planned yet: a model picker for a remote Bot with a model problem (no remote route sets a Bot's model). +- PR 3 follow-up: `peerBotSessionCompat` dropped `accessRequest` and `plan` from session reads, so a reload lost the card; both are now kept (an unreadable one becomes null). +- PR 3b (Remote revision 67, provisional; re-claim at merge): `GET /bots/{botId}/session/entries?before=&limit=` (projector `olderEntries`, same audience as the snapshot; unknown `before` = 409 operation_stale) and `POST /bots/{botId}/queued/{submissionId}/withdraw` (needs `bot:activity`; routine/intro inputs read `gone`; runtime gained `withdraw`). No feature tokens: the server feature list is at its 32-token cap, so the desktop treats a 404 as an older host. Peer ops `botSessionEntries`, `botWithdrawQueued`; the follower's `loadOlder` + `carryOlderRemoteBotEntries` keep loaded pages across same-epoch snapshots. "Every waiting approval" was dropped: the next approval already follows each answer, and a count would need a new opt-in because phone approval decoders are strict. +- Still to come: PR 4 (phones show Needs you), PR 5 (headless server sends the same Bot signals). Not planned yet: a model picker for a remote Bot with a model problem (no remote route sets a Bot's model). diff --git a/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBackgroundJobsTest.kt b/android/app/src/test/java/sbtbiswas/AidenOnTheGo/AidenBackgroundJobsTest.kt index 9132edec1c..028384ef18 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(66, contract.getValue("contractRevision").jsonPrimitive.int) + assertEquals(67, 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 e242325aa1..fc732d7088 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(66, root.getValue("contractRevision").jsonPrimitive.int) + assertEquals(67, 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 ff5873c9c2..fe464b2b75 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(66, root.getValue("contractRevision").jsonPrimitive.int) + assertEquals(67, 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 50c42e8612..8a0e416356 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(66, fixture.getValue("contractRevision").jsonPrimitive.int) + assertEquals(67, 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 3ea7458e0b..283771669d 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. A computer paired before Bots could be shared (it never gave this Mac Bot access) shows "To use 's Bots here, pair this Mac with it again." under its name instead of an empty list. A Bot that computer cannot describe (an edit time before its creation time after a clock change, a name longer than today's limit) is left out of its list rather than emptying the list for every device. 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 you send shows in the chat at once, before that computer has it (it goes away again if that computer refuses it, and the draft stays in the composer). 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, and propose a plan before a long task. Current iOS and Android clients answer those cards, and so does a Mac: the same access card (**Allow once**, **Always for this folder**, **Not now**) and plan card (**Allow once**, **Not now**, then **Stop plan** while it runs) appear in the paired computer's Bot chat under **Needs you**, and the answer goes to that computer, which grants the access there. A computer too old to send them shows a notice to answer there instead. A routine the Bot suggests can be added or turned down from here, and the routine is made on the Bot's computer; a "Memory updated" line says to open the memory there. 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. A computer paired before Bots could be shared (it never gave this Mac Bot access) shows "To use 's Bots here, pair this Mac with it again." under its name instead of an empty list. A Bot that computer cannot describe (an edit time before its creation time after a clock change, a name longer than today's limit) is left out of its list rather than emptying the list for every device. 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 you send shows in the chat at once, before that computer has it (it goes away again if that computer refuses it, and the draft stays in the composer). 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, and propose a plan before a long task. Current iOS and Android clients answer those cards, and so does a Mac: the same access card (**Allow once**, **Always for this folder**, **Not now**) and plan card (**Allow once**, **Not now**, then **Stop plan** while it runs) appear in the paired computer's Bot chat under **Needs you**, and the answer goes to that computer, which grants the access there. A computer too old to send them shows a notice to answer there instead. A routine the Bot suggests can be added or turned down from here, and the routine is made on the Bot's computer; a "Memory updated" line says to open the memory there. A long chat opens at its newest messages, and **Load older messages** at the top shows earlier ones a page at a time. A message queued while the Bot is busy can be taken back with **Remove** before its turn starts. Both need that computer on contract revision 67; with an older one, the chat says the older messages are there, and Remove says to update Aiden there. 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 cc6fa76f3d..5b51118308 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1504,3 +1504,16 @@ Revision 66 is provisional: it was written when `main` was at 65, and the host k **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). + +## Bot chat pages and queued messages, revision 67 (provisional) + +Revision 67 is provisional: it was written when `main` was at 65 and revision 66 was still open, and the host keeps it in one constant (`AIDEN_REMOTE_BOT_SESSION_PAGES_CONTRACT_REVISION`), so claiming the next free number at merge changes only that constant. It adds two Bot session routes and no capability or feature token: the server feature list is already at its 32-token limit, so a client tells an older host apart by its 404. + +**Older entries.** `GET /bots/{botId}/session/entries?before={entryId}&limit={n}` (`getBotSessionEntries`; `bot:read` and `chat:read`, like the session) returns `{ botId, epoch, entries, hasOlder }`: up to `limit` entries (1 to 200, default 50) just older than `before`, oldest first. `before` is required and must be an entry the device's current session holds, usually its oldest. The page is projected exactly as the device's session and stream are (the same opt-ins decide which entries show and what they carry) and fits the session's byte limit, so it may hold fewer than `limit` entries; `hasOlder` is truthful. An entry id the session does not hold (another epoch, a rewritten history, an id the device was never sent) is `409 operation_stale`, and the client reads the session again. A client places a page only onto the same `epoch`. + +**Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. + +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows; a reconnect's snapshot of the same epoch keeps the loaded pages. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. + +**Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). + diff --git a/ios/AidenOnTheGoTests/AidenBackgroundJobsTests.swift b/ios/AidenOnTheGoTests/AidenBackgroundJobsTests.swift index 515be08a3b..2ca18bca1f 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, 66) + XCTAssertEqual(root["contractRevision"] as? Int, 67) 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 9705c78469..3f0dcb0e0c 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, 66) + XCTAssertEqual(root["contractRevision"] as? Int, 67) 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 b672f6dfd1..87160bc618 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, 66) + XCTAssertEqual(root["contractRevision"] as? Int, 67) 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 fa6fef1bed..e76ffc9378 100644 --- a/ios/AidenOnTheGoTests/AidenRemotePhase0Tests.swift +++ b/ios/AidenOnTheGoTests/AidenRemotePhase0Tests.swift @@ -171,7 +171,7 @@ final class AidenRemotePhase0Tests: XCTestCase { from: data ) - XCTAssertEqual(fixture.contractRevision, 66) + XCTAssertEqual(fixture.contractRevision, 67) 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, 66) + XCTAssertEqual(fixture.contractRevision, 67) let recovery = try XCTUnwrap(fixture.streamRecovery) XCTAssertEqual(recovery.capability, .streamSnapshotReasons) XCTAssertEqual(recovery.gapEvents.map(\.sequence), [4097, 4098, 4099]) diff --git a/main/services/aiden-remote-bot-session.test.ts b/main/services/aiden-remote-bot-session.test.ts index 567f4f6913..4388e2ee6b 100644 --- a/main/services/aiden-remote-bot-session.test.ts +++ b/main/services/aiden-remote-bot-session.test.ts @@ -181,6 +181,9 @@ function fakeRuntime(initial: BotSessionState) { async placedSubmissions() { return new Map(); }, + async withdraw() { + return "gone"; + }, }; return { runtime, @@ -4839,3 +4842,105 @@ test("revision 61: a Bot approval carries the typed card only for approval:cards } } }); + +test("a device pages back from the oldest entry it holds to the start of the chat, in order and without repeats", async () => { + const history = Array.from({ length: 260 }, (_, index) => user(index + 1, `Message ${index + 1}`)); + const driven = drivenConversation(history); + const fake = fakeRuntime({ kind: "idle" }); + const service = new AidenRemoteBotSessionService({ + bots: botService(), + runtime: async () => ({ ...fake.runtime, conversation: async () => driven.conversation as never }), + }); + try { + const session = await service.session(BOT_ID); + assert.equal(session.hasOlder, true); + let texts = session.entries.map((entry: any) => entry.text as string); + let before = session.entries[0]!.id; + let hasOlder = true; + let pages = 0; + while (hasOlder) { + const page = await service.olderEntries(BOT_ID, { before, limit: 25 }); + assert.equal(page.epoch, session.epoch, "a page names the session it belongs to"); + assert.ok(page.entries.length > 0 && page.entries.length <= 25); + texts = [...page.entries.map((entry: any) => entry.text as string), ...texts]; + before = page.entries[0]!.id; + hasOlder = page.hasOlder; + pages += 1; + } + assert.ok(pages >= 3); + assert.deepEqual(texts, history.map((_, index) => `Message ${index + 1}`)); + await assert.rejects(service.olderEntries(BOT_ID, { before: "entry_this_device_never_saw" }), { code: "operation_stale" }); + await assert.rejects(service.olderEntries(BOT_ID, { before, limit: 0 }), { code: "invalid_request" }); + } finally { + await service.close(); + } +}); + +test("the person takes back a queued message before its turn: it never runs, and a routine's input is not theirs to take", async () => { + const profileDir = mkdtempSync(path.join(os.tmpdir(), "aiden-remote-bot-withdraw-")); + durableRoots.push(profileDir); + const releases: Array<() => void> = []; + const command = countingTool("run_command", () => new Promise((resolve) => releases.push(() => resolve("done")))); + const fauxModels = createFauxModels([ + fauxAssistantMessage([fauxToolCall("run_command", { text: "tidy" })], { stopReason: "toolUse" }), + fauxAssistantMessage("Tidied."), + fauxAssistantMessage("Inbox is quiet."), + ]); + const runtime = await createBotSessionService({ + profileDir, + models: fauxModels.models, + extension: recordingDeps({ tools: [{ tool: command, replay: "unsafe" }] }), + resolveModel: async () => FAUX_MODEL_REF, + knownBotIds: async () => new Set([BOT_ID]), + }); + const service = new AidenRemoteBotSessionService({ bots: activityBots(), runtime: async () => runtime, turnIntents: createBotTurnIntents() }); + const holder = await openAudienceStream(service, { activity: true }); + const queuedNow = () => { + const frames = holder.frames.filter((frame) => frame.type === "queued" || frame.type === "snapshot"); + const last = frames[frames.length - 1]; + return ((last?.type === "queued" ? last.payload.queued : last?.payload.session.queued) ?? []) as Array<{ submissionId: string }>; + }; + try { + await holder.until(() => holder.frames.length >= 1, "the first snapshot"); + await service.send(DEVICE_ID, BOT_ID, "send-request-withdraw-00001", { text: "Tidy my notes" }); + await waitFor(() => command.executions.length === 1, { what: "the first turn to work" }); + const queued = await service.send(DEVICE_ID, BOT_ID, "send-request-withdraw-00002", { text: "Then forget it", whenBusy: "queue" }); + await holder.until(() => queuedNow().some((message) => message.submissionId === queued.submissionId), "the queued message"); + + const receipt = await service.withdrawQueued(DEVICE_ID, BOT_ID, queued.submissionId, "withdraw-request-0000001", {}); + assert.deepEqual(receipt, { submissionId: queued.submissionId, outcome: "withdrawn" }); + await holder.until(() => queuedNow().length === 0, "the queue to empty"); + assert.deepEqual( + await service.withdrawQueued(DEVICE_ID, BOT_ID, queued.submissionId, "withdraw-request-0000001", {}), + receipt, + "a retried request replays its receipt", + ); + assert.equal( + (await service.withdrawQueued(DEVICE_ID, BOT_ID, queued.submissionId, "withdraw-request-0000002", {})).outcome, + "gone", + ); + + const routine = await runtime.send(BOT_ID, { text: "Check my inbox.", requestId: "routine:task_1:1", label: "Morning brief" }); + assert.equal( + (await service.withdrawQueued(DEVICE_ID, BOT_ID, routine.submissionId, "withdraw-request-0000003", {})).outcome, + "gone", + "a routine's input stays queued", + ); + await assert.rejects(service.withdrawQueued(DEVICE_ID, BOT_ID, "not a submission", "withdraw-request-0000004", {}), { code: "invalid_request" }); + + releases.shift()!(); + await holder.until( + () => holder.frames.some((frame) => frame.type === "entry" && frame.payload.entry.text === "Inbox is quiet."), + "the routine's reply", + ); + await waitFor(async () => (await runtime.state(BOT_ID)).kind === "idle", { what: "the turns to end" }); + const texts = (await service.session(BOT_ID)).entries.map((entry: any) => entry.text); + assert.equal(texts.includes("Then forget it"), false, "the withdrawn message never joined the chat"); + assert.ok(texts.includes("Check my inbox.")); + } finally { + for (const release of releases) release(); + await holder.close(); + await service.close(); + await runtime.shutdown(); + } +}); diff --git a/main/services/aiden-remote-bot-session.ts b/main/services/aiden-remote-bot-session.ts index 4fb7bc9eab..b63dba671a 100644 --- a/main/services/aiden-remote-bot-session.ts +++ b/main/services/aiden-remote-bot-session.ts @@ -117,6 +117,12 @@ import { type AidenRemoteBotRoutineSuggestionList, AIDEN_REMOTE_BOT_PRESETS_MAX, AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES, + AIDEN_REMOTE_BOT_SESSION_PAGE_DEFAULT_LIMIT, + parseAidenRemoteBotSessionEntriesPage, + parseAidenRemoteBotSessionEntryId, + parseAidenRemoteBotSubmissionId, + type AidenRemoteBotQueuedWithdrawReceipt, + type AidenRemoteBotSessionEntriesPage, AIDEN_REMOTE_BOT_SESSION_MAX_TEXT_CHARS, AIDEN_REMOTE_MAX_SSE_FRAME_BYTES, AIDEN_REMOTE_PROTOCOL_VERSION, @@ -259,6 +265,11 @@ export interface AidenRemoteBotSessionRuntime { * the self-intro (`BotSessionRuntime.placedSubmissions`). */ placedSubmissions(botId: string): Promise>; + /** + * Revision 67: take back a queued submission before its turn starts, as the + * desktop's Remove does (`BotSessionService.withdraw`). + */ + withdraw(botId: string, submissionId: string): Promise<"withdrawn" | "started" | "gone">; } export interface AidenRemoteBotSessionServiceOptions { @@ -865,9 +876,10 @@ export function projectBotSessionState( function windowed( entries: AidenRemoteBotSessionEntry[], budgetBytes: number, + maxEntries: number = AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES, ): { entries: AidenRemoteBotSessionEntry[]; hasOlder: boolean } { const limit = Math.min(MAX_SESSION_JSON_BYTES, budgetBytes); - let start = Math.max(0, entries.length - AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES); + let start = Math.max(0, entries.length - Math.min(maxEntries, AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES)); let window = entries.slice(start); while (window.length > 0 && Buffer.byteLength(JSON.stringify(window), "utf8") > limit) { start = Math.min(entries.length, start + Math.max(1, Math.floor(window.length / 4))); @@ -1142,6 +1154,19 @@ class BotLiveProjector { }); } + /** + * Revision 67: up to `limit` entries just older than `before`, as this + * device's session shows them, inside the transcript's byte limit. Null when + * `before` is not an entry this device's session holds (another epoch, or + * an id it was never sent). + */ + olderEntries(audience: Audience, before: string, limit: number): { entries: AidenRemoteBotSessionEntry[]; hasOlder: boolean } | null { + const shown = entriesFor(this.entries, audience); + const index = shown.findIndex((entry) => entry.id === before); + if (index < 0) return null; + return windowed(shown.slice(0, index), MAX_SESSION_JSON_BYTES, limit); + } + private issuesFor(audience: Audience): AidenRemoteBotIssue[] { return audience.accessRequests ? this.issues : this.legacyIssues; } @@ -2697,6 +2722,70 @@ export class AidenRemoteBotSessionService { } } + /** + * Revision 67, `GET /bots/{botId}/session/entries`: the entries just older + * than `before`, as this device's session shows them. A `before` the + * session does not hold is `operation_stale`: read the session again. + */ + async olderEntries( + botId: string, + query: { before: string; limit?: number }, + options: AudienceOptions = {}, + ): Promise { + const before = parseOrInvalid(parseAidenRemoteBotSessionEntryId, query.before, "The session page cursor is invalid."); + const limit = query.limit ?? AIDEN_REMOTE_BOT_SESSION_PAGE_DEFAULT_LIMIT; + if (!Number.isSafeInteger(limit) || limit < 1 || limit > AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES) { + throw new AidenRemoteServiceError("invalid_request", "The session page limit is invalid.", 400); + } + const bot = await this.options.bots.bot(botId); + const audience = this.audience(options); + let projector: BotLiveProjector; + try { + projector = await this.liveProjector(bot.id); + } catch (error) { + return mapSessionError(error, audience); + } + const page = projector.olderEntries(audience, before, limit); + if (!page) throw new AidenRemoteServiceError("operation_stale", "This Bot's chat changed. Read it again.", 409); + return parseAidenRemoteBotSessionEntriesPage({ botId: bot.id, epoch: projector.epoch, ...page }); + } + + /** + * Revision 67, `POST /bots/{botId}/queued/{submissionId}/withdraw`: take + * back one of the person's queued messages. Only the person's own message + * is theirs to take back, so a routine's input or the self-intro reads as + * `gone`, as does an id the host can't find; one whose turn began is + * `started` and stays in the chat. Idempotent per key. + */ + async withdrawQueued( + deviceId: string, + botId: string, + submissionId: string, + key: string, + input: unknown, + ): Promise { + if (!this.supportsActivity) throw new AidenRemoteServiceError("not_found", "This endpoint is unavailable.", 404); + const id = parseOrInvalid(parseAidenRemoteBotSubmissionId, submissionId, "The queued message is invalid."); + parseOrInvalid((value) => parseAidenRemoteEmptyRequest(value, "Bot request"), input ?? {}, "The Bot request is invalid."); + const bot = await this.options.bots.bot(botId); + try { + const receipt = await this.options.bots.executeIdempotent( + { deviceId, route: "POST /bots/{id}/queued/{submissionId}/withdraw", resourceId: `${bot.id}:${id}`, key }, + {}, + async (): Promise => { + const runtime = await this.options.runtime(); + const quiet = await runtime.quietInputs(bot.id, [id]); + if (quiet.get(id) === true) return { submissionId: id, outcome: "gone" }; + return { submissionId: id, outcome: await runtime.withdraw(bot.id, id) }; + }, + ); + await this.afterAction(bot.id); + return receipt; + } catch (error) { + return mapSessionError(error); + } + } + /** SSE: a `snapshot` first, then `partial` / `entry` / `state`, and `closed` when the session closes. */ async openEvents( deviceId: string, diff --git a/main/services/aiden-remote-protocol.test.ts b/main/services/aiden-remote-protocol.test.ts index 666d189cbe..9f342315c7 100644 --- a/main/services/aiden-remote-protocol.test.ts +++ b/main/services/aiden-remote-protocol.test.ts @@ -608,12 +608,14 @@ test("OpenAPI freezes every planned route under authenticated Aiden v1 semantics "/bot-presets", "/bots/from-preset", "/bots/{botId}/session", + "/bots/{botId}/session/entries", "/bots/{botId}/session/events", "/bots/{botId}/messages", "/bots/{botId}/attachments", "/bots/{botId}/attachments/{attachmentId}", "/bots/{botId}/resume", "/bots/{botId}/dismiss", + "/bots/{botId}/queued/{submissionId}/withdraw", "/bots/{botId}/stop", "/bots/{botId}/questions/{waitId}/answer", "/bots/{botId}/handoffs/{waitId}/answer", @@ -1371,10 +1373,12 @@ test("Bot OpenAPI freezes bounded DTOs, conjunctive grants, and privacy-safe rou ["/bot-presets", "get", "200", "BotPresetList"], ["/bots/from-preset", "post", "201", "BotPresetCreateResult"], ["/bots/{botId}/session", "get", "200", "BotSession"], + ["/bots/{botId}/session/entries", "get", "200", "BotSessionEntriesPage"], ["/bots/{botId}/messages", "post", "200", "BotMessageReceipt"], ["/bots/{botId}/attachments", "post", "201", "AttachmentReference"], ["/bots/{botId}/resume", "post", "200", "BotSessionState"], ["/bots/{botId}/dismiss", "post", "200", "BotSessionState"], + ["/bots/{botId}/queued/{submissionId}/withdraw", "post", "200", "BotQueuedWithdrawReceipt"], ["/bots/{botId}/stop", "post", "200", "BotSessionState"], ["/bots/{botId}/questions/{waitId}/answer", "post", "200", "BotQuestionAnswerReceipt"], ["/bots/{botId}/handoffs/{waitId}/answer", "post", "200", "BotHandoffAnswerReceipt"], @@ -3618,7 +3622,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, 66); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 67); assert.equal(section.pending.status, "pending"); assert.equal(section.active.steps[0].status, "done"); const parse = protocol.parseAidenRemoteBotPlan; @@ -3705,7 +3709,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, 66); + assert.equal(protocol.AIDEN_REMOTE_BOT_ALLOWED_CONTRACT_REVISION, 57); assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 67); 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 +3818,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, 66); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 67); const fixture = protocol.parseAidenRemoteContractFixture(raw).stoppedSteps; assert.ok(fixture); assert.deepEqual(fixture.stoppedStepIds, ["tool-3"]); @@ -3922,7 +3926,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, 66); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 67); const parsedFixture = protocol.parseAidenRemoteContractFixture(raw); const section = parsedFixture.streamRecovery; assert.ok(section); @@ -4036,3 +4040,34 @@ test("revision 66 host feed Bot rows carry a one-line preview and refuse anythin assert.equal(feedBot(row), true, JSON.stringify(feedBot.errors)); assert.equal(feedBot({ ...row, preview: "x".repeat(141) }), false); }); + +test("revision 67 session pages and queued withdraw receipts decode strictly and match the OpenAPI contract", async () => { + const protocol = await import("./aiden-remote-protocol.js"); + assert.equal(protocol.AIDEN_REMOTE_BOT_SESSION_PAGES_CONTRACT_REVISION, 67); + assert.equal(protocol.AIDEN_REMOTE_CONTRACT_REVISION, 67); + const raw = await json("fixtures/contract.json") as Record; + const entries = (raw.botSession.entries as unknown[]).slice(0, 2); + const page = { botId: raw.botSession.botId, epoch: raw.botSession.epoch, entries, hasOlder: true }; + assert.deepEqual(protocol.parseAidenRemoteBotSessionEntriesPage(page), page); + assert.throws(() => protocol.parseAidenRemoteBotSessionEntriesPage({ ...page, seq: 3 }), /unsupported field/u); + assert.throws(() => protocol.parseAidenRemoteBotSessionEntriesPage({ ...page, entries: [entries[0], entries[0]] }), /unique/u); + assert.throws(() => protocol.parseAidenRemoteBotSessionEntriesPage({ ...page, hasOlder: undefined })); + const receipt = { submissionId: "42", outcome: "started" }; + assert.deepEqual(protocol.parseAidenRemoteBotQueuedWithdrawReceipt(receipt), receipt); + assert.throws(() => protocol.parseAidenRemoteBotQueuedWithdrawReceipt({ ...receipt, outcome: "cancelled" })); + assert.throws(() => protocol.parseAidenRemoteBotQueuedWithdrawReceipt({ ...receipt, submissionId: "a/b" })); + + 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; paths: Record }; + const ajv = new Ajv2020({ strict: false }); + addFormats(ajv); + const pageSchema = ajv.compile({ $ref: "#/components/schemas/BotSessionEntriesPage", components: spec.components }); + assert.equal(pageSchema(page), true, JSON.stringify(pageSchema.errors)); + assert.equal(pageSchema({ ...page, seq: 3 }), false); + const receiptSchema = ajv.compile({ $ref: "#/components/schemas/BotQueuedWithdrawReceipt", components: spec.components }); + assert.equal(receiptSchema(receipt), true); + assert.equal(receiptSchema({ ...receipt, outcome: "cancelled" }), false); + assert.equal(spec.paths["/bots/{botId}/session/entries"].get.operationId, "getBotSessionEntries"); + assert.equal(spec.paths["/bots/{botId}/queued/{submissionId}/withdraw"].post.operationId, "withdrawBotQueuedMessage"); +}); diff --git a/main/services/aiden-remote-protocol.ts b/main/services/aiden-remote-protocol.ts index 25b0e8c135..16120f80a4 100644 --- a/main/services/aiden-remote-protocol.ts +++ b/main/services/aiden-remote-protocol.ts @@ -381,7 +381,18 @@ export const AIDEN_REMOTE_STREAM_SNAPSHOT_REASONS_CONTRACT_REVISION = 65 as cons * 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; +/** + * Contract revision 67 (provisional; re-claim the next revision after + * `main`'s at merge by changing only this constant): two Bot session routes. + * `GET /bots/{botId}/session/entries?before=&limit=` pages the transcript + * back from an entry the device already has, so a chat can show more than the + * snapshot's window. `POST /bots/{botId}/queued/{submissionId}/withdraw` + * takes back one of the person's queued messages before its turn starts. + * Neither has a feature token, since the server feature list is full: a host + * older than this revision answers both with 404, and the client says so. + */ +export const AIDEN_REMOTE_BOT_SESSION_PAGES_CONTRACT_REVISION = 67 as const; +export const AIDEN_REMOTE_CONTRACT_REVISION = AIDEN_REMOTE_BOT_SESSION_PAGES_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; @@ -2121,6 +2132,32 @@ export interface AidenRemoteBotSession extends AidenRemoteBotSessionStateView { issues?: AidenRemoteBotIssue[]; } +/** + * Revision 67, `GET /bots/{botId}/session/entries?before=&limit=`: the entries + * just older than `before`, oldest first, as the device's session shows them. + * `epoch` is the session the page belongs to; a page from another epoch does + * not join the transcript the device holds. + */ +export interface AidenRemoteBotSessionEntriesPage { + botId: string; + epoch: string; + entries: AidenRemoteBotSessionEntry[]; + hasOlder: boolean; +} + +export const AIDEN_REMOTE_BOT_SESSION_PAGE_DEFAULT_LIMIT = 50; + +export const AIDEN_REMOTE_BOT_QUEUED_WITHDRAW_OUTCOMES = ["withdrawn", "started", "gone"] as const; +/** + * Revision 67, `POST /bots/{botId}/queued/{submissionId}/withdraw`: what + * became of the queued message. `started` means its turn already began, so it + * stays in the chat; `gone` means the host no longer has it to take back. + */ +export interface AidenRemoteBotQueuedWithdrawReceipt { + submissionId: string; + outcome: (typeof AIDEN_REMOTE_BOT_QUEUED_WITHDRAW_OUTCOMES)[number]; +} + export type AidenRemoteBotSessionEventPayload = | { type: "snapshot"; payload: { session: AidenRemoteBotSession } } | { type: "partial"; payload: { text: string } } @@ -6630,6 +6667,47 @@ export function parseAidenRemoteBotSession(value: unknown): AidenRemoteBotSessio }; } +export function parseAidenRemoteBotSessionEntriesPage(value: unknown): AidenRemoteBotSessionEntriesPage { + if (!isRecord(value)) throw new Error("Bot session page must be an object."); + assertExactKeys(value, ["botId", "epoch", "entries", "hasOlder"], "Bot session page"); + if (!Array.isArray(value.entries) || value.entries.length > AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES) { + throw new Error(`Bot session page entries must contain at most ${AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES} items.`); + } + const entries = value.entries.map(parseAidenRemoteBotSessionEntry); + if (new Set(entries.map((entry) => entry.id)).size !== entries.length) { + throw new Error("Bot session page entry ids must be unique."); + } + return { + botId: boundedBotId(value.botId, "Bot session page botId"), + epoch: boundedEpoch(value.epoch, "Bot session page epoch"), + entries, + hasOlder: requiredBooleanValue(value.hasOlder, "Bot session page hasOlder"), + }; +} + +/** The `before` cursor of a session page: an entry id the device already holds. */ +export function parseAidenRemoteBotSessionEntryId(value: unknown): string { + const id = boundedText(value, "Bot session entry id", 128); + if (!BOT_SESSION_ENTRY_ID.test(id)) throw new Error("Bot session entry id is invalid."); + return id; +} + +/** A queued message's `submissionId`, as the session's `queued` list names it. */ +export function parseAidenRemoteBotSubmissionId(value: unknown): string { + const id = boundedText(value, "Bot submissionId", 64); + if (!AIDEN_REMOTE_BOT_SUBMISSION_ID.test(id)) throw new Error("Bot submissionId is invalid."); + return id; +} + +export function parseAidenRemoteBotQueuedWithdrawReceipt(value: unknown): AidenRemoteBotQueuedWithdrawReceipt { + if (!isRecord(value)) throw new Error("Bot queued withdraw receipt must be an object."); + assertExactKeys(value, ["submissionId", "outcome"], "Bot queued withdraw receipt"); + return { + submissionId: parseAidenRemoteBotSubmissionId(value.submissionId), + outcome: enumMember(value.outcome, AIDEN_REMOTE_BOT_QUEUED_WITHDRAW_OUTCOMES, "Bot queued withdraw outcome"), + }; +} + export function parseAidenRemoteBotSessionEvent(value: unknown): AidenRemoteBotSessionEvent { if (!isRecord(value)) throw new Error("Bot session event must be an object."); assertExactKeys(value, ["protocolVersion", "botId", "epoch", "seq", "type", "payload"], "Bot session event"); diff --git a/main/services/aiden-remote-router.test.ts b/main/services/aiden-remote-router.test.ts index 38177ce43a..8e45878215 100644 --- a/main/services/aiden-remote-router.test.ts +++ b/main/services/aiden-remote-router.test.ts @@ -6076,6 +6076,7 @@ test("a bubble's submissionId reaches only a device holding bot:activity, on a f }) as never, quietInputs: async () => new Map(), placedSubmissions: async () => new Map([["1", "17"]]), + withdraw: async () => "gone" as const, }), turnIntents: createBotTurnIntents(), }); @@ -6158,6 +6159,7 @@ test("a send the paused Bot refused is not recorded: once resumed, the same key conversation: async () => { throw new Error("not used"); }, quietInputs: async () => new Map(), placedSubmissions: async () => new Map(), + withdraw: async () => "gone" as const, }), }); const app = await fixture({ @@ -6600,6 +6602,7 @@ test("a phone answers a real hand-off and pauses its Bot over HTTP, while a lega }) as never, quietInputs: async () => new Map(), placedSubmissions: async () => new Map(), + withdraw: async () => "gone" as const, }), }); const holder = await fixture({ @@ -7751,3 +7754,68 @@ test("revision 65 advertises stream:snapshot-reasons only when streams are wired } } }); + +test("revision 67: a device pages back through a Bot's chat and takes back a queued message, each only with the grants the session needs", async () => { + const headers = { authorization: `Bearer ${"a".repeat(43)}`, "aiden-protocol-version": "1" }; + const seen: string[] = []; + const sessions = () => ({ + ...(recordingRevision27Sessions(seen, { memory: false, proactive: false }) as Record), + supportsActivity: true, + olderEntries: async (botId: string, query: { before: string; limit?: number }, options: { activity?: boolean; peers?: boolean } = {}) => { + seen.push(`older:${botId}:${query.before}:${query.limit ?? "default"}:${options.activity === true}`); + return { botId, epoch: "epoch_1", entries: [], hasOlder: false }; + }, + withdrawQueued: async (deviceId: string, botId: string, submissionId: string, key: string, body: unknown) => { + seen.push(`withdraw:${deviceId.slice(-8)}:${botId}:${submissionId}:${key}:${JSON.stringify(body)}`); + return { submissionId, outcome: "withdrawn" }; + }, + }) as unknown as import("./aiden-remote-router.js").AidenRemoteRouterDependencies["botSessions"]; + const withdraw = (base: string, key = "withdraw-key-00000001") => + fetch(`${base}/bots/bot-1/queued/42/withdraw`, { + method: "POST", + headers: { ...headers, "content-type": "application/json", "idempotency-key": key }, + body: "{}", + }); + + const holder = await fixture({ + capabilities: ["server:read", "bot:read", "bot:write", "chat:read", "chat:write", "bot:activity"], + acceptsBotCapabilities: true, + deviceType: "mac", + chatActivity: true, + botSessions: sessions(), + }); + try { + assert.equal((await fetch(`${holder.base}/bots/bot-1/session/entries?before=entry_9&limit=25`, { headers })).status, 200); + assert.equal((await fetch(`${holder.base}/bots/bot-1/session/entries?before=entry_9`, { headers })).status, 200); + for (const query of ["", "?limit=25", "?before=entry_9&limit=0", "?before=entry_9&limit=201", "?before=a/b", "?before=entry_9&x=1"]) { + assert.equal((await fetch(`${holder.base}/bots/bot-1/session/entries${query}`, { headers })).status, 400, query); + } + const receipt = await withdraw(holder.base); + assert.equal(receipt.status, 200); + assert.deepEqual(await receipt.json(), { submissionId: "42", outcome: "withdrawn" }); + const keyless = await fetch(`${holder.base}/bots/bot-1/queued/42/withdraw`, { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: "{}" }); + assert.equal(keyless.status, 400); + } finally { + await holder.close(); + } + + // Without bot:activity the queue is never shown, so nothing in it can be taken back; without chat:read the transcript stays closed. + const reader = await fixture({ + capabilities: ["server:read", "bot:read", "bot:write", "chat:write"], + acceptsBotCapabilities: true, + deviceType: "mac", + chatActivity: true, + botSessions: sessions(), + }); + try { + assert.equal((await fetch(`${reader.base}/bots/bot-1/session/entries?before=entry_9`, { headers })).status, 403); + assert.equal((await withdraw(reader.base)).status, 403); + } finally { + await reader.close(); + } + assert.deepEqual(seen, [ + "older:bot-1:entry_9:25:true", + "older:bot-1:entry_9:default:true", + 'withdraw:12345678:bot-1:42:withdraw-key-00000001:{}', + ]); +}); diff --git a/main/services/aiden-remote-router.ts b/main/services/aiden-remote-router.ts index fe22c58471..f7418eef43 100644 --- a/main/services/aiden-remote-router.ts +++ b/main/services/aiden-remote-router.ts @@ -52,6 +52,7 @@ import { AIDEN_REMOTE_BOT_CONNECTION_REQUESTS_FEATURE, AIDEN_REMOTE_BOT_DELETE_FEATURE, AIDEN_REMOTE_BOT_DURABLE_SESSION_FEATURE, + AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES, AIDEN_REMOTE_BOT_PRESETS_FEATURE, AIDEN_REMOTE_BOT_ROUTINES_FEATURE, AIDEN_REMOTE_BOT_MEMORY_FEATURE, @@ -413,6 +414,9 @@ export interface AidenRemoteRouterDependencies { | "respondPlan" | "supportsAccessRequests" | "answerAccessRequest" + // Contract revision 67: older transcript pages and taking back a queued message. + | "olderEntries" + | "withdrawQueued" // Contract revision 45 (`bot:images`). | "sharedImage" | "supportsSharedImages" @@ -497,6 +501,8 @@ export type AidenRemoteRouteLabel = | "botSession" | "botAttachment" | "botSessionEvents" + | "botSessionEntries" + | "botQueuedWithdraw" | "botSessionImage" | "botQuestionAnswer" | "botAllowed" @@ -611,6 +617,8 @@ export const AIDEN_REMOTE_ROUTE_TEMPLATES: Readonly parses(parseAidenRemoteBotSessionEntry, entry)) }; +} + /** An event this client cannot apply: the session must be read again. */ export interface PeerBotSessionResync { type: "resync"; diff --git a/main/services/peer-operation.test.ts b/main/services/peer-operation.test.ts index 9fb867c08e..8c153fd449 100644 --- a/main/services/peer-operation.test.ts +++ b/main/services/peer-operation.test.ts @@ -64,6 +64,8 @@ test("expanded peer operations resolve to the contract's routes, not arbitrary U [{ 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"], + [{ operation: "botSessionEntries", resourceId: "bot_1", before: "entry_7", limit: 50 }, "getBotSessionEntries"], + [{ operation: "botWithdrawQueued", resourceId: "bot_1", itemId: "42", idempotencyKey: KEY }, "withdrawBotQueuedMessage"], [{ operation: "botSend", resourceId: "bot_1", idempotencyKey: KEY, body: { text: "hi" } }, "sendBotMessage"], [{ operation: "botResume", resourceId: "bot_1", idempotencyKey: KEY }, "resumeBotSession"], [{ operation: "botDismiss", resourceId: "bot_1", idempotencyKey: KEY }, "dismissBotSession"], @@ -585,3 +587,31 @@ test("plan, access-card and routine-suggestion answers send what the host's rout await assert.rejects(peerOperationResult({ operation: "botRespondPlan" }, { ...plan.response, status: "pending" })); await assert.rejects(peerOperationResult({ operation: "botAnswerAccessRequest" }, { answered: false })); }); + +test("a remote Bot chat pages back from its oldest entry and takes back a queued message on the host's own routes", async () => { + const page = peerOperationRequest({ operation: "botSessionEntries", resourceId: "bot_1", before: "entry_7", limit: 50 }); + assert.equal(page.method, "GET"); + assert.equal(page.path, "/bots/bot_1/session/entries?before=entry_7&limit=50"); + assert.equal(peerOperationRequest({ operation: "botSessionEntries", resourceId: "bot_1", before: "entry_7" }).path, "/bots/bot_1/session/entries?before=entry_7"); + for (const bad of [{ before: "a/b" }, {}, { before: "entry_7", limit: 201 }, { before: "entry_7", limit: 0 }]) { + assert.throws(() => peerOperationRequest({ operation: "botSessionEntries", resourceId: "bot_1", ...bad }), JSON.stringify(bad)); + } + const withdraw = peerOperationRequest({ operation: "botWithdrawQueued", resourceId: "bot_1", itemId: "42", idempotencyKey: KEY }); + assert.deepEqual([withdraw.method, withdraw.path, withdraw.body], ["POST", "/bots/bot_1/queued/42/withdraw", {}]); + assert.throws(() => peerOperationRequest({ operation: "botWithdrawQueued", resourceId: "bot_1", itemId: "../x", idempotencyKey: KEY })); + assert.throws(() => peerOperationRequest({ operation: "botWithdrawQueued", resourceId: "bot_1", itemId: "42", idempotencyKey: KEY, body: { now: true } })); + + // A newer host's page is read as far as this Mac understands it; anything else about it must be exact. + const entries = (contract.botSession.entries as unknown[]).slice(0, 2); + const read = (await peerOperationResult( + { operation: "botSessionEntries", resourceId: "bot_1" }, + { botId: "bot_1", epoch: "e1", entries: [...entries, { type: "hand_off", id: "h1", text: "Sign in" }], hasOlder: true }, + )) as { entries: unknown[]; hasOlder: boolean }; + assert.deepEqual(read, { botId: "bot_1", epoch: "e1", entries, hasOlder: true }); + await assert.rejects(peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries })); + assert.deepEqual( + await peerOperationResult({ operation: "botWithdrawQueued", resourceId: "bot_1" }, { submissionId: "42", outcome: "started" }), + { submissionId: "42", outcome: "started" }, + ); + await assert.rejects(peerOperationResult({ operation: "botWithdrawQueued", resourceId: "bot_1" }, { submissionId: "42", outcome: "maybe" })); +}); diff --git a/main/services/peer-operation.ts b/main/services/peer-operation.ts index 4738a32761..84a50df83f 100644 --- a/main/services/peer-operation.ts +++ b/main/services/peer-operation.ts @@ -1,4 +1,4 @@ -import { peerBotSessionCompat } from "./peer-bot-session-compat.js"; +import { peerBotSessionCompat, peerBotSessionPageCompat } from "./peer-bot-session-compat.js"; import { validatePeerResponse } from "./peer-response.js"; import { hostIdentifier } from "../../renderer/shared/peer-host.js"; import type { @@ -24,6 +24,11 @@ import { parseAidenRemoteBotHandoffOpenOnMacReceipt, parseAidenRemoteBotMessageReceipt, parseAidenRemoteBotPlanRespondReceipt, + parseAidenRemoteBotQueuedWithdrawReceipt, + parseAidenRemoteBotSessionEntriesPage, + parseAidenRemoteBotSessionEntryId, + parseAidenRemoteBotSubmissionId, + AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES, parseAidenRemoteBotPlanRespondRequest, parseAidenRemoteBotQuestionAnswerReceipt, parseAidenRemoteBotRoutineProposalId, @@ -101,6 +106,7 @@ export const PEER_BOT_SESSION_MUTATIONS: ReadonlySet = new Set([ "botRespondPlan", "botAnswerAccessRequest", "botRespondRoutineProposal", + "botWithdrawQueued", ]); /** A fork names one message to cut at and, optionally, a summary of what followed. */ @@ -171,6 +177,12 @@ export async function peerOperationResult( await validatePeerResponse(name, session); return parseAidenRemoteBotSession(session); } + if (name === "botSessionEntries") { + // Like the session: an entry this client cannot read is left out. + const page = peerBotSessionPageCompat(value); + await validatePeerResponse(name, page); + return parseAidenRemoteBotSessionEntriesPage(page); + } await validatePeerResponse(name, value); if (name === "summaries") return parseAidenRemoteChatSummaryPage(value, "Peer chat summaries"); @@ -197,6 +209,7 @@ export async function peerOperationResult( if (name === "botRespondPlan") return parseAidenRemoteBotPlanRespondReceipt(value); if (name === "botAnswerAccessRequest") return parseAidenRemoteBotAccessAnswerReceipt(value); if (name === "botRespondRoutineProposal") return parseAidenRemoteBotRoutineProposalRespondResult(value); + if (name === "botWithdrawQueued") return parseAidenRemoteBotQueuedWithdrawReceipt(value); return value; } @@ -399,6 +412,12 @@ export function peerOperationRequest( case "botAvatar": path = `/bots/${id()}/avatar/${item()}`; break; + case "botSessionEntries": + path = `/bots/${id()}/session/entries${query([ + ["before", parseAidenRemoteBotSessionEntryId(input.before)], + ["limit", limit(AIDEN_REMOTE_BOT_SESSION_MAX_ENTRIES)], + ])}`; + break; case "createChat": path = "/chats"; method = "POST"; @@ -591,6 +610,14 @@ export function peerOperationRequest( needsKey = true; body = parseAidenRemoteBotRoutineProposalRespondRequest(input.body); break; + case "botWithdrawQueued": + path = `/bots/${id()}/queued/${parseAidenRemoteBotSubmissionId(input.itemId)}/withdraw`; + method = "POST"; + needsKey = true; + if (input.body !== undefined && Object.keys(peerRecord(input.body)).length > 0) + throw new Error("Invalid peer Bot session request."); + body = {}; + break; case "uploadBotAttachment": // Not keyed, like a chat upload: an unused staged upload expires on the host. path = `/bots/${id()}/attachments`; diff --git a/main/services/peer-response.ts b/main/services/peer-response.ts index 5bb92af34f..d901d335ff 100644 --- a/main/services/peer-response.ts +++ b/main/services/peer-response.ts @@ -54,6 +54,7 @@ const operationIds: Record = { botSession: "getBotSession", botSessionImage: "getBotSessionImage", botAvatar: "getBotAvatarContent", + botSessionEntries: "getBotSessionEntries", botSend: "sendBotMessage", botResume: "resumeBotSession", botDismiss: "dismissBotSession", @@ -67,6 +68,7 @@ const operationIds: Record = { botRespondPlan: "respondBotPlan", botAnswerAccessRequest: "answerBotAccessRequest", botRespondRoutineProposal: "respondBotRoutineProposal", + botWithdrawQueued: "withdrawBotQueuedMessage", uploadBotAttachment: "uploadBotAttachment", removeBotAttachment: "removeBotAttachment", }; diff --git a/protocol/aiden-remote/v1/fixtures/contract.json b/protocol/aiden-remote/v1/fixtures/contract.json index 2917b72d06..988b852134 100644 --- a/protocol/aiden-remote/v1/fixtures/contract.json +++ b/protocol/aiden-remote/v1/fixtures/contract.json @@ -1,5 +1,5 @@ { - "contractRevision": 66, + "contractRevision": 67, "peerRouteAdvertisement": { "feature": "peer-routes-v1", "routes": [ @@ -2299,7 +2299,7 @@ "instanceId": "instance_fixture_01", "displayName": "Fixture Aiden", "platform": "mac", - "contractRevision": 66, + "contractRevision": 67, "pairingRequests": true }, "hostFeedEvents": [ diff --git a/protocol/aiden-remote/v1/openapi.json b/protocol/aiden-remote/v1/openapi.json index 0edf3c3f39..404bdf1303 100644 --- a/protocol/aiden-remote/v1/openapi.json +++ b/protocol/aiden-remote/v1/openapi.json @@ -2293,6 +2293,64 @@ } } }, + "/bots/{botId}/session/entries": { + "parameters": [ + { + "$ref": "#/components/parameters/BotId" + }, + { + "$ref": "#/components/parameters/ProtocolVersion" + } + ], + "get": { + "operationId": "getBotSessionEntries", + "x-aiden-capability": "bot:read", + "x-aiden-capabilities": [ + "bot:read", + "chat:read" + ], + "description": "Revision 67. The entries just older than `before`, oldest first, projected exactly as this device's session is (the same opt-ins decide what shows). `before` must be an entry the device's current session holds; one it does not (another epoch, or an id it was never sent) is 409 operation_stale, and the client reads the session again. Pages fit the session's byte limit, so a page may hold fewer than `limit` entries; `hasOlder` is truthful. A host older than revision 67 answers 404.", + "parameters": [ + { + "name": "before", + "in": "query", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._:-]{1,128}$" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + } + } + ], + "responses": { + "200": { + "description": "One page of older entries", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BotSessionEntriesPage" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + }, "/bots/{botId}/session/events": { "parameters": [ { @@ -2570,6 +2628,71 @@ } } }, + "/bots/{botId}/queued/{submissionId}/withdraw": { + "parameters": [ + { + "$ref": "#/components/parameters/BotId" + }, + { + "name": "submissionId", + "in": "path", + "required": true, + "description": "A queued message's submissionId, as the session's queued list names it.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[A-Za-z0-9._:-]+$" + } + }, + { + "$ref": "#/components/parameters/ProtocolVersion" + } + ], + "post": { + "operationId": "withdrawBotQueuedMessage", + "x-aiden-capability": "bot:write", + "x-aiden-capabilities": [ + "bot:read", + "bot:write", + "chat:write", + "bot:activity" + ], + "description": "Revision 67. Take back one of the person's queued messages before its turn starts, as the host's own Remove does. Requires Idempotency-Key; a repeat replays the original receipt. withdrawn: it will not run. started: its turn already began, so it stays in the chat. gone: the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back. Needs bot:activity, the grant that shows the queue. A host older than revision 67, or one without Bot chat activity, answers 404.", + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "maxProperties": 0 + } + } + } + }, + "responses": { + "200": { + "description": "What became of the queued message", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BotQueuedWithdrawReceipt" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + } + } + }, "/bots/{botId}/stop": { "parameters": [ { @@ -25278,6 +25401,63 @@ "description": "Records the exact earlier durable folder approval, including a replay after removal. It does not confirm current saved access or issue temporary run access." } } + }, + "BotSessionEntriesPage": { + "type": "object", + "description": "Revision 67: one page of a Bot session's older entries.", + "required": [ + "botId", + "epoch", + "entries", + "hasOlder" + ], + "properties": { + "botId": { + "type": "string", + "minLength": 1, + "maxLength": 160, + "pattern": "^[A-Za-z0-9._:-]+$" + }, + "epoch": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "The session the page belongs to. A page from another epoch does not join the transcript the device holds." + }, + "entries": { + "type": "array", + "maxItems": 200, + "items": { + "$ref": "#/components/schemas/BotSessionEntry" + } + }, + "hasOlder": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "BotQueuedWithdrawReceipt": { + "type": "object", + "description": "Revision 67: what became of a queued message.", + "required": [ + "submissionId", + "outcome" + ], + "properties": { + "submissionId": { + "type": "string", + "pattern": "^[A-Za-z0-9._:-]{1,64}$" + }, + "outcome": { + "enum": [ + "withdrawn", + "started", + "gone" + ] + } + }, + "additionalProperties": false } } } diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index 19964d7d07..bceda0627c 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -5,8 +5,18 @@ import type { PeerBotSessionMessage, PeerBotSessionStreamState, PeerBotSessionSubscription } from "../../shared/peer-bot-session"; import type { PeerOperationOutcome } from "../../shared/peer-host"; -import type { AidenRemoteBotSession, AidenRemoteBotSessionEvent } from "../../../main/services/aiden-remote-protocol"; -import { applyRemoteBotSessionEvent, remoteBotSessionView, type RemoteBotSessionView } from "./remote-bot-session"; +import type { + AidenRemoteBotSession, + AidenRemoteBotSessionEntriesPage, + AidenRemoteBotSessionEvent, +} from "../../../main/services/aiden-remote-protocol"; +import { + applyRemoteBotSessionEvent, + carryOlderRemoteBotEntries, + remoteBotSessionView, + withOlderRemoteBotEntries, + type RemoteBotSessionView, +} from "./remote-bot-session"; export interface RemoteBotSessionTransport { subscribe(hostId: string, botId: string): Promise; @@ -14,8 +24,17 @@ export interface RemoteBotSessionTransport { onMessage(handler: (message: PeerBotSessionMessage) => void): () => void; /** `GET /bots/{botId}/session` through the host supervisor. */ read(hostId: string, botId: string): Promise; + /** Contract revision 67: `GET /bots/{botId}/session/entries?before=` through the host supervisor. */ + older?(hostId: string, botId: string, before: string): Promise; } +/** + * What Load older came to: `loaded` (or nothing left to load), `unsupported` + * when the host is older than revision 67, `failed` with the host's reason. + * A page the session moved past reads the session again and reports `loaded`. + */ +export type RemoteBotOlderOutcome = { kind: "loaded" } | { kind: "unsupported" } | { kind: "failed"; message: string }; + export interface RemoteBotSessionState { view: RemoteBotSessionView | null; /** The live stream's connection, for the "Reconnecting" line. */ @@ -41,6 +60,7 @@ export class RemoteBotSessionFollower { private subscribing = false; private resyncPending = false; private buffered: AidenRemoteBotSessionEvent[] = []; + private loadingOlder: Promise | null = null; constructor( private readonly transport: RemoteBotSessionTransport, @@ -81,6 +101,46 @@ export class RemoteBotSessionFollower { void this.read(); }; + /** Contract revision 67: place the page of entries just older than the oldest one shown. One at a time. */ + loadOlder = (): Promise => { + if (this.loadingOlder) return this.loadingOlder; + const view = this.state.view; + if (this.stopped || !view || !view.hasOlder || !view.olderCursor || !this.transport.older) + return Promise.resolve({ kind: this.transport.older ? "loaded" : "unsupported" }); + const { epoch } = view.snapshot; + const request = this.transport.older(this.hostId, this.botId, view.olderCursor).then( + (outcome): RemoteBotOlderOutcome => { + if (this.stopped) return { kind: "loaded" }; + if (!outcome.ok) { + // Older hosts have no such route. + if (outcome.error.status === 404) return { kind: "unsupported" }; + // The session moved on (a new epoch, a rewrite): read it again. + if (outcome.error.status === 409) { + this.reload(); + return { kind: "loaded" }; + } + return { kind: "failed", message: outcome.error.message }; + } + const current = this.state.view; + const page = outcome.value as AidenRemoteBotSessionEntriesPage; + if (!current || current.snapshot.epoch !== epoch || page.epoch !== epoch) { + this.reload(); + return { kind: "loaded" }; + } + this.publish({ view: withOlderRemoteBotEntries(current, page) }); + return { kind: "loaded" }; + }, + (error: unknown): RemoteBotOlderOutcome => ({ + kind: "failed", + message: error instanceof Error ? error.message : "The request failed.", + }), + ); + this.loadingOlder = request.finally(() => { + this.loadingOlder = null; + }); + return this.loadingOlder; + }; + private follow(): void { this.subscribing = true; this.transport.subscribe(this.hostId, this.botId).then( @@ -134,7 +194,10 @@ export class RemoteBotSessionFollower { else this.publish({ failed: outcome.error.message }); return; } - let view: RemoteBotSessionView | null = remoteBotSessionView(outcome.value as AidenRemoteBotSession); + let view: RemoteBotSessionView | null = carryOlderRemoteBotEntries( + this.state.view, + remoteBotSessionView(outcome.value as AidenRemoteBotSession), + ); for (const event of buffered) { if (view === null) break; view = applyRemoteBotSessionEvent(view, event); @@ -167,7 +230,11 @@ export class RemoteBotSessionFollower { this.inFlight = false; this.resyncPending = false; this.buffered = []; - this.publish({ view: remoteBotSessionView(event.payload.session), failed: null, gone: false }); + this.publish({ + view: carryOlderRemoteBotEntries(this.state.view, remoteBotSessionView(event.payload.session)), + failed: null, + gone: false, + }); return; } if (this.inFlight) { diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index afeb15202a..c8eee22d28 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -415,3 +415,52 @@ test("a host's memory line and routine suggestion become this Mac's own transcri { proposalId: "4b1f8a52-7f0e-4b8e-9d55-3f2c1a6b7e10", name: "Morning brief", label: "Weekdays at 8:00 AM" }, ); }); + +test("Load older places the host's earlier page before what is shown, keeps it across a reconnect, and tells an older host apart", async () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + const newest = session({ hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }); + const fake = fakeTransport([newest, newest]); + const asked: string[] = []; + const pages: Record = { + m5: { ok: true, value: { botId: "bot_1", epoch: "e1", entries: [message("m3", "Three"), message("m4", "Four")], hasOlder: true } }, + m3: { ok: true, value: { botId: "bot_1", epoch: "e1", entries: [message("m1", "One"), message("m2", "Two")], hasOlder: false } }, + }; + fake.transport.older = async (_hostId, _botId, before) => { + asked.push(before); + return pages[before]!; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + const texts = () => follower.getState().view!.snapshot.entries.map((entry) => (entry as { text?: string }).text); + assert.deepEqual(await follower.loadOlder(), { kind: "loaded" }); + assert.deepEqual(texts(), ["Three", "Four", "Five", "Six"]); + assert.equal(follower.getState().view!.hasOlder, true); + + // A reconnect's snapshot of the same session keeps what was loaded. + fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six"), message("m7", "Seven")] }) } })); + assert.deepEqual(texts(), ["Three", "Four", "Five", "Six", "Seven"]); + + await follower.loadOlder(); + assert.deepEqual(texts(), ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]); + assert.equal(follower.getState().view!.hasOlder, false); + assert.deepEqual(asked, ["m5", "m3"], "each page ends where the last began"); + + // A new epoch is another transcript: the loaded pages go. + fake.push(event(0, { type: "snapshot", payload: { session: session({ epoch: "e2", seq: 0, hasOlder: true, entries: [message("n1", "New")] }) } }, "e2")); + assert.deepEqual(texts(), ["New"]); + follower.stop(); + + // A host older than revision 67 has no such route; one that moved on is read again. + const old = fakeTransport([newest, newest]); + old.transport.older = async () => ({ ok: false, error: { code: "not_found", message: "This Aiden Remote endpoint does not exist.", status: 404 } }); + const legacy = new RemoteBotSessionFollower(old.transport, "host_a", "bot_1"); + legacy.start(); + await settle(); + assert.deepEqual(await legacy.loadOlder(), { kind: "unsupported" }); + old.transport.older = async () => ({ ok: false, error: { code: "operation_stale", message: "This Bot's chat changed.", status: 409 } }); + assert.deepEqual(await legacy.loadOlder(), { kind: "loaded" }); + await settle(); + assert.equal(old.reads(), 2, "the session is read again"); + legacy.stop(); +}); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index 090b88c5dc..265fdea9bf 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -17,6 +17,7 @@ import type { AidenRemoteBotQueuedMessage, AidenRemoteBotSession, AidenRemoteBotSessionActivity, + AidenRemoteBotSessionEntriesPage, AidenRemoteBotSessionEntry, AidenRemoteBotSessionEvent, AidenRemoteBotSessionStateView, @@ -40,6 +41,10 @@ export interface RemoteBotSessionView { * interrupted again once it is lifted. */ paused: boolean; + /** Contract revision 67: the host holds entries older than the oldest one here. */ + hasOlder: boolean; + /** The host's id of the oldest entry here, drawn or not: where the next older page ends. */ + olderCursor: string | null; } /** @@ -243,6 +248,51 @@ export function remoteBotSessionView(session: AidenRemoteBotSession): RemoteBotS approval: session.approval, handoff: session.handoff ?? null, paused: remoteBotSessionPaused(session), + hasOlder: session.hasOlder, + olderCursor: session.entries[0]?.id ?? null, + }; +} + +/** + * A fresh read or a reconnect's snapshot of the same session keeps the older + * pages this Mac already loaded, when the snapshot's window starts inside + * them. Anything else (another epoch, a gap, a whole transcript) is the + * snapshot as sent. + */ +export function carryOlderRemoteBotEntries( + previous: RemoteBotSessionView | null, + next: RemoteBotSessionView, +): RemoteBotSessionView { + if (!previous || !next.hasOlder || previous.snapshot.epoch !== next.snapshot.epoch) return next; + const first = next.snapshot.entries[0]; + if (!first) return next; + const index = previous.snapshot.entries.findIndex((entry) => entry.id === first.id); + if (index <= 0) return next; + return { + ...next, + snapshot: { ...next.snapshot, entries: [...previous.snapshot.entries.slice(0, index), ...next.snapshot.entries] }, + hasOlder: previous.hasOlder, + olderCursor: previous.olderCursor, + }; +} + +/** + * Contract revision 67: one page of entries older than the view's oldest, + * placed before it. A page from another epoch is not this transcript's: the + * view is returned unchanged and the caller reads the session again. + */ +export function withOlderRemoteBotEntries( + view: RemoteBotSessionView, + page: AidenRemoteBotSessionEntriesPage, +): RemoteBotSessionView { + if (page.botId !== view.snapshot.botId || page.epoch !== view.snapshot.epoch) return view; + const held = new Set(view.snapshot.entries.map((entry) => entry.id)); + const older = entries(page.entries).filter((entry) => !held.has(entry.id)); + return { + ...view, + snapshot: { ...view.snapshot, entries: [...older, ...view.snapshot.entries] }, + hasOlder: page.hasOlder, + olderCursor: page.entries[0]?.id ?? view.olderCursor, }; } diff --git a/renderer/lib/hosts/use-remote-bot-session.ts b/renderer/lib/hosts/use-remote-bot-session.ts index 4db8734bba..3a8db61a70 100644 --- a/renderer/lib/hosts/use-remote-bot-session.ts +++ b/renderer/lib/hosts/use-remote-bot-session.ts @@ -1,12 +1,19 @@ import * as React from "react"; import { peerHostsApi } from "../ipc"; -import { RemoteBotSessionFollower, type RemoteBotSessionState, type RemoteBotSessionTransport } from "./remote-bot-session-follower"; +import { + RemoteBotSessionFollower, + type RemoteBotOlderOutcome, + type RemoteBotSessionState, + type RemoteBotSessionTransport, +} from "./remote-bot-session-follower"; const transport: RemoteBotSessionTransport = { subscribe: (hostId, botId) => peerHostsApi.botSessionSubscribe(hostId, botId), unsubscribe: (subscriptionId) => peerHostsApi.botSessionUnsubscribe(subscriptionId), onMessage: (handler) => peerHostsApi.onBotSession(handler), read: (hostId, botId) => peerHostsApi.call(hostId, { operation: "botSession", resourceId: botId }), + older: (hostId, botId, before) => + peerHostsApi.call(hostId, { operation: "botSessionEntries", resourceId: botId, before }), }; const IDLE: RemoteBotSessionState = { view: null, stream: "waiting", failed: null, gone: false }; @@ -16,7 +23,7 @@ export function useRemoteBotSession( hostId: string, botId: string, enabled = true, -): RemoteBotSessionState & { reload(): void } { +): RemoteBotSessionState & { reload(): void; loadOlder(): Promise } { const [follower, setFollower] = React.useState(null); React.useEffect(() => { if (!enabled) { @@ -34,7 +41,11 @@ export function useRemoteBotSession( current?.getState ?? idleState, ); const reload = React.useCallback(() => current?.reload(), [current]); - return React.useMemo(() => ({ ...state, reload }), [state, reload]); + const loadOlder = React.useCallback( + (): Promise => current?.loadOlder() ?? Promise.resolve({ kind: "loaded" }), + [current], + ); + return React.useMemo(() => ({ ...state, reload, loadOlder }), [state, reload, loadOlder]); } const noSubscribe = () => () => undefined; diff --git a/renderer/main/remote-bot-chat-view.test.tsx b/renderer/main/remote-bot-chat-view.test.tsx index ec0abbfdc9..949eabfce2 100644 --- a/renderer/main/remote-bot-chat-view.test.tsx +++ b/renderer/main/remote-bot-chat-view.test.tsx @@ -8,6 +8,7 @@ import { detectedKeyboardPlatform } from "../shared/keybindings"; import type { PeerHostView } from "../shared/peer-host"; import type { PeerOperation } from "../shared/peer-operation"; import { RemoteBotChatView } from "./remote-bot-chat-view"; +import { toast } from "../components/ui"; import { clearHandoffTaken } from "../components/bots/handoff-taken"; import { AIDEN_CONTENT_REGIONS_SOURCE, @@ -741,3 +742,55 @@ test("a send the other computer refuses takes its echo away and keeps the draft" await waitFor(() => assert.equal(box.value, "Move the dentist to Friday")); await waitFor(() => assert.equal(document.querySelector("[data-bot-pending-send]"), null)); }); + +test("a message waiting for a Bot on another computer can be taken back from here, and an older computer says it can't", async (t) => { + const told: unknown[] = []; + t.mock.method(toast, "info", (message: unknown) => { + told.push(message); + return "toast-id"; + }); + const running = { ...SESSION, state: "running", activity: null, queued: [{ submissionId: "s9", mode: "queue", text: "and Friday?" }] }; + let outcome: unknown = { ok: true, value: { submissionId: "s9", outcome: "started" } }; + const { peerCalls } = await mountCards(running, { botWithdrawQueued: () => outcome }); + const remove = await screen.findByRole("button", { name: "Remove queued message: and Friday?" }); + await act(async () => { + fireEvent.click(remove); + }); + const withdraw = peerCalls().find((call) => call.operation === "botWithdrawQueued")!; + assert.deepEqual([withdraw.resourceId, withdraw.itemId, withdraw.body], ["bot_1", "s9", {}]); + assert.ok(withdraw.idempotencyKey); + await waitFor(() => assert.deepEqual(told, ["That message already started, so it stays."])); + + outcome = { ok: false, error: { code: "not_found", message: "This Aiden Remote endpoint does not exist.", status: 404 } }; + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Remove queued message: and Friday?" })); + }); + await waitFor(() => assert.equal(told.at(-1), "Update Aiden on Studio to remove a waiting message from here.")); +}); + +test("earlier messages of a Bot on another computer load a page at a time above the chat", async () => { + const pages: Record = { + m1: { ok: true, value: { botId: "bot_1", epoch: "e1", entries: [{ type: "message", id: "m0", role: "assistant", text: "Morning! Coffee first?" }], hasOlder: false } }, + }; + const { peerCalls } = await mountCards({ ...SESSION, hasOlder: true }, { botSessionEntries: (operation) => pages[operation.before!] }); + await screen.findByText("Two meetings and a dentist."); + assert.equal(screen.queryByText("Morning! Coffee first?"), null); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Load older messages" })); + }); + await screen.findByText("Morning! Coffee first?"); + assert.equal(peerCalls().find((call) => call.operation === "botSessionEntries")?.before, "m1", "the page ends where the chat began"); + assert.equal(screen.queryByRole("button", { name: "Load older messages" }), null, "nothing older is left"); +}); + +test("a computer too old to page back says where the older messages are", async () => { + await mountCards({ ...SESSION, hasOlder: true }, { + botSessionEntries: () => ({ ok: false, error: { code: "not_found", message: "This Aiden Remote endpoint does not exist.", status: 404 } }), + }); + await screen.findByText("Two meetings and a dentist."); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Load older messages" })); + }); + await screen.findByText("Older messages are on Studio. Update Aiden there to see them here."); + assert.equal(screen.queryByRole("button", { name: "Load older messages" }), null); +}); diff --git a/renderer/main/remote-bot-chat-view.tsx b/renderer/main/remote-bot-chat-view.tsx index b5aafa5b04..395082a588 100644 --- a/renderer/main/remote-bot-chat-view.tsx +++ b/renderer/main/remote-bot-chat-view.tsx @@ -7,7 +7,7 @@ import * as React from "react"; import { useReportGoalView } from "../lib/use-report-goal-view"; import { skipToken, useQuery } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; -import { Ellipsis, Pause, Play, Square } from "lucide-react"; +import { Ellipsis, Loader2, Pause, Play, Square } from "lucide-react"; import { BotAvatar as BotAvatarMark } from "../components/bot-avatar"; import { AskUserQuestionComposer } from "../components/ask-user-question-composer"; import { AccessRequestCard } from "../components/bots/access-request-card"; @@ -229,6 +229,57 @@ export function RemoteBotChatView({ hostId, botId }: { hostId: string; botId: st throw Object.assign(new Error(outcome.error.message || failure), { code: outcome.error.code }); }; + // Contract revision 67: earlier messages, a page at a time. A host older than that keeps them. + const [loadingOlder, setLoadingOlder] = React.useState(false); + const [olderOnHostOnly, setOlderOnHostOnly] = React.useState(false); + const loadOlder = async () => { + setLoadingOlder(true); + try { + const outcome = await live.loadOlder(); + if (outcome.kind === "unsupported") setOlderOnHostOnly(true); + else if (outcome.kind === "failed") toast.error(outcome.message || "Aiden couldn’t load older messages."); + } finally { + setLoadingOlder(false); + } + }; + + // Queued messages taken back here, while the host's answer is on its way. + const [removing, setRemoving] = React.useState>(() => new Set()); + const removeQueued = async (submissionId: string, button: HTMLButtonElement) => { + // The row leaves the page, so keyboard focus moves on first: the next Remove, else the composer. + const removes = Array.from(document.querySelectorAll("[data-bot-queued-remove]")); + const next = removes[removes.indexOf(button) + 1]; + (next ?? composerRef.current)?.focus(); + setRemoving((ids) => new Set(ids).add(submissionId)); + try { + const outcome = await peerHostsApi.call(hostId, { + operation: "botWithdrawQueued", + resourceId: botId, + itemId: submissionId, + idempotencyKey: mintPeerIdempotencyKey(), + body: {}, + }); + if (outcome.ok) { + if ((outcome.value as { outcome?: string }).outcome === "started") toast.info("That message already started, so it stays."); + if (live.stream !== "streaming") live.reload(); + } else if (outcome.error.status === 404) { + toast.info(`Update Aiden on ${hostName} to remove a waiting message from here.`); + } else { + toast.error( + outcome.error.code === "outcome_unknown" + ? `${hostName} may not have received that. Check the chat before trying again.` + : outcome.error.message || "Aiden couldn’t remove that message.", + ); + } + } finally { + setRemoving((ids) => { + const rest = new Set(ids); + rest.delete(submissionId); + return rest; + }); + } + }; + /** Pause the Bot on its own Mac, or lift the pause. The host's stream then carries the new state. */ const setPaused = (pause: boolean) => run("pause", async () => { @@ -888,6 +939,20 @@ export function RemoteBotChatView({ hostId, botId }: { hostId: string; botId: st Reconnecting to {hostName}… ) : null} + {view.hasOlder ? ( + olderOnHostOnly ? ( + + Older messages are on {hostName}. Update Aiden there to see them here. + + ) : ( +
+ +
+ ) + ) : null} void removeQueued(id, button) } : {})} retrying={busy("retry")} onConnect={(pluginId) => void connect(pluginId)} connectLabel={`Finish on ${hostName}`} diff --git a/renderer/shared/peer-operation.ts b/renderer/shared/peer-operation.ts index 363023bfab..2acdc95daa 100644 --- a/renderer/shared/peer-operation.ts +++ b/renderer/shared/peer-operation.ts @@ -28,7 +28,9 @@ export type PeerReadOperation = /** Contract revision 45 (`bot:images`): one shared image's bytes; `itemId` is its entry. */ | "botSessionImage" /** A Bot's photo avatar bytes (`GET /bots/{botId}/avatar/{assetRevision}`); `itemId` is the asset revision. */ - | "botAvatar"; + | "botAvatar" + /** Contract revision 67: the session entries just older than `before` (`GET /bots/{botId}/session/entries`). */ + | "botSessionEntries"; export type PeerWriteOperation = | "createChat" | "send" @@ -78,6 +80,8 @@ export type PeerWriteOperation = | "botAnswerAccessRequest" /** Contract revision 27 (`bot:cards`): accept or dismiss a suggested routine; `itemId` is its `proposalId`. */ | "botRespondRoutineProposal" + /** Contract revision 67 (`bot:activity`): take back a queued message; `itemId` is its `submissionId`. */ + | "botWithdrawQueued" | "uploadBotAttachment" /** `itemId` is the staged attachment. */ | "removeBotAttachment"; @@ -89,7 +93,7 @@ export interface PeerOperation { itemId?: string; workspaceId?: string; cursor?: string; - /** `messagesWindow`: the message ID the window ends before. */ + /** `messagesWindow` and `botSessionEntries`: the message or entry ID the page ends before. */ before?: string; limit?: number; /** `botConversations` search text. */ From f6f3a596bca7a427619f2a6a3447c4273652cdfa Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:05:24 +0000 Subject: [PATCH 02/16] Keep the older-page cursor only while the session has older entries Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- renderer/lib/hosts/remote-bot-session.ts | 7 ++++--- renderer/main/remote-bot-chat-view.test.tsx | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index 265fdea9bf..e8767b15bb 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -43,7 +43,7 @@ export interface RemoteBotSessionView { paused: boolean; /** Contract revision 67: the host holds entries older than the oldest one here. */ hasOlder: boolean; - /** The host's id of the oldest entry here, drawn or not: where the next older page ends. */ + /** While `hasOlder`, the host's id of the oldest entry here, drawn or not: where the next older page ends. */ olderCursor: string | null; } @@ -249,7 +249,8 @@ export function remoteBotSessionView(session: AidenRemoteBotSession): RemoteBotS handoff: session.handoff ?? null, paused: remoteBotSessionPaused(session), hasOlder: session.hasOlder, - olderCursor: session.entries[0]?.id ?? null, + // Only a transcript with more before it needs a place to page back from. + olderCursor: session.hasOlder ? (session.entries[0]?.id ?? null) : null, }; } @@ -292,7 +293,7 @@ export function withOlderRemoteBotEntries( ...view, snapshot: { ...view.snapshot, entries: [...older, ...view.snapshot.entries] }, hasOlder: page.hasOlder, - olderCursor: page.entries[0]?.id ?? view.olderCursor, + olderCursor: page.hasOlder ? (page.entries[0]?.id ?? view.olderCursor) : null, }; } diff --git a/renderer/main/remote-bot-chat-view.test.tsx b/renderer/main/remote-bot-chat-view.test.tsx index 949eabfce2..0769814c56 100644 --- a/renderer/main/remote-bot-chat-view.test.tsx +++ b/renderer/main/remote-bot-chat-view.test.tsx @@ -765,7 +765,7 @@ test("a message waiting for a Bot on another computer can be taken back from her await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Remove queued message: and Friday?" })); }); - await waitFor(() => assert.equal(told.at(-1), "Update Aiden on Studio to remove a waiting message from here.")); + await waitFor(() => assert.equal(told[told.length - 1], "Update Aiden on Studio to remove a waiting message from here.")); }); test("earlier messages of a Bot on another computer load a page at a time above the chat", async () => { From 85123b38cbd98f78b5229792c99f89151b99d6cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:54:44 +0000 Subject: [PATCH 03/16] Fence remote Bot paging against rewrites and decide queued ownership with the abort - Taking back a queued message checks whose message it is inside the Bot's lane, with the abort, so a request racing a routine's send never takes the routine's input. - A same-epoch snapshot can mean the host removed or reordered entries, so older pages kept across it are read again and replaced (or dropped if that fails), and a page asked for before a snapshot is never placed. - A page whose oldest entries this Mac can't show still moves Load older past them: the host supervisor returns the host's own oldest entry as the next cursor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 4 +- .../services/aiden-remote-bot-session.test.ts | 29 ++++++-- main/services/aiden-remote-bot-session.ts | 11 +-- .../bot-runtime/bot-session-service.ts | 11 ++- main/services/peer-bot-session-compat.ts | 15 ++++ main/services/peer-operation.test.ts | 14 +++- main/services/peer-operation.ts | 7 +- .../lib/hosts/remote-bot-session-follower.ts | 71 ++++++++++++++----- renderer/lib/hosts/remote-bot-session.test.ts | 56 ++++++++++++++- renderer/lib/hosts/remote-bot-session.ts | 38 +++++++++- renderer/lib/hosts/use-remote-bot-session.ts | 4 +- 11 files changed, 219 insertions(+), 41 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 91d1e4004d..f8ac19b02e 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1511,9 +1511,9 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Older entries.** `GET /bots/{botId}/session/entries?before={entryId}&limit={n}` (`getBotSessionEntries`; `bot:read` and `chat:read`, like the session) returns `{ botId, epoch, entries, hasOlder }`: up to `limit` entries (1 to 200, default 50) just older than `before`, oldest first. `before` is required and must be an entry the device's current session holds, usually its oldest. The page is projected exactly as the device's session and stream are (the same opt-ins decide which entries show and what they carry) and fits the session's byte limit, so it may hold fewer than `limit` entries; `hasOlder` is truthful. An entry id the session does not hold (another epoch, a rewritten history, an id the device was never sent) is `409 operation_stale`, and the client reads the session again. A client places a page only onto the same `epoch`. -**Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. +**Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows; a reconnect's snapshot of the same epoch keeps the loaded pages. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, and drops them if that fails; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/main/services/aiden-remote-bot-session.test.ts b/main/services/aiden-remote-bot-session.test.ts index 4388e2ee6b..28f0a144d8 100644 --- a/main/services/aiden-remote-bot-session.test.ts +++ b/main/services/aiden-remote-bot-session.test.ts @@ -4921,11 +4921,30 @@ test("the person takes back a queued message before its turn: it never runs, and ); const routine = await runtime.send(BOT_ID, { text: "Check my inbox.", requestId: "routine:task_1:1", label: "Morning brief" }); - assert.equal( - (await service.withdrawQueued(DEVICE_ID, BOT_ID, routine.submissionId, "withdraw-request-0000003", {})).outcome, - "gone", - "a routine's input stays queued", - ); + // A request that raced the routine's send could only have looked before the + // id existed, when nothing marked it as a routine's. Whose message it is must + // be decided with the abort, so even that request leaves the routine queued. + const lookedTooEarly = new Proxy(runtime, { + get: (target, property, receiver) => + property === "quietInputs" + ? async (_botId: string, ids: readonly string[]) => new Map(ids.map((id) => [id, false])) + : Reflect.get(target, property, receiver), + }); + const raced = new AidenRemoteBotSessionService({ bots: activityBots(), runtime: async () => lookedTooEarly, turnIntents: createBotTurnIntents() }); + try { + assert.equal( + (await raced.withdrawQueued(DEVICE_ID, BOT_ID, routine.submissionId, "withdraw-request-0000003", {})).outcome, + "gone", + "a routine's input stays queued", + ); + assert.equal( + (await raced.withdrawQueued(DEVICE_ID, BOT_ID, String(Number(routine.submissionId) + 1000), "withdraw-request-0000005", {})).outcome, + "gone", + "an id the Bot doesn't hold is gone", + ); + } finally { + await raced.close(); + } await assert.rejects(service.withdrawQueued(DEVICE_ID, BOT_ID, "not a submission", "withdraw-request-0000004", {}), { code: "invalid_request" }); releases.shift()!(); diff --git a/main/services/aiden-remote-bot-session.ts b/main/services/aiden-remote-bot-session.ts index b63dba671a..35006bc1e7 100644 --- a/main/services/aiden-remote-bot-session.ts +++ b/main/services/aiden-remote-bot-session.ts @@ -267,9 +267,11 @@ export interface AidenRemoteBotSessionRuntime { placedSubmissions(botId: string): Promise>; /** * Revision 67: take back a queued submission before its turn starts, as the - * desktop's Remove does (`BotSessionService.withdraw`). + * desktop's Remove does (`BotSessionService.withdraw`). `personOnly` makes a + * routine's input, the self-intro or an unknown id `gone`, checked in the + * Bot's lane so a send racing the request is seen. */ - withdraw(botId: string, submissionId: string): Promise<"withdrawn" | "started" | "gone">; + withdraw(botId: string, submissionId: string, options?: { personOnly?: boolean }): Promise<"withdrawn" | "started" | "gone">; } export interface AidenRemoteBotSessionServiceOptions { @@ -2774,9 +2776,8 @@ export class AidenRemoteBotSessionService { {}, async (): Promise => { const runtime = await this.options.runtime(); - const quiet = await runtime.quietInputs(bot.id, [id]); - if (quiet.get(id) === true) return { submissionId: id, outcome: "gone" }; - return { submissionId: id, outcome: await runtime.withdraw(bot.id, id) }; + // Whose message it is is decided in the Bot's lane, with the abort, not before it. + return { submissionId: id, outcome: await runtime.withdraw(bot.id, id, { personOnly: true }) }; }, ); await this.afterAction(bot.id); diff --git a/main/services/bot-runtime/bot-session-service.ts b/main/services/bot-runtime/bot-session-service.ts index ffb5e31557..42205ea2cb 100644 --- a/main/services/bot-runtime/bot-session-service.ts +++ b/main/services/bot-runtime/bot-session-service.ts @@ -241,8 +241,11 @@ export interface BotSessionService { /** * Withdraw one queued message before its turn starts (Pi's * `abortSubmission`). A message already placed in a turn keeps running. + * `personOnly`: only the person's own message may be taken back; a routine's + * input, the self-intro or an id this Bot doesn't hold is `gone`. That check + * runs in the Bot's lane, so a send that allocates the id first is seen. */ - withdraw(botId: string, submissionId: string): Promise; + withdraw(botId: string, submissionId: string, options?: { personOnly?: boolean }): Promise; state(botId: string): Promise; deleteBot(botId: string): Promise; /** @@ -1116,13 +1119,17 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom }); }, - withdraw(botId, submissionId) { + withdraw(botId, submissionId, options = {}) { return serialize(botId, async () => { const id = Number(submissionId); // A rounded id could name a different submission. if (!Number.isSafeInteger(id)) return "gone"; await openBot(botId); const opened = await requireHost().open(botId); + if (options.personOnly) { + const record = (await requireHost().inspect(botId)).submissions.find((candidate) => Number(candidate.id) === id); + if (record === undefined || isQuietSubmission(record)) return "gone"; + } const result = await opened.harness.abortSubmission( id as SubmissionId, ctx, diff --git a/main/services/peer-bot-session-compat.ts b/main/services/peer-bot-session-compat.ts index f032d8c46c..c2db657420 100644 --- a/main/services/peer-bot-session-compat.ts +++ b/main/services/peer-bot-session-compat.ts @@ -16,6 +16,7 @@ import { parseAidenRemoteBotQuestion, parseAidenRemoteBotSessionActivity, parseAidenRemoteBotSessionEntry, + parseAidenRemoteBotSessionEntryId, parseAidenRemoteBotSessionEvent, parseAidenRemoteBotQueuedList, type AidenRemoteBotSessionEvent, @@ -107,6 +108,20 @@ export function peerBotSessionPageCompat(value: unknown): unknown { return { ...value, entries: value.entries.filter((entry) => parses(parseAidenRemoteBotSessionEntry, entry)) }; } +/** + * Where the next older page starts: the oldest entry the host sent, read or + * not. Paging from the oldest entry this client kept would ask for the same + * page again when the oldest ones (or the whole page) are of a kind it can't + * show, and never reach the history before them. + */ +export function peerBotSessionPageCursor(value: unknown): string | undefined { + if (!isRecord(value) || !Array.isArray(value.entries)) return undefined; + for (const entry of value.entries) { + if (isRecord(entry) && parses(parseAidenRemoteBotSessionEntryId, entry.id)) return entry.id as string; + } + return undefined; +} + /** An event this client cannot apply: the session must be read again. */ export interface PeerBotSessionResync { type: "resync"; diff --git a/main/services/peer-operation.test.ts b/main/services/peer-operation.test.ts index 8c153fd449..06f8afc263 100644 --- a/main/services/peer-operation.test.ts +++ b/main/services/peer-operation.test.ts @@ -607,7 +607,19 @@ test("a remote Bot chat pages back from its oldest entry and takes back a queued { operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries: [...entries, { type: "hand_off", id: "h1", text: "Sign in" }], hasOlder: true }, )) as { entries: unknown[]; hasOlder: boolean }; - assert.deepEqual(read, { botId: "bot_1", epoch: "e1", entries, hasOlder: true }); + const oldest = (entries[0] as { id: string }).id; + assert.deepEqual(read, { botId: "bot_1", epoch: "e1", entries, hasOlder: true, olderCursor: oldest }); + // When the oldest entries are of a kind this Mac can't show, the next page still starts at the host's oldest, + // so paging moves past them instead of asking for the same page again. + const unreadable = { type: "hand_off", id: "h0", text: "Sign in" }; + assert.deepEqual( + await peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries: [unreadable, ...entries], hasOlder: true }), + { botId: "bot_1", epoch: "e1", entries, hasOlder: true, olderCursor: "h0" }, + ); + assert.deepEqual( + await peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries: [unreadable], hasOlder: true }), + { botId: "bot_1", epoch: "e1", entries: [], hasOlder: true, olderCursor: "h0" }, + ); await assert.rejects(peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries })); assert.deepEqual( await peerOperationResult({ operation: "botWithdrawQueued", resourceId: "bot_1" }, { submissionId: "42", outcome: "started" }), diff --git a/main/services/peer-operation.ts b/main/services/peer-operation.ts index 84a50df83f..98663a3dd2 100644 --- a/main/services/peer-operation.ts +++ b/main/services/peer-operation.ts @@ -1,4 +1,4 @@ -import { peerBotSessionCompat, peerBotSessionPageCompat } from "./peer-bot-session-compat.js"; +import { peerBotSessionCompat, peerBotSessionPageCompat, peerBotSessionPageCursor } from "./peer-bot-session-compat.js"; import { validatePeerResponse } from "./peer-response.js"; import { hostIdentifier } from "../../renderer/shared/peer-host.js"; import type { @@ -181,7 +181,10 @@ export async function peerOperationResult( // Like the session: an entry this client cannot read is left out. const page = peerBotSessionPageCompat(value); await validatePeerResponse(name, page); - return parseAidenRemoteBotSessionEntriesPage(page); + const parsed = parseAidenRemoteBotSessionEntriesPage(page); + // Not part of the wire page: the host's own oldest entry, for the next request. + const olderCursor = peerBotSessionPageCursor(value); + return olderCursor === undefined ? parsed : { ...parsed, olderCursor }; } await validatePeerResponse(name, value); if (name === "summaries") diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index bceda0627c..f1884fc72d 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -5,27 +5,28 @@ import type { PeerBotSessionMessage, PeerBotSessionStreamState, PeerBotSessionSubscription } from "../../shared/peer-bot-session"; import type { PeerOperationOutcome } from "../../shared/peer-host"; -import type { - AidenRemoteBotSession, - AidenRemoteBotSessionEntriesPage, - AidenRemoteBotSessionEvent, -} from "../../../main/services/aiden-remote-protocol"; +import type { AidenRemoteBotSession, AidenRemoteBotSessionEvent } from "../../../main/services/aiden-remote-protocol"; import { applyRemoteBotSessionEvent, carryOlderRemoteBotEntries, remoteBotSessionView, withOlderRemoteBotEntries, + withRereadOlderRemoteBotEntries, + type RemoteBotSessionEntriesPage, type RemoteBotSessionView, } from "./remote-bot-session"; +/** The host's largest page (`limit`, revision 67). */ +const OLDER_PAGE_MAX = 200; + export interface RemoteBotSessionTransport { subscribe(hostId: string, botId: string): Promise; unsubscribe(subscriptionId: string): Promise; onMessage(handler: (message: PeerBotSessionMessage) => void): () => void; /** `GET /bots/{botId}/session` through the host supervisor. */ read(hostId: string, botId: string): Promise; - /** Contract revision 67: `GET /bots/{botId}/session/entries?before=` through the host supervisor. */ - older?(hostId: string, botId: string, before: string): Promise; + /** Contract revision 67: `GET /bots/{botId}/session/entries?before=&limit=` through the host supervisor. */ + older?(hostId: string, botId: string, before: string, limit?: number): Promise; } /** @@ -61,6 +62,12 @@ export class RemoteBotSessionFollower { private resyncPending = false; private buffered: AidenRemoteBotSessionEvent[] = []; private loadingOlder: Promise | null = null; + /** + * Bumped whenever the shown history is replaced (a snapshot, or older + * entries read again). A page asked for before that belongs to history this + * Mac no longer shows, so it is never placed. + */ + private history = 0; constructor( private readonly transport: RemoteBotSessionTransport, @@ -108,6 +115,7 @@ export class RemoteBotSessionFollower { if (this.stopped || !view || !view.hasOlder || !view.olderCursor || !this.transport.older) return Promise.resolve({ kind: this.transport.older ? "loaded" : "unsupported" }); const { epoch } = view.snapshot; + const history = this.history; const request = this.transport.older(this.hostId, this.botId, view.olderCursor).then( (outcome): RemoteBotOlderOutcome => { if (this.stopped) return { kind: "loaded" }; @@ -121,8 +129,10 @@ export class RemoteBotSessionFollower { } return { kind: "failed", message: outcome.error.message }; } + // The history changed while the page was out; the button reads the new history. + if (history !== this.history) return { kind: "loaded" }; const current = this.state.view; - const page = outcome.value as AidenRemoteBotSessionEntriesPage; + const page = outcome.value as RemoteBotSessionEntriesPage; if (!current || current.snapshot.epoch !== epoch || page.epoch !== epoch) { this.reload(); return { kind: "loaded" }; @@ -194,10 +204,9 @@ export class RemoteBotSessionFollower { else this.publish({ failed: outcome.error.message }); return; } - let view: RemoteBotSessionView | null = carryOlderRemoteBotEntries( - this.state.view, - remoteBotSessionView(outcome.value as AidenRemoteBotSession), - ); + const fresh = remoteBotSessionView(outcome.value as AidenRemoteBotSession); + let view: RemoteBotSessionView | null = carryOlderRemoteBotEntries(this.state.view, fresh); + const carried = view.snapshot.entries.length - fresh.snapshot.entries.length; for (const event of buffered) { if (view === null) break; view = applyRemoteBotSessionEvent(view, event); @@ -206,7 +215,35 @@ export class RemoteBotSessionFollower { void this.read(); return; } + this.history += 1; this.publish({ view, failed: null, gone: false }); + this.rereadCarried(carried, fresh); + } + + /** + * The host may have rewritten history inside the same epoch (a snapshot + * also says so), so older entries kept across a snapshot are read again + * and replaced, or dropped if that fails. + */ + private rereadCarried(carried: number, fresh: RemoteBotSessionView): void { + const view = this.state.view; + if (carried <= 0 || !view) return; + const own = view.snapshot.entries[carried]?.id; + const history = this.history; + const settle = (page: RemoteBotSessionEntriesPage | null) => { + const current = this.state.view; + if (this.stopped || history !== this.history || !current) return; + this.history += 1; + this.publish({ view: withRereadOlderRemoteBotEntries(current, carried, fresh, page) }); + }; + if (!own || !this.transport.older) { + settle(null); + return; + } + this.transport.older(this.hostId, this.botId, own, Math.min(carried, OLDER_PAGE_MAX)).then( + (outcome) => settle(outcome.ok ? (outcome.value as RemoteBotSessionEntriesPage) : null), + () => settle(null), + ); } private receive(message: PeerBotSessionMessage): void { @@ -230,11 +267,11 @@ export class RemoteBotSessionFollower { this.inFlight = false; this.resyncPending = false; this.buffered = []; - this.publish({ - view: carryOlderRemoteBotEntries(this.state.view, remoteBotSessionView(event.payload.session)), - failed: null, - gone: false, - }); + const fresh = remoteBotSessionView(event.payload.session); + const view = carryOlderRemoteBotEntries(this.state.view, fresh); + this.history += 1; + this.publish({ view, failed: null, gone: false }); + this.rereadCarried(view.snapshot.entries.length - fresh.snapshot.entries.length, fresh); return; } if (this.inFlight) { diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index c8eee22d28..23a706aff6 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -16,6 +16,7 @@ import { hostServesBotHandoffs, hostSharesBotSessions, remoteBotSessionView, + withOlderRemoteBotEntries, type RemoteBotSessionView, } from "./remote-bot-session"; @@ -437,14 +438,16 @@ test("Load older places the host's earlier page before what is shown, keeps it a assert.deepEqual(texts(), ["Three", "Four", "Five", "Six"]); assert.equal(follower.getState().view!.hasOlder, true); - // A reconnect's snapshot of the same session keeps what was loaded. + // A reconnect's snapshot of the same session keeps what was loaded, read again from the host. fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six"), message("m7", "Seven")] }) } })); assert.deepEqual(texts(), ["Three", "Four", "Five", "Six", "Seven"]); + await settle(); + assert.deepEqual(texts(), ["Three", "Four", "Five", "Six", "Seven"]); await follower.loadOlder(); assert.deepEqual(texts(), ["One", "Two", "Three", "Four", "Five", "Six", "Seven"]); assert.equal(follower.getState().view!.hasOlder, false); - assert.deepEqual(asked, ["m5", "m3"], "each page ends where the last began"); + assert.deepEqual(asked, ["m5", "m5", "m3"], "each page ends where the last began"); // A new epoch is another transcript: the loaded pages go. fake.push(event(0, { type: "snapshot", payload: { session: session({ epoch: "e2", seq: 0, hasOlder: true, entries: [message("n1", "New")] }) } }, "e2")); @@ -464,3 +467,52 @@ test("Load older places the host's earlier page before what is shown, keeps it a assert.equal(old.reads(), 2, "the session is read again"); legacy.stop(); }); + +test("a snapshot that rewrote loaded history replaces it, and a page asked for before the snapshot is never placed", async () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + const newest = session({ hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }); + const fake = fakeTransport([newest]); + // The host's history: "Four" is a routine's input that a later [SILENT] turn hides. + let history = [message("m1", "One"), message("m2", "Two"), message("m3", "Three"), message("m4", "Four")]; + const asked: Array<[string, number | undefined]> = []; + let hold: (() => void) | null = null; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + if (hold === null && asked.length === 3) await new Promise((resolve) => (hold = resolve)); + const end = before === "m5" ? history.length : history.findIndex((entry) => entry.id === before); + const start = Math.max(0, end - (limit ?? 2)); + return { ok: true, value: { botId: "bot_1", epoch: "e1", entries: history.slice(start, end), hasOlder: start > 0 } }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + const texts = () => follower.getState().view!.snapshot.entries.map((entry) => (entry as { text?: string }).text); + await follower.loadOlder(); + assert.deepEqual(texts(), ["Three", "Four", "Five", "Six"]); + + // The host hides "Four" and sends a snapshot of the same epoch: it is gone once the loaded part is read again. + history = history.filter((entry) => entry.id !== "m4"); + fake.push(event(3, { type: "snapshot", payload: { session: session({ seq: 4, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }) } })); + await settle(); + assert.deepEqual(texts(), ["Two", "Three", "Five", "Six"]); + assert.deepEqual(asked[1], ["m5", 2], "the loaded part is read again, as many entries as were kept"); + + // A Load older that is out when another snapshot arrives belongs to the history before it. + const pending = follower.loadOlder(); + await settle(); + fake.push(event(5, { type: "snapshot", payload: { session: session({ seq: 6, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }) } })); + await settle(); + hold!(); + assert.deepEqual(await pending, { kind: "loaded" }); + await settle(); + assert.equal(texts().includes("One"), false, "the page asked for before the snapshot was not placed"); + follower.stop(); +}); + +test("a page whose entries this Mac can't show still moves Load older past them", () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + const view = remoteBotSessionView(session({ hasOlder: true, entries: [message("m5", "Five")] })); + const skipped = withOlderRemoteBotEntries(view, { botId: "bot_1", epoch: "e1", entries: [], hasOlder: true, olderCursor: "h3" }); + assert.equal(skipped.olderCursor, "h3", "the next page starts before the entries left out"); + assert.equal(skipped.hasOlder, true); +}); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index e8767b15bb..094a38ee9a 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -254,11 +254,22 @@ export function remoteBotSessionView(session: AidenRemoteBotSession): RemoteBotS }; } +/** + * A page of older entries as the host supervisor returns it: the wire page + * plus `olderCursor`, the oldest entry the host sent (read or not), where the + * next page starts. Entries this Mac can't read are already left out, so the + * page's own oldest entry may be newer than that, or missing. + */ +export type RemoteBotSessionEntriesPage = AidenRemoteBotSessionEntriesPage & { olderCursor?: string }; + /** * A fresh read or a reconnect's snapshot of the same session keeps the older * pages this Mac already loaded, when the snapshot's window starts inside * them. Anything else (another epoch, a gap, a whole transcript) is the - * snapshot as sent. + * snapshot as sent. A snapshot can also mean the host rewrote its history + * (removed or reordered entries) within the same epoch, so what this keeps is + * provisional: the follower reads those entries again and replaces them + * (`withRereadOlderRemoteBotEntries`), or drops them if it can't. */ export function carryOlderRemoteBotEntries( previous: RemoteBotSessionView | null, @@ -284,7 +295,7 @@ export function carryOlderRemoteBotEntries( */ export function withOlderRemoteBotEntries( view: RemoteBotSessionView, - page: AidenRemoteBotSessionEntriesPage, + page: RemoteBotSessionEntriesPage, ): RemoteBotSessionView { if (page.botId !== view.snapshot.botId || page.epoch !== view.snapshot.epoch) return view; const held = new Set(view.snapshot.entries.map((entry) => entry.id)); @@ -293,10 +304,31 @@ export function withOlderRemoteBotEntries( ...view, snapshot: { ...view.snapshot, entries: [...older, ...view.snapshot.entries] }, hasOlder: page.hasOlder, - olderCursor: page.hasOlder ? (page.entries[0]?.id ?? view.olderCursor) : null, + olderCursor: page.hasOlder ? (page.olderCursor ?? page.entries[0]?.id ?? view.olderCursor) : null, }; } +/** + * The first `carried` entries of `view` were kept from before a snapshot + * (`carryOlderRemoteBotEntries`); `page` is those entries read again from the + * host, just older than the snapshot's own. They are replaced with the page, + * so history the host removed or reordered doesn't stay. Without a page, or + * with one from another epoch, they are dropped and the snapshot's own + * "older" state comes back. + */ +export function withRereadOlderRemoteBotEntries( + view: RemoteBotSessionView, + carried: number, + snapshot: Pick, + page: RemoteBotSessionEntriesPage | null, +): RemoteBotSessionView { + const own = view.snapshot.entries.slice(carried); + if (page === null || page.botId !== view.snapshot.botId || page.epoch !== view.snapshot.epoch) { + return { ...view, snapshot: { ...view.snapshot, entries: own }, ...snapshot }; + } + return withOlderRemoteBotEntries({ ...view, snapshot: { ...view.snapshot, entries: own } }, page); +} + /** * Apply one stream event. Returns null when it cannot be applied (another * epoch, or a gap in `seq`): the caller reads the session again. diff --git a/renderer/lib/hosts/use-remote-bot-session.ts b/renderer/lib/hosts/use-remote-bot-session.ts index 3a8db61a70..dd2bf0d5a8 100644 --- a/renderer/lib/hosts/use-remote-bot-session.ts +++ b/renderer/lib/hosts/use-remote-bot-session.ts @@ -12,8 +12,8 @@ const transport: RemoteBotSessionTransport = { unsubscribe: (subscriptionId) => peerHostsApi.botSessionUnsubscribe(subscriptionId), onMessage: (handler) => peerHostsApi.onBotSession(handler), read: (hostId, botId) => peerHostsApi.call(hostId, { operation: "botSession", resourceId: botId }), - older: (hostId, botId, before) => - peerHostsApi.call(hostId, { operation: "botSessionEntries", resourceId: botId, before }), + older: (hostId, botId, before, limit) => + peerHostsApi.call(hostId, { operation: "botSessionEntries", resourceId: botId, before, ...(limit === undefined ? {} : { limit }) }), }; const IDLE: RemoteBotSessionState = { view: null, stream: "waiting", failed: null, gone: false }; From e8c218b5819a2e8da4ffda2057a7bd1a3d4419af Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:10:18 +0000 Subject: [PATCH 04/16] Re-read all carried Bot history across a snapshot, a bounded page at a time A same-epoch snapshot re-read only one 200-entry page and then dropped the rest of the loaded history. Read pages until every kept entry is covered, and keep the pages read so far if a later one fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 43 +++++++++++----- renderer/lib/hosts/remote-bot-session.test.ts | 51 +++++++++++++++++++ renderer/lib/hosts/remote-bot-session.ts | 26 ++++++---- 4 files changed, 99 insertions(+), 23 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index f8ac19b02e..7da59e9209 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, and drops them if that fails; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until all of them are covered; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index f1884fc72d..898bf398d8 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -222,28 +222,47 @@ export class RemoteBotSessionFollower { /** * The host may have rewritten history inside the same epoch (a snapshot - * also says so), so older entries kept across a snapshot are read again - * and replaced, or dropped if that fails. + * also says so), so older entries kept across a snapshot are read again, a + * bounded page at a time until all of them are covered, and replaced. A read + * that fails keeps the pages already read (Load older continues from there), + * or drops the kept entries if none was. */ private rereadCarried(carried: number, fresh: RemoteBotSessionView): void { const view = this.state.view; if (carried <= 0 || !view) return; const own = view.snapshot.entries[carried]?.id; const history = this.history; - const settle = (page: RemoteBotSessionEntriesPage | null) => { - const current = this.state.view; - if (this.stopped || history !== this.history || !current) return; + const current = () => !this.stopped && history === this.history && this.state.view !== null; + const settle = (pages: RemoteBotSessionEntriesPage[]) => { + const latest = this.state.view; + if (!current() || !latest) return; this.history += 1; - this.publish({ view: withRereadOlderRemoteBotEntries(current, carried, fresh, page) }); + this.publish({ view: withRereadOlderRemoteBotEntries(latest, carried, fresh, pages) }); }; - if (!own || !this.transport.older) { - settle(null); + const { transport } = this; + if (!own || !transport.older) { + settle([]); return; } - this.transport.older(this.hostId, this.botId, own, Math.min(carried, OLDER_PAGE_MAX)).then( - (outcome) => settle(outcome.ok ? (outcome.value as RemoteBotSessionEntriesPage) : null), - () => settle(null), - ); + const pages: RemoteBotSessionEntriesPage[] = []; + const next = (before: string, read: number): void => { + if (!transport.older) return settle(pages); + transport.older(this.hostId, this.botId, before, Math.min(Math.max(carried - read, 1), OLDER_PAGE_MAX)).then( + (outcome) => { + if (!current()) return; + if (!outcome.ok) return settle(pages); + const page = outcome.value as RemoteBotSessionEntriesPage; + pages.push(page); + const total = read + page.entries.length; + const cursor = page.olderCursor ?? page.entries[0]?.id; + // Every kept entry is covered, or the host has nothing older. + if (total >= carried || !page.hasOlder || !cursor || cursor === before) return settle(pages); + next(cursor, total); + }, + () => settle(pages), + ); + }; + next(own, 0); } private receive(message: PeerBotSessionMessage): void { diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 23a706aff6..e6ac78500c 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -509,6 +509,57 @@ test("a snapshot that rewrote loaded history replaces it, and a page asked for b follower.stop(); }); +test("loaded history longer than one page survives a same-epoch snapshot whole, and a rewrite in its oldest page still shows", async () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + let history = Array.from({ length: 450 }, (_, index) => message(`h${index}`, `Message ${index}`)); + const newest = () => session({ seq: 4, hasOlder: true, entries: history.slice(-2) }); + const fake = fakeTransport([newest()]); + const asked: Array<[string, number | undefined]> = []; + let failAt: number | null = null; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + if (failAt === asked.length) return { ok: false, error: { code: "failed", message: "Offline.", status: 503 } }; + const end = history.findIndex((entry) => entry.id === before); + const start = Math.max(0, end - (limit ?? 150)); + return { ok: true, value: { botId: "bot_1", epoch: "e1", entries: history.slice(start, end), hasOlder: start > 0 } }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + const ids = () => follower.getState().view!.snapshot.entries.map((entry) => entry.id); + await follower.loadOlder(); + await follower.loadOlder(); + const loaded = history.slice(-302).map((entry) => entry.id); + assert.deepEqual(ids(), loaded); + + // Nothing changed on the host: every one of the 300 loaded entries stays. + asked.length = 0; + fake.push(event(4, { type: "snapshot", payload: { session: newest() } })); + await settle(); + assert.deepEqual(ids(), loaded); + assert.equal(follower.getState().view!.olderCursor, loaded[0]); + assert.ok(asked.every(([, limit]) => limit !== undefined && limit <= 200), "each read is a bounded page"); + + // The host hides the oldest loaded entry: it goes, and the rest stays. + history = history.filter((entry) => entry.id !== loaded[0]); + fake.push(event(4, { type: "snapshot", payload: { session: newest() } })); + await settle(); + assert.equal(ids().includes(loaded[0]!), false); + assert.deepEqual(ids().slice(-301), loaded.slice(1)); + + // A later page that fails keeps the pages already read, and Load older continues from there. + asked.length = 0; + failAt = 2; + fake.push(event(4, { type: "snapshot", payload: { session: newest() } })); + await settle(); + const kept = ids(); + assert.equal(kept.length, 202); + assert.deepEqual(kept, loaded.slice(-202)); + assert.equal(follower.getState().view!.hasOlder, true); + assert.equal(follower.getState().view!.olderCursor, kept[0]); + follower.stop(); +}); + test("a page whose entries this Mac can't show still moves Load older past them", () => { const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); const view = remoteBotSessionView(session({ hasOlder: true, entries: [message("m5", "Five")] })); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index 094a38ee9a..c2d08a52d8 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -310,23 +310,29 @@ export function withOlderRemoteBotEntries( /** * The first `carried` entries of `view` were kept from before a snapshot - * (`carryOlderRemoteBotEntries`); `page` is those entries read again from the - * host, just older than the snapshot's own. They are replaced with the page, - * so history the host removed or reordered doesn't stay. Without a page, or - * with one from another epoch, they are dropped and the snapshot's own - * "older" state comes back. + * (`carryOlderRemoteBotEntries`); `pages` are that history read again from the + * host, newest page first, each just older than the one before it, starting + * just older than the snapshot's own entries. The kept entries are replaced + * with the pages, so history the host removed or reordered doesn't stay. Pages + * that stop short of the kept range (a later page failed) leave Load older + * where the last one ends. Without a page, or with one from another epoch, the + * kept entries are dropped and the snapshot's own "older" state comes back. */ export function withRereadOlderRemoteBotEntries( view: RemoteBotSessionView, carried: number, snapshot: Pick, - page: RemoteBotSessionEntriesPage | null, + pages: readonly RemoteBotSessionEntriesPage[] | null, ): RemoteBotSessionView { - const own = view.snapshot.entries.slice(carried); - if (page === null || page.botId !== view.snapshot.botId || page.epoch !== view.snapshot.epoch) { - return { ...view, snapshot: { ...view.snapshot, entries: own }, ...snapshot }; + const own: RemoteBotSessionView = { ...view, snapshot: { ...view.snapshot, entries: view.snapshot.entries.slice(carried) } }; + if ( + !pages || + pages.length === 0 || + pages.some((page) => page.botId !== view.snapshot.botId || page.epoch !== view.snapshot.epoch) + ) { + return { ...own, ...snapshot }; } - return withOlderRemoteBotEntries({ ...view, snapshot: { ...view.snapshot, entries: own } }, page); + return pages.reduce(withOlderRemoteBotEntries, own); } /** From 9ff30540a6736643fabce53d05fcaae47a014bc5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:19:10 +0000 Subject: [PATCH 05/16] Count a newer host's unshown entries when re-reading kept Bot history Bound the re-read by the entries the host sent, read or not, so pages of entry kinds this Mac filters out can't walk it past the kept range. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- main/services/peer-operation.test.ts | 6 +-- main/services/peer-operation.ts | 6 ++- .../lib/hosts/remote-bot-session-follower.ts | 7 ++- renderer/lib/hosts/remote-bot-session.test.ts | 43 +++++++++++++++++++ renderer/lib/hosts/remote-bot-session.ts | 7 +-- 6 files changed, 60 insertions(+), 11 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 7da59e9209..9dc891edb5 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until all of them are covered; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until as many of the host's entries as were kept have been read (entries this Mac can't show count too, so the re-read never goes further back than the kept range); if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/main/services/peer-operation.test.ts b/main/services/peer-operation.test.ts index 06f8afc263..3a04b1c45d 100644 --- a/main/services/peer-operation.test.ts +++ b/main/services/peer-operation.test.ts @@ -608,17 +608,17 @@ test("a remote Bot chat pages back from its oldest entry and takes back a queued { botId: "bot_1", epoch: "e1", entries: [...entries, { type: "hand_off", id: "h1", text: "Sign in" }], hasOlder: true }, )) as { entries: unknown[]; hasOlder: boolean }; const oldest = (entries[0] as { id: string }).id; - assert.deepEqual(read, { botId: "bot_1", epoch: "e1", entries, hasOlder: true, olderCursor: oldest }); + assert.deepEqual(read, { botId: "bot_1", epoch: "e1", entries, hasOlder: true, olderCursor: oldest, hostCount: 3 }); // When the oldest entries are of a kind this Mac can't show, the next page still starts at the host's oldest, // so paging moves past them instead of asking for the same page again. const unreadable = { type: "hand_off", id: "h0", text: "Sign in" }; assert.deepEqual( await peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries: [unreadable, ...entries], hasOlder: true }), - { botId: "bot_1", epoch: "e1", entries, hasOlder: true, olderCursor: "h0" }, + { botId: "bot_1", epoch: "e1", entries, hasOlder: true, olderCursor: "h0", hostCount: 3 }, ); assert.deepEqual( await peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries: [unreadable], hasOlder: true }), - { botId: "bot_1", epoch: "e1", entries: [], hasOlder: true, olderCursor: "h0" }, + { botId: "bot_1", epoch: "e1", entries: [], hasOlder: true, olderCursor: "h0", hostCount: 1 }, ); await assert.rejects(peerOperationResult({ operation: "botSessionEntries", resourceId: "bot_1" }, { botId: "bot_1", epoch: "e1", entries })); assert.deepEqual( diff --git a/main/services/peer-operation.ts b/main/services/peer-operation.ts index 98663a3dd2..42682bd68f 100644 --- a/main/services/peer-operation.ts +++ b/main/services/peer-operation.ts @@ -182,9 +182,11 @@ export async function peerOperationResult( const page = peerBotSessionPageCompat(value); await validatePeerResponse(name, page); const parsed = parseAidenRemoteBotSessionEntriesPage(page); - // Not part of the wire page: the host's own oldest entry, for the next request. + // Not part of the wire page: the host's own oldest entry, for the next request, + // and how many entries the host sent, read or not, so paging is counted in its entries. const olderCursor = peerBotSessionPageCursor(value); - return olderCursor === undefined ? parsed : { ...parsed, olderCursor }; + const hostCount = (value as { entries: unknown[] }).entries.length; + return { ...parsed, ...(olderCursor === undefined ? {} : { olderCursor }), hostCount }; } await validatePeerResponse(name, value); if (name === "summaries") diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index 898bf398d8..a745328cae 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -223,7 +223,8 @@ export class RemoteBotSessionFollower { /** * The host may have rewritten history inside the same epoch (a snapshot * also says so), so older entries kept across a snapshot are read again, a - * bounded page at a time until all of them are covered, and replaced. A read + * bounded page at a time until as many host entries as were kept are read + * (at most one more request per 200 kept), and replaced. A read * that fails keeps the pages already read (Load older continues from there), * or drops the kept entries if none was. */ @@ -253,7 +254,9 @@ export class RemoteBotSessionFollower { if (!outcome.ok) return settle(pages); const page = outcome.value as RemoteBotSessionEntriesPage; pages.push(page); - const total = read + page.entries.length; + // Counted in the host's entries, read or not: entries this Mac leaves out + // still use up the kept range, so a newer host's pages never walk past it. + const total = read + (page.hostCount ?? page.entries.length); const cursor = page.olderCursor ?? page.entries[0]?.id; // Every kept entry is covered, or the host has nothing older. if (total >= carried || !page.hasOlder || !cursor || cursor === before) return settle(pages); diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index e6ac78500c..441043a3df 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -560,6 +560,49 @@ test("loaded history longer than one page survives a same-epoch snapshot whole, follower.stop(); }); +test("re-reading kept history from a newer host counts the entries this Mac leaves out, so it never walks past the kept range", async () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + const newest = session({ hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }); + const fake = fakeTransport([newest]); + // The host, newer than this Mac: two entries of a kind this Mac can't show sit just before "Five". + const host = ["m1", "m2", "m3", "m4", "u1", "u2"]; + const asked: Array<[string, number | undefined]> = []; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + const end = before === "m5" ? host.length : host.indexOf(before); + const start = Math.max(0, end - (limit ?? 2)); + const sent = host.slice(start, end); + return { + ok: true, + value: { + botId: "bot_1", epoch: "e1", hasOlder: start > 0, olderCursor: sent[0], hostCount: sent.length, + entries: sent.filter((id) => id.startsWith("m")).map((id) => message(id, id)), + }, + }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + const ids = () => follower.getState().view!.snapshot.entries.map((entry) => entry.id); + // Two Load olders: an all-unknown page, then "m3" and "m4". + await follower.loadOlder(); + assert.deepEqual(ids(), ["m5", "m6"]); + await follower.loadOlder(); + assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); + + // A snapshot keeps 2 shown entries; the host's 2 newest older ones are unknown, and re-reading stops there. + asked.length = 0; + fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }) } })); + await settle(); + assert.deepEqual(asked, [["m5", 2]], "one request, for as many host entries as were kept"); + assert.deepEqual(ids(), ["m5", "m6"]); + assert.equal(follower.getState().view!.hasOlder, true); + assert.equal(follower.getState().view!.olderCursor, "u1", "Load older continues past the entries left out"); + await follower.loadOlder(); + assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); + follower.stop(); +}); + test("a page whose entries this Mac can't show still moves Load older past them", () => { const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); const view = remoteBotSessionView(session({ hasOlder: true, entries: [message("m5", "Five")] })); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index c2d08a52d8..382e71d8de 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -257,10 +257,11 @@ export function remoteBotSessionView(session: AidenRemoteBotSession): RemoteBotS /** * A page of older entries as the host supervisor returns it: the wire page * plus `olderCursor`, the oldest entry the host sent (read or not), where the - * next page starts. Entries this Mac can't read are already left out, so the - * page's own oldest entry may be newer than that, or missing. + * next page starts, and `hostCount`, how many entries the host sent. Entries + * this Mac can't read are already left out, so the page's own oldest entry may + * be newer than that, or missing, and it may hold fewer than `hostCount`. */ -export type RemoteBotSessionEntriesPage = AidenRemoteBotSessionEntriesPage & { olderCursor?: string }; +export type RemoteBotSessionEntriesPage = AidenRemoteBotSessionEntriesPage & { olderCursor?: string; hostCount?: number }; /** * A fresh read or a reconnect's snapshot of the same session keeps the older From 17dd2104d77f8ac145d49f402f72c18cf50fa7c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:26:45 +0000 Subject: [PATCH 06/16] Re-read kept Bot history to its oldest entry, bounded by the host span it covered Track how many host entries the loaded pages spanned (drawn or not) and re-read until the oldest kept entry, or that span if the host dropped it, so messages older than entries this Mac can't show stay after a snapshot. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 20 +++++++------ renderer/lib/hosts/remote-bot-session.test.ts | 28 +++++++++++++------ renderer/lib/hosts/remote-bot-session.ts | 20 ++++++++++++- 4 files changed, 50 insertions(+), 20 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 9dc891edb5..da4d76bb42 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until as many of the host's entries as were kept have been read (entries this Mac can't show count too, so the re-read never goes further back than the kept range); if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, or, if the host no longer has that entry, until it has read as many host entries as the loaded pages spanned (entries this Mac can't show count too, so the re-read covers the same range and never goes further back); if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index a745328cae..a01861054b 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -223,15 +223,18 @@ export class RemoteBotSessionFollower { /** * The host may have rewritten history inside the same epoch (a snapshot * also says so), so older entries kept across a snapshot are read again, a - * bounded page at a time until as many host entries as were kept are read - * (at most one more request per 200 kept), and replaced. A read - * that fails keeps the pages already read (Load older continues from there), - * or drops the kept entries if none was. + * bounded page at a time, and replaced. Reading stops at the oldest kept + * entry, or, if the host no longer has it, once as many host entries as the + * kept ones spanned (drawn or not) are read. A read that fails keeps the + * pages already read (Load older continues from there), or drops the kept + * entries if none was. */ private rereadCarried(carried: number, fresh: RemoteBotSessionView): void { const view = this.state.view; if (carried <= 0 || !view) return; const own = view.snapshot.entries[carried]?.id; + const oldest = view.snapshot.entries[0]?.id; + const span = Math.max(view.olderHostSpan ?? 0, carried); const history = this.history; const current = () => !this.stopped && history === this.history && this.state.view !== null; const settle = (pages: RemoteBotSessionEntriesPage[]) => { @@ -248,18 +251,17 @@ export class RemoteBotSessionFollower { const pages: RemoteBotSessionEntriesPage[] = []; const next = (before: string, read: number): void => { if (!transport.older) return settle(pages); - transport.older(this.hostId, this.botId, before, Math.min(Math.max(carried - read, 1), OLDER_PAGE_MAX)).then( + transport.older(this.hostId, this.botId, before, Math.min(Math.max(span - read, 1), OLDER_PAGE_MAX)).then( (outcome) => { if (!current()) return; if (!outcome.ok) return settle(pages); const page = outcome.value as RemoteBotSessionEntriesPage; pages.push(page); - // Counted in the host's entries, read or not: entries this Mac leaves out - // still use up the kept range, so a newer host's pages never walk past it. + // Counted in the host's entries, drawn or not, as the kept span was. const total = read + (page.hostCount ?? page.entries.length); const cursor = page.olderCursor ?? page.entries[0]?.id; - // Every kept entry is covered, or the host has nothing older. - if (total >= carried || !page.hasOlder || !cursor || cursor === before) return settle(pages); + const reachedOldest = page.entries.some((entry) => entry.id === oldest); + if (reachedOldest || total >= span || !page.hasOlder || !cursor || cursor === before) return settle(pages); next(cursor, total); }, () => settle(pages), diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 441043a3df..edc4658143 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -560,12 +560,12 @@ test("loaded history longer than one page survives a same-epoch snapshot whole, follower.stop(); }); -test("re-reading kept history from a newer host counts the entries this Mac leaves out, so it never walks past the kept range", async () => { +test("re-reading kept history from a newer host covers the same span, entries this Mac leaves out included, and no further", async () => { const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); const newest = session({ hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }); const fake = fakeTransport([newest]); // The host, newer than this Mac: two entries of a kind this Mac can't show sit just before "Five". - const host = ["m1", "m2", "m3", "m4", "u1", "u2"]; + let host = ["m1", "m2", "m3", "m4", "u1", "u2"]; const asked: Array<[string, number | undefined]> = []; fake.transport.older = async (_hostId, _botId, before, limit) => { asked.push([before, limit]); @@ -584,22 +584,32 @@ test("re-reading kept history from a newer host counts the entries this Mac leav follower.start(); await settle(); const ids = () => follower.getState().view!.snapshot.entries.map((entry) => entry.id); + const snapshot = (seq: number) => + fake.push(event(seq, { type: "snapshot", payload: { session: session({ seq: seq + 1, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }) } })); // Two Load olders: an all-unknown page, then "m3" and "m4". await follower.loadOlder(); assert.deepEqual(ids(), ["m5", "m6"]); await follower.loadOlder(); assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); - // A snapshot keeps 2 shown entries; the host's 2 newest older ones are unknown, and re-reading stops there. + // Unchanged history: the re-read spans the four host entries loaded, so "m3" and "m4" stay. asked.length = 0; - fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }) } })); + snapshot(4); await settle(); - assert.deepEqual(asked, [["m5", 2]], "one request, for as many host entries as were kept"); - assert.deepEqual(ids(), ["m5", "m6"]); - assert.equal(follower.getState().view!.hasOlder, true); - assert.equal(follower.getState().view!.olderCursor, "u1", "Load older continues past the entries left out"); - await follower.loadOlder(); + assert.deepEqual(asked, [["m5", 4]], "one request, for the host entries the loaded pages spanned"); assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); + assert.equal(follower.getState().view!.olderCursor, "m3"); + + // The host drops "m3": the re-read stops after the same span instead of walking to the start. + host = host.filter((id) => id !== "m3"); + asked.length = 0; + snapshot(6); + await settle(); + assert.deepEqual(asked, [["m5", 4]]); + assert.deepEqual(ids(), ["m2", "m4", "m5", "m6"]); + await follower.loadOlder(); + assert.deepEqual(ids(), ["m1", "m2", "m4", "m5", "m6"]); + assert.equal(follower.getState().view!.hasOlder, false); follower.stop(); }); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index 382e71d8de..e06860ee2d 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -45,6 +45,13 @@ export interface RemoteBotSessionView { hasOlder: boolean; /** While `hasOlder`, the host's id of the oldest entry here, drawn or not: where the next older page ends. */ olderCursor: string | null; + /** + * Of the entries shown, how many came before the newest snapshot's own + * (loaded pages, or entries kept across a snapshot), and how many host + * entries those span, drawn or not. A snapshot re-reads that span. + */ + olderLoaded?: number; + olderHostSpan?: number; } /** @@ -281,11 +288,15 @@ export function carryOlderRemoteBotEntries( if (!first) return next; const index = previous.snapshot.entries.findIndex((entry) => entry.id === first.id); if (index <= 0) return next; + // The kept part is what earlier pages loaded plus the old snapshot's own entries before `first`. + const loaded = previous.olderLoaded ?? 0; return { ...next, snapshot: { ...next.snapshot, entries: [...previous.snapshot.entries.slice(0, index), ...next.snapshot.entries] }, hasOlder: previous.hasOlder, olderCursor: previous.olderCursor, + olderLoaded: index, + olderHostSpan: (previous.olderHostSpan ?? 0) + Math.max(0, index - loaded), }; } @@ -304,6 +315,8 @@ export function withOlderRemoteBotEntries( return { ...view, snapshot: { ...view.snapshot, entries: [...older, ...view.snapshot.entries] }, + olderLoaded: (view.olderLoaded ?? 0) + older.length, + olderHostSpan: (view.olderHostSpan ?? 0) + (page.hostCount ?? page.entries.length), hasOlder: page.hasOlder, olderCursor: page.hasOlder ? (page.olderCursor ?? page.entries[0]?.id ?? view.olderCursor) : null, }; @@ -325,7 +338,12 @@ export function withRereadOlderRemoteBotEntries( snapshot: Pick, pages: readonly RemoteBotSessionEntriesPage[] | null, ): RemoteBotSessionView { - const own: RemoteBotSessionView = { ...view, snapshot: { ...view.snapshot, entries: view.snapshot.entries.slice(carried) } }; + const own: RemoteBotSessionView = { + ...view, + snapshot: { ...view.snapshot, entries: view.snapshot.entries.slice(carried) }, + olderLoaded: 0, + olderHostSpan: 0, + }; if ( !pages || pages.length === 0 || From 805f572fc55d2490f1ec5bd1a8e35a159a870a77 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:35:46 +0000 Subject: [PATCH 07/16] Cut a Bot history re-read back to the oldest kept entry When a same-epoch snapshot moves into the loaded range, read until the oldest kept entry and drop anything older the pages brought, so what was shown stays and nothing older is added; the span is only a bound when that entry is gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 13 +++-- renderer/lib/hosts/remote-bot-session.test.ts | 48 +++++++++++++++++-- renderer/lib/hosts/remote-bot-session.ts | 18 ++++++- 4 files changed, 69 insertions(+), 12 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index da4d76bb42..75a3aacf6b 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, or, if the host no longer has that entry, until it has read as many host entries as the loaded pages spanned (entries this Mac can't show count too, so the re-read covers the same range and never goes further back); if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if the host no longer has that entry, the re-read stops after about as many host entries as the loaded part spanned (entries this Mac can't show count too); if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index a01861054b..e9143ecc2f 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -224,8 +224,8 @@ export class RemoteBotSessionFollower { * The host may have rewritten history inside the same epoch (a snapshot * also says so), so older entries kept across a snapshot are read again, a * bounded page at a time, and replaced. Reading stops at the oldest kept - * entry, or, if the host no longer has it, once as many host entries as the - * kept ones spanned (drawn or not) are read. A read that fails keeps the + * entry (anything past it is cut off), or, if the host no longer has it, once + * the host entries the kept ones spanned, plus a slack, are read. A read that fails keeps the * pages already read (Load older continues from there), or drops the kept * entries if none was. */ @@ -234,7 +234,11 @@ export class RemoteBotSessionFollower { if (carried <= 0 || !view) return; const own = view.snapshot.entries[carried]?.id; const oldest = view.snapshot.entries[0]?.id; + // The host entries the kept part spans, as far as this Mac can count them + // (a snapshot's own entries are counted as shown), and a slack of the kept + // count for entries it couldn't see: a bound for when the oldest is gone. const span = Math.max(view.olderHostSpan ?? 0, carried); + const bound = span + carried; const history = this.history; const current = () => !this.stopped && history === this.history && this.state.view !== null; const settle = (pages: RemoteBotSessionEntriesPage[]) => { @@ -251,7 +255,8 @@ export class RemoteBotSessionFollower { const pages: RemoteBotSessionEntriesPage[] = []; const next = (before: string, read: number): void => { if (!transport.older) return settle(pages); - transport.older(this.hostId, this.botId, before, Math.min(Math.max(span - read, 1), OLDER_PAGE_MAX)).then( + const want = read < span ? span - read : bound - read; + transport.older(this.hostId, this.botId, before, Math.min(Math.max(want, 1), OLDER_PAGE_MAX)).then( (outcome) => { if (!current()) return; if (!outcome.ok) return settle(pages); @@ -261,7 +266,7 @@ export class RemoteBotSessionFollower { const total = read + (page.hostCount ?? page.entries.length); const cursor = page.olderCursor ?? page.entries[0]?.id; const reachedOldest = page.entries.some((entry) => entry.id === oldest); - if (reachedOldest || total >= span || !page.hasOlder || !cursor || cursor === before) return settle(pages); + if (reachedOldest || total >= bound || !page.hasOlder || !cursor || cursor === before) return settle(pages); next(cursor, total); }, () => settle(pages), diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index edc4658143..94fdf43322 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -494,7 +494,7 @@ test("a snapshot that rewrote loaded history replaces it, and a page asked for b history = history.filter((entry) => entry.id !== "m4"); fake.push(event(3, { type: "snapshot", payload: { session: session({ seq: 4, hasOlder: true, entries: [message("m5", "Five"), message("m6", "Six")] }) } })); await settle(); - assert.deepEqual(texts(), ["Two", "Three", "Five", "Six"]); + assert.deepEqual(texts(), ["Three", "Five", "Six"], "nothing older than what was shown is added"); assert.deepEqual(asked[1], ["m5", 2], "the loaded part is read again, as many entries as were kept"); // A Load older that is out when another snapshot arrives belongs to the history before it. @@ -600,19 +600,57 @@ test("re-reading kept history from a newer host covers the same span, entries th assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); assert.equal(follower.getState().view!.olderCursor, "m3"); - // The host drops "m3": the re-read stops after the same span instead of walking to the start. + // The host drops "m3", the oldest kept: the re-read is bounded by the span it covered plus a slack. host = host.filter((id) => id !== "m3"); asked.length = 0; snapshot(6); await settle(); - assert.deepEqual(asked, [["m5", 4]]); - assert.deepEqual(ids(), ["m2", "m4", "m5", "m6"]); - await follower.loadOlder(); + assert.deepEqual(asked, [["m5", 4], ["m2", 2]]); assert.deepEqual(ids(), ["m1", "m2", "m4", "m5", "m6"]); assert.equal(follower.getState().view!.hasOlder, false); follower.stop(); }); +test("a same-epoch snapshot that starts inside the loaded history keeps what was shown, and adds nothing older", async () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + // The host, newer than this Mac: "u…" entries are of kinds this Mac can't show. + const host = ["m1", "m2", "m3", "m4", "u1", "u2", "m5", "u3", "m6", "m7"]; + const fake = fakeTransport([session({ hasOlder: true, entries: [message("m5", "m5"), message("m6", "m6")] })]); + const asked: Array<[string, number | undefined]> = []; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + const end = host.indexOf(before); + const start = Math.max(0, end - (limit ?? 2)); + const sent = host.slice(start, end); + return { + ok: true, + value: { + botId: "bot_1", epoch: "e1", hasOlder: start > 0, olderCursor: sent[0], hostCount: sent.length, + entries: sent.filter((id) => id.startsWith("m")).map((id) => message(id, id)), + }, + }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + const ids = () => follower.getState().view!.snapshot.entries.map((entry) => entry.id); + await follower.loadOlder(); + await follower.loadOlder(); + assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); + + // A new reply: the snapshot now starts at "m6", so "m5" joins the kept part. + asked.length = 0; + fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: [message("m6", "m6"), message("m7", "m7")] }) } })); + await settle(); + assert.deepEqual(ids(), ["m3", "m4", "m5", "m6", "m7"], "everything shown stays, and m1 and m2 are not added"); + assert.equal(follower.getState().view!.olderCursor, "m3", "Load older resumes where it was"); + assert.equal(follower.getState().view!.hasOlder, true); + assert.ok(asked.length <= 2 && asked.every(([, limit]) => (limit ?? 0) <= 200), JSON.stringify(asked)); + await follower.loadOlder(); + assert.deepEqual(ids(), ["m1", "m2", "m3", "m4", "m5", "m6", "m7"]); + follower.stop(); +}); + test("a page whose entries this Mac can't show still moves Load older past them", () => { const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); const view = remoteBotSessionView(session({ hasOlder: true, entries: [message("m5", "Five")] })); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index e06860ee2d..4c0d8f7cbf 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -327,7 +327,8 @@ export function withOlderRemoteBotEntries( * (`carryOlderRemoteBotEntries`); `pages` are that history read again from the * host, newest page first, each just older than the one before it, starting * just older than the snapshot's own entries. The kept entries are replaced - * with the pages, so history the host removed or reordered doesn't stay. Pages + * with the pages, so history the host removed or reordered doesn't stay, and + * cut back to the oldest kept entry when they reach past it. Pages * that stop short of the kept range (a later page failed) leave Load older * where the last one ends. Without a page, or with one from another epoch, the * kept entries are dropped and the snapshot's own "older" state comes back. @@ -351,7 +352,20 @@ export function withRereadOlderRemoteBotEntries( ) { return { ...own, ...snapshot }; } - return pages.reduce(withOlderRemoteBotEntries, own); + const reread = pages.reduce(withOlderRemoteBotEntries, own); + // Pages that reached past the oldest kept entry are cut back to it, so history + // older than what was shown before isn't added; Load older resumes where it was. + const oldest = view.snapshot.entries[0]?.id; + const at = carried > 0 && oldest !== undefined ? reread.snapshot.entries.findIndex((entry) => entry.id === oldest) : -1; + if (at <= 0) return reread; + return { + ...reread, + snapshot: { ...reread.snapshot, entries: reread.snapshot.entries.slice(at) }, + hasOlder: view.hasOlder, + olderCursor: view.olderCursor, + olderLoaded: (reread.olderLoaded ?? 0) - at, + olderHostSpan: view.olderHostSpan ?? 0, + }; } /** From e8eea76986003f219d5e3d0e02c00ef08d729e05 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:45:57 +0000 Subject: [PATCH 08/16] Trim a re-read at the earliest kept Bot entry the host still has When the oldest kept entry is deleted, cut the re-read back to the earliest surviving kept entry and resume Load older from it, instead of adding history the person had not loaded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 3 ++- renderer/lib/hosts/remote-bot-session.test.ts | 8 ++++++-- renderer/lib/hosts/remote-bot-session.ts | 19 ++++++++++++------- 4 files changed, 21 insertions(+), 11 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 75a3aacf6b..f9d3168005 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if the host no longer has that entry, the re-read stops after about as many host entries as the loaded part spanned (entries this Mac can't show count too); if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if the host no longer has that entry, the re-read stops after about as many host entries as the loaded part spanned (entries this Mac can't show count too) and is cut back to the earliest loaded entry the host still has, with Load older resuming from it; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index e9143ecc2f..af0494dae4 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -225,7 +225,8 @@ export class RemoteBotSessionFollower { * also says so), so older entries kept across a snapshot are read again, a * bounded page at a time, and replaced. Reading stops at the oldest kept * entry (anything past it is cut off), or, if the host no longer has it, once - * the host entries the kept ones spanned, plus a slack, are read. A read that fails keeps the + * the host entries the kept ones spanned, plus a slack, are read; then it is + * cut back to the earliest kept entry the host still has. A read that fails keeps the * pages already read (Load older continues from there), or drops the kept * entries if none was. */ diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 94fdf43322..7662c7ad6a 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -600,14 +600,18 @@ test("re-reading kept history from a newer host covers the same span, entries th assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"]); assert.equal(follower.getState().view!.olderCursor, "m3"); - // The host drops "m3", the oldest kept: the re-read is bounded by the span it covered plus a slack. + // The host drops "m3", the oldest kept: the re-read is bounded by the span it covered plus a slack, + // and cut back to "m4", the earliest kept entry the host still has, so "m1" and "m2" are not added. host = host.filter((id) => id !== "m3"); asked.length = 0; snapshot(6); await settle(); assert.deepEqual(asked, [["m5", 4], ["m2", 2]]); + assert.deepEqual(ids(), ["m4", "m5", "m6"]); + assert.equal(follower.getState().view!.hasOlder, true); + assert.equal(follower.getState().view!.olderCursor, "m4", "Load older resumes from an entry the host has"); + await follower.loadOlder(); assert.deepEqual(ids(), ["m1", "m2", "m4", "m5", "m6"]); - assert.equal(follower.getState().view!.hasOlder, false); follower.stop(); }); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index 4c0d8f7cbf..9ab770de8b 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -328,7 +328,8 @@ export function withOlderRemoteBotEntries( * host, newest page first, each just older than the one before it, starting * just older than the snapshot's own entries. The kept entries are replaced * with the pages, so history the host removed or reordered doesn't stay, and - * cut back to the oldest kept entry when they reach past it. Pages + * cut back to the earliest kept entry the host still has when they reach past + * it. Pages * that stop short of the kept range (a later page failed) leave Load older * where the last one ends. Without a page, or with one from another epoch, the * kept entries are dropped and the snapshot's own "older" state comes back. @@ -353,16 +354,20 @@ export function withRereadOlderRemoteBotEntries( return { ...own, ...snapshot }; } const reread = pages.reduce(withOlderRemoteBotEntries, own); - // Pages that reached past the oldest kept entry are cut back to it, so history - // older than what was shown before isn't added; Load older resumes where it was. - const oldest = view.snapshot.entries[0]?.id; - const at = carried > 0 && oldest !== undefined ? reread.snapshot.entries.findIndex((entry) => entry.id === oldest) : -1; + // Pages that reached past the kept entries are cut back to the earliest one + // the host still has, so history older than what was shown before isn't + // added. At the oldest kept entry Load older resumes where it was; at a later + // one (the host removed the older ones), it resumes from that entry. + const ids = reread.snapshot.entries.map((entry) => entry.id); + const kept = view.snapshot.entries.slice(0, Math.max(0, carried)); + const boundary = kept.findIndex((entry) => ids.includes(entry.id)); + const at = boundary < 0 ? -1 : ids.indexOf(kept[boundary]!.id); if (at <= 0) return reread; return { ...reread, snapshot: { ...reread.snapshot, entries: reread.snapshot.entries.slice(at) }, - hasOlder: view.hasOlder, - olderCursor: view.olderCursor, + hasOlder: boundary === 0 ? view.hasOlder : true, + olderCursor: boundary === 0 ? view.olderCursor : kept[boundary]!.id, olderLoaded: (reread.olderLoaded ?? 0) - at, olderHostSpan: view.olderHostSpan ?? 0, }; From 29460b43b1e47fba02f609a76c6290987772b866 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:49:46 +0000 Subject: [PATCH 09/16] Read kept Bot history back to the earliest entry the host still has A newer host's unshown entries can make the gap between kept entries larger than the bounded re-read. When the bound runs out first, ask the host whether it still has the oldest kept entry, then each later one, and read on to the earliest it has, so shown messages are not dropped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 49 ++++++++++++++----- renderer/lib/hosts/remote-bot-session.test.ts | 46 +++++++++++++++++ 3 files changed, 85 insertions(+), 12 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index f9d3168005..c793fdaa23 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if the host no longer has that entry, the re-read stops after about as many host entries as the loaded part spanned (entries this Mac can't show count too) and is cut back to the earliest loaded entry the host still has, with Load older resuming from it; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if that entry isn't reached within about as many host entries as the loaded part spanned (entries this Mac can't show count too), the Mac asks the host whether it still has it, then each later loaded entry in turn (one-entry pages; `operation_stale` means gone), reads on to the earliest one the host has and cuts back to it, so loaded messages the host still has stay; only if it has none does the bounded read stand; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index af0494dae4..7801de8cfe 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -224,9 +224,12 @@ export class RemoteBotSessionFollower { * The host may have rewritten history inside the same epoch (a snapshot * also says so), so older entries kept across a snapshot are read again, a * bounded page at a time, and replaced. Reading stops at the oldest kept - * entry (anything past it is cut off), or, if the host no longer has it, once - * the host entries the kept ones spanned, plus a slack, are read; then it is - * cut back to the earliest kept entry the host still has. A read that fails keeps the + * entry (anything past it is cut off). If it isn't reached within the host + * entries the kept ones spanned, plus a slack (a newer host's entries this + * Mac can't show may sit between them), the host is asked whether it still + * has it, then each later kept entry in turn: reading goes on to the + * earliest one it has, and the re-read is cut back to it. Only if the host + * has none of them does the bounded read stand. A read that fails keeps the * pages already read (Load older continues from there), or drops the kept * entries if none was. */ @@ -234,10 +237,10 @@ export class RemoteBotSessionFollower { const view = this.state.view; if (carried <= 0 || !view) return; const own = view.snapshot.entries[carried]?.id; - const oldest = view.snapshot.entries[0]?.id; + const kept = view.snapshot.entries.slice(0, carried).map((entry) => entry.id); // The host entries the kept part spans, as far as this Mac can count them // (a snapshot's own entries are counted as shown), and a slack of the kept - // count for entries it couldn't see: a bound for when the oldest is gone. + // count for entries it couldn't see. const span = Math.max(view.olderHostSpan ?? 0, carried); const bound = span + carried; const history = this.history; @@ -254,9 +257,13 @@ export class RemoteBotSessionFollower { return; } const pages: RemoteBotSessionEntriesPage[] = []; - const next = (before: string, read: number): void => { + const read = (id: string) => pages.some((page) => page.entries.some((entry) => entry.id === id)); + // The kept entry to read back to; null while the read is bounded. + let target: string | null = kept[0] ?? null; + let bounded = true; + const next = (before: string, total: number): void => { if (!transport.older) return settle(pages); - const want = read < span ? span - read : bound - read; + const want = !bounded ? OLDER_PAGE_MAX : total < span ? span - total : bound - total; transport.older(this.hostId, this.botId, before, Math.min(Math.max(want, 1), OLDER_PAGE_MAX)).then( (outcome) => { if (!current()) return; @@ -264,11 +271,31 @@ export class RemoteBotSessionFollower { const page = outcome.value as RemoteBotSessionEntriesPage; pages.push(page); // Counted in the host's entries, drawn or not, as the kept span was. - const total = read + (page.hostCount ?? page.entries.length); + const after = total + (page.hostCount ?? page.entries.length); const cursor = page.olderCursor ?? page.entries[0]?.id; - const reachedOldest = page.entries.some((entry) => entry.id === oldest); - if (reachedOldest || total >= bound || !page.hasOlder || !cursor || cursor === before) return settle(pages); - next(cursor, total); + if ((target !== null && read(target)) || !page.hasOlder || !cursor || cursor === before) return settle(pages); + if (bounded && after >= bound) return probe(0, cursor, after); + next(cursor, after); + }, + () => settle(pages), + ); + }; + // Asks for one entry before kept[index]: the host answers `operation_stale` + // when it no longer has that entry. + const probe = (index: number, cursor: string, total: number): void => { + const id = kept[index]; + if (id === undefined || !transport.older) return settle(pages); + if (read(id)) return settle(pages); + transport.older(this.hostId, this.botId, id, 1).then( + (outcome) => { + if (!current()) return; + if (outcome.ok) { + target = id; + bounded = false; + return next(cursor, total); + } + if (outcome.error.remoteCode === "operation_stale") return probe(index + 1, cursor, total); + settle(pages); }, () => settle(pages), ); diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 7662c7ad6a..6dbfb2ca9d 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -655,6 +655,52 @@ test("a same-epoch snapshot that starts inside the loaded history keeps what was follower.stop(); }); +test("a shifted snapshot keeps every kept entry the host still has, however many unshown entries sit between them", async () => { + const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); + // The host, newer than this Mac: five "u…" entries this Mac can't show sit between "m3" and "m4", + // more than the two entries this Mac keeps across the snapshot. + let host = ["m1", "m2", "m3", "u1", "u2", "u3", "u4", "u5", "m4", "m5", "m6", "m7"]; + const fake = fakeTransport([session({ hasOlder: true, entries: [message("m3", "m3"), message("m4", "m4"), message("m5", "m5")] })]); + const asked: Array<[string, number | undefined]> = []; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + const end = host.indexOf(before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; + const start = Math.max(0, end - (limit ?? 2)); + const sent = host.slice(start, end); + return { + ok: true, + value: { + botId: "bot_1", epoch: "e1", hasOlder: start > 0, olderCursor: sent[0], hostCount: sent.length, + entries: sent.filter((id) => id.startsWith("m")).map((id) => message(id, id)), + }, + }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + const ids = () => follower.getState().view!.snapshot.entries.map((entry) => entry.id); + const snapshot = (seq: number, entries: string[]) => + fake.push(event(seq, { type: "snapshot", payload: { session: session({ seq: seq + 1, hasOlder: true, entries: entries.map((id) => message(id, id)) }) } })); + + // The snapshot now starts at "m5": "m3" and "m4" are kept, and both are read back. + snapshot(4, ["m5", "m6"]); + await settle(); + assert.deepEqual(ids(), ["m3", "m4", "m5", "m6"], "nothing shown is lost, and m1 and m2 are not added"); + assert.equal(follower.getState().view!.hasOlder, true); + assert.ok(asked.every(([, limit]) => (limit ?? 0) <= 200), JSON.stringify(asked)); + + // The host drops "m3": the re-read stops at "m4", the earliest kept entry it still has. + host = host.filter((id) => id !== "m3"); + snapshot(6, ["m6", "m7"]); + await settle(); + assert.deepEqual(ids(), ["m4", "m5", "m6", "m7"]); + assert.ok(host.includes(follower.getState().view!.olderCursor ?? ""), "Load older starts from an entry the host has"); + await follower.loadOlder(); + assert.deepEqual(ids(), ["m2", "m4", "m5", "m6", "m7"], "Load older goes on from an entry the host has"); + follower.stop(); +}); + test("a page whose entries this Mac can't show still moves Load older past them", () => { const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); const view = remoteBotSessionView(session({ hasOlder: true, entries: [message("m5", "Five")] })); From b646dab76331dea502d6430c9fd921bbf494dd44 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:55:16 +0000 Subject: [PATCH 10/16] Trim a Bot history re-read at the kept entry that comes first now The host may reorder kept entries within the same epoch, so the re-read is cut at whichever kept entry comes first in its current order rather than in the order this Mac showed them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- renderer/lib/hosts/remote-bot-session.test.ts | 17 +++++++++++++++++ renderer/lib/hosts/remote-bot-session.ts | 18 ++++++++++-------- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 6dbfb2ca9d..feff0c544d 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -13,10 +13,12 @@ import { import { RemoteBotSessionFollower, type RemoteBotSessionTransport } from "./remote-bot-session-follower"; import { applyRemoteBotSessionEvent, + carryOlderRemoteBotEntries, hostServesBotHandoffs, hostSharesBotSessions, remoteBotSessionView, withOlderRemoteBotEntries, + withRereadOlderRemoteBotEntries, type RemoteBotSessionView, } from "./remote-bot-session"; @@ -701,6 +703,21 @@ test("a shifted snapshot keeps every kept entry the host still has, however many follower.stop(); }); +test("a host that reorders kept entries keeps every one the re-read finds, in the host's order", () => { + const message = (id: string) => ({ type: "message" as const, id, role: "assistant" as const, text: id }); + const shown = remoteBotSessionView(session({ hasOlder: true, entries: ["m3", "m4", "m5", "m6"].map(message) })); + const fresh = remoteBotSessionView(session({ seq: 6, hasOlder: true, entries: ["m5", "m6"].map(message) })); + const kept = carryOlderRemoteBotEntries(shown, fresh); + assert.deepEqual(kept.snapshot.entries.map((entry) => entry.id), ["m3", "m4", "m5", "m6"]); + // The host now has "m4" before "m3". + const reread = withRereadOlderRemoteBotEntries(kept, 2, fresh, [ + { botId: "bot_1", epoch: "e1", entries: ["m1", "m4", "m3"].map(message), hasOlder: false }, + ]); + assert.deepEqual(reread.snapshot.entries.map((entry) => entry.id), ["m4", "m3", "m5", "m6"], "m1 is not added and m4 stays"); + assert.equal(reread.hasOlder, true); + assert.equal(reread.olderCursor, "m4"); +}); + test("a page whose entries this Mac can't show still moves Load older past them", () => { const message = (id: string, text: string) => ({ type: "message" as const, id, role: "assistant" as const, text }); const view = remoteBotSessionView(session({ hasOlder: true, entries: [message("m5", "Five")] })); diff --git a/renderer/lib/hosts/remote-bot-session.ts b/renderer/lib/hosts/remote-bot-session.ts index 9ab770de8b..ea0b15be5d 100644 --- a/renderer/lib/hosts/remote-bot-session.ts +++ b/renderer/lib/hosts/remote-bot-session.ts @@ -356,18 +356,20 @@ export function withRereadOlderRemoteBotEntries( const reread = pages.reduce(withOlderRemoteBotEntries, own); // Pages that reached past the kept entries are cut back to the earliest one // the host still has, so history older than what was shown before isn't - // added. At the oldest kept entry Load older resumes where it was; at a later - // one (the host removed the older ones), it resumes from that entry. - const ids = reread.snapshot.entries.map((entry) => entry.id); - const kept = view.snapshot.entries.slice(0, Math.max(0, carried)); - const boundary = kept.findIndex((entry) => ids.includes(entry.id)); - const at = boundary < 0 ? -1 : ids.indexOf(kept[boundary]!.id); + // added. At the oldest kept entry Load older resumes where it was; at another + // (the host removed or moved the older ones), it resumes from that entry. + // The boundary is whichever kept entry comes first in the host's order now, + // so a reorder doesn't cut off a kept entry that moved earlier. + const kept = new Set(view.snapshot.entries.slice(0, Math.max(0, carried)).map((entry) => entry.id)); + const at = reread.snapshot.entries.findIndex((entry) => kept.has(entry.id)); if (at <= 0) return reread; + const boundary = reread.snapshot.entries[at]!.id; + const same = boundary === view.snapshot.entries[0]?.id; return { ...reread, snapshot: { ...reread.snapshot, entries: reread.snapshot.entries.slice(at) }, - hasOlder: boundary === 0 ? view.hasOlder : true, - olderCursor: boundary === 0 ? view.olderCursor : kept[boundary]!.id, + hasOlder: same ? view.hasOlder : true, + olderCursor: same ? view.olderCursor : boundary, olderLoaded: (reread.olderLoaded ?? 0) - at, olderHostSpan: view.olderHostSpan ?? 0, }; From 3053180bc01f2ba284521b4ec327cc68287f7436 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:58:09 +0000 Subject: [PATCH 11/16] Ask the host about at most 8 kept Bot entries after a re-read misses A rewrite that removed every kept entry no longer costs one request per loaded entry: after 8 gone the bounded re-read stands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 6 ++-- renderer/lib/hosts/remote-bot-session.test.ts | 29 +++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index c793fdaa23..7feb5bcae3 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if that entry isn't reached within about as many host entries as the loaded part spanned (entries this Mac can't show count too), the Mac asks the host whether it still has it, then each later loaded entry in turn (one-entry pages; `operation_stale` means gone), reads on to the earliest one the host has and cuts back to it, so loaded messages the host still has stay; only if it has none does the bounded read stand; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if that entry isn't reached within about as many host entries as the loaded part spanned (entries this Mac can't show count too), the Mac asks the host whether it still has it, then each later loaded entry in turn, at most 8 in all (one-entry pages; `operation_stale` means gone), reads on to the earliest one the host has and cuts back to it, so loaded messages the host still has stay; only if it has none of those does the bounded read stand; the cut is at whichever loaded entry comes first in the host's current order; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index 7801de8cfe..f7cc8f3523 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -18,6 +18,8 @@ import { /** The host's largest page (`limit`, revision 67). */ const OLDER_PAGE_MAX = 200; +/** At most this many kept entries are asked about after a bounded re-read misses the oldest. */ +const KEPT_PROBE_MAX = 8; export interface RemoteBotSessionTransport { subscribe(hostId: string, botId: string): Promise; @@ -229,7 +231,7 @@ export class RemoteBotSessionFollower { * Mac can't show may sit between them), the host is asked whether it still * has it, then each later kept entry in turn: reading goes on to the * earliest one it has, and the re-read is cut back to it. Only if the host - * has none of them does the bounded read stand. A read that fails keeps the + * has none of the first few (`KEPT_PROBE_MAX`) does the bounded read stand. A read that fails keeps the * pages already read (Load older continues from there), or drops the kept * entries if none was. */ @@ -284,7 +286,7 @@ export class RemoteBotSessionFollower { // when it no longer has that entry. const probe = (index: number, cursor: string, total: number): void => { const id = kept[index]; - if (id === undefined || !transport.older) return settle(pages); + if (id === undefined || index >= KEPT_PROBE_MAX || !transport.older) return settle(pages); if (read(id)) return settle(pages); transport.older(this.hostId, this.botId, id, 1).then( (outcome) => { diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index feff0c544d..9879c6c644 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -703,6 +703,35 @@ test("a shifted snapshot keeps every kept entry the host still has, however many follower.stop(); }); +test("a rewrite that removed every kept entry asks the host about only a few of them", async () => { + const message = (id: string) => ({ type: "message" as const, id, role: "assistant" as const, text: id }); + const keptIds = Array.from({ length: 30 }, (_, index) => `k${index + 1}`); + // The host rewrote its history: none of the kept entries is left. + const host = [...Array.from({ length: 80 }, (_, index) => `h${index + 1}`), "m5", "m6", "m7"]; + const fake = fakeTransport([session({ hasOlder: true, entries: [...keptIds, "m5", "m6"].map(message) })]); + const asked: Array<[string, number | undefined]> = []; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + const end = host.indexOf(before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; + const start = Math.max(0, end - (limit ?? 2)); + const sent = host.slice(start, end); + return { ok: true, value: { botId: "bot_1", epoch: "e1", hasOlder: start > 0, olderCursor: sent[0], hostCount: sent.length, entries: sent.map(message) } }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: ["m5", "m6", "m7"].map(message) }) } })); + await settle(); + const probes = asked.filter(([before]) => before.startsWith("k")); + assert.ok(probes.length > 0 && probes.length <= 8, JSON.stringify(probes)); + assert.ok(asked.length <= probes.length + 2, JSON.stringify(asked)); + const ids = follower.getState().view!.snapshot.entries.map((entry) => entry.id); + assert.ok(!ids.some((id) => id.startsWith("k")), "the removed entries are gone"); + assert.deepEqual(ids.slice(-3), ["m5", "m6", "m7"]); + follower.stop(); +}); + test("a host that reorders kept entries keeps every one the re-read finds, in the host's order", () => { const message = (id: string) => ({ type: "message" as const, id, role: "assistant" as const, text: id }); const shown = remoteBotSessionView(session({ hasOlder: true, entries: ["m3", "m4", "m5", "m6"].map(message) })); From 3333387c4c13f06dc91561fe2713756e6d3ddba3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 09:03:19 +0000 Subject: [PATCH 12/16] Read back a kept Bot entry the host moved further back Reaching the oldest kept entry no longer ends a re-read while another kept entry is still unread: the host is asked about it (within the same 8-entry budget) and reading goes on to it, so a reordered entry isn't dropped. Test hosts answer operation_stale for ids they don't have, as the real host does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 51 ++++++++++--------- renderer/lib/hosts/remote-bot-session.test.ts | 38 +++++++++++++- 3 files changed, 66 insertions(+), 25 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 7feb5bcae3..58e7a41f9c 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; if that entry isn't reached within about as many host entries as the loaded part spanned (entries this Mac can't show count too), the Mac asks the host whether it still has it, then each later loaded entry in turn, at most 8 in all (one-entry pages; `operation_stale` means gone), reads on to the earliest one the host has and cuts back to it, so loaded messages the host still has stay; only if it has none of those does the bounded read stand; the cut is at whichever loaded entry comes first in the host's current order; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; once it has read about as many host entries as the loaded part spanned (entries this Mac can't show count too), or has reached that entry, it asks the host about each loaded entry not yet read back (one the host removed or moved further back), at most 8 in all (one-entry pages; `operation_stale` means gone), reading on to each one the host still has; the cut is at whichever loaded entry comes first in the host's current order, so loaded messages the host still has stay; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index f7cc8f3523..f42cf6de6b 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -18,7 +18,7 @@ import { /** The host's largest page (`limit`, revision 67). */ const OLDER_PAGE_MAX = 200; -/** At most this many kept entries are asked about after a bounded re-read misses the oldest. */ +/** At most this many kept entries a re-read didn't reach are asked about. */ const KEPT_PROBE_MAX = 8; export interface RemoteBotSessionTransport { @@ -225,15 +225,15 @@ export class RemoteBotSessionFollower { /** * The host may have rewritten history inside the same epoch (a snapshot * also says so), so older entries kept across a snapshot are read again, a - * bounded page at a time, and replaced. Reading stops at the oldest kept - * entry (anything past it is cut off). If it isn't reached within the host - * entries the kept ones spanned, plus a slack (a newer host's entries this - * Mac can't show may sit between them), the host is asked whether it still - * has it, then each later kept entry in turn: reading goes on to the - * earliest one it has, and the re-read is cut back to it. Only if the host - * has none of the first few (`KEPT_PROBE_MAX`) does the bounded read stand. A read that fails keeps the - * pages already read (Load older continues from there), or drops the kept - * entries if none was. + * bounded page at a time, and replaced. Reading goes back to the oldest kept + * entry within the host entries the kept ones spanned, plus a slack (a newer + * host's entries this Mac can't show may sit between them). Then any kept + * entry still not read (one the host removed, or moved further back) is + * asked about, at most `KEPT_PROBE_MAX` in all: reading goes on to each one + * the host still has. The re-read is cut back to whichever kept entry comes + * first, so nothing older than before is added and no kept entry the host + * has is dropped. A read that fails keeps the pages already read (Load older + * continues from there), or drops the kept entries if none was. */ private rereadCarried(carried: number, fresh: RemoteBotSessionView): void { const view = this.state.view; @@ -259,9 +259,12 @@ export class RemoteBotSessionFollower { return; } const pages: RemoteBotSessionEntriesPage[] = []; - const read = (id: string) => pages.some((page) => page.entries.some((entry) => entry.id === id)); - // The kept entry to read back to; null while the read is bounded. - let target: string | null = kept[0] ?? null; + // Entries read back, the snapshot's own included (a kept entry may have moved into it). + const seen = new Set(fresh.snapshot.entries.map((entry) => entry.id)); + const gone = new Set(); + let probes = 0; + // The kept entry being read back to; while bounded, the oldest. + let target = kept[0]!; let bounded = true; const next = (before: string, total: number): void => { if (!transport.older) return settle(pages); @@ -272,22 +275,23 @@ export class RemoteBotSessionFollower { if (!outcome.ok) return settle(pages); const page = outcome.value as RemoteBotSessionEntriesPage; pages.push(page); + for (const entry of page.entries) seen.add(entry.id); // Counted in the host's entries, drawn or not, as the kept span was. const after = total + (page.hostCount ?? page.entries.length); const cursor = page.olderCursor ?? page.entries[0]?.id; - if ((target !== null && read(target)) || !page.hasOlder || !cursor || cursor === before) return settle(pages); - if (bounded && after >= bound) return probe(0, cursor, after); + if (!page.hasOlder || !cursor || cursor === before) return settle(pages); + if (seen.has(target) || (bounded && after >= bound)) return ask(cursor, after); next(cursor, after); }, () => settle(pages), ); }; - // Asks for one entry before kept[index]: the host answers `operation_stale` - // when it no longer has that entry. - const probe = (index: number, cursor: string, total: number): void => { - const id = kept[index]; - if (id === undefined || index >= KEPT_PROBE_MAX || !transport.older) return settle(pages); - if (read(id)) return settle(pages); + // Asks for one entry before the next kept entry not yet read: the host + // answers `operation_stale` when it no longer has it. + const ask = (cursor: string, total: number): void => { + const id = kept.find((candidate) => !seen.has(candidate) && !gone.has(candidate)); + if (id === undefined || probes >= KEPT_PROBE_MAX || !transport.older) return settle(pages); + probes += 1; transport.older(this.hostId, this.botId, id, 1).then( (outcome) => { if (!current()) return; @@ -296,8 +300,9 @@ export class RemoteBotSessionFollower { bounded = false; return next(cursor, total); } - if (outcome.error.remoteCode === "operation_stale") return probe(index + 1, cursor, total); - settle(pages); + if (outcome.error.remoteCode !== "operation_stale") return settle(pages); + gone.add(id); + ask(cursor, total); }, () => settle(pages), ); diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 9879c6c644..39b47a0ff8 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -480,8 +480,10 @@ test("a snapshot that rewrote loaded history replaces it, and a page asked for b let hold: (() => void) | null = null; fake.transport.older = async (_hostId, _botId, before, limit) => { asked.push([before, limit]); - if (hold === null && asked.length === 3) await new Promise((resolve) => (hold = resolve)); + // Holds the second Load older (re-reads always ask for a number of entries). + if (hold === null && asked.length > 1 && limit === undefined) await new Promise((resolve) => (hold = resolve)); const end = before === "m5" ? history.length : history.findIndex((entry) => entry.id === before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; const start = Math.max(0, end - (limit ?? 2)); return { ok: true, value: { botId: "bot_1", epoch: "e1", entries: history.slice(start, end), hasOlder: start > 0 } }; }; @@ -522,6 +524,7 @@ test("loaded history longer than one page survives a same-epoch snapshot whole, asked.push([before, limit]); if (failAt === asked.length) return { ok: false, error: { code: "failed", message: "Offline.", status: 503 } }; const end = history.findIndex((entry) => entry.id === before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; const start = Math.max(0, end - (limit ?? 150)); return { ok: true, value: { botId: "bot_1", epoch: "e1", entries: history.slice(start, end), hasOlder: start > 0 } }; }; @@ -572,6 +575,7 @@ test("re-reading kept history from a newer host covers the same span, entries th fake.transport.older = async (_hostId, _botId, before, limit) => { asked.push([before, limit]); const end = before === "m5" ? host.length : host.indexOf(before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; const start = Math.max(0, end - (limit ?? 2)); const sent = host.slice(start, end); return { @@ -626,6 +630,7 @@ test("a same-epoch snapshot that starts inside the loaded history keeps what was fake.transport.older = async (_hostId, _botId, before, limit) => { asked.push([before, limit]); const end = host.indexOf(before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; const start = Math.max(0, end - (limit ?? 2)); const sent = host.slice(start, end); return { @@ -732,6 +737,37 @@ test("a rewrite that removed every kept entry asks the host about only a few of follower.stop(); }); +test("a kept entry the host moved further back than the oldest is still read back", async () => { + const message = (id: string) => ({ type: "message" as const, id, role: "assistant" as const, text: id }); + // The host moved "m4" before "m3", with an entry this Mac can't show between them. + const host = ["m1", "m4", "u1", "m3", "m5", "m6", "m7"]; + const fake = fakeTransport([session({ hasOlder: true, entries: ["m3", "m4", "m5", "m6"].map(message) })]); + const asked: Array<[string, number | undefined]> = []; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + const end = host.indexOf(before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; + const start = Math.max(0, end - (limit ?? 2)); + const sent = host.slice(start, end); + return { + ok: true, + value: { + botId: "bot_1", epoch: "e1", hasOlder: start > 0, olderCursor: sent[0], hostCount: sent.length, + entries: sent.filter((id) => id.startsWith("m")).map(message), + }, + }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: ["m5", "m6", "m7"].map(message) }) } })); + await settle(); + assert.deepEqual(asked[0], ["m5", 2], "the first read reaches m3 but not m4"); + assert.deepEqual(follower.getState().view!.snapshot.entries.map((entry) => entry.id), ["m4", "m3", "m5", "m6", "m7"]); + assert.equal(follower.getState().view!.hasOlder, true); + follower.stop(); +}); + test("a host that reorders kept entries keeps every one the re-read finds, in the host's order", () => { const message = (id: string) => ({ type: "message" as const, id, role: "assistant" as const, text: id }); const shown = remoteBotSessionView(session({ hasOlder: true, entries: ["m3", "m4", "m5", "m6"].map(message) })); From cfac9e5cbda660e5e4949afccd16d48f69a38e6b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 09:10:29 +0000 Subject: [PATCH 13/16] Drop loaded Bot history rather than guess when re-read questions run out After 8 questions with kept entries still unaccounted for, the loaded part is dropped and Load older starts again from the snapshot, instead of showing a partial re-read that may miss entries the host kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- docs/aiden-remote-api-v1.md | 2 +- .../lib/hosts/remote-bot-session-follower.ts | 8 +++- renderer/lib/hosts/remote-bot-session.test.ts | 38 ++++++++++++++++++- 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/docs/aiden-remote-api-v1.md b/docs/aiden-remote-api-v1.md index 58e7a41f9c..8de5bb30f5 100644 --- a/docs/aiden-remote-api-v1.md +++ b/docs/aiden-remote-api-v1.md @@ -1513,7 +1513,7 @@ Revision 67 is provisional: it was written when `main` was at 65 and revision 66 **Taking back a queued message.** `POST /bots/{botId}/queued/{submissionId}/withdraw` (`withdrawBotQueuedMessage`; `bot:write` with `bot:read`, `chat:write` and `bot:activity`, the grant that shows the queue; `Idempotency-Key` required, empty body) takes back one of the person's queued messages before its turn starts, as the host's own **Remove** does. It returns `{ submissionId, outcome }`: `withdrawn` (it will not run), `started` (its turn already began, so it stays in the chat) or `gone` (the host no longer has it, or it is a routine's input or the Bot's self-introduction, which are not the person's to take back). Whose message it is is decided in the same step as taking it back, after any send already under way, so a request racing a routine's send never takes the routine's input. A repeat with the same key replays the receipt. A host without Bot chat activity answers 404, as does a host older than revision 67. -**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; once it has read about as many host entries as the loaded part spanned (entries this Mac can't show count too), or has reached that entry, it asks the host about each loaded entry not yet read back (one the host removed or moved further back), at most 8 in all (one-entry pages; `operation_stale` means gone), reading on to each one the host still has; the cut is at whichever loaded entry comes first in the host's current order, so loaded messages the host still has stay; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. +**Desktop clients.** A paired Mac shows **Load older messages** above a remote Bot's chat while the session says `hasOlder`, and places each page before what it shows. A snapshot of the same epoch (a reconnect, or the host removing or reordering entries) keeps the loaded pages only after reading them again from the host, in pages of at most 200 until it reaches the oldest loaded entry, and anything older that a page brought is cut off, so nothing older than before is added and Load older resumes where it was; once it has read about as many host entries as the loaded part spanned (entries this Mac can't show count too), or has reached that entry, it asks the host about each loaded entry not yet read back (one the host removed or moved further back), at most 8 in all (one-entry pages; `operation_stale` means gone), reading on to each one the host still has; if loaded entries are still unaccounted for after 8, the loaded pages are dropped and Load older starts again from the snapshot; the cut is at whichever loaded entry comes first in the host's current order, so loaded messages the host still has stay; if a read fails it keeps the pages already read and Load older continues from there, or drops the loaded pages if none was read; a page asked for before a snapshot is not placed. A page's oldest entry of a kind this Mac can't show still moves the next page past it. Against an older host the button gives way to "Older messages are on . Update Aiden there to see them here." Queued messages in a remote Bot chat (shown only with `bot:activity`) get the same **Remove** as local ones; `started` says "That message already started, so it stays.", and an older host is told to update. Phones don't use either route yet. **Fixtures.** The fixture carries only the new `contractRevision`; the protocol test checks both shapes against the parser and the OpenAPI schemas (`BotSessionEntriesPage`, `BotQueuedWithdrawReceipt`). diff --git a/renderer/lib/hosts/remote-bot-session-follower.ts b/renderer/lib/hosts/remote-bot-session-follower.ts index f42cf6de6b..c897fa7c0d 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -232,7 +232,8 @@ export class RemoteBotSessionFollower { * asked about, at most `KEPT_PROBE_MAX` in all: reading goes on to each one * the host still has. The re-read is cut back to whichever kept entry comes * first, so nothing older than before is added and no kept entry the host - * has is dropped. A read that fails keeps the pages already read (Load older + * has is dropped. If the questions run out with kept entries still not + * accounted for, the loaded part is dropped instead. A read that fails keeps the pages already read (Load older * continues from there), or drops the kept entries if none was. */ private rereadCarried(carried: number, fresh: RemoteBotSessionView): void { @@ -290,7 +291,10 @@ export class RemoteBotSessionFollower { // answers `operation_stale` when it no longer has it. const ask = (cursor: string, total: number): void => { const id = kept.find((candidate) => !seen.has(candidate) && !gone.has(candidate)); - if (id === undefined || probes >= KEPT_PROBE_MAX || !transport.older) return settle(pages); + if (id === undefined || !transport.older) return settle(pages); + // Out of questions with kept entries still unaccounted for: the loaded + // part is dropped rather than guessed at, and Load older starts again. + if (probes >= KEPT_PROBE_MAX) return settle([]); probes += 1; transport.older(this.hostId, this.botId, id, 1).then( (outcome) => { diff --git a/renderer/lib/hosts/remote-bot-session.test.ts b/renderer/lib/hosts/remote-bot-session.test.ts index 39b47a0ff8..9968f8b367 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -731,9 +731,43 @@ test("a rewrite that removed every kept entry asks the host about only a few of const probes = asked.filter(([before]) => before.startsWith("k")); assert.ok(probes.length > 0 && probes.length <= 8, JSON.stringify(probes)); assert.ok(asked.length <= probes.length + 2, JSON.stringify(asked)); + // Kept entries were left unasked, so the loaded part is dropped and Load older starts again. + assert.deepEqual(follower.getState().view!.snapshot.entries.map((entry) => entry.id), ["m5", "m6", "m7"]); + assert.equal(follower.getState().view!.hasOlder, true); + follower.stop(); +}); + +test("running out of questions drops the loaded part rather than show a partial re-read as it", async () => { + const message = (id: string) => ({ type: "message" as const, id, role: "assistant" as const, text: id }); + const keptIds = Array.from({ length: 12 }, (_, index) => `k${index + 1}`); + // The host removed the first ten kept entries; "k11" and "k12" remain, far back behind entries this Mac + // can't show, and two new entries sit where the bounded re-read reaches. + const host = ["k11", "k12", ...Array.from({ length: 60 }, (_, index) => `u${index + 1}`), "o1", "o2", "m5", "m6", "m7"]; + const fake = fakeTransport([session({ hasOlder: true, entries: [...keptIds, "m5", "m6"].map(message) })]); + const asked: Array<[string, number | undefined]> = []; + fake.transport.older = async (_hostId, _botId, before, limit) => { + asked.push([before, limit]); + const end = host.indexOf(before); + if (end < 0) return { ok: false, error: { code: "http_error", status: 409, remoteCode: "operation_stale", message: "This Bot's chat changed. Read it again." } }; + const start = Math.max(0, end - (limit ?? 2)); + const sent = host.slice(start, end); + return { + ok: true, + value: { + botId: "bot_1", epoch: "e1", hasOlder: start > 0, olderCursor: sent[0], hostCount: sent.length, + entries: sent.filter((id) => !id.startsWith("u")).map(message), + }, + }; + }; + const follower = new RemoteBotSessionFollower(fake.transport, "host_a", "bot_1"); + follower.start(); + await settle(); + fake.push(event(4, { type: "snapshot", payload: { session: session({ seq: 5, hasOlder: true, entries: ["m5", "m6", "m7"].map(message) }) } })); + await settle(); + assert.ok(asked.filter(([before]) => before.startsWith("k")).length <= 8, JSON.stringify(asked)); const ids = follower.getState().view!.snapshot.entries.map((entry) => entry.id); - assert.ok(!ids.some((id) => id.startsWith("k")), "the removed entries are gone"); - assert.deepEqual(ids.slice(-3), ["m5", "m6", "m7"]); + assert.deepEqual(ids, ["m5", "m6", "m7"], "a partial re-read missing k11 and k12 is not shown as the loaded part"); + assert.equal(follower.getState().view!.hasOlder, true); follower.stop(); }); From 542d584d6eb9032a540913ec4609a840882d7e73 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 05:52:55 -0500 Subject: [PATCH 14/16] Resume the recording card on the main thread in its ownership UI test The Compose test rule runs composition coroutines on an unconfined dispatcher, so the card's Play continuation adopted its file on the IO worker that finished the download. The test's main-thread sync did not wait for it, and a disposal could land between adopt's disposed check and its owned assignment, leaving the file unreleased. That surfaced as a bare AssertionError from eventually in replacingCardReleasesOldDeliveryAndOwnsTheNextOne on CI. The test's load now hops back to the main thread, as the card does on a device, with a hop that always suspends and ignores cancellation so late delivery after disposal is still covered. App code is unchanged. --- .memory/browser-recordings-chat-and-phones.md | 7 +++++++ .../AidenBrowserRecordingOwnershipUiTest.kt | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/.memory/browser-recordings-chat-and-phones.md b/.memory/browser-recordings-chat-and-phones.md index 5dd1363fc4..0845c281bb 100644 --- a/.memory/browser-recordings-chat-and-phones.md +++ b/.memory/browser-recordings-chat-and-phones.md @@ -37,3 +37,10 @@ Status (2026-10-27): implemented on branch `claude/project-thread-p5v2my-browser - iOS local validation: focused 10 recording checks pass; broader AidenChatTests, AidenRemoteClientTests and AidenBrowserRecordingOwnershipTests run 519 tests with zero failures and the three existing physical-device-only checks skipped. Destination: dedicated iPhone 17 / iOS 26.5 simulator `DD3ECACB-4B94-41F8-AC36-E559833ADC03`. Physical-device playback/Keychain acceptance is not claimed. - Initial local checks caught a Swift actor-isolated default initializer and Android comment indentation; corrected without suppressions or policy changes. One Android instrumentation attempt was interrupted by my own queued force-stop while diagnosing the slow first emulator startup; the subsequent unchanged six-case run passed. Final diff review caught a callback/method name collision in the Android owner; the five release-path tests failed on that compiled intermediate candidate (the cancellation control passed), and the callback was renamed before rebuilding. This was a deterministic implementation failure, not a flaky rerun. Final checks are recorded in the PR checkpoint. - Final checkpoint validation: Android full JVM suite 1,120 tests / zero failures; all six production lifecycle instrumentation cases pass on the corrected binary, with Kotlin app/test compilation and `lintDebug` passing. Broader iOS results are 516 passes plus the three configured physical-only skips (519 total), zero failures. Final source/test/docs review and diff checks pass; fresh `origin/main` remains `9b2875d65f316265323d3d06a73904fbe00e2277`. No retry, timeout, lint baseline or failure-policy weakening. PR remains open for root's exact-head CI and merge decision. + +## 2026-11-24: Android ownership UI test race (found on PR #910 CI) + +- `AidenBrowserRecordingOwnershipUiTest.replacingCardReleasesOldDeliveryAndOwnsTheNextOne` failed once in hosted CI (run 45362691722, job 138337222924) with a bare `AssertionError` from `eventually`. The PR it ran on changed no Android app code. +- Cause was the test harness, not the card. `createComposeRule()` runs composition coroutines on an unconfined test dispatcher, so the card's Play continuation (`owner.adopt`, `playing = file`) ran on the `Dispatchers.IO` worker that finished the download. The test's `runOnMainSync {}` therefore did not wait for it, and a main-thread disposal could run between adopt's `disposed` check and its `owned` assignment, leaving the file unreleased. On a device the card resumes on the main thread. +- Logging showed the delivery on `DefaultDispatcher-worker-*`. A temporary 300 ms pause in `adopt` when it was off the main thread turned four of the six cases red, with the same `eventually` symptom. +- Fix (test only): the test's `load` hops back to the main thread before handing over the result. It uses a hop that always suspends and ignores cancellation, so late delivery after disposal is still exercised. Do not use `suspendCoroutine` with a posted resume for this: it can resume before suspending and stay on the worker. Production code is unchanged. diff --git a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt index a4f50aa58e..835f9d6428 100644 --- a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt +++ b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt @@ -1,6 +1,8 @@ package sbtbiswas.AidenOnTheGo.features.chat import android.content.Context +import android.os.Handler +import android.os.Looper import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -43,6 +45,10 @@ import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit +import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED +import kotlin.coroutines.intrinsics.intercepted +import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn +import kotlin.coroutines.resume import javax.net.ssl.KeyManagerFactory import javax.net.ssl.SSLContext import sbtbiswas.AidenOnTheGo.auth.InMemoryAidenSecureStore @@ -58,6 +64,7 @@ class AidenBrowserRecordingOwnershipUiTest { @get:Rule val compose = createComposeRule() private val instrumentation get() = InstrumentationRegistry.getInstrumentation() + private val mainThread = Handler(Looper.getMainLooper()) private val visible = mutableStateOf(true) private val releaseFiles = CopyOnWriteArrayList() private val requested = CountDownLatch(1) @@ -144,6 +151,7 @@ class AidenBrowserRecordingOwnershipUiTest { // transfers a real file; the disposed owner must reject it. withContext(NonCancellable) { model.browserRecording(recording) } } else model.browserRecording(recording) + continueOnMainThread() resultFile = (loaded as? AidenBrowserRecordingLoad.Ready)?.recording delivered.add(loaded) loaded @@ -188,6 +196,18 @@ class AidenBrowserRecordingOwnershipUiTest { } } + /** + * The test composition's dispatcher is unconfined, so the card would otherwise adopt its + * file on the download thread, racing its main-thread disposal and finishing after + * [finishWithoutFrame]'s main-thread sync. On a device the card resumes on the main thread. + * Always suspends, and resumes even when the card was cancelled, so a late delivery still + * reaches the disposed owner. + */ + private suspend fun continueOnMainThread(): Unit = suspendCoroutineUninterceptedOrReturn { continuation -> + mainThread.post { continuation.intercepted().resume(Unit) } + COROUTINE_SUSPENDED + } + private fun startPaused() { compose.mainClock.autoAdvance = false compose.onNodeWithText("Play").performClick() From f68566c490d046052a03b2b64dc4946b1bf64f4f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 11:03:13 +0000 Subject: [PATCH 15/16] Hop to the main thread through withContext in the recording ownership test Resuming the raw continuation from a main-thread post could run it before the download thread had returned COROUTINE_SUSPENDED. withContext handles a resume that races the suspension, and NonCancellable keeps the late-delivery-after-disposal case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018VA6REg8PpdXdPfTkkCKZJ --- .../chat/AidenBrowserRecordingOwnershipUiTest.kt | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt index 835f9d6428..a9abe63c1f 100644 --- a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt +++ b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt @@ -1,8 +1,6 @@ package sbtbiswas.AidenOnTheGo.features.chat import android.content.Context -import android.os.Handler -import android.os.Looper import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -45,10 +43,6 @@ import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit -import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED -import kotlin.coroutines.intrinsics.intercepted -import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn -import kotlin.coroutines.resume import javax.net.ssl.KeyManagerFactory import javax.net.ssl.SSLContext import sbtbiswas.AidenOnTheGo.auth.InMemoryAidenSecureStore @@ -64,7 +58,6 @@ class AidenBrowserRecordingOwnershipUiTest { @get:Rule val compose = createComposeRule() private val instrumentation get() = InstrumentationRegistry.getInstrumentation() - private val mainThread = Handler(Looper.getMainLooper()) private val visible = mutableStateOf(true) private val releaseFiles = CopyOnWriteArrayList() private val requested = CountDownLatch(1) @@ -200,12 +193,11 @@ class AidenBrowserRecordingOwnershipUiTest { * The test composition's dispatcher is unconfined, so the card would otherwise adopt its * file on the download thread, racing its main-thread disposal and finishing after * [finishWithoutFrame]'s main-thread sync. On a device the card resumes on the main thread. - * Always suspends, and resumes even when the card was cancelled, so a late delivery still - * reaches the disposed owner. + * Hops through the coroutine library, which handles a resume that races the suspension, and + * ignores cancellation, so a late delivery still reaches the disposed owner. */ - private suspend fun continueOnMainThread(): Unit = suspendCoroutineUninterceptedOrReturn { continuation -> - mainThread.post { continuation.intercepted().resume(Unit) } - COROUTINE_SUSPENDED + private suspend fun continueOnMainThread() { + withContext(NonCancellable) { withContext(Dispatchers.Main) {} } } private fun startPaused() { From 73ab98049fdc21a9849951fe829eeb9a3fe81f83 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 06:08:16 -0500 Subject: [PATCH 16/16] Restore the post-and-resume main-thread hop in the recording ownership test The withContext(Dispatchers.Main) {} hop from the previous commit does not keep the card on the main thread. The empty block usually finishes on main before the download thread suspends, so that thread takes the result and carries on. With a pause in adopt whenever it ran off the main thread, 10 of 13 adopts were on the worker and 3 or 4 of the 6 cases failed on each run. The hop now always suspends and is resumed only by the posted main-thread task. With the same probe, 15 of 15 adopts ran on main and all cases passed. Resuming while the worker is still returning COROUTINE_SUSPENDED is the ordinary dispatcher handoff. --- .memory/browser-recordings-chat-and-phones.md | 1 + .../AidenBrowserRecordingOwnershipUiTest.kt | 21 +++++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/.memory/browser-recordings-chat-and-phones.md b/.memory/browser-recordings-chat-and-phones.md index 0845c281bb..5cf2edb578 100644 --- a/.memory/browser-recordings-chat-and-phones.md +++ b/.memory/browser-recordings-chat-and-phones.md @@ -44,3 +44,4 @@ Status (2026-10-27): implemented on branch `claude/project-thread-p5v2my-browser - Cause was the test harness, not the card. `createComposeRule()` runs composition coroutines on an unconfined test dispatcher, so the card's Play continuation (`owner.adopt`, `playing = file`) ran on the `Dispatchers.IO` worker that finished the download. The test's `runOnMainSync {}` therefore did not wait for it, and a main-thread disposal could run between adopt's `disposed` check and its `owned` assignment, leaving the file unreleased. On a device the card resumes on the main thread. - Logging showed the delivery on `DefaultDispatcher-worker-*`. A temporary 300 ms pause in `adopt` when it was off the main thread turned four of the six cases red, with the same `eventually` symptom. - Fix (test only): the test's `load` hops back to the main thread before handing over the result. It uses a hop that always suspends and ignores cancellation, so late delivery after disposal is still exercised. Do not use `suspendCoroutine` with a posted resume for this: it can resume before suspending and stay on the worker. Production code is unchanged. +- `withContext(NonCancellable) { withContext(Dispatchers.Main) {} }` was tried as a replacement (f68566c49) and does not hold. With the same off-main probe, 10 of 13 adopts ran on the worker and 3 or 4 of the 6 cases failed on each run: the empty main-thread block usually finishes before the caller suspends, so the caller continues on the download thread. The `suspendCoroutineUninterceptedOrReturn` post-and-resume hop puts 15 of 15 adopts on main. diff --git a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt index a9abe63c1f..c4a02cb0b5 100644 --- a/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt +++ b/android/app/src/androidTest/java/sbtbiswas/AidenOnTheGo/features/chat/AidenBrowserRecordingOwnershipUiTest.kt @@ -1,6 +1,8 @@ package sbtbiswas.AidenOnTheGo.features.chat import android.content.Context +import android.os.Handler +import android.os.Looper import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -43,6 +45,10 @@ import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit +import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED +import kotlin.coroutines.intrinsics.intercepted +import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn +import kotlin.coroutines.resume import javax.net.ssl.KeyManagerFactory import javax.net.ssl.SSLContext import sbtbiswas.AidenOnTheGo.auth.InMemoryAidenSecureStore @@ -58,6 +64,7 @@ class AidenBrowserRecordingOwnershipUiTest { @get:Rule val compose = createComposeRule() private val instrumentation get() = InstrumentationRegistry.getInstrumentation() + private val mainThread = Handler(Looper.getMainLooper()) private val visible = mutableStateOf(true) private val releaseFiles = CopyOnWriteArrayList() private val requested = CountDownLatch(1) @@ -193,11 +200,17 @@ class AidenBrowserRecordingOwnershipUiTest { * The test composition's dispatcher is unconfined, so the card would otherwise adopt its * file on the download thread, racing its main-thread disposal and finishing after * [finishWithoutFrame]'s main-thread sync. On a device the card resumes on the main thread. - * Hops through the coroutine library, which handles a resume that races the suspension, and - * ignores cancellation, so a late delivery still reaches the disposed owner. + * Ignores cancellation, so a late delivery still reaches the disposed owner. + * + * This always suspends and is always resumed by the posted main-thread task. A + * `withContext(Dispatchers.Main) {}` hop is not enough: when its empty block finishes before + * the caller suspends, the caller keeps the result and carries on on the download thread. + * Resuming from main while the download thread is still returning COROUTINE_SUSPENDED is the + * ordinary dispatcher handoff; nothing runs on that thread after the return. */ - private suspend fun continueOnMainThread() { - withContext(NonCancellable) { withContext(Dispatchers.Main) {} } + private suspend fun continueOnMainThread(): Unit = suspendCoroutineUninterceptedOrReturn { continuation -> + mainThread.post { continuation.intercepted().resume(Unit) } + COROUTINE_SUSPENDED } private fun startPaused() {