@agi-fans/dsh-tui 0.21.0 → 0.22.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.
Files changed (243) hide show
  1. package/lib/CHANGELOG.md +158 -1
  2. package/lib/chrome/box.d.ts +47 -16
  3. package/lib/chrome/box.js +172 -130
  4. package/lib/chrome/box.js.map +1 -1
  5. package/lib/chrome/code-highlight.d.ts +15 -0
  6. package/lib/chrome/code-highlight.js +60 -4
  7. package/lib/chrome/code-highlight.js.map +1 -1
  8. package/lib/chrome/command-output.d.ts +29 -2
  9. package/lib/chrome/command-output.js +100 -4
  10. package/lib/chrome/command-output.js.map +1 -1
  11. package/lib/chrome/main-screen-renderer.d.ts +16 -0
  12. package/lib/chrome/main-screen-renderer.js +53 -5
  13. package/lib/chrome/main-screen-renderer.js.map +1 -1
  14. package/lib/chrome/markdown.js +30 -10
  15. package/lib/chrome/markdown.js.map +1 -1
  16. package/lib/chrome/relative-time.d.ts +17 -0
  17. package/lib/chrome/relative-time.js +36 -0
  18. package/lib/chrome/relative-time.js.map +1 -1
  19. package/lib/chrome/secret-mask.d.ts +35 -0
  20. package/lib/chrome/secret-mask.js +180 -0
  21. package/lib/chrome/secret-mask.js.map +1 -0
  22. package/lib/chrome/status-config.d.ts +161 -51
  23. package/lib/chrome/status-config.js +237 -126
  24. package/lib/chrome/status-config.js.map +1 -1
  25. package/lib/chrome/status-line.d.ts +3 -2
  26. package/lib/chrome/status-line.js +105 -63
  27. package/lib/chrome/status-line.js.map +1 -1
  28. package/lib/chrome/terminal-colors.d.ts +85 -0
  29. package/lib/chrome/terminal-colors.js +230 -0
  30. package/lib/chrome/terminal-colors.js.map +1 -0
  31. package/lib/chrome/terminal-images.d.ts +9 -1
  32. package/lib/chrome/terminal-images.js +27 -4
  33. package/lib/chrome/terminal-images.js.map +1 -1
  34. package/lib/chrome/theme.d.ts +32 -9
  35. package/lib/chrome/theme.js +595 -498
  36. package/lib/chrome/theme.js.map +1 -1
  37. package/lib/chrome/tool-renderers.js +69 -13
  38. package/lib/chrome/tool-renderers.js.map +1 -1
  39. package/lib/chrome/tools-list.d.ts +1 -4
  40. package/lib/chrome/tools-list.js +1 -41
  41. package/lib/chrome/tools-list.js.map +1 -1
  42. package/lib/chrome/welcome-tips.d.ts +20 -8
  43. package/lib/chrome/welcome-tips.js +22 -42
  44. package/lib/chrome/welcome-tips.js.map +1 -1
  45. package/lib/commands/auth-ids.d.ts +25 -0
  46. package/lib/commands/auth-ids.js +27 -0
  47. package/lib/commands/auth-ids.js.map +1 -0
  48. package/lib/commands/auth-input.d.ts +34 -0
  49. package/lib/commands/auth-input.js +96 -0
  50. package/lib/commands/auth-input.js.map +1 -0
  51. package/lib/commands/auth-providers.d.ts +39 -0
  52. package/lib/commands/auth-providers.js +125 -0
  53. package/lib/commands/auth-providers.js.map +1 -0
  54. package/lib/commands/auth.d.ts +12 -20
  55. package/lib/commands/auth.js +42 -229
  56. package/lib/commands/auth.js.map +1 -1
  57. package/lib/commands/btw.d.ts +13 -1
  58. package/lib/commands/btw.js +37 -104
  59. package/lib/commands/btw.js.map +1 -1
  60. package/lib/commands/diff.js +1 -96
  61. package/lib/commands/diff.js.map +1 -1
  62. package/lib/commands/export.d.ts +1 -1
  63. package/lib/commands/export.js +3 -27
  64. package/lib/commands/export.js.map +1 -1
  65. package/lib/commands/files.d.ts +17 -1
  66. package/lib/commands/files.js +67 -107
  67. package/lib/commands/files.js.map +1 -1
  68. package/lib/commands/jobs.d.ts +19 -4
  69. package/lib/commands/jobs.js +50 -7
  70. package/lib/commands/jobs.js.map +1 -1
  71. package/lib/commands/model.js +108 -76
  72. package/lib/commands/model.js.map +1 -1
  73. package/lib/commands/permission.js +15 -16
  74. package/lib/commands/permission.js.map +1 -1
  75. package/lib/commands/plugins.js +133 -16
  76. package/lib/commands/plugins.js.map +1 -1
  77. package/lib/commands/schedule.d.ts +10 -0
  78. package/lib/commands/schedule.js +45 -14
  79. package/lib/commands/schedule.js.map +1 -1
  80. package/lib/commands/session-configuration.js +2 -10
  81. package/lib/commands/session-configuration.js.map +1 -1
  82. package/lib/commands/session.js +14 -38
  83. package/lib/commands/session.js.map +1 -1
  84. package/lib/commands/terminal.d.ts +14 -8
  85. package/lib/commands/terminal.js +19 -178
  86. package/lib/commands/terminal.js.map +1 -1
  87. package/lib/commands/trajectory.js +4 -1
  88. package/lib/commands/trajectory.js.map +1 -1
  89. package/lib/definition.d.ts +122 -22
  90. package/lib/definition.js.map +1 -1
  91. package/lib/index.d.ts +1 -0
  92. package/lib/index.js +1 -0
  93. package/lib/index.js.map +1 -1
  94. package/lib/input/actions.d.ts +51 -0
  95. package/lib/input/actions.js +120 -0
  96. package/lib/input/actions.js.map +1 -0
  97. package/lib/input/editor.d.ts +0 -10
  98. package/lib/input/editor.js +11 -9
  99. package/lib/input/editor.js.map +1 -1
  100. package/lib/input/image-paste.d.ts +19 -1
  101. package/lib/input/image-paste.js +82 -1
  102. package/lib/input/image-paste.js.map +1 -1
  103. package/lib/input/keybindings-config.d.ts +12 -5
  104. package/lib/input/keybindings-config.js +30 -57
  105. package/lib/input/keybindings-config.js.map +1 -1
  106. package/lib/input/keys.d.ts +16 -0
  107. package/lib/input/keys.js +38 -3
  108. package/lib/input/keys.js.map +1 -1
  109. package/lib/input/wheel-scroll.d.ts +46 -0
  110. package/lib/input/wheel-scroll.js +69 -0
  111. package/lib/input/wheel-scroll.js.map +1 -0
  112. package/lib/prompt-intents.d.ts +182 -0
  113. package/lib/prompt-intents.js +127 -0
  114. package/lib/prompt-intents.js.map +1 -0
  115. package/lib/runtime/cancellable.d.ts +75 -0
  116. package/lib/runtime/cancellable.js +76 -0
  117. package/lib/runtime/cancellable.js.map +1 -0
  118. package/lib/runtime/composer-images.js +5 -4
  119. package/lib/runtime/composer-images.js.map +1 -1
  120. package/lib/runtime/composer-shell.d.ts +17 -2
  121. package/lib/runtime/composer-shell.js +109 -43
  122. package/lib/runtime/composer-shell.js.map +1 -1
  123. package/lib/runtime/file-recovery-review.d.ts +0 -1
  124. package/lib/runtime/file-recovery-review.js +29 -30
  125. package/lib/runtime/file-recovery-review.js.map +1 -1
  126. package/lib/runtime/file-recovery-store.js +5 -1
  127. package/lib/runtime/file-recovery-store.js.map +1 -1
  128. package/lib/runtime/file-review.js +1 -1
  129. package/lib/runtime/file-review.js.map +1 -1
  130. package/lib/runtime/hook-settings.d.ts +2 -2
  131. package/lib/runtime/plain-tui.d.ts +2 -0
  132. package/lib/runtime/plain-tui.js +7 -1
  133. package/lib/runtime/plain-tui.js.map +1 -1
  134. package/lib/runtime/plugin-settings.d.ts +1 -1
  135. package/lib/runtime/plugin-settings.js +10 -8
  136. package/lib/runtime/plugin-settings.js.map +1 -1
  137. package/lib/runtime/provider-local.d.ts +57 -15
  138. package/lib/runtime/provider-local.js +1112 -471
  139. package/lib/runtime/provider-local.js.map +1 -1
  140. package/lib/runtime/runner.js +5 -11
  141. package/lib/runtime/runner.js.map +1 -1
  142. package/lib/runtime/settings-preferences.js +1 -1
  143. package/lib/runtime/settings-preferences.js.map +1 -1
  144. package/lib/runtime/startup-notices.js +2 -0
  145. package/lib/runtime/startup-notices.js.map +1 -1
  146. package/lib/runtime/terminal-modes.d.ts +47 -0
  147. package/lib/runtime/terminal-modes.js +86 -0
  148. package/lib/runtime/terminal-modes.js.map +1 -0
  149. package/lib/runtime/terminal-notifications.d.ts +3 -5
  150. package/lib/runtime/terminal-notifications.js +4 -8
  151. package/lib/runtime/terminal-notifications.js.map +1 -1
  152. package/lib/runtime/terminal-probe.d.ts +36 -0
  153. package/lib/runtime/terminal-probe.js +37 -0
  154. package/lib/runtime/terminal-probe.js.map +1 -0
  155. package/lib/runtime/terminal-session.d.ts +57 -0
  156. package/lib/runtime/terminal-session.js +164 -0
  157. package/lib/runtime/terminal-session.js.map +1 -0
  158. package/lib/session/interaction-adapter.js +7 -8
  159. package/lib/session/interaction-adapter.js.map +1 -1
  160. package/lib/session/message-queue.js +1 -1
  161. package/lib/session/message-queue.js.map +1 -1
  162. package/lib/session/package-metadata.d.ts +8 -0
  163. package/lib/session/package-metadata.js +8 -0
  164. package/lib/session/package-metadata.js.map +1 -1
  165. package/lib/session/session-controller.d.ts +10 -11
  166. package/lib/session/session-controller.js +95 -13
  167. package/lib/session/session-controller.js.map +1 -1
  168. package/lib/session/session-tree.d.ts +2 -0
  169. package/lib/session/session-tree.js +2 -0
  170. package/lib/session/session-tree.js.map +1 -1
  171. package/lib/session/tui-settings.d.ts +40 -11
  172. package/lib/session/tui-settings.js +73 -34
  173. package/lib/session/tui-settings.js.map +1 -1
  174. package/lib/views/autocomplete.d.ts +18 -2
  175. package/lib/views/autocomplete.js +51 -38
  176. package/lib/views/autocomplete.js.map +1 -1
  177. package/lib/views/copy-targets.d.ts +12 -13
  178. package/lib/views/copy-targets.js +16 -46
  179. package/lib/views/copy-targets.js.map +1 -1
  180. package/lib/views/document-reader.js +18 -5
  181. package/lib/views/document-reader.js.map +1 -1
  182. package/lib/views/event-views.js +42 -6
  183. package/lib/views/event-views.js.map +1 -1
  184. package/lib/views/history-search.js +15 -21
  185. package/lib/views/history-search.js.map +1 -1
  186. package/lib/views/hotkeys.d.ts +7 -1
  187. package/lib/views/hotkeys.js +49 -25
  188. package/lib/views/hotkeys.js.map +1 -1
  189. package/lib/views/list-navigation.d.ts +62 -0
  190. package/lib/views/list-navigation.js +73 -0
  191. package/lib/views/list-navigation.js.map +1 -0
  192. package/lib/views/list-view.d.ts +99 -0
  193. package/lib/views/list-view.js +165 -0
  194. package/lib/views/list-view.js.map +1 -0
  195. package/lib/views/prompt-selector.d.ts +31 -3
  196. package/lib/views/prompt-selector.js +249 -125
  197. package/lib/views/prompt-selector.js.map +1 -1
  198. package/lib/views/session-files.d.ts +1 -2
  199. package/lib/views/session-files.js +1 -11
  200. package/lib/views/session-files.js.map +1 -1
  201. package/lib/views/settings-list.d.ts +10 -8
  202. package/lib/views/settings-list.js +116 -283
  203. package/lib/views/settings-list.js.map +1 -1
  204. package/lib/views/trajectory-timeline.d.ts +72 -0
  205. package/lib/views/trajectory-timeline.js +133 -0
  206. package/lib/views/trajectory-timeline.js.map +1 -0
  207. package/lib/views/trajectory.d.ts +15 -4
  208. package/lib/views/trajectory.js +557 -123
  209. package/lib/views/trajectory.js.map +1 -1
  210. package/lib/views/transcript-render.d.ts +95 -25
  211. package/lib/views/transcript-render.js +501 -167
  212. package/lib/views/transcript-render.js.map +1 -1
  213. package/lib/views/transcript-search.d.ts +39 -6
  214. package/lib/views/transcript-search.js +46 -11
  215. package/lib/views/transcript-search.js.map +1 -1
  216. package/lib/views/transcript-types.d.ts +63 -5
  217. package/lib/views/transcript-types.js +23 -11
  218. package/lib/views/transcript-types.js.map +1 -1
  219. package/package.json +67 -86
  220. package/lib/commands/advisor.d.ts +0 -15
  221. package/lib/commands/advisor.js +0 -200
  222. package/lib/commands/advisor.js.map +0 -1
  223. package/lib/commands/loop.d.ts +0 -52
  224. package/lib/commands/loop.js +0 -307
  225. package/lib/commands/loop.js.map +0 -1
  226. package/lib/commands/rate.d.ts +0 -33
  227. package/lib/commands/rate.js +0 -212
  228. package/lib/commands/rate.js.map +0 -1
  229. package/lib/commands/steer.d.ts +0 -5
  230. package/lib/commands/steer.js +0 -24
  231. package/lib/commands/steer.js.map +0 -1
  232. package/lib/commands/worktree.d.ts +0 -5
  233. package/lib/commands/worktree.js +0 -103
  234. package/lib/commands/worktree.js.map +0 -1
  235. package/lib/runtime/terminal-reader.d.ts +0 -11
  236. package/lib/runtime/terminal-reader.js +0 -87
  237. package/lib/runtime/terminal-reader.js.map +0 -1
  238. package/lib/views/agent-hub.d.ts +0 -32
  239. package/lib/views/agent-hub.js +0 -209
  240. package/lib/views/agent-hub.js.map +0 -1
  241. package/lib/views/copy-selector.d.ts +0 -54
  242. package/lib/views/copy-selector.js +0 -170
  243. package/lib/views/copy-selector.js.map +0 -1
@@ -2,7 +2,7 @@
2
2
  * TUI capability seam — local terminal provider.
3
3
 
4
4
  * Owns the tty: raw-mode key input (editing, history, slash/tab
5
- * autocomplete, /settings overlay, /copy picker, Ctrl-R history search, PgUp/PgDn
5
+ * autocomplete, /settings overlay, Ctrl-R history search, PgUp/PgDn
6
6
  * and Shift+Up/Down transcript scroll, Ctrl-O tool
7
7
  * expand, bracketed paste, double-Escape conversation rewind, double Ctrl-C exit, Ctrl-D quit),
8
8
  * SIGWINCH reflow, and the differential renderer. In non-tty mode
@@ -10,8 +10,11 @@
10
10
  * printing of settled blocks.
11
11
  * @module @agi-fans/dsh-tui
12
12
  */
13
- import { TerminalNotificationController, TerminalNotificationQueue, terminalNotificationSequence, terminalProgressSequence, } from "./terminal-notifications.js";
13
+ import { TerminalNotificationController, TerminalNotificationQueue, terminalNotificationSequence, } from "./terminal-notifications.js";
14
14
  import { PROGRAM_STATUS_QUERY, programStatusSequence, terminalTitle } from "./terminal-state.js";
15
+ import { TerminalSession } from "./terminal-session.js";
16
+ import { BRACKETED_PASTE, FOCUS_REPORTING, MOUSE_TRACKING, } from "./terminal-modes.js";
17
+ import { IDLE_WHEEL, terminalAcceleratesWheel, wheelStep } from "../input/wheel-scroll.js";
15
18
  import { HerdrAgentReporter } from "./herdr-agent.js";
16
19
  import { imageProtocol } from "../chrome/terminal-images.js";
17
20
  import { previewImages } from "./image-preview.js";
@@ -36,17 +39,15 @@ import { matchesAtShortcutQuery, nextSelectableAutocompleteIndex, searchAtSugges
36
39
  import { readTmuxMouseEnabled } from "../input/mouse-policy.js";
37
40
  import { TextSelection } from "../input/text-selection.js";
38
41
  import { copyToClipboard, readFromClipboard } from "../input/clipboard.js";
39
- import { applyCopySelectorEvent, createCopySelector, } from "../views/copy-selector.js";
40
- import { buildCopyTargets, extractCopyTarget, parseCopyKind } from "../views/copy-targets.js";
42
+ import { buildCopyTargets } from "../views/copy-targets.js";
41
43
  import { applyHistorySearchEvent, createHistorySearch, } from "../views/history-search.js";
42
44
  import { InputEditor, lineEnd, lineStart } from "../input/editor.js";
43
45
  import { applySettingsEvent, createSettings, refreshSettings, tuiSettingItems, } from "../views/settings-list.js";
44
46
  import { editSettingsEntry, pluginSettingsEntries, resetSettingsControl, setSettingsEntry, showSettingsError } from "./plugin-settings.js";
45
47
  import { preferenceChanges } from "./settings-preferences.js";
46
48
  import { appendTrajectoryEvent, applyTrajectoryEvent, createTrajectory, trajectoryDetailMetrics, trajectoryListMetrics, } from "../views/trajectory.js";
47
- import { applyAgentHubEvent, createAgentHub, updateAgentHub, } from "../views/agent-hub.js";
48
- import { applyEvent, applyStreamChunk, blockSearchText, initialTranscript, replayEvents, renderView, turnGroups, transcriptSeam, TRANSCRIPT_FAST_SCROLL, withWorkspaceSummary, } from "../views/event-views.js";
49
- import { applyTranscriptSearchEvent, createTranscriptSearch, searchBlockIndexes, } from "../views/transcript-search.js";
49
+ import { applyEvent, applyStreamChunk, renderedBlocks, formatAgentElapsed, subagentPreviewStart, initialTranscript, replayEvents, renderView, turnGroups, transcriptSeam, TRANSCRIPT_FAST_SCROLL, withWorkspaceSummary, } from "../views/event-views.js";
50
+ import { applyTranscriptSearchEvent, createTranscriptSearch, searchMatches, } from "../views/transcript-search.js";
50
51
  import { nextRevealStep, revealStreamingAssistant, streamingAssistantKey, streamingAssistantUnits, } from "../views/streaming-reveal.js";
51
52
  import { flushPending, parseKeys } from "../input/keys.js";
52
53
  import { sanitizeDisplayLine } from "../chrome/renderer.js";
@@ -54,27 +55,45 @@ import { blockFileAction } from "../views/file-actions.js";
54
55
  import { fileDocument, reviewFiles } from "./file-review.js";
55
56
  import { stripAnsi } from "../chrome/width.js";
56
57
  import { MainScreenRenderer } from "../chrome/main-screen-renderer.js";
57
- import { colorDisabledByEnv, createTheme, detectTrueColor } from "../chrome/theme.js";
58
+ import { colorDisabledByEnv, createTheme, detectColorDepth } from "../chrome/theme.js";
59
+ import { formatToolsText } from "../chrome/tools-list.js";
58
60
  import { renderTool } from "../chrome/tool-renderers.js";
59
- import { TUI_SETTINGS_ENTRY, TUI_SETTINGS_FIELDS } from "../session/tui-settings.js";
60
- import { defaultStatusBarConfig, resolveStatusBarConfig } from "../chrome/status-config.js";
61
+ import { NOTIFICATION_THRESHOLD_MS, resolveNotificationMode, TUI_SETTINGS_ENTRY, TUI_SETTINGS_FIELDS, } from "../session/tui-settings.js";
62
+ import { DEFAULT_STATUS_DENSITY, resolveStatusBarConfig, statusBarDocument } from "../chrome/status-config.js";
61
63
  import { HistoryStore } from "../session/history-store.js";
62
64
  import { PasteBurst } from "../input/paste-burst.js";
63
65
  import { DEFAULT_KEYBINDINGS, loadKeybindings, saveKeybindings, TUI_ACTION_LABELS, TUI_ACTIONS } from "../input/keybindings-config.js";
64
66
  import { discoverEditors } from "../input/editor-discovery.js";
65
67
  import { editExternally, editFileExternally } from "../input/external-editor.js";
66
68
  import z from '@deepseek-ai/schemastery';
67
- import { movePromptSelection, movePromptTree, searchPromptSelection, filteredPromptOptions, refreshPromptOptions, promptTreePageSize, selectedPromptAnswer, selectedFilteredPromptAnswer, togglePromptSelection, } from "../views/prompt-selector.js";
69
+ import { movePromptSelection, movePromptTree, searchPromptSelection, filteredPromptOptions, refreshPromptOptions, promptTreePageSize, selectedPromptAnswer, selectedFilteredPromptAnswer, togglePromptSelection, documentRows, findInRows, } from "../views/prompt-selector.js";
70
+ import { edgeIndex, listNavigation, navigateIndex } from "../views/list-navigation.js";
68
71
  import { refreshProjectContext, resolveGitStatusFiles, resolveProjectContext } from "../session/project-context.js";
69
- import { pickWelcomeTips } from "../chrome/welcome-tips.js";
70
72
  import { modelRouteReady } from "../session/model-readiness.js";
71
73
  import { formatEssentialHotkeysText, formatHotkeysText, hotkeyCount, keysForAction } from "../views/hotkeys.js";
72
- import { imagePathCandidates, stripComposerImageMarkers, readImageFile, readImageFromClipboard, readMacClipboardFiles, } from "../input/image-paste.js";
73
- import { APP_NAME, APP_VERSION } from "../session/package-metadata.js";
74
+ import { imagePathCandidates, splitComposerImageMarkers, stripComposerImageMarkers, readImageFile, readImageFromClipboard, readMacClipboardFiles, } from "../input/image-paste.js";
75
+ import { APP_DISPLAY_NAME, APP_NAME, APP_VERSION } from "../session/package-metadata.js";
74
76
  const DOUBLE_CTRL_C_MS = 500;
77
+ /**
78
+ * Whether an open completion menu still speaks for the `@` token being typed.
79
+ *
80
+ * A `@` menu is built for a prefix, and the reader extends that prefix one
81
+ * keystroke at a time while the search for the new one is still running. The
82
+ * rows on screen describe a token this one extends, so they stay. Anything else
83
+ * — a new `@`, a different path, a token that was never recorded — describes
84
+ * nothing on screen and must not be reused.
85
+ */
86
+ export function completionDescribes(described, current) {
87
+ if (described === undefined)
88
+ return false;
89
+ return current.startsWith(described) || described.startsWith(current);
90
+ }
91
+ /** How long a confirmation stays on the composer's border before it fades. */
92
+ const TRANSIENT_STATUS_MS = 3_000;
93
+ /** Shortest interval between repaints while a Shell command writes. */
94
+ const SHELL_PAINT_INTERVAL_MS = 80;
75
95
  const DOUBLE_ESCAPE_MS = 500;
76
96
  const STREAMING_REVEAL_MS = 1000 / 30;
77
- const TERMINAL_PROGRESS_KEEPALIVE_MS = 1_000;
78
97
  /**
79
98
  * Durable settlement events that arrive in bursts while a turn runs. Renders
80
99
  * for these are coalesced through the stream-render timer; rarer control
@@ -157,18 +176,11 @@ export class LocalTui {
157
176
  if (!this.#tty)
158
177
  throw new Error('Opening an editor requires an interactive terminal.');
159
178
  try {
160
- this.#setMouseTracking(false);
161
- this.#term.output.write('\x1b[?1004l');
162
- this.#term.input.setRawMode?.(false);
163
- editFileExternally(path, this.#externalEditor);
179
+ this.#handTerminal(() => { editFileExternally(path, this.#externalEditor); });
164
180
  }
165
181
  finally {
166
- if (!this.#disposed) {
167
- this.#term.input.setRawMode?.(true);
168
- this.#term.output.write('\x1b[?1004h');
169
- this.#renderer.reset();
182
+ if (!this.#disposed)
170
183
  this.#render();
171
- }
172
184
  }
173
185
  }
174
186
  #deferInitialRender = false;
@@ -231,6 +243,10 @@ export class LocalTui {
231
243
  #draftTimer;
232
244
  #unsavedDrafts = new Map();
233
245
  #draftError = false;
246
+ /**
247
+ * The open completion menu. `query` is the `@` prefix the rows were built for,
248
+ * so the next keystroke can tell "that token, extended" from "a different one".
249
+ */
234
250
  #ac = null;
235
251
  #search = null;
236
252
  #transcriptSearch = null;
@@ -239,9 +255,7 @@ export class LocalTui {
239
255
  #features;
240
256
  /** Profile patch the Tools feature controls write; absent hides those controls. */
241
257
  #featurePatch;
242
- #copySelector = null;
243
258
  #trajectory = null;
244
- #agentHub = null;
245
259
  #pending = null;
246
260
  #queuedSubmissions = [];
247
261
  /** Newer queue entries temporarily detached while Up browses backward. */
@@ -308,17 +322,37 @@ export class LocalTui {
308
322
  #terminalState = 'auto';
309
323
  #programSupported = false;
310
324
  #programQuerySent = false;
325
+ /** What the terminal reported about its own colors; empty until (and unless) it answers. */
326
+ get #terminalColors() { return this.#session.colors; }
327
+ /** Capability probe, reported colors, keyboard protocol, and every terminal mode this session turned on. */
328
+ #session = new TerminalSession({
329
+ write: bytes => { this.#term.output.write(bytes); },
330
+ alternateActive: () => this.#renderer?.alternateActive ?? false,
331
+ setAlternateScreenModes: modes => { this.#renderer?.setAlternateScreenModes(modes); },
332
+ deferUntilMainScreen: bytes => { this.#renderer?.deferUntilMainScreen(bytes); },
333
+ colorsChanged: () => { this.#render(); },
334
+ probeSettled: () => {
335
+ this.#probeGate = false;
336
+ if (!this.#disposed && !this.#deferInitialRender)
337
+ this.#render();
338
+ },
339
+ });
340
+ #offExit;
341
+ /** Accumulated wheel gesture, so fast spins move further than one notch. */
342
+ #wheelGesture = IDLE_WHEEL;
343
+ #wheelAccelerates;
344
+ /** When the pending provider retry fires, so the working row can count down. */
345
+ #retryDeadline;
346
+ /** When the running compaction started. */
347
+ #compactionStartedAt;
348
+ #readImageInput;
311
349
  #writtenProgramState;
312
- #terminalProgress = false;
313
- #terminalProgressActive = false;
314
- #terminalProgressTick = null;
315
350
  #checkUpdates = true;
316
351
  #startupChangelog = 'summary';
317
352
  #notifications = new TerminalNotificationController();
318
353
  #notificationQueue = new TerminalNotificationQueue();
319
354
  #notificationTimer;
320
355
  #terminalFocused;
321
- #notificationFocus = 'unfocused';
322
356
  /**
323
357
  * Herdr lifecycle authority for this pane. The plugin entry injects the
324
358
  * environment-aware reporter; a directly constructed instance is inert so
@@ -326,9 +360,10 @@ export class LocalTui {
326
360
  */
327
361
  #herdr;
328
362
  #notificationPolicy = 'off';
329
- #notificationThreshold = '30s';
330
- #statusBar = defaultStatusBarConfig();
363
+ #statusBar = resolveStatusBarConfig({ density: DEFAULT_STATUS_DENSITY, hidden: [] });
331
364
  #toolsExpanded = false;
365
+ /** Command outputs the reader opened; the rest fold after their preview. */
366
+ #expandedOutputs = new Set();
332
367
  /**
333
368
  * The reader opened something with Ctrl+O or Alt+O and is reading it.
334
369
  *
@@ -347,11 +382,31 @@ export class LocalTui {
347
382
  #copyOnSelect = true;
348
383
  #mathMode = 'auto';
349
384
  #mermaidMode = 'auto';
385
+ /** Transcript collapses every thought to one line; Ctrl+T flips it. */
386
+ #hideThinking = false;
350
387
  #mouseInteraction = 'auto';
351
388
  #tmuxMouseEnabled;
352
389
  #jumpPress;
353
390
  #jumpToLatest;
354
391
  #openedGroups = new Set();
392
+ /** Side-conversation pane; owned here so Esc can close it from any state. */
393
+ #aside;
394
+ /** Set while the pane is open, so closing it stops the work it was showing. */
395
+ #asideAbort;
396
+ /** Thoughts a reader opened individually, addressed by reasoning identity. */
397
+ #expandedReasoning = new Set();
398
+ /**
399
+ * The last action's confirmation, drawn on the composer's bottom border.
400
+ *
401
+ * A status that reports what a key just did is not part of the conversation,
402
+ * so it never enters the block list: it replaces itself, and it is dropped by
403
+ * the next keystroke. Writing it into the transcript would put chatter into
404
+ * native scrollback, which cannot be taken back.
405
+ */
406
+ #transientStatus;
407
+ #transientTimer = null;
408
+ /** Aborts the live Shell card, so Ctrl+C interrupts the command it belongs to. */
409
+ #shellAbort;
355
410
  /** Turn scopes whose tools stay detailed as new calls arrive during inspection. */
356
411
  #detailedTurns = new Set();
357
412
  #tools = [];
@@ -367,8 +422,6 @@ export class LocalTui {
367
422
  * when the prompt settles.
368
423
  */
369
424
  #promptDisplaced = null;
370
- #recentSessions = [];
371
- #welcomeTips;
372
425
  #sessionId;
373
426
  #sessionTitle;
374
427
  #writtenWindowTitle;
@@ -376,7 +429,13 @@ export class LocalTui {
376
429
  #sessionControls;
377
430
  #loopStatus;
378
431
  #subagents;
379
- #subagentLauncherFocused = false;
432
+ /**
433
+ * The roster row the reader is pointing at, or `undefined` when the composer
434
+ * owns the keyboard. `↓` on an empty composer enters the bar; `Enter` opens the
435
+ * child. The bar is the roster now — the full-screen hub it used to open was a
436
+ * second stop on the way to the same transcript.
437
+ */
438
+ #subagentSelection;
380
439
  #inspected;
381
440
  #promptDocument;
382
441
  /**
@@ -384,7 +443,9 @@ export class LocalTui {
384
443
  * preference changes so a session that starts colorless can still enable
385
444
  * hexadecimal palettes without a restart.
386
445
  */
387
- #trueColor = false;
446
+ #colorDepth = 'ansi16';
447
+ /** Hold the first frame until the capability probe settles; scrollback rows are immutable, so the first real paint must use the reported colors. */
448
+ #probeGate = false;
388
449
  #copy;
389
450
  #copyTask = Promise.resolve();
390
451
  #readClipboard;
@@ -455,14 +516,15 @@ export class LocalTui {
455
516
  this.#searchFileMentions = paths.searchFileMentions;
456
517
  this.#searchSessions = paths.searchSessions;
457
518
  this.#autocompleteDebounceMs = Math.max(0, paths.autocompleteDebounceMs ?? 100);
458
- this.#welcomeTips = pickWelcomeTips();
459
519
  this.#deferInitialRender = paths.deferInitialRender === true;
460
520
  this.#terminalProfile = paths.terminalProfile ?? detectTerminalProfile();
461
521
  this.#imageProtocol = this.#terminalProfile !== 'direct' || paths.imageProtocol === 'none' ? undefined : paths.imageProtocol ?? imageProtocol(process.env);
522
+ this.#readImageInput = paths.readImageInput;
462
523
  this.#resizeDebounceMs = Math.max(0, paths.resizeDebounceMs ?? 120);
463
524
  this.#streamRenderMs = Math.max(0, paths.streamRenderMs ?? 8);
525
+ this.#wheelAccelerates = paths.wheelAcceleration ?? !terminalAcceleratesWheel();
464
526
  this.#herdr = paths.herdrReporter ?? new HerdrAgentReporter({ env: {} });
465
- this.#syncTrueColor();
527
+ this.#syncColorDepth();
466
528
  this.#tty = term.input.isTTY === true && term.output.isTTY === true;
467
529
  this.#draftStore = this.#tty && paths.draftsPath !== undefined ? new ComposerDraftStore(paths.draftsPath) : undefined;
468
530
  this.#plain = new PlainTui({
@@ -470,6 +532,7 @@ export class LocalTui {
470
532
  blocks: () => this.#state.blocks,
471
533
  mathMode: () => this.#mathMode,
472
534
  mermaidMode: () => this.#mermaidMode,
535
+ hideThinking: () => this.#hideThinking,
473
536
  promptRequest: () => this.#prompt?.request,
474
537
  finishPrompt: answer => { this.#finishPrompt(answer); },
475
538
  });
@@ -516,14 +579,22 @@ export class LocalTui {
516
579
  this.#programQuerySent = false;
517
580
  this.#programSupported = false;
518
581
  this.#syncWindowTitle();
519
- this.#term.output.write('\x1b[?1004h');
582
+ this.#session.takeBack();
520
583
  this.#renderer.reset();
521
584
  this.#render();
522
585
  };
523
586
  process.on('SIGCONT', resume);
524
587
  this.#offResume = () => { process.off('SIGCONT', resume); };
525
588
  }
526
- term.output.write('\x1b[?2004h\x1b[?1004h');
589
+ this.#session.setMode('paste', BRACKETED_PASTE, true);
590
+ this.#session.setMode('focus', FOCUS_REPORTING, true);
591
+ this.#probeGate = this.#deferInitialRender;
592
+ // A crash or `process.exit` skips dispose; the shell must still get its
593
+ // terminal back rather than a stuck alternate screen or key encoding.
594
+ const onExit = () => { this.#restoreTerminalOnExit(); };
595
+ process.once('exit', onExit);
596
+ this.#offExit = () => { process.off('exit', onExit); };
597
+ this.#session.start();
527
598
  }
528
599
  this.#render();
529
600
  this.#herdr.start();
@@ -562,7 +633,16 @@ export class LocalTui {
562
633
  this.#syncStreamingReveal(undefined);
563
634
  this.#render();
564
635
  }
636
+ if (event.type === 'llm/retry')
637
+ this.#retryDeadline = Date.now() + event.data.delayMs;
638
+ if (event.type === 'llm/retry-started' || event.type === 'turn/end')
639
+ this.#retryDeadline = undefined;
565
640
  this.#state = applyEvent(this.#state, event, presentation, workspace);
641
+ const compacting = this.#state.status === 'compacting';
642
+ if (compacting && this.#compactionStartedAt === undefined)
643
+ this.#compactionStartedAt = Date.now();
644
+ else if (!compacting)
645
+ this.#compactionStartedAt = undefined;
566
646
  if (event.type === 'turn/end' && this.#inspected === undefined) {
567
647
  this.#herdr.settled(event.data.reason.kind);
568
648
  this.#syncWindowTitle();
@@ -675,13 +755,7 @@ export class LocalTui {
675
755
  ? undefined
676
756
  : { agents: roster.agents.map(agent => ({ ...agent, activity: [...agent.activity] })) };
677
757
  if ((this.#subagents?.agents.length ?? 0) === 0)
678
- this.#subagentLauncherFocused = false;
679
- if (this.#agentHub !== null) {
680
- if (this.#subagents === undefined)
681
- this.#agentHub = null;
682
- else
683
- this.#agentHub = updateAgentHub(this.#agentHub, this.#subagents);
684
- }
758
+ this.#subagentSelection = undefined;
685
759
  const inspected = this.#inspected;
686
760
  if (inspected !== undefined) {
687
761
  const current = this.#subagents?.agents.find(agent => agent.id === inspected.id);
@@ -695,7 +769,7 @@ export class LocalTui {
695
769
  };
696
770
  }
697
771
  }
698
- if (!statusChanged && this.#agentHub === null)
772
+ if (!statusChanged)
699
773
  return;
700
774
  this.#syncTick();
701
775
  if (this.#tty)
@@ -710,7 +784,7 @@ export class LocalTui {
710
784
  this.#inspected = inspected === undefined ? undefined : { ...inspected };
711
785
  if (inspected !== undefined) {
712
786
  this.#inspectEscapeFenceUntil = 0;
713
- this.#subagentLauncherFocused = false;
787
+ this.#subagentSelection = undefined;
714
788
  }
715
789
  this.#syncTick();
716
790
  if (this.#tty)
@@ -735,9 +809,7 @@ export class LocalTui {
735
809
  return false;
736
810
  this.#finishPrompt(null);
737
811
  this.#trajectory = createTrajectory(events);
738
- this.#agentHub = null;
739
812
  this.#settings = null;
740
- this.#copySelector = null;
741
813
  this.#search = null;
742
814
  this.#ac = null;
743
815
  this.#render();
@@ -816,6 +888,198 @@ export class LocalTui {
816
888
  else
817
889
  this.#plain.print();
818
890
  }
891
+ /**
892
+ * Run a Shell line as a live card that streams in place.
893
+ *
894
+ * The card is appended before the command starts and updated as it writes, so
895
+ * the reader watches their own command rather than switching to another
896
+ * surface and coming back. It never waits for an exit gesture: when the
897
+ * command finishes the card is finished too, exactly like a tool call.
898
+ */
899
+ async shellCommand(request) {
900
+ const block = { kind: 'shell', command: request.command, output: '', status: 'running' };
901
+ this.#insertShellBlock(block);
902
+ // Ctrl+C belongs to the running command while its card is alive, the same
903
+ // way it belongs to an active turn. The caller decides what to do with the
904
+ // abort; the provider only routes the key.
905
+ this.#shellAbort = request.abort;
906
+ let lastPaint = 0;
907
+ let pending = '';
908
+ let pendingPaint;
909
+ const cancelPending = () => { if (pendingPaint !== undefined) {
910
+ clearTimeout(pendingPaint);
911
+ pendingPaint = undefined;
912
+ } };
913
+ const paint = () => { if (this.#tty && !this.#disposed)
914
+ this.#render(); };
915
+ // Output can arrive faster than a frame is worth; coalescing keeps a chatty
916
+ // command from spending the whole turn in the renderer.
917
+ const append = (output) => {
918
+ pending = output;
919
+ const now = Date.now();
920
+ if (now - lastPaint < SHELL_PAINT_INTERVAL_MS) {
921
+ cancelPending();
922
+ pendingPaint = setTimeout(paint, SHELL_PAINT_INTERVAL_MS - (now - lastPaint));
923
+ return;
924
+ }
925
+ lastPaint = now;
926
+ this.#updateShellBlock(request.command, current => ({ ...current, output: pending }));
927
+ paint();
928
+ };
929
+ let result;
930
+ try {
931
+ result = await request.run(append, request.signal);
932
+ }
933
+ catch (error) {
934
+ this.#updateShellBlock(request.command, current => ({ ...current, status: 'error' }));
935
+ paint();
936
+ throw error;
937
+ }
938
+ finally {
939
+ cancelPending();
940
+ if (this.#shellAbort === request.abort)
941
+ this.#shellAbort = undefined;
942
+ }
943
+ const failed = result.interrupted === true || (result.code !== undefined && result.code !== 0);
944
+ this.#updateShellBlock(request.command, current => ({
945
+ ...current,
946
+ output: result.output === '' ? current.output : result.output,
947
+ status: failed ? 'error' : 'ok',
948
+ ...(result.code === undefined ? {} : { code: result.code }),
949
+ ...(request.share === true ? { shared: true } : {}),
950
+ }));
951
+ paint();
952
+ return result;
953
+ }
954
+ /**
955
+ * A side question, streamed into its own transcript block.
956
+ *
957
+ * Modelled on `shellCommand` rather than on `commandOutput`: the answer arrives
958
+ * over time, and the reader should watch it arrive where it will stay. Coalesced
959
+ * the same way, because a chatty stream would otherwise spend the turn in the
960
+ * renderer.
961
+ */
962
+ /** Navigation belongs to the pane only when nothing else is claiming it. */
963
+ #asideOwnsKeys() {
964
+ return this.#editor.text === '' && this.#ac === null && this.#prompt === null;
965
+ }
966
+ /**
967
+ * Leaving the pane stops the consultation.
968
+ *
969
+ * Without this the request kept running invisibly and its answer was dropped,
970
+ * so the reader could neither read it nor stop paying for it.
971
+ */
972
+ #closeAside() {
973
+ const aside = this.#aside;
974
+ this.#asideAbort?.abort();
975
+ this.#asideAbort = undefined;
976
+ this.#aside = undefined;
977
+ /**
978
+ * A finished answer collapses into one line rather than disappearing.
979
+ *
980
+ * The pane is above the composer, so closing it was the only way to get the
981
+ * screen height back — and that cost the text. Keeping the exchange as a
982
+ * folded block means the reader can always close the pane. A consultation
983
+ * still running records nothing: the reader left before there was an answer.
984
+ */
985
+ if (aside !== undefined && aside.status !== 'running' && aside.text.trim() !== '') {
986
+ this.#state = { ...this.#state, blocks: [...this.#state.blocks, { kind: 'aside', question: aside.question, text: aside.text }] };
987
+ this.#followTail();
988
+ }
989
+ this.#render();
990
+ }
991
+ /**
992
+ * A side question, streamed into its own pane above the composer.
993
+ *
994
+ * Not a transcript block: the exchange belongs to a conversation that is not
995
+ * this one, so it gets its own pane rather than a row in the conversation the
996
+ * reader is working in. The pane is docked, `Esc` closes it, and the session
997
+ * looks exactly as it did. Coalesced the same way a Shell card is, because a
998
+ * chatty stream would otherwise spend the turn in the renderer.
999
+ */
1000
+ async asideQuestion(request) {
1001
+ this.#asideAbort?.abort();
1002
+ const abort = new AbortController();
1003
+ this.#asideAbort = abort;
1004
+ // Leaving the pane and losing the session both stop the consultation.
1005
+ if (request.signal.aborted)
1006
+ abort.abort();
1007
+ else
1008
+ request.signal.addEventListener('abort', () => abort.abort(), { once: true });
1009
+ this.#aside = { question: request.question, text: '', status: 'running', scroll: 0 };
1010
+ this.#render();
1011
+ let lastPaint = 0;
1012
+ let pending = '';
1013
+ let pendingPaint;
1014
+ const paint = () => { if (this.#tty && !this.#disposed)
1015
+ this.#render(); };
1016
+ const show = (change) => {
1017
+ if (this.#aside !== undefined)
1018
+ this.#aside = { ...this.#aside, ...change };
1019
+ };
1020
+ /**
1021
+ * The pending text is applied by the paint, not merely followed by one: a
1022
+ * chunk that arrives inside the throttle window used to schedule a repaint of
1023
+ * the *old* text, so the last words before a pause never appeared.
1024
+ */
1025
+ const flush = () => {
1026
+ if (pendingPaint !== undefined) {
1027
+ clearTimeout(pendingPaint);
1028
+ pendingPaint = undefined;
1029
+ }
1030
+ lastPaint = Date.now();
1031
+ show({ text: pending });
1032
+ paint();
1033
+ };
1034
+ const stream = (text) => {
1035
+ pending = text;
1036
+ const wait = SHELL_PAINT_INTERVAL_MS - (Date.now() - lastPaint);
1037
+ if (wait <= 0) {
1038
+ flush();
1039
+ return;
1040
+ }
1041
+ if (pendingPaint !== undefined)
1042
+ clearTimeout(pendingPaint);
1043
+ pendingPaint = setTimeout(flush, wait);
1044
+ };
1045
+ try {
1046
+ const result = await request.run(stream, abort.signal);
1047
+ show({
1048
+ text: result.text,
1049
+ status: result.failed === true ? 'error' : 'done',
1050
+ ...(result.detail === undefined ? {} : { detail: result.detail }),
1051
+ });
1052
+ }
1053
+ catch (error) {
1054
+ if (!abort.signal.aborted)
1055
+ show({ status: 'error', detail: error instanceof Error ? error.message : String(error) });
1056
+ }
1057
+ finally {
1058
+ if (pendingPaint !== undefined)
1059
+ clearTimeout(pendingPaint);
1060
+ if (this.#asideAbort === abort)
1061
+ this.#asideAbort = undefined;
1062
+ paint();
1063
+ }
1064
+ }
1065
+ /** Append a Shell card and follow it, so the reader sees it start. */
1066
+ #insertShellBlock(block) {
1067
+ this.#state = { ...this.#state, blocks: [...this.#state.blocks, block] };
1068
+ this.#followTail();
1069
+ if (this.#tty)
1070
+ this.#render();
1071
+ else
1072
+ this.#plain.print();
1073
+ }
1074
+ /** Replace the newest Shell card for `command`; a card is identified by its position. */
1075
+ #updateShellBlock(command, update) {
1076
+ const at = this.#state.blocks.findLastIndex(block => block.kind === 'shell' && block.command === command);
1077
+ if (at < 0)
1078
+ return;
1079
+ const next = this.#state.blocks.slice();
1080
+ next[at] = update(next[at]);
1081
+ this.#state = { ...this.#state, blocks: next };
1082
+ }
819
1083
  prompt(request) {
820
1084
  // Background approvals take the terminal from a user-opened file reader.
821
1085
  if (this.#fileReviewAbort !== undefined && request.signal !== this.#fileReviewAbort.signal)
@@ -933,9 +1197,9 @@ export class LocalTui {
933
1197
  this.#fileReviewAbort?.abort();
934
1198
  this.#trajectory = null;
935
1199
  const state = replayEvents(events, presentations);
936
- // Notices and tool catalogs do not turn a blank session into a document
937
- // that /new needs to separate. Refreshes are the same document.
938
- const boundary = reason === 'open' || (reason === 'new' && this.#state.blocks.some(block => block.kind !== 'notice' && block.kind !== 'toolCatalog'));
1200
+ // A notice does not turn a blank session into a document that /new needs
1201
+ // to separate. Refreshes are the same document.
1202
+ const boundary = reason === 'open' || (reason === 'new' && this.#state.blocks.some(block => block.kind !== 'notice'));
939
1203
  const blocks = boundary ? [transcriptSeam('session-opened'), ...state.blocks] : state.blocks;
940
1204
  this.#state = { ...state, status, compactCommandId: undefined, blocks };
941
1205
  this.#plain.resetPrinted();
@@ -955,7 +1219,6 @@ export class LocalTui {
955
1219
  this.#herdr.setSession(info.id);
956
1220
  const title = info.title?.trim();
957
1221
  this.#sessionTitle = title === undefined || title === '' ? undefined : title;
958
- this.#recentSessions = info.recent.map((session) => ({ ...session }));
959
1222
  this.#sessionStats = info.stats === undefined ? undefined : { ...info.stats };
960
1223
  this.#sessionControls = info.controls === undefined
961
1224
  ? undefined
@@ -1003,11 +1266,11 @@ export class LocalTui {
1003
1266
  this.#term.output.write(sequence);
1004
1267
  }
1005
1268
  /**
1006
- * Re-derive the 24-bit switch from the active color preference. Every path
1269
+ * Re-derive the color depth from the active color preference. Every path
1007
1270
  * that changes `#colors` calls this so `/settings` takes effect immediately.
1008
1271
  */
1009
- #syncTrueColor() {
1010
- this.#trueColor = this.#colors && detectTrueColor();
1272
+ #syncColorDepth() {
1273
+ this.#colorDepth = this.#colors ? detectColorDepth() : 'ansi16';
1011
1274
  }
1012
1275
  /** Apply prefs loaded from this entry's config (does not persist). */
1013
1276
  applyStoredPrefs(prefs) {
@@ -1029,8 +1292,8 @@ export class LocalTui {
1029
1292
  motion: this.#motion,
1030
1293
  mathMode: this.#mathMode,
1031
1294
  mermaidMode: this.#mermaidMode,
1295
+ hideThinking: this.#hideThinking,
1032
1296
  editor: this.#externalEditor,
1033
- terminalProgress: this.#terminalProgress,
1034
1297
  terminalTitle: this.#terminalTitle,
1035
1298
  terminalState: this.#terminalState,
1036
1299
  copyOnSelect: this.#copyOnSelect,
@@ -1039,17 +1302,10 @@ export class LocalTui {
1039
1302
  checkUpdates: this.#checkUpdates,
1040
1303
  startupChangelog: this.#startupChangelog,
1041
1304
  notifications: this.#notificationPolicy,
1042
- notificationThreshold: this.#notificationThreshold,
1043
- notificationFocus: this.#notificationFocus,
1044
- statusBar: {
1045
- ...this.#statusBar,
1046
- groups: [...this.#statusBar.groups],
1047
- ...(this.#statusBar.order === undefined ? {} : { order: [...this.#statusBar.order] }),
1048
- ...(this.#statusBar.meta === undefined ? {} : { meta: [...this.#statusBar.meta] }),
1049
- ...(this.#statusBar.metaOrder === undefined ? {} : { metaOrder: [...this.#statusBar.metaOrder] }),
1050
- ...(this.#statusBar.colors === undefined ? {} : { colors: { ...this.#statusBar.colors } }),
1051
- ...(this.#statusBar.sides === undefined ? {} : { sides: { ...this.#statusBar.sides } }),
1052
- },
1305
+ // The whole document, not the density alone: a projection that dropped the
1306
+ // narrowing made every later re-read of the preferences show the parts the
1307
+ // reader had just hidden.
1308
+ statusBar: statusBarDocument(this.#statusBar),
1053
1309
  };
1054
1310
  }
1055
1311
  /** Called after a live `/settings` change. */
@@ -1253,6 +1509,21 @@ export class LocalTui {
1253
1509
  return () => { if (this.#steerHandler === handler)
1254
1510
  this.#steerHandler = undefined; };
1255
1511
  }
1512
+ /**
1513
+ * Last-resort restore for a process that exits without disposing: leave the
1514
+ * alternate screen, give every mode back and show the cursor. Writes to a TTY
1515
+ * are synchronous, so this completes before the process ends.
1516
+ */
1517
+ #restoreTerminalOnExit() {
1518
+ if (this.#disposed || !this.#tty)
1519
+ return;
1520
+ try {
1521
+ this.#renderer.finish();
1522
+ }
1523
+ catch { /* best effort while exiting */ }
1524
+ this.#session.release();
1525
+ this.#term.output.write('\x1b[?25h');
1526
+ }
1256
1527
  dispose() {
1257
1528
  if (this.#disposed)
1258
1529
  return this.#disposeTask ?? this.#herdr.release();
@@ -1262,6 +1533,7 @@ export class LocalTui {
1262
1533
  this.#steerHandler = undefined;
1263
1534
  this.#imagePreviewAbort?.abort();
1264
1535
  this.#fileReviewAbort?.abort();
1536
+ this.#asideAbort?.abort();
1265
1537
  for (const directory of this.#imageTemporary) {
1266
1538
  try {
1267
1539
  rmSync(directory, { recursive: true, force: true });
@@ -1291,7 +1563,6 @@ export class LocalTui {
1291
1563
  this.#tick = null;
1292
1564
  }
1293
1565
  this.#stopRevealTick();
1294
- this.#setTerminalProgress(false);
1295
1566
  if (this.#loopTick !== null) {
1296
1567
  clearInterval(this.#loopTick);
1297
1568
  this.#loopTick = null;
@@ -1314,7 +1585,10 @@ export class LocalTui {
1314
1585
  if (this.#writtenProgramState !== undefined)
1315
1586
  this.#term.output.write(programStatusSequence('clear'));
1316
1587
  this.#writtenProgramState = undefined;
1317
- this.#term.output.write('\x1b[?2004l\x1b[?1004l\x1b[?25h\r\n');
1588
+ this.#offExit?.();
1589
+ this.#offExit = undefined;
1590
+ this.#session.dispose();
1591
+ this.#term.output.write('\x1b[?25h\r\n');
1318
1592
  if (this.#resumeHintRequested && this.#sessionId !== undefined) {
1319
1593
  this.#term.output.write(`\r\nResume this session with ${APP_NAME} --resume ${this.#sessionId}\r\n`);
1320
1594
  }
@@ -1324,6 +1598,10 @@ export class LocalTui {
1324
1598
  }
1325
1599
  if (this.#escapeTimer !== null)
1326
1600
  clearTimeout(this.#escapeTimer);
1601
+ if (this.#transientTimer !== null) {
1602
+ clearTimeout(this.#transientTimer);
1603
+ this.#transientTimer = null;
1604
+ }
1327
1605
  if (this.#autocompleteTimer !== null)
1328
1606
  clearTimeout(this.#autocompleteTimer);
1329
1607
  this.#autocompleteAbort?.abort();
@@ -1357,11 +1635,30 @@ export class LocalTui {
1357
1635
  return true;
1358
1636
  return this.#subagents?.agents.some(agent => agent.phase === 'running' || agent.phase === 'starting') === true;
1359
1637
  }
1638
+ /** Countdown shown on the working row while a retry or a compaction is pending. */
1639
+ #workingLabel() {
1640
+ if (this.#retryDeadline !== undefined) {
1641
+ return `Retrying in ${Math.max(0, Math.ceil((this.#retryDeadline - Date.now()) / 1000))}s`;
1642
+ }
1643
+ if (this.#state.status === 'compacting' && this.#compactionStartedAt !== undefined) {
1644
+ return `Compacting ${Math.max(0, Math.floor((Date.now() - this.#compactionStartedAt) / 1000))}s`;
1645
+ }
1646
+ return undefined;
1647
+ }
1648
+ /** The newest image the transcript carries, whichever side produced it. */
1649
+ #latestImageRef() {
1650
+ for (let index = this.#state.blocks.length - 1; index >= 0; index -= 1) {
1651
+ const block = this.#state.blocks[index];
1652
+ const image = block.kind === 'tool' || block.kind === 'user' ? block.image : undefined;
1653
+ if (image !== undefined)
1654
+ return image;
1655
+ }
1656
+ return undefined;
1657
+ }
1360
1658
  #syncTick() {
1361
1659
  if (!this.#tty)
1362
1660
  return;
1363
1661
  const busy = this.#busy();
1364
- this.#setTerminalProgress(this.#terminalProgress && busy);
1365
1662
  if (busy && this.#motion !== 'off') {
1366
1663
  if (this.#tick === null) {
1367
1664
  this.#tick = setInterval(() => {
@@ -1418,31 +1715,6 @@ export class LocalTui {
1418
1715
  clearInterval(this.#revealTick);
1419
1716
  this.#revealTick = null;
1420
1717
  }
1421
- #setTerminalProgress(active) {
1422
- if (!this.#tty)
1423
- return;
1424
- if (active) {
1425
- if (this.#terminalProgressActive)
1426
- return;
1427
- this.#terminalProgressActive = true;
1428
- this.#term.output.write(terminalProgressSequence(true));
1429
- this.#terminalProgressTick = setInterval(() => {
1430
- if (!this.#disposed && this.#terminalProgressActive) {
1431
- this.#term.output.write(terminalProgressSequence(true));
1432
- }
1433
- }, TERMINAL_PROGRESS_KEEPALIVE_MS);
1434
- this.#terminalProgressTick.unref?.();
1435
- return;
1436
- }
1437
- if (this.#terminalProgressTick !== null) {
1438
- clearInterval(this.#terminalProgressTick);
1439
- this.#terminalProgressTick = null;
1440
- }
1441
- if (!this.#terminalProgressActive)
1442
- return;
1443
- this.#terminalProgressActive = false;
1444
- this.#term.output.write(terminalProgressSequence(false));
1445
- }
1446
1718
  #syncLoopTick() {
1447
1719
  if (!this.#tty)
1448
1720
  return;
@@ -1561,10 +1833,14 @@ export class LocalTui {
1561
1833
  }
1562
1834
  if (this.#deferInitialRender)
1563
1835
  return;
1836
+ // Rows committed to scrollback are immutable; the first real paint waits for the probe so it already uses the reported colors.
1837
+ if (this.#probeGate)
1838
+ return;
1564
1839
  const width = this.#term.width();
1565
1840
  const renderState = this.#reveal === undefined
1566
1841
  ? this.#state
1567
1842
  : revealStreamingAssistant(this.#state, this.#reveal.revealed);
1843
+ const workingLabel = this.#workingLabel();
1568
1844
  const frame = this.#tty
1569
1845
  ? renderView(renderState, {
1570
1846
  width,
@@ -1572,6 +1848,7 @@ export class LocalTui {
1572
1848
  imageCellSize: this.#imageCellSize,
1573
1849
  mathMode: this.#mathMode,
1574
1850
  mermaidMode: this.#mermaidMode,
1851
+ hideThinking: this.#hideThinking,
1575
1852
  height: this.#term.height(),
1576
1853
  model: this.#model,
1577
1854
  ...(this.#reasoningEffort === undefined ? {} : { reasoningEffort: this.#reasoningEffort }),
@@ -1587,47 +1864,47 @@ export class LocalTui {
1587
1864
  ...(this.#sessionTitle === undefined ? {} : { sessionTitle: this.#sessionTitle }),
1588
1865
  version: APP_VERSION,
1589
1866
  appName: APP_NAME,
1867
+ displayName: APP_DISPLAY_NAME,
1590
1868
  spinnerFrame: this.#spinner,
1591
1869
  motion: this.#motion,
1592
- trueColor: this.#trueColor,
1870
+ colorDepth: this.#colorDepth,
1593
1871
  themeName: this.#themeName,
1872
+ terminal: this.#terminalColors,
1873
+ ...(workingLabel === undefined ? {} : { workingLabel }),
1874
+ ...(this.#transientStatus === undefined ? {} : { transientStatus: this.#transientStatus }),
1594
1875
  scrollStart: this.#follow ? Number.POSITIVE_INFINITY : this.#scrollStart,
1595
1876
  ...(this.#focusBlock === undefined ? {} : { focusBlock: this.#focusBlock, focusBlockEdge: this.#focusBlockEdge ?? 'start' }),
1596
1877
  ...(this.#transcriptSearch === null ? {} : {
1597
1878
  transcriptSearch: {
1598
1879
  query: this.#transcriptSearch.query,
1599
- matches: searchBlockIndexes(this.#state.blocks.map(blockSearchText), this.#transcriptSearch.query),
1600
1880
  focus: this.#transcriptSearch.focus,
1601
1881
  editing: this.#transcriptSearch.editing,
1602
1882
  },
1603
1883
  }),
1604
1884
  toolsExpanded: this.#toolsExpanded,
1885
+ expandedOutputs: this.#expandedOutputs,
1605
1886
  expandedTools: this.#detailedToolIds(),
1606
1887
  toolDetailsKey: keysForAction(this.#keybindings, 'toggle-tool-details'),
1607
1888
  turnDetailsKey: keysForAction(this.#keybindings, 'toggle-tools'),
1608
1889
  ...(this.#steerHandler === undefined ? {} : { steerKey: keysForAction(this.#keybindings, 'steer-turn') }),
1609
1890
  openedGroups: this.#openedGroups,
1610
1891
  commands: this.#commands(),
1611
- recentSessions: this.#recentSessions,
1612
- welcomeTips: this.#welcomeTips,
1613
1892
  modelReady: this.#modelReady,
1614
1893
  ...(this.#sessionStats === undefined ? {} : { sessionStats: this.#sessionStats }),
1615
1894
  ...(this.#sessionControls === undefined ? {} : { sessionControls: this.#sessionControls }),
1616
1895
  ...(this.#loopStatus === undefined ? {} : { loopStatus: this.#loopStatus }),
1617
1896
  ...(this.#subagents === undefined ? {} : { subagents: this.#subagents }),
1618
- subagentLauncherFocused: this.#subagentLauncherFocused,
1897
+ ...(this.#subagentSelection === undefined ? {} : { subagentSelection: this.#subagentSelection }),
1619
1898
  ...(this.#inspected === undefined ? {} : { inspected: this.#inspected }),
1620
1899
  ...(this.#trajectory === null ? {} : { trajectory: this.#trajectory }),
1621
- ...(this.#agentHub === null ? {} : { agentHub: this.#agentHub }),
1900
+ ...(this.#aside === undefined ? {} : { aside: this.#aside }),
1622
1901
  statusBar: this.#statusBar,
1623
1902
  ...(this.#prompt === null ? {} : { promptSelector: this.#prompt }),
1624
1903
  ...(this.#settings !== null
1625
1904
  ? { settings: this.#settings }
1626
- : this.#copySelector !== null
1627
- ? { copySelector: this.#copySelector }
1628
- : this.#search !== null
1629
- ? { historySearch: this.#search }
1630
- : this.#ac !== null ? { autocomplete: this.#ac } : {}),
1905
+ : this.#search !== null
1906
+ ? { historySearch: this.#search }
1907
+ : this.#ac !== null ? { autocomplete: this.#ac } : {}),
1631
1908
  })
1632
1909
  : { lines: [] };
1633
1910
  this.#focusBlock = undefined;
@@ -1731,7 +2008,27 @@ export class LocalTui {
1731
2008
  if (!this.#tty || enabled === this.#mouseTracking)
1732
2009
  return;
1733
2010
  this.#mouseTracking = enabled;
1734
- this.#term.output.write(enabled ? '\x1b[?1000h\x1b[?1002h\x1b[?1006h' : '\x1b[?1006l\x1b[?1002l\x1b[?1000l');
2011
+ this.#session.setMode('mouse', MOUSE_TRACKING, enabled);
2012
+ }
2013
+ /** Give every terminal mode back before the terminal is lent out (Ctrl+Z, external editor). */
2014
+ #handOffTerminal() {
2015
+ this.#setMouseTracking(false);
2016
+ this.#session.handOff();
2017
+ }
2018
+ /** Run `run` with the terminal handed off; take it back and repaint afterwards. */
2019
+ #handTerminal(run) {
2020
+ this.#handOffTerminal();
2021
+ this.#term.input.setRawMode?.(false);
2022
+ try {
2023
+ return run();
2024
+ }
2025
+ finally {
2026
+ if (!this.#disposed) {
2027
+ this.#term.input.setRawMode?.(true);
2028
+ this.#session.takeBack();
2029
+ this.#renderer.reset();
2030
+ }
2031
+ }
1735
2032
  }
1736
2033
  /**
1737
2034
  * After a Ctrl+O toggle: read what is open in a browsing frame at `target`,
@@ -1783,8 +2080,8 @@ export class LocalTui {
1783
2080
  }
1784
2081
  #routeInputBatch(events) {
1785
2082
  if (this.#pasteProtection && this.#state.status !== 'compacting' && !this.#paste && this.#pasteInFlight === 0
1786
- && this.#prompt === null && this.#settings === null && this.#copySelector === null
1787
- && this.#search === null && this.#trajectory === null && this.#agentHub === null && this.#transcriptSearch === null
2083
+ && this.#prompt === null && this.#settings === null
2084
+ && this.#search === null && this.#trajectory === null && this.#transcriptSearch === null
1788
2085
  && events.every(event => event.type === 'text' || (event.type === 'key' && ['enter', 'ctrl+j', 'tab'].includes(event.id)))) {
1789
2086
  if (this.#pasteBurstTimer !== undefined)
1790
2087
  clearTimeout(this.#pasteBurstTimer);
@@ -1807,8 +2104,8 @@ export class LocalTui {
1807
2104
  this.#dispatch(event);
1808
2105
  return;
1809
2106
  }
1810
- const composer = this.#state.status !== 'compacting' && this.#prompt === null && this.#settings === null && this.#copySelector === null
1811
- && this.#search === null && this.#trajectory === null && this.#agentHub === null && this.#transcriptSearch === null;
2107
+ const composer = this.#state.status !== 'compacting' && this.#prompt === null && this.#settings === null
2108
+ && this.#search === null && this.#trajectory === null && this.#transcriptSearch === null;
1812
2109
  if (this.#paste || this.#pasteInFlight > 0 || !this.#pasteProtection || !composer
1813
2110
  || event.type === 'paste-start' || event.type === 'paste-end') {
1814
2111
  this.#flushPasteBurst(true);
@@ -1861,7 +2158,7 @@ export class LocalTui {
1861
2158
  async #acceptPastedText(text) {
1862
2159
  if (this.#prompt !== null) {
1863
2160
  const prompt = this.#prompt;
1864
- if (prompt.request.documentSource !== undefined && prompt.documentInput !== undefined) {
2161
+ if (prompt.documentInput !== undefined) {
1865
2162
  this.#handleDocumentReader({ type: 'text', value: text }, prompt);
1866
2163
  return;
1867
2164
  }
@@ -1874,7 +2171,7 @@ export class LocalTui {
1874
2171
  this.#render();
1875
2172
  return;
1876
2173
  }
1877
- if (this.#settings !== null || this.#copySelector !== null)
2174
+ if (this.#settings !== null)
1878
2175
  return;
1879
2176
  if (this.#search !== null) {
1880
2177
  this.#applySearch({ type: 'text', value: text });
@@ -1914,7 +2211,7 @@ export class LocalTui {
1914
2211
  this.#render();
1915
2212
  }
1916
2213
  async #pasteClipboard() {
1917
- if (this.#search === null && this.#settings === null && this.#copySelector === null) {
2214
+ if (this.#search === null && this.#settings === null) {
1918
2215
  const image = await this.#readClipboardImage();
1919
2216
  if (image !== null) {
1920
2217
  if (await this.#images.admit(image)) {
@@ -2058,6 +2355,10 @@ export class LocalTui {
2058
2355
  this.#fileReviewAbort = undefined; });
2059
2356
  }
2060
2357
  #dispatch(event) {
2358
+ // Any input makes the last confirmation stale; a note that survives typing
2359
+ // starts competing with the command the reader is writing.
2360
+ if (event.type === 'key' || event.type === 'text')
2361
+ this.#clearTransientStatus();
2061
2362
  if (event.type === 'cell-size') {
2062
2363
  this.#imageCellSize = { width: event.width, height: event.height };
2063
2364
  if (this.#prompt?.request.documentImage !== undefined)
@@ -2069,9 +2370,11 @@ export class LocalTui {
2069
2370
  this.#syncWindowTitle();
2070
2371
  return;
2071
2372
  }
2373
+ if (this.#session.handle(event))
2374
+ return;
2072
2375
  if (event.type === 'focus') {
2073
2376
  this.#terminalFocused = event.focused;
2074
- if (event.focused && this.#notificationFocus === 'unfocused')
2377
+ if (event.focused && this.#notificationPolicy === 'unfocused')
2075
2378
  this.#notificationQueue.clear();
2076
2379
  return;
2077
2380
  }
@@ -2095,7 +2398,10 @@ export class LocalTui {
2095
2398
  if (event.type === 'wheel') {
2096
2399
  this.#jumpPress = undefined;
2097
2400
  if (this.#mouseTracking && !this.#paste && this.#pasteInFlight === 0) {
2098
- this.#scrollBy(event.direction === 'up' ? -3 : 3);
2401
+ const step = wheelStep(this.#wheelGesture, Date.now(), event.direction === 'up' ? -1 : 1, !this.#wheelAccelerates);
2402
+ this.#wheelGesture = step.gesture;
2403
+ if (step.lines !== 0)
2404
+ this.#scrollBy(step.lines);
2099
2405
  }
2100
2406
  return;
2101
2407
  }
@@ -2161,7 +2467,7 @@ export class LocalTui {
2161
2467
  if (this.#handlePrompt(event))
2162
2468
  return;
2163
2469
  if (this.#trajectory !== null) {
2164
- const { pageSize } = trajectoryListMetrics(this.#trajectory, this.#term.height());
2470
+ const { pageSize } = trajectoryListMetrics(this.#trajectory, this.#term.height(), this.#term.width());
2165
2471
  const { pageLines } = trajectoryDetailMetrics(this.#trajectory, this.#term.height());
2166
2472
  const command = applyTrajectoryEvent(this.#trajectory, event, { pageSize, detailPageLines: pageLines });
2167
2473
  if ('close' in command)
@@ -2171,25 +2477,12 @@ export class LocalTui {
2171
2477
  this.#render();
2172
2478
  return;
2173
2479
  }
2174
- if (this.#agentHub !== null) {
2175
- const command = applyAgentHubEvent(this.#agentHub, event);
2176
- if ('close' in command)
2177
- this.#agentHub = null;
2178
- else if ('open' in command) {
2179
- this.#agentHub = null;
2180
- this.#openInspect(command.open);
2181
- }
2182
- else
2183
- this.#agentHub = command.state;
2184
- this.#render();
2185
- return;
2186
- }
2187
2480
  if (this.#transcriptSearch !== null) {
2188
2481
  this.#applyTranscriptSearch(event);
2189
2482
  return;
2190
2483
  }
2191
2484
  if (event.type === 'key' && event.id === 'end' && this.#jumpToLatest !== undefined
2192
- && this.#settings === null && this.#copySelector === null && this.#search === null) {
2485
+ && this.#settings === null && this.#search === null) {
2193
2486
  this.#followTail();
2194
2487
  this.#render();
2195
2488
  return;
@@ -2200,53 +2493,31 @@ export class LocalTui {
2200
2493
  return;
2201
2494
  }
2202
2495
  if (this.#inspected !== undefined && this.#inspected.writable !== true && event.type === 'text'
2203
- && this.#prompt === null && this.#settings === null && this.#copySelector === null && this.#search === null) {
2204
- return;
2205
- }
2206
- if (event.type === 'key' && event.id === 'ctrl+c') {
2207
- if (this.#prompt !== null) {
2208
- this.#finishPrompt(null);
2209
- this.#editor.setText('');
2210
- this.#render();
2211
- return;
2212
- }
2213
- if (this.#settings !== null) {
2214
- this.#settings = null;
2215
- this.#render();
2216
- return;
2217
- }
2218
- if (this.#copySelector !== null) {
2219
- this.#copySelector = null;
2220
- this.#render();
2221
- return;
2222
- }
2223
- if (this.#search !== null) {
2224
- this.#search = null;
2225
- this.#render();
2226
- return;
2227
- }
2228
- const now = Date.now();
2229
- if (now - this.#lastSigintTime < DOUBLE_CTRL_C_MS) {
2230
- this.#lastSigintTime = 0;
2231
- this.#quit();
2232
- return;
2233
- }
2234
- this.#lastSigintTime = now;
2235
- if (this.#state.status !== 'idle') {
2236
- for (const listener of this.#interrupts)
2237
- listener();
2238
- }
2239
- else {
2240
- this.#clearComposerWithUndo();
2241
- }
2496
+ && this.#prompt === null && this.#settings === null && this.#search === null) {
2242
2497
  return;
2243
2498
  }
2244
2499
  if (this.#settings !== null) {
2245
2500
  this.#applySettings(event);
2246
2501
  return;
2247
2502
  }
2248
- if (this.#copySelector !== null) {
2249
- this.#applyCopySelector(event);
2503
+ /**
2504
+ * The side pane is a companion, not a mode: it answers where the reader is
2505
+ * already working, so it must not take keys the composer is using. It reads
2506
+ * navigation only while the composer is empty and nothing else is offering a
2507
+ * choice — a draft, an autocomplete list, or historical recall all keep their
2508
+ * arrows, and Escape keeps closing whatever is actually on top.
2509
+ */
2510
+ if (this.#aside !== undefined && this.#asideOwnsKeys() && event.type === 'key'
2511
+ && (event.id === 'up' || event.id === 'down' || event.id === 'pageUp' || event.id === 'pageDown')) {
2512
+ const step = event.id === 'pageUp' || event.id === 'pageDown' ? 6 : 1;
2513
+ const delta = event.id === 'up' || event.id === 'pageUp' ? -step : step;
2514
+ this.#aside = { ...this.#aside, scroll: Math.max(0, this.#aside.scroll + delta) };
2515
+ this.#render();
2516
+ return;
2517
+ }
2518
+ if (this.#aside !== undefined && event.type === 'key' && event.id === 'escape'
2519
+ && this.#editor.text === '' && this.#ac === null) {
2520
+ this.#closeAside();
2250
2521
  return;
2251
2522
  }
2252
2523
  if (this.#search !== null) {
@@ -2260,41 +2531,17 @@ export class LocalTui {
2260
2531
  }
2261
2532
  if (this.#handleSubagentLauncher(event))
2262
2533
  return;
2263
- if (event.type === 'key' && event.id === 'escape') {
2264
- if (this.#inspected !== undefined) {
2265
- if (this.#inspected.writable === true && this.#hasComposerContent()) {
2266
- this.#clearComposerWithUndo();
2267
- return;
2268
- }
2269
- this.#closeInspect();
2270
- return;
2271
- }
2272
- if (this.#state.status !== 'idle' || this.#pending === null
2273
- || this.#hasComposerContent()) {
2274
- this.#lastEscapeTime = 0;
2275
- }
2276
- else {
2277
- const now = Date.now();
2278
- if (now - this.#lastEscapeTime < DOUBLE_ESCAPE_MS) {
2279
- this.#lastEscapeTime = 0;
2280
- for (const listener of this.#rewinds)
2281
- listener();
2282
- }
2283
- else {
2284
- this.#lastEscapeTime = now;
2285
- }
2286
- return;
2287
- }
2288
- }
2534
+ // Escape is the one key that gives back exactly one layer, so it is resolved
2535
+ // here — after the overlays and the autocomplete have had their turn — and
2536
+ // not with the other actions above.
2537
+ if (event.type === 'key' && this.#boundAction(event.id) === 'interrupt' && this.#runInterrupt())
2538
+ return;
2289
2539
  if (event.type === 'key' && (event.id === 'backspace' || event.id === 'delete')
2290
2540
  && this.#images.removeAtCursor(event.id)) {
2291
2541
  this.#refreshAutocomplete();
2292
2542
  this.#render();
2293
2543
  return;
2294
2544
  }
2295
- if (event.type === 'key' && event.id === 'alt+up' && this.#restoreLatestQueuedSubmission(true)) {
2296
- return;
2297
- }
2298
2545
  if (event.type === 'key' && (event.id === 'ctrl+-' || event.id === 'ctrl+_')
2299
2546
  && this.#clearedDraft !== undefined && this.#clearedDraft.revision === this.#editor.revision
2300
2547
  && !this.#hasComposerContent()) {
@@ -2308,6 +2555,131 @@ export class LocalTui {
2308
2555
  }
2309
2556
  this.#applyCommand(this.#editor.handle(event));
2310
2557
  }
2558
+ /**
2559
+ * Resolve `interrupt` against whatever currently owns the screen.
2560
+ *
2561
+ * One action, one meaning — cancel what is happening — but the thing that is
2562
+ * happening depends on how deep the reader is. The order runs from the most
2563
+ * transient surface to the least, so Escape always gives back exactly one
2564
+ * layer instead of dropping the reader somewhere unrelated.
2565
+ */
2566
+ #runInterrupt() {
2567
+ if (this.#prompt !== null) {
2568
+ if (this.#prompt.request.presentation === 'progress' || this.#prompt.request.interrupt === undefined) {
2569
+ this.#finishPrompt(null);
2570
+ return true;
2571
+ }
2572
+ const handled = this.#prompt.request.interrupt();
2573
+ this.#finishPrompt(null);
2574
+ if (handled !== true && this.#state.status !== 'idle')
2575
+ for (const listener of this.#interrupts)
2576
+ listener();
2577
+ return true;
2578
+ }
2579
+ // Escaping a child transcript returns to the parent, and a writable child
2580
+ // with a draft clears it first — the same order the reader expects from
2581
+ // any other depth.
2582
+ if (this.#inspected !== undefined) {
2583
+ if (this.#inspected.writable === true && this.#hasComposerContent()) {
2584
+ this.#clearComposerWithUndo();
2585
+ return true;
2586
+ }
2587
+ this.#closeInspect();
2588
+ return true;
2589
+ }
2590
+ if (this.#state.status !== 'idle') {
2591
+ // Aborting a turn would strand whatever the user queued behind it. Pi
2592
+ // hands those drafts back first, so nothing typed during the turn is lost
2593
+ // to the abort that ends it.
2594
+ this.#restoreQueuedBeforeAbort();
2595
+ for (const listener of this.#interrupts)
2596
+ listener();
2597
+ return true;
2598
+ }
2599
+ if (!this.#hasComposerContent()) {
2600
+ // Nothing to cancel and nothing typed: the second Escape opens the session
2601
+ // tree, which is where a reader goes when they want to leave this point.
2602
+ const now = Date.now();
2603
+ if (now - this.#lastEscapeTime < DOUBLE_ESCAPE_MS) {
2604
+ this.#lastEscapeTime = 0;
2605
+ for (const listener of this.#rewinds)
2606
+ listener();
2607
+ }
2608
+ else {
2609
+ this.#lastEscapeTime = now;
2610
+ }
2611
+ return true;
2612
+ }
2613
+ // Something is typed: Escape is not a no-op, but it also has nothing to
2614
+ // cancel, so the editor keeps the keystroke.
2615
+ return false;
2616
+ }
2617
+ /**
2618
+ * Empty the composer, or exit on a second press.
2619
+ *
2620
+ * Ctrl+C is a composer gesture everywhere else on a terminal; keeping
2621
+ * interrupt on Escape leaves this to do exactly one job.
2622
+ */
2623
+ #runClearComposer() {
2624
+ if (this.#prompt !== null) {
2625
+ this.#finishPrompt(null);
2626
+ this.#editor.setText('');
2627
+ this.#render();
2628
+ return true;
2629
+ }
2630
+ // A running Shell line owns Ctrl+C before the composer does: the reader is
2631
+ // watching a command, and the key they press to stop it is the same one.
2632
+ if (this.#shellAbort !== undefined && !this.#hasComposerContent()) {
2633
+ this.#shellAbort();
2634
+ return true;
2635
+ }
2636
+ if (this.#settings !== null) {
2637
+ this.#settings = null;
2638
+ this.#render();
2639
+ return true;
2640
+ }
2641
+ if (this.#search !== null) {
2642
+ this.#search = null;
2643
+ this.#render();
2644
+ return true;
2645
+ }
2646
+ if (this.#transcriptSearch !== null) {
2647
+ this.#transcriptSearch = null;
2648
+ this.#render();
2649
+ return true;
2650
+ }
2651
+ const now = Date.now();
2652
+ if (now - this.#lastSigintTime < DOUBLE_CTRL_C_MS) {
2653
+ this.#lastSigintTime = 0;
2654
+ this.#quit();
2655
+ return true;
2656
+ }
2657
+ this.#lastSigintTime = now;
2658
+ // A running turn keeps Ctrl+C as the familiar abort while the composer is
2659
+ // empty; Escape already covers it, and refusing the reflex would be worse.
2660
+ if (this.#state.status !== 'idle' && !this.#hasComposerContent()) {
2661
+ this.#restoreQueuedBeforeAbort();
2662
+ for (const listener of this.#interrupts)
2663
+ listener();
2664
+ return true;
2665
+ }
2666
+ this.#clearComposerWithUndo();
2667
+ return true;
2668
+ }
2669
+ /**
2670
+ * Hand durable follow-ups back to the composer before a turn is abandoned.
2671
+ *
2672
+ * The queued messages would otherwise be delivered to a turn that will never
2673
+ * produce the step they were aimed at, which silently loses them.
2674
+ */
2675
+ #restoreQueuedBeforeAbort() {
2676
+ if (!this.#state.nextTurnInbox.some(message => message.source.kind === 'user'))
2677
+ return;
2678
+ if (this.#hasComposerContent())
2679
+ return;
2680
+ for (const listener of this.#queueEdits)
2681
+ listener();
2682
+ }
2311
2683
  #handlePrompt(event) {
2312
2684
  let prompt = this.#prompt;
2313
2685
  if (prompt === null)
@@ -2384,8 +2756,8 @@ export class LocalTui {
2384
2756
  const count = filtered.length;
2385
2757
  const keyAction = prompt.request.actions?.find(item => item.key.toLowerCase() === event.id.toLowerCase());
2386
2758
  if (keyAction !== undefined && (keyAction.scope === 'list'
2387
- || prompt.request.presentation === 'fullscreen-tree'
2388
- || prompt.request.presentation === 'fullscreen-list')) {
2759
+ || prompt.request.presentation === 'tree'
2760
+ || prompt.request.presentation === 'card')) {
2389
2761
  if (!disarmed) {
2390
2762
  const selected = filtered[prompt.selected];
2391
2763
  if (keyAction.scope === 'list' || selected !== undefined) {
@@ -2397,10 +2769,24 @@ export class LocalTui {
2397
2769
  return true;
2398
2770
  }
2399
2771
  if (event.id === 'escape' || event.id === 'ctrl+c') {
2400
- if (event.id === 'escape' && prompt.request.presentation === 'fullscreen-tree' && this.#editor.text !== '') {
2401
- const selected = filtered[prompt.selected]?.value;
2772
+ /**
2773
+ * Escape gives back one layer: an active filter clears before the card
2774
+ * closes.
2775
+ *
2776
+ * Only the tree used to do this, so a filtered `/model` or `/copy` closed
2777
+ * outright and a reader who wanted their list back had to reopen it.
2778
+ */
2779
+ if (event.id === 'escape' && prompt.request.filterable === true && this.#editor.text !== '') {
2780
+ const selected = filtered[prompt.selected]?.value ?? filtered[prompt.selected]?.label;
2402
2781
  this.#editor.setText('');
2403
- this.#prompt = { ...prompt, collapsed: new Set(), selected: Math.max(0, filteredPromptOptions(prompt.request, '').findIndex(option => option.value === selected)), previewScroll: 0 };
2782
+ const restored = filteredPromptOptions(prompt.request, '', prompt.collapsed);
2783
+ const at = restored.findIndex(option => (option.value ?? option.label) === selected);
2784
+ this.#prompt = {
2785
+ ...prompt,
2786
+ ...(prompt.request.presentation === 'tree' ? { collapsed: new Set() } : {}),
2787
+ selected: Math.max(0, at),
2788
+ previewScroll: 0,
2789
+ };
2404
2790
  this.#render();
2405
2791
  return true;
2406
2792
  }
@@ -2408,12 +2794,12 @@ export class LocalTui {
2408
2794
  this.#render();
2409
2795
  return true;
2410
2796
  }
2411
- if (prompt.request.presentation === 'fullscreen-tree' && (event.id === 'left' || event.id === 'right')) {
2797
+ if (prompt.request.presentation === 'tree' && (event.id === 'left' || event.id === 'right')) {
2412
2798
  this.#prompt = movePromptTree(prompt, event.id, this.#editor.text);
2413
2799
  this.#render();
2414
2800
  return true;
2415
2801
  }
2416
- if (prompt.request.presentation === 'fullscreen-tree' && (event.id === 'ctrl+up' || event.id === 'ctrl+down')) {
2802
+ if (prompt.request.presentation === 'tree' && (event.id === 'ctrl+up' || event.id === 'ctrl+down')) {
2417
2803
  const start = this.#promptDocument?.start ?? prompt.previewScroll ?? 0;
2418
2804
  this.#prompt = { ...prompt, previewScroll: Math.max(0, Math.min(start + (event.id === 'ctrl+up' ? -1 : 1), this.#promptDocument?.maxStart ?? 0)) };
2419
2805
  this.#render();
@@ -2431,29 +2817,30 @@ export class LocalTui {
2431
2817
  }
2432
2818
  return true;
2433
2819
  }
2434
- let next;
2435
- const page = prompt.request.presentation === 'fullscreen-tree'
2820
+ // Movement comes from the shared reading, so this selector cannot drift from
2821
+ // the other lists about what `tab` or `pageUp` means. `enter` stays below
2822
+ // because what it submits depends on the editor and on multi-select.
2823
+ const page = prompt.request.presentation === 'tree'
2436
2824
  ? promptTreePageSize(prompt.request, this.#term.width(), this.#term.height()) : 10;
2437
- if (event.id === 'up' || event.id === 'shift+tab')
2438
- next = prompt.selected - 1;
2439
- else if (event.id === 'down' || event.id === 'tab')
2440
- next = prompt.selected + 1;
2441
- else if (event.id === 'pageUp')
2442
- next = prompt.request.presentation === 'fullscreen-tree' ? Math.max(0, prompt.selected - page) : prompt.selected - page;
2443
- else if (event.id === 'pageDown')
2444
- next = prompt.request.presentation === 'fullscreen-tree' ? Math.min(count - 1, prompt.selected + page) : prompt.selected + page;
2445
- else if (event.id === 'home')
2446
- next = 0;
2447
- else if (event.id === 'end')
2448
- next = count - 1;
2449
- if (next !== undefined) {
2450
- this.#prompt = movePromptSelection(prompt, next, count);
2825
+ const navigation = listNavigation(event);
2826
+ if (navigation.kind === 'move' || navigation.kind === 'page') {
2827
+ // The tree clamps: its rows are a structure, and wrapping past the last
2828
+ // branch lands the reader somewhere unrelated to the one they left.
2829
+ const wrap = prompt.request.presentation !== 'tree';
2830
+ this.#prompt = movePromptSelection(prompt, navigateIndex(navigation, prompt.selected, count, page, { wrap }), count);
2831
+ this.#render();
2832
+ return true;
2833
+ }
2834
+ if (navigation.kind === 'edge') {
2835
+ this.#prompt = movePromptSelection(prompt, edgeIndex(navigation, count), count);
2451
2836
  this.#render();
2452
2837
  return true;
2453
2838
  }
2454
2839
  if (event.id === 'enter' && (this.#editor.text === '' || prompt.request.multiSelect === true)) {
2455
2840
  const answer = selectedPromptAnswer(prompt);
2456
- if (prompt.request.multiSelect === true && answer === null)
2841
+ // A disabled row and an empty multi-select both swallow Enter: nothing is
2842
+ // being answered, so the surface stays where the reader is.
2843
+ if (answer === null)
2457
2844
  return true;
2458
2845
  this.#finishPrompt(answer);
2459
2846
  this.#render();
@@ -2461,6 +2848,10 @@ export class LocalTui {
2461
2848
  }
2462
2849
  if (event.id === 'enter' && prompt.request.filterable === true) {
2463
2850
  const answer = selectedFilteredPromptAnswer(prompt, this.#editor.text);
2851
+ // A heading under a filter is still a heading: clearing the query and
2852
+ // closing on it would lose both the list and the filter.
2853
+ if (answer === null)
2854
+ return true;
2464
2855
  this.#editor.setText('');
2465
2856
  this.#finishPrompt(answer);
2466
2857
  this.#render();
@@ -2481,6 +2872,8 @@ export class LocalTui {
2481
2872
  const disarmed = prompt.armedUntil !== undefined && Date.now() < prompt.armedUntil;
2482
2873
  if (document && prompt.request.documentSource !== undefined && this.#handleDocumentReader(event, prompt))
2483
2874
  return true;
2875
+ if (document && prompt.request.documentSource === undefined && this.#handleRenderedDocument(event, prompt))
2876
+ return true;
2484
2877
  if (document && event.type === 'text') {
2485
2878
  const action = prompt.request.actions?.find(item => item.key.toLowerCase() === event.value.toLowerCase());
2486
2879
  if (action !== undefined && !disarmed) {
@@ -2591,9 +2984,78 @@ export class LocalTui {
2591
2984
  }
2592
2985
  return true;
2593
2986
  }
2987
+ /**
2988
+ * Find in a rendered document.
2989
+ *
2990
+ * The source reader searches its model; a rendered page is its rows, so the
2991
+ * search runs over exactly what the reader is looking at. Without this, `/help`
2992
+ * — sixty rows of grouped commands — was the one surface with no way to look
2993
+ * something up in it.
2994
+ */
2995
+ #handleRenderedDocument(event, prompt) {
2996
+ const rows = () => documentRows(prompt.request, createTheme(this.#colors, this.#colorDepth, this.#themeName, this.#terminalColors), Math.max(1, this.#term.width() - 6));
2997
+ // Always build on the newest state: typing updates the query while the find
2998
+ // is open, and jumping from a stale copy would drop it again.
2999
+ const jumpTo = (row) => {
3000
+ this.#prompt = { ...(this.#prompt ?? prompt), documentScroll: Math.max(0, row - 1), documentTarget: row, documentAnchor: undefined };
3001
+ };
3002
+ if (prompt.documentInput !== undefined) {
3003
+ if (event.type === 'key' && (event.id === 'escape' || event.id === 'ctrl+c')) {
3004
+ this.#editor.setText('');
3005
+ this.#prompt = { ...prompt, documentInput: undefined, documentQuery: prompt.documentOriginalQuery ?? '', documentError: undefined };
3006
+ this.#render();
3007
+ return true;
3008
+ }
3009
+ if (event.type === 'key' && (event.id === 'enter' || event.id === 'ctrl+j')) {
3010
+ const query = this.#editor.text.trim();
3011
+ this.#prompt = { ...(this.#prompt ?? prompt), documentInput: undefined, documentQuery: query, documentError: undefined };
3012
+ const matches = findInRows(rows(), query);
3013
+ if (matches.length > 0)
3014
+ jumpTo(matches[0].row);
3015
+ else
3016
+ this.#prompt = { ...(this.#prompt ?? prompt), documentTarget: undefined };
3017
+ this.#render();
3018
+ return true;
3019
+ }
3020
+ // Typing narrows the query as it is entered, so the count is live.
3021
+ if (event.type === 'text') {
3022
+ this.#editor.handle(event);
3023
+ this.#prompt = { ...(this.#prompt ?? prompt), documentQuery: this.#editor.text };
3024
+ this.#render();
3025
+ return true;
3026
+ }
3027
+ if (event.type === 'key') {
3028
+ this.#editor.handle(event);
3029
+ this.#prompt = { ...(this.#prompt ?? prompt), documentQuery: this.#editor.text };
3030
+ this.#render();
3031
+ return true;
3032
+ }
3033
+ return false;
3034
+ }
3035
+ const search = event.type === 'key' && event.id === 'ctrl+f' || event.type === 'text' && event.value === '/';
3036
+ if (search) {
3037
+ this.#editor.setText(prompt.documentQuery ?? '');
3038
+ this.#prompt = { ...prompt, documentInput: 'search', documentOriginalQuery: prompt.documentQuery ?? '', documentError: undefined };
3039
+ this.#render();
3040
+ return true;
3041
+ }
3042
+ if (event.type === 'key' && (event.id === 'ctrl+n' || event.id === 'ctrl+p')) {
3043
+ const matches = findInRows(rows(), prompt.documentQuery ?? '');
3044
+ if (matches.length === 0)
3045
+ return true;
3046
+ const current = prompt.documentTarget ?? prompt.documentScroll ?? 0;
3047
+ const from = event.id === 'ctrl+n'
3048
+ ? (matches.findIndex(match => match.row > current) + matches.length) % matches.length
3049
+ : (matches.findLastIndex(match => match.row < current) + matches.length) % matches.length;
3050
+ jumpTo(matches[from].row);
3051
+ this.#render();
3052
+ return true;
3053
+ }
3054
+ return false;
3055
+ }
2594
3056
  #handleDocumentReader(event, prompt) {
2595
3057
  const source = prompt.request.documentSource;
2596
- const layout = documentLayout(source, createTheme(this.#colors, this.#trueColor, this.#themeName), Math.max(1, this.#term.width() - 6), {
3058
+ const layout = documentLayout(source, createTheme(this.#colors, this.#colorDepth, this.#themeName, this.#terminalColors), Math.max(1, this.#term.width() - 6), {
2597
3059
  wordWrap: prompt.documentWordWrap ?? true, column: prompt.documentColumn ?? 0,
2598
3060
  });
2599
3061
  const start = this.#promptDocument?.start ?? 0;
@@ -2675,37 +3137,72 @@ export class LocalTui {
2675
3137
  listener(id);
2676
3138
  }
2677
3139
  #handleSubagentLauncher(event) {
2678
- const hasAgents = (this.#subagents?.agents.length ?? 0) > 0;
2679
- if (this.#subagentLauncherFocused) {
2680
- if (!hasAgents) {
2681
- this.#subagentLauncherFocused = false;
3140
+ const agents = this.#subagents?.agents ?? [];
3141
+ if (this.#subagentSelection !== undefined) {
3142
+ if (agents.length === 0) {
3143
+ this.#subagentSelection = undefined;
2682
3144
  return false;
2683
3145
  }
3146
+ const at = Math.min(this.#subagentSelection, agents.length - 1);
2684
3147
  if (event.type === 'key' && event.id === 'enter') {
2685
- this.#subagentLauncherFocused = false;
2686
- void this.#pickSubagent();
3148
+ this.#subagentSelection = undefined;
3149
+ this.#openSelectedSubagent(agents[at]);
2687
3150
  return true;
2688
3151
  }
2689
- if (event.type === 'key' && (event.id === 'escape' || event.id === 'up')) {
2690
- this.#subagentLauncherFocused = false;
3152
+ if (event.type === 'key' && event.id === 'escape') {
3153
+ this.#subagentSelection = undefined;
2691
3154
  this.#render();
2692
3155
  return true;
2693
3156
  }
2694
- if (event.type === 'key' && event.id === 'down')
3157
+ if (event.type === 'key' && (event.id === 'up' || event.id === 'down')) {
3158
+ const delta = event.id === 'up' ? -1 : 1;
3159
+ // `up` from the first row leaves the bar; `down` stops at the last one.
3160
+ if (at + delta < 0)
3161
+ this.#subagentSelection = undefined;
3162
+ else
3163
+ this.#subagentSelection = Math.min(agents.length - 1, at + delta);
3164
+ this.#render();
2695
3165
  return true;
2696
- this.#subagentLauncherFocused = false;
2697
- return false;
3166
+ }
3167
+ return true;
2698
3168
  }
2699
- if (!hasAgents || event.type !== 'key' || event.id !== 'down')
3169
+ if (agents.length === 0 || event.type !== 'key' || event.id !== 'down')
2700
3170
  return false;
2701
3171
  if (this.#editor.text !== '' || this.#images.count > 0 || this.#historyIndex !== 0 || this.#ac !== null)
2702
3172
  return false;
2703
3173
  if (this.#queuedSubmissions.length > 0 || this.#queueEditNewer !== null || this.#queueEditPending)
2704
3174
  return false;
2705
- this.#subagentLauncherFocused = true;
3175
+ this.#subagentSelection = Math.min(agents.length - 1, Math.max(0, subagentPreviewStart(agents)));
2706
3176
  this.#render();
2707
3177
  return true;
2708
3178
  }
3179
+ /**
3180
+ * Open what the selected row has.
3181
+ *
3182
+ * A local child has a transcript to read, so `Enter` swaps the view. An external
3183
+ * child has none by construction — its results land in the parent session — so
3184
+ * `Enter` prints its status and recent activity as a fold-able transcript
3185
+ * result instead of opening a surface for it.
3186
+ */
3187
+ #openSelectedSubagent(agent) {
3188
+ if (agent.mode === 'external') {
3189
+ this.commandOutput(`Agent · ${agent.label}`, [
3190
+ `${agent.phase === 'completed' ? 'Completed' : agent.phase === 'error' ? 'Failed' : 'Running'} · ${formatAgentElapsed(agent)}`,
3191
+ '',
3192
+ `Mode: ${agent.mode}`,
3193
+ `Session: ${agent.id}`,
3194
+ `Parent: ${agent.parentId ?? 'root session'}`,
3195
+ `Depth: ${agent.depth}`,
3196
+ ...(agent.workflow === undefined ? [] : [`Workflow: ${agent.workflow.name}`, `Phase: ${agent.workflow.phase ?? '—'}`]),
3197
+ ...(agent.activity.length === 0 ? [] : ['', 'Recent activity', ...agent.activity.map(item => `${item.status.padEnd(8)} ${item.text}`)]),
3198
+ '',
3199
+ 'An external agent keeps no local transcript; its results arrive in this session.',
3200
+ ].join('\n'));
3201
+ return;
3202
+ }
3203
+ this.#openInspect(agent.id);
3204
+ this.#render();
3205
+ }
2709
3206
  #closeInspect() {
2710
3207
  if (this.#inspected === undefined)
2711
3208
  return;
@@ -2715,46 +3212,28 @@ export class LocalTui {
2715
3212
  for (const listener of this.#inspectCloses)
2716
3213
  listener();
2717
3214
  }
2718
- #pickSubagent() {
2719
- this.#subagentLauncherFocused = false;
2720
- const agents = this.#subagents?.agents ?? [];
2721
- if (agents.length === 0 && !this.#subagents?.workflows?.length) {
2722
- this.notice('No subagents are available in this session.');
2723
- return;
2724
- }
2725
- this.#prompt = null;
2726
- this.#settings = null;
2727
- this.#copySelector = null;
2728
- this.#search = null;
2729
- this.#trajectory = null;
2730
- this.#ac = null;
2731
- this.#agentHub = createAgentHub(this.#subagents ?? { agents });
2732
- this.#render();
2733
- }
2734
3215
  #applyPrefs(prefs, options) {
2735
3216
  const previous = options.persist ? this.prefs() : undefined;
2736
3217
  const version = this.#prefsVersion;
2737
3218
  const previousMotion = this.#motion;
2738
3219
  this.#themeName = prefs.theme;
2739
3220
  this.#colors = prefs.colors;
2740
- this.#syncTrueColor();
3221
+ this.#syncColorDepth();
2741
3222
  this.#motion = prefs.motion ?? 'full';
2742
3223
  this.#flushPasteBurst(true);
2743
3224
  this.#pasteProtection = prefs.pasteProtection !== false;
2744
3225
  this.#externalEditor = prefs.editor ?? 'auto';
2745
- this.#terminalProgress = prefs.terminalProgress ?? false;
2746
3226
  this.#terminalTitle = prefs.terminalTitle ?? 'status';
2747
3227
  this.#terminalState = prefs.terminalState ?? 'auto';
2748
3228
  this.#syncWindowTitle();
2749
3229
  this.#copyOnSelect = prefs.copyOnSelect ?? true;
2750
3230
  this.#mathMode = prefs.mathMode ?? 'auto';
2751
3231
  this.#mermaidMode = prefs.mermaidMode ?? 'auto';
3232
+ this.#hideThinking = prefs.hideThinking === true;
2752
3233
  this.#mouseInteraction = prefs.mouseInteraction ?? 'auto';
2753
3234
  this.#checkUpdates = prefs.checkUpdates ?? true;
2754
3235
  this.#startupChangelog = prefs.startupChangelog ?? 'summary';
2755
- this.#notificationPolicy = prefs.notifications ?? 'off';
2756
- this.#notificationThreshold = prefs.notificationThreshold ?? '30s';
2757
- this.#notificationFocus = prefs.notificationFocus ?? 'unfocused';
3236
+ this.#notificationPolicy = resolveNotificationMode(prefs.notifications, prefs.notificationFocus);
2758
3237
  if (this.#notificationPolicy === 'off')
2759
3238
  this.#notificationQueue.clear();
2760
3239
  this.#configureNotifications();
@@ -2949,36 +3428,17 @@ export class LocalTui {
2949
3428
  this.#render();
2950
3429
  });
2951
3430
  }
2952
- #applyCopySelector(event) {
2953
- if (this.#copySelector === null)
2954
- return;
2955
- const command = applyCopySelectorEvent(this.#copySelector, event);
2956
- if (command.kind === 'update') {
2957
- this.#copySelector = command.state;
2958
- this.#render();
2959
- return;
2960
- }
2961
- if (command.kind === 'pick') {
2962
- this.#copySelector = null;
2963
- void this.#copyPicked(command.item.text, command.item.copyMessage);
2964
- return;
2965
- }
2966
- if (command.kind === 'close') {
2967
- this.#copySelector = null;
2968
- this.#render();
2969
- }
2970
- }
2971
3431
  async #copyPicked(text, label) {
2972
3432
  try {
2973
3433
  const delivery = await this.#deliverCopy(text);
2974
3434
  if (this.#disposed)
2975
3435
  return;
2976
- this.#notice(delivery === 'requested' ? 'Sent ' + label + ' to the terminal clipboard' : 'Copied ' + label);
3436
+ this.#showTransientStatus(delivery === 'requested' ? 'Sent ' + label + ' to the terminal clipboard' : 'Copied ' + label);
2977
3437
  }
2978
3438
  catch {
2979
3439
  if (this.#disposed)
2980
3440
  return;
2981
- this.#notice('Copy failed');
3441
+ this.#showTransientStatus('Copy failed');
2982
3442
  }
2983
3443
  this.#render();
2984
3444
  }
@@ -3076,10 +3536,22 @@ export class LocalTui {
3076
3536
  const harnessAt = at !== undefined
3077
3537
  && (this.#searchFileMentions !== undefined || this.#searchSessions !== undefined);
3078
3538
  if (fuzzyAt || harnessAt || shortcutAt) {
3539
+ // A `@` query is answered by a debounced search, so almost every keystroke
3540
+ // lands before an answer exists. Clearing the menu here emptied the screen
3541
+ // for the whole debounce-plus-search interval and refilled it afterwards —
3542
+ // one flash per character, and the same again on every delete.
3543
+ //
3544
+ // The rows already on screen still describe the token this keystroke is
3545
+ // extending, so they stay until a real result replaces them. A genuinely
3546
+ // different token closes the menu, because those rows no longer apply.
3079
3547
  if ((harnessAt || shortcutAt) && !fuzzyAt) {
3080
- this.#setAutocomplete(pathSuggestions(this.#editor.text, this.#editor.cursor, pathOptions, commands));
3548
+ const listing = pathSuggestions(this.#editor.text, this.#editor.cursor, pathOptions, commands);
3549
+ if (listing !== null)
3550
+ this.#setAutocomplete(listing, atPrefix);
3551
+ else if (!this.#acDescribes(atPrefix))
3552
+ this.#ac = null;
3081
3553
  }
3082
- else {
3554
+ else if (!this.#acDescribes(atPrefix)) {
3083
3555
  this.#ac = null;
3084
3556
  }
3085
3557
  const text = this.#editor.text;
@@ -3108,7 +3580,13 @@ export class LocalTui {
3108
3580
  if (this.#disposed || controller.signal.aborted || requestId !== this.#autocompleteRequestId)
3109
3581
  return;
3110
3582
  this.#autocompleteAbort = null;
3111
- this.#setAutocomplete(result);
3583
+ // An empty answer for a `@` query means "nothing matched yet", not
3584
+ // "close the menu": keeping the live list is what stops the flash when
3585
+ // a prefix has no rows of its own.
3586
+ if (result !== null)
3587
+ this.#setAutocomplete(result, atPrefix);
3588
+ else if (!this.#acDescribes(atPrefix))
3589
+ this.#setAutocomplete(null);
3112
3590
  this.#render();
3113
3591
  }).catch((error) => {
3114
3592
  if (controller.signal.aborted || requestId !== this.#autocompleteRequestId)
@@ -3124,7 +3602,16 @@ export class LocalTui {
3124
3602
  const result = pathSuggestions(this.#editor.text, this.#editor.cursor, pathOptions, commands);
3125
3603
  this.#setAutocomplete(result);
3126
3604
  }
3127
- #setAutocomplete(result) {
3605
+ /**
3606
+ * Whether the open menu still speaks for the `@` token being typed.
3607
+ *
3608
+ * A menu with no token recorded belongs to a slash or path completion and is
3609
+ * never reused across an `@` keystroke.
3610
+ */
3611
+ #acDescribes(atPrefix) {
3612
+ return completionDescribes(this.#ac?.query, atPrefix);
3613
+ }
3614
+ #setAutocomplete(result, query) {
3128
3615
  if (result === null) {
3129
3616
  this.#ac = null;
3130
3617
  return;
@@ -3136,7 +3623,7 @@ export class LocalTui {
3136
3623
  if (idx >= 0)
3137
3624
  selected = idx;
3138
3625
  }
3139
- this.#ac = { items: result.items, selected };
3626
+ this.#ac = { items: result.items, selected, ...(query === undefined ? {} : { query }) };
3140
3627
  }
3141
3628
  #moveAutocomplete(dir) {
3142
3629
  if (this.#ac === null || this.#ac.items.length === 0)
@@ -3184,40 +3671,69 @@ export class LocalTui {
3184
3671
  this.#historyNext();
3185
3672
  return;
3186
3673
  }
3187
- if (command.kind === 'interrupt') {
3188
- if (this.#state.status === 'running') {
3189
- for (const listener of this.#interrupts)
3190
- listener();
3191
- }
3192
- return;
3193
- }
3194
- if (command.kind === 'clear') {
3195
- this.#clearComposerWithUndo({ clearQueueEdit: true, closeSearch: true });
3196
- return;
3197
- }
3198
- if (command.kind === 'quit') {
3199
- this.#quit();
3674
+ }
3675
+ /**
3676
+ * Show a one-line confirmation that goes away on its own.
3677
+ *
3678
+ * Replaced, never appended: two presses in a row leave one line saying what
3679
+ * the second one did, which is what the reader is looking for.
3680
+ */
3681
+ #showTransientStatus(text, ttlMs = TRANSIENT_STATUS_MS) {
3682
+ this.#transientStatus = text;
3683
+ if (this.#transientTimer !== null)
3684
+ clearTimeout(this.#transientTimer);
3685
+ this.#transientTimer = setTimeout(() => {
3686
+ this.#transientTimer = null;
3687
+ if (this.#transientStatus !== text)
3688
+ return;
3689
+ this.#transientStatus = undefined;
3690
+ if (!this.#disposed && this.#tty)
3691
+ this.#render();
3692
+ }, ttlMs);
3693
+ this.#transientTimer.unref?.();
3694
+ this.#render();
3695
+ }
3696
+ /** Any keystroke makes the last confirmation stale. */
3697
+ #clearTransientStatus() {
3698
+ if (this.#transientStatus === undefined)
3200
3699
  return;
3700
+ this.#transientStatus = undefined;
3701
+ if (this.#transientTimer !== null) {
3702
+ clearTimeout(this.#transientTimer);
3703
+ this.#transientTimer = null;
3201
3704
  }
3202
- if (command.kind === 'suspend') {
3203
- if (process.platform !== 'win32') {
3204
- if (this.#inspecting) {
3205
- this.#followTail();
3206
- this.#render();
3207
- }
3208
- this.#setMouseTracking(false);
3209
- this.#term.output.write('\x1b[?1004l');
3210
- try {
3211
- process.kill(process.pid, 'SIGTSTP');
3212
- }
3213
- catch { /* no controlling tty */ }
3214
- }
3705
+ }
3706
+ /**
3707
+ * Show or hide thinking across the whole transcript, and remember the choice.
3708
+ *
3709
+ * A revealed transcript is one where no thought is folded, so the per-thought
3710
+ * openings a reader made are dropped at the same time; keeping them would
3711
+ * leave a thought open inside a transcript that claims to show everything.
3712
+ */
3713
+ #toggleThinking() {
3714
+ const next = !this.#hideThinking;
3715
+ this.#hideThinking = next;
3716
+ if (!next)
3717
+ this.#expandedReasoning.clear();
3718
+ const persist = this.#persistPrefs;
3719
+ if (persist !== null)
3720
+ void persist(this.prefs(), [{ op: 'set', path: ['hideThinking'], value: next }]);
3721
+ this.#showTransientStatus(next ? 'Thinking: hidden' : 'Thinking: shown');
3722
+ }
3723
+ /** Hand the terminal to the shell and stop until SIGCONT brings it back. */
3724
+ #suspend() {
3725
+ if (process.platform === 'win32')
3215
3726
  return;
3216
- }
3217
- if (command.kind === 'resetDisplay') {
3218
- this.#renderer.reset();
3727
+ if (this.#inspecting) {
3728
+ this.#followTail();
3219
3729
  this.#render();
3220
3730
  }
3731
+ // The shell that takes over gets every mode back; SIGCONT takes them again.
3732
+ this.#handOffTerminal();
3733
+ try {
3734
+ process.kill(process.pid, 'SIGTSTP');
3735
+ }
3736
+ catch { /* no controlling tty */ }
3221
3737
  }
3222
3738
  #historyPrev() {
3223
3739
  if (this.#images.count > 0)
@@ -3298,6 +3814,34 @@ export class LocalTui {
3298
3814
  this.#quitRequested = true;
3299
3815
  }
3300
3816
  }
3817
+ /**
3818
+ * Turn composer text into a submission, shared by the main and inspected
3819
+ * composers.
3820
+ *
3821
+ * The composer marker is a draft affordance, not something the reader said,
3822
+ * so it leaves the text; it still records where the picture sat, so the
3823
+ * segments keep that order.
3824
+ */
3825
+ #buildSubmission(text) {
3826
+ const images = this.#images.copies();
3827
+ const files = this.#files.copies();
3828
+ const typedText = this.#files.text(images.length > 0 ? text.trim() : text);
3829
+ const segments = images.length === 0 ? [] : splitComposerImageMarkers(typedText, images);
3830
+ // Stripping a marker that sat on its own line leaves that line break behind.
3831
+ const submittedText = images.length > 0 ? stripComposerImageMarkers(typedText, images).trim() : typedText;
3832
+ const literal = text === this.#editor.expandedText && (this.#literalInput || this.#editor.startsWithPaste);
3833
+ const historyText = submittedText.replace(/[ \t]{2,}/gu, ' ').trim();
3834
+ return {
3835
+ submission: {
3836
+ text: submittedText,
3837
+ images,
3838
+ ...(segments.length === 0 ? {} : { segments }),
3839
+ ...(files.length === 0 ? {} : { files }),
3840
+ ...(literal ? { literal: true } : {}),
3841
+ },
3842
+ historyText,
3843
+ };
3844
+ }
3301
3845
  #submit(text) {
3302
3846
  if (this.#prompt !== null) {
3303
3847
  if (this.#prompt.request.presentation === 'progress')
@@ -3308,15 +3852,9 @@ export class LocalTui {
3308
3852
  this.#render();
3309
3853
  return;
3310
3854
  }
3311
- const images = this.#images.copies();
3312
- const files = this.#files.copies();
3313
- const submittedText = this.#files.text(images.length > 0 ? text.trim() : text);
3314
- const literal = text === this.#editor.expandedText && (this.#literalInput || this.#editor.startsWithPaste);
3315
- const submission = { text: submittedText, images, ...(files.length === 0 ? {} : { files }), ...(literal ? { literal: true } : {}) };
3855
+ const { submission, historyText } = this.#buildSubmission(text);
3856
+ const { images, files = [], literal = false, text: submittedText } = submission;
3316
3857
  const queueEditNewer = this.#queueEditNewer;
3317
- const historyText = stripComposerImageMarkers(submittedText, images)
3318
- .replace(/[ \t]{2,}/gu, ' ')
3319
- .trim();
3320
3858
  if (historyText !== '' && this.#history[this.#history.length - 1] !== historyText) {
3321
3859
  this.#history.push(historyText);
3322
3860
  this.#historyStore?.add(historyText);
@@ -3333,9 +3871,7 @@ export class LocalTui {
3333
3871
  this.#ac = null;
3334
3872
  this.#search = null;
3335
3873
  this.#settings = null;
3336
- this.#copySelector = null;
3337
3874
  this.#trajectory = null;
3338
- this.#agentHub = null;
3339
3875
  // Image placeholders are TUI-owned. Mixed image+slash drafts stay a
3340
3876
  // submission so restore can keep the original markers; the runner strips
3341
3877
  // them only to detect and execute Harness commands.
@@ -3368,13 +3904,8 @@ export class LocalTui {
3368
3904
  this.#render();
3369
3905
  }
3370
3906
  #submitInspect(text) {
3371
- const literal = text === this.#editor.expandedText && (this.#literalInput || this.#editor.startsWithPaste);
3372
- const images = this.#images.copies();
3373
- const files = this.#files.copies();
3374
- const submittedText = this.#files.text(images.length > 0 ? text.trim() : text);
3375
- const historyText = stripComposerImageMarkers(submittedText, images)
3376
- .replace(/[ \t]{2,}/gu, ' ')
3377
- .trim();
3907
+ const { submission, historyText } = this.#buildSubmission(text);
3908
+ const { images, files = [], literal = false, text: submittedText } = submission;
3378
3909
  if (historyText !== '' && this.#history[this.#history.length - 1] !== historyText) {
3379
3910
  this.#history.push(historyText);
3380
3911
  this.#historyStore?.add(historyText);
@@ -3398,8 +3929,9 @@ export class LocalTui {
3398
3929
  this.#render();
3399
3930
  return;
3400
3931
  }
3932
+ const { literal: _literal, ...inspectSubmission } = submission;
3401
3933
  for (const listener of this.#inspectSubmits)
3402
- listener({ text: submittedText, images, ...(files.length === 0 ? {} : { files }) });
3934
+ listener(inspectSubmission);
3403
3935
  this.#popStashedDraft();
3404
3936
  this.#render();
3405
3937
  }
@@ -3463,8 +3995,7 @@ export class LocalTui {
3463
3995
  return;
3464
3996
  }
3465
3997
  if (command.name === 'tools') {
3466
- this.#toolCatalog();
3467
- this.#render();
3998
+ this.#runTools();
3468
3999
  return;
3469
4000
  }
3470
4001
  if (args !== '' && args !== 'full') {
@@ -3472,28 +4003,7 @@ export class LocalTui {
3472
4003
  this.#render();
3473
4004
  return;
3474
4005
  }
3475
- const full = args === 'full';
3476
- this.#state = {
3477
- ...this.#state,
3478
- blocks: [...this.#state.blocks, {
3479
- kind: 'commandOutput',
3480
- command: 'help',
3481
- text: [
3482
- formatHelpText(this.#commands()),
3483
- '',
3484
- full
3485
- ? `**Keyboard Shortcuts · ${hotkeyCount(this.#keybindings)} shortcuts**`
3486
- : '**Essential Shortcuts**',
3487
- '',
3488
- full
3489
- ? formatHotkeysText(this.#keybindings)
3490
- : formatEssentialHotkeysText(this.#keybindings),
3491
- ...(full ? [] : ['', 'Use `/help full` to view every keyboard shortcut.']),
3492
- ].join('\n'),
3493
- }],
3494
- };
3495
- this.#focusLatestBlock();
3496
- this.#render();
4006
+ this.#runHelp(args === 'full');
3497
4007
  }
3498
4008
  #commands() {
3499
4009
  const localNames = new Set(BUILTIN_SLASH_COMMANDS.flatMap((command) => [command.name, ...(command.aliases ?? [])]));
@@ -3503,6 +4013,7 @@ export class LocalTui {
3503
4013
  name: command.name,
3504
4014
  description: command.description,
3505
4015
  ...(command.inputHint === undefined ? {} : { inputHint: command.inputHint }),
4016
+ ...(command.complete === undefined ? {} : { complete: command.complete }),
3506
4017
  }));
3507
4018
  return [...BUILTIN_SLASH_COMMANDS, ...runtime];
3508
4019
  }
@@ -3545,17 +4056,11 @@ export class LocalTui {
3545
4056
  #displaceSurface() {
3546
4057
  const displaced = this.#trajectory !== null
3547
4058
  ? { kind: 'trajectory', state: this.#trajectory }
3548
- : this.#agentHub !== null
3549
- ? { kind: 'agentHub', state: this.#agentHub }
3550
- : this.#settings !== null
3551
- ? { kind: 'settings', state: this.#settings }
3552
- : this.#copySelector !== null
3553
- ? { kind: 'copySelector', state: this.#copySelector }
3554
- : this.#search !== null ? { kind: 'search', state: this.#search } : null;
4059
+ : this.#settings !== null
4060
+ ? { kind: 'settings', state: this.#settings }
4061
+ : this.#search !== null ? { kind: 'search', state: this.#search } : null;
3555
4062
  this.#trajectory = null;
3556
- this.#agentHub = null;
3557
4063
  this.#settings = null;
3558
- this.#copySelector = null;
3559
4064
  this.#search = null;
3560
4065
  return displaced;
3561
4066
  }
@@ -3567,52 +4072,71 @@ export class LocalTui {
3567
4072
  return;
3568
4073
  if (displaced.kind === 'trajectory')
3569
4074
  this.#trajectory = displaced.state;
3570
- else if (displaced.kind === 'agentHub')
3571
- this.#agentHub = displaced.state;
3572
4075
  else if (displaced.kind === 'settings') {
3573
4076
  this.#settings = displaced.state;
3574
4077
  this.#rebuildSettings(this.#pluginSettings?.entries() ?? []);
3575
4078
  this.#refreshSettingsCatalog();
3576
4079
  }
3577
- else if (displaced.kind === 'copySelector')
3578
- this.#copySelector = displaced.state;
3579
4080
  else
3580
4081
  this.#search = displaced.state;
3581
4082
  }
4083
+ /** The pane's answer, offered to `/copy` while it is on screen and finished. */
4084
+ #copyableAside() {
4085
+ if (this.#aside === undefined || this.#aside.status === 'running' || this.#aside.text.trim() === '')
4086
+ return undefined;
4087
+ return { question: this.#aside.question, text: this.#aside.text };
4088
+ }
4089
+ /**
4090
+ * Copy something out of the transcript.
4091
+ *
4092
+ * There used to be four kinds — `text`, `code`, `cmd`, `output` — and each one
4093
+ * asked the reader to remember a word to skip a keystroke in the picker. A kind
4094
+ * that means "the default" is a no-op, and the other three name a row the picker
4095
+ * already shows with its content, its language and its size. One command, one
4096
+ * list: the choice is made by looking, not by recalling.
4097
+ */
3582
4098
  async #runCopy(args) {
3583
- if (args.trim() === '') {
3584
- const items = buildCopyTargets(this.#state.blocks);
3585
- if (items.length === 0) {
3586
- this.#notice('Nothing to copy.');
3587
- this.#render();
3588
- return;
3589
- }
3590
- this.#search = null;
3591
- this.#ac = null;
3592
- this.#settings = null;
3593
- this.#copySelector = createCopySelector(items);
4099
+ if (args.trim() !== '') {
4100
+ this.#notice('Usage: /copy');
3594
4101
  this.#render();
3595
4102
  return;
3596
4103
  }
3597
- const kind = parseCopyKind(args);
3598
- if (kind === undefined) {
3599
- this.#notice('Usage: /copy [code|cmd|output]');
4104
+ const items = buildCopyTargets(this.#state.blocks, undefined, this.#copyableAside());
4105
+ if (items.length === 0) {
4106
+ this.#notice('Nothing to copy.');
3600
4107
  this.#render();
3601
4108
  return;
3602
4109
  }
3603
- const target = extractCopyTarget(this.#state.blocks, kind);
3604
- if (target === undefined) {
3605
- this.#notice(kind === 'code'
3606
- ? 'No code block to copy.'
3607
- : kind === 'cmd'
3608
- ? 'No command to copy.'
3609
- : kind === 'output'
3610
- ? 'No tool output to copy.'
3611
- : 'Nothing to copy.');
3612
- this.#render();
4110
+ /**
4111
+ * The same card as every other list.
4112
+ *
4113
+ * This used to be a bespoke overlay with its own key model: a filter that
4114
+ * stayed inactive until `/` — so typing a letter did nothing and Space
4115
+ * copied — and a nine-row hotkey table of its own. It was the last surface
4116
+ * that did not answer to the shared list vocabulary, which is exactly the
4117
+ * inconsistency the reader noticed.
4118
+ */
4119
+ const answer = await this.prompt({
4120
+ title: 'Copy',
4121
+ question: items.length === 1 ? 'One thing to copy' : 'Choose what to copy',
4122
+ filterable: true,
4123
+ allowCustom: false,
4124
+ notify: false,
4125
+ options: items.map(item => ({
4126
+ label: item.label,
4127
+ value: item.id,
4128
+ ...(item.hint === '' ? {} : { description: item.hint }),
4129
+ // The preview is the payload: choosing blind is what the row labels
4130
+ // cannot prevent when two replies open with the same words.
4131
+ preview: item.text,
4132
+ })),
4133
+ });
4134
+ if (answer === null)
3613
4135
  return;
3614
- }
3615
- await this.#copyPicked(target.text, target.label);
4136
+ const picked = items.find(item => item.id === answer);
4137
+ if (picked === undefined)
4138
+ return;
4139
+ void this.#copyPicked(picked.text, picked.copyMessage);
3616
4140
  }
3617
4141
  #runSettings(args) {
3618
4142
  if (args.trim() !== '') {
@@ -3683,40 +4207,59 @@ export class LocalTui {
3683
4207
  };
3684
4208
  }
3685
4209
  #configureNotifications() {
3686
- const thresholds = { '15s': 15_000, '30s': 30_000, '1m': 60_000, '2m': 120_000 };
3687
4210
  this.#notifications.configure({
3688
4211
  policy: this.#notificationPolicy,
3689
- thresholdMs: thresholds[this.#notificationThreshold],
4212
+ thresholdMs: NOTIFICATION_THRESHOLD_MS,
3690
4213
  });
3691
4214
  }
3692
4215
  #emitNotification(notification) {
3693
4216
  if (notification === undefined || !this.#tty || this.#disposed)
3694
4217
  return;
3695
- if (this.#notificationFocus === 'unfocused' && this.#terminalFocused === true)
4218
+ if (this.#notificationPolicy === 'unfocused' && this.#terminalFocused === true)
3696
4219
  return;
3697
4220
  this.#notificationQueue.offer(notification);
3698
4221
  if (this.#notificationTimer !== undefined)
3699
4222
  return;
3700
4223
  this.#notificationTimer = setTimeout(() => {
3701
4224
  this.#notificationTimer = undefined;
3702
- const pending = this.#notificationQueue.take(this.#notificationFocus, this.#terminalFocused);
4225
+ const pending = this.#notificationQueue.take();
3703
4226
  if (pending === undefined || this.#disposed || this.#notificationPolicy === 'off')
3704
4227
  return;
4228
+ // Re-read focus at delivery time: the reader may have come back inside the
4229
+ // coalescing window, and a turn finishing while they watch is not news.
4230
+ if (this.#notificationPolicy === 'unfocused' && this.#terminalFocused === true)
4231
+ return;
3705
4232
  const sequence = terminalNotificationSequence(pending);
3706
4233
  if (sequence !== '')
3707
4234
  this.#term.output.write(sequence);
3708
4235
  }, 25);
3709
4236
  }
3710
- #toolCatalog() {
3711
- this.#state = {
3712
- ...this.#state,
3713
- blocks: [...this.#state.blocks, { kind: 'toolCatalog', tools: this.#tools }],
3714
- };
3715
- this.#focusLatestBlock();
4237
+ /**
4238
+ * Help is reference, not conversation: 60 rows of it pushed into immutable
4239
+ * scrollback and vanished on resume, so the reader paid for it twice. It opens
4240
+ * in the reading surface instead, where it can be searched and left with Esc.
4241
+ */
4242
+ #runHelp(full) {
4243
+ const text = [
4244
+ formatHelpText(this.#commands()),
4245
+ '',
4246
+ full
4247
+ ? `**Keyboard Shortcuts · ${hotkeyCount(this.#keybindings)} shortcuts**`
4248
+ : '**Essential Shortcuts**',
4249
+ '',
4250
+ full ? formatHotkeysText(this.#keybindings) : formatEssentialHotkeysText(this.#keybindings),
4251
+ ...(full ? [] : ['', 'Use `/help full` to view every keyboard shortcut.']),
4252
+ ].join('\n');
4253
+ this.commandOutput('help', text, { focus: true });
3716
4254
  }
3717
- #focusLatestBlock() {
3718
- this.#follow = false;
3719
- this.#focusBlock = Math.max(0, this.#state.blocks.length - 1);
4255
+ /**
4256
+ * Tools are reference, like the command list: a table of names and
4257
+ * descriptions the reader consults and dismisses, not a step of the work.
4258
+ */
4259
+ #runTools() {
4260
+ // The first row of a command result is its heading, so a table needs one.
4261
+ const heading = `Tools · ${this.#tools.length} active`;
4262
+ this.commandOutput('tools', `${heading}\n\n${formatToolsText(this.#tools)}`, { focus: true });
3720
4263
  }
3721
4264
  /** Resolve a configured action for one key id, tolerating camelCase ids. */
3722
4265
  #boundAction(id) {
@@ -3724,8 +4267,44 @@ export class LocalTui {
3724
4267
  }
3725
4268
  /** Run one configured action; returns true when the event was consumed. */
3726
4269
  #runAction(action) {
3727
- if (this.#prompt !== null || this.#settings !== null || this.#copySelector !== null)
4270
+ // `interrupt` is resolved further down, after every surface that wants to
4271
+ // interpret Escape itself — a settings search clears before the overlay
4272
+ // closes. Claiming it here would skip that layering.
4273
+ if (action === 'interrupt')
3728
4274
  return false;
4275
+ if (action === 'clear-composer')
4276
+ return this.#runClearComposer();
4277
+ if (action === 'quit') {
4278
+ if (this.#hasComposerContent() || this.#editor.text !== '')
4279
+ return false;
4280
+ this.#quit();
4281
+ return true;
4282
+ }
4283
+ if (action === 'suspend') {
4284
+ this.#suspend();
4285
+ return true;
4286
+ }
4287
+ if (action === 'reset-display') {
4288
+ this.#renderer.reset();
4289
+ this.#render();
4290
+ return true;
4291
+ }
4292
+ if (this.#prompt !== null || this.#settings !== null)
4293
+ return false;
4294
+ if (action === 'select-model') {
4295
+ this.#submit('/model');
4296
+ return true;
4297
+ }
4298
+ if (action === 'cycle-thinking') {
4299
+ this.#submit('/model reasoning');
4300
+ return true;
4301
+ }
4302
+ if (action === 'toggle-thinking') {
4303
+ this.#toggleThinking();
4304
+ return true;
4305
+ }
4306
+ if (action === 'dequeue')
4307
+ return this.#restoreLatestQueuedSubmission(true);
3729
4308
  if (action === 'stash-draft') {
3730
4309
  if (this.#search !== null)
3731
4310
  return false;
@@ -3735,8 +4314,28 @@ export class LocalTui {
3735
4314
  if (action === 'preview-images') {
3736
4315
  if (this.#search !== null || this.#inspected !== undefined)
3737
4316
  return false;
3738
- if (this.#images.count === 0)
3739
- this.notice('Paste an image before opening its preview.');
4317
+ if (this.#images.count === 0) {
4318
+ // No draft image: preview the newest image the conversation carries,
4319
+ // which is the only way a settled card can still show its picture.
4320
+ const ref = this.#latestImageRef();
4321
+ if (ref === undefined)
4322
+ this.notice('Paste an image before opening its preview.');
4323
+ else if (this.#readImageInput === undefined)
4324
+ this.notice('This deployment cannot reopen that image.');
4325
+ else if (this.#imagePreviewAbort === undefined) {
4326
+ const abort = new AbortController();
4327
+ this.#imagePreviewAbort = abort;
4328
+ void this.#readImageInput(ref, abort.signal)
4329
+ .then(image => image === undefined
4330
+ ? this.notice('That image could not be read back for a preview.', { level: 'error' })
4331
+ : previewImages(this, [image], abort.signal))
4332
+ .catch((error) => { if (!abort.signal.aborted && !this.#disposed)
4333
+ this.notice(error instanceof Error ? error.message : String(error), { level: 'error' }); })
4334
+ .finally(() => { if (this.#imagePreviewAbort === abort)
4335
+ this.#imagePreviewAbort = undefined; });
4336
+ }
4337
+ return true;
4338
+ }
3740
4339
  else if (this.#imagePreviewAbort === undefined) {
3741
4340
  const abort = new AbortController();
3742
4341
  const revision = this.#images.revision;
@@ -3811,29 +4410,27 @@ export class LocalTui {
3811
4410
  return true;
3812
4411
  }
3813
4412
  if (action === 'review-changes') {
3814
- let anchor = this.#viewportBlock() ?? this.#state.blocks.length - 1;
4413
+ // The keyboard twin of right-clicking a tool's path: open the files the
4414
+ // tool under the viewport declared. It shares the mouse path's region
4415
+ // lookup, so the two can never disagree about which call is under the
4416
+ // reader's eye.
4417
+ //
4418
+ // This used to also derive the turn under the viewport and forward
4419
+ // `/diff turn N` when no tool was there — twenty lines of anchor
4420
+ // backtracking to reach what `/diff` already asks for on its own. A
4421
+ // reader who wants this turn's changes types `/diff`.
3815
4422
  const rows = this.#renderer.viewport().map((_, row) => this.#renderer.documentRowAt(row)).filter((row) => row !== undefined);
3816
4423
  const top = this.#follow ? undefined : rows[0];
3817
4424
  const regions = this.#fileActionFrame?.transcript?.fileRegions ?? [];
3818
4425
  const region = (top === undefined ? undefined : regions.find(region => top >= region.start && top < region.end))
3819
4426
  ?? (this.#inspecting ? regions.find(region => this.#state.blocks[region.block]?.kind === 'tool' && rows.some(row => row >= region.start && row < region.end)) : undefined);
3820
- const block = this.#state.blocks[region?.block ?? anchor];
4427
+ const block = this.#state.blocks[region?.block ?? (this.#viewportBlock() ?? this.#state.blocks.length - 1)];
3821
4428
  const files = block?.kind === 'tool' ? blockFileAction(block) : undefined;
3822
- if (files !== undefined) {
3823
- this.#openFileAction(files);
4429
+ if (files === undefined) {
4430
+ this.#showTransientStatus('No tool files here · use /diff', 4_000);
3824
4431
  return true;
3825
4432
  }
3826
- // A short inspection cannot scroll its first call above the welcome card
3827
- // or startup notices. Those rows address the first human turn, not an
3828
- // empty slice before it.
3829
- if (!this.#state.blocks.slice(0, anchor + 1).some(block => block.kind === 'user')) {
3830
- const firstUser = this.#state.blocks.findIndex(block => block.kind === 'user');
3831
- if (firstUser >= 0)
3832
- anchor = firstUser;
3833
- }
3834
- const nextUser = this.#state.blocks.findIndex((block, index) => index > anchor && block.kind === 'user');
3835
- const workspace = this.#state.blocks.slice(0, nextUser < 0 ? undefined : nextUser).findLast(block => block.kind === 'workspace');
3836
- this.#runSlash('diff', workspace?.kind === 'workspace' ? `turn ${workspace.turn}` : '');
4433
+ this.#openFileAction(files);
3837
4434
  return true;
3838
4435
  }
3839
4436
  if (action === 'scroll-page-up') {
@@ -3892,10 +4489,6 @@ export class LocalTui {
3892
4489
  this.#render();
3893
4490
  return true;
3894
4491
  }
3895
- if (action === 'inspect-subagent') {
3896
- void this.#pickSubagent();
3897
- return true;
3898
- }
3899
4492
  if (action === 'retry') {
3900
4493
  this.#submit('/retry');
3901
4494
  return true;
@@ -3908,10 +4501,6 @@ export class LocalTui {
3908
4501
  this.#submit('/model previous');
3909
4502
  return true;
3910
4503
  }
3911
- if (action === 'cycle-reasoning') {
3912
- this.#submit('/model reasoning');
3913
- return true;
3914
- }
3915
4504
  if (action === 'copy-prompt') {
3916
4505
  void this.#copyPicked(this.#editor.expandedText, 'current prompt');
3917
4506
  return true;
@@ -3925,23 +4514,29 @@ export class LocalTui {
3925
4514
  this.#startAsyncPaste(this.#pasteClipboard());
3926
4515
  return true;
3927
4516
  }
4517
+ // A queued follow-up is the one action that must still work while the turn
4518
+ // it belongs to is running; Enter is which-turn, this is after-this-turn.
4519
+ if (action === 'follow-up') {
4520
+ if (this.#editor.expandedText.trim() === '')
4521
+ return false;
4522
+ this.#submit(this.#editor.expandedText);
4523
+ return true;
4524
+ }
4525
+ if (action !== 'external-editor')
4526
+ return false;
3928
4527
  try {
3929
- this.#setMouseTracking(false);
3930
- this.#term.output.write('\x1b[?1004l');
3931
- this.#term.input.setRawMode?.(false);
3932
- this.#literalInput ||= this.#editor.startsWithPaste;
3933
- const text = editExternally(this.#editor.expandedText, this.#externalEditor);
3934
- this.#editor.setText(text);
3935
- this.#images.reconcile();
4528
+ this.#handTerminal(() => {
4529
+ this.#literalInput ||= this.#editor.startsWithPaste;
4530
+ const text = editExternally(this.#editor.expandedText, this.#externalEditor);
4531
+ this.#editor.setText(text);
4532
+ this.#images.reconcile();
4533
+ });
3936
4534
  }
3937
4535
  catch (error) {
3938
4536
  this.notice(error instanceof Error ? error.message : String(error), { level: 'error' });
3939
4537
  }
3940
4538
  finally {
3941
4539
  if (!this.#disposed) {
3942
- this.#term.input.setRawMode?.(true);
3943
- this.#term.output.write('\x1b[?1004h');
3944
- this.#renderer.reset();
3945
4540
  this.#refreshAutocomplete();
3946
4541
  this.#render();
3947
4542
  }
@@ -3950,24 +4545,19 @@ export class LocalTui {
3950
4545
  }
3951
4546
  #openPlanFeedbackEditor(prompt) {
3952
4547
  try {
3953
- this.#setMouseTracking(false);
3954
- this.#term.output.write('\x1b[?1004l');
3955
- this.#term.input.setRawMode?.(false);
3956
- const initial = prompt.feedback === true ? this.#editor.expandedText : '';
3957
- const text = editExternally(initial, this.#externalEditor);
3958
- this.#editor.setText(text);
3959
- this.#prompt = { ...prompt, feedback: true };
4548
+ this.#handTerminal(() => {
4549
+ const initial = prompt.feedback === true ? this.#editor.expandedText : '';
4550
+ const text = editExternally(initial, this.#externalEditor);
4551
+ this.#editor.setText(text);
4552
+ this.#prompt = { ...prompt, feedback: true };
4553
+ });
3960
4554
  }
3961
4555
  catch (error) {
3962
4556
  this.notice(error instanceof Error ? error.message : String(error), { level: 'error' });
3963
4557
  }
3964
4558
  finally {
3965
- if (!this.#disposed) {
3966
- this.#term.input.setRawMode?.(true);
3967
- this.#term.output.write('\x1b[?1004h');
3968
- this.#renderer.reset();
4559
+ if (!this.#disposed)
3969
4560
  this.#render();
3970
- }
3971
4561
  }
3972
4562
  }
3973
4563
  #hasComposerContent() {
@@ -4159,6 +4749,22 @@ export class LocalTui {
4159
4749
  return;
4160
4750
  }
4161
4751
  const anchor = this.#viewportBlock();
4752
+ /**
4753
+ * A long command result and a collapsed side answer fold the same way, and
4754
+ * this is the key that opens either. It is answered before the run lookup
4755
+ * because neither is a run: the reader aimed at those rows, not at the run
4756
+ * above them.
4757
+ */
4758
+ const anchored = anchor === undefined ? undefined : this.#state.blocks[anchor];
4759
+ if (anchor !== undefined && (anchored?.kind === 'commandOutput' || anchored?.kind === 'aside')) {
4760
+ if (this.#expandedOutputs.has(anchored))
4761
+ this.#expandedOutputs.delete(anchored);
4762
+ else
4763
+ this.#expandedOutputs.add(anchored);
4764
+ this.#inspect(anchor);
4765
+ this.#render();
4766
+ return;
4767
+ }
4162
4768
  const groups = turnGroups(this.#state).filter(item => !item.live);
4163
4769
  // The answer, changed-file record, and following notices still address
4164
4770
  // their turn when the reader is following the tail.
@@ -4187,11 +4793,6 @@ export class LocalTui {
4187
4793
  this.#render();
4188
4794
  return;
4189
4795
  }
4190
- if (anchor !== undefined && this.#state.blocks[anchor]?.kind === 'toolCatalog') {
4191
- this.#toolsExpanded = !this.#toolsExpanded;
4192
- this.#inspect(anchor);
4193
- this.#render();
4194
- }
4195
4796
  // A live turn already has the process presentation; Alt+O owns tool details.
4196
4797
  }
4197
4798
  #detailScope(group) {
@@ -4254,20 +4855,47 @@ export class LocalTui {
4254
4855
  else
4255
4856
  set.add(key);
4256
4857
  }
4858
+ /**
4859
+ * Every occurrence of the active query, in reading order.
4860
+ *
4861
+ * Stepping needs the same list the painter uses, so it asks the renderer rather
4862
+ * than scanning source text: a hit inside a folded row or a wrapped Markdown
4863
+ * table exists only in the rendered rows.
4864
+ */
4865
+ #searchOccurrences() {
4866
+ const search = this.#transcriptSearch;
4867
+ if (search === null || search.query.trim() === '')
4868
+ return [];
4869
+ const options = {
4870
+ width: this.#term.width(),
4871
+ colors: this.#colors,
4872
+ themeName: this.#themeName,
4873
+ ...(this.#colorDepth === undefined ? {} : { colorDepth: this.#colorDepth }),
4874
+ mathMode: this.#mathMode,
4875
+ toolsExpanded: this.#toolsExpanded,
4876
+ expandedOutputs: this.#expandedOutputs,
4877
+ hideThinking: this.#hideThinking,
4878
+ expandedTools: this.#detailedToolIds(),
4879
+ ...(this.#openedGroups === undefined ? {} : { openedGroups: this.#openedGroups }),
4880
+ };
4881
+ return searchMatches(renderedBlocks(this.#state, options), search.query);
4882
+ }
4257
4883
  /** Fold one event into the active transcript search. */
4258
4884
  #applyTranscriptSearch(event) {
4259
4885
  const state = this.#transcriptSearch;
4260
4886
  if (state === null)
4261
4887
  return;
4262
- const command = applyTranscriptSearchEvent(state, event, this.#state.blocks.map(blockSearchText));
4888
+ const command = applyTranscriptSearchEvent(state, event, this.#searchOccurrences());
4263
4889
  if (command.kind === 'close') {
4264
4890
  this.#transcriptSearch = null;
4265
4891
  this.#render();
4266
4892
  return;
4267
4893
  }
4268
4894
  this.#transcriptSearch = command.state;
4269
- if (command.kind === 'focus')
4270
- this.#focusBlock = command.block;
4895
+ if (command.kind === 'focus') {
4896
+ this.#focusBlock = command.match.block;
4897
+ this.#focusBlockEdge = 'start';
4898
+ }
4271
4899
  this.#render();
4272
4900
  }
4273
4901
  }
@@ -4291,6 +4919,21 @@ export function apply(ctx, config) {
4291
4919
  };
4292
4920
  const tui = new LocalTui(term, config.model, config.colors.get(), config.theme.get(), copyToClipboard, {
4293
4921
  deferInitialRender: true,
4922
+ readImageInput: async (ref, signal) => {
4923
+ const attachments = ctx.get('attachments');
4924
+ if (attachments === undefined)
4925
+ return undefined;
4926
+ const stored = await attachments.readImage(ref, signal);
4927
+ if (stored === undefined)
4928
+ return undefined;
4929
+ return {
4930
+ data: stored.data,
4931
+ mediaType: stored.ref.mediaType,
4932
+ ...(stored.ref.name === undefined ? {} : { name: stored.ref.name }),
4933
+ width: stored.ref.width,
4934
+ height: stored.ref.height,
4935
+ };
4936
+ },
4294
4937
  terminalProfile,
4295
4938
  alternateScreenOverlays: terminalProfile === 'direct',
4296
4939
  herdrReporter: new HerdrAgentReporter({ interactive: term.input.isTTY === true && term.output.isTTY === true }),
@@ -4304,7 +4947,7 @@ export function apply(ctx, config) {
4304
4947
  });
4305
4948
  ctx.provide(TUI_SERVICE, tui);
4306
4949
  ctx.effect(() => () => tui.dispose());
4307
- // A missing route must be visible without turning the welcome card into a
4950
+ // A missing route must be visible without turning the startup header into a
4308
4951
  // credential check: the seams answer optimistically when they cannot tell.
4309
4952
  ctx.inject(['settings', 'credentials'], readyCtx => {
4310
4953
  const refreshModelReady = () => {
@@ -4341,7 +4984,6 @@ export function apply(ctx, config) {
4341
4984
  mathMode: config.mathMode.get(),
4342
4985
  mermaidMode: config.mermaidMode.get(),
4343
4986
  editor: config.editor.get(),
4344
- terminalProgress: config.terminalProgress.get(),
4345
4987
  terminalTitle: config.terminalTitle.get(),
4346
4988
  terminalState: config.terminalState.get(),
4347
4989
  copyOnSelect: config.copyOnSelect.get(),
@@ -4350,7 +4992,6 @@ export function apply(ctx, config) {
4350
4992
  checkUpdates: config.checkUpdates.get(),
4351
4993
  startupChangelog: config.startupChangelog.get(),
4352
4994
  notifications: config.notifications.get(),
4353
- notificationThreshold: config.notificationThreshold.get(),
4354
4995
  notificationFocus: config.notificationFocus.get(),
4355
4996
  };
4356
4997
  const statusBar = config.statusBar.get();