@narumitw/pi-btw 0.61.2 → 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,231 +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 configuredModifiers = parts.slice(0, -1);
1737
- if (new Set(configuredModifiers).size !== configuredModifiers.length || configuredModifiers.some((modifier) => !KEY_MODIFIER_ORDER.includes(modifier)))
1738
- return "";
1739
- const normalizedBase = base === "esc" ? "escape" : base === "return" ? "enter" : base;
1740
- const modifiers = KEY_MODIFIER_ORDER.filter((modifier) => parts.includes(modifier));
1741
- return [...modifiers, normalizedBase].join("+");
1742
- }
1743
- function formatEffectiveKeyLabel(key) {
1744
- const parts = key.split("+");
1745
- const base = parts.at(-1);
1746
- if (base === "pageup") parts[parts.length - 1] = "pageUp";
1747
- if (base === "pagedown") parts[parts.length - 1] = "pageDown";
1748
- return formatKeyLabel2(parts.join("+"));
1749
- }
1750
- function canMatchKeyInput(key) {
1751
- const parts = key.split("+");
1752
- const base = parts.at(-1) ?? "";
1753
- const modifiers = parts.slice(0, -1);
1754
- if (base === "escape") return modifiers.length === 0;
1755
- if (base === "clear") {
1756
- return modifiers.length === 0 || modifiers.length === 1 && (modifiers[0] === "shift" || modifiers[0] === "ctrl");
1757
- }
1758
- if (/^f(?:[1-9]|1[0-2])$/u.test(base)) return modifiers.length === 0;
1759
- return MATCHABLE_SPECIAL_KEYS.has(base) || base.length === 1 && (/^[a-z0-9]$/u.test(base) || MATCHABLE_SYMBOL_KEYS.has(base));
1760
- }
1761
- function rawCtrlInput(base) {
1762
- if (base.length !== 1) return void 0;
1763
- const rawBase = base === "-" ? "_" : base;
1764
- if (!"abcdefghijklmnopqrstuvwxyz[\\]_".includes(rawBase)) return void 0;
1765
- return String.fromCharCode(rawBase.charCodeAt(0) & 31);
1766
- }
1767
- function legacyRawInput(key) {
1768
- const parts = key.split("+");
1769
- const base = parts.at(-1) ?? "";
1770
- if (parts.length === 2 && parts[0] === "ctrl") return rawCtrlInput(base);
1771
- if (isKittyProtocolActive2()) return void 0;
1772
- if (parts.length === 2 && parts[0] === "alt" && base.length === 1) return `\x1B${base}`;
1773
- if (parts.length === 3 && parts[0] === "ctrl" && parts[1] === "alt") {
1774
- const input = rawCtrlInput(base);
1775
- return input ? `\x1B${input}` : void 0;
1776
- }
1777
- return void 0;
1778
- }
1779
- function keyInputIdentity(key) {
1780
- const identity = normalizedKeyId(key);
1781
- const input = legacyRawInput(identity);
1782
- return input ? normalizedKeyId(parseKey(input) ?? identity) : identity;
1783
- }
1784
- function hasManualSelectionCopyApi() {
1785
- return typeof TuiAltScreen.prototype.hasActiveSelection === "function" && typeof TuiAltScreen.prototype.copyActiveSelectionToClipboard === "function";
1786
- }
1787
- function createBtwFullscreenTui(parent, theme, keybindings, copyOnSelect, manualSelectionCopySupported, openUrl, copyToClipboard2) {
1788
- if (!copyOnSelect && !manualSelectionCopySupported) {
1789
- throw new Error(
1790
- "Manual fullscreen selection copying is unavailable in this Pi version; update Pi or enable automatic selection copying."
1791
- );
1792
- }
1793
- const styleSearchMatch = (text) => theme.bg("searchMatchBg", theme.fg("searchMatchText", text));
1794
- const fullscreen = new BtwTuiAltScreen(parent.terminal, parent.getShowHardwareCursor(), void 0, {
1795
- mouse: true,
1796
- copyOnSelect,
1797
- searchMatchStyle: (text) => theme.underline(styleSearchMatch(text)),
1798
- scrollToEndIndicator: () => {
1799
- const unavailableKeyIdentities = /* @__PURE__ */ new Set([keyInputIdentity(Key2.ctrl("c"))]);
1800
- for (const action of ALT_SCREEN_ACTIONS_BEFORE_BOTTOM) {
1801
- for (const actionKey of keybindings.getKeys(action)) {
1802
- unavailableKeyIdentities.add(keyInputIdentity(String(actionKey)));
1803
- }
1804
- }
1805
- if (!copyOnSelect) {
1806
- for (const copyKey of keybindings.getKeys("app.message.copy")) {
1807
- unavailableKeyIdentities.add(keyInputIdentity(String(copyKey)));
1808
- }
1809
- }
1810
- const key = keybindings.getKeys("tui.altScreen.bottom").map((candidate) => keyInputIdentity(String(candidate))).find(
1811
- (identity) => identity && canMatchKeyInput(identity) && !unavailableKeyIdentities.has(identity) && formatEffectiveKeyLabel(identity)
1812
- );
1813
- const label = theme.fg("text", " \u2193 Jump to latest message");
1814
- const shortcut = key ? theme.fg("muted", ` \xB7 ${formatEffectiveKeyLabel(key)}`) : "";
1815
- return theme.bg("selectedBg", `${label}${shortcut} `);
1816
- },
1817
- searchCurrentMatchStyle: (text) => theme.bold(theme.inverse(styleSearchMatch(text))),
1818
- openUrl,
1819
- copySelection: async (text) => {
1820
- try {
1821
- await copyToClipboard2(text);
1822
- return true;
1823
- } catch {
1824
- return false;
1825
- }
1980
+ if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
1981
+ } catch {
1826
1982
  }
1827
- });
1828
- if (!copyOnSelect) {
1829
- let isInBracketedPaste = false;
1830
- fullscreen.addInputListenerBeforeViewport((data) => {
1831
- const wasInBracketedPaste = isInBracketedPaste;
1832
- const startsBracketedPaste = data.includes(BRACKETED_PASTE_START);
1833
- if (startsBracketedPaste) isInBracketedPaste = true;
1834
- if (isInBracketedPaste && data.includes(BRACKETED_PASTE_END)) {
1835
- isInBracketedPaste = false;
1836
- }
1837
- if (wasInBracketedPaste || startsBracketedPaste || fullscreen.hasFocusedOverlay() || isKeyRelease2(data) || !keybindings.matches(data, "app.message.copy")) {
1838
- return void 0;
1839
- }
1840
- if (!fullscreen.hasActiveSelection()) {
1841
- fullscreen.flash("No selection to copy");
1842
- return { consume: true };
1843
- }
1844
- void fullscreen.copyActiveSelectionToClipboard().catch(() => fullscreen.flash("Copy failed"));
1845
- return { consume: true };
1846
- });
1847
1983
  }
1848
- return fullscreen;
1849
- }
1850
- function openUrlInBrowser(target) {
1851
- const [command, args] = process.platform === "darwin" ? ["open", [target]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : ["xdg-open", [target]];
1852
- spawn(command, args, { stdio: "ignore", detached: true }).on("error", () => {
1853
- }).unref();
1984
+ if (outcome.kind === "failed") throw outcome.error;
1985
+ return outcome.value;
1854
1986
  }
1855
1987
  var BtwFullscreenHost = class {
1856
1988
  constructor(parent, theme, keybindings, ctx, run, done, createTui, options) {
@@ -1918,15 +2050,23 @@ var BtwFullscreenHost = class {
1918
2050
  if (this.disposed || this.finished) return;
1919
2051
  this.disposed = true;
1920
2052
  this.lifetimeController.abort();
1921
- this.cancelActiveCustom?.();
2053
+ try {
2054
+ this.cancelActiveCustom?.();
2055
+ } finally {
2056
+ this.queueParentRestore();
2057
+ }
1922
2058
  }
1923
2059
  async start() {
1924
2060
  if (this.started || this.finished) return;
1925
2061
  this.started = true;
1926
- this.watchUpstreamCancellation();
1927
2062
  let outcome;
1928
2063
  try {
2064
+ this.watchUpstreamCancellation();
1929
2065
  if (this.disposed) throw new FullscreenUiDisposedError();
2066
+ if ((this.options.layout ?? "fullscreen") !== "fullscreen") {
2067
+ getParentFullscreenLayout(this.parent);
2068
+ getParentFullscreenScrollView(this.parent);
2069
+ }
1930
2070
  this.parent.stop({ preserveScreen: true });
1931
2071
  this.parentStopped = true;
1932
2072
  if (this.disposed) throw new FullscreenUiDisposedError();
@@ -1940,6 +2080,11 @@ var BtwFullscreenHost = class {
1940
2080
  this.options.copyOnSelect ?? true
1941
2081
  );
1942
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
+ );
1943
2088
  let previousWarnings = [];
1944
2089
  const reportWarnings = () => {
1945
2090
  const warnings = shortcuts.warnings;
@@ -1966,7 +2111,7 @@ var BtwFullscreenHost = class {
1966
2111
  }
1967
2112
  return { consume: true };
1968
2113
  });
1969
- const value = await this.run(this.createContext());
2114
+ const value = await this.runUntilCancelled();
1970
2115
  await this.waitForSidePaneWrites();
1971
2116
  outcome = { kind: "completed", value };
1972
2117
  } catch (error) {
@@ -1984,8 +2129,31 @@ var BtwFullscreenHost = class {
1984
2129
  this.finished = true;
1985
2130
  this.done(outcome);
1986
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
+ }
1987
2152
  watchUpstreamCancellation() {
1988
- 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;
1989
2157
  if (!signal) return;
1990
2158
  const onAbort = () => this.dispose();
1991
2159
  signal.addEventListener("abort", onAbort, { once: true });
@@ -2029,7 +2197,11 @@ var BtwFullscreenHost = class {
2029
2197
  } catch (error) {
2030
2198
  this.cleanupError ??= error;
2031
2199
  }
2032
- this.mainThreadInput.dispose();
2200
+ try {
2201
+ this.mainThreadInput.dispose();
2202
+ } catch (error) {
2203
+ this.cleanupError ??= error;
2204
+ }
2033
2205
  const removeUpstreamAbortListener = this.removeUpstreamAbortListener;
2034
2206
  this.removeUpstreamAbortListener = void 0;
2035
2207
  try {
@@ -2062,6 +2234,7 @@ var BtwFullscreenHost = class {
2062
2234
  }
2063
2235
  try {
2064
2236
  this.parentRestoreAttempted = true;
2237
+ if (this.options.canRestoreParent?.() === false) return;
2065
2238
  this.parent.start();
2066
2239
  this.parent.renderNow(false);
2067
2240
  } catch (error) {
@@ -2076,13 +2249,19 @@ var BtwFullscreenHost = class {
2076
2249
  }
2077
2250
  if (property === "notify") {
2078
2251
  return (message, level) => {
2252
+ if (this.disposed || this.finished) return;
2079
2253
  target.notify(message, level);
2080
2254
  const display = sanitizeSingleLine(message);
2081
2255
  if (display) this.fullscreen?.flash?.(display);
2082
2256
  };
2083
2257
  }
2084
2258
  const value = Reflect.get(target, property, target);
2085
- 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;
2086
2265
  }
2087
2266
  });
2088
2267
  const signal = this.ctx.signal ? AbortSignal.any([this.ctx.signal, this.lifetimeController.signal]) : this.lifetimeController.signal;
@@ -2132,7 +2311,11 @@ var BtwFullscreenHost = class {
2132
2311
  } catch (error) {
2133
2312
  cleanupError = error;
2134
2313
  }
2135
- splitPane?.dispose();
2314
+ try {
2315
+ splitPane?.dispose();
2316
+ } catch (error) {
2317
+ cleanupError ??= error;
2318
+ }
2136
2319
  splitPane = void 0;
2137
2320
  try {
2138
2321
  if (overlay) overlay.hide();
@@ -2253,9 +2436,11 @@ var BtwFullscreenHost = class {
2253
2436
  sideLayout,
2254
2437
  mainThread: this.parent,
2255
2438
  mainLayout: getParentFullscreenLayout(this.parent),
2439
+ mainScrollView: getParentFullscreenScrollView(this.parent),
2256
2440
  mainInput: this.mainThreadInput,
2257
2441
  sideScrollView: isFullscreenLayoutComponent(component) ? component.getPrimaryScrollView?.() : void 0,
2258
2442
  layout: workspaceLayout,
2443
+ shortcuts: getBtwShortcuts(fullscreen),
2259
2444
  theme: this.theme,
2260
2445
  terminalColumns: () => fullscreen.terminal.columns,
2261
2446
  terminalRows: () => fullscreen.terminal.rows,
@@ -2329,7 +2514,18 @@ function getFocusedComponent(tui) {
2329
2514
  function getParentFullscreenLayout(tui) {
2330
2515
  if (tui.mode !== "fullscreen") return void 0;
2331
2516
  const layoutRoot = Reflect.get(tui, "layoutRoot");
2332
- 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;
2333
2529
  }
2334
2530
  function isComponent(value) {
2335
2531
  return typeof value === "object" && value !== null && "render" in value && typeof value.render === "function" && "invalidate" in value && typeof value.invalidate === "function";
@@ -2426,7 +2622,8 @@ async function showBtwCommandMenu(ctx, options) {
2426
2622
  const shortcutLabels = {
2427
2623
  exit: "Exit shortcut",
2428
2624
  cycleThinkingLevel: "Cycle thinking level shortcut",
2429
- bringToMain: "Bring to main shortcut"
2625
+ bringToMain: "Bring to main shortcut",
2626
+ switchPane: "Switch pane shortcut"
2430
2627
  };
2431
2628
  const shortcutValue = (settings, action) => {
2432
2629
  if (!keybindings) return "Default";
@@ -2845,7 +3042,7 @@ async function showBtwCommandMenu(ctx, options) {
2845
3042
  });
2846
3043
  const result = await runBtwMenuPreservingEditor(
2847
3044
  ctx,
2848
- (menuContext) => runMenu(menuContext, menu, { getState: loadState }),
3045
+ (menuContext) => runMenu(menuContext, menu, { getState: loadState, signal: ctx.signal }),
2849
3046
  (manager) => {
2850
3047
  keybindings = manager;
2851
3048
  }
@@ -2856,36 +3053,46 @@ async function showBtwCommandMenu(ctx, options) {
2856
3053
  return startSelected ? "start" : "closed";
2857
3054
  }
2858
3055
  async function showBtwCustomPreservingEditor(ctx, factory) {
3056
+ const { runCustomInteraction } = await import("@narumitw/pi-tui-kit");
3057
+ if (ctx.signal?.aborted) return void 0;
2859
3058
  let liveEditorText = ctx.ui.getEditorText();
2860
3059
  let completed = false;
2861
- const result = await ctx.ui.custom(
2862
- (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;
2863
3064
  try {
2864
3065
  liveEditorText = ctx.ui.getEditorText();
2865
3066
  } catch {
2866
3067
  }
2867
3068
  completed = true;
2868
- done(value);
3069
+ complete(value);
2869
3070
  })
2870
- );
2871
- if (completed) {
3071
+ });
3072
+ if (result.kind === "error") throw result.error;
3073
+ if (!ctx.signal?.aborted && completed) {
2872
3074
  try {
2873
3075
  if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
2874
3076
  } catch {
2875
3077
  }
2876
3078
  }
2877
- return result;
3079
+ return result.kind === "completed" ? result.value : void 0;
2878
3080
  }
2879
3081
  async function runBtwMenuPreservingEditor(ctx, run, onKeybindings) {
3082
+ if (ctx.signal?.aborted) return { kind: "stale" };
2880
3083
  let liveEditorText = ctx.ui.getEditorText();
2881
3084
  let completed = false;
2882
3085
  const ui = new Proxy(ctx.ui, {
2883
3086
  get(target, property) {
2884
3087
  if (property === "custom") {
2885
- 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) => {
2886
3089
  onKeybindings?.(keybindings);
2887
3090
  return factory(tui, theme, keybindings, (value2) => {
2888
3091
  try {
3092
+ if (ctx.signal?.aborted) {
3093
+ done(value2);
3094
+ return;
3095
+ }
2889
3096
  liveEditorText = target.getEditorText();
2890
3097
  } catch {
2891
3098
  }
@@ -2899,7 +3106,7 @@ async function runBtwMenuPreservingEditor(ctx, run, onKeybindings) {
2899
3106
  }
2900
3107
  });
2901
3108
  const result = await run({ mode: ctx.mode, hasUI: ctx.hasUI, ui });
2902
- if (result.kind !== "stale" && completed) {
3109
+ if (!ctx.signal?.aborted && result.kind !== "stale" && completed) {
2903
3110
  try {
2904
3111
  if (ctx.ui.getEditorText() !== liveEditorText) ctx.ui.setEditorText(liveEditorText);
2905
3112
  } catch {
@@ -2943,6 +3150,7 @@ function notifySaveFailure(ctx, error) {
2943
3150
  );
2944
3151
  }
2945
3152
  function notifySafely(ctx, message, level) {
3153
+ if (ctx.signal?.aborted) return;
2946
3154
  try {
2947
3155
  ctx.ui.notify(sanitizeSingleLine(message), level);
2948
3156
  } catch {
@@ -3262,6 +3470,63 @@ function formatError5(error) {
3262
3470
  return error instanceof Error ? error.message : String(error);
3263
3471
  }
3264
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
+
3265
3530
  // src/transcript-markdown.ts
3266
3531
  var MERMAID_MARKDOWN_MODULE = "@narumitw/pi-tui-kit/markdown";
3267
3532
  var noMarkdownTransformers = () => [];
@@ -3314,20 +3579,191 @@ import {
3314
3579
  import {
3315
3580
  CURSOR_MARKER,
3316
3581
  Editor,
3317
- Key as Key4,
3318
- Loader,
3319
- Markdown,
3320
- matchesKey as matchesKey4,
3321
- ScrollView as ScrollView2,
3322
- truncateToWidth as truncateToWidth4,
3582
+ isKeyRelease as isKeyRelease4,
3583
+ renderFakeCursor,
3584
+ ScrollView as ScrollView3,
3585
+ Spacer,
3586
+ Text,
3587
+ truncateToWidth as truncateToWidth5,
3323
3588
  VStack,
3324
- visibleWidth as visibleWidth3
3589
+ visibleWidth as visibleWidth4
3325
3590
  } from "@earendil-works/pi-tui";
3326
- 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
3327
3647
  var MAX_STEERING_DISPLAY_LINES = 3;
3328
3648
  var OSC133_MARKERS = ["\x1B]133;A\x07", "\x1B]133;B\x07", "\x1B]133;C\x07"];
3329
3649
  var RESERVED_APP_LINES = 3;
3330
- 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 {
3331
3767
  updateLayout(contentHeight, viewportHeight, requestRender) {
3332
3768
  const preserveManualPosition = !this.isFollowingEnd;
3333
3769
  super.updateLayout(contentHeight, viewportHeight, requestRender);
@@ -3342,12 +3778,12 @@ var BtwTranscriptPager = class {
3342
3778
  this.theme = theme;
3343
3779
  this.onAction = onAction;
3344
3780
  this.options = options;
3345
- this.shortcuts = getBtwShortcuts(tui, options.thinking?.keybindings);
3781
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
3346
3782
  this.transcriptComponents = buildTranscriptComponents(turns, this.theme, void 0, options.markdownTransformers);
3347
3783
  this.canBringToMain = turns.some((turn) => turn.kind === "answered");
3348
3784
  this.thinkingLevel = options.thinking?.level;
3349
3785
  const editorTheme = {
3350
- borderColor: (text) => this.theme.fg("accent", text),
3786
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
3351
3787
  selectList: {
3352
3788
  selectedPrefix: (text) => this.theme.fg("accent", text),
3353
3789
  selectedText: (text) => this.theme.fg("accent", text),
@@ -3356,7 +3792,7 @@ var BtwTranscriptPager = class {
3356
3792
  noMatch: (text) => this.theme.fg("warning", text)
3357
3793
  }
3358
3794
  };
3359
- this.editor = new Editor(this.tui, editorTheme);
3795
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data));
3360
3796
  if (options.initialQuestion) this.editor.setText(options.initialQuestion);
3361
3797
  this.editor.onChange = () => {
3362
3798
  this.warning = void 0;
@@ -3372,20 +3808,34 @@ var BtwTranscriptPager = class {
3372
3808
  };
3373
3809
  const transcript = this.createTranscriptComponent();
3374
3810
  this.scrollView = new PreservingScrollView(transcript, {
3375
- follow: options.startAtBottom ? "end" : "none",
3376
- 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)
3377
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
+ ]);
3378
3822
  this.layoutRoot = new VStack([
3379
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
3380
3823
  { component: this.scrollView, basis: 0, grow: 1, minSize: 0 },
3381
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
3382
- { component: this.editor, basis: "auto", shrink: 1, minSize: 0 }
3824
+ { component: dock, basis: "auto", shrink: 1, minSize: 1 }
3383
3825
  ]);
3384
3826
  }
3385
3827
  tui;
3386
3828
  theme;
3387
3829
  onAction;
3388
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
+ }
3389
3839
  shortcuts;
3390
3840
  pasteGuard = new BtwPasteGuard();
3391
3841
  transcriptComponents;
@@ -3412,26 +3862,25 @@ var BtwTranscriptPager = class {
3412
3862
  return this.scrollView;
3413
3863
  }
3414
3864
  render(width) {
3415
- if (width <= 0) return [];
3865
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
3416
3866
  const safeWidth = Math.max(1, width);
3417
3867
  const editorLines = this.editor.render(safeWidth);
3418
3868
  const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
3419
- const viewportHeight = Math.max(0, availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES);
3420
3869
  const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
3421
3870
  this.lastContentLineCount = contentLines.length;
3871
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - this.renderFooter(safeWidth).length);
3422
3872
  this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
3423
3873
  return fitComposerLayout(
3424
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
3425
3874
  contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
3426
3875
  this.renderFooter(safeWidth),
3427
3876
  editorLines,
3428
3877
  availableRows
3429
- ).map((line) => truncateToWidth4(line, safeWidth));
3878
+ ).map((line) => truncateToWidth5(line, safeWidth));
3430
3879
  }
3431
3880
  handleInput(data) {
3432
3881
  if (this.finished) return;
3433
3882
  if (this.pasteGuard.consume(data)) {
3434
- this.editor.handleInput(data);
3883
+ this.editor.handleEditorInput(data);
3435
3884
  this.tui.requestRender();
3436
3885
  return;
3437
3886
  }
@@ -3457,73 +3906,54 @@ var BtwTranscriptPager = class {
3457
3906
  }
3458
3907
  return;
3459
3908
  }
3460
- if (matchesKey4(data, Key4.pageUp)) {
3461
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
3462
- this.tui.requestRender();
3463
- return;
3464
- }
3465
- if (matchesKey4(data, Key4.pageDown)) {
3466
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
3467
- this.tui.requestRender();
3468
- return;
3909
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
3910
+ this.editor.handleEditorInput(data);
3469
3911
  }
3470
- this.editor.handleInput(data);
3471
3912
  if (!this.finished) this.tui.requestRender();
3472
3913
  }
3473
3914
  invalidate() {
3474
3915
  this.layoutRoot.invalidate();
3475
3916
  }
3476
3917
  dispose() {
3918
+ releaseScrollbar(this.scrollView);
3477
3919
  if (this.finished) return;
3478
3920
  this.finished = true;
3479
3921
  this.onAction({ kind: "close" });
3480
3922
  }
3481
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) {
3482
3933
  const exit = this.shortcuts.label("exit");
3483
3934
  const bring = this.canBringToMain && this.shortcuts.keys.bringToMain.length > 0;
3484
3935
  const bringKey = this.shortcuts.label("bringToMain");
3485
- if (this.warning) {
3486
- const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} exit`;
3487
- return truncateToWidth4(this.theme.fg("warning", warning), width);
3488
- }
3489
- const scrollable = this.getMaxScrollOffset() > 0;
3936
+ if (this.warning) return fittingHint(width, [`${this.warning} \u2022 ${exit} exit`, `Empty \u2022 ${exit}`, exit]);
3490
3937
  const thinking = this.options.thinking;
3491
- const cycleHint = thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length ? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label("cycleThinkingLevel")} cycle` : "";
3492
- const base = bring ? `btw \u2022 Enter send \u2022 ${bringKey} bring to main \u2022 ${exit} exit` : `btw \u2022 Enter send \u2022 ${exit} exit`;
3493
- const fullBase = `${base}${cycleHint}`;
3494
- const fallbackBase = `btw \u2022 Enter \u2022 ${exit}`;
3495
- const compactBase = bring ? `btw \u2022 Enter \u2022 ${bringKey} \u2022 ${exit}` : fallbackBase;
3496
- const compactWithThinking = `${compactBase}${cycleHint}`;
3497
- let hints = visibleWidth3(fullBase) <= width ? fullBase : visibleWidth3(compactWithThinking) <= width ? compactWithThinking : visibleWidth3(compactBase) <= width ? compactBase : fallbackBase;
3498
- if (scrollable) {
3499
- const history = ` \u2022 ${this.scrollView.scrollTop > 0 ? "\u2191 older" : "\u2193 newer"} \u2022 PgUp/PgDn history`;
3500
- const compactHistory = " \u2022 PgUp/PgDn";
3501
- const compactScrollable = bring ? `Enter \u2022 ${bringKey} \u2022 ${exit} \u2022 PgUp/PgDn` : `${fallbackBase}${compactHistory}`;
3502
- if (visibleWidth3(`${hints}${history}`) <= width) {
3503
- hints += history;
3504
- } else if (visibleWidth3(`${compactBase}${history}`) <= width) {
3505
- hints = `${compactBase}${history}`;
3506
- } else if (visibleWidth3(`${hints}${compactHistory}`) <= width) {
3507
- hints += compactHistory;
3508
- } else if (visibleWidth3(`${compactBase}${compactHistory}`) <= width) {
3509
- hints = `${compactBase}${compactHistory}`;
3510
- } else if (visibleWidth3(compactScrollable) <= width) {
3511
- hints = compactScrollable;
3512
- }
3513
- }
3514
- return truncateToWidth4(this.theme.fg("muted", hints), width);
3515
- }
3516
- createHeaderComponent() {
3517
- return {
3518
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
3519
- invalidate() {
3520
- }
3521
- };
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
+ ]);
3522
3952
  }
3523
3953
  createTranscriptComponent() {
3524
3954
  return {
3525
3955
  render: (width) => {
3526
- const lines = renderTranscriptLines(this.transcriptComponents, width);
3956
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
3527
3957
  this.lastContentLineCount = lines.length;
3528
3958
  return lines;
3529
3959
  },
@@ -3534,7 +3964,7 @@ var BtwTranscriptPager = class {
3534
3964
  }
3535
3965
  createFooterComponent() {
3536
3966
  return {
3537
- render: (width) => [this.renderFooter(width)],
3967
+ render: (width) => this.renderFooter(width),
3538
3968
  invalidate() {
3539
3969
  }
3540
3970
  };
@@ -3549,7 +3979,7 @@ var BtwAnsweringView = class {
3549
3979
  this.theme = theme;
3550
3980
  this.onCancel = onCancel;
3551
3981
  this.options = options;
3552
- this.shortcuts = getBtwShortcuts(tui, options.steering?.thinking?.keybindings);
3982
+ this.shortcuts = getBtwShortcuts(tui, this.keybindings);
3553
3983
  this.transcriptComponents = buildTranscriptComponents(
3554
3984
  turns,
3555
3985
  this.theme,
@@ -3557,7 +3987,7 @@ var BtwAnsweringView = class {
3557
3987
  options.markdownTransformers
3558
3988
  );
3559
3989
  this.thinkingLevel = options.steering?.thinking?.level ?? thinkingLevel;
3560
- this.loader = new Loader(
3990
+ this.loader = new BtwWorkingIndicator(
3561
3991
  this.tui,
3562
3992
  (text) => this.theme.fg("accent", text),
3563
3993
  (text) => this.theme.fg("muted", text),
@@ -3565,7 +3995,7 @@ var BtwAnsweringView = class {
3565
3995
  );
3566
3996
  if (options.steering) {
3567
3997
  const editorTheme = {
3568
- borderColor: (text) => this.theme.fg("accent", text),
3998
+ borderColor: (text) => thinkingBorder(this.theme, this.thinkingLevel, text),
3569
3999
  selectList: {
3570
4000
  selectedPrefix: (text) => this.theme.fg("accent", text),
3571
4001
  selectedText: (text) => this.theme.fg("accent", text),
@@ -3574,7 +4004,7 @@ var BtwAnsweringView = class {
3574
4004
  noMatch: (text) => this.theme.fg("warning", text)
3575
4005
  }
3576
4006
  };
3577
- this.editor = new Editor(this.tui, editorTheme);
4007
+ this.editor = new BtwComposer(this.tui, editorTheme, (data) => this.handleInput(data), this.loader);
3578
4008
  this.editor.onChange = () => {
3579
4009
  this.warning = void 0;
3580
4010
  };
@@ -3589,10 +4019,14 @@ var BtwAnsweringView = class {
3589
4019
  };
3590
4020
  }
3591
4021
  const transcript = this.createTranscriptComponent();
3592
- this.scrollView = new PreservingScrollView(transcript, { follow: "end", primary: true });
3593
- this.layoutRoot = new VStack([
3594
- { component: this.createHeaderComponent(), basis: 1, shrink: 0, minSize: 1 },
3595
- { 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([
3596
4030
  {
3597
4031
  component: this.createSteeringComponent(),
3598
4032
  basis: "auto",
@@ -3600,14 +4034,26 @@ var BtwAnsweringView = class {
3600
4034
  minSize: 0,
3601
4035
  maxSize: MAX_STEERING_DISPLAY_LINES
3602
4036
  },
3603
- { component: this.createFooterComponent(), basis: 1, shrink: 0, minSize: 1 },
3604
- ...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 }
3605
4043
  ]);
3606
4044
  }
3607
4045
  tui;
3608
4046
  theme;
3609
4047
  onCancel;
3610
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
+ }
3611
4057
  shortcuts;
3612
4058
  pasteGuard = new BtwPasteGuard();
3613
4059
  transcriptComponents;
@@ -3638,37 +4084,34 @@ var BtwAnsweringView = class {
3638
4084
  return this.scrollView;
3639
4085
  }
3640
4086
  render(width) {
3641
- if (width <= 0) return [];
4087
+ if (width <= 0 || this.tui.terminal.rows <= 0) return [];
3642
4088
  const safeWidth = Math.max(1, width);
3643
4089
  const availableRows = Math.max(1, this.tui.terminal.rows - RESERVED_APP_LINES);
3644
- const editorLines = this.editor?.render(safeWidth) ?? [];
3645
- 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);
3646
4095
  const steeringLines = renderSteeringLines(
3647
4096
  this.options.steering?.questions ?? [],
3648
4097
  safeWidth,
3649
4098
  this.theme,
3650
4099
  Math.min(MAX_STEERING_DISPLAY_LINES, steeringCapacity)
3651
4100
  );
3652
- const viewportHeight = Math.max(
3653
- 0,
3654
- availableRows - editorLines.length - TRANSCRIPT_CHROME_LINES - steeringLines.length
3655
- );
3656
- const contentLines = renderTranscriptLines(this.transcriptComponents, safeWidth);
3657
- this.lastContentLineCount = contentLines.length;
4101
+ const viewportHeight = Math.max(0, availableRows - editorLines.length - footerLines.length - steeringLines.length);
3658
4102
  this.scrollView.updateLayout(contentLines.length, viewportHeight, () => this.tui.requestRender());
3659
4103
  return fitComposerLayout(
3660
- renderSideThreadHeader(safeWidth, this.theme, this.thinkingLevel),
3661
4104
  contentLines.slice(this.scrollView.scrollTop, this.scrollView.scrollTop + viewportHeight),
3662
4105
  this.renderFooter(safeWidth),
3663
4106
  editorLines,
3664
4107
  availableRows,
3665
4108
  steeringLines
3666
- ).map((line) => truncateToWidth4(line, safeWidth));
4109
+ ).map((line) => truncateToWidth5(line, safeWidth));
3667
4110
  }
3668
4111
  handleInput(data) {
3669
4112
  if (this.finished) return;
3670
4113
  if (this.pasteGuard.consume(data)) {
3671
- this.editor?.handleInput(data);
4114
+ this.editor?.handleEditorInput(data);
3672
4115
  this.tui.requestRender();
3673
4116
  return;
3674
4117
  }
@@ -3691,17 +4134,9 @@ var BtwAnsweringView = class {
3691
4134
  }
3692
4135
  return;
3693
4136
  }
3694
- if (matchesKey4(data, Key4.pageUp)) {
3695
- this.scrollView.scrollBy(-Math.max(1, this.scrollView.viewportHeight));
3696
- this.tui.requestRender();
3697
- return;
3698
- }
3699
- if (matchesKey4(data, Key4.pageDown)) {
3700
- this.scrollView.scrollBy(Math.max(1, this.scrollView.viewportHeight));
3701
- this.tui.requestRender();
3702
- return;
4137
+ if (!handleFallbackPaging(data, this.tui, this.keybindings, this.scrollView)) {
4138
+ this.editor?.handleEditorInput(data);
3703
4139
  }
3704
- this.editor?.handleInput(data);
3705
4140
  this.tui.requestRender();
3706
4141
  }
3707
4142
  invalidate() {
@@ -3709,9 +4144,11 @@ var BtwAnsweringView = class {
3709
4144
  }
3710
4145
  finish() {
3711
4146
  this.finished = true;
4147
+ releaseScrollbar(this.scrollView);
3712
4148
  this.loader.stop();
3713
4149
  }
3714
4150
  dispose() {
4151
+ releaseScrollbar(this.scrollView);
3715
4152
  if (this.finished) {
3716
4153
  this.loader.stop();
3717
4154
  this.controller.abort();
@@ -3723,33 +4160,42 @@ var BtwAnsweringView = class {
3723
4160
  this.onCancel();
3724
4161
  }
3725
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) {
3726
4172
  const exit = this.shortcuts.label("exit");
3727
- if (this.warning) {
3728
- const warning = width < 32 ? `Empty \u2022 ${exit}` : `${this.warning} \u2022 ${exit} cancel`;
3729
- return truncateToWidth4(this.theme.fg("warning", warning), width);
3730
- }
3731
- 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") : "";
3732
4175
  const thinking = this.options.steering?.thinking;
3733
- const cycleHint = thinking && thinking.levels.length > 1 && this.thinkingLevel && this.shortcuts.keys.cycleThinkingLevel.length ? ` \u2022 thinking ${this.thinkingLevel} \u2022 ${this.shortcuts.label("cycleThinkingLevel")} cycle` : "";
3734
- const scrollHint = this.getMaxScrollOffset() > 0 ? " \u2022 PgUp/PgDn history" : "";
3735
- const hints = `${baseHint}${cycleHint}${scrollHint}`;
3736
- const compactHints = this.editor ? `Enter \u2022 ${exit}` : exit;
3737
- const selectedHints = visibleWidth3(hints) <= width ? hints : compactHints;
3738
- const loaderWidth = Math.max(1, width - visibleWidth3(selectedHints) - 3);
3739
- const loaderLine = this.loader.render(loaderWidth).at(-1) ?? "Answering\u2026";
3740
- return truncateToWidth4(`${loaderLine} \u2022 ${this.theme.fg("muted", selectedHints)}`, width);
3741
- }
3742
- createHeaderComponent() {
3743
- return {
3744
- render: (width) => [renderSideThreadHeader(width, this.theme, this.thinkingLevel)],
3745
- invalidate() {
3746
- }
3747
- };
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() };
3748
4194
  }
3749
4195
  createTranscriptComponent() {
3750
4196
  return {
3751
4197
  render: (width) => {
3752
- const lines = renderTranscriptLines(this.transcriptComponents, width);
4198
+ const lines = renderTranscriptLines(this.transcriptComponents, width, true);
3753
4199
  this.lastContentLineCount = lines.length;
3754
4200
  return lines;
3755
4201
  },
@@ -3767,7 +4213,7 @@ var BtwAnsweringView = class {
3767
4213
  }
3768
4214
  createFooterComponent() {
3769
4215
  return {
3770
- render: (width) => [this.renderFooter(width)],
4216
+ render: (width) => this.renderFooter(width),
3771
4217
  invalidate: () => this.loader.invalidate()
3772
4218
  };
3773
4219
  }
@@ -3776,7 +4222,8 @@ var BtwAnsweringView = class {
3776
4222
  }
3777
4223
  };
3778
4224
  function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransformers = []) {
3779
- const components = turns.flatMap((turn) => {
4225
+ const components = turns.flatMap((turn, index) => {
4226
+ const preceding = index > 0 ? [new Spacer(1)] : [];
3780
4227
  const question = new UserMessageComponent(
3781
4228
  escapeTerminalControls2(turn.question),
3782
4229
  getMarkdownTheme(),
@@ -3784,10 +4231,12 @@ function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransf
3784
4231
  markdownTransformers
3785
4232
  );
3786
4233
  if (turn.kind === "error") {
3787
- const error = new Markdown(`Error: ${escapeTerminalControls2(turn.answer)}`, 1, 1, getMarkdownTheme(), {
3788
- color: (text) => theme.fg("error", text)
3789
- });
3790
- 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];
3791
4240
  }
3792
4241
  const response = {
3793
4242
  ...turn.response,
@@ -3795,30 +4244,47 @@ function buildTranscriptComponents(turns, theme, pendingQuestion, markdownTransf
3795
4244
  stopReason: "stop",
3796
4245
  errorMessage: void 0
3797
4246
  };
3798
- return [question, new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)];
4247
+ return [
4248
+ ...preceding,
4249
+ question,
4250
+ new AssistantMessageComponent(response, true, getMarkdownTheme(), "", 1, markdownTransformers)
4251
+ ];
3799
4252
  });
3800
4253
  if (pendingQuestion) {
4254
+ if (components.length > 0) components.push(new Spacer(1));
3801
4255
  components.push(
3802
4256
  new UserMessageComponent(escapeTerminalControls2(pendingQuestion), getMarkdownTheme(), 1, markdownTransformers)
3803
4257
  );
3804
4258
  }
3805
4259
  return components;
3806
4260
  }
3807
- function renderTranscriptLines(components, width) {
3808
- return components.flatMap((component) => component.render(width)).map(stripShellIntegrationMarkers);
3809
- }
3810
- function renderSideThreadHeader(width, theme, thinkingLevel) {
3811
- const thinking = thinkingLevel ? ` \xB7 thinking ${thinkingLevel}` : "";
3812
- const title = truncateToWidth4(`\u2500 btw \xB7 side thread${thinking} `, width);
3813
- const ruleWidth = Math.max(0, width - visibleWidth3(title));
3814
- 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
+ });
3815
4275
  }
3816
- function fitComposerLayout(header, contentLines, footer, editorLines, availableRows, statusLines = []) {
3817
- const lines = [header, ...contentLines, ...statusLines, footer, ...editorLines];
3818
- if (lines.length <= availableRows) return lines;
3819
- if (availableRows <= 1) return [header];
3820
- const editorBudget = Math.max(0, availableRows - 2);
3821
- 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
+ ];
3822
4288
  }
3823
4289
  function fitEditorLines(editorLines, budget) {
3824
4290
  if (budget <= 0) return [];
@@ -3833,22 +4299,22 @@ function renderSteeringLines(questions, width, theme, maxLines) {
3833
4299
  const formatQuestion = (question) => sanitizeSingleLine(question) || "(non-printing message)";
3834
4300
  if (maxLines === 1 && questions.length > 1) {
3835
4301
  return [
3836
- truncateToWidth4(
3837
- 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] ?? "")}`),
3838
4304
  width
3839
4305
  )
3840
4306
  ];
3841
4307
  }
3842
4308
  const hasOverflow = questions.length > maxLines;
3843
4309
  const questionLimit = hasOverflow ? Math.max(1, maxLines - 1) : maxLines;
3844
- 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));
3845
4311
  if (hasOverflow) {
3846
- 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));
3847
4313
  }
3848
4314
  return lines;
3849
4315
  }
3850
4316
  function stripShellIntegrationMarkers(line) {
3851
- return OSC133_MARKERS.reduce((result, marker) => result.replaceAll(marker, ""), line);
4317
+ return line.replace(/\u001b\]133;[^\u0007\u001b]*(?:\u0007|\u001b\\)/gu, "");
3852
4318
  }
3853
4319
  function escapeTerminalControls2(text) {
3854
4320
  return [...text].map((character) => {
@@ -3908,6 +4374,7 @@ function readBtwSessionId(ctx) {
3908
4374
  return sessionId.length > 0 ? sessionId : void 0;
3909
4375
  }
3910
4376
  function notifySafely3(ctx, message, level) {
4377
+ if (ctx.signal?.aborted) return;
3911
4378
  try {
3912
4379
  ctx.ui.notify(sanitizeSingleLine(message), level);
3913
4380
  } catch {
@@ -3921,111 +4388,135 @@ function btw(pi, dependencies = {}) {
3921
4388
  const runThread = dependencies.runThread ?? runBtwThread;
3922
4389
  const runFullscreen = dependencies.runFullscreen ?? runBtwFullscreen;
3923
4390
  const subscribeMainThreadUpdates = registerBtwMainThreadUpdates(pi);
3924
- const resumableThreads = /* @__PURE__ */ new Map();
4391
+ const getLifetime = registerBtwSessionLifetimes(pi);
4392
+ const sessionThreads = /* @__PURE__ */ new WeakMap();
3925
4393
  let nextThreadNumber = 1;
3926
- 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) => ({
3927
4395
  id: state.id,
3928
4396
  title: state.title ?? "Untitled side thread",
3929
4397
  questionCount: state.thread.turns.length
3930
4398
  }));
3931
4399
  pi.registerCommand("btw", {
3932
4400
  description: "Ask a quick side question without adding it to the main conversation",
3933
- handler: async (args, ctx) => {
3934
- const question = args.trim();
3935
- if (ctx.mode !== "tui") {
3936
- ctx.ui.notify("/btw requires interactive TUI mode", "error");
3937
- return;
3938
- }
3939
- let menuResult = "start";
3940
- let selectedConversationContext;
3941
- if (!question) {
3942
- while (true) {
3943
- menuResult = await showCommandMenu(pi, ctx, listResumeThreads());
3944
- if (menuResult === "closed") return;
3945
- if (menuResult !== "tree") break;
3946
- const treeResult = await pickEntry(pi, ctx);
3947
- if (treeResult.kind === "closed") return;
3948
- if (treeResult.kind === "back") continue;
3949
- try {
3950
- if (!ctx.sessionManager.getEntry(treeResult.entryId)) {
3951
- notifySafely3(ctx, "The selected main-thread entry is no longer available", "warning");
3952
- continue;
3953
- }
3954
- const branch = ctx.sessionManager.getBranch(treeResult.entryId);
3955
- if (branch.at(-1)?.id !== treeResult.entryId) {
3956
- notifySafely3(ctx, "The selected main-thread branch is no longer available", "warning");
3957
- continue;
3958
- }
3959
- selectedConversationContext = buildConversationContext(branch);
3960
- menuResult = "start";
3961
- break;
3962
- } catch {
3963
- 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;
3964
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;
3965
4449
  }
3966
4450
  }
3967
- const settings = await loadSettings(ctx);
3968
- const sameAsMainThinkingLevel = settings.thinkingLevel === void 0;
3969
- const resolution = await resolveModel(settings, ctx);
3970
- if (resolution.kind === "cancelled") {
3971
- notifySafely3(ctx, "Cancelled", "info");
3972
- return;
3973
- }
3974
- if (resolution.kind === "unavailable") {
3975
- notifySafely3(ctx, "No available model for /btw", "error");
3976
- return;
3977
- }
3978
- let state = typeof menuResult === "object" ? resumableThreads.get(menuResult.threadId) : void 0;
3979
- if (typeof menuResult === "object" && !state) {
3980
- notifySafely3(ctx, "The selected /btw side thread is no longer available", "warning");
3981
- return;
3982
- }
3983
- const startingTurnCount = state?.thread.turns.length ?? 0;
3984
- try {
3985
- await runFullscreen(
3986
- ctx,
3987
- (fullscreenCtx) => {
3988
- if (!state) {
3989
- const createdAt = Date.now();
3990
- state = {
3991
- id: `btw-${nextThreadNumber}`,
3992
- thread: createSideThread(
3993
- selectedConversationContext ?? buildConversationContext(fullscreenCtx.sessionManager.getBranch())
3994
- ),
3995
- thinkingLevel: settings.thinkingLevel ?? pi.getThinkingLevel(),
3996
- createdAt,
3997
- updatedAt: createdAt
3998
- };
3999
- nextThreadNumber += 1;
4000
- }
4001
- 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({
4002
4491
  initialQuestion: question || void 0,
4003
4492
  selected: resolution.selected,
4004
4493
  thinkingLevel: state.thinkingLevel,
4005
4494
  rememberThinkingLevelChanges: !sameAsMainThinkingLevel && effectiveRememberThinkingLevelChanges(settings),
4006
4495
  state,
4007
4496
  ctx: fullscreenCtx
4008
- });
4009
- },
4010
- {
4011
- copyOnSelect: effectiveFullscreenCopyOnSelect(settings),
4012
- layout: effectiveBtwLayout(settings),
4013
- sidePaneRatio: effectiveBtwSidePaneRatio(settings),
4014
- persistSidePaneRatio: (ratio, signal) => updateBtwSettings({ sidePaneRatio: ratio }, { signal }).then(() => void 0),
4015
- subscribeMainThreadUpdates: (listener) => subscribeMainThreadUpdates(ctx.sessionManager, listener),
4016
- ...settings.keybindings ? { keybindings: settings.keybindings } : {}
4017
- }
4018
- );
4019
- } finally {
4020
- if (state?.title && state.thread.turns.length > 0) {
4021
- if (state.thread.turns.length > startingTurnCount) {
4022
- resumableThreads.delete(state.id);
4023
- }
4024
- 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);
4025
4515
  }
4516
+ resumableThreads.set(state.id, state);
4026
4517
  }
4027
4518
  }
4028
- });
4519
+ }
4029
4520
  }
4030
4521
  async function showCommandMenuForBtw(pi, ctx, resumeThreads) {
4031
4522
  return showBtwCommandMenu(ctx, {
@@ -4060,6 +4551,7 @@ async function runBtwThread({
4060
4551
  ctx,
4061
4552
  dependencies = {}
4062
4553
  }) {
4554
+ if (ctx.signal?.aborted) return { kind: "closed" };
4063
4555
  const ask = dependencies.ask ?? askThreadQuestion;
4064
4556
  const interact = dependencies.interact ?? showThreadComposer;
4065
4557
  const chooseBringToMainAction = dependencies.chooseBringToMain ?? chooseBringToMain;
@@ -4078,7 +4570,7 @@ async function runBtwThread({
4078
4570
  level: activeThinkingLevel,
4079
4571
  levels: thinkingLevels,
4080
4572
  onChange: (level) => {
4081
- if (!thinkingLevels.includes(level)) return;
4573
+ if (ctx.signal?.aborted || !thinkingLevels.includes(level)) return;
4082
4574
  activeThinkingLevel = level;
4083
4575
  if (state) state.thinkingLevel = level;
4084
4576
  if (!rememberThinkingLevelChanges) return;
@@ -4095,18 +4587,23 @@ async function runBtwThread({
4095
4587
  });
4096
4588
  try {
4097
4589
  while (true) {
4590
+ if (ctx.signal?.aborted) return { kind: "closed" };
4098
4591
  if (!pendingQuestion) {
4099
- const action = await interact(thread, thread.turns.length > 0, ctx, composerDraft, createThinkingControl());
4100
- 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" };
4101
4597
  if (action.kind === "bringToMain") {
4102
4598
  const choice = await chooseBringToMainAction(thread, ctx);
4599
+ if (ctx.signal?.aborted) return { kind: "closed" };
4103
4600
  if (choice.kind === "closed") return choice;
4104
4601
  if (choice.kind === "back") {
4105
4602
  composerDraft = action.questionDraft;
4106
4603
  continue;
4107
4604
  }
4108
4605
  const delivery = await deliverBringToMainDraft(choice.draft, ctx, choice.summary);
4109
- if (delivery === "loaded" || delivery === "closed") return { kind: "closed" };
4606
+ if (ctx.signal?.aborted || delivery === "loaded" || delivery === "closed") return { kind: "closed" };
4110
4607
  composerDraft = action.questionDraft;
4111
4608
  continue;
4112
4609
  }
@@ -4115,9 +4612,12 @@ async function runBtwThread({
4115
4612
  }
4116
4613
  const result = await ask(thread, pendingQuestion, selected, activeThinkingLevel, ctx, {
4117
4614
  questions: steeringQuestions,
4118
- submit: (question) => steeringQuestions.push(question),
4615
+ submit: (question) => {
4616
+ if (!ctx.signal?.aborted) steeringQuestions.push(question);
4617
+ },
4119
4618
  thinking: createThinkingControl()
4120
4619
  });
4620
+ if (ctx.signal?.aborted) return { kind: "closed" };
4121
4621
  if (result.kind === "aborted") {
4122
4622
  notifySafely3(ctx, "Cancelled", "info");
4123
4623
  return { kind: "closed" };
@@ -4140,6 +4640,7 @@ async function runBtwThread({
4140
4640
  }
4141
4641
  }
4142
4642
  async function chooseBringToMain(thread, ctx, dependencies = {}) {
4643
+ if (ctx.signal?.aborted) return { kind: "closed" };
4143
4644
  const answered = getAnsweredTurns(thread.turns);
4144
4645
  if (answered.length === 0) return { kind: "back" };
4145
4646
  const showMenu = dependencies.showMenu ?? showBtwMenu;
@@ -4164,7 +4665,7 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4164
4665
  [latestOption, fromOption, exactOption, entireOption, cancelOption],
4165
4666
  selectedScope
4166
4667
  );
4167
- if (scopeResult.kind === "close") return { kind: "closed" };
4668
+ if (ctx.signal?.aborted || scopeResult.kind === "close") return { kind: "closed" };
4168
4669
  if (scopeResult.kind === "back" || scopeResult.value === cancelOption) return { kind: "back" };
4169
4670
  const scope = scopeResult.value;
4170
4671
  selectedScope = scope;
@@ -4172,7 +4673,7 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4172
4673
  if (scope === entireOption) {
4173
4674
  const choice = makeChoice(entireSegments);
4174
4675
  const preview = await showPreview(ctx, choice.draft, choice.summary);
4175
- if (preview.kind === "close") return { kind: "closed" };
4676
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
4176
4677
  if (preview.kind === "back") continue;
4177
4678
  return choice;
4178
4679
  }
@@ -4183,14 +4684,14 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4183
4684
  let selectedQuestion;
4184
4685
  while (true) {
4185
4686
  const questionResult = await showMenu(ctx, "Start from which question?", questions, selectedQuestion);
4186
- if (questionResult.kind === "close") return { kind: "closed" };
4687
+ if (ctx.signal?.aborted || questionResult.kind === "close") return { kind: "closed" };
4187
4688
  if (questionResult.kind === "back") break;
4188
4689
  const answeredTurnIndex = questions.indexOf(questionResult.value);
4189
4690
  if (answeredTurnIndex < 0) continue;
4190
4691
  selectedQuestion = questionResult.value;
4191
4692
  const choice = makeChoice(buildQuickBringToMainSegments(thread.turns, { kind: "from", answeredTurnIndex }));
4192
4693
  const preview = await showPreview(ctx, choice.draft, choice.summary);
4193
- if (preview.kind === "close") return { kind: "closed" };
4694
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
4194
4695
  if (preview.kind === "back") continue;
4195
4696
  return choice;
4196
4697
  }
@@ -4218,11 +4719,11 @@ async function chooseBringToMain(thread, ctx, dependencies = {}) {
4218
4719
  return selector;
4219
4720
  }
4220
4721
  );
4221
- if (!selectedRange) return { kind: "closed" };
4722
+ if (ctx.signal?.aborted || !selectedRange) return { kind: "closed" };
4222
4723
  if (selectedRange.kind === "closed") return selectedRange;
4223
4724
  if (selectedRange.kind === "back") break;
4224
4725
  const preview = await showPreview(ctx, selectedRange.draft, selectedRange.summary);
4225
- if (preview.kind === "close") return { kind: "closed" };
4726
+ if (ctx.signal?.aborted || preview.kind === "close") return { kind: "closed" };
4226
4727
  if (preview.kind === "back") {
4227
4728
  selectionState = selectedRange.selectionState;
4228
4729
  continue;
@@ -4262,8 +4763,9 @@ async function showBringToMainPreview(ctx, draft, summary) {
4262
4763
  });
4263
4764
  const result = await runBtwMenuPreservingEditor(
4264
4765
  ctx,
4265
- (menuContext) => runMenu(menuContext, menu, { getState: () => void 0 })
4766
+ (menuContext) => runMenu(menuContext, menu, { getState: () => void 0, signal: ctx.signal })
4266
4767
  );
4768
+ if (ctx.signal?.aborted) return { kind: "close" };
4267
4769
  if (confirmed && result.kind === "closed" && result.reason === "close") {
4268
4770
  return { kind: "bring" };
4269
4771
  }
@@ -4297,8 +4799,9 @@ async function showBtwMenu(ctx, title, options, initialValue) {
4297
4799
  });
4298
4800
  const result = await runBtwMenuPreservingEditor(
4299
4801
  ctx,
4300
- (menuContext) => runMenu(menuContext, menu, { getState: () => void 0 })
4802
+ (menuContext) => runMenu(menuContext, menu, { getState: () => void 0, signal: ctx.signal })
4301
4803
  );
4804
+ if (ctx.signal?.aborted) return { kind: "close" };
4302
4805
  return selectedValue !== void 0 && result.kind === "closed" && result.reason === "close" ? { kind: "select", value: selectedValue } : terminalBtwMenuAction(result);
4303
4806
  }
4304
4807
  function terminalBtwMenuAction(result) {
@@ -4307,6 +4810,7 @@ function terminalBtwMenuAction(result) {
4307
4810
  return { kind: "close" };
4308
4811
  }
4309
4812
  async function loadBringToMainDraft(draft, ctx, summary) {
4813
+ if (ctx.signal?.aborted) return "closed";
4310
4814
  const describeContent = () => `${summary.messages} ${summary.messages === 1 ? "message" : "messages"} (~${summary.tokens} ${summary.tokens === 1 ? "token" : "tokens"})`;
4311
4815
  const existing = ctx.ui.getEditorText();
4312
4816
  if (!existing.trim()) {
@@ -4323,7 +4827,7 @@ async function loadBringToMainDraft(draft, ctx, summary) {
4323
4827
  replaceOption,
4324
4828
  cancelOption
4325
4829
  ]);
4326
- if (action.kind === "close") return "closed";
4830
+ if (ctx.signal?.aborted || action.kind === "close") return "closed";
4327
4831
  if (action.kind === "back" || action.value === cancelOption) return "back";
4328
4832
  if (action.value === appendOption) {
4329
4833
  ctx.ui.setEditorText(`${ctx.ui.getEditorText()}
@@ -4342,7 +4846,7 @@ ${draft}`);
4342
4846
  "Back Keep current editor text",
4343
4847
  "\u26A0 Replace current draft Cannot be undone"
4344
4848
  ]);
4345
- if (confirmed.kind === "close") return "closed";
4849
+ if (ctx.signal?.aborted || confirmed.kind === "close") return "closed";
4346
4850
  if (confirmed.kind === "back" || confirmed.value === "Back Keep current editor text") continue;
4347
4851
  if (confirmed.value !== "\u26A0 Replace current draft Cannot be undone") continue;
4348
4852
  if (ctx.ui.getEditorText() !== current) {
@@ -4362,6 +4866,7 @@ function truncatePreview(text) {
4362
4866
  }
4363
4867
  async function prepareCurrentTranscriptMarkdown(thread, pendingQuestion, ctx) {
4364
4868
  while (true) {
4869
+ if (ctx.signal?.aborted) return void 0;
4365
4870
  const turnCount = thread.turns.length;
4366
4871
  const createMarkdownTransformers = ctx.signal ? await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion, ctx.signal) : await prepareBtwTranscriptMarkdown(thread.turns, pendingQuestion);
4367
4872
  if (!createMarkdownTransformers || ctx.signal?.aborted) return void 0;
@@ -4370,7 +4875,7 @@ async function prepareCurrentTranscriptMarkdown(thread, pendingQuestion, ctx) {
4370
4875
  }
4371
4876
  async function askThreadQuestion(thread, question, selected, thinkingLevel, ctx, steering) {
4372
4877
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, question, ctx);
4373
- if (!createMarkdownTransformers) return { kind: "aborted" };
4878
+ if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "aborted" };
4374
4879
  return ctx.ui.custom((tui, theme, keybindings, done) => {
4375
4880
  let settled = false;
4376
4881
  const view = new BtwAnsweringView(
@@ -4385,6 +4890,7 @@ async function askThreadQuestion(thread, question, selected, thinkingLevel, ctx,
4385
4890
  },
4386
4891
  thinkingLevel,
4387
4892
  {
4893
+ model: { id: selected.model.id, provider: selected.model.provider },
4388
4894
  markdownTransformers: createMarkdownTransformers(theme),
4389
4895
  steering: {
4390
4896
  questions: steering.questions,
@@ -4410,13 +4916,14 @@ async function askThreadQuestion(thread, question, selected, thinkingLevel, ctx,
4410
4916
  return view;
4411
4917
  });
4412
4918
  }
4413
- async function showThreadComposer(thread, startAtBottom, ctx, initialQuestion, thinking) {
4919
+ async function showThreadComposer(thread, startAtBottom, ctx, initialQuestion, thinking, model) {
4414
4920
  const createMarkdownTransformers = await prepareCurrentTranscriptMarkdown(thread, initialQuestion, ctx);
4415
- if (!createMarkdownTransformers) return { kind: "close" };
4921
+ if (!createMarkdownTransformers || ctx.signal?.aborted) return { kind: "close" };
4416
4922
  return ctx.ui.custom(
4417
4923
  (tui, theme, keybindings, done) => new BtwTranscriptPager(tui, theme, thread.turns, done, {
4418
4924
  startAtBottom,
4419
4925
  initialQuestion,
4926
+ model,
4420
4927
  markdownTransformers: createMarkdownTransformers(theme),
4421
4928
  thinking: { ...thinking, keybindings }
4422
4929
  })