@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/dist/index.ts CHANGED
@@ -488,26 +488,19 @@ ${text.slice(-maxChars)}`;
488
488
  }
489
489
 
490
490
  // src/fullscreen-ui.ts
491
- import { spawn } from "node:child_process";
492
491
  import {
493
492
  copyToClipboard as copyToHostClipboard
494
493
  } from "@earendil-works/pi-coding-agent";
495
- import {
496
- isKeyRelease as isKeyRelease2,
497
- isKittyProtocolActive as isKittyProtocolActive2,
498
- Key as Key2,
499
- parseKey,
500
- TuiAltScreen,
501
- truncateToWidth as truncateToWidth3
502
- } from "@earendil-works/pi-tui";
494
+ import { ScrollView as ScrollView2, truncateToWidth as truncateToWidth3 } from "@earendil-works/pi-tui";
503
495
 
504
- // src/keybindings.ts
496
+ // src/fullscreen-renderer.ts
497
+ import { spawn } from "node:child_process";
505
498
  import {
506
499
  isKeyRelease,
507
500
  isKittyProtocolActive,
508
- KeybindingsManager,
509
- matchesKey as matchesKey2,
510
- TUI_KEYBINDINGS
501
+ Key as Key2,
502
+ parseKey,
503
+ TuiAltScreen
511
504
  } from "@earendil-works/pi-tui";
512
505
 
513
506
  // src/text.ts
@@ -530,8 +523,250 @@ function formatKeyLabel2(key) {
530
523
  }).join("+");
531
524
  }
532
525
 
526
+ // src/fullscreen-renderer.ts
527
+ var btwInputListeners = /* @__PURE__ */ new WeakMap();
528
+ function dispatchBtwInput(listeners, data) {
529
+ let current = data;
530
+ for (const group of [listeners.beforeAll, listeners.beforeViewport, listeners.regular]) {
531
+ for (const listener of group) {
532
+ const result = listener(current);
533
+ if (result?.consume) return result;
534
+ if (result?.data !== void 0) current = result.data;
535
+ }
536
+ }
537
+ return current === data ? void 0 : { data: current };
538
+ }
539
+ var BtwTuiAltScreen = class extends TuiAltScreen {
540
+ terminalActive = false;
541
+ beforeTerminalStart() {
542
+ super.beforeTerminalStart();
543
+ this.terminalActive = true;
544
+ }
545
+ beforeTerminalStop(options) {
546
+ this.terminalActive = false;
547
+ super.beforeTerminalStop(options);
548
+ }
549
+ flash(message, durationMs) {
550
+ if (this.terminalActive) super.flash(message, durationMs);
551
+ }
552
+ hasFocusedOverlay() {
553
+ return this.isOverlayFocused();
554
+ }
555
+ setViewportTarget(scrollView) {
556
+ const layout = Reflect.get(this, "currentLayout");
557
+ if (layout === void 0) return;
558
+ if (typeof layout !== "object" || layout === null || !Reflect.set(layout, "primaryScrollView", scrollView)) {
559
+ throw new Error("Pi BTW cannot route this fullscreen layout; update Pi.");
560
+ }
561
+ }
562
+ addInputListener(listener) {
563
+ let listeners = btwInputListeners.get(this);
564
+ if (!listeners) {
565
+ const registeredListeners = {
566
+ beforeAll: /* @__PURE__ */ new Set(),
567
+ beforeViewport: /* @__PURE__ */ new Set(),
568
+ regular: /* @__PURE__ */ new Set()
569
+ };
570
+ btwInputListeners.set(this, registeredListeners);
571
+ super.addInputListener((data) => dispatchBtwInput(registeredListeners, data));
572
+ listeners = registeredListeners;
573
+ }
574
+ listeners.regular.add(listener);
575
+ return () => listeners.regular.delete(listener);
576
+ }
577
+ addInputListenerBeforeAll(listener) {
578
+ const listeners = btwInputListeners.get(this);
579
+ if (!listeners) return super.addInputListener(listener);
580
+ listeners.beforeAll.add(listener);
581
+ return () => listeners.beforeAll.delete(listener);
582
+ }
583
+ addInputListenerBeforeViewport(listener) {
584
+ const listeners = btwInputListeners.get(this);
585
+ if (!listeners) return super.addInputListener(listener);
586
+ listeners.beforeViewport.add(listener);
587
+ return () => listeners.beforeViewport.delete(listener);
588
+ }
589
+ removeInputListener(listener) {
590
+ const listeners = btwInputListeners.get(this);
591
+ if (!listeners) {
592
+ super.removeInputListener(listener);
593
+ return;
594
+ }
595
+ listeners.beforeAll.delete(listener);
596
+ listeners.beforeViewport.delete(listener);
597
+ listeners.regular.delete(listener);
598
+ }
599
+ };
600
+ var BRACKETED_PASTE_START = "\x1B[200~";
601
+ var BRACKETED_PASTE_END = "\x1B[201~";
602
+ var ALT_SCREEN_ACTIONS_BEFORE_BOTTOM = [
603
+ "tui.altScreen.search",
604
+ "tui.altScreen.searchNext",
605
+ "tui.altScreen.searchPrevious",
606
+ "tui.altScreen.searchClose",
607
+ "tui.altScreen.pageUp",
608
+ "tui.altScreen.pageDown",
609
+ "tui.altScreen.halfPageUp",
610
+ "tui.altScreen.halfPageDown",
611
+ "tui.altScreen.lineUp",
612
+ "tui.altScreen.lineDown",
613
+ "tui.altScreen.previousPrompt",
614
+ "tui.altScreen.nextPrompt",
615
+ "tui.altScreen.top"
616
+ ];
617
+ var KEY_MODIFIER_ORDER = ["shift", "ctrl", "alt", "super"];
618
+ var MATCHABLE_SPECIAL_KEYS = /* @__PURE__ */ new Set([
619
+ "space",
620
+ "tab",
621
+ "enter",
622
+ "backspace",
623
+ "delete",
624
+ "insert",
625
+ "home",
626
+ "end",
627
+ "pageup",
628
+ "pagedown",
629
+ "up",
630
+ "down",
631
+ "left",
632
+ "right"
633
+ ]);
634
+ var MATCHABLE_SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?");
635
+ function normalizedKeyId(key) {
636
+ const parts = key.toLowerCase().split("+");
637
+ const base = parts.at(-1);
638
+ if (!base) return "";
639
+ const configuredModifiers = parts.slice(0, -1);
640
+ if (new Set(configuredModifiers).size !== configuredModifiers.length || configuredModifiers.some((modifier) => !KEY_MODIFIER_ORDER.includes(modifier)))
641
+ return "";
642
+ const normalizedBase = base === "esc" ? "escape" : base === "return" ? "enter" : base;
643
+ const modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));
644
+ return [...modifiers, normalizedBase].join("+");
645
+ }
646
+ function formatEffectiveKeyLabel(key) {
647
+ const parts = key.split("+");
648
+ const base = parts.at(-1);
649
+ if (base === "pageup") parts[parts.length - 1] = "pageUp";
650
+ if (base === "pagedown") parts[parts.length - 1] = "pageDown";
651
+ return formatKeyLabel2(parts.join("+"));
652
+ }
653
+ function canMatchKeyInput(key) {
654
+ const parts = key.split("+");
655
+ const base = parts.at(-1) ?? "";
656
+ const modifiers = parts.slice(0, -1);
657
+ if (base === "escape") return modifiers.length === 0;
658
+ if (base === "clear") {
659
+ return modifiers.length === 0 || modifiers.length === 1 && (modifiers[0] === "shift" || modifiers[0] === "ctrl");
660
+ }
661
+ if (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;
662
+ return MATCHABLE_SPECIAL_KEYS.has(base) || base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base));
663
+ }
664
+ function rawCtrlInput(base) {
665
+ if (base.length !== 1) return void 0;
666
+ const rawBase = base === "-" ? "_" : base;
667
+ if (!"abcdefghijklmnopqrstuvwxyz[\\]_".includes(rawBase)) return void 0;
668
+ return String.fromCharCode(rawBase.charCodeAt(0) & 31);
669
+ }
670
+ function legacyRawInput(key) {
671
+ const parts = key.split("+");
672
+ const base = parts.at(-1) ?? "";
673
+ if (parts.length === 2 && parts[0] === "ctrl") return rawCtrlInput(base);
674
+ if (isKittyProtocolActive()) return void 0;
675
+ if (parts.length === 2 && parts[0] === "alt" && base.length === 1) return `\x1B${base}`;
676
+ if (parts.length === 3 && parts[0] === "ctrl" && parts[1] === "alt") {
677
+ const input = rawCtrlInput(base);
678
+ return input ? `\x1B${input}` : void 0;
679
+ }
680
+ return void 0;
681
+ }
682
+ function keyInputIdentity(key) {
683
+ const identity = normalizedKeyId(key);
684
+ const input = legacyRawInput(identity);
685
+ return input ? normalizedKeyId(parseKey(input) ?? identity) : identity;
686
+ }
687
+ function hasManualSelectionCopyApi() {
688
+ return typeof TuiAltScreen.prototype.hasActiveSelection === "function" && typeof TuiAltScreen.prototype.copyActiveSelectionToClipboard === "function";
689
+ }
690
+ function createBtwFullscreenTui(parent, theme, keybindings, copyOnSelect, manualSelectionCopySupported, openUrl, copyToClipboard2) {
691
+ if (!copyOnSelect && !manualSelectionCopySupported) {
692
+ throw new Error(
693
+ "Manual fullscreen selection copying is unavailable in this Pi version; update Pi or enable automatic selection copying."
694
+ );
695
+ }
696
+ const styleSearchMatch = (text) => theme.bg("searchMatchBg", theme.fg("searchMatchText", text));
697
+ const fullscreen = new BtwTuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), void 0, {
698
+ mouse: true,
699
+ wheelScrollLines: "auto",
700
+ copyOnSelect,
701
+ searchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),
702
+ scrollToEndIndicator: () => {
703
+ const unavailableKeyIdentities = /* @__PURE__ */ new Set([keyInputIdentity(Key2.ctrl("c"))]);
704
+ for (const action of ALT_SCREEN_ACTIONS_BEFORE_BOTTOM) {
705
+ for (const actionKey of keybindings.getKeys(action)) {
706
+ unavailableKeyIdentities.add(keyInputIdentity(String(actionKey)));
707
+ }
708
+ }
709
+ if (!copyOnSelect) {
710
+ for (const copyKey of keybindings.getKeys("app.message.copy")) {
711
+ unavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));
712
+ }
713
+ }
714
+ const key = keybindings.getKeys("tui.altScreen.bottom").map((candidate) => keyInputIdentity(String(candidate))).find(
715
+ (identity) => identity && canMatchKeyInput(identity) && !unavailableKeyIdentities.has(identity) && formatEffectiveKeyLabel(identity)
716
+ );
717
+ const label = theme.fg("text", " \u2193 Jump to latest message");
718
+ const shortcut = key ? theme.fg("muted", ` \xB7 ${formatEffectiveKeyLabel(key)}`) : "";
719
+ return theme.bg("selectedBg", `${label}${shortcut} `);
720
+ },
721
+ searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),
722
+ searchNavigationButtonStyle: (text, hovered) => hovered ? theme.underline(text) : text,
723
+ openUrl,
724
+ copySelection: async (text) => {
725
+ try {
726
+ await copyToClipboard2(text);
727
+ return true;
728
+ } catch (error) {
729
+ return sanitizeSingleLine(error instanceof Error ? error.message : String(error)) || "Copy failed";
730
+ }
731
+ }
732
+ });
733
+ if (!copyOnSelect) {
734
+ let isInBracketedPaste = false;
735
+ fullscreen.addInputListenerBeforeViewport((data) => {
736
+ const wasInBracketedPaste = isInBracketedPaste;
737
+ const startsBracketedPaste = data.includes(BRACKETED_PASTE_START);
738
+ if (startsBracketedPaste) isInBracketedPaste = true;
739
+ if (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {
740
+ isInBracketedPaste = false;
741
+ }
742
+ if (wasInBracketedPaste || startsBracketedPaste || fullscreen.hasFocusedOverlay() || isKeyRelease(data) || !keybindings.matches(data, "app.message.copy")) {
743
+ return void 0;
744
+ }
745
+ if (!fullscreen.hasActiveSelection()) {
746
+ fullscreen.flash("No selection to copy");
747
+ return { consume: true };
748
+ }
749
+ void fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash("Copy failed"));
750
+ return { consume: true };
751
+ });
752
+ }
753
+ return fullscreen;
754
+ }
755
+ function openUrlInBrowser(target) {
756
+ const [command, args] = process.platform === "darwin" ? ["open", [target]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : ["xdg-open", [target]];
757
+ spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {
758
+ }).unref();
759
+ }
760
+
533
761
  // src/keybindings.ts
534
- var BTW_SHORTCUT_ACTIONS = ["exit", "cycleThinkingLevel", "bringToMain"];
762
+ import {
763
+ isKeyRelease as isKeyRelease2,
764
+ isKittyProtocolActive as isKittyProtocolActive2,
765
+ KeybindingsManager,
766
+ matchesKey as matchesKey2,
767
+ TUI_KEYBINDINGS
768
+ } from "@earendil-works/pi-tui";
769
+ var BTW_SHORTCUT_ACTIONS = ["exit", "cycleThinkingLevel", "bringToMain", "switchPane"];
535
770
  var MODIFIERS = ["shift", "alt", "ctrl", "super"];
536
771
  var SYMBOLS = "`-=[]\\;',./!@#$%^&*()_|~{}:<>?";
537
772
  var SPECIAL = {
@@ -586,9 +821,47 @@ function inputsFor(key) {
586
821
  const inputs = code === void 0 ? LEGACY_INPUTS : [...LEGACY_INPUTS, `\x1B[${code};${modifier + 1}u`];
587
822
  return inputs.filter((input) => matchesKey2(input, key));
588
823
  }
824
+ function btwKeyHasReachableInput(candidate, blockers) {
825
+ const key = normalizeBtwKey(candidate);
826
+ return key !== void 0 && inputsFor(key).some(
827
+ (input) => !blockers.some((other) => typeof other === "string" && matchesKey2(input, other))
828
+ );
829
+ }
830
+ function protocolIdentity(value) {
831
+ let base = value.toLowerCase();
832
+ const seen = /* @__PURE__ */ new Set();
833
+ for (; ; ) {
834
+ const part = MODIFIERS.find((modifier) => base.startsWith(`${modifier}+`));
835
+ if (!part) break;
836
+ if (seen.has(part)) return void 0;
837
+ seen.add(part);
838
+ base = base.slice(part.length + 1);
839
+ }
840
+ if (!base || base.includes("+") && base !== "+") return void 0;
841
+ if (base === "esc") base = "escape";
842
+ if (base === "return") base = "enter";
843
+ const codepoint = SPECIAL[base] ?? (base.length === 1 ? base.charCodeAt(0) : void 0);
844
+ if (codepoint === void 0) return void 0;
845
+ return { codepoint, modifier: MODIFIERS.reduce((mask, part, bit) => mask | (seen.has(part) ? 1 << bit : 0), 0) };
846
+ }
847
+ function protocolInputs(first, second) {
848
+ const identity = protocolIdentity(first);
849
+ const alternate = protocolIdentity(second)?.codepoint;
850
+ if (!identity || alternate === void 0) return [];
851
+ const { codepoint, modifier } = identity;
852
+ return [
853
+ // Alternate layout fields describe printable keys, not invented functional
854
+ // key mappings such as Ctrl+Up with a Latin base-layout key.
855
+ ...codepoint >= 33 && codepoint <= 126 && alternate >= 33 && alternate <= 126 ? [`\x1B[${codepoint}:${alternate};${modifier + 1}u`, `\x1B[${codepoint}::${alternate};${modifier + 1}u`] : [],
856
+ `\x1B[27;${modifier + 1};${codepoint}~`
857
+ ];
858
+ }
589
859
  function btwKeysOverlap(first, second) {
590
860
  const normalized = normalizeBtwKey(first);
591
- return normalized !== void 0 && inputsFor(normalized).some((input) => matchesKey2(input, second));
861
+ if (normalized === void 0) return false;
862
+ return [...inputsFor(normalized), ...protocolInputs(normalized, second), ...protocolInputs(second, normalized)].some(
863
+ (input) => matchesKey2(input, normalized) && matchesKey2(input, second)
864
+ );
592
865
  }
593
866
  function reservedKeys(keybindings, copyOnSelect) {
594
867
  return [
@@ -618,11 +891,11 @@ function isTextKey(key) {
618
891
  return (base.length === 1 || base === "space") && !parts.some((part) => ["ctrl", "alt", "super"].includes(part));
619
892
  }
620
893
  function resolveBtwShortcuts(overrides = {}, keybindings, copyOnSelect = true) {
621
- let mode = isKittyProtocolActive();
894
+ let mode = isKittyProtocolActive2();
622
895
  let snapshot = resolveShortcutSnapshot(overrides, keybindings, copyOnSelect);
623
896
  const current = () => {
624
- if (mode !== isKittyProtocolActive()) {
625
- mode = isKittyProtocolActive();
897
+ if (mode !== isKittyProtocolActive2()) {
898
+ mode = isKittyProtocolActive2();
626
899
  snapshot = resolveShortcutSnapshot(overrides, keybindings, copyOnSelect);
627
900
  }
628
901
  return snapshot;
@@ -640,12 +913,13 @@ function resolveBtwShortcuts(overrides = {}, keybindings, copyOnSelect = true) {
640
913
  }
641
914
  function resolveShortcutSnapshot(overrides = {}, keybindings, copyOnSelect = true) {
642
915
  const reserved = reservedKeys(keybindings, copyOnSelect);
643
- const keys = { exit: ["ctrl+c"], cycleThinkingLevel: [], bringToMain: [] };
916
+ const keys = { exit: ["ctrl+c"], cycleThinkingLevel: [], bringToMain: [], switchPane: [] };
644
917
  const warnings = [];
645
918
  const defaults = {
646
919
  exit: ["ctrl+c"],
647
920
  cycleThinkingLevel: keybindings.getKeys("app.thinking.cycle"),
648
- bringToMain: ["ctrl+r"]
921
+ bringToMain: ["ctrl+r"],
922
+ switchPane: ["f6", "f7", "f8"]
649
923
  };
650
924
  const usable = (action, candidate, inherited = false) => {
651
925
  const key = normalizeBtwKey(candidate);
@@ -653,8 +927,7 @@ function resolveShortcutSnapshot(overrides = {}, keybindings, copyOnSelect = tru
653
927
  const inputs = inputsFor(key);
654
928
  if (!inputs.length) return void 0;
655
929
  if (action === "exit" && key === "ctrl+c") return key;
656
- if (reserved.some((other) => typeof other === "string" && inputs.some((input) => matchesKey2(input, other))))
657
- return void 0;
930
+ if (reserved.some((other) => typeof other === "string" && btwKeysOverlap(key, other))) return void 0;
658
931
  return key;
659
932
  };
660
933
  const candidates = {};
@@ -664,6 +937,13 @@ function resolveShortcutSnapshot(overrides = {}, keybindings, copyOnSelect = tru
664
937
  const override = overrides[action];
665
938
  if (override !== void 0) candidates[action] = usable(action, override);
666
939
  }
940
+ availableDefaults.switchPane = availableDefaults.switchPane.filter(
941
+ (key) => BTW_SHORTCUT_ACTIONS.some(
942
+ (action) => action !== "switchPane" && (candidates[action] ? [candidates[action]] : availableDefaults[action]).some(
943
+ (other) => btwKeysOverlap(key, other)
944
+ )
945
+ ) === false
946
+ ).slice(0, 1);
667
947
  for (; ; ) {
668
948
  const rejected = BTW_SHORTCUT_ACTIONS.filter((action) => {
669
949
  const candidate = candidates[action];
@@ -688,14 +968,14 @@ function resolveShortcutSnapshot(overrides = {}, keybindings, copyOnSelect = tru
688
968
  (other) => other !== action && keys[other].some((used) => btwKeysOverlap(key, used))
689
969
  )
690
970
  );
691
- keys[action] = action === "exit" ? [.../* @__PURE__ */ new Set([...effective, "ctrl+c"])] : effective;
971
+ keys[action] = action === "exit" ? [.../* @__PURE__ */ new Set([...effective, "ctrl+c"])] : action === "switchPane" ? effective.slice(0, 1) : effective;
692
972
  if (!keys[action].length && (override !== void 0 || defaults[action].length > 0))
693
973
  warnings.push(`${action}: no usable shortcut; change Pi BTW Settings or Pi keybindings.`);
694
974
  }
695
975
  return {
696
976
  keys,
697
977
  warnings,
698
- matches: (data, action) => !isKeyRelease(data) && keys[action].some((key) => matchesKey2(data, key)),
978
+ matches: (data, action) => !isKeyRelease2(data) && keys[action].some((key) => matchesKey2(data, key)),
699
979
  label: (action) => keys[action].length ? formatKeyLabel2(keys[action][0] ?? "") : "Unavailable"
700
980
  };
701
981
  }
@@ -706,24 +986,35 @@ function validateBtwShortcutEdit(action, value, overrides, keybindings, copyOnSe
706
986
  const resolved = resolveBtwShortcuts(next, keybindings, copyOnSelect);
707
987
  const previous = resolveBtwShortcuts(overrides, keybindings, copyOnSelect);
708
988
  for (const item of BTW_SHORTCUT_ACTIONS) {
709
- if (item === action && !resolved.keys[item].includes(normalizeBtwKey(value) ?? "") || item !== action && previous.keys[item].some((key) => !resolved.keys[item].includes(key))) {
989
+ if (item === action && !resolved.keys[item].includes(normalizeBtwKey(value) ?? "") || item !== action && !(item === "switchPane" && overrides.switchPane === void 0) && previous.keys[item].some((key) => !resolved.keys[item].includes(key))) {
710
990
  return `${item} conflicts with another BTW shortcut, editing, selection, search, scrolling, or copying. Choose a different key.`;
711
991
  }
712
992
  }
713
993
  return void 0;
714
994
  }
995
+ var hostInputBlockersByTui = /* @__PURE__ */ new WeakMap();
996
+ function setBtwHostInputBlockers(tui, keys) {
997
+ hostInputBlockersByTui.set(tui, keys);
998
+ }
999
+ function getBtwHostInputBlockers(tui) {
1000
+ return hostInputBlockersByTui.get(tui) ?? [];
1001
+ }
1002
+ var keybindingsByTui = /* @__PURE__ */ new WeakMap();
1003
+ function setBtwKeybindings(tui, keybindings) {
1004
+ keybindingsByTui.set(tui, keybindings);
1005
+ }
1006
+ function getBtwKeybindings(tui, keybindings) {
1007
+ return keybindingsByTui.get(tui) ?? keybindings ?? new KeybindingsManager({
1008
+ ...TUI_KEYBINDINGS,
1009
+ "app.thinking.cycle": { defaultKeys: "shift+tab" }
1010
+ });
1011
+ }
715
1012
  var bindingsByTui = /* @__PURE__ */ new WeakMap();
716
1013
  function setBtwShortcuts(tui, shortcuts) {
717
1014
  bindingsByTui.set(tui, shortcuts);
718
1015
  }
719
1016
  function getBtwShortcuts(tui, keybindings) {
720
- return bindingsByTui.get(tui) ?? resolveBtwShortcuts(
721
- {},
722
- keybindings ?? new KeybindingsManager({
723
- ...TUI_KEYBINDINGS,
724
- "app.thinking.cycle": { defaultKeys: "shift+tab" }
725
- })
726
- );
1017
+ return bindingsByTui.get(tui) ?? resolveBtwShortcuts({}, getBtwKeybindings(tui, keybindings));
727
1018
  }
728
1019
  var BtwPasteGuard = class {
729
1020
  active = false;
@@ -740,6 +1031,7 @@ var BtwPasteGuard = class {
740
1031
  import {
741
1032
  HStack,
742
1033
  isFocusable,
1034
+ isKeyRelease as isKeyRelease3,
743
1035
  ScrollView,
744
1036
  truncateToWidth as truncateToWidth2,
745
1037
  visibleWidth as visibleWidth2
@@ -1175,20 +1467,23 @@ var BtwMainThreadInput = class {
1175
1467
  }
1176
1468
  refreshTarget() {
1177
1469
  if (this.disposed) return;
1178
- const next = this.resolveTarget();
1179
- if (!hasInput(next) || next === this.target) return;
1470
+ const resolved = this.resolveTarget();
1471
+ const next = hasInput(resolved) ? resolved : void 0;
1472
+ if (next === this.target) return;
1180
1473
  if (this._focused && this.target && isFocusable(this.target)) this.target.focused = false;
1181
1474
  this.target = next;
1182
- if (this._focused && isFocusable(next)) next.focused = true;
1475
+ if (this._focused && next && isFocusable(next)) next.focused = true;
1183
1476
  }
1184
1477
  invalidate() {
1185
1478
  }
1186
1479
  dispose() {
1187
1480
  if (this.disposed) return;
1188
1481
  this.disposed = true;
1189
- if (this._focused && this.target && isFocusable(this.target)) this.target.focused = false;
1482
+ const target = this.target;
1483
+ const wasFocused = this._focused;
1190
1484
  this.target = void 0;
1191
1485
  this._focused = false;
1486
+ if (wasFocused && target && isFocusable(target)) target.focused = false;
1192
1487
  }
1193
1488
  };
1194
1489
  var BtwSplitPane = class {
@@ -1196,20 +1491,27 @@ var BtwSplitPane = class {
1196
1491
  this.options = options;
1197
1492
  this.sidePaneRatio = clampSidePaneRatio(options.sidePaneRatio ?? DEFAULT_BTW_SIDE_PANE_RATIO);
1198
1493
  this.persistedSidePaneRatio = this.sidePaneRatio;
1199
- this.mainPane = new MainThreadPane(options.mainThread, options.mainLayout, options.theme, options.terminalRows);
1494
+ this.mainPane = new MainThreadPane(
1495
+ options.mainThread,
1496
+ options.mainLayout,
1497
+ options.mainScrollView,
1498
+ options.theme,
1499
+ options.terminalRows
1500
+ );
1501
+ const side = options.sideScrollView ? options.sideLayout : new ScrollView(options.sideLayout, { primary: true });
1200
1502
  this.viewportRouter = new PaneViewportRouter(
1201
- options.sideScrollView ?? findPrimaryScrollView(options.sideLayout),
1503
+ options.sideScrollView ?? side,
1202
1504
  this.mainPane.getPrimaryScrollView(),
1203
1505
  options.setViewportTarget
1204
1506
  );
1205
1507
  this.viewportRouter.activate("side");
1508
+ this.updateFocusLabel();
1206
1509
  const separator = {
1207
1510
  render: (width) => Array.from({ length: Math.max(1, options.terminalRows()) }, () => truncateToWidth2(this.renderDivider(), width)),
1208
1511
  handleMouse: (event) => this.handleDividerMouse(event),
1209
1512
  invalidate() {
1210
1513
  }
1211
1514
  };
1212
- const side = options.sideLayout;
1213
1515
  const main = this.mainPane.getLayout();
1214
1516
  this.layoutRoot = options.layout === "left-pane" ? new ResponsivePaneRow(
1215
1517
  side,
@@ -1254,7 +1556,14 @@ var BtwSplitPane = class {
1254
1556
  this.forwardPastedInput(data);
1255
1557
  return true;
1256
1558
  }
1257
- if (width < MIN_BTW_SPLIT_COLUMNS) return false;
1559
+ if (width < MIN_BTW_SPLIT_COLUMNS || isKeyRelease3(data)) return false;
1560
+ if (this.options.shortcuts?.matches(data, "switchPane")) {
1561
+ this.focusGeneration += 1;
1562
+ this.cancelDividerDrag();
1563
+ this.activatePane(this.activePane === "side" ? "main" : "side");
1564
+ return true;
1565
+ }
1566
+ this.updateFocusLabel();
1258
1567
  const pane = paneForMouseClick(data, width, this.options.layout, this.sidePaneRatio);
1259
1568
  if (pane) this.queuePaneFocus(pane);
1260
1569
  return false;
@@ -1290,7 +1599,27 @@ var BtwSplitPane = class {
1290
1599
  this.focusGeneration += 1;
1291
1600
  this.dividerDragStartRatio = void 0;
1292
1601
  this.failedRatioSaveGenerationDuringDrag = void 0;
1293
- this.viewportRouter.dispose();
1602
+ let error;
1603
+ for (const cleanup of [
1604
+ () => this.viewportRouter.dispose(),
1605
+ () => this.mainPane.dispose(),
1606
+ () => this.setFocusLabel(void 0)
1607
+ ]) {
1608
+ try {
1609
+ cleanup();
1610
+ } catch (failure) {
1611
+ error ??= failure;
1612
+ }
1613
+ }
1614
+ if (error !== void 0) throw error;
1615
+ }
1616
+ updateFocusLabel() {
1617
+ const shortcuts = this.options.shortcuts;
1618
+ this.setFocusLabel(shortcuts?.keys.switchPane.length ? shortcuts.label("switchPane") : void 0);
1619
+ }
1620
+ setFocusLabel(shortcutLabel) {
1621
+ const component = this.options.sideComponent;
1622
+ component.setWorkspaceFocus?.(this.activePane, shortcutLabel);
1294
1623
  }
1295
1624
  renderDivider() {
1296
1625
  return this.options.theme.fg("borderMuted", "\u2502");
@@ -1358,7 +1687,7 @@ var BtwSplitPane = class {
1358
1687
  this.failedRatioSaveGenerationDuringDrag = void 0;
1359
1688
  const saveGeneration = ++this.ratioSaveGeneration;
1360
1689
  void Promise.resolve().then(() => persist(ratio)).then(() => {
1361
- if (saveGeneration <= this.confirmedRatioSaveGeneration) return;
1690
+ if (this.disposed || saveGeneration <= this.confirmedRatioSaveGeneration) return;
1362
1691
  this.confirmedRatioSaveGeneration = saveGeneration;
1363
1692
  this.persistedSidePaneRatio = ratio;
1364
1693
  }).catch(() => {
@@ -1397,6 +1726,7 @@ var BtwSplitPane = class {
1397
1726
  activatePane(pane) {
1398
1727
  if (this.disposed) return;
1399
1728
  this.activePane = pane;
1729
+ this.updateFocusLabel();
1400
1730
  this.viewportRouter.activate(pane);
1401
1731
  this.options.setFocus(pane === "side" ? this.options.sideComponent : this.options.mainInput);
1402
1732
  this.options.requestRender();
@@ -1453,8 +1783,9 @@ var ResponsivePaneRow = class extends HStack {
1453
1783
  }
1454
1784
  };
1455
1785
  var MainThreadPane = class {
1456
- constructor(mainThread, mainLayout, theme, terminalRows) {
1786
+ constructor(mainThread, mainLayout, mainScrollView, theme, terminalRows) {
1457
1787
  this.terminalRows = terminalRows;
1788
+ this.borrowedScroll = mainLayout !== void 0;
1458
1789
  this.body = {
1459
1790
  render: (width) => mainThread.render(Math.max(1, width)).map((line) => truncateToWidth2(line, Math.max(1, width))),
1460
1791
  invalidate() {
@@ -1462,7 +1793,8 @@ var MainThreadPane = class {
1462
1793
  };
1463
1794
  if (mainLayout) {
1464
1795
  this.layout = mainLayout;
1465
- this.scroll = findPrimaryScrollView(mainLayout);
1796
+ if (!mainScrollView) throw new Error("The native main pane has no compatible viewport.");
1797
+ this.scroll = mainScrollView;
1466
1798
  return;
1467
1799
  }
1468
1800
  this.scroll = new ScrollView(this.body, {
@@ -1474,12 +1806,18 @@ var MainThreadPane = class {
1474
1806
  this.layout = this.scroll;
1475
1807
  }
1476
1808
  terminalRows;
1809
+ borrowedScroll;
1477
1810
  body;
1478
1811
  layout;
1479
1812
  scroll;
1480
1813
  getLayout() {
1481
1814
  return this.layout;
1482
1815
  }
1816
+ dispose() {
1817
+ if (this.borrowedScroll) return;
1818
+ this.scroll?.setScrollbarActive(false);
1819
+ this.scroll?.setScrollbar("hidden");
1820
+ }
1483
1821
  getPrimaryScrollView() {
1484
1822
  return this.scroll;
1485
1823
  }
@@ -1497,7 +1835,12 @@ var PaneViewportRouter = class {
1497
1835
  this.main = main;
1498
1836
  this.setViewportTarget = setViewportTarget;
1499
1837
  for (const scrollView of [side, main]) {
1500
- if (scrollView) this.originalPrimary.set(scrollView, scrollView.primary);
1838
+ if (!scrollView) continue;
1839
+ const primary = Object.getOwnPropertyDescriptor(scrollView, "primary");
1840
+ if (!primary?.writable || typeof primary.value !== "boolean") {
1841
+ throw new Error("Pi BTW cannot route this viewport; update Pi.");
1842
+ }
1843
+ this.originalPrimary.set(scrollView, scrollView.primary);
1501
1844
  }
1502
1845
  }
1503
1846
  side;
@@ -1508,35 +1851,37 @@ var PaneViewportRouter = class {
1508
1851
  activate(pane) {
1509
1852
  if (this.disposed) return;
1510
1853
  const target = pane === "side" ? this.side : this.main;
1511
- for (const scrollView of this.originalPrimary.keys()) setScrollViewPrimary(scrollView, scrollView === target);
1512
- this.setViewportTarget(target);
1854
+ const previous = new Map([...this.originalPrimary.keys()].map((scrollView) => [scrollView, scrollView.primary]));
1855
+ try {
1856
+ for (const scrollView of this.originalPrimary.keys()) setScrollViewPrimary(scrollView, scrollView === target);
1857
+ this.setViewportTarget(target);
1858
+ } catch (error) {
1859
+ for (const [scrollView, primary] of previous) setScrollViewPrimary(scrollView, primary);
1860
+ throw error;
1861
+ }
1513
1862
  }
1514
1863
  dispose() {
1515
1864
  if (this.disposed) return;
1516
1865
  this.disposed = true;
1517
- for (const [scrollView, primary] of this.originalPrimary) setScrollViewPrimary(scrollView, primary);
1518
- this.setViewportTarget(void 0);
1866
+ let error;
1867
+ for (const [scrollView, primary] of this.originalPrimary) {
1868
+ try {
1869
+ setScrollViewPrimary(scrollView, primary);
1870
+ } catch (failure) {
1871
+ error ??= failure;
1872
+ }
1873
+ }
1874
+ this.originalPrimary.clear();
1875
+ try {
1876
+ this.setViewportTarget(void 0);
1877
+ } catch (failure) {
1878
+ error ??= failure;
1879
+ }
1880
+ if (error !== void 0) throw error;
1519
1881
  }
1520
1882
  };
1521
1883
  function setScrollViewPrimary(scrollView, primary) {
1522
- Reflect.set(scrollView, "primary", primary);
1523
- }
1524
- function findPrimaryScrollView(root) {
1525
- const visited = /* @__PURE__ */ new Set();
1526
- let fallback;
1527
- let primary;
1528
- const visit = (component) => {
1529
- if (visited.has(component)) return;
1530
- visited.add(component);
1531
- if (component instanceof ScrollView) {
1532
- fallback ??= component;
1533
- if (component.primary) primary = component;
1534
- }
1535
- if (!("children" in component) || !Array.isArray(component.children)) return;
1536
- for (const child of component.children) visit(child);
1537
- };
1538
- visit(root);
1539
- return primary ?? fallback;
1884
+ if (!Reflect.set(scrollView, "primary", primary)) throw new Error("Pi BTW could not restore viewport ownership.");
1540
1885
  }
1541
1886
  function paneForMouseClick(data, terminalColumns, layout, sidePaneRatio) {
1542
1887
  const match = SGR_MOUSE_PRESS_PATTERN.exec(data);
@@ -1610,6 +1955,10 @@ async function runBtwFullscreen(ctx, run, options = {}, dependencies = {}) {
1610
1955
  run,
1611
1956
  (value) => {
1612
1957
  try {
1958
+ if (options.canRestoreParent?.() === false) {
1959
+ done(value);
1960
+ return;
1961
+ }
1613
1962
  liveEditorText = ctx.ui.getEditorText();
1614
1963
  restoreEditor = true;
1615
1964
  } catch {
@@ -1626,228 +1975,14 @@ async function runBtwFullscreen(ctx, run, options = {}, dependencies = {}) {
1626
1975
  onHandle: (handle) => host?.setParentOverlay(handle)
1627
1976
  }
1628
1977
  );
1629
- if (restoreEditor) {
1978
+ if (restoreEditor && options.canRestoreParent?.() !== false) {
1630
1979
  try {
1631
- if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
1632
- } catch {
1633
- }
1634
- }
1635
- if (outcome.kind === "failed") throw outcome.error;
1636
- return outcome.value;
1637
- }
1638
- var btwInputListeners = /* @__PURE__ */ new WeakMap();
1639
- function dispatchBtwInput(listeners, data) {
1640
- let current = data;
1641
- for (const group of [listeners.beforeAll, listeners.beforeViewport, listeners.regular]) {
1642
- for (const listener of group) {
1643
- const result = listener(current);
1644
- if (result?.consume) return result;
1645
- if (result?.data !== void 0) current = result.data;
1646
- }
1647
- }
1648
- return current === data ? void 0 : { data: current };
1649
- }
1650
- var BtwTuiAltScreen = class extends TuiAltScreen {
1651
- hasFocusedOverlay() {
1652
- return this.isOverlayFocused();
1653
- }
1654
- setViewportTarget(scrollView) {
1655
- if (!scrollView) return;
1656
- const layout = Reflect.get(this, "currentLayout");
1657
- if (layout) layout.primaryScrollView = scrollView;
1658
- }
1659
- addInputListener(listener) {
1660
- let listeners = btwInputListeners.get(this);
1661
- if (!listeners) {
1662
- const registeredListeners = {
1663
- beforeAll: /* @__PURE__ */ new Set(),
1664
- beforeViewport: /* @__PURE__ */ new Set(),
1665
- regular: /* @__PURE__ */ new Set()
1666
- };
1667
- btwInputListeners.set(this, registeredListeners);
1668
- super.addInputListener((data) => dispatchBtwInput(registeredListeners, data));
1669
- listeners = registeredListeners;
1670
- }
1671
- listeners.regular.add(listener);
1672
- return () => listeners.regular.delete(listener);
1673
- }
1674
- addInputListenerBeforeAll(listener) {
1675
- const listeners = btwInputListeners.get(this);
1676
- if (!listeners) return super.addInputListener(listener);
1677
- listeners.beforeAll.add(listener);
1678
- return () => listeners.beforeAll.delete(listener);
1679
- }
1680
- addInputListenerBeforeViewport(listener) {
1681
- const listeners = btwInputListeners.get(this);
1682
- if (!listeners) return super.addInputListener(listener);
1683
- listeners.beforeViewport.add(listener);
1684
- return () => listeners.beforeViewport.delete(listener);
1685
- }
1686
- removeInputListener(listener) {
1687
- const listeners = btwInputListeners.get(this);
1688
- if (!listeners) {
1689
- super.removeInputListener(listener);
1690
- return;
1691
- }
1692
- listeners.beforeAll.delete(listener);
1693
- listeners.beforeViewport.delete(listener);
1694
- listeners.regular.delete(listener);
1695
- }
1696
- };
1697
- var BRACKETED_PASTE_START = "\x1B[200~";
1698
- var BRACKETED_PASTE_END = "\x1B[201~";
1699
- var ALT_SCREEN_ACTIONS_BEFORE_BOTTOM = [
1700
- "tui.altScreen.search",
1701
- "tui.altScreen.searchNext",
1702
- "tui.altScreen.searchPrevious",
1703
- "tui.altScreen.searchClose",
1704
- "tui.altScreen.pageUp",
1705
- "tui.altScreen.pageDown",
1706
- "tui.altScreen.halfPageUp",
1707
- "tui.altScreen.halfPageDown",
1708
- "tui.altScreen.lineUp",
1709
- "tui.altScreen.lineDown",
1710
- "tui.altScreen.previousPrompt",
1711
- "tui.altScreen.nextPrompt",
1712
- "tui.altScreen.top"
1713
- ];
1714
- var KEY_MODIFIER_ORDER = ["shift", "ctrl", "alt", "super"];
1715
- var MATCHABLE_SPECIAL_KEYS = /* @__PURE__ */ new Set([
1716
- "space",
1717
- "tab",
1718
- "enter",
1719
- "backspace",
1720
- "delete",
1721
- "insert",
1722
- "home",
1723
- "end",
1724
- "pageup",
1725
- "pagedown",
1726
- "up",
1727
- "down",
1728
- "left",
1729
- "right"
1730
- ]);
1731
- var MATCHABLE_SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?");
1732
- function normalizedKeyId(key) {
1733
- const parts = key.toLowerCase().split("+");
1734
- const base = parts.at(-1);
1735
- if (!base) return "";
1736
- const normalizedBase = base === "esc" ? "escape" : base === "return" ? "enter" : base;
1737
- const modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));
1738
- return [...modifiers, normalizedBase].join("+");
1739
- }
1740
- function formatEffectiveKeyLabel(key) {
1741
- const parts = key.split("+");
1742
- const base = parts.at(-1);
1743
- if (base === "pageup") parts[parts.length - 1] = "pageUp";
1744
- if (base === "pagedown") parts[parts.length - 1] = "pageDown";
1745
- return formatKeyLabel2(parts.join("+"));
1746
- }
1747
- function canMatchKeyInput(key) {
1748
- const parts = key.split("+");
1749
- const base = parts.at(-1) ?? "";
1750
- const modifiers = parts.slice(0, -1);
1751
- if (base === "escape") return modifiers.length === 0;
1752
- if (base === "clear") {
1753
- return modifiers.length === 0 || modifiers.length === 1 && (modifiers[0] === "shift" || modifiers[0] === "ctrl");
1754
- }
1755
- if (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;
1756
- return MATCHABLE_SPECIAL_KEYS.has(base) || base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base));
1757
- }
1758
- function rawCtrlInput(base) {
1759
- if (base.length !== 1) return void 0;
1760
- const rawBase = base === "-" ? "_" : base;
1761
- if (!"abcdefghijklmnopqrstuvwxyz[\\]_".includes(rawBase)) return void 0;
1762
- return String.fromCharCode(rawBase.charCodeAt(0) & 31);
1763
- }
1764
- function legacyRawInput(key) {
1765
- const parts = key.split("+");
1766
- const base = parts.at(-1) ?? "";
1767
- if (parts.length === 2 && parts[0] === "ctrl") return rawCtrlInput(base);
1768
- if (isKittyProtocolActive2()) return void 0;
1769
- if (parts.length === 2 && parts[0] === "alt" && base.length === 1) return `\x1B${base}`;
1770
- if (parts.length === 3 && parts[0] === "ctrl" && parts[1] === "alt") {
1771
- const input = rawCtrlInput(base);
1772
- return input ? `\x1B${input}` : void 0;
1773
- }
1774
- return void 0;
1775
- }
1776
- function keyInputIdentity(key) {
1777
- const identity = normalizedKeyId(key);
1778
- const input = legacyRawInput(identity);
1779
- return input ? normalizedKeyId(parseKey(input) ?? identity) : identity;
1780
- }
1781
- function hasManualSelectionCopyApi() {
1782
- return typeof TuiAltScreen.prototype.hasActiveSelection === "function" && typeof TuiAltScreen.prototype.copyActiveSelectionToClipboard === "function";
1783
- }
1784
- function createBtwFullscreenTui(parent, theme, keybindings, copyOnSelect, manualSelectionCopySupported, openUrl, copyToClipboard2) {
1785
- if (!copyOnSelect && !manualSelectionCopySupported) {
1786
- throw new Error(
1787
- "Manual fullscreen selection copying is unavailable in this Pi version; update Pi or enable automatic selection copying."
1788
- );
1789
- }
1790
- const styleSearchMatch = (text) => theme.bg("searchMatchBg", theme.fg("searchMatchText", text));
1791
- const fullscreen = new BtwTuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), void 0, {
1792
- mouse: true,
1793
- copyOnSelect,
1794
- searchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),
1795
- scrollToEndIndicator: () => {
1796
- const unavailableKeyIdentities = /* @__PURE__ */ new Set([keyInputIdentity(Key2.ctrl("c"))]);
1797
- for (const action of ALT_SCREEN_ACTIONS_BEFORE_BOTTOM) {
1798
- for (const actionKey of keybindings.getKeys(action)) {
1799
- unavailableKeyIdentities.add(keyInputIdentity(String(actionKey)));
1800
- }
1801
- }
1802
- if (!copyOnSelect) {
1803
- for (const copyKey of keybindings.getKeys("app.message.copy")) {
1804
- unavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));
1805
- }
1806
- }
1807
- const key = keybindings.getKeys("tui.altScreen.bottom").map((candidate) => keyInputIdentity(String(candidate))).find(
1808
- (identity) => identity && canMatchKeyInput(identity) && !unavailableKeyIdentities.has(identity) && formatEffectiveKeyLabel(identity)
1809
- );
1810
- const label = theme.fg("text", " \u2193 Jump to latest message");
1811
- const shortcut = key ? theme.fg("muted", ` \xB7 ${formatEffectiveKeyLabel(key)}`) : "";
1812
- return theme.bg("selectedBg", `${label}${shortcut} `);
1813
- },
1814
- searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),
1815
- openUrl,
1816
- copySelection: async (text) => {
1817
- try {
1818
- await copyToClipboard2(text);
1819
- return true;
1820
- } catch {
1821
- return false;
1822
- }
1980
+ if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
1981
+ } catch {
1823
1982
  }
1824
- });
1825
- if (!copyOnSelect) {
1826
- let isInBracketedPaste = false;
1827
- fullscreen.addInputListenerBeforeViewport((data) => {
1828
- const wasInBracketedPaste = isInBracketedPaste;
1829
- const startsBracketedPaste = data.includes(BRACKETED_PASTE_START);
1830
- if (startsBracketedPaste) isInBracketedPaste = true;
1831
- if (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {
1832
- isInBracketedPaste = false;
1833
- }
1834
- if (wasInBracketedPaste || startsBracketedPaste || fullscreen.hasFocusedOverlay() || isKeyRelease2(data) || !keybindings.matches(data, "app.message.copy")) {
1835
- return void 0;
1836
- }
1837
- if (!fullscreen.hasActiveSelection()) {
1838
- fullscreen.flash("No selection to copy");
1839
- return { consume: true };
1840
- }
1841
- void fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash("Copy failed"));
1842
- return { consume: true };
1843
- });
1844
1983
  }
1845
- return fullscreen;
1846
- }
1847
- function openUrlInBrowser(target) {
1848
- const [command, args] = process.platform === "darwin" ? ["open", [target]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : ["xdg-open", [target]];
1849
- spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {
1850
- }).unref();
1984
+ if (outcome.kind === "failed") throw outcome.error;
1985
+ return outcome.value;
1851
1986
  }
1852
1987
  var BtwFullscreenHost = class {
1853
1988
  constructor(parent, theme, keybindings, ctx, run, done, createTui, options) {
@@ -1915,15 +2050,23 @@ var BtwFullscreenHost = class {
1915
2050
  if (this.disposed || this.finished) return;
1916
2051
  this.disposed = true;
1917
2052
  this.lifetimeController.abort();
1918
- this.cancelActiveCustom?.();
2053
+ try {
2054
+ this.cancelActiveCustom?.();
2055
+ } finally {
2056
+ this.queueParentRestore();
2057
+ }
1919
2058
  }
1920
2059
  async start() {
1921
2060
  if (this.started || this.finished) return;
1922
2061
  this.started = true;
1923
- this.watchUpstreamCancellation();
1924
2062
  let outcome;
1925
2063
  try {
2064
+ this.watchUpstreamCancellation();
1926
2065
  if (this.disposed) throw new FullscreenUiDisposedError();
2066
+ if ((this.options.layout ?? "fullscreen") !== "fullscreen") {
2067
+ getParentFullscreenLayout(this.parent);
2068
+ getParentFullscreenScrollView(this.parent);
2069
+ }
1927
2070
  this.parent.stop({ preserveScreen: true });
1928
2071
  this.parentStopped = true;
1929
2072
  if (this.disposed) throw new FullscreenUiDisposedError();
@@ -1937,6 +2080,11 @@ var BtwFullscreenHost = class {
1937
2080
  this.options.copyOnSelect ?? true
1938
2081
  );
1939
2082
  setBtwShortcuts(this.fullscreen, shortcuts);
2083
+ setBtwKeybindings(this.fullscreen, this.keybindings);
2084
+ setBtwHostInputBlockers(
2085
+ this.fullscreen,
2086
+ this.options.copyOnSelect === false ? this.keybindings.getKeys("app.message.copy") : []
2087
+ );
1940
2088
  let previousWarnings = [];
1941
2089
  const reportWarnings = () => {
1942
2090
  const warnings = shortcuts.warnings;
@@ -1963,7 +2111,7 @@ var BtwFullscreenHost = class {
1963
2111
  }
1964
2112
  return { consume: true };
1965
2113
  });
1966
- const value = await this.run(this.createContext());
2114
+ const value = await this.runUntilCancelled();
1967
2115
  await this.waitForSidePaneWrites();
1968
2116
  outcome = { kind: "completed", value };
1969
2117
  } catch (error) {
@@ -1981,8 +2129,31 @@ var BtwFullscreenHost = class {
1981
2129
  this.finished = true;
1982
2130
  this.done(outcome);
1983
2131
  }
2132
+ async runUntilCancelled() {
2133
+ const signal = this.lifetimeController.signal;
2134
+ let removeAbort;
2135
+ let cancellation;
2136
+ const cancelled = new Promise((_resolve, reject) => {
2137
+ const onAbort = () => {
2138
+ cancellation ??= setImmediate(() => reject(new FullscreenUiDisposedError()));
2139
+ };
2140
+ signal.addEventListener("abort", onAbort, { once: true });
2141
+ removeAbort = () => signal.removeEventListener("abort", onAbort);
2142
+ if (signal.aborted) onAbort();
2143
+ });
2144
+ try {
2145
+ if (signal.aborted) throw new FullscreenUiDisposedError();
2146
+ return await Promise.race([this.run(this.createContext()), cancelled]);
2147
+ } finally {
2148
+ removeAbort?.();
2149
+ if (cancellation) clearImmediate(cancellation);
2150
+ }
2151
+ }
1984
2152
  watchUpstreamCancellation() {
1985
- const signal = this.ctx.signal;
2153
+ const signals = [this.ctx.signal, this.options.signal].filter(
2154
+ (signal2) => signal2 !== void 0
2155
+ );
2156
+ const signal = signals.length ? AbortSignal.any(signals) : void 0;
1986
2157
  if (!signal) return;
1987
2158
  const onAbort = () => this.dispose();
1988
2159
  signal.addEventListener("abort", onAbort, { once: true });
@@ -2026,7 +2197,11 @@ var BtwFullscreenHost = class {
2026
2197
  } catch (error) {
2027
2198
  this.cleanupError ??= error;
2028
2199
  }
2029
- this.mainThreadInput.dispose();
2200
+ try {
2201
+ this.mainThreadInput.dispose();
2202
+ } catch (error) {
2203
+ this.cleanupError ??= error;
2204
+ }
2030
2205
  const removeUpstreamAbortListener = this.removeUpstreamAbortListener;
2031
2206
  this.removeUpstreamAbortListener = void 0;
2032
2207
  try {
@@ -2059,6 +2234,7 @@ var BtwFullscreenHost = class {
2059
2234
  }
2060
2235
  try {
2061
2236
  this.parentRestoreAttempted = true;
2237
+ if (this.options.canRestoreParent?.() === false) return;
2062
2238
  this.parent.start();
2063
2239
  this.parent.renderNow(false);
2064
2240
  } catch (error) {
@@ -2073,13 +2249,19 @@ var BtwFullscreenHost = class {
2073
2249
  }
2074
2250
  if (property === "notify") {
2075
2251
  return (message, level) => {
2252
+ if (this.disposed || this.finished) return;
2076
2253
  target.notify(message, level);
2077
2254
  const display = sanitizeSingleLine(message);
2078
2255
  if (display) this.fullscreen?.flash?.(display);
2079
2256
  };
2080
2257
  }
2081
2258
  const value = Reflect.get(target, property, target);
2082
- return typeof value === "function" ? value.bind(target) : value;
2259
+ return typeof value === "function" ? (...args) => {
2260
+ if (this.disposed || this.finished || this.lifetimeController.signal.aborted || this.options.canRestoreParent?.() === false) {
2261
+ throw new FullscreenUiDisposedError();
2262
+ }
2263
+ return Reflect.apply(value, target, args);
2264
+ } : value;
2083
2265
  }
2084
2266
  });
2085
2267
  const signal = this.ctx.signal ? AbortSignal.any([this.ctx.signal, this.lifetimeController.signal]) : this.lifetimeController.signal;
@@ -2129,7 +2311,11 @@ var BtwFullscreenHost = class {
2129
2311
  } catch (error) {
2130
2312
  cleanupError = error;
2131
2313
  }
2132
- splitPane?.dispose();
2314
+ try {
2315
+ splitPane?.dispose();
2316
+ } catch (error) {
2317
+ cleanupError ??= error;
2318
+ }
2133
2319
  splitPane = void 0;
2134
2320
  try {
2135
2321
  if (overlay) overlay.hide();
@@ -2250,9 +2436,11 @@ var BtwFullscreenHost = class {
2250
2436
  sideLayout,
2251
2437
  mainThread: this.parent,
2252
2438
  mainLayout: getParentFullscreenLayout(this.parent),
2439
+ mainScrollView: getParentFullscreenScrollView(this.parent),
2253
2440
  mainInput: this.mainThreadInput,
2254
2441
  sideScrollView: isFullscreenLayoutComponent(component) ? component.getPrimaryScrollView?.() : void 0,
2255
2442
  layout: workspaceLayout,
2443
+ shortcuts: getBtwShortcuts(fullscreen),
2256
2444
  theme: this.theme,
2257
2445
  terminalColumns: () => fullscreen.terminal.columns,
2258
2446
  terminalRows: () => fullscreen.terminal.rows,
@@ -2326,7 +2514,18 @@ function getFocusedComponent(tui) {
2326
2514
  function getParentFullscreenLayout(tui) {
2327
2515
  if (tui.mode !== "fullscreen") return void 0;
2328
2516
  const layoutRoot = Reflect.get(tui, "layoutRoot");
2329
- return isComponent(layoutRoot) ? layoutRoot : void 0;
2517
+ if (!isComponent(layoutRoot)) {
2518
+ throw new Error("Pi BTW cannot compose this fullscreen layout; use the fullscreen BTW layout or update Pi.");
2519
+ }
2520
+ return layoutRoot;
2521
+ }
2522
+ function getParentFullscreenScrollView(tui) {
2523
+ if (tui.mode !== "fullscreen") return void 0;
2524
+ const layout = Reflect.get(tui, "currentLayout");
2525
+ if (!layout || !(layout.primaryScrollView instanceof ScrollView2)) {
2526
+ throw new Error("Pi BTW cannot identify this fullscreen viewport; use the fullscreen BTW layout or update Pi.");
2527
+ }
2528
+ return layout.primaryScrollView;
2330
2529
  }
2331
2530
  function isComponent(value) {
2332
2531
  return typeof value === "object" && value !== null && "render" in value && typeof value.render === "function" && "invalidate" in value && typeof value.invalidate === "function";
@@ -2423,7 +2622,8 @@ async function showBtwCommandMenu(ctx, options) {
2423
2622
  const shortcutLabels = {
2424
2623
  exit: "Exit shortcut",
2425
2624
  cycleThinkingLevel: "Cycle thinking level shortcut",
2426
- bringToMain: "Bring to main shortcut"
2625
+ bringToMain: "Bring to main shortcut",
2626
+ switchPane: "Switch pane shortcut"
2427
2627
  };
2428
2628
  const shortcutValue = (settings, action) => {
2429
2629
  if (!keybindings) return "Default";
@@ -2842,7 +3042,7 @@ async function showBtwCommandMenu(ctx, options) {
2842
3042
  });
2843
3043
  const result = await runBtwMenuPreservingEditor(
2844
3044
  ctx,
2845
- (menuContext) => runMenu(menuContext, menu, { getState: loadState }),
3045
+ (menuContext) => runMenu(menuContext, menu, { getState: loadState, signal: ctx.signal }),
2846
3046
  (manager) => {
2847
3047
  keybindings = manager;
2848
3048
  }
@@ -2853,36 +3053,46 @@ async function showBtwCommandMenu(ctx, options) {
2853
3053
  return startSelected ? "start" : "closed";
2854
3054
  }
2855
3055
  async function showBtwCustomPreservingEditor(ctx, factory) {
3056
+ const { runCustomInteraction } = await import("@narumitw/pi-tui-kit");
3057
+ if (ctx.signal?.aborted) return void 0;
2856
3058
  let liveEditorText = ctx.ui.getEditorText();
2857
3059
  let completed = false;
2858
- const result = await ctx.ui.custom(
2859
- (tui, theme, keybindings, done) => factory(tui, theme, keybindings, (value) => {
3060
+ const result = await runCustomInteraction(ctx, {
3061
+ signal: ctx.signal,
3062
+ create: ({ tui, theme, keybindings, complete }) => factory(tui, theme, keybindings, (value) => {
3063
+ if (ctx.signal?.aborted) return;
2860
3064
  try {
2861
3065
  liveEditorText = ctx.ui.getEditorText();
2862
3066
  } catch {
2863
3067
  }
2864
3068
  completed = true;
2865
- done(value);
3069
+ complete(value);
2866
3070
  })
2867
- );
2868
- if (completed) {
3071
+ });
3072
+ if (result.kind === "error") throw result.error;
3073
+ if (!ctx.signal?.aborted && completed) {
2869
3074
  try {
2870
3075
  if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
2871
3076
  } catch {
2872
3077
  }
2873
3078
  }
2874
- return result;
3079
+ return result.kind === "completed" ? result.value : void 0;
2875
3080
  }
2876
3081
  async function runBtwMenuPreservingEditor(ctx, run, onKeybindings) {
3082
+ if (ctx.signal?.aborted) return { kind: "stale" };
2877
3083
  let liveEditorText = ctx.ui.getEditorText();
2878
3084
  let completed = false;
2879
3085
  const ui = new Proxy(ctx.ui, {
2880
3086
  get(target, property) {
2881
3087
  if (property === "custom") {
2882
- return (factory, customOptions) => target.custom((tui, theme, keybindings, done) => {
3088
+ return (factory, customOptions) => ctx.signal?.aborted ? Promise.resolve(void 0) : target.custom((tui, theme, keybindings, done) => {
2883
3089
  onKeybindings?.(keybindings);
2884
3090
  return factory(tui, theme, keybindings, (value2) => {
2885
3091
  try {
3092
+ if (ctx.signal?.aborted) {
3093
+ done(value2);
3094
+ return;
3095
+ }
2886
3096
  liveEditorText = target.getEditorText();
2887
3097
  } catch {
2888
3098
  }
@@ -2896,7 +3106,7 @@ async function runBtwMenuPreservingEditor(ctx, run, onKeybindings) {
2896
3106
  }
2897
3107
  });
2898
3108
  const result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });
2899
- if (result.kind !== "stale" && completed) {
3109
+ if (!ctx.signal?.aborted && result.kind !== "stale" && completed) {
2900
3110
  try {
2901
3111
  if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
2902
3112
  } catch {
@@ -2940,6 +3150,7 @@ function notifySaveFailure(ctx, error) {
2940
3150
  );
2941
3151
  }
2942
3152
  function notifySafely(ctx, message, level) {
3153
+ if (ctx.signal?.aborted) return;
2943
3154
  try {
2944
3155
  ctx.ui.notify(sanitizeSingleLine(message), level);
2945
3156
  } catch {
@@ -3259,6 +3470,63 @@ function formatError5(error) {
3259
3470
  return error instanceof Error ? error.message : String(error);
3260
3471
  }
3261
3472
 
3473
+ // src/session-lifetime.ts
3474
+ var BtwSessionLifetime = class {
3475
+ controller = new AbortController();
3476
+ tasks = /* @__PURE__ */ new Set();
3477
+ restoreParent = true;
3478
+ shutdown;
3479
+ get signal() {
3480
+ return this.controller.signal;
3481
+ }
3482
+ canRestoreParent = () => this.restoreParent;
3483
+ track(task) {
3484
+ this.tasks.add(task);
3485
+ void task.then(
3486
+ () => this.tasks.delete(task),
3487
+ () => this.tasks.delete(task)
3488
+ );
3489
+ return task;
3490
+ }
3491
+ stop(quit) {
3492
+ if (quit) this.restoreParent = false;
3493
+ if (this.shutdown) return this.shutdown;
3494
+ this.controller.abort(new DOMException("Pi BTW session ended", "AbortError"));
3495
+ this.shutdown = (async () => {
3496
+ try {
3497
+ await Promise.allSettled([...this.tasks]);
3498
+ await awaitBtwSettingsWrites();
3499
+ } finally {
3500
+ this.restoreParent = false;
3501
+ }
3502
+ })();
3503
+ return this.shutdown;
3504
+ }
3505
+ };
3506
+ function registerBtwSessionLifetimes(pi) {
3507
+ const sessions = /* @__PURE__ */ new WeakMap();
3508
+ let previous;
3509
+ pi.on("session_start", async (_event, ctx) => {
3510
+ const replaced = previous;
3511
+ const lifetime = new BtwSessionLifetime();
3512
+ sessions.set(ctx.sessionManager, lifetime);
3513
+ previous = lifetime;
3514
+ await replaced?.stop(false);
3515
+ });
3516
+ pi.on("session_shutdown", async (event, ctx) => {
3517
+ await sessions.get(ctx.sessionManager)?.stop(event.reason === "quit");
3518
+ });
3519
+ return (ctx) => {
3520
+ let lifetime = sessions.get(ctx.sessionManager);
3521
+ if (!lifetime) {
3522
+ lifetime = new BtwSessionLifetime();
3523
+ sessions.set(ctx.sessionManager, lifetime);
3524
+ previous = lifetime;
3525
+ }
3526
+ return lifetime;
3527
+ };
3528
+ }
3529
+
3262
3530
  // src/transcript-markdown.ts
3263
3531
  var MERMAID_MARKDOWN_MODULE = "@narumitw/pi-tui-kit/markdown";
3264
3532
  var noMarkdownTransformers = () => [];
@@ -3311,20 +3579,191 @@ import {
3311
3579
  import {
3312
3580
  CURSOR_MARKER,
3313
3581
  Editor,
3314
- Key as Key4,
3315
- Loader,
3316
- Markdown,
3317
- matchesKey as matchesKey4,
3318
- ScrollView as ScrollView2,
3319
- truncateToWidth as truncateToWidth4,
3582
+ isKeyRelease as isKeyRelease4,
3583
+ renderFakeCursor,
3584
+ ScrollView as ScrollView3,
3585
+ Spacer,
3586
+ Text,
3587
+ truncateToWidth as truncateToWidth5,
3320
3588
  VStack,
3321
- visibleWidth as visibleWidth3
3589
+ visibleWidth as visibleWidth4
3322
3590
  } from "@earendil-works/pi-tui";
3323
- var TRANSCRIPT_CHROME_LINES = 2;
3591
+
3592
+ // src/conversation-chrome.ts
3593
+ import { Loader, truncateToWidth as truncateToWidth4, visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
3594
+ var BtwWorkingIndicator = class extends Loader {
3595
+ renderInBorder(width) {
3596
+ const line = super.render(width + 2)[1] ?? "";
3597
+ return truncateToWidth4(line.startsWith(" ") ? line.slice(1).trimEnd() : line.trimEnd(), width, "");
3598
+ }
3599
+ renderSpinnerInBorder(width) {
3600
+ return truncateToWidth4(this.getRenderedIndicator(), width, "");
3601
+ }
3602
+ };
3603
+ function renderWorkingBorder(width, hiddenLineCount, borderColor, status) {
3604
+ if (width <= 0) return "";
3605
+ let label = status.renderInBorder(Math.max(1, width - 5));
3606
+ let labelWidth = visibleWidth3(label);
3607
+ if (labelWidth === 0) return void 0;
3608
+ const overflow = hiddenLineCount > 0 ? ` \u2191 ${hiddenLineCount} more ` : void 0;
3609
+ const overflowWidth = overflow ? visibleWidth3(overflow) : 0;
3610
+ const overflowStart = Math.floor((width - overflowWidth) / 2);
3611
+ const fitsOverflow = () => overflow !== void 0 && overflowWidth + 2 <= width && overflowStart - (3 + labelWidth + 1) >= 1;
3612
+ if (overflow && !fitsOverflow()) {
3613
+ label = status.renderSpinnerInBorder(width);
3614
+ labelWidth = visibleWidth3(label);
3615
+ }
3616
+ if (fitsOverflow()) {
3617
+ const leftWidth = 3 + labelWidth + 1;
3618
+ return borderColor("\u2500\u2500 ") + label + borderColor(
3619
+ ` ${"\u2500".repeat(overflowStart - leftWidth)}${overflow}${"\u2500".repeat(width - overflowStart - overflowWidth)}`
3620
+ );
3621
+ }
3622
+ if (width >= labelWidth + 5) {
3623
+ return borderColor("\u2500\u2500 ") + label + borderColor(` ${"\u2500".repeat(width - labelWidth - 4)}`);
3624
+ }
3625
+ label = status.renderSpinnerInBorder(width);
3626
+ labelWidth = visibleWidth3(label);
3627
+ const prefix = Math.min(3, Math.max(0, width - labelWidth));
3628
+ return borderColor("\u2500".repeat(prefix)) + label + borderColor("\u2500".repeat(Math.max(0, width - prefix - labelWidth)));
3629
+ }
3630
+ function renderConversationFooter(width, theme, options) {
3631
+ if (width < 3) return [];
3632
+ const focus = options.focus ? `${options.focus.pane === "side" ? "BTW" : "Main"} focus` : void 0;
3633
+ const left = focus && visibleWidth3(`btw \xB7 ${focus}`) <= width ? `btw \xB7 ${focus}` : "btw";
3634
+ const model = options.model ? sanitizeSingleLine(`${options.model.provider}/${options.model.id}`) : "";
3635
+ const thinking = options.thinkingLevel ? `thinking ${options.thinkingLevel}` : "";
3636
+ const right = [[model, thinking].filter(Boolean).join(" \u2022 "), thinking, model].find(
3637
+ (value) => value && visibleWidth3(left) + 2 + visibleWidth3(value) <= width
3638
+ );
3639
+ const identity = right ? `${left}${" ".repeat(width - visibleWidth3(left) - visibleWidth3(right))}${right}` : left;
3640
+ return [
3641
+ theme.fg("dim", identity),
3642
+ ...options.hint ? [theme.fg(options.warning ? "warning" : "muted", options.hint)] : []
3643
+ ];
3644
+ }
3645
+
3646
+ // src/transcript-pager.ts
3324
3647
  var MAX_STEERING_DISPLAY_LINES = 3;
3325
3648
  var OSC133_MARKERS = ["\x1B]133;A\x07", "\x1B]133;B\x07", "\x1B]133;C\x07"];
3326
3649
  var RESERVED_APP_LINES = 3;
3327
- var PreservingScrollView = class extends ScrollView2 {
3650
+ var BtwComposer = class extends Editor {
3651
+ constructor(tui, theme, dispatch, loader) {
3652
+ super(tui, theme);
3653
+ this.dispatch = dispatch;
3654
+ this.loader = loader;
3655
+ }
3656
+ dispatch;
3657
+ loader;
3658
+ handleInput(data) {
3659
+ this.dispatch(data);
3660
+ }
3661
+ handleEditorInput(data) {
3662
+ super.handleInput(data);
3663
+ }
3664
+ render(width) {
3665
+ if (width <= 0) return [];
3666
+ return super.render(Math.max(3, width)).map((line) => {
3667
+ if (width <= 2 && line.includes(CURSOR_MARKER))
3668
+ return CURSOR_MARKER + renderFakeCursor(" ") + " ".repeat(width - 1);
3669
+ return truncateToWidth5(line, width, "");
3670
+ });
3671
+ }
3672
+ renderTopBorder(width, hiddenLineCount) {
3673
+ if (!this.loader) return super.renderTopBorder(width, hiddenLineCount);
3674
+ return renderWorkingBorder(width, hiddenLineCount, this.borderColor, this.loader) ?? super.renderTopBorder(width, hiddenLineCount);
3675
+ }
3676
+ };
3677
+ var VIEWPORT_ACTIONS = [
3678
+ "tui.altScreen.search",
3679
+ "tui.altScreen.pageUp",
3680
+ "tui.altScreen.pageDown",
3681
+ "tui.altScreen.halfPageUp",
3682
+ "tui.altScreen.halfPageDown",
3683
+ "tui.altScreen.lineUp",
3684
+ "tui.altScreen.lineDown",
3685
+ "tui.altScreen.previousPrompt",
3686
+ "tui.altScreen.nextPrompt",
3687
+ "tui.altScreen.top",
3688
+ "tui.altScreen.bottom"
3689
+ ];
3690
+ var BEFORE_SUBMIT = [
3691
+ "tui.input.copy",
3692
+ "tui.editor.undo",
3693
+ "tui.input.tab",
3694
+ "tui.editor.deleteToLineEnd",
3695
+ "tui.editor.deleteToLineStart",
3696
+ "tui.editor.deleteWordBackward",
3697
+ "tui.editor.deleteWordForward",
3698
+ "tui.editor.deleteCharBackward",
3699
+ "tui.editor.deleteCharForward",
3700
+ "tui.editor.yank",
3701
+ "tui.editor.yankPop",
3702
+ "tui.editor.historyPrevious",
3703
+ "tui.editor.historyNext",
3704
+ "tui.editor.cursorLineStart",
3705
+ "tui.editor.cursorLineEnd",
3706
+ "tui.editor.cursorWordLeft",
3707
+ "tui.editor.cursorWordRight",
3708
+ "tui.input.newLine"
3709
+ ];
3710
+ function usableKeys(keybindings, action, blockers) {
3711
+ return keybindings.getKeys(action).flatMap((candidate) => {
3712
+ const key = normalizeBtwKey(candidate);
3713
+ return key && btwKeyHasReachableInput(key, blockers) ? [key] : [];
3714
+ });
3715
+ }
3716
+ function submitHint(tui, keybindings, verb) {
3717
+ const earlier = tui.mode === "fullscreen" ? VIEWPORT_ACTIONS : ["tui.altScreen.pageUp", "tui.altScreen.pageDown"];
3718
+ const blockers = [
3719
+ ...getBtwHostInputBlockers(tui),
3720
+ "ctrl+c",
3721
+ "shift+backspace",
3722
+ "shift+delete",
3723
+ ...[...earlier, ...BEFORE_SUBMIT].flatMap((id) => keybindings.getKeys(id))
3724
+ ];
3725
+ const key = usableKeys(keybindings, "tui.input.submit", blockers)[0];
3726
+ return key ? `${formatKeyLabel2(key)} ${verb}` : "";
3727
+ }
3728
+ function pagingHint(tui, keybindings) {
3729
+ const actions = ["tui.altScreen.pageUp", "tui.altScreen.pageDown"];
3730
+ const labels = actions.flatMap((action) => {
3731
+ const earlier = tui.mode === "fullscreen" ? VIEWPORT_ACTIONS.slice(0, VIEWPORT_ACTIONS.indexOf(action)) : action === "tui.altScreen.pageDown" ? ["tui.altScreen.pageUp"] : [];
3732
+ const blockers = [...getBtwHostInputBlockers(tui), "ctrl+c", ...earlier.flatMap((id) => keybindings.getKeys(id))];
3733
+ const key = usableKeys(keybindings, action, blockers)[0];
3734
+ return key ? [
3735
+ formatKeyLabel2(key).replace(/Pageup$/u, "PgUp").replace(/Pagedown$/u, "PgDn")
3736
+ ] : [];
3737
+ });
3738
+ return labels.length ? `${labels.join("/")} history` : "";
3739
+ }
3740
+ function handleFallbackPaging(data, tui, keybindings, scrollView) {
3741
+ if (tui.mode === "fullscreen" || isKeyRelease4(data)) return false;
3742
+ for (const [action, direction] of [
3743
+ ["tui.altScreen.pageUp", -1],
3744
+ ["tui.altScreen.pageDown", 1]
3745
+ ]) {
3746
+ if (keybindings.matches(data, action)) {
3747
+ scrollView.scrollBy(direction * Math.max(1, scrollView.viewportHeight - 4));
3748
+ return true;
3749
+ }
3750
+ }
3751
+ return false;
3752
+ }
3753
+ function fittingHint(width, variants) {
3754
+ return variants.find((hint) => visibleWidth4(hint) <= Math.max(0, width)) ?? "";
3755
+ }
3756
+ function compactHints(parts) {
3757
+ return parts.filter(Boolean).join(" \u2022 ");
3758
+ }
3759
+ function releaseScrollbar(scrollView) {
3760
+ scrollView.setScrollbarActive(false);
3761
+ scrollView.setScrollbar("hidden");
3762
+ }
3763
+ function thinkingBorder(theme, level, text) {
3764
+ return level && theme.getThinkingBorderColor ? theme.getThinkingBorderColor(level)(text) : theme.fg("borderMuted", text);
3765
+ }
3766
+ var PreservingScrollView = class extends ScrollView3 {
3328
3767
  updateLayout(contentHeight, viewportHeight, requestRender) {
3329
3768
  const preserveManualPosition = !this.isFollowingEnd;
3330
3769
  super.updateLayout(contentHeight, viewportHeight, requestRender);
@@ -3339,12 +3778,12 @@ var BtwTranscriptPager = class {
3339
3778
  this.theme = theme;
3340
3779
  this.onAction = onAction;
3341
3780
  this.options = options;
3342
- this.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);
3781
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
3343
3782
  this.transcriptComponents = buildTranscriptComponents(turns, this.theme, void 0, options.markdownTransformers);
3344
3783
  this.canBringToMain = turns.some((turn) => turn.kind === "answered");
3345
3784
  this.thinkingLevel = options.thinking?.level;
3346
3785
  const editorTheme = {
3347
- borderColor: (text) => this.theme.fg("accent", text),
3786
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
3348
3787
  selectList: {
3349
3788
  selectedPrefix: (text) => this.theme.fg("accent", text),
3350
3789
  selectedText: (text) => this.theme.fg("accent", text),
@@ -3353,7 +3792,7 @@ var BtwTranscriptPager = class {
3353
3792
  noMatch: (text) => this.theme.fg("warning", text)
3354
3793
  }
3355
3794
  };
3356
- this.editor = new Editor(this.tui, editorTheme);
3795
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data));
3357
3796
  if (options.initialQuestion) this.editor.setText(options.initialQuestion);
3358
3797
  this.editor.onChange = () => {
3359
3798
  this.warning = void 0;
@@ -3369,20 +3808,34 @@ var BtwTranscriptPager = class {
3369
3808
  };
3370
3809
  const transcript = this.createTranscriptComponent();
3371
3810
  this.scrollView = new PreservingScrollView(transcript, {
3372
- follow: options.startAtBottom ? "end" : "none",
3373
- primary: true
3811
+ follow: "end",
3812
+ primary: true,
3813
+ scrollbar: "auto",
3814
+ scrollbarTrackStyle: (text) => this.theme.fg("scrollbarTrack", text),
3815
+ scrollbarThumbStyle: (text) => this.theme.fg("scrollbarThumb", text)
3374
3816
  });
3817
+ if (!options.startAtBottom) this.scrollView.scrollTo(0, { disableFollow: true });
3818
+ const dock = new VStack([
3819
+ { component: this.editor, basis: "auto", shrink: 1, minSize: 1 },
3820
+ { component: this.createFooterComponent(), basis: "auto", shrink: 1, minSize: 0 }
3821
+ ]);
3375
3822
  this.layoutRoot = new VStack([
3376
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
3377
3823
  { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
3378
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
3379
- { component: this.editor, basis: "auto", shrink: 1, minSize: 0 }
3824
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
3380
3825
  ]);
3381
3826
  }
3382
3827
  tui;
3383
3828
  theme;
3384
3829
  onAction;
3385
3830
  options;
3831
+ workspaceFocus;
3832
+ get keybindings() {
3833
+ return getBtwKeybindings(this.tui, this.options.keybindings ?? this.options.thinking?.keybindings);
3834
+ }
3835
+ setWorkspaceFocus(pane, shortcutLabel) {
3836
+ this.workspaceFocus = { pane, shortcutLabel: shortcutLabel ? sanitizeSingleLine(shortcutLabel) : void 0 };
3837
+ this.tui.requestRender();
3838
+ }
3386
3839
  shortcuts;
3387
3840
  pasteGuard = new BtwPasteGuard();
3388
3841
  transcriptComponents;
@@ -3409,26 +3862,25 @@ var BtwTranscriptPager = class {
3409
3862
  return this.scrollView;
3410
3863
  }
3411
3864
  render(width) {
3412
- if (width <= 0) return [];
3865
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
3413
3866
  const safeWidth = Math.max(1, width);
3414
3867
  const editorLines = this.editor.render(safeWidth);
3415
3868
  const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
3416
- const viewportHeight = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
3417
3869
  const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
3418
3870
  this.lastContentLineCount = contentLines.length;
3871
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - this.renderFooter(safeWidth).length);
3419
3872
  this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
3420
3873
  return fitComposerLayout(
3421
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
3422
3874
  contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
3423
3875
  this.renderFooter(safeWidth),
3424
3876
  editorLines,
3425
3877
  availableRows
3426
- ).map((line) => truncateToWidth4(line, safeWidth));
3878
+ ).map((line) => truncateToWidth5(line, safeWidth));
3427
3879
  }
3428
3880
  handleInput(data) {
3429
3881
  if (this.finished) return;
3430
3882
  if (this.pasteGuard.consume(data)) {
3431
- this.editor.handleInput(data);
3883
+ this.editor.handleEditorInput(data);
3432
3884
  this.tui.requestRender();
3433
3885
  return;
3434
3886
  }
@@ -3454,73 +3906,54 @@ var BtwTranscriptPager = class {
3454
3906
  }
3455
3907
  return;
3456
3908
  }
3457
- if (matchesKey4(data, Key4.pageUp)) {
3458
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
3459
- this.tui.requestRender();
3460
- return;
3461
- }
3462
- if (matchesKey4(data, Key4.pageDown)) {
3463
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
3464
- this.tui.requestRender();
3465
- return;
3909
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
3910
+ this.editor.handleEditorInput(data);
3466
3911
  }
3467
- this.editor.handleInput(data);
3468
3912
  if (!this.finished) this.tui.requestRender();
3469
3913
  }
3470
3914
  invalidate() {
3471
3915
  this.layoutRoot.invalidate();
3472
3916
  }
3473
3917
  dispose() {
3918
+ releaseScrollbar(this.scrollView);
3474
3919
  if (this.finished) return;
3475
3920
  this.finished = true;
3476
3921
  this.onAction({ kind: "close" });
3477
3922
  }
3478
3923
  renderFooter(width) {
3924
+ return renderConversationFooter(width, this.theme, {
3925
+ model: this.options.model,
3926
+ thinkingLevel: this.thinkingLevel,
3927
+ focus: this.workspaceFocus,
3928
+ hint: this.renderHints(width),
3929
+ warning: this.warning !== void 0
3930
+ });
3931
+ }
3932
+ renderHints(width) {
3479
3933
  const exit = this.shortcuts.label("exit");
3480
3934
  const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;
3481
3935
  const bringKey = this.shortcuts.label("bringToMain");
3482
- if (this.warning) {
3483
- const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} exit`;
3484
- return truncateToWidth4(this.theme.fg("warning", warning), width);
3485
- }
3486
- const scrollable = this.getMaxScrollOffset() > 0;
3936
+ if (this.warning) return fittingHint(width, [`${this.warning} \u2022 ${exit} exit`, `Empty \u2022 ${exit}`, exit]);
3487
3937
  const thinking = this.options.thinking;
3488
- const cycleHint = thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length ? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label("cycleThinkingLevel")} cycle` : "";
3489
- const base = bring ? `btw \u2022 Enter send \u2022 ${bringKey} bring to main \u2022 ${exit} exit` : `btw \u2022 Enter send \u2022 ${exit} exit`;
3490
- const fullBase = `${base}${cycleHint}`;
3491
- const fallbackBase = `btw \u2022 Enter \u2022 ${exit}`;
3492
- const compactBase = bring ? `btw \u2022 Enter \u2022 ${bringKey} \u2022 ${exit}` : fallbackBase;
3493
- const compactWithThinking = `${compactBase}${cycleHint}`;
3494
- let hints = visibleWidth3(fullBase) <= width ? fullBase : visibleWidth3(compactWithThinking) <= width ? compactWithThinking : visibleWidth3(compactBase) <= width ? compactBase : fallbackBase;
3495
- if (scrollable) {
3496
- const history = ` \u2022 ${this.scrollView.scrollTop > 0 ? "\u2191 older" : "\u2193 newer"} \u2022 PgUp/PgDn history`;
3497
- const compactHistory = " \u2022 PgUp/PgDn";
3498
- const compactScrollable = bring ? `Enter \u2022 ${bringKey} \u2022 ${exit} \u2022 PgUp/PgDn` : `${fallbackBase}${compactHistory}`;
3499
- if (visibleWidth3(`${hints}${history}`) <= width) {
3500
- hints += history;
3501
- } else if (visibleWidth3(`${compactBase}${history}`) <= width) {
3502
- hints = `${compactBase}${history}`;
3503
- } else if (visibleWidth3(`${hints}${compactHistory}`) <= width) {
3504
- hints += compactHistory;
3505
- } else if (visibleWidth3(`${compactBase}${compactHistory}`) <= width) {
3506
- hints = `${compactBase}${compactHistory}`;
3507
- } else if (visibleWidth3(compactScrollable) <= width) {
3508
- hints = compactScrollable;
3509
- }
3510
- }
3511
- return truncateToWidth4(this.theme.fg("muted", hints), width);
3512
- }
3513
- createHeaderComponent() {
3514
- return {
3515
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
3516
- invalidate() {
3517
- }
3518
- };
3938
+ const cycle = thinking && thinking.levels.length > 1 && this.shortcuts.keys.cycleThinkingLevel.length ? `${this.shortcuts.label("cycleThinkingLevel")} thinking` : "";
3939
+ const submit = submitHint(this.tui, this.keybindings, "send");
3940
+ const history = this.getMaxScrollOffset() > 0 ? pagingHint(this.tui, this.keybindings) : "";
3941
+ const switchPane = this.workspaceFocus?.shortcutLabel ? `${this.workspaceFocus.shortcutLabel} switch` : "";
3942
+ const submitKey = submit.split(" ")[0] ?? "";
3943
+ return fittingHint(width, [
3944
+ compactHints([submit, bring ? `${bringKey} bring to main` : "", `${exit} exit`, cycle, history, switchPane]),
3945
+ compactHints([submit, bring ? bringKey : "", exit, cycle, history, switchPane]),
3946
+ compactHints([submitKey, bring ? bringKey : "", exit, cycle, history.replace(/ history$/u, ""), switchPane]),
3947
+ compactHints([submitKey, bring ? bringKey : "", exit, history.replace(/ history$/u, "")]),
3948
+ compactHints([submitKey, bring ? bringKey : "", exit]),
3949
+ compactHints([submitKey, exit]),
3950
+ exit
3951
+ ]);
3519
3952
  }
3520
3953
  createTranscriptComponent() {
3521
3954
  return {
3522
3955
  render: (width) => {
3523
- const lines = renderTranscriptLines(this.transcriptComponents, width);
3956
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
3524
3957
  this.lastContentLineCount = lines.length;
3525
3958
  return lines;
3526
3959
  },
@@ -3531,7 +3964,7 @@ var BtwTranscriptPager = class {
3531
3964
  }
3532
3965
  createFooterComponent() {
3533
3966
  return {
3534
- render: (width) => [this.renderFooter(width)],
3967
+ render: (width) => this.renderFooter(width),
3535
3968
  invalidate() {
3536
3969
  }
3537
3970
  };
@@ -3546,7 +3979,7 @@ var BtwAnsweringView = class {
3546
3979
  this.theme = theme;
3547
3980
  this.onCancel = onCancel;
3548
3981
  this.options = options;
3549
- this.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);
3982
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
3550
3983
  this.transcriptComponents = buildTranscriptComponents(
3551
3984
  turns,
3552
3985
  this.theme,
@@ -3554,7 +3987,7 @@ var BtwAnsweringView = class {
3554
3987
  options.markdownTransformers
3555
3988
  );
3556
3989
  this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;
3557
- this.loader = new Loader(
3990
+ this.loader = new BtwWorkingIndicator(
3558
3991
  this.tui,
3559
3992
  (text) => this.theme.fg("accent", text),
3560
3993
  (text) => this.theme.fg("muted", text),
@@ -3562,7 +3995,7 @@ var BtwAnsweringView = class {
3562
3995
  );
3563
3996
  if (options.steering) {
3564
3997
  const editorTheme = {
3565
- borderColor: (text) => this.theme.fg("accent", text),
3998
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
3566
3999
  selectList: {
3567
4000
  selectedPrefix: (text) => this.theme.fg("accent", text),
3568
4001
  selectedText: (text) => this.theme.fg("accent", text),
@@ -3571,7 +4004,7 @@ var BtwAnsweringView = class {
3571
4004
  noMatch: (text) => this.theme.fg("warning", text)
3572
4005
  }
3573
4006
  };
3574
- this.editor = new Editor(this.tui, editorTheme);
4007
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data), this.loader);
3575
4008
  this.editor.onChange = () => {
3576
4009
  this.warning = void 0;
3577
4010
  };
@@ -3586,10 +4019,14 @@ var BtwAnsweringView = class {
3586
4019
  };
3587
4020
  }
3588
4021
  const transcript = this.createTranscriptComponent();
3589
- this.scrollView = new PreservingScrollView(transcript, { follow: "end", primary: true });
3590
- this.layoutRoot = new VStack([
3591
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
3592
- { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
4022
+ this.scrollView = new PreservingScrollView(transcript, {
4023
+ follow: "end",
4024
+ primary: true,
4025
+ scrollbar: "auto",
4026
+ scrollbarTrackStyle: (text) => this.theme.fg("scrollbarTrack", text),
4027
+ scrollbarThumbStyle: (text) => this.theme.fg("scrollbarThumb", text)
4028
+ });
4029
+ const dock = new VStack([
3593
4030
  {
3594
4031
  component: this.createSteeringComponent(),
3595
4032
  basis: "auto",
@@ -3597,14 +4034,26 @@ var BtwAnsweringView = class {
3597
4034
  minSize: 0,
3598
4035
  maxSize: MAX_STEERING_DISPLAY_LINES
3599
4036
  },
3600
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
3601
- ...this.editor ? [{ component: this.editor, basis: "auto", shrink: 1, minSize: 0 }] : []
4037
+ { component: this.editor ?? this.createWorkingComponent(), basis: "auto", shrink: 1, minSize: 1 },
4038
+ { component: this.createFooterComponent(), basis: "auto", shrink: 1, minSize: 0 }
4039
+ ]);
4040
+ this.layoutRoot = new VStack([
4041
+ { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
4042
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
3602
4043
  ]);
3603
4044
  }
3604
4045
  tui;
3605
4046
  theme;
3606
4047
  onCancel;
3607
4048
  options;
4049
+ workspaceFocus;
4050
+ get keybindings() {
4051
+ return getBtwKeybindings(this.tui, this.options.keybindings ?? this.options.steering?.thinking?.keybindings);
4052
+ }
4053
+ setWorkspaceFocus(pane, shortcutLabel) {
4054
+ this.workspaceFocus = { pane, shortcutLabel: shortcutLabel ? sanitizeSingleLine(shortcutLabel) : void 0 };
4055
+ this.tui.requestRender();
4056
+ }
3608
4057
  shortcuts;
3609
4058
  pasteGuard = new BtwPasteGuard();
3610
4059
  transcriptComponents;
@@ -3635,37 +4084,34 @@ var BtwAnsweringView = class {
3635
4084
  return this.scrollView;
3636
4085
  }
3637
4086
  render(width) {
3638
- if (width <= 0) return [];
4087
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
3639
4088
  const safeWidth = Math.max(1, width);
3640
4089
  const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
3641
- const editorLines = this.editor?.render(safeWidth) ?? [];
3642
- const steeringCapacity = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
4090
+ const editorLines = this.editor?.render(safeWidth) ?? this.renderWorking(safeWidth);
4091
+ const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
4092
+ this.lastContentLineCount = contentLines.length;
4093
+ const footerLines = this.renderFooter(safeWidth);
4094
+ const steeringCapacity = Math.max(0, availableRows - editorLines.length - footerLines.length);
3643
4095
  const steeringLines = renderSteeringLines(
3644
4096
  this.options.steering?.questions ?? [],
3645
4097
  safeWidth,
3646
4098
  this.theme,
3647
4099
  Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity)
3648
4100
  );
3649
- const viewportHeight = Math.max(
3650
- 0,
3651
- availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length
3652
- );
3653
- const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
3654
- this.lastContentLineCount = contentLines.length;
4101
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - footerLines.length - steeringLines.length);
3655
4102
  this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
3656
4103
  return fitComposerLayout(
3657
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
3658
4104
  contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
3659
4105
  this.renderFooter(safeWidth),
3660
4106
  editorLines,
3661
4107
  availableRows,
3662
4108
  steeringLines
3663
- ).map((line) => truncateToWidth4(line, safeWidth));
4109
+ ).map((line) => truncateToWidth5(line, safeWidth));
3664
4110
  }
3665
4111
  handleInput(data) {
3666
4112
  if (this.finished) return;
3667
4113
  if (this.pasteGuard.consume(data)) {
3668
- this.editor?.handleInput(data);
4114
+ this.editor?.handleEditorInput(data);
3669
4115
  this.tui.requestRender();
3670
4116
  return;
3671
4117
  }
@@ -3688,17 +4134,9 @@ var BtwAnsweringView = class {
3688
4134
  }
3689
4135
  return;
3690
4136
  }
3691
- if (matchesKey4(data, Key4.pageUp)) {
3692
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
3693
- this.tui.requestRender();
3694
- return;
3695
- }
3696
- if (matchesKey4(data, Key4.pageDown)) {
3697
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
3698
- this.tui.requestRender();
3699
- return;
4137
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
4138
+ this.editor?.handleEditorInput(data);
3700
4139
  }
3701
- this.editor?.handleInput(data);
3702
4140
  this.tui.requestRender();
3703
4141
  }
3704
4142
  invalidate() {
@@ -3706,9 +4144,11 @@ var BtwAnsweringView = class {
3706
4144
  }
3707
4145
  finish() {
3708
4146
  this.finished = true;
4147
+ releaseScrollbar(this.scrollView);
3709
4148
  this.loader.stop();
3710
4149
  }
3711
4150
  dispose() {
4151
+ releaseScrollbar(this.scrollView);
3712
4152
  if (this.finished) {
3713
4153
  this.loader.stop();
3714
4154
  this.controller.abort();
@@ -3720,33 +4160,42 @@ var BtwAnsweringView = class {
3720
4160
  this.onCancel();
3721
4161
  }
3722
4162
  renderFooter(width) {
4163
+ return renderConversationFooter(width, this.theme, {
4164
+ model: this.options.model,
4165
+ thinkingLevel: this.thinkingLevel,
4166
+ focus: this.workspaceFocus,
4167
+ hint: this.renderHints(width),
4168
+ warning: this.warning !== void 0
4169
+ });
4170
+ }
4171
+ renderHints(width) {
3723
4172
  const exit = this.shortcuts.label("exit");
3724
- if (this.warning) {
3725
- const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} cancel`;
3726
- return truncateToWidth4(this.theme.fg("warning", warning), width);
3727
- }
3728
- const baseHint = this.editor ? `Enter steer \u2022 ${exit} cancel` : `${exit} cancel`;
4173
+ if (this.warning) return fittingHint(width, [`${this.warning} \u2022 ${exit} cancel`, `Empty \u2022 ${exit}`, exit]);
4174
+ const submit = this.editor ? submitHint(this.tui, this.keybindings, "queue next") : "";
3729
4175
  const thinking = this.options.steering?.thinking;
3730
- const cycleHint = thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length ? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label("cycleThinkingLevel")} cycle` : "";
3731
- const scrollHint = this.getMaxScrollOffset() > 0 ? " \u2022 PgUp/PgDn history" : "";
3732
- const hints = `${baseHint}${cycleHint}${scrollHint}`;
3733
- const compactHints = this.editor ? `Enter \u2022 ${exit}` : exit;
3734
- const selectedHints = visibleWidth3(hints) <= width ? hints : compactHints;
3735
- const loaderWidth = Math.max(1, width - visibleWidth3(selectedHints) - 3);
3736
- const loaderLine = this.loader.render(loaderWidth).at(-1) ?? "Answering\u2026";
3737
- return truncateToWidth4(`${loaderLine} \u2022 ${this.theme.fg("muted", selectedHints)}`, width);
3738
- }
3739
- createHeaderComponent() {
3740
- return {
3741
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
3742
- invalidate() {
3743
- }
3744
- };
4176
+ const cycle = thinking && thinking.levels.length > 1 && this.shortcuts.keys.cycleThinkingLevel.length ? `${this.shortcuts.label("cycleThinkingLevel")} thinking` : "";
4177
+ const history = this.getMaxScrollOffset() > 0 ? pagingHint(this.tui, this.keybindings) : "";
4178
+ const switchPane = this.workspaceFocus?.shortcutLabel ? `${this.workspaceFocus.shortcutLabel} switch` : "";
4179
+ const submitKey = submit.split(" ")[0] ?? "";
4180
+ return fittingHint(width, [
4181
+ compactHints([submit, `${exit} cancel`, cycle, history, switchPane]),
4182
+ compactHints([submit, exit, cycle, history, switchPane]),
4183
+ compactHints([submitKey, exit, cycle, history.replace(/ history$/u, ""), switchPane]),
4184
+ compactHints([submitKey, exit, history.replace(/ history$/u, "")]),
4185
+ compactHints([submitKey, exit]),
4186
+ exit
4187
+ ]);
4188
+ }
4189
+ renderWorking(width) {
4190
+ return [this.loader.renderInBorder(Math.max(0, width))];
4191
+ }
4192
+ createWorkingComponent() {
4193
+ return { render: (width) => this.renderWorking(width), invalidate: () => this.loader.invalidate() };
3745
4194
  }
3746
4195
  createTranscriptComponent() {
3747
4196
  return {
3748
4197
  render: (width) => {
3749
- const lines = renderTranscriptLines(this.transcriptComponents, width);
4198
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
3750
4199
  this.lastContentLineCount = lines.length;
3751
4200
  return lines;
3752
4201
  },
@@ -3764,7 +4213,7 @@ var BtwAnsweringView = class {
3764
4213
  }
3765
4214
  createFooterComponent() {
3766
4215
  return {
3767
- render: (width) => [this.renderFooter(width)],
4216
+ render: (width) => this.renderFooter(width),
3768
4217
  invalidate: () => this.loader.invalidate()
3769
4218
  };
3770
4219
  }
@@ -3773,7 +4222,8 @@ var BtwAnsweringView = class {
3773
4222
  }
3774
4223
  };
3775
4224
  function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransformers = []) {
3776
- const components = turns.flatMap((turn) => {
4225
+ const components = turns.flatMap((turn, index) => {
4226
+ const preceding = index > 0 ? [new Spacer(1)] : [];
3777
4227
  const question = new UserMessageComponent(
3778
4228
  escapeTerminalControls2(turn.question),
3779
4229
  getMarkdownTheme(),
@@ -3781,10 +4231,12 @@ function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransf
3781
4231
  markdownTransformers
3782
4232
  );
3783
4233
  if (turn.kind === "error") {
3784
- const error = new Markdown(`Error: ${escapeTerminalControls2(turn.answer)}`, 1, 1, getMarkdownTheme(), {
3785
- color: (text) => theme.fg("error", text)
3786
- });
3787
- return [question, error];
4234
+ const error = {
4235
+ render: (width) => new Text(theme.fg("error", `Error: ${escapeTerminalControls2(turn.answer)}`), 1, 0).render(width),
4236
+ invalidate() {
4237
+ }
4238
+ };
4239
+ return [...preceding, question, new Spacer(1), error];
3788
4240
  }
3789
4241
  const response = {
3790
4242
  ...turn.response,
@@ -3792,30 +4244,47 @@ function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransf
3792
4244
  stopReason: "stop",
3793
4245
  errorMessage: void 0
3794
4246
  };
3795
- return [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)];
4247
+ return [
4248
+ ...preceding,
4249
+ question,
4250
+ new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)
4251
+ ];
3796
4252
  });
3797
4253
  if (pendingQuestion) {
4254
+ if (components.length > 0) components.push(new Spacer(1));
3798
4255
  components.push(
3799
4256
  new UserMessageComponent(escapeTerminalControls2(pendingQuestion), getMarkdownTheme(), 1, markdownTransformers)
3800
4257
  );
3801
4258
  }
3802
4259
  return components;
3803
4260
  }
3804
- function renderTranscriptLines(components, width) {
3805
- return components.flatMap((component) => component.render(width)).map(stripShellIntegrationMarkers);
3806
- }
3807
- function renderSideThreadHeader(width, theme, thinkingLevel) {
3808
- const thinking = thinkingLevel ? ` \xB7 thinking ${thinkingLevel}` : "";
3809
- const title = truncateToWidth4(`\u2500 btw \xB7 side thread${thinking} `, width);
3810
- const ruleWidth = Math.max(0, width - visibleWidth3(title));
3811
- return theme.fg("muted", `${title}${"\u2500".repeat(ruleWidth)}`);
4261
+ function renderTranscriptLines(components, width, native = false) {
4262
+ return components.flatMap((component) => {
4263
+ const lines = component.render(width);
4264
+ const trusted = component instanceof UserMessageComponent || component instanceof AssistantMessageComponent;
4265
+ return lines.map((line, index) => {
4266
+ let prefix = "";
4267
+ if (native && trusted) {
4268
+ if (index === 0 && line.startsWith(OSC133_MARKERS[0] ?? "")) prefix += OSC133_MARKERS[0];
4269
+ const end = `${OSC133_MARKERS[1]}${OSC133_MARKERS[2]}`;
4270
+ if (index === lines.length - 1 && line.slice(prefix.length).startsWith(end)) prefix += end;
4271
+ }
4272
+ return prefix + truncateToWidth5(stripShellIntegrationMarkers(line), Math.max(0, width), "");
4273
+ });
4274
+ });
3812
4275
  }
3813
- function fitComposerLayout(header, contentLines, footer, editorLines, availableRows, statusLines = []) {
3814
- const lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];
3815
- if (lines.length <= availableRows) return lines;
3816
- if (availableRows <= 1) return [header];
3817
- const editorBudget = Math.max(0, availableRows - 2);
3818
- return [header, footer, ...fitEditorLines(editorLines, editorBudget)];
4276
+ function fitComposerLayout(contentLines, footerLines, editorLines, availableRows, statusLines = []) {
4277
+ if (availableRows <= 0) return [];
4278
+ const editorBudget = Math.min(editorLines.length, availableRows);
4279
+ const footerBudget = Math.min(footerLines.length, availableRows - editorBudget);
4280
+ const statusBudget = Math.min(statusLines.length, availableRows - editorBudget - footerBudget);
4281
+ const transcriptBudget = availableRows - editorBudget - footerBudget - statusBudget;
4282
+ return [
4283
+ ...contentLines.slice(0, transcriptBudget),
4284
+ ...statusLines.slice(0, statusBudget),
4285
+ ...fitEditorLines(editorLines, editorBudget),
4286
+ ...footerLines.slice(0, footerBudget)
4287
+ ];
3819
4288
  }
3820
4289
  function fitEditorLines(editorLines, budget) {
3821
4290
  if (budget <= 0) return [];
@@ -3830,22 +4299,22 @@ function renderSteeringLines(questions, width, theme, maxLines) {
3830
4299
  const formatQuestion = (question) => sanitizeSingleLine(question) || "(non-printing message)";
3831
4300
  if (maxLines === 1 && questions.length > 1) {
3832
4301
  return [
3833
- truncateToWidth4(
3834
- theme.fg("dim", `Steering (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
4302
+ truncateToWidth5(
4303
+ theme.fg("dim", ` Steering next (+${questions.length - 1} more): ${formatQuestion(questions[0] ?? "")}`),
3835
4304
  width
3836
4305
  )
3837
4306
  ];
3838
4307
  }
3839
4308
  const hasOverflow = questions.length > maxLines;
3840
4309
  const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
3841
- const lines = questions.slice(0, questionLimit).map((question) => truncateToWidth4(theme.fg("dim", `Steering: ${formatQuestion(question)}`), width));
4310
+ const lines = questions.slice(0, questionLimit).map((question) => truncateToWidth5(theme.fg("dim", ` Steering next: ${formatQuestion(question)}`), width));
3842
4311
  if (hasOverflow) {
3843
- lines.push(truncateToWidth4(theme.fg("dim", `Steering: \u2026 +${questions.length - questionLimit} more`), width));
4312
+ lines.push(truncateToWidth5(theme.fg("dim", ` Steering next: \u2026 +${questions.length - questionLimit} more`), width));
3844
4313
  }
3845
4314
  return lines;
3846
4315
  }
3847
4316
  function stripShellIntegrationMarkers(line) {
3848
- return OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, ""), line);
4317
+ return line.replace(/\u001b\]133;[^\u0007\u001b]*(?:\u0007|\u001b\\)/gu, "");
3849
4318
  }
3850
4319
  function escapeTerminalControls2(text) {
3851
4320
  return [...text].map((character) => {
@@ -3905,6 +4374,7 @@ function readBtwSessionId(ctx) {
3905
4374
  return sessionId.length > 0 ? sessionId : void 0;
3906
4375
  }
3907
4376
  function notifySafely3(ctx, message, level) {
4377
+ if (ctx.signal?.aborted) return;
3908
4378
  try {
3909
4379
  ctx.ui.notify(sanitizeSingleLine(message), level);
3910
4380
  } catch {
@@ -3918,111 +4388,135 @@ function btw(pi, dependencies = {}) {
3918
4388
  const runThread = dependencies.runThread ?? runBtwThread;
3919
4389
  const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;
3920
4390
  const subscribeMainThreadUpdates = registerBtwMainThreadUpdates(pi);
3921
- const resumableThreads = /* @__PURE__ */ new Map();
4391
+ const getLifetime = registerBtwSessionLifetimes(pi);
4392
+ const sessionThreads = /* @__PURE__ */ new WeakMap();
3922
4393
  let nextThreadNumber = 1;
3923
- const listResumeThreads = () => [...resumableThreads.values()].reverse().filter((state) => state.thread.turns.length > 0 && state.title).sort((first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt).map((state) => ({
4394
+ const listResumeThreads = (resumableThreads) => [...resumableThreads.values()].reverse().filter((state) => state.thread.turns.length > 0 && state.title).sort((first, second) => second.updatedAt - first.updatedAt || second.createdAt - first.createdAt).map((state) => ({
3924
4395
  id: state.id,
3925
4396
  title: state.title ?? "Untitled side thread",
3926
4397
  questionCount: state.thread.turns.length
3927
4398
  }));
3928
4399
  pi.registerCommand("btw", {
3929
4400
  description: "Ask a quick side question without adding it to the main conversation",
3930
- handler: async (args, ctx) => {
3931
- const question = args.trim();
3932
- if (ctx.mode !== "tui") {
3933
- ctx.ui.notify("/btw requires interactive TUI mode", "error");
3934
- return;
3935
- }
3936
- let menuResult = "start";
3937
- let selectedConversationContext;
3938
- if (!question) {
3939
- while (true) {
3940
- menuResult = await showCommandMenu(pi, ctx, listResumeThreads());
3941
- if (menuResult === "closed") return;
3942
- if (menuResult !== "tree") break;
3943
- const treeResult = await pickEntry(pi, ctx);
3944
- if (treeResult.kind === "closed") return;
3945
- if (treeResult.kind === "back") continue;
3946
- try {
3947
- if (!ctx.sessionManager.getEntry(treeResult.entryId)) {
3948
- notifySafely3(ctx, "The selected main-thread entry is no longer available", "warning");
3949
- continue;
3950
- }
3951
- const branch = ctx.sessionManager.getBranch(treeResult.entryId);
3952
- if (branch.at(-1)?.id !== treeResult.entryId) {
3953
- notifySafely3(ctx, "The selected main-thread branch is no longer available", "warning");
3954
- continue;
3955
- }
3956
- selectedConversationContext = buildConversationContext(branch);
3957
- menuResult = "start";
3958
- break;
3959
- } catch {
3960
- return;
4401
+ handler: (args, ctx) => {
4402
+ const lifetime = getLifetime(ctx);
4403
+ if (lifetime.signal.aborted) return Promise.resolve();
4404
+ const commandCtx = Object.create(ctx);
4405
+ Object.defineProperty(commandCtx, "signal", { value: lifetime.signal, configurable: true });
4406
+ return lifetime.track(
4407
+ handleCommand(args, commandCtx, lifetime).catch((error) => {
4408
+ if (!lifetime.signal.aborted) throw error;
4409
+ })
4410
+ );
4411
+ }
4412
+ });
4413
+ async function handleCommand(args, ctx, lifetime) {
4414
+ let resumableThreads = sessionThreads.get(lifetime);
4415
+ if (!resumableThreads) {
4416
+ resumableThreads = /* @__PURE__ */ new Map();
4417
+ sessionThreads.set(lifetime, resumableThreads);
4418
+ }
4419
+ const question = args.trim();
4420
+ if (ctx.mode !== "tui") {
4421
+ ctx.ui.notify("/btw requires interactive TUI mode", "error");
4422
+ return;
4423
+ }
4424
+ let menuResult = "start";
4425
+ let selectedConversationContext;
4426
+ if (!question) {
4427
+ while (true) {
4428
+ menuResult = await showCommandMenu(pi, ctx, listResumeThreads(resumableThreads));
4429
+ if (lifetime.signal.aborted || menuResult === "closed") return;
4430
+ if (menuResult !== "tree") break;
4431
+ const treeResult = await pickEntry(pi, ctx);
4432
+ if (lifetime.signal.aborted || treeResult.kind === "closed") return;
4433
+ if (treeResult.kind === "back") continue;
4434
+ try {
4435
+ if (!ctx.sessionManager.getEntry(treeResult.entryId)) {
4436
+ notifySafely3(ctx, "The selected main-thread entry is no longer available", "warning");
4437
+ continue;
3961
4438
  }
4439
+ const branch = ctx.sessionManager.getBranch(treeResult.entryId);
4440
+ if (branch.at(-1)?.id !== treeResult.entryId) {
4441
+ notifySafely3(ctx, "The selected main-thread branch is no longer available", "warning");
4442
+ continue;
4443
+ }
4444
+ selectedConversationContext = buildConversationContext(branch);
4445
+ menuResult = "start";
4446
+ break;
4447
+ } catch {
4448
+ return;
3962
4449
  }
3963
4450
  }
3964
- const settings = await loadSettings(ctx);
3965
- const sameAsMainThinkingLevel = settings.thinkingLevel === void 0;
3966
- const resolution = await resolveModel(settings, ctx);
3967
- if (resolution.kind === "cancelled") {
3968
- notifySafely3(ctx, "Cancelled", "info");
3969
- return;
3970
- }
3971
- if (resolution.kind === "unavailable") {
3972
- notifySafely3(ctx, "No available model for /btw", "error");
3973
- return;
3974
- }
3975
- let state = typeof menuResult === "object" ? resumableThreads.get(menuResult.threadId) : void 0;
3976
- if (typeof menuResult === "object" && !state) {
3977
- notifySafely3(ctx, "The selected /btw side thread is no longer available", "warning");
3978
- return;
3979
- }
3980
- const startingTurnCount = state?.thread.turns.length ?? 0;
3981
- try {
3982
- await runFullscreen(
3983
- ctx,
3984
- (fullscreenCtx) => {
3985
- if (!state) {
3986
- const createdAt = Date.now();
3987
- state = {
3988
- id: `btw-${nextThreadNumber}`,
3989
- thread: createSideThread(
3990
- selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch())
3991
- ),
3992
- thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
3993
- createdAt,
3994
- updatedAt: createdAt
3995
- };
3996
- nextThreadNumber += 1;
3997
- }
3998
- return runThread({
4451
+ }
4452
+ const settings = await loadSettings(ctx);
4453
+ if (lifetime.signal.aborted) return;
4454
+ const sameAsMainThinkingLevel = settings.thinkingLevel === void 0;
4455
+ const resolution = await resolveModel(settings, ctx);
4456
+ if (lifetime.signal.aborted) return;
4457
+ if (resolution.kind === "cancelled") {
4458
+ notifySafely3(ctx, "Cancelled", "info");
4459
+ return;
4460
+ }
4461
+ if (resolution.kind === "unavailable") {
4462
+ notifySafely3(ctx, "No available model for /btw", "error");
4463
+ return;
4464
+ }
4465
+ let state = typeof menuResult === "object" ? resumableThreads.get(menuResult.threadId) : void 0;
4466
+ if (typeof menuResult === "object" && !state) {
4467
+ notifySafely3(ctx, "The selected /btw side thread is no longer available", "warning");
4468
+ return;
4469
+ }
4470
+ const startingTurnCount = state?.thread.turns.length ?? 0;
4471
+ try {
4472
+ await runFullscreen(
4473
+ ctx,
4474
+ (fullscreenCtx) => {
4475
+ if (lifetime.signal.aborted) return Promise.resolve({ kind: "closed" });
4476
+ if (!state) {
4477
+ const createdAt = Date.now();
4478
+ state = {
4479
+ id: `btw-${nextThreadNumber}`,
4480
+ thread: createSideThread(
4481
+ selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch())
4482
+ ),
4483
+ thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
4484
+ createdAt,
4485
+ updatedAt: createdAt
4486
+ };
4487
+ nextThreadNumber += 1;
4488
+ }
4489
+ return lifetime.track(
4490
+ runThread({
3999
4491
  initialQuestion: question || void 0,
4000
4492
  selected: resolution.selected,
4001
4493
  thinkingLevel: state.thinkingLevel,
4002
4494
  rememberThinkingLevelChanges: !sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),
4003
4495
  state,
4004
4496
  ctx: fullscreenCtx
4005
- });
4006
- },
4007
- {
4008
- copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
4009
- layout: effectiveBtwLayout(settings),
4010
- sidePaneRatio: effectiveBtwSidePaneRatio(settings),
4011
- persistSidePaneRatio: (ratio, signal) => updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => void 0),
4012
- subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
4013
- ...settings.keybindings ? { keybindings: settings.keybindings } : {}
4014
- }
4015
- );
4016
- } finally {
4017
- if (state?.title && state.thread.turns.length > 0) {
4018
- if (state.thread.turns.length > startingTurnCount) {
4019
- resumableThreads.delete(state.id);
4020
- }
4021
- resumableThreads.set(state.id, state);
4497
+ })
4498
+ );
4499
+ },
4500
+ {
4501
+ signal: lifetime.signal,
4502
+ canRestoreParent: lifetime.canRestoreParent,
4503
+ copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
4504
+ layout: effectiveBtwLayout(settings),
4505
+ sidePaneRatio: effectiveBtwSidePaneRatio(settings),
4506
+ persistSidePaneRatio: (ratio, signal) => updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => void 0),
4507
+ subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
4508
+ ...settings.keybindings ? { keybindings: settings.keybindings } : {}
4509
+ }
4510
+ );
4511
+ } finally {
4512
+ if (!lifetime.signal.aborted && state?.title && state.thread.turns.length > 0) {
4513
+ if (state.thread.turns.length > startingTurnCount) {
4514
+ resumableThreads.delete(state.id);
4022
4515
  }
4516
+ resumableThreads.set(state.id, state);
4023
4517
  }
4024
4518
  }
4025
- });
4519
+ }
4026
4520
  }
4027
4521
  async function showCommandMenuForBtw(pi, ctx, resumeThreads) {
4028
4522
  return showBtwCommandMenu(ctx, {
@@ -4057,6 +4551,7 @@ async function runBtwThread({
4057
4551
  ctx,
4058
4552
  dependencies = {}
4059
4553
  }) {
4554
+ if (ctx.signal?.aborted) return { kind: "closed" };
4060
4555
  const ask = dependencies.ask ?? askThreadQuestion;
4061
4556
  const interact = dependencies.interact ?? showThreadComposer;
4062
4557
  const chooseBringToMainAction = dependencies.chooseBringToMain ?? chooseBringToMain;
@@ -4075,7 +4570,7 @@ async function runBtwThread({
4075
4570
  level: activeThinkingLevel,
4076
4571
  levels: thinkingLevels,
4077
4572
  onChange: (level) => {
4078
- if (!thinkingLevels.includes(level)) return;
4573
+ if (ctx.signal?.aborted || !thinkingLevels.includes(level)) return;
4079
4574
  activeThinkingLevel = level;
4080
4575
  if (state) state.thinkingLevel = level;
4081
4576
  if (!rememberThinkingLevelChanges) return;
@@ -4092,18 +4587,23 @@ async function runBtwThread({
4092
4587
  });
4093
4588
  try {
4094
4589
  while (true) {
4590
+ if (ctx.signal?.aborted) return { kind: "closed" };
4095
4591
  if (!pendingQuestion) {
4096
- const action = await interact(thread, thread.turns.length > 0, ctx, composerDraft, createThinkingControl());
4097
- if (action.kind === "close") return { kind: "closed" };
4592
+ const action = await interact(thread, thread.turns.length > 0, ctx, composerDraft, createThinkingControl(), {
4593
+ id: selected.model.id,
4594
+ provider: selected.model.provider
4595
+ });
4596
+ if (ctx.signal?.aborted || action.kind === "close") return { kind: "closed" };
4098
4597
  if (action.kind === "bringToMain") {
4099
4598
  const choice = await chooseBringToMainAction(thread, ctx);
4599
+ if (ctx.signal?.aborted) return { kind: "closed" };
4100
4600
  if (choice.kind === "closed") return choice;
4101
4601
  if (choice.kind === "back") {
4102
4602
  composerDraft = action.questionDraft;
4103
4603
  continue;
4104
4604
  }
4105
4605
  const delivery = await deliverBringToMainDraft(choice.draft, ctx, choice.summary);
4106
- if (delivery === "loaded" || delivery === "closed") return { kind: "closed" };
4606
+ if (ctx.signal?.aborted || delivery === "loaded" || delivery === "closed") return { kind: "closed" };
4107
4607
  composerDraft = action.questionDraft;
4108
4608
  continue;
4109
4609
  }
@@ -4112,9 +4612,12 @@ async function runBtwThread({
4112
4612
  }
4113
4613
  const result = await ask(thread, pendingQuestion, selected, activeThinkingLevel, ctx, {
4114
4614
  questions: steeringQuestions,
4115
- submit: (question) => steeringQuestions.push(question),
4615
+ submit: (question) => {
4616
+ if (!ctx.signal?.aborted) steeringQuestions.push(question);
4617
+ },
4116
4618
  thinking: createThinkingControl()
4117
4619
  });
4620
+ if (ctx.signal?.aborted) return { kind: "closed" };
4118
4621
  if (result.kind === "aborted") {
4119
4622
  notifySafely3(ctx, "Cancelled", "info");
4120
4623
  return { kind: "closed" };
@@ -4137,6 +4640,7 @@ async function runBtwThread({
4137
4640
  }
4138
4641
  }
4139
4642
  async function chooseBringToMain(thread, ctx, dependencies = {}) {
4643
+ if (ctx.signal?.aborted) return { kind: "closed" };
4140
4644
  const answered = getAnsweredTurns(thread.turns);
4141
4645
  if (answered.length === 0) return { kind: "back" };
4142
4646
  const showMenu = dependencies.showMenu ?? showBtwMenu;
@@ -4161,7 +4665,7 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4161
4665
  [latestOption, fromOption, exactOption, entireOption, cancelOption],
4162
4666
  selectedScope
4163
4667
  );
4164
- if (scopeResult.kind === "close") return { kind: "closed" };
4668
+ if (ctx.signal?.aborted || scopeResult.kind === "close") return { kind: "closed" };
4165
4669
  if (scopeResult.kind === "back" || scopeResult.value === cancelOption) return { kind: "back" };
4166
4670
  const scope = scopeResult.value;
4167
4671
  selectedScope = scope;
@@ -4169,7 +4673,7 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4169
4673
  if (scope === entireOption) {
4170
4674
  const choice = makeChoice(entireSegments);
4171
4675
  const preview = await showPreview(ctx, choice.draft, choice.summary);
4172
- if (preview.kind === "close") return { kind: "closed" };
4676
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
4173
4677
  if (preview.kind === "back") continue;
4174
4678
  return choice;
4175
4679
  }
@@ -4180,14 +4684,14 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4180
4684
  let selectedQuestion;
4181
4685
  while (true) {
4182
4686
  const questionResult = await showMenu(ctx, "Start from which question?", questions, selectedQuestion);
4183
- if (questionResult.kind === "close") return { kind: "closed" };
4687
+ if (ctx.signal?.aborted || questionResult.kind === "close") return { kind: "closed" };
4184
4688
  if (questionResult.kind === "back") break;
4185
4689
  const answeredTurnIndex = questions.indexOf(questionResult.value);
4186
4690
  if (answeredTurnIndex < 0) continue;
4187
4691
  selectedQuestion = questionResult.value;
4188
4692
  const choice = makeChoice(buildQuickBringToMainSegments(thread.turns, { kind: "from", answeredTurnIndex }));
4189
4693
  const preview = await showPreview(ctx, choice.draft, choice.summary);
4190
- if (preview.kind === "close") return { kind: "closed" };
4694
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
4191
4695
  if (preview.kind === "back") continue;
4192
4696
  return choice;
4193
4697
  }
@@ -4215,11 +4719,11 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4215
4719
  return selector;
4216
4720
  }
4217
4721
  );
4218
- if (!selectedRange) return { kind: "closed" };
4722
+ if (ctx.signal?.aborted || !selectedRange) return { kind: "closed" };
4219
4723
  if (selectedRange.kind === "closed") return selectedRange;
4220
4724
  if (selectedRange.kind === "back") break;
4221
4725
  const preview = await showPreview(ctx, selectedRange.draft, selectedRange.summary);
4222
- if (preview.kind === "close") return { kind: "closed" };
4726
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
4223
4727
  if (preview.kind === "back") {
4224
4728
  selectionState = selectedRange.selectionState;
4225
4729
  continue;
@@ -4259,8 +4763,9 @@ async function showBringToMainPreview(ctx, draft, summary) {
4259
4763
  });
4260
4764
  const result = await runBtwMenuPreservingEditor(
4261
4765
  ctx,
4262
- (menuContext) => runMenu(menuContext, menu, { getState: () => void 0 })
4766
+ (menuContext) => runMenu(menuContext, menu, { getState: () => void 0, signal: ctx.signal })
4263
4767
  );
4768
+ if (ctx.signal?.aborted) return { kind: "close" };
4264
4769
  if (confirmed && result.kind === "closed" && result.reason === "close") {
4265
4770
  return { kind: "bring" };
4266
4771
  }
@@ -4294,8 +4799,9 @@ async function showBtwMenu(ctx, title, options, initialValue) {
4294
4799
  });
4295
4800
  const result = await runBtwMenuPreservingEditor(
4296
4801
  ctx,
4297
- (menuContext) => runMenu(menuContext, menu, { getState: () => void 0 })
4802
+ (menuContext) => runMenu(menuContext, menu, { getState: () => void 0, signal: ctx.signal })
4298
4803
  );
4804
+ if (ctx.signal?.aborted) return { kind: "close" };
4299
4805
  return selectedValue !== void 0 && result.kind === "closed" && result.reason === "close" ? { kind: "select", value: selectedValue } : terminalBtwMenuAction(result);
4300
4806
  }
4301
4807
  function terminalBtwMenuAction(result) {
@@ -4304,6 +4810,7 @@ function terminalBtwMenuAction(result) {
4304
4810
  return { kind: "close" };
4305
4811
  }
4306
4812
  async function loadBringToMainDraft(draft, ctx, summary) {
4813
+ if (ctx.signal?.aborted) return "closed";
4307
4814
  const describeContent = () => `${summary.messages} ${summary.messages === 1 ? "message" : "messages"} (~${summary.tokens} ${summary.tokens === 1 ? "token" : "tokens"})`;
4308
4815
  const existing = ctx.ui.getEditorText();
4309
4816
  if (!existing.trim()) {
@@ -4320,7 +4827,7 @@ async function loadBringToMainDraft(draft, ctx, summary) {
4320
4827
  replaceOption,
4321
4828
  cancelOption
4322
4829
  ]);
4323
- if (action.kind === "close") return "closed";
4830
+ if (ctx.signal?.aborted || action.kind === "close") return "closed";
4324
4831
  if (action.kind === "back" || action.value === cancelOption) return "back";
4325
4832
  if (action.value === appendOption) {
4326
4833
  ctx.ui.setEditorText(`${ctx.ui.getEditorText()}
@@ -4339,7 +4846,7 @@ ${draft}`);
4339
4846
  "Back Keep current editor text",
4340
4847
  "\u26A0 Replace current draft Cannot be undone"
4341
4848
  ]);
4342
- if (confirmed.kind === "close") return "closed";
4849
+ if (ctx.signal?.aborted || confirmed.kind === "close") return "closed";
4343
4850
  if (confirmed.kind === "back" || confirmed.value === "Back Keep current editor text") continue;
4344
4851
  if (confirmed.value !== "\u26A0 Replace current draft Cannot be undone") continue;
4345
4852
  if (ctx.ui.getEditorText() !== current) {
@@ -4359,6 +4866,7 @@ function truncatePreview(text) {
4359
4866
  }
4360
4867
  async function prepareCurrentTranscriptMarkdown(thread, pendingQuestion, ctx) {
4361
4868
  while (true) {
4869
+ if (ctx.signal?.aborted) return void 0;
4362
4870
  const turnCount = thread.turns.length;
4363
4871
  const createMarkdownTransformers = ctx.signal ? await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion, ctx.signal) : await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion);
4364
4872
  if (!createMarkdownTransformers || ctx.signal?.aborted) return void 0;
@@ -4367,7 +4875,7 @@ async function prepareCurrentTranscriptMarkdown(thread, pendingQuestion, ctx) {
4367
4875
  }
4368
4876
  async function askThreadQuestion(thread, question, selected, thinkingLevel, ctx, steering) {
4369
4877
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, question, ctx);
4370
- if (!createMarkdownTransformers) return { kind: "aborted" };
4878
+ if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "aborted" };
4371
4879
  return ctx.ui.custom((tui, theme, keybindings, done) => {
4372
4880
  let settled = false;
4373
4881
  const view = new BtwAnsweringView(
@@ -4382,6 +4890,7 @@ async function askThreadQuestion(thread, question, selected, thinkingLevel, ctx,
4382
4890
  },
4383
4891
  thinkingLevel,
4384
4892
  {
4893
+ model: { id: selected.model.id, provider: selected.model.provider },
4385
4894
  markdownTransformers: createMarkdownTransformers(theme),
4386
4895
  steering: {
4387
4896
  questions: steering.questions,
@@ -4407,13 +4916,14 @@ async function askThreadQuestion(thread, question, selected, thinkingLevel, ctx,
4407
4916
  return view;
4408
4917
  });
4409
4918
  }
4410
- async function showThreadComposer(thread, startAtBottom, ctx, initialQuestion, thinking) {
4919
+ async function showThreadComposer(thread, startAtBottom, ctx, initialQuestion, thinking, model) {
4411
4920
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);
4412
- if (!createMarkdownTransformers) return { kind: "close" };
4921
+ if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "close" };
4413
4922
  return ctx.ui.custom(
4414
4923
  (tui, theme, keybindings, done) => new BtwTranscriptPager(tui, theme, thread.turns, done, {
4415
4924
  startAtBottom,
4416
4925
  initialQuestion,
4926
+ model,
4417
4927
  markdownTransformers: createMarkdownTransformers(theme),
4418
4928
  thinking: { ...thinking, keybindings }
4419
4929
  })