pi-render-btw 0.6.17 → 0.6.19

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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.19 — 2026-11-23
4
+
5
+ - Fix BTW prompts submitted during streaming by always routing them as steering input, including rapid submits that race the first run's startup.
6
+ - 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.
7
+
8
+ ## 0.6.18 — 2026-11-20
9
+
10
+ - 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.
11
+
3
12
  ## 0.6.17 — 2026-09-18
4
13
 
5
14
  - Add clickable `[preview]` actions beside `[Esc]` in BTW and BTW Peek for opening the focused tool's read-only Tool Output.
package/README.md CHANGED
@@ -93,6 +93,8 @@ 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
96
98
  - `Ctrl+Alt+W` is a fallback focus toggle for terminals that do not deliver `Alt+/` as a usable shortcut
97
99
  - `Ctrl+G` opens the current BTW draft in `$VISUAL`/`$EDITOR` (falling back to `nano`) and reads it back when the editor exits successfully
98
100
  - 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,23 @@
1
+ import { buildSessionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { Message } from "@earendil-works/pi-ai";
3
+ import { describe, expect, it } from "vitest";
4
+ import { createBtwSessionManager } from "./btw.ts";
5
+
6
+ function userMessage(text: string): Message {
7
+ return {
8
+ role: "user",
9
+ content: [{ type: "text", text }],
10
+ timestamp: 0,
11
+ };
12
+ }
13
+
14
+ describe("BTW contextual seed", () => {
15
+ it("persists the main-session seed in the sub-session manager", () => {
16
+ const seed = [userMessage("MAIN_SESSION_CONTEXT_SENTINEL")];
17
+ const sessionManager = createBtwSessionManager(seed);
18
+
19
+ const context = buildSessionContext(sessionManager.getEntries(), sessionManager.getLeafId());
20
+
21
+ expect(context.messages).toEqual(seed);
22
+ });
23
+ });
@@ -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
  () => {},
@@ -684,6 +685,88 @@ describe("BTW transcript message layout", () => {
684
685
  expect(output).toContain("(no output)");
685
686
  });
686
687
 
688
+ it("steers a busy BTW session instead of prompting without streaming behavior", async () => {
689
+ const calls: Array<{ text: string; behavior: string | undefined }> = [];
690
+ const accepted: string[] = [];
691
+ const session = {
692
+ isStreaming: true,
693
+ prompt: async (text: string, options?: { streamingBehavior?: string; preflightResult?: (value: "started" | "queued" | "handled") => void }) => {
694
+ calls.push({ text, behavior: options?.streamingBehavior });
695
+ options?.preflightResult?.("queued");
696
+ },
697
+ } as unknown as Pick<AgentSession, "isStreaming" | "prompt">;
698
+
699
+ await submitBtwPrompt(session, "steer this", (disposition) => accepted.push(disposition));
700
+
701
+ expect(calls).toEqual([{ text: "steer this", behavior: "steer" }]);
702
+ expect(accepted).toEqual(["queued"]);
703
+ });
704
+
705
+ it("supplies steer behavior from idle state to close rapid-submit races", async () => {
706
+ let behavior: string | undefined;
707
+ const session = {
708
+ isStreaming: false,
709
+ prompt: async (_text: string, options?: { streamingBehavior?: string; preflightResult?: (value: "started" | "queued" | "handled") => void }) => {
710
+ behavior = options?.streamingBehavior;
711
+ options?.preflightResult?.("started");
712
+ },
713
+ } as unknown as Pick<AgentSession, "isStreaming" | "prompt">;
714
+
715
+ await submitBtwPrompt(session, "first rapid prompt", () => {});
716
+
717
+ expect(behavior).toBe("steer");
718
+ });
719
+
720
+ it("stops only an active BTW run and clears its queued prompts", async () => {
721
+ const calls: string[] = [];
722
+ const active = {
723
+ isStreaming: true,
724
+ clearQueue: () => { calls.push("clearQueue"); return { steering: [], followUp: [] }; },
725
+ abort: async () => { calls.push("abort"); },
726
+ } as unknown as Pick<AgentSession, "isStreaming" | "clearQueue" | "abort">;
727
+ const idle = {
728
+ isStreaming: false,
729
+ clearQueue: () => { calls.push("idle-clearQueue"); return { steering: [], followUp: [] }; },
730
+ abort: async () => { calls.push("idle-abort"); },
731
+ } as unknown as Pick<AgentSession, "isStreaming" | "clearQueue" | "abort">;
732
+
733
+ await expect(stopBtwRun(active)).resolves.toBe(true);
734
+ await expect(stopBtwRun(idle)).resolves.toBe(false);
735
+
736
+ expect(calls).toEqual(["clearQueue", "abort"]);
737
+ });
738
+
739
+ it("uses Ctrl+X to stop an active BTW run without dismissing the overlay", () => {
740
+ let submitted = "";
741
+ let dismissed = 0;
742
+ let stopRequests = 0;
743
+ const component = new BtwOverlayComponent(
744
+ tui,
745
+ theme,
746
+ keybindings,
747
+ () => [],
748
+ () => null,
749
+ () => "contextual",
750
+ (value) => { submitted = value; },
751
+ () => { dismissed++; },
752
+ () => {},
753
+ undefined,
754
+ undefined,
755
+ undefined,
756
+ () => true,
757
+ () => { stopRequests++; },
758
+ );
759
+
760
+ component.handleInput("\x18"); // Ctrl+X
761
+ expect(stopRequests).toBe(1);
762
+ expect(dismissed).toBe(0);
763
+ expect(component.render(80).join("\n")).toContain("Ctrl+X stop");
764
+
765
+ component.setDraft("still usable");
766
+ component.handleInput("\r");
767
+ expect(submitted).toBe("still usable");
768
+ });
769
+
687
770
  it("keeps Enter and Escape composer behavior outside Peek", () => {
688
771
  let submitted = "";
689
772
  let dismissed = 0;
package/extensions/btw.ts CHANGED
@@ -444,6 +444,18 @@ function buildBtwSeedState(
444
444
  };
445
445
  }
446
446
 
447
+ /**
448
+ * Own the BTW seed in its SessionManager so Pi can reconstruct it for the
449
+ * next model request. Kept as a small seam for context-related regressions.
450
+ */
451
+ export function createBtwSessionManager(seedMessages: readonly Message[]): SessionManager {
452
+ const sessionManager = SessionManager.inMemory();
453
+ for (const message of seedMessages) {
454
+ sessionManager.appendMessage(message);
455
+ }
456
+ return sessionManager;
457
+ }
458
+
447
459
  function extractToolText(value: unknown): string | undefined {
448
460
  if (Array.isArray(value)) {
449
461
  const text = value
@@ -1063,6 +1075,17 @@ type BtwHandoffExchange = {
1063
1075
  assistant: string;
1064
1076
  };
1065
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
+
1066
1089
  function buildBtwMessageContent(question: string, answer: string): string {
1067
1090
  return `Q: ${question}\n\nA: ${answer}`;
1068
1091
  }
@@ -1082,9 +1105,12 @@ function isThreadContinuationMarker(messages: Message[], index: number): boolean
1082
1105
  );
1083
1106
  }
1084
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
+
1085
1113
  function extractBtwHandoffThread(sessionRuntime: BtwSessionRuntime): BtwHandoffExchange[] {
1086
- const handoffMessages = sessionRuntime.session.state.messages.slice(sessionRuntime.sideThreadStartIndex);
1087
- const threadMessages = isThreadContinuationMarker(handoffMessages as Message[], 0) ? handoffMessages.slice(2) : handoffMessages;
1088
1114
  const exchanges: BtwHandoffExchange[] = [];
1089
1115
  let currentUser = "";
1090
1116
  let currentAssistant = "";
@@ -1102,7 +1128,7 @@ function extractBtwHandoffThread(sessionRuntime: BtwSessionRuntime): BtwHandoffE
1102
1128
  currentAssistant = "";
1103
1129
  };
1104
1130
 
1105
- for (const message of threadMessages) {
1131
+ for (const message of getBtwThreadMessages(sessionRuntime)) {
1106
1132
  if (message.role !== "user" && message.role !== "assistant") {
1107
1133
  continue;
1108
1134
  }
@@ -1125,6 +1151,36 @@ function extractBtwHandoffThread(sessionRuntime: BtwSessionRuntime): BtwHandoffE
1125
1151
  return exchanges;
1126
1152
  }
1127
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
+
1128
1184
  function saveVisibleBtwNote(
1129
1185
  pi: ExtensionAPI,
1130
1186
  details: BtwDetails,
@@ -1191,6 +1247,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1191
1247
  private readonly onUnfocusCallback: () => void;
1192
1248
  private readonly onExternalEditorCallback?: () => void;
1193
1249
  private readonly readToolArtifact?: (toolCallId: string) => ToolArtifact | null;
1250
+ private readonly isBtwRunning?: () => boolean;
1251
+ private readonly onStopCallback?: () => void;
1194
1252
  /** BTW keeps its own recall cursor so Alt+Up works even when host history bindings are unset. */
1195
1253
  private draftHistory: string[] = [];
1196
1254
  private draftHistoryIndex = -1;
@@ -1265,6 +1323,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1265
1323
  onExternalEditor?: () => void,
1266
1324
  cwd?: string,
1267
1325
  readToolArtifact?: (toolCallId: string) => ToolArtifact | null,
1326
+ isBtwRunning?: () => boolean,
1327
+ onStop?: () => void,
1268
1328
  ) {
1269
1329
  super();
1270
1330
  this.tui = tui;
@@ -1277,6 +1337,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
1277
1337
  this.onUnfocusCallback = onUnfocus;
1278
1338
  this.onExternalEditorCallback = onExternalEditor;
1279
1339
  this.readToolArtifact = readToolArtifact;
1340
+ this.isBtwRunning = isBtwRunning;
1341
+ this.onStopCallback = onStop;
1280
1342
 
1281
1343
  this.modeText = new Text("", 1, 0);
1282
1344
  this.summaryText = new Text("", 1, 0);
@@ -1986,6 +2048,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
1986
2048
  }
1987
2049
 
1988
2050
  handleInput(data: string): void {
2051
+ if (matchesKey(data, Key.ctrl("x")) && this.isBtwRunning?.()) {
2052
+ this.onStopCallback?.();
2053
+ return;
2054
+ }
2055
+
1989
2056
  if (matchesBtwFocusShortcut(data)) {
1990
2057
  this.onUnfocusCallback();
1991
2058
  return;
@@ -2189,7 +2256,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
2189
2256
  this.modeText.setText(this.modeTextValue);
2190
2257
  const entries = this.readTranscriptEntries();
2191
2258
  const exchanges = getCompletedExchangeCount(entries);
2192
- const active = hasStreamingTranscriptEntry(entries) ? " · streaming" : " · idle";
2259
+ const running = this.isBtwRunning?.() ?? false;
2260
+ const active = running || hasStreamingTranscriptEntry(entries) ? " · streaming" : " · idle";
2193
2261
  this.summaryTextValue = `${exchanges} exchange${exchanges === 1 ? "" : "s"}${active}`;
2194
2262
  this.summaryText.setText(this.summaryTextValue);
2195
2263
 
@@ -2198,7 +2266,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
2198
2266
  const status = this.getStatus() ?? "Ready. Enter submits; Escape dismisses without clearing.";
2199
2267
  this.statusTextValue = status;
2200
2268
  this.statusText.setText(this.statusTextValue);
2201
- this.hintsTextValue = "Scroll wheel ↑↓ PgUp/PgDn · Enter · Ctrl+P peek · Alt+/ focus · Esc";
2269
+ this.hintsTextValue = running
2270
+ ? "Scroll wheel ↑↓ PgUp/PgDn · Enter steer · Ctrl+X stop · Ctrl+P peek · Alt+/ focus · Esc"
2271
+ : "Scroll wheel ↑↓ PgUp/PgDn · Enter submit · Ctrl+P peek · Alt+/ focus · Esc";
2202
2272
  this.hintsText.setText(this.hintsTextValue);
2203
2273
  this.tui.requestRender();
2204
2274
  }
@@ -3092,6 +3162,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
3092
3162
 
3093
3163
  export default function (pi: ExtensionAPI) {
3094
3164
  let pendingThread: BtwDetails[] = [];
3165
+ let pendingBtwPrompts: BtwPendingPrompt[] = [];
3095
3166
  let pendingMode: BtwThreadMode = "contextual";
3096
3167
  let btwModelOverride: SessionModel | null = null;
3097
3168
  let btwThinkingOverride: SessionThinkingLevel | null = null;
@@ -3298,6 +3369,104 @@ export default function (pi: ExtensionAPI) {
3298
3369
  }
3299
3370
  }
3300
3371
 
3372
+ async function persistSettledBtwPrompts(
3373
+ sessionRuntime: BtwSessionRuntime,
3374
+ aborted: boolean,
3375
+ ctx?: ExtensionContext | ExtensionCommandContext,
3376
+ ): Promise<void> {
3377
+ if (activeBtwSession?.session !== sessionRuntime.session) {
3378
+ return;
3379
+ }
3380
+
3381
+ if (aborted) {
3382
+ pendingBtwPrompts = [];
3383
+ if (closeRestoredStreamingTurns(transcriptState)) {
3384
+ persistTranscriptState();
3385
+ await flushTranscriptState();
3386
+ }
3387
+ setOverlayStatus("Stopped. BTW is ready for a new prompt.", ctx);
3388
+ return;
3389
+ }
3390
+
3391
+ const prompts = pendingBtwPrompts;
3392
+ pendingBtwPrompts = [];
3393
+ const messages = sessionRuntime.session.state.messages as Message[];
3394
+ let saveState: SaveState = "not-saved";
3395
+
3396
+ for (let index = 0; index < prompts.length; index++) {
3397
+ const prompt = prompts[index];
3398
+ if (prompt.messageIndex === null) {
3399
+ continue;
3400
+ }
3401
+
3402
+ const nextPromptIndex = prompts.slice(index + 1).find((candidate) => candidate.messageIndex !== null)?.messageIndex;
3403
+ const endIndex = nextPromptIndex ?? messages.length;
3404
+ let response: AssistantMessage | null = null;
3405
+ for (let messageIndex = endIndex - 1; messageIndex > prompt.messageIndex; messageIndex--) {
3406
+ const message = messages[messageIndex];
3407
+ if (message?.role === "assistant") {
3408
+ response = message as AssistantMessage;
3409
+ break;
3410
+ }
3411
+ }
3412
+
3413
+ if (!response) {
3414
+ continue;
3415
+ }
3416
+ if (response.stopReason === "error") {
3417
+ setTranscriptFailure(transcriptState, response.errorMessage || "BTW request failed.");
3418
+ continue;
3419
+ }
3420
+
3421
+ const submittedMessage = messages[prompt.messageIndex];
3422
+ const question = submittedMessage ? extractMessageText(submittedMessage).trim() || prompt.question : prompt.question;
3423
+ const details: BtwDetails = {
3424
+ schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
3425
+ question,
3426
+ thinking: extractThinking(response),
3427
+ answer: extractAnswer(response),
3428
+ provider: prompt.model.provider,
3429
+ model: prompt.model.id,
3430
+ api: prompt.model.api,
3431
+ thinkingLevel: prompt.thinkingLevel,
3432
+ timestamp: Date.now(),
3433
+ usage: response.usage,
3434
+ };
3435
+ pendingThread.push(details);
3436
+ pi.appendEntry(BTW_ENTRY_TYPE, details);
3437
+ const nextSaveState = saveVisibleBtwNote(pi, details, prompt.saveRequested, prompt.wasMainSessionBusy);
3438
+ if (nextSaveState !== "not-saved") {
3439
+ saveState = nextSaveState;
3440
+ }
3441
+ }
3442
+
3443
+ persistTranscriptState();
3444
+ await flushTranscriptState();
3445
+
3446
+ if (saveState === "saved") {
3447
+ if (ctx) notify(ctx, "Saved BTW note to the session.", "info");
3448
+ setOverlayStatus("Saved BTW note to the session.", ctx);
3449
+ } else if (saveState === "queued") {
3450
+ if (ctx) notify(ctx, "BTW note queued to save after the current turn finishes.", "info");
3451
+ setOverlayStatus("BTW note queued to save after the current turn finishes.", ctx);
3452
+ } else {
3453
+ setOverlayStatus("Ready for a follow-up. Hidden BTW thread updated.", ctx);
3454
+ }
3455
+ }
3456
+
3457
+ async function stopActiveBtwRun(ctx: ExtensionContext | ExtensionCommandContext): Promise<void> {
3458
+ const session = activeBtwSession?.session;
3459
+ if (!session || !session.isStreaming) {
3460
+ return;
3461
+ }
3462
+
3463
+ setOverlayStatus("⏹ stopping BTW agent and tool output...", ctx);
3464
+ await stopBtwRun(session);
3465
+ if (activeBtwSession?.session === session) {
3466
+ setOverlayStatus("Stopped. BTW is ready for a new prompt.", ctx);
3467
+ }
3468
+ }
3469
+
3301
3470
  function handleBtwSessionEvent(
3302
3471
  sessionRuntime: BtwSessionRuntime,
3303
3472
  event: AgentSessionEvent,
@@ -3311,6 +3480,25 @@ export default function (pi: ExtensionAPI) {
3311
3480
  applyTranscriptEvent(transcriptState, event);
3312
3481
  persistTranscriptState();
3313
3482
 
3483
+ if (event.type === "message_end" && event.message.role === "user") {
3484
+ // AgentSession adds finalized messages to state before emitting message_end.
3485
+ // message_start arrives too early for state-based response boundaries.
3486
+ const prompt = pendingBtwPrompts.find((candidate) => candidate.messageIndex === null);
3487
+ const messageIndex = sessionRuntime.session.state.messages.indexOf(event.message);
3488
+ if (prompt && messageIndex >= sessionRuntime.sideThreadStartIndex) {
3489
+ prompt.messageIndex = messageIndex;
3490
+ }
3491
+ }
3492
+
3493
+ if (event.type === "agent_settled") {
3494
+ void persistSettledBtwPrompts(sessionRuntime, event.aborted, ctx).catch((error) => {
3495
+ const message = error instanceof Error ? error.message : String(error);
3496
+ setTranscriptFailure(transcriptState, message);
3497
+ persistTranscriptState();
3498
+ setOverlayStatus("Failed to persist BTW thread.", ctx);
3499
+ });
3500
+ }
3501
+
3314
3502
  if (!overlayRuntime) {
3315
3503
  return;
3316
3504
  }
@@ -3358,6 +3546,7 @@ export default function (pi: ExtensionAPI) {
3358
3546
  async function disposeBtwSession(): Promise<void> {
3359
3547
  const current = activeBtwSession;
3360
3548
  activeBtwSession = null;
3549
+ pendingBtwPrompts = [];
3361
3550
  if (!current) {
3362
3551
  await flushTranscriptState();
3363
3552
  return;
@@ -3519,11 +3708,13 @@ export default function (pi: ExtensionAPI) {
3519
3708
  }
3520
3709
 
3521
3710
  const parentModelRuntime = (ctx.modelRegistry as unknown as { runtime?: ModelRuntime | null }).runtime ?? undefined;
3711
+ const { messages: seedMessages, sideThreadStartIndex } = buildBtwSeedState(ctx, pendingThread, mode, settings.model);
3712
+ const sessionManager = createBtwSessionManager(seedMessages);
3522
3713
  const sessionOptions: Parameters<typeof createAgentSession>[0] & {
3523
3714
  modelRegistry?: ExtensionContext["modelRegistry"];
3524
3715
  modelRuntime?: ModelRuntime;
3525
3716
  } = {
3526
- sessionManager: SessionManager.inMemory(),
3717
+ sessionManager,
3527
3718
  model: settings.model,
3528
3719
  ...(parentModelRuntime !== undefined && { modelRuntime: parentModelRuntime }),
3529
3720
  thinkingLevel: settings.thinkingLevel,
@@ -3535,11 +3726,6 @@ export default function (pi: ExtensionAPI) {
3535
3726
  };
3536
3727
  const { session } = await createAgentSession(sessionOptions);
3537
3728
 
3538
- const { messages: seedMessages, sideThreadStartIndex } = buildBtwSeedState(ctx, pendingThread, mode, settings.model);
3539
- if (seedMessages.length > 0) {
3540
- session.agent.state.messages = seedMessages as typeof session.state.messages;
3541
- }
3542
-
3543
3729
  return { session, mode, subscriptions: new Set(), sideThreadStartIndex };
3544
3730
  }
3545
3731
 
@@ -3616,6 +3802,10 @@ export default function (pi: ExtensionAPI) {
3616
3802
  undefined,
3617
3803
  ctx.cwd,
3618
3804
  (toolCallId) => btwStore?.readToolArtifact(toolCallId) ?? null,
3805
+ () => activeBtwSession?.session.isStreaming ?? false,
3806
+ () => {
3807
+ void stopActiveBtwRun(ctx);
3808
+ },
3619
3809
  );
3620
3810
 
3621
3811
  overlay.focused = runtime.handle?.isFocused() ?? true;
@@ -3891,6 +4081,7 @@ export default function (pi: ExtensionAPI) {
3891
4081
  ): Promise<void> {
3892
4082
  await disposeBtwSession();
3893
4083
  pendingThread = [];
4084
+ pendingBtwPrompts = [];
3894
4085
  pendingMode = mode;
3895
4086
  transcriptState = createEmptyTranscriptState();
3896
4087
  ensureBtwStore(ctx);
@@ -3908,6 +4099,7 @@ export default function (pi: ExtensionAPI) {
3908
4099
  async function restoreThread(ctx: ExtensionContext): Promise<void> {
3909
4100
  await disposeBtwSession();
3910
4101
  pendingThread = [];
4102
+ pendingBtwPrompts = [];
3911
4103
  pendingMode = "contextual";
3912
4104
  btwModelOverride = null;
3913
4105
  btwThinkingOverride = null;
@@ -4068,57 +4260,19 @@ export default function (pi: ExtensionAPI) {
4068
4260
  await ensureOverlay(ctx);
4069
4261
 
4070
4262
  try {
4071
- await session.prompt(question, { source: "extension" });
4072
-
4073
- const response = getLastAssistantMessage(session);
4074
- if (!response) {
4075
- throw new Error("BTW request finished without a response.");
4076
- }
4077
- if (response.stopReason === "aborted") {
4078
- removeTranscriptTurn(transcriptState, transcriptState.lastTurnId ?? transcriptState.currentTurnId);
4079
- persistTranscriptState();
4080
- await flushTranscriptState();
4081
- setOverlayStatus("Request aborted.", ctx);
4082
- return;
4083
- }
4084
- if (response.stopReason === "error") {
4085
- throw new Error(response.errorMessage || "BTW request failed.");
4086
- }
4087
-
4088
- const completedTurnId = transcriptState.lastTurnId ?? transcriptState.currentTurnId;
4089
- const streamedThinking =
4090
- completedTurnId !== null ? findLatestTranscriptEntry(transcriptState, completedTurnId, "thinking")?.text : "";
4091
- const answer = extractAnswer(response);
4092
- const thinking = extractThinking(response) || streamedThinking || "";
4093
-
4094
- const details: BtwDetails = {
4095
- schemaVersion: BTW_TRANSCRIPT_SCHEMA_VERSION,
4096
- question,
4097
- thinking,
4098
- answer,
4099
- provider: model.provider,
4100
- model: model.id,
4101
- api: model.api,
4102
- thinkingLevel,
4103
- timestamp: Date.now(),
4104
- usage: response.usage,
4105
- };
4106
-
4107
- pendingThread.push(details);
4108
- pi.appendEntry(BTW_ENTRY_TYPE, details);
4109
- persistTranscriptState();
4110
- await flushTranscriptState();
4111
-
4112
- const saveState = saveVisibleBtwNote(pi, details, saveRequested, wasBusy);
4113
- if (saveState === "saved") {
4114
- notify(ctx, "Saved BTW note to the session.", "info");
4115
- setOverlayStatus("Saved BTW note to the session.", ctx);
4116
- } else if (saveState === "queued") {
4117
- notify(ctx, "BTW note queued to save after the current turn finishes.", "info");
4118
- setOverlayStatus("BTW note queued to save after the current turn finishes.", ctx);
4119
- } else {
4120
- setOverlayStatus("Ready for a follow-up. Hidden BTW thread updated.", ctx);
4121
- }
4263
+ await submitBtwPrompt(session, question, (disposition) => {
4264
+ pendingBtwPrompts.push({
4265
+ question,
4266
+ messageIndex: null,
4267
+ saveRequested,
4268
+ wasMainSessionBusy: wasBusy,
4269
+ model,
4270
+ thinkingLevel,
4271
+ });
4272
+ if (disposition === "queued") {
4273
+ setOverlayStatus("↳ steer queued after the current tool or assistant turn...", ctx);
4274
+ }
4275
+ });
4122
4276
  } catch (error) {
4123
4277
  const errorMessage = error instanceof Error ? error.message : String(error);
4124
4278
  setTranscriptFailure(transcriptState, errorMessage);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-render-btw",
3
- "version": "0.6.17",
3
+ "version": "0.6.19",
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",