diff --git a/.memory/bot-chat-activity.md b/.memory/bot-chat-activity.md new file mode 100644 index 0000000000..bc3838e1d7 --- /dev/null +++ b/.memory/bot-chat-activity.md @@ -0,0 +1,32 @@ +# Bot chat activity (2026-10-14) + +Spec: docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md (§17 lists the slice B rulings). Slice B plan: docs/superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md. Branch `claude/bot-chat-activity-b-status-line`, stacked on PR #475. + +## Slice B (desktop) — what shipped +- Phase vocabulary and tool classifier: `renderer/shared/bot-activity.ts` (shared with main, the CLI, and slice D's phones). Unknown ids → `working`. Always "Thinking" keeps waiting/stopping/reconnecting. +- Main derives `BotLiveSnapshot.activity` + `activity` event in `live-projection.ts` (`liveBotActivity`), gated on session state `running` (a paused Bot still has `pi.live.run`). Stop reaches it through `notifyStopping` in the `bots:stop` handler; Resume reaches it through the service's `onResumed` callback (`bot-session-main.ts`) → `notifyResuming`, so a Resume from any surface marks it; approvals refresh it via `botApprovals.onChange`. +- Run identity is the run's first input (`inputs[0]`), not the generation task id. Resume is marked by the service's `onResumed` callback inside the per-Bot serialize; Stop/Resume flags are run-scoped (a double Stop never leaks "Stopping" into the next turn). `startedAt` renews for a queued follow-up turn. +- Transcript tool calls carry `kind/label/detail/app` (`bot-activity-detail.ts`). Command steps never show the command: only the model's `description`, redacted with `sanitizeDiagnosticText` before cutting to 80. Tool results carry `status: ok|failed|blocked|stopped` (Pi's `blocked` diagnostic; `stopped` for Stop/restart, rendered neutrally) and `durationMs`. +- `BotDefinition.chatActivity?` `{ level: quiet|summary|detailed, wording: follows|thinking }`; absent = Quiet/Follows; an update without it keeps the stored value. It is stored last in the Bot record (the revision hashes the record JSON); identity updates merge a partial `chatActivity` onto the freshly read Bot. Remote identity PATCH still rejects it (slice D). +- Renderer: `BotStatusLine` (hides only while reply text streams with no active tool step; the visible line is a `role="group"` named by its words; announcements go to `BotStatusAnnouncer`, one always-mounted, initially empty `role="status"` region in the pane that clears while words stream, 2 s throttle), `BotActivityRecap` (Bot-specific, not ActivityFeed), progress narration as bubbles (`BotUpdates` and `bot-reply-projection.ts` deleted), "You stopped this reply." derived from an `aborted` reply or a `stopped` tool result (a Stop during a tool run writes only the round's results; a later `interrupted` notice turns it back into a restart). The still-going note hides while the line reads Waiting or Stopping. Every user entry begins a turn (pi-durable places steers after a round's tool results). +- Queue/Steer: `pi.inbox` projected as `snapshot.queued` — the person's own inputs only, classified by durable submission requestId (`routine:`/`intro:`) plus the hidden flag, failing closed. Follow-ups show faded with Remove (`bots:withdraw` → `Harness.abortSubmission`: withdrawn | started | gone); steers are normal bubbles. +- Advanced → Chat activity (`?page=chat-activity`, `bot-chat-activity-page.tsx`): saves on pick through a serial queue, per-level Reduce Motion still frames, Reduce Motion read live. +- `BotAvatar` faces glance via `data-working` with a shared off-screen observer; list's green dot removed. Under Reduce Motion (setting or OS) a working face holds the glance's look-aside pose (`translateX(-2.6px)` on the eyes, no animation), so it still differs from idle. +- Onboarding: the Bots gallery tile (`BotsArt`: name pill, one exchange, routine chip) shows neither the list nor the Updates line, so it needed no redraw. + +## For slice D (phones) +- Remote wire is unchanged by B. D adds `activity` (phase, app ≤ 40, startedAt only) to the session stream and `chatActivity` to detail/PATCH behind `bot-activity-v1`; reuse `botActivityDisplay`, `botElapsedLabel` and `nextBotAnnouncement` semantics and the §5 table as the shared fixture. +- Remote Stop bypasses the `bots:stop` handler, so a phone Stop doesn't show Stopping on the Mac; D's planned `botTurnIntents` covers it. A phone Resume already shows "Picking up where it left off" on the Mac (the same runtime resume fires `onResumed`). +- Choosing Chat activity changes the Bot revision, so a phone's next identity edit gets `revision_conflict` and refreshes (safe). + +## Follow-ups and deferred minors +- Pre-existing on main: adding a description to a Bot that had none gives a save/reload revision mismatch (projectBot key order vs update append), a spurious conflict after restart. A canonical-JSON hash would fix it but changes every revision once. +- Accessibility: the always-mounted status region is in place (final fix wave); it still needs a manual VoiceOver check before merge. +- `botToolApp` derives the app label from the sanitized MCP tool name (lossy for punctuation or ~50+ char names); a real label from `facts.mcpTools()` would be better. `botToolPhase(toolName, app?)` gives `working` if `app` is forgotten. +- Untested step phrases (editing, photo, computer, helper, remembering plural, routine, waiting, working); "Using an app" fallback is not in the spec. +- Model-authored command descriptions pass only the generic redactor (a repeated `-pSecret` flag would show). Infrastructure throws in `checkPolicy` also yield "blocked". +- Recap: rows/header are not memoised per partial delta; `aria-controls` points to an unrendered region; truncated header has no title; `durationMs` default 0 shows "Worked for 1s"; missing tests for non-adjacent repeats, interrupted-with-unfinished-call, toggle across turn change; stale previous-turn recap when running precedes the new user entry. +- Transcript: live recap may jump after commit when the partial becomes narration; possible one-frame duplicate partial/committed bubble and remount flash on commit (key "partial" vs entry id) — check manually; desktop no longer de-dupes repeated paragraphs (phones still do). +- Queue: Remove focus moves before the withdraw resolves; the fade couples to `MessageBubble`'s private `bg-control` class (prefer a variant prop); the hidden flag is not durable (latent); a missing-id streak is never logged; no backoff on permanent inspect failure (1/s per live feed); an `openFeed` failure could orphan a retry timer. +- Runtime: `deps.state` rejection at run end leaves `{preparing}` stuck (pre-existing fallback); interrupted-with-run and approval-flip lack projection-level tests; `onResumed` → projection wire (`bot-session-main.ts`) is untested end to end and unguarded inside serialize. +- Chat activity page: `useReducedMotion` subscribe closure re-subscribes every render (hoist); Summary still-frame folded state not asserted; Pause under Reduce Motion freezes mid-loop. diff --git a/.memory/bots-rework-ui.md b/.memory/bots-rework-ui.md index bc09852d0f..45e4abf8c0 100644 --- a/.memory/bots-rework-ui.md +++ b/.memory/bots-rework-ui.md @@ -2,13 +2,15 @@ Status: implemented on PR #377 (`feature/bot-ui-durable-sessions-2f4474`). Physical-device acceptance is pending. Spec: `docs/superpowers/specs/2026-10-07-bots-rework-design.md`. Plan: `docs/superpowers/plans/2026-10-07-bots-rework.md`. Runtime: `.memory/bot-durable-runtime.md`. +See `.memory/bot-chat-activity.md` for the status line, Chat activity and recaps. + ## Screen map (desktop, iOS, Android) -- **List:** one list of Bots, with search and +. Row: avatar with an activity dot, name, subtitle pill, last-message preview, relative time. A paused Bot shows "Paused — tap to resume". Tapping a row opens its chat. Long-press or context menu: Profile, Memory (phones: only when the Mac serves `bot-memory-v1`), Advanced, separator, Delete Bot (2026-10-14; phones label it Delete). Bots from a paired Mac show a small Mac badge. +- **List:** one list of Bots, with search and +. Row: avatar whose face glances while working, name, subtitle pill, last-message preview, relative time. A paused Bot shows "Paused — tap to resume". Tapping a row opens its chat. Long-press or context menu: Profile, Memory (phones: only when the Mac serves `bot-memory-v1`), Advanced, separator, Delete Bot (2026-10-14; phones label it Delete). Bots from a paired Mac show a small Mac badge. - **First run ("Meet your first Bot"):** a carousel of starter presets. Start chat creates the preset (idempotent, keyed `preset:`) and opens its chat. Create my own opens the create flow. - **Create (two steps):** name and "What should it help with?", then optional connect-now chips (Back + Create). The self-intro runs only on genuine creation, with a model configured. -- **Chat:** header with back, a name pill that opens Profile, and ••• (Profile, Files, Memory, Advanced, separator, Delete Bot). Phones show Memory only when the Mac serves `bot-memory-v1`. Model choice in New Bot and Advanced (2026-10-14): desktop uses `BotModelPicker`, iOS a Model row pushing `AidenBotModelListView`, Android `AidenModelPickerField`. iOS New Bot and Advanced share `AidenBotEditorDraft.photoModelNeed` (none / choose / unavailable); with no usable image model on the Mac a text-only Bot saves without one. Android New Bot mints its Create key through `AidenBotCreateAttempts` (reuse only for the same request after an uncertain failure) and refetches the catalog after a failed Create so a vanished model is named. Plain bubbles, file chips, A–E quick replies (up to 5 options), connect cards, and one collapsible "Working…" / "Updates" line. Long-press gives Copy and Reply. Desktop chat mode hides workspace, git, permission, model and thinking pickers. +- **Chat:** header with back, a name pill that opens Profile, and ••• (Profile, Files, Memory, Advanced, separator, Delete Bot). Phones show Memory only when the Mac serves `bot-memory-v1`. Model choice in New Bot and Advanced (2026-10-14): desktop uses `BotModelPicker`, iOS a Model row pushing `AidenBotModelListView`, Android `AidenModelPickerField`. iOS New Bot and Advanced share `AidenBotEditorDraft.photoModelNeed` (none / choose / unavailable); with no usable image model on the Mac a text-only Bot saves without one. Android New Bot mints its Create key through `AidenBotCreateAttempts` (reuse only for the same request after an uncertain failure) and refetches the catalog after a failed Create so a vanished model is named. Plain bubbles, file chips, A–E quick replies (up to 5 options), connect cards, a status line while it works (Chat activity: Quiet/Summary/Detailed), recaps for Summary/Detailed, faded Queued bubbles with Remove. Long-press gives Copy and Reply. Desktop chat mode hides workspace, git, permission, model and thinking pickers. - **Profile:** photo (Choose photo, Generate on iOS only, Remove photo), inline name and subtitle, Character (colour and shape, Reset to default), Instructions full-screen editor, Routines, and ••• (Advanced, Delete Bot). -- **Advanced:** model and image model (auto by default), Full or Custom access, opening greeting, and the Telegram binding (desktop only). +- **Advanced:** model and image model (auto by default), Full or Custom access, opening greeting, a Chat activity row that opens its own page (`?page=chat-activity`: Quiet/Summary/Detailed and Follows the work / Always “Thinking”, saved on pick; desktop only until slice D), and the Telegram binding (desktop only). - **Delete:** a confirmation dialog with a destructive button. ## Desktop layout and save model (2026-10-09 redo) @@ -22,14 +24,14 @@ Status: implemented on PR #377 (`feature/bot-ui-durable-sessions-2f4474`). Physi - Routines group: inset-separated rows with chevrons, an "Add routine" row, skeleton/empty/error rows. Routine editor uses `FieldLabel`/`Input` (date, time)/`Select` (month day) and a red `Callout` for errors. Files dialog has a single Close, a friendly title (Bot's files / file name with its path as description), skeletons, Try again, and an empty state. ## Key files -- Desktop: `renderer/main/bots-view.tsx` (route shell), `renderer/main/bots/*` (`bot-page-shell.tsx`, `bot-page-search.ts`, `bot-list.tsx`, `bot-starter-carousel.tsx`, `bot-create-flow.tsx`, `bot-model-choice.ts`, `bot-model-picker.tsx` (`BotModelPicker`), `bot-chat-pane.tsx`, `bot-chat-header.tsx`, `bot-profile.tsx`, `bot-advanced.tsx`, `bot-delete-dialog.tsx`, `bot-routines.tsx`, `bot-routine-editor.tsx`, `bot-character-card.tsx`, `bot-updates.tsx`, `bot-session-state.ts`, `use-connection-setup.tsx`), `renderer/components/bots/connect-card.tsx`, `connection-chips.tsx` and `bot-notice-card.tsx`, shared helpers `renderer/shared/bot-presets.ts`, `bot-routine-label.ts`, `bot-routine-schedule.ts`, `bot-connections.ts`, live hook `renderer/lib/use-bot-live.ts`. +- Desktop: `renderer/main/bots-view.tsx` (route shell), `renderer/main/bots/*` (`bot-page-shell.tsx`, `bot-page-search.ts`, `bot-list.tsx`, `bot-starter-carousel.tsx`, `bot-create-flow.tsx`, `bot-model-choice.ts`, `bot-model-picker.tsx` (`BotModelPicker`), `bot-chat-pane.tsx`, `bot-chat-header.tsx`, `bot-profile.tsx`, `bot-advanced.tsx`, `bot-delete-dialog.tsx`, `bot-routines.tsx`, `bot-routine-editor.tsx`, `bot-character-card.tsx`, `bot-status-line.tsx`, `bot-activity-recap.tsx`, `bot-activity-steps.ts`, `bot-chat-activity-page.tsx`, `bot-session-state.ts`, `use-connection-setup.tsx`), `renderer/components/bots/connect-card.tsx`, `connection-chips.tsx` and `bot-notice-card.tsx`, shared helpers `renderer/shared/bot-activity.ts`, `main/services/bot-runtime/bot-activity-detail.ts`, `renderer/shared/bot-presets.ts`, `bot-routine-label.ts`, `bot-routine-schedule.ts`, `bot-connections.ts`, live hook `renderer/lib/use-bot-live.ts`. - iOS: `ios/AidenOnTheGo/Features/Bots/*` (`AidenBotsHomeView`, `AidenBotPresetsView`, `AidenBotCreateView`, `AidenBotSessionChatView`, `AidenBotSessionModel`, `AidenBotProfileView`, `AidenBotAdvancedView` (also `AidenBotModelRow`, `AidenBotModelListView`, `aidenBotModelListSections`), `AidenBotRoutinesView`, `AidenBotCharacter`, `AidenBotImagePlaygroundView`), models `Models/AidenBotSession.swift` and `Models/AidenBotRoutine.swift`. - Android: `android/app/src/main/java/sbtbiswas/AidenOnTheGo/features/bots/*` (`AidenBotsHomeScreen`, `AidenBotPresetCarousel`, `AidenBotSessionScreen`, `AidenBotSessionController`, `AidenBotProfileScreen`, `AidenBotAdvancedScreen`, `AidenBotModelChoice.kt` (`aidenBotModelPickerProviders`, `aidenBotRecommendedModel`), `AidenBotRoutines`, `AidenBotDeleteDialog`, `AidenBotCharacterCard`, `AidenBotChatHeader`, `AidenBotCanonicalAvatarView`). - Remote host: `main/services/aiden-remote-protocol.ts` (revision and feature tokens), `main/services/aiden-remote-router.ts` (routes), `main/services/aiden-remote-bot-session.ts`. - Main: `main/services/bot-runtime/*`, `main/services/bot-connection-setup.ts`, `main/services/bot-connection-dismissals.ts`, `main/services/scheduled-bot-routines.ts`. ## Deleted -- Desktop: the Conversations section and `startConversation`, the `BotEditor` wizard, `BotAccessSummary`, `BotFaceStudio`, the LLM avatar generator (`bot-avatar-generator-core.ts`, `bots:suggestAvatar`, `cancelAvatarSuggestion`), archive UI, `bots:openChat`. +- Desktop: the Conversations section and `startConversation`, the `BotEditor` wizard, `BotAccessSummary`, `BotFaceStudio`, the LLM avatar generator (`bot-avatar-generator-core.ts`, `bots:suggestAvatar`, `cancelAvatarSuggestion`), archive UI, `bots:openChat`, `bot-updates.tsx` and `bot-reply-projection.ts` (2026-10-14). - iOS: `Prototype/BotFirstPrototype.swift` and its snapshot test, `AidenBotEditorView`, `AidenBotCustomAccessFlowView`, Favorites, the compose chooser, the Full Access notice wall, the "Set Up Image Understanding" alert. - Android: `prototype/BotFirstPrototype.kt`, `AidenBotCustomAccessFlowScreen.kt`, `features/remote/AidenBotChatToolsView.kt`, `AidenBotImagePlaygroundView.kt`, Favorites, FAB chooser, Recent Chats, eye and accessory pickers. - Remote: `/bot-favorites`, `/chats/:chatId/capabilities` for Bots, `/bots/:id/archive|restore` (now refused). Delete is `DELETE /bots/{botId}`. @@ -65,7 +67,6 @@ Status: implemented on PR #377 (`feature/bot-ui-durable-sessions-2f4474`). Physi - The Bot model picker popover keeps a tall fixed list height with empty space under short lists. - **iOS simulator flake:** on Xcode-beta iOS 27, `AidenRemoteClientTests` failed to launch the host in parallel mode and passed serially. Record the run link on the PR. - Monthly routines are limited to days 1–28. -- The Updates fold shows narration only (one line per reply on desktop). - Telegram turns and routine turns that hit an approval-gated tool wait for an answer on desktop or phone. - Android has no Generate (Image Playground) option. - Phones show no inline file chips: Remote session entries carry no file metadata. diff --git a/docs/plans/README.md b/docs/plans/README.md index 9bc5d4f838..309d14ffda 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -13,7 +13,7 @@ Last refreshed 2026-10-01 against `main` at `d2197dfef` (0.51.0 plus later merge - [Bot memory, soul and proactivity](2026-10-09-bot-memory-soul-proactivity.md) — Merged in [PR #433](https://github.com/sambitcreate/aiden-agent/pull/433) after PR #428; ships in 0.56.0. Spec: [design](../superpowers/specs/2026-10-09-bot-memory-soul-proactivity-design.md). Hermes-style bounded per-Bot memory (`MEMORY.md`/`USER.md` under `/bots//memory/`, main-owned `bot_memory` tool, frozen prompt snapshot, compaction flush and steered summary, add-only background review every 10 person turns) with Profile → Memory on desktop, iOS and Android; routine results to phones and Telegram, catch-up after pause, approve/Not now routine proposals, per-routine notes and a daily check-in suggestion; `openingGreeting` removed. Persona stays in the Bot record (no `SOUL.md` file). Three parallel tracks (A memory core, B proactivity + Remote, C clients); Remote contract revision 27 is provisional and is claimed at merge (`bot-memory-v1`, `bot-proactive-v1`, device capability `bot:cards`). -- [Bot chat activity, Bots sidebar and side panel](../superpowers/specs/2026-10-14-bot-chat-activity-design.md) — Active (2026-10-14). Five stacked slices: A quick fixes ([plan](../superpowers/plans/2026-10-14-bot-chat-activity-a-quick-fixes.md): model choice in New Bot on desktop/iOS/Android, Advanced and Memory in every ••• menu, Advanced model control fix), B quiet status line + per-Bot Chat activity setting, C1 workbench shell extraction, C2 Bots-only sidebar + Bot side panel (stacked on C1), D phones (Remote revision 30, `bot-activity-v1`). B–D plans are written before each starts. +- [Bot chat activity, Bots sidebar and side panel](../superpowers/specs/2026-10-14-bot-chat-activity-design.md) — Active (2026-10-14). Five stacked slices: A quick fixes ([plan](../superpowers/plans/2026-10-14-bot-chat-activity-a-quick-fixes.md): model choice in New Bot on desktop/iOS/Android, Advanced and Memory in every ••• menu, Advanced model control fix), B quiet status line + per-Bot Chat activity setting ([plan](../superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md); implemented on `claude/bot-chat-activity-b-status-line`, stacked on PR #475, 2026-10-14), C1 workbench shell extraction, C2 Bots-only sidebar + Bot side panel (stacked on C1), D phones (Remote revision 30, `bot-activity-v1`). B–D plans are written before each starts. - [Bots rework (Grok-style Bots + Pi Durable sessions)](../superpowers/specs/2026-10-07-bots-rework-design.md) — Implemented on [PR #377](https://github.com/sambitcreate/aiden-agent/pull/377); physical-device acceptance pending. Plan: [implementation plan](../superpowers/plans/2026-10-07-bots-rework.md). Bots are single-thread chats on desktop, iOS and Android, each with one Pi Durable session on `@earendil-works/pi-durable` 1.0.3 (`/bots//session.sqlite`) and explicit Resume/Dismiss after an interruption. Also shipped: per-Bot routines, starter presets, consent-first connection cards and a permanent Delete that replaces Archive. Aiden Remote is at contract revision 25 (`bot-delete-v1`, `bot-durable-session-v1`, `bot-routines-v1`, `bot-connection-requests-v1`, `bot-presets-v1`). Known follow-ups are listed in `.memory/bots-rework-ui.md`. diff --git a/docs/superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md b/docs/superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md new file mode 100644 index 0000000000..bc72cf7ac0 --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md @@ -0,0 +1,3965 @@ +# Bot chat activity · Slice B (status line and Chat activity, desktop) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** While a Bot works, its desktop chat shows one calm status line ("Thinking", "Reading", "Searching the web"…), never tool rows by default. Each Bot gets a Chat activity setting (Quiet, Summary or Detailed; Follows the work or Always "Thinking") with live previews. Narration becomes ordinary bubbles, queued messages show faded with Remove, and Bot faces glance while their Bot works. + +**Architecture:** One shared module (`renderer/shared/bot-activity.ts`) owns the phase vocabulary, the tool → phase classifier, step phrases, elapsed-time and announcement throttling, so main, the renderer and (in slice D) the phones read one table. Main derives a live `activity` (phase, start time, safe step) from `pi.live` plus question, approval, stop and resume state, and enriches transcript tool calls and results (`kind`, `label`, `detail`, `status`, `durationMs`). It also projects queued inputs from `pi.inbox`. The renderer draws `BotStatusLine` and a Bot-specific recap fold, chosen per Bot through `BotDefinition.chatActivity`, saved through the existing `bots:update` path. + +**Tech Stack:** Electron main (Node, `@earendil-works/pi-durable` 1.0.3 harness), React 19 + TanStack Router/Query + Radix RadioGroup in `renderer/`, `node:test` via `tsx --test`, Testing Library on happy-dom (`renderer/main/bots/test-dom.ts`), pi-ai faux provider for real harness turns. + +**Spec:** [`docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md`](../specs/2026-10-14-bot-chat-activity-design.md). Slice B is §4 row B, §5, §6, §7, §14, §15 and the B rows of §16. Slice A ([plan](2026-10-14-bot-chat-activity-a-quick-fixes.md)) lands first. This plan assumes its files exist: `bot-model-choice.ts`, `bot-model-picker.tsx`, Advanced's `ModelSection` using `BotModelPicker`, and Memory and Advanced in every ••• menu. + +## Findings this plan rests on + +- **Pi Durable can withdraw one queued submission.** `@earendil-works/pi-durable@1.0.3` exposes `Harness.abortSubmission(id, context, conversationId)` and `Submission.abort(context)` (`dist/harness/submissions.js`). A submission still `queued` is settled `unanswered`/`aborted` and its `pi.inbox` item is removed. One already placed returns `already_placed`; a finished one returns `settled`. **So the Queued bubble gets a Remove** (Task 8). +- **Refusals are marked durably.** When a `beforeTool` hook blocks a call (policy refusal, a denied approval, an ingress rule), Pi writes the tool result with `isError: true` and `data.diagnostics[*].code === "blocked"` (`dist/harness/tool.js`, `harnessError("blocked", …)`). Any other error result is a failure. That is how `status: "blocked"` and `status: "failed"` are told apart (Task 2). +- **Queued and steered input lives in `pi.inbox`** (`InboxState.items: { id, mode: "steer" | "followUp" | "write", content | entry }[]`). The live feed already receives every conversation doc in `watch.value.docs`. +- **A paused (interrupted) Bot still has `pi.live.run`.** So the live activity is gated on the session state being `running`, not on `pi.live.run` alone (Task 3). +- **MCP and Composio tool names** are minted by `mcpAgentToolName` (`main/services/mcp-tool-identity.ts`) as `___<12 hex>`, with non `[A-Za-z0-9_-]` characters replaced by `_`. The connection label for "Using {app}" is read back from that prefix (Task 1). +- **The Remote projection picks wire fields explicitly** (`projectBotSessionEntries` in `main/services/aiden-remote-bot-session.ts`; Bot detail in `aiden-remote-bots.ts`). The new transcript fields and `chatActivity` therefore never reach phones in this slice. iOS and Android consume only the Remote wire, so this slice needs no mobile code change. Task 11 re-runs the Remote suite to prove the wire is unchanged. + +## Rulings on spec ambiguities + +1. **Recap component.** §6 says the trail reuses `ActivityFeed`. `ActivityFeed` owns its open state: it auto-opens only on issues, and while running its ticker replaces the header. It also tints issues amber. That contradicts §6's Detailed rules (open while live, auto-fold on finish, a manual toggle sticks) and its red "1 issue". Slice B therefore adds a small Bot recap (`BotActivityRecap`). It reuses the feed's tone tokens (`text-red`, `text-support-warning`), its `agent-thinking-shimmer` class and its row rhythm, but takes its wording from the shared step phrases rather than `summarizeActivity`. `summarizeActivity` says "Explored 1 file … 1 tool call" and cannot name apps, while §6 asks for "read 1 file, searched the web, edited 1 file, used Notion". Task 11 records this in the spec. +2. **Where categories live.** `agent-steps.ts` has verb pairs but no tool categories, so nothing moves out of it. The phase table lives only in `renderer/shared/bot-activity.ts`. +3. **Connection label.** It is parsed from the MCP agent tool name, which is sync and pure, rather than looked up through `facts.mcpTools()`. The projection has no tool facts, and `projectBotTranscript` must stay pure for Remote. +4. **Command detail.** Main prefers the model's own `description` argument, matching `safeToolDescriptor` in `generation-timeline.ts`. Otherwise it shows the first 80 characters of `command`. Either way the text is passed through `sanitizeDiagnosticText` (the existing path and secret redaction) *before* it is cut, so a secret is never split past the redactor. +5. **`chatActivity` on update** is optional. When it is absent the stored value is **kept**. Profile edits (`updateBotIdentity`) and Remote `PATCH` (which builds the update without it) must not reset the choice. +6. **Always "Thinking" hides the peek.** With that wording, neither the hover peek nor the status line's accessible name includes the step. +7. **Blocked versus failed on the recap.** The red "N issues" counts failed steps. Blocked steps get their own amber "N blocked", so the two never look alike. +8. **Extra live fields.** `BotLiveSnapshot` also gains `queued` (from `pi.inbox`), with a `queued` live event. A transcript tool call also carries `app?`, so steps from the same app can merge. +9. **Stopped turns.** "You stopped this reply." is derived in the renderer from an assistant entry with `stopReason: "aborted"` that is not followed by an `interrupted` notice. Nothing is stored. A tool result aborted by Stop counts as `failed`. +10. **Onboarding.** The Bots tile (`BotsArt` in `renderer/components/onboarding-art/control-art.tsx`) shows a chat with a bubble and typing bars. It shows neither the old list nor the Updates line, so §15 needs no redraw. Task 11 records the review. + +## Global Constraints + +- Phase ids, words and marks are exactly §5's table. Unknown ids render as `working`. +- Always "Thinking" keeps the words of `waiting`, `stopping` and `reconnecting` only. +- Elapsed time appears after 20 seconds ("· 1m 12s", measured from `activity.startedAt`). After 2 minutes a centred note reads "Still going. I'll message you when it's done." Stop appears on the Mac's line after 20 seconds. +- The status line is hidden while the reply's visible text streams. +- `step.detail` is at most 80 characters, built in main and redacted. Thinking text is never projected. +- `chatActivity` absent means `{ level: "quiet", wording: "follows" }`. New Bots never write it. +- Status line semantics: `role="status"`, accessible name = word (plus `, {detail}` on the Mac with Follows the work), announced at most once every 2 seconds. +- Motion: marks and faces freeze on their still pose under Reduce Motion and off-screen. Shimmer runs only under `data-reduce-motion="false"`. Previews pause. +- No decorative borders or outlines on radio rows; selection uses the radio plus `bg-list-selection`. Keep every `focus-visible` ring. Settings pages follow `docs/settings-design-system.md` (BotPageShell, FieldSet groups, trailing values). +- Copy, exact: "Chat activity", "How much to show", "What the status line says", "Quiet", "Summary", "Detailed", "Recommended", "Follows the work", "Always “Thinking”", "On iPhone and Android", "Queued", "Remove", "You stopped this reply.", "Still going. I'll message you when it's done.", "Worked for {t}", "Couldn’t {verb}", "Blocked: {verb}". +- Desktop only. No Remote route, wire field, feature token or protocol revision changes (slice D). +- Every new test file goes in the matching `package.json` script **and** `scripts/ci-test-registry.json`, then `npm run test:ci-policy` passes. Tests are behavioural: no source greps, no class-string or snapshot assertions. +- No network calls are added. + +## Review Focus + +1. **A Profile edit (or a phone's Remote `PATCH`) after choosing Summary.** Expected: renaming the Bot keeps Summary; only an explicit choice changes it. Test: Task 4, Step 1, test 1. +2. **A `bots.json` record whose `chatActivity` is hand-edited, from a newer build, or malformed** (`level: "verbose"`, extra keys). Expected: the Bot still loads, and its chat behaves as Quiet / Follows the work. Test: Task 4, Step 1, test 2. +3. **Remove pressed on a queued message whose turn already started.** Expected: nothing is withdrawn. The service reports `started`, and the message runs as a normal turn. Test: Task 8, Step 1, test 2. +4. **Picking a Chat activity choice fails to save** (revision conflict, Bot deleted). Expected: the radio returns to the saved choice and a toast says it couldn't save. A half-applied state never shows. Test: Task 9, Step 1, test 3. +5. **Stop pressed while nothing is running (a double-click after the reply landed).** Expected: the next turn starts at "Getting ready", never "Stopping". Test: Task 3, Step 1, test 4. + +--- + +## File map + +| File | Responsibility | +|---|---| +| Create `renderer/shared/bot-activity.ts` (+ `.test.ts`) | Phase vocabulary, tool → phase classifier, app label, step phrases, elapsed labels, announcement throttle, parallel tie-break | +| Create `main/services/bot-runtime/bot-activity-detail.ts` (+ `.test.ts`) | `botStepDescriptor`: kind, past label, bounded redacted detail for one tool call | +| Modify `renderer/shared/bot-live.ts` | Tool call `kind/label/detail/app`; tool result `status/durationMs/at`; `BotLiveActivity`; `BotQueuedMessage`; `activity` and `queued` events | +| Modify `main/services/bot-runtime/live-projection.ts` (+ test) | Enriched transcript; `liveBotActivity`; `liveQueuedMessages`; feed activity/queued; `notifyStopping`, `notifyResuming`, `refreshActivity` | +| Modify `main/services/bot-runtime/bot-session-main.ts` | `approvalPending` dep; approval changes refresh activity | +| Modify `main/services/bot-runtime/bot-session-service.ts` | `withdraw(botId, submissionId)` | +| Modify `main/handlers/bots.ts`, `main/handlers/bot-params.ts` (+ test), `main/handlers/bot-live.test.ts` | Stop/resume notify the projection; `bots:withdraw`; `chatActivity` on `bots:update` | +| Modify `renderer/shared/bots.ts`, `main/services/bot-store-core.ts` (+ test) | `BotChatActivity` type, parser, default; stored and kept across edits | +| Modify `renderer/main/bots/bot-identity.ts`, `renderer/lib/ipc.ts` | `chatActivity` patch; `botsApi.withdraw` | +| Create `renderer/main/bots/bot-status-line.tsx` (+ `.test.tsx`) | `BotStatusLine` | +| Create `renderer/main/bots/bot-activity-steps.ts`, `bot-activity-recap.tsx` (+ `bot-activity-recap.test.tsx`) | Recap step model, merge, sentence; the recap fold | +| Modify `renderer/main/bots/bot-transcript-rows.ts` (+ test), `bot-chat-pane.tsx` (+ test) | Levels, recap rows, stopped line, progress bubbles, queued rows, status line, Remove | +| Delete `renderer/main/bots/bot-updates.tsx`, `renderer/main/bots/bot-reply-projection.ts`; modify `bot-chat-mode.test.tsx` | Updates line removed | +| Create `renderer/main/bots/bot-chat-activity-page.tsx` (+ `.test.tsx`) | Advanced → Chat activity sub-page and previews | +| Modify `renderer/main/bots/bot-advanced.tsx`, `bot-page-search.ts`, `renderer/main/bots-view.tsx` | "Chat activity" row; `?page=chat-activity` | +| Modify `renderer/components/bot-avatar.tsx`, `aiden-activity-mark.tsx`, `renderer/styles.css`, `bot-chat-header.tsx`, `bot-list.tsx` (+ `bot-list.test.tsx`) | `working` faces | +| Modify `package.json`, `scripts/ci-test-registry.json`, the spec, `docs/plans/README.md`; create `.memory/bot-chat-activity.md`; modify `.memory/bots-rework-ui.md` | Registration, docs, memory | + +--- + +### Task 1: Shared status vocabulary and tool classifier + +**Files:** +- Create: `renderer/shared/bot-activity.ts` +- Test: `renderer/shared/bot-activity.test.ts` +- Modify: `package.json` (`test:bots`), `scripts/ci-test-registry.json` + +**Interfaces:** +- Consumes: `ActivityMark` from `renderer/shared/activity-marks.ts`. `BotChatActivityWording` is declared here as a local string union so this task has no dependency on Task 4. Task 4 re-exports it from `bots.ts`. +- Produces: + - `BOT_ACTIVITY_PHASES`, `type BotActivityPhase`, `isBotActivityPhase(value): value is BotActivityPhase` + - `type BotToolPhase` (the subset a tool maps to, including `"waiting"`) + - `type BotChatActivityWording = "follows" | "thinking"` + - `BOT_APP_LABEL_CHARS = 40`, `botToolApp(toolName): string | undefined`, `botToolPhase(toolName, app?): BotToolPhase` + - `botPhaseWord(phase, app?): string`, `botActivityDisplay(phase: string, wording, app?): { phase; word; mark }` + - `botStepPhrase(kind: BotToolPhase, count, app?): string` (past tense, "Read 6 files"), `botStepInfinitive(kind, app?): string` ("run a command") + - `BOT_ELAPSED_AFTER_MS = 20_000`, `BOT_STILL_GOING_AFTER_MS = 120_000`, `botDurationLabel(ms)`, `botElapsedLabel(startedAt, now): string | null` + - `BOT_ANNOUNCE_GAP_MS = 2_000`, `interface BotAnnouncement { text; at }`, `nextBotAnnouncement(current, text, now, gapMs?) → { shown; retryInMs? }` + - `pickActiveToolSlot(slots): T | undefined` + +- [ ] **Step 1: Write the failing tests** + +```ts +// renderer/shared/bot-activity.test.ts +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + botActivityDisplay, + botElapsedLabel, + botStepInfinitive, + botStepPhrase, + botToolApp, + botToolPhase, + nextBotAnnouncement, + pickActiveToolSlot, +} from "./bot-activity"; + +// The spec's §5.1 table, row by row: the independent oracle. +const SPEC_TOOL_PHASES: ReadonlyArray<[string, string]> = [ + ["read_file", "reading"], + ["list_dir", "reading"], + ["glob", "reading"], + ["grep", "reading"], + ["edit_file", "editing"], + ["write_file", "editing"], + ["run_command", "command"], + ["web_search", "searching"], + ["computer_use", "computer"], + ["form_fill", "computer"], + ["inspect_image", "photo"], + ["subagent", "helper"], + ["bot_memory", "remembering"], + ["routines", "routine"], + ["routine_notes", "routine"], + ["ask_user_question", "waiting"], + ["share_image", "working"], + ["suggest_connection", "working"], + ["skill_meal_planning", "working"], + ["constructor", "working"], +]; + +test("every Bot tool maps to the phase in the spec's table, and anything else is working", () => { + for (const [tool, phase] of SPEC_TOOL_PHASES) { + assert.equal(botToolPhase(tool, botToolApp(tool)), phase, tool); + } +}); + +test("a connection tool is Using {app}, named from the connection, and bounded", () => { + const tool = "Google_Calendar__list_events_0123456789ab"; + assert.equal(botToolApp(tool), "Google Calendar"); + assert.equal(botToolPhase(tool, botToolApp(tool)), "app"); + assert.equal(botActivityDisplay("app", "follows", "Google Calendar").word, "Using Google Calendar"); + const long = `${"A".repeat(60)}__search_0123456789ab`; + assert.equal([...(botToolApp(long) ?? "")].length, 40); + // Not a minted connection tool name: no app. + assert.equal(botToolApp("web_search"), undefined); + assert.equal(botToolApp("Notion__search"), undefined); +}); + +test("when tools run in parallel, the most recently started one wins", () => { + const slots = [ + { name: "a", status: "done" }, + { name: "b", status: "running" }, + { name: "c", status: "running" }, + { name: "d", status: "pending" }, + ]; + assert.equal(pickActiveToolSlot(slots)?.name, "c"); + assert.equal(pickActiveToolSlot([{ name: "x", status: "pending" }, { name: "y", status: "pending" }])?.name, "x"); + assert.equal(pickActiveToolSlot([{ name: "z", status: "done" }]), undefined); + assert.equal(pickActiveToolSlot(undefined), undefined); +}); + +test("each phase has the spec's word and mark, and an unknown phase is working", () => { + assert.deepEqual(botActivityDisplay("preparing", "follows"), { phase: "preparing", word: "Getting ready", mark: "bounce" }); + assert.deepEqual(botActivityDisplay("reading", "follows"), { phase: "reading", word: "Reading", mark: "scan-grid" }); + assert.deepEqual(botActivityDisplay("tidying", "follows"), { phase: "tidying", word: "Tidying up its notes", mark: "bounce" }); + assert.deepEqual(botActivityDisplay("browsing", "follows"), { phase: "working", word: "Working", mark: "quad-shuffle" }); +}); + +test("Always Thinking says Thinking for everything except waiting, stopping and reconnecting", () => { + for (const phase of ["preparing", "reading", "command", "app", "writing", "tidying", "resuming", "browsing"]) { + assert.deepEqual(botActivityDisplay(phase, "thinking", "Notion"), { phase: "thinking", word: "Thinking", mark: "tri-step" }, phase); + } + assert.equal(botActivityDisplay("waiting", "thinking").word, "Waiting for you"); + assert.equal(botActivityDisplay("stopping", "thinking").word, "Stopping"); + assert.equal(botActivityDisplay("reconnecting", "thinking").word, "Reconnecting to your Mac"); +}); + +test("elapsed time shows only after 20 seconds, as minutes and seconds", () => { + assert.equal(botElapsedLabel(0, 19_999), null); + assert.equal(botElapsedLabel(0, 20_000), "20s"); + assert.equal(botElapsedLabel(0, 72_400), "1m 12s"); + assert.equal(botElapsedLabel(0, 120_000), "2m"); + assert.equal(botElapsedLabel(0, 3_725_000), "1h 2m"); + assert.equal(botElapsedLabel(Number.NaN, 50_000), null); +}); + +test("announcements change at most once every 2 seconds, and the newest wording wins once the gap passes", () => { + const first = nextBotAnnouncement(null, "Reading", 1_000); + assert.deepEqual(first, { shown: { text: "Reading", at: 1_000 } }); + const tooSoon = nextBotAnnouncement(first.shown, "Searching the web", 1_500); + assert.deepEqual(tooSoon, { shown: { text: "Reading", at: 1_000 }, retryInMs: 1_500 }); + const same = nextBotAnnouncement(first.shown, "Reading", 1_200); + assert.equal(same.shown, first.shown); + assert.equal(same.retryInMs, undefined); + assert.deepEqual(nextBotAnnouncement(first.shown, "Editing files", 3_000), { shown: { text: "Editing files", at: 3_000 } }); +}); + +test("step phrases read naturally and count repeats", () => { + assert.equal(botStepPhrase("reading", 1), "Read 1 file"); + assert.equal(botStepPhrase("reading", 6), "Read 6 files"); + assert.equal(botStepPhrase("searching", 1), "Searched the web"); + assert.equal(botStepPhrase("searching", 3), "Searched the web 3 times"); + assert.equal(botStepPhrase("app", 1, "Notion"), "Used Notion"); + assert.equal(botStepPhrase("command", 2), "Ran 2 commands"); + assert.equal(botStepInfinitive("command"), "run a command"); + assert.equal(botStepInfinitive("app", "Notion"), "use Notion"); +}); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test renderer/shared/bot-activity.test.ts` +Expected: FAIL, `Cannot find module './bot-activity'`. + +- [ ] **Step 3: Write the implementation** + +```ts +// renderer/shared/bot-activity.ts +// What a working Bot's status line says (spec 2026-10-14 §5): one phase at a +// time, with the same ids, words and marks on the Mac and, from slice D, on +// phones. Main classifies the active tool with this table, the renderer draws +// it, and the CLI bundles it as is. + +import type { ActivityMark } from "./activity-marks.js"; + +export const BOT_ACTIVITY_PHASES = [ + "preparing", + "thinking", + "reading", + "photo", + "searching", + "command", + "editing", + "app", + "helper", + "computer", + "remembering", + "routine", + "working", + "writing", + "waiting", + "tidying", + "stopping", + "resuming", + "reconnecting", +] as const; +export type BotActivityPhase = (typeof BOT_ACTIVITY_PHASES)[number]; + +/** The phases an active tool maps to (§5.1). */ +export type BotToolPhase = Extract< + BotActivityPhase, + | "reading" + | "photo" + | "searching" + | "command" + | "editing" + | "app" + | "helper" + | "computer" + | "remembering" + | "routine" + | "working" + | "waiting" +>; + +/** What the status line says: the work, or always "Thinking". */ +export type BotChatActivityWording = "follows" | "thinking"; + +const PHASES: Record = { + preparing: { word: "Getting ready", mark: "bounce" }, + thinking: { word: "Thinking", mark: "tri-step" }, + reading: { word: "Reading", mark: "scan-grid" }, + photo: { word: "Looking at your photo", mark: "scan-grid" }, + searching: { word: "Searching the web", mark: "scan-grid" }, + command: { word: "Running a command", mark: "quad-shuffle" }, + editing: { word: "Editing files", mark: "quad-shuffle" }, + app: { word: "Using an app", mark: "quad-shuffle" }, + helper: { word: "Asking a helper", mark: "quad-shuffle" }, + computer: { word: "Using your Mac", mark: "quad-shuffle" }, + remembering: { word: "Remembering", mark: "compose" }, + routine: { word: "Setting up a routine", mark: "tri-step" }, + working: { word: "Working", mark: "quad-shuffle" }, + writing: { word: "Writing", mark: "compose" }, + waiting: { word: "Waiting for you", mark: "glance" }, + tidying: { word: "Tidying up its notes", mark: "bounce" }, + stopping: { word: "Stopping", mark: "bounce" }, + resuming: { word: "Picking up where it left off", mark: "bounce" }, + reconnecting: { word: "Reconnecting to your Mac", mark: "bounce" }, +}; + +/** The Bot tool set's fixed tools (`bot-tool-policy.ts`, `bot-file-tool-router.ts`). */ +const TOOL_PHASES: ReadonlyMap = new Map([ + ["read_file", "reading"], + ["list_dir", "reading"], + ["glob", "reading"], + ["grep", "reading"], + ["edit_file", "editing"], + ["write_file", "editing"], + ["run_command", "command"], + ["web_search", "searching"], + ["computer_use", "computer"], + ["form_fill", "computer"], + ["inspect_image", "photo"], + ["subagent", "helper"], + ["bot_memory", "remembering"], + ["routines", "routine"], + ["routine_notes", "routine"], + ["ask_user_question", "waiting"], +]); + +const PHASE_IDS: ReadonlySet = new Set(BOT_ACTIVITY_PHASES); + +export function isBotActivityPhase(value: unknown): value is BotActivityPhase { + return typeof value === "string" && PHASE_IDS.has(value); +} + +/** The longest connection label a status line shows; the Remote wire uses the same bound (§11). */ +export const BOT_APP_LABEL_CHARS = 40; + +// `mcpAgentToolName` (main/services/mcp-tool-identity.ts) mints connection +// tools as `___<12 hex>`, with other characters as `_`. +const MCP_AGENT_TOOL = /^(.+?)__.+_[0-9a-f]{12}$/u; + +/** The connection label of an MCP or Composio tool, or undefined for Aiden's own tools. */ +export function botToolApp(toolName: string): string | undefined { + const match = MCP_AGENT_TOOL.exec(toolName); + const label = match?.[1]?.replace(/_+/gu, " ").trim(); + if (!label) return undefined; + const points = [...label]; + return points.length > BOT_APP_LABEL_CHARS ? points.slice(0, BOT_APP_LABEL_CHARS).join("").trimEnd() : label; +} + +/** The phase an active tool puts its Bot in (§5.1). */ +export function botToolPhase(toolName: string, app?: string): BotToolPhase { + return TOOL_PHASES.get(toolName) ?? (app ? "app" : "working"); +} + +/** The status line's word for a phase; `app` fills "Using {app}". */ +export function botPhaseWord(phase: BotActivityPhase, app?: string): string { + return phase === "app" && app ? `Using ${app}` : PHASES[phase].word; +} + +/** Phases that keep their own word under Always "Thinking": they change what the person should do. */ +const KEEPS_ITS_WORD: ReadonlySet = new Set(["waiting", "stopping", "reconnecting"]); + +export interface BotActivityDisplay { + phase: BotActivityPhase; + word: string; + mark: ActivityMark; +} + +/** What the line shows for a phase id from any client: unknown ids read as `working` (§5.2). */ +export function botActivityDisplay(phase: string, wording: BotChatActivityWording, app?: string): BotActivityDisplay { + const known: BotActivityPhase = isBotActivityPhase(phase) ? phase : "working"; + const shown: BotActivityPhase = wording === "thinking" && !KEEPS_ITS_WORD.has(known) ? "thinking" : known; + return { phase: shown, word: botPhaseWord(shown, app), mark: PHASES[shown].mark }; +} + +interface StepPhrases { + one: string; + many(count: number): string; + infinitive: string; +} + +function stepPhrases(kind: BotToolPhase, app?: string): StepPhrases { + const name = app ?? "an app"; + switch (kind) { + case "reading": + return { one: "Read 1 file", many: (n) => `Read ${n} files`, infinitive: "read a file" }; + case "editing": + return { one: "Edited 1 file", many: (n) => `Edited ${n} files`, infinitive: "edit a file" }; + case "command": + return { one: "Ran a command", many: (n) => `Ran ${n} commands`, infinitive: "run a command" }; + case "searching": + return { one: "Searched the web", many: (n) => `Searched the web ${n} times`, infinitive: "search the web" }; + case "photo": + return { one: "Looked at your photo", many: (n) => `Looked at ${n} photos`, infinitive: "look at your photo" }; + case "computer": + return { one: "Used your Mac", many: (n) => `Used your Mac ${n} times`, infinitive: "use your Mac" }; + case "helper": + return { one: "Asked a helper", many: (n) => `Asked ${n} helpers`, infinitive: "ask a helper" }; + case "remembering": + return { one: "Updated its memory", many: () => "Updated its memory", infinitive: "update its memory" }; + case "routine": + return { one: "Set up a routine", many: (n) => `Worked on ${n} routines`, infinitive: "set up a routine" }; + case "app": + return { one: `Used ${name}`, many: (n) => `Used ${name} ${n} times`, infinitive: `use ${name}` }; + case "waiting": + return { one: "Asked you a question", many: (n) => `Asked you ${n} questions`, infinitive: "ask you a question" }; + case "working": + return { one: "Used a tool", many: (n) => `Used ${n} tools`, infinitive: "use a tool" }; + } +} + +/** A finished step, past tense: "Read 1 file", "Read 6 files", "Used Notion". */ +export function botStepPhrase(kind: BotToolPhase, count: number, app?: string): string { + const phrases = stepPhrases(kind, app); + return count <= 1 ? phrases.one : phrases.many(count); +} + +/** The bare verb phrase for "Couldn’t …" and "Blocked: …". */ +export function botStepInfinitive(kind: BotToolPhase, app?: string): string { + return stepPhrases(kind, app).infinitive; +} + +export const BOT_ELAPSED_AFTER_MS = 20_000; +export const BOT_STILL_GOING_AFTER_MS = 120_000; + +/** "18s", "1m 12s", "2m", "1h 2m". Never less than one second. */ +export function botDurationLabel(ms: number): string { + const seconds = Math.max(1, Math.floor(ms / 1_000)); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + if (minutes < 60) return rest ? `${minutes}m ${rest}s` : `${minutes}m`; + const hours = Math.floor(minutes / 60); + const remainder = minutes % 60; + return remainder ? `${hours}h ${remainder}m` : `${hours}h`; +} + +/** The status line's elapsed time, once a turn has run for 20 seconds. */ +export function botElapsedLabel(startedAt: number, now: number): string | null { + const elapsed = now - startedAt; + return Number.isFinite(elapsed) && elapsed >= BOT_ELAPSED_AFTER_MS ? botDurationLabel(elapsed) : null; +} + +/** Screen readers hear a phase change at most this often (§14). */ +export const BOT_ANNOUNCE_GAP_MS = 2_000; + +export interface BotAnnouncement { + text: string; + at: number; +} + +/** + * What to announce now. A change inside the gap keeps the current text and + * says when to try again; the newest text wins once the gap has passed. + */ +export function nextBotAnnouncement( + current: BotAnnouncement | null, + text: string, + now: number, + gapMs = BOT_ANNOUNCE_GAP_MS, +): { shown: BotAnnouncement; retryInMs?: number } { + if (current !== null && current.text === text) return { shown: current }; + if (current === null || now - current.at >= gapMs) return { shown: { text, at: now } }; + return { shown: current, retryInMs: gapMs - (now - current.at) }; +} + +/** + * The tool slot a status line follows. Slots are in call order and parallel + * calls start in that order, so the last running one started most recently; + * with none running, the first one about to start. + */ +export function pickActiveToolSlot(slots: readonly T[] | undefined): T | undefined { + if (!slots) return undefined; + for (let index = slots.length - 1; index >= 0; index -= 1) { + if (slots[index]!.status === "running") return slots[index]; + } + return slots.find((slot) => slot.status === "pending"); +} +``` + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npx tsx --test renderer/shared/bot-activity.test.ts` +Expected: PASS (8 tests). + +- [ ] **Step 5: Register the test** + +Append ` renderer/shared/bot-activity.test.ts` to the end of the `test:bots` command string in `package.json`. In `scripts/ci-test-registry.json`, add `"renderer/shared/bot-activity.test.ts",` directly after `"renderer/shared/bot-capabilities.test.ts",`. + +Run: `npm run test:ci-policy` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add renderer/shared/bot-activity.ts renderer/shared/bot-activity.test.ts package.json scripts/ci-test-registry.json +git commit -m "Bots: shared status words and tool phase classifier" +``` + +--- + +### Task 2: Transcript tool calls and results carry kind, label, detail and status + +**Files:** +- Create: `main/services/bot-runtime/bot-activity-detail.ts` +- Test: `main/services/bot-runtime/bot-activity-detail.test.ts` +- Modify: `renderer/shared/bot-live.ts` (types), `main/services/bot-runtime/live-projection.ts` (`projectBotTranscript`), `main/services/bot-runtime/live-projection.test.ts` +- Modify fixtures: `renderer/main/bots/bot-transcript-rows.test.ts` (`step`, `result`), `renderer/main/bots/bot-chat-pane.test.tsx` (the inline calendar call at about line 305 and `toolStep` at about line 478) +- Modify: `package.json` (`test:bot-runtime`), `scripts/ci-test-registry.json` + +**Interfaces:** +- Consumes: `botToolApp`, `botToolPhase`, `botStepPhrase`, `BotToolPhase` (Task 1); `sanitizeDiagnosticText` from `main/services/diagnostics-contract.ts`. +- Produces: + - `BOT_STEP_DETAIL_CHARS = 80`; `botStepDescriptor(toolName: string, args: unknown): BotStepDescriptor` where `interface BotStepDescriptor { kind: BotToolPhase; label: string; detail?: string; app?: string }` (label is `botStepPhrase(kind, 1, app)`). + - `BotTranscriptToolCall` becomes `{ id: string; name: string; kind: BotToolPhase; label: string; detail?: string; app?: string }`. + - `type BotToolResultStatus = "ok" | "failed" | "blocked"`. The `tool_result` entry gains `status: BotToolResultStatus; durationMs?: number; at?: number` and keeps `isError`. + +- [ ] **Step 1: Write the failing tests** + +```ts +// main/services/bot-runtime/bot-activity-detail.test.ts +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mcpAgentToolName } from "../mcp-tool-identity.js"; +import { BOT_STEP_DETAIL_CHARS, botStepDescriptor } from "./bot-activity-detail.js"; + +test("a file step names only the file's base name", () => { + assert.deepEqual(botStepDescriptor("read_file", { path: "/Users/sam/Lists/grocery-list.md" }), { + kind: "reading", + label: "Read 1 file", + detail: "grocery-list.md", + }); + assert.deepEqual(botStepDescriptor("edit_file", { path: "notes\\week.md" }), { + kind: "editing", + label: "Edited 1 file", + detail: "week.md", + }); + assert.equal(botStepDescriptor("grep", { pattern: "tofu", path: "recipes" }).detail, "tofu"); +}); + +test("a command step is bounded and never shows a secret or an absolute path", () => { + const secret = botStepDescriptor("run_command", { + command: "export OPENAI_API_KEY=sk-live1234567890abcdef && ls /Users/sam/Private", + }); + assert.equal(secret.kind, "command"); + assert.equal(secret.label, "Ran a command"); + assert.ok(secret.detail); + assert.doesNotMatch(secret.detail, /sk-live/u); + assert.doesNotMatch(secret.detail, /\/Users\/sam/u); + const long = botStepDescriptor("run_command", { command: "echo hi && ".repeat(20) }).detail ?? ""; + assert.ok([...long].length <= BOT_STEP_DETAIL_CHARS); + assert.ok(long.endsWith("…")); + // The model's own description is preferred over the raw command. + assert.equal(botStepDescriptor("run_command", { command: "ls -la", description: "List the folder" }).detail, "List the folder"); +}); + +test("a search step shows its query; a connection step names the app and shows no arguments", () => { + assert.deepEqual(botStepDescriptor("web_search", { query: "lisbon trains" }), { + kind: "searching", + label: "Searched the web", + detail: "lisbon trains", + }); + const notion = mcpAgentToolName({ id: "srv-1", name: "Notion" }, "search_pages"); + assert.deepEqual(botStepDescriptor(notion, { query: "private plans" }), { + kind: "app", + label: "Used Notion", + app: "Notion", + }); + assert.deepEqual(botStepDescriptor("ask_user_question", {}), { kind: "waiting", label: "Asked you a question" }); + assert.deepEqual(botStepDescriptor("read_file", "not an object"), { kind: "reading", label: "Read 1 file" }); +}); +``` + +Add to `main/services/bot-runtime/live-projection.test.ts`. Add `countingTool` to the import from `./test-support/fixtures.js`. Below the existing "files the Bot wrote…" test: + +```ts +test("tool calls carry a kind, a past-tense label and a short safe detail; results say ok, failed or blocked", () => { + const result = (id: number, toolCallId: string, toolName: string, timestamp: number, code?: string) => ({ + id, + kind: "pi.tool-result", + data: { diagnostics: code ? [{ severity: "error", code, message: code }] : [] }, + model: [{ role: "toolResult", toolCallId, toolName, isError: code !== undefined, content: [], timestamp }], + }); + const entries = projectBotTranscript([ + { id: 1, kind: "pi.user", model: [{ role: "user", content: [{ type: "text", text: "Plan dinners" }], timestamp: 900 }] }, + { + id: 2, + kind: "pi.assistant", + model: [{ + role: "assistant", + stopReason: "toolUse", + timestamp: 1_000, + content: [ + { type: "toolCall", id: "c1", name: "read_file", arguments: { path: "/Users/sam/lists/grocery-list.md" } }, + { type: "toolCall", id: "c2", name: "run_command", arguments: { command: "cat /Users/sam/.ssh/id_rsa" } }, + { type: "toolCall", id: "c3", name: "web_search", arguments: { query: "lisbon trains" } }, + ], + }], + }, + result(3, "c1", "read_file", 1_400), + result(4, "c2", "run_command", 1_050, "blocked"), + result(5, "c3", "web_search", 2_000, "tool_error"), + ] as never); + const assistant = entries.find((entry) => entry.type === "assistant"); + assert.ok(assistant?.type === "assistant"); + assert.deepEqual(assistant.toolCalls[0], { id: "c1", name: "read_file", kind: "reading", label: "Read 1 file", detail: "grocery-list.md" }); + assert.equal(assistant.toolCalls[1]!.kind, "command"); + assert.doesNotMatch(assistant.toolCalls[1]!.detail ?? "", /\/Users|id_rsa/u); + assert.deepEqual(assistant.toolCalls[2], { id: "c3", name: "web_search", kind: "searching", label: "Searched the web", detail: "lisbon trains" }); + const results = entries.flatMap((entry) => + entry.type === "tool_result" ? [[entry.toolCallId, entry.status, entry.durationMs, entry.at]] : [], + ); + assert.deepEqual(results, [ + ["c1", "ok", 400, 1_400], + ["c2", "blocked", 50, 1_050], + ["c3", "failed", 1_000, 2_000], + ]); +}); + +test("a tool the Bot's access refused is blocked, a tool that broke is failed, and neither looks like the other", async () => { + const shell = countingTool("run_command"); + const search = countingTool("web_search", async () => { + throw new Error("The search service is down."); + }); + const fauxModels = createFauxModels([ + fauxAssistantMessage([fauxToolCall("run_command", { text: "ls" }), fauxToolCall("web_search", { text: "trains" })], { + stopReason: "toolUse", + }), + fauxAssistantMessage("I couldn't do that one."), + ]); + const live = await start(fauxModels, { + service: { + extension: recordingDeps({ + tools: [ + { tool: shell, replay: "unsafe" }, + { tool: search, replay: "unsafe" }, + ], + policy: (name) => (name === "run_command" ? { allowed: false, reason: "The shell is off for this Bot." } : { allowed: true }), + }), + }, + }); + try { + const sent = await live.service.send("bot:a", { text: "go", requestId: "desk-1" }); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + const view = await (await live.service.conversation("bot:a")).context(ctx); + const statuses = new Map( + projectBotTranscript(view.entries).flatMap((entry) => (entry.type === "tool_result" ? [[entry.toolName, entry]] : [])), + ); + assert.equal(statuses.get("run_command")?.status, "blocked"); + assert.equal(statuses.get("web_search")?.status, "failed"); + assert.deepEqual(shell.executions, [], "a refused tool never runs"); + for (const entry of statuses.values()) { + assert.ok(typeof entry.durationMs === "number" && entry.durationMs >= 0); + } + } finally { + await live.close(); + } +}); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test main/services/bot-runtime/bot-activity-detail.test.ts main/services/bot-runtime/live-projection.test.ts` +Expected: FAIL. `Cannot find module './bot-activity-detail.js'`, then (once the module exists) `toolCalls[0]` has only `{ id, name }` and `status` is undefined. + +- [ ] **Step 3: Write the descriptor** + +```ts +// main/services/bot-runtime/bot-activity-detail.ts +// One Bot tool call, as the chat may show it (spec §6 "Projection changes"): +// its phase kind, a past-tense label and a short, safe detail. The detail is +// built here in main and only from allow-listed arguments: a file's base name, +// a search query or pattern, or a command (the model's own description when it +// gave one). Text passes the diagnostic redactor before it is cut, so a secret +// is never split past it. Arguments of connection tools are never shown. + +import { + botStepPhrase, + botToolApp, + botToolPhase, + type BotToolPhase, +} from "../../../renderer/shared/bot-activity.js"; +import { sanitizeDiagnosticText } from "../diagnostics-contract.js"; + +export const BOT_STEP_DETAIL_CHARS = 80; +/** Longest argument read before redaction; enough for any useful first 80 characters. */ +const RAW_DETAIL_CHARS = 4_000; + +export interface BotStepDescriptor { + kind: BotToolPhase; + label: string; + detail?: string; + app?: string; +} + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; +} + +function stringOf(value: unknown): string | undefined { + return typeof value === "string" && value.trim() ? value : undefined; +} + +function baseName(value: unknown): string | undefined { + const text = stringOf(value); + if (!text) return undefined; + const parts = text.replace(/\\/gu, "/").split("/").filter(Boolean); + return parts[parts.length - 1]; +} + +function bounded(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const clean = sanitizeDiagnosticText([...value].slice(0, RAW_DETAIL_CHARS).join(""), RAW_DETAIL_CHARS); + if (!clean) return undefined; + const points = [...clean]; + return points.length > BOT_STEP_DETAIL_CHARS + ? `${points.slice(0, BOT_STEP_DETAIL_CHARS - 1).join("").trimEnd()}…` + : clean; +} + +function rawDetail(toolName: string, kind: BotToolPhase, args: Record): string | undefined { + switch (kind) { + case "reading": + case "editing": + return toolName === "glob" || toolName === "grep" + ? stringOf(args.pattern) + : baseName(args.path ?? args.filePath ?? args.directory); + case "command": + return stringOf(args.description) ?? stringOf(args.command); + case "searching": + return stringOf(args.query); + default: + return undefined; + } +} + +export function botStepDescriptor(toolName: string, args: unknown): BotStepDescriptor { + const app = botToolApp(toolName); + const kind = botToolPhase(toolName, app); + const detail = bounded(rawDetail(toolName, kind, record(args))); + return { + kind, + label: botStepPhrase(kind, 1, app), + ...(detail ? { detail } : {}), + ...(app ? { app } : {}), + }; +} +``` + +- [ ] **Step 4: Extend the shared types** + +In `renderer/shared/bot-live.ts`, add the import and replace `BotTranscriptToolCall`: + +```ts +import type { BotToolPhase } from "./bot-activity.js"; +``` + +```ts +export interface BotTranscriptToolCall { + id: string; + name: string; + /** The phase this call puts its Bot in (`botToolPhase`). */ + kind: BotToolPhase; + /** Past tense, for recaps: "Read 1 file", "Used Notion". */ + label: string; + /** A short, safe object of the action, built and redacted in main. */ + detail?: string; + /** The connection's display label, for connection tools. */ + app?: string; +} + +/** How a tool call ended. `blocked`: the Bot's access or the person refused it before it ran. */ +export type BotToolResultStatus = "ok" | "failed" | "blocked"; +``` + +Replace the `tool_result` member of `BotTranscriptEntry`: + +```ts + | { + id: string; + type: "tool_result"; + toolCallId: string; + toolName: string; + isError: boolean; + status: BotToolResultStatus; + /** From the answer that made the call to its result. */ + durationMs?: number; + at?: number; + } +``` + +- [ ] **Step 5: Project them in main** + +In `main/services/bot-runtime/live-projection.ts`: + +1. Import the descriptor and the status type: + +```ts +import { botStepDescriptor } from "./bot-activity-detail.js"; +``` + +and add `type BotToolResultStatus,` to the existing `../../../renderer/shared/bot-live.js` import. + +2. Add above `projectBotTranscript`: + +```ts +/** `blocked` when Pi's `beforeTool` refused the call (policy, a denied approval, ingress); any other error failed. */ +function toolResultStatus(record: EntryRecord, isError: boolean): BotToolResultStatus { + if (!isError) return "ok"; + const diagnostics = (record.data as { diagnostics?: unknown } | undefined)?.diagnostics; + const blocked = Array.isArray(diagnostics) && diagnostics.some((item) => (item as { code?: unknown } | null)?.code === "blocked"); + return blocked ? "blocked" : "failed"; +} +``` + +3. In `projectBotTranscript`, next to `homeFileCalls`, add: + +```ts + /** When the answer that made each call was written, for its duration. */ + const callStartedAt = new Map(); +``` + +4. In the `pi.assistant` branch, replace + +```ts + const toolCalls = calls.map((call) => ({ id: call.id, name: call.name })); +``` + +with + +```ts + for (const call of calls) { + if (typeof message.timestamp === "number") callStartedAt.set(call.id, message.timestamp); + } + const toolCalls = calls.map((call) => ({ id: call.id, name: call.name, ...botStepDescriptor(call.name, call.arguments) })); +``` + +5. In the `pi.tool-result` branch, replace the `mapped.push({ entry: { id, type: "tool_result", … } })` block with: + +```ts + const startedAt = callStartedAt.get(message.toolCallId); + const at = typeof message.timestamp === "number" ? message.timestamp : undefined; + mapped.push({ + entry: { + id, + type: "tool_result", + toolCallId: message.toolCallId, + toolName: message.toolName, + isError: message.isError, + status: toolResultStatus(record, message.isError), + ...(startedAt !== undefined && at !== undefined ? { durationMs: Math.max(0, at - startedAt) } : {}), + ...(at === undefined ? {} : { at }), + }, + turn, + }); +``` + +`textOf` already drops thinking parts. Do not change it. + +- [ ] **Step 6: Update the renderer fixtures for the new required fields** + +`renderer/main/bots/bot-transcript-rows.test.ts`: + +```ts +const step = (id: string, text: string): BotTranscriptEntry => ({ + id, + type: "assistant", + text, + toolCalls: [{ id: `${id}-call`, name: "web_search", kind: "searching", label: "Searched the web" }], + stopReason: "toolUse", +}); +``` + +```ts +const result = (id: string): BotTranscriptEntry => ({ + id, + type: "tool_result", + toolCallId: `${id}-call`, + toolName: "web_search", + isError: false, + status: "ok", +}); +``` + +`renderer/main/bots/bot-chat-pane.test.tsx`: in the "text before a tool call…" test, use `toolCalls: [{ id: "t1", name: "calendar", kind: "working", label: "Used a tool" }]`, and add `status: "ok"` to its `tool_result`. In `toolStep`, use `toolCalls: [{ id: \`${id}-call\`, name: "web_search", kind: "searching", label: "Searched the web" }]`. + +- [ ] **Step 7: Run the tests to verify they pass** + +Run: `npx tsx --test main/services/bot-runtime/bot-activity-detail.test.ts main/services/bot-runtime/live-projection.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: PASS. + +Run: `npx tsx --test main/services/aiden-remote-bot-session.test.ts` +Expected: PASS. Remote picks wire fields explicitly, so its entries are unchanged. + +- [ ] **Step 8: Register and type-check** + +Append ` main/services/bot-runtime/bot-activity-detail.test.ts` to the end of `test:bot-runtime` in `package.json`. In `scripts/ci-test-registry.json`, add `"main/services/bot-runtime/bot-activity-detail.test.ts",` directly after `"main/services/bot-runtime/live-projection.test.ts",`. + +Run: `npm run test:ci-policy && npm run type-check` +Expected: PASS. + +- [ ] **Step 9: Commit** + +```bash +git add main/services/bot-runtime/bot-activity-detail.ts main/services/bot-runtime/bot-activity-detail.test.ts main/services/bot-runtime/live-projection.ts main/services/bot-runtime/live-projection.test.ts renderer/shared/bot-live.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx package.json scripts/ci-test-registry.json +git commit -m "Bots: tool steps carry kind, label, safe detail, and ok/failed/blocked status" +``` + +--- + +### Task 3: Live activity in the projection + +**Files:** +- Modify: `renderer/shared/bot-live.ts`, `main/services/bot-runtime/live-projection.ts`, `main/services/bot-runtime/bot-session-main.ts`, `main/handlers/bots.ts` +- Test: `main/services/bot-runtime/live-projection.test.ts`, `main/handlers/bot-live.test.ts` (fake projection), `renderer/main/bots/bot-chat-pane.test.tsx` (snapshot helper) + +**Interfaces:** +- Consumes: `pickActiveToolSlot`, `botPhaseWord`, `BotActivityPhase` (Task 1); `botStepDescriptor` (Task 2). +- Produces: + - `interface BotLiveActivityStep { kind: BotToolPhase; label: string; detail?: string }` (label is the present-tense phase word, "Reading"). + - `interface BotLiveActivity { phase: BotActivityPhase; app?: string; startedAt: number; step?: BotLiveActivityStep }`. + - `BotLiveSnapshot.activity: BotLiveActivity | null`; event `{ type: "activity"; activity: BotLiveActivity | null }`. + - `export function liveBotActivity(input: BotLiveActivityInput): BotLiveActivity | null` with `interface BotLiveActivityInput { entries: readonly EntryRecord[]; docs: Readonly>; waiting: boolean; stopping: boolean; resuming: boolean; startedAt: number }`. It returns null when `pi.live.run` is absent. + - `BotLiveProjectionDeps` gains `approvalPending?(botId): boolean` and `now?(): number`. + - `BotLiveProjection` gains `notifyStopping(botId): void`, `notifyResuming(botId): void`, `refreshActivity(botId): Promise`. + +- [ ] **Step 1: Write the failing tests** + +In `live-projection.test.ts`, add `liveBotActivity` to the `./live-projection.js` import and `fauxText, fauxThinking` to the faux import. Then add: + +```ts +function observedPhases(events: readonly BotLiveEvent[]): Array { + const phases: Array = []; + for (const event of events) { + const activity = event.type === "activity" ? event.activity : event.type === "snapshot" ? event.snapshot.activity : undefined; + if (activity === undefined) continue; + const phase = activity?.phase ?? null; + if (phases[phases.length - 1] !== phase) phases.push(phase); + } + return phases; +} + +/** Every phase seen appears in `allowed`, in that order (frames may coalesce, so some can be skipped). */ +function inOrder(phases: ReadonlyArray, allowed: readonly string[]): boolean { + let at = 0; + for (const phase of phases) { + if (phase === null) continue; + const found = allowed.indexOf(phase, at); + if (found === -1) return false; + at = found; + } + return true; +} + +// Test 1 +test("a reply's activity follows the work: getting ready, reading while a file tool runs, writing, then nothing", async () => { + let release!: () => void; + const released = new Promise((resolve) => (release = resolve)); + const reader = countingTool("read_file", async () => { + await released; + return "eggs, milk"; + }); + const fauxModels = createFauxModels( + [ + fauxAssistantMessage([fauxToolCall("read_file", { text: "groceries" })], { stopReason: "toolUse" }), + fauxAssistantMessage("word ".repeat(60)), + ], + { tokensPerSecond: 40 }, + ); + const live = await start(fauxModels, { + service: { extension: recordingDeps({ tools: [{ tool: reader, replay: "safe" }] }) }, + }); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + assert.equal(snapshot.activity, null); + const sent = await live.service.send("bot:a", { text: "What's on my list?", requestId: "desk-1" }); + await waitFor(() => tape.view?.activity?.phase === "reading", { what: "the reading phase" }); + assert.deepEqual(tape.view?.activity?.step, { kind: "reading", label: "Reading" }); + assert.ok((tape.view?.activity?.startedAt ?? 0) > 0); + release(); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the line to clear" }); + const phases = observedPhases(tape.events); + assert.ok(inOrder(phases, ["preparing", "thinking", "reading", "thinking", "writing"]), phases.join(" → ")); + assert.ok(phases.includes("writing"), phases.join(" → ")); + assert.equal(phases[phases.length - 1], null); + unsubscribe(); + } finally { + await live.close(); + } +}); + +// Test 2 +test("thinking text is never projected, in the transcript or the live activity", () => { + const entries = [ + { id: 1, kind: "pi.user", model: [{ role: "user", content: [{ type: "text", text: "Hi" }], timestamp: 1 }] }, + { + id: 2, + kind: "pi.assistant", + model: [{ role: "assistant", stopReason: "stop", timestamp: 2, content: [fauxThinking("SECRET-PLAN"), fauxText("Done.")] }], + }, + ]; + assert.doesNotMatch(JSON.stringify(projectBotTranscript(entries as never)), /SECRET-PLAN/u); + const activity = liveBotActivity({ + entries: entries as never, + docs: { "pi.live": { run: { taskId: 1, inputs: [1] }, generation: { attempt: 1, message: { content: [fauxThinking("SECRET-PLAN")] } } } }, + waiting: false, + stopping: false, + resuming: false, + startedAt: 5, + }); + assert.deepEqual(activity, { phase: "thinking", startedAt: 5 }); +}); + +// Test 3 +test("the live phase reads stop, a waiting card, compaction, the newest running tool, and resume, in that order", () => { + const user = { id: 1, kind: "pi.user", model: [{ role: "user", content: "go", timestamp: 1 }] }; + const calling = { + id: 2, + kind: "pi.assistant", + model: [{ + role: "assistant", + stopReason: "toolUse", + timestamp: 2, + content: [ + { type: "toolCall", id: "c1", name: "read_file", arguments: { path: "lists/a.md" } }, + { type: "toolCall", id: "c2", name: "web_search", arguments: { query: "tofu bowls" } }, + ], + }], + }; + const tools = [ + { callId: "c1", name: "read_file", status: "running" }, + { callId: "c2", name: "web_search", status: "running" }, + ]; + const base = { entries: [user, calling] as never, waiting: false, stopping: false, resuming: false, startedAt: 9 }; + const docs = (live: Record) => ({ "pi.live": { run: { taskId: 1, inputs: [1] }, ...live } }); + assert.equal(liveBotActivity({ ...base, docs: {} }), null, "no run, no line"); + assert.deepEqual(liveBotActivity({ ...base, docs: docs({ tools }) }), { + phase: "searching", + startedAt: 9, + step: { kind: "searching", label: "Searching the web", detail: "tofu bowls" }, + }); + assert.equal(liveBotActivity({ ...base, docs: docs({ compactions: [{ blocking: true }], tools }) })?.phase, "tidying"); + assert.equal(liveBotActivity({ ...base, waiting: true, docs: docs({ tools }) })?.phase, "waiting"); + assert.equal(liveBotActivity({ ...base, waiting: true, stopping: true, docs: docs({ tools }) })?.phase, "stopping"); + assert.equal(liveBotActivity({ ...base, entries: [user] as never, docs: docs({}) })?.phase, "preparing"); + assert.equal(liveBotActivity({ ...base, docs: docs({}) })?.phase, "thinking"); + assert.equal(liveBotActivity({ ...base, resuming: true, docs: docs({}) })?.phase, "resuming"); + assert.equal( + liveBotActivity({ ...base, docs: docs({ generation: { attempt: 1, message: { content: [{ type: "text", text: "Here" }] } } }) })?.phase, + "writing", + ); +}); + +// Test 4 (Review Focus 5) +test("Stop pressed while nothing runs is ignored, so the next reply never starts at Stopping", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("word ".repeat(40))], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + live.projection.notifyStopping("bot:a"); + const sent = await live.service.send("bot:a", { text: "hi", requestId: "desk-1" }); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the reply to land" }); + assert.equal(observedPhases(tape.events).includes("stopping"), false); + unsubscribe(); + } finally { + await live.close(); + } +}); +``` + +Extend two existing tests: + +- "subscribing mid-stream returns a snapshot that already has the partial reply": after the `partial` assertion add `assert.equal(snapshot.activity?.phase, "writing");`. +- "Stop ends the running reply…": replace `const state = await live.service.stop("bot:a");` with + +```ts + live.projection.notifyStopping("bot:a"); + const state = await live.service.stop("bot:a"); +``` + + and after the `waitFor` add: + +```ts + const phases = observedPhases(tape.events); + assert.ok(phases.includes("stopping"), phases.join(" → ")); + assert.equal(phases[phases.length - 1], null); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test main/services/bot-runtime/live-projection.test.ts` +Expected: FAIL. `liveBotActivity` is not exported, `notifyStopping` is not a function, and `snapshot.activity` is undefined. + +- [ ] **Step 3: Extend the live types** + +In `renderer/shared/bot-live.ts`, extend the Task 2 import to `import type { BotActivityPhase, BotToolPhase } from "./bot-activity.js";` and add: + +```ts +/** The step behind the current phase, for the Mac's hover peek and Detailed steps. */ +export interface BotLiveActivityStep { + kind: BotToolPhase; + /** Present tense, the phase word: "Reading", "Using Notion". */ + label: string; + detail?: string; +} + +/** What a Bot in a running turn is doing now (spec §5). Null when no turn runs. */ +export interface BotLiveActivity { + phase: BotActivityPhase; + /** The connection's label, for `app`. */ + app?: string; + /** When the turn started, for elapsed time. */ + startedAt: number; + step?: BotLiveActivityStep; +} +``` + +Add `activity: BotLiveActivity | null;` to `BotLiveSnapshot` (after `question`). Add `| { type: "activity"; activity: BotLiveActivity | null }` to `BotLiveEventBody`. In `applyBotLiveEvent`'s switch, add: + +```ts + case "activity": + return { ...snapshot, seq: event.seq, activity: event.activity }; +``` + +- [ ] **Step 4: Derive the activity in the projection** + +In `main/services/bot-runtime/live-projection.ts`: + +1. Imports: add `pickActiveToolSlot, botPhaseWord, type BotActivityPhase` from `../../../renderer/shared/bot-activity.js`, and `type BotLiveActivity` to the `bot-live.js` import. + +2. Below `liveRunActive`, add: + +```ts +interface LiveDocView { + run?: unknown; + generation?: { message?: { content?: unknown } }; + tools?: Array<{ callId: string; name: string; status: string }>; + compactions?: Array<{ blocking?: boolean }>; +} + +export interface BotLiveActivityInput { + entries: readonly EntryRecord[]; + docs: Readonly>; + /** An approval or A–E question is open. */ + waiting: boolean; + /** The person pressed Stop and the run has not ended. */ + stopping: boolean; + /** This run is a Resume and has not moved on yet. */ + resuming: boolean; + startedAt: number; +} + +/** Whether the newest input already has an assistant entry after it. */ +function inputAnswered(entries: readonly EntryRecord[]): boolean { + for (let index = entries.length - 1; index >= 0; index -= 1) { + const kind = entries[index]!.kind; + if (kind === "pi.assistant") return true; + if (kind === "pi.user") return false; + } + return false; +} + +/** The arguments of tool call `callId`, from the answer that made it. */ +function callArguments(entries: readonly EntryRecord[], callId: string): unknown { + for (let index = entries.length - 1; index >= 0; index -= 1) { + const message = firstMessage(entries[index]!); + if (message?.role !== "assistant") continue; + const call = message.content.find((part): part is ToolCall => part.type === "toolCall" && part.id === callId); + if (call) return call.arguments; + } + return undefined; +} + +/** + * The phase of a run from `pi.live` (spec §5): Stop, then an open card, + * then compaction inside the turn, then the newest running tool (§5.2), then + * the reply's text, then Resume, then thinking (or "getting ready" before + * the model produced anything). Thinking content is read only to know the + * model is generating; its text is never copied. + */ +export function liveBotActivity(input: BotLiveActivityInput): BotLiveActivity | null { + const live = input.docs["pi.live"] as LiveDocView | undefined; + if (live?.run === undefined) return null; + const at = (phase: BotActivityPhase): BotLiveActivity => ({ phase, startedAt: input.startedAt }); + if (input.stopping) return at("stopping"); + if (input.waiting) return at("waiting"); + if (live.compactions?.some((compaction) => compaction.blocking === true)) return at("tidying"); + const slot = pickActiveToolSlot(live.tools); + if (slot) { + const step = botStepDescriptor(slot.name, callArguments(input.entries, slot.callId)); + return { + phase: step.kind, + startedAt: input.startedAt, + ...(step.app ? { app: step.app } : {}), + step: { kind: step.kind, label: botPhaseWord(step.kind, step.app), ...(step.detail ? { detail: step.detail } : {}) }, + }; + } + const content = live.generation?.message?.content; + if (Array.isArray(content) && textOf(content as TextContent[]).trim()) return at("writing"); + if (input.resuming) return at("resuming"); + if (Array.isArray(content) && content.length > 0) return at("thinking"); + return at(inputAnswered(input.entries) ? "thinking" : "preparing"); +} +``` + +3. Extend `BotLiveProjectionDeps`: + +```ts + /** Whether a tool approval is waiting on the person. */ + approvalPending?(botId: string): boolean; + /** Clock for `startedAt`; defaults to `Date.now`. */ + now?(): number; +``` + +4. Extend `BotLiveProjection`: + +```ts + /** The person pressed Stop: the running turn reads "Stopping" until it ends. Ignored when nothing runs. */ + notifyStopping(botId: string): void; + /** The next run starts from Resume: it reads "Picking up where it left off" until it moves on. */ + notifyResuming(botId: string): void; + /** An approval appeared or settled: re-derive the activity. */ + refreshActivity(botId: string): Promise; +``` + +5. Extend `Feed`: + +```ts + activity: BotLiveActivity | null; + /** When the current running turn started. */ + startedAt: number; + stopping: boolean; + resuming: boolean; + /** The newest frame, so approvals, questions and Stop can re-derive the activity. */ + frame: { entries: readonly EntryRecord[]; docs: Readonly> }; +``` + +6. Inside `createBotLiveProjection`, below `const newEpoch = …`: + +```ts + const now = deps.now ?? Date.now; + /** Bots whose next run is a Resume. */ + const resumingBots = new Set(); +``` + +Add `activity: feed.activity,` to the object `snapshotOf` returns. Below `emitSnapshot`, add: + +```ts + function waitingOn(botId: string): boolean { + return (deps.question?.(botId) ?? null) !== null || deps.approvalPending?.(botId) === true; + } + + /** Null unless the session is running: a paused Bot keeps `pi.live.run` but is not working. */ + function computeActivity(feed: Feed): BotLiveActivity | null { + if (feed.state.kind !== "running") return null; + return ( + liveBotActivity({ + ...feed.frame, + waiting: waitingOn(feed.botId), + stopping: feed.stopping, + resuming: feed.resuming, + startedAt: feed.startedAt, + }) ?? { phase: "preparing", startedAt: feed.startedAt } + ); + } + + function updateActivity(feed: Feed): void { + const activity = computeActivity(feed); + if (activity && activity.phase !== "resuming") feed.resuming = false; + if (JSON.stringify(activity) === JSON.stringify(feed.activity)) return; + feed.activity = activity; + emit(feed, { type: "activity", activity }); + } + + function startRun(feed: Feed): void { + feed.startedAt = now(); + feed.stopping = false; + feed.resuming = resumingBots.delete(feed.botId); + } +``` + +7. Replace `onFrame` and `setState`: + +```ts + async function onFrame(feed: Feed, entries: readonly EntryRecord[], docs: Readonly>) { + if (feed.ended) return; + feed.frame = { entries, docs }; + applyEntries(feed, await resolveCards(feed.botId, projectBotTranscript(entries))); + const partial = livePartialText(docs); + if (partial !== feed.partial) { + feed.partial = partial; + emit(feed, { type: "partial", text: partial }); + } + const runActive = liveRunActive(docs); + if (runActive === feed.runActive) { + updateActivity(feed); + return; + } + feed.runActive = runActive; + // The run's end is reported with its new state, so the line never flashes a phase after the reply. + const state = await deps.state(feed.botId).catch(() => feed.state); + setState(feed, state); + updateActivity(feed); + if (!runActive) { + deps.onRunSettled?.(feed.botId, state); + void closeIfUnwatched(feed); + } + } + + function setState(feed: Feed, state: BotSessionState): void { + if (JSON.stringify(state) === JSON.stringify(feed.state)) return; + const wasRunning = feed.state.kind === "running"; + feed.state = state; + if (state.kind === "running" && !wasRunning) startRun(feed); + if (state.kind !== "running") { + feed.stopping = false; + feed.resuming = false; + } + emit(feed, { type: "state", state }); + updateActivity(feed); + } +``` + +8. In `openFeed`, add these fields to the `Feed` literal: + +```ts + activity: null, + startedAt: now(), + stopping: false, + resuming: false, + frame: { entries: initial.entries, docs: initial.docs }, +``` + +Directly after the literal and before `feeds.set(botId, feed);`, add: + +```ts + if (feed.state.kind === "running") startRun(feed); + feed.activity = computeActivity(feed); +``` + +9. In `syncQuestion`, after `emit(feed, { type: "question", question });`, add `updateActivity(feed);`. + +10. In `notifyState`, add as the first line: `if (state.kind !== "running") resumingBots.delete(botId);`. + +11. Add the three methods to the returned object: + +```ts + notifyStopping(botId) { + const feed = feeds.get(botId); + if (!feed || feed.ended) return; + void enqueueWork(feed, async () => { + if (feed.state.kind !== "running") return; + feed.stopping = true; + updateActivity(feed); + }); + }, + + notifyResuming(botId) { + resumingBots.add(botId); + }, + + async refreshActivity(botId) { + const feed = feeds.get(botId); + if (!feed || feed.ended) return; + await enqueueWork(feed, async () => updateActivity(feed)); + }, +``` + +- [ ] **Step 5: Wire main** + +`main/services/bot-runtime/bot-session-main.ts`. In `createBotLiveProjection({ … })`, add `approvalPending: (botId) => botApprovals.pending(botId).length > 0,`. Next to the `botQuestions.onChange(...)` block, add: + +```ts +// An approval appearing or settling changes the line to and from "Waiting for you". +botApprovals.onChange((botId) => { + void liveProjection?.refreshActivity(botId).catch((error: unknown) => + logger.warn("bots", `Bot ${botId} activity view report.`, error), + ); +}); +``` + +`main/handlers/bots.ts`. Replace the `bots:resume` and `bots:stop` handlers: + +```ts + ipcMain.handle("bots:resume", async (_event, input: unknown) => { + const { botId, requestId } = parseBotSessionAction(input, "resume"); + botLiveProjection().notifyResuming(botId); + return (await botSessionRuntime()).resume(botId, requestId); + }); +``` + +```ts + ipcMain.handle("bots:stop", async (_event, id: unknown) => { + const botId = parseBotId(id); + botLiveProjection().notifyStopping(botId); + return (await botSessionRuntime()).stop(botId); + }); +``` + +- [ ] **Step 6: Update the fakes and fixtures** + +`main/handlers/bot-live.test.ts`: add `activity: null,` to the fake snapshot, and add to the fake projection: + +```ts + notifyStopping: () => undefined, + notifyResuming: () => undefined, + refreshActivity: async () => undefined, +``` + +`renderer/main/bots/bot-chat-pane.test.tsx`: add `activity: null,` to the `snapshot()` helper defaults. + +- [ ] **Step 7: Run the tests to verify they pass** + +Run: `npx tsx --test main/services/bot-runtime/live-projection.test.ts main/handlers/bot-live.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: PASS. + +Run: `npm run test:bot-runtime && npm run type-check` +Expected: PASS. If `bot-starter.test.ts` or another test builds a `BotLiveSnapshot` by hand, add `activity: null`. + +- [ ] **Step 8: Commit** + +```bash +git add renderer/shared/bot-live.ts main/services/bot-runtime/live-projection.ts main/services/bot-runtime/live-projection.test.ts main/services/bot-runtime/bot-session-main.ts main/handlers/bots.ts main/handlers/bot-live.test.ts renderer/main/bots/bot-chat-pane.test.tsx +git commit -m "Bots: project the live activity phase from pi.live, cards, Stop and Resume" +``` + +--- + +### Task 4: `chatActivity` on the Bot record + +**Files:** +- Modify: `renderer/shared/bots.ts`, `main/services/bot-store-core.ts`, `main/handlers/bot-params.ts`, `renderer/main/bots/bot-identity.ts` +- Test: `main/services/bot-store-core.test.ts`, `main/handlers/bot-params.test.ts` + +**Interfaces:** +- Consumes: nothing new. +- Produces (in `renderer/shared/bots.ts`): + - `BOT_CHAT_ACTIVITY_LEVELS = ["quiet", "summary", "detailed"] as const`, `type BotChatActivityLevel` + - `BOT_CHAT_ACTIVITY_WORDINGS = ["follows", "thinking"] as const`, `type BotChatActivityWording` (re-exported to match Task 1's union) + - `interface BotChatActivity { level: BotChatActivityLevel; wording: BotChatActivityWording }`, `DEFAULT_BOT_CHAT_ACTIVITY` + - `parseBotChatActivity(value: unknown): BotChatActivity | undefined` (exact keys, enum values), `resolveBotChatActivity(value: BotChatActivity | undefined): BotChatActivity` + - `BotDefinition.chatActivity?: BotChatActivity`; `BotUpdateInput.chatActivity?: BotChatActivity` (absent keeps the stored value) + - `BotIdentityPatch.chatActivity?: BotChatActivity` + +- [ ] **Step 1: Write the failing tests** + +Add to `main/services/bot-store-core.test.ts` (import `BotIdentityRevisionConflictError` is not needed): + +```ts +// Test 1 (Review Focus 1) +test("a Bot's chat activity is saved with a new revision, and identity edits that leave it out keep it", async () => { + const { root, store } = await fixture(); + try { + const created = await store.create({ + name: "Planner", + instructions: "Plan dinners.", + avatar: { version: 1, shape: "hex", color: "sun" }, + }); + assert.equal(created.chatActivity, undefined, "new Bots store nothing: absent means Quiet"); + const chosen = await store.update({ + id: created.id, + expectedRevision: created.revision, + name: created.name, + instructions: created.instructions, + avatar: created.avatar, + chatActivity: { level: "summary", wording: "thinking" }, + }); + assert.deepEqual(chosen.chatActivity, { level: "summary", wording: "thinking" }); + assert.notEqual(chosen.revision, created.revision); + const renamed = await store.update({ + id: created.id, + expectedRevision: chosen.revision, + name: "Meal planner", + instructions: created.instructions, + avatar: created.avatar, + }); + assert.equal(renamed.name, "Meal planner"); + assert.deepEqual(renamed.chatActivity, { level: "summary", wording: "thinking" }); + await assert.rejects( + store.update({ + id: created.id, + expectedRevision: renamed.revision, + name: renamed.name, + instructions: renamed.instructions, + avatar: renamed.avatar, + chatActivity: { level: "verbose", wording: "follows" } as never, + }), + /chat activity/u, + ); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +// Test 2 (Review Focus 2) +test("a stored chat activity that isn't a current choice reads as absent and keeps the Bot", async () => { + const { root } = await fixture(); + try { + const bot = (id: string, chatActivity: unknown) => ({ + id, + name: id, + instructions: "x", + avatar: { version: 1, shape: "orb", color: "sky" }, + createdAt: 1, + updatedAt: 1, + chatActivity, + }); + await writeFile( + join(root, "bots.json"), + JSON.stringify({ + version: 1, + bots: [ + bot("bot:newer", { level: "verbose", wording: "follows" }), + bot("bot:extra", { level: "summary", wording: "follows", sound: true }), + bot("bot:good", { level: "detailed", wording: "follows" }), + ], + }), + ); + const store = createBotStore({ root: () => root, now: () => 50 }); + const byId = new Map((await store.list()).map((entry) => [entry.id, entry.chatActivity])); + assert.equal(byId.size, 3, "no Bot is lost to a bad setting"); + assert.equal(byId.get("bot:newer"), undefined); + assert.equal(byId.get("bot:extra"), undefined); + assert.deepEqual(byId.get("bot:good"), { level: "detailed", wording: "follows" }); + assert.deepEqual(resolveBotChatActivity(byId.get("bot:newer")), { level: "quiet", wording: "follows" }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); +``` + +and extend the import: `import { DEFAULT_BOT_AVATAR, resolveBotChatActivity } from "../../renderer/shared/bots.js";`. + +Add to `main/handlers/bot-params.test.ts`: + +```ts +test("a Bot update may carry an exact chat activity choice, and nothing else new", () => { + const fields = { + id: "bot-1", + expectedRevision: "botrev:one", + name: "Planner", + instructions: "Plan.", + avatar: { version: 1 as const, shape: "hex" as const, color: "sun" as const }, + }; + assert.deepEqual(parseBotUpdate({ ...fields, chatActivity: { level: "detailed", wording: "thinking" } }), { + ...fields, + description: undefined, + chatActivity: { level: "detailed", wording: "thinking" }, + }); + assert.equal("chatActivity" in parseBotUpdate(fields), false); + assert.throws(() => parseBotUpdate({ ...fields, chatActivity: { level: "loud", wording: "follows" } }), /chat activity/u); + assert.throws( + () => parseBotUpdate({ ...fields, chatActivity: { level: "quiet", wording: "follows", extra: 1 } }), + /chat activity/u, + ); + assert.throws(() => parseBotUpdate({ ...fields, chatActivity: "quiet" }), /chat activity/u); +}); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test main/services/bot-store-core.test.ts main/handlers/bot-params.test.ts` +Expected: FAIL. `resolveBotChatActivity` is not exported, and `parseBotUpdate` rejects the `chatActivity` key as `Invalid bot update fields`. + +- [ ] **Step 3: Add the shared type** + +In `renderer/shared/bots.ts`, after `BOT_LIMITS`: + +```ts +export const BOT_CHAT_ACTIVITY_LEVELS = ["quiet", "summary", "detailed"] as const; +export type BotChatActivityLevel = (typeof BOT_CHAT_ACTIVITY_LEVELS)[number]; +export const BOT_CHAT_ACTIVITY_WORDINGS = ["follows", "thinking"] as const; +export type BotChatActivityWording = (typeof BOT_CHAT_ACTIVITY_WORDINGS)[number]; + +/** How much a Bot chat shows while the Bot works, and what its status line says (spec §7). */ +export interface BotChatActivity { + level: BotChatActivityLevel; + wording: BotChatActivityWording; +} + +/** What an absent setting means; new Bots never store it. */ +export const DEFAULT_BOT_CHAT_ACTIVITY: BotChatActivity = { level: "quiet", wording: "follows" }; + +/** Exact check: both keys, current values, nothing else. */ +export function parseBotChatActivity(value: unknown): BotChatActivity | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const record = value as Record; + const keys = Object.keys(record); + if (keys.length !== 2 || !keys.every((key) => key === "level" || key === "wording")) return undefined; + if (!includes(BOT_CHAT_ACTIVITY_LEVELS, record.level) || !includes(BOT_CHAT_ACTIVITY_WORDINGS, record.wording)) return undefined; + return { level: record.level, wording: record.wording }; +} + +export function resolveBotChatActivity(value: BotChatActivity | undefined): BotChatActivity { + return value ? { level: value.level, wording: value.wording } : { ...DEFAULT_BOT_CHAT_ACTIVITY }; +} +``` + +`includes` is declared further down the file as a function declaration, so it is hoisted. Add to `BotDefinition` after `avatar`: + +```ts + /** Absent: Quiet, Follows the work. */ + chatActivity?: BotChatActivity; +``` + +Replace `BotUpdateInput`: + +```ts +export interface BotUpdateInput extends BotCreateInput { + id: string; + expectedRevision: string; + /** Absent keeps the stored choice, so identity edits never reset it. */ + chatActivity?: BotChatActivity; +} +``` + +To keep one union, change Task 1's local declaration in `renderer/shared/bot-activity.ts` to a re-export: + +```ts +export type { BotChatActivityWording } from "./bots.js"; +``` + +Then add `import type { BotChatActivityWording } from "./bots.js";` for its own use. + +- [ ] **Step 4: Normalise and keep it in the store** + +`main/services/bot-store-core.ts`: import `parseBotChatActivity`. In `projectBot`, add to `projected` after `avatar,`: + +```ts + // A choice this build does not know reads as absent (Quiet); the Bot itself is kept. + ...(parseBotChatActivity(bot.chatActivity) ? { chatActivity: parseBotChatActivity(bot.chatActivity)! } : {}), +``` + +In `update`, after `const normalized = normalizeInput(input);`: + +```ts + const chatActivity = input.chatActivity === undefined ? undefined : parseBotChatActivity(input.chatActivity); + if (input.chatActivity !== undefined && !chatActivity) throw new Error("Choose a valid chat activity."); +``` + +and inside the draft mutation, after the avatar assignment: + +```ts + if (chatActivity) bot.chatActivity = chatActivity; +``` + +`main/handlers/bot-params.ts`: import `parseBotChatActivity` from `../../renderer/shared/bots.js`. Change `UPDATE_KEYS` to `new Set([...CREATE_KEYS, "chatActivity", "expectedRevision", "id"])`, and `parseBotUpdate` to: + +```ts +export function parseBotUpdate(value: unknown): BotUpdateInput { + const record = exact(value, UPDATE_KEYS, "bot update fields"); + const chatActivity = record.chatActivity === undefined ? undefined : parseBotChatActivity(record.chatActivity); + if (record.chatActivity !== undefined && !chatActivity) throw new Error("Invalid bot chat activity."); + return { + id: parseBotId(record.id), + expectedRevision: parseBotRevision(record.expectedRevision), + ...createFields(record), + ...(chatActivity ? { chatActivity } : {}), + }; +} +``` + +- [ ] **Step 5: Let the renderer patch it** + +`renderer/main/bots/bot-identity.ts`: change the `BotAvatar` import to `import type { BotAvatar, BotChatActivity, BotDefinition } from "../../shared/bots";`, add `chatActivity: BotChatActivity;` to `BotIdentityPatch`, and in `botsApi.update({ … })` add after `avatar: next.avatar,`: + +```ts + ...(patch.chatActivity ? { chatActivity: patch.chatActivity } : {}), +``` + +- [ ] **Step 6: Run the tests to verify they pass** + +Run: `npx tsx --test main/services/bot-store-core.test.ts main/handlers/bot-params.test.ts && npx tsx --test main/services/aiden-remote-bots.test.ts` +Expected: PASS. Remote `PATCH` builds its update without `chatActivity`, so the stored choice is kept and Remote's tests are unchanged. + +Run: `npm run type-check` +Expected: PASS. + +- [ ] **Step 7: Commit** + +```bash +git add renderer/shared/bots.ts renderer/shared/bot-activity.ts main/services/bot-store-core.ts main/services/bot-store-core.test.ts main/handlers/bot-params.ts main/handlers/bot-params.test.ts renderer/main/bots/bot-identity.ts +git commit -m "Bots: store a per-Bot chat activity choice, kept across identity edits" +``` + +--- + +### Task 5: `BotStatusLine` in the Bot chat + +**Files:** +- Create: `renderer/main/bots/bot-status-line.tsx` +- Test: `renderer/main/bots/bot-status-line.test.tsx` +- Modify: `renderer/main/bots/bot-chat-pane.tsx`, `renderer/main/bots/bot-chat-pane.test.tsx` +- Modify: `package.json` (`test:bots`), `scripts/ci-test-registry.json` + +**Interfaces:** +- Consumes: `botActivityDisplay`, `botElapsedLabel`, `nextBotAnnouncement`, `BOT_STILL_GOING_AFTER_MS`, `BotAnnouncement` (Task 1); `BotLiveActivity` (Task 3); `BotChatActivityWording`, `resolveBotChatActivity` (Task 4); `AidenActivityMark`. +- Produces: `BotStatusLine({ activity, wording, now?, onStop? }: { activity: BotLiveActivity; wording: BotChatActivityWording; now?: number; onStop?(): void })`. `now` freezes the clock (tests, previews); `onStop` shows Stop after 20 seconds. + +- [ ] **Step 1: Write the failing tests** + +```tsx +// renderer/main/bots/bot-status-line.test.tsx +import "./test-dom"; +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import type { BotLiveActivity } from "../../shared/bot-live"; +import { BotStatusLine } from "./bot-status-line"; + +afterEach(cleanup); + +const reading: BotLiveActivity = { + phase: "reading", + startedAt: 1_000, + step: { kind: "reading", label: "Reading", detail: "grocery-list.md" }, +}; + +test("the line says the phase with its step on the Mac, and only Thinking with Always Thinking", () => { + render(); + assert.ok(screen.getByRole("status", { name: "Reading, grocery-list.md" })); + cleanup(); + render(); + assert.ok(screen.getByRole("status", { name: "Thinking" })); + assert.equal(screen.queryByText(/grocery-list\.md/u), null, "Always Thinking never peeks at the step"); +}); + +test("waiting keeps its word under Always Thinking, and an unknown phase reads as Working", () => { + render(); + assert.ok(screen.getByRole("status", { name: "Waiting for you" })); + cleanup(); + render(); + assert.ok(screen.getByRole("status", { name: "Working" })); +}); + +test("after 20 seconds the line shows elapsed time and Stop; after 2 minutes, a still-going note", () => { + const calls: string[] = []; + render( calls.push("stop")} />); + assert.equal(screen.queryByRole("button", { name: "Stop" }), null); + assert.equal(screen.queryByText(/19s/u), null); + cleanup(); + render( calls.push("stop")} />); + assert.ok(screen.getByText("· 1m 12s")); + fireEvent.click(screen.getByRole("button", { name: "Stop" })); + assert.deepEqual(calls, ["stop"]); + assert.equal(screen.queryByRole("note"), null); + cleanup(); + render(); + assert.ok(screen.getByRole("note")); + assert.ok(screen.getByText("Still going. I'll message you when it's done.")); +}); +``` + +In `renderer/main/bots/bot-chat-pane.test.tsx`, replace the test "a just-sent message shows the Bot working before any reply text arrives" with: + +```tsx +test("a just-sent message shows the status line before any reply text arrives", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [userEntry("u1", "Plan Lisbon")], + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "preparing", startedAt: Date.now() }, + }), + }); + assert.ok(await screen.findByText("Plan Lisbon")); + assert.ok(await screen.findByRole("status", { name: "Getting ready" })); +}); + +test("the status line follows live activity, and hides while the reply's words stream", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [userEntry("u1", "What's on my list?")], + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "groceries.md" } }, + }), + }); + assert.ok(await screen.findByRole("status", { name: "Reading, groceries.md" })); + emitBotTestNotification("bots:live:event", { + botId: "bot-1", + epoch: "epoch-1", + seq: 1, + type: "activity", + activity: { phase: "writing", startedAt: Date.now() }, + }); + emitBotTestNotification("bots:live:event", { botId: "bot-1", epoch: "epoch-1", seq: 2, type: "partial", text: "Eggs and milk." }); + await waitFor(() => assert.equal(screen.queryByText("Reading"), null)); + assert.equal(screen.queryByText("Writing"), null, "the words themselves are the signal"); +}); + +test("a Bot set to Always Thinking says Thinking while it reads", async () => { + await mountChat({ + "bots:get": () => botFixture({ chatActivity: { level: "quiet", wording: "thinking" } }), + "bots:live:subscribe": () => + snapshot({ + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "groceries.md" } }, + }), + }); + assert.ok(await screen.findByRole("status", { name: "Thinking" })); +}); +``` + +`mountChat` spreads `handlers` after its default `bots:get`, so the override in the third test wins. + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-chat-pane.test.tsx` +Expected: FAIL. `Cannot find module './bot-status-line'`, and the pane has no status role named "Getting ready". + +- [ ] **Step 3: Write the component** + +```tsx +// renderer/main/bots/bot-status-line.tsx +// The one calm line a working Bot shows (spec §5, §6, §14): an activity mark +// and a word, a hover/focus peek at the current step on the Mac, elapsed time +// and Stop after 20 seconds, and a still-going note after 2 minutes. The +// accessible name changes at most once every 2 seconds. + +import * as React from "react"; +import { Square } from "lucide-react"; +import { AidenActivityMark } from "../../components/aiden-activity-mark"; +import { Button, Text } from "../../components/ui"; +import { + BOT_STILL_GOING_AFTER_MS, + botActivityDisplay, + botElapsedLabel, + nextBotAnnouncement, + type BotAnnouncement, +} from "../../shared/bot-activity"; +import type { BotLiveActivity } from "../../shared/bot-live"; +import type { BotChatActivityWording } from "../../shared/bots"; + +function useClock(fixed: number | undefined): number { + const [now, setNow] = React.useState(() => fixed ?? Date.now()); + React.useEffect(() => { + if (fixed !== undefined) return; + const timer = window.setInterval(() => setNow(Date.now()), 1_000); + return () => window.clearInterval(timer); + }, [fixed]); + return fixed ?? now; +} + +/** The text screen readers hear: the newest wording, at most once per gap. */ +function useAnnouncement(text: string): string { + const [shown, setShown] = React.useState(() => ({ text, at: Date.now() })); + React.useEffect(() => { + const next = nextBotAnnouncement(shown, text, Date.now()); + if (next.shown !== shown) setShown(next.shown); + if (next.retryInMs === undefined) return; + const timer = window.setTimeout(() => setShown({ text, at: Date.now() }), next.retryInMs); + return () => window.clearTimeout(timer); + }, [text, shown]); + return shown.text; +} + +export function BotStatusLine({ + activity, + wording, + now: fixedNow, + onStop, +}: { + activity: BotLiveActivity; + wording: BotChatActivityWording; + /** A fixed clock (tests and previews); otherwise the line ticks each second. */ + now?: number; + /** Shown as Stop once the turn has run for 20 seconds. */ + onStop?(): void; +}) { + const display = botActivityDisplay(activity.phase, wording, activity.app); + const now = useClock(fixedNow); + const detail = wording === "follows" && display.phase !== "thinking" ? activity.step?.detail : undefined; + const elapsed = botElapsedLabel(activity.startedAt, now); + const stillGoing = now - activity.startedAt >= BOT_STILL_GOING_AFTER_MS; + const announced = useAnnouncement(detail ? `${display.word}, ${detail}` : display.word); + const shimmer = display.phase !== "waiting" && display.phase !== "stopping"; + return ( +
+
+
+ + +
+ {elapsed && onStop ? ( + + ) : null} +
+ {stillGoing ? ( + + Still going. I'll message you when it's done. + + ) : null} +
+ ); +} +``` + +- [ ] **Step 4: Show it in the chat** + +In `renderer/main/bots/bot-chat-pane.tsx`: + +1. Imports: `import { BotStatusLine } from "./bot-status-line";` and `import { resolveBotChatActivity } from "../../shared/bots";`. +2. In the `shell`'s `autoScrollDeps`, add `snapshot?.activity?.phase,`. +3. After `const question = snapshot.question;`, add: + +```tsx + const chatActivity = resolveBotChatActivity(current.chatActivity); + // While the reply's visible words stream, the words are the signal (§5.2). + const replyStreaming = running && (snapshot.partial?.trim().length ?? 0) > 0; +``` + +4. In the final `shell(...)` body, directly after ``: + +```tsx + {snapshot.activity && !replyStreaming ? ( + + ) : null} +``` + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `npx tsx --test renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-chat-pane.test.tsx` +Expected: PASS. + +- [ ] **Step 6: Register the test** + +Append ` renderer/main/bots/bot-status-line.test.tsx` to `test:bots` in `package.json`. In `scripts/ci-test-registry.json`, add `"renderer/main/bots/bot-status-line.test.tsx",` directly after `"renderer/main/bots/bot-transcript-rows.test.ts",`. + +Run: `npm run test:ci-policy` +Expected: PASS. + +- [ ] **Step 7: Commit** + +```bash +git add renderer/main/bots/bot-status-line.tsx renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-chat-pane.tsx renderer/main/bots/bot-chat-pane.test.tsx package.json scripts/ci-test-registry.json +git commit -m "Bots: one calm status line while a Bot works" +``` + +--- + +### Task 6: Summary and Detailed recaps, failed versus blocked, and the stopped line + +**Files:** +- Create: `renderer/main/bots/bot-activity-steps.ts`, `renderer/main/bots/bot-activity-recap.tsx` +- Test: `renderer/main/bots/bot-activity-recap.test.tsx` +- Modify: `renderer/main/bots/bot-transcript-rows.ts`, `renderer/main/bots/bot-transcript-rows.test.ts`, `renderer/main/bots/bot-chat-pane.tsx`, `renderer/main/bots/bot-chat-pane.test.tsx` +- Modify: `package.json` (`test:bots`), `scripts/ci-test-registry.json` + +**Interfaces:** +- Consumes: `botStepPhrase`, `botStepInfinitive`, `botPhaseWord`, `botDurationLabel`, `BotToolPhase` (Task 1); `BotToolResultStatus`, the enriched tool calls (Task 2); `BotChatActivityLevel` (Task 4). +- Produces: + - `bot-activity-steps.ts`: `type BotRecapStepStatus = BotToolResultStatus | "running"`; `interface BotRecapStep { id: string; kind: BotToolPhase; label: string; detail?: string; app?: string; status: BotRecapStepStatus; count?: number }`; `mergeBotSteps(steps): BotRecapStep[]`; `botRecapSentence(steps): string`; `botRecapHeader(steps, durationMs, live): string`; `botRecapIssues(steps): { failed: number; blocked: number }`; `botStepLine(step): { text: string; detail?: string; tone: "normal" | "warning" | "error"; active: boolean }`. + - `BotActivityRecap({ steps, durationMs, live, level })`. + - `botTranscriptRows(entries, partial, options: BotTranscriptRowOptions)` where `interface BotTranscriptRowOptions { running: boolean; level: BotChatActivityLevel }`. New row kinds: `{ kind: "recap"; id; steps: BotRecapStep[]; durationMs: number; live: boolean }` and `{ kind: "stopped"; id }`. + +- [ ] **Step 1: Write the failing tests** + +```tsx +// renderer/main/bots/bot-activity-recap.test.tsx +import "./test-dom"; +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { BotActivityRecap } from "./bot-activity-recap"; +import type { BotRecapStep } from "./bot-activity-steps"; + +afterEach(cleanup); + +const ok = (id: string, kind: BotRecapStep["kind"], label: string, extra: Partial = {}): BotRecapStep => ({ + id, + kind, + label, + status: "ok", + ...extra, +}); + +const TURN: BotRecapStep[] = [ + ok("1", "reading", "Read 1 file", { detail: "a.md" }), + ok("2", "reading", "Read 1 file", { detail: "b.md" }), + ok("3", "searching", "Searched the web", { detail: "lisbon trains" }), + ok("4", "app", "Used Notion", { app: "Notion" }), +]; + +test("a finished recap is one closed line that opens to its merged steps", () => { + render(); + const header = screen.getByRole("button", { name: "Worked for 18s · read 2 files, searched the web, used Notion" }); + assert.equal(header.getAttribute("aria-expanded"), "false"); + fireEvent.click(header); + const list = screen.getByRole("list", { name: "Steps" }); + assert.deepEqual( + within(list).getAllByRole("listitem").map((item) => item.textContent), + ["Read 2 files", "Searched the web · lisbon trains", "Used Notion"], + ); +}); + +test("Detailed opens while live with the last three steps, and folds itself when the reply lands", () => { + const live = [...TURN, { id: "5", kind: "editing" as const, label: "Edited 1 file", detail: "plan.md", status: "running" as const }]; + const { rerender } = render(); + const list = screen.getByRole("list", { name: "Steps" }); + assert.deepEqual( + within(list).getAllByRole("listitem").map((item) => item.textContent), + ["Searched the web · lisbon trains", "Used Notion", "Editing files · plan.md"], + ); + rerender( ({ ...step, status: "ok" }))} durationMs={9_000} live={false} level="detailed" />); + assert.equal(screen.queryByRole("list", { name: "Steps" }), null); +}); + +test("a manual close or open during the run sticks after the reply lands", () => { + const { rerender } = render(); + fireEvent.click(screen.getByRole("button", { name: /^Working/u })); + rerender(); + assert.equal(screen.queryByRole("list", { name: "Steps" }), null, "closed by hand stays closed while live"); + fireEvent.click(screen.getByRole("button", { name: /^Working/u })); + rerender(); + assert.ok(screen.getByRole("list", { name: "Steps" }), "opened by hand stays open after the reply"); +}); + +test("a failed step is a red issue and a refused one is amber Blocked, never alike", () => { + render( + , + ); + const header = screen.getByRole("button", { name: "Worked for 5s · read 1 file · 1 issue · 1 blocked" }); + fireEvent.click(header); + assert.ok(screen.getByText("Couldn’t run a command")); + assert.ok(screen.getByText("Blocked: search the web")); +}); +``` + +Replace the body of `renderer/main/bots/bot-transcript-rows.test.ts` from the first `test(` through the end with the following. Keep the imports and the `user`/`step`/`answer`/`result`/`failed`/`kinds` helpers, and add `at` support to `user` and `answer`: + +```ts +const userAt = (id: string, text: string, at: number): BotTranscriptEntry => ({ id, type: "user", text, imageCount: 0, at }); +const answerAt = (id: string, text: string, at: number): BotTranscriptEntry => ({ id, type: "assistant", text, toolCalls: [], stopReason: "stop", at }); +const quiet = { running: false, level: "quiet" } as const; + +test("every tool round of one reply folds into a single Updates line before the answer", () => { + const rows = botTranscriptRows( + [ + user("u1", "Find flights"), + step("a1", "Searching airlines."), + result("a1"), + step("a2", "Comparing prices."), + result("a2"), + answer("a3", "The cheapest is TAP on Friday."), + ], + null, + quiet, + ); + assert.deepEqual(kinds(rows), ["user", "updates", "assistant"]); +}); + +test("Quiet never adds a recap; Summary puts one recap of the turn right above its answer", () => { + const entries = [ + userAt("u1", "Find flights", 1_000), + step("a1", ""), + { ...result("a1"), at: 4_000 } as BotTranscriptEntry, + { id: "f1", type: "file", path: "trips.md", operation: "written" } as BotTranscriptEntry, + answerAt("a2", "TAP on Friday.", 19_000), + ]; + assert.equal(kinds(botTranscriptRows(entries, null, quiet)).includes("recap"), false); + const rows = botTranscriptRows(entries, null, { running: false, level: "summary" }); + // The Updates line is still here until Task 7 removes it. + assert.deepEqual(kinds(rows), ["user", "updates", "file", "recap", "assistant"]); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.equal(recap.live, false); + assert.equal(recap.durationMs, 18_000); + assert.deepEqual(recap.steps.map((s) => [s.kind, s.status]), [["searching", "ok"]]); +}); + +test("while running, Summary shows no recap yet and Detailed shows a live one at the end", () => { + const entries = [user("u1", "Plan dinner"), step("a1", "")]; + assert.equal(kinds(botTranscriptRows(entries, null, { running: true, level: "summary" })).includes("recap"), false); + const rows = botTranscriptRows(entries, null, { running: true, level: "detailed" }); + const recap = rows[rows.length - 1]; + assert.ok(recap?.kind === "recap"); + assert.equal(recap.live, true); + assert.deepEqual(recap.steps.map((s) => s.status), ["running"]); +}); + +test("a call with no result in a finished turn counts as failed", () => { + const rows = botTranscriptRows([user("u1", "go"), step("a1", ""), answer("a2", "Done.")], null, { running: false, level: "summary" }); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.deepEqual(recap.steps.map((s) => s.status), ["failed"]); +}); + +test("a reply the person stopped ends with a stopped line; an interrupted one does not", () => { + const aborted: BotTranscriptEntry = { id: "a1", type: "assistant", text: "Once upon", toolCalls: [], stopReason: "aborted" }; + assert.deepEqual(kinds(botTranscriptRows([user("u1", "Story"), aborted], null, quiet)), ["user", "assistant", "stopped"]); + const interrupted = botTranscriptRows( + [user("u1", "Story"), aborted, { id: "n1", type: "notice", notice: "interrupted" }], + null, + quiet, + ); + assert.deepEqual(kinds(interrupted), ["user", "assistant", "notice"]); +}); + +test("only the newest failed turn offers Retry, and never while the Bot is working", () => { + const history = [user("u1", "Plan dinner"), failed("a1:failed", "Plan dinner")]; + const latest = botTranscriptRows(history, null, quiet).slice(-1)[0]; + assert.deepEqual(latest, { kind: "failed", id: "a1:failed", retryText: "Plan dinner" }); + + const older = botTranscriptRows([...history, user("u2", "Never mind"), answer("a2", "Okay.")], null, quiet); + assert.deepEqual(older.find((row) => row.kind === "failed"), { kind: "failed", id: "a1:failed", retryText: null }); + + const busy = botTranscriptRows(history, null, { running: true, level: "quiet" }).find((row) => row.kind === "failed"); + assert.equal(busy?.kind === "failed" && busy.retryText, null); + + const routine = botTranscriptRows([failed("r1:failed", null)], null, quiet)[0]; + assert.equal(routine?.kind === "failed" && routine.retryText, null); +}); + +test("a paused reply keeps what it wrote as a bubble", () => { + const rows = botTranscriptRows([user("u1", "Summarize")], "Here is what I have so far", quiet); + assert.deepEqual(rows[rows.length - 1], { kind: "assistant", id: "partial", text: "Here is what I have so far" }); +}); +``` + +Delete the now-replaced tests "a running reply keeps one Working line…" and "files and shared images show as chips…". Task 7 rewrites the Updates expectations. + +In `renderer/main/bots/bot-chat-pane.test.tsx`, add: + +```tsx +test("a Summary Bot shows one recap above its answer that opens to the steps", async () => { + await mountChat({ + "bots:get": () => botFixture({ chatActivity: { level: "summary", wording: "follows" } }), + "bots:live:subscribe": () => + snapshot({ + entries: [ + { ...userEntry("u1", "Find flights"), at: 1_000 } as BotTranscriptEntry, + toolStep("a1", ""), + { id: "r1", type: "tool_result", toolCallId: "a1-call", toolName: "web_search", isError: false, status: "ok", at: 5_000 }, + { ...assistantEntry("a2", "TAP on Friday is cheapest."), at: 19_000 } as BotTranscriptEntry, + ], + }), + }); + const recap = await screen.findByRole("button", { name: "Worked for 18s · searched the web" }); + fireEvent.click(recap); + assert.ok(await screen.findByText("Searched the web")); +}); + +test("a reply the person stopped says so in a quiet centred line", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [ + userEntry("u1", "Tell me a story"), + { id: "a1", type: "assistant", text: "Once upon", toolCalls: [], stopReason: "aborted" }, + ], + }), + }); + assert.ok(await screen.findByText("You stopped this reply.")); +}); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test renderer/main/bots/bot-activity-recap.test.tsx renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: FAIL. `Cannot find module './bot-activity-recap'`, and `botTranscriptRows` is called with an options object while it still takes a boolean, so no recap is produced. + +- [ ] **Step 3: Write the step model** + +```ts +// renderer/main/bots/bot-activity-steps.ts +// A turn's tool steps as the recap shows them (spec §6): merged repeats +// ("Read 6 files"), one deterministic sentence, and failed versus refused +// steps that never look alike. + +import { + botDurationLabel, + botPhaseWord, + botStepInfinitive, + botStepPhrase, + type BotToolPhase, +} from "../../shared/bot-activity"; +import type { BotToolResultStatus } from "../../shared/bot-live"; + +export type BotRecapStepStatus = BotToolResultStatus | "running"; + +export interface BotRecapStep { + id: string; + kind: BotToolPhase; + /** Past tense: "Read 1 file". */ + label: string; + detail?: string; + app?: string; + status: BotRecapStepStatus; + /** Set on a merged row. */ + count?: number; +} + +/** Consecutive successful steps of the same kind (and app) become one row. */ +export function mergeBotSteps(steps: readonly BotRecapStep[]): BotRecapStep[] { + const merged: BotRecapStep[] = []; + for (const step of steps) { + const last = merged[merged.length - 1]; + if (last && last.status === "ok" && step.status === "ok" && last.kind === step.kind && last.app === step.app) { + const { detail: _detail, ...rest } = last; + const count = (last.count ?? 1) + 1; + merged[merged.length - 1] = { ...rest, count, label: botStepPhrase(step.kind, count, step.app) }; + continue; + } + merged.push(step); + } + return merged; +} + +function lowerFirst(text: string): string { + return text.charAt(0).toLowerCase() + text.slice(1); +} + +/** "read 2 files, searched the web, used Notion": successful steps, grouped in first-seen order. */ +export function botRecapSentence(steps: readonly BotRecapStep[]): string { + const groups = new Map(); + for (const step of steps) { + if (step.status !== "ok" || step.kind === "waiting") continue; + const key = `${step.kind}\u0000${step.app ?? ""}`; + const group = groups.get(key); + if (group) group.count += 1; + else groups.set(key, { kind: step.kind, ...(step.app ? { app: step.app } : {}), count: 1 }); + } + return [...groups.values()].map(({ kind, app, count }) => lowerFirst(botStepPhrase(kind, count, app))).join(", "); +} + +export function botRecapHeader(steps: readonly BotRecapStep[], durationMs: number, live: boolean): string { + const sentence = botRecapSentence(steps); + const lead = live ? "Working" : `Worked for ${botDurationLabel(durationMs)}`; + return sentence ? `${lead} · ${sentence}` : lead; +} + +export function botRecapIssues(steps: readonly BotRecapStep[]): { failed: number; blocked: number } { + return { + failed: steps.filter((step) => step.status === "failed").length, + blocked: steps.filter((step) => step.status === "blocked").length, + }; +} + +export function botStepLine(step: BotRecapStep): { + text: string; + detail?: string; + tone: "normal" | "warning" | "error"; + active: boolean; +} { + const detail = step.detail ? { detail: step.detail } : {}; + switch (step.status) { + case "running": + return { text: botPhaseWord(step.kind, step.app), ...detail, tone: "normal", active: true }; + case "failed": + return { text: `Couldn’t ${botStepInfinitive(step.kind, step.app)}`, ...detail, tone: "error", active: false }; + case "blocked": + return { text: `Blocked: ${botStepInfinitive(step.kind, step.app)}`, ...detail, tone: "warning", active: false }; + case "ok": + return { text: step.label, ...detail, tone: "normal", active: false }; + } +} +``` + +- [ ] **Step 4: Write the recap fold** + +```tsx +// renderer/main/bots/bot-activity-recap.tsx +// One collapsed account of a turn's steps (spec §6). Summary: closed. Detailed: +// open while the turn runs (its last three steps, the active one shimmering) +// and folded when the reply lands. A manual open or close sticks. Tones reuse +// the activity feed's tokens; red is a failure, amber a refusal. + +import * as React from "react"; +import { ChevronRight } from "lucide-react"; +import type { BotChatActivityLevel } from "../../shared/bots"; +import { + botRecapHeader, + botRecapIssues, + botStepLine, + mergeBotSteps, + type BotRecapStep, +} from "./bot-activity-steps"; + +const LIVE_ROWS = 3; + +function toneClass(tone: "normal" | "warning" | "error"): string { + if (tone === "error") return "text-red"; + if (tone === "warning") return "text-support-warning"; + return "text-secondary"; +} + +function RecapStepRow({ step }: { step: BotRecapStep }) { + const line = botStepLine(step); + return ( +
+ + {line.text} + {line.detail ? · {line.detail} : null} + +
+ ); +} + +export function BotActivityRecap({ + steps, + durationMs, + live, + level, +}: { + steps: readonly BotRecapStep[]; + durationMs: number; + live: boolean; + level: BotChatActivityLevel; +}) { + const [choice, setChoice] = React.useState(null); + const regionId = React.useId(); + const open = choice ?? (live && level === "detailed"); + const issues = botRecapIssues(steps); + const header = botRecapHeader(steps, durationMs, live); + const name = [ + header, + issues.failed ? (issues.failed === 1 ? "1 issue" : `${issues.failed} issues`) : "", + issues.blocked ? `${issues.blocked} blocked` : "", + ] + .filter(Boolean) + .join(" · "); + const shown = live ? steps.slice(-LIVE_ROWS) : mergeBotSteps(steps); + return ( +
+ + {open ? ( +
+ {shown.map((step) => ( + + ))} +
+ ) : null} +
+ ); +} +``` + +- [ ] **Step 5: Build recap and stopped rows** + +Replace `renderer/main/bots/bot-transcript-rows.ts` with: + +```ts +// What a Bot chat shows, row by row, from the durable projection. +// +// A reply's turn starts at the person's message (or a routine, or their answer +// to a question) and ends at the next one. Narration written before tool +// calls, and the in-flight partial while the reply runs, fold into ONE +// "Updates" line per reply. With Summary or Detailed chat activity, a turn +// that used tools also gets one recap of its steps just above its answer; +// Detailed shows it, live, while the turn runs. A reply the person stopped +// ends with a "stopped" line that is derived here and never stored. + +import { botRetryableFailedTurn, type BotTranscriptEntry } from "../../shared/bot-live"; +import type { BotChatActivityLevel } from "../../shared/bots"; +import type { ConnectCardEntry } from "../../shared/bot-connections"; +import type { BotRoutineProposalEntryData, BotRoutineProposalStatus } from "../../shared/bot-routine-proposals"; +import type { BotRecapStep } from "./bot-activity-steps"; +import { resolveBotReplyProjection } from "./bot-reply-projection"; + +export interface BotTranscriptRowOptions { + running: boolean; + level: BotChatActivityLevel; +} + +export type BotTranscriptRow = + | { kind: "user"; id: string; text: string } + | { kind: "routine"; id: string; label: string; text: string } + | { kind: "assistant"; id: string; text: string; streaming?: boolean } + /** The one collapsed progress line of a reply; `active` while it runs. */ + | { kind: "updates"; id: string; progressText: string; active: boolean } + /** One turn's steps; `live` while the turn runs (Detailed only). */ + | { kind: "recap"; id: string; steps: BotRecapStep[]; durationMs: number; live: boolean } + /** "You stopped this reply." */ + | { kind: "stopped"; id: string } + | { kind: "file"; id: string; path: string; operation: "written" | "edited" } + | { kind: "image"; id: string; name: string; mimeType: string; size: number; data: string } + | { kind: "notice"; id: string; notice: "interrupted" | "session_reset" } + | { kind: "connect"; id: string; card: ConnectCardEntry } + /** `retryText` is set only on the newest failed turn, when Retry applies. */ + | { kind: "failed"; id: string; retryText: string | null; errorMessage?: string } + /** A quiet "Memory updated" caption; never folded into Updates. */ + | { kind: "memory_update"; id: string } + | { + kind: "routine_proposal"; + id: string; + proposal: BotRoutineProposalEntryData; + status: BotRoutineProposalStatus; + routineId?: string; + }; + +type UpdatesRow = Extract; + +interface Turn { + id: string; + startAt?: number; + lastAt?: number; + /** Index of the turn's answer bubble in `rows`, once it has one. */ + answerRow: number | null; + steps: BotRecapStep[]; + byCall: Map; + stopped: boolean; +} + +function joinProgress(parts: readonly string[]): string { + return parts.map((part) => part.trim()).filter(Boolean).join("\n\n"); +} + +export function botTranscriptRows( + entries: readonly BotTranscriptEntry[], + partial: string | null, + { running, level }: BotTranscriptRowOptions, +): BotTranscriptRow[] { + const rows: BotTranscriptRow[] = []; + const retryable = running ? null : botRetryableFailedTurn(entries); + const state: { turn: Turn | null; updates: { row: UpdatesRow; parts: string[] } | null } = { turn: null, updates: null }; + + const fold = (id: string, text: string) => { + if (!state.updates) { + const row: UpdatesRow = { kind: "updates", id: `${id}:updates`, progressText: "", active: false }; + rows.push(row); + state.updates = { row, parts: [] }; + } + state.updates.parts.push(text); + state.updates.row.progressText = joinProgress(state.updates.parts); + }; + + const endTurn = (live: boolean) => { + state.updates = null; + const turn = state.turn; + state.turn = null; + if (!turn) return; + const steps = turn.steps.filter((step) => step.kind !== "waiting"); + if (steps.length > 0 && (level === "detailed" || (level === "summary" && !live))) { + const recap: BotTranscriptRow = { + kind: "recap", + id: `${turn.id}:recap`, + steps: live ? steps : steps.map((step) => (step.status === "running" ? { ...step, status: "failed" } : step)), + durationMs: Math.max(0, (turn.lastAt ?? 0) - (turn.startAt ?? turn.lastAt ?? 0)), + live, + }; + if (live || turn.answerRow === null) rows.push(recap); + else rows.splice(turn.answerRow, 0, recap); + } + if (turn.stopped && !live) rows.push({ kind: "stopped", id: `${turn.id}:stopped` }); + }; + + const beginTurn = (id: string, at: number | undefined) => { + endTurn(false); + state.turn = { + id, + ...(at === undefined ? {} : { startAt: at, lastAt: at }), + answerRow: null, + steps: [], + byCall: new Map(), + stopped: false, + }; + }; + + const touch = (at: number | undefined) => { + if (state.turn && at !== undefined) state.turn.lastAt = at; + }; + + for (const entry of entries) { + switch (entry.type) { + case "user": + beginTurn(entry.id, entry.at); + rows.push({ kind: "user", id: entry.id, text: entry.text }); + break; + case "question_answer": + beginTurn(entry.id, entry.at); + rows.push({ kind: "user", id: entry.id, text: entry.text }); + break; + case "routine": + beginTurn(entry.id, entry.at); + rows.push({ kind: "routine", id: entry.id, label: entry.label, text: entry.text }); + break; + case "assistant": { + // A reply with no visible input (the self-intro) still gets a turn. + if (!state.turn) beginTurn(entry.id, entry.at); + const turn = state.turn!; + touch(entry.at); + for (const call of entry.toolCalls) { + const step: BotRecapStep = { + id: call.id, + kind: call.kind, + label: call.label, + ...(call.detail ? { detail: call.detail } : {}), + ...(call.app ? { app: call.app } : {}), + status: "running", + }; + turn.steps.push(step); + turn.byCall.set(call.id, step); + } + if (entry.stopReason === "aborted") turn.stopped = true; + if (entry.toolCalls.length > 0) fold(entry.id, entry.text); + else if (entry.text.trim()) { + turn.answerRow = rows.length; + rows.push({ kind: "assistant", id: entry.id, text: entry.text }); + } + break; + } + case "tool_result": { + touch(entry.at); + const step = state.turn?.byCall.get(entry.toolCallId); + if (step) step.status = entry.status; + break; + } + case "file": + rows.push({ kind: "file", id: entry.id, path: entry.path, operation: entry.operation }); + break; + case "shared_image": + rows.push({ kind: "image", id: entry.id, name: entry.name, mimeType: entry.mimeType, size: entry.size, data: entry.data }); + break; + case "notice": + // A paused turn that was dismissed was not stopped by the person. + if (entry.notice === "interrupted" && state.turn) state.turn.stopped = false; + endTurn(false); + rows.push({ kind: "notice", id: entry.id, notice: entry.notice }); + break; + case "connect_card": + rows.push({ kind: "connect", id: entry.id, card: entry.card }); + break; + case "failed_turn": + rows.push({ + kind: "failed", + id: entry.id, + retryText: retryable?.id === entry.id ? entry.retryText : null, + ...(entry.errorMessage ? { errorMessage: entry.errorMessage } : {}), + }); + break; + case "memory_update": + // Back-to-back saves read as one update. + if (rows[rows.length - 1]?.kind !== "memory_update") rows.push({ kind: "memory_update", id: entry.id }); + break; + case "routine_proposal": + rows.push({ + kind: "routine_proposal", + id: entry.id, + proposal: entry.proposal, + status: entry.status, + ...(entry.routineId ? { routineId: entry.routineId } : {}), + }); + break; + } + } + + if (running) { + // Everything streamed so far is progress until the reply commits. + const { progressText } = partial === null ? { progressText: "" } : resolveBotReplyProjection(partial, null, true); + const current = state.updates; + if (current) { + current.row.active = true; + if (progressText) current.row.progressText = joinProgress([...current.parts, progressText]); + } else { + rows.push({ kind: "updates", id: "working", progressText, active: true }); + } + endTurn(true); + } else { + endTurn(false); + if (partial !== null && partial.trim()) rows.push({ kind: "assistant", id: "partial", text: partial }); + } + return rows; +} +``` + +- [ ] **Step 6: Render the rows** + +In `renderer/main/bots/bot-chat-pane.tsx`: + +1. Import `import { BotActivityRecap } from "./bot-activity-recap";` and `import type { BotChatActivityLevel } from "../../shared/bots";`. +2. Add `level: BotChatActivityLevel;` to the `TranscriptEntries` props type and destructure it. Change the rows call to `botTranscriptRows(entries, partial, { running, level })`. +3. Add two `case`s to the row switch: + +```tsx + case "recap": + return ; + case "stopped": + return ( + + You stopped this reply. + + ); +``` + +4. Pass `level={chatActivity.level}` to ``. + +- [ ] **Step 7: Run the tests to verify they pass** + +Run: `npx tsx --test renderer/main/bots/bot-activity-recap.test.tsx renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: PASS. + +- [ ] **Step 8: Register and check** + +Append ` renderer/main/bots/bot-activity-recap.test.tsx` to `test:bots`. In `scripts/ci-test-registry.json`, add `"renderer/main/bots/bot-activity-recap.test.tsx",` after the Task 5 entry. + +Run: `npm run test:ci-policy && npm run type-check` +Expected: PASS. + +- [ ] **Step 9: Commit** + +```bash +git add renderer/main/bots/bot-activity-steps.ts renderer/main/bots/bot-activity-recap.tsx renderer/main/bots/bot-activity-recap.test.tsx renderer/main/bots/bot-transcript-rows.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.tsx renderer/main/bots/bot-chat-pane.test.tsx package.json scripts/ci-test-registry.json +git commit -m "Bots: Summary and Detailed recaps, failed versus blocked steps, stopped line" +``` + +--- + +### Task 7: Progress narration becomes bubbles; the Updates line goes + +**Files:** +- Modify: `renderer/main/bots/bot-transcript-rows.ts`, `renderer/main/bots/bot-transcript-rows.test.ts`, `renderer/main/bots/bot-chat-pane.tsx`, `renderer/main/bots/bot-chat-pane.test.tsx`, `renderer/main/bots/bot-chat-mode.test.tsx` +- Delete: `renderer/main/bots/bot-updates.tsx`, `renderer/main/bots/bot-reply-projection.ts` + +**Interfaces:** +- Consumes: Task 6's `botTranscriptRows` shape. +- Produces: the `updates` row kind is removed. A running partial is `{ kind: "assistant", id: "partial", text, streaming: true }`. + +- [ ] **Step 1: Write the failing tests** + +In `renderer/main/bots/bot-transcript-rows.test.ts`, replace the "every tool round … single Updates line" test with: + +```ts +test("narration written alongside tool calls is a bubble, and tool steps never become rows", () => { + const rows = botTranscriptRows( + [ + user("u1", "Find flights"), + step("a1", "On it, I'll check the airlines."), + result("a1"), + step("a2", ""), + result("a2"), + answer("a3", "The cheapest is TAP on Friday."), + ], + null, + quiet, + ); + assert.deepEqual( + rows.map((row) => (row.kind === "assistant" ? `assistant:${row.text}` : row.kind)), + ["user", "assistant:On it, I'll check the airlines.", "assistant:The cheapest is TAP on Friday."], + ); +}); + +test("a running reply streams as a bubble, and nothing is shown before it has words", () => { + const rows = botTranscriptRows([user("u1", "Plan dinner")], "Looking at recipes", { running: true, level: "quiet" }); + assert.deepEqual(rows[rows.length - 1], { kind: "assistant", id: "partial", text: "Looking at recipes", streaming: true }); + assert.deepEqual(kinds(botTranscriptRows([user("u1", "Hi")], null, { running: true, level: "quiet" })), ["user"]); +}); +``` + +Also in that file, in the "Quiet never adds a recap; Summary puts one…" test, change the expected kinds to `["user", "file", "recap", "assistant"]` and delete its "Updates line is still here" comment. A tool step with no text no longer adds a row. + +In `renderer/main/bots/bot-chat-pane.test.tsx`: + +- Replace "a reply still being written is folded under Working and opens to its text" with: + +```tsx +test("a reply still being written shows as its own bubble", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ partial: "Checking your calendar now", state: { kind: "running", submissionId: "s1" } }), + }); + assert.ok(await screen.findByText("Checking your calendar now")); + assert.equal(screen.queryByRole("button", { name: /Working|Updates/u }), null); +}); +``` + +- Replace "text before a tool call folds under Updates, and only the final answer is a bubble" with: + +```tsx +test("the Bot's own progress message is a bubble at every level, and Quiet shows no tool rows", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [ + userEntry("u1", "Am I free Friday?"), + { + id: "a1", + type: "assistant", + text: "Let me check your calendar.", + toolCalls: [{ id: "t1", name: "calendar", kind: "working", label: "Used a tool" }], + stopReason: "toolUse", + }, + { id: "r1", type: "tool_result", toolCallId: "t1", toolName: "calendar", isError: false, status: "ok" }, + assistantEntry("a2", "You are free all day Friday."), + ], + }), + }); + assert.ok(await screen.findByText("Let me check your calendar.")); + assert.ok(screen.getByText("You are free all day Friday.")); + assert.equal(screen.queryByText(/Used a tool/u), null); +}); +``` + +- Replace "all tool rounds before an answer fold into one Updates line" with: + +```tsx +test("each round's narration is its own bubble before the answer", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [ + userEntry("u1", "Find flights"), + toolStep("a1", "Searching airlines."), + toolStep("a2", "Comparing prices."), + assistantEntry("a3", "TAP on Friday is cheapest."), + ], + }), + }); + assert.ok(await screen.findByText("Searching airlines.")); + assert.ok(screen.getByText("Comparing prices.")); + assert.ok(screen.getByText("TAP on Friday is cheapest.")); +}); +``` + +- In "a renderer reload mid-reply…", delete the line `fireEvent.click(await screen.findByRole("button", { name: /Working/u }));`. The `findByText` that follows now finds the streaming bubble directly. + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: FAIL. Narration still folds into `updates`, and "Checking your calendar now" is hidden under a collapsed Working line. + +- [ ] **Step 3: Remove the fold from the rows** + +In `renderer/main/bots/bot-transcript-rows.ts`: + +1. Replace the file header comment's second sentence block with: "Everything the Bot writes is a bubble, including the narration it writes alongside tool calls (spec decision 9); tool steps themselves never become rows." +2. Delete the `resolveBotReplyProjection` import, the `updates` member of `BotTranscriptRow`, `UpdatesRow`, `joinProgress`, `fold`, and the `updates` field of `state` (and `state.updates = null;` in `endTurn`). +3. In the `assistant` case, replace + +```ts + if (entry.toolCalls.length > 0) fold(entry.id, entry.text); + else if (entry.text.trim()) { + turn.answerRow = rows.length; + rows.push({ kind: "assistant", id: entry.id, text: entry.text }); + } +``` + +with + +```ts + if (entry.text.trim()) { + if (entry.toolCalls.length === 0) turn.answerRow = rows.length; + rows.push({ kind: "assistant", id: entry.id, text: entry.text }); + } +``` + +4. Replace the `if (running) { … } else { … }` tail with: + +```ts + endTurn(running); + if (partial !== null && partial.trim()) { + rows.push({ kind: "assistant", id: "partial", text: partial, ...(running ? { streaming: true } : {}) }); + } + return rows; +``` + +- [ ] **Step 4: Remove the Updates line from the chat** + +In `renderer/main/bots/bot-chat-pane.tsx`, delete `import { BotUpdates } from "./bot-updates";` and the `case "updates":` branch. In the `assistant` case, pass `streaming={row.streaming}` to `SafeMessageBubble`. Update the `TranscriptEntries` doc comment to "Chat transcript rows: bubbles, recaps, chips, cards." + +Delete the files: + +```bash +git rm renderer/main/bots/bot-updates.tsx renderer/main/bots/bot-reply-projection.ts +``` + +In `renderer/main/bots/bot-chat-mode.test.tsx`, delete the test "the reply projection matches the phone rule…", its `toolTimeline` helper, and the now-unused imports (`resolveBotReplyProjection`, and `GenerationTimeline` if nothing else uses it). + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `npx tsx --test renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx renderer/main/bots/bot-chat-mode.test.tsx` +Expected: PASS. + +Run: `npm run type-check && npm run lint` +Expected: PASS. Nothing else imports the deleted modules. + +- [ ] **Step 6: Commit** + +```bash +git add -A renderer/main/bots +git commit -m "Bots: progress narration is a bubble; remove the Updates line" +``` + +--- + +### Task 8: Steer and Queue, with a faded Queued bubble and Remove + +**Files:** +- Modify: `renderer/shared/bot-live.ts`, `main/services/bot-runtime/live-projection.ts`, `main/services/bot-runtime/bot-session-service.ts`, `main/handlers/bots.ts`, `main/handlers/bot-params.ts`, `renderer/lib/ipc.ts`, `renderer/main/bots/bot-transcript-rows.ts`, `renderer/main/bots/bot-chat-pane.tsx` +- Test: `main/services/bot-runtime/live-projection.test.ts`, `main/handlers/bot-params.test.ts`, `main/handlers/bot-live.test.ts`, `renderer/main/bots/bot-transcript-rows.test.ts`, `renderer/main/bots/bot-chat-pane.test.tsx` + +**Interfaces:** +- Consumes: Task 3's feed and events; Task 7's rows. +- Produces: + - `interface BotQueuedMessage { submissionId: string; mode: "steer" | "followUp"; text: string; imageCount: number }`; `BotLiveSnapshot.queued: BotQueuedMessage[]`; event `{ type: "queued"; queued: BotQueuedMessage[] }`. + - `export function liveQueuedMessages(docs): BotQueuedMessage[]` (routine and hidden inputs are left out). + - `type BotWithdrawResult = "withdrawn" | "started" | "gone"`; `BotSessionService.withdraw(botId, submissionId): Promise`. + - IPC `bots:withdraw` `{ botId, submissionId }`; `parseBotWithdraw(input): { botId: string; submissionId: string }`; `botsApi.withdraw(botId, submissionId): Promise`. + - `BotTranscriptRowOptions.queued?: readonly BotQueuedMessage[]`; row kind `{ kind: "queued"; id: string; submissionId: string; text: string }`. + +- [ ] **Step 1: Write the failing tests** + +In `main/services/bot-runtime/live-projection.test.ts` (add `liveQueuedMessages` to the import): + +```ts +// Test 1 +test("a follow-up sent while the Bot works shows as queued, and Remove withdraws it before it runs", async () => { + const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("never")], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + assert.deepEqual(snapshot.queued, []); + await live.service.send("bot:a", { text: "Plan dinners", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply to stream" }); + const queued = await live.service.send("bot:a", { text: "Also add dessert", requestId: "desk-2", whenBusy: "followUp" }); + await waitFor(() => tape.view?.queued.length === 1, { what: "the queued message" }); + assert.deepEqual(tape.view?.queued, [ + { submissionId: queued.submissionId, mode: "followUp", text: "Also add dessert", imageCount: 0 }, + ]); + assert.equal(await live.service.withdraw("bot:a", queued.submissionId), "withdrawn"); + await waitFor(() => tape.view?.queued.length === 0, { what: "the queued message to leave" }); + await live.service.stop("bot:a"); + await waitFor(() => tape.view?.state.kind === "idle", { what: "the stop" }); + assert.equal(fauxModels.calls(), 1, "the withdrawn follow-up never reached the model"); + assert.equal(visibleText(tape.view).includes("user:Also add dessert"), false); + unsubscribe(); + } finally { + await live.close(); + } +}); + +// Test 2 (Review Focus 3) +test("Remove on a queued message whose turn already started withdraws nothing", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("word ".repeat(30)), slowAnswer()], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "one", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply" }); + const second = await live.service.send("bot:a", { text: "two", requestId: "desk-2", whenBusy: "followUp" }); + await waitFor(() => visibleText(tape.view).includes("user:two"), { what: "the follow-up to start" }); + assert.equal(await live.service.withdraw("bot:a", second.submissionId), "started"); + assert.equal(await live.service.withdraw("bot:a", "999999"), "gone"); + await live.service.stop("bot:a"); + unsubscribe(); + } finally { + await live.close(); + } +}); + +// Test 3 +test("queued routine and hidden prompts are not shown as the person's messages", () => { + const notice = (data: unknown) => ({ id: 1, mode: "write", entry: { kind: "aiden.bot-notice", data } }); + assert.deepEqual( + liveQueuedMessages({ + "pi.inbox": { + items: [ + notice({ notice: "routine", label: "Morning check-in", requestId: "routine:r1:1" }), + { id: 2, mode: "followUp", content: "Check in on today" }, + notice({ notice: "hidden_input", requestId: "intro:1" }), + { id: 4, mode: "followUp", content: "Introduce yourself" }, + { id: 5, mode: "steer", content: [{ type: "text", text: "Make it vegetarian" }, { type: "image", data: "AA", mimeType: "image/png" }] }, + ], + }, + }), + [{ submissionId: "5", mode: "steer", text: "Make it vegetarian", imageCount: 1 }], + ); + assert.deepEqual(liveQueuedMessages({}), []); +}); +``` + +In `main/handlers/bot-params.test.ts` (add `parseBotWithdraw` to the import): + +```ts +test("Remove names an exact Bot and one numeric submission id", () => { + assert.deepEqual(parseBotWithdraw({ botId: "bot-1", submissionId: "42" }), { botId: "bot-1", submissionId: "42" }); + assert.throws(() => parseBotWithdraw({ botId: "bot-1", submissionId: "42; drop" }), /submission/u); + assert.throws(() => parseBotWithdraw({ botId: "bot-1", submissionId: "42", extra: true }), /withdraw fields/u); + assert.throws(() => parseBotWithdraw({ botId: "../x", submissionId: "1" }), /bot id/u); +}); +``` + +In `renderer/main/bots/bot-transcript-rows.test.ts`: + +```ts +test("a queued follow-up is a faded row at the end, and a steer is a normal bubble right away", () => { + const rows = botTranscriptRows([user("u1", "Plan dinner")], null, { + running: true, + level: "quiet", + queued: [ + { submissionId: "7", mode: "steer", text: "Make it vegetarian", imageCount: 0 }, + { submissionId: "8", mode: "followUp", text: "", imageCount: 2 }, + { submissionId: "9", mode: "followUp", text: "", imageCount: 0 }, + ], + }); + assert.deepEqual(rows.slice(1), [ + { kind: "user", id: "queued:7", text: "Make it vegetarian" }, + { kind: "queued", id: "queued:8", submissionId: "8", text: "2 photos" }, + ]); +}); +``` + +In `renderer/main/bots/bot-chat-pane.test.tsx`: + +```tsx +test("a queued message shows faded as Queued, and Remove withdraws that one submission", async () => { + const calls = await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [userEntry("u1", "Plan dinners")], + state: { kind: "running", submissionId: "s1" }, + queued: [{ submissionId: "8", mode: "followUp", text: "Also add dessert", imageCount: 0 }], + }), + "bots:withdraw": () => "withdrawn", + }); + assert.ok(await screen.findByText("Also add dessert")); + assert.ok(screen.getByText("Queued")); + fireEvent.click(screen.getByRole("button", { name: "Remove queued message" })); + await waitFor(() => + assert.deepEqual(calls.find((call) => call.channel === "bots:withdraw")?.args, [{ botId: "bot-1", submissionId: "8" }]), + ); +}); +``` + +Add `queued: [],` to the `snapshot()` helper defaults here and to the fake snapshot in `main/handlers/bot-live.test.ts`. + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test main/services/bot-runtime/live-projection.test.ts main/handlers/bot-params.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: FAIL. `snapshot.queued` is undefined, `withdraw` is not a function, `parseBotWithdraw` is not exported, and the queued options are ignored. + +- [ ] **Step 3: Types and events** + +In `renderer/shared/bot-live.ts`, add: + +```ts +/** A message waiting for the running turn: a follow-up (queued) or a steer (joins at the next step). */ +export interface BotQueuedMessage { + /** The durable submission id; Remove withdraws it. */ + submissionId: string; + mode: "steer" | "followUp"; + text: string; + imageCount: number; +} +``` + +Add `queued: BotQueuedMessage[];` to `BotLiveSnapshot`, `| { type: "queued"; queued: BotQueuedMessage[] }` to `BotLiveEventBody`, and to `applyBotLiveEvent`: + +```ts + case "queued": + return { ...snapshot, seq: event.seq, queued: event.queued }; +``` + +- [ ] **Step 4: Project `pi.inbox`** + +In `main/services/bot-runtime/live-projection.ts`, add `type BotQueuedMessage` to the `bot-live.js` import and, below `liveBotActivity`: + +```ts +/** + * Inputs waiting in `pi.inbox`, as the person sent them. A routine's input and + * the hidden self-intro are preceded by their notice write and are not shown. + */ +export function liveQueuedMessages(docs: Readonly>): BotQueuedMessage[] { + const items = (docs["pi.inbox"] as { items?: unknown } | undefined)?.items; + if (!Array.isArray(items)) return []; + const queued: BotQueuedMessage[] = []; + let skipNext = false; + for (const value of items) { + const item = value as { id?: unknown; mode?: unknown; content?: unknown; entry?: { kind?: unknown; data?: unknown } }; + if (item.mode === "write") { + const notice = (item.entry?.data as { notice?: unknown } | undefined)?.notice; + if (item.entry?.kind === BOT_NOTICE_ENTRY_KIND && (notice === "routine" || notice === "hidden_input")) skipNext = true; + continue; + } + if (item.mode !== "steer" && item.mode !== "followUp") continue; + if (skipNext) { + skipNext = false; + continue; + } + const content = item.content as UserContent | undefined; + if (content === undefined || (typeof item.id !== "number" && typeof item.id !== "string")) continue; + queued.push({ submissionId: String(item.id), mode: item.mode, text: textOf(content), imageCount: imageCount(content) }); + } + return queued; +} +``` + +Add `queued: BotQueuedMessage[];` to `Feed`, `queued: feed.queued,` to `snapshotOf`, and `queued: liveQueuedMessages(initial.docs),` to the `openFeed` literal. In `onFrame`, directly after the `partial` block: + +```ts + const queued = liveQueuedMessages(docs); + if (JSON.stringify(queued) !== JSON.stringify(feed.queued)) { + feed.queued = queued; + emit(feed, { type: "queued", queued }); + } +``` + +- [ ] **Step 5: Withdraw in the session service** + +In `main/services/bot-runtime/bot-session-service.ts`: + +```ts +/** Remove's outcome: withdrawn before it ran, already started, or no longer waiting. */ +export type BotWithdrawResult = "withdrawn" | "started" | "gone"; +``` + +Add to `BotSessionService`: + +```ts + /** + * Withdraw one queued message before its turn starts (Pi's + * `abortSubmission`). A message already placed in a turn keeps running. + */ + withdraw(botId: string, submissionId: string): Promise; +``` + +and to the `service` object: + +```ts + withdraw(botId, submissionId) { + return serialize(botId, async () => { + await openBot(botId); + const opened = await requireHost().open(botId); + const result = await opened.harness.abortSubmission( + Number(submissionId) as SubmissionId, + ctx, + opened.conversation.id, + ); + if (result === "aborted") return "withdrawn"; + return result === "already_placed" ? "started" : "gone"; + }); + }, +``` + +If `npm run type-check` reports a hand-written `BotSessionService` fake elsewhere, add `withdraw: async () => "gone" as const` to it. + +- [ ] **Step 6: IPC** + +`main/handlers/bot-params.ts`: + +```ts +const BOT_SUBMISSION_ID = /^\d{1,16}$/u; + +/** Remove on a queued message: the Bot and one durable submission id. */ +export function parseBotWithdraw(input: unknown): { botId: string; submissionId: string } { + if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid bot withdraw fields."); + const fields = input as Record; + if (!Object.keys(fields).every((key) => key === "botId" || key === "submissionId")) { + throw new Error("Invalid bot withdraw fields."); + } + if (typeof fields.submissionId !== "string" || !BOT_SUBMISSION_ID.test(fields.submissionId)) { + throw new Error("Invalid bot submission id."); + } + return { botId: parseBotId(fields.botId), submissionId: fields.submissionId }; +} +``` + +`main/handlers/bots.ts`: import `parseBotWithdraw` and, next to `bots:stop`: + +```ts + ipcMain.handle("bots:withdraw", async (_event, input: unknown) => { + const { botId, submissionId } = parseBotWithdraw(input); + return (await botSessionRuntime()).withdraw(botId, submissionId); + }); +``` + +`renderer/lib/ipc.ts`, in `botsApi` after `stop`: + +```ts + /** Remove a queued message before its turn starts. */ + withdraw: (botId: string, submissionId: string) => + invoke("bots:withdraw", { + botId, + submissionId, + }), +``` + +- [ ] **Step 7: Rows and the Queued bubble** + +`renderer/main/bots/bot-transcript-rows.ts`: import `type BotQueuedMessage` from `../../shared/bot-live`. Add `queued?: readonly BotQueuedMessage[];` to `BotTranscriptRowOptions` and destructure it. Add the row kind: + +```ts + /** A follow-up waiting for the running turn; shown faded with Remove. */ + | { kind: "queued"; id: string; submissionId: string; text: string } +``` + +Before `return rows;`: + +```ts + for (const message of queued ?? []) { + const text = message.text.trim() + ? message.text + : message.imageCount === 1 + ? "Photo" + : message.imageCount > 1 + ? `${message.imageCount} photos` + : ""; + if (!text) continue; + // A steer joins the running turn: it reads as sent right away (§6). + if (message.mode === "steer") rows.push({ kind: "user", id: `queued:${message.submissionId}`, text }); + else rows.push({ kind: "queued", id: `queued:${message.submissionId}`, submissionId: message.submissionId, text }); + } +``` + +`renderer/main/bots/bot-chat-pane.tsx`: + +1. Add the component above `TranscriptEntries`: + +```tsx +/** A follow-up waiting for the running turn: a faded bubble, "Queued", and Remove. */ +function BotQueuedBubble({ text, removing, onRemove }: { text: string; removing: boolean; onRemove(): void }) { + return ( +
+
+ +
+
+ Queued + +
+
+ ); +} +``` + +2. `TranscriptEntries` gains props `queued: readonly BotQueuedMessage[]`, `removing: string | null` and `onRemoveQueued(submissionId: string): void`. Pass `queued` into `botTranscriptRows(entries, partial, { running, level, queued })`, and add: + +```tsx + case "queued": + return ( + onRemoveQueued(row.submissionId)} + /> + ); +``` + +3. In `BotChatPane`, add `const [removing, setRemoving] = React.useState(null);` and, next to `stop`: + +```tsx + const removeQueued = async (submissionId: string) => { + setRemoving(submissionId); + try { + const result = await botsApi.withdraw(current.id, submissionId); + if (result === "started") toast.info("That message already started, so it stays."); + } catch (error) { + toast.error(userFacingErrorMessage(error, "Aiden couldn’t remove that message.")); + } finally { + setRemoving(null); + } + }; +``` + + Then pass `queued={snapshot.queued}`, `removing={removing}` and `onRemoveQueued={(id) => void removeQueued(id)}` to `TranscriptEntries`. Import `type BotQueuedMessage` from `../../shared/bot-live`. + +4. Add `snapshot?.queued.length,` to `autoScrollDeps`. + +The composer already sends `onQueue` as `whenBusy: "followUp"` and `onSteer` as `"steer"`. No composer change is needed. + +- [ ] **Step 8: Run the tests to verify they pass** + +Run: `npx tsx --test main/services/bot-runtime/live-projection.test.ts main/handlers/bot-params.test.ts main/handlers/bot-live.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.test.tsx` +Expected: PASS. + +Run: `npx tsx --test main/handlers/ipc-contract.test.ts && npm run type-check` +Expected: PASS. The AST inventory sees `bots:withdraw` both registered in main and invoked by `ipc.ts`. + +- [ ] **Step 9: Commit** + +```bash +git add renderer/shared/bot-live.ts main/services/bot-runtime/live-projection.ts main/services/bot-runtime/live-projection.test.ts main/services/bot-runtime/bot-session-service.ts main/handlers/bots.ts main/handlers/bot-params.ts main/handlers/bot-params.test.ts main/handlers/bot-live.test.ts renderer/lib/ipc.ts renderer/main/bots/bot-transcript-rows.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-chat-pane.tsx renderer/main/bots/bot-chat-pane.test.tsx +git commit -m "Bots: queued follow-ups show faded with Remove; steers show at once" +``` + +--- + +### Task 9: Advanced → Chat activity, with live previews + +**Files:** +- Create: `renderer/main/bots/bot-chat-activity-page.tsx` +- Test: `renderer/main/bots/bot-chat-activity-page.test.tsx` +- Modify: `renderer/main/bots/bot-page-search.ts`, `renderer/main/bots-view.tsx`, `renderer/main/bots/bot-advanced.tsx` +- Modify: `package.json` (`test:bots`), `scripts/ci-test-registry.json` + +**Interfaces:** +- Consumes: `BotStatusLine` (Task 5); `BotActivityRecap`, `BotRecapStep` (Task 6); `resolveBotChatActivity`, `BotChatActivity*` (Task 4); `updateBotIdentity` (Task 4); `prefersReducedMotion` from `renderer/lib/appearance-runtime.ts`; `BotPageShell`. +- Produces: + - `BOT_CHAT_ACTIVITY_LEVEL_LABELS`, `BOT_CHAT_ACTIVITY_WORDING_LABELS`, `botChatActivitySummary(value?: BotChatActivity): string` ("Quiet · Follows the work"). + - `BotChatActivityPage({ bot, onClose })`; `BotChatActivityPreview({ level, wording, label, name })`. + - `BotSubpage` gains `"chat-activity"`; `BotAdvanced` gains `onOpenChatActivity(): void`. + +- [ ] **Step 1: Write the failing tests** + +```tsx +// renderer/main/bots/bot-chat-activity-page.test.tsx +import { installBotTestIpc } from "./test-dom"; +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react"; +import type { BotDefinition, BotUpdateInput } from "../../shared/bots"; +import { BotsView } from "../bots-view"; +import { botFixture, catalogFixture } from "./test-fixtures"; +import { mountWithBotRouter } from "./test-providers"; + +afterEach(() => { + cleanup(); + delete document.documentElement.dataset.reduceMotion; +}); + +function store(initial: BotDefinition, options: { failUpdate?: boolean } = {}) { + let bot = initial; + const updates: BotUpdateInput[] = []; + installBotTestIpc({ + "bots:list": () => [bot], + "bots:get": () => bot, + "bots:update": (input) => { + const update = input as BotUpdateInput; + updates.push(update); + if (options.failUpdate) throw new Error("This Bot changed on another surface. Refresh it and try again."); + const { id: _id, expectedRevision: _revision, ...fields } = update; + bot = { ...bot, ...fields, revision: `${bot.revision}+` }; + return bot; + }, + "bots:getCapabilityCatalog": () => catalogFixture(), + "bots:getBotAccess": () => ({ + access: { botId: "bot-1", revision: "acc-1", policyEpoch: "e", summary: "", accessMode: "full" }, + modelSelection: { providerId: "prov-text", modelId: "model-text" }, + visionModelSelection: { providerId: "prov-vision", modelId: "model-vision" }, + }), + "bots:getTelegramBinding": () => null, + }); + return { updates, current: () => bot }; +} + +// Test 1 +test("Advanced shows the current choice and opens Chat activity; Back returns to Advanced", async () => { + store(botFixture({ chatActivity: { level: "summary", wording: "follows" } })); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=advanced" }); + const row = await screen.findByRole("button", { name: "Chat activity" }); + assert.ok(within(row).getByText("Summary · Follows the work")); + fireEvent.click(row); + assert.ok(await screen.findByRole("heading", { name: "Chat activity" })); + fireEvent.click(screen.getByRole("button", { name: "Back" })); + assert.ok(await screen.findByRole("radiogroup", { name: "What it can use" })); +}); + +// Test 2 +test("each choice saves as it is picked, with the Bot's revision and nothing else changed", async () => { + const bots = store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + assert.equal((within(level).getByRole("radio", { name: "Quiet" }) as HTMLButtonElement).getAttribute("data-state"), "checked"); + fireEvent.click(within(level).getByRole("radio", { name: "Detailed" })); + await waitFor(() => assert.equal(bots.updates.length, 1)); + assert.deepEqual(bots.updates[0]!.chatActivity, { level: "detailed", wording: "follows" }); + assert.equal(bots.updates[0]!.expectedRevision, "rev-1"); + assert.equal(bots.updates[0]!.name, "Planner"); + const wording = screen.getByRole("radiogroup", { name: "What the status line says" }); + fireEvent.click(within(wording).getByRole("radio", { name: "Always “Thinking”" })); + await waitFor(() => assert.equal(bots.updates.length, 2)); + assert.deepEqual(bots.updates[1]!.chatActivity, { level: "detailed", wording: "thinking" }); + assert.equal(bots.updates[1]!.expectedRevision, "rev-1+"); + assert.equal(screen.queryByRole("button", { name: "Save" }), null, "no Save button on this page"); +}); + +// Test 3 (Review Focus 4) +test("a choice that fails to save goes back to the saved one", async () => { + store(botFixture(), { failUpdate: true }); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + fireEvent.click(within(level).getByRole("radio", { name: "Summary" })); + await waitFor(() => + assert.equal(within(level).getByRole("radio", { name: "Quiet" }).getAttribute("data-state"), "checked"), + ); +}); + +// Test 4 +test("under Reduce Motion each preview is a still frame with Play, built from the real status line", async () => { + document.documentElement.dataset.reduceMotion = "true"; + store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + await screen.findByRole("radiogroup", { name: "How much to show" }); + const follows = document.querySelector('[data-bot-chat-activity-preview="wording-follows"]') as HTMLElement; + const thinking = document.querySelector('[data-bot-chat-activity-preview="wording-thinking"]') as HTMLElement; + assert.ok(within(follows).getByText("Searching the web")); + assert.ok(within(thinking).getByText("Thinking")); + const play = screen.getByRole("button", { name: "Play preview: Detailed" }); + fireEvent.click(play); + assert.ok(screen.getByRole("button", { name: "Pause preview: Detailed" })); + // The phones group explains that phones always show just the line. + assert.ok(screen.getByText("Always just the line, with the same words.")); +}); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test renderer/main/bots/bot-chat-activity-page.test.tsx` +Expected: FAIL. Advanced has no "Chat activity" row, and `?page=chat-activity` falls back to Profile. + +- [ ] **Step 3: Write the page and previews** + +```tsx +// renderer/main/bots/bot-chat-activity-page.tsx +// Advanced → Chat activity (spec §7): how much a Bot chat shows while the Bot +// works, and what its status line says, each choice with a looping preview +// built from the real status line and recap. Choices save as they are picked. +// Previews pause off-screen; under Reduce Motion they hold a still frame with +// Play. Radio rows show selection with the radio and background, no borders. + +import * as React from "react"; +import { Pause, Play } from "lucide-react"; +import { useQueryClient } from "@tanstack/react-query"; +import { Button, Field, FieldSet, Label, RadioGroup, RadioGroupItem, toast } from "../../components/ui"; +import { prefersReducedMotion } from "../../lib/appearance-runtime"; +import { userFacingErrorMessage } from "../../lib/ipc-error"; +import type { BotToolPhase } from "../../shared/bot-activity"; +import { + resolveBotChatActivity, + type BotChatActivity, + type BotChatActivityLevel, + type BotChatActivityWording, + type BotDefinition, +} from "../../shared/bots"; +import { BotActivityRecap } from "./bot-activity-recap"; +import type { BotRecapStep } from "./bot-activity-steps"; +import { updateBotIdentity } from "./bot-identity"; +import { BotPageShell } from "./bot-page-shell"; +import { BotStatusLine } from "./bot-status-line"; + +export const BOT_CHAT_ACTIVITY_LEVEL_LABELS: Record = { + quiet: "Quiet", + summary: "Summary", + detailed: "Detailed", +}; + +export const BOT_CHAT_ACTIVITY_WORDING_LABELS: Record = { + follows: "Follows the work", + thinking: "Always “Thinking”", +}; + +/** Advanced's trailing value: "Quiet · Follows the work". */ +export function botChatActivitySummary(value?: BotChatActivity): string { + const resolved = resolveBotChatActivity(value); + return `${BOT_CHAT_ACTIVITY_LEVEL_LABELS[resolved.level]} · ${BOT_CHAT_ACTIVITY_WORDING_LABELS[resolved.wording]}`; +} + +const LEVEL_CHOICES: ReadonlyArray<{ value: BotChatActivityLevel; description: string; recommended?: true }> = [ + { value: "quiet", description: "One line that says what it’s doing.", recommended: true }, + { value: "summary", description: "Adds a short recap above each reply." }, + { value: "detailed", description: "Also shows its last few steps while it works." }, +]; + +const WORDING_CHOICES: ReadonlyArray<{ value: BotChatActivityWording; description: string }> = [ + { value: "follows", description: "Says what it’s doing, like Reading or Searching the web." }, + { value: "thinking", description: "One calm word, whatever it’s doing." }, +]; + +const PREVIEW_STEPS: readonly BotRecapStep[] = [ + { id: "p1", kind: "reading", label: "Read 1 file", detail: "recipes.md", status: "ok" }, + { id: "p2", kind: "searching", label: "Searched the web", detail: "quick weeknight dinners", status: "ok" }, + { id: "p3", kind: "editing", label: "Edited 1 file", detail: "meal-plan.md", status: "ok" }, +]; + +/** One scripted turn: think, read, search, edit, reply. `step` indexes `PREVIEW_STEPS`. */ +const PREVIEW_FRAMES: ReadonlyArray<{ ms: number; phase?: "thinking" | BotToolPhase; step?: number }> = [ + { ms: 1_400, phase: "thinking" }, + { ms: 1_600, phase: "reading", step: 0 }, + { ms: 1_600, phase: "searching", step: 1 }, + { ms: 1_400, phase: "editing", step: 2 }, + { ms: 2_800 }, +]; +/** Reduce Motion's still frame: mid-turn, with a step and the line showing. */ +const STILL_FRAME = 2; +const PREVIEW_STARTED_AT = 0; + +export function BotChatActivityPreview({ + level, + wording, + label, + name, +}: { + level: BotChatActivityLevel; + wording: BotChatActivityWording; + /** For the Play control's name: "Play preview: Detailed". */ + label: string; + /** A stable hook for this preview, such as `level-quiet`. */ + name: string; +}) { + const ref = React.useRef(null); + const [reduced] = React.useState(() => prefersReducedMotion()); + const [playing, setPlaying] = React.useState(!reduced); + const [visible, setVisible] = React.useState(true); + const [tick, setTick] = React.useState(reduced ? STILL_FRAME : 0); + + React.useEffect(() => { + const node = ref.current; + if (!node || typeof IntersectionObserver === "undefined") return; + const observer = new IntersectionObserver((entries) => setVisible(entries.some((entry) => entry.isIntersecting))); + observer.observe(node); + return () => observer.disconnect(); + }, []); + + React.useEffect(() => { + if (!playing || !visible) return; + const frame = PREVIEW_FRAMES[tick % PREVIEW_FRAMES.length]!; + const timer = window.setTimeout(() => setTick((value) => value + 1), frame.ms); + return () => window.clearTimeout(timer); + }, [playing, visible, tick]); + + const frame = PREVIEW_FRAMES[tick % PREVIEW_FRAMES.length]!; + const loop = Math.floor(tick / PREVIEW_FRAMES.length); + const replied = frame.phase === undefined; + const done = replied ? PREVIEW_STEPS.length : (frame.step ?? 0); + const steps: BotRecapStep[] = [ + ...PREVIEW_STEPS.slice(0, done), + ...(frame.step !== undefined ? [{ ...PREVIEW_STEPS[frame.step]!, status: "running" as const }] : []), + ]; + const showRecap = level === "detailed" ? steps.length > 0 : level === "summary" && replied; + const current = frame.step !== undefined ? PREVIEW_STEPS[frame.step] : undefined; + + return ( +
+ + {reduced ? ( + + ) : null} +
+ ); +} + +function ChoiceRow({ + value, + label, + description, + recommended, + preview, +}: { + value: string; + label: string; + description: string; + recommended?: boolean; + preview: React.ReactNode; +}) { + return ( +
+ +
{preview}
+
+ ); +} + +export function BotChatActivityPage({ bot, onClose }: { bot: BotDefinition; onClose(): void }) { + const qc = useQueryClient(); + const [value, setValue] = React.useState(() => resolveBotChatActivity(bot.chatActivity)); + const queue = React.useRef>(Promise.resolve()); + + const pick = (next: BotChatActivity) => { + const previous = value; + if (next.level === previous.level && next.wording === previous.wording) return; + setValue(next); + queue.current = queue.current.then(async () => { + try { + await updateBotIdentity(qc, bot.id, { chatActivity: next }); + } catch (error) { + setValue(previous); + toast.error(userFacingErrorMessage(error, "Aiden couldn’t save that choice.")); + } + }); + }; + + return ( + +
+ + pick({ ...value, level: level as BotChatActivityLevel })} + > + {LEVEL_CHOICES.map((choice) => ( + + } + /> + ))} + + +
+
+ + pick({ ...value, wording: wording as BotChatActivityWording })} + > + {WORDING_CHOICES.map((choice) => ( + + } + /> + ))} + + +
+
+ + + +
+
+ ); +} +``` + +If `Field`'s `description` renders only alongside a `label`, pass `label="Always just the line"` with `description="With the same words as on the Mac."` instead, and update test 4's text to match. Check `renderer/components/ui` before choosing. + +- [ ] **Step 4: Route it and add the Advanced row** + +`renderer/main/bots/bot-page-search.ts`: + +```ts +/** A Bot page reached from its Profile; `/bots/$botId?page=advanced` opens Advanced directly. */ +export type BotSubpage = "instructions" | "advanced" | "memory" | "chat-activity"; + +const SUBPAGES: ReadonlySet = new Set(["instructions", "advanced", "memory", "chat-activity"]); +``` + +`renderer/main/bots-view.tsx`: import `BotChatActivityPage` and change the page switch: + +```tsx + ) : page === "advanced" ? ( + openPage("chat-activity")} + /> + ) : page === "chat-activity" ? ( + openPage("advanced")} /> + ) : page === "memory" ? ( +``` + +`renderer/main/bots/bot-advanced.tsx`: + +1. Import `ChevronRight` from `lucide-react` and `botChatActivitySummary` from `./bot-chat-activity-page`. +2. Change the signature to `export function BotAdvanced({ bot, onClose, onOpenChatActivity }: { bot: BotDefinition; onClose(): void; onOpenChatActivity(): void })`. +3. Below `const guard = useDiscardChangesGuard({ … });`, add a second guard so unsaved access edits are not lost silently: + +```tsx + const chatActivityGuard = useDiscardChangesGuard({ + dirty, + onLeave: onOpenChatActivity, + description: `Your changes to ${bot.name}’s Advanced settings won’t be saved.`, + }); +``` + +4. Directly before ``, add: + +```tsx +
+ +
+``` + + and `{chatActivityGuard.dialog}` next to `{guard.dialog}`. + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `npx tsx --test renderer/main/bots/bot-chat-activity-page.test.tsx renderer/main/bots/bot-profile.test.tsx` +Expected: PASS. Profile and Advanced behaviour is otherwise unchanged. + +- [ ] **Step 6: Register and look at it** + +Append ` renderer/main/bots/bot-chat-activity-page.test.tsx` to `test:bots`. In `scripts/ci-test-registry.json`, add `"renderer/main/bots/bot-chat-activity-page.test.tsx",` after the Task 6 entry. + +Run: `npm run test:ci-policy && npm run type-check` +Expected: PASS. + +Run the app (`npm run dev`, or use the `run` skill). Open a Bot → ••• → Advanced → Chat activity in light and dark, and with Settings → Appearance → Reduce Motion on and off. Confirm: +- the rows have no borders and the selected row uses the selection background; +- the arrow keys move within each radio group, with a visible focus ring; +- the previews loop with motion on and hold a still frame with Play under Reduce Motion; +- choosing Detailed shows the open live recap in a real chat. + +- [ ] **Step 7: Commit** + +```bash +git add renderer/main/bots/bot-chat-activity-page.tsx renderer/main/bots/bot-chat-activity-page.test.tsx renderer/main/bots/bot-page-search.ts renderer/main/bots-view.tsx renderer/main/bots/bot-advanced.tsx package.json scripts/ci-test-registry.json +git commit -m "Bots: Advanced → Chat activity with live previews, saved on pick" +``` + +--- + +### Task 10: Faces glance while their Bot works + +**Files:** +- Modify: `renderer/components/aiden-activity-mark.tsx`, `renderer/components/bot-avatar.tsx`, `renderer/styles.css`, `renderer/main/bots/bot-chat-header.tsx`, `renderer/main/bots/bot-chat-pane.tsx`, `renderer/main/bots/bot-list.tsx` +- Test: `renderer/main/bots/bot-list.test.tsx`, `renderer/main/bots/bot-chat-pane.test.tsx` + +**Interfaces:** +- Consumes: `AidenActivityMark` and the `aiden-mark-look`/`aiden-mark-blink` keyframes in `styles.css`. +- Produces: + - `observeOffscreen(node: Element): () => void` (exported from `aiden-activity-mark.tsx`, sharing its observer). + - `BotAvatar` gains `working?: boolean`, and its root carries `data-working` while working. A canonical face glances; a photo shows a `glance` mark badge. + - `BotChatNamePill` gains `working?: boolean`. + +- [ ] **Step 1: Write the failing tests** + +In `renderer/main/bots/bot-list.test.tsx`: + +```tsx +test("a working Bot's face is marked working; an idle one is not", () => { + renderList([ + { bot: bot("b1", "Runner"), state: { kind: "running", submissionId: "s1" } }, + { bot: bot("b2", "Sleeper"), state: { kind: "idle" } }, + ]); + assert.equal(screen.getByTitle("Runner").hasAttribute("data-working"), true); + assert.equal(screen.getByTitle("Sleeper").hasAttribute("data-working"), false); + assert.ok(within(screen.getByRole("button", { name: /^Runner/u })).getByText("Working")); +}); +``` + +In `renderer/main/bots/bot-chat-pane.test.tsx`: + +```tsx +test("the chat header's face works while the Bot works, and a photo gets a small activity badge", async () => { + await mountChat({ + "bots:getCanonicalPhoto": () => ({ assetRevision: "a1", dataUrl: "data:image/png;base64,AAAA" }), + "bots:live:subscribe": () => + snapshot({ state: { kind: "running", submissionId: "s1" }, activity: { phase: "thinking", startedAt: Date.now() } }), + }); + const pill = await screen.findByRole("button", { name: "Planner profile" }); + const face = within(pill).getByTitle("Planner"); + assert.equal(face.hasAttribute("data-working"), true); + await waitFor(() => assert.ok(face.querySelector('[data-aiden-mark="glance"]'))); +}); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npx tsx --test renderer/main/bots/bot-list.test.tsx renderer/main/bots/bot-chat-pane.test.tsx` +Expected: FAIL. `data-working` is absent. + +- [ ] **Step 3: Share the off-screen observer** + +In `renderer/components/aiden-activity-mark.tsx`, change the observer callback to `(entry.target as Element).toggleAttribute("data-offscreen", !entry.isIntersecting);` and add below `visibilityObserver`: + +```ts +/** Pause an element's animations while it is scrolled out of view (`data-offscreen`), on the shared observer. */ +export function observeOffscreen(node: Element): () => void { + const observer = visibilityObserver(); + if (!observer) return () => undefined; + observer.observe(node); + return () => observer.unobserve(node); +} +``` + +Use it in `AidenActivityMark`'s first effect: `React.useEffect(() => { const node = ref.current; return node ? observeOffscreen(node) : undefined; }, []);`. + +- [ ] **Step 4: Working faces** + +In `renderer/components/bot-avatar.tsx`: + +1. Import `{ AidenActivityMark, observeOffscreen } from "./aiden-activity-mark"`. +2. Replace `EyeMark` so each eye can blink as one shape and both can glance: + +```tsx +/** The one fixed eye mark every Bot shares; only colour and shape vary. Eyes glance while working. */ +function EyeMark({ y, spread }: { y: number; spread: number }) { + return ( + + {[20 - spread, 20 + spread].map((x) => ( + + + + + ))} + + ); +} +``` + +3. Add `working = false,` and `working?: boolean;` to `BotAvatar`'s props. Below the photo state: + +```tsx + React.useEffect(() => { + const node = avatarRef.current; + if (!working || !node) return; + return observeOffscreen(node); + }, [working]); +``` + +4. On the root ``, add `data-working={working ? "" : undefined}` and prefix its className with `bot-avatar `. After the `` block, add: + +```tsx + {showPhoto && working ? ( + + + + ) : null} +``` + +`renderer/styles.css`: directly after the `/* Bounce: the typing trio. */` block, add: + +```css +/* Bot faces glance and blink while their Bot works (spec §6), reusing the glance + keyframes. Motion runs only with Reduce Motion off and on screen; otherwise the + face holds its still pose. */ +:root[data-reduce-motion="false"] .bot-avatar[data-working] .bot-avatar-eyes { animation: aiden-mark-look 4s cubic-bezier(.5, 0, .3, 1) infinite; } +:root[data-reduce-motion="false"] .bot-avatar[data-working] .bot-avatar-eye { transform-box: fill-box; transform-origin: center; animation: aiden-mark-blink 4s ease-in-out infinite; } +.bot-avatar[data-offscreen] * { animation-play-state: paused !important; } +@media (prefers-reduced-motion: reduce) { + .bot-avatar[data-working] * { animation: none !important; } +} +``` + +- [ ] **Step 5: Use it where Bots are listed and chatted with** + +`renderer/main/bots/bot-chat-header.tsx`: add `working?: boolean` to `BotChatNamePill`'s props (default `false`) and pass `working={working}` to its `BotAvatar`. + +`renderer/main/bots/bot-chat-pane.tsx`: in `shell`'s `title`, pass `working={running}` to `BotChatNamePill`. + +`renderer/main/bots/bot-list.tsx`: pass `working={working}` to the row's `BotAvatar`, and delete the green dot `` block. The face, or the photo badge, is now the indicator. Keep the `sr-only` "Working" text. + +- [ ] **Step 6: Run the tests to verify they pass** + +Run: `npx tsx --test renderer/main/bots/bot-list.test.tsx renderer/main/bots/bot-chat-pane.test.tsx renderer/components/aiden-activity-mark.test.tsx renderer/main/bots-view.test.tsx` +Expected: PASS. + +In the running app, confirm that a working Bot's face glances in the list and the header pill. With Reduce Motion on it stays still. A Bot with a photo shows a small glance badge. + +- [ ] **Step 7: Commit** + +```bash +git add renderer/components/aiden-activity-mark.tsx renderer/components/bot-avatar.tsx renderer/styles.css renderer/main/bots/bot-chat-header.tsx renderer/main/bots/bot-chat-pane.tsx renderer/main/bots/bot-list.tsx renderer/main/bots/bot-list.test.tsx renderer/main/bots/bot-chat-pane.test.tsx +git commit -m "Bots: faces glance while their Bot works" +``` + +--- + +### Task 11: Docs, memory, onboarding review and full verification + +**Files:** +- Modify: `docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md` (§6, §17), `docs/plans/README.md`, `.memory/bots-rework-ui.md` +- Create: `.memory/bot-chat-activity.md` + +- [ ] **Step 1: Record the plan's rulings in the spec** + +In §6, replace "The recap reuses `summarizeActivity`. The trail reuses `ActivityFeed` and the `agent-steps` verbs." with: + +> The recap is a Bot-specific fold (`renderer/main/bots/bot-activity-recap.tsx`). It reuses the activity feed's tone tokens, shimmer and row rhythm. Its wording comes from the shared step phrases in `renderer/shared/bot-activity.ts`, because `ActivityFeed` owns its own open state and `summarizeActivity` cannot name apps. + +In §17, add: + +> - **Slice B rulings (2026-10-14):** +> - Pi Durable 1.0.3 withdraws one queued submission (`Harness.abortSubmission`), so the Queued bubble has Remove. +> - Refusals are told from failures by Pi's `blocked` tool diagnostic. +> - `chatActivity` left out of an update keeps the stored value. +> - The app label is read from the MCP agent tool name. +> - A command's detail prefers the model's `description`, and is redacted before it is cut. +> - Always "Thinking" hides the peek. +> - The recap shows red "N issues" and amber "N blocked" separately. +> - The snapshot also carries `queued` from `pi.inbox`. +> - The Bots onboarding tile needed no redraw: it shows neither the list nor the Updates line. + +- [ ] **Step 2: Update the plan index** + +In `docs/plans/README.md`, in the "Bot chat activity…" row that slice A added, after "B quiet status line + per-Bot Chat activity setting", insert ` ([plan](../superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md))`. + +- [ ] **Step 3: Project memory** + +Create `.memory/bot-chat-activity.md`: + +```markdown +# Bot chat activity (2026-10-14) + +Spec: docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md. Slice B plan: docs/superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.md. + +## Slice B (desktop) — what shipped +- Phase vocabulary and tool classifier: `renderer/shared/bot-activity.ts` (shared with main, the CLI, and slice D's phones). Unknown ids → `working`. Always "Thinking" keeps waiting/stopping/reconnecting. +- Main derives `BotLiveSnapshot.activity` + `activity` event in `live-projection.ts` (`liveBotActivity`), gated on session state `running` (a paused Bot still has `pi.live.run`). Stop/Resume reach it through `notifyStopping`/`notifyResuming` in the `bots:stop`/`bots:resume` handlers; approvals refresh it via `botApprovals.onChange`. +- Transcript tool calls carry `kind/label/detail/app` (`bot-activity-detail.ts`, redacted with `sanitizeDiagnosticText` before cutting to 80); tool results carry `status: ok|failed|blocked` (Pi's `blocked` diagnostic) and `durationMs`. +- `BotDefinition.chatActivity?` `{ level: quiet|summary|detailed, wording: follows|thinking }`; absent = Quiet/Follows; an update without it keeps the stored value (Profile and Remote PATCH never reset it). +- Renderer: `BotStatusLine`, `BotActivityRecap` (Bot-specific, not ActivityFeed), progress narration as bubbles (`BotUpdates` and `bot-reply-projection.ts` deleted), "You stopped this reply." derived from `stopReason: "aborted"`. +- Queue/Steer: `pi.inbox` projected as `snapshot.queued`; follow-ups faded with Remove (`bots:withdraw` → `Harness.abortSubmission`), steers as normal bubbles. +- Advanced → Chat activity (`?page=chat-activity`, `bot-chat-activity-page.tsx`), saved on pick through `updateBotIdentity`. +- `BotAvatar working` (glance eyes; photo → glance badge); list's green dot removed. + +## For slice D (phones) +- Remote wire is unchanged by B. D adds `activity` (phase, app ≤ 40, startedAt only) to the session stream and `chatActivity` to detail/PATCH behind `bot-activity-v1`; reuse `botActivityDisplay`, `botElapsedLabel` and `nextBotAnnouncement` semantics and the §5 table as the shared fixture. +``` + +In `.memory/bots-rework-ui.md`: +- In the Chat bullet, replace "and one collapsible "Working…" / "Updates" line" with "a status line while it works (Chat activity: Quiet/Summary/Detailed), recaps for Summary/Detailed, faded Queued bubbles with Remove". +- In the List bullet, replace "avatar with an activity dot" with "avatar whose face glances while working". +- In Key files, add `bot-status-line.tsx`, `bot-activity-recap.tsx`, `bot-activity-steps.ts`, `bot-chat-activity-page.tsx`, `renderer/shared/bot-activity.ts`, `main/services/bot-runtime/bot-activity-detail.ts`. +- In Deleted, add `bot-updates.tsx` and `bot-reply-projection.ts` (2026-10-14). +- Add "See `.memory/bot-chat-activity.md`." + +- [ ] **Step 4: Check the native clients and Remote** + +iOS and Android read Bot sessions only through the Remote wire. Slice B leaves that wire unchanged: `projectBotSessionEntries` picks fields explicitly, and Bot detail does not include `chatActivity`. Confirm with: + +```bash +npm run test:aiden-remote +``` + +Expected: PASS with no fixture changes. The mobile suites are not affected by this slice; slice D runs them. + +- [ ] **Step 5: Run every affected suite** + +```bash +npm run type-check +npm run lint +npm run test:bots +npm run test:bot-runtime +npm run test:ci-policy +npx tsx --test main/handlers/ipc-contract.test.ts main/handlers/bot-live.test.ts +``` + +Expected: all PASS. + +- [ ] **Step 6: Commit** + +```bash +git add docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md docs/plans/README.md .memory/bots-rework-ui.md .memory/bot-chat-activity.md +git commit -m "Docs: slice B rulings, plan index, project memory" +``` diff --git a/docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md b/docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md index 98761fce79..24e65ad0e8 100644 --- a/docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md +++ b/docs/superpowers/specs/2026-10-14-bot-chat-activity-design.md @@ -169,7 +169,7 @@ When a new tool kind ships (a browser, image generation), it gets its own phase | Summary | Same as Quiet. | One collapsed recap above the reply: "Worked for 18s · read 1 file, searched the web, edited 1 file, used Notion". It opens to the step trail. | | Detailed | The status line plus the last three steps, the active one shimmering. | The same recap, open while live and auto-folded when the reply lands. A manual open or close during the run sticks. | -The recap reuses `summarizeActivity`. The trail reuses `ActivityFeed` and the `agent-steps` verbs. Repeats merge: reading six files becomes "Read 6 files", and page visits become "Browsed 3 pages". +The recap is a Bot-specific fold (`renderer/main/bots/bot-activity-recap.tsx`). It reuses the activity feed's tone tokens, shimmer and row rhythm. Its wording comes from the shared step phrases in `renderer/shared/bot-activity.ts`, because `ActivityFeed` owns its own open state and `summarizeActivity` cannot name apps. Repeats merge: reading six files becomes "Read 6 files", and page visits become "Browsed 3 pages". Shown at every level: @@ -362,3 +362,19 @@ Every new test file is registered in the matching `package.json` script and `scr - Workbench shell: its own PR, with C2 stacked on it (decision 12, §4). - Tool categories: §5.1 (decision 13). - Left to the plan: whether Pi Durable can withdraw a single queued submission (decides the Remove button). + +- **Slice B rulings (2026-10-14):** + - Pi Durable 1.0.3 withdraws one queued submission (`Harness.abortSubmission`), so the Queued bubble has Remove. It reports `withdrawn`, `started` or `gone`; only `withdrawn` removes the bubble. + - Refusals are told from failures by Pi's `blocked` tool diagnostic. A fourth result status, `stopped`, covers steps cut off by Stop or a restart; it renders neutrally, never red. + - `chatActivity` left out of an update keeps the stored value. Identity updates merge a partial `chatActivity` onto the freshly read Bot. It is stored last in the Bot record because the revision hashes the record JSON. Remote's identity PATCH still rejects it (slice D). + - The app label is read from the MCP agent tool name. + - A command step never shows the command. It shows only the model's `description`, redacted before it is cut to 80 characters; with no description the step has no detail. + - Always "Thinking" hides the peek. + - The recap shows red "N issues" and amber "N blocked" separately. + - The snapshot also carries `queued` from `pi.inbox`. The queued list holds only the person's own inputs: it is classified by the durable submission request id (`routine:`, `intro:`) plus the hidden flag, and fails closed when an id is missing. + - Run identity is the run's first input (`inputs[0]`), not the generation task id. A Resume is marked by the service's `onResumed` callback inside the per-Bot serialize, and the Stop and Resume flags are scoped to that run, so a double Stop never carries "Stopping" into the next turn. + - Every user entry begins a turn in the transcript rows (Pi Durable places a steer after the round's tool results). + - The status line hides only while reply text streams with no active tool step. Announcements go through sr-only text inside `role="status"`, throttled to one per 2 seconds. + - The Chat activity page saves on pick through a serial queue (a failed save returns the radio to the saved choice with a toast). Each level has its own Reduce Motion still frame, and Reduce Motion is read live. + - Faces glance through `data-working` on the avatar, with one shared off-screen observer. + - The Bots onboarding tile needed no redraw: it shows neither the list nor the Updates line (it draws the name pill, one exchange and a routine chip). diff --git a/main/handlers/bot-live.test.ts b/main/handlers/bot-live.test.ts index 88bac8e2ed..a1c0321d45 100644 --- a/main/handlers/bot-live.test.ts +++ b/main/handlers/bot-live.test.ts @@ -39,12 +39,18 @@ function fakeProjection() { partial: null, state: { kind: "idle" }, question: null, + activity: null, + queued: [], }; return { snapshot, unsubscribe: () => sinks.delete(id) }; }, notifyState: () => undefined, refresh: async () => undefined, refreshQuestion: async () => undefined, + notifyStopping: () => undefined, + notifyResuming: () => undefined, + cancelStopping: () => undefined, + refreshActivity: async () => undefined, summary: async (botId) => ({ botId, preview: "hi", updatedAt: 1, state: { kind: "idle" } }), close: async () => undefined, }; diff --git a/main/handlers/bot-params.test.ts b/main/handlers/bot-params.test.ts index 5b9396beb8..892f409dd4 100644 --- a/main/handlers/bot-params.test.ts +++ b/main/handlers/bot-params.test.ts @@ -9,6 +9,7 @@ import { parseBotSend, parseBotSessionAction, parseBotUpdate, + parseBotWithdraw, } from "./bot-params.js"; test("bot mutation and conversation envelopes are exact and bounded", () => { @@ -188,3 +189,34 @@ test("a Bot approval answer names its waitId and allow or deny, nothing else", ( assert.throws(() => parseBotApprovalDecision({ waitId, decision: "allow", scope: "always" }), /fields/u); assert.throws(() => parseBotApprovalDecision(null), /fields/u); }); + +test("a Bot update may carry an exact chat activity choice, and nothing else new", () => { + const fields = { + id: "bot-1", + expectedRevision: "botrev:one", + name: "Planner", + instructions: "Plan.", + avatar: { version: 1 as const, shape: "hex" as const, color: "sun" as const }, + }; + assert.deepEqual(parseBotUpdate({ ...fields, chatActivity: { level: "detailed", wording: "thinking" } }), { + ...fields, + description: undefined, + chatActivity: { level: "detailed", wording: "thinking" }, + }); + assert.equal("chatActivity" in parseBotUpdate(fields), false); + assert.throws(() => parseBotUpdate({ ...fields, chatActivity: { level: "loud", wording: "follows" } }), /chat activity/u); + assert.throws( + () => parseBotUpdate({ ...fields, chatActivity: { level: "quiet", wording: "follows", extra: 1 } }), + /chat activity/u, + ); + assert.throws(() => parseBotUpdate({ ...fields, chatActivity: "quiet" }), /chat activity/u); +}); + +test("Remove names an exact Bot and one numeric submission id", () => { + assert.deepEqual(parseBotWithdraw({ botId: "bot-1", submissionId: "42" }), { botId: "bot-1", submissionId: "42" }); + assert.throws(() => parseBotWithdraw({ botId: "bot-1", submissionId: "42; drop" }), /submission/u); + assert.throws(() => parseBotWithdraw({ botId: "bot-1", submissionId: "9007199254740993" }), /submission/u, "too long to stay exact"); + assert.deepEqual(parseBotWithdraw({ botId: "bot-1", submissionId: "999999999999999" }).submissionId, "999999999999999"); + assert.throws(() => parseBotWithdraw({ botId: "bot-1", submissionId: "42", extra: true }), /withdraw fields/u); + assert.throws(() => parseBotWithdraw({ botId: "../x", submissionId: "1" }), /bot id/u); +}); diff --git a/main/handlers/bot-params.ts b/main/handlers/bot-params.ts index 9876057c4b..fbf299a614 100644 --- a/main/handlers/bot-params.ts +++ b/main/handlers/bot-params.ts @@ -1,6 +1,7 @@ import { BOT_LIMITS, isBotAvatar, + parseBotChatActivity, type BotCreateInput, type BotUpdateInput, } from "../../renderer/shared/bots.js"; @@ -28,7 +29,7 @@ const CREATE_KEYS = new Set([ "name", ]); const CREATE_WITH_ACCESS_KEYS = new Set(["access", "bot"]); -const UPDATE_KEYS = new Set([...CREATE_KEYS, "expectedRevision", "id"]); +const UPDATE_KEYS = new Set([...CREATE_KEYS, "chatActivity", "expectedRevision", "id"]); const CHAT_KEYS = new Set(["botId", "model", "providerId", "workspaceId"]); const ACCESS_UPDATE_KEYS = new Set(["access", "botId", "expectedRevision"]); function exact(value: unknown, keys: ReadonlySet, label: string) { @@ -102,10 +103,13 @@ export function parseConnectionPluginId(value: unknown): string { export function parseBotUpdate(value: unknown): BotUpdateInput { const record = exact(value, UPDATE_KEYS, "bot update fields"); + const chatActivity = record.chatActivity === undefined ? undefined : parseBotChatActivity(record.chatActivity); + if (record.chatActivity !== undefined && !chatActivity) throw new Error("Invalid bot chat activity."); return { id: parseBotId(record.id), expectedRevision: parseBotRevision(record.expectedRevision), ...createFields(record), + ...(chatActivity ? { chatActivity } : {}), }; } @@ -203,6 +207,22 @@ export function parseBotSessionAction( return { botId: parseBotId(fields.botId), requestId: fields.requestId }; } +/** At most 15 digits, so `Number()` stays exact (below 2^53). */ +const BOT_SUBMISSION_ID = /^\d{1,15}$/u; + +/** Remove on a queued message: the Bot and one durable submission id. */ +export function parseBotWithdraw(input: unknown): { botId: string; submissionId: string } { + if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid bot withdraw fields."); + const fields = input as Record; + if (!Object.keys(fields).every((key) => key === "botId" || key === "submissionId")) { + throw new Error("Invalid bot withdraw fields."); + } + if (typeof fields.submissionId !== "string" || !BOT_SUBMISSION_ID.test(fields.submissionId)) { + throw new Error("Invalid bot submission id."); + } + return { botId: parseBotId(fields.botId), submissionId: fields.submissionId }; +} + const BOT_APPROVAL_WAIT_ID = /^[A-Za-z0-9-]{1,64}$/u; /** A Bot approval answer: the durable `waitId` and allow or deny. */ diff --git a/main/handlers/bots.ts b/main/handlers/bots.ts index d14f64de85..67fd59977c 100644 --- a/main/handlers/bots.ts +++ b/main/handlers/bots.ts @@ -49,6 +49,7 @@ import { parseBotSessionAction, parseBotApprovalDecision, parseBotUpdate, + parseBotWithdraw, } from "./bot-params.js"; async function desktopAvatarAdapter() { @@ -202,9 +203,20 @@ export function registerBotHandlers(): void { const { botId, requestId } = parseBotSessionAction(input, "dismiss"); return (await botSessionRuntime()).dismiss(botId, requestId); }); - ipcMain.handle("bots:stop", async (_event, id: unknown) => - (await botSessionRuntime()).stop(parseBotId(id)), - ); + ipcMain.handle("bots:withdraw", async (_event, input: unknown) => { + const { botId, submissionId } = parseBotWithdraw(input); + return (await botSessionRuntime()).withdraw(botId, submissionId); + }); + ipcMain.handle("bots:stop", async (_event, id: unknown) => { + const botId = parseBotId(id); + botLiveProjection().notifyStopping(botId); + try { + return await (await botSessionRuntime()).stop(botId); + } catch (error) { + botLiveProjection().cancelStopping(botId); + throw error; + } + }); ipcMain.handle("bots:createFromPreset", async (_event, input: unknown) => { const { presetId, access } = parseBotCreateFromPreset(input); const { bot, created } = await botStarter().startFromPreset(presetId, access === undefined ? {} : { access }); diff --git a/main/services/aiden-remote-bots.test.ts b/main/services/aiden-remote-bots.test.ts index a75a3b3262..77b847d9bd 100644 --- a/main/services/aiden-remote-bots.test.ts +++ b/main/services/aiden-remote-bots.test.ts @@ -634,6 +634,16 @@ test("an omitted first-chat pair inherits Bot authority without resolving a new assert.equal(app.resolvedSelections.length, 0); }); +test("a phone cannot set a Bot's chat activity through the identity patch, and the Bot's detail does not carry it", async () => { + const app = fixture(); + const detail = await app.service.get("bot_1"); + await assert.rejects( + app.service.updateIdentity("bot_1", detail.revision, { chatActivity: { level: "summary", wording: "follows" } }), + (error: unknown) => (error as { code?: string }).code === "invalid_request", + ); + assert.equal("chatActivity" in detail, false); +}); + test("stale identity and policy revisions return authoritative conflicts", async () => { const app = fixture(); const detail = await app.service.get("bot_1"); diff --git a/main/services/bot-runtime/bot-activity-detail.test.ts b/main/services/bot-runtime/bot-activity-detail.test.ts new file mode 100644 index 0000000000..cf79cd4f39 --- /dev/null +++ b/main/services/bot-runtime/bot-activity-detail.test.ts @@ -0,0 +1,75 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mcpAgentToolName } from "../mcp-tool-identity.js"; +import { BOT_STEP_DETAIL_CHARS, botStepDescriptor } from "./bot-activity-detail.js"; + +test("a file step names only the file's base name", () => { + assert.deepEqual(botStepDescriptor("read_file", { path: "/Users/sam/Lists/grocery-list.md" }), { + kind: "reading", + label: "Read 1 file", + detail: "grocery-list.md", + }); + assert.deepEqual(botStepDescriptor("edit_file", { path: "notes\\week.md" }), { + kind: "editing", + label: "Edited 1 file", + detail: "week.md", + }); + assert.equal(botStepDescriptor("grep", { pattern: "tofu", path: "recipes" }).detail, "tofu"); +}); + +test("a command step shows only its description, bounded and redacted; the command never appears", () => { + const noDescription = botStepDescriptor("run_command", { + command: "curl -H 'X-Api-Key: hunter2hunter2' https://x.test && mysql -u root -pS3cretPass && cat ~/.ssh/id_rsa && ls /Taxes2025", + }); + assert.deepEqual(noDescription, { kind: "command", label: "Ran a command" }); + const secret = botStepDescriptor("run_command", { + command: "ls", + description: "Export OPENAI_API_KEY=sk-live1234567890abcdef then list /Users/sam/Private", + }); + assert.ok(secret.detail); + assert.doesNotMatch(secret.detail, /sk-live/u); + assert.doesNotMatch(secret.detail, /\/Users\/sam/u); + const long = botStepDescriptor("run_command", { command: "ls", description: "Tidy the notes and ".repeat(20) }).detail ?? ""; + assert.ok([...long].length <= BOT_STEP_DETAIL_CHARS); + assert.ok(long.endsWith("…")); + assert.equal(botStepDescriptor("run_command", { command: "ls -la", description: "List the folder" }).detail, "List the folder"); +}); + +test("invisible format characters are stripped, and a secret-shaped search query is redacted", () => { + const spoofed = botStepDescriptor("web_search", { query: "invoice\u202Egpj.exe \u200Bnow" }).detail; + assert.equal(spoofed, "invoicegpj.exe now"); + const leaky = botStepDescriptor("web_search", { query: "why does token=sk-live1234567890abcdef fail" }).detail; + assert.ok(leaky); + assert.doesNotMatch(leaky, /sk-live/u); + // A secret far past the shown length cannot leak through a long query either. + const far = botStepDescriptor("web_search", { query: `${"word ".repeat(5_000)}sk-live1234567890abcdef` }).detail ?? ""; + assert.doesNotMatch(far, /sk-live/u); + assert.ok([...far].length <= BOT_STEP_DETAIL_CHARS); +}); + +test("a search step shows its query; a connection step names the app and shows no arguments", () => { + assert.deepEqual(botStepDescriptor("web_search", { query: "lisbon trains" }), { + kind: "searching", + label: "Searched the web", + detail: "lisbon trains", + }); + const notion = mcpAgentToolName({ id: "srv-1", name: "Notion" }, "search_pages"); + assert.deepEqual(botStepDescriptor(notion, { query: "private plans" }), { + kind: "app", + label: "Used Notion", + app: "Notion", + }); + assert.deepEqual(botStepDescriptor("ask_user_question", {}), { kind: "waiting", label: "Asked you a question" }); + assert.deepEqual(botStepDescriptor("read_file", "not an object"), { kind: "reading", label: "Read 1 file" }); +}); + +test("an argument of thousands of spaces is cut without stalling the main process", () => { + const started = performance.now(); + const padded = botStepDescriptor("web_search", { query: `tofu${" ".repeat(15_990)}alpha beta gamma delta epsilon` }).detail ?? ""; + const blank = botStepDescriptor("web_search", { query: `${" ".repeat(20_000)}tofu` }).detail; + const elapsed = performance.now() - started; + assert.ok(elapsed < 250, `took ${elapsed.toFixed(0)} ms`); + assert.ok([...padded].length <= BOT_STEP_DETAIL_CHARS); + assert.match(padded, /^tofu/u); + assert.ok(blank === undefined || [...blank].length <= BOT_STEP_DETAIL_CHARS); +}); diff --git a/main/services/bot-runtime/bot-activity-detail.ts b/main/services/bot-runtime/bot-activity-detail.ts new file mode 100644 index 0000000000..32d636d7a8 --- /dev/null +++ b/main/services/bot-runtime/bot-activity-detail.ts @@ -0,0 +1,103 @@ +// One Bot tool call, as the chat may show it (spec §6 "Projection changes"): +// its phase kind, a past-tense label and a short, safe detail. The detail is +// built here in main and only from allow-listed arguments: a file's base name, +// a search query or pattern, or a command's own description (the model's +// plain-words summary). The command itself is never shown: the redactor does +// not know shell shapes (`curl -H 'X-Api-Key: …'`, `mysql -pSecret`). Text +// passes the diagnostic redactor before it is cut to the display length. +// Arguments of connection tools are never shown. + +import { + botStepPhrase, + botToolApp, + botToolPhase, + type BotToolPhase, +} from "../../../renderer/shared/bot-activity.js"; +import { sanitizeDiagnosticText } from "../diagnostics-contract.js"; + +export const BOT_STEP_DETAIL_CHARS = 80; +/** + * Longest argument read before redaction. Far beyond the 80 characters shown, + * and cut at whitespace, so a secret straddling the cut cannot reach the + * visible part as a clipped prefix the redactor no longer recognises. + */ +const RAW_DETAIL_CHARS = 16_000; +/** Invisible format characters (bidi overrides, zero-width marks) can disguise text. */ +const FORMAT_CHARACTERS = /\p{Cf}/gu; + +export interface BotStepDescriptor { + kind: BotToolPhase; + label: string; + detail?: string; + app?: string; +} + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record) : {}; +} + +function stringOf(value: unknown): string | undefined { + return typeof value === "string" && value.trim() ? value : undefined; +} + +function baseName(value: unknown): string | undefined { + const text = stringOf(value); + if (!text) return undefined; + const parts = text.replace(/\\/gu, "/").split("/").filter(Boolean); + return parts[parts.length - 1]; +} + +/** + * Drops the last word and the whitespace before it. A linear scan: the + * equivalent `/\s+\S*$/` backtracks quadratically on long runs of spaces. + */ +function cutAtLastWhitespace(text: string): string { + let end = text.length; + while (end > 0 && !/\s/u.test(text[end - 1]!)) end -= 1; + if (end === 0) return text; + while (end > 0 && /\s/u.test(text[end - 1]!)) end -= 1; + return text.slice(0, end); +} + +function bounded(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const stripped = value.replace(FORMAT_CHARACTERS, ""); + const points = [...stripped]; + const window = + points.length > RAW_DETAIL_CHARS ? cutAtLastWhitespace(points.slice(0, RAW_DETAIL_CHARS).join("")) : stripped; + const clean = sanitizeDiagnosticText(window, RAW_DETAIL_CHARS); + if (!clean) return undefined; + const shown = [...clean]; + return shown.length > BOT_STEP_DETAIL_CHARS + ? `${shown.slice(0, BOT_STEP_DETAIL_CHARS - 1).join("").trimEnd()}…` + : clean; +} + +function rawDetail(toolName: string, kind: BotToolPhase, args: Record): string | undefined { + switch (kind) { + case "reading": + case "editing": + return toolName === "glob" || toolName === "grep" + ? stringOf(args.pattern) + : baseName(args.path ?? args.filePath ?? args.directory); + case "command": + // Only the model's own description; never the command (see the header). + return stringOf(args.description); + case "searching": + return stringOf(args.query); + default: + return undefined; + } +} + +export function botStepDescriptor(toolName: string, args: unknown): BotStepDescriptor { + const app = botToolApp(toolName); + const kind = botToolPhase(toolName, app); + const detail = bounded(rawDetail(toolName, kind, record(args))); + return { + kind, + label: botStepPhrase(kind, 1, app), + ...(detail ? { detail } : {}), + ...(app ? { app } : {}), + }; +} diff --git a/main/services/bot-runtime/bot-extension.test.ts b/main/services/bot-runtime/bot-extension.test.ts index 85398ae8e8..e2d5a4b8cc 100644 --- a/main/services/bot-runtime/bot-extension.test.ts +++ b/main/services/bot-runtime/bot-extension.test.ts @@ -12,9 +12,11 @@ import { renderBotMemorySection } from "../bot-memory/prompt.js"; import { createBotMemoryService, type BotMemoryRuntime } from "../bot-memory/service.js"; import { createBotMemoryStore } from "../bot-memory/store.js"; import { botMemoryToolEntry, withBotMemoryIngress } from "../bot-memory/tool.js"; +import { botTranscriptRows } from "../../../renderer/main/bots/bot-transcript-rows.js"; import { createBotRegistry, type BotExtensionDeps, type BotRegistry } from "./bot-extension.js"; import { botIngressAllowsTool } from "./bot-tool-policy.js"; import { createBotHarnessHost, type BotHarnessHost } from "./harness-host.js"; +import { projectBotTranscript } from "./live-projection.js"; import { spawnHarnessChild } from "./test-support/child.js"; import { countingTool, recordingDeps } from "./test-support/fixtures.js"; import { createFauxModels, FAUX_MODEL_REF, type FauxModels } from "./test-support/faux.js"; @@ -277,6 +279,11 @@ test("(f) after SIGKILL mid-tool an unsafe tool becomes an interrupted error and assert.equal(unsafeResult.isError, true); assert.match(unsafeResult.content.map((part) => part.text ?? "").join(""), /interrupted/u); assert.equal(safeResult.isError, false); + // The resumed reply finished: the chat must not say the person stopped it. + const transcript = projectBotTranscript((await conversation.context(ctx)).entries); + const rows = botTranscriptRows(transcript, null, { running: false, level: "summary" }); + assert.equal(rows[rows.length - 1]?.kind, "assistant", rows.map((row) => row.kind).join(", ")); + assert.equal(rows.some((row) => row.kind === "stopped"), false, rows.map((row) => row.kind).join(", ")); } finally { await host.shutdown(); } diff --git a/main/services/bot-runtime/bot-session-main.ts b/main/services/bot-runtime/bot-session-main.ts index 2bb73e8ceb..e8317882bf 100644 --- a/main/services/bot-runtime/bot-session-main.ts +++ b/main/services/bot-runtime/bot-session-main.ts @@ -326,12 +326,21 @@ botQuestions.onChange((botId) => { ); }); +// An approval appearing or settling changes the line to and from "Waiting for you". +botApprovals.onChange((botId) => { + void liveProjection?.refreshActivity(botId).catch((error: unknown) => + logger.warn("bots", `Bot ${botId} activity view report.`, error), + ); +}); + /** The process-wide live projection that renderer windows subscribe to. */ export function botLiveProjection(): BotLiveProjection { liveProjection ??= createBotLiveProjection({ conversation: async (botId) => (await botSessionRuntime()).conversation(botId), state: async (botId) => (await botSessionRuntime()).state(botId), + quietInputs: async (botId, ids) => (await botSessionRuntime()).quietInputs(botId, ids), question: (botId) => botQuestions.pending(botId)[0] ?? null, + approvalPending: (botId) => botApprovals.pending(botId).length > 0, connectCardStatus, onRunSettled: broadcastState, onError: (botId, error) => logger.warn("bots", `Bot ${botId} live view report.`, error), @@ -374,6 +383,7 @@ export function botSessionRuntime(): Promise { unbindTelegram, eraseBotData, ], + onResumed: (botId) => botLiveProjection().notifyResuming(botId), onStateChange: (botId, state) => { broadcastState(botId, state); botLiveProjection().notifyState(botId, state); diff --git a/main/services/bot-runtime/bot-session-service.test.ts b/main/services/bot-runtime/bot-session-service.test.ts index c914dd16a4..b9cf0de208 100644 --- a/main/services/bot-runtime/bot-session-service.test.ts +++ b/main/services/bot-runtime/bot-session-service.test.ts @@ -166,6 +166,38 @@ test("Resume called twice at once makes one fresh provider request", async () => } }); +test("Resume reports it resumed only for the call that did: not for a replay, a second request, or a blocked one", async () => { + const profile = tempProfile(); + await killMidStream(profile); + const resumed: string[] = []; + const fauxModels = createFauxModels([fauxAssistantMessage("resumed answer")]); + const service = await serviceFor(profile, fauxModels, { onResumed: (botId) => resumed.push(botId) }); + try { + await service.initialize(); + await Promise.all([service.resume("bot:killed", "phone-1"), service.resume("bot:killed", "desk-1")]); + await service.resume("bot:killed", "phone-1"); + await waitFor(async () => (await service.state("bot:killed")).kind === "idle", { what: "resumed turn to finish" }); + await service.resume("bot:killed", "desk-2"); + assert.deepEqual(resumed, ["bot:killed"]); + } finally { + await service.shutdown(); + } + const blockedProfile = tempProfile(); + await killMidStream(blockedProfile); + const blocked: string[] = []; + const refused = await serviceFor(blockedProfile, createFauxModels([fauxAssistantMessage("must not run")]), { + extension: recordingDeps({ readmit: () => ({ ok: false, reason: "access_changed" }) }), + onResumed: (botId) => blocked.push(botId), + }); + try { + await refused.initialize(); + await refused.resume("bot:killed", "r"); + assert.deepEqual(blocked, []); + } finally { + await refused.shutdown(); + } +}); + test("Dismiss after a restart makes no provider request and keeps the partial as interrupted", async () => { const profile = tempProfile(); const submissionId = await killMidStream(profile); diff --git a/main/services/bot-runtime/bot-session-service.ts b/main/services/bot-runtime/bot-session-service.ts index 9e08e0caae..f6471fe898 100644 --- a/main/services/bot-runtime/bot-session-service.ts +++ b/main/services/bot-runtime/bot-session-service.ts @@ -36,6 +36,7 @@ import { type BotRegistry, } from "./bot-extension.js"; import { writeFileAtomic } from "../durable-fs.js"; +import { BOT_INTRO_REQUEST_PREFIX } from "./bot-intro.js"; import { createBotHarnessHost, isBotHarnessHostUnavailable, @@ -133,6 +134,9 @@ function defaultMessage(reason: BotSessionErrorReason): string { } } +/** Remove's outcome: withdrawn before it ran, already started, or no longer waiting. */ +export type BotWithdrawResult = "withdrawn" | "started" | "gone"; + export interface BotSessionService { send(botId: string, input: BotSendInput): Promise<{ submissionId: string; deduped: boolean }>; resume(botId: string, requestId: string): Promise; @@ -143,6 +147,11 @@ export interface BotSessionService { * paused (interrupted) turn is left for Resume or Dismiss. */ stop(botId: string): Promise; + /** + * Withdraw one queued message before its turn starts (Pi's + * `abortSubmission`). A message already placed in a turn keeps running. + */ + withdraw(botId: string, submissionId: string): Promise; state(botId: string): Promise; deleteBot(botId: string): Promise; /** @@ -160,6 +169,12 @@ export interface BotSessionRuntime extends BotSessionService { initialize(): Promise<{ removedOrphans: string[]; interrupted: string[] }>; /** The Bot's conversation, opened lazily (for live projection). */ conversation(botId: string): Promise; + /** + * For each of these queued submission ids it can find: whether it is not the + * person's own message (`true`: a routine's input or the hidden self-intro, + * known from its durable request id). Ids it cannot find are left out. + */ + quietInputs(botId: string, submissionIds: readonly string[]): Promise>; /** * Compact the Bot's one conversation now (Telegram `/new`), focused on what * the person shared and what the Bot promised (`compactionInstructions`). @@ -202,6 +217,8 @@ export interface BotSessionServiceDeps { idleCloseMs?: number; now?: () => number; onStateChange?(botId: string, state: BotSessionState): void; + /** `resume` restarted an interrupted turn (not called for replays, blocked or no-op resumes). */ + onResumed?(botId: string): void; onReport?(botId: string, error: unknown): void; } @@ -281,6 +298,8 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom }); const host: BotHarnessHost | null = isBotHarnessHostUnavailable(hostOrUnavailable) ? null : hostOrUnavailable; const serialize = createKeyedQueue(); + /** Submissions sent with `hidden`, whatever their request id. */ + const hiddenSubmissions = new Set(); /** Outcomes of resume/dismiss requests, so a retried request replays its answer. */ const answered = new Map(); /** Interrupted turns whose Resume was refused because the Bot's access changed. */ @@ -416,6 +435,27 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom return (await openBot(botId)).conversation; }, + async quietInputs(botId, submissionIds) { + const answers = new Map(); + if (submissionIds.length === 0 || deleted.has(botId)) return answers; + // `inspect`, not `open`: opening would consume a pending recovery notice that only a send reports. + const inspection = await requireHost().inspect(botId); + const wanted = new Set(submissionIds); + for (const record of inspection.submissions) { + const id = String(record.id); + if (!wanted.has(id)) continue; + const requestId = record.requestId ?? ""; + // `hiddenSubmissions` is latent: the only hidden sender (the self-intro) already has the + // `intro:` prefix. Any future hidden sender needs a durable request-id prefix, because this + // set is lost on restart. + answers.set( + id, + requestId.startsWith("routine:") || requestId.startsWith(BOT_INTRO_REQUEST_PREFIX) || hiddenSubmissions.has(id), + ); + } + return answers; + }, + state(botId) { return currentState(botId); }, @@ -448,6 +488,7 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom }, ctx, ); + if (input.hidden === true) hiddenSubmissions.add(String(submission.id)); requireHost().touch(botId); publish(botId, await currentState(botId)); return { submissionId: String(submission.id), deduped: false }; @@ -472,6 +513,7 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom await prepareToRun(botId, conversation, registry); const opened = await requireHost().open(botId); opened.harness.resume(); + deps.onResumed?.(botId); requireHost().touch(botId); return remember(key, publish(botId, await currentState(botId))); }); @@ -503,6 +545,23 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom }); }, + withdraw(botId, submissionId) { + 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); + const result = await opened.harness.abortSubmission( + id as SubmissionId, + ctx, + opened.conversation.id, + ); + if (result === "aborted") return "withdrawn"; + return result === "already_placed" ? "started" : "gone"; + }); + }, + deleteBot(botId) { return serialize(botId, async () => { // Another process holding the profile owns the session; erasing the @@ -524,6 +583,7 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom if (deleted.has(botId)) return { kind: "interrupted", settled: true }; const opened = await requireHost().open(botId); const id = Number(submissionId) as SubmissionId; + if (!Number.isSafeInteger(id)) return { kind: "failed", error: "This reply is no longer tracked." }; const submission = await opened.harness.submission(id, ctx); if (submission === undefined) return { kind: "failed", error: "This reply is no longer tracked." }; // `wait()` would start a paused scheduler, which is Resume's decision. diff --git a/main/services/bot-runtime/bot-starter.test.ts b/main/services/bot-runtime/bot-starter.test.ts index 851129faa5..4fb9fa125f 100644 --- a/main/services/bot-runtime/bot-starter.test.ts +++ b/main/services/bot-runtime/bot-starter.test.ts @@ -78,6 +78,7 @@ async function visibleTranscript(session: BotSessionRuntime, botId: string): Pro const projection = createBotLiveProjection({ conversation: (id) => session.conversation(id), state: (id) => session.state(id), + quietInputs: (id, ids) => session.quietInputs(id, ids), }); const { snapshot, unsubscribe } = await projection.subscribe(botId, { send: () => undefined }); unsubscribe(); diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 3dbc21a7a4..2b90e76c2f 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -4,23 +4,27 @@ import * as os from "node:os"; import * as path from "node:path"; import { after, test } from "node:test"; import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; -import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai/providers/faux"; +import { fauxAssistantMessage, fauxText, fauxThinking, fauxToolCall } from "@earendil-works/pi-ai/providers/faux"; import { applyBotLiveEvent, botRetryableFailedTurn, type BotLiveEvent, type BotLiveSnapshot, } from "../../../renderer/shared/bot-live.js"; +import { botTranscriptRows } from "../../../renderer/main/bots/bot-transcript-rows.js"; import { createBotSessionService, type BotSessionRuntime, type BotSessionServiceDeps } from "./bot-session-service.js"; import { BOT_CONNECT_CARD_ENTRY_KIND, createBotLiveProjection, + liveBotActivity, + liveQueuedInputIds, + liveQueuedMessages, projectBotTranscript, type BotLiveProjection, type BotLiveProjectionDeps, } from "./live-projection.js"; import { createBotQuestions } from "./bot-questions.js"; -import { recordingDeps } from "./test-support/fixtures.js"; +import { countingTool, recordingDeps } from "./test-support/fixtures.js"; import { optionAnswer, QUESTION_ARGS, QUESTION_TOOL_NAME, questionEntries } from "./test-support/question-fixtures.js"; import { createFauxModels, FAUX_MODEL_REF, slowAnswer, waitFor, type FauxModels } from "./test-support/faux.js"; @@ -58,6 +62,7 @@ async function start( projection = createBotLiveProjection({ conversation: (botId) => service.conversation(botId), state: (botId) => service.state(botId), + quietInputs: (botId, ids) => service.quietInputs(botId, ids), ...options.projection, }); return { @@ -113,6 +118,29 @@ async function waitForStreamedText(service: BotSessionRuntime, botId: string): P } } +function observedPhases(events: readonly BotLiveEvent[]): Array { + const phases: Array = []; + for (const event of events) { + const activity = event.type === "activity" ? event.activity : event.type === "snapshot" ? event.snapshot.activity : undefined; + if (activity === undefined) continue; + const phase = activity?.phase ?? null; + if (phases[phases.length - 1] !== phase) phases.push(phase); + } + return phases; +} + +/** Every phase seen appears in `allowed`, in that order (frames may coalesce, so some can be skipped). */ +function inOrder(phases: ReadonlyArray, allowed: readonly string[]): boolean { + let at = 0; + for (const phase of phases) { + if (phase === null) continue; + const found = allowed.indexOf(phase, at); + if (found === -1) return false; + at = found; + } + return true; +} + const visibleText =(snapshot: BotLiveSnapshot | null) => (snapshot?.entries ?? []).map((entry) => entry.type === "user" || entry.type === "assistant" @@ -134,6 +162,7 @@ test("subscribing mid-stream returns a snapshot that already has the partial rep try { assert.equal(snapshot.state.kind, "running"); assert.match(snapshot.partial ?? "", /^word word/u); + assert.equal(snapshot.activity?.phase, "writing"); assert.deepEqual(visibleText(snapshot), ["user:tell me a story"]); } finally { unsubscribe(); @@ -341,6 +370,105 @@ test("files the Bot wrote in its folder and images it shared become chips; faile ); }); +test("tool calls carry a kind, a past-tense label and a short safe detail; results say ok, failed or blocked", () => { + const result = (id: number, toolCallId: string, toolName: string, timestamp: number, code?: string) => ({ + id, + kind: "pi.tool-result", + data: { diagnostics: code ? [{ severity: "error", code, message: code }] : [] }, + model: [{ role: "toolResult", toolCallId, toolName, isError: code !== undefined, content: [], timestamp }], + }); + const entries = projectBotTranscript([ + { id: 1, kind: "pi.user", model: [{ role: "user", content: [{ type: "text", text: "Plan dinners" }], timestamp: 900 }] }, + { + id: 2, + kind: "pi.assistant", + model: [{ + role: "assistant", + stopReason: "toolUse", + timestamp: 1_000, + content: [ + { type: "toolCall", id: "c1", name: "read_file", arguments: { path: "/Users/sam/lists/grocery-list.md" } }, + { type: "toolCall", id: "c2", name: "run_command", arguments: { command: "cat /Users/sam/.ssh/id_rsa" } }, + { type: "toolCall", id: "c3", name: "web_search", arguments: { query: "lisbon trains" } }, + { type: "toolCall", id: "c4", name: "web_search", arguments: { query: "slow thing" } }, + { type: "toolCall", id: "c5", name: "read_file", arguments: { path: "restart.md" } }, + ], + }], + }, + result(3, "c1", "read_file", 1_400), + result(4, "c2", "run_command", 1_050, "blocked"), + result(5, "c3", "web_search", 2_000, "tool_error"), + result(6, "c4", "web_search", 2_500, "aborted"), + result(7, "c5", "read_file", 2_600, "interrupted"), + ] as never); + const assistant = entries.find((entry) => entry.type === "assistant"); + assert.ok(assistant?.type === "assistant"); + assert.deepEqual(assistant.toolCalls[0], { id: "c1", name: "read_file", kind: "reading", label: "Read 1 file", detail: "grocery-list.md" }); + // A command with no description shows no detail: the command itself never reaches the chat. + assert.deepEqual(assistant.toolCalls[1], { id: "c2", name: "run_command", kind: "command", label: "Ran a command" }); + assert.deepEqual(assistant.toolCalls[2], { id: "c3", name: "web_search", kind: "searching", label: "Searched the web", detail: "lisbon trains" }); + const results = entries.flatMap((entry) => + entry.type === "tool_result" ? [[entry.toolCallId, entry.status, entry.durationMs, entry.at]] : [], + ); + assert.deepEqual(results, [ + ["c1", "ok", 400, 1_400], + ["c2", "blocked", 50, 1_050], + ["c3", "failed", 1_000, 2_000], + ["c4", "stopped", 1_500, 2_500], + ["c5", "stopped", 1_600, 2_600], + ]); +}); + +test("a tool the Bot's access or the person refused is blocked, a tool that broke is failed, and neither looks like the other", async () => { + const shell = countingTool("run_command"); + const gated = countingTool("send_email"); + const search = countingTool("web_search", async () => { + throw new Error("The search service is down."); + }); + const fauxModels = createFauxModels([ + fauxAssistantMessage([fauxToolCall("run_command", { text: "ls" }), fauxToolCall("web_search", { text: "trains" }), fauxToolCall("send_email", { text: "hi" })], { + stopReason: "toolUse", + }), + fauxAssistantMessage("I couldn't do that one."), + ]); + const live = await start(fauxModels, { + service: { + extension: recordingDeps({ + tools: [ + { tool: shell, replay: "unsafe" }, + { tool: search, replay: "unsafe" }, + { tool: gated, replay: "unsafe" }, + ], + policy: (name) => + name === "run_command" + ? { allowed: false, reason: "The shell is off for this Bot." } + : name === "send_email" + ? { allowed: true, approval: { summary: "Send an email" } } + : { allowed: true }, + approve: async () => "deny", + }), + }, + }); + try { + const sent = await live.service.send("bot:a", { text: "go", requestId: "desk-1" }); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + const view = await (await live.service.conversation("bot:a")).context(ctx); + const statuses = new Map( + projectBotTranscript(view.entries).flatMap((entry) => (entry.type === "tool_result" ? [[entry.toolName, entry] as const] : [])), + ); + assert.equal(statuses.get("run_command")?.status, "blocked"); + assert.equal(statuses.get("web_search")?.status, "failed"); + assert.equal(statuses.get("send_email")?.status, "blocked", "a declined approval is blocked, not failed"); + assert.deepEqual(shell.executions, [], "a refused tool never runs"); + assert.deepEqual(gated.executions, [], "a declined tool never runs"); + for (const entry of statuses.values()) { + assert.ok(typeof entry.durationMs === "number" && entry.durationMs >= 0); + } + } finally { + await live.close(); + } +}); + test("memory saves show one quiet line each: in-turn saves that changed something and reviews that added", () => { const result = (id: number, toolCallId: string, details: unknown, isError = false) => ({ id, @@ -429,9 +557,13 @@ test("Stop ends the running reply, keeps what was written, and the Bot is idle a tape.start(snapshot); await live.service.send("bot:a", { text: "go", requestId: "desk-1" }); await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "a partial reply" }); + live.projection.notifyStopping("bot:a"); const state = await live.service.stop("bot:a"); assert.equal(state.kind, "idle"); await waitFor(() => tape.view?.partial === null && tape.view.state.kind === "idle", { what: "the stop to land" }); + const phases = observedPhases(tape.events); + assert.ok(phases.includes("stopping"), phases.join(" → ")); + assert.equal(phases[phases.length - 1], null); const last = tape.view!.entries[tape.view!.entries.length - 1]; assert.equal(last?.type, "assistant"); assert.equal(last?.type === "assistant" ? last.stopReason : null, "aborted"); @@ -570,3 +702,518 @@ test("a waiting question reaches subscribers and late joiners, and its answer re await live.close(); } }); + +test("Stop pressed while a slow tool runs ends the chat with the person's stopped line", async () => { + const reader = countingTool( + "read_file", + (_params, signal) => + new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true }); + }), + ); + const fauxModels = createFauxModels( + [ + fauxAssistantMessage([fauxToolCall("read_file", { text: "groceries" })], { stopReason: "toolUse" }), + fauxAssistantMessage("word ".repeat(40)), + ], + { tokensPerSecond: 40 }, + ); + const live = await start(fauxModels, { + service: { extension: recordingDeps({ tools: [{ tool: reader, replay: "safe" }] }) }, + }); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "What's on my list?", requestId: "desk-1" }); + await waitFor(() => tape.view?.activity?.phase === "reading", { what: "the tool to run" }); + live.projection.notifyStopping("bot:a"); + const state = await live.service.stop("bot:a"); + assert.equal(state.kind, "idle"); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the stop to land" }); + const entries = tape.view!.entries; + const results = entries.filter((entry) => entry.type === "tool_result"); + assert.deepEqual( + results.map((entry) => (entry.type === "tool_result" ? entry.status : null)), + ["stopped"], + ); + for (const level of ["quiet", "summary"] as const) { + const rows = botTranscriptRows(entries, tape.view!.partial, { running: false, level }); + assert.equal(rows[rows.length - 1]?.kind, "stopped", `${level}: ${rows.map((row) => row.kind).join(", ")}`); + const recap = rows.find((row) => row.kind === "recap"); + if (recap?.kind === "recap") assert.deepEqual(recap.steps.map((step) => step.status), ["stopped"]); + } + assert.equal(fauxModels.calls(), 1, "the second reply never ran"); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("a reply's activity follows the work: getting ready, reading while a file tool runs, writing, then nothing", async () => { + let release!: () => void; + const released = new Promise((resolve) => (release = resolve)); + const reader = countingTool("read_file", async () => { + await released; + return "eggs, milk"; + }); + const fauxModels = createFauxModels( + [ + fauxAssistantMessage([fauxToolCall("read_file", { text: "groceries" })], { stopReason: "toolUse" }), + fauxAssistantMessage("word ".repeat(60)), + ], + { tokensPerSecond: 40 }, + ); + const live = await start(fauxModels, { + service: { extension: recordingDeps({ tools: [{ tool: reader, replay: "safe" }] }) }, + }); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + assert.equal(snapshot.activity, null); + const sent = await live.service.send("bot:a", { text: "What's on my list?", requestId: "desk-1" }); + await waitFor(() => tape.view?.activity?.phase === "reading", { what: "the reading phase" }); + assert.deepEqual(tape.view?.activity?.step, { kind: "reading", label: "Reading" }); + assert.ok((tape.view?.activity?.startedAt ?? 0) > 0); + release(); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the line to clear" }); + const phases = observedPhases(tape.events); + assert.ok(inOrder(phases, ["preparing", "thinking", "reading", "thinking", "writing"]), phases.join(" → ")); + assert.ok(phases.includes("writing"), phases.join(" → ")); + assert.equal(phases[phases.length - 1], null); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("thinking text is never projected, in the transcript or the live activity", () => { + const entries = [ + { id: 1, kind: "pi.user", model: [{ role: "user", content: [{ type: "text", text: "Hi" }], timestamp: 1 }] }, + { + id: 2, + kind: "pi.assistant", + model: [{ role: "assistant", stopReason: "stop", timestamp: 2, content: [fauxThinking("SECRET-PLAN"), fauxText("Done.")] }], + }, + ]; + assert.doesNotMatch(JSON.stringify(projectBotTranscript(entries as never)), /SECRET-PLAN/u); + const activity = liveBotActivity({ + entries: entries as never, + docs: { "pi.live": { run: { taskId: 1, inputs: [1] }, generation: { attempt: 1, message: { content: [fauxThinking("SECRET-PLAN")] } } } }, + waiting: false, + stopping: false, + resuming: false, + startedAt: 5, + }); + assert.deepEqual(activity, { phase: "thinking", startedAt: 5 }); +}); + +test("the live phase reads stop, a waiting card, compaction, the newest running tool, and resume, in that order", () => { + const user = { id: 1, kind: "pi.user", model: [{ role: "user", content: "go", timestamp: 1 }] }; + const calling = { + id: 2, + kind: "pi.assistant", + model: [{ + role: "assistant", + stopReason: "toolUse", + timestamp: 2, + content: [ + { type: "toolCall", id: "c1", name: "read_file", arguments: { path: "lists/a.md" } }, + { type: "toolCall", id: "c2", name: "web_search", arguments: { query: "tofu bowls" } }, + ], + }], + }; + const tools = [ + { callId: "c1", name: "read_file", status: "running" }, + { callId: "c2", name: "web_search", status: "running" }, + ]; + const base = { entries: [user, calling] as never, waiting: false, stopping: false, resuming: false, startedAt: 9 }; + const docs = (live: Record) => ({ "pi.live": { run: { taskId: 1, inputs: [1] }, ...live } }); + assert.equal(liveBotActivity({ ...base, docs: {} }), null, "no run, no line"); + assert.deepEqual(liveBotActivity({ ...base, docs: docs({ tools }) }), { + phase: "searching", + startedAt: 9, + step: { kind: "searching", label: "Searching the web", detail: "tofu bowls" }, + }); + assert.equal(liveBotActivity({ ...base, docs: docs({ compactions: [{ blocking: true }], tools }) })?.phase, "tidying"); + assert.equal(liveBotActivity({ ...base, waiting: true, docs: docs({ tools }) })?.phase, "waiting"); + assert.equal(liveBotActivity({ ...base, waiting: true, stopping: true, docs: docs({ tools }) })?.phase, "stopping"); + assert.equal(liveBotActivity({ ...base, entries: [user] as never, docs: docs({}) })?.phase, "preparing"); + assert.equal(liveBotActivity({ ...base, docs: docs({}) })?.phase, "thinking"); + assert.equal(liveBotActivity({ ...base, resuming: true, docs: docs({}) })?.phase, "resuming"); + assert.equal( + liveBotActivity({ ...base, docs: docs({ generation: { attempt: 1, message: { content: [{ type: "text", text: "Here" }] } } }) })?.phase, + "writing", + ); +}); + +test("Stop pressed while nothing runs is ignored, so the next reply never starts at Stopping", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("word ".repeat(40))], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + live.projection.notifyStopping("bot:a"); + const sent = await live.service.send("bot:a", { text: "hi", requestId: "desk-1" }); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the reply to land" }); + assert.equal(observedPhases(tape.events).includes("stopping"), false); + unsubscribe(); + } finally { + await live.close(); + } +}); + +/** Every distinct (turn start, phase) the line showed, in order. */ +function observedTurns(events: readonly BotLiveEvent[]): Array<{ startedAt: number; phase: string }> { + const seen: Array<{ startedAt: number; phase: string }> = []; + for (const event of events) { + const activity = event.type === "activity" ? event.activity : event.type === "snapshot" ? event.snapshot.activity : null; + if (!activity) continue; + const last = seen[seen.length - 1]; + if (last?.startedAt !== activity.startedAt || last.phase !== activity.phase) { + seen.push({ startedAt: activity.startedAt, phase: activity.phase }); + } + } + return seen; +} + +test("a Resume marks the run it started, and the turn after it reads normally", async () => { + const fauxModels = createFauxModels( + [fauxAssistantMessage("word ".repeat(30)), fauxAssistantMessage("word ".repeat(30))], + { tokensPerSecond: 40 }, + ); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + const reply = async (text: string, requestId: string) => { + const sent = await live.service.send("bot:a", { text, requestId }); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the reply to land" }); + }; + live.projection.notifyResuming("bot:a"); + await reply("resumed turn", "desk-1"); + assert.ok(observedPhases(tape.events).includes("resuming")); + const after = tape.events.length; + await reply("the next turn", "desk-2"); + assert.equal(observedPhases(tape.events.slice(after)).includes("resuming"), false); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("a tool round hands the run to a new generation but is still one turn: one start time, and Stop keeps reading Stopping", async () => { + let release!: () => void; + const released = new Promise((resolve) => (release = resolve)); + const reader = countingTool("read_file", async () => { + await released; + return "eggs, milk"; + }); + const fauxModels = createFauxModels( + [ + fauxAssistantMessage([fauxToolCall("read_file", { text: "groceries" })], { stopReason: "toolUse" }), + fauxAssistantMessage("word ".repeat(40)), + ], + { tokensPerSecond: 40 }, + ); + let tick = 1_000; + const live = await start(fauxModels, { + service: { extension: recordingDeps({ tools: [{ tool: reader, replay: "safe" }] }) }, + projection: { now: () => (tick += 1_000) }, + }); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + const sent = await live.service.send("bot:a", { text: "list?", requestId: "desk-1" }); + await waitFor(() => tape.view?.activity?.phase === "reading", { what: "the reading phase" }); + live.projection.notifyStopping("bot:a"); + await waitFor(() => tape.view?.activity?.phase === "stopping", { what: "the stopping line" }); + const stoppedAt = tape.events.length; + release(); + await live.service.awaitReply("bot:a", sent.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the reply to land" }); + const turns = observedTurns(tape.events); + assert.equal(new Set(turns.map((turn) => turn.startedAt)).size, 1, JSON.stringify(turns)); + const after = observedPhases(tape.events.slice(stoppedAt)).filter((phase) => phase !== null); + // The line never left Stopping after the hand-over: no other phase appears before it clears. + assert.deepEqual(after, [], after.join(" → ")); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("a follow-up turn queued behind a running one gets its own start time and a clean line", async () => { + const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("word ".repeat(20))], { tokensPerSecond: 40 }); + let tick = 1_000; + const live = await start(fauxModels, { projection: { now: () => (tick += 1_000) } }); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "tell me a story", requestId: "desk-1" }); + await waitFor(() => tape.view?.activity?.phase === "writing", { what: "the first reply to stream" }); + live.projection.notifyStopping("bot:a"); + await waitFor(() => tape.view?.activity?.phase === "stopping", { what: "the stopping line" }); + const queued = await live.service.send("bot:a", { text: "and another", requestId: "desk-2" }); + await live.service.awaitReply("bot:a", queued.submissionId, new AbortController().signal); + await waitFor(() => tape.view?.activity === null && tape.view.state.kind === "idle", { what: "the replies to land" }); + const turns = observedTurns(tape.events); + const starts = [...new Set(turns.map((turn) => turn.startedAt))]; + assert.ok(starts.length >= 2, JSON.stringify(turns)); + assert.ok(starts[1]! > starts[0]!, JSON.stringify(turns)); + const second = turns.filter((turn) => turn.startedAt === starts[1]); + assert.notEqual(second[0]?.phase, "stopping", JSON.stringify(turns)); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("a follow-up sent while the Bot works shows as queued, and Remove withdraws it before it runs", async () => { + const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("never")], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + assert.deepEqual(snapshot.queued, []); + await live.service.send("bot:a", { text: "Plan dinners", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply to stream" }); + const queued = await live.service.send("bot:a", { text: "Also add dessert", requestId: "desk-2", whenBusy: "followUp" }); + await waitFor(() => tape.view?.queued.length === 1, { what: "the queued message" }); + assert.deepEqual(tape.view?.queued, [ + { submissionId: queued.submissionId, mode: "followUp", text: "Also add dessert", imageCount: 0 }, + ]); + assert.equal(await live.service.withdraw("bot:a", queued.submissionId), "withdrawn"); + await waitFor(() => tape.view?.queued.length === 0, { what: "the queued message to leave" }); + await live.service.stop("bot:a"); + await waitFor(() => tape.view?.state.kind === "idle", { what: "the stop" }); + assert.equal(fauxModels.calls(), 1, "the withdrawn follow-up never reached the model"); + assert.equal(visibleText(tape.view).includes("user:Also add dessert"), false); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("Remove on a queued message whose turn already started withdraws nothing", async () => { + const fauxModels = createFauxModels([fauxAssistantMessage("word ".repeat(30)), slowAnswer()], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "one", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply" }); + const second = await live.service.send("bot:a", { text: "two", requestId: "desk-2", whenBusy: "followUp" }); + await waitFor(() => visibleText(tape.view).includes("user:two"), { what: "the follow-up to start" }); + assert.equal(await live.service.withdraw("bot:a", second.submissionId), "started"); + assert.equal(await live.service.withdraw("bot:a", "999999"), "gone"); + await live.service.stop("bot:a"); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("queued inputs are listed by the person's ids only; passive writes never show", () => { + const notice = (data: unknown) => ({ id: 1, mode: "write", entry: { kind: "aiden.bot-notice", data } }); + const docs = { + "pi.inbox": { + items: [ + notice({ notice: "routine", label: "Morning check-in", requestId: "routine:r1:1" }), + { id: 2, mode: "followUp", content: "Check in on today" }, + { id: 4, mode: "followUp", content: "Introduce yourself" }, + { id: 5, mode: "steer", content: [{ type: "text", text: "Make it vegetarian" }, { type: "image", data: "AA", mimeType: "image/png" }] }, + ], + }, + }; + assert.deepEqual(liveQueuedInputIds(docs), ["2", "4", "5"]); + assert.deepEqual(liveQueuedMessages(docs, new Set(["2", "4"])), [ + { submissionId: "5", mode: "steer", text: "Make it vegetarian", imageCount: 1 }, + ]); + assert.deepEqual(liveQueuedMessages({}), []); +}); + +/** Wait, outside the projection, until the conversation's `pi.inbox` satisfies `predicate`. */ +async function waitForInbox( + service: BotSessionRuntime, + botId: string, + predicate: (items: Array<{ mode?: string }>) => boolean, +): Promise { + const watch = await (await service.conversation(botId)).watch(ctx); + const items = () => ((watch.value.docs["pi.inbox"] as { items?: Array<{ mode?: string }> } | undefined)?.items ?? []); + watch.start(async () => undefined); + try { + await waitFor(() => predicate(items()), { what: "the inbox" }); + } finally { + await watch.stop(); + } +} + +const queuedTexts = (events: readonly BotLiveEvent[]) => + events.flatMap((event) => (event.type === "queued" ? event.queued.map((item) => item.text) : [])); + +test("a routine queued behind a reply that calls a tool is never listed, even once its notice is placed", async () => { + let release!: () => void; + const released = new Promise((resolve) => (release = resolve)); + const reader = countingTool("read_file", async () => { + await released; + return "eggs, milk"; + }); + const fauxModels = createFauxModels( + [ + fauxAssistantMessage([fauxToolCall("read_file", { text: "groceries" })], { stopReason: "toolUse" }), + fauxAssistantMessage("word ".repeat(10)), + fauxAssistantMessage("routine reply"), + ], + { tokensPerSecond: 40 }, + ); + const live = await start(fauxModels, { + service: { extension: recordingDeps({ tools: [{ tool: reader, replay: "safe" }] }) }, + }); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "list?", requestId: "desk-1" }); + await waitFor(() => tape.view?.activity?.phase === "reading", { what: "the tool to run" }); + await live.service.send("bot:a", { text: "Check in on today", requestId: "routine:r1:1", label: "Morning check-in" }); + await waitForInbox(live.service, "bot:a", (items) => items.some((item) => item.mode === "followUp")); + release(); + await waitFor(() => visibleText(tape.view).includes("assistant:routine reply"), { what: "the routine's reply" }); + await waitFor(() => tape.view?.state.kind === "idle", { what: "the Bot to settle" }); + assert.deepEqual(queuedTexts(tape.events), []); + assert.deepEqual(tape.view?.queued, []); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("a notice left behind by Stop does not hide the person's next queued message", async () => { + const fauxModels = createFauxModels([slowAnswer(), slowAnswer(), fauxAssistantMessage("never")], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "one", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply to stream" }); + await live.service.send("bot:a", { text: "Check in on today", requestId: "routine:r1:1", label: "Morning check-in" }); + await live.service.stop("bot:a"); + await waitFor(() => tape.view?.state.kind === "idle", { what: "the stop" }); + await live.service.send("bot:a", { text: "two", requestId: "desk-2" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the next reply to stream" }); + await live.service.send("bot:a", { text: "three", requestId: "desk-3", whenBusy: "followUp" }); + await waitFor(() => tape.view?.queued.some((item) => item.text === "three") === true, { what: "the queued message" }); + assert.equal(queuedTexts(tape.events).includes("Check in on today"), false); + await live.service.stop("bot:a"); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("an intro prompt queued behind a running reply is not listed as the person's message", async () => { + const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("hello there")], { tokensPerSecond: 40 }); + const live = await start(fauxModels); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "one", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply to stream" }); + await live.service.send("bot:a", { text: "Introduce yourself", requestId: "intro:bot:a", hidden: true }); + await live.service.send("bot:a", { text: "two", requestId: "desk-2" }); + await waitFor(() => tape.view?.queued.some((item) => item.text === "two") === true, { what: "the person's message" }); + assert.deepEqual(tape.view?.queued.map((item) => item.text), ["two"]); + assert.equal(queuedTexts(tape.events).includes("Introduce yourself"), false); + await live.service.stop("bot:a"); + unsubscribe(); + } finally { + await live.close(); + } +}); + +/** A projection whose classification can be made to fail or come back empty, with every call and report counted. */ +async function startFlaky() { + const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("never")], { tokensPerSecond: 40 }); + const control = { mode: "ok" as "ok" | "throw" | "empty", calls: 0, reports: 0 }; + const live = await start(fauxModels, { + projection: { + classifyRetryMs: 150, + onError: () => { + control.reports += 1; + }, + quietInputs: async (botId, ids) => { + control.calls += 1; + if (control.mode === "throw") throw new Error("inspect failed"); + if (control.mode === "empty") return new Map(); + return live.service.quietInputs(botId, ids); + }, + }, + }); + return { live, control }; +} + +test("while classifying fails, a cached routine stays hidden and the person's classified message stays listed; the new one waits, then appears", async () => { + const { live, control } = await startFlaky(); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "one", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply to stream" }); + await live.service.send("bot:a", { text: "Check in on today", requestId: "routine:r1:1", label: "Morning check-in" }); + await live.service.send("bot:a", { text: "dessert", requestId: "desk-2" }); + await waitFor(() => tape.view?.queued.some((item) => item.text === "dessert") === true, { what: "dessert, classified" }); + control.mode = "throw"; + control.calls = 0; + control.reports = 0; + await live.service.send("bot:a", { text: "drinks", requestId: "desk-3" }); + await new Promise((resolve) => setTimeout(resolve, 700)); + assert.deepEqual(tape.view?.queued.map((item) => item.text), ["dessert"], "drinks waits; the routine never shows"); + assert.equal(queuedTexts(tape.events).includes("Check in on today"), false); + assert.equal(control.reports, 1, "one report per failure streak"); + assert.ok(control.calls <= 6, `retries are throttled, saw ${control.calls}`); + control.mode = "ok"; + await waitFor(() => tape.view?.queued.some((item) => item.text === "drinks") === true, { + what: "drinks after the retry, with no new frame needed", + }); + assert.deepEqual(tape.view?.queued.map((item) => item.text), ["dessert", "drinks"]); + await live.service.stop("bot:a"); + unsubscribe(); + } finally { + await live.close(); + } +}); + +test("an id the session cannot find stays hidden and is retried", async () => { + const { live, control } = await startFlaky(); + try { + const tape = recorder(); + const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); + tape.start(snapshot); + await live.service.send("bot:a", { text: "one", requestId: "desk-1" }); + await waitFor(() => (tape.view?.partial ?? "").length > 0, { what: "the first reply to stream" }); + control.mode = "empty"; + await live.service.send("bot:a", { text: "dessert", requestId: "desk-2" }); + await new Promise((resolve) => setTimeout(resolve, 400)); + assert.deepEqual(tape.view?.queued, []); + control.mode = "ok"; + await waitFor(() => tape.view?.queued.some((item) => item.text === "dessert") === true, { what: "dessert after the retry" }); + await live.service.stop("bot:a"); + unsubscribe(); + } finally { + await live.close(); + } +}); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 8e20ec9a3f..a78c1bc874 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -28,13 +28,17 @@ import { botFailedTurnId, botQuestionAnswerText, botTranscriptPreview, + type BotLiveActivity, type BotLiveEvent, type BotPendingQuestion, + type BotQueuedMessage, type BotLiveEventBody, type BotLiveSnapshot, type BotLiveSummary, + type BotToolResultStatus, type BotTranscriptEntry, } from "../../../renderer/shared/bot-live.js"; +import { botPhaseWord, pickActiveToolSlot, type BotActivityPhase } from "../../../renderer/shared/bot-activity.js"; import { parseProducedFile } from "../../../renderer/shared/produced-file.js"; import { BOT_MEMORY_REVIEW_ENTRY_KIND, @@ -47,6 +51,7 @@ import { type BotRoutineProposalEntryData, type BotRoutineProposalStatusEntryData, } from "../../../renderer/shared/bot-routine-proposals.js"; +import { botStepDescriptor } from "./bot-activity-detail.js"; import { BOT_SHARED_IMAGE_ENTRY_KIND } from "./bot-images.js"; import { BOT_NOTICE_ENTRY_KIND, type BotNotice, type BotSessionState } from "./bot-session-service.js"; @@ -174,6 +179,22 @@ function connectCardOf(data: unknown): ConnectCardEntry | null { return { type: "connect_card", pluginId: record.pluginId, reason: record.reason, status }; } +/** + * `blocked` when Pi's `beforeTool` refused the call (policy, a denied approval, + * ingress); `stopped` when the run was stopped or interrupted mid-call; any + * other error failed. + */ +function toolResultStatus(record: EntryRecord, isError: boolean): BotToolResultStatus { + if (!isError) return "ok"; + const diagnostics = (record.data as { diagnostics?: unknown } | undefined)?.diagnostics; + const codes = new Set( + Array.isArray(diagnostics) ? diagnostics.map((item) => (item as { code?: unknown } | null)?.code) : [], + ); + if (codes.has("blocked")) return "blocked"; + if (codes.has("aborted") || codes.has("interrupted")) return "stopped"; + return "failed"; +} + /** * Map raw Pi Durable entries to what a Bot chat shows. Pure: the same entries * always give the same view, so a full re-projection can be diffed safely. @@ -203,6 +224,8 @@ export function projectBotTranscript(entries: readonly EntryRecord[]): BotTransc let pendingHidden = false; /** File tool calls aimed at the default location (the Bot's folder), by call id. */ const homeFileCalls = new Set(); + /** When the answer that made each call was written, for its duration. */ + const callStartedAt = new Map(); let turn: Turn | null = null; /** The newest decision on each proposal: cards show what is true now. */ const proposalStatus = new Map(); @@ -285,7 +308,10 @@ export function projectBotTranscript(entries: readonly EntryRecord[]): BotTransc homeFileCalls.add(call.id); } } - const toolCalls = calls.map((call) => ({ id: call.id, name: call.name })); + for (const call of calls) { + if (typeof message.timestamp === "number") callStartedAt.set(call.id, message.timestamp); + } + const toolCalls = calls.map((call) => ({ id: call.id, name: call.name, ...botStepDescriptor(call.name, call.arguments) })); const stopReason = stopReasonOf(message); const text = textOf(message.content); if (stopReason === "error") { @@ -329,6 +355,8 @@ export function projectBotTranscript(entries: readonly EntryRecord[]): BotTransc mapped.push({ entry: { id, type: "question_answer", text: answerText, at: message.timestamp }, turn }); continue; } + const startedAt = callStartedAt.get(message.toolCallId); + const at = typeof message.timestamp === "number" ? message.timestamp : undefined; mapped.push({ entry: { id, @@ -336,6 +364,9 @@ export function projectBotTranscript(entries: readonly EntryRecord[]): BotTransc toolCallId: message.toolCallId, toolName: message.toolName, isError: message.isError, + status: toolResultStatus(record, message.isError), + ...(startedAt !== undefined && at !== undefined ? { durationMs: Math.max(0, at - startedAt) } : {}), + ...(at === undefined ? {} : { at }), }, turn, }); @@ -377,11 +408,133 @@ export function livePartialText(docs: Readonly>): string return text; } +/** + * The turn's identity, or null when no run: its first input. A queued follow-up + * starts a new run (fresh inputs) while `pi.live.run` stays present; steering + * appends to the inputs and a tool round hands the run to a new generation + * task, so neither changes the key (and neither is a new turn). + */ +function liveRunKey(docs: Readonly>): string | null { + const live = docs["pi.live"] as { run?: { inputs?: unknown } } | undefined; + const run = live?.run; + if (run === undefined) return null; + const first = Array.isArray(run.inputs) ? run.inputs[0] : undefined; + return String(first); +} + function liveRunActive(docs: Readonly>): boolean { const live = docs["pi.live"] as { run?: unknown } | undefined; return live?.run !== undefined; } +interface LiveDocView { + run?: unknown; + generation?: { message?: { content?: unknown } }; + tools?: Array<{ callId: string; name: string; status: string }>; + compactions?: Array<{ blocking?: boolean }>; +} + +export interface BotLiveActivityInput { + entries: readonly EntryRecord[]; + docs: Readonly>; + /** An approval or A–E question is open. */ + waiting: boolean; + /** The person pressed Stop and the run has not ended. */ + stopping: boolean; + /** This run is a Resume and has not moved on yet. */ + resuming: boolean; + startedAt: number; +} + +/** Whether the newest input already has an assistant entry after it. */ +function inputAnswered(entries: readonly EntryRecord[]): boolean { + for (let index = entries.length - 1; index >= 0; index -= 1) { + const kind = entries[index]!.kind; + if (kind === "pi.assistant") return true; + if (kind === "pi.user") return false; + } + return false; +} + +/** The arguments of tool call `callId`, from the answer that made it. */ +function callArguments(entries: readonly EntryRecord[], callId: string): unknown { + for (let index = entries.length - 1; index >= 0; index -= 1) { + const message = firstMessage(entries[index]!); + if (message?.role !== "assistant") continue; + const call = message.content.find((part): part is ToolCall => part.type === "toolCall" && part.id === callId); + if (call) return call.arguments; + } + return undefined; +} + +/** + * The phase of a run from `pi.live` (spec §5): Stop, then an open card, + * then compaction inside the turn, then the newest running tool (§5.2), then + * the reply's text, then Resume, then thinking (or "getting ready" before + * the model produced anything). Thinking content is read only to know the + * model is generating; its text is never copied. + */ +export function liveBotActivity(input: BotLiveActivityInput): BotLiveActivity | null { + const live = input.docs["pi.live"] as LiveDocView | undefined; + if (live?.run === undefined) return null; + const at = (phase: BotActivityPhase): BotLiveActivity => ({ phase, startedAt: input.startedAt }); + if (input.stopping) return at("stopping"); + if (input.waiting) return at("waiting"); + if (live.compactions?.some((compaction) => compaction.blocking === true)) return at("tidying"); + const slot = pickActiveToolSlot(live.tools); + if (slot) { + const step = botStepDescriptor(slot.name, callArguments(input.entries, slot.callId)); + return { + phase: step.kind, + startedAt: input.startedAt, + ...(step.app ? { app: step.app } : {}), + step: { kind: step.kind, label: botPhaseWord(step.kind, step.app), ...(step.detail ? { detail: step.detail } : {}) }, + }; + } + const content = live.generation?.message?.content; + if (Array.isArray(content) && textOf(content as TextContent[]).trim()) return at("writing"); + if (input.resuming) return at("resuming"); + if (Array.isArray(content) && content.length > 0) return at("thinking"); + return at(inputAnswered(input.entries) ? "thinking" : "preparing"); +} + +/** The submission ids of inputs (not passive writes) waiting in `pi.inbox`. */ +export function liveQueuedInputIds(docs: Readonly>): string[] { + const items = (docs["pi.inbox"] as { items?: unknown } | undefined)?.items; + if (!Array.isArray(items)) return []; + const ids: string[] = []; + for (const value of items) { + const item = value as { id?: unknown; mode?: unknown }; + if (item.mode !== "steer" && item.mode !== "followUp") continue; + if (typeof item.id === "number" || typeof item.id === "string") ids.push(String(item.id)); + } + return ids; +} + +/** + * Inputs waiting in `pi.inbox` that the person sent. `quiet` holds the ids of + * routine and hidden (self-intro) submissions, which are decided by their + * request id and never shown. + */ +export function liveQueuedMessages( + docs: Readonly>, + quiet: ReadonlySet = new Set(), +): BotQueuedMessage[] { + const items = (docs["pi.inbox"] as { items?: unknown } | undefined)?.items; + if (!Array.isArray(items)) return []; + const queued: BotQueuedMessage[] = []; + for (const value of items) { + const item = value as { id?: unknown; mode?: unknown; content?: unknown }; + if (item.mode !== "steer" && item.mode !== "followUp") continue; + if (typeof item.id !== "number" && typeof item.id !== "string") continue; + const submissionId = String(item.id); + const content = item.content as UserContent | undefined; + if (content === undefined || quiet.has(submissionId)) continue; + queued.push({ submissionId, mode: item.mode, text: textOf(content), imageCount: imageCount(content) }); + } + return queued; +} + /* ------------------------------------------------------------------------- */ /* Feeds and subscribers */ /* ------------------------------------------------------------------------- */ @@ -395,11 +548,24 @@ export interface BotLiveProjectionDeps { state(botId: string): Promise; /** The question the Bot is waiting on right now, if any. */ question?(botId: string): BotPendingQuestion | null; + /** + * Classify queued submission ids: `true` for a routine's input or the hidden + * self-intro, `false` for the person's own message. Decided from durable + * request ids. An id the session cannot find is left out of the answer; an + * id with no answer, or a failure, stays hidden and is retried. + */ + quietInputs(botId: string, submissionIds: readonly string[]): Promise>; + /** Whether a tool approval is waiting on the person. */ + approvalPending?(botId: string): boolean; + /** Clock for `startedAt`; defaults to `Date.now`. */ + now?(): number; /** The current status of a connect card (connected or dismissed since it was offered). */ connectCardStatus?(botId: string, card: ConnectCardEntry): Promise; /** Schedules a subscriber flush. Defaults to the next macrotask. */ schedule?(flush: () => void): void; maxPending?: number; + /** Pause before a failed queued-message classification is tried again. Defaults to one second. */ + classifyRetryMs?: number; newEpoch?(): string; /** A reply finished (or the Bot paused): list rows refresh from this. */ onRunSettled?(botId: string, state: BotSessionState): void; @@ -419,6 +585,18 @@ export interface BotLiveProjection { refresh(botId: string): Promise; /** The Bot's pending question changed (asked, answered, withdrawn): push a `question` event. */ refreshQuestion(botId: string): Promise; + /** The person pressed Stop: the running turn reads "Stopping" until it ends. Ignored when nothing runs. */ + notifyStopping(botId: string): void; + /** + * The session resumed an interrupted turn (called by the service, inside its per-Bot + * serialization, only when this call resumed it): the run reads "Picking up where it left off" + * until it moves on. + */ + notifyResuming(botId: string): void; + /** The Stop did not take (it failed): the run goes on and no longer reads "Stopping". */ + cancelStopping(botId: string): void; + /** An approval appeared or settled: re-derive the activity. */ + refreshActivity(botId: string): Promise; /** Preview, time and state for a list row. */ summary(botId: string): Promise; /** Stop every feed (the Bot was deleted, or the app is quitting). */ @@ -441,7 +619,24 @@ interface Feed { partial: string | null; state: BotSessionState; question: BotPendingQuestion | null; + activity: BotLiveActivity | null; + queued: BotQueuedMessage[]; + /** Queued submission ids already classified as quiet (true) or the person's (false). */ + inputKinds: Map; + /** Classifying failed and has not succeeded since; logged once per streak. */ + classifyFailing: boolean; + /** No classification attempt before this time (a throttle for a persistent failure). */ + classifyNotBefore: number; + classifyRetry: ReturnType | null; + /** When the current running turn started. */ + startedAt: number; + stopping: boolean; + resuming: boolean; + /** The newest frame, so approvals, questions and Stop can re-derive the activity. */ + frame: { entries: readonly EntryRecord[]; docs: Readonly> }; runActive: boolean; + /** Identity of the current run; a follow-up turn replaces the run without a gap. */ + runKey: string | null; watch: ConversationWatch; cancel: () => void; ended: boolean; @@ -457,6 +652,9 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro const maxPending = deps.maxPending ?? BOT_LIVE_MAX_PENDING_EVENTS; const schedule = deps.schedule ?? ((flush: () => void) => void setTimeout(flush, 0)); const newEpoch = deps.newEpoch ?? (() => randomUUID()); + const now = deps.now ?? Date.now; + /** Bots whose next run is a Resume. */ + const resumingBots = new Set(); const feeds = new Map(); const opening = new Map>(); const subscribers = new Map>(); @@ -464,6 +662,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro const lastSeq = new Map(); const report = (botId: string, error: unknown) => deps.onError?.(botId, error); + const classifyRetryMs = deps.classifyRetryMs ?? 1_000; function snapshotOf(feed: Feed): BotLiveSnapshot { return { @@ -474,6 +673,8 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro partial: feed.partial, state: feed.state, question: feed.question, + activity: feed.activity, + queued: feed.queued, }; } @@ -533,6 +734,39 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro for (const subscriber of subscribers.get(feed.botId) ?? []) enqueue(subscriber, feed.botId, event); } + function waitingOn(feed: Feed): boolean { + return feed.question !== null || deps.approvalPending?.(feed.botId) === true; + } + + /** Null unless the session is running: a paused Bot keeps `pi.live.run` but is not working. */ + function computeActivity(feed: Feed): BotLiveActivity | null { + if (feed.state.kind !== "running") return null; + return ( + liveBotActivity({ + ...feed.frame, + waiting: waitingOn(feed), + stopping: feed.stopping, + resuming: feed.resuming, + startedAt: feed.startedAt, + }) ?? { phase: "preparing", startedAt: feed.startedAt } + ); + } + + function updateActivity(feed: Feed): void { + const activity = computeActivity(feed); + if (activity && activity.phase !== "resuming") feed.resuming = false; + if (JSON.stringify(activity) === JSON.stringify(feed.activity)) return; + feed.activity = activity; + emit(feed, { type: "activity", activity }); + } + + /** A new run began: its start time, Stop and Resume marks belong to it alone. */ + function startRun(feed: Feed): void { + feed.startedAt = now(); + feed.stopping = false; + feed.resuming = resumingBots.delete(feed.botId); + } + async function resolveCards(botId: string, entries: BotTranscriptEntry[]): Promise { if (!deps.connectCardStatus) return entries; const resolved: BotTranscriptEntry[] = []; @@ -561,30 +795,104 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro for (const entry of next.slice(previous.length)) emit(feed, { type: "entry", entry }); } + /** + * The person's queued messages. Each queued id is classified once; an id that + * is not yet classified as the person's own stays hidden (fail closed), so a + * routine's prompt never shows as a message the person sent. A failed or + * incomplete classification is retried after a pause, not on every frame. + */ + async function queuedFor(feed: Feed, docs: Readonly>): Promise { + const ids = liveQueuedInputIds(docs); + for (const id of [...feed.inputKinds.keys()]) if (!ids.includes(id)) feed.inputKinds.delete(id); + const unknown = ids.filter((id) => !feed.inputKinds.has(id)); + if (unknown.length > 0 && now() >= feed.classifyNotBefore) { + try { + const answers = await deps.quietInputs(feed.botId, unknown); + for (const id of unknown) { + const quiet = answers.get(id); + if (quiet !== undefined) feed.inputKinds.set(id, quiet); + } + feed.classifyFailing = false; + } catch (error) { + if (!feed.classifyFailing) report(feed.botId, error); + feed.classifyFailing = true; + } + if (unknown.some((id) => !feed.inputKinds.has(id))) scheduleClassifyRetry(feed); + } else if (unknown.length > 0) { + scheduleClassifyRetry(feed); + } + return liveQueuedMessages(docs, new Set(ids.filter((id) => feed.inputKinds.get(id) !== false))); + } + + /** One retry after the pause, through the feed queue, even if no frame arrives. */ + function scheduleClassifyRetry(feed: Feed): void { + feed.classifyNotBefore = Math.max(feed.classifyNotBefore, now() + classifyRetryMs); + if (feed.classifyRetry !== null || feed.ended) return; + feed.classifyRetry = setTimeout(() => { + feed.classifyRetry = null; + void enqueueWork(feed, async () => { + if (feed.ended) return; + feed.classifyNotBefore = 0; + const queued = await queuedFor(feed, feed.frame.docs); + if (JSON.stringify(queued) !== JSON.stringify(feed.queued)) { + feed.queued = queued; + emit(feed, { type: "queued", queued }); + } + }); + }, classifyRetryMs); + feed.classifyRetry.unref?.(); + } + async function onFrame(feed: Feed, entries: readonly EntryRecord[], docs: Readonly>) { if (feed.ended) return; + feed.frame = { entries, docs }; + const runKey = liveRunKey(docs); + // A queued follow-up replaces the run without the feed ever seeing it end. + if (runKey !== null && feed.runKey !== null && runKey !== feed.runKey && feed.state.kind === "running") { + startRun(feed); + } + feed.runKey = runKey; applyEntries(feed, await resolveCards(feed.botId, projectBotTranscript(entries))); const partial = livePartialText(docs); if (partial !== feed.partial) { feed.partial = partial; emit(feed, { type: "partial", text: partial }); } + const queued = await queuedFor(feed, docs); + if (JSON.stringify(queued) !== JSON.stringify(feed.queued)) { + feed.queued = queued; + emit(feed, { type: "queued", queued }); + } const runActive = liveRunActive(docs); - if (runActive !== feed.runActive) { - feed.runActive = runActive; - const state = await deps.state(feed.botId).catch(() => feed.state); - setState(feed, state); - if (!runActive) { - deps.onRunSettled?.(feed.botId, state); - void closeIfUnwatched(feed); - } + if (runActive === feed.runActive) { + updateActivity(feed); + return; + } + feed.runActive = runActive; + // The run's end is reported with its new state, so the line never flashes a phase after the reply. + const state = await deps.state(feed.botId).catch(() => feed.state); + setState(feed, state); + updateActivity(feed); + if (!runActive) { + feed.stopping = false; + feed.resuming = false; + resumingBots.delete(feed.botId); + deps.onRunSettled?.(feed.botId, state); + void closeIfUnwatched(feed); } } function setState(feed: Feed, state: BotSessionState): void { if (JSON.stringify(state) === JSON.stringify(feed.state)) return; + const wasRunning = feed.state.kind === "running"; feed.state = state; + if (state.kind === "running" && !wasRunning) startRun(feed); + if (state.kind !== "running") { + feed.stopping = false; + feed.resuming = false; + } emit(feed, { type: "state", state }); + updateActivity(feed); } function enqueueWork(feed: Feed, work: () => Promise): Promise { @@ -611,12 +919,26 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro partial: livePartialText(initial.docs), state: await deps.state(botId), question: deps.question?.(botId) ?? null, + activity: null, + queued: [], + inputKinds: new Map(), + classifyFailing: false, + classifyNotBefore: 0, + classifyRetry: null, + startedAt: now(), + stopping: false, + resuming: false, + frame: { entries: initial.entries, docs: initial.docs }, runActive: liveRunActive(initial.docs), + runKey: liveRunKey(initial.docs), watch, cancel: () => cancel(new Error("Bot live feed closed.")), ended: false, queue: Promise.resolve(), }; + if (feed.state.kind === "running") startRun(feed); + feed.activity = computeActivity(feed); + feed.queued = await queuedFor(feed, initial.docs); feeds.set(botId, feed); watch.start((value) => enqueueWork(feed, () => onFrame(feed, value.entries, value.docs))); void watch.closed.then(() => { @@ -655,6 +977,8 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro async function stopFeed(feed: Feed): Promise { feed.ended = true; + if (feed.classifyRetry !== null) clearTimeout(feed.classifyRetry); + feed.classifyRetry = null; if (feeds.get(feed.botId) === feed) feeds.delete(feed.botId); await feed.watch.stop().catch(() => undefined); feed.cancel(); @@ -673,6 +997,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro if (question?.waitId === feed.question?.waitId) return; feed.question = question; emit(feed, { type: "question", question }); + updateActivity(feed); }); } @@ -701,6 +1026,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro }, notifyState(botId, state) { + if (state.kind !== "running") resumingBots.delete(botId); const feed = feeds.get(botId); if (feed && !feed.ended) { void enqueueWork(feed, async () => setState(feed, state)); @@ -714,6 +1040,35 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro ); }, + notifyStopping(botId) { + const feed = feeds.get(botId); + if (!feed || feed.ended) return; + void enqueueWork(feed, async () => { + if (feed.state.kind !== "running") return; + feed.stopping = true; + updateActivity(feed); + }); + }, + + notifyResuming(botId) { + resumingBots.add(botId); + }, + + cancelStopping(botId) { + const feed = feeds.get(botId); + if (!feed || feed.ended) return; + void enqueueWork(feed, async () => { + feed.stopping = false; + updateActivity(feed); + }); + }, + + async refreshActivity(botId) { + const feed = feeds.get(botId); + if (!feed || feed.ended) return; + await enqueueWork(feed, async () => updateActivity(feed)); + }, + async refresh(botId) { const feed = feeds.get(botId); if (!feed || feed.ended) return; diff --git a/main/services/bot-store-core.test.ts b/main/services/bot-store-core.test.ts index b03ffdcd00..57bcbca975 100644 --- a/main/services/bot-store-core.test.ts +++ b/main/services/bot-store-core.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { createBotStore } from "./bot-store-core.js"; -import { DEFAULT_BOT_AVATAR } from "../../renderer/shared/bots.js"; +import { DEFAULT_BOT_AVATAR, resolveBotChatActivity } from "../../renderer/shared/bots.js"; async function fixture() { const root = await mkdtemp(join(tmpdir(), "aiden-bots-")); @@ -302,3 +302,84 @@ test("bot store rejects unsupported document versions and enforces bounded requi await rm(root, { recursive: true, force: true }); } }); + +test("a Bot's chat activity is saved with a new revision, and identity edits that leave it out keep it", async () => { + const { root, store } = await fixture(); + try { + const created = await store.create({ + name: "Planner", + instructions: "Plan dinners.", + avatar: { version: 1, shape: "hex", color: "sun" }, + }); + assert.equal(created.chatActivity, undefined, "new Bots store nothing: absent means Quiet"); + const chosen = await store.update({ + id: created.id, + expectedRevision: created.revision, + name: created.name, + instructions: created.instructions, + avatar: created.avatar, + chatActivity: { level: "summary", wording: "thinking" }, + }); + assert.deepEqual(chosen.chatActivity, { level: "summary", wording: "thinking" }); + assert.notEqual(chosen.revision, created.revision); + const reopened = await createBotStore({ root: () => root, now: () => 500 }).get(created.id); + assert.equal(reopened?.revision, chosen.revision, "a saved record and the reloaded one share a revision"); + const renamed = await store.update({ + id: created.id, + expectedRevision: chosen.revision, + name: "Meal planner", + instructions: created.instructions, + avatar: created.avatar, + }); + assert.equal(renamed.name, "Meal planner"); + assert.deepEqual(renamed.chatActivity, { level: "summary", wording: "thinking" }); + await assert.rejects( + store.update({ + id: created.id, + expectedRevision: renamed.revision, + name: renamed.name, + instructions: renamed.instructions, + avatar: renamed.avatar, + chatActivity: { level: "verbose", wording: "follows" } as never, + }), + /chat activity/u, + ); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a stored chat activity that isn't a current choice reads as absent and keeps the Bot", async () => { + const { root } = await fixture(); + try { + const bot = (id: string, chatActivity: unknown) => ({ + id, + name: id, + instructions: "x", + avatar: { version: 1, shape: "orb", color: "sky" }, + createdAt: 1, + updatedAt: 1, + chatActivity, + }); + await writeFile( + join(root, "bots.json"), + JSON.stringify({ + version: 1, + bots: [ + bot("bot:newer", { level: "verbose", wording: "follows" }), + bot("bot:extra", { level: "summary", wording: "follows", sound: true }), + bot("bot:good", { level: "detailed", wording: "follows" }), + ], + }), + ); + const store = createBotStore({ root: () => root, now: () => 50 }); + const byId = new Map((await store.list()).map((entry) => [entry.id, entry.chatActivity])); + assert.equal(byId.size, 3, "no Bot is lost to a bad setting"); + assert.equal(byId.get("bot:newer"), undefined); + assert.equal(byId.get("bot:extra"), undefined); + assert.deepEqual(byId.get("bot:good"), { level: "detailed", wording: "follows" }); + assert.deepEqual(resolveBotChatActivity(byId.get("bot:newer")), { level: "quiet", wording: "follows" }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/main/services/bot-store-core.ts b/main/services/bot-store-core.ts index ca45cb0937..c42e401e3f 100644 --- a/main/services/bot-store-core.ts +++ b/main/services/bot-store-core.ts @@ -5,6 +5,7 @@ import { DEFAULT_BOT_AVATAR, isBotAvatar, isBotAvatarAppearance, + parseBotChatActivity, type BotAvatarAppearance, type BotCreateInput, type BotDefinition, @@ -108,6 +109,7 @@ function projectBot(value: unknown): StoredBotDefinition | null { const avatar: BotAvatarAppearance = isBotAvatarAppearance(bot.avatar) ? { version: 1, shape: bot.avatar.shape, color: bot.avatar.color } : { ...DEFAULT_BOT_AVATAR }; + const chatActivity = parseBotChatActivity(bot.chatActivity); const projected = { id: bot.id as string, name: (bot.name as string).trim(), @@ -120,6 +122,9 @@ function projectBot(value: unknown): StoredBotDefinition | null { createdAt: bot.createdAt as number, updatedAt: bot.updatedAt as number, ...(typeof bot.archivedAt === "number" ? { archivedAt: bot.archivedAt } : {}), + // Last, so a freshly saved choice and a reloaded record serialise (and hash into the revision) alike. + // A choice this build does not know reads as absent (Quiet); the Bot itself is kept. + ...(chatActivity ? { chatActivity } : {}), }; return projected; } @@ -256,6 +261,8 @@ export function createBotStore(options: { async update(input: BotUpdateInput): Promise { return queueMutation(async () => { const normalized = normalizeInput(input); + const chatActivity = input.chatActivity === undefined ? undefined : parseBotChatActivity(input.chatActivity); + if (input.chatActivity !== undefined && !chatActivity) throw new Error("Choose a valid chat activity."); await loadBotState(); return store.update((draft) => { const bot = draft.bots.find((entry) => entry.id === input.id); @@ -270,6 +277,7 @@ export function createBotStore(options: { if (normalized.description) bot.description = normalized.description; else delete bot.description; bot.avatar = { version: 1, shape: normalized.avatar.shape, color: normalized.avatar.color }; + if (chatActivity) bot.chatActivity = chatActivity; bot.updatedAt = nextIdentityTimestamp(bot.updatedAt, now); return structuredClone(botForRenderer(bot)); }); diff --git a/package.json b/package.json index 2e84d812a4..e1f8cfa35f 100644 --- a/package.json +++ b/package.json @@ -128,8 +128,8 @@ "pi-upgrade:advance": "node --import tsx scripts/pi-upgrade-advance.mjs", "pretest:bots": "npm run build:bot-inbox-writer && node scripts/build-bot-inbox-writer.mjs --test && node --test scripts/bot-inbox-writer.test.mjs && tsx --test main/services/bot-share-image-tool.test.ts main/services/bot-inbound-attachment-inbox.test.ts main/services/vision-analysis-tool.test.ts", "test:telegram": "tsx --test main/services/telegram/bot-reply-outbox.test.ts main/services/telegram/telegram-profile-mutation-fence.test.ts main/services/telegram/telegram-controls.test.ts main/services/telegram/telegram-inbound.test.ts main/services/telegram/telegram-outbound.test.ts main/services/telegram/telegram-queue.test.ts main/services/telegram/telegram-markdown.test.ts main/services/telegram/telegram-bot-api.test.ts main/services/telegram/telegram-turn.test.ts main/services/telegram/telegram-session.test.ts main/services/telegram/telegram-service-core.test.ts main/services/telegram/telegram-workspace-core.test.ts main/services/telegram/telegram-activity.test.ts main/services/telegram/telegram-profile-config.test.ts main/services/telegram/telegram-extension-registry.test.ts main/services/telegram/telegram-thread-store.test.ts main/services/telegram/telegram-ownership.test.ts main/services/telegram/telegram-agent-tools.test.ts main/services/telegram/telegram-bot-binding-store.test.ts main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts renderer/lib/telegram-workspace-options.test.ts", - "test:bots": "tsx --test main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts main/services/bot-avatar-store.test.ts main/services/bot-store-core.test.ts main/services/bot-chat-store.test.ts main/services/bot-mutation-gate.test.ts main/services/bot-inbox-projection.test.ts main/services/bot-system-prompt.test.ts main/services/bot-generation-preparation.test.ts main/services/bot-inbound-attachment-home.test.ts main/services/bot-file-tool-router.test.ts main/services/bot-tool-authority.test.ts main/services/bot-capability-store-core.test.ts main/services/bot-capability-store.test.ts main/services/bot-capability-state-checkpoint.test.ts main/services/bot-capability-keychain-anchor.test.ts main/services/bot-capability-secret-service-anchor.test.ts main/services/bot-capability-lease.test.ts main/services/bot-runtime-inventory-lease.test.ts main/services/bot-runtime-inventory-publication.test.ts main/services/bot-runtime-authority.test.ts main/services/bot-capability-catalog-core.test.ts main/services/bot-capability-bindings.test.ts main/services/bot-capability-key-store.test.ts main/services/bot-capability-migration-seal.test.ts main/services/bot-capability-incarnation-store.test.ts main/services/bot-capability-inventory-ports.test.ts main/services/bot-capability-production-shape.test.ts main/services/bot-mcp-inventory.test.ts main/services/bot-skill-inventory.test.ts main/services/bot-skill-content-watcher.test.ts main/services/bot-managed-workspace-core.test.ts main/services/bot-lifecycle-journal-core.test.ts main/services/bot-application-service.test.ts main/handlers/bot-params.test.ts main/handlers/bot-renderer-errors.test.ts main/handlers/bots.contract.test.ts renderer/main/bots-view.test.tsx renderer/main/bots/bot-character-card.test.tsx renderer/main/bots/bot-chat-header.test.tsx renderer/main/bots/bot-chat-mode.test.tsx renderer/main/bots/bot-delete-dialog.test.tsx renderer/main/bots/bot-list.test.tsx renderer/main/bots/bots-home.test.tsx renderer/main/bots/bot-create-flow.test.tsx renderer/main/bots/bot-profile.test.tsx renderer/main/bots/bot-profile-photo.test.tsx renderer/lib/model-picker-data.test.ts renderer/lib/command-system-core.test.ts renderer/shared/bot-capabilities.test.ts renderer/shared/bot-presets.test.ts renderer/shared/bot-connections.test.ts renderer/components/bots/bot-connection-ui.test.tsx main/services/bot-runtime-tools/suggest-connection.test.ts main/services/bot-connection-dismissals.test.ts main/handlers/bot-live.test.ts main/handlers/bot-questions.test.ts renderer/main/bots/bot-chat-pane.test.tsx renderer/main/bots/bot-routines.test.tsx main/services/bot-connection-setup-core.test.ts main/handlers/bot-files.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-memory-page.test.tsx main/services/bot-routine-notes.test.ts main/services/bot-routine-proposals.test.ts main/services/bot-routine-notifications.test.ts renderer/main/bots/bot-model-choice.test.ts renderer/main/bots/bot-model-picker.test.tsx", - "test:bot-runtime": "tsx --test main/services/bot-runtime/profile-lock.test.ts main/services/bot-runtime/harness-host.test.ts main/services/bot-runtime/tool-adapter.test.ts main/services/bot-runtime/bot-extension.test.ts main/services/bot-runtime/bot-session-service.test.ts main/services/bot-runtime/bot-tool-assembly.test.ts main/services/bot-runtime/bot-delete.test.ts main/services/bot-runtime/live-projection.test.ts main/services/bot-runtime/bot-starter.test.ts main/services/bot-runtime/bot-question-tool.test.ts main/services/bot-memory/store.test.ts main/services/bot-memory/scan.test.ts main/services/bot-memory/tool.test.ts main/services/bot-memory/compaction.test.ts main/services/bot-memory/review.test.ts main/handlers/bot-memory.test.ts", + "test:bots": "tsx --test main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts main/services/bot-avatar-store.test.ts main/services/bot-store-core.test.ts main/services/bot-chat-store.test.ts main/services/bot-mutation-gate.test.ts main/services/bot-inbox-projection.test.ts main/services/bot-system-prompt.test.ts main/services/bot-generation-preparation.test.ts main/services/bot-inbound-attachment-home.test.ts main/services/bot-file-tool-router.test.ts main/services/bot-tool-authority.test.ts main/services/bot-capability-store-core.test.ts main/services/bot-capability-store.test.ts main/services/bot-capability-state-checkpoint.test.ts main/services/bot-capability-keychain-anchor.test.ts main/services/bot-capability-secret-service-anchor.test.ts main/services/bot-capability-lease.test.ts main/services/bot-runtime-inventory-lease.test.ts main/services/bot-runtime-inventory-publication.test.ts main/services/bot-runtime-authority.test.ts main/services/bot-capability-catalog-core.test.ts main/services/bot-capability-bindings.test.ts main/services/bot-capability-key-store.test.ts main/services/bot-capability-migration-seal.test.ts main/services/bot-capability-incarnation-store.test.ts main/services/bot-capability-inventory-ports.test.ts main/services/bot-capability-production-shape.test.ts main/services/bot-mcp-inventory.test.ts main/services/bot-skill-inventory.test.ts main/services/bot-skill-content-watcher.test.ts main/services/bot-managed-workspace-core.test.ts main/services/bot-lifecycle-journal-core.test.ts main/services/bot-application-service.test.ts main/handlers/bot-params.test.ts main/handlers/bot-renderer-errors.test.ts main/handlers/bots.contract.test.ts renderer/main/bots-view.test.tsx renderer/main/bots/bot-character-card.test.tsx renderer/main/bots/bot-chat-header.test.tsx renderer/main/bots/bot-chat-mode.test.tsx renderer/main/bots/bot-delete-dialog.test.tsx renderer/main/bots/bot-list.test.tsx renderer/main/bots/bots-home.test.tsx renderer/main/bots/bot-create-flow.test.tsx renderer/main/bots/bot-profile.test.tsx renderer/main/bots/bot-profile-photo.test.tsx renderer/lib/model-picker-data.test.ts renderer/lib/command-system-core.test.ts renderer/shared/bot-capabilities.test.ts renderer/shared/bot-presets.test.ts renderer/shared/bot-connections.test.ts renderer/components/bots/bot-connection-ui.test.tsx main/services/bot-runtime-tools/suggest-connection.test.ts main/services/bot-connection-dismissals.test.ts main/handlers/bot-live.test.ts main/handlers/bot-questions.test.ts renderer/main/bots/bot-chat-pane.test.tsx renderer/main/bots/bot-routines.test.tsx main/services/bot-connection-setup-core.test.ts main/handlers/bot-files.test.ts renderer/main/bots/bot-transcript-rows.test.ts renderer/main/bots/bot-memory-page.test.tsx main/services/bot-routine-notes.test.ts main/services/bot-routine-proposals.test.ts main/services/bot-routine-notifications.test.ts renderer/main/bots/bot-model-choice.test.ts renderer/main/bots/bot-model-picker.test.tsx renderer/shared/bot-activity.test.ts renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-activity-recap.test.tsx renderer/main/bots/bot-chat-activity-page.test.tsx", + "test:bot-runtime": "tsx --test main/services/bot-runtime/profile-lock.test.ts main/services/bot-runtime/harness-host.test.ts main/services/bot-runtime/tool-adapter.test.ts main/services/bot-runtime/bot-extension.test.ts main/services/bot-runtime/bot-session-service.test.ts main/services/bot-runtime/bot-tool-assembly.test.ts main/services/bot-runtime/bot-delete.test.ts main/services/bot-runtime/live-projection.test.ts main/services/bot-runtime/bot-starter.test.ts main/services/bot-runtime/bot-question-tool.test.ts main/services/bot-memory/store.test.ts main/services/bot-memory/scan.test.ts main/services/bot-memory/tool.test.ts main/services/bot-memory/compaction.test.ts main/services/bot-memory/review.test.ts main/handlers/bot-memory.test.ts main/services/bot-runtime/bot-activity-detail.test.ts", "test:bots:coverage": "node scripts/run-registered-tests-with-coverage.mjs test:bots", "test:voice": "tsx --test main/services/dictation-hold-settings.test.ts main/services/linux-dictation-portal.test.ts main/services/transcription-core.test.ts main/services/gemini-live-transcription-core.test.ts main/services/dictation-coordinator.test.ts main/services/dictation-paste.test.ts main/services/local-speech-protocol.test.ts main/services/local-speech-process-core.test.ts main/services/local-speech-worker-host.test.ts main/services/local-speech-lane.test.ts renderer/shared/voice-models.test.ts renderer/shared/gemini-usage-scope.test.ts renderer/components/settings/gemini-voice-setup.test.tsx renderer/lib/accessibility-permission-core.test.ts renderer/lib/accessibility-refresh.test.ts renderer/lib/dictation-operation-gate.test.ts renderer/lib/gemini-recorded-retry.test.ts renderer/lib/live-pcm-capture.test.ts renderer/lib/voice-recorder-core.test.ts renderer/lib/wav-audio.test.ts main/services/local-speech-idle-unload.test.ts renderer/shared/dictation-dictionary.test.ts renderer/shared/dictation-preferences.test.ts renderer/components/settings/dictation-dictionary-settings.test.tsx renderer/pill/pill-copied-notice.test.tsx main/services/local-speech-catalog.test.ts main/services/local-speech-downloads.test.ts renderer/shared/voice-language.test.ts renderer/shared/voice-preferences.test.ts main/services/local-speech-vad.test.ts main/services/local-speech-engine.test.ts main/services/local-speech-worker-core.test.ts renderer/shared/voice-provider.test.ts main/services/transcription-routing.test.ts main/services/local-speech-opus.test.ts main/services/voice-provider-resolution.test.ts renderer/components/settings/local-voice-settings.test.tsx renderer/components/settings/model-manager-view.test.tsx renderer/components/settings/voice-settings.test.tsx renderer/lib/slow-model-load.test.ts main/services/local-speech-model-state.test.ts renderer/pill/pill-app.test.tsx main/services/dictation-voice-check.test.ts", "test:tts": "tsx --test main/services/tts/authority-contract.test.ts renderer/components/settings/tts-settings.test.tsx main/services/tts/audio-store.test.ts renderer/lib/tts-client.test.ts renderer/lib/tts-player.test.ts main/services/tts/speech-text.test.ts main/services/tts/source.test.ts main/services/tts/gemini-wire.test.ts main/services/tts/service.test.ts main/services/tts/gemini-provider.loopback.test.ts renderer/components/message-bubble.test.tsx renderer/shared/tts.test.ts", diff --git a/renderer/components/aiden-activity-mark.tsx b/renderer/components/aiden-activity-mark.tsx index bfa077de5e..bad8f6beed 100644 --- a/renderer/components/aiden-activity-mark.tsx +++ b/renderer/components/aiden-activity-mark.tsx @@ -124,12 +124,20 @@ function visibilityObserver(): IntersectionObserver | null { if (typeof IntersectionObserver === "undefined") return null; sharedObserver ??= new IntersectionObserver((entries) => { for (const entry of entries) { - (entry.target as SVGElement).toggleAttribute("data-offscreen", !entry.isIntersecting); + (entry.target as Element).toggleAttribute("data-offscreen", !entry.isIntersecting); } }); return sharedObserver; } +/** Pause an element's animations while it is scrolled out of view (`data-offscreen`), on the shared observer. */ +export function observeOffscreen(node: Element): () => void { + const observer = visibilityObserver(); + if (!observer) return () => undefined; + observer.observe(node); + return () => observer.unobserve(node); +} + function reduceMotionActive(): boolean { return document.documentElement.dataset.reduceMotion === "true" || window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true; @@ -175,10 +183,7 @@ export function AidenActivityMark({ React.useEffect(() => { const node = ref.current; - const observer = visibilityObserver(); - if (!node || !observer) return; - observer.observe(node); - return () => observer.unobserve(node); + return node ? observeOffscreen(node) : undefined; }, []); React.useEffect(() => { diff --git a/renderer/components/bot-avatar.tsx b/renderer/components/bot-avatar.tsx index 87f4ea3118..c9b500e085 100644 --- a/renderer/components/bot-avatar.tsx +++ b/renderer/components/bot-avatar.tsx @@ -4,6 +4,7 @@ import { type BotAvatar as BotAvatarValue, type BotAvatarShape, } from "../shared/bots"; +import { AidenActivityMark, observeOffscreen } from "./aiden-activity-mark"; import { useBotCanonicalPhoto } from "../lib/bot-canonical-photo-cache"; interface AvatarBody { @@ -55,21 +56,17 @@ const avatarBodies: Record = { }, }; -/** The one fixed eye mark every Bot shares; only colour and shape vary. */ +/** The one fixed eye mark every Bot shares; only colour and shape vary. Eyes glance while working. */ function EyeMark({ y, spread }: { y: number; spread: number }) { - const left = 20 - spread; - const right = 20 + spread; return ( - <> - - - - - - - - - + + {[20 - spread, 20 + spread].map((x) => ( + + + + + ))} + ); } @@ -114,12 +111,15 @@ export function BotAvatar({ name, photoLoading = "none", size = "medium", + working = false, }: { avatar: BotAvatarValue; botId?: string; name: string; photoLoading?: "none" | "visible" | "immediate"; size?: "small" | "medium" | "large" | "preview"; + /** The Bot is in a running turn: its face glances (a photo shows a small activity badge instead). */ + working?: boolean; }) { const avatarRef = React.useRef(null); const [nearViewport, setNearViewport] = React.useState(photoLoading === "immediate"); @@ -151,12 +151,18 @@ export function BotAvatar({ ); const [failedRevision, setFailedRevision] = React.useState(); const showPhoto = photo && failedRevision !== photo.assetRevision; + React.useEffect(() => { + const node = avatarRef.current; + if (!working || !node) return; + return observeOffscreen(node); + }, [working]); return ( ); } diff --git a/renderer/lib/ipc.ts b/renderer/lib/ipc.ts index e50ed10e04..ead90d3f74 100644 --- a/renderer/lib/ipc.ts +++ b/renderer/lib/ipc.ts @@ -1368,6 +1368,12 @@ export const botsApi = { invoke("bots:dismiss", { botId, requestId }), /** Stop the reply that is running now. */ stop: (botId: string) => invoke("bots:stop", botId), + /** Remove a queued message before its turn starts. */ + withdraw: (botId: string, submissionId: string) => + invoke("bots:withdraw", { + botId, + submissionId, + }), /** Answer a Bot tool approval by its wait id; the first answer wins. */ approve: (waitId: string, decision: "allow" | "deny") => invoke<{ decided: boolean }>("bots:approve", { waitId, decision }), diff --git a/renderer/main/bots-view.tsx b/renderer/main/bots-view.tsx index a982aa91c8..610a361d34 100644 --- a/renderer/main/bots-view.tsx +++ b/renderer/main/bots-view.tsx @@ -7,6 +7,7 @@ import { botsApi } from "../lib/ipc"; import { useBot, useBots } from "../lib/queries"; import type { BotDefinition } from "../shared/bots"; import { BotAdvanced } from "./bots/bot-advanced"; +import { BotChatActivityPage } from "./bots/bot-chat-activity-page"; import { BotCreateFlow } from "./bots/bot-create-flow"; import { BotDeleteDialog } from "./bots/bot-delete-dialog"; import { BotInstructionsEditor } from "./bots/bot-instructions-editor"; @@ -131,7 +132,14 @@ function BotPage({ botId }: { botId: string }) { {page === "instructions" ? ( ) : page === "advanced" ? ( - + openPage("chat-activity")} + /> + ) : page === "chat-activity" ? ( + openPage("advanced")} /> ) : page === "memory" ? ( ) : ( diff --git a/renderer/main/bots/bot-activity-recap.test.tsx b/renderer/main/bots/bot-activity-recap.test.tsx new file mode 100644 index 0000000000..f93fb144d6 --- /dev/null +++ b/renderer/main/bots/bot-activity-recap.test.tsx @@ -0,0 +1,91 @@ +import "./test-dom"; +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { cleanup, fireEvent, render, screen, within } from "@testing-library/react"; +import { BotActivityRecap } from "./bot-activity-recap"; +import type { BotRecapStep } from "./bot-activity-steps"; + +afterEach(cleanup); + +const ok = (id: string, kind: BotRecapStep["kind"], label: string, extra: Partial = {}): BotRecapStep => ({ + id, + kind, + label, + status: "ok", + ...extra, +}); + +const TURN: BotRecapStep[] = [ + ok("1", "reading", "Read 1 file", { detail: "a.md" }), + ok("2", "reading", "Read 1 file", { detail: "b.md" }), + ok("3", "searching", "Searched the web", { detail: "lisbon trains" }), + ok("4", "app", "Used Notion", { app: "Notion" }), +]; + +const itemTexts = () => + within(screen.getByRole("list", { name: "Steps" })).getAllByRole("listitem").map((item) => item.textContent); + +test("a finished recap is one closed line that opens to its merged steps", () => { + render(); + const header = screen.getByRole("button", { name: "Worked for 18s · read 2 files, searched the web, used Notion" }); + assert.equal(header.getAttribute("aria-expanded"), "false"); + fireEvent.click(header); + assert.deepEqual(itemTexts(), ["Read 2 files", "Searched the web · lisbon trains", "Used Notion"]); +}); + +test("Detailed opens while live with the last three steps, and folds itself when the reply lands", () => { + const live = [...TURN, { id: "5", kind: "editing" as const, label: "Edited 1 file", detail: "plan.md", status: "running" as const }]; + const { rerender } = render(); + assert.deepEqual(itemTexts(), ["Searched the web · lisbon trains", "Used Notion", "Editing files · plan.md"]); + rerender( ({ ...step, status: "ok" }))} durationMs={9_000} live={false} level="detailed" />); + assert.equal(screen.queryByRole("list", { name: "Steps" }), null); +}); + +test("a manual close or open during the run sticks after the reply lands", () => { + const { rerender } = render(); + fireEvent.click(screen.getByRole("button", { name: /^Working/u })); + rerender(); + assert.equal(screen.queryByRole("list", { name: "Steps" }), null, "closed by hand stays closed while live"); + fireEvent.click(screen.getByRole("button", { name: /^Working/u })); + rerender(); + assert.ok(screen.getByRole("list", { name: "Steps" }), "opened by hand stays open after the reply"); +}); + +test("a failed step is a red issue and a refused one is amber Blocked, never alike", () => { + render( + , + ); + const header = screen.getByRole("button", { name: "Worked for 5s · read 1 file · 1 issue · 1 blocked" }); + fireEvent.click(header); + assert.ok(screen.getByText("Couldn’t run a command")); + assert.ok(screen.getByText("Blocked: search the web")); +}); + +test("a step the person stopped is a neutral line, never an issue or a block, and reads fine without a detail", () => { + render( + , + ); + const header = screen.getByRole("button", { name: "Worked for 7s · read 1 file" }); + fireEvent.click(header); + assert.deepEqual(itemTexts(), ["Read 1 file", "Stopped: run a command"]); + assert.equal(screen.queryByText(/issue/u), null); + assert.equal(screen.queryByText(/Couldn’t/u), null); + assert.equal(screen.queryByText(/blocked/iu), null); +}); diff --git a/renderer/main/bots/bot-activity-recap.tsx b/renderer/main/bots/bot-activity-recap.tsx new file mode 100644 index 0000000000..ba92d64ab0 --- /dev/null +++ b/renderer/main/bots/bot-activity-recap.tsx @@ -0,0 +1,85 @@ +// One collapsed account of a turn's steps (spec §6). Summary: closed. Detailed: +// open while the turn runs (its last three steps, the active one shimmering) +// and folded when the reply lands. A manual open or close sticks. Tones reuse +// the activity feed's tokens; red is a failure, amber a refusal, and a step the +// person stopped stays neutral. + +import * as React from "react"; +import { ChevronRight } from "lucide-react"; +import type { BotChatActivityLevel } from "../../shared/bots"; +import { + botRecapHeader, + botRecapIssues, + botStepLine, + mergeBotSteps, + type BotRecapStep, +} from "./bot-activity-steps"; + +const LIVE_ROWS = 3; + +function toneClass(tone: "normal" | "warning" | "error"): string { + if (tone === "error") return "text-red"; + if (tone === "warning") return "text-support-warning"; + return "text-secondary"; +} + +function RecapStepRow({ step }: { step: BotRecapStep }) { + const line = botStepLine(step); + return ( +
+ + {line.text} + {line.detail ? · {line.detail} : null} + +
+ ); +} + +export function BotActivityRecap({ + steps, + durationMs, + live, + level, +}: { + steps: readonly BotRecapStep[]; + durationMs: number; + live: boolean; + level: BotChatActivityLevel; +}) { + const [choice, setChoice] = React.useState(null); + const regionId = React.useId(); + const open = choice ?? (live && level === "detailed"); + const issues = botRecapIssues(steps); + const header = botRecapHeader(steps, durationMs, live); + const issueText = issues.failed ? (issues.failed === 1 ? "1 issue" : `${issues.failed} issues`) : ""; + const blockedText = issues.blocked ? `${issues.blocked} blocked` : ""; + const name = [header, issueText, blockedText].filter(Boolean).join(" · "); + const shown = live ? steps.slice(-LIVE_ROWS) : mergeBotSteps(steps); + return ( +
+ + {open ? ( +
+ {shown.map((step) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/renderer/main/bots/bot-activity-steps.ts b/renderer/main/bots/bot-activity-steps.ts new file mode 100644 index 0000000000..46c04b0621 --- /dev/null +++ b/renderer/main/bots/bot-activity-steps.ts @@ -0,0 +1,95 @@ +// A turn's tool steps as the recap shows them (spec §6): merged repeats +// ("Read 6 files"), one deterministic sentence, and failed, refused and +// stopped steps that never look alike. + +import { + botDurationLabel, + botPhaseWord, + botStepInfinitive, + botStepPhrase, + type BotToolPhase, +} from "../../shared/bot-activity"; +import type { BotToolResultStatus } from "../../shared/bot-live"; + +export type BotRecapStepStatus = BotToolResultStatus | "running"; + +export interface BotRecapStep { + id: string; + kind: BotToolPhase; + /** Past tense: "Read 1 file". */ + label: string; + /** Absent when the model gave no description of the action. */ + detail?: string; + app?: string; + status: BotRecapStepStatus; + /** Set on a merged row. */ + count?: number; +} + +/** Consecutive successful steps of the same kind (and app) become one row. */ +export function mergeBotSteps(steps: readonly BotRecapStep[]): BotRecapStep[] { + const merged: BotRecapStep[] = []; + for (const step of steps) { + const last = merged[merged.length - 1]; + if (last && last.status === "ok" && step.status === "ok" && last.kind === step.kind && last.app === step.app) { + const { detail: _detail, ...rest } = last; + const count = (last.count ?? 1) + 1; + merged[merged.length - 1] = { ...rest, count, label: botStepPhrase(step.kind, count, step.app) }; + continue; + } + merged.push(step); + } + return merged; +} + +function lowerFirst(text: string): string { + return text.charAt(0).toLowerCase() + text.slice(1); +} + +/** "read 2 files, searched the web, used Notion": successful steps, grouped in first-seen order. */ +function botRecapSentence(steps: readonly BotRecapStep[]): string { + const groups = new Map(); + for (const step of steps) { + if (step.status !== "ok" || step.kind === "waiting") continue; + const key = `${step.kind}\u0000${step.app ?? ""}`; + const group = groups.get(key); + if (group) group.count += 1; + else groups.set(key, { kind: step.kind, ...(step.app ? { app: step.app } : {}), count: 1 }); + } + return [...groups.values()].map(({ kind, app, count }) => lowerFirst(botStepPhrase(kind, count, app))).join(", "); +} + +export function botRecapHeader(steps: readonly BotRecapStep[], durationMs: number, live: boolean): string { + const sentence = botRecapSentence(steps); + const lead = live ? "Working" : `Worked for ${botDurationLabel(durationMs)}`; + return sentence ? `${lead} · ${sentence}` : lead; +} + +/** Failures and refusals are counted apart; a step the person stopped is neither. */ +export function botRecapIssues(steps: readonly BotRecapStep[]): { failed: number; blocked: number } { + return { + failed: steps.filter((step) => step.status === "failed").length, + blocked: steps.filter((step) => step.status === "blocked").length, + }; +} + +export function botStepLine(step: BotRecapStep): { + text: string; + detail?: string; + tone: "normal" | "warning" | "error"; + active: boolean; +} { + const detail = step.detail ? { detail: step.detail } : {}; + switch (step.status) { + case "running": + return { text: botPhaseWord(step.kind, step.app), ...detail, tone: "normal", active: true }; + case "failed": + return { text: `Couldn’t ${botStepInfinitive(step.kind, step.app)}`, ...detail, tone: "error", active: false }; + case "blocked": + return { text: `Blocked: ${botStepInfinitive(step.kind, step.app)}`, ...detail, tone: "warning", active: false }; + case "stopped": + return { text: `Stopped: ${botStepInfinitive(step.kind, step.app)}`, ...detail, tone: "normal", active: false }; + case "ok": + return { text: step.label, ...detail, tone: "normal", active: false }; + } +} diff --git a/renderer/main/bots/bot-advanced.tsx b/renderer/main/bots/bot-advanced.tsx index 2ae5fdb342..29b7c55d2b 100644 --- a/renderer/main/bots/bot-advanced.tsx +++ b/renderer/main/bots/bot-advanced.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import { Link2, RotateCcw, Unlink } from "lucide-react"; +import { ChevronRight, Link2, RotateCcw, Unlink } from "lucide-react"; import { useQueryClient } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { @@ -53,6 +53,7 @@ import { recommendedBotModelChoice, sameBotModelChoice, } from "./bot-model-choice"; +import { botChatActivitySummary } from "./bot-chat-activity-page"; import { BotModelPicker, botModelCapabilityLabel } from "./bot-model-picker"; import { BotPageShell, BotPageSkeleton, useDiscardChangesGuard } from "./bot-page-shell"; @@ -430,7 +431,15 @@ function TelegramSection({ bot }: { bot: Pick }) { * Back with unsaved edits asks before discarding them. Telegram is a * connection with its own Connect and Disconnect actions. */ -export function BotAdvanced({ bot, onClose }: { bot: BotDefinition; onClose(): void }) { +export function BotAdvanced({ + bot, + onClose, + onOpenChatActivity, +}: { + bot: BotDefinition; + onClose(): void; + onOpenChatActivity(): void; +}) { const qc = useQueryClient(); const navigate = useNavigate(); const catalogQuery = useBotCapabilityCatalog(true, bot.id); @@ -449,10 +458,12 @@ export function BotAdvanced({ bot, onClose }: { bot: BotDefinition; onClose(): v const accessChanged = draft !== null && !sameDraft(draft, baseline); const dirty = accessChanged; - const guard = useDiscardChangesGuard({ + const discardDescription = `Your changes to ${bot.name}’s Advanced settings won’t be saved.`; + const guard = useDiscardChangesGuard({ dirty, onLeave: onClose, description: discardDescription }); + const chatActivityGuard = useDiscardChangesGuard({ dirty, - onLeave: onClose, - description: `Your changes to ${bot.name}’s Advanced settings won’t be saved.`, + onLeave: onOpenChatActivity, + description: discardDescription, }); const saveAccess = async (current: BotAccessDraft, start: BotAccessDraft) => { @@ -553,8 +564,26 @@ export function BotAdvanced({ bot, onClose }: { bot: BotDefinition; onClose(): v )} +
+ +
{guard.dialog} + {chatActivityGuard.dialog} ); } diff --git a/renderer/main/bots/bot-chat-activity-page.test.tsx b/renderer/main/bots/bot-chat-activity-page.test.tsx new file mode 100644 index 0000000000..04912e1b70 --- /dev/null +++ b/renderer/main/bots/bot-chat-activity-page.test.tsx @@ -0,0 +1,253 @@ +import { installBotTestIpc } from "./test-dom"; +import assert from "node:assert/strict"; +import { afterEach, test } from "node:test"; +import { cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react"; +import type { BotDefinition, BotUpdateInput } from "../../shared/bots"; +import { toast } from "../../components/ui"; +import { APPEARANCE_CHANGE_EVENT } from "../../lib/appearance-runtime"; +import { BotsView } from "../bots-view"; +import { botFixture, catalogFixture } from "./test-fixtures"; +import { mountWithBotRouter } from "./test-providers"; + +afterEach(() => { + cleanup(); + delete document.documentElement.dataset.reduceMotion; +}); + +/** The test DOM does not mount sonner's viewport, so observe the errors the person would be shown. */ +function captureErrorToasts(): { shown: string[]; restore(): void } { + const shown: string[] = []; + const original = toast.error; + toast.error = ((message: unknown) => { + shown.push(String(message)); + return "toast"; + }) as typeof toast.error; + return { shown, restore: () => void (toast.error = original) }; +} + +function deferred() { + let resolve!: () => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} + +function store( + initial: BotDefinition, + options: { + failUpdate?: boolean; + /** Awaited before the nth (0-based) update applies; a rejection fails that save. */ + gate?: (call: number) => Promise | undefined; + } = {}, +) { + let bot = initial; + const updates: BotUpdateInput[] = []; + installBotTestIpc({ + "bots:list": () => [bot], + "bots:get": () => bot, + "bots:update": async (input) => { + const update = input as BotUpdateInput; + updates.push(update); + await options.gate?.(updates.length - 1); + if (options.failUpdate) throw new Error("This Bot changed on another surface. Refresh it and try again."); + const { id: _id, expectedRevision: _revision, ...fields } = update; + bot = { ...bot, ...fields, revision: `${bot.revision}+` }; + return bot; + }, + "bots:getCapabilityCatalog": () => catalogFixture(), + "bots:getBotAccess": () => ({ + access: { botId: "bot-1", revision: "acc-1", policyEpoch: "e", summary: "", accessMode: "full" }, + modelSelection: { providerId: "prov-text", modelId: "model-text" }, + visionModelSelection: { providerId: "prov-vision", modelId: "model-vision" }, + }), + "bots:getTelegramBinding": () => null, + }); + return { updates, current: () => bot, change: (next: BotDefinition) => void (bot = next) }; +} + +test("Advanced shows the current choice and opens Chat activity; Back returns to Advanced", async () => { + store(botFixture({ chatActivity: { level: "summary", wording: "follows" } })); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=advanced" }); + const row = await screen.findByRole("button", { name: "Chat activity" }); + assert.ok(within(row).getByText("Summary · Follows the work")); + fireEvent.click(row); + assert.ok(await screen.findByRole("heading", { name: "Chat activity" })); + fireEvent.click(screen.getByRole("button", { name: "Back" })); + assert.ok(await screen.findByRole("radiogroup", { name: "What it can use" })); +}); + +test("the Advanced row shows the new choice after a pick and Back", async () => { + store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=advanced" }); + fireEvent.click(await screen.findByRole("button", { name: "Chat activity" })); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + fireEvent.click(within(level).getByRole("radio", { name: "Detailed" })); + await waitFor(() => + assert.equal(within(level).getByRole("radio", { name: "Detailed" }).getAttribute("data-state"), "checked"), + ); + fireEvent.click(screen.getByRole("button", { name: "Back" })); + const row = await screen.findByRole("button", { name: "Chat activity" }); + await waitFor(() => assert.ok(within(row).getByText("Detailed · Follows the work"))); +}); + +test("each choice saves as it is picked, with the Bot's revision and nothing else changed", async () => { + const bots = store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + assert.equal(within(level).getByRole("radio", { name: "Quiet" }).getAttribute("data-state"), "checked"); + fireEvent.click(within(level).getByRole("radio", { name: "Detailed" })); + await waitFor(() => assert.equal(bots.updates.length, 1)); + assert.deepEqual(bots.updates[0]!.chatActivity, { level: "detailed", wording: "follows" }); + assert.equal(bots.updates[0]!.expectedRevision, "rev-1"); + assert.equal(bots.updates[0]!.name, "Planner"); + const wording = screen.getByRole("radiogroup", { name: "What the status line says" }); + fireEvent.click(within(wording).getByRole("radio", { name: "Always “Thinking”" })); + await waitFor(() => assert.equal(bots.updates.length, 2)); + assert.deepEqual(bots.updates[1]!.chatActivity, { level: "detailed", wording: "thinking" }); + assert.equal(bots.updates[1]!.expectedRevision, "rev-1+"); + assert.ok(!screen.queryByRole("button", { name: "Save" }), "no Save button on this page"); +}); + +test("a choice that fails to save goes back to the saved one and says so", async () => { + const toasts = captureErrorToasts(); + try { + store(botFixture(), { failUpdate: true }); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + fireEvent.click(within(level).getByRole("radio", { name: "Summary" })); + await waitFor(() => assert.equal(toasts.shown.length, 1)); + assert.equal(toasts.shown[0], "This Bot changed on another surface. Refresh it and try again."); + await waitFor(() => + assert.equal(within(level).getByRole("radio", { name: "Quiet" }).getAttribute("data-state"), "checked"), + ); + assert.equal(within(level).getByRole("radio", { name: "Summary" }).getAttribute("data-state"), "unchecked"); + } finally { + toasts.restore(); + } +}); + +test("a failure with no message says Aiden couldn’t save the choice", async () => { + const toasts = captureErrorToasts(); + try { + store(botFixture(), { + gate: () => Promise.reject(new Error("")), + }); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const wording = await screen.findByRole("radiogroup", { name: "What the status line says" }); + fireEvent.click(within(wording).getByRole("radio", { name: "Always “Thinking”" })); + await waitFor(() => assert.deepEqual(toasts.shown, ["Aiden couldn’t save that choice."])); + await waitFor(() => + assert.equal(within(wording).getByRole("radio", { name: "Follows the work" }).getAttribute("data-state"), "checked"), + ); + } finally { + toasts.restore(); + } +}); + +test("two quick picks save in order, the second built on the first's saved choice", async () => { + const first = deferred(); + const bots = store(botFixture(), { gate: (call) => (call === 0 ? first.promise : undefined) }); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + const wording = screen.getByRole("radiogroup", { name: "What the status line says" }); + fireEvent.click(within(level).getByRole("radio", { name: "Detailed" })); + await waitFor(() => assert.equal(bots.updates.length, 1)); + fireEvent.click(within(wording).getByRole("radio", { name: "Always “Thinking”" })); + // Both choices show at once, but the second save waits for the first. + assert.equal(within(level).getByRole("radio", { name: "Detailed" }).getAttribute("data-state"), "checked"); + assert.equal(within(wording).getByRole("radio", { name: "Always “Thinking”" }).getAttribute("data-state"), "checked"); + assert.equal(bots.updates.length, 1); + first.resolve(); + await waitFor(() => assert.equal(bots.updates.length, 2)); + assert.deepEqual(bots.updates[0]!.chatActivity, { level: "detailed", wording: "follows" }); + assert.deepEqual(bots.updates[1]!.chatActivity, { level: "detailed", wording: "thinking" }); + assert.equal(bots.updates[1]!.expectedRevision, "rev-1+"); +}); + +test("a failed save does not leak into the next one, and the radios settle on what was saved", async () => { + const toasts = captureErrorToasts(); + try { + const first = deferred(); + const bots = store(botFixture(), { gate: (call) => (call === 0 ? first.promise : undefined) }); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + const wording = screen.getByRole("radiogroup", { name: "What the status line says" }); + fireEvent.click(within(level).getByRole("radio", { name: "Detailed" })); + await waitFor(() => assert.equal(bots.updates.length, 1)); + fireEvent.click(within(wording).getByRole("radio", { name: "Always “Thinking”" })); + first.reject(new Error("This Bot changed on another surface. Refresh it and try again.")); + await waitFor(() => assert.equal(bots.updates.length, 2)); + // The second save carries only its own choice; the failed Detailed is not applied. + assert.deepEqual(bots.updates[1]!.chatActivity, { level: "quiet", wording: "thinking" }); + await waitFor(() => + assert.equal(within(level).getByRole("radio", { name: "Quiet" }).getAttribute("data-state"), "checked"), + ); + assert.equal(within(wording).getByRole("radio", { name: "Always “Thinking”" }).getAttribute("data-state"), "checked"); + assert.equal(toasts.shown.length, 1); + assert.deepEqual(bots.current().chatActivity, { level: "quiet", wording: "thinking" }); + } finally { + toasts.restore(); + } +}); + +test("a pick changes only that field, even when the Bot changed elsewhere since the page opened", async () => { + const bots = store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const wording = await screen.findByRole("radiogroup", { name: "What the status line says" }); + // Another surface chose Summary after this page opened. + bots.change(botFixture({ revision: "rev-2", chatActivity: { level: "summary", wording: "follows" } })); + fireEvent.click(within(wording).getByRole("radio", { name: "Always “Thinking”" })); + await waitFor(() => assert.equal(bots.updates.length, 1)); + assert.deepEqual(bots.updates[0]!.chatActivity, { level: "summary", wording: "thinking" }); + assert.equal(bots.updates[0]!.expectedRevision, "rev-2"); +}); + +test("each choice names its description and badge for assistive tech", async () => { + store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + const level = await screen.findByRole("radiogroup", { name: "How much to show" }); + const described = (name: string) => { + const ids = (within(level).getByRole("radio", { name }).getAttribute("aria-describedby") ?? "").split(" "); + return ids.map((id) => document.getElementById(id)?.textContent ?? "").join(" "); + }; + assert.equal(described("Quiet"), "Recommended One line that says what it’s doing."); + assert.equal(described("Summary"), "Adds a short recap above each reply."); +}); + +test("under Reduce Motion each preview is a still frame with Play, built from the real status line", async () => { + document.documentElement.dataset.reduceMotion = "true"; + store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + await screen.findByRole("radiogroup", { name: "How much to show" }); + const preview = (name: string) => + document.querySelector(`[data-bot-chat-activity-preview="${name}"]`) as HTMLElement; + const follows = preview("wording-follows"); + const thinking = preview("wording-thinking"); + assert.ok(follows.querySelector('[data-bot-status-phase="searching"]')); + assert.ok(thinking.querySelector('[data-bot-status-phase="thinking"]')); + assert.ok(within(follows).getAllByText("Searching the web").length > 0); + assert.ok(within(thinking).getAllByText("Thinking").length > 0); + // Each level's still frame shows what it adds. + assert.ok(!preview("level-quiet").querySelector("[data-bot-recap]")); + assert.ok(preview("level-quiet").querySelector("[data-bot-status-phase]")); + assert.equal(preview("level-summary").querySelector("[data-bot-recap]")?.getAttribute("data-bot-recap"), "done"); + assert.equal(preview("level-detailed").querySelector("[data-bot-recap]")?.getAttribute("data-bot-recap"), "live"); + const play = screen.getByRole("button", { name: "Play preview: Detailed" }); + fireEvent.click(play); + assert.ok(screen.getByRole("button", { name: "Pause preview: Detailed" })); + // The phones group explains that phones always show just the line. + assert.ok(screen.getByText("Always just the line, with the same words.")); +}); + +test("turning Reduce Motion off while the page is open starts the previews", async () => { + document.documentElement.dataset.reduceMotion = "true"; + store(botFixture()); + await mountWithBotRouter(, { initialPath: "/bots/bot-1?page=chat-activity" }); + await screen.findByRole("button", { name: "Play preview: Detailed" }); + document.documentElement.dataset.reduceMotion = "false"; + window.dispatchEvent(new CustomEvent(APPEARANCE_CHANGE_EVENT)); + await waitFor(() => assert.ok(!screen.queryByRole("button", { name: "Play preview: Detailed" }))); +}); diff --git a/renderer/main/bots/bot-chat-activity-page.tsx b/renderer/main/bots/bot-chat-activity-page.tsx new file mode 100644 index 0000000000..1bec39753c --- /dev/null +++ b/renderer/main/bots/bot-chat-activity-page.tsx @@ -0,0 +1,342 @@ +// Advanced → Chat activity (spec §7): how much a Bot chat shows while the Bot +// works, and what its status line says, each choice with a looping preview +// built from the real status line and recap. Choices save as they are picked. +// Previews pause off-screen; under Reduce Motion they hold a still frame with +// Play. Radio rows show selection with the radio and background, no borders. + +import * as React from "react"; +import { Pause, Play } from "lucide-react"; +import { useQueryClient } from "@tanstack/react-query"; +import { Button, Field, FieldSet, Label, RadioGroup, RadioGroupItem, toast } from "../../components/ui"; +import { APPEARANCE_CHANGE_EVENT, prefersReducedMotion } from "../../lib/appearance-runtime"; +import { userFacingErrorMessage } from "../../lib/ipc-error"; +import type { BotToolPhase } from "../../shared/bot-activity"; +import { + resolveBotChatActivity, + type BotChatActivity, + type BotChatActivityLevel, + type BotChatActivityWording, + type BotDefinition, +} from "../../shared/bots"; +import type { BotLiveActivity } from "../../shared/bot-live"; +import { BotActivityRecap } from "./bot-activity-recap"; +import type { BotRecapStep } from "./bot-activity-steps"; +import { updateBotIdentity } from "./bot-identity"; +import { BotPageShell } from "./bot-page-shell"; +import { BotStatusLine } from "./bot-status-line"; + +export const BOT_CHAT_ACTIVITY_LEVEL_LABELS: Record = { + quiet: "Quiet", + summary: "Summary", + detailed: "Detailed", +}; + +export const BOT_CHAT_ACTIVITY_WORDING_LABELS: Record = { + follows: "Follows the work", + thinking: "Always “Thinking”", +}; + +/** Advanced's trailing value: "Quiet · Follows the work". */ +export function botChatActivitySummary(value?: BotChatActivity): string { + const resolved = resolveBotChatActivity(value); + return `${BOT_CHAT_ACTIVITY_LEVEL_LABELS[resolved.level]} · ${BOT_CHAT_ACTIVITY_WORDING_LABELS[resolved.wording]}`; +} + +const LEVEL_CHOICES: ReadonlyArray<{ value: BotChatActivityLevel; description: string; recommended?: true }> = [ + { value: "quiet", description: "One line that says what it’s doing.", recommended: true }, + { value: "summary", description: "Adds a short recap above each reply." }, + { value: "detailed", description: "Also shows its last few steps while it works." }, +]; + +const WORDING_CHOICES: ReadonlyArray<{ value: BotChatActivityWording; description: string }> = [ + { value: "follows", description: "Says what it’s doing, like Reading or Searching the web." }, + { value: "thinking", description: "One calm word, whatever it’s doing." }, +]; + +const PREVIEW_STEPS: readonly BotRecapStep[] = [ + { id: "p1", kind: "reading", label: "Read 1 file", detail: "recipes.md", status: "ok" }, + { id: "p2", kind: "searching", label: "Searched the web", detail: "quick weeknight dinners", status: "ok" }, + { id: "p3", kind: "editing", label: "Edited 1 file", detail: "meal-plan.md", status: "ok" }, +]; + +/** One scripted turn: think, read, search, edit, reply. `step` indexes `PREVIEW_STEPS`. */ +const PREVIEW_FRAMES: ReadonlyArray<{ ms: number; phase?: "thinking" | BotToolPhase; step?: number }> = [ + { ms: 1_400, phase: "thinking" }, + { ms: 1_600, phase: "reading", step: 0 }, + { ms: 1_600, phase: "searching", step: 1 }, + { ms: 1_400, phase: "editing", step: 2 }, + { ms: 2_800 }, +]; +/** + * Reduce Motion's still pose shows what each level adds: Summary holds the + * replied frame with its folded recap; Quiet and Detailed hold mid-turn, where + * Detailed has its steps open. + */ +function stillFrameFor(level: BotChatActivityLevel): number { + return level === "summary" ? PREVIEW_FRAMES.length - 1 : 2; +} + +/** Follows the app's Reduce Motion setting and the system's, live. */ +function useReducedMotion(): boolean { + return React.useSyncExternalStore( + (notify) => { + const query = window.matchMedia?.("(prefers-reduced-motion: reduce)"); + window.addEventListener(APPEARANCE_CHANGE_EVENT, notify); + query?.addEventListener?.("change", notify); + return () => { + window.removeEventListener(APPEARANCE_CHANGE_EVENT, notify); + query?.removeEventListener?.("change", notify); + }; + }, + prefersReducedMotion, + () => false, + ); +} +const PREVIEW_STARTED_AT = 0; + +function BotChatActivityPreview({ + level, + wording, + label, + name, +}: { + level: BotChatActivityLevel; + wording: BotChatActivityWording; + /** For the Play control's name: "Play preview: Detailed". */ + label: string; + /** A stable hook for this preview, such as `level-quiet`. */ + name: string; +}) { + const ref = React.useRef(null); + const reduced = useReducedMotion(); + const still = stillFrameFor(level); + // Under Reduce Motion the preview waits for Play; otherwise it always loops. + const [played, setPlayed] = React.useState(false); + const playing = !reduced || played; + const [visible, setVisible] = React.useState(true); + const [tick, setTick] = React.useState(reduced ? still : 0); + + // A change of setting (or level) returns to that mode's starting pose. + React.useEffect(() => { + setPlayed(false); + setTick(reduced ? still : 0); + }, [reduced, still]); + + React.useEffect(() => { + const node = ref.current; + if (!node || typeof IntersectionObserver === "undefined") return; + const observer = new IntersectionObserver((entries) => { + const latest = entries[entries.length - 1]; + if (latest) setVisible(latest.isIntersecting); + }); + observer.observe(node); + return () => observer.disconnect(); + }, []); + + React.useEffect(() => { + if (!playing || !visible) return; + const frame = PREVIEW_FRAMES[tick % PREVIEW_FRAMES.length]!; + const timer = window.setTimeout(() => setTick((value) => value + 1), frame.ms); + return () => window.clearTimeout(timer); + }, [playing, visible, tick]); + + const frame = PREVIEW_FRAMES[tick % PREVIEW_FRAMES.length]!; + const loop = Math.floor(tick / PREVIEW_FRAMES.length); + const replied = frame.phase === undefined; + const done = replied ? PREVIEW_STEPS.length : (frame.step ?? 0); + const current = frame.step !== undefined ? PREVIEW_STEPS[frame.step] : undefined; + const steps: BotRecapStep[] = [ + ...PREVIEW_STEPS.slice(0, done), + ...(current ? [{ ...current, status: "running" as const }] : []), + ]; + const showRecap = level === "detailed" ? steps.length > 0 : level === "summary" && replied; + const activity: BotLiveActivity | null = replied + ? null + : { + phase: frame.phase!, + startedAt: PREVIEW_STARTED_AT, + ...(current + ? { step: { kind: current.kind, label: current.label, ...(current.detail ? { detail: current.detail } : {}) } } + : {}), + }; + + return ( +
+ + {reduced ? ( + + ) : null} +
+ ); +} + +function ChoiceRow({ + value, + label, + description, + recommended, + preview, +}: { + value: string; + label: string; + description: string; + recommended?: boolean; + preview: React.ReactNode; +}) { + const id = React.useId(); + const badgeId = `${id}-recommended`; + const descriptionId = `${id}-description`; + return ( +
+ +
{preview}
+
+ ); +} + +export function BotChatActivityPage({ bot, onClose }: { bot: BotDefinition; onClose(): void }) { + const qc = useQueryClient(); + const [value, setValue] = React.useState(() => resolveBotChatActivity(bot.chatActivity)); + // Saves run one at a time, each carrying only its own patch, so quick picks + // never conflict and a failed one never leaks into the next. + const queue = React.useRef>(Promise.resolve()); + const pending = React.useRef(0); + // The last choice that reached the Bot; the page settles on it when saves end. + const saved = React.useRef(value); + + const pick = (patch: Partial) => { + const next = { ...value, ...patch }; + if (next.level === value.level && next.wording === value.wording) return; + setValue(next); + pending.current += 1; + queue.current = queue.current.then(async () => { + try { + // The helper merges the patch onto the freshly read Bot, so only the picked field changes. + const stored = await updateBotIdentity(qc, bot.id, { chatActivity: patch }); + saved.current = resolveBotChatActivity(stored.chatActivity); + } catch (error) { + toast.error(userFacingErrorMessage(error, "Aiden couldn’t save that choice.")); + } finally { + pending.current -= 1; + if (pending.current === 0) setValue(saved.current); + } + }); + }; + + return ( + +
+ + pick({ level: level as BotChatActivityLevel })} + > + {LEVEL_CHOICES.map((choice) => ( + + } + /> + ))} + + +
+
+ + pick({ wording: wording as BotChatActivityWording })} + > + {WORDING_CHOICES.map((choice) => ( + + } + /> + ))} + + +
+
+ + + +
+
+ ); +} diff --git a/renderer/main/bots/bot-chat-header.tsx b/renderer/main/bots/bot-chat-header.tsx index eb52bed72a..c4dbb438af 100644 --- a/renderer/main/bots/bot-chat-header.tsx +++ b/renderer/main/bots/bot-chat-header.tsx @@ -24,9 +24,12 @@ export function BotChatBackButton({ onBack }: { onBack(): void }) { export function BotChatNamePill({ bot, onOpenProfile, + working = false, }: { bot: Pick; onOpenProfile(): void; + /** The Bot is in a running turn: its face glances. */ + working?: boolean; }) { return ( ); diff --git a/renderer/main/bots/bot-chat-mode.test.tsx b/renderer/main/bots/bot-chat-mode.test.tsx index c127c26935..1b0ce215b8 100644 --- a/renderer/main/bots/bot-chat-mode.test.tsx +++ b/renderer/main/bots/bot-chat-mode.test.tsx @@ -7,9 +7,7 @@ import { CommandSystemProvider } from "../../lib/command-system"; import { Composer } from "../../components/composer"; import { LOCAL_COMPOSER_SURFACES, type ComposerSurfaces } from "../../lib/hosts/composer-surfaces"; import type { Workspace } from "../../lib/types"; -import type { GenerationTimeline } from "../../shared/generation-timeline"; import { BOT_CHAT_COMPOSER_SURFACES } from "./bot-chat-mode"; -import { resolveBotReplyProjection } from "./bot-reply-projection"; import { createBotTestQueryClient } from "./test-providers"; afterEach(cleanup); @@ -76,51 +74,3 @@ test("a Bot chat has no slash palette for rename, fork, side questions, or expor renderComposer(BOT_CHAT_COMPOSER_SURFACES); assert.deepEqual(await typeSlash(), []); }); - -function toolTimeline(contentOffset: number): GenerationTimeline { - return { - version: 3, - generationId: "gen-1", - status: "completed", - startedAt: 1, - finishedAt: 3, - steps: [ - { - id: "step-1", - order: 0, - kind: "tool", - toolCallId: "call-1", - toolName: "web_search", - label: "Searched the web", - detail: "weeknight dinners", - status: "completed", - startedAt: 1, - updatedAt: 2, - finishedAt: 2, - contentOffset, - }, - ], - }; -} - -test("the reply projection matches the phone rule for split, running, and tool-free replies", () => { - const text = "Checking.\n\nChecking.\n\nDone: three dinners."; - const boundary = text.indexOf("Done"); - assert.deepEqual(resolveBotReplyProjection(text, toolTimeline(boundary), false), { - finalText: "Done: three dinners.", - progressText: "Checking.", - }); - assert.deepEqual(resolveBotReplyProjection(text, toolTimeline(boundary), true), { - finalText: "", - progressText: "Checking.\n\nDone: three dinners.", - }); - assert.deepEqual(resolveBotReplyProjection(" Hi there ", null, false), { - finalText: "Hi there", - progressText: "", - }); - const emoji = "😀 done"; - assert.deepEqual(resolveBotReplyProjection(emoji, toolTimeline(1), false), { - finalText: emoji, - progressText: "", - }); -}); diff --git a/renderer/main/bots/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index 9505797ace..34ab36dfeb 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -4,6 +4,7 @@ import { afterEach, test } from "node:test"; import { cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react"; import { BotChatRoute } from "../bot-chat-route"; import { mountWithBotRouter } from "./test-providers"; +import { toast } from "../../components/ui"; import { botFixture } from "./test-fixtures"; import type { BotLiveSnapshot, BotTranscriptEntry } from "../../shared/bot-live"; @@ -20,6 +21,8 @@ function snapshot(overrides: Partial = {}): BotLiveSnapshot { partial: null, state: { kind: "idle" }, question: null, + activity: null, + queued: [], ...overrides, }; } @@ -34,6 +37,16 @@ const COLOUR_QUESTION = { ], }; +/** The chat's status live region, which stays mounted while the line comes and goes. */ +function statusRegion(): Element | undefined { + return screen.queryAllByRole("status").find((node) => node.hasAttribute("data-bot-status-announcement")); +} + +/** What a screen reader is told by the status line ("" while no line shows), or null without a region. */ +function announced(): string | null { + return statusRegion()?.textContent ?? null; +} + function userEntry(id: string, text: string): BotTranscriptEntry { return { id, type: "user", text, imageCount: 0 }; } @@ -52,13 +65,13 @@ async function mountChat(handlers: Record unknow return calls; } -test("a reply still being written is folded under Working and opens to its text", async () => { +test("a reply still being written shows as its own bubble", async () => { await mountChat({ - "bots:live:subscribe": () => snapshot({ partial: "Checking your calendar now", state: { kind: "running", submissionId: "s1" } }), + "bots:live:subscribe": () => + snapshot({ partial: "Checking your calendar now", state: { kind: "running", submissionId: "s1" } }), }); - const working = await screen.findByRole("button", { name: /Working/u }); - fireEvent.click(working); assert.ok(await screen.findByText("Checking your calendar now")); + assert.equal(screen.queryByRole("button", { name: /Working|Updates/u }), null); }); test("a Bot's A–E question shows its card, and submitting a chosen option answers it by wait id", async () => { @@ -296,22 +309,27 @@ test("a connect card answered with Not now reads Not connected and stays put", a assert.equal(within(card).queryByRole("button", { name: "Connect Gmail" }), null); }); -test("text before a tool call folds under Updates, and only the final answer is a bubble", async () => { +test("the Bot's own progress message is a bubble at every level, and Quiet shows no tool rows", async () => { await mountChat({ "bots:live:subscribe": () => snapshot({ entries: [ userEntry("u1", "Am I free Friday?"), - { id: "a1", type: "assistant", text: "Let me check your calendar.", toolCalls: [{ id: "t1", name: "calendar" }], stopReason: "toolUse" }, - { id: "r1", type: "tool_result", toolCallId: "t1", toolName: "calendar", isError: false }, + { + id: "a1", + type: "assistant", + text: "Let me check your calendar.", + toolCalls: [{ id: "t1", name: "calendar", kind: "working", label: "Used a tool" }], + stopReason: "toolUse", + }, + { id: "r1", type: "tool_result", toolCallId: "t1", toolName: "calendar", isError: false, status: "ok" }, assistantEntry("a2", "You are free all day Friday."), ], }), }); - assert.ok(await screen.findByText("You are free all day Friday.")); - assert.equal(screen.queryByText("Let me check your calendar."), null); - fireEvent.click(screen.getByRole("button", { name: "Updates" })); assert.ok(await screen.findByText("Let me check your calendar.")); + assert.ok(screen.getByText("You are free all day Friday.")); + assert.equal(screen.queryByText(/Used a tool/u), null); }); test("a tool call that needs approval asks in the chat and answers by wait id", async () => { @@ -392,13 +410,102 @@ test("a Bot open in another Aiden window says so in plain words", async () => { assert.equal(screen.queryByPlaceholderText(/held_by_live_process/u), null); }); -test("a just-sent message shows the Bot working before any reply text arrives", async () => { +test("a just-sent message shows the status line before any reply text arrives", async () => { await mountChat({ "bots:live:subscribe": () => - snapshot({ entries: [userEntry("u1", "Plan Lisbon")], state: { kind: "running", submissionId: "s1" } }), + snapshot({ + entries: [userEntry("u1", "Plan Lisbon")], + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "preparing", startedAt: Date.now() }, + }), }); assert.ok(await screen.findByText("Plan Lisbon")); - assert.ok(await screen.findByRole("button", { name: /Working/u })); + await waitFor(() => assert.equal(announced(), "Getting ready")); +}); + +test("the status line follows live activity, and hides while the reply's words stream", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [userEntry("u1", "What's on my list?")], + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "groceries.md" } }, + }), + }); + await waitFor(() => assert.equal(announced(), "Reading, groceries.md")); + emitBotTestNotification("bots:live:event", { + botId: "bot-1", + epoch: "epoch-1", + seq: 1, + type: "activity", + activity: { phase: "writing", startedAt: Date.now() }, + }); + emitBotTestNotification("bots:live:event", { botId: "bot-1", epoch: "epoch-1", seq: 2, type: "partial", text: "Eggs and milk." }); + await waitFor(() => assert.equal(screen.queryByText("Reading") === null, true)); + assert.equal(screen.queryByText("Writing") === null, true, "the words themselves are the signal"); +}); + +test("one status region stays mounted from an idle chat through streaming, so each new line is announced", async () => { + await mountChat({ + "bots:live:subscribe": () => snapshot({ entries: [assistantEntry("a1", "Hi there.")] }), + }); + assert.ok(await screen.findByText("Hi there.")); + const region = statusRegion(); + assert.ok(region, "the region is there before the Bot does anything"); + assert.equal(announced(), ""); + + emitBotTestNotification("bots:live:event", { + botId: "bot-1", + epoch: "epoch-1", + seq: 1, + type: "state", + state: { kind: "running", submissionId: "s1" }, + }); + emitBotTestNotification("bots:live:event", { + botId: "bot-1", + epoch: "epoch-1", + seq: 2, + type: "activity", + activity: { phase: "writing", startedAt: Date.now() }, + }); + await waitFor(() => assert.equal(announced(), "Writing")); + emitBotTestNotification("bots:live:event", { botId: "bot-1", epoch: "epoch-1", seq: 3, type: "partial", text: "Let me check." }); + await waitFor(() => assert.equal(announced(), "", "words are streaming, so the region is quiet")); + + emitBotTestNotification("bots:live:event", { + botId: "bot-1", + epoch: "epoch-1", + seq: 4, + type: "activity", + activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "notes.md" } }, + }); + await waitFor(() => assert.equal(announced(), "Reading, notes.md"), { timeout: 3_000 }); + assert.equal(statusRegion() === region, true, "the same region announced both stretches"); +}); + +test("a Bot set to Always Thinking says Thinking while it reads", async () => { + await mountChat({ + "bots:get": () => botFixture({ chatActivity: { level: "quiet", wording: "thinking" } }), + "bots:live:subscribe": () => + snapshot({ + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "groceries.md" } }, + }), + }); + await waitFor(() => assert.equal(announced(), "Thinking")); +}); + +test("the status line stays through a tool that follows narration, even while that narration is still the partial", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [userEntry("u1", "Tidy my notes")], + partial: "On it.", + state: { kind: "running", submissionId: "s1" }, + activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "notes.md" } }, + }), + }); + await waitFor(() => assert.equal(announced(), "Reading, notes.md")); }); test("a deleted Bot's chat says it was not found instead of loading forever", async () => { @@ -451,7 +558,6 @@ test("a renderer reload mid-reply shows the partial reply from the fresh snapsho type: "partial", text: "Once upon a time there was a fox.", }); - fireEvent.click(await screen.findByRole("button", { name: /Working/u })); assert.ok(await screen.findByText("Once upon a time there was a fox.")); assert.equal(calls.filter((call) => call.channel === "bots:live:subscribe").length, 2); assert.equal(calls.filter((call) => call.channel === "bots:live:unsubscribe").length, 1); @@ -476,7 +582,7 @@ const FILE_HANDLERS = { }; function toolStep(id: string, text: string): BotTranscriptEntry { - return { id, type: "assistant", text, toolCalls: [{ id: `${id}-call`, name: "web_search" }], stopReason: "toolUse" }; + return { id, type: "assistant", text, toolCalls: [{ id: `${id}-call`, name: "web_search", kind: "searching", label: "Searched the web" }], stopReason: "toolUse" }; } test("Files in the ••• menu lists the Bot's folder and opens a file", async () => { @@ -505,7 +611,7 @@ test("a file the Bot wrote shows as a chip that opens that file", async () => { assert.equal((await screen.findByLabelText("Contents of lists/groceries.md")).textContent, "eggs\nmilk"); }); -test("all tool rounds before an answer fold into one Updates line", async () => { +test("each round's narration is its own bubble before the answer", async () => { await mountChat({ "bots:live:subscribe": () => snapshot({ @@ -517,10 +623,40 @@ test("all tool rounds before an answer fold into one Updates line", async () => ], }), }); - assert.ok(await screen.findByText("TAP on Friday is cheapest.")); - assert.equal(screen.getAllByRole("button", { name: "Updates" }).length, 1); - fireEvent.click(screen.getByRole("button", { name: "Updates" })); - assert.ok(await screen.findByText(/Searching airlines\.\s+Comparing prices\./u)); + assert.ok(await screen.findByText("Searching airlines.")); + assert.ok(screen.getByText("Comparing prices.")); + assert.ok(screen.getByText("TAP on Friday is cheapest.")); +}); + +test("a Summary Bot shows one recap above its answer that opens to the steps", async () => { + await mountChat({ + "bots:get": () => botFixture({ chatActivity: { level: "summary", wording: "follows" } }), + "bots:live:subscribe": () => + snapshot({ + entries: [ + { ...userEntry("u1", "Find flights"), at: 1_000 } as BotTranscriptEntry, + toolStep("a1", ""), + { id: "r1", type: "tool_result", toolCallId: "a1-call", toolName: "web_search", isError: false, status: "ok", at: 5_000 }, + { ...assistantEntry("a2", "TAP on Friday is cheapest."), at: 19_000 } as BotTranscriptEntry, + ], + }), + }); + const recap = await screen.findByRole("button", { name: "Worked for 18s · searched the web" }); + fireEvent.click(recap); + assert.ok(await screen.findByText("Searched the web")); +}); + +test("a reply the person stopped says so in a quiet centred line", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [ + userEntry("u1", "Tell me a story"), + { id: "a1", type: "assistant", text: "Once upon", toolCalls: [], stopReason: "aborted" }, + ], + }), + }); + assert.ok(await screen.findByText("You stopped this reply.")); }); test("Reply quotes a message at the start of the composer", async () => { @@ -689,7 +825,7 @@ function proposalEntry(status: "pending" | "accepted" | "dismissed", routineId?: return { id: "p1", type: "routine_proposal", proposal: CHECK_IN_PROPOSAL, status, ...(routineId ? { routineId } : {}) }; } -test("Memory updated is a quiet caption, outside Updates, that opens this Bot's Memory page", async () => { +test("Memory updated is a quiet caption, that opens this Bot's Memory page", async () => { installBotTestIpc({ "bots:get": () => botFixture(), "bots:pendingApprovals": () => [], @@ -707,7 +843,6 @@ test("Memory updated is a quiet caption, outside Updates, that opens this Bot's await screen.findByText("Noted."); const captions = screen.getAllByRole("button", { name: "Memory updated. Open Memory" }); assert.equal(captions.length, 1, "back-to-back saves read as one line"); - assert.equal(screen.queryByRole("button", { name: /Updates/u }) === null, true, "never folded into Updates"); fireEvent.click(captions[0]!); await waitFor(() => assert.equal(router.state.location.pathname, "/bots/bot-1")); assert.equal((router.state.location.search as { page?: string }).page, "memory"); @@ -774,3 +909,103 @@ test("a failed answer keeps the proposal answerable, and one answered elsewhere }); assert.ok(await screen.findByText("Added ✓ · Every day at 9:00 AM")); }); + +test("a queued message shows faded as Queued, and Remove withdraws that one submission", async () => { + const calls = await mountChat({ + "bots:live:subscribe": () => + snapshot({ + entries: [userEntry("u1", "Plan dinners")], + state: { kind: "running", submissionId: "s1" }, + queued: [{ submissionId: "8", mode: "followUp", text: "Also add dessert", imageCount: 0 }], + }), + "bots:withdraw": () => "withdrawn", + }); + assert.ok(await screen.findByText("Also add dessert")); + assert.ok(screen.getByText("Queued")); + fireEvent.click(screen.getByRole("button", { name: "Remove queued message: Also add dessert" })); + await waitFor(() => + assert.deepEqual(calls.find((call) => call.channel === "bots:withdraw")?.args, [{ botId: "bot-1", submissionId: "8" }]), + ); +}); + +const QUEUED_BASE = { + entries: [userEntry("u1", "Plan dinners")], + state: { kind: "running", submissionId: "s1" } as const, +}; + +test("Remove on a message that already started says it stays", async () => { + // The test DOM does not mount sonner's viewport, so observe the toast the person would be shown. + const shown: string[] = []; + const original = toast.info; + toast.info = ((message: unknown) => { + shown.push(String(message)); + return "toast"; + }) as typeof toast.info; + try { + const calls = await mountChat({ + "bots:live:subscribe": () => + snapshot({ ...QUEUED_BASE, queued: [{ submissionId: "8", mode: "followUp", text: "Also add dessert", imageCount: 0 }] }), + "bots:withdraw": () => "started", + }); + fireEvent.click(await screen.findByRole("button", { name: "Remove queued message: Also add dessert" })); + await waitFor(() => assert.deepEqual(shown, ["That message already started, so it stays."])); + assert.equal(calls.filter((call) => call.channel === "bots:withdraw").length, 1); + } finally { + toast.info = original; + } +}); + +test("a queued message leaves the page when the queue event empties it", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ ...QUEUED_BASE, queued: [{ submissionId: "8", mode: "followUp", text: "Also add dessert", imageCount: 0 }] }), + }); + assert.ok(await screen.findByText("Also add dessert")); + emitBotTestNotification("bots:live:event", { botId: "bot-1", epoch: "epoch-1", seq: 1, type: "queued", queued: [] }); + await waitFor(() => assert.equal(document.body.textContent?.includes("Also add dessert"), false)); + assert.equal(screen.queryByText("Queued"), null); +}); + +test("each queued message has its own Remove, and removing one moves focus on: the next Remove, else the composer", async () => { + await mountChat({ + "bots:live:subscribe": () => + snapshot({ + ...QUEUED_BASE, + queued: [ + { submissionId: "8", mode: "followUp", text: "Also add dessert", imageCount: 0 }, + { submissionId: "9", mode: "followUp", text: "And a drinks list", imageCount: 0 }, + ], + }), + "bots:withdraw": () => "withdrawn", + }); + const first = await screen.findByRole("button", { name: "Remove queued message: Also add dessert" }); + const second = screen.getByRole("button", { name: "Remove queued message: And a drinks list" }); + first.focus(); + fireEvent.click(first); + await waitFor(() => assert.equal(document.activeElement, second)); + fireEvent.click(second); + await waitFor(() => assert.equal((document.activeElement as HTMLElement | null)?.getAttribute("placeholder"), "Ask Planner")); +}); + +test("the chat header's face works only while the Bot works, and a photo gets a small activity badge", async () => { + await mountChat({ + "bots:getCanonicalPhoto": () => ({ assetRevision: "a1", dataUrl: "data:image/png;base64,AAAA" }), + "bots:live:subscribe": () => + snapshot({ state: { kind: "running", submissionId: "s1" }, activity: { phase: "thinking", startedAt: Date.now() } }), + }); + const pill = await screen.findByRole("button", { name: "Planner profile" }); + const face = within(pill).getByTitle("Planner"); + await waitFor(() => { + assert.equal(face.hasAttribute("data-working"), true); + assert.ok(face.querySelector('[data-aiden-mark="glance"]')); + }); + emitBotTestNotification("bots:live:event", { + botId: "bot-1", + epoch: "epoch-1", + seq: 1, + type: "state", + state: { kind: "idle" }, + }); + await waitFor(() => assert.equal(face.hasAttribute("data-working"), false)); + assert.equal(face.querySelector('[data-aiden-mark="glance"]'), null); +}); diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index bf80fd9dfe..983a51dc85 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -20,9 +20,10 @@ import { BotNoticeCard } from "../../components/bots/bot-notice-card"; import { botsApi } from "../../lib/ipc"; import { userFacingErrorMessage } from "../../lib/ipc-error"; import type { Attachment } from "../../lib/types"; +import { resolveBotChatActivity, type BotChatActivityLevel } from "../../shared/bots"; import { useBot } from "../../lib/queries"; import { useBotLive } from "../../lib/use-bot-live"; -import { BOT_FAILED_TURN_TEXT, type BotPendingQuestion, type BotTranscriptEntry } from "../../shared/bot-live"; +import { BOT_FAILED_TURN_TEXT, type BotPendingQuestion, type BotQueuedMessage, type BotTranscriptEntry } from "../../shared/bot-live"; import type { AskUserQuestionPromptV1, AskUserQuestionResponseV1 } from "../../shared/ask-user-question"; import type { BotApprovalPrompt } from "../../../main/services/bot-runtime/bot-approvals"; import type { BotRoutineProposalDecision, BotRoutineProposalStatus } from "../../shared/bot-routine-proposals"; @@ -30,12 +31,13 @@ import { BotChatActions, BotChatBackButton, BotChatNamePill } from "./bot-chat-h import { BOT_CHAT_COMPOSER_SURFACES } from "./bot-chat-mode"; import { BotDeleteDialog } from "./bot-delete-dialog"; import { BotNeedsModel } from "./bot-needs-model"; +import { BotActivityRecap } from "./bot-activity-recap"; +import { BotStatusAnnouncer, BotStatusLine, botStatusSpeech } from "./bot-status-line"; import { BotFilesDialog } from "./bot-files-dialog"; import { BotMessageActions, botReplyQuote } from "./bot-message-actions"; import { botTranscriptRows } from "./bot-transcript-rows"; import { BOT_UNAVAILABLE_LABEL, type BotSessionState } from "./bot-session-state"; import { botRoutinesKey } from "./bot-routines"; -import { BotUpdates } from "./bot-updates"; import { useConnectionSetup } from "./use-connection-setup"; export const BOT_INTERRUPTED_TEXT = "I got interrupted while working on this."; @@ -288,13 +290,53 @@ function BotMemoryUpdatedCaption({ onOpen }: { onOpen(): void }) { ); } -/** Chat transcript rows: bubbles, one Updates line per reply, chips, cards. */ +const QUEUED_PREVIEW_CHARS = 40; + +/** A follow-up waiting for the running turn: a faded bubble surface, "Queued", and Remove. */ +function BotQueuedBubble({ + text, + removing, + onRemove, +}: { + text: string; + removing: boolean; + onRemove(button: HTMLButtonElement): void; +}) { + const oneLine = text.replace(/\s+/gu, " ").trim(); + const preview = oneLine.length > QUEUED_PREVIEW_CHARS ? `${oneLine.slice(0, QUEUED_PREVIEW_CHARS).trimEnd()}…` : oneLine; + return ( +
+
+ +
+
+ Queued + +
+
+ ); +} + +/** Chat transcript rows: bubbles, recaps, chips, cards. */ function TranscriptEntries({ name, entries, partial, running, + level, + queued, + removing, retrying, + onRemoveQueued, onConnect, onDismissConnection, onOpenFile, @@ -307,7 +349,11 @@ function TranscriptEntries({ entries: readonly BotTranscriptEntry[]; partial: string | null; running: boolean; + level: BotChatActivityLevel; + queued: readonly BotQueuedMessage[]; + removing: ReadonlySet; retrying: boolean; + onRemoveQueued(submissionId: string, button: HTMLButtonElement): void; onConnect(pluginId: string): void; onDismissConnection(pluginId: string): void; onOpenFile(path: string): void; @@ -319,7 +365,7 @@ function TranscriptEntries({ decision: BotRoutineProposalDecision, ): Promise | null>; }) { - const rows = botTranscriptRows(entries, partial, running); + const rows = botTranscriptRows(entries, partial, { running, level, queued }); return ( <> {rows.map((row) => { @@ -344,11 +390,26 @@ function TranscriptEntries({ case "assistant": return ( - + ); - case "updates": - return ; + case "recap": + return ; + case "queued": + return ( + onRemoveQueued(row.submissionId, button)} + /> + ); + case "stopped": + return ( + + You stopped this reply. + + ); case "file": return onOpenFile(row.path)} />; case "image": @@ -415,7 +476,9 @@ export function BotChatPane({ botId }: { botId: string }) { const [deleteOpen, setDeleteOpen] = React.useState(false); const [files, setFiles] = React.useState<{ open: boolean; path: string | null }>({ open: false, path: null }); const [retrying, setRetrying] = React.useState(false); + const [removing, setRemoving] = React.useState>(new Set()); const [pausedBusy, setPausedBusy] = React.useState(false); + const [statusLayout, setStatusLayout] = React.useState(""); const composerRef = React.useRef(null); const snapshot = live.snapshot; const state: BotSessionState | undefined = snapshot?.state; @@ -440,6 +503,7 @@ export function BotChatPane({ botId }: { botId: string }) { current ? ( void navigate({ to: "/bots/$botId", params: { botId: current.id } })} /> ) : bot.isLoading ? ( @@ -468,6 +532,9 @@ export function BotChatPane({ botId }: { botId: string }) { state?.kind, approvals.prompts.length, snapshot?.question?.waitId, + snapshot?.activity?.phase, + snapshot?.queued?.length ?? 0, + statusLayout, ]} showScrollToBottomButton streaming={running} @@ -533,6 +600,16 @@ export function BotChatPane({ botId }: { botId: string }) { } const question = snapshot.question; + const chatActivity = resolveBotChatActivity(current.chatActivity); + // While the reply's visible words stream, the words are the signal (§5.2). The + // partial text can outlast narration into a tool call, so a running step keeps the line. + const activityPhase = snapshot.activity?.phase; + const replyStreaming = + running && + (snapshot.partial?.trim().length ?? 0) > 0 && + (activityPhase === "writing" || activityPhase === "thinking") && + !snapshot.activity?.step; + const statusActivity = snapshot.activity && !replyStreaming ? snapshot.activity : null; const send = async ( text: string, @@ -625,6 +702,26 @@ export function BotChatPane({ botId }: { botId: string }) { }); }; + 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 result = await botsApi.withdraw(current.id, submissionId); + if (result === "started") toast.info("That message already started, so it stays."); + } catch (error) { + toast.error(userFacingErrorMessage(error, "Aiden couldn’t remove that message.")); + } finally { + setRemoving((ids) => { + const rest = new Set(ids); + rest.delete(submissionId); + return rest; + }); + } + }; + const respondToProposal = async (proposalId: string, decision: BotRoutineProposalDecision) => { try { const result = await botsApi.routineProposals.respond({ botId: current.id, proposalId, decision }); @@ -715,6 +812,10 @@ export function BotChatPane({ botId }: { botId: string }) { entries={snapshot.entries} partial={snapshot.partial} running={running} + level={chatActivity.level} + queued={snapshot.queued ?? []} + removing={removing} + onRemoveQueued={(id, button) => void removeQueued(id, button)} retrying={retrying} onConnect={(pluginId) => void connectionSetup.open(pluginId)} onDismissConnection={(pluginId) => void dismissConnection(pluginId)} @@ -725,6 +826,15 @@ export function BotChatPane({ botId }: { botId: string }) { onRespondToProposal={respondToProposal} /> + + {statusActivity ? ( + + ) : null} {state?.kind === "interrupted" ? ( ; }>; /** @@ -30,6 +32,9 @@ export async function updateBotIdentity( ...(description ? { description } : {}), instructions: next.instructions, avatar: next.avatar, + ...(patch.chatActivity + ? { chatActivity: { ...resolveBotChatActivity(latest.chatActivity), ...patch.chatActivity } } + : {}), }); qc.setQueryData(queryKeys.bot(saved.id), saved); await qc.invalidateQueries({ queryKey: queryKeys.bots }); diff --git a/renderer/main/bots/bot-list.test.tsx b/renderer/main/bots/bot-list.test.tsx index b13a40b791..8022b82382 100644 --- a/renderer/main/bots/bot-list.test.tsx +++ b/renderer/main/bots/bot-list.test.tsx @@ -147,3 +147,13 @@ test("row times read as a clock time today, a day name this week, then a date", ), ); }); + +test("a working Bot's face is marked working; an idle one is not", () => { + renderList([ + { bot: bot("b1", "Runner"), state: { kind: "running", submissionId: "s1" } }, + { bot: bot("b2", "Sleeper"), state: { kind: "idle" } }, + ]); + assert.equal(screen.getByTitle("Runner").hasAttribute("data-working"), true); + assert.equal(screen.getByTitle("Sleeper").hasAttribute("data-working"), false); + assert.ok(within(screen.getByRole("button", { name: /^Runner/u })).getByText("Working")); +}); diff --git a/renderer/main/bots/bot-list.tsx b/renderer/main/bots/bot-list.tsx index 184c860ce0..ed0e3362a7 100644 --- a/renderer/main/bots/bot-list.tsx +++ b/renderer/main/bots/bot-list.tsx @@ -114,20 +114,15 @@ function BotListItem({ className="flex w-full min-w-0 items-center gap-3 rounded-card py-2.5 pl-3 pr-12 text-left outline-none transition-colors duration-150 hover:bg-list-hover focus-visible:bg-list-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus-ring motion-reduce:transition-none" onClick={() => onOpen(bot)} > - + - {working ? ( - diff --git a/renderer/main/bots/bot-page-search.ts b/renderer/main/bots/bot-page-search.ts index f3d6f9d276..b767842f0b 100644 --- a/renderer/main/bots/bot-page-search.ts +++ b/renderer/main/bots/bot-page-search.ts @@ -1,7 +1,7 @@ /** A Bot page reached from its Profile; `/bots/$botId?page=advanced` opens Advanced directly. */ -export type BotSubpage = "instructions" | "advanced" | "memory"; +export type BotSubpage = "instructions" | "advanced" | "memory" | "chat-activity"; -const SUBPAGES: ReadonlySet = new Set(["instructions", "advanced", "memory"]); +const SUBPAGES: ReadonlySet = new Set(["instructions", "advanced", "memory", "chat-activity"]); export function parseBotPageSearch(search: Record): { page?: BotSubpage } { return typeof search.page === "string" && SUBPAGES.has(search.page) ? { page: search.page as BotSubpage } : {}; diff --git a/renderer/main/bots/bot-profile-photo.test.tsx b/renderer/main/bots/bot-profile-photo.test.tsx index 905639ba97..614da4130b 100644 --- a/renderer/main/bots/bot-profile-photo.test.tsx +++ b/renderer/main/bots/bot-profile-photo.test.tsx @@ -3,7 +3,6 @@ import assert from "node:assert/strict"; import { afterEach, test } from "node:test"; import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react"; import type { BotRendererCanonicalPhoto } from "../../shared/bots"; -import { invalidateBotCanonicalPhotos } from "../../lib/bot-canonical-photo-cache"; import { BotsView } from "../bots-view"; import { mountWithBotRouter } from "./test-providers"; import { botFixture } from "./test-fixtures"; @@ -26,8 +25,6 @@ const EXISTING_PHOTO: BotRendererCanonicalPhoto = { * reads from the store, so the avatar only changes when the write lands. */ function photoIpc(initial: BotRendererCanonicalPhoto | null) { - // The photo cache is process-wide; a photo cached by an earlier test must not answer this one. - invalidateBotCanonicalPhotos(); let photo = initial; const calls: BotTestIpcCall[] = installBotTestIpc({ "bots:list": () => [botFixture()], diff --git a/renderer/main/bots/bot-reply-projection.ts b/renderer/main/bots/bot-reply-projection.ts deleted file mode 100644 index 1e6bc815c8..0000000000 --- a/renderer/main/bots/bot-reply-projection.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { isToolStep, type GenerationTimeline } from "../../shared/generation-timeline"; - -export interface BotReplyProjection { - /** The answer shown as the Bot's bubble. */ - finalText: string; - /** Narration written before the last tool call, folded into "Updates". */ - progressText: string; -} - -/** - * Splits a Bot reply the way Aiden On The Go does (`AidenBotReplyProjection` - * on iOS): text written before the last tool call is progress, and only what - * follows it is the answer. While the reply is still running nothing is final - * yet, so all text so far is progress. - */ -export function resolveBotReplyProjection( - text: string, - timeline: GenerationTimeline | null | undefined, - isActive: boolean, -): BotReplyProjection { - const cleaned = text.trim(); - if (!cleaned) return { finalText: "", progressText: "" }; - if (isActive) return { finalText: "", progressText: deduplicatedProgress(text) }; - const offsets = (timeline?.steps ?? []) - .filter(isToolStep) - .map((step) => step.contentOffset) - .filter((offset): offset is number => Number.isSafeInteger(offset)); - if (offsets.length === 0) return { finalText: cleaned, progressText: "" }; - const boundary = Math.max(...offsets); - if (boundary < 0 || boundary > text.length) return { finalText: cleaned, progressText: "" }; - // Never split a surrogate pair: back up to the start of the code point. - const unit = text.charCodeAt(boundary); - const split = boundary > 0 && unit >= 0xdc00 && unit <= 0xdfff ? boundary - 1 : boundary; - return { - finalText: text.slice(split).trim(), - progressText: deduplicatedProgress(text.slice(0, split)), - }; -} - -/** Drops repeated paragraphs, comparing them with whitespace collapsed. */ -function deduplicatedProgress(text: string): string { - const seen = new Set(); - const kept: string[] = []; - for (const paragraph of text.split("\n\n")) { - const cleaned = paragraph.trim(); - if (!cleaned) continue; - const identity = cleaned.split(/\s+/u).join(" "); - if (seen.has(identity)) continue; - seen.add(identity); - kept.push(cleaned); - } - return kept.join("\n\n"); -} diff --git a/renderer/main/bots/bot-status-line.test.tsx b/renderer/main/bots/bot-status-line.test.tsx new file mode 100644 index 0000000000..033ad09481 --- /dev/null +++ b/renderer/main/bots/bot-status-line.test.tsx @@ -0,0 +1,137 @@ +import "./test-dom"; +import assert from "node:assert/strict"; +import { afterEach, mock, test } from "node:test"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import type { BotLiveActivity } from "../../shared/bot-live"; +import { BotStatusAnnouncer, BotStatusLine } from "./bot-status-line"; + +afterEach(() => { + mock.timers.reset(); + cleanup(); +}); + +const reading: BotLiveActivity = { + phase: "reading", + startedAt: 1_000, + step: { kind: "reading", label: "Reading", detail: "grocery-list.md" }, +}; + +/** What the line says when a screen reader reaches it. */ +function said(): string | null { + return screen.getByRole("group").getAttribute("aria-label"); +} + +/** What a screen reader is told: the live region's text. */ +function announced(): string | null { + return screen.getByRole("status").textContent; +} + +test("the line says the phase with its step on the Mac, and only Thinking with Always Thinking", () => { + render(); + assert.equal(said(), "Reading, grocery-list.md"); + cleanup(); + render(); + assert.equal(said(), "Thinking"); + assert.equal(screen.queryByText(/grocery-list\.md/u) === null, true, "Always Thinking never peeks at the step"); +}); + +test("waiting keeps its word under Always Thinking, and an unknown phase reads as Working", () => { + render(); + assert.equal(said(), "Waiting for you"); + cleanup(); + render(); + assert.equal(said(), "Working"); +}); + +test("after 20 seconds the line shows elapsed time and Stop; after 2 minutes, a still-going note", () => { + const calls: string[] = []; + render( calls.push("stop")} />); + assert.equal(screen.queryByRole("button", { name: "Stop" }) === null, true); + assert.equal(screen.queryByText(/19s/u) === null, true); + cleanup(); + render( calls.push("stop")} />); + assert.ok(screen.getByText("· 1m 12s")); + fireEvent.click(screen.getByRole("button", { name: "Stop" })); + assert.deepEqual(calls, ["stop"]); + assert.equal(screen.queryByRole("note") === null, true); + cleanup(); + render(); + assert.ok(screen.getByRole("note")); + assert.ok(screen.getByText("Still going. I'll message you when it's done.")); +}); + +test("Stop needs a handler, and goes away while the Bot is already stopping", () => { + render(); + assert.equal(screen.queryByRole("button", { name: "Stop" }) === null, true, "no handler, no Stop"); + cleanup(); + render( + {}} />, + ); + assert.equal(said(), "Stopping"); + assert.equal(screen.queryByRole("button", { name: "Stop" }) === null, true, "already stopping"); +}); + +test("the still-going note is only for work in progress, not while it waits on you or stops", () => { + const late = 1_000 + 121_000; + render(); + assert.equal(said(), "Waiting for you"); + assert.equal(screen.queryByRole("note") === null, true, "waiting on the person"); + cleanup(); + render(); + assert.equal(said(), "Stopping"); + assert.equal(screen.queryByRole("note") === null, true, "already stopping"); +}); + +test("the live region starts empty and fills after it mounts, so the first wording is announced", () => { + const observer = new MutationObserver(() => {}); + const view = render(
); + observer.observe(view.container, { subtree: true, childList: true, characterData: true }); + view.rerender(); + const records = observer.takeRecords(); + observer.disconnect(); + const region = screen.getByRole("status"); + assert.equal(announced(), "Getting ready"); + const filledLater = records.some( + (record) => record.target === region && Array.from(record.addedNodes).some((node) => node.textContent === "Getting ready"), + ); + assert.equal(filledLater, true, "the wording arrives as a change inside the already-mounted region"); +}); + +test("the announcement changes at most once every 2 seconds, and ends on the newest wording", () => { + mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 }); + const view = render(); + assert.equal(announced(), "Reading, grocery-list.md"); + + mock.timers.tick(500); + view.rerender(); + assert.equal(announced(), "Reading, grocery-list.md", "a change inside the gap waits"); + + mock.timers.tick(500); + view.rerender(); + assert.equal(announced(), "Reading, grocery-list.md", "still inside the gap"); + + act(() => mock.timers.tick(1_000)); + assert.equal(announced(), "Writing", "the gap passed: the newest wording wins, not the skipped one"); +}); + +test("a change after a quiet spell is announced at once", () => { + mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 }); + const view = render(); + mock.timers.tick(3_000); + view.rerender(); + assert.equal(announced(), "Writing"); +}); + +test("hiding the line clears the region at once, and the gap still holds for what comes next", () => { + mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 }); + const view = render(); + mock.timers.tick(500); + view.rerender(); + assert.equal(announced(), "", "the words are streaming: nothing stale stays in the region"); + + mock.timers.tick(500); + view.rerender(); + assert.equal(announced(), "", "inside the gap since the last announcement"); + act(() => mock.timers.tick(1_000)); + assert.equal(announced(), "Editing files"); +}); diff --git a/renderer/main/bots/bot-status-line.tsx b/renderer/main/bots/bot-status-line.tsx new file mode 100644 index 0000000000..1fac352a5f --- /dev/null +++ b/renderer/main/bots/bot-status-line.tsx @@ -0,0 +1,152 @@ +// The one calm line a working Bot shows (spec §5, §6, §14): an activity mark +// and a word, a hover/focus peek at the current step on the Mac, elapsed time +// and Stop after 20 seconds, and a still-going note after 2 minutes. Screen +// readers hear it through `BotStatusAnnouncer`, a live region the chat keeps +// mounted while the line comes and goes, at most once every 2 seconds. + +import * as React from "react"; +import { Square } from "lucide-react"; +import { AidenActivityMark } from "../../components/aiden-activity-mark"; +import { Button, Text } from "../../components/ui"; +import { + BOT_STILL_GOING_AFTER_MS, + botActivityDisplay, + botElapsedLabel, + nextBotAnnouncement, + type BotAnnouncement, +} from "../../shared/bot-activity"; +import type { BotLiveActivity } from "../../shared/bot-live"; +import type { BotChatActivityWording } from "../../shared/bots"; + +function useClock(fixed: number | undefined): number { + const [now, setNow] = React.useState(() => fixed ?? Date.now()); + React.useEffect(() => { + if (fixed !== undefined) return; + const timer = window.setInterval(() => setNow(Date.now()), 1_000); + return () => window.clearInterval(timer); + }, [fixed]); + return fixed ?? now; +} + +const SILENT: BotAnnouncement = { text: "", at: Number.NEGATIVE_INFINITY }; + +/** Clearing is immediate and keeps the last announcement's time, so the gap still holds after it. */ +function settleAnnouncement(shown: BotAnnouncement, text: string, now: number): { shown: BotAnnouncement; retryInMs?: number } { + if (text === "") return { shown: shown.text === "" ? shown : { text: "", at: shown.at } }; + return nextBotAnnouncement(shown, text, now); +} + +/** + * The text screen readers hear: the newest wording, at most once per gap. + * A change inside the gap keeps the last text until a timer releases the newest. + * The first commit is always empty, so a live region mounted with the text still announces it. + */ +function useAnnouncement(text: string): string { + const [armed, setArmed] = React.useState(false); + React.useEffect(() => setArmed(true), []); + const wanted = armed ? text : ""; + const [shown, setShown] = React.useState(SILENT); + if (shown.text !== wanted) { + const next = settleAnnouncement(shown, wanted, Date.now()); + if (next.shown !== shown) setShown(next.shown); + } + React.useEffect(() => { + if (shown.text === wanted) return; + const wait = settleAnnouncement(shown, wanted, Date.now()).retryInMs ?? 0; + const timer = setTimeout(() => setShown({ text: wanted, at: Date.now() }), wait); + return () => clearTimeout(timer); + }, [wanted, shown]); + return shown.text; +} + +/** The line's word and mark, plus the step's detail on the Mac with Follows the work. */ +function botStatusParts(activity: BotLiveActivity, wording: BotChatActivityWording) { + const display = botActivityDisplay(activity.phase, wording, activity.app); + const detail = wording === "follows" && display.phase !== "thinking" ? activity.step?.detail : undefined; + return { display, detail }; +} + +/** What the line says to a screen reader: the word, plus the step on the Mac with Follows the work. */ +export function botStatusSpeech(activity: BotLiveActivity, wording: BotChatActivityWording): string { + const { display, detail } = botStatusParts(activity, wording); + return detail ? `${display.word}, ${detail}` : display.word; +} + +/** + * The status line's live region. Keep it mounted for the whole chat and pass "" + * while no line shows: a region that mounts together with its text may stay silent. + */ +export function BotStatusAnnouncer({ text }: { text: string }) { + const announced = useAnnouncement(text); + return ( +
+ {announced} +
+ ); +} + +export function BotStatusLine({ + activity, + wording, + now: fixedNow, + onStop, + onLayoutChange, +}: { + activity: BotLiveActivity; + wording: BotChatActivityWording; + /** A fixed clock (tests and previews); otherwise the line ticks each second. */ + now?: number; + /** Shown as Stop once the turn has run for 20 seconds. */ + onStop?(): void; + /** Reports which optional parts are showing, so a pinned scroll view can follow the height change. */ + onLayoutChange?(key: string): void; +}) { + const { display, detail } = botStatusParts(activity, wording); + const now = useClock(fixedNow); + const elapsed = botElapsedLabel(activity.startedAt, now); + // Waiting on the person, or already stopping: "I'll message you when it's done" would mislead. + const stillGoing = + now - activity.startedAt >= BOT_STILL_GOING_AFTER_MS && display.phase !== "waiting" && display.phase !== "stopping"; + const layoutKey = `${elapsed ? "e" : ""}${stillGoing ? "s" : ""}`; + React.useEffect(() => { + onLayoutChange?.(layoutKey); + return () => onLayoutChange?.(""); + }, [layoutKey, onLayoutChange]); + const stoppable = Boolean(elapsed && onStop) && activity.phase !== "stopping"; + const shimmer = display.phase !== "waiting" && display.phase !== "stopping"; + return ( +
+
+
+ + +
+ {stoppable ? ( + + ) : null} +
+ {stillGoing ? ( + + Still going. I'll message you when it's done. + + ) : null} +
+ ); +} diff --git a/renderer/main/bots/bot-transcript-rows.test.ts b/renderer/main/bots/bot-transcript-rows.test.ts index 2489d81ff5..61b3217c3d 100644 --- a/renderer/main/bots/bot-transcript-rows.test.ts +++ b/renderer/main/bots/bot-transcript-rows.test.ts @@ -4,91 +4,244 @@ import type { BotTranscriptEntry } from "../../shared/bot-live"; import { botTranscriptRows } from "./bot-transcript-rows"; const user = (id: string, text: string): BotTranscriptEntry => ({ id, type: "user", text, imageCount: 0 }); +const userAt = (id: string, text: string, at: number): BotTranscriptEntry => ({ id, type: "user", text, imageCount: 0, at }); const step = (id: string, text: string): BotTranscriptEntry => ({ id, type: "assistant", text, - toolCalls: [{ id: `${id}-call`, name: "web_search" }], + toolCalls: [{ id: `${id}-call`, name: "web_search", kind: "searching", label: "Searched the web" }], stopReason: "toolUse", }); const answer = (id: string, text: string): BotTranscriptEntry => ({ id, type: "assistant", text, toolCalls: [], stopReason: "stop" }); -const result = (id: string): BotTranscriptEntry => ({ id, type: "tool_result", toolCallId: `${id}-call`, toolName: "web_search", isError: false }); +const answerAt = (id: string, text: string, at: number): BotTranscriptEntry => ({ id, type: "assistant", text, toolCalls: [], stopReason: "stop", at }); +const result = (id: string): BotTranscriptEntry => ({ id, type: "tool_result", toolCallId: `${id}-call`, toolName: "web_search", isError: false, status: "ok" }); const failed = (id: string, retryText: string | null): BotTranscriptEntry => ({ id, type: "failed_turn", retryText }); const kinds = (rows: ReturnType) => rows.map((row) => row.kind); -test("every tool round of one reply folds into a single Updates line before the answer", () => { +const quiet = { running: false, level: "quiet" } as const; + +test("narration written alongside tool calls is a bubble, and tool steps never become rows", () => { const rows = botTranscriptRows( [ user("u1", "Find flights"), - step("a1", "Searching airlines."), + step("a1", "On it, I'll check the airlines."), result("a1"), - step("a2", "Comparing prices."), + step("a2", ""), result("a2"), - step("a3", ""), - result("a3"), - answer("a4", "The cheapest is TAP on Friday."), - user("u2", "Book it"), - step("b1", "Opening the booking page."), - result("b1"), - answer("b2", "Booked."), + answer("a3", "The cheapest is TAP on Friday."), ], null, - false, + quiet, + ); + assert.deepEqual( + rows.map((row) => (row.kind === "assistant" ? `assistant:${row.text}` : row.kind)), + ["user", "assistant:On it, I'll check the airlines.", "assistant:The cheapest is TAP on Friday."], ); - assert.deepEqual(kinds(rows), ["user", "updates", "assistant", "user", "updates", "assistant"]); - const first = rows[1]; - assert.equal(first?.kind === "updates" && first.progressText, "Searching airlines.\n\nComparing prices."); - assert.equal(first?.kind === "updates" && first.active, false); }); -test("a running reply keeps one Working line that also carries the streamed text", () => { - const rows = botTranscriptRows( - [user("u1", "Plan dinner"), step("a1", "Checking the fridge list."), result("a1")], - "Looking at recipes", - true, +test("a running reply streams as a bubble, and nothing is shown before it has words", () => { + const rows = botTranscriptRows([user("u1", "Plan dinner")], "Looking at recipes", { running: true, level: "quiet" }); + assert.deepEqual(rows[rows.length - 1], { kind: "assistant", id: "partial", text: "Looking at recipes", streaming: true }); + assert.deepEqual(kinds(botTranscriptRows([user("u1", "Hi")], null, { running: true, level: "quiet" })), ["user"]); +}); + +test("Quiet never adds a recap; Summary puts one recap of the turn right above its answer", () => { + const entries = [ + userAt("u1", "Find flights", 1_000), + step("a1", ""), + { ...result("a1"), at: 4_000 } as BotTranscriptEntry, + { id: "f1", type: "file", path: "trips.md", operation: "written" } as BotTranscriptEntry, + answerAt("a2", "TAP on Friday.", 19_000), + ]; + assert.equal(kinds(botTranscriptRows(entries, null, quiet)).includes("recap"), false); + const rows = botTranscriptRows(entries, null, { running: false, level: "summary" }); + assert.deepEqual(kinds(rows), ["user", "file", "recap", "assistant"]); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.equal(recap.live, false); + assert.equal(recap.durationMs, 18_000); + assert.deepEqual(recap.steps.map((s) => [s.kind, s.status]), [["searching", "ok"]]); +}); + +test("while running, Summary shows no recap yet and Detailed shows a live one at the end", () => { + const entries = [user("u1", "Plan dinner"), step("a1", "")]; + assert.equal(kinds(botTranscriptRows(entries, null, { running: true, level: "summary" })).includes("recap"), false); + const rows = botTranscriptRows(entries, null, { running: true, level: "detailed" }); + const recap = rows[rows.length - 1]; + assert.ok(recap?.kind === "recap"); + assert.equal(recap.live, true); + assert.deepEqual(recap.steps.map((s) => s.status), ["running"]); +}); + +test("a call with no result in a finished turn counts as failed", () => { + const rows = botTranscriptRows([user("u1", "go"), step("a1", ""), answer("a2", "Done.")], null, { running: false, level: "summary" }); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.deepEqual(recap.steps.map((s) => s.status), ["failed"]); +}); + +test("Stop during a tool run: the step reads as stopped and the turn ends with a stopped line", () => { + // The harness writes only the round's tool results (status "stopped"); no aborted reply follows. + const stoppedResult = { ...result("a1"), status: "stopped", isError: true } as BotTranscriptEntry; + const rows = botTranscriptRows([user("u1", "go"), step("a1", ""), stoppedResult], null, { running: false, level: "summary" }); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.deepEqual(recap.steps.map((s) => s.status), ["stopped"]); + assert.equal(rows[rows.length - 1]?.kind, "stopped"); + const quietRows = botTranscriptRows([user("u1", "go"), step("a1", ""), stoppedResult], null, quiet); + assert.equal(quietRows[quietRows.length - 1]?.kind, "stopped", "Quiet shows the stopped line too"); + + const restarted = botTranscriptRows( + [user("u1", "go"), step("a1", ""), stoppedResult, { id: "n1", type: "notice", notice: "interrupted" }], + null, + quiet, ); - assert.deepEqual(kinds(rows), ["user", "updates"]); - const updates = rows[1]; - assert.equal(updates?.kind === "updates" && updates.active, true); - assert.equal(updates?.kind === "updates" && updates.progressText, "Checking the fridge list.\n\nLooking at recipes"); + assert.equal(kinds(restarted).includes("stopped"), false, "a restart cut it short; the person did not stop it"); +}); - // Just sent: nothing written yet, the Bot is still shown working. - assert.deepEqual(kinds(botTranscriptRows([user("u1", "Hi")], null, true)), ["user", "updates"]); +test("an unfinished call in a reply the person stopped is stopped, not failed", () => { + const aborted: BotTranscriptEntry = { + id: "a1", + type: "assistant", + text: "", + toolCalls: [{ id: "a1-call", name: "run_command", kind: "command", label: "Ran a command" }], + stopReason: "aborted", + }; + const rows = botTranscriptRows([user("u1", "go"), aborted], null, { running: false, level: "summary" }); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.deepEqual(recap.steps.map((s) => s.status), ["stopped"]); + assert.equal(rows[rows.length - 1]?.kind, "stopped"); }); -test("files and shared images show as chips in the reply, not as extra Updates lines", () => { - const rows = botTranscriptRows( - [ - user("u1", "Write my list"), - step("a1", "Writing it."), - result("a1"), - { id: "f1", type: "file", path: "lists/groceries.md", operation: "written" }, - { id: "i1", type: "shared_image", name: "chart.png", mimeType: "image/png", size: 3, data: "AAAA" }, - ], +test("a reply that carries on after a restart's stop marker and finishes never reads as stopped", () => { + // Resume after a restart: recovery settles an unsafe in-flight tool as interrupted ("stopped"), then the run goes on. + const interruptedResult = { ...result("a1"), status: "stopped", isError: true } as BotTranscriptEntry; + const resumed = botTranscriptRows( + [user("u1", "go"), step("a1", ""), interruptedResult, answer("a2", "Recovered.")], null, - true, + { running: false, level: "summary" }, ); - assert.deepEqual(kinds(rows), ["user", "updates", "file", "image"]); - assert.equal(rows[1]?.kind === "updates" && rows[1].active, true); + assert.equal(kinds(resumed).includes("stopped"), false, kinds(resumed).join(", ")); + const recap = resumed.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.deepEqual(recap.steps.map((s) => s.status), ["stopped"], "the cut-short step stays neutral"); + + // A retried request after a restart mid-stream: the partial lands as an aborted reply, then the retry answers. + const partialCall: BotTranscriptEntry = { + id: "a1", + type: "assistant", + text: "Once upon", + toolCalls: [{ id: "a1-call", name: "run_command", kind: "command", label: "Ran a command" }], + stopReason: "aborted", + }; + const retried = botTranscriptRows([user("u1", "Story"), partialCall, answer("a2", "Recovered.")], null, { + running: false, + level: "summary", + }); + assert.equal(kinds(retried).includes("stopped"), false, kinds(retried).join(", ")); + const retriedRecap = retried.find((row) => row.kind === "recap"); + assert.ok(retriedRecap?.kind === "recap"); + assert.deepEqual(retriedRecap.steps.map((s) => s.status), ["stopped"], "the unfinished call is neither failed nor running"); +}); + +test("a reply the person stopped ends with a stopped line; an interrupted one does not", () => { + const aborted: BotTranscriptEntry = { id: "a1", type: "assistant", text: "Once upon", toolCalls: [], stopReason: "aborted" }; + assert.deepEqual(kinds(botTranscriptRows([user("u1", "Story"), aborted], null, quiet)), ["user", "assistant", "stopped"]); + const interrupted = botTranscriptRows( + [user("u1", "Story"), aborted, { id: "n1", type: "notice", notice: "interrupted" }], + null, + quiet, + ); + assert.deepEqual(kinds(interrupted), ["user", "assistant", "notice"]); }); test("only the newest failed turn offers Retry, and never while the Bot is working", () => { const history = [user("u1", "Plan dinner"), failed("a1:failed", "Plan dinner")]; - const latest = botTranscriptRows(history, null, false).slice(-1)[0]; + const latest = botTranscriptRows(history, null, quiet).slice(-1)[0]; assert.deepEqual(latest, { kind: "failed", id: "a1:failed", retryText: "Plan dinner" }); - const older = botTranscriptRows([...history, user("u2", "Never mind"), answer("a2", "Okay.")], null, false); + const older = botTranscriptRows([...history, user("u2", "Never mind"), answer("a2", "Okay.")], null, quiet); assert.deepEqual(older.find((row) => row.kind === "failed"), { kind: "failed", id: "a1:failed", retryText: null }); - const busy = botTranscriptRows(history, null, true).find((row) => row.kind === "failed"); + const busy = botTranscriptRows(history, null, { running: true, level: "quiet" }).find((row) => row.kind === "failed"); assert.equal(busy?.kind === "failed" && busy.retryText, null); - const routine = botTranscriptRows([failed("r1:failed", null)], null, false)[0]; + const routine = botTranscriptRows([failed("r1:failed", null)], null, quiet)[0]; assert.equal(routine?.kind === "failed" && routine.retryText, null); }); -test("a paused reply keeps what it wrote as a bubble instead of a Working line", () => { - const rows = botTranscriptRows([user("u1", "Summarize")], "Here is what I have so far", false); +test("a paused reply keeps what it wrote as a bubble", () => { + const rows = botTranscriptRows([user("u1", "Summarize")], "Here is what I have so far", quiet); assert.deepEqual(rows[rows.length - 1], { kind: "assistant", id: "partial", text: "Here is what I have so far" }); }); + +test("a queued follow-up is a faded row at the end, and a steer is a normal bubble right away", () => { + const rows = botTranscriptRows([user("u1", "Plan dinner")], null, { + running: true, + level: "quiet", + queued: [ + { submissionId: "7", mode: "steer", text: "Make it vegetarian", imageCount: 0 }, + { submissionId: "8", mode: "followUp", text: "", imageCount: 2 }, + { submissionId: "9", mode: "followUp", text: "", imageCount: 0 }, + ], + }); + assert.deepEqual(rows.slice(1), [ + { kind: "user", id: "queued:7", text: "Make it vegetarian" }, + { kind: "queued", id: "queued:8", submissionId: "8", text: "2 photos" }, + ]); +}); + +test("a steer placed after the round's tool results keeps the step ok and reads in order", () => { + // pi-durable places a steer at the post-tools boundary: result first, then the steer, then the reply continues. + const entries = [ + userAt("u1", "Find flights", 1_000), + step("a1", ""), + { ...result("a1"), at: 4_000 } as BotTranscriptEntry, + user("u2", "Make it cheap"), + answerAt("a2", "TAP on Friday.", 9_000), + ]; + const rows = botTranscriptRows(entries, null, { running: false, level: "summary" }); + assert.deepEqual( + rows.map((row) => (row.kind === "user" ? `user:${row.text}` : row.kind)), + ["user:Find flights", "recap", "user:Make it cheap", "assistant"], + ); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.deepEqual(recap.steps.map((s) => [s.kind, s.status]), [["searching", "ok"]]); +}); + +test("a new message after a reply stopped mid tool call starts its own turn; the stopped line stays with the first", () => { + const aborted: BotTranscriptEntry = { + id: "a1", + type: "assistant", + text: "", + toolCalls: [{ id: "a1-call", name: "web_search", kind: "searching", label: "Searched the web" }], + stopReason: "aborted", + at: 2_000, + }; + const entries = [userAt("u1", "Find flights", 1_000), aborted, userAt("u2", "Never mind, hotels", 3_600_000), answerAt("a3", "Hotel X.", 3_601_000)]; + const rows = botTranscriptRows(entries, null, { running: false, level: "summary" }); + assert.deepEqual( + rows.map((row) => (row.kind === "user" ? `user:${row.text}` : row.kind)), + ["user:Find flights", "recap", "stopped", "user:Never mind, hotels", "assistant"], + ); + const recap = rows.find((row) => row.kind === "recap"); + assert.ok(recap?.kind === "recap"); + assert.equal(recap.durationMs, 1_000); + assert.deepEqual(recap.steps.map((s) => s.status), ["stopped"]); +}); + +test("a new message after a finished tool starts a new turn with its own recap", () => { + const entries = [ + user("u1", "Find flights"), + step("a1", ""), + result("a1"), + answer("a2", "TAP."), + user("u2", "And hotels"), + answer("a3", "Hotel X."), + ]; + const rows = botTranscriptRows(entries, null, { running: false, level: "summary" }); + assert.deepEqual(kinds(rows), ["user", "recap", "assistant", "user", "assistant"]); +}); diff --git a/renderer/main/bots/bot-transcript-rows.ts b/renderer/main/bots/bot-transcript-rows.ts index 0ffb1369fc..94c7dc33eb 100644 --- a/renderer/main/bots/bot-transcript-rows.ts +++ b/renderer/main/bots/bot-transcript-rows.ts @@ -1,31 +1,44 @@ // What a Bot chat shows, row by row, from the durable projection. // -// Everything a Bot did on the way to its answer folds into ONE "Updates" line -// per reply: narration written before tool calls, and the in-flight partial -// while the reply runs. A reply's turn starts at the person's message (or a -// routine, or their answer to a question) and ends at the next one. +// A reply's turn starts at the person's message (or a routine, or their answer +// to a question) and ends at the next one. Everything the Bot writes is a +// bubble, including the narration it writes alongside tool calls (spec +// decision 9); tool steps themselves never become rows. With Summary or +// Detailed chat activity, a turn that used tools also gets one recap of its +// steps just above its answer; Detailed shows it, live, while the turn runs. +// A reply the person stopped ends with a "stopped" line that is derived here +// and never stored. -import { - botRetryableFailedTurn, - type BotTranscriptEntry, -} from "../../shared/bot-live"; +import { botRetryableFailedTurn, type BotQueuedMessage, type BotTranscriptEntry } from "../../shared/bot-live"; +import type { BotChatActivityLevel } from "../../shared/bots"; import type { ConnectCardEntry } from "../../shared/bot-connections"; import type { BotRoutineProposalEntryData, BotRoutineProposalStatus } from "../../shared/bot-routine-proposals"; -import { resolveBotReplyProjection } from "./bot-reply-projection"; +import type { BotRecapStep } from "./bot-activity-steps"; + +export interface BotTranscriptRowOptions { + running: boolean; + level: BotChatActivityLevel; + /** Messages waiting for the running turn (a follow-up is faded; a steer reads as sent). */ + queued?: readonly BotQueuedMessage[]; +} export type BotTranscriptRow = | { kind: "user"; id: string; text: string } | { kind: "routine"; id: string; label: string; text: string } | { kind: "assistant"; id: string; text: string; streaming?: boolean } - /** The one collapsed progress line of a reply; `active` while it runs. */ - | { kind: "updates"; id: string; progressText: string; active: boolean } + /** One turn's steps; `live` while the turn runs (Detailed only). */ + | { kind: "recap"; id: string; steps: BotRecapStep[]; durationMs: number; live: boolean } + /** "You stopped this reply." */ + | { kind: "stopped"; id: string } + /** A follow-up waiting for the running turn; shown faded with Remove. */ + | { kind: "queued"; id: string; submissionId: string; text: string } | { kind: "file"; id: string; path: string; operation: "written" | "edited" } | { kind: "image"; id: string; name: string; mimeType: string; size: number; data: string } | { kind: "notice"; id: string; notice: "interrupted" | "session_reset" } | { kind: "connect"; id: string; card: ConnectCardEntry } /** `retryText` is set only on the newest failed turn, when Retry applies. */ | { kind: "failed"; id: string; retryText: string | null; errorMessage?: string } - /** A quiet "Memory updated" caption; never folded into Updates. */ + /** A quiet "Memory updated" caption. */ | { kind: "memory_update"; id: string } | { kind: "routine_proposal"; @@ -35,52 +48,117 @@ export type BotTranscriptRow = routineId?: string; }; -type UpdatesRow = Extract; - -function joinProgress(parts: readonly string[]): string { - return parts.map((part) => part.trim()).filter(Boolean).join("\n\n"); +interface Turn { + id: string; + startAt?: number; + lastAt?: number; + /** Index of the turn's answer bubble in `rows`, once it has one. */ + answerRow: number | null; + steps: BotRecapStep[]; + byCall: Map; + /** The person pressed Stop during this reply. */ + stopped: boolean; + /** The app restarted mid-turn; a call with no result was cut short, not failed. */ + interrupted: boolean; } export function botTranscriptRows( entries: readonly BotTranscriptEntry[], partial: string | null, - running: boolean, + { running, level, queued }: BotTranscriptRowOptions, ): BotTranscriptRow[] { const rows: BotTranscriptRow[] = []; const retryable = running ? null : botRetryableFailedTurn(entries); - // The current reply's Updates row and the narration folded into it so far. - let updates: { row: UpdatesRow; parts: string[] } | null = null; - const fold = (id: string, text: string) => { - if (!updates) { - const row: UpdatesRow = { kind: "updates", id: `${id}:updates`, progressText: "", active: false }; - rows.push(row); - updates = { row, parts: [] }; + // The current turn, once a message has started one. + const state: { turn: Turn | null } = { turn: null }; + + const endTurn = (live: boolean) => { + const turn = state.turn; + state.turn = null; + if (!turn) return; + const steps = turn.steps.filter((step) => step.kind !== "waiting"); + if (steps.length > 0 && (level === "detailed" || (level === "summary" && !live))) { + // A finished turn has no running step: a call that never reported back + // was cut short by Stop or a restart, or else it failed. + const unfinished = turn.stopped || turn.interrupted ? "stopped" : "failed"; + const recap: BotTranscriptRow = { + kind: "recap", + id: `${turn.id}:recap`, + steps: live ? steps : steps.map((step) => (step.status === "running" ? { ...step, status: unfinished } : step)), + durationMs: Math.max(0, (turn.lastAt ?? 0) - (turn.startAt ?? turn.lastAt ?? 0)), + live, + }; + if (live || turn.answerRow === null) rows.push(recap); + else rows.splice(turn.answerRow, 0, recap); } - updates.parts.push(text); - updates.row.progressText = joinProgress(updates.parts); + if (turn.stopped && !live) rows.push({ kind: "stopped", id: `${turn.id}:stopped` }); + }; + + const beginTurn = (id: string, at: number | undefined) => { + endTurn(false); + state.turn = { + id, + ...(at === undefined ? {} : { startAt: at, lastAt: at }), + answerRow: null, + steps: [], + byCall: new Map(), + stopped: false, + interrupted: false, + }; + }; + + // A person's Stop ends the run. If the run carries on after a stop marker, a + // restart cut it short and Resume or a retry picked it up: no stopped line. + const carriedOn = (turn: Turn) => { + if (!turn.stopped) return; + turn.stopped = false; + turn.interrupted = true; }; - const endTurn = () => { - updates = null; + + const touch = (at: number | undefined) => { + if (state.turn && at !== undefined) state.turn.lastAt = at; }; for (const entry of entries) { switch (entry.type) { case "user": - endTurn(); + // Every message starts a turn: a steer is placed after the round's tool results, so it never splits a step from its result. + beginTurn(entry.id, entry.at); rows.push({ kind: "user", id: entry.id, text: entry.text }); break; case "question_answer": - endTurn(); + beginTurn(entry.id, entry.at); rows.push({ kind: "user", id: entry.id, text: entry.text }); break; case "routine": - endTurn(); + beginTurn(entry.id, entry.at); rows.push({ kind: "routine", id: entry.id, label: entry.label, text: entry.text }); break; - case "assistant": - if (entry.toolCalls.length > 0) fold(entry.id, entry.text); - else if (entry.text.trim()) rows.push({ kind: "assistant", id: entry.id, text: entry.text }); + case "assistant": { + // A reply with no visible input (the self-intro) still gets a turn. + if (!state.turn) beginTurn(entry.id, entry.at); + const turn = state.turn!; + touch(entry.at); + for (const call of entry.toolCalls) { + const recapStep: BotRecapStep = { + id: call.id, + kind: call.kind, + label: call.label, + ...(call.detail ? { detail: call.detail } : {}), + ...(call.app ? { app: call.app } : {}), + status: "running", + }; + turn.steps.push(recapStep); + turn.byCall.set(call.id, recapStep); + } + if (entry.stopReason === "aborted") turn.stopped = true; + else carriedOn(turn); + if (entry.text.trim()) { + if (entry.toolCalls.length === 0) turn.answerRow = rows.length; + rows.push({ kind: "assistant", id: entry.id, text: entry.text }); + } break; + } case "file": rows.push({ kind: "file", id: entry.id, path: entry.path, operation: entry.operation }); break; @@ -88,13 +166,19 @@ export function botTranscriptRows( rows.push({ kind: "image", id: entry.id, name: entry.name, mimeType: entry.mimeType, size: entry.size, data: entry.data }); break; case "notice": - endTurn(); + // A restart cut the turn short; the person did not stop it. + if (entry.notice === "interrupted" && state.turn) { + state.turn.stopped = false; + state.turn.interrupted = true; + } + endTurn(false); rows.push({ kind: "notice", id: entry.id, notice: entry.notice }); break; case "connect_card": rows.push({ kind: "connect", id: entry.id, card: entry.card }); break; case "failed_turn": + if (state.turn) carriedOn(state.turn); rows.push({ kind: "failed", id: entry.id, @@ -115,26 +199,34 @@ export function botTranscriptRows( ...(entry.routineId ? { routineId: entry.routineId } : {}), }); break; - case "tool_result": + case "tool_result": { + touch(entry.at); + const recapStep = state.turn?.byCall.get(entry.toolCallId); + if (recapStep) recapStep.status = entry.status; + // A Stop during a tool run writes only the round's results; no aborted reply follows. + // A later "interrupted" notice still turns it back into a restart. + if (entry.status === "stopped" && state.turn) state.turn.stopped = true; break; + } } } - if (running) { - // Everything streamed so far is progress until the reply commits. - const { progressText } = partial === null ? { progressText: "" } : resolveBotReplyProjection(partial, null, true); - // The reply's existing Updates line carries it, even with chips below it. - const current = updates as { row: UpdatesRow; parts: string[] } | null; - if (current) { - current.row.active = true; - if (progressText) current.row.progressText = joinProgress([...current.parts, progressText]); - } else { - rows.push({ kind: "updates", id: "working", progressText, active: true }); - } - } else if (partial !== null) { - // A paused reply keeps what it wrote, as a bubble. - const text = partial.trim(); - if (text) rows.push({ kind: "assistant", id: "partial", text: partial }); + endTurn(running); + if (partial !== null && partial.trim()) { + rows.push({ kind: "assistant", id: "partial", text: partial, ...(running ? { streaming: true } : {}) }); + } + for (const message of queued ?? []) { + const text = message.text.trim() + ? message.text + : message.imageCount === 1 + ? "Photo" + : message.imageCount > 1 + ? `${message.imageCount} photos` + : ""; + if (!text) continue; + // A steer joins the running turn: it reads as sent right away. + if (message.mode === "steer") rows.push({ kind: "user", id: `queued:${message.submissionId}`, text }); + else rows.push({ kind: "queued", id: `queued:${message.submissionId}`, submissionId: message.submissionId, text }); } return rows; } diff --git a/renderer/main/bots/bot-updates.tsx b/renderer/main/bots/bot-updates.tsx deleted file mode 100644 index 761a5ffc18..0000000000 --- a/renderer/main/bots/bot-updates.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import * as React from "react"; -import { ChevronRight } from "lucide-react"; -import { ActivityFeed } from "../../components/activity-feed"; -import { Text } from "../../components/ui"; -import type { GenerationTimeline } from "../../shared/generation-timeline"; - -/** - * One quiet line that holds everything a Bot did on the way to its answer: - * tool activity and any narration before the final reply. Collapsed by - * default; "Working…" while the reply is still running. - */ -export function BotUpdates({ - progressText, - timeline, - active, -}: { - progressText: string; - /** Tool steps only; empty or null when the Bot used no tools. */ - timeline: GenerationTimeline | null; - active: boolean; -}) { - const [open, setOpen] = React.useState(false); - const regionId = React.useId(); - const hasActivity = Boolean(timeline && timeline.steps.length > 0); - if (!progressText && !hasActivity && !active) return null; - return ( -
- - {open ? ( -
- {hasActivity ? : null} - {progressText ? ( - - {progressText} - - ) : null} -
- ) : null} -
- ); -} diff --git a/renderer/main/bots/bots-home.test.tsx b/renderer/main/bots/bots-home.test.tsx index 052a3575c2..8b955a9f2a 100644 --- a/renderer/main/bots/bots-home.test.tsx +++ b/renderer/main/bots/bots-home.test.tsx @@ -74,6 +74,9 @@ test("Start chat on a starter Bot sends one create request and opens its chat", entries: [], partial: null, state: { kind: "idle" }, + question: null, + activity: null, + queued: [], }), }); const { router } = await mountWithBotRouter(, { initialPath: "/bots" }); diff --git a/renderer/main/bots/test-dom.ts b/renderer/main/bots/test-dom.ts index 09aeb3a16c..c40fedcc62 100644 --- a/renderer/main/bots/test-dom.ts +++ b/renderer/main/bots/test-dom.ts @@ -1,4 +1,5 @@ import { Window } from "happy-dom"; +import { invalidateBotCanonicalPhotos } from "../../lib/bot-canonical-photo-cache"; const GLOBAL_KEYS = [ "window", @@ -108,6 +109,8 @@ export function installBotTestIpc( ): BotTestIpcCall[] { const calls: BotTestIpcCall[] = []; notificationListeners.clear(); + // The photo cache is process-wide; a photo cached by an earlier test must not answer this one. + invalidateBotCanonicalPhotos(); (window as unknown as { aidenAPI: unknown }).aidenAPI = { ipc: { invoke: async (channel: string, ...args: unknown[]) => { diff --git a/renderer/shared/bot-activity.test.ts b/renderer/shared/bot-activity.test.ts new file mode 100644 index 0000000000..33e6d432ba --- /dev/null +++ b/renderer/shared/bot-activity.test.ts @@ -0,0 +1,114 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + botActivityDisplay, + botElapsedLabel, + botStepInfinitive, + botStepPhrase, + botToolApp, + botToolPhase, + nextBotAnnouncement, + pickActiveToolSlot, +} from "./bot-activity"; + +// The spec's §5.1 table, row by row: the independent oracle. +const SPEC_TOOL_PHASES: ReadonlyArray<[string, string]> = [ + ["read_file", "reading"], + ["list_dir", "reading"], + ["glob", "reading"], + ["grep", "reading"], + ["edit_file", "editing"], + ["write_file", "editing"], + ["run_command", "command"], + ["web_search", "searching"], + ["computer_use", "computer"], + ["form_fill", "computer"], + ["inspect_image", "photo"], + ["subagent", "helper"], + ["bot_memory", "remembering"], + ["routines", "routine"], + ["routine_notes", "routine"], + ["ask_user_question", "waiting"], + ["share_image", "working"], + ["suggest_connection", "working"], + ["skill_meal_planning", "working"], + ["constructor", "working"], +]; + +test("every Bot tool maps to the phase in the spec's table, and anything else is working", () => { + for (const [tool, phase] of SPEC_TOOL_PHASES) { + assert.equal(botToolPhase(tool, botToolApp(tool)), phase, tool); + } +}); + +test("a connection tool is Using {app}, named from the connection, and bounded", () => { + const tool = "Google_Calendar__list_events_0123456789ab"; + assert.equal(botToolApp(tool), "Google Calendar"); + assert.equal(botToolPhase(tool, botToolApp(tool)), "app"); + assert.equal(botActivityDisplay("app", "follows", "Google Calendar").word, "Using Google Calendar"); + const long = `${"A".repeat(60)}__search_0123456789ab`; + assert.equal([...(botToolApp(long) ?? "")].length, 40); + // Not a minted connection tool name: no app. + assert.equal(botToolApp("web_search"), undefined); + assert.equal(botToolApp("Notion__search"), undefined); +}); + +test("when tools run in parallel, the most recently started one wins", () => { + const slots = [ + { name: "a", status: "done" }, + { name: "b", status: "running" }, + { name: "c", status: "running" }, + { name: "d", status: "pending" }, + ]; + assert.equal(pickActiveToolSlot(slots)?.name, "c"); + assert.equal(pickActiveToolSlot([{ name: "x", status: "pending" }, { name: "y", status: "pending" }])?.name, "x"); + assert.equal(pickActiveToolSlot([{ name: "z", status: "done" }]), undefined); + assert.equal(pickActiveToolSlot(undefined), undefined); +}); + +test("each phase has the spec's word and mark, and an unknown phase is working", () => { + assert.deepEqual(botActivityDisplay("preparing", "follows"), { phase: "preparing", word: "Getting ready", mark: "bounce" }); + assert.deepEqual(botActivityDisplay("reading", "follows"), { phase: "reading", word: "Reading", mark: "scan-grid" }); + assert.deepEqual(botActivityDisplay("tidying", "follows"), { phase: "tidying", word: "Tidying up its notes", mark: "bounce" }); + assert.deepEqual(botActivityDisplay("browsing", "follows"), { phase: "working", word: "Working", mark: "quad-shuffle" }); +}); + +test("Always Thinking says Thinking for everything except waiting, stopping and reconnecting", () => { + for (const phase of ["preparing", "reading", "command", "app", "writing", "tidying", "resuming", "browsing"]) { + assert.deepEqual(botActivityDisplay(phase, "thinking", "Notion"), { phase: "thinking", word: "Thinking", mark: "tri-step" }, phase); + } + assert.equal(botActivityDisplay("waiting", "thinking").word, "Waiting for you"); + assert.equal(botActivityDisplay("stopping", "thinking").word, "Stopping"); + assert.equal(botActivityDisplay("reconnecting", "thinking").word, "Reconnecting to your Mac"); +}); + +test("elapsed time shows only after 20 seconds, as minutes and seconds", () => { + assert.equal(botElapsedLabel(0, 19_999), null); + assert.equal(botElapsedLabel(0, 20_000), "20s"); + assert.equal(botElapsedLabel(0, 72_400), "1m 12s"); + assert.equal(botElapsedLabel(0, 120_000), "2m"); + assert.equal(botElapsedLabel(0, 3_725_000), "1h 2m"); + assert.equal(botElapsedLabel(Number.NaN, 50_000), null); +}); + +test("announcements change at most once every 2 seconds, and the newest wording wins once the gap passes", () => { + const first = nextBotAnnouncement(null, "Reading", 1_000); + assert.deepEqual(first, { shown: { text: "Reading", at: 1_000 } }); + const tooSoon = nextBotAnnouncement(first.shown, "Searching the web", 1_500); + assert.deepEqual(tooSoon, { shown: { text: "Reading", at: 1_000 }, retryInMs: 1_500 }); + const same = nextBotAnnouncement(first.shown, "Reading", 1_200); + assert.equal(same.shown, first.shown); + assert.equal(same.retryInMs, undefined); + assert.deepEqual(nextBotAnnouncement(first.shown, "Editing files", 3_000), { shown: { text: "Editing files", at: 3_000 } }); +}); + +test("step phrases read naturally and count repeats", () => { + assert.equal(botStepPhrase("reading", 1), "Read 1 file"); + assert.equal(botStepPhrase("reading", 6), "Read 6 files"); + assert.equal(botStepPhrase("searching", 1), "Searched the web"); + assert.equal(botStepPhrase("searching", 3), "Searched the web 3 times"); + assert.equal(botStepPhrase("app", 1, "Notion"), "Used Notion"); + assert.equal(botStepPhrase("command", 2), "Ran 2 commands"); + assert.equal(botStepInfinitive("command"), "run a command"); + assert.equal(botStepInfinitive("app", "Notion"), "use Notion"); +}); diff --git a/renderer/shared/bot-activity.ts b/renderer/shared/bot-activity.ts new file mode 100644 index 0000000000..b9016eee68 --- /dev/null +++ b/renderer/shared/bot-activity.ts @@ -0,0 +1,243 @@ +// What a working Bot's status line says (spec 2026-10-14 §5): one phase at a +// time, with the same ids, words and marks on the Mac and, from slice D, on +// phones. Main classifies the active tool with this table, the renderer draws +// it, and the CLI bundles it as is. + +import type { ActivityMark } from "./activity-marks.js"; +import type { BotChatActivityWording } from "./bots.js"; + +export const BOT_ACTIVITY_PHASES = [ + "preparing", + "thinking", + "reading", + "photo", + "searching", + "command", + "editing", + "app", + "helper", + "computer", + "remembering", + "routine", + "working", + "writing", + "waiting", + "tidying", + "stopping", + "resuming", + "reconnecting", +] as const; +export type BotActivityPhase = (typeof BOT_ACTIVITY_PHASES)[number]; + +/** The phases an active tool maps to (§5.1). */ +export type BotToolPhase = Extract< + BotActivityPhase, + | "reading" + | "photo" + | "searching" + | "command" + | "editing" + | "app" + | "helper" + | "computer" + | "remembering" + | "routine" + | "working" + | "waiting" +>; + +export type { BotChatActivityWording } from "./bots.js"; + +const PHASES: Record = { + preparing: { word: "Getting ready", mark: "bounce" }, + thinking: { word: "Thinking", mark: "tri-step" }, + reading: { word: "Reading", mark: "scan-grid" }, + photo: { word: "Looking at your photo", mark: "scan-grid" }, + searching: { word: "Searching the web", mark: "scan-grid" }, + command: { word: "Running a command", mark: "quad-shuffle" }, + editing: { word: "Editing files", mark: "quad-shuffle" }, + app: { word: "Using an app", mark: "quad-shuffle" }, + helper: { word: "Asking a helper", mark: "quad-shuffle" }, + computer: { word: "Using your Mac", mark: "quad-shuffle" }, + remembering: { word: "Remembering", mark: "compose" }, + routine: { word: "Setting up a routine", mark: "tri-step" }, + working: { word: "Working", mark: "quad-shuffle" }, + writing: { word: "Writing", mark: "compose" }, + waiting: { word: "Waiting for you", mark: "glance" }, + tidying: { word: "Tidying up its notes", mark: "bounce" }, + stopping: { word: "Stopping", mark: "bounce" }, + resuming: { word: "Picking up where it left off", mark: "bounce" }, + reconnecting: { word: "Reconnecting to your Mac", mark: "bounce" }, +}; + +/** The Bot tool set's fixed tools (`bot-tool-policy.ts`, `bot-file-tool-router.ts`). */ +const TOOL_PHASES: ReadonlyMap = new Map([ + ["read_file", "reading"], + ["list_dir", "reading"], + ["glob", "reading"], + ["grep", "reading"], + ["edit_file", "editing"], + ["write_file", "editing"], + ["run_command", "command"], + ["web_search", "searching"], + ["computer_use", "computer"], + ["form_fill", "computer"], + ["inspect_image", "photo"], + ["subagent", "helper"], + ["bot_memory", "remembering"], + ["routines", "routine"], + ["routine_notes", "routine"], + ["ask_user_question", "waiting"], +]); + +const PHASE_IDS: ReadonlySet = new Set(BOT_ACTIVITY_PHASES); + +function isBotActivityPhase(value: unknown): value is BotActivityPhase { + return typeof value === "string" && PHASE_IDS.has(value); +} + +/** The longest connection label a status line shows; the Remote wire uses the same bound (§11). */ +export const BOT_APP_LABEL_CHARS = 40; + +// `mcpAgentToolName` (main/services/mcp-tool-identity.ts) mints connection +// tools as `___<12 hex>`, with other characters as `_`. +const MCP_AGENT_TOOL = /^(.+?)__.+_[0-9a-f]{12}$/u; + +/** The connection label of an MCP or Composio tool, or undefined for Aiden's own tools. */ +export function botToolApp(toolName: string): string | undefined { + const match = MCP_AGENT_TOOL.exec(toolName); + const label = match?.[1]?.replace(/_+/gu, " ").trim(); + if (!label) return undefined; + const points = [...label]; + return points.length > BOT_APP_LABEL_CHARS ? points.slice(0, BOT_APP_LABEL_CHARS).join("").trimEnd() : label; +} + +/** The phase an active tool puts its Bot in (§5.1). */ +export function botToolPhase(toolName: string, app?: string): BotToolPhase { + return TOOL_PHASES.get(toolName) ?? (app ? "app" : "working"); +} + +/** The status line's word for a phase; `app` fills "Using {app}". */ +export function botPhaseWord(phase: BotActivityPhase, app?: string): string { + return phase === "app" && app ? `Using ${app}` : PHASES[phase].word; +} + +/** Phases that keep their own word under Always "Thinking": they change what the person should do. */ +const KEEPS_ITS_WORD: ReadonlySet = new Set(["waiting", "stopping", "reconnecting"]); + +export interface BotActivityDisplay { + phase: BotActivityPhase; + word: string; + mark: ActivityMark; +} + +/** What the line shows for a phase id from any client: unknown ids read as `working` (§5.2). */ +export function botActivityDisplay(phase: string, wording: BotChatActivityWording, app?: string): BotActivityDisplay { + const known: BotActivityPhase = isBotActivityPhase(phase) ? phase : "working"; + const shown: BotActivityPhase = wording === "thinking" && !KEEPS_ITS_WORD.has(known) ? "thinking" : known; + return { phase: shown, word: botPhaseWord(shown, app), mark: PHASES[shown].mark }; +} + +interface StepPhrases { + one: string; + many(count: number): string; + infinitive: string; +} + +function stepPhrases(kind: BotToolPhase, app?: string): StepPhrases { + const name = app ?? "an app"; + switch (kind) { + case "reading": + return { one: "Read 1 file", many: (n) => `Read ${n} files`, infinitive: "read a file" }; + case "editing": + return { one: "Edited 1 file", many: (n) => `Edited ${n} files`, infinitive: "edit a file" }; + case "command": + return { one: "Ran a command", many: (n) => `Ran ${n} commands`, infinitive: "run a command" }; + case "searching": + return { one: "Searched the web", many: (n) => `Searched the web ${n} times`, infinitive: "search the web" }; + case "photo": + return { one: "Looked at your photo", many: (n) => `Looked at ${n} photos`, infinitive: "look at your photo" }; + case "computer": + return { one: "Used your Mac", many: (n) => `Used your Mac ${n} times`, infinitive: "use your Mac" }; + case "helper": + return { one: "Asked a helper", many: (n) => `Asked ${n} helpers`, infinitive: "ask a helper" }; + case "remembering": + return { one: "Updated its memory", many: () => "Updated its memory", infinitive: "update its memory" }; + case "routine": + return { one: "Set up a routine", many: (n) => `Worked on ${n} routines`, infinitive: "set up a routine" }; + case "app": + return { one: `Used ${name}`, many: (n) => `Used ${name} ${n} times`, infinitive: `use ${name}` }; + case "waiting": + return { one: "Asked you a question", many: (n) => `Asked you ${n} questions`, infinitive: "ask you a question" }; + case "working": + return { one: "Used a tool", many: (n) => `Used ${n} tools`, infinitive: "use a tool" }; + } +} + +/** A finished step, past tense: "Read 1 file", "Read 6 files", "Used Notion". */ +export function botStepPhrase(kind: BotToolPhase, count: number, app?: string): string { + const phrases = stepPhrases(kind, app); + return count <= 1 ? phrases.one : phrases.many(count); +} + +/** The bare verb phrase for "Couldn’t …" and "Blocked: …". */ +export function botStepInfinitive(kind: BotToolPhase, app?: string): string { + return stepPhrases(kind, app).infinitive; +} + +const BOT_ELAPSED_AFTER_MS = 20_000; +export const BOT_STILL_GOING_AFTER_MS = 120_000; + +/** "18s", "1m 12s", "2m", "1h 2m". Never less than one second. */ +export function botDurationLabel(ms: number): string { + const seconds = Math.max(1, Math.floor(ms / 1_000)); + if (seconds < 60) return `${seconds}s`; + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + if (minutes < 60) return rest ? `${minutes}m ${rest}s` : `${minutes}m`; + const hours = Math.floor(minutes / 60); + const remainder = minutes % 60; + return remainder ? `${hours}h ${remainder}m` : `${hours}h`; +} + +/** The status line's elapsed time, once a turn has run for 20 seconds. */ +export function botElapsedLabel(startedAt: number, now: number): string | null { + const elapsed = now - startedAt; + return Number.isFinite(elapsed) && elapsed >= BOT_ELAPSED_AFTER_MS ? botDurationLabel(elapsed) : null; +} + +/** Screen readers hear a phase change at most this often (§14). */ +export const BOT_ANNOUNCE_GAP_MS = 2_000; + +export interface BotAnnouncement { + text: string; + at: number; +} + +/** + * What to announce now. A change inside the gap keeps the current text and + * says when to try again; the newest text wins once the gap has passed. + */ +export function nextBotAnnouncement( + current: BotAnnouncement | null, + text: string, + now: number, + gapMs = BOT_ANNOUNCE_GAP_MS, +): { shown: BotAnnouncement; retryInMs?: number } { + if (current !== null && current.text === text) return { shown: current }; + if (current === null || now - current.at >= gapMs) return { shown: { text, at: now } }; + return { shown: current, retryInMs: gapMs - (now - current.at) }; +} + +/** + * The tool slot a status line follows. Slots are in call order and parallel + * calls start in that order, so the last running one started most recently; + * with none running, the first one about to start. + */ +export function pickActiveToolSlot(slots: readonly T[] | undefined): T | undefined { + if (!slots) return undefined; + for (let index = slots.length - 1; index >= 0; index -= 1) { + if (slots[index]!.status === "running") return slots[index]; + } + return slots.find((slot) => slot.status === "pending"); +} diff --git a/renderer/shared/bot-live.ts b/renderer/shared/bot-live.ts index 7b293c51c3..f186c54656 100644 --- a/renderer/shared/bot-live.ts +++ b/renderer/shared/bot-live.ts @@ -7,6 +7,7 @@ // that sees a different epoch or a gap re-subscribes for a fresh snapshot. import type { BotSessionState } from "../../main/services/bot-runtime/bot-session-service.js"; +import type { BotActivityPhase, BotToolPhase } from "./bot-activity.js"; import type { ConnectCardEntry } from "./bot-connections.js"; import type { AskUserQuestionV1 } from "./ask-user-question.js"; import type { BotMemorySource, BotMemoryTarget } from "./bot-memory.js"; @@ -44,8 +45,23 @@ export function botQuestionAnswerText(details: unknown): string | undefined { export interface BotTranscriptToolCall { id: string; name: string; + /** The phase this call puts its Bot in (`botToolPhase`). */ + kind: BotToolPhase; + /** Past tense, for recaps: "Read 1 file", "Used Notion". */ + label: string; + /** A short, safe object of the action, built and redacted in main. */ + detail?: string; + /** The connection's display label, for connection tools. */ + app?: string; } +/** + * How a tool call ended. `blocked`: the Bot's access or the person refused it + * before it ran. `stopped`: the person stopped the reply, or the app restarted, + * while it ran; not a problem to report. + */ +export type BotToolResultStatus = "ok" | "failed" | "blocked" | "stopped"; + export type BotTranscriptEntry = | { id: string; @@ -77,6 +93,10 @@ export type BotTranscriptEntry = toolCallId: string; toolName: string; isError: boolean; + status: BotToolResultStatus; + /** From the answer that made the call to its result. */ + durationMs?: number; + at?: number; } | { id: string; @@ -162,6 +182,33 @@ export function botRetryableFailedTurn( return last?.type === "failed_turn" && last.retryText !== null ? last : null; } +/** The step behind the current phase, for the Mac's hover peek and Detailed steps. */ +export interface BotLiveActivityStep { + kind: BotToolPhase; + /** Present tense, the phase word: "Reading", "Using Notion". */ + label: string; + detail?: string; +} + +/** What a Bot in a running turn is doing now (spec §5). Null when no turn runs. */ +export interface BotLiveActivity { + phase: BotActivityPhase; + /** The connection's label, for `app`. */ + app?: string; + /** When the turn started, for elapsed time. */ + startedAt: number; + step?: BotLiveActivityStep; +} + +/** A message waiting for the running turn: a follow-up (queued) or a steer (joins at the next step). */ +export interface BotQueuedMessage { + /** The durable submission id; Remove withdraws it. */ + submissionId: string; + mode: "steer" | "followUp"; + text: string; + imageCount: number; +} + export interface BotLiveSnapshot { botId: string; epoch: string; @@ -172,6 +219,10 @@ export interface BotLiveSnapshot { state: BotSessionState; /** The question the Bot is waiting on, or null. */ question: BotPendingQuestion | null; + /** What the Bot is doing in the running turn, or null. */ + activity: BotLiveActivity | null; + /** Messages waiting for the running turn, oldest first. */ + queued: BotQueuedMessage[]; } export type BotLiveEventBody = @@ -179,6 +230,8 @@ export type BotLiveEventBody = | { type: "partial"; text: string | null } | { type: "state"; state: BotSessionState } | { type: "question"; question: BotPendingQuestion | null } + | { type: "activity"; activity: BotLiveActivity | null } + | { type: "queued"; queued: BotQueuedMessage[] } /** Replaces everything: after an overflow, a reopen, or a retroactive change. */ | { type: "snapshot"; snapshot: BotLiveSnapshot }; @@ -240,5 +293,9 @@ export function applyBotLiveEvent(snapshot: BotLiveSnapshot, event: BotLiveEvent return { ...snapshot, seq: event.seq, state: event.state }; case "question": return { ...snapshot, seq: event.seq, question: event.question }; + case "activity": + return { ...snapshot, seq: event.seq, activity: event.activity }; + case "queued": + return { ...snapshot, seq: event.seq, queued: event.queued }; } } diff --git a/renderer/shared/bots.ts b/renderer/shared/bots.ts index 9b42e578a4..b730d607f6 100644 --- a/renderer/shared/bots.ts +++ b/renderer/shared/bots.ts @@ -97,6 +97,35 @@ export const BOT_LIMITS = { instructionsChars: 32_000, } as const; +export const BOT_CHAT_ACTIVITY_LEVELS = ["quiet", "summary", "detailed"] as const; +export type BotChatActivityLevel = (typeof BOT_CHAT_ACTIVITY_LEVELS)[number]; +export const BOT_CHAT_ACTIVITY_WORDINGS = ["follows", "thinking"] as const; +export type BotChatActivityWording = (typeof BOT_CHAT_ACTIVITY_WORDINGS)[number]; + +/** How much a Bot chat shows while the Bot works, and what its status line says (spec §7). */ +export interface BotChatActivity { + level: BotChatActivityLevel; + wording: BotChatActivityWording; +} + +/** What an absent setting means; new Bots never store it. */ +const DEFAULT_BOT_CHAT_ACTIVITY: BotChatActivity = { level: "quiet", wording: "follows" }; + +/** Exact check: both keys, current values, nothing else. */ +export function parseBotChatActivity(value: unknown): BotChatActivity | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const record = value as Record; + const keys = Object.keys(record); + if (keys.length !== 2 || !keys.every((key) => key === "level" || key === "wording")) return undefined; + if (!includes(BOT_CHAT_ACTIVITY_LEVELS, record.level) || !includes(BOT_CHAT_ACTIVITY_WORDINGS, record.wording)) + return undefined; + return { level: record.level, wording: record.wording }; +} + +export function resolveBotChatActivity(value: BotChatActivity | undefined): BotChatActivity { + return value ? { level: value.level, wording: value.wording } : { ...DEFAULT_BOT_CHAT_ACTIVITY }; +} + export interface BotDefinition { id: string; /** Main-owned optimistic concurrency token for identity/archive mutations. */ @@ -106,6 +135,8 @@ export interface BotDefinition { /** The Bot's soul: person-authored personality and how it helps (Profile → Instructions). */ instructions: string; avatar: BotAvatar; + /** Absent: Quiet, Follows the work. */ + chatActivity?: BotChatActivity; createdAt: number; updatedAt: number; } @@ -126,6 +157,8 @@ export interface BotCreateInput { export interface BotUpdateInput extends BotCreateInput { id: string; expectedRevision: string; + /** Absent keeps the stored choice, so identity edits never reset it. */ + chatActivity?: BotChatActivity; } export interface TelegramBotBindingView { diff --git a/renderer/styles.css b/renderer/styles.css index b7c882c12f..c1ca138b4c 100644 --- a/renderer/styles.css +++ b/renderer/styles.css @@ -2975,6 +2975,20 @@ textarea { .aiden-mark[data-aiden-mark="bounce"] circle { animation: aiden-mark-bounce 1.2s cubic-bezier(.45, 0, .55, 1) infinite both; } @keyframes aiden-mark-bounce { 0%, 55%, 100% { transform: translateY(0); } 27% { transform: translateY(-5px); } } +/* Bot faces glance and blink while their Bot works (spec §6), reusing the glance + keyframes. Motion runs only with Reduce Motion off and on screen; off screen the + face pauses where it is. */ +:root[data-reduce-motion="false"] .bot-avatar[data-working] .bot-avatar-eyes { animation: aiden-mark-look 4s cubic-bezier(.5, 0, .3, 1) infinite; } +:root[data-reduce-motion="false"] .bot-avatar[data-working] .bot-avatar-eye { transform-box: fill-box; transform-origin: center; animation: aiden-mark-blink 4s ease-in-out infinite; } +.bot-avatar[data-offscreen] * { animation-play-state: paused !important; } +/* Under Reduce Motion a working face holds the glance's look-aside pose instead, + so it still reads as working without moving. */ +:root[data-reduce-motion="true"] .bot-avatar[data-working] .bot-avatar-eyes { transform: translateX(-2.6px); } +@media (prefers-reduced-motion: reduce) { + .bot-avatar[data-working] * { animation: none !important; } + .bot-avatar[data-working] .bot-avatar-eyes { transform: translateX(-2.6px); } +} + /* Helix family (Live). Position and depth run on the same period with depth a quarter behind (per-circle delays are inline), so the strands read as passing in front of each other. */ diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index b46d0d35c6..6cf9ef34be 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -418,6 +418,7 @@ "main/services/bot-runtime/bot-delete.test.ts", "main/services/bot-runtime/bot-starter.test.ts", "main/services/bot-runtime/live-projection.test.ts", + "main/services/bot-runtime/bot-activity-detail.test.ts", "main/services/bot-runtime/bot-extension.test.ts", "main/services/bot-runtime/bot-question-tool.test.ts", "main/services/bot-runtime/bot-session-service.test.ts", @@ -857,6 +858,9 @@ "renderer/main/bots/bots-home.test.tsx", "renderer/main/bots/bot-chat-pane.test.tsx", "renderer/main/bots/bot-transcript-rows.test.ts", + "renderer/main/bots/bot-status-line.test.tsx", + "renderer/main/bots/bot-activity-recap.test.tsx", + "renderer/main/bots/bot-chat-activity-page.test.tsx", "renderer/main/bots/bot-routines.test.tsx", "renderer/main/bots/bot-memory-page.test.tsx", "main/handlers/bot-live.test.ts", @@ -876,6 +880,7 @@ "renderer/shared/assistant.test.ts", "renderer/shared/attachment-contract.test.ts", "renderer/shared/bot-capabilities.test.ts", + "renderer/shared/bot-activity.test.ts", "renderer/shared/bot-routine-label.test.ts", "renderer/shared/btw.test.ts", "renderer/shared/chat-message-contract.test.ts", diff --git a/tests/e2e/bots-starter.spec.ts b/tests/e2e/bots-starter.spec.ts index bb0d032c60..85a125b3b5 100644 --- a/tests/e2e/bots-starter.spec.ts +++ b/tests/e2e/bots-starter.spec.ts @@ -33,7 +33,7 @@ test("an empty Bots list opens a starter Bot chat, sends to it, and answers its state.created = true; return { bot: fixture, created: true }; }); - ipcMain.handle("bots:live:subscribe", () => ({ ...idle, epoch: "e1", seq: 0, entries: [], partial: null, question: null })); + ipcMain.handle("bots:live:subscribe", () => ({ ...idle, epoch: "e1", seq: 0, entries: [], partial: null, question: null, activity: null, queued: [] })); ipcMain.handle("bots:live:summary", () => idle); ipcMain.handle("bots:getCanonicalPhoto", () => null); ipcMain.handle("bots:pendingApprovals", () => []); @@ -160,7 +160,7 @@ test("onboarding Start Chat creates the starter Bot and opens its chat when setu state.created += 1; return { bot: fixture, created: true }; }); - ipcMain.handle("bots:live:subscribe", () => ({ ...idle, epoch: "e1", seq: 0, entries: [], partial: null, question: null })); + ipcMain.handle("bots:live:subscribe", () => ({ ...idle, epoch: "e1", seq: 0, entries: [], partial: null, question: null, activity: null, queued: [] })); ipcMain.handle("bots:live:summary", () => idle); ipcMain.handle("bots:getCanonicalPhoto", () => null); ipcMain.handle("bots:pendingApprovals", () => []); @@ -193,3 +193,38 @@ test("onboarding Start Chat creates the starter Bot and opens its chat when setu await aiden.app.evaluate(() => (globalThis as unknown as { botOnboardingE2e: { created: number } }).botOnboardingE2e.created), ).toBe(1); }); + +// Under Reduce Motion the working face cannot glance, so it holds the glance's +// look-aside pose: still, and still different from an idle face. +test("under Reduce Motion a working Bot's face looks aside without moving, and an idle face looks ahead", async ({ aiden }) => { + const { page } = aiden; + const working = botFixture({ id: "bot-chief", name: "Chief of Staff" }); + const idle = botFixture({ id: "bot-owl", name: "Night Owl" }); + await finishLmStudioOnboarding(page); + await aiden.app.evaluate(({ ipcMain }, fixtures) => { + for (const channel of ["bots:list", "bots:live:summary", "bots:getCanonicalPhoto"]) ipcMain.removeHandler(channel); + ipcMain.handle("bots:list", () => fixtures); + ipcMain.handle("bots:live:summary", (_event, botId: string) => ({ + botId, + preview: null, + updatedAt: null, + state: botId === "bot-chief" ? { kind: "running", submissionId: "s-1" } : { kind: "idle" }, + })); + ipcMain.handle("bots:getCanonicalPhoto", () => null); + }, [working, idle]); + await page.emulateMedia({ reducedMotion: "reduce" }); + + await page.getByRole("button", { name: "Bots", exact: true }).click(); + const face = (name: string) => + page.getByRole("listitem").filter({ hasText: name }).locator(".bot-avatar-eyes").first(); + const pose = (name: string) => + face(name).evaluate((eyes) => ({ + transform: getComputedStyle(eyes).transform, + moving: eyes.getAnimations({ subtree: true }).length > 0, + })); + await expect(page.getByRole("listitem").filter({ hasText: "Chief of Staff" }).getByText("Working")).toBeAttached(); + + await expect.poll(async () => (await pose("Chief of Staff")).transform).not.toBe("none"); + expect(await pose("Chief of Staff")).toMatchObject({ moving: false }); + expect(await pose("Night Owl")).toEqual({ transform: "none", moving: false }); +}); diff --git a/tests/e2e/guided-setup.spec.ts b/tests/e2e/guided-setup.spec.ts index 3321a6f949..e7848e0232 100644 --- a/tests/e2e/guided-setup.spec.ts +++ b/tests/e2e/guided-setup.spec.ts @@ -111,7 +111,7 @@ async function substituteBotIpc(app: ElectronApplication, options: { failFirstCr state.accessUpdates.push(input); return { ...fixture.access.access, revision: "access-2", accessMode: "custom", custom: { providerId: "custom:lmstudio", modelId: "aiden-e2e-vision", fileScopeIds: [], shellEnabled: false, connectionIds: [], skillIds: [], otherCapabilityIds: [] } }; }); - ipcMain.handle("bots:live:subscribe", () => ({ ...fixture.idle, epoch: "e1", seq: 0, entries: [], partial: null })); + ipcMain.handle("bots:live:subscribe", () => ({ ...fixture.idle, epoch: "e1", seq: 0, entries: [], partial: null, activity: null, queued: [] })); ipcMain.handle("bots:live:summary", () => fixture.idle); ipcMain.handle("bots:getCanonicalPhoto", () => null); ipcMain.handle("bots:pendingApprovals", () => []);