@narumitw/pi-btw 0.61.1 → 0.62.0

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/docs/workflows.md CHANGED
@@ -17,43 +17,56 @@ Opening and closing without a new result does not reorder them.
17
17
 
18
18
  ## Read, select, and search
19
19
 
20
- The dedicated workspace keeps answers above the editor and identifies itself with a fixed `btw · side thread` header.
20
+ The dedicated workspace places the scrollable transcript above pending questions, the editor, and a compact footer.
21
+ The footer identifies BTW and shows the selected side model and thinking level when space permits; a split workspace also shows **BTW focus** or **Main focus**.
22
+ Reachable shortcut hints appear below the editor, not above it.
23
+ At constrained sizes, the active input cursor takes priority over queue previews, metadata, and hints; zero-sized views remain empty.
24
+ The [appearance reference](./native-appearance.md) records native-default comparisons and limits.
21
25
  The default **Fullscreen** layout gives the side thread the complete workspace.
22
26
  **Side thread left** and **Side thread right** place it beside Pi's native, live main-thread rendering; terminals narrower than 80 columns show only the side thread.
23
- A single muted divider separates the panes; click either pane to move keyboard focus to it.
27
+ A single muted divider separates the panes; click either pane or use the displayed pane-switch key to move keyboard focus.
28
+ By default, the switch key is the first usable F6, F7, or F8; it can be changed in [Keybindings](../README.md#keybindings).
29
+ Nested overlays keep their input ownership and block background pane switching.
24
30
  Drag the divider with the primary mouse button to resize the side thread between 20% and 80% of the workspace.
25
31
  Releasing the button saves that side-thread ratio for either pane placement; a failed save restores the last saved width and reports the error.
26
32
  Pi's search and keyboard viewport controls apply to the active pane.
27
33
  The mouse wheel scrolls the pane under the pointer without moving keyboard focus, and a narrow terminal returns focus to the visible side thread.
28
34
  A branch selected through **Start from main thread tree…** supplies side-model context but does not replace the active main thread shown in the other pane.
29
35
  The main agent may keep running, and the main pane redraws its progress while either pane is active.
30
- Submit each question with Enter; successful prior questions and answers remain available to the side model.
36
+ Submit each question with Pi's effective editor submission binding, Enter by default; successful prior questions and answers remain available to the side model.
31
37
 
32
38
  Drag the primary mouse button across the transcript to select text.
33
39
  Automatic selection copying requests Pi's host clipboard helper immediately and is enabled by default.
34
40
  With **Copy selection automatically** off, the selection stays highlighted and Pi's effective `app.message.copy` binding copies it.
35
41
  Manual copying requires Pi's fullscreen selection APIs; if unavailable, pi-btw restores the main TUI and asks you to update Pi or re-enable automatic copying.
36
- The view reports `No selection to copy`, `Copied!`, or `Copy failed` for the request; actual clipboard access still depends on the operating system and terminal.
42
+ The view reports `No selection to copy`, `Copied!`, or a sanitized clipboard error for the request; actual clipboard access still depends on the operating system and terminal.
43
+ Right-click clipboard paste is not installed because Pi has no public clipboard-read callback for this workspace.
37
44
  Ctrl+C always cancels the side flow, even if `app.message.copy` is also mapped to Ctrl+C.
38
45
 
39
- Press `Ctrl+Shift+F` to search completed or in-progress transcript text, excluding the fixed header and footer.
40
- Enter or `Ctrl+G` finds the next match; `Shift+Enter` or `Ctrl+Shift+G` finds the previous match.
41
- Escape closes search and returns focus to the composer.
46
+ Use Pi's effective transcript-search binding (`Ctrl+Shift+F` by default) to search completed or in-progress transcript text, excluding the footer.
47
+ The default next-match keys are Enter or `Ctrl+G`; previous-match keys are `Shift+Enter` or `Ctrl+Shift+G`.
48
+ Pi's effective search-close binding, Escape by default, closes search and returns focus to the composer.
42
49
 
43
- Scroll with the mouse wheel, trackpad, or `PgUp`/`PgDn`.
50
+ Scroll with the mouse wheel, trackpad, or Pi's effective viewport paging bindings (`PgUp`/`PgDn` by default).
51
+ Remapped or disabled bindings control behavior; the composer does not retain hidden literal paging shortcuts.
52
+ The native transcript uses automatic scrollbars and previous/next-message navigation metadata.
53
+ Manual scrolling stays fixed during incoming output, resize, and temporary content fits; explicitly returning to the latest content resumes follow mode.
44
54
  On Pi 0.85 or newer, scrolling away from the latest content reveals **Jump to latest message**.
45
- Click it or use Pi's effective `tui.altScreen.bottom` binding (`End` by default) to resume following new output.
55
+ Click it or use Pi's effective `tui.altScreen.bottom` binding (`Ctrl+End` by default) to resume following new output.
46
56
 
47
57
  ## Thinking and queued questions
48
58
 
49
- The header shows the current side-thread thinking level.
50
- Use the thinking-cycle shortcut shown in the composer to cycle supported levels for later questions.
59
+ The footer shows the current side-thread thinking level when space permits.
60
+ Use the thinking-cycle shortcut shown below the editor to cycle supported levels for later questions.
51
61
  It inherits Pi's `app.thinking.cycle` (`Shift+Tab` by default) unless overridden in [Keybindings](../README.md#keybindings).
52
62
  Whether that change is remembered depends on [Settings](../README.md#-settings); it never changes the main session's thinking level.
53
63
 
54
- During a response, submit another question to queue it as `Steering`.
64
+ During a response, the editor's top border shows `Answering…` with a spinner.
65
+ Submit another question to queue it as `Steering next`.
55
66
  Queued questions run in order after the current response, using the thinking level effective when each turn starts.
67
+ They do not interrupt the current provider response or enter Pi's main-session steering/follow-up queue.
56
68
  A failed response remains visible without discarding later queued questions.
69
+ The bounded preview above the editor shows queued questions in order and an omitted-item count when needed.
57
70
  Steering does not append to the main conversation or editor.
58
71
 
59
72
  The configured exit shortcut, or the permanent Ctrl+C hard-cancel key, cancels the active response and discards the current draft and steering queue.
@@ -63,7 +76,8 @@ Completed questions, answers, and visible errors remain resumable until the exte
63
76
 
64
77
  After a successful answer, use the bring-to-main shortcut (`Ctrl+R` by default) to choose the latest question and answer, everything from one question onward, an exact range, or the full thread.
65
78
  The scope chooser reports the latest exchange and full-thread sizes.
66
- Question-suffix, exact-range, and full-thread choices preview an editable context block before closing the side thread.
79
+ Question-suffix, exact-range, and full-thread choices show an exact, read-only preview before closing the side thread.
80
+ The context block is editable after it is loaded into the main editor.
67
81
  Escape returns; Ctrl+C closes without bringing context back.
68
82
 
69
83
  The exact-range selector works on raw source text, not terminal-wrapped rows, and reports line, message, and approximate token counts.
@@ -80,3 +94,10 @@ The success message reports whether context was loaded, appended, or replaced an
80
94
  Without an explicit bring action, closing `/btw` never changes the main conversation.
81
95
  Resume state is memory-only: `/new`, Pi `/resume`, `/reload`, extension replacement, and process restart discard it.
82
96
  Unsent drafts, steering queues, interrupted answers, and model credentials are not retained.
97
+
98
+ ## Core compatibility and verification
99
+
100
+ The [core-alignment handoff](./core-alignment.md) records finding dispositions, deterministic evidence, retained workspace deviations, and proposed Pi APIs.
101
+ The [appearance reference](./native-appearance.md) contains native CLI reference frames, before/after BTW frames, public API reuse decisions, and terminal-review instructions.
102
+ The package-directory smoke is non-interactive and does not contact a provider.
103
+ Terminal-specific mouse, clipboard, IME, keyboard-protocol, and visual acceptance still require a terminal operator.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-btw",
3
- "version": "0.61.1",
3
+ "version": "0.62.0",
4
4
  "description": "Pi extension that adds a /btw side-question command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,9 +32,9 @@
32
32
  "prepack": "npm run build"
33
33
  },
34
34
  "devDependencies": {
35
- "@earendil-works/pi-ai": "0.87.1",
36
- "@earendil-works/pi-coding-agent": "0.87.1",
37
- "@earendil-works/pi-tui": "0.87.1",
35
+ "@earendil-works/pi-ai": "1.3.0",
36
+ "@earendil-works/pi-coding-agent": "1.3.0",
37
+ "@earendil-works/pi-tui": "1.3.0",
38
38
  "esbuild": "0.28.2",
39
39
  "typescript": "7.0.2"
40
40
  },
package/src/btw.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  getAnsweredTurns,
13
13
  summarizeBringToMain,
14
14
  } from "./bring-to-main.js";
15
+ import type { BtwDisplayModel } from "./conversation-chrome.js";
15
16
  import { buildConversationContext } from "./conversation-context.js";
16
17
  import { type RunBtwFullscreen, runBtwFullscreen } from "./fullscreen-ui.js";
17
18
  import { registerBtwMainThreadUpdates } from "./main-thread-updates.js";
@@ -23,6 +24,7 @@ import {
23
24
  showBtwCommandMenu,
24
25
  showBtwCustomPreservingEditor,
25
26
  } from "./menu.js";
27
+ import { type BtwSessionLifetime, registerBtwSessionLifetimes } from "./session-lifetime.js";
26
28
  import {
27
29
  type BtwSettings,
28
30
  effectiveBtwLayout,
@@ -178,6 +180,7 @@ function notifySafely(
178
180
  message: string,
179
181
  level: Parameters<ExtensionCommandContext["ui"]["notify"]>[1],
180
182
  ): void {
183
+ if (ctx.signal?.aborted) return;
181
184
  try {
182
185
  ctx.ui.notify(sanitizeSingleLine(message), level);
183
186
  } catch {
@@ -209,10 +212,10 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
209
212
  const runThread = dependencies.runThread ?? runBtwThread;
210
213
  const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;
211
214
  const subscribeMainThreadUpdates = registerBtwMainThreadUpdates(pi);
212
- // Pi creates a fresh extension instance after session replacement or reload.
213
- const resumableThreads = new Map<string, BtwThreadState>();
215
+ const getLifetime = registerBtwSessionLifetimes(pi);
216
+ const sessionThreads = new WeakMap<BtwSessionLifetime, Map<string, BtwThreadState>>();
214
217
  let nextThreadNumber = 1;
215
- const listResumeThreads = (): BtwResumeThreadSummary[] =>
218
+ const listResumeThreads = (resumableThreads: Map<string, BtwThreadState>): BtwResumeThreadSummary[] =>
216
219
  [...resumableThreads.values()]
217
220
  .reverse()
218
221
  .filter((state) => state.thread.turns.length > 0 && state.title)
@@ -224,108 +227,132 @@ export default function btw(pi: ExtensionAPI, dependencies: BtwExtensionDependen
224
227
  }));
225
228
  pi.registerCommand("btw", {
226
229
  description: "Ask a quick side question without adding it to the main conversation",
227
- handler: async (args, ctx) => {
228
- const question = args.trim();
229
- if (ctx.mode !== "tui") {
230
- ctx.ui.notify("/btw requires interactive TUI mode", "error");
231
- return;
232
- }
230
+ handler: (args, ctx) => {
231
+ const lifetime = getLifetime(ctx);
232
+ if (lifetime.signal.aborted) return Promise.resolve();
233
+ const commandCtx = Object.create(ctx) as ExtensionCommandContext;
234
+ Object.defineProperty(commandCtx, "signal", { value: lifetime.signal, configurable: true });
235
+ return lifetime.track(
236
+ handleCommand(args, commandCtx, lifetime).catch((error: unknown) => {
237
+ if (!lifetime.signal.aborted) throw error;
238
+ }),
239
+ );
240
+ },
241
+ });
233
242
 
234
- let menuResult: BtwCommandMenuResult = "start";
235
- let selectedConversationContext: string | undefined;
236
- if (!question) {
237
- while (true) {
238
- menuResult = await showCommandMenu(pi, ctx, listResumeThreads());
239
- if (menuResult === "closed") return;
240
- if (menuResult !== "tree") break;
241
-
242
- const treeResult = await pickEntry(pi, ctx);
243
- if (treeResult.kind === "closed") return;
244
- if (treeResult.kind === "back") continue;
245
- try {
246
- if (!ctx.sessionManager.getEntry(treeResult.entryId)) {
247
- notifySafely(ctx, "The selected main-thread entry is no longer available", "warning");
248
- continue;
249
- }
250
- const branch = ctx.sessionManager.getBranch(treeResult.entryId);
251
- if (branch.at(-1)?.id !== treeResult.entryId) {
252
- notifySafely(ctx, "The selected main-thread branch is no longer available", "warning");
253
- continue;
254
- }
255
- selectedConversationContext = buildConversationContext(branch);
256
- menuResult = "start";
257
- break;
258
- } catch {
259
- return;
243
+ async function handleCommand(args: string, ctx: ExtensionCommandContext, lifetime: BtwSessionLifetime) {
244
+ let resumableThreads = sessionThreads.get(lifetime);
245
+ if (!resumableThreads) {
246
+ resumableThreads = new Map();
247
+ sessionThreads.set(lifetime, resumableThreads);
248
+ }
249
+ const question = args.trim();
250
+ if (ctx.mode !== "tui") {
251
+ ctx.ui.notify("/btw requires interactive TUI mode", "error");
252
+ return;
253
+ }
254
+
255
+ let menuResult: BtwCommandMenuResult = "start";
256
+ let selectedConversationContext: string | undefined;
257
+ if (!question) {
258
+ while (true) {
259
+ menuResult = await showCommandMenu(pi, ctx, listResumeThreads(resumableThreads));
260
+ if (lifetime.signal.aborted || menuResult === "closed") return;
261
+ if (menuResult !== "tree") break;
262
+
263
+ const treeResult = await pickEntry(pi, ctx);
264
+ if (lifetime.signal.aborted || treeResult.kind === "closed") return;
265
+ if (treeResult.kind === "back") continue;
266
+ try {
267
+ if (!ctx.sessionManager.getEntry(treeResult.entryId)) {
268
+ notifySafely(ctx, "The selected main-thread entry is no longer available", "warning");
269
+ continue;
260
270
  }
271
+ const branch = ctx.sessionManager.getBranch(treeResult.entryId);
272
+ if (branch.at(-1)?.id !== treeResult.entryId) {
273
+ notifySafely(ctx, "The selected main-thread branch is no longer available", "warning");
274
+ continue;
275
+ }
276
+ selectedConversationContext = buildConversationContext(branch);
277
+ menuResult = "start";
278
+ break;
279
+ } catch {
280
+ return;
261
281
  }
262
282
  }
283
+ }
263
284
 
264
- const settings = await loadSettings(ctx);
265
- const sameAsMainThinkingLevel = settings.thinkingLevel === undefined;
266
- const resolution = await resolveModel(settings, ctx);
267
- if (resolution.kind === "cancelled") {
268
- notifySafely(ctx, "Cancelled", "info");
269
- return;
270
- }
271
- if (resolution.kind === "unavailable") {
272
- notifySafely(ctx, "No available model for /btw", "error");
273
- return;
274
- }
285
+ const settings = await loadSettings(ctx);
286
+ if (lifetime.signal.aborted) return;
287
+ const sameAsMainThinkingLevel = settings.thinkingLevel === undefined;
288
+ const resolution = await resolveModel(settings, ctx);
289
+ if (lifetime.signal.aborted) return;
290
+ if (resolution.kind === "cancelled") {
291
+ notifySafely(ctx, "Cancelled", "info");
292
+ return;
293
+ }
294
+ if (resolution.kind === "unavailable") {
295
+ notifySafely(ctx, "No available model for /btw", "error");
296
+ return;
297
+ }
275
298
 
276
- let state = typeof menuResult === "object" ? resumableThreads.get(menuResult.threadId) : undefined;
277
- if (typeof menuResult === "object" && !state) {
278
- notifySafely(ctx, "The selected /btw side thread is no longer available", "warning");
279
- return;
280
- }
281
- const startingTurnCount = state?.thread.turns.length ?? 0;
282
-
283
- try {
284
- await runFullscreen(
285
- ctx,
286
- (fullscreenCtx) => {
287
- if (!state) {
288
- const createdAt = Date.now();
289
- state = {
290
- id: `btw-${nextThreadNumber}`,
291
- thread: createSideThread(
292
- selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch()),
293
- ),
294
- thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
295
- createdAt,
296
- updatedAt: createdAt,
297
- };
298
- nextThreadNumber += 1;
299
- }
300
- return runThread({
299
+ let state = typeof menuResult === "object" ? resumableThreads.get(menuResult.threadId) : undefined;
300
+ if (typeof menuResult === "object" && !state) {
301
+ notifySafely(ctx, "The selected /btw side thread is no longer available", "warning");
302
+ return;
303
+ }
304
+ const startingTurnCount = state?.thread.turns.length ?? 0;
305
+
306
+ try {
307
+ await runFullscreen(
308
+ ctx,
309
+ (fullscreenCtx) => {
310
+ if (lifetime.signal.aborted) return Promise.resolve({ kind: "closed" as const });
311
+ if (!state) {
312
+ const createdAt = Date.now();
313
+ state = {
314
+ id: `btw-${nextThreadNumber}`,
315
+ thread: createSideThread(
316
+ selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch()),
317
+ ),
318
+ thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
319
+ createdAt,
320
+ updatedAt: createdAt,
321
+ };
322
+ nextThreadNumber += 1;
323
+ }
324
+ return lifetime.track(
325
+ runThread({
301
326
  initialQuestion: question || undefined,
302
327
  selected: resolution.selected,
303
328
  thinkingLevel: state.thinkingLevel,
304
329
  rememberThinkingLevelChanges: !sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),
305
330
  state,
306
331
  ctx: fullscreenCtx,
307
- });
308
- },
309
- {
310
- copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
311
- layout: effectiveBtwLayout(settings),
312
- sidePaneRatio: effectiveBtwSidePaneRatio(settings),
313
- persistSidePaneRatio: (ratio, signal) =>
314
- updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => undefined),
315
- subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
316
- ...(settings.keybindings ? { keybindings: settings.keybindings } : {}),
317
- },
318
- );
319
- } finally {
320
- if (state?.title && state.thread.turns.length > 0) {
321
- if (state.thread.turns.length > startingTurnCount) {
322
- resumableThreads.delete(state.id);
323
- }
324
- resumableThreads.set(state.id, state);
332
+ }),
333
+ );
334
+ },
335
+ {
336
+ signal: lifetime.signal,
337
+ canRestoreParent: lifetime.canRestoreParent,
338
+ copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
339
+ layout: effectiveBtwLayout(settings),
340
+ sidePaneRatio: effectiveBtwSidePaneRatio(settings),
341
+ persistSidePaneRatio: (ratio, signal) =>
342
+ updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => undefined),
343
+ subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
344
+ ...(settings.keybindings ? { keybindings: settings.keybindings } : {}),
345
+ },
346
+ );
347
+ } finally {
348
+ if (!lifetime.signal.aborted && state?.title && state.thread.turns.length > 0) {
349
+ if (state.thread.turns.length > startingTurnCount) {
350
+ resumableThreads.delete(state.id);
325
351
  }
352
+ resumableThreads.set(state.id, state);
326
353
  }
327
- },
328
- });
354
+ }
355
+ }
329
356
  }
330
357
 
331
358
  async function showCommandMenuForBtw(
@@ -418,6 +445,7 @@ export async function runBtwThread({
418
445
  ctx,
419
446
  dependencies = {},
420
447
  }: RunBtwThreadOptions): Promise<BtwThreadResult> {
448
+ if (ctx.signal?.aborted) return { kind: "closed" };
421
449
  const ask = dependencies.ask ?? askThreadQuestion;
422
450
  const interact = dependencies.interact ?? showThreadComposer;
423
451
  const chooseBringToMainAction = dependencies.chooseBringToMain ?? chooseBringToMain;
@@ -438,7 +466,7 @@ export async function runBtwThread({
438
466
  level: activeThinkingLevel,
439
467
  levels: thinkingLevels,
440
468
  onChange: (level) => {
441
- if (!thinkingLevels.includes(level)) return;
469
+ if (ctx.signal?.aborted || !thinkingLevels.includes(level)) return;
442
470
  activeThinkingLevel = level;
443
471
  if (state) state.thinkingLevel = level;
444
472
  if (!rememberThinkingLevelChanges) return;
@@ -460,18 +488,23 @@ export async function runBtwThread({
460
488
 
461
489
  try {
462
490
  while (true) {
491
+ if (ctx.signal?.aborted) return { kind: "closed" };
463
492
  if (!pendingQuestion) {
464
- const action = await interact(thread, thread.turns.length > 0, ctx, composerDraft, createThinkingControl());
465
- if (action.kind === "close") return { kind: "closed" };
493
+ const action = await interact(thread, thread.turns.length > 0, ctx, composerDraft, createThinkingControl(), {
494
+ id: selected.model.id,
495
+ provider: selected.model.provider,
496
+ });
497
+ if (ctx.signal?.aborted || action.kind === "close") return { kind: "closed" };
466
498
  if (action.kind === "bringToMain") {
467
499
  const choice = await chooseBringToMainAction(thread, ctx);
500
+ if (ctx.signal?.aborted) return { kind: "closed" };
468
501
  if (choice.kind === "closed") return choice;
469
502
  if (choice.kind === "back") {
470
503
  composerDraft = action.questionDraft;
471
504
  continue;
472
505
  }
473
506
  const delivery = await deliverBringToMainDraft(choice.draft, ctx, choice.summary);
474
- if (delivery === "loaded" || delivery === "closed") return { kind: "closed" };
507
+ if (ctx.signal?.aborted || delivery === "loaded" || delivery === "closed") return { kind: "closed" };
475
508
  composerDraft = action.questionDraft;
476
509
  continue;
477
510
  }
@@ -481,9 +514,12 @@ export async function runBtwThread({
481
514
 
482
515
  const result = await ask(thread, pendingQuestion, selected, activeThinkingLevel, ctx, {
483
516
  questions: steeringQuestions,
484
- submit: (question) => steeringQuestions.push(question),
517
+ submit: (question) => {
518
+ if (!ctx.signal?.aborted) steeringQuestions.push(question);
519
+ },
485
520
  thinking: createThinkingControl(),
486
521
  });
522
+ if (ctx.signal?.aborted) return { kind: "closed" };
487
523
  if (result.kind === "aborted") {
488
524
  notifySafely(ctx, "Cancelled", "info");
489
525
  return { kind: "closed" };
@@ -517,6 +553,7 @@ export async function chooseBringToMain(
517
553
  ctx: ExtensionCommandContext,
518
554
  dependencies: ChooseBringToMainDependencies = {},
519
555
  ): Promise<BtwBringToMainChoice> {
556
+ if (ctx.signal?.aborted) return { kind: "closed" };
520
557
  const answered = getAnsweredTurns(thread.turns);
521
558
  if (answered.length === 0) return { kind: "back" };
522
559
  const showMenu = dependencies.showMenu ?? showBtwMenu;
@@ -543,7 +580,7 @@ export async function chooseBringToMain(
543
580
  [latestOption, fromOption, exactOption, entireOption, cancelOption],
544
581
  selectedScope,
545
582
  );
546
- if (scopeResult.kind === "close") return { kind: "closed" };
583
+ if (ctx.signal?.aborted || scopeResult.kind === "close") return { kind: "closed" };
547
584
  if (scopeResult.kind === "back" || scopeResult.value === cancelOption) return { kind: "back" };
548
585
  const scope = scopeResult.value;
549
586
  selectedScope = scope;
@@ -551,7 +588,7 @@ export async function chooseBringToMain(
551
588
  if (scope === entireOption) {
552
589
  const choice = makeChoice(entireSegments);
553
590
  const preview = await showPreview(ctx, choice.draft, choice.summary);
554
- if (preview.kind === "close") return { kind: "closed" };
591
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
555
592
  if (preview.kind === "back") continue;
556
593
  return choice;
557
594
  }
@@ -562,14 +599,14 @@ export async function chooseBringToMain(
562
599
  let selectedQuestion: string | undefined;
563
600
  while (true) {
564
601
  const questionResult = await showMenu(ctx, "Start from which question?", questions, selectedQuestion);
565
- if (questionResult.kind === "close") return { kind: "closed" };
602
+ if (ctx.signal?.aborted || questionResult.kind === "close") return { kind: "closed" };
566
603
  if (questionResult.kind === "back") break;
567
604
  const answeredTurnIndex = questions.indexOf(questionResult.value);
568
605
  if (answeredTurnIndex < 0) continue;
569
606
  selectedQuestion = questionResult.value;
570
607
  const choice = makeChoice(buildQuickBringToMainSegments(thread.turns, { kind: "from", answeredTurnIndex }));
571
608
  const preview = await showPreview(ctx, choice.draft, choice.summary);
572
- if (preview.kind === "close") return { kind: "closed" };
609
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
573
610
  if (preview.kind === "back") continue;
574
611
  return choice;
575
612
  }
@@ -598,11 +635,11 @@ export async function chooseBringToMain(
598
635
  return selector;
599
636
  },
600
637
  );
601
- if (!selectedRange) return { kind: "closed" };
638
+ if (ctx.signal?.aborted || !selectedRange) return { kind: "closed" };
602
639
  if (selectedRange.kind === "closed") return selectedRange;
603
640
  if (selectedRange.kind === "back") break;
604
641
  const preview = await showPreview(ctx, selectedRange.draft, selectedRange.summary);
605
- if (preview.kind === "close") return { kind: "closed" };
642
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
606
643
  if (preview.kind === "back") {
607
644
  selectionState = selectedRange.selectionState;
608
645
  continue;
@@ -650,8 +687,9 @@ async function showBringToMainPreview(
650
687
  },
651
688
  });
652
689
  const result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>
653
- runMenu(menuContext, menu, { getState: () => undefined }),
690
+ runMenu(menuContext, menu, { getState: () => undefined, signal: ctx.signal }),
654
691
  );
692
+ if (ctx.signal?.aborted) return { kind: "close" };
655
693
  if (confirmed && result.kind === "closed" && result.reason === "close") {
656
694
  return { kind: "bring" };
657
695
  }
@@ -690,8 +728,9 @@ async function showBtwMenu(
690
728
  },
691
729
  });
692
730
  const result = await runBtwMenuPreservingEditor(ctx, (menuContext) =>
693
- runMenu(menuContext, menu, { getState: () => undefined }),
731
+ runMenu(menuContext, menu, { getState: () => undefined, signal: ctx.signal }),
694
732
  );
733
+ if (ctx.signal?.aborted) return { kind: "close" };
695
734
  return selectedValue !== undefined && result.kind === "closed" && result.reason === "close"
696
735
  ? { kind: "select", value: selectedValue }
697
736
  : terminalBtwMenuAction(result);
@@ -708,6 +747,7 @@ export async function loadBringToMainDraft(
708
747
  ctx: ExtensionCommandContext,
709
748
  summary: BtwBringToMainSummary,
710
749
  ): Promise<BtwBringToMainDelivery> {
750
+ if (ctx.signal?.aborted) return "closed";
711
751
  const describeContent = () =>
712
752
  `${summary.messages} ${summary.messages === 1 ? "message" : "messages"} (~${summary.tokens} ${summary.tokens === 1 ? "token" : "tokens"})`;
713
753
  const existing = ctx.ui.getEditorText();
@@ -726,7 +766,7 @@ export async function loadBringToMainDraft(
726
766
  replaceOption,
727
767
  cancelOption,
728
768
  ]);
729
- if (action.kind === "close") return "closed";
769
+ if (ctx.signal?.aborted || action.kind === "close") return "closed";
730
770
  if (action.kind === "back" || action.value === cancelOption) return "back";
731
771
  if (action.value === appendOption) {
732
772
  ctx.ui.setEditorText(`${ctx.ui.getEditorText()}\n\n${draft}`);
@@ -744,7 +784,7 @@ export async function loadBringToMainDraft(
744
784
  "Back Keep current editor text",
745
785
  "⚠ Replace current draft Cannot be undone",
746
786
  ]);
747
- if (confirmed.kind === "close") return "closed";
787
+ if (ctx.signal?.aborted || confirmed.kind === "close") return "closed";
748
788
  if (confirmed.kind === "back" || confirmed.value === "Back Keep current editor text") continue;
749
789
  if (confirmed.value !== "⚠ Replace current draft Cannot be undone") continue;
750
790
  if (ctx.ui.getEditorText() !== current) {
@@ -770,6 +810,7 @@ async function prepareCurrentTranscriptMarkdown(
770
810
  ctx: ExtensionCommandContext,
771
811
  ): Promise<BtwMarkdownTransformers | undefined> {
772
812
  while (true) {
813
+ if (ctx.signal?.aborted) return undefined;
773
814
  const turnCount = thread.turns.length;
774
815
  const createMarkdownTransformers = ctx.signal
775
816
  ? await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion, ctx.signal)
@@ -788,7 +829,7 @@ async function askThreadQuestion(
788
829
  steering: BtwThreadSteeringControl,
789
830
  ) {
790
831
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, question, ctx);
791
- if (!createMarkdownTransformers) return { kind: "aborted" as const };
832
+ if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "aborted" as const };
792
833
  return ctx.ui.custom<Awaited<ReturnType<typeof completeSideThreadTurn>>>((tui, theme, keybindings, done) => {
793
834
  let settled = false;
794
835
  const view = new BtwAnsweringView(
@@ -803,6 +844,7 @@ async function askThreadQuestion(
803
844
  },
804
845
  thinkingLevel,
805
846
  {
847
+ model: { id: selected.model.id, provider: selected.model.provider },
806
848
  markdownTransformers: createMarkdownTransformers(theme),
807
849
  steering: {
808
850
  questions: steering.questions,
@@ -835,14 +877,16 @@ async function showThreadComposer(
835
877
  ctx: ExtensionCommandContext,
836
878
  initialQuestion: string | undefined,
837
879
  thinking: BtwThreadThinkingControl,
880
+ model?: BtwDisplayModel,
838
881
  ): Promise<TranscriptPagerAction> {
839
882
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);
840
- if (!createMarkdownTransformers) return { kind: "close" };
883
+ if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "close" };
841
884
  return ctx.ui.custom<TranscriptPagerAction>(
842
885
  (tui, theme, keybindings, done) =>
843
886
  new BtwTranscriptPager(tui, theme, thread.turns, done, {
844
887
  startAtBottom,
845
888
  initialQuestion,
889
+ model,
846
890
  markdownTransformers: createMarkdownTransformers(theme),
847
891
  thinking: { ...thinking, keybindings },
848
892
  }),