pi-render-btw 0.6.18 → 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,10 @@
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
+
3
8
  ## 0.6.18 — 2026-11-20
4
9
 
5
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.
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。
@@ -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
@@ -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;
@@ -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);
@@ -1998,6 +2048,11 @@ export class BtwOverlayComponent extends Container implements Focusable {
1998
2048
  }
1999
2049
 
2000
2050
  handleInput(data: string): void {
2051
+ if (matchesKey(data, Key.ctrl("x")) && this.isBtwRunning?.()) {
2052
+ this.onStopCallback?.();
2053
+ return;
2054
+ }
2055
+
2001
2056
  if (matchesBtwFocusShortcut(data)) {
2002
2057
  this.onUnfocusCallback();
2003
2058
  return;
@@ -2201,7 +2256,8 @@ export class BtwOverlayComponent extends Container implements Focusable {
2201
2256
  this.modeText.setText(this.modeTextValue);
2202
2257
  const entries = this.readTranscriptEntries();
2203
2258
  const exchanges = getCompletedExchangeCount(entries);
2204
- const active = hasStreamingTranscriptEntry(entries) ? " · streaming" : " · idle";
2259
+ const running = this.isBtwRunning?.() ?? false;
2260
+ const active = running || hasStreamingTranscriptEntry(entries) ? " · streaming" : " · idle";
2205
2261
  this.summaryTextValue = `${exchanges} exchange${exchanges === 1 ? "" : "s"}${active}`;
2206
2262
  this.summaryText.setText(this.summaryTextValue);
2207
2263
 
@@ -2210,7 +2266,9 @@ export class BtwOverlayComponent extends Container implements Focusable {
2210
2266
  const status = this.getStatus() ?? "Ready. Enter submits; Escape dismisses without clearing.";
2211
2267
  this.statusTextValue = status;
2212
2268
  this.statusText.setText(this.statusTextValue);
2213
- 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";
2214
2272
  this.hintsText.setText(this.hintsTextValue);
2215
2273
  this.tui.requestRender();
2216
2274
  }
@@ -3104,6 +3162,7 @@ export class BtwOverlayComponent extends Container implements Focusable {
3104
3162
 
3105
3163
  export default function (pi: ExtensionAPI) {
3106
3164
  let pendingThread: BtwDetails[] = [];
3165
+ let pendingBtwPrompts: BtwPendingPrompt[] = [];
3107
3166
  let pendingMode: BtwThreadMode = "contextual";
3108
3167
  let btwModelOverride: SessionModel | null = null;
3109
3168
  let btwThinkingOverride: SessionThinkingLevel | null = null;
@@ -3310,6 +3369,104 @@ export default function (pi: ExtensionAPI) {
3310
3369
  }
3311
3370
  }
3312
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
+
3313
3470
  function handleBtwSessionEvent(
3314
3471
  sessionRuntime: BtwSessionRuntime,
3315
3472
  event: AgentSessionEvent,
@@ -3323,6 +3480,25 @@ export default function (pi: ExtensionAPI) {
3323
3480
  applyTranscriptEvent(transcriptState, event);
3324
3481
  persistTranscriptState();
3325
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
+
3326
3502
  if (!overlayRuntime) {
3327
3503
  return;
3328
3504
  }
@@ -3370,6 +3546,7 @@ export default function (pi: ExtensionAPI) {
3370
3546
  async function disposeBtwSession(): Promise<void> {
3371
3547
  const current = activeBtwSession;
3372
3548
  activeBtwSession = null;
3549
+ pendingBtwPrompts = [];
3373
3550
  if (!current) {
3374
3551
  await flushTranscriptState();
3375
3552
  return;
@@ -3625,6 +3802,10 @@ export default function (pi: ExtensionAPI) {
3625
3802
  undefined,
3626
3803
  ctx.cwd,
3627
3804
  (toolCallId) => btwStore?.readToolArtifact(toolCallId) ?? null,
3805
+ () => activeBtwSession?.session.isStreaming ?? false,
3806
+ () => {
3807
+ void stopActiveBtwRun(ctx);
3808
+ },
3628
3809
  );
3629
3810
 
3630
3811
  overlay.focused = runtime.handle?.isFocused() ?? true;
@@ -3900,6 +4081,7 @@ export default function (pi: ExtensionAPI) {
3900
4081
  ): Promise<void> {
3901
4082
  await disposeBtwSession();
3902
4083
  pendingThread = [];
4084
+ pendingBtwPrompts = [];
3903
4085
  pendingMode = mode;
3904
4086
  transcriptState = createEmptyTranscriptState();
3905
4087
  ensureBtwStore(ctx);
@@ -3917,6 +4099,7 @@ export default function (pi: ExtensionAPI) {
3917
4099
  async function restoreThread(ctx: ExtensionContext): Promise<void> {
3918
4100
  await disposeBtwSession();
3919
4101
  pendingThread = [];
4102
+ pendingBtwPrompts = [];
3920
4103
  pendingMode = "contextual";
3921
4104
  btwModelOverride = null;
3922
4105
  btwThinkingOverride = null;
@@ -4077,57 +4260,19 @@ export default function (pi: ExtensionAPI) {
4077
4260
  await ensureOverlay(ctx);
4078
4261
 
4079
4262
  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
- }
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
+ });
4131
4276
  } catch (error) {
4132
4277
  const errorMessage = error instanceof Error ? error.message : String(error);
4133
4278
  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.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",