pi-render-btw 0.6.18 → 0.6.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.20 — 2026-11-23
4
+
5
+ - Make the BTW transcript's `▎` a persistent selected-block rail: the newest block starts selected, click any block to move focus, and hover no longer moves it.
6
+ - Keep THINKING blocks focusable and visible; click a tool block to toggle its inline show-more details while preserving the full Tool Output preview.
7
+ - Support click-to-focus and tool toggling on hosts that deliver raw SGR mouse press/release input, and ignore clicks on the frame and scrollbar rail.
8
+
9
+ ## 0.6.19 — 2026-11-23
10
+
11
+ - Fix BTW prompts submitted during streaming by always routing them as steering input, including rapid submits that race the first run's startup.
12
+ - Add a streaming-aware composer with `Ctrl+X` to stop only the BTW agent/tool run and its queued BTW prompts while keeping the BTW overlay and session available for the next prompt.
13
+
3
14
  ## 0.6.18 — 2026-11-20
4
15
 
5
16
  - Fix contextual BTW sub-sessions losing the current main-session context before their first model request. Seed messages now enter the sub-session `SessionManager`, which Pi uses as the authoritative source for model context.
package/README.md CHANGED
@@ -93,6 +93,10 @@ pi install /path/to/pi-render-btw
93
93
  ## Overlay controls
94
94
 
95
95
  - `Alt+/` toggles focus between BTW and the main editor without closing the overlay
96
+ - while BTW is streaming, `Enter` steers the BTW agent after its current tool or assistant turn instead of rejecting the new prompt
97
+ - `Ctrl+X` stops only the active BTW agent/tool run and clears its queued BTW prompts; the overlay and BTW session stay ready for the next message
98
+ - the newest transcript block starts focused with a persistent `▎` rail; clicking any block moves that focus without hover changing it
99
+ - clicking a focused tool row toggles its `[click more]` / `[click less]` details; `Ctrl+O` and title `[preview]` still open the full read-only Tool Output
96
100
  - `Ctrl+Alt+W` is a fallback focus toggle for terminals that do not deliver `Alt+/` as a usable shortcut
97
101
  - `Ctrl+G` opens the current BTW draft in `$VISUAL`/`$EDITOR` (falling back to `nano`) and reads it back when the editor exits successfully
98
102
  - the composer uses Pi's native editor behavior for undo, paste, prompt history, and Tab file-path completion (including `@` prefixes) relative to the BTW working directory; `Alt+Up` (`a-up`/`alt+up`) recalls a submitted draft
@@ -0,0 +1,81 @@
1
+ # BTW steer 與中斷 Implementation Plan
2
+
3
+ > [!NOTE]
4
+ > 此目錄由 npm tarball 建立,沒有 Git metadata;本次不建立 commit、tag 或 publish。
5
+
6
+ **Goal:** BTW 子 session 串流或執行工具時,新的輸入能 steer 而不拋出 processing error,且 Ctrl+X 僅中斷 BTW 的當前 agent/tool run,保留視窗與 session 供後續對話。
7
+
8
+ **Architecture:** `runBtw()` 將每個已接受的輸入登記為待完成請求,並在 `agent_settled` 以 BTW session 的實際 user/assistant 訊息配對後持久化,避免 busy submission 讀到前一輪回答。Overlay 維持常駐 composer;busy 時顯示 steer 狀態,Ctrl+X 直接呼叫子 session 的 queue-clear 與 `abort()`,不 dispose、dismiss 或接觸主 session。
9
+
10
+ **Tech Stack:** TypeScript、Pi `AgentSession`、Vitest、Pi TUI。
11
+
12
+ ## Global Constraints
13
+
14
+ - Busy prompt 使用 Pi 的 `streamingBehavior: "steer"`,使訊息在目前 tool execution 完成後、下一次 LLM request 前送入。
15
+ - Ctrl+X 只能操作 `activeBtwSession.session`,不得呼叫主 session API、`disposeBtwSession()` 或 overlay dismiss。
16
+ - `agent_settled` 才是完成持久化邊界;`turn_end` 不足以代表 queued steer 已完成。
17
+ - 保留既有 `--save`、tangent/contextual、手動 inject/summarize 行為。
18
+
19
+ ---
20
+
21
+ ### Task 1: 建立可測的 prompt 與 stop 邊界
22
+
23
+ **Files:**
24
+ - Modify: `extensions/btw.ts`
25
+ - Test: `extensions/btw-transcript.test.ts`
26
+
27
+ **Interfaces:**
28
+ - Produces: `submitBtwPrompt(session, question, onAccepted)`,以 `preflightResult` 回報 `started` / `queued` / `handled`。
29
+ - Produces: `stopBtwRun(session)`,在 streaming 時清除 queued side prompts、await `session.abort()`,回傳是否實際停止。
30
+
31
+ - [ ] 新增失敗測試:busy session 以 `streamingBehavior: "steer"` 接受輸入,不使用無選項 `prompt()`。
32
+ - [ ] 新增失敗測試:`stopBtwRun()` 只呼叫 fake BTW session 的 `clearQueue()` 與 `abort()`;idle session 不呼叫任何一者。
33
+ - [ ] 實作兩個最小 helper,使用 Pi public `AgentSession` 方法與型別。
34
+ - [ ] 執行:`./node_modules/.bin/vitest --run extensions/btw-transcript.test.ts`。
35
+
36
+ ### Task 2: 將完成持久化移至 agent-settled
37
+
38
+ **Files:**
39
+ - Modify: `extensions/btw.ts`
40
+ - Test: `extensions/btw-transcript.test.ts`
41
+
42
+ **Interfaces:**
43
+ - Produces: `BtwPendingPrompt`,包含 question、saveRequested、主 session busy 狀態、model 與 thinking level。
44
+ - Produces: `persistSettledBtwPrompts(sessionRuntime, aborted, ctx)`,將 `sideThreadStartIndex` 之後完成的 user/assistant pairs 寫為 `BtwDetails` 與 durable thread entries。
45
+
46
+ - [ ] 在 `runBtw()` 的 `preflightResult` 登記已開始或已排隊的 prompt;移除直接讀取 `getLastAssistantMessage()` 後立即持久化的流程。
47
+ - [ ] 在 session event handler 收到 `agent_settled` 時,非 aborted run 依提交順序持久化完整 exchanges;aborted run 丟棄尚未完成的 pending prompts 並保留 session。
48
+ - [ ] reset、restore、dispose 時清空 stale pending prompt metadata,避免舊 session completion 汙染新 session。
49
+ - [ ] 執行既有 transcript suite,確認 persistence、Peek、tool artifact 行為沒有回歸。
50
+
51
+ ### Task 3: 將 steer 與 Ctrl+X 呈現在 BTW overlay
52
+
53
+ **Files:**
54
+ - Modify: `extensions/btw.ts`
55
+ - Test: `extensions/btw-transcript.test.ts`
56
+ - Modify: `README.md`
57
+
58
+ **Interfaces:**
59
+ - `BtwOverlayComponent` 新增可選 `isBtwRunning()` 與 `onStop()` callbacks。
60
+ - busy composer hint:`Enter steer · Ctrl+X stop`;idle composer hint:`Enter submit`。
61
+
62
+ - [ ] 新增失敗測試:busy overlay 顯示 steer/stop hint,Ctrl+X 觸發 stop callback 而非 dismiss,且之後 Enter 仍能送出新 prompt。
63
+ - [ ] 在 `handleInput()` 於 Peek/Tool Output routing 前攔截 Ctrl+X;僅 busy 時呼叫 `onStop()`。
64
+ - [ ] 在 extension runtime 將 overlay stop callback 接到 `stopBtwRun(activeBtwSession.session)`;狀態依序顯示 stopping 與 ready。
65
+ - [ ] 更新 README 的 overlay controls 與 real sub-session behavior,說明 Enter busy 時 steer、Ctrl+X 僅停止 BTW 子 session run。
66
+
67
+ ### Task 4: 驗證
68
+
69
+ **Files:**
70
+ - Test: `extensions/btw-transcript.test.ts`
71
+
72
+ - [ ] 執行 focused red/green tests:`./node_modules/.bin/vitest --run extensions/btw-transcript.test.ts`。
73
+ - [ ] 執行全套:`npm test`。
74
+ - [ ] 執行變更檔案的 TypeScript check:`./node_modules/.bin/tsc --noEmit --target es2022 --module nodenext --moduleResolution nodenext --allowImportingTsExtensions --skipLibCheck extensions/btw.ts extensions/btw-transcript.test.ts`。
75
+ - [ ] 由獨立 reviewer 檢查 session queue、abort scope 與 persistence race。
76
+
77
+ ## Self-review
78
+
79
+ - Spec coverage:Task 1/2 消除 busy prompt 的 processing error 與 stale-answer persistence;Task 3 套用常駐 composer steer UX、實作 Ctrl+X 的 BTW-only stop;Task 4 覆蓋回歸與獨立檢查。
80
+ - Placeholder scan:沒有 TBD、TODO 或模糊的「適當處理」步驟。
81
+ - Type consistency:`BtwPendingPrompt` 僅在 extension closure 持有;公開 helper 只依賴 Pi `AgentSession` 的 prompt、clearQueue、abort API。
@@ -0,0 +1,80 @@
1
+ # BTW Agent View 焦點互動 Implementation Plan
2
+
3
+ > [!NOTE]
4
+ > 此目錄由 npm tarball 建立,沒有 Git metadata;本次不建立 commit、tag 或 publish。
5
+
6
+ **Goal:** BTW transcript 採用 Agent View 風格的 selected-block focus:`▎` 常駐於當前焦點 block,滑鼠 hover 不改變焦點;點擊任一 block 切換焦點,點擊工具 block 同時切換其 show-more 內容,並保留 THINKING block。
7
+
8
+ **Architecture:** `BtwOverlayComponent` 以 `liveFocusedEntryId` 作為唯一 transcript selection state;首次 render 選擇最新可互動 block,之後只由 explicit click 改變。render 時以 `transcriptLineEntryIds` 將 rail 套到選定 block 的所有內容行;tool block 沿用既有 `liveExpandedToolCallId` 做同一焦點工具的 inline show-more toggle,完整 Tool Output preview 仍可由 Ctrl+O 或 title `[preview]` 進入。
9
+
10
+ **Tech Stack:** TypeScript、Pi TUI、Vitest。
11
+
12
+ ## Global Constraints
13
+
14
+ - transcript hover 不得修改 `liveFocusedEntryId` 或 rail。
15
+ - explicit left click 任一可互動 block 都必須更新 focus;非 tool click 清除 stale tool focus。
16
+ - tool click 必須更新 focus,並在同一 tool 上切換 `[click more]` / `[click less]`;不影響 Ctrl+O 的唯讀完整 preview。
17
+ - THINKING 保持現有 badge、Markdown rendering、streaming marker,且可被 focus。
18
+ - rail 使用 `▎`,不改變右側 scrollbar 的所有權。
19
+
20
+ ---
21
+
22
+ ### Task 1: 寫 focus 與工具 click 的失敗測試
23
+
24
+ **Files:**
25
+ - Test: `extensions/btw-transcript.test.ts`
26
+
27
+ **Interfaces:**
28
+ - `BtwOverlayComponent.handleMouse()` 的 explicit `click` 為 selection 邊界。
29
+ - `BtwOverlayComponent.render()` 對 selected block 的可見行輸出 `▎`。
30
+
31
+ - [ ] 建立包含 USER、THINKING、TOOL、ASSISTANT 的 fixture。
32
+ - [ ] 斷言初始 render 的最新 block 有 `▎`;mouse move 到別 block 後 rail 不變。
33
+ - [ ] 斷言 click THINKING 後 THINKING 行有 rail 且內容仍存在。
34
+ - [ ] 斷言 click tool 後 tool 取得 rail、展開 `[click less]` 與 details;再次 click 收合為 `[click more]`。
35
+ - [ ] 執行 `./node_modules/.bin/vitest --run extensions/btw-transcript.test.ts`,確認測試在舊 hover 實作失敗。
36
+
37
+ ### Task 2: 將 transcript rail 改為 selected-block render
38
+
39
+ **Files:**
40
+ - Modify: `extensions/btw.ts`
41
+
42
+ **Interfaces:**
43
+ - `liveFocusedEntryId: number | null` 是唯一 transcript focus state。
44
+ - `ensureLiveTranscriptFocus(entries)` 在無有效 focus 時選擇最新 non-boundary entry。
45
+ - `applyFocusedTranscriptRail(lines, entryIds)` 在 selected entry 所有實質行套用 `▎`。
46
+
47
+ - [ ] 移除 `liveHoveredEntryId` 的 state、render 分支與 live transcript move handling。
48
+ - [ ] 在 build transcript 前確認 initial selected block,在 line IDs 建好後將 rail 套在 selected block 的所有實質行。
49
+ - [ ] 保持 THINKING 與 streaming text 的既有 rendering,讓其 entry ID 可接收 rail。
50
+
51
+ ### Task 3: 對齊 click focus 與 tool show-more
52
+
53
+ **Files:**
54
+ - Modify: `extensions/btw.ts`
55
+ - Test: `extensions/btw-transcript.test.ts`
56
+ - Modify: `README.md`
57
+
58
+ **Interfaces:**
59
+ - `focusLiveTranscriptEntry(entryId)` 僅由 explicit click 呼叫。
60
+ - `liveExpandedToolCallId` 維持 selected tool 的 inline show-more toggle。
61
+
62
+ - [ ] click 一般 block:更新 `liveFocusedEntryId`、清除 stale tool focus,不展開工具。
63
+ - [ ] click tool block:更新 focus,切換同 tool 的 expanded state;點不同 tool 時切換至該 tool。
64
+ - [ ] README 說明常駐 selected rail、click-to-focus 與工具 show-more。
65
+
66
+ ### Task 4: 驗證
67
+
68
+ **Files:**
69
+ - Test: `extensions/btw-transcript.test.ts`
70
+
71
+ - [ ] 執行 focused suite:`./node_modules/.bin/vitest --run extensions/btw-transcript.test.ts`。
72
+ - [ ] 執行全套:`npm test`。
73
+ - [ ] 執行變更檔案的 TypeScript check:`./node_modules/.bin/tsc --noEmit --target es2022 --module nodenext --moduleResolution nodenext --allowImportingTsExtensions --skipLibCheck extensions/btw.ts extensions/btw-transcript.test.ts`。
74
+ - [ ] 由獨立 reviewer 檢查 rail width、scrollbar、click scope、thinking preservation 與 tool-preview toggle。
75
+
76
+ ## Self-review
77
+
78
+ - Spec coverage:Task 1 先把 user 要求變成 red tests;Task 2 移除 hover-driven rail;Task 3 實作 click focus、tool toggle 與文件;Task 4 驗證 rendering/integration risk。
79
+ - Placeholder scan:沒有 TBD、TODO 或模糊交付項。
80
+ - Type consistency:每個 transcript row 維持 `entryId` 對應;selection 只保存 entry ID,expanded tool 只保存 tool call ID。
@@ -1,8 +1,9 @@
1
1
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import path from "node:path";
4
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
4
5
  import { describe, expect, it } from "vitest";
5
- import { BtwOverlayComponent } from "./btw.ts";
6
+ import { BtwOverlayComponent, stopBtwRun, submitBtwPrompt } from "./btw.ts";
6
7
  import { BtwTranscriptStore } from "./btw/transcript-store.ts";
7
8
 
8
9
  const theme = {
@@ -25,7 +26,7 @@ function transcriptLines(entries: unknown[]): string[] {
25
26
  tui,
26
27
  theme,
27
28
  keybindings,
28
- () => entries,
29
+ () => entries as any,
29
30
  () => null,
30
31
  () => "contextual",
31
32
  () => {},
@@ -41,7 +42,7 @@ describe("BTW transcript message layout", () => {
41
42
  { id: 1, turnId: 1, type: "user-message", text: "Prompt" },
42
43
  ]);
43
44
 
44
- expect(lines.slice(0, 2)).toEqual([" USER ", " Prompt"]);
45
+ expect(lines.slice(0, 2)).toEqual(["▎USER ", "▎ Prompt"]);
45
46
  });
46
47
 
47
48
  it("keeps assistant heading and response on separate lines", () => {
@@ -49,8 +50,8 @@ describe("BTW transcript message layout", () => {
49
50
  { id: 1, turnId: 1, type: "assistant-text", text: "Response", streaming: false },
50
51
  ]);
51
52
 
52
- expect(lines[0]).toBe(" ASSISTANT ");
53
- expect(lines[1].startsWith(" Response")).toBe(true);
53
+ expect(lines[0]).toBe("▎ASSISTANT ");
54
+ expect(lines[1].startsWith("▎ Response")).toBe(true);
54
55
  });
55
56
 
56
57
  it("opens Peek with Ctrl+P even when the composer contains a draft", () => {
@@ -530,6 +531,112 @@ describe("BTW transcript message layout", () => {
530
531
  }
531
532
  });
532
533
 
534
+ it("keeps a persistent clicked rail, ignores transcript hover, and toggles tool details", () => {
535
+ const entries = [
536
+ { id: 1, turnId: 1, type: "user-message", text: "Question" },
537
+ { id: 2, turnId: 1, type: "thinking", text: "Reasoning line one\nReasoning line two", streaming: false },
538
+ { id: 3, turnId: 1, type: "tool-call", toolCallId: "call-focus", toolName: "read", args: "src/index.ts" },
539
+ { id: 4, turnId: 1, type: "assistant-text", text: "Answer", streaming: false },
540
+ ] as any;
541
+ const component = new BtwOverlayComponent(
542
+ tui,
543
+ theme,
544
+ keybindings,
545
+ () => entries,
546
+ () => null,
547
+ () => "contextual",
548
+ () => {},
549
+ () => {},
550
+ () => {},
551
+ );
552
+
553
+ let lines = component.render(80);
554
+ expect(lines.some((line) => line.includes("▎") && line.includes("ASSISTANT"))).toBe(true);
555
+ const contentTop = (component as any).transcriptContentTop as number;
556
+ const lineEntryIds = (component as any).transcriptLineEntryIds as Array<number | null>;
557
+ const hostRowFor = (entryId: number) => contentTop - 1 + lineEntryIds.indexOf(entryId);
558
+
559
+ component.handleMouse({ type: "click", button: "left", x: 5, y: hostRowFor(2) } as any);
560
+ expect((component as any).liveFocusedEntryId).toBe(2);
561
+ lines = component.render(80);
562
+ expect(lines.filter((line) => line.includes("▎")).length).toBeGreaterThanOrEqual(2);
563
+ expect(lines.some((line) => line.includes("THINKING"))).toBe(true);
564
+
565
+ component.handleMouse({ type: "move", button: "none", x: 5, y: hostRowFor(1) } as any);
566
+ expect((component as any).liveFocusedEntryId).toBe(2);
567
+
568
+ component.handleMouse({ type: "click", button: "left", x: 5, y: hostRowFor(3) } as any);
569
+ expect((component as any).liveFocusedEntryId).toBe(3);
570
+ expect((component as any).liveExpandedToolCallId).toBe("call-focus");
571
+ expect(component.render(80).join("\n")).toContain("[click less]");
572
+
573
+ component.handleMouse({ type: "click", button: "left", x: 5, y: hostRowFor(3) } as any);
574
+ expect((component as any).liveExpandedToolCallId).toBeNull();
575
+ expect(component.render(80).join("\n")).toContain("[click more]");
576
+ });
577
+
578
+ it("uses raw SGR clicks to focus blocks and toggle a tool", () => {
579
+ const entries = [
580
+ { id: 1, turnId: 1, type: "user-message", text: "Question" },
581
+ { id: 2, turnId: 1, type: "tool-call", toolCallId: "call-sgr", toolName: "read", args: "src/index.ts" },
582
+ { id: 3, turnId: 1, type: "assistant-text", text: "Answer", streaming: false },
583
+ ] as any;
584
+ const component = new BtwOverlayComponent(
585
+ tui,
586
+ theme,
587
+ keybindings,
588
+ () => entries,
589
+ () => null,
590
+ () => "contextual",
591
+ () => {},
592
+ () => {},
593
+ () => {},
594
+ );
595
+
596
+ component.render(80);
597
+ const contentTop = (component as any).transcriptContentTop as number;
598
+ const lineEntryIds = (component as any).transcriptLineEntryIds as Array<number | null>;
599
+ const rawClick = (entryId: number) => {
600
+ const y = contentTop + lineEntryIds.indexOf(entryId);
601
+ component.handleInput(`\x1b[<0;5;${y}M`);
602
+ component.handleInput(`\x1b[<0;5;${y}m`);
603
+ };
604
+
605
+ rawClick(1);
606
+ expect((component as any).liveFocusedEntryId).toBe(1);
607
+
608
+ rawClick(2);
609
+ expect((component as any).liveFocusedEntryId).toBe(2);
610
+ expect((component as any).liveExpandedToolCallId).toBe("call-sgr");
611
+ });
612
+
613
+ it("does not focus or toggle a tool when clicking the scrollbar rail", () => {
614
+ const entries = [
615
+ { id: 1, turnId: 1, type: "tool-call", toolCallId: "call-rail", toolName: "read", args: "src/index.ts" },
616
+ { id: 2, turnId: 1, type: "assistant-text", text: "Answer", streaming: false },
617
+ ] as any;
618
+ const component = new BtwOverlayComponent(
619
+ tui,
620
+ theme,
621
+ keybindings,
622
+ () => entries,
623
+ () => null,
624
+ () => "contextual",
625
+ () => {},
626
+ () => {},
627
+ () => {},
628
+ );
629
+
630
+ component.render(80);
631
+ const contentTop = (component as any).transcriptContentTop as number;
632
+ const lineEntryIds = (component as any).transcriptLineEntryIds as Array<number | null>;
633
+ const toolHostRow = contentTop - 1 + lineEntryIds.indexOf(1);
634
+ component.handleMouse({ type: "click", button: "left", x: 78, y: toolHostRow } as any);
635
+
636
+ expect((component as any).liveFocusedEntryId).toBe(2);
637
+ expect((component as any).liveExpandedToolCallId).toBeNull();
638
+ });
639
+
533
640
  it("focuses and expands a live tool, scrolls locally, and opens Ctrl+O output", () => {
534
641
  const entries = [
535
642
  { id: 1, turnId: 1, type: "tool-call", toolCallId: "call-1", toolName: "write", args: "compact input" },
@@ -566,10 +673,10 @@ describe("BTW transcript message layout", () => {
566
673
  const hostToolRow = contentTop - 1;
567
674
  component.handleMouse({ type: "press", button: "left", x: 5, y: hostToolRow } as any);
568
675
  component.handleMouse({ type: "release", button: "left", x: 5, y: hostToolRow } as any);
569
- expect((component as any).liveFocusedToolCallId).toBeNull();
676
+ expect((component as any).liveFocusedToolCallId).toBe("call-1");
570
677
 
571
678
  component.handleMouse({ type: "move", button: "none", x: 5, y: hostToolRow } as any);
572
- expect((component as any).liveHoveredEntryId).toBe(1);
679
+ expect((component as any).liveFocusedEntryId).toBe(2);
573
680
  component.handleMouse({ type: "click", button: "left", x: 5, y: hostToolRow } as any);
574
681
  expect((component as any).liveFocusedToolCallId).toBe("call-1");
575
682
  expect((component as any).liveExpandedToolCallId).toBe("call-1");
@@ -684,6 +791,88 @@ describe("BTW transcript message layout", () => {
684
791
  expect(output).toContain("(no output)");
685
792
  });
686
793
 
794
+ it("steers a busy BTW session instead of prompting without streaming behavior", async () => {
795
+ const calls: Array<{ text: string; behavior: string | undefined }> = [];
796
+ const accepted: string[] = [];
797
+ const session = {
798
+ isStreaming: true,
799
+ prompt: async (text: string, options?: { streamingBehavior?: string; preflightResult?: (value: "started" | "queued" | "handled") => void }) => {
800
+ calls.push({ text, behavior: options?.streamingBehavior });
801
+ options?.preflightResult?.("queued");
802
+ },
803
+ } as unknown as Pick<AgentSession, "isStreaming" | "prompt">;
804
+
805
+ await submitBtwPrompt(session, "steer this", (disposition) => accepted.push(disposition));
806
+
807
+ expect(calls).toEqual([{ text: "steer this", behavior: "steer" }]);
808
+ expect(accepted).toEqual(["queued"]);
809
+ });
810
+
811
+ it("supplies steer behavior from idle state to close rapid-submit races", async () => {
812
+ let behavior: string | undefined;
813
+ const session = {
814
+ isStreaming: false,
815
+ prompt: async (_text: string, options?: { streamingBehavior?: string; preflightResult?: (value: "started" | "queued" | "handled") => void }) => {
816
+ behavior = options?.streamingBehavior;
817
+ options?.preflightResult?.("started");
818
+ },
819
+ } as unknown as Pick<AgentSession, "isStreaming" | "prompt">;
820
+
821
+ await submitBtwPrompt(session, "first rapid prompt", () => {});
822
+
823
+ expect(behavior).toBe("steer");
824
+ });
825
+
826
+ it("stops only an active BTW run and clears its queued prompts", async () => {
827
+ const calls: string[] = [];
828
+ const active = {
829
+ isStreaming: true,
830
+ clearQueue: () => { calls.push("clearQueue"); return { steering: [], followUp: [] }; },
831
+ abort: async () => { calls.push("abort"); },
832
+ } as unknown as Pick<AgentSession, "isStreaming" | "clearQueue" | "abort">;
833
+ const idle = {
834
+ isStreaming: false,
835
+ clearQueue: () => { calls.push("idle-clearQueue"); return { steering: [], followUp: [] }; },
836
+ abort: async () => { calls.push("idle-abort"); },
837
+ } as unknown as Pick<AgentSession, "isStreaming" | "clearQueue" | "abort">;
838
+
839
+ await expect(stopBtwRun(active)).resolves.toBe(true);
840
+ await expect(stopBtwRun(idle)).resolves.toBe(false);
841
+
842
+ expect(calls).toEqual(["clearQueue", "abort"]);
843
+ });
844
+
845
+ it("uses Ctrl+X to stop an active BTW run without dismissing the overlay", () => {
846
+ let submitted = "";
847
+ let dismissed = 0;
848
+ let stopRequests = 0;
849
+ const component = new BtwOverlayComponent(
850
+ tui,
851
+ theme,
852
+ keybindings,
853
+ () => [],
854
+ () => null,
855
+ () => "contextual",
856
+ (value) => { submitted = value; },
857
+ () => { dismissed++; },
858
+ () => {},
859
+ undefined,
860
+ undefined,
861
+ undefined,
862
+ () => true,
863
+ () => { stopRequests++; },
864
+ );
865
+
866
+ component.handleInput("\x18"); // Ctrl+X
867
+ expect(stopRequests).toBe(1);
868
+ expect(dismissed).toBe(0);
869
+ expect(component.render(80).join("\n")).toContain("Ctrl+X stop");
870
+
871
+ component.setDraft("still usable");
872
+ component.handleInput("\r");
873
+ expect(submitted).toBe("still usable");
874
+ });
875
+
687
876
  it("keeps Enter and Escape composer behavior outside Peek", () => {
688
877
  let submitted = "";
689
878
  let dismissed = 0;
package/extensions/btw.ts CHANGED
@@ -1075,6 +1075,17 @@ type BtwHandoffExchange = {
1075
1075
  assistant: string;
1076
1076
  };
1077
1077
 
1078
+ type BtwPromptDisposition = "started" | "queued";
1079
+
1080
+ type BtwPendingPrompt = {
1081
+ question: string;
1082
+ messageIndex: number | null;
1083
+ saveRequested: boolean;
1084
+ wasMainSessionBusy: boolean;
1085
+ model: SessionModel;
1086
+ thinkingLevel: SessionThinkingLevel;
1087
+ };
1088
+
1078
1089
  function buildBtwMessageContent(question: string, answer: string): string {
1079
1090
  return `Q: ${question}\n\nA: ${answer}`;
1080
1091
  }
@@ -1094,9 +1105,12 @@ function isThreadContinuationMarker(messages: Message[], index: number): boolean
1094
1105
  );
1095
1106
  }
1096
1107
 
1108
+ function getBtwThreadMessages(sessionRuntime: BtwSessionRuntime): Message[] {
1109
+ const handoffMessages = sessionRuntime.session.state.messages.slice(sessionRuntime.sideThreadStartIndex) as Message[];
1110
+ return isThreadContinuationMarker(handoffMessages, 0) ? handoffMessages.slice(2) : handoffMessages;
1111
+ }
1112
+
1097
1113
  function extractBtwHandoffThread(sessionRuntime: BtwSessionRuntime): BtwHandoffExchange[] {
1098
- const handoffMessages = sessionRuntime.session.state.messages.slice(sessionRuntime.sideThreadStartIndex);
1099
- const threadMessages = isThreadContinuationMarker(handoffMessages as Message[], 0) ? handoffMessages.slice(2) : handoffMessages;
1100
1114
  const exchanges: BtwHandoffExchange[] = [];
1101
1115
  let currentUser = "";
1102
1116
  let currentAssistant = "";
@@ -1114,7 +1128,7 @@ function extractBtwHandoffThread(sessionRuntime: BtwSessionRuntime): BtwHandoffE
1114
1128
  currentAssistant = "";
1115
1129
  };
1116
1130
 
1117
- for (const message of threadMessages) {
1131
+ for (const message of getBtwThreadMessages(sessionRuntime)) {
1118
1132
  if (message.role !== "user" && message.role !== "assistant") {
1119
1133
  continue;
1120
1134
  }
@@ -1137,6 +1151,36 @@ function extractBtwHandoffThread(sessionRuntime: BtwSessionRuntime): BtwHandoffE
1137
1151
  return exchanges;
1138
1152
  }
1139
1153
 
1154
+ /** Queue normal BTW input or steer a currently active BTW agent run. */
1155
+ export async function submitBtwPrompt(
1156
+ session: Pick<AgentSession, "isStreaming" | "prompt">,
1157
+ question: string,
1158
+ onAccepted: (disposition: BtwPromptDisposition) => void,
1159
+ ): Promise<void> {
1160
+ await session.prompt(question, {
1161
+ source: "extension",
1162
+ // Always supply this to close the idle-to-streaming preflight race between
1163
+ // rapid submits. Pi ignores streamingBehavior while the session is idle.
1164
+ streamingBehavior: "steer",
1165
+ preflightResult: (disposition) => {
1166
+ if (disposition !== "handled") {
1167
+ onAccepted(disposition);
1168
+ }
1169
+ },
1170
+ });
1171
+ }
1172
+
1173
+ /** Stop only the active BTW run, including any queued BTW prompts. */
1174
+ export async function stopBtwRun(session: Pick<AgentSession, "isStreaming" | "clearQueue" | "abort">): Promise<boolean> {
1175
+ if (!session.isStreaming) {
1176
+ return false;
1177
+ }
1178
+
1179
+ session.clearQueue();
1180
+ await session.abort();
1181
+ return true;
1182
+ }
1183
+
1140
1184
  function saveVisibleBtwNote(
1141
1185
  pi: ExtensionAPI,
1142
1186
  details: BtwDetails,
@@ -1203,6 +1247,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1203
1247
  private readonly onUnfocusCallback: () => void;
1204
1248
  private readonly onExternalEditorCallback?: () => void;
1205
1249
  private readonly readToolArtifact?: (toolCallId: string) => ToolArtifact | null;
1250
+ private readonly isBtwRunning?: () => boolean;
1251
+ private readonly onStopCallback?: () => void;
1206
1252
  /** BTW keeps its own recall cursor so Alt+Up works even when host history bindings are unset. */
1207
1253
  private draftHistory: string[] = [];
1208
1254
  private draftHistoryIndex = -1;
@@ -1217,7 +1263,6 @@ export class BtwOverlayComponent extends Container implements Focusable {
1217
1263
  private transcriptViewportHeight = 8;
1218
1264
  private followTranscript = true;
1219
1265
  private scrollbarActive = false;
1220
- private liveHoveredEntryId: number | null = null;
1221
1266
  private liveFocusedEntryId: number | null = null;
1222
1267
  private liveFocusedToolCallId: string | null = null;
1223
1268
  private liveExpandedToolCallId: string | null = null;
@@ -1246,6 +1291,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1246
1291
  private hoveredPreviewHint = false;
1247
1292
  private rawEscapePress = false;
1248
1293
  private rawPreviewPress = false;
1294
+ private rawContentPress: { x: number; y: number } | null = null;
1249
1295
  /** The same bounded preview is used by Peek and by the live BTW panel. */
1250
1296
  private toolPreviewParent: "peek" | "live" | null = null;
1251
1297
  private liveToolPreviewBlock: PeekBlock | null = null;
@@ -1277,6 +1323,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1277
1323
  onExternalEditor?: () => void,
1278
1324
  cwd?: string,
1279
1325
  readToolArtifact?: (toolCallId: string) => ToolArtifact | null,
1326
+ isBtwRunning?: () => boolean,
1327
+ onStop?: () => void,
1280
1328
  ) {
1281
1329
  super();
1282
1330
  this.tui = tui;
@@ -1289,6 +1337,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1289
1337
  this.onUnfocusCallback = onUnfocus;
1290
1338
  this.onExternalEditorCallback = onExternalEditor;
1291
1339
  this.readToolArtifact = readToolArtifact;
1340
+ this.isBtwRunning = isBtwRunning;
1341
+ this.onStopCallback = onStop;
1292
1342
 
1293
1343
  this.modeText = new Text("", 1, 0);
1294
1344
  this.summaryText = new Text("", 1, 0);
@@ -1550,6 +1600,16 @@ export class BtwOverlayComponent extends Container implements Focusable {
1550
1600
  return [this.theme.fg("dim", "No BTW thread yet. Ask a side question to start one.")];
1551
1601
  }
1552
1602
 
1603
+ const hasFocusedEntry = entries.some((entry) => entry.id === this.liveFocusedEntryId && entry.type !== "turn-boundary");
1604
+ if (!hasFocusedEntry) {
1605
+ const fallbackEntry = [...entries].reverse().find((entry) => entry.type !== "turn-boundary");
1606
+ this.liveFocusedEntryId = fallbackEntry?.id ?? null;
1607
+ this.liveFocusedToolCallId = fallbackEntry?.type === "tool-call" || fallbackEntry?.type === "tool-result"
1608
+ ? fallbackEntry.toolCallId ?? null
1609
+ : null;
1610
+ this.liveExpandedToolCallId = null;
1611
+ }
1612
+
1553
1613
  const allLines: string[] = [];
1554
1614
  const lineEntryIds: Array<number | null> = [];
1555
1615
  const markBlock = (entryId: number, start: number): void => {
@@ -1559,8 +1619,6 @@ export class BtwOverlayComponent extends Container implements Focusable {
1559
1619
  lineEntryIds[index] = value.trim() && !/^─+$/.test(value.trim()) ? entryId : null;
1560
1620
  }
1561
1621
  };
1562
- const focusRail = (entryId: number): string =>
1563
- this.liveFocusedEntryId === entryId ? "▎ " : this.liveHoveredEntryId === entryId ? "│ " : "";
1564
1622
  const userBadge = buildTranscriptBadge(this.theme, "USER", "userMessageBg", "accent");
1565
1623
  const thinkingBadge = buildTranscriptBadge(this.theme, "THINKING", "toolPendingBg", "warning");
1566
1624
  const assistantBadge = buildTranscriptBadge(this.theme, "ASSISTANT", "customMessageBg", "success");
@@ -1592,7 +1650,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1592
1650
 
1593
1651
  if (entry.type === "user-message") {
1594
1652
  pushBlank();
1595
- allLines.push(`${focusRail(entry.id)}${userBadge}`);
1653
+ allLines.push(userBadge);
1596
1654
  const boundedText = entry.text.length > 16_000 ? `${entry.text.slice(0, 15_970)}\n… [truncated]` : entry.text;
1597
1655
  const mdLines = renderBtwMarkdown(boundedText, mdContentWidth, this.theme, "user", this.mdTheme);
1598
1656
  for (const line of mdLines) {
@@ -1605,7 +1663,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1605
1663
  if (entry.type === "thinking") {
1606
1664
  const thinkingHeader = entry.streaming ? `${thinkingBadge} ${this.theme.fg("warning", "▍")}` : thinkingBadge;
1607
1665
  pushBlank();
1608
- allLines.push(`${focusRail(entry.id)}${thinkingHeader}`);
1666
+ allLines.push(thinkingHeader);
1609
1667
  const markdownLines = renderBtwMarkdown(entry.text, mdContentWidth, this.theme, "thinking", this.mdTheme);
1610
1668
  for (const line of markdownLines) {
1611
1669
  allLines.push(`${blockIndent}${line.replace(/[ \t]+$/u, "")}`);
@@ -1620,7 +1678,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1620
1678
  const isExpanded = this.liveExpandedToolCallId === entry.toolCallId;
1621
1679
  const moreLabel = this.theme.fg("dim", isExpanded ? " · [click less]" : " · [click more]");
1622
1680
  pushBlank();
1623
- allLines.push(`${focusRail(entry.id)}${toolLabel}${argsLabel}${moreLabel}`);
1681
+ allLines.push(`${toolLabel}${argsLabel}${moreLabel}`);
1624
1682
  if (isExpanded && entry.args) {
1625
1683
  const toolLines = renderBtwToolText(entry.args, mdContentWidth, this.theme);
1626
1684
  for (const line of toolLines) {
@@ -1640,7 +1698,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1640
1698
  const isExpanded = this.liveExpandedToolCallId === entry.toolCallId;
1641
1699
  const moreLabel = this.theme.fg("dim", isExpanded ? " · [click less]" : " · [click more]");
1642
1700
  pushBlank();
1643
- allLines.push(`${focusRail(entry.id)}${resultLabel}${summary}${truncLabel}${moreLabel}`);
1701
+ allLines.push(`${resultLabel}${summary}${truncLabel}${moreLabel}`);
1644
1702
  if (isExpanded) {
1645
1703
  const toolLines = renderBtwToolText(
1646
1704
  entry.fullContent ?? entry.content,
@@ -1660,7 +1718,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
1660
1718
  if (entry.type === "assistant-text") {
1661
1719
  pushBlank();
1662
1720
  const header = entry.streaming ? `${assistantBadge} ${this.theme.fg("warning", "▍")}` : assistantBadge;
1663
- allLines.push(`${focusRail(entry.id)}${header}`);
1721
+ allLines.push(header);
1664
1722
 
1665
1723
  // Use the same Pi Markdown renderer for completed and streaming text.
1666
1724
  // Markdown is intentionally cheap here because the overlay already
@@ -1680,7 +1738,13 @@ export class BtwOverlayComponent extends Container implements Focusable {
1680
1738
  }
1681
1739
 
1682
1740
  this.transcriptLineEntryIds = lineEntryIds;
1683
- return allLines;
1741
+ return allLines.map((line, index) => {
1742
+ if (lineEntryIds[index] !== this.liveFocusedEntryId) {
1743
+ return line;
1744
+ }
1745
+ const rail = this.theme.fg("accent", "▎");
1746
+ return line.startsWith(" ") ? `${rail}${line.slice(1)}` : `${rail}${line}`;
1747
+ });
1684
1748
  }
1685
1749
 
1686
1750
  private getDialogHeight(inputLines: number): number {
@@ -1742,10 +1806,12 @@ export class BtwOverlayComponent extends Container implements Focusable {
1742
1806
  const entry = this.readTranscriptEntries().find((candidate) => candidate.id === entryId);
1743
1807
  if (!entry || entry.type === "turn-boundary") return false;
1744
1808
  this.liveFocusedEntryId = entryId;
1745
- this.liveHoveredEntryId = entryId;
1746
1809
  this.liveFocusedToolCallId = entry.type === "tool-call" || entry.type === "tool-result"
1747
1810
  ? entry.toolCallId ?? null
1748
1811
  : null;
1812
+ if (this.liveFocusedToolCallId === null) {
1813
+ this.liveExpandedToolCallId = null;
1814
+ }
1749
1815
  this.tui.requestRender();
1750
1816
  return true;
1751
1817
  }
@@ -1926,11 +1992,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1926
1992
  this.render(this.lastRenderWidth);
1927
1993
  }
1928
1994
  if (normalized.action === "move" || normalized.action === "drag") {
1929
- const hoveredEntryId = this.transcriptEntryAtLine(normalized.y);
1930
- if (hoveredEntryId === this.liveHoveredEntryId) return { handled: true, render: false };
1931
- this.liveHoveredEntryId = hoveredEntryId;
1932
- this.tui.requestRender();
1933
- return { handled: true, render: true };
1995
+ // Transcript focus changes only through explicit clicks. Hover remains
1996
+ // intentionally inert so the persistent rail never jumps under the pointer.
1997
+ return { handled: true, render: false };
1934
1998
  }
1935
1999
  if (normalized.action === "press" || normalized.action === "release") {
1936
2000
  return { handled: true, render: false };
@@ -1938,7 +2002,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
1938
2002
  if (normalized.action !== "click" || normalized.button !== 0) {
1939
2003
  return { handled: true, render: false };
1940
2004
  }
1941
- if (normalized.x < 1 || normalized.x > this.lastRenderWidth) {
2005
+ // The outer frame and right-hand scrollbar are navigation chrome, not
2006
+ // transcript content. Keep their clicks from changing block focus.
2007
+ if (normalized.x < 2 || normalized.x > this.lastRenderWidth - 2) {
1942
2008
  return { handled: true, render: false };
1943
2009
  }
1944
2010
  const entryId = this.transcriptEntryAtLine(normalized.y);
@@ -1998,6 +2064,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
1998
2064
  }
1999
2065
 
2000
2066
  handleInput(data: string): void {
2067
+ if (matchesKey(data, Key.ctrl("x")) && this.isBtwRunning?.()) {
2068
+ this.onStopCallback?.();
2069
+ return;
2070
+ }
2071
+
2001
2072
  if (matchesBtwFocusShortcut(data)) {
2002
2073
  this.onUnfocusCallback();
2003
2074
  return;
@@ -2035,9 +2106,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
2035
2106
  }
2036
2107
  return;
2037
2108
  }
2038
- // Consume bounded SGR button events locally. Older hosts do not expose
2039
- // normalized click dispatch, so retain preview/close press/release pairs
2040
- // as the actionable fallback; transcript clicks remain read-only.
2109
+ // Older hosts expose raw SGR press/release pairs instead of normalized
2110
+ // click events. Recreate explicit clicks so transcript selection and tool
2111
+ // show-more retain the same behavior on both host generations.
2041
2112
  if (mouseEvent) {
2042
2113
  const overPreviewHint = this.isPreviewHintHit(mouseEvent.x, mouseEvent.y);
2043
2114
  const overEscapeHint = this.isEscapeHintHit(mouseEvent.x, mouseEvent.y);
@@ -2045,22 +2116,28 @@ export class BtwOverlayComponent extends Container implements Focusable {
2045
2116
  if (mouseEvent.button === 0 && mouseEvent.action === "press") {
2046
2117
  this.rawPreviewPress = overPreviewHint;
2047
2118
  this.rawEscapePress = overEscapeHint;
2119
+ this.rawContentPress = overPreviewHint || overEscapeHint ? null : { x: mouseEvent.x, y: mouseEvent.y };
2048
2120
  } else if (mouseEvent.button === 0 && mouseEvent.action === "release") {
2049
2121
  const preview = this.rawPreviewPress && overPreviewHint;
2050
2122
  const close = this.rawEscapePress && overEscapeHint;
2123
+ const contentClick = this.rawContentPress?.x === mouseEvent.x && this.rawContentPress.y === mouseEvent.y && !preview && !close;
2051
2124
  this.rawPreviewPress = false;
2052
2125
  this.rawEscapePress = false;
2126
+ this.rawContentPress = null;
2053
2127
  if (preview) {
2054
2128
  if (this.peekState.active) this.enterToolPreview();
2055
2129
  else this.enterLiveToolPreview();
2056
2130
  } else if (close) {
2057
2131
  this.closeEscapeTarget();
2132
+ } else if (contentClick && !this.peekState.active) {
2133
+ this.handleMouse({ ...mouseEvent, action: "click", button: 0 });
2058
2134
  }
2059
2135
  }
2060
2136
  return;
2061
2137
  }
2062
2138
  this.rawPreviewPress = false;
2063
2139
  this.rawEscapePress = false;
2140
+ this.rawContentPress = null;
2064
2141
 
2065
2142
  // Peek mode active → route all input to peek handler
2066
2143
  if (this.peekState.active) {
@@ -2201,7 +2278,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
2201
2278
  this.modeText.setText(this.modeTextValue);
2202
2279
  const entries = this.readTranscriptEntries();
2203
2280
  const exchanges = getCompletedExchangeCount(entries);
2204
- const active = hasStreamingTranscriptEntry(entries) ? " · streaming" : " · idle";
2281
+ const running = this.isBtwRunning?.() ?? false;
2282
+ const active = running || hasStreamingTranscriptEntry(entries) ? " · streaming" : " · idle";
2205
2283
  this.summaryTextValue = `${exchanges} exchange${exchanges === 1 ? "" : "s"}${active}`;
2206
2284
  this.summaryText.setText(this.summaryTextValue);
2207
2285
 
@@ -2210,7 +2288,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
2210
2288
  const status = this.getStatus() ?? "Ready. Enter submits; Escape dismisses without clearing.";
2211
2289
  this.statusTextValue = status;
2212
2290
  this.statusText.setText(this.statusTextValue);
2213
- this.hintsTextValue = "Scroll wheel ↑↓ PgUp/PgDn · Enter · Ctrl+P peek · Alt+/ focus · Esc";
2291
+ this.hintsTextValue = running
2292
+ ? "Scroll wheel ↑↓ PgUp/PgDn · Enter steer · Ctrl+X stop · Ctrl+P peek · Alt+/ focus · Esc"
2293
+ : "Scroll wheel ↑↓ PgUp/PgDn · Enter submit · Ctrl+P peek · Alt+/ focus · Esc";
2214
2294
  this.hintsText.setText(this.hintsTextValue);
2215
2295
  this.tui.requestRender();
2216
2296
  }
@@ -3104,6 +3184,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
3104
3184
 
3105
3185
  export default function (pi: ExtensionAPI) {
3106
3186
  let pendingThread: BtwDetails[] = [];
3187
+ let pendingBtwPrompts: BtwPendingPrompt[] = [];
3107
3188
  let pendingMode: BtwThreadMode = "contextual";
3108
3189
  let btwModelOverride: SessionModel | null = null;
3109
3190
  let btwThinkingOverride: SessionThinkingLevel | null = null;
@@ -3310,6 +3391,104 @@ export default function (pi: ExtensionAPI) {
3310
3391
  }
3311
3392
  }
3312
3393
 
3394
+ async function persistSettledBtwPrompts(
3395
+ sessionRuntime: BtwSessionRuntime,
3396
+ aborted: boolean,
3397
+ ctx?: ExtensionContext | ExtensionCommandContext,
3398
+ ): Promise<void> {
3399
+ if (activeBtwSession?.session !== sessionRuntime.session) {
3400
+ return;
3401
+ }
3402
+
3403
+ if (aborted) {
3404
+ pendingBtwPrompts = [];
3405
+ if (closeRestoredStreamingTurns(transcriptState)) {
3406
+ persistTranscriptState();
3407
+ await flushTranscriptState();
3408
+ }
3409
+ setOverlayStatus("Stopped. BTW is ready for a new prompt.", ctx);
3410
+ return;
3411
+ }
3412
+
3413
+ const prompts = pendingBtwPrompts;
3414
+ pendingBtwPrompts = [];
3415
+ const messages = sessionRuntime.session.state.messages as Message[];
3416
+ let saveState: SaveState = "not-saved";
3417
+
3418
+ for (let index = 0; index < prompts.length; index++) {
3419
+ const prompt = prompts[index];
3420
+ if (prompt.messageIndex === null) {
3421
+ continue;
3422
+ }
3423
+
3424
+ const nextPromptIndex = prompts.slice(index + 1).find((candidate) => candidate.messageIndex !== null)?.messageIndex;
3425
+ const endIndex = nextPromptIndex ?? messages.length;
3426
+ let response: AssistantMessage | null = null;
3427
+ for (let messageIndex = endIndex - 1; messageIndex > prompt.messageIndex; messageIndex--) {
3428
+ const message = messages[messageIndex];
3429
+ if (message?.role === "assistant") {
3430
+ response = message as AssistantMessage;
3431
+ break;
3432
+ }
3433
+ }
3434
+
3435
+ if (!response) {
3436
+ continue;
3437
+ }
3438
+ if (response.stopReason === "error") {
3439
+ setTranscriptFailure(transcriptState, response.errorMessage || "BTW request failed.");
3440
+ continue;
3441
+ }
3442
+
3443
+ const submittedMessage = messages[prompt.messageIndex];
3444
+ const question = submittedMessage ? extractMessageText(submittedMessage).trim() || prompt.question : prompt.question;
3445
+ const details: BtwDetails = {
3446
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
3447
+ question,
3448
+ thinking: extractThinking(response),
3449
+ answer: extractAnswer(response),
3450
+ provider: prompt.model.provider,
3451
+ model: prompt.model.id,
3452
+ api: prompt.model.api,
3453
+ thinkingLevel: prompt.thinkingLevel,
3454
+ timestamp: Date.now(),
3455
+ usage: response.usage,
3456
+ };
3457
+ pendingThread.push(details);
3458
+ pi.appendEntry(BTW_ENTRY_TYPE, details);
3459
+ const nextSaveState = saveVisibleBtwNote(pi, details, prompt.saveRequested, prompt.wasMainSessionBusy);
3460
+ if (nextSaveState !== "not-saved") {
3461
+ saveState = nextSaveState;
3462
+ }
3463
+ }
3464
+
3465
+ persistTranscriptState();
3466
+ await flushTranscriptState();
3467
+
3468
+ if (saveState === "saved") {
3469
+ if (ctx) notify(ctx, "Saved BTW note to the session.", "info");
3470
+ setOverlayStatus("Saved BTW note to the session.", ctx);
3471
+ } else if (saveState === "queued") {
3472
+ if (ctx) notify(ctx, "BTW note queued to save after the current turn finishes.", "info");
3473
+ setOverlayStatus("BTW note queued to save after the current turn finishes.", ctx);
3474
+ } else {
3475
+ setOverlayStatus("Ready for a follow-up. Hidden BTW thread updated.", ctx);
3476
+ }
3477
+ }
3478
+
3479
+ async function stopActiveBtwRun(ctx: ExtensionContext | ExtensionCommandContext): Promise<void> {
3480
+ const session = activeBtwSession?.session;
3481
+ if (!session || !session.isStreaming) {
3482
+ return;
3483
+ }
3484
+
3485
+ setOverlayStatus("⏹ stopping BTW agent and tool output...", ctx);
3486
+ await stopBtwRun(session);
3487
+ if (activeBtwSession?.session === session) {
3488
+ setOverlayStatus("Stopped. BTW is ready for a new prompt.", ctx);
3489
+ }
3490
+ }
3491
+
3313
3492
  function handleBtwSessionEvent(
3314
3493
  sessionRuntime: BtwSessionRuntime,
3315
3494
  event: AgentSessionEvent,
@@ -3323,6 +3502,25 @@ export default function (pi: ExtensionAPI) {
3323
3502
  applyTranscriptEvent(transcriptState, event);
3324
3503
  persistTranscriptState();
3325
3504
 
3505
+ if (event.type === "message_end" && event.message.role === "user") {
3506
+ // AgentSession adds finalized messages to state before emitting message_end.
3507
+ // message_start arrives too early for state-based response boundaries.
3508
+ const prompt = pendingBtwPrompts.find((candidate) => candidate.messageIndex === null);
3509
+ const messageIndex = sessionRuntime.session.state.messages.indexOf(event.message);
3510
+ if (prompt && messageIndex >= sessionRuntime.sideThreadStartIndex) {
3511
+ prompt.messageIndex = messageIndex;
3512
+ }
3513
+ }
3514
+
3515
+ if (event.type === "agent_settled") {
3516
+ void persistSettledBtwPrompts(sessionRuntime, event.aborted, ctx).catch((error) => {
3517
+ const message = error instanceof Error ? error.message : String(error);
3518
+ setTranscriptFailure(transcriptState, message);
3519
+ persistTranscriptState();
3520
+ setOverlayStatus("Failed to persist BTW thread.", ctx);
3521
+ });
3522
+ }
3523
+
3326
3524
  if (!overlayRuntime) {
3327
3525
  return;
3328
3526
  }
@@ -3370,6 +3568,7 @@ export default function (pi: ExtensionAPI) {
3370
3568
  async function disposeBtwSession(): Promise<void> {
3371
3569
  const current = activeBtwSession;
3372
3570
  activeBtwSession = null;
3571
+ pendingBtwPrompts = [];
3373
3572
  if (!current) {
3374
3573
  await flushTranscriptState();
3375
3574
  return;
@@ -3625,6 +3824,10 @@ export default function (pi: ExtensionAPI) {
3625
3824
  undefined,
3626
3825
  ctx.cwd,
3627
3826
  (toolCallId) => btwStore?.readToolArtifact(toolCallId) ?? null,
3827
+ () => activeBtwSession?.session.isStreaming ?? false,
3828
+ () => {
3829
+ void stopActiveBtwRun(ctx);
3830
+ },
3628
3831
  );
3629
3832
 
3630
3833
  overlay.focused = runtime.handle?.isFocused() ?? true;
@@ -3900,6 +4103,7 @@ export default function (pi: ExtensionAPI) {
3900
4103
  ): Promise<void> {
3901
4104
  await disposeBtwSession();
3902
4105
  pendingThread = [];
4106
+ pendingBtwPrompts = [];
3903
4107
  pendingMode = mode;
3904
4108
  transcriptState = createEmptyTranscriptState();
3905
4109
  ensureBtwStore(ctx);
@@ -3917,6 +4121,7 @@ export default function (pi: ExtensionAPI) {
3917
4121
  async function restoreThread(ctx: ExtensionContext): Promise<void> {
3918
4122
  await disposeBtwSession();
3919
4123
  pendingThread = [];
4124
+ pendingBtwPrompts = [];
3920
4125
  pendingMode = "contextual";
3921
4126
  btwModelOverride = null;
3922
4127
  btwThinkingOverride = null;
@@ -4077,57 +4282,19 @@ export default function (pi: ExtensionAPI) {
4077
4282
  await ensureOverlay(ctx);
4078
4283
 
4079
4284
  try {
4080
- await session.prompt(question, { source: "extension" });
4081
-
4082
- const response = getLastAssistantMessage(session);
4083
- if (!response) {
4084
- throw new Error("BTW request finished without a response.");
4085
- }
4086
- if (response.stopReason === "aborted") {
4087
- removeTranscriptTurn(transcriptState, transcriptState.lastTurnId ?? transcriptState.currentTurnId);
4088
- persistTranscriptState();
4089
- await flushTranscriptState();
4090
- setOverlayStatus("Request aborted.", ctx);
4091
- return;
4092
- }
4093
- if (response.stopReason === "error") {
4094
- throw new Error(response.errorMessage || "BTW request failed.");
4095
- }
4096
-
4097
- const completedTurnId = transcriptState.lastTurnId ?? transcriptState.currentTurnId;
4098
- const streamedThinking =
4099
- completedTurnId !== null ? findLatestTranscriptEntry(transcriptState, completedTurnId, "thinking")?.text : "";
4100
- const answer = extractAnswer(response);
4101
- const thinking = extractThinking(response) || streamedThinking || "";
4102
-
4103
- const details: BtwDetails = {
4104
- schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
4105
- question,
4106
- thinking,
4107
- answer,
4108
- provider: model.provider,
4109
- model: model.id,
4110
- api: model.api,
4111
- thinkingLevel,
4112
- timestamp: Date.now(),
4113
- usage: response.usage,
4114
- };
4115
-
4116
- pendingThread.push(details);
4117
- pi.appendEntry(BTW_ENTRY_TYPE, details);
4118
- persistTranscriptState();
4119
- await flushTranscriptState();
4120
-
4121
- const saveState = saveVisibleBtwNote(pi, details, saveRequested, wasBusy);
4122
- if (saveState === "saved") {
4123
- notify(ctx, "Saved BTW note to the session.", "info");
4124
- setOverlayStatus("Saved BTW note to the session.", ctx);
4125
- } else if (saveState === "queued") {
4126
- notify(ctx, "BTW note queued to save after the current turn finishes.", "info");
4127
- setOverlayStatus("BTW note queued to save after the current turn finishes.", ctx);
4128
- } else {
4129
- setOverlayStatus("Ready for a follow-up. Hidden BTW thread updated.", ctx);
4130
- }
4285
+ await submitBtwPrompt(session, question, (disposition) => {
4286
+ pendingBtwPrompts.push({
4287
+ question,
4288
+ messageIndex: null,
4289
+ saveRequested,
4290
+ wasMainSessionBusy: wasBusy,
4291
+ model,
4292
+ thinkingLevel,
4293
+ });
4294
+ if (disposition === "queued") {
4295
+ setOverlayStatus("↳ steer queued after the current tool or assistant turn...", ctx);
4296
+ }
4297
+ });
4131
4298
  } catch (error) {
4132
4299
  const errorMessage = error instanceof Error ? error.message : String(error);
4133
4300
  setTranscriptFailure(transcriptState, errorMessage);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-render-btw",
3
- "version": "0.6.18",
3
+ "version": "0.6.20",
4
4
  "description": "A pi extension for parallel side conversations with /btw — with markdown rendering in the floating window",
5
5
  "type": "module",
6
6
  "license": "MIT",