@asterxsk/kiln 0.1.0 → 0.2.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 (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,621 +1,621 @@
1
- /**
2
- * /ps UI — two-stage full-screen overlay over the synchronous
3
- * TerminalReadModel:
4
- * - TerminalDashboard: list of all tracked terminals (select, kill, open).
5
- * - TerminalDetailView: read-only inspector for one terminal — metadata,
6
- * stdout/stderr toggle, scrolling, live tail. No input surface: background
7
- * terminals have no stdin by design.
8
- */
9
-
10
- import type {
11
- ExtensionCommandContext,
12
- KeybindingsManager,
13
- Theme,
14
- } from "@earendil-works/pi-coding-agent";
15
- import { formatSize } from "@earendil-works/pi-coding-agent";
16
- import type { Component, TUI } from "@earendil-works/pi-tui";
17
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
18
- import { formatElapsed, formatExit, type TerminalSnapshot } from "../domain.ts";
19
- import type { TerminalReadModel } from "../manager.ts";
20
- import { createOutputLineCache, sanitizeText } from "./output-view.ts";
21
-
22
- /** One-line-safe rendering of model-provided text (titles, commands): a
23
- * newline or control char inside a fixed-height row desyncs the renderer. */
24
- function oneLine(text: string) {
25
- return sanitizeText(text.replace(/\s+/g, " "));
26
- }
27
-
28
- function configuredKeys(
29
- keybindings: KeybindingsManager,
30
- binding: Parameters<KeybindingsManager["getKeys"]>[0],
31
- ) {
32
- return keybindings.getKeys(binding).join("/") || "unbound";
33
- }
34
-
35
- function statusGlyph(snap: TerminalSnapshot, theme: Theme) {
36
- switch (snap.status) {
37
- case "running":
38
- return theme.fg("warning", "■");
39
- case "done":
40
- return theme.fg("success", "■");
41
- case "failed":
42
- return theme.fg("error", "■");
43
- case "killed":
44
- return theme.fg("muted", "■");
45
- }
46
- }
47
-
48
- function statusWord(snap: TerminalSnapshot, theme: Theme) {
49
- switch (snap.status) {
50
- case "running":
51
- return theme.fg("warning", "running");
52
- case "done":
53
- return theme.fg("success", "done");
54
- case "failed":
55
- return theme.fg("error", "failed");
56
- case "killed":
57
- return theme.fg("muted", "killed");
58
- }
59
- }
60
-
61
- // --- Entry point ---------------------------------------------------------------
62
-
63
- export async function openTerminalPicker(
64
- ctx: ExtensionCommandContext,
65
- view: TerminalReadModel,
66
- ) {
67
- const selection: DashboardSelection = { index: 0 };
68
-
69
- while (true) {
70
- if (view.size() === 0) {
71
- ctx.ui.notify("No background terminals", "info");
72
- return;
73
- }
74
-
75
- const picked = await ctx.ui.custom<string | null>(
76
- (tui, theme, keybindings, done) =>
77
- new TerminalDashboard(tui, theme, keybindings, view, selection, done),
78
- {
79
- overlay: true,
80
- overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
81
- },
82
- );
83
-
84
- if (!picked) return;
85
- if (!view.get(picked)) continue;
86
-
87
- await ctx.ui.custom<null>(
88
- (tui, theme, keybindings, done) =>
89
- new TerminalDetailView(tui, theme, keybindings, picked, view, done),
90
- {
91
- overlay: true,
92
- overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
93
- },
94
- );
95
- // After leaving the detail view, fall back to the dashboard.
96
- }
97
- }
98
-
99
- // --- Dashboard (fullscreen overlay) ----------------------------------------------
100
-
101
- export interface DashboardSelection {
102
- id?: string;
103
- index: number;
104
- }
105
-
106
- export function reconcileDashboardSelection(
107
- selection: DashboardSelection,
108
- terminals: ReadonlyArray<Pick<TerminalSnapshot, "id">>,
109
- ) {
110
- const stableIndex = selection.id
111
- ? terminals.findIndex((snap) => snap.id === selection.id)
112
- : -1;
113
- selection.index =
114
- stableIndex >= 0
115
- ? stableIndex
116
- : Math.min(
117
- Math.max(0, selection.index),
118
- Math.max(0, terminals.length - 1),
119
- );
120
- selection.id = terminals[selection.index]?.id;
121
- }
122
-
123
- class TerminalDashboard implements Component {
124
- private tui: TUI;
125
- private theme: Theme;
126
- private keybindings: KeybindingsManager;
127
- private view: TerminalReadModel;
128
- private selection: DashboardSelection;
129
- private done: (value: string | null) => void;
130
-
131
- private closed = false;
132
- private ticker: ReturnType<typeof setInterval>;
133
- private unsubChange: () => void;
134
-
135
- constructor(
136
- tui: TUI,
137
- theme: Theme,
138
- keybindings: KeybindingsManager,
139
- view: TerminalReadModel,
140
- selection: DashboardSelection,
141
- done: (value: string | null) => void,
142
- ) {
143
- this.tui = tui;
144
- this.theme = theme;
145
- this.keybindings = keybindings;
146
- this.view = view;
147
- this.selection = selection;
148
- this.done = done;
149
- // Elapsed times and output sizes tick along at 1Hz.
150
- this.ticker = setInterval(() => this.tui.requestRender(), 1000);
151
- this.unsubChange = view.subscribe(() => this.tui.requestRender());
152
- }
153
-
154
- private terminals(): ReadonlyArray<TerminalSnapshot> {
155
- return this.view.list();
156
- }
157
-
158
- private cleanup() {
159
- if (this.closed) return false;
160
- this.closed = true;
161
- clearInterval(this.ticker);
162
- this.unsubChange();
163
- return true;
164
- }
165
-
166
- private close(result: string | null) {
167
- if (this.cleanup()) this.done(result);
168
- }
169
-
170
- dispose(): void {
171
- this.cleanup();
172
- }
173
-
174
- handleInput(data: string): void {
175
- const terminals = this.terminals();
176
- reconcileDashboardSelection(this.selection, terminals);
177
-
178
- if (this.keybindings.matches(data, "tui.select.cancel")) {
179
- this.close(null);
180
- return;
181
- }
182
- if (this.keybindings.matches(data, "tui.select.confirm")) {
183
- const snap = terminals[this.selection.index];
184
- if (snap) this.close(snap.id);
185
- return;
186
- }
187
- if (this.keybindings.matches(data, "tui.select.up") || data === "k") {
188
- if (terminals.length > 0) {
189
- this.selection.index =
190
- (this.selection.index - 1 + terminals.length) % terminals.length;
191
- this.selection.id = terminals[this.selection.index]?.id;
192
- this.tui.requestRender();
193
- }
194
- return;
195
- }
196
- if (this.keybindings.matches(data, "tui.select.down") || data === "j") {
197
- if (terminals.length > 0) {
198
- this.selection.index = (this.selection.index + 1) % terminals.length;
199
- this.selection.id = terminals[this.selection.index]?.id;
200
- this.tui.requestRender();
201
- }
202
- return;
203
- }
204
- if (data === "x") {
205
- const snap = terminals[this.selection.index];
206
- if (snap && snap.status === "running") this.view.requestKill(snap.id);
207
- return;
208
- }
209
- }
210
-
211
- private pad(text: string, width: number): string {
212
- const truncated = truncateToWidth(text, width);
213
- return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
214
- }
215
-
216
- private borderSegment(width: number, title: string): string {
217
- const theme = this.theme;
218
- const label = title
219
- ? ` ${truncateToWidth(title, Math.max(0, width - 3))} `
220
- : "";
221
- const labelWidth = visibleWidth(label);
222
- return (
223
- theme.fg("border", "─") +
224
- (label ? theme.fg("text", label) : "") +
225
- theme.fg("border", "─".repeat(Math.max(0, width - 1 - labelWidth)))
226
- );
227
- }
228
-
229
- render(width: number): string[] {
230
- const theme = this.theme;
231
- const terminals = this.terminals();
232
- reconcileDashboardSelection(this.selection, terminals);
233
-
234
- const rows = this.tui.terminal.rows || 30;
235
- // Render exactly terminal rows - 1 so the overlay covers the header,
236
- // chat, editor, and extra footer lines while leaving pi's final footer
237
- // row visible.
238
- const bodyHeight = Math.max(6, rows - 5);
239
- const innerWidth = width - 2;
240
-
241
- const lines: string[] = [];
242
-
243
- // Header: title left, count right
244
- const headerLeft = theme.fg("accent", theme.bold("Background terminals"));
245
- const headerRight = theme.fg(
246
- "muted",
247
- `${terminals.length} terminal${terminals.length === 1 ? "" : "s"}`,
248
- );
249
- const headerPad = Math.max(
250
- 1,
251
- width - visibleWidth(headerLeft) - visibleWidth(headerRight) - 4,
252
- );
253
- lines.push(
254
- truncateToWidth(
255
- ` ${headerLeft}${" ".repeat(headerPad)}${headerRight} `,
256
- width,
257
- ),
258
- );
259
-
260
- // Top border with panel title
261
- const running = terminals.filter((s) => s.status === "running").length;
262
- lines.push(
263
- theme.fg("border", "╭") +
264
- this.borderSegment(
265
- innerWidth,
266
- `terminals · ${running} running / ${terminals.length}`,
267
- ) +
268
- theme.fg("border", "╮"),
269
- );
270
-
271
- // Rows
272
- const divider = theme.fg("border", "│");
273
- const rowLines = this.renderRows(terminals, innerWidth, bodyHeight);
274
- for (let i = 0; i < bodyHeight; i++) {
275
- lines.push(divider + this.pad(rowLines[i] ?? "", innerWidth) + divider);
276
- }
277
-
278
- // Bottom border
279
- lines.push(
280
- theme.fg("border", "╰") +
281
- theme.fg("border", "─".repeat(Math.max(0, innerWidth))) +
282
- theme.fg("border", "╯"),
283
- );
284
-
285
- // Hints
286
- lines.push(
287
- truncateToWidth(
288
- theme.fg(
289
- "dim",
290
- ` ${configuredKeys(this.keybindings, "tui.select.up")}/${configuredKeys(this.keybindings, "tui.select.down")}/jk select · ${configuredKeys(this.keybindings, "tui.select.confirm")} inspect · x kill · ${configuredKeys(this.keybindings, "tui.select.cancel")} close`,
291
- ),
292
- width,
293
- ),
294
- );
295
-
296
- return lines;
297
- }
298
-
299
- private renderRows(
300
- terminals: ReadonlyArray<TerminalSnapshot>,
301
- width: number,
302
- height: number,
303
- ): string[] {
304
- const theme = this.theme;
305
- const out: string[] = [];
306
-
307
- // Scroll window around selection
308
- let start = 0;
309
- if (terminals.length > height) {
310
- start = Math.min(
311
- Math.max(0, this.selection.index - Math.floor(height / 2)),
312
- terminals.length - height,
313
- );
314
- }
315
- const visible = terminals.slice(start, start + height);
316
-
317
- for (let i = 0; i < visible.length; i++) {
318
- const snap = visible[i];
319
- const index = start + i;
320
- const isSelected = index === this.selection.index;
321
-
322
- // Left: marker, status square, title, dim id
323
- const marker = isSelected ? theme.fg("accent", "❯") : " ";
324
- const title = isSelected
325
- ? theme.fg("accent", oneLine(snap.title))
326
- : theme.fg("text", oneLine(snap.title));
327
- const left = ` ${marker} ${statusGlyph(snap, theme)} ${title} ${theme.fg("dim", snap.id)}`;
328
-
329
- // Right: pid · elapsed · exit/status
330
- const dot = theme.fg("dim", " · ");
331
- const rightParts = [
332
- theme.fg("muted", `pid ${snap.pid ?? "?"}`),
333
- theme.fg("muted", formatElapsed(snap)),
334
- snap.status === "running"
335
- ? statusWord(snap, theme)
336
- : theme.fg("muted", formatExit(snap)),
337
- ];
338
- const right = `${rightParts.join(dot)} `;
339
-
340
- const rightWidth = visibleWidth(right);
341
- const leftMax = Math.max(0, width - rightWidth - 2);
342
- const leftTruncated = truncateToWidth(left, leftMax);
343
- const gap = Math.max(2, width - visibleWidth(leftTruncated) - rightWidth);
344
- out.push(truncateToWidth(leftTruncated + " ".repeat(gap) + right, width));
345
- }
346
-
347
- if (start > 0) {
348
- out[0] = truncateToWidth(theme.fg("dim", ` ... ${start} more`), width);
349
- }
350
- if (start + height < terminals.length) {
351
- out[out.length - 1] = truncateToWidth(
352
- theme.fg("dim", ` ... ${terminals.length - start - height} more`),
353
- width,
354
- );
355
- }
356
- return out;
357
- }
358
-
359
- invalidate(): void {}
360
- }
361
-
362
- // --- Detail view (read-only inspector) --------------------------------------------
363
-
364
- const OUTPUT_SCROLL_STEP = 6;
365
-
366
- class TerminalDetailView implements Component {
367
- private tui: TUI;
368
- private theme: Theme;
369
- private keybindings: KeybindingsManager;
370
- private id: string;
371
- private view: TerminalReadModel;
372
- private done: (value: null) => void;
373
-
374
- /** Active output stream shown in the viewport; `t` toggles. */
375
- private stream: "stdout" | "stderr" = "stdout";
376
- /** Scroll offset in lines from the bottom. 0 = pinned to bottom (live tail). */
377
- private scrollOffset = 0;
378
- private lineCache = createOutputLineCache();
379
- private unsubscribe: () => void;
380
- private renderTimer?: ReturnType<typeof setTimeout>;
381
- private ticker: ReturnType<typeof setInterval>;
382
- private closed = false;
383
-
384
- constructor(
385
- tui: TUI,
386
- theme: Theme,
387
- keybindings: KeybindingsManager,
388
- id: string,
389
- view: TerminalReadModel,
390
- done: (value: null) => void,
391
- ) {
392
- this.tui = tui;
393
- this.theme = theme;
394
- this.keybindings = keybindings;
395
- this.id = id;
396
- this.view = view;
397
- this.done = done;
398
- this.unsubscribe = view.subscribeTo(id, () => this.scheduleRender());
399
- // Elapsed time in the header ticks along at 1Hz.
400
- this.ticker = setInterval(() => this.tui.requestRender(), 1000);
401
- }
402
-
403
- private snap(): TerminalSnapshot | undefined {
404
- return this.view.get(this.id);
405
- }
406
-
407
- private scheduleRender() {
408
- if (this.renderTimer) return;
409
- // A chatty process emits a chunk per write. Limit terminal repaints so
410
- // this view cannot starve input handling.
411
- this.renderTimer = setTimeout(() => {
412
- this.renderTimer = undefined;
413
- if (!this.closed) this.tui.requestRender();
414
- }, 50);
415
- }
416
-
417
- private cleanup() {
418
- if (this.closed) return false;
419
- this.closed = true;
420
- this.unsubscribe();
421
- clearInterval(this.ticker);
422
- if (this.renderTimer) clearTimeout(this.renderTimer);
423
- this.renderTimer = undefined;
424
- return true;
425
- }
426
-
427
- private close() {
428
- if (this.cleanup()) this.done(null);
429
- }
430
-
431
- dispose(): void {
432
- this.cleanup();
433
- }
434
-
435
- handleInput(data: string): void {
436
- if (
437
- this.keybindings.matches(data, "app.interrupt") ||
438
- this.keybindings.matches(data, "tui.select.cancel")
439
- ) {
440
- this.close();
441
- return;
442
- }
443
- if (data === "t") {
444
- this.stream = this.stream === "stdout" ? "stderr" : "stdout";
445
- this.lineCache = createOutputLineCache();
446
- this.scrollOffset = 0;
447
- this.tui.requestRender();
448
- return;
449
- }
450
- if (data === "x") {
451
- const snap = this.snap();
452
- if (snap?.status === "running") this.view.requestKill(this.id);
453
- return;
454
- }
455
- if (this.keybindings.matches(data, "tui.editor.cursorUp") || data === "k") {
456
- this.scrollOffset += OUTPUT_SCROLL_STEP;
457
- this.tui.requestRender();
458
- return;
459
- }
460
- if (
461
- this.keybindings.matches(data, "tui.editor.cursorDown") ||
462
- data === "j"
463
- ) {
464
- this.scrollOffset = Math.max(0, this.scrollOffset - OUTPUT_SCROLL_STEP);
465
- this.tui.requestRender();
466
- return;
467
- }
468
- if (this.keybindings.matches(data, "tui.editor.pageUp")) {
469
- this.scrollOffset += this.viewportHeight();
470
- this.tui.requestRender();
471
- return;
472
- }
473
- if (this.keybindings.matches(data, "tui.editor.pageDown")) {
474
- this.scrollOffset = Math.max(
475
- 0,
476
- this.scrollOffset - this.viewportHeight(),
477
- );
478
- this.tui.requestRender();
479
- return;
480
- }
481
- if (data === "g") {
482
- this.scrollOffset = Number.MAX_SAFE_INTEGER; // clamped to top in render
483
- this.tui.requestRender();
484
- return;
485
- }
486
- if (data === "G") {
487
- this.scrollOffset = 0;
488
- this.tui.requestRender();
489
- return;
490
- }
491
- }
492
-
493
- private viewportHeight(): number {
494
- const rows = this.tui.terminal.rows || 30;
495
- // The complete view renders viewport + 8 chrome rows (borders, header,
496
- // command, tab, hints). rows - 9 makes the overlay ~terminal rows - 1.
497
- return Math.max(6, rows - 9);
498
- }
499
-
500
- render(width: number): string[] {
501
- const theme = this.theme;
502
- const border = theme.fg("borderAccent", "─".repeat(Math.max(1, width)));
503
- const lines: string[] = [];
504
- const snap = this.snap();
505
-
506
- if (!snap) {
507
- lines.push(border);
508
- lines.push(theme.fg("dim", `${this.id} is no longer tracked`));
509
- lines.push(border);
510
- return lines;
511
- }
512
-
513
- lines.push(border);
514
- const header =
515
- `${statusGlyph(snap, theme)} ` +
516
- theme.fg("accent", theme.bold(`${snap.id} · ${oneLine(snap.title)}`)) +
517
- theme.fg(
518
- "muted",
519
- ` · ${snap.status} · ${formatElapsed(snap)} · pid ${snap.pid ?? "?"}`,
520
- ) +
521
- (snap.status !== "running"
522
- ? theme.fg("muted", ` · ${formatExit(snap)}`)
523
- : "") +
524
- theme.fg("dim", ` · ${snap.cwd}`);
525
- lines.push(truncateToWidth(header, width));
526
- lines.push(
527
- truncateToWidth(
528
- theme.fg("dim", "$ ") + theme.fg("text", oneLine(snap.command)),
529
- width,
530
- ),
531
- );
532
- lines.push(border);
533
-
534
- // Stream tab line: which stream is active, both sizes.
535
- const active = this.stream;
536
- const viewData = active === "stdout" ? snap.stdout : snap.stderr;
537
- const tab = (name: "stdout" | "stderr", size: number) =>
538
- name === active
539
- ? theme.fg("accent", theme.bold(`${name} (${formatSize(size)})`))
540
- : theme.fg("dim", `${name} (${formatSize(size)})`);
541
- lines.push(
542
- truncateToWidth(
543
- ` ${tab("stdout", snap.stdout.totalBytes)}${theme.fg("dim", " | ")}${tab("stderr", snap.stderr.totalBytes)}${theme.fg("dim", " — t to switch")}`,
544
- width,
545
- ),
546
- );
547
-
548
- // Fixed-height output viewport. Notes and scroll status consume rows
549
- // inside the viewport so streaming/scrolling never changes overlay height.
550
- const buffer = viewData;
551
- const version =
552
- // The cached view text identity changes with the buffer; totalBytes is a
553
- // monotonically increasing proxy for a version counter.
554
- buffer.totalBytes;
555
- const output = this.lineCache.get(buffer.text, version, width - 2);
556
- const viewport = this.viewportHeight();
557
-
558
- const noteRows: string[] = [];
559
- if (snap.errorText) {
560
- noteRows.push(
561
- truncateToWidth(
562
- theme.fg("error", `error: ${oneLine(snap.errorText)}`),
563
- width,
564
- ),
565
- );
566
- }
567
- if (buffer.truncatedBytes > 0) {
568
- noteRows.push(
569
- truncateToWidth(
570
- theme.fg(
571
- "dim",
572
- `first ${formatSize(buffer.truncatedBytes)} dropped from view — full log: ${buffer.spillPath ?? "(unavailable)"}`,
573
- ),
574
- width,
575
- ),
576
- );
577
- }
578
-
579
- const body: string[] = [...noteRows];
580
- const scrollRows = this.scrollOffset > 0 ? 1 : 0;
581
- const capacity = Math.max(1, viewport - body.length - scrollRows);
582
- const maxOffset = Math.max(0, output.length - capacity);
583
- if (this.scrollOffset > maxOffset) this.scrollOffset = maxOffset;
584
-
585
- const end = output.length - this.scrollOffset;
586
- const visible = output.slice(Math.max(0, end - capacity), end);
587
- if (visible.length === 0) {
588
- body.push(theme.fg("dim", `(no ${active} yet)`));
589
- } else {
590
- for (const line of visible) {
591
- body.push(truncateToWidth(` ${line}`, width));
592
- }
593
- }
594
-
595
- if (this.scrollOffset > 0) {
596
- body.push(
597
- truncateToWidth(
598
- theme.fg("dim", `... ${this.scrollOffset} lines below · ↓/pgdn`),
599
- width,
600
- ),
601
- );
602
- }
603
- while (body.length < viewport) body.push("");
604
- lines.push(...body.slice(0, viewport));
605
-
606
- lines.push(border);
607
- lines.push(
608
- truncateToWidth(
609
- theme.fg(
610
- "dim",
611
- `${configuredKeys(this.keybindings, "tui.select.cancel")} back · t stdout/stderr · x kill · ${configuredKeys(this.keybindings, "tui.editor.cursorUp")}/${configuredKeys(this.keybindings, "tui.editor.cursorDown")}/jk scroll · ${configuredKeys(this.keybindings, "tui.editor.pageUp")}/${configuredKeys(this.keybindings, "tui.editor.pageDown")} page · g/G top/bottom`,
612
- ),
613
- width,
614
- ),
615
- );
616
- lines.push(border);
617
- return lines;
618
- }
619
-
620
- invalidate(): void {}
621
- }
1
+ /**
2
+ * /ps UI — two-stage full-screen overlay over the synchronous
3
+ * TerminalReadModel:
4
+ * - TerminalDashboard: list of all tracked terminals (select, kill, open).
5
+ * - TerminalDetailView: read-only inspector for one terminal — metadata,
6
+ * stdout/stderr toggle, scrolling, live tail. No input surface: background
7
+ * terminals have no stdin by design.
8
+ */
9
+
10
+ import type {
11
+ ExtensionCommandContext,
12
+ KeybindingsManager,
13
+ Theme,
14
+ } from "@earendil-works/pi-coding-agent";
15
+ import { formatSize } from "@earendil-works/pi-coding-agent";
16
+ import type { Component, TUI } from "@earendil-works/pi-tui";
17
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
18
+ import { formatElapsed, formatExit, type TerminalSnapshot } from "../domain.ts";
19
+ import type { TerminalReadModel } from "../manager.ts";
20
+ import { createOutputLineCache, sanitizeText } from "./output-view.ts";
21
+
22
+ /** One-line-safe rendering of model-provided text (titles, commands): a
23
+ * newline or control char inside a fixed-height row desyncs the renderer. */
24
+ function oneLine(text: string) {
25
+ return sanitizeText(text.replace(/\s+/g, " "));
26
+ }
27
+
28
+ function configuredKeys(
29
+ keybindings: KeybindingsManager,
30
+ binding: Parameters<KeybindingsManager["getKeys"]>[0],
31
+ ) {
32
+ return keybindings.getKeys(binding).join("/") || "unbound";
33
+ }
34
+
35
+ function statusGlyph(snap: TerminalSnapshot, theme: Theme) {
36
+ switch (snap.status) {
37
+ case "running":
38
+ return theme.fg("warning", "■");
39
+ case "done":
40
+ return theme.fg("success", "■");
41
+ case "failed":
42
+ return theme.fg("error", "■");
43
+ case "killed":
44
+ return theme.fg("muted", "■");
45
+ }
46
+ }
47
+
48
+ function statusWord(snap: TerminalSnapshot, theme: Theme) {
49
+ switch (snap.status) {
50
+ case "running":
51
+ return theme.fg("warning", "running");
52
+ case "done":
53
+ return theme.fg("success", "done");
54
+ case "failed":
55
+ return theme.fg("error", "failed");
56
+ case "killed":
57
+ return theme.fg("muted", "killed");
58
+ }
59
+ }
60
+
61
+ // --- Entry point ---------------------------------------------------------------
62
+
63
+ export async function openTerminalPicker(
64
+ ctx: ExtensionCommandContext,
65
+ view: TerminalReadModel,
66
+ ) {
67
+ const selection: DashboardSelection = { index: 0 };
68
+
69
+ while (true) {
70
+ if (view.size() === 0) {
71
+ ctx.ui.notify("No background terminals", "info");
72
+ return;
73
+ }
74
+
75
+ const picked = await ctx.ui.custom<string | null>(
76
+ (tui, theme, keybindings, done) =>
77
+ new TerminalDashboard(tui, theme, keybindings, view, selection, done),
78
+ {
79
+ overlay: true,
80
+ overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
81
+ },
82
+ );
83
+
84
+ if (!picked) return;
85
+ if (!view.get(picked)) continue;
86
+
87
+ await ctx.ui.custom<null>(
88
+ (tui, theme, keybindings, done) =>
89
+ new TerminalDetailView(tui, theme, keybindings, picked, view, done),
90
+ {
91
+ overlay: true,
92
+ overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
93
+ },
94
+ );
95
+ // After leaving the detail view, fall back to the dashboard.
96
+ }
97
+ }
98
+
99
+ // --- Dashboard (fullscreen overlay) ----------------------------------------------
100
+
101
+ export interface DashboardSelection {
102
+ id?: string;
103
+ index: number;
104
+ }
105
+
106
+ export function reconcileDashboardSelection(
107
+ selection: DashboardSelection,
108
+ terminals: ReadonlyArray<Pick<TerminalSnapshot, "id">>,
109
+ ) {
110
+ const stableIndex = selection.id
111
+ ? terminals.findIndex((snap) => snap.id === selection.id)
112
+ : -1;
113
+ selection.index =
114
+ stableIndex >= 0
115
+ ? stableIndex
116
+ : Math.min(
117
+ Math.max(0, selection.index),
118
+ Math.max(0, terminals.length - 1),
119
+ );
120
+ selection.id = terminals[selection.index]?.id;
121
+ }
122
+
123
+ class TerminalDashboard implements Component {
124
+ private tui: TUI;
125
+ private theme: Theme;
126
+ private keybindings: KeybindingsManager;
127
+ private view: TerminalReadModel;
128
+ private selection: DashboardSelection;
129
+ private done: (value: string | null) => void;
130
+
131
+ private closed = false;
132
+ private ticker: ReturnType<typeof setInterval>;
133
+ private unsubChange: () => void;
134
+
135
+ constructor(
136
+ tui: TUI,
137
+ theme: Theme,
138
+ keybindings: KeybindingsManager,
139
+ view: TerminalReadModel,
140
+ selection: DashboardSelection,
141
+ done: (value: string | null) => void,
142
+ ) {
143
+ this.tui = tui;
144
+ this.theme = theme;
145
+ this.keybindings = keybindings;
146
+ this.view = view;
147
+ this.selection = selection;
148
+ this.done = done;
149
+ // Elapsed times and output sizes tick along at 1Hz.
150
+ this.ticker = setInterval(() => this.tui.requestRender(), 1000);
151
+ this.unsubChange = view.subscribe(() => this.tui.requestRender());
152
+ }
153
+
154
+ private terminals(): ReadonlyArray<TerminalSnapshot> {
155
+ return this.view.list();
156
+ }
157
+
158
+ private cleanup() {
159
+ if (this.closed) return false;
160
+ this.closed = true;
161
+ clearInterval(this.ticker);
162
+ this.unsubChange();
163
+ return true;
164
+ }
165
+
166
+ private close(result: string | null) {
167
+ if (this.cleanup()) this.done(result);
168
+ }
169
+
170
+ dispose(): void {
171
+ this.cleanup();
172
+ }
173
+
174
+ handleInput(data: string): void {
175
+ const terminals = this.terminals();
176
+ reconcileDashboardSelection(this.selection, terminals);
177
+
178
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
179
+ this.close(null);
180
+ return;
181
+ }
182
+ if (this.keybindings.matches(data, "tui.select.confirm")) {
183
+ const snap = terminals[this.selection.index];
184
+ if (snap) this.close(snap.id);
185
+ return;
186
+ }
187
+ if (this.keybindings.matches(data, "tui.select.up") || data === "k") {
188
+ if (terminals.length > 0) {
189
+ this.selection.index =
190
+ (this.selection.index - 1 + terminals.length) % terminals.length;
191
+ this.selection.id = terminals[this.selection.index]?.id;
192
+ this.tui.requestRender();
193
+ }
194
+ return;
195
+ }
196
+ if (this.keybindings.matches(data, "tui.select.down") || data === "j") {
197
+ if (terminals.length > 0) {
198
+ this.selection.index = (this.selection.index + 1) % terminals.length;
199
+ this.selection.id = terminals[this.selection.index]?.id;
200
+ this.tui.requestRender();
201
+ }
202
+ return;
203
+ }
204
+ if (data === "x") {
205
+ const snap = terminals[this.selection.index];
206
+ if (snap && snap.status === "running") this.view.requestKill(snap.id);
207
+ return;
208
+ }
209
+ }
210
+
211
+ private pad(text: string, width: number): string {
212
+ const truncated = truncateToWidth(text, width);
213
+ return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
214
+ }
215
+
216
+ private borderSegment(width: number, title: string): string {
217
+ const theme = this.theme;
218
+ const label = title
219
+ ? ` ${truncateToWidth(title, Math.max(0, width - 3))} `
220
+ : "";
221
+ const labelWidth = visibleWidth(label);
222
+ return (
223
+ theme.fg("border", "─") +
224
+ (label ? theme.fg("text", label) : "") +
225
+ theme.fg("border", "─".repeat(Math.max(0, width - 1 - labelWidth)))
226
+ );
227
+ }
228
+
229
+ render(width: number): string[] {
230
+ const theme = this.theme;
231
+ const terminals = this.terminals();
232
+ reconcileDashboardSelection(this.selection, terminals);
233
+
234
+ const rows = this.tui.terminal.rows || 30;
235
+ // Render exactly terminal rows - 1 so the overlay covers the header,
236
+ // chat, editor, and extra footer lines while leaving pi's final footer
237
+ // row visible.
238
+ const bodyHeight = Math.max(6, rows - 5);
239
+ const innerWidth = width - 2;
240
+
241
+ const lines: string[] = [];
242
+
243
+ // Header: title left, count right
244
+ const headerLeft = theme.fg("accent", theme.bold("Background terminals"));
245
+ const headerRight = theme.fg(
246
+ "muted",
247
+ `${terminals.length} terminal${terminals.length === 1 ? "" : "s"}`,
248
+ );
249
+ const headerPad = Math.max(
250
+ 1,
251
+ width - visibleWidth(headerLeft) - visibleWidth(headerRight) - 4,
252
+ );
253
+ lines.push(
254
+ truncateToWidth(
255
+ ` ${headerLeft}${" ".repeat(headerPad)}${headerRight} `,
256
+ width,
257
+ ),
258
+ );
259
+
260
+ // Top border with panel title
261
+ const running = terminals.filter((s) => s.status === "running").length;
262
+ lines.push(
263
+ theme.fg("border", "╭") +
264
+ this.borderSegment(
265
+ innerWidth,
266
+ `terminals · ${running} running / ${terminals.length}`,
267
+ ) +
268
+ theme.fg("border", "╮"),
269
+ );
270
+
271
+ // Rows
272
+ const divider = theme.fg("border", "│");
273
+ const rowLines = this.renderRows(terminals, innerWidth, bodyHeight);
274
+ for (let i = 0; i < bodyHeight; i++) {
275
+ lines.push(divider + this.pad(rowLines[i] ?? "", innerWidth) + divider);
276
+ }
277
+
278
+ // Bottom border
279
+ lines.push(
280
+ theme.fg("border", "╰") +
281
+ theme.fg("border", "─".repeat(Math.max(0, innerWidth))) +
282
+ theme.fg("border", "╯"),
283
+ );
284
+
285
+ // Hints
286
+ lines.push(
287
+ truncateToWidth(
288
+ theme.fg(
289
+ "dim",
290
+ ` ${configuredKeys(this.keybindings, "tui.select.up")}/${configuredKeys(this.keybindings, "tui.select.down")}/jk select · ${configuredKeys(this.keybindings, "tui.select.confirm")} inspect · x kill · ${configuredKeys(this.keybindings, "tui.select.cancel")} close`,
291
+ ),
292
+ width,
293
+ ),
294
+ );
295
+
296
+ return lines;
297
+ }
298
+
299
+ private renderRows(
300
+ terminals: ReadonlyArray<TerminalSnapshot>,
301
+ width: number,
302
+ height: number,
303
+ ): string[] {
304
+ const theme = this.theme;
305
+ const out: string[] = [];
306
+
307
+ // Scroll window around selection
308
+ let start = 0;
309
+ if (terminals.length > height) {
310
+ start = Math.min(
311
+ Math.max(0, this.selection.index - Math.floor(height / 2)),
312
+ terminals.length - height,
313
+ );
314
+ }
315
+ const visible = terminals.slice(start, start + height);
316
+
317
+ for (let i = 0; i < visible.length; i++) {
318
+ const snap = visible[i];
319
+ const index = start + i;
320
+ const isSelected = index === this.selection.index;
321
+
322
+ // Left: marker, status square, title, dim id
323
+ const marker = isSelected ? theme.fg("accent", "❯") : " ";
324
+ const title = isSelected
325
+ ? theme.fg("accent", oneLine(snap.title))
326
+ : theme.fg("text", oneLine(snap.title));
327
+ const left = ` ${marker} ${statusGlyph(snap, theme)} ${title} ${theme.fg("dim", snap.id)}`;
328
+
329
+ // Right: pid · elapsed · exit/status
330
+ const dot = theme.fg("dim", " · ");
331
+ const rightParts = [
332
+ theme.fg("muted", `pid ${snap.pid ?? "?"}`),
333
+ theme.fg("muted", formatElapsed(snap)),
334
+ snap.status === "running"
335
+ ? statusWord(snap, theme)
336
+ : theme.fg("muted", formatExit(snap)),
337
+ ];
338
+ const right = `${rightParts.join(dot)} `;
339
+
340
+ const rightWidth = visibleWidth(right);
341
+ const leftMax = Math.max(0, width - rightWidth - 2);
342
+ const leftTruncated = truncateToWidth(left, leftMax);
343
+ const gap = Math.max(2, width - visibleWidth(leftTruncated) - rightWidth);
344
+ out.push(truncateToWidth(leftTruncated + " ".repeat(gap) + right, width));
345
+ }
346
+
347
+ if (start > 0) {
348
+ out[0] = truncateToWidth(theme.fg("dim", ` ... ${start} more`), width);
349
+ }
350
+ if (start + height < terminals.length) {
351
+ out[out.length - 1] = truncateToWidth(
352
+ theme.fg("dim", ` ... ${terminals.length - start - height} more`),
353
+ width,
354
+ );
355
+ }
356
+ return out;
357
+ }
358
+
359
+ invalidate(): void {}
360
+ }
361
+
362
+ // --- Detail view (read-only inspector) --------------------------------------------
363
+
364
+ const OUTPUT_SCROLL_STEP = 6;
365
+
366
+ class TerminalDetailView implements Component {
367
+ private tui: TUI;
368
+ private theme: Theme;
369
+ private keybindings: KeybindingsManager;
370
+ private id: string;
371
+ private view: TerminalReadModel;
372
+ private done: (value: null) => void;
373
+
374
+ /** Active output stream shown in the viewport; `t` toggles. */
375
+ private stream: "stdout" | "stderr" = "stdout";
376
+ /** Scroll offset in lines from the bottom. 0 = pinned to bottom (live tail). */
377
+ private scrollOffset = 0;
378
+ private lineCache = createOutputLineCache();
379
+ private unsubscribe: () => void;
380
+ private renderTimer?: ReturnType<typeof setTimeout>;
381
+ private ticker: ReturnType<typeof setInterval>;
382
+ private closed = false;
383
+
384
+ constructor(
385
+ tui: TUI,
386
+ theme: Theme,
387
+ keybindings: KeybindingsManager,
388
+ id: string,
389
+ view: TerminalReadModel,
390
+ done: (value: null) => void,
391
+ ) {
392
+ this.tui = tui;
393
+ this.theme = theme;
394
+ this.keybindings = keybindings;
395
+ this.id = id;
396
+ this.view = view;
397
+ this.done = done;
398
+ this.unsubscribe = view.subscribeTo(id, () => this.scheduleRender());
399
+ // Elapsed time in the header ticks along at 1Hz.
400
+ this.ticker = setInterval(() => this.tui.requestRender(), 1000);
401
+ }
402
+
403
+ private snap(): TerminalSnapshot | undefined {
404
+ return this.view.get(this.id);
405
+ }
406
+
407
+ private scheduleRender() {
408
+ if (this.renderTimer) return;
409
+ // A chatty process emits a chunk per write. Limit terminal repaints so
410
+ // this view cannot starve input handling.
411
+ this.renderTimer = setTimeout(() => {
412
+ this.renderTimer = undefined;
413
+ if (!this.closed) this.tui.requestRender();
414
+ }, 50);
415
+ }
416
+
417
+ private cleanup() {
418
+ if (this.closed) return false;
419
+ this.closed = true;
420
+ this.unsubscribe();
421
+ clearInterval(this.ticker);
422
+ if (this.renderTimer) clearTimeout(this.renderTimer);
423
+ this.renderTimer = undefined;
424
+ return true;
425
+ }
426
+
427
+ private close() {
428
+ if (this.cleanup()) this.done(null);
429
+ }
430
+
431
+ dispose(): void {
432
+ this.cleanup();
433
+ }
434
+
435
+ handleInput(data: string): void {
436
+ if (
437
+ this.keybindings.matches(data, "app.interrupt") ||
438
+ this.keybindings.matches(data, "tui.select.cancel")
439
+ ) {
440
+ this.close();
441
+ return;
442
+ }
443
+ if (data === "t") {
444
+ this.stream = this.stream === "stdout" ? "stderr" : "stdout";
445
+ this.lineCache = createOutputLineCache();
446
+ this.scrollOffset = 0;
447
+ this.tui.requestRender();
448
+ return;
449
+ }
450
+ if (data === "x") {
451
+ const snap = this.snap();
452
+ if (snap?.status === "running") this.view.requestKill(this.id);
453
+ return;
454
+ }
455
+ if (this.keybindings.matches(data, "tui.editor.cursorUp") || data === "k") {
456
+ this.scrollOffset += OUTPUT_SCROLL_STEP;
457
+ this.tui.requestRender();
458
+ return;
459
+ }
460
+ if (
461
+ this.keybindings.matches(data, "tui.editor.cursorDown") ||
462
+ data === "j"
463
+ ) {
464
+ this.scrollOffset = Math.max(0, this.scrollOffset - OUTPUT_SCROLL_STEP);
465
+ this.tui.requestRender();
466
+ return;
467
+ }
468
+ if (this.keybindings.matches(data, "tui.editor.pageUp")) {
469
+ this.scrollOffset += this.viewportHeight();
470
+ this.tui.requestRender();
471
+ return;
472
+ }
473
+ if (this.keybindings.matches(data, "tui.editor.pageDown")) {
474
+ this.scrollOffset = Math.max(
475
+ 0,
476
+ this.scrollOffset - this.viewportHeight(),
477
+ );
478
+ this.tui.requestRender();
479
+ return;
480
+ }
481
+ if (data === "g") {
482
+ this.scrollOffset = Number.MAX_SAFE_INTEGER; // clamped to top in render
483
+ this.tui.requestRender();
484
+ return;
485
+ }
486
+ if (data === "G") {
487
+ this.scrollOffset = 0;
488
+ this.tui.requestRender();
489
+ return;
490
+ }
491
+ }
492
+
493
+ private viewportHeight(): number {
494
+ const rows = this.tui.terminal.rows || 30;
495
+ // The complete view renders viewport + 8 chrome rows (borders, header,
496
+ // command, tab, hints). rows - 9 makes the overlay ~terminal rows - 1.
497
+ return Math.max(6, rows - 9);
498
+ }
499
+
500
+ render(width: number): string[] {
501
+ const theme = this.theme;
502
+ const border = theme.fg("borderAccent", "─".repeat(Math.max(1, width)));
503
+ const lines: string[] = [];
504
+ const snap = this.snap();
505
+
506
+ if (!snap) {
507
+ lines.push(border);
508
+ lines.push(theme.fg("dim", `${this.id} is no longer tracked`));
509
+ lines.push(border);
510
+ return lines;
511
+ }
512
+
513
+ lines.push(border);
514
+ const header =
515
+ `${statusGlyph(snap, theme)} ` +
516
+ theme.fg("accent", theme.bold(`${snap.id} · ${oneLine(snap.title)}`)) +
517
+ theme.fg(
518
+ "muted",
519
+ ` · ${snap.status} · ${formatElapsed(snap)} · pid ${snap.pid ?? "?"}`,
520
+ ) +
521
+ (snap.status !== "running"
522
+ ? theme.fg("muted", ` · ${formatExit(snap)}`)
523
+ : "") +
524
+ theme.fg("dim", ` · ${snap.cwd}`);
525
+ lines.push(truncateToWidth(header, width));
526
+ lines.push(
527
+ truncateToWidth(
528
+ theme.fg("dim", "$ ") + theme.fg("text", oneLine(snap.command)),
529
+ width,
530
+ ),
531
+ );
532
+ lines.push(border);
533
+
534
+ // Stream tab line: which stream is active, both sizes.
535
+ const active = this.stream;
536
+ const viewData = active === "stdout" ? snap.stdout : snap.stderr;
537
+ const tab = (name: "stdout" | "stderr", size: number) =>
538
+ name === active
539
+ ? theme.fg("accent", theme.bold(`${name} (${formatSize(size)})`))
540
+ : theme.fg("dim", `${name} (${formatSize(size)})`);
541
+ lines.push(
542
+ truncateToWidth(
543
+ ` ${tab("stdout", snap.stdout.totalBytes)}${theme.fg("dim", " | ")}${tab("stderr", snap.stderr.totalBytes)}${theme.fg("dim", " — t to switch")}`,
544
+ width,
545
+ ),
546
+ );
547
+
548
+ // Fixed-height output viewport. Notes and scroll status consume rows
549
+ // inside the viewport so streaming/scrolling never changes overlay height.
550
+ const buffer = viewData;
551
+ const version =
552
+ // The cached view text identity changes with the buffer; totalBytes is a
553
+ // monotonically increasing proxy for a version counter.
554
+ buffer.totalBytes;
555
+ const output = this.lineCache.get(buffer.text, version, width - 2);
556
+ const viewport = this.viewportHeight();
557
+
558
+ const noteRows: string[] = [];
559
+ if (snap.errorText) {
560
+ noteRows.push(
561
+ truncateToWidth(
562
+ theme.fg("error", `error: ${oneLine(snap.errorText)}`),
563
+ width,
564
+ ),
565
+ );
566
+ }
567
+ if (buffer.truncatedBytes > 0) {
568
+ noteRows.push(
569
+ truncateToWidth(
570
+ theme.fg(
571
+ "dim",
572
+ `first ${formatSize(buffer.truncatedBytes)} dropped from view — full log: ${buffer.spillPath ?? "(unavailable)"}`,
573
+ ),
574
+ width,
575
+ ),
576
+ );
577
+ }
578
+
579
+ const body: string[] = [...noteRows];
580
+ const scrollRows = this.scrollOffset > 0 ? 1 : 0;
581
+ const capacity = Math.max(1, viewport - body.length - scrollRows);
582
+ const maxOffset = Math.max(0, output.length - capacity);
583
+ if (this.scrollOffset > maxOffset) this.scrollOffset = maxOffset;
584
+
585
+ const end = output.length - this.scrollOffset;
586
+ const visible = output.slice(Math.max(0, end - capacity), end);
587
+ if (visible.length === 0) {
588
+ body.push(theme.fg("dim", `(no ${active} yet)`));
589
+ } else {
590
+ for (const line of visible) {
591
+ body.push(truncateToWidth(` ${line}`, width));
592
+ }
593
+ }
594
+
595
+ if (this.scrollOffset > 0) {
596
+ body.push(
597
+ truncateToWidth(
598
+ theme.fg("dim", `... ${this.scrollOffset} lines below · ↓/pgdn`),
599
+ width,
600
+ ),
601
+ );
602
+ }
603
+ while (body.length < viewport) body.push("");
604
+ lines.push(...body.slice(0, viewport));
605
+
606
+ lines.push(border);
607
+ lines.push(
608
+ truncateToWidth(
609
+ theme.fg(
610
+ "dim",
611
+ `${configuredKeys(this.keybindings, "tui.select.cancel")} back · t stdout/stderr · x kill · ${configuredKeys(this.keybindings, "tui.editor.cursorUp")}/${configuredKeys(this.keybindings, "tui.editor.cursorDown")}/jk scroll · ${configuredKeys(this.keybindings, "tui.editor.pageUp")}/${configuredKeys(this.keybindings, "tui.editor.pageDown")} page · g/G top/bottom`,
612
+ ),
613
+ width,
614
+ ),
615
+ );
616
+ lines.push(border);
617
+ return lines;
618
+ }
619
+
620
+ invalidate(): void {}
621
+ }