@linxiraos/pi-tui 1.4.7 → 1.4.9

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 (172) hide show
  1. package/CHANGELOG.md +28 -109
  2. package/README.md +7 -1
  3. package/dist/types/app-keybindings.d.ts +5 -0
  4. package/dist/types/charts/table-data.d.ts +4 -2
  5. package/dist/types/chat/bash-execution.d.ts +4 -1
  6. package/dist/types/chat/eval-execution.d.ts +2 -0
  7. package/dist/types/chat/execution-shared.d.ts +14 -8
  8. package/dist/types/chat/figure-markdown.d.ts +2 -0
  9. package/dist/types/chat/svg-figure.d.ts +5 -0
  10. package/dist/types/chat/table-chart.d.ts +2 -0
  11. package/dist/types/chat/transcript-render-helpers.d.ts +11 -3
  12. package/dist/types/chrome/dynamic-border.d.ts +6 -0
  13. package/dist/types/chrome/transcript-status.d.ts +2 -2
  14. package/dist/types/components/editor.d.ts +15 -6
  15. package/dist/types/components/image.d.ts +6 -0
  16. package/dist/types/components/loader.d.ts +2 -0
  17. package/dist/types/keybinding-matchers.d.ts +7 -0
  18. package/dist/types/native/describe.d.ts +4 -2
  19. package/dist/types/native/node.d.ts +2 -3
  20. package/dist/types/native/overlay.d.ts +42 -2
  21. package/dist/types/native/state.d.ts +4 -0
  22. package/dist/types/overlays/btw-history-panel.d.ts +15 -0
  23. package/dist/types/overlays/btw-history.d.ts +24 -0
  24. package/dist/types/overlays/btw-inject.d.ts +22 -0
  25. package/dist/types/overlays/btw-panel.d.ts +7 -0
  26. package/dist/types/overlays/hook-editor.d.ts +2 -0
  27. package/dist/types/overlays/jobs-panel.d.ts +4 -0
  28. package/dist/types/overlays/model-browser.d.ts +1 -1
  29. package/dist/types/overlays/session-selector.d.ts +11 -2
  30. package/dist/types/prompt/composer.d.ts +13 -5
  31. package/dist/types/render/render-utils.d.ts +23 -1
  32. package/dist/types/status-line/startup.d.ts +0 -15
  33. package/dist/types/terminal-capabilities.d.ts +1 -1
  34. package/dist/types/theme/symbols.d.ts +3 -1
  35. package/dist/types/theme/theme-class.d.ts +1 -0
  36. package/dist/types/theme/theme.d.ts +1 -1
  37. package/dist/types/theme/tui-adapters.d.ts +2 -0
  38. package/dist/types/thinking.d.ts +8 -6
  39. package/dist/types/tools/ast-grep.d.ts +2 -0
  40. package/dist/types/tools/eval.d.ts +2 -0
  41. package/dist/types/tools/find.d.ts +1 -1
  42. package/dist/types/tools/grouped-file-output.d.ts +100 -19
  43. package/dist/types/tools/hashline-format.d.ts +5 -0
  44. package/dist/types/tools/native-view.d.ts +2 -0
  45. package/dist/types/tools/output-meta.d.ts +27 -0
  46. package/dist/types/tools/read.d.ts +14 -4
  47. package/dist/types/tools/task.d.ts +4 -3
  48. package/dist/types/tools/wait.d.ts +2 -0
  49. package/dist/types/tui.d.ts +12 -0
  50. package/dist/types/utils.d.ts +4 -0
  51. package/package.json +9 -9
  52. package/src/app-keybindings.d.ts +5 -0
  53. package/src/app-keybindings.ts +5 -0
  54. package/src/apps/git/git-tui.ts +10 -17
  55. package/src/apps/git/sidebar.ts +21 -35
  56. package/src/apps/ps-top.ts +4 -12
  57. package/src/charts/chart-plan.ts +0 -29
  58. package/src/charts/table-data.d.ts +4 -2
  59. package/src/charts/table-data.ts +55 -6
  60. package/src/chat/bash-execution.d.ts +4 -1
  61. package/src/chat/bash-execution.ts +20 -9
  62. package/src/chat/chat-transcript-builder.ts +5 -2
  63. package/src/chat/eval-execution.d.ts +2 -0
  64. package/src/chat/eval-execution.ts +14 -7
  65. package/src/chat/execution-shared.d.ts +14 -8
  66. package/src/chat/execution-shared.ts +39 -18
  67. package/src/chat/figure-markdown.d.ts +2 -0
  68. package/src/chat/figure-markdown.ts +6 -4
  69. package/src/chat/read-tool-group.ts +56 -36
  70. package/src/chat/svg-figure.d.ts +5 -0
  71. package/src/chat/svg-figure.ts +55 -16
  72. package/src/chat/table-chart.d.ts +2 -0
  73. package/src/chat/table-chart.ts +19 -2
  74. package/src/chat/transcript-render-helpers.d.ts +11 -3
  75. package/src/chat/transcript-render-helpers.ts +70 -22
  76. package/src/chrome/dynamic-border.d.ts +6 -0
  77. package/src/chrome/dynamic-border.ts +28 -2
  78. package/src/chrome/transcript-status.d.ts +2 -2
  79. package/src/chrome/transcript-status.ts +5 -3
  80. package/src/components/editor.d.ts +15 -6
  81. package/src/components/editor.ts +123 -24
  82. package/src/components/image.d.ts +6 -0
  83. package/src/components/image.ts +13 -0
  84. package/src/components/key-value-list.ts +9 -9
  85. package/src/components/loader.d.ts +2 -0
  86. package/src/components/loader.ts +7 -0
  87. package/src/components/section.ts +1 -9
  88. package/src/components/table.ts +1 -9
  89. package/src/keybinding-matchers.d.ts +7 -0
  90. package/src/keybinding-matchers.ts +13 -0
  91. package/src/native/backend.ts +7 -3
  92. package/src/native/describe.d.ts +4 -2
  93. package/src/native/describe.ts +9 -4
  94. package/src/native/node.d.ts +2 -3
  95. package/src/native/node.ts +2 -3
  96. package/src/native/overlay.d.ts +42 -2
  97. package/src/native/overlay.ts +124 -16
  98. package/src/native/state.d.ts +4 -0
  99. package/src/native/state.ts +25 -5
  100. package/src/overlays/btw-history-panel.ts +106 -14
  101. package/src/overlays/btw-history.ts +65 -0
  102. package/src/overlays/btw-inject.ts +91 -0
  103. package/src/overlays/btw-panel.ts +53 -12
  104. package/src/overlays/extensions/extension-dashboard.ts +7 -8
  105. package/src/overlays/hook-editor.ts +6 -0
  106. package/src/overlays/jobs-panel.ts +82 -22
  107. package/src/overlays/login-dialog.ts +8 -26
  108. package/src/overlays/model-browser.ts +69 -10
  109. package/src/overlays/session-selector.ts +25 -5
  110. package/src/overlays/settings-defs.ts +2 -2
  111. package/src/overlays/tree-selector.ts +83 -27
  112. package/src/overlays/usage-dashboard.ts +4 -6
  113. package/src/prompt/composer.ts +17 -5
  114. package/src/render/code-cell.ts +1 -1
  115. package/src/render/file-list.ts +4 -7
  116. package/src/render/render-utils.d.ts +23 -1
  117. package/src/render/render-utils.ts +38 -6
  118. package/src/setup/scenes/glyph.ts +1 -1
  119. package/src/status-line/startup.ts +36 -70
  120. package/src/terminal-capabilities.d.ts +1 -1
  121. package/src/terminal-capabilities.ts +5 -0
  122. package/src/theme/symbols.d.ts +3 -1
  123. package/src/theme/symbols.ts +16 -9
  124. package/src/theme/theme-class.d.ts +1 -0
  125. package/src/theme/theme-class.ts +15 -3
  126. package/src/theme/theme.d.ts +1 -1
  127. package/src/theme/theme.ts +1 -0
  128. package/src/theme/tui-adapters.d.ts +2 -0
  129. package/src/theme/tui-adapters.ts +8 -3
  130. package/src/thinking.d.ts +8 -6
  131. package/src/thinking.ts +17 -11
  132. package/src/tmux.ts +1 -0
  133. package/src/tools/agent-tree.ts +13 -11
  134. package/src/tools/ask.ts +24 -37
  135. package/src/tools/ast-edit.ts +48 -93
  136. package/src/tools/ast-grep.d.ts +2 -0
  137. package/src/tools/ast-grep.ts +31 -67
  138. package/src/tools/bash.ts +7 -0
  139. package/src/tools/default-renderer.ts +1 -1
  140. package/src/tools/edit.ts +50 -43
  141. package/src/tools/eval.d.ts +2 -0
  142. package/src/tools/eval.ts +2 -0
  143. package/src/tools/fetch.ts +2 -1
  144. package/src/tools/find.d.ts +1 -1
  145. package/src/tools/find.ts +13 -5
  146. package/src/tools/github.ts +14 -46
  147. package/src/tools/glob.ts +2 -1
  148. package/src/tools/grep.ts +47 -277
  149. package/src/tools/grouped-file-output.d.ts +100 -19
  150. package/src/tools/grouped-file-output.ts +414 -103
  151. package/src/tools/hashline-format.d.ts +5 -0
  152. package/src/tools/hashline-format.ts +5 -0
  153. package/src/tools/json-tree.ts +1 -5
  154. package/src/tools/lsp.ts +210 -32
  155. package/src/tools/native-view.d.ts +2 -0
  156. package/src/tools/native-view.ts +11 -5
  157. package/src/tools/output-meta.d.ts +27 -0
  158. package/src/tools/output-meta.ts +68 -4
  159. package/src/tools/proc-render.ts +3 -3
  160. package/src/tools/read.d.ts +14 -4
  161. package/src/tools/read.ts +20 -5
  162. package/src/tools/task.d.ts +4 -3
  163. package/src/tools/task.ts +41 -81
  164. package/src/tools/vibe.ts +4 -4
  165. package/src/tools/wait.d.ts +2 -0
  166. package/src/tools/wait.ts +8 -5
  167. package/src/tools/write.ts +17 -27
  168. package/src/tools/yield.ts +1 -1
  169. package/src/tui.d.ts +12 -0
  170. package/src/tui.ts +91 -9
  171. package/src/utils.d.ts +4 -0
  172. package/src/utils.ts +10 -0
@@ -1,10 +1,21 @@
1
1
  import * as path from "node:path";
2
2
 
3
- import { buildPathTree, isUrlLikePath, type PathTreeInput, walkPathTree } from "@linxiraos/pi-utils";
3
+ import {
4
+ buildPathTree,
5
+ isRecord,
6
+ isUrlLikePath,
7
+ type PathTreeInput,
8
+ sanitizeText,
9
+ walkPathTree,
10
+ } from "@linxiraos/pi-utils";
4
11
  import type { TspTone } from "@linxiraos/pi-wire";
5
- import { code, col, keyed, span, text } from "../native/describe";
12
+ import { code, col, keyed } from "../native/describe";
6
13
  import type { NativeNode } from "../native/node";
7
- import { formatHashlineHeader } from "./hashline-format";
14
+ import { getLanguageFromPath } from "../lang-from-path";
15
+ import { fileHyperlink, uriHyperlink } from "../render/hyperlink";
16
+ import { FILE_NAME_COLOR, formatMoreItems, formatStyledPath, replaceTabs } from "../render/render-utils";
17
+ import { highlightCode, isHighlightLanguage, type Theme, type ThemeColor } from "../theme/theme";
18
+ import { formatHashlineHeader, HASHLINE_TAG_SUFFIX_RE } from "./hashline-format";
8
19
  import { fileRow } from "./native-view";
9
20
 
10
21
  // =============================================================================
@@ -148,20 +159,37 @@ export function formatFileMatches(
148
159
 
149
160
  const GROUPED_HEADER_RE = /^(#+)\s+(.*)$/;
150
161
  const HEADER_SUFFIX_RE = /\s+\([^)]*\)\s*$/;
151
- const HEADER_HASH_TAG_RE = /#[0-9a-f]+$/i;
162
+ /** `*12│text`, ` 12|text`, `*12:text`: optional match marker, line number, gutter, content. */
163
+ const GROUPED_NUMBERED_LINE_RE = /^\s*(\*?)(\d+)(?:│|[:|])(.*)$/;
164
+ const GROUPED_MATCH_ROW_RE = /^\s*\*\d+(?:│|[:|])/;
165
+
166
+ /** Whether a row of grouped output is a code-frame row the search matched (`*12│…`). */
167
+ export function isMatchRow(line: string): boolean {
168
+ return GROUPED_MATCH_ROW_RE.test(line);
169
+ }
152
170
 
153
- /** Per-line classification of grouped output, used by renderers for hyperlinks. */
171
+ /** Per-line classification of grouped output, used by renderers for file rows and hyperlinks. */
154
172
  export interface GroupedLineContext {
155
173
  /** Directory header, file header, or any non-header body/content line. */
156
174
  kind: "dir" | "file" | "content";
157
175
  /** Number of leading `#` for headers; 0 for content lines. */
158
176
  depth: number;
159
- /** Resolved absolute path of the dir/file a header points at (when resolvable). */
177
+ /** Resolved absolute path of the file a header points at (when resolvable). */
160
178
  headerPath?: string;
179
+ /**
180
+ * For file headers, the full display path: the folded directory chain joined
181
+ * with the name, without `#` markers or the hashline tag.
182
+ */
183
+ displayPath?: string;
184
+ /** For file headers, a trailing parenthesized note such as `(2 replacements)`. */
185
+ suffix?: string;
161
186
  /** For content lines, the absolute path of the owning file (line hyperlinks). */
162
187
  filePath?: string;
163
- /** Header is an internal/url-like target the caller resolves itself. */
164
- isUrl?: boolean;
188
+ /**
189
+ * The internal or url-like target, as written, that a header names or a
190
+ * content line belongs to; the caller resolves it (no filesystem path).
191
+ */
192
+ url?: string;
165
193
  }
166
194
 
167
195
  function resolveGroupedPath(parent: string | undefined, name: string): string | undefined {
@@ -174,7 +202,8 @@ function resolveGroupedPath(parent: string | undefined, name: string): string |
174
202
 
175
203
  /**
176
204
  * Walk grouped output lines, tracking a directory stack keyed by header depth, so
177
- * each header and body line can be linked back to its absolute filesystem path.
205
+ * each header and body line can be linked back to its absolute filesystem path
206
+ * and each file header to its full display path.
178
207
  * Reconstruction is stack-based (not per-blank-group) so nested directory headers
179
208
  * resolve correctly across the whole output.
180
209
  *
@@ -183,7 +212,9 @@ function resolveGroupedPath(parent: string | undefined, name: string): string |
183
212
  * formatted relative to cwd regardless of the (sub)directory the search was
184
213
  * scoped to. `fileScope` is the initial owning file for body lines that appear
185
214
  * before any header (single-file scopes have no `#` headers); it defaults to
186
- * `headerBase` and should be passed the scoped file's absolute path.
215
+ * `headerBase` and should be passed the scoped file's absolute path. A URL base
216
+ * or scope (`local://…`) is no filesystem path: headerless lines belong to the
217
+ * URL, and headers under a URL base get no path.
187
218
  */
188
219
  export function classifyGroupedLines(
189
220
  lines: readonly string[],
@@ -191,49 +222,224 @@ export function classifyGroupedLines(
191
222
  fileScope: string | undefined = headerBase,
192
223
  ): GroupedLineContext[] {
193
224
  const result: GroupedLineContext[] = [];
194
- const dirAtDepth = new Map<number, string>();
195
- // Body lines before any header (single-file scopes) link to the scoped file.
196
- let currentFile = fileScope;
197
-
198
- const clearDeeper = (depth: number) => {
199
- for (const key of dirAtDepth.keys()) {
200
- if (key >= depth) dirAtDepth.delete(key);
201
- }
202
- };
225
+ const base = headerBase !== undefined && isUrlLikePath(headerBase) ? undefined : headerBase;
226
+ // Per depth (index `depth - 1`): each directory's absolute path, and its display
227
+ // name with the trailing `/`, so the `# /` root of absolute paths keeps its separator.
228
+ const dirAtDepth: (string | undefined)[] = [];
229
+ const displayDirAtDepth: string[] = [];
230
+ // Body lines before any header (single-file scopes) belong to the scoped file or URL.
231
+ const scopeIsUrl = fileScope !== undefined && isUrlLikePath(fileScope);
232
+ let currentFile = scopeIsUrl ? undefined : fileScope;
233
+ let currentUrl = scopeIsUrl ? fileScope : undefined;
203
234
 
204
235
  for (const line of lines) {
205
236
  const match = GROUPED_HEADER_RE.exec(line);
206
237
  if (!match) {
207
- result.push({ kind: "content", depth: 0, filePath: currentFile });
238
+ result.push({ kind: "content", depth: 0, filePath: currentFile, url: currentUrl });
208
239
  continue;
209
240
  }
210
241
  const depth = match[1]!.length;
211
242
  const rest = match[2]!.trimEnd();
212
- if (isUrlLikePath(rest)) {
213
- clearDeeper(depth);
214
- currentFile = undefined;
215
- result.push({ kind: "file", depth, isUrl: true });
243
+ const parent = depth > 1 ? dirAtDepth[depth - 2] : base;
244
+ const url = isUrlLikePath(rest);
245
+ dirAtDepth.length = displayDirAtDepth.length = depth - 1;
246
+ currentFile = currentUrl = undefined;
247
+ if (!url && rest.endsWith("/")) {
248
+ // Directory headers are always `name/`: a trailing `(…)` is part of the name, not a suffix.
249
+ const name = rest.slice(0, -1);
250
+ dirAtDepth.push(resolveGroupedPath(parent, name));
251
+ displayDirAtDepth.push(`${name}/`);
252
+ result.push({ kind: "dir", depth });
216
253
  continue;
217
254
  }
218
- const parent = depth > 1 ? dirAtDepth.get(depth - 1) : headerBase;
219
- if (rest.endsWith("/")) {
220
- const name = rest.slice(0, -1).replace(HEADER_SUFFIX_RE, "");
221
- const abs = resolveGroupedPath(parent, name);
222
- clearDeeper(depth);
223
- if (abs !== undefined) dirAtDepth.set(depth, abs);
224
- currentFile = undefined;
225
- result.push({ kind: "dir", depth, headerPath: abs });
255
+ const suffix = HEADER_SUFFIX_RE.exec(rest);
256
+ const target = suffix ? rest.slice(0, suffix.index) : rest;
257
+ const name = target.replace(HASHLINE_TAG_SUFFIX_RE, "");
258
+ const note = suffix?.[0].trim();
259
+ if (url) {
260
+ currentUrl = target;
261
+ result.push({ kind: "file", depth, url: target, displayPath: name, suffix: note });
226
262
  continue;
227
263
  }
228
- const name = rest.replace(HEADER_SUFFIX_RE, "").replace(HEADER_HASH_TAG_RE, "");
229
- const abs = name ? resolveGroupedPath(parent, name) : undefined;
230
- currentFile = abs;
231
- result.push({ kind: "file", depth, headerPath: abs });
264
+ currentFile = name ? resolveGroupedPath(parent, name) : undefined;
265
+ const displayPath = displayDirAtDepth.join("") + name;
266
+ result.push({ kind: "file", depth, headerPath: currentFile, displayPath, suffix: note });
232
267
  }
233
268
 
234
269
  return result;
235
270
  }
236
271
 
272
+ /**
273
+ * Line groups with one file per group, for terminal tree lists: `# dir/`
274
+ * header rows are dropped (each file row carries its full path), and every
275
+ * file row starts a group of its own, so each file gets its own branch instead
276
+ * of hanging under the previous file of its directory. Rows before a group's
277
+ * first file row (notes, a single-file scope's matches) keep their group.
278
+ */
279
+ export function groupsByFile(
280
+ groups: readonly (readonly number[])[],
281
+ contexts: readonly GroupedLineContext[],
282
+ ): number[][] {
283
+ const result: number[][] = [];
284
+ for (const group of groups) {
285
+ let current: number[] = [];
286
+ for (const index of group) {
287
+ const kind = contexts[index]!.kind;
288
+ if (kind === "dir") continue;
289
+ if (kind === "file" && current.length > 0) {
290
+ result.push(current);
291
+ current = [];
292
+ }
293
+ current.push(index);
294
+ }
295
+ if (current.length > 0) result.push(current);
296
+ }
297
+ return result;
298
+ }
299
+
300
+ function stringField(record: Record<string, unknown>, key: string): string | undefined {
301
+ const value = record[key];
302
+ return typeof value === "string" ? value : undefined;
303
+ }
304
+
305
+ function stringRecordField(record: Record<string, unknown>, key: string): Record<string, string> | undefined {
306
+ const value = record[key];
307
+ if (!isRecord(value)) return undefined;
308
+ for (const entry in value) if (typeof value[entry] !== "string") return undefined;
309
+ return value as Record<string, string>;
310
+ }
311
+
312
+ /** Details fields a grouped-output tool records for links: the display base paths and resolved URL targets. */
313
+ export interface GroupedLinkDetails {
314
+ cwd?: string;
315
+ searchPath?: string;
316
+ displayTargets?: Record<string, string>;
317
+ }
318
+
319
+ /**
320
+ * Link targets for the rows of sanitized grouped output: a file row's file, a
321
+ * body row's owning file, and for an internal URL the file `displayTargets`
322
+ * resolves it to. Destinations keep the original path bytes: while the raw
323
+ * `displayContent` still aligns line-for-line with the sanitized `displayText`,
324
+ * a row takes its raw classification's target. Raw text never links a row the
325
+ * sanitized output leaves unlinked.
326
+ */
327
+ export function groupedLinkTargets(
328
+ contexts: readonly GroupedLineContext[],
329
+ displayText: string,
330
+ details: GroupedLinkDetails | undefined,
331
+ rawDetails: unknown,
332
+ ): (index: number) => string | undefined {
333
+ const targetOf = (ctx: GroupedLineContext, urlTargets: Record<string, string> | undefined) =>
334
+ (ctx.kind === "file" ? ctx.headerPath : ctx.filePath) ?? (ctx.url ? urlTargets?.[ctx.url] : undefined);
335
+ // Detail sanitization keeps record keys raw; the display rows carry sanitized URLs.
336
+ const displayTargets = details?.displayTargets
337
+ ? Object.fromEntries(Object.entries(details.displayTargets).map(([url, file]) => [sanitizeText(url), file]))
338
+ : undefined;
339
+ const raw = rawDetails !== details && isRecord(rawDetails) ? rawDetails : undefined;
340
+ const rawContent = raw && stringField(raw, "displayContent");
341
+ const rawLines = rawContent?.split("\n");
342
+ const rawContexts =
343
+ raw && rawLines?.length === contexts.length && sanitizeText(rawContent!) === displayText
344
+ ? classifyGroupedLines(
345
+ rawLines,
346
+ stringField(raw, "cwd") ?? stringField(raw, "searchPath"),
347
+ stringField(raw, "searchPath"),
348
+ )
349
+ : undefined;
350
+ const rawTargets = raw && stringRecordField(raw, "displayTargets");
351
+ return index => {
352
+ const ctx = contexts[index]!;
353
+ const target = targetOf(ctx, displayTargets);
354
+ const rawContext = rawContexts?.[index];
355
+ if (!target || rawContext?.kind !== ctx.kind || rawContext.depth !== ctx.depth) return target;
356
+ return targetOf(rawContext, rawTargets) ?? target;
357
+ };
358
+ }
359
+
360
+ /**
361
+ * A memoized styler for the rows of grouped output, so a collapsed preview
362
+ * styles only the rows it shows. A file row is its full path (dim directory,
363
+ * name in {@link FILE_NAME_COLOR}; a URL whole in that color) and any dim
364
+ * suffix, linked to `linkTarget`'s file or, for an unresolved URL, the URL.
365
+ * Body rows come from `styleBody`, tabs expanded; with `linkLines` a numbered
366
+ * code-frame row links to its line in the owning file.
367
+ */
368
+ export function createGroupedRowStyler(
369
+ lines: readonly string[],
370
+ contexts: readonly GroupedLineContext[],
371
+ theme: Theme,
372
+ options: {
373
+ linkTarget: (index: number) => string | undefined;
374
+ styleBody: (index: number) => string;
375
+ linkLines?: boolean;
376
+ },
377
+ ): (index: number) => string {
378
+ const styled: string[] = [];
379
+ return index => {
380
+ const cached = styled[index];
381
+ if (cached !== undefined) return cached;
382
+ const ctx = contexts[index]!;
383
+ const target = options.linkTarget(index);
384
+ let row: string;
385
+ if (ctx.kind === "file") {
386
+ const name = replaceTabs(ctx.displayPath ?? "");
387
+ const label = ctx.url ? theme.fg(FILE_NAME_COLOR, name) : formatStyledPath(name, theme);
388
+ const suffix = ctx.suffix ? ` ${theme.fg("dim", replaceTabs(ctx.suffix))}` : "";
389
+ const linked = target ? fileHyperlink(target, label) : ctx.url ? uriHyperlink(ctx.url, label) : label;
390
+ row = linked + suffix;
391
+ } else {
392
+ row = replaceTabs(options.styleBody(index));
393
+ const line = options.linkLines && target ? GROUPED_NUMBERED_LINE_RE.exec(lines[index]!)?.[2] : undefined;
394
+ if (line) row = fileHyperlink(target!, row, { line: Number(line) });
395
+ }
396
+ styled[index] = row;
397
+ return row;
398
+ };
399
+ }
400
+
401
+ /**
402
+ * Fit line groups (one file each) into `budget` rows, the `… N more` summary row
403
+ * included: whole groups first, then the next group cut short when it can still
404
+ * show a row under its file row (the first group always shows its head). The
405
+ * summary counts the `unit`s left out, the rows `isUnit` accepts, out of `total`
406
+ * when the caller knows it; with none left out it counts hidden lines. `gap`
407
+ * rows separate shown groups (framed lists put a blank line between files).
408
+ */
409
+ export function fitGroupsToBudget(
410
+ groups: readonly (readonly number[])[],
411
+ budget: number,
412
+ options: { isUnit: (index: number) => boolean; unit: string; total?: number; gap?: number },
413
+ ): { shown: (readonly number[])[]; summary: string } {
414
+ const gap = options.gap ?? 0;
415
+ let totalLines = Math.max(groups.length - 1, 0) * gap;
416
+ for (const group of groups) totalLines += group.length;
417
+ if (totalLines <= budget) return { shown: [...groups], summary: "" };
418
+ if (budget <= 0) return { shown: [], summary: "" };
419
+
420
+ const room = budget - 1;
421
+ const shown: (readonly number[])[] = [];
422
+ let used = 0;
423
+ let shownUnits = 0;
424
+ for (const group of groups) {
425
+ const lead = shown.length > 0 ? gap : 0;
426
+ const take = Math.min(group.length, room - used - lead);
427
+ if (take <= 0 || (take < Math.min(group.length, 2) && shown.length > 0)) break;
428
+ const part = take === group.length ? group : group.slice(0, take);
429
+ shown.push(part);
430
+ used += lead + take;
431
+ for (const index of part) if (options.isUnit(index)) shownUnits++;
432
+ if (part !== group) break;
433
+ }
434
+
435
+ let allUnits = options.total ?? 0;
436
+ if (!allUnits) for (const group of groups) for (const index of group) if (options.isUnit(index)) allUnits++;
437
+ const hiddenUnits = allUnits - shownUnits;
438
+ if (hiddenUnits > 0) return { shown, summary: formatMoreItems(hiddenUnits, options.unit) };
439
+ const hiddenLines = totalLines - used;
440
+ return { shown, summary: hiddenLines > 0 ? formatMoreItems(hiddenLines, "line") : "" };
441
+ }
442
+
237
443
  /**
238
444
  * Split line indices into blank-line-separated groups, mirroring
239
445
  * `splitGroupsByBlankLine`: when any blank line is present, break on runs of
@@ -266,6 +472,129 @@ export function groupLineIndicesByBlank(rawLines: readonly string[]): number[][]
266
472
  return groups;
267
473
  }
268
474
 
475
+ // =============================================================================
476
+ // Code frames highlighted in their file's language (TUI renderers)
477
+ // =============================================================================
478
+
479
+ /** A code-frame row split after its rule: the gutter (match marker, line number, rule) and the source line. */
480
+ interface CodeFrameRow {
481
+ gutter: string;
482
+ source: string;
483
+ }
484
+
485
+ /**
486
+ * Draw the code-frame rows of consecutive source lines: each gutter in
487
+ * `color`, the sources highlighted in `lang` as one run, so a multi-line
488
+ * string or comment keeps its colors. Without a language the sources take
489
+ * `color` too.
490
+ */
491
+ function renderCodeFrameRun(
492
+ rows: readonly CodeFrameRow[],
493
+ lang: string | undefined,
494
+ color: ThemeColor,
495
+ theme: Theme,
496
+ ): string[] {
497
+ const sources = rows.map(row => replaceTabs(row.source));
498
+ const highlighted = isHighlightLanguage(lang) ? highlightCode(sources.join("\n"), lang, theme) : undefined;
499
+ return rows.map((row, index) => {
500
+ const source = highlighted?.[index] ?? theme.fg(color, sources[index]!);
501
+ return `${theme.fg(color, row.gutter)}${source}`;
502
+ });
503
+ }
504
+
505
+ /** A numbered code-frame row of search output, with its line number. */
506
+ interface NumberedCodeFrame {
507
+ row: CodeFrameRow;
508
+ n: number;
509
+ }
510
+
511
+ function parseNumberedCodeFrame(line: string): NumberedCodeFrame | undefined {
512
+ const match = GROUPED_NUMBERED_LINE_RE.exec(line);
513
+ if (!match) return undefined;
514
+ const source = match[3]!;
515
+ return { row: { gutter: line.slice(0, line.length - source.length), source }, n: Number(match[2]) };
516
+ }
517
+
518
+ /**
519
+ * Source rows highlighted together. A run longer than this (a huge AST match) highlights chunk by chunk as rows
520
+ * are requested, so a collapsed view never tokenizes source it hides; a string or comment spanning a chunk
521
+ * boundary loses its continuation there.
522
+ */
523
+ const CODE_FRAME_CHUNK_ROWS = 64;
524
+
525
+ /**
526
+ * Styled code-frame rows of grouped search output, highlighted in each owning
527
+ * file's language (`lang` overrides it when the highlighter knows it). A run of
528
+ * consecutive line numbers in one file highlights together on its first
529
+ * request; a gap row, a jump in line numbers or another file starts a new run.
530
+ * Rows without a numbered code frame (headers, gap rows, notes) return
531
+ * undefined, for the caller to style.
532
+ */
533
+ export function createCodeFrameStyler(
534
+ lines: readonly string[],
535
+ contexts: readonly GroupedLineContext[],
536
+ color: ThemeColor,
537
+ theme: Theme,
538
+ lang?: string,
539
+ ): (index: number) => string | undefined {
540
+ // Each body row's language: the override, else its owning file's, from the resolved path or its header's name.
541
+ const langOverride = isHighlightLanguage(lang) ? lang : undefined;
542
+ const langs: (string | undefined)[] = [];
543
+ let headerLang: string | undefined;
544
+ for (let index = 0; index < lines.length; index++) {
545
+ const ctx = contexts[index]!;
546
+ if (ctx.kind === "content") {
547
+ langs.push(langOverride ?? (ctx.filePath ? getLanguageFromPath(ctx.filePath) : headerLang));
548
+ continue;
549
+ }
550
+ headerLang = ctx.kind === "file" ? getLanguageFromPath(ctx.displayPath ?? "") : undefined;
551
+ langs.push(undefined);
552
+ }
553
+
554
+ const frames: (NumberedCodeFrame | null)[] = [];
555
+ const frameAt = (index: number): NumberedCodeFrame | null => {
556
+ let frame = frames[index];
557
+ if (frame === undefined) {
558
+ frame = contexts[index]!.kind === "content" ? (parseNumberedCodeFrame(lines[index]!) ?? null) : null;
559
+ frames[index] = frame;
560
+ }
561
+ return frame;
562
+ };
563
+ // Whether the row at `index` continues the run of the row above it.
564
+ const continuesRun = (index: number): boolean => {
565
+ if (index <= 0 || langs[index] !== langs[index - 1]) return false;
566
+ const frame = frameAt(index);
567
+ const above = frameAt(index - 1);
568
+ return frame !== null && above !== null && frame.n === above.n + 1;
569
+ };
570
+ // First row of each row's run, memoized so walking back through a long run happens once.
571
+ const runStarts: number[] = [];
572
+ const runStartOf = (index: number): number => {
573
+ let row = index;
574
+ while (runStarts[row] === undefined && continuesRun(row)) row--;
575
+ const start = runStarts[row] ?? row;
576
+ for (let filled = row; filled <= index; filled++) runStarts[filled] = start;
577
+ return start;
578
+ };
579
+
580
+ const styled: string[] = [];
581
+ return index => {
582
+ if (frameAt(index) === null) return undefined;
583
+ const cached = styled[index];
584
+ if (cached !== undefined) return cached;
585
+ const runStart = runStartOf(index);
586
+ const start = runStart + Math.floor((index - runStart) / CODE_FRAME_CHUNK_ROWS) * CODE_FRAME_CHUNK_ROWS;
587
+ let end = index + 1;
588
+ while (end < start + CODE_FRAME_CHUNK_ROWS && end < lines.length && continuesRun(end)) end++;
589
+ const chunkRows: CodeFrameRow[] = [];
590
+ for (let row = start; row < end; row++) chunkRows.push(frameAt(row)!.row);
591
+ renderCodeFrameRun(chunkRows, langs[index], color, theme).forEach((row, offset) => {
592
+ styled[start + offset] = row;
593
+ });
594
+ return styled[index];
595
+ };
596
+ }
597
+
269
598
  // =============================================================================
270
599
  // Native (TSP) description of grouped output
271
600
  // =============================================================================
@@ -278,38 +607,27 @@ export type GroupedOutputEvent =
278
607
 
279
608
  /**
280
609
  * Walk grouped output (`# dir/`, `## file.ts (suffix)`, body lines), resolving
281
- * each file header to its full display path (the folded directory chain
282
- * joined with the name) and dropping blank separator lines.
610
+ * each file header to its full display path (see {@link classifyGroupedLines})
611
+ * and dropping blank separator lines.
283
612
  */
284
613
  export function* walkGroupedOutput(lines: readonly string[]): Generator<GroupedOutputEvent> {
285
- const dirAtDepth: string[] = [];
286
- for (const line of lines) {
287
- const header = GROUPED_HEADER_RE.exec(line);
288
- if (!header) {
289
- if (line.trim().length > 0) yield { kind: "line", text: line };
290
- continue;
291
- }
292
- const depth = header[1]!.length;
293
- const rest = header[2]!.trimEnd();
294
- dirAtDepth.length = depth - 1;
295
- if (rest.endsWith("/") && !isUrlLikePath(rest)) {
296
- dirAtDepth[depth - 1] = rest.slice(0, -1).replace(HEADER_SUFFIX_RE, "");
614
+ const contexts = classifyGroupedLines(lines, undefined);
615
+ for (const [index, ctx] of contexts.entries()) {
616
+ if (ctx.kind === "dir") {
297
617
  yield { kind: "dir" };
298
- continue;
618
+ } else if (ctx.kind === "file") {
619
+ yield { kind: "file", path: ctx.displayPath ?? "", suffix: ctx.suffix };
620
+ } else {
621
+ const text = lines[index]!;
622
+ if (text.trim().length > 0) yield { kind: "line", text };
299
623
  }
300
- const suffix = HEADER_SUFFIX_RE.exec(rest)?.[0].trim();
301
- const name = rest.replace(HEADER_SUFFIX_RE, "").replace(HEADER_HASH_TAG_RE, "");
302
- const prefix = dirAtDepth.filter(Boolean).join("/");
303
- yield { kind: "file", path: prefix ? `${prefix}/${name}` : name, suffix };
304
624
  }
305
625
  }
306
626
 
307
- /** `*12│text`, ` 12|text`, `*12:text`: optional match marker, line number, gutter, content. */
308
- const GROUPED_NUMBERED_LINE_RE = /^\s*(\*?)(\d+)(?:│|[:|])(.*)$/;
309
- /** ` │...`: grep's gap between non-adjacent context runs (drawn as {@link numberedCode}'s `…` row). */
627
+ /** ` │...`: grep's gap between non-adjacent context runs (Tern draws it from the jump in {@link numberedCode}'s numbers). */
310
628
  const GROUPED_GAP_LINE_RE = /^\s*│\.\.\.$/;
311
629
 
312
- /** One source line for {@link numberedCode}: its number (`null` for an elision marker), text and match mark. */
630
+ /** One source line for {@link numberedCode}: its number (`null` for an elision marker, which adds no line), text and match mark. */
313
631
  export interface NumberedLine {
314
632
  n: number | null;
315
633
  text: string;
@@ -317,58 +635,52 @@ export interface NumberedLine {
317
635
  }
318
636
 
319
637
  /**
320
- * Numbered `code` for possibly non-contiguous source lines: one block per run
321
- * of consecutive line numbers (`start` = the run's first line, match lines
322
- * `mark`ed), with a `…` row wherever the numbers jump or an elision marker
323
- * (`n: null`) sits. `path` is the file the lines come from: Tern picks their
324
- * grammar from it and draws no header (the row or head above names the file).
325
- * `wrap` soft-wraps long lines instead of scrolling the block sideways.
638
+ * One numbered `code` block for possibly non-contiguous source lines (match
639
+ * lines `mark`ed by their line number): `start` when the numbers run on
640
+ * consecutively, else `nums` (each line's number), from whose jumps Tern draws
641
+ * the `…` gap rows in the gutter. Elision markers (`n: null`) add no line; the
642
+ * numbers jump around them. `path` is the file the lines come from: Tern picks
643
+ * their grammar from it and draws no header (the row or head above names the
644
+ * file). `wrap` soft-wraps long lines instead of scrolling the block sideways.
645
+ * `undefined` when no line is numbered.
326
646
  */
327
647
  export function numberedCode(
328
648
  lines: readonly NumberedLine[],
329
649
  opts: { path?: string; wrap?: boolean } = {},
330
- ): NativeNode[] {
331
- const out: NativeNode[] = [];
332
- let run: { start: number; text: string[]; marks: { line: number; tone: TspTone }[] } | undefined;
333
- const flush = () => {
334
- if (!run) return;
335
- // The quiet `…` row between two non-adjacent runs.
336
- if (out.length > 0) out.push(keyed(text([span("…", "dim")], { wrap: "none" }), `g${run.start}`));
337
- out.push(
338
- keyed(
339
- code(run.text.join("\n"), {
340
- start: run.start,
341
- numbers: true,
342
- path: opts.path,
343
- wrap: opts.wrap,
344
- marks: run.marks.length > 0 ? run.marks : undefined,
345
- }),
346
- `c${run.start}`,
347
- ),
348
- );
349
- run = undefined;
350
- };
650
+ ): NativeNode | undefined {
651
+ const nums: number[] = [];
652
+ const body: string[] = [];
653
+ const marks: { line: number; tone: TspTone }[] = [];
654
+ let contiguous = true;
351
655
  for (const line of lines) {
352
- if (line.n === null) {
353
- flush();
354
- continue;
355
- }
356
- if (run && run.start + run.text.length !== line.n) flush();
357
- run ??= { start: line.n, text: [], marks: [] };
358
- run.text.push(line.text);
359
- if (line.mark) run.marks.push({ line: line.n, tone: "accent" });
656
+ if (line.n === null) continue;
657
+ if (nums.length > 0 && line.n !== nums[nums.length - 1]! + 1) contiguous = false;
658
+ nums.push(line.n);
659
+ body.push(line.text);
660
+ if (line.mark) marks.push({ line: line.n, tone: "accent" });
360
661
  }
361
- flush();
362
- return out;
662
+ if (nums.length === 0) return undefined;
663
+ return keyed(
664
+ code(body.join("\n"), {
665
+ start: contiguous ? nums[0] : undefined,
666
+ nums: contiguous ? undefined : nums,
667
+ numbers: true,
668
+ path: opts.path,
669
+ wrap: opts.wrap,
670
+ marks: marks.length > 0 ? marks : undefined,
671
+ }),
672
+ `c${nums[0]}`,
673
+ );
363
674
  }
364
675
 
365
676
  /**
366
677
  * Describe grouped search output (grep / ast-grep / ast-edit display content)
367
678
  * by file (§7.3 grep): per file a 22px path row (dim dir, strong name, the
368
679
  * header's suffix or the match count as a chip), then its lines as
369
- * {@link numberedCode} with match lines marked and `…` between non-adjacent
370
- * runs. Unnumbered body lines stay plain `code`. `maxFiles` keeps only the
371
- * first files (the caller says how many were left out). `file` owns the lines
680
+ * one {@link numberedCode} block with match lines marked (gaps between
681
+ * non-adjacent runs drawn in its gutter). Unnumbered body lines stay plain
682
+ * `code`. `maxFiles` keeps only the first files (the caller says how many
683
+ * were left out). `file` owns the lines
372
684
  * before any header: a single-file search prints none, yet its lines get the
373
685
  * same file row as a directory search's.
374
686
  */
@@ -386,10 +698,9 @@ export function describeGroupedOutput(
386
698
 
387
699
  const flushLines = () => {
388
700
  const target = current?.children ?? loose;
389
- if (numbered.length > 0) {
390
- target.push(...numberedCode(numbered, { path: current?.path }));
391
- numbered = [];
392
- }
701
+ const block = numberedCode(numbered, { path: current?.path });
702
+ if (block) target.push(block);
703
+ numbered = [];
393
704
  if (plain.length > 0) {
394
705
  target.push(keyed(code(plain.join("\n")), `p${target.length}`));
395
706
  plain = [];
@@ -6,6 +6,11 @@ export declare const HL_FILE_SUFFIX = "]";
6
6
  export declare const HL_FILE_HASH_SEP = "#";
7
7
  /** Number of characters in a displayed file hash. */
8
8
  export declare const HL_FILE_HASH_LENGTH = 4;
9
+ /**
10
+ * A trailing `#TAG` file hash exactly as the hashline store writes it (uppercase
11
+ * hex), so a name's own `#dead` or `#v2` ending survives stripping.
12
+ */
13
+ export declare const HASHLINE_TAG_SUFFIX_RE: RegExp;
9
14
  /** Keyword identifying a file move operation. */
10
15
  export declare const HL_MOVE_KEYWORD = "MV";
11
16
  /** Keyword identifying a file removal operation. */
@@ -14,6 +14,11 @@ export const HL_FILE_SUFFIX = "]";
14
14
  export const HL_FILE_HASH_SEP = "#";
15
15
  /** Number of characters in a displayed file hash. */
16
16
  export const HL_FILE_HASH_LENGTH = 4;
17
+ /**
18
+ * A trailing `#TAG` file hash exactly as the hashline store writes it (uppercase
19
+ * hex), so a name's own `#dead` or `#v2` ending survives stripping.
20
+ */
21
+ export const HASHLINE_TAG_SUFFIX_RE = new RegExp(`${HL_FILE_HASH_SEP}[0-9A-F]{${HL_FILE_HASH_LENGTH}}$`);
17
22
  /** Keyword identifying a file move operation. */
18
23
  export const HL_MOVE_KEYWORD = "MV";
19
24
  /** Keyword identifying a file removal operation. */
@@ -2,7 +2,7 @@
2
2
  * JSON tree rendering utilities shared across tool renderers.
3
3
  */
4
4
  import { INTENT_FIELD, type TspSpan, type TspTreeNode } from "@linxiraos/pi-wire";
5
- import { sanitizeText, sanitizeTextDeep } from "@linxiraos/pi-utils";
5
+ import { isRecord, sanitizeText, sanitizeTextDeep } from "@linxiraos/pi-utils";
6
6
  import { TreeView, treeRowPrefix } from "../components/tree-view";
7
7
  import { truncateToWidth } from "../render/render-utils";
8
8
  import type { Theme, ThemeColor } from "../theme/theme";
@@ -35,10 +35,6 @@ const ARGS_INLINE_MORE_WIDTH = Bun.stringWidth(ARGS_INLINE_MORE);
35
35
  /** Minimal value footprint (quotes + a couple chars) reserved for each not-yet-rendered key. */
36
36
  const ARGS_INLINE_TAIL_VALUE_RESERVE = 4;
37
37
 
38
- function isRecord(value: unknown): value is Record<string, unknown> {
39
- return !!value && typeof value === "object" && !Array.isArray(value);
40
- }
41
-
42
38
  /** Sanitization, string summary, and budgeting policy for inline JSON. */
43
39
  export interface InlineFormatOptions {
44
40
  sanitizeText?: (text: string) => string;