diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md index 8f550a7bdc..a7e7de6847 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`, record version 2). Every time in it is the host's, never this Mac's clock: a per-host baseline (the newest `lastReplyAt` when this Mac first lists that host's Bots, so existing replies start read) and per-Bot seen times. A reply counts as seen only once the remote chat's session view shows it (`remoteBotShownReplyAt`), not when its row is selected. The host baseline is taken only from a listing whose every row is `summarized: true` (proof of revision 66, and no Bot whose summary read failed is left out; `summarized` marks every row whose summary the host read, so a host whose Bots are all still empty gets baseline 0 and their first reply shows a dot), since an older host sends `lastReplyAt` only for open feeds. Host feed Bot signals are cached per Bot (`createHostFeedBotSignalsCache` in `aiden-remote-host-feed.ts`) and invalidated by that Bot's `bots:changed` / `bots:attention`; `onBroadcast` forwards only the `botId` of a `bots:*` payload. - 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` is a hash of what the card shows, so re-reading the same plan keeps the card mounted) 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 (and logs by id) a Bot whose summary fails the contract instead of failing the whole list (and the host feed); a transient summary read error fails the list so clients keep their last rows. -- 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/.memory/browser-recordings-chat-and-phones.md b/.memory/browser-recordings-chat-and-phones.md index 5dd1363fc4..5cf2edb578 100644 --- a/.memory/browser-recordings-chat-and-phones.md +++ b/.memory/browser-recordings-chat-and-phones.md @@ -37,3 +37,11 @@ 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. +- `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 a4f50aa58e..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) @@ -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,23 @@ 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. + * 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(): Unit = suspendCoroutineUninterceptedOrReturn { continuation -> + mainThread.post { continuation.intercepted().resume(Unit) } + COROUTINE_SUSPENDED + } + private fun startPaused() { compose.mainClock.autoAdvance = false compose.onNodeWithText("Play").performClick() 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 f2700cd70b..c349c53ecb 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 reply that arrives after this Mac first lists the Bot, and that its chat here hasn't shown yet, shows an unread dot. The last message and the dot need that computer on contract revision 66; with an older one the line stays empty. A Bot's description is never shown as its line; search still matches it. Opening one row leaves the others clickable. 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 reply that arrives after this Mac first lists the Bot, and that its chat here hasn't shown yet, shows an unread dot. The last message and the dot need that computer on contract revision 66; with an older one the line stays empty. A Bot's description is never shown as its line; search still matches it. Opening one row leaves the others clickable. 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 14f7e49cb3..1f4068de42 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, or, before it showed any, than the host's newest `lastReplyAt` when this Mac first listed that host's Bots (any reply at all, if none of them had replied yet). It takes that baseline only from a listing whose every row is `summarized`, which shows the host is on revision 66 and reported every listed Bot's reply, even when none of its Bots has a message yet; a listing where one Bot's summary read failed waits for the next refresh, so that Bot's earlier reply isn't left out of the baseline. An older host marks no row: a baseline from it would be too low, so its earlier replies would read as new once it upgrades. Only the host's times are compared, never this Mac's clock. That record is kept per Mac in local storage, by host and Bot. Older desktops ignore the key. Phones don't read the host feed. **Fixtures.** `protocol/aiden-remote/v1/fixtures/contract.json` adds a `bot.upsert` host feed event with `needsYou`, `lastReplyAt`, `preview` and `summarized`. The desktop parser checks every snapshot and `bot.upsert` Bot row against the same rules (no `issueCount`, `needsYou`, `failed` and `summarized` only `true`, a date-time `lastReplyAt`, a trimmed one-line `preview` of at most 140 characters). + +## 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). 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; 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/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..28f0a144d8 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,124 @@ 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" }); + // 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()!(); + 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..35006bc1e7 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,13 @@ 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`). `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, options?: { personOnly?: boolean }): Promise<"withdrawn" | "started" | "gone">; } export interface AidenRemoteBotSessionServiceOptions { @@ -865,9 +878,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 +1156,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 +2724,69 @@ 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(); + // 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); + 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 69d7099055..227b1cfcc7 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); @@ -4039,3 +4043,34 @@ test("revision 66 host feed Bot rows carry a one-line preview and refuse anythin assert.equal(feedBot({ ...row, preview: "x".repeat(141) }), false); assert.equal(feedBot({ ...row, summarized: false }), 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 a833930371..fb7e27b401 100644 --- a/main/services/aiden-remote-protocol.ts +++ b/main/services/aiden-remote-protocol.ts @@ -382,7 +382,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; @@ -2122,6 +2133,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 } } @@ -6632,6 +6669,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; + 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 94b9ce210f..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, @@ -101,6 +102,26 @@ export function peerBotSessionCompat(value: unknown): unknown { return session; } +/** One page of older entries as this client can read it: an entry it cannot read is left out. */ +export function peerBotSessionPageCompat(value: unknown): unknown { + if (!isRecord(value) || !Array.isArray(value.entries)) return value; + 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 9fb867c08e..3a04b1c45d 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,43 @@ 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 }; + const oldest = (entries[0] as { id: string }).id; + 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", 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", hostCount: 1 }, + ); + 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..42682bd68f 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, peerBotSessionPageCursor } 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,17 @@ 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); + const parsed = parseAidenRemoteBotSessionEntriesPage(page); + // 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); + const hostCount = (value as { entries: unknown[] }).entries.length; + return { ...parsed, ...(olderCursor === undefined ? {} : { olderCursor }), hostCount }; + } await validatePeerResponse(name, value); if (name === "summaries") return parseAidenRemoteChatSummaryPage(value, "Peer chat summaries"); @@ -197,6 +214,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 +417,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 +615,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 7ed24dde82..0b6ee5c88f 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 a0f32ff872..4b1d53f250 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": [ { @@ -25282,6 +25405,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..c897fa7c0d 100644 --- a/renderer/lib/hosts/remote-bot-session-follower.ts +++ b/renderer/lib/hosts/remote-bot-session-follower.ts @@ -6,7 +6,20 @@ 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 { + 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; +/** At most this many kept entries a re-read didn't reach are asked about. */ +const KEPT_PROBE_MAX = 8; export interface RemoteBotSessionTransport { subscribe(hostId: string, botId: string): Promise; @@ -14,8 +27,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=&limit=` through the host supervisor. */ + older?(hostId: string, botId: string, before: string, limit?: number): 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 +63,13 @@ export class RemoteBotSessionFollower { private subscribing = false; 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, @@ -81,6 +110,49 @@ 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 history = this.history; + 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 }; + } + // 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 RemoteBotSessionEntriesPage; + 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 +206,9 @@ export class RemoteBotSessionFollower { else this.publish({ failed: outcome.error.message }); return; } - let view: RemoteBotSessionView | null = 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); @@ -143,7 +217,101 @@ 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, a + * 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. 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 { + const view = this.state.view; + if (carried <= 0 || !view) return; + const own = view.snapshot.entries[carried]?.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. + 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[]) => { + const latest = this.state.view; + if (!current() || !latest) return; + this.history += 1; + this.publish({ view: withRereadOlderRemoteBotEntries(latest, carried, fresh, pages) }); + }; + const { transport } = this; + if (!own || !transport.older) { + settle([]); + return; + } + const pages: RemoteBotSessionEntriesPage[] = []; + // 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); + 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; + 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 (!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 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 || !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) => { + if (!current()) return; + if (outcome.ok) { + target = id; + bounded = false; + return next(cursor, total); + } + if (outcome.error.remoteCode !== "operation_stale") return settle(pages); + gone.add(id); + ask(cursor, total); + }, + () => settle(pages), + ); + }; + next(own, 0); } private receive(message: PeerBotSessionMessage): void { @@ -167,7 +335,11 @@ export class RemoteBotSessionFollower { this.inFlight = false; this.resyncPending = false; this.buffered = []; - this.publish({ 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 e76014b2fd..50f56f6b2b 100644 --- a/renderer/lib/hosts/remote-bot-session.test.ts +++ b/renderer/lib/hosts/remote-bot-session.test.ts @@ -13,10 +13,13 @@ import { import { RemoteBotSessionFollower, type RemoteBotSessionTransport } from "./remote-bot-session-follower"; import { applyRemoteBotSessionEvent, + carryOlderRemoteBotEntries, hostServesBotHandoffs, hostSharesBotSessions, remoteBotPlanView, remoteBotSessionView, + withOlderRemoteBotEntries, + withRereadOlderRemoteBotEntries, type RemoteBotSessionView, } from "./remote-bot-session"; @@ -422,3 +425,409 @@ 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, 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", "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(); +}); + +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]); + // 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 } }; + }; + 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(), ["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. + 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("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); + 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 } }; + }; + 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("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". + 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]); + 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 { + 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) => + 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"]); + + // Unchanged history: the re-read spans the four host entries loaded, so "m3" and "m4" stay. + asked.length = 0; + snapshot(4); + await settle(); + 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 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"]); + 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); + 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); + 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 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 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)); + // 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.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(); +}); + +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) })); + 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")] })); + 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 d6f6b1f1a0..cd3a78e0ac 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,17 @@ 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; + /** 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; } /** @@ -265,6 +277,123 @@ export function remoteBotSessionView(session: AidenRemoteBotSession): RemoteBotS approval: session.approval, handoff: session.handoff ?? null, paused: remoteBotSessionPaused(session), + hasOlder: session.hasOlder, + // Only a transcript with more before it needs a place to page back from. + olderCursor: session.hasOlder ? (session.entries[0]?.id ?? null) : null, + }; +} + +/** + * 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, 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; hostCount?: number }; + +/** + * 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. 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, + 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; + // 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), + }; +} + +/** + * 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: 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)); + const older = entries(page.entries).filter((entry) => !held.has(entry.id)); + 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, + }; +} + +/** + * The first `carried` entries of `view` were kept from before a snapshot + * (`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, and + * 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. + */ +export function withRereadOlderRemoteBotEntries( + view: RemoteBotSessionView, + carried: number, + snapshot: Pick, + pages: readonly RemoteBotSessionEntriesPage[] | null, +): RemoteBotSessionView { + const own: RemoteBotSessionView = { + ...view, + snapshot: { ...view.snapshot, entries: view.snapshot.entries.slice(carried) }, + olderLoaded: 0, + olderHostSpan: 0, + }; + if ( + !pages || + pages.length === 0 || + pages.some((page) => page.botId !== view.snapshot.botId || page.epoch !== view.snapshot.epoch) + ) { + return { ...own, ...snapshot }; + } + 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 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: same ? view.hasOlder : true, + olderCursor: same ? view.olderCursor : boundary, + olderLoaded: (reread.olderLoaded ?? 0) - at, + olderHostSpan: view.olderHostSpan ?? 0, }; } diff --git a/renderer/lib/hosts/use-remote-bot-session.ts b/renderer/lib/hosts/use-remote-bot-session.ts index 4db8734bba..dd2bf0d5a8 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, limit) => + peerHostsApi.call(hostId, { operation: "botSessionEntries", resourceId: botId, before, ...(limit === undefined ? {} : { limit }) }), }; 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 b7ff467b70..116fbb294a 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 { RemoteBotsSection } from "../components/remote-bots-section"; import { REMOTE_BOT_SEEN_KEY, resetRemoteBotSeenForTests } from "../lib/remote-bot-seen"; @@ -773,6 +774,58 @@ test("a send the other computer refuses takes its echo away and keeps the draft" 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[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 () => { + 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); +}); + test("a paired Mac's Bot's dot clears only once its chat shows the new reply", async () => { const before = Date.parse("2026-11-24T08:00:00.000Z"); const replyAt = "2026-11-24T09:00:00.000Z"; diff --git a/renderer/main/remote-bot-chat-view.tsx b/renderer/main/remote-bot-chat-view.tsx index 4df7933b2b..3fc9c640e5 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"; @@ -234,6 +234,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 () => { @@ -893,6 +944,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. */