From 2efdc57089235a9e3432f4af8b70dc76456f74dc Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 01:56:21 -0400 Subject: [PATCH 01/26] Plan: Bot chat activity slice B (status line and Chat activity) Co-Authored-By: Claude Opus 5.5 --- ...6-10-14-bot-chat-activity-b-status-line.md | 3965 +++++++++++++++++ 1 file changed, 3965 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-14-bot-chat-activity-b-status-line.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" +``` From ab74d94a76bbebbdb2051149bafd0f8347d9ff47 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 01:58:24 -0400 Subject: [PATCH 02/26] Bots: shared status words and tool phase classifier Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- renderer/shared/bot-activity.test.ts | 114 +++++++++++++ renderer/shared/bot-activity.ts | 243 +++++++++++++++++++++++++++ scripts/ci-test-registry.json | 1 + 4 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 renderer/shared/bot-activity.test.ts create mode 100644 renderer/shared/bot-activity.ts diff --git a/package.json b/package.json index 2e84d812a4..e75d6e2fa9 100644 --- a/package.json +++ b/package.json @@ -128,7 +128,7 @@ "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: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", "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: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", 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..ce64de49dd --- /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"; + +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"); +} diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index b46d0d35c6..69cc92e4de 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -876,6 +876,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", From 03eda735378bd9fd9071e0aff4793ac366748df5 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 02:03:30 -0400 Subject: [PATCH 03/26] Bots: tool steps carry kind, label, safe detail, and ok/failed/blocked status Co-Authored-By: Claude Opus 5.5 --- .../bot-runtime/bot-activity-detail.test.ts | 50 +++++++++++ .../bot-runtime/bot-activity-detail.ts | 78 +++++++++++++++++ .../bot-runtime/live-projection.test.ts | 85 ++++++++++++++++++- main/services/bot-runtime/live-projection.ts | 22 ++++- package.json | 2 +- renderer/main/bots/bot-chat-pane.test.tsx | 6 +- .../main/bots/bot-transcript-rows.test.ts | 4 +- renderer/shared/bot-live.ts | 16 ++++ scripts/ci-test-registry.json | 1 + 9 files changed, 256 insertions(+), 8 deletions(-) create mode 100644 main/services/bot-runtime/bot-activity-detail.test.ts create mode 100644 main/services/bot-runtime/bot-activity-detail.ts 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..a2bcb97a9a --- /dev/null +++ b/main/services/bot-runtime/bot-activity-detail.test.ts @@ -0,0 +1,50 @@ +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" }); +}); 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..f79e375d90 --- /dev/null +++ b/main/services/bot-runtime/bot-activity-detail.ts @@ -0,0 +1,78 @@ +// 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 } : {}), + }; +} diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 3dbc21a7a4..e892960224 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -20,7 +20,7 @@ import { 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"; @@ -341,6 +341,89 @@ 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" } }, + ], + }], + }, + 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] as const] : [])), + ); + 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(); + } +}); + 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, diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 8e20ec9a3f..1b2f7d24f8 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -33,6 +33,7 @@ import { type BotLiveEventBody, type BotLiveSnapshot, type BotLiveSummary, + type BotToolResultStatus, type BotTranscriptEntry, } from "../../../renderer/shared/bot-live.js"; import { parseProducedFile } from "../../../renderer/shared/produced-file.js"; @@ -47,6 +48,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 +176,14 @@ 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); 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"; +} + /** * 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 +213,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 +297,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 +344,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 +353,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, }); diff --git a/package.json b/package.json index e75d6e2fa9..d16956a518 100644 --- a/package.json +++ b/package.json @@ -129,7 +129,7 @@ "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 renderer/shared/bot-activity.test.ts", - "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: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/main/bots/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index 9505797ace..33b984b5e3 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -302,8 +302,8 @@ test("text before a tool call folds under Updates, and only the final answer is 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."), ], }), @@ -476,7 +476,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 () => { diff --git a/renderer/main/bots/bot-transcript-rows.test.ts b/renderer/main/bots/bot-transcript-rows.test.ts index 2489d81ff5..dcb3c0dc5d 100644 --- a/renderer/main/bots/bot-transcript-rows.test.ts +++ b/renderer/main/bots/bot-transcript-rows.test.ts @@ -8,11 +8,11 @@ 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 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); diff --git a/renderer/shared/bot-live.ts b/renderer/shared/bot-live.ts index 7b293c51c3..26992a81c2 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 { 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,19 @@ 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. */ +export type BotToolResultStatus = "ok" | "failed" | "blocked"; + export type BotTranscriptEntry = | { id: string; @@ -77,6 +89,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; diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index 69cc92e4de..fb909471ff 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", From 5f802f892fe24954cbe8866d49b51a49288d6010 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 02:08:19 -0400 Subject: [PATCH 04/26] Bots: command steps never show the command; stopped steps; stricter detail Co-Authored-By: Claude Opus 5.5 --- .../bot-runtime/bot-activity-detail.test.ts | 26 +++++++++++---- .../bot-runtime/bot-activity-detail.ts | 33 +++++++++++++------ .../bot-runtime/live-projection.test.ts | 26 ++++++++++++--- main/services/bot-runtime/live-projection.ts | 14 ++++++-- renderer/shared/bot-live.ts | 8 +++-- 5 files changed, 81 insertions(+), 26 deletions(-) diff --git a/main/services/bot-runtime/bot-activity-detail.test.ts b/main/services/bot-runtime/bot-activity-detail.test.ts index a2bcb97a9a..cc79915f7a 100644 --- a/main/services/bot-runtime/bot-activity-detail.test.ts +++ b/main/services/bot-runtime/bot-activity-detail.test.ts @@ -17,22 +17,36 @@ test("a file step names only the file's base name", () => { 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", () => { +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: "export OPENAI_API_KEY=sk-live1234567890abcdef && ls /Users/sam/Private", + command: "ls", + description: "Export OPENAI_API_KEY=sk-live1234567890abcdef then list /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 ?? ""; + 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("…")); - // 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("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", diff --git a/main/services/bot-runtime/bot-activity-detail.ts b/main/services/bot-runtime/bot-activity-detail.ts index f79e375d90..1d9ad9352a 100644 --- a/main/services/bot-runtime/bot-activity-detail.ts +++ b/main/services/bot-runtime/bot-activity-detail.ts @@ -1,9 +1,11 @@ // 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. +// 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, @@ -14,8 +16,14 @@ import { 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; +/** + * 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; @@ -41,11 +49,15 @@ function baseName(value: unknown): string | undefined { 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); + const stripped = value.replace(FORMAT_CHARACTERS, ""); + const points = [...stripped]; + const window = + points.length > RAW_DETAIL_CHARS ? points.slice(0, RAW_DETAIL_CHARS).join("").replace(/\s+\S*$/u, "") : stripped; + const clean = sanitizeDiagnosticText(window, 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()}…` + const shown = [...clean]; + return shown.length > BOT_STEP_DETAIL_CHARS + ? `${shown.slice(0, BOT_STEP_DETAIL_CHARS - 1).join("").trimEnd()}…` : clean; } @@ -57,7 +69,8 @@ function rawDetail(toolName: string, kind: BotToolPhase, args: Record 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); + // 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]] : [], @@ -381,16 +385,19 @@ test("tool calls carry a kind, a past-tense label and a short safe detail; resul ["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 refused is blocked, a tool that broke is failed, and neither looks like the other", async () => { +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" })], { + 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."), @@ -401,8 +408,15 @@ test("a tool the Bot's access refused is blocked, a tool that broke is failed, a 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." } : { allowed: true }), + 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", }), }, }); @@ -415,7 +429,9 @@ test("a tool the Bot's access refused is blocked, a tool that broke is failed, a ); 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); } diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 1b2f7d24f8..c3d4605745 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -176,12 +176,20 @@ 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); any other error failed. */ +/** + * `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 blocked = Array.isArray(diagnostics) && diagnostics.some((item) => (item as { code?: unknown } | null)?.code === "blocked"); - return blocked ? "blocked" : "failed"; + 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"; } /** diff --git a/renderer/shared/bot-live.ts b/renderer/shared/bot-live.ts index 26992a81c2..bd369b0ea0 100644 --- a/renderer/shared/bot-live.ts +++ b/renderer/shared/bot-live.ts @@ -55,8 +55,12 @@ export interface BotTranscriptToolCall { 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"; +/** + * 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 = | { From 6c70fdd5ef7409a1f9a7fad919838b37a592936e Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 02:13:56 -0400 Subject: [PATCH 05/26] Bots: project the live activity phase from pi.live, cards, Stop and Resume Also replaces the quadratic whitespace cut in bot step details with a linear scan. Co-Authored-By: Claude Opus 5.5 --- main/handlers/bot-live.test.ts | 4 + main/handlers/bots.ts | 14 +- .../bot-runtime/bot-activity-detail.test.ts | 11 ++ .../bot-runtime/bot-activity-detail.ts | 14 +- main/services/bot-runtime/bot-session-main.ts | 8 + .../bot-runtime/live-projection.test.ts | 148 +++++++++++++- main/services/bot-runtime/live-projection.ts | 183 +++++++++++++++++- renderer/main/bots/bot-chat-pane.test.tsx | 1 + renderer/shared/bot-live.ts | 25 ++- 9 files changed, 393 insertions(+), 15 deletions(-) diff --git a/main/handlers/bot-live.test.ts b/main/handlers/bot-live.test.ts index 88bac8e2ed..b1ce0d0440 100644 --- a/main/handlers/bot-live.test.ts +++ b/main/handlers/bot-live.test.ts @@ -39,12 +39,16 @@ function fakeProjection() { partial: null, state: { kind: "idle" }, question: null, + activity: null, }; return { snapshot, unsubscribe: () => sinks.delete(id) }; }, notifyState: () => undefined, refresh: async () => undefined, refreshQuestion: async () => undefined, + notifyStopping: () => undefined, + notifyResuming: () => undefined, + refreshActivity: async () => undefined, summary: async (botId) => ({ botId, preview: "hi", updatedAt: 1, state: { kind: "idle" } }), close: async () => undefined, }; diff --git a/main/handlers/bots.ts b/main/handlers/bots.ts index d14f64de85..b2cd723a3e 100644 --- a/main/handlers/bots.ts +++ b/main/handlers/bots.ts @@ -196,15 +196,21 @@ export function registerBotHandlers(): void { }); ipcMain.handle("bots:resume", async (_event, input: unknown) => { const { botId, requestId } = parseBotSessionAction(input, "resume"); - return (await botSessionRuntime()).resume(botId, requestId); + botLiveProjection().notifyResuming(botId); + const state = await (await botSessionRuntime()).resume(botId, requestId); + // A Resume that did not start a run must not leave its mark on the next turn. + if (state.kind !== "running") botLiveProjection().notifyState(botId, state); + return state; }); ipcMain.handle("bots:dismiss", async (_event, input: unknown) => { 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:stop", async (_event, id: unknown) => { + const botId = parseBotId(id); + botLiveProjection().notifyStopping(botId); + return (await botSessionRuntime()).stop(botId); + }); 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/bot-runtime/bot-activity-detail.test.ts b/main/services/bot-runtime/bot-activity-detail.test.ts index cc79915f7a..c1e37d4ccb 100644 --- a/main/services/bot-runtime/bot-activity-detail.test.ts +++ b/main/services/bot-runtime/bot-activity-detail.test.ts @@ -62,3 +62,14 @@ test("a search step shows its query; a connection step names the app and shows n 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 < 50, `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 index 1d9ad9352a..32d636d7a8 100644 --- a/main/services/bot-runtime/bot-activity-detail.ts +++ b/main/services/bot-runtime/bot-activity-detail.ts @@ -47,12 +47,24 @@ function baseName(value: unknown): string | undefined { 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 ? points.slice(0, RAW_DETAIL_CHARS).join("").replace(/\s+\S*$/u, "") : stripped; + 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]; diff --git a/main/services/bot-runtime/bot-session-main.ts b/main/services/bot-runtime/bot-session-main.ts index 2bb73e8ceb..745543c1e7 100644 --- a/main/services/bot-runtime/bot-session-main.ts +++ b/main/services/bot-runtime/bot-session-main.ts @@ -326,12 +326,20 @@ 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), 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), diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index dc2997cc97..3e4f76a42a 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -4,7 +4,7 @@ import * as os from "node:os"; import * as path from "node:path"; import { after, test } from "node:test"; import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; -import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai/providers/faux"; +import { fauxAssistantMessage, fauxText, fauxThinking, fauxToolCall } from "@earendil-works/pi-ai/providers/faux"; import { applyBotLiveEvent, botRetryableFailedTurn, @@ -15,6 +15,7 @@ import { createBotSessionService, type BotSessionRuntime, type BotSessionService import { BOT_CONNECT_CARD_ENTRY_KIND, createBotLiveProjection, + liveBotActivity, projectBotTranscript, type BotLiveProjection, type BotLiveProjectionDeps, @@ -113,6 +114,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 +158,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(); @@ -528,9 +553,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"); @@ -669,3 +698,120 @@ test("a waiting question reaches subscribers and late joiners, and its answer re 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(); + } +}); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index c3d4605745..bd4fd284d9 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -28,6 +28,7 @@ import { botFailedTurnId, botQuestionAnswerText, botTranscriptPreview, + type BotLiveActivity, type BotLiveEvent, type BotPendingQuestion, type BotLiveEventBody, @@ -36,6 +37,7 @@ import { 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, @@ -410,6 +412,77 @@ function liveRunActive(docs: Readonly>): boolean { 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"); +} + /* ------------------------------------------------------------------------- */ /* Feeds and subscribers */ /* ------------------------------------------------------------------------- */ @@ -423,6 +496,10 @@ export interface BotLiveProjectionDeps { state(botId: string): Promise; /** The question the Bot is waiting on right now, if any. */ question?(botId: string): BotPendingQuestion | null; + /** 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. */ @@ -447,6 +524,12 @@ 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 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; /** Preview, time and state for a list row. */ summary(botId: string): Promise; /** Stop every feed (the Bot was deleted, or the app is quitting). */ @@ -469,6 +552,13 @@ interface Feed { partial: string | null; state: BotSessionState; question: BotPendingQuestion | null; + 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> }; runActive: boolean; watch: ConversationWatch; cancel: () => void; @@ -485,6 +575,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>(); @@ -502,6 +595,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro partial: feed.partial, state: feed.state, question: feed.question, + activity: feed.activity, }; } @@ -561,6 +655,38 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro for (const subscriber of subscribers.get(feed.botId) ?? []) enqueue(subscriber, feed.botId, event); } + 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); + } + async function resolveCards(botId: string, entries: BotTranscriptEntry[]): Promise { if (!deps.connectCardStatus) return entries; const resolved: BotTranscriptEntry[] = []; @@ -591,6 +717,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro 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) { @@ -598,21 +725,32 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro emit(feed, { type: "partial", text: partial }); } 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) { + 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 { @@ -639,12 +777,19 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro partial: livePartialText(initial.docs), state: await deps.state(botId), question: deps.question?.(botId) ?? null, + activity: null, + startedAt: now(), + stopping: false, + resuming: false, + frame: { entries: initial.entries, docs: initial.docs }, runActive: liveRunActive(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); feeds.set(botId, feed); watch.start((value) => enqueueWork(feed, () => onFrame(feed, value.entries, value.docs))); void watch.closed.then(() => { @@ -701,6 +846,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro if (question?.waitId === feed.question?.waitId) return; feed.question = question; emit(feed, { type: "question", question }); + updateActivity(feed); }); } @@ -729,6 +875,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)); @@ -742,6 +889,26 @@ 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); + }, + + 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/renderer/main/bots/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index 33b984b5e3..e40647aa04 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -20,6 +20,7 @@ function snapshot(overrides: Partial = {}): BotLiveSnapshot { partial: null, state: { kind: "idle" }, question: null, + activity: null, ...overrides, }; } diff --git a/renderer/shared/bot-live.ts b/renderer/shared/bot-live.ts index bd369b0ea0..87c441feb4 100644 --- a/renderer/shared/bot-live.ts +++ b/renderer/shared/bot-live.ts @@ -7,7 +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 { BotToolPhase } from "./bot-activity.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"; @@ -182,6 +182,24 @@ 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; +} + export interface BotLiveSnapshot { botId: string; epoch: string; @@ -192,6 +210,8 @@ 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; } export type BotLiveEventBody = @@ -199,6 +219,7 @@ export type BotLiveEventBody = | { type: "partial"; text: string | null } | { type: "state"; state: BotSessionState } | { type: "question"; question: BotPendingQuestion | null } + | { type: "activity"; activity: BotLiveActivity | null } /** Replaces everything: after an overflow, a reopen, or a retroactive change. */ | { type: "snapshot"; snapshot: BotLiveSnapshot }; @@ -260,5 +281,7 @@ 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 }; } } From 69c06dab2e9b902e4304c65412e9ac3eb0bd8e81 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 02:27:09 -0400 Subject: [PATCH 06/26] Bots: run-scoped Stop/Resume flags; renew startedAt for follow-up turns Co-Authored-By: Claude Opus 5.5 --- main/handlers/bot-live.test.ts | 4 +- main/handlers/bots.ts | 22 +++-- .../bot-runtime/bot-activity-detail.test.ts | 2 +- .../bot-runtime/live-projection.test.ts | 91 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 57 ++++++++++-- 5 files changed, 161 insertions(+), 15 deletions(-) diff --git a/main/handlers/bot-live.test.ts b/main/handlers/bot-live.test.ts index b1ce0d0440..fbc37f72c6 100644 --- a/main/handlers/bot-live.test.ts +++ b/main/handlers/bot-live.test.ts @@ -47,7 +47,9 @@ function fakeProjection() { refresh: async () => undefined, refreshQuestion: async () => undefined, notifyStopping: () => undefined, - notifyResuming: () => undefined, + notifyResuming: async () => undefined, + cancelResuming: () => 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/bots.ts b/main/handlers/bots.ts index b2cd723a3e..32f87d0fec 100644 --- a/main/handlers/bots.ts +++ b/main/handlers/bots.ts @@ -196,11 +196,16 @@ export function registerBotHandlers(): void { }); ipcMain.handle("bots:resume", async (_event, input: unknown) => { const { botId, requestId } = parseBotSessionAction(input, "resume"); - botLiveProjection().notifyResuming(botId); - const state = await (await botSessionRuntime()).resume(botId, requestId); - // A Resume that did not start a run must not leave its mark on the next turn. - if (state.kind !== "running") botLiveProjection().notifyState(botId, state); - return state; + await botLiveProjection().notifyResuming(botId); + try { + const state = await (await botSessionRuntime()).resume(botId, requestId); + // A Resume that did not start a run must not leave its mark on the next turn. + if (state.kind !== "running") botLiveProjection().cancelResuming(botId); + return state; + } catch (error) { + botLiveProjection().cancelResuming(botId); + throw error; + } }); ipcMain.handle("bots:dismiss", async (_event, input: unknown) => { const { botId, requestId } = parseBotSessionAction(input, "dismiss"); @@ -209,7 +214,12 @@ export function registerBotHandlers(): void { ipcMain.handle("bots:stop", async (_event, id: unknown) => { const botId = parseBotId(id); botLiveProjection().notifyStopping(botId); - return (await botSessionRuntime()).stop(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); diff --git a/main/services/bot-runtime/bot-activity-detail.test.ts b/main/services/bot-runtime/bot-activity-detail.test.ts index c1e37d4ccb..cf79cd4f39 100644 --- a/main/services/bot-runtime/bot-activity-detail.test.ts +++ b/main/services/bot-runtime/bot-activity-detail.test.ts @@ -68,7 +68,7 @@ test("an argument of thousands of spaces is cut without stalling the main proces 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 < 50, `took ${elapsed.toFixed(0)} ms`); + 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/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 3e4f76a42a..8dc041eaec 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -815,3 +815,94 @@ test("Stop pressed while nothing runs is ignored, so the next reply never starts 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 that never started a run does not mark the next turn, and one that did marks only its own", async () => { + const fauxModels = createFauxModels( + [fauxAssistantMessage("word ".repeat(30)), fauxAssistantMessage("word ".repeat(30)), fauxAssistantMessage("word ".repeat(30))], + { tokensPerSecond: 40 }, + ); + let interrupted = false; + const holder: { live?: Harness } = {}; + const live = await start(fauxModels, { + projection: { + state: async (botId) => (interrupted ? { kind: "interrupted", submissionId: "earlier" } : holder.live!.service.state(botId)), + }, + }); + holder.live = live; + 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" }); + }; + + // A Resume while the Bot is not interrupted (stale button, second window) is refused. + await live.projection.notifyResuming("bot:a"); + await reply("first", "desk-1"); + assert.equal(observedPhases(tape.events).includes("resuming"), false); + + // A Resume that failed before any run began is forgotten. + interrupted = true; + await live.projection.notifyResuming("bot:a"); + interrupted = false; + live.projection.cancelResuming("bot:a"); + const before = tape.events.length; + await reply("second", "desk-2"); + assert.equal(observedPhases(tape.events.slice(before)).includes("resuming"), false); + + // A Resume that did start the run reads "resuming" for that run only. + interrupted = true; + await live.projection.notifyResuming("bot:a"); + interrupted = false; + const resumedFrom = tape.events.length; + await reply("third", "desk-3"); + assert.ok(observedPhases(tape.events.slice(resumedFrom)).includes("resuming")); + 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(); + } +}); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index bd4fd284d9..4b20404419 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -407,6 +407,15 @@ export function livePartialText(docs: Readonly>): string return text; } +/** The run's identity, or null when none: a queued follow-up starts a new run while `pi.live.run` stays present. */ +function liveRunKey(docs: Readonly>): string | null { + const live = docs["pi.live"] as { run?: { taskId?: unknown; inputs?: unknown } } | undefined; + const run = live?.run; + if (run === undefined) return null; + const inputs = Array.isArray(run.inputs) ? run.inputs : []; + return `${String(run.taskId)}:${String(inputs[0])}`; +} + function liveRunActive(docs: Readonly>): boolean { const live = docs["pi.live"] as { run?: unknown } | undefined; return live?.run !== undefined; @@ -526,8 +535,15 @@ export interface BotLiveProjection { 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 next run starts from Resume: it reads "Picking up where it left off" until it moves on. */ - notifyResuming(botId: string): void; + /** + * The next run starts from Resume: it reads "Picking up where it left off" until it moves on. + * Honoured only while the Bot is interrupted; resolves once the flag is set or refused. + */ + notifyResuming(botId: string): Promise; + /** The Resume did not start a run (it failed or was refused): forget it. */ + cancelResuming(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. */ @@ -560,6 +576,8 @@ interface Feed { /** 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; @@ -655,8 +673,8 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro for (const subscriber of subscribers.get(feed.botId) ?? []) enqueue(subscriber, feed.botId, event); } - function waitingOn(botId: string): boolean { - return (deps.question?.(botId) ?? null) !== null || deps.approvalPending?.(botId) === true; + 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. */ @@ -665,7 +683,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro return ( liveBotActivity({ ...feed.frame, - waiting: waitingOn(feed.botId), + waiting: waitingOn(feed), stopping: feed.stopping, resuming: feed.resuming, startedAt: feed.startedAt, @@ -681,6 +699,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro 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; @@ -718,6 +737,12 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro 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) { @@ -735,6 +760,9 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro 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); } @@ -783,6 +811,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro 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, @@ -899,8 +928,22 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro }); }, - notifyResuming(botId) { - resumingBots.add(botId); + async notifyResuming(botId) { + const state = await deps.state(botId).catch(() => null); + if (state?.kind === "interrupted") resumingBots.add(botId); + }, + + cancelResuming(botId) { + resumingBots.delete(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) { From 85a21f3b401417d67ffafdfc1fe900b494e6d7de Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 02:40:40 -0400 Subject: [PATCH 07/26] Bots: key a turn on its first input, not the generation task Co-Authored-By: Claude Opus 5.5 --- main/handlers/bot-live.test.ts | 3 +- main/handlers/bots.ts | 11 +-- main/services/bot-runtime/bot-session-main.ts | 1 + .../bot-runtime/bot-session-service.test.ts | 32 ++++++++ .../bot-runtime/bot-session-service.ts | 3 + .../bot-runtime/live-projection.test.ts | 81 ++++++++++++------- main/services/bot-runtime/live-projection.ts | 31 ++++--- 7 files changed, 103 insertions(+), 59 deletions(-) diff --git a/main/handlers/bot-live.test.ts b/main/handlers/bot-live.test.ts index fbc37f72c6..8a0f7179d2 100644 --- a/main/handlers/bot-live.test.ts +++ b/main/handlers/bot-live.test.ts @@ -47,8 +47,7 @@ function fakeProjection() { refresh: async () => undefined, refreshQuestion: async () => undefined, notifyStopping: () => undefined, - notifyResuming: async () => undefined, - cancelResuming: () => undefined, + notifyResuming: () => undefined, cancelStopping: () => undefined, refreshActivity: async () => undefined, summary: async (botId) => ({ botId, preview: "hi", updatedAt: 1, state: { kind: "idle" } }), diff --git a/main/handlers/bots.ts b/main/handlers/bots.ts index 32f87d0fec..e29b67dc45 100644 --- a/main/handlers/bots.ts +++ b/main/handlers/bots.ts @@ -196,16 +196,7 @@ export function registerBotHandlers(): void { }); ipcMain.handle("bots:resume", async (_event, input: unknown) => { const { botId, requestId } = parseBotSessionAction(input, "resume"); - await botLiveProjection().notifyResuming(botId); - try { - const state = await (await botSessionRuntime()).resume(botId, requestId); - // A Resume that did not start a run must not leave its mark on the next turn. - if (state.kind !== "running") botLiveProjection().cancelResuming(botId); - return state; - } catch (error) { - botLiveProjection().cancelResuming(botId); - throw error; - } + return (await botSessionRuntime()).resume(botId, requestId); }); ipcMain.handle("bots:dismiss", async (_event, input: unknown) => { const { botId, requestId } = parseBotSessionAction(input, "dismiss"); diff --git a/main/services/bot-runtime/bot-session-main.ts b/main/services/bot-runtime/bot-session-main.ts index 745543c1e7..d1458874eb 100644 --- a/main/services/bot-runtime/bot-session-main.ts +++ b/main/services/bot-runtime/bot-session-main.ts @@ -382,6 +382,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..09e12a6e11 100644 --- a/main/services/bot-runtime/bot-session-service.ts +++ b/main/services/bot-runtime/bot-session-service.ts @@ -202,6 +202,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; } @@ -472,6 +474,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))); }); diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index 8dc041eaec..dd06afb662 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -830,19 +830,12 @@ function observedTurns(events: readonly BotLiveEvent[]): Array<{ startedAt: numb return seen; } -test("a Resume that never started a run does not mark the next turn, and one that did marks only its own", async () => { +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)), fauxAssistantMessage("word ".repeat(30))], + [fauxAssistantMessage("word ".repeat(30)), fauxAssistantMessage("word ".repeat(30))], { tokensPerSecond: 40 }, ); - let interrupted = false; - const holder: { live?: Harness } = {}; - const live = await start(fauxModels, { - projection: { - state: async (botId) => (interrupted ? { kind: "interrupted", submissionId: "earlier" } : holder.live!.service.state(botId)), - }, - }); - holder.live = live; + const live = await start(fauxModels); try { const tape = recorder(); const { snapshot, unsubscribe } = await live.projection.subscribe("bot:a", tape.sink); @@ -852,28 +845,54 @@ test("a Resume that never started a run does not mark the next turn, and one tha 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(); + } +}); - // A Resume while the Bot is not interrupted (stale button, second window) is refused. - await live.projection.notifyResuming("bot:a"); - await reply("first", "desk-1"); - assert.equal(observedPhases(tape.events).includes("resuming"), false); - - // A Resume that failed before any run began is forgotten. - interrupted = true; - await live.projection.notifyResuming("bot:a"); - interrupted = false; - live.projection.cancelResuming("bot:a"); - const before = tape.events.length; - await reply("second", "desk-2"); - assert.equal(observedPhases(tape.events.slice(before)).includes("resuming"), false); - - // A Resume that did start the run reads "resuming" for that run only. - interrupted = true; - await live.projection.notifyResuming("bot:a"); - interrupted = false; - const resumedFrom = tape.events.length; - await reply("third", "desk-3"); - assert.ok(observedPhases(tape.events.slice(resumedFrom)).includes("resuming")); +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(); diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index 4b20404419..867bc7b045 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -407,13 +407,18 @@ export function livePartialText(docs: Readonly>): string return text; } -/** The run's identity, or null when none: a queued follow-up starts a new run while `pi.live.run` stays present. */ +/** + * 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?: { taskId?: unknown; inputs?: unknown } } | undefined; + const live = docs["pi.live"] as { run?: { inputs?: unknown } } | undefined; const run = live?.run; if (run === undefined) return null; - const inputs = Array.isArray(run.inputs) ? run.inputs : []; - return `${String(run.taskId)}:${String(inputs[0])}`; + const first = Array.isArray(run.inputs) ? run.inputs[0] : undefined; + return String(first); } function liveRunActive(docs: Readonly>): boolean { @@ -536,12 +541,11 @@ export interface BotLiveProjection { /** 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. - * Honoured only while the Bot is interrupted; resolves once the flag is set or refused. + * 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): Promise; - /** The Resume did not start a run (it failed or was refused): forget it. */ - cancelResuming(botId: string): void; + 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. */ @@ -928,13 +932,8 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro }); }, - async notifyResuming(botId) { - const state = await deps.state(botId).catch(() => null); - if (state?.kind === "interrupted") resumingBots.add(botId); - }, - - cancelResuming(botId) { - resumingBots.delete(botId); + notifyResuming(botId) { + resumingBots.add(botId); }, cancelStopping(botId) { From e354e48d8cfca3ad30d37b88c1783569065dc492 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 03:10:27 -0400 Subject: [PATCH 08/26] Bots: store a per-Bot chat activity choice, kept across identity edits Co-Authored-By: Claude Opus 5.5 --- main/handlers/bot-params.test.ts | 22 +++++++ main/handlers/bot-params.ts | 6 +- main/services/aiden-remote-bots.test.ts | 10 +++ main/services/bot-store-core.test.ts | 81 ++++++++++++++++++++++++- main/services/bot-store-core.ts | 8 +++ renderer/main/bots/bot-identity.ts | 4 +- renderer/shared/bot-activity.ts | 4 +- renderer/shared/bots.ts | 33 ++++++++++ 8 files changed, 163 insertions(+), 5 deletions(-) diff --git a/main/handlers/bot-params.test.ts b/main/handlers/bot-params.test.ts index 5b9396beb8..c9ee745566 100644 --- a/main/handlers/bot-params.test.ts +++ b/main/handlers/bot-params.test.ts @@ -188,3 +188,25 @@ 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); +}); diff --git a/main/handlers/bot-params.ts b/main/handlers/bot-params.ts index 9876057c4b..487000f0f2 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 } : {}), }; } 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-store-core.test.ts b/main/services/bot-store-core.test.ts index b03ffdcd00..e2a5e5254f 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,82 @@ 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 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/renderer/main/bots/bot-identity.ts b/renderer/main/bots/bot-identity.ts index b5fdc05321..bbde999b63 100644 --- a/renderer/main/bots/bot-identity.ts +++ b/renderer/main/bots/bot-identity.ts @@ -1,13 +1,14 @@ import type { QueryClient } from "@tanstack/react-query"; import { botsApi } from "../../lib/ipc"; import { queryKeys } from "../../lib/queries"; -import type { BotAvatar, BotDefinition } from "../../shared/bots"; +import type { BotAvatar, BotChatActivity, BotDefinition } from "../../shared/bots"; export type BotIdentityPatch = Partial<{ name: string; description: string; instructions: string; avatar: BotAvatar; + chatActivity: BotChatActivity; }>; /** @@ -30,6 +31,7 @@ export async function updateBotIdentity( ...(description ? { description } : {}), instructions: next.instructions, avatar: next.avatar, + ...(patch.chatActivity ? { chatActivity: patch.chatActivity } : {}), }); qc.setQueryData(queryKeys.bot(saved.id), saved); await qc.invalidateQueries({ queryKey: queryKeys.bots }); diff --git a/renderer/shared/bot-activity.ts b/renderer/shared/bot-activity.ts index ce64de49dd..33dbd059c7 100644 --- a/renderer/shared/bot-activity.ts +++ b/renderer/shared/bot-activity.ts @@ -4,6 +4,7 @@ // 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", @@ -45,8 +46,7 @@ export type BotToolPhase = Extract< | "waiting" >; -/** What the status line says: the work, or always "Thinking". */ -export type BotChatActivityWording = "follows" | "thinking"; +export type { BotChatActivityWording } from "./bots.js"; const PHASES: Record = { preparing: { word: "Getting ready", mark: "bounce" }, diff --git a/renderer/shared/bots.ts b/renderer/shared/bots.ts index 9b42e578a4..e62bc7ef50 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. */ +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 }; +} + 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 { From 70cf2370be99cf68025838b0d908c4b018fa6ac1 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 03:13:09 -0400 Subject: [PATCH 09/26] Bots: pin save/reload revision equality for chat activity Co-Authored-By: Claude Opus 5.5 --- main/services/bot-store-core.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/main/services/bot-store-core.test.ts b/main/services/bot-store-core.test.ts index e2a5e5254f..57bcbca975 100644 --- a/main/services/bot-store-core.test.ts +++ b/main/services/bot-store-core.test.ts @@ -322,6 +322,8 @@ test("a Bot's chat activity is saved with a new revision, and identity edits tha }); 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, From bd8bf9f0fdf551ffe08f2e36540d2bb3533202f6 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 03:22:58 -0400 Subject: [PATCH 10/26] Bots: one calm status line while a Bot works Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- renderer/main/bots/bot-chat-pane.test.tsx | 44 ++++++++- renderer/main/bots/bot-chat-pane.tsx | 9 ++ renderer/main/bots/bot-status-line.test.tsx | 48 ++++++++++ renderer/main/bots/bot-status-line.tsx | 98 +++++++++++++++++++++ scripts/ci-test-registry.json | 1 + 6 files changed, 198 insertions(+), 4 deletions(-) create mode 100644 renderer/main/bots/bot-status-line.test.tsx create mode 100644 renderer/main/bots/bot-status-line.tsx diff --git a/package.json b/package.json index d16956a518..d066b9f399 100644 --- a/package.json +++ b/package.json @@ -128,7 +128,7 @@ "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 renderer/shared/bot-activity.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", "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", diff --git a/renderer/main/bots/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index e40647aa04..7382bda566 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -393,13 +393,51 @@ 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 })); + 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, true)); + assert.equal(screen.queryByText("Writing") === null, true, "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" })); }); test("a deleted Bot's chat says it was not found instead of loading forever", async () => { diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index bf80fd9dfe..2b2bf47a36 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -20,6 +20,7 @@ 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 } 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"; @@ -30,6 +31,7 @@ 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 { BotStatusLine } from "./bot-status-line"; import { BotFilesDialog } from "./bot-files-dialog"; import { BotMessageActions, botReplyQuote } from "./bot-message-actions"; import { botTranscriptRows } from "./bot-transcript-rows"; @@ -468,6 +470,7 @@ export function BotChatPane({ botId }: { botId: string }) { state?.kind, approvals.prompts.length, snapshot?.question?.waitId, + snapshot?.activity?.phase, ]} showScrollToBottomButton streaming={running} @@ -533,6 +536,9 @@ 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). + const replyStreaming = running && (snapshot.partial?.trim().length ?? 0) > 0; const send = async ( text: string, @@ -725,6 +731,9 @@ export function BotChatPane({ botId }: { botId: string }) { onRespondToProposal={respondToProposal} /> + {snapshot.activity && !replyStreaming ? ( + + ) : null} {state?.kind === "interrupted" ? ( { + 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, 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.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, 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.")); +}); diff --git a/renderer/main/bots/bot-status-line.tsx b/renderer/main/bots/bot-status-line.tsx new file mode 100644 index 0000000000..4098046265 --- /dev/null +++ b/renderer/main/bots/bot-status-line.tsx @@ -0,0 +1,98 @@ +// 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} +
+ ); +} diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index fb909471ff..eaca7a00a0 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -858,6 +858,7 @@ "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-routines.test.tsx", "renderer/main/bots/bot-memory-page.test.tsx", "main/handlers/bot-live.test.ts", From 5bdb77b2cf23eb5edc5b6734e211d5aa239e62bd Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 03:29:46 -0400 Subject: [PATCH 11/26] Bots: status line announces through text; stays visible during tools Co-Authored-By: Claude Opus 5.5 --- renderer/main/bots/bot-chat-pane.test.tsx | 25 +++++++-- renderer/main/bots/bot-chat-pane.tsx | 19 +++++-- renderer/main/bots/bot-status-line.test.tsx | 60 ++++++++++++++++++--- renderer/main/bots/bot-status-line.tsx | 34 +++++++++--- 4 files changed, 117 insertions(+), 21 deletions(-) diff --git a/renderer/main/bots/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index 7382bda566..2103f125ec 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -35,6 +35,12 @@ const COLOUR_QUESTION = { ], }; +/** What a screen reader is told by the status line, or null while it is not shown. */ +function announced(): string | null { + const line = screen.queryAllByRole("status").find((node) => node.querySelector("[data-bot-status-announcement]")); + return line?.querySelector("[data-bot-status-announcement]")?.textContent ?? null; +} + function userEntry(id: string, text: string): BotTranscriptEntry { return { id, type: "user", text, imageCount: 0 }; } @@ -403,7 +409,7 @@ test("a just-sent message shows the status line before any reply text arrives", }), }); assert.ok(await screen.findByText("Plan Lisbon")); - assert.ok(await screen.findByRole("status", { name: "Getting ready" })); + await waitFor(() => assert.equal(announced(), "Getting ready")); }); test("the status line follows live activity, and hides while the reply's words stream", async () => { @@ -415,7 +421,7 @@ test("the status line follows live activity, and hides while the reply's words s activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "groceries.md" } }, }), }); - assert.ok(await screen.findByRole("status", { name: "Reading, groceries.md" })); + await waitFor(() => assert.equal(announced(), "Reading, groceries.md")); emitBotTestNotification("bots:live:event", { botId: "bot-1", epoch: "epoch-1", @@ -437,7 +443,20 @@ test("a Bot set to Always Thinking says Thinking while it reads", async () => { activity: { phase: "reading", startedAt: Date.now(), step: { kind: "reading", label: "Reading", detail: "groceries.md" } }, }), }); - assert.ok(await screen.findByRole("status", { name: "Thinking" })); + 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 () => { diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index 2b2bf47a36..86c82cdcb1 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -418,6 +418,7 @@ export function BotChatPane({ botId }: { botId: string }) { const [files, setFiles] = React.useState<{ open: boolean; path: string | null }>({ open: false, path: null }); const [retrying, setRetrying] = React.useState(false); 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; @@ -471,6 +472,7 @@ export function BotChatPane({ botId }: { botId: string }) { approvals.prompts.length, snapshot?.question?.waitId, snapshot?.activity?.phase, + statusLayout, ]} showScrollToBottomButton streaming={running} @@ -537,8 +539,14 @@ 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). - const replyStreaming = running && (snapshot.partial?.trim().length ?? 0) > 0; + // 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 send = async ( text: string, @@ -732,7 +740,12 @@ export function BotChatPane({ botId }: { botId: string }) { /> {snapshot.activity && !replyStreaming ? ( - + ) : null} {state?.kind === "interrupted" ? ( { + mock.timers.reset(); + cleanup(); +}); const reading: BotLiveActivity = { phase: "reading", @@ -13,21 +16,26 @@ const reading: BotLiveActivity = { step: { kind: "reading", label: "Reading", detail: "grocery-list.md" }, }; +/** What a screen reader is told: the status region's announcement text. */ +function announced(): string | null { + return screen.getByRole("status").querySelector("[data-bot-status-announcement]")?.textContent ?? null; +} + 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" })); + assert.equal(announced(), "Reading, grocery-list.md"); cleanup(); render(); - assert.ok(screen.getByRole("status", { name: "Thinking" })); + assert.equal(announced(), "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.ok(screen.getByRole("status", { name: "Waiting for you" })); + assert.equal(announced(), "Waiting for you"); cleanup(); render(); - assert.ok(screen.getByRole("status", { name: "Working" })); + assert.equal(announced(), "Working"); }); test("after 20 seconds the line shows elapsed time and Stop; after 2 minutes, a still-going note", () => { @@ -46,3 +54,41 @@ test("after 20 seconds the line shows elapsed time and Stop; after 2 minutes, a 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(announced(), "Stopping"); + assert.equal(screen.queryByRole("button", { name: "Stop" }) === null, true, "already stopping"); +}); + +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 searching: BotLiveActivity = { phase: "searching", startedAt: 0 }; + const writing: BotLiveActivity = { phase: "writing", startedAt: 0 }; + 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"); +}); diff --git a/renderer/main/bots/bot-status-line.tsx b/renderer/main/bots/bot-status-line.tsx index 4098046265..285d5bfc79 100644 --- a/renderer/main/bots/bot-status-line.tsx +++ b/renderer/main/bots/bot-status-line.tsx @@ -27,15 +27,21 @@ function useClock(fixed: number | undefined): number { return fixed ?? now; } -/** The text screen readers hear: the newest wording, at most once per gap. */ +/** + * 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. + */ function useAnnouncement(text: string): string { const [shown, setShown] = React.useState(() => ({ text, at: Date.now() })); - React.useEffect(() => { + if (shown.text !== text) { 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); + } + React.useEffect(() => { + if (shown.text === text) return; + const wait = nextBotAnnouncement(shown, text, Date.now()).retryInMs ?? 0; + const timer = setTimeout(() => setShown({ text, at: Date.now() }), wait); + return () => clearTimeout(timer); }, [text, shown]); return shown.text; } @@ -45,6 +51,7 @@ export function BotStatusLine({ wording, now: fixedNow, onStop, + onLayoutChange, }: { activity: BotLiveActivity; wording: BotChatActivityWording; @@ -52,6 +59,8 @@ export function BotStatusLine({ 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 = botActivityDisplay(activity.phase, wording, activity.app); const now = useClock(fixedNow); @@ -59,18 +68,27 @@ export function BotStatusLine({ 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 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 (
+ {/* Live regions announce text changes, so the throttled wording lives here as text. */} + + {announced} +
- {elapsed && onStop ? ( + {stoppable ? ( + {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..5052a8ad14 --- /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. */ +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; +} + +/** 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-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index 2103f125ec..0e6c0a4373 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -581,6 +581,37 @@ test("all tool rounds before an answer fold into one Updates line", async () => assert.ok(await screen.findByText(/Searching airlines\.\s+Comparing prices\./u)); }); +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 () => { await mountChat({ "bots:live:subscribe": () => snapshot({ entries: [userEntry("u1", "Plan Lisbon"), assistantEntry("a1", "Day one: Alfama.")] }), diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index 86c82cdcb1..8c2c846640 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -20,7 +20,7 @@ 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 } from "../../shared/bots"; +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"; @@ -31,6 +31,7 @@ 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 { BotStatusLine } from "./bot-status-line"; import { BotFilesDialog } from "./bot-files-dialog"; import { BotMessageActions, botReplyQuote } from "./bot-message-actions"; @@ -296,6 +297,7 @@ function TranscriptEntries({ entries, partial, running, + level, retrying, onConnect, onDismissConnection, @@ -309,6 +311,7 @@ function TranscriptEntries({ entries: readonly BotTranscriptEntry[]; partial: string | null; running: boolean; + level: BotChatActivityLevel; retrying: boolean; onConnect(pluginId: string): void; onDismissConnection(pluginId: string): void; @@ -321,7 +324,7 @@ function TranscriptEntries({ decision: BotRoutineProposalDecision, ): Promise | null>; }) { - const rows = botTranscriptRows(entries, partial, running); + const rows = botTranscriptRows(entries, partial, { running, level }); return ( <> {rows.map((row) => { @@ -351,6 +354,14 @@ function TranscriptEntries({ ); case "updates": return ; + case "recap": + return ; + case "stopped": + return ( + + You stopped this reply. + + ); case "file": return onOpenFile(row.path)} />; case "image": @@ -729,6 +740,7 @@ export function BotChatPane({ botId }: { botId: string }) { entries={snapshot.entries} partial={snapshot.partial} running={running} + level={chatActivity.level} retrying={retrying} onConnect={(pluginId) => void connectionSetup.open(pluginId)} onDismissConnection={(pluginId) => void dismissConnection(pluginId)} diff --git a/renderer/main/bots/bot-transcript-rows.test.ts b/renderer/main/bots/bot-transcript-rows.test.ts index dcb3c0dc5d..2ced09a432 100644 --- a/renderer/main/bots/bot-transcript-rows.test.ts +++ b/renderer/main/bots/bot-transcript-rows.test.ts @@ -4,6 +4,7 @@ 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", @@ -12,11 +13,14 @@ const step = (id: string, text: string): BotTranscriptEntry => ({ stopReason: "toolUse", }); const answer = (id: string, text: string): BotTranscriptEntry => ({ id, type: "assistant", text, toolCalls: [], stopReason: "stop" }); +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); +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( [ @@ -25,70 +29,97 @@ test("every tool round of one reply folds into a single Updates line before the result("a1"), step("a2", "Comparing prices."), 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(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); + assert.deepEqual(kinds(rows), ["user", "updates", "assistant"]); }); -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, - ); - 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"); +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"]]); +}); - // Just sent: nothing written yet, the Bot is still shown working. - assert.deepEqual(kinds(botTranscriptRows([user("u1", "Hi")], null, true)), ["user", "updates"]); +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("files and shared images show as chips in the reply, not as extra Updates lines", () => { +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 stopped step carries through as stopped, and an unfinished call in a stopped turn is stopped, not failed", () => { + const stoppedResult = { ...result("a1"), status: "stopped", isError: true } as BotTranscriptEntry; + const aborted: BotTranscriptEntry = { + id: "a2", + type: "assistant", + text: "", + toolCalls: [{ id: "a2-call", name: "run_command", kind: "command", label: "Ran a command" }], + stopReason: "aborted", + }; 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" }, - ], + [user("u1", "go"), step("a1", ""), stoppedResult, 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", "stopped"]); + assert.equal(rows[rows.length - 1]?.kind, "stopped"); +}); + +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, - true, + quiet, ); - assert.deepEqual(kinds(rows), ["user", "updates", "file", "image"]); - assert.equal(rows[1]?.kind === "updates" && rows[1].active, true); + 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" }); }); diff --git a/renderer/main/bots/bot-transcript-rows.ts b/renderer/main/bots/bot-transcript-rows.ts index 0ffb1369fc..129f7c9c90 100644 --- a/renderer/main/bots/bot-transcript-rows.ts +++ b/renderer/main/bots/bot-transcript-rows.ts @@ -1,24 +1,35 @@ // 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. 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 { 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" } @@ -37,6 +48,20 @@ export type BotTranscriptRow = 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; + /** 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; +} + function joinProgress(parts: readonly string[]): string { return parts.map((part) => part.trim()).filter(Boolean).join("\n\n"); } @@ -44,43 +69,105 @@ function joinProgress(parts: readonly string[]): string { export function botTranscriptRows( entries: readonly BotTranscriptEntry[], partial: string | null, - running: boolean, + { running, level }: 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; + // The current turn, and its reply's Updates row with the narration folded into it so far. + const state: { turn: Turn | null; updates: { row: UpdatesRow; parts: string[] } | null } = { + turn: null, + updates: null, + }; + const fold = (id: string, text: string) => { - if (!updates) { + if (!state.updates) { const row: UpdatesRow = { kind: "updates", id: `${id}:updates`, progressText: "", active: false }; rows.push(row); - updates = { row, parts: [] }; + state.updates = { row, parts: [] }; } - updates.parts.push(text); - updates.row.progressText = joinProgress(updates.parts); + state.updates.parts.push(text); + state.updates.row.progressText = joinProgress(state.updates.parts); }; - const endTurn = () => { - updates = null; + + 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))) { + // 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); + } + 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, + }; + }; + + 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(); + 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": + 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; 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 }); + else if (entry.text.trim()) { + 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,7 +175,12 @@ 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": @@ -115,8 +207,12 @@ 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; break; + } } } @@ -124,17 +220,18 @@ export function botTranscriptRows( // 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; + 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 }); } - } else if (partial !== null) { + endTurn(true); + } else { + endTurn(false); // A paused reply keeps what it wrote, as a bubble. - const text = partial.trim(); - if (text) rows.push({ kind: "assistant", id: "partial", text: partial }); + if (partial !== null && partial.trim()) rows.push({ kind: "assistant", id: "partial", text: partial }); } return rows; } diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index eaca7a00a0..e308c1f6f1 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -859,6 +859,7 @@ "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-routines.test.tsx", "renderer/main/bots/bot-memory-page.test.tsx", "main/handlers/bot-live.test.ts", From 99f45845a4d07fbc33fa18a70883e0b8d711b289 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 03:40:22 -0400 Subject: [PATCH 13/26] Bots: progress narration is a bubble; remove the Updates line Co-Authored-By: Claude Opus 5.5 --- renderer/main/bots/bot-chat-mode.test.tsx | 50 -------------- renderer/main/bots/bot-chat-pane.test.tsx | 36 +++++----- renderer/main/bots/bot-chat-pane.tsx | 7 +- renderer/main/bots/bot-reply-projection.ts | 53 --------------- .../main/bots/bot-transcript-rows.test.ts | 20 ++++-- renderer/main/bots/bot-transcript-rows.ts | 66 +++++-------------- renderer/main/bots/bot-updates.tsx | 55 ---------------- 7 files changed, 50 insertions(+), 237 deletions(-) delete mode 100644 renderer/main/bots/bot-reply-projection.ts delete mode 100644 renderer/main/bots/bot-updates.tsx 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 0e6c0a4373..32e39d0d4a 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -59,13 +59,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 () => { @@ -303,22 +303,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", kind: "working", label: "Used a tool" }], stopReason: "toolUse" }, + { + 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 () => { @@ -509,7 +514,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); @@ -563,7 +567,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({ @@ -575,10 +579,9 @@ 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 () => { @@ -778,7 +781,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": () => [], @@ -796,7 +799,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"); diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index 8c2c846640..c8b1e8f92b 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -38,7 +38,6 @@ 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."; @@ -291,7 +290,7 @@ function BotMemoryUpdatedCaption({ onOpen }: { onOpen(): void }) { ); } -/** Chat transcript rows: bubbles, one Updates line per reply, chips, cards. */ +/** Chat transcript rows: bubbles, recaps, chips, cards. */ function TranscriptEntries({ name, entries, @@ -349,11 +348,9 @@ function TranscriptEntries({ case "assistant": return ( - + ); - case "updates": - return ; case "recap": return ; case "stopped": 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-transcript-rows.test.ts b/renderer/main/bots/bot-transcript-rows.test.ts index 2ced09a432..4cb945728a 100644 --- a/renderer/main/bots/bot-transcript-rows.test.ts +++ b/renderer/main/bots/bot-transcript-rows.test.ts @@ -21,20 +21,29 @@ const kinds = (rows: ReturnType) => rows.map((row) => const quiet = { running: false, level: "quiet" } as const; -test("every tool round of one reply folds into a single Updates line before the answer", () => { +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"), answer("a3", "The cheapest is TAP on Friday."), ], null, quiet, ); - assert.deepEqual(kinds(rows), ["user", "updates", "assistant"]); + 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"]); }); test("Quiet never adds a recap; Summary puts one recap of the turn right above its answer", () => { @@ -47,8 +56,7 @@ test("Quiet never adds a recap; Summary puts one recap of the turn right above i ]; 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"]); + 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); diff --git a/renderer/main/bots/bot-transcript-rows.ts b/renderer/main/bots/bot-transcript-rows.ts index 129f7c9c90..82c4e22c99 100644 --- a/renderer/main/bots/bot-transcript-rows.ts +++ b/renderer/main/bots/bot-transcript-rows.ts @@ -1,19 +1,19 @@ // 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. +// 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 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; @@ -24,8 +24,6 @@ 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." */ @@ -36,7 +34,7 @@ export type BotTranscriptRow = | { 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"; @@ -46,8 +44,6 @@ export type BotTranscriptRow = routineId?: string; }; -type UpdatesRow = Extract; - interface Turn { id: string; startAt?: number; @@ -62,10 +58,6 @@ interface Turn { interrupted: 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, @@ -73,24 +65,10 @@ export function botTranscriptRows( ): BotTranscriptRow[] { const rows: BotTranscriptRow[] = []; const retryable = running ? null : botRetryableFailedTurn(entries); - // The current turn, and its reply's Updates row with the narration folded into it so far. - 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); - }; + // The current turn, once a message has started one. + const state: { turn: Turn | null } = { turn: null }; const endTurn = (live: boolean) => { - state.updates = null; const turn = state.turn; state.turn = null; if (!turn) return; @@ -161,9 +139,8 @@ export function botTranscriptRows( turn.byCall.set(call.id, recapStep); } 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; + if (entry.text.trim()) { + if (entry.toolCalls.length === 0) turn.answerRow = rows.length; rows.push({ kind: "assistant", id: entry.id, text: entry.text }); } break; @@ -216,22 +193,9 @@ export function botTranscriptRows( } } - 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 = 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); - // A paused reply keeps what it wrote, as a bubble. - if (partial !== null && partial.trim()) 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 } : {}) }); } 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} -
- ); -} From 6daa18ced781f29fc1ce08440a3b0c1cef94a61d Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 03:50:39 -0400 Subject: [PATCH 14/26] Bots: queued follow-ups show faded with Remove; steers show at once A steer that lands while a tool is still running now joins the running turn, so the tool result no longer reads as failed. Co-Authored-By: Claude Opus 5.5 --- main/handlers/bot-live.test.ts | 1 + main/handlers/bot-params.test.ts | 8 ++ main/handlers/bot-params.ts | 15 +++ main/handlers/bots.ts | 5 + .../bot-runtime/bot-session-service.ts | 22 +++++ .../bot-runtime/live-projection.test.ts | 93 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 37 ++++++++ renderer/lib/ipc.ts | 6 ++ renderer/main/bots/bot-chat-pane.test.tsx | 19 ++++ renderer/main/bots/bot-chat-pane.tsx | 53 ++++++++++- .../main/bots/bot-transcript-rows.test.ts | 47 ++++++++++ renderer/main/bots/bot-transcript-rows.ts | 26 +++++- renderer/shared/bot-live.ts | 14 +++ 13 files changed, 341 insertions(+), 5 deletions(-) diff --git a/main/handlers/bot-live.test.ts b/main/handlers/bot-live.test.ts index 8a0f7179d2..a1c0321d45 100644 --- a/main/handlers/bot-live.test.ts +++ b/main/handlers/bot-live.test.ts @@ -40,6 +40,7 @@ function fakeProjection() { state: { kind: "idle" }, question: null, activity: null, + queued: [], }; return { snapshot, unsubscribe: () => sinks.delete(id) }; }, diff --git a/main/handlers/bot-params.test.ts b/main/handlers/bot-params.test.ts index c9ee745566..8ed8ac50e7 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", () => { @@ -210,3 +211,10 @@ test("a Bot update may carry an exact chat activity choice, and nothing else new ); 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: "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 487000f0f2..10ee85b6e1 100644 --- a/main/handlers/bot-params.ts +++ b/main/handlers/bot-params.ts @@ -207,6 +207,21 @@ export function parseBotSessionAction( return { botId: parseBotId(fields.botId), requestId: fields.requestId }; } +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 }; +} + 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 e29b67dc45..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,6 +203,10 @@ export function registerBotHandlers(): void { const { botId, requestId } = parseBotSessionAction(input, "dismiss"); return (await botSessionRuntime()).dismiss(botId, requestId); }); + 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); diff --git a/main/services/bot-runtime/bot-session-service.ts b/main/services/bot-runtime/bot-session-service.ts index 09e12a6e11..01a689ec56 100644 --- a/main/services/bot-runtime/bot-session-service.ts +++ b/main/services/bot-runtime/bot-session-service.ts @@ -133,6 +133,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 +146,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; /** @@ -506,6 +514,20 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom }); }, + 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"; + }); + }, + deleteBot(botId) { return serialize(botId, async () => { // Another process holding the profile owns the session; erasing the diff --git a/main/services/bot-runtime/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index dd06afb662..d3d3efbd01 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -16,6 +16,7 @@ import { BOT_CONNECT_CARD_ENTRY_KIND, createBotLiveProjection, liveBotActivity, + liveQueuedMessages, projectBotTranscript, type BotLiveProjection, type BotLiveProjectionDeps, @@ -925,3 +926,95 @@ test("a follow-up turn queued behind a running one gets its own start time and a 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 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({}), []); +}); + +test("a routine or hidden prompt waiting behind a running reply never appears as a queued message", async () => { + const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("routine done"), fauxAssistantMessage("hello")], { + 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: "Plan dinners", 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", requestId: "routine:r1:1", label: "Morning check-in" }); + await live.service.send("bot:a", { text: "Introduce yourself", requestId: "intro:1", hidden: true }); + await live.service.send("bot:a", { text: "Also dessert", requestId: "desk-2", whenBusy: "steer" }); + await waitFor(() => tape.view?.queued.some((item) => item.text === "Also dessert") === true, { what: "the steer" }); + assert.deepEqual( + tape.events.flatMap((event) => (event.type === "queued" ? event.queued.map((item) => item.text) : [])).filter((text) => text !== "Also dessert"), + [], + ); + 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 867bc7b045..feda178f27 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -31,6 +31,7 @@ import { type BotLiveActivity, type BotLiveEvent, type BotPendingQuestion, + type BotQueuedMessage, type BotLiveEventBody, type BotLiveSnapshot, type BotLiveSummary, @@ -497,6 +498,34 @@ export function liveBotActivity(input: BotLiveActivityInput): BotLiveActivity | return at(inputAnswered(input.entries) ? "thinking" : "preparing"); } +/** + * 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; +} + /* ------------------------------------------------------------------------- */ /* Feeds and subscribers */ /* ------------------------------------------------------------------------- */ @@ -573,6 +602,7 @@ interface Feed { state: BotSessionState; question: BotPendingQuestion | null; activity: BotLiveActivity | null; + queued: BotQueuedMessage[]; /** When the current running turn started. */ startedAt: number; stopping: boolean; @@ -618,6 +648,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro state: feed.state, question: feed.question, activity: feed.activity, + queued: feed.queued, }; } @@ -753,6 +784,11 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro feed.partial = partial; emit(feed, { type: "partial", text: partial }); } + const queued = liveQueuedMessages(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) { updateActivity(feed); @@ -810,6 +846,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro state: await deps.state(botId), question: deps.question?.(botId) ?? null, activity: null, + queued: liveQueuedMessages(initial.docs), startedAt: now(), stopping: false, resuming: false, 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/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index 32e39d0d4a..b92c5d4102 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -21,6 +21,7 @@ function snapshot(overrides: Partial = {}): BotLiveSnapshot { state: { kind: "idle" }, question: null, activity: null, + queued: [], ...overrides, }; } @@ -865,3 +866,21 @@ 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" })); + await waitFor(() => + assert.deepEqual(calls.find((call) => call.channel === "bots:withdraw")?.args, [{ botId: "bot-1", submissionId: "8" }]), + ); +}); diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index c8b1e8f92b..4443f899d1 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -23,7 +23,7 @@ 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"; @@ -290,6 +290,23 @@ function BotMemoryUpdatedCaption({ onOpen }: { onOpen(): void }) { ); } +/** 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 + +
+
+ ); +} + /** Chat transcript rows: bubbles, recaps, chips, cards. */ function TranscriptEntries({ name, @@ -297,7 +314,10 @@ function TranscriptEntries({ partial, running, level, + queued, + removing, retrying, + onRemoveQueued, onConnect, onDismissConnection, onOpenFile, @@ -311,7 +331,10 @@ function TranscriptEntries({ partial: string | null; running: boolean; level: BotChatActivityLevel; + queued: readonly BotQueuedMessage[]; + removing: string | null; retrying: boolean; + onRemoveQueued(submissionId: string): void; onConnect(pluginId: string): void; onDismissConnection(pluginId: string): void; onOpenFile(path: string): void; @@ -323,7 +346,7 @@ function TranscriptEntries({ decision: BotRoutineProposalDecision, ): Promise | null>; }) { - const rows = botTranscriptRows(entries, partial, { running, level }); + const rows = botTranscriptRows(entries, partial, { running, level, queued }); return ( <> {rows.map((row) => { @@ -353,6 +376,15 @@ function TranscriptEntries({ ); case "recap": return ; + case "queued": + return ( + onRemoveQueued(row.submissionId)} + /> + ); case "stopped": return ( @@ -425,6 +457,7 @@ 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(null); const [pausedBusy, setPausedBusy] = React.useState(false); const [statusLayout, setStatusLayout] = React.useState(""); const composerRef = React.useRef(null); @@ -480,6 +513,7 @@ export function BotChatPane({ botId }: { botId: string }) { approvals.prompts.length, snapshot?.question?.waitId, snapshot?.activity?.phase, + snapshot?.queued.length, statusLayout, ]} showScrollToBottomButton @@ -647,6 +681,18 @@ export function BotChatPane({ botId }: { botId: string }) { }); }; + 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); + } + }; + const respondToProposal = async (proposalId: string, decision: BotRoutineProposalDecision) => { try { const result = await botsApi.routineProposals.respond({ botId: current.id, proposalId, decision }); @@ -738,6 +784,9 @@ export function BotChatPane({ botId }: { botId: string }) { partial={snapshot.partial} running={running} level={chatActivity.level} + queued={snapshot.queued} + removing={removing} + onRemoveQueued={(id) => void removeQueued(id)} retrying={retrying} onConnect={(pluginId) => void connectionSetup.open(pluginId)} onDismissConnection={(pluginId) => void dismissConnection(pluginId)} diff --git a/renderer/main/bots/bot-transcript-rows.test.ts b/renderer/main/bots/bot-transcript-rows.test.ts index 4cb945728a..684fcce8aa 100644 --- a/renderer/main/bots/bot-transcript-rows.test.ts +++ b/renderer/main/bots/bot-transcript-rows.test.ts @@ -131,3 +131,50 @@ 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 that lands before a running tool's result keeps that step in its turn, not failed", () => { + const entries = [ + userAt("u1", "Find flights", 1_000), + step("a1", ""), + user("u2", "Make it cheap"), + { ...result("a1"), at: 4_000 } as BotTranscriptEntry, + 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", "user:Make it cheap", "recap", "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 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 82c4e22c99..ed57b51fbd 100644 --- a/renderer/main/bots/bot-transcript-rows.ts +++ b/renderer/main/bots/bot-transcript-rows.ts @@ -9,7 +9,7 @@ // 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"; @@ -18,6 +18,8 @@ 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 = @@ -28,6 +30,8 @@ export type BotTranscriptRow = | { 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" } @@ -61,7 +65,7 @@ interface Turn { export function botTranscriptRows( entries: readonly BotTranscriptEntry[], partial: string | null, - { running, level }: BotTranscriptRowOptions, + { running, level, queued }: BotTranscriptRowOptions, ): BotTranscriptRow[] { const rows: BotTranscriptRow[] = []; const retryable = running ? null : botRetryableFailedTurn(entries); @@ -110,7 +114,10 @@ export function botTranscriptRows( for (const entry of entries) { switch (entry.type) { case "user": - beginTurn(entry.id, entry.at); + // A steer lands while a tool is still running and joins that turn; a + // new message after the turn's tools reported back starts a new turn. + if (!state.turn?.steps.some((step) => step.status === "running")) beginTurn(entry.id, entry.at); + else touch(entry.at); rows.push({ kind: "user", id: entry.id, text: entry.text }); break; case "question_answer": @@ -197,5 +204,18 @@ export function botTranscriptRows( 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/shared/bot-live.ts b/renderer/shared/bot-live.ts index 87c441feb4..f186c54656 100644 --- a/renderer/shared/bot-live.ts +++ b/renderer/shared/bot-live.ts @@ -200,6 +200,15 @@ export interface BotLiveActivity { 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; @@ -212,6 +221,8 @@ export interface BotLiveSnapshot { 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 = @@ -220,6 +231,7 @@ export type BotLiveEventBody = | { 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 }; @@ -283,5 +295,7 @@ export function applyBotLiveEvent(snapshot: BotLiveSnapshot, event: BotLiveEvent 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 }; } } From e2c96aa520ae13b577741d6e7ef980848fe33678 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 04:04:20 -0400 Subject: [PATCH 15/26] Bots: queued list by request id; turns split on every user entry Co-Authored-By: Claude Opus 5.5 --- main/handlers/bot-params.test.ts | 2 + main/handlers/bot-params.ts | 3 +- main/services/bot-runtime/bot-session-main.ts | 1 + .../bot-runtime/bot-session-service.ts | 33 +++++- .../bot-runtime/live-projection.test.ts | 110 +++++++++++++----- main/services/bot-runtime/live-projection.ts | 74 +++++++++--- renderer/main/bots/bot-chat-pane.test.tsx | 62 +++++++++- renderer/main/bots/bot-chat-pane.tsx | 53 ++++++--- .../main/bots/bot-transcript-rows.test.ts | 28 ++++- renderer/main/bots/bot-transcript-rows.ts | 6 +- 10 files changed, 304 insertions(+), 68 deletions(-) diff --git a/main/handlers/bot-params.test.ts b/main/handlers/bot-params.test.ts index 8ed8ac50e7..892f409dd4 100644 --- a/main/handlers/bot-params.test.ts +++ b/main/handlers/bot-params.test.ts @@ -215,6 +215,8 @@ test("a Bot update may carry an exact chat activity choice, and nothing else new 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 10ee85b6e1..fbf299a614 100644 --- a/main/handlers/bot-params.ts +++ b/main/handlers/bot-params.ts @@ -207,7 +207,8 @@ export function parseBotSessionAction( return { botId: parseBotId(fields.botId), requestId: fields.requestId }; } -const BOT_SUBMISSION_ID = /^\d{1,16}$/u; +/** 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 } { diff --git a/main/services/bot-runtime/bot-session-main.ts b/main/services/bot-runtime/bot-session-main.ts index d1458874eb..e8317882bf 100644 --- a/main/services/bot-runtime/bot-session-main.ts +++ b/main/services/bot-runtime/bot-session-main.ts @@ -338,6 +338,7 @@ 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, diff --git a/main/services/bot-runtime/bot-session-service.ts b/main/services/bot-runtime/bot-session-service.ts index 01a689ec56..b221d686b9 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, @@ -168,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; + /** + * Of these queued submission ids, the ones that are not the person's own + * messages: a routine's input and the hidden self-intro, known from their + * durable request ids. + */ + 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`). @@ -291,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. */ @@ -426,6 +435,23 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom return (await openBot(botId)).conversation; }, + async quietInputs(botId, submissionIds) { + const quiet = new Set(); + if (submissionIds.length === 0 || deleted.has(botId)) return quiet; + const opened = await requireHost().open(botId); + const inspection = await opened.harness.inspect(ctx); + 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 ?? ""; + if (requestId.startsWith("routine:") || requestId.startsWith(BOT_INTRO_REQUEST_PREFIX) || hiddenSubmissions.has(id)) { + quiet.add(id); + } + } + return quiet; + }, + state(botId) { return currentState(botId); }, @@ -458,6 +484,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 }; @@ -516,10 +543,13 @@ 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( - Number(submissionId) as SubmissionId, + id as SubmissionId, ctx, opened.conversation.id, ); @@ -549,6 +579,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/live-projection.test.ts b/main/services/bot-runtime/live-projection.test.ts index d3d3efbd01..0481338db3 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -16,6 +16,7 @@ import { BOT_CONNECT_CARD_ENTRY_KIND, createBotLiveProjection, liveBotActivity, + liveQueuedInputIds, liveQueuedMessages, projectBotTranscript, type BotLiveProjection, @@ -60,6 +61,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 { @@ -974,44 +976,98 @@ test("Remove on a queued message whose turn already started withdraws nothing", } }); -test("queued routine and hidden prompts are not shown as the person's messages", () => { +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 } }); - 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 }], - ); + 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({}), []); }); -test("a routine or hidden prompt waiting behind a running reply never appears as a queued message", async () => { - const fauxModels = createFauxModels([slowAnswer(), fauxAssistantMessage("routine done"), fauxAssistantMessage("hello")], { - tokensPerSecond: 40, +/** 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: "Plan dinners", requestId: "desk-1" }); + 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", requestId: "routine:r1:1", label: "Morning check-in" }); - await live.service.send("bot:a", { text: "Introduce yourself", requestId: "intro:1", hidden: true }); - await live.service.send("bot:a", { text: "Also dessert", requestId: "desk-2", whenBusy: "steer" }); - await waitFor(() => tape.view?.queued.some((item) => item.text === "Also dessert") === true, { what: "the steer" }); - assert.deepEqual( - tape.events.flatMap((event) => (event.type === "queued" ? event.queued.map((item) => item.text) : [])).filter((text) => text !== "Also dessert"), - [], - ); + 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 { diff --git a/main/services/bot-runtime/live-projection.ts b/main/services/bot-runtime/live-projection.ts index feda178f27..47ee0f67b2 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -498,30 +498,39 @@ export function liveBotActivity(input: BotLiveActivityInput): BotLiveActivity | 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`, as the person sent them. A routine's input and - * the hidden self-intro are preceded by their notice write and are not shown. + * 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>): BotQueuedMessage[] { +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[] = []; - 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; - } + const item = value as { id?: unknown; mode?: unknown; content?: unknown }; if (item.mode !== "steer" && item.mode !== "followUp") continue; - if (skipNext) { - skipNext = false; - 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 || (typeof item.id !== "number" && typeof item.id !== "string")) continue; - queued.push({ submissionId: String(item.id), mode: item.mode, text: textOf(content), imageCount: imageCount(content) }); + if (content === undefined || quiet.has(submissionId)) continue; + queued.push({ submissionId, mode: item.mode, text: textOf(content), imageCount: imageCount(content) }); } return queued; } @@ -539,6 +548,12 @@ export interface BotLiveProjectionDeps { state(botId: string): Promise; /** The question the Bot is waiting on right now, if any. */ question?(botId: string): BotPendingQuestion | null; + /** + * Which of these queued submission ids are not the person's own messages (a + * routine's input or the hidden self-intro). Decided from durable request + * ids; a failure hides them until the next frame. + */ + 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`. */ @@ -603,6 +618,8 @@ interface Feed { question: BotPendingQuestion | null; activity: BotLiveActivity | null; queued: BotQueuedMessage[]; + /** Queued submission ids already classified as quiet (true) or the person's (false). */ + inputKinds: Map; /** When the current running turn started. */ startedAt: number; stopping: boolean; @@ -769,6 +786,25 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro for (const entry of next.slice(previous.length)) emit(feed, { type: "entry", entry }); } + /** The person's queued messages, classifying each new queued id once. */ + 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 && deps.quietInputs) { + try { + const quiet = await deps.quietInputs(feed.botId, unknown); + for (const id of unknown) feed.inputKinds.set(id, quiet.has(id)); + } catch (error) { + report(feed.botId, error); + // Unclassified ids stay hidden until the next frame can decide. + return liveQueuedMessages(docs, new Set(unknown)); + } + } + const quiet = new Set([...feed.inputKinds].filter(([, isQuiet]) => isQuiet).map(([id]) => id)); + return liveQueuedMessages(docs, quiet); + } + async function onFrame(feed: Feed, entries: readonly EntryRecord[], docs: Readonly>) { if (feed.ended) return; feed.frame = { entries, docs }; @@ -784,7 +820,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro feed.partial = partial; emit(feed, { type: "partial", text: partial }); } - const queued = liveQueuedMessages(docs); + const queued = await queuedFor(feed, docs); if (JSON.stringify(queued) !== JSON.stringify(feed.queued)) { feed.queued = queued; emit(feed, { type: "queued", queued }); @@ -846,7 +882,8 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro state: await deps.state(botId), question: deps.question?.(botId) ?? null, activity: null, - queued: liveQueuedMessages(initial.docs), + queued: [], + inputKinds: new Map(), startedAt: now(), stopping: false, resuming: false, @@ -860,6 +897,7 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro }; 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(() => { diff --git a/renderer/main/bots/bot-chat-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index b92c5d4102..f460e37711 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"; @@ -879,8 +880,67 @@ test("a queued message shows faded as Queued, and Remove withdraws that one subm }); assert.ok(await screen.findByText("Also add dessert")); assert.ok(screen.getByText("Queued")); - fireEvent.click(screen.getByRole("button", { name: "Remove queued message" })); + 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")); +}); diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index 4443f899d1..067be5b9d0 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -290,16 +290,35 @@ function BotMemoryUpdatedCaption({ onOpen }: { onOpen(): void }) { ); } -/** 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 }) { +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 -
@@ -332,9 +351,9 @@ function TranscriptEntries({ running: boolean; level: BotChatActivityLevel; queued: readonly BotQueuedMessage[]; - removing: string | null; + removing: ReadonlySet; retrying: boolean; - onRemoveQueued(submissionId: string): void; + onRemoveQueued(submissionId: string, button: HTMLButtonElement): void; onConnect(pluginId: string): void; onDismissConnection(pluginId: string): void; onOpenFile(path: string): void; @@ -381,8 +400,8 @@ function TranscriptEntries({ onRemoveQueued(row.submissionId)} + removing={removing.has(row.submissionId)} + onRemove={(button) => onRemoveQueued(row.submissionId, button)} /> ); case "stopped": @@ -457,7 +476,7 @@ 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(null); + const [removing, setRemoving] = React.useState>(new Set()); const [pausedBusy, setPausedBusy] = React.useState(false); const [statusLayout, setStatusLayout] = React.useState(""); const composerRef = React.useRef(null); @@ -681,15 +700,23 @@ export function BotChatPane({ botId }: { botId: string }) { }); }; - const removeQueued = async (submissionId: string) => { - setRemoving(submissionId); + 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(null); + setRemoving((ids) => { + const rest = new Set(ids); + rest.delete(submissionId); + return rest; + }); } }; @@ -786,7 +813,7 @@ export function BotChatPane({ botId }: { botId: string }) { level={chatActivity.level} queued={snapshot.queued} removing={removing} - onRemoveQueued={(id) => void removeQueued(id)} + onRemoveQueued={(id, button) => void removeQueued(id, button)} retrying={retrying} onConnect={(pluginId) => void connectionSetup.open(pluginId)} onDismissConnection={(pluginId) => void dismissConnection(pluginId)} diff --git a/renderer/main/bots/bot-transcript-rows.test.ts b/renderer/main/bots/bot-transcript-rows.test.ts index 684fcce8aa..0d58b6c2d2 100644 --- a/renderer/main/bots/bot-transcript-rows.test.ts +++ b/renderer/main/bots/bot-transcript-rows.test.ts @@ -148,24 +148,46 @@ test("a queued follow-up is a faded row at the end, and a steer is a normal bubb ]); }); -test("a steer that lands before a running tool's result keeps that step in its turn, not failed", () => { +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", ""), - user("u2", "Make it cheap"), { ...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", "user:Make it cheap", "recap", "assistant"], + ["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"), diff --git a/renderer/main/bots/bot-transcript-rows.ts b/renderer/main/bots/bot-transcript-rows.ts index ed57b51fbd..d82ce94443 100644 --- a/renderer/main/bots/bot-transcript-rows.ts +++ b/renderer/main/bots/bot-transcript-rows.ts @@ -114,10 +114,8 @@ export function botTranscriptRows( for (const entry of entries) { switch (entry.type) { case "user": - // A steer lands while a tool is still running and joins that turn; a - // new message after the turn's tools reported back starts a new turn. - if (!state.turn?.steps.some((step) => step.status === "running")) beginTurn(entry.id, entry.at); - else touch(entry.at); + // 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": From d6f02bc6531b6c784a56006ff448c13a805155eb Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 04:15:52 -0400 Subject: [PATCH 16/26] Bots: queued classification fails closed Co-Authored-By: Claude Opus 5.5 --- .../bot-runtime/bot-session-service.ts | 28 +++--- main/services/bot-runtime/bot-starter.test.ts | 1 + .../bot-runtime/live-projection.test.ts | 95 +++++++++++++++++++ main/services/bot-runtime/live-projection.ts | 69 +++++++++++--- 4 files changed, 168 insertions(+), 25 deletions(-) diff --git a/main/services/bot-runtime/bot-session-service.ts b/main/services/bot-runtime/bot-session-service.ts index b221d686b9..f6471fe898 100644 --- a/main/services/bot-runtime/bot-session-service.ts +++ b/main/services/bot-runtime/bot-session-service.ts @@ -170,11 +170,11 @@ export interface BotSessionRuntime extends BotSessionService { /** The Bot's conversation, opened lazily (for live projection). */ conversation(botId: string): Promise; /** - * Of these queued submission ids, the ones that are not the person's own - * messages: a routine's input and the hidden self-intro, known from their - * durable request ids. + * 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>; + 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`). @@ -436,20 +436,24 @@ export async function createBotSessionService(deps: BotSessionServiceDeps): Prom }, async quietInputs(botId, submissionIds) { - const quiet = new Set(); - if (submissionIds.length === 0 || deleted.has(botId)) return quiet; - const opened = await requireHost().open(botId); - const inspection = await opened.harness.inspect(ctx); + 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 ?? ""; - if (requestId.startsWith("routine:") || requestId.startsWith(BOT_INTRO_REQUEST_PREFIX) || hiddenSubmissions.has(id)) { - quiet.add(id); - } + // `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 quiet; + return answers; }, state(botId) { 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 0481338db3..e4b08efd19 100644 --- a/main/services/bot-runtime/live-projection.test.ts +++ b/main/services/bot-runtime/live-projection.test.ts @@ -1074,3 +1074,98 @@ test("a notice left behind by Stop does not hide the person's next queued messag 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 47ee0f67b2..a78c1bc874 100644 --- a/main/services/bot-runtime/live-projection.ts +++ b/main/services/bot-runtime/live-projection.ts @@ -549,11 +549,12 @@ export interface BotLiveProjectionDeps { /** The question the Bot is waiting on right now, if any. */ question?(botId: string): BotPendingQuestion | null; /** - * Which of these queued submission ids are not the person's own messages (a - * routine's input or the hidden self-intro). Decided from durable request - * ids; a failure hides them until the next frame. + * 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>; + 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`. */ @@ -563,6 +564,8 @@ export interface BotLiveProjectionDeps { /** 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; @@ -620,6 +623,11 @@ interface Feed { 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; @@ -654,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 { @@ -786,23 +795,52 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro for (const entry of next.slice(previous.length)) emit(feed, { type: "entry", entry }); } - /** The person's queued messages, classifying each new queued id once. */ + /** + * 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 && deps.quietInputs) { + if (unknown.length > 0 && now() >= feed.classifyNotBefore) { try { - const quiet = await deps.quietInputs(feed.botId, unknown); - for (const id of unknown) feed.inputKinds.set(id, quiet.has(id)); + 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) { - report(feed.botId, error); - // Unclassified ids stay hidden until the next frame can decide. - return liveQueuedMessages(docs, new Set(unknown)); + 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); } - const quiet = new Set([...feed.inputKinds].filter(([, isQuiet]) => isQuiet).map(([id]) => id)); - return liveQueuedMessages(docs, quiet); + 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>) { @@ -884,6 +922,9 @@ export function createBotLiveProjection(deps: BotLiveProjectionDeps): BotLivePro activity: null, queued: [], inputKinds: new Map(), + classifyFailing: false, + classifyNotBefore: 0, + classifyRetry: null, startedAt: now(), stopping: false, resuming: false, @@ -936,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(); From 4f894c702fe64e32b4809ff9a4e3fbce1a75b4a0 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 04:21:08 -0400 Subject: [PATCH 17/26] =?UTF-8?q?Bots:=20Advanced=20=E2=86=92=20Chat=20act?= =?UTF-8?q?ivity=20with=20live=20previews,=20saved=20on=20pick?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- renderer/main/bots-view.tsx | 10 +- renderer/main/bots/bot-advanced.tsx | 37 ++- .../main/bots/bot-chat-activity-page.test.tsx | 96 ++++++ renderer/main/bots/bot-chat-activity-page.tsx | 298 ++++++++++++++++++ renderer/main/bots/bot-page-search.ts | 4 +- scripts/ci-test-registry.json | 1 + 7 files changed, 442 insertions(+), 6 deletions(-) create mode 100644 renderer/main/bots/bot-chat-activity-page.test.tsx create mode 100644 renderer/main/bots/bot-chat-activity-page.tsx diff --git a/package.json b/package.json index b231ad9781..e1f8cfa35f 100644 --- a/package.json +++ b/package.json @@ -128,7 +128,7 @@ "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 renderer/shared/bot-activity.test.ts renderer/main/bots/bot-status-line.test.tsx renderer/main/bots/bot-activity-recap.test.tsx", + "test:bots": "tsx --test main/services/telegram/telegram-bot-chat-lifecycle.test.ts main/services/telegram/telegram-bot-binding-reconciliation.test.ts main/services/telegram/telegram-bot-binding-validation.test.ts main/services/telegram/telegram-bot-binding-authority.test.ts main/services/bot-avatar-store.test.ts main/services/bot-store-core.test.ts main/services/bot-chat-store.test.ts main/services/bot-mutation-gate.test.ts main/services/bot-inbox-projection.test.ts main/services/bot-system-prompt.test.ts main/services/bot-generation-preparation.test.ts main/services/bot-inbound-attachment-home.test.ts main/services/bot-file-tool-router.test.ts main/services/bot-tool-authority.test.ts main/services/bot-capability-store-core.test.ts main/services/bot-capability-store.test.ts main/services/bot-capability-state-checkpoint.test.ts main/services/bot-capability-keychain-anchor.test.ts main/services/bot-capability-secret-service-anchor.test.ts main/services/bot-capability-lease.test.ts main/services/bot-runtime-inventory-lease.test.ts main/services/bot-runtime-inventory-publication.test.ts main/services/bot-runtime-authority.test.ts main/services/bot-capability-catalog-core.test.ts main/services/bot-capability-bindings.test.ts main/services/bot-capability-key-store.test.ts main/services/bot-capability-migration-seal.test.ts main/services/bot-capability-incarnation-store.test.ts main/services/bot-capability-inventory-ports.test.ts main/services/bot-capability-production-shape.test.ts main/services/bot-mcp-inventory.test.ts main/services/bot-skill-inventory.test.ts main/services/bot-skill-content-watcher.test.ts main/services/bot-managed-workspace-core.test.ts main/services/bot-lifecycle-journal-core.test.ts main/services/bot-application-service.test.ts main/handlers/bot-params.test.ts main/handlers/bot-renderer-errors.test.ts main/handlers/bots.contract.test.ts 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", 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-advanced.tsx b/renderer/main/bots/bot-advanced.tsx index 2ae5fdb342..e186402fce 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); @@ -455,6 +464,12 @@ export function BotAdvanced({ bot, onClose }: { bot: BotDefinition; onClose(): v description: `Your changes to ${bot.name}’s Advanced settings won’t be saved.`, }); + const chatActivityGuard = useDiscardChangesGuard({ + dirty, + onLeave: onOpenChatActivity, + description: `Your changes to ${bot.name}’s Advanced settings won’t be saved.`, + }); + const saveAccess = async (current: BotAccessDraft, start: BotAccessDraft) => { const [state, readCatalog] = await Promise.all([ botsApi.getBotAccess(bot.id), @@ -553,8 +568,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..93b759cbd3 --- /dev/null +++ b/renderer/main/bots/bot-chat-activity-page.test.tsx @@ -0,0 +1,96 @@ +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("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("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.equal(screen.queryByRole("button", { name: "Save" }), null, "no Save button on this page"); +}); + +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"), + ); + assert.equal(within(level).getByRole("radio", { name: "Summary" }).getAttribute("data-state"), "unchecked"); +}); + +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(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); + 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.")); +}); 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..d6cd080dd8 --- /dev/null +++ b/renderer/main/bots/bot-chat-activity-page.tsx @@ -0,0 +1,298 @@ +// 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 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 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) => { + 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; +}) { + 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 applied to the last saved choice, 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 { + const choice = { ...saved.current, ...patch }; + await updateBotIdentity(qc, bot.id, { chatActivity: choice }); + saved.current = choice; + } 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-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/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index e308c1f6f1..6cf9ef34be 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -860,6 +860,7 @@ "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", From 434f47565206004f039e5301bd0eb9379d82eb28 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 04:24:27 -0400 Subject: [PATCH 18/26] Bots: faces glance while their Bot works Co-Authored-By: Claude Opus 5.5 --- renderer/components/aiden-activity-mark.tsx | 15 +++++--- renderer/components/bot-avatar.tsx | 39 +++++++++++++-------- renderer/main/bots/bot-chat-header.tsx | 5 ++- renderer/main/bots/bot-chat-pane.test.tsx | 14 ++++++++ renderer/main/bots/bot-chat-pane.tsx | 1 + renderer/main/bots/bot-list.test.tsx | 10 ++++++ renderer/main/bots/bot-list.tsx | 7 +--- renderer/styles.css | 10 ++++++ 8 files changed, 75 insertions(+), 26 deletions(-) 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/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-pane.test.tsx b/renderer/main/bots/bot-chat-pane.test.tsx index f460e37711..fc1f602f0f 100644 --- a/renderer/main/bots/bot-chat-pane.test.tsx +++ b/renderer/main/bots/bot-chat-pane.test.tsx @@ -6,6 +6,7 @@ import { BotChatRoute } from "../bot-chat-route"; import { mountWithBotRouter } from "./test-providers"; import { toast } from "../../components/ui"; import { botFixture } from "./test-fixtures"; +import { invalidateBotCanonicalPhotos } from "../../lib/bot-canonical-photo-cache"; import type { BotLiveSnapshot, BotTranscriptEntry } from "../../shared/bot-live"; afterEach(cleanup); @@ -944,3 +945,16 @@ test("each queued message has its own Remove, and removing one moves focus on: t fireEvent.click(second); await waitFor(() => assert.equal((document.activeElement as HTMLElement | null)?.getAttribute("placeholder"), "Ask Planner")); }); + +test("the chat header's face works while the Bot works, and a photo gets a small activity badge", async () => { + invalidateBotCanonicalPhotos(); + 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"]'))); +}); diff --git a/renderer/main/bots/bot-chat-pane.tsx b/renderer/main/bots/bot-chat-pane.tsx index 067be5b9d0..fb4bb83dbf 100644 --- a/renderer/main/bots/bot-chat-pane.tsx +++ b/renderer/main/bots/bot-chat-pane.tsx @@ -503,6 +503,7 @@ export function BotChatPane({ botId }: { botId: string }) { current ? ( void navigate({ to: "/bots/$botId", params: { botId: current.id } })} /> ) : bot.isLoading ? ( 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..e4f1fc893d 100644 --- a/renderer/main/bots/bot-list.tsx +++ b/renderer/main/bots/bot-list.tsx @@ -121,13 +121,8 @@ function BotListItem({ name={bot.name} photoLoading="visible" size="large" + working={working} /> - {working ? ( - diff --git a/renderer/styles.css b/renderer/styles.css index b7c882c12f..f7a37b33e3 100644 --- a/renderer/styles.css +++ b/renderer/styles.css @@ -2975,6 +2975,16 @@ 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; 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; } +} + /* 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. */ From 3c4465ff16837511be4ab7ae82e0d9639bea15aa Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Wed, 14 Oct 2026 04:33:38 -0400 Subject: [PATCH 19/26] Bots: Chat activity still frames per level; tested save queue Co-Authored-By: Claude Opus 5.5 --- .../main/bots/bot-chat-activity-page.test.tsx | 183 ++++++++++++++++-- renderer/main/bots/bot-chat-activity-page.tsx | 74 +++++-- renderer/main/bots/bot-identity.ts | 9 +- 3 files changed, 235 insertions(+), 31 deletions(-) diff --git a/renderer/main/bots/bot-chat-activity-page.test.tsx b/renderer/main/bots/bot-chat-activity-page.test.tsx index 93b759cbd3..04912e1b70 100644 --- a/renderer/main/bots/bot-chat-activity-page.test.tsx +++ b/renderer/main/bots/bot-chat-activity-page.test.tsx @@ -3,6 +3,8 @@ 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"; @@ -12,15 +14,44 @@ afterEach(() => { delete document.documentElement.dataset.reduceMotion; }); -function store(initial: BotDefinition, options: { failUpdate?: boolean } = {}) { +/** 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": (input) => { + "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}+` }; @@ -34,7 +65,7 @@ function store(initial: BotDefinition, options: { failUpdate?: boolean } = {}) { }), "bots:getTelegramBinding": () => null, }); - return { updates, current: () => bot }; + 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 () => { @@ -48,6 +79,20 @@ test("Advanced shows the current choice and opens Chat activity; Back returns to 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" }); @@ -63,18 +108,113 @@ test("each choice saves as it is picked, with the Bot's revision and nothing els 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"); + 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("a choice that fails to save goes back to the saved one", async () => { - store(botFixture(), { failUpdate: true }); +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" }); - fireEvent.click(within(level).getByRole("radio", { name: "Summary" })); - 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"); + 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 () => { @@ -82,15 +222,32 @@ test("under Reduce Motion each preview is a still frame with Play, built from th 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; + 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 index d6cd080dd8..c0c478ca17 100644 --- a/renderer/main/bots/bot-chat-activity-page.tsx +++ b/renderer/main/bots/bot-chat-activity-page.tsx @@ -8,7 +8,7 @@ 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 { APPEARANCE_CHANGE_EVENT, prefersReducedMotion } from "../../lib/appearance-runtime"; import { userFacingErrorMessage } from "../../lib/ipc-error"; import type { BotToolPhase } from "../../shared/bot-activity"; import { @@ -67,8 +67,31 @@ const PREVIEW_FRAMES: ReadonlyArray<{ ms: number; phase?: "thinking" | BotToolPh { 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; +/** + * 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; export function BotChatActivityPreview({ @@ -85,10 +108,19 @@ export function BotChatActivityPreview({ name: string; }) { const ref = React.useRef(null); - const [reduced] = React.useState(() => prefersReducedMotion()); - const [playing, setPlaying] = React.useState(!reduced); + 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_FRAME : 0); + 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; @@ -153,7 +185,7 @@ export function BotChatActivityPreview({ size="small" className="self-start" aria-label={`${playing ? "Pause" : "Play"} preview: ${label}`} - onClick={() => setPlaying((value) => !value)} + onClick={() => setPlayed((value) => !value)} > {playing ?