@oh-my-pi/pi-tui 18.6.3 → 18.8.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 (116) hide show
  1. package/CHANGELOG.md +46 -109
  2. package/dist/types/app-keybindings.d.ts +1 -1
  3. package/dist/types/apps/debug/log-viewer.d.ts +4 -0
  4. package/dist/types/apps/debug/raw-sse-buffer.d.ts +2 -0
  5. package/dist/types/autocomplete.d.ts +5 -2
  6. package/dist/types/charts/chart-plan.d.ts +92 -0
  7. package/dist/types/charts/chart-svg.d.ts +30 -0
  8. package/dist/types/charts/table-data.d.ts +107 -0
  9. package/dist/types/chat/assistant-message.d.ts +4 -0
  10. package/dist/types/chat/chat-transcript-builder.d.ts +2 -0
  11. package/dist/types/chat/fence-figure.d.ts +42 -0
  12. package/dist/types/chat/figure-markdown.d.ts +42 -0
  13. package/dist/types/chat/svg-figure.d.ts +33 -0
  14. package/dist/types/chat/svg-source.d.ts +49 -0
  15. package/dist/types/chat/table-chart.d.ts +88 -0
  16. package/dist/types/chat/tool-execution.d.ts +2 -0
  17. package/dist/types/components/editor.d.ts +9 -4
  18. package/dist/types/components/image.d.ts +9 -0
  19. package/dist/types/components/markdown.d.ts +16 -2
  20. package/dist/types/fuzzy.d.ts +29 -1
  21. package/dist/types/keybindings.d.ts +1 -1
  22. package/dist/types/native/backend.d.ts +2 -1
  23. package/dist/types/native/blobs.d.ts +4 -2
  24. package/dist/types/native/encode.d.ts +3 -4
  25. package/dist/types/overlays/agent-transcript-viewer.d.ts +8 -1
  26. package/dist/types/overlays/agents-hub.d.ts +9 -0
  27. package/dist/types/overlays/annotation-overlay.d.ts +5 -2
  28. package/dist/types/overlays/history-search.d.ts +10 -0
  29. package/dist/types/overlays/model-browser.d.ts +31 -3
  30. package/dist/types/overlays/plan-review-overlay.d.ts +3 -2
  31. package/dist/types/prompt/custom-editor.d.ts +7 -4
  32. package/dist/types/prompt/interactive-context-helpers.d.ts +4 -1
  33. package/dist/types/prompt/model-mention-autocomplete.d.ts +1 -1
  34. package/dist/types/render/composite.d.ts +2 -0
  35. package/dist/types/tools/glob.d.ts +4 -0
  36. package/dist/types/tools/renderer.d.ts +22 -0
  37. package/dist/types/tools/streaming-output.d.ts +11 -1
  38. package/dist/types/tools/write.d.ts +8 -1
  39. package/dist/types/utils.d.ts +6 -0
  40. package/package.json +9 -9
  41. package/src/apps/debug/log-viewer.ts +188 -72
  42. package/src/apps/debug/raw-sse-buffer.ts +8 -0
  43. package/src/apps/debug/raw-sse.ts +39 -5
  44. package/src/apps/git/diff-pane.ts +26 -5
  45. package/src/autocomplete.ts +67 -43
  46. package/src/charts/chart-plan.ts +367 -0
  47. package/src/charts/chart-svg.ts +693 -0
  48. package/src/charts/table-data.ts +436 -0
  49. package/src/chat/assistant-message.ts +169 -39
  50. package/src/chat/chat-transcript-builder.ts +4 -0
  51. package/src/chat/fence-figure.ts +80 -0
  52. package/src/chat/figure-markdown.ts +174 -0
  53. package/src/chat/svg-figure.ts +362 -0
  54. package/src/chat/svg-source.ts +188 -0
  55. package/src/chat/table-chart.ts +301 -0
  56. package/src/chat/tool-execution.ts +53 -4
  57. package/src/chrome/transcript-container.ts +7 -1
  58. package/src/components/editor.ts +68 -33
  59. package/src/components/image.ts +27 -1
  60. package/src/components/markdown.ts +80 -304
  61. package/src/fuzzy.ts +115 -30
  62. package/src/keybindings.ts +1 -1
  63. package/src/native/backend.ts +170 -15
  64. package/src/native/blobs.ts +4 -2
  65. package/src/native/encode.ts +58 -31
  66. package/src/overlays/agent-hub-projection.ts +70 -2
  67. package/src/overlays/agent-hub.ts +3 -2
  68. package/src/overlays/agent-transcript-viewer.ts +66 -13
  69. package/src/overlays/agents-hub.ts +28 -8
  70. package/src/overlays/annotation-overlay.ts +179 -80
  71. package/src/overlays/ask-dialog.ts +1 -1
  72. package/src/overlays/copy-selector.ts +30 -8
  73. package/src/overlays/extensions/state-manager.ts +52 -12
  74. package/src/overlays/history-search.ts +100 -7
  75. package/src/overlays/jobs-panel.ts +30 -2
  76. package/src/overlays/model-browser.ts +269 -90
  77. package/src/overlays/model-hub.ts +34 -7
  78. package/src/overlays/oauth-selector.ts +41 -26
  79. package/src/overlays/plan-review-overlay.ts +183 -68
  80. package/src/overlays/rewind-selector.ts +86 -17
  81. package/src/overlays/session-selector.ts +24 -4
  82. package/src/overlays/settings-selector.ts +21 -6
  83. package/src/overlays/tree-selector.ts +20 -4
  84. package/src/overlays/usage-dashboard.ts +12 -15
  85. package/src/prompt/attachment-chips.ts +2 -1
  86. package/src/prompt/composer-attachments.ts +6 -4
  87. package/src/prompt/composer.ts +2 -14
  88. package/src/prompt/custom-editor.ts +48 -19
  89. package/src/prompt/interactive-context-helpers.ts +30 -18
  90. package/src/prompt/macos-spelling.ts +7 -0
  91. package/src/prompt/magic-keywords.ts +11 -2
  92. package/src/prompt/model-mention-autocomplete.ts +14 -14
  93. package/src/prompt/word-completion.ts +38 -5
  94. package/src/render/composite.ts +62 -0
  95. package/src/setup/scenes/splash.ts +109 -45
  96. package/src/status-line/component.ts +220 -64
  97. package/src/status-line/segments.ts +8 -3
  98. package/src/terminal.ts +3 -2
  99. package/src/tools/ast-edit.ts +59 -35
  100. package/src/tools/ast-grep.ts +35 -16
  101. package/src/tools/default-renderer.ts +35 -19
  102. package/src/tools/eval-format/index.ts +28 -2
  103. package/src/tools/eval-format/javascript.ts +7 -5
  104. package/src/tools/eval.ts +164 -78
  105. package/src/tools/glob.ts +23 -6
  106. package/src/tools/grep.ts +81 -48
  107. package/src/tools/lsp.ts +81 -59
  108. package/src/tools/mcp.ts +98 -68
  109. package/src/tools/renderer.ts +27 -0
  110. package/src/tools/streaming-output.ts +120 -48
  111. package/src/tools/task.ts +111 -54
  112. package/src/tools/todo.ts +115 -29
  113. package/src/tools/wait.ts +34 -24
  114. package/src/tools/write.ts +77 -39
  115. package/src/tui.ts +118 -105
  116. package/src/utils.ts +19 -0
package/src/tools/eval.ts CHANGED
@@ -16,7 +16,12 @@ import { footnoteText, resultText } from "./native-view";
16
16
  import { renderAgentTreeRow } from "./agent-tree";
17
17
  import { truncateToVisualLines } from "../chrome/visual-truncate";
18
18
  import { getMarkdownTheme, type Theme } from "../theme/theme";
19
- import { markFramedBlockComponent, outputBlockContentWidth, renderCodeCell } from "../render/index";
19
+ import {
20
+ type CodeCellOptions,
21
+ markFramedBlockComponent,
22
+ outputBlockContentWidth,
23
+ renderCodeCell,
24
+ } from "../render/index";
20
25
  import { formatOutputPaneLines } from "../render/output-pane";
21
26
  import { formatEvalCodeForDisplay } from "./eval-format/index";
22
27
  import {
@@ -144,6 +149,37 @@ function getRenderCells(args: EvalRenderArgs | undefined): EvalRenderCell[] {
144
149
  return out;
145
150
  }
146
151
 
152
+ /**
153
+ * A rendered {@link renderCodeCell} box. Its first row is the header bar, the
154
+ * only row that depends on `spinnerFrame`; the code and output rows below it
155
+ * are reused across spinner ticks.
156
+ */
157
+ interface RenderedCodeCell {
158
+ readonly options: CodeCellOptions;
159
+ readonly lines: readonly string[];
160
+ }
161
+
162
+ /**
163
+ * Append `cell` for `spinnerFrame`. Only a running header animates, so only it
164
+ * is redrawn for a new frame: `renderOutputBlock` lays the header bar out from
165
+ * the header fields and width alone, so rendering an empty cell with the same
166
+ * header yields the identical bar row.
167
+ */
168
+ function pushCodeCellLines(
169
+ out: string[],
170
+ cell: RenderedCodeCell,
171
+ spinnerFrame: number | undefined,
172
+ theme: Theme,
173
+ ): void {
174
+ const { options, lines } = cell;
175
+ const header =
176
+ options.status === "running" && options.spinnerFrame !== spinnerFrame
177
+ ? renderCodeCell({ ...options, code: "", output: undefined, spinnerFrame }, theme)[0]!
178
+ : lines[0]!;
179
+ out.push(header);
180
+ for (let i = 1; i < lines.length; i++) out.push(lines[i]!);
181
+ }
182
+
147
183
  type AgentEventStatus = "pending" | "running" | "completed" | "failed" | "aborted";
148
184
 
149
185
  /**
@@ -757,47 +793,59 @@ export const evalToolRenderer = {
757
793
  return new Text(text, 0, 0);
758
794
  }
759
795
 
760
- let cached: { key: string; width: number; result: string[] } | undefined;
796
+ // Cell bodies depend on width, expansion, the viewport window and whether
797
+ // the call is live; a spinner tick only redraws the running header rows.
798
+ let bodies: { key: string; cells: RenderedCodeCell[] } | undefined;
799
+ let cached: { key: string; result: string[] } | undefined;
761
800
 
762
801
  return markFramedBlockComponent({
763
802
  render: (width: number): readonly string[] => {
764
- const key = `${options.expanded ? 1 : 0}|${options.spinnerFrame ?? "-"}|${previewWindowRows()}|${cells.map(c => `${c.language}:${c.title ?? ""}:${c.code.length}`).join("|")}`;
765
- if (cached && cached.key === key && cached.width === width) {
803
+ const spinnerFrame = options.spinnerFrame;
804
+ const windowRows = previewWindowRows();
805
+ const bodyKey = `${width}|${options.expanded ? 1 : 0}|${windowRows}|${spinnerFrame === undefined ? 0 : 1}`;
806
+ const key = `${bodyKey}|${spinnerFrame ?? "-"}`;
807
+ if (cached?.key === key) {
766
808
  return cached.result;
767
809
  }
768
810
 
811
+ if (bodies?.key !== bodyKey) {
812
+ bodies = {
813
+ key: bodyKey,
814
+ cells: cells.map((cell, i) => {
815
+ const cellOptions: CodeCellOptions = {
816
+ code: cell.code,
817
+ language: languageForHighlighter(cell.language),
818
+ showLanguage: true,
819
+ index: i,
820
+ total: cells.length,
821
+ title: cell.title,
822
+ status: spinnerFrame !== undefined ? "running" : "pending",
823
+ spinnerFrame,
824
+ width,
825
+ // Viewport-sized tail window following the newest streamed code
826
+ // line; renderResult keeps the same cap so the cell never snaps
827
+ // open on completion. Only ctrl+o uncaps.
828
+ codeTail: true,
829
+ codeMaxLines: windowRows,
830
+ expanded: options.expanded,
831
+ };
832
+ return { options: cellOptions, lines: renderCodeCell(cellOptions, uiTheme) };
833
+ }),
834
+ };
835
+ }
836
+
769
837
  const lines: string[] = [];
770
- for (let i = 0; i < cells.length; i++) {
771
- const cell = cells[i];
772
- const cellLines = renderCodeCell(
773
- {
774
- code: cell.code,
775
- language: languageForHighlighter(cell.language),
776
- showLanguage: true,
777
- index: i,
778
- total: cells.length,
779
- title: cell.title,
780
- status: options.spinnerFrame !== undefined ? "running" : "pending",
781
- spinnerFrame: options.spinnerFrame,
782
- width,
783
- // Viewport-sized tail window following the newest streamed code
784
- // line; renderResult keeps the same cap so the cell never snaps
785
- // open on completion. Only ctrl+o uncaps.
786
- codeTail: true,
787
- codeMaxLines: previewWindowRows(),
788
- expanded: options.expanded,
789
- },
790
- uiTheme,
791
- );
792
- lines.push(...cellLines);
838
+ for (let i = 0; i < bodies.cells.length; i++) {
839
+ pushCodeCellLines(lines, bodies.cells[i]!, spinnerFrame, uiTheme);
793
840
  if (i < cells.length - 1) {
794
841
  lines.push("");
795
842
  }
796
843
  }
797
- cached = { key, width, result: lines };
844
+ cached = { key, result: lines };
798
845
  return lines;
799
846
  },
800
847
  invalidate: () => {
848
+ bodies = undefined;
801
849
  cached = undefined;
802
850
  },
803
851
  });
@@ -848,69 +896,106 @@ export const evalToolRenderer = {
848
896
  if (cellResults && cellResults.length > 0) {
849
897
  const displayCells = cellResults.map(cell => {
850
898
  const language = cell.language ?? details?.language ?? "python";
851
- return { cell, code: formatEvalCodeForDisplay(cell.code, language), language };
899
+ const allEvents = cell.statusEvents ?? [];
900
+ const agentEvents = allEvents.filter(e => e.op === "agent");
901
+ return {
902
+ cell,
903
+ code: formatEvalCodeForDisplay(cell.code, language),
904
+ language,
905
+ agentEvents,
906
+ otherEvents: agentEvents.length > 0 ? allEvents.filter(e => e.op !== "agent") : allEvents,
907
+ // Running agent rows carry the spinner; settled ones are frame-independent.
908
+ agentLive: agentEvents.some(e => agentEventStatus(e.status) === "running"),
909
+ };
852
910
  });
853
- let cached: { key: string; width: number; result: string[] } | undefined;
911
+ // Per-cell rows keyed by everything but the spinner frame: a tick only
912
+ // redraws running headers and running agent rows.
913
+ let bodies:
914
+ | {
915
+ key: string;
916
+ cells: { codeCell: RenderedCodeCell; agentLines: string[]; agentFrame: number | undefined }[];
917
+ }
918
+ | undefined;
919
+ let cached: { key: string; result: string[] } | undefined;
854
920
 
855
921
  return markFramedBlockComponent({
856
922
  render: (width: number): readonly string[] => {
923
+ const spinnerFrame = options.spinnerFrame;
857
924
  const expanded = options.renderContext?.expanded ?? options.expanded;
925
+ const windowRows = previewWindowRows();
858
926
  const previewLines = Math.min(
859
927
  options.renderContext?.previewLines ?? EVAL_DEFAULT_PREVIEW_LINES,
860
- previewWindowRows(),
928
+ windowRows,
861
929
  );
862
- const key = `${expanded}|${previewLines}|${options.spinnerFrame}|${previewWindowRows()}`;
863
- if (cached && cached.key === key && cached.width === width) {
930
+ const bodyKey = `${width}|${expanded}|${previewLines}|${windowRows}`;
931
+ const key = `${bodyKey}|${spinnerFrame}`;
932
+ if (cached?.key === key) {
864
933
  return cached.result;
865
934
  }
866
935
 
936
+ if (bodies?.key !== bodyKey) {
937
+ bodies = {
938
+ key: bodyKey,
939
+ cells: displayCells.map(({ cell, code, language, agentEvents, otherEvents }, i) => {
940
+ const statusLines = renderStatusEvents(otherEvents, uiTheme, expanded);
941
+ const outputContent = formatCellOutputLines(cell, expanded, previewLines, uiTheme, width);
942
+ const outputLines = [...outputContent.lines];
943
+ if (!expanded && outputContent.hiddenCount > 0) {
944
+ outputLines.push(
945
+ uiTheme.fg(
946
+ "dim",
947
+ `… ${outputContent.hiddenCount} more lines (${expandKeyHint()} to expand)`,
948
+ ),
949
+ );
950
+ }
951
+ if (statusLines.length > 0) {
952
+ if (outputLines.length > 0) {
953
+ outputLines.push(uiTheme.fg("dim", "Status"));
954
+ }
955
+ outputLines.push(...statusLines);
956
+ }
957
+ const cellOptions: CodeCellOptions = {
958
+ code,
959
+ language: languageForHighlighter(language),
960
+ showLanguage: true,
961
+ index: i,
962
+ total: cellResults.length,
963
+ title: cell.title,
964
+ status: cell.status,
965
+ spinnerFrame,
966
+ duration: cell.durationMs,
967
+ output: outputLines.length > 0 ? outputLines.join("\n") : undefined,
968
+ outputMaxLines: outputLines.length,
969
+ // Same viewport-sized tail window as the pending preview so the
970
+ // cell never snaps open on completion; only ctrl+o uncaps.
971
+ // `output` keeps its own preview cap from above.
972
+ codeTail: true,
973
+ codeMaxLines: windowRows,
974
+ expanded,
975
+ width,
976
+ };
977
+ return {
978
+ codeCell: { options: cellOptions, lines: renderCodeCell(cellOptions, uiTheme) },
979
+ agentLines:
980
+ agentEvents.length > 0
981
+ ? renderAgentProgressEvents(agentEvents, uiTheme, width, spinnerFrame)
982
+ : [],
983
+ agentFrame: spinnerFrame,
984
+ };
985
+ }),
986
+ };
987
+ }
988
+
867
989
  const lines: string[] = [];
868
990
  for (let i = 0; i < displayCells.length; i++) {
869
- const { cell, code, language } = displayCells[i];
870
- const allEvents = cell.statusEvents ?? [];
871
- const agentEvents = allEvents.filter(e => e.op === "agent");
872
- const otherEvents = agentEvents.length > 0 ? allEvents.filter(e => e.op !== "agent") : allEvents;
873
- const statusLines = renderStatusEvents(otherEvents, uiTheme, expanded);
874
- const outputContent = formatCellOutputLines(cell, expanded, previewLines, uiTheme, width);
875
- const outputLines = [...outputContent.lines];
876
- if (!expanded && outputContent.hiddenCount > 0) {
877
- outputLines.push(
878
- uiTheme.fg("dim", `… ${outputContent.hiddenCount} more lines (${expandKeyHint()} to expand)`),
879
- );
880
- }
881
- if (statusLines.length > 0) {
882
- if (outputLines.length > 0) {
883
- outputLines.push(uiTheme.fg("dim", "Status"));
884
- }
885
- outputLines.push(...statusLines);
886
- }
887
- const cellLines = renderCodeCell(
888
- {
889
- code,
890
- language: languageForHighlighter(language),
891
- showLanguage: true,
892
- index: i,
893
- total: cellResults.length,
894
- title: cell.title,
895
- status: cell.status,
896
- spinnerFrame: options.spinnerFrame,
897
- duration: cell.durationMs,
898
- output: outputLines.length > 0 ? outputLines.join("\n") : undefined,
899
- outputMaxLines: outputLines.length,
900
- // Same viewport-sized tail window as the pending preview so the
901
- // cell never snaps open on completion; only ctrl+o uncaps.
902
- // `output` keeps its own preview cap from above.
903
- codeTail: true,
904
- codeMaxLines: previewWindowRows(),
905
- expanded,
906
- width,
907
- },
908
- uiTheme,
909
- );
910
- lines.push(...cellLines);
911
- if (agentEvents.length > 0) {
912
- lines.push(...renderAgentProgressEvents(agentEvents, uiTheme, width, options.spinnerFrame));
991
+ const { agentEvents, agentLive } = displayCells[i]!;
992
+ const body = bodies.cells[i]!;
993
+ pushCodeCellLines(lines, body.codeCell, spinnerFrame, uiTheme);
994
+ if (agentLive && body.agentFrame !== spinnerFrame) {
995
+ body.agentLines = renderAgentProgressEvents(agentEvents, uiTheme, width, spinnerFrame);
996
+ body.agentFrame = spinnerFrame;
913
997
  }
998
+ lines.push(...body.agentLines);
914
999
  if (i < cellResults.length - 1) {
915
1000
  lines.push("");
916
1001
  }
@@ -928,10 +1013,11 @@ export const evalToolRenderer = {
928
1013
  if (warningLine) {
929
1014
  lines.push(warningLine);
930
1015
  }
931
- cached = { key, width, result: lines };
1016
+ cached = { key, result: lines };
932
1017
  return lines;
933
1018
  },
934
1019
  invalidate: () => {
1020
+ bodies = undefined;
935
1021
  cached = undefined;
936
1022
  },
937
1023
  });
package/src/tools/glob.ts CHANGED
@@ -29,6 +29,10 @@ export interface GlobToolDetails {
29
29
  fileCount?: number;
30
30
  files?: string[];
31
31
  truncated?: boolean;
32
+ /** The scan hit the tool deadline, so the listed files are an incomplete
33
+ * set rather than a complete answer. Distinct from `truncated`, which also
34
+ * covers result-limit and output truncation. */
35
+ timedOut?: boolean;
32
36
  error?: string;
33
37
  /** Working directory at search time. Used by the renderer to resolve relative
34
38
  * file paths to absolute paths for OSC 8 hyperlinks. */
@@ -184,6 +188,10 @@ export const globToolRenderer = {
184
188
  const truncation = details?.truncation ?? details?.meta?.truncation;
185
189
  const limits = details?.meta?.limits;
186
190
  const truncated = Boolean(details?.truncated || truncation || details?.resultLimitReached || limits?.resultLimit);
191
+ // A non-empty timed-out result is the case `truncated` alone cannot
192
+ // explain: the listing is short because the scan died, not because it
193
+ // finished. Say which one it was.
194
+ const timedOut = Boolean(details?.timedOut);
187
195
  const files = details?.files ?? [];
188
196
 
189
197
  const missingPaths = details?.missingPaths ?? [];
@@ -192,15 +200,18 @@ export const globToolRenderer = {
192
200
 
193
201
  if (fileCount === 0) {
194
202
  // `truncated` on an empty result means the scan timed out mid-walk —
195
- // render "incomplete", not a definitive "No files found".
196
- const emptyLabel = truncated ? "No matches before timeout (scan incomplete)" : "No files found";
203
+ // render "incomplete", not a definitive "No files found". `timedOut`
204
+ // states it outright; the inference stays for old transcripts that
205
+ // predate the field.
206
+ const emptyTimedOut = timedOut || truncated;
207
+ const emptyLabel = emptyTimedOut ? "No matches before timeout (scan incomplete)" : "No files found";
197
208
  const header = renderStatusLine(
198
209
  {
199
210
  icon: "warning",
200
211
  title: "Glob",
201
212
  titleColor: "toolTitle",
202
213
  description: formatGlobRenderPaths(args),
203
- meta: truncated ? ["0 files", uiTheme.fg("warning", "timed out")] : ["0 files"],
214
+ meta: emptyTimedOut ? ["0 files", uiTheme.fg("warning", "timed out")] : ["0 files"],
204
215
  },
205
216
  uiTheme,
206
217
  );
@@ -210,7 +221,7 @@ export const globToolRenderer = {
210
221
  }
211
222
  const meta: string[] = [formatCount("file", fileCount)];
212
223
  if (details?.scopePath) meta.push(`in ${details.scopePath}`);
213
- if (truncated) meta.push(uiTheme.fg("warning", "truncated"));
224
+ if (truncated) meta.push(uiTheme.fg("warning", timedOut ? "timed out" : "truncated"));
214
225
  const header = renderStatusLine(
215
226
  {
216
227
  ...(truncated ? { icon: "warning" as const } : { iconOverride: globStatusIcon(uiTheme) }),
@@ -294,6 +305,7 @@ export const globToolRenderer = {
294
305
  const truncation = details.truncation ?? details.meta?.truncation;
295
306
  const limits = details.meta?.limits;
296
307
  const truncated = Boolean(details.truncated || truncation || details.resultLimitReached || limits?.resultLimit);
308
+ const timedOut = Boolean(details.timedOut);
297
309
  const missingPaths = details.missingPaths ?? [];
298
310
  const missingNote = missingPaths.length > 0 ? `skipped missing: ${missingPaths.join(", ")}` : undefined;
299
311
  const scope = details.scopePath ? `in ${details.scopePath}` : undefined;
@@ -301,7 +313,10 @@ export const globToolRenderer = {
301
313
  const foot = footnoteText(compact([missingNote]));
302
314
  return {
303
315
  // `truncated` on an empty result means the scan timed out mid-walk.
304
- tool: { ...globNativeHead(args, compact(["0 files", scope])), note: truncated ? "timed out" : undefined },
316
+ tool: {
317
+ ...globNativeHead(args, compact(["0 files", scope])),
318
+ note: timedOut || truncated ? "timed out" : undefined,
319
+ },
305
320
  tone: "warning",
306
321
  inline: true,
307
322
  body: foot ? [foot] : undefined,
@@ -315,7 +330,9 @@ export const globToolRenderer = {
315
330
  if (artifactId) reasons.push(formatFullOutputReference(artifactId));
316
331
  const head = globNativeHead(args, compact([formatCount("file", details.fileCount), scope]));
317
332
  return {
318
- tool: truncated ? { ...head, badges: [{ text: "truncated", tone: "warning" }] } : head,
333
+ tool: truncated
334
+ ? { ...head, badges: [{ text: timedOut ? "timed out" : "truncated", tone: "warning" }] }
335
+ : head,
319
336
  inline: true,
320
337
  body: compact<NativeChild>([
321
338
  describeGlobFiles(details.files ?? [], details.cwd),
package/src/tools/grep.ts CHANGED
@@ -111,11 +111,6 @@ function parseSearchDisplayLineNumber(line: string): number | undefined {
111
111
 
112
112
  const SEARCH_MATCH_LINE_RE = /^\s*\*\d+(?:│|[:|])/;
113
113
 
114
- interface RenderedSearchLine {
115
- raw: string;
116
- styled: string;
117
- }
118
-
119
114
  function isSearchMatchLine(line: string): boolean {
120
115
  return SEARCH_MATCH_LINE_RE.test(line);
121
116
  }
@@ -126,61 +121,91 @@ function isSearchHeaderLine(line: string): boolean {
126
121
 
127
122
  const URL_HEADER_PREFIX_RE = /^#+\s+/;
128
123
 
129
- function renderSearchDisplayLines(
124
+ /**
125
+ * Build a memoized per-line styler for search display output. Classification
126
+ * and URL-target tracking walk the whole output once (nested directory stacks
127
+ * span blank-line groups), but styling and hyperlinking run only for the rows
128
+ * a preview actually shows.
129
+ */
130
+ function createSearchLineStyler(
130
131
  lines: readonly string[],
131
132
  headerBase: string | undefined,
132
133
  fileScope: string | undefined,
133
134
  uiTheme: Theme,
134
135
  displayTargets: Record<string, string> | undefined,
135
- ): RenderedSearchLine[] {
136
+ ): (index: number) => string {
136
137
  const contexts = classifyGroupedLines(lines, headerBase, fileScope);
137
138
  // `classifyGroupedLines` can't resolve internal URLs (TUI-only), so track the
138
139
  // resolved URL target here and use it for the body lines that follow.
140
+ const urlRaw: (string | undefined)[] = Array.from({ length: lines.length }, () => undefined);
141
+ const urlFiles: (string | undefined)[] = Array.from({ length: lines.length }, () => undefined);
139
142
  let urlFile: string | undefined;
140
- return lines.map((line, index) => {
143
+ for (let index = 0; index < lines.length; index++) {
141
144
  const ctx = contexts[index]!;
142
145
  if (ctx.kind === "dir") {
143
146
  urlFile = undefined;
144
- const styled = uiTheme.fg("accent", line);
145
- return { raw: line, styled: ctx.headerPath ? fileHyperlink(ctx.headerPath, styled) : styled };
146
- }
147
- if (ctx.kind === "file") {
147
+ } else if (ctx.kind === "file") {
148
148
  if (ctx.isUrl) {
149
- const raw = line
150
- .replace(URL_HEADER_PREFIX_RE, "")
149
+ const raw = lines[index]!.replace(URL_HEADER_PREFIX_RE, "")
151
150
  .trimEnd()
152
151
  .replace(/\s+\([^)]*\)\s*$/, "");
153
- const linked = linkUrlLikeSearchHeader(raw, uiTheme.fg("accent", line), displayTargets?.[raw]);
154
- urlFile = linked.absPath;
155
- return { raw: line, styled: linked.line };
152
+ urlRaw[index] = raw;
153
+ urlFile = displayTargets?.[raw];
154
+ } else {
155
+ urlFile = undefined;
156
156
  }
157
- urlFile = undefined;
158
- // Root-level files keep the bright accent; nested file headers are dimmed.
159
- const styled = uiTheme.fg(ctx.depth === 1 ? "accent" : "dim", line);
160
- return { raw: line, styled: ctx.headerPath ? fileHyperlink(ctx.headerPath, styled) : styled };
157
+ } else {
158
+ urlFiles[index] = urlFile;
161
159
  }
162
- const styled = uiTheme.fg("toolOutput", line);
163
- const lineNumber = parseSearchDisplayLineNumber(line);
164
- const filePath = ctx.filePath ?? urlFile;
165
- return {
166
- raw: line,
167
- styled: filePath && lineNumber !== undefined ? fileHyperlink(filePath, styled, { line: lineNumber }) : styled,
168
- };
169
- });
160
+ }
161
+ const styledLines: (string | undefined)[] = Array.from({ length: lines.length }, () => undefined);
162
+ return index => {
163
+ const cached = styledLines[index];
164
+ if (cached !== undefined) return cached;
165
+ const line = lines[index]!;
166
+ const ctx = contexts[index]!;
167
+ let styled: string;
168
+ if (ctx.kind === "dir") {
169
+ const accent = uiTheme.fg("accent", line);
170
+ styled = ctx.headerPath ? fileHyperlink(ctx.headerPath, accent) : accent;
171
+ } else if (ctx.kind === "file") {
172
+ const raw = urlRaw[index];
173
+ if (raw !== undefined) {
174
+ styled = linkUrlLikeSearchHeader(raw, uiTheme.fg("accent", line), displayTargets?.[raw]).line;
175
+ } else {
176
+ // Root-level files keep the bright accent; nested file headers are dimmed.
177
+ const tinted = uiTheme.fg(ctx.depth === 1 ? "accent" : "dim", line);
178
+ styled = ctx.headerPath ? fileHyperlink(ctx.headerPath, tinted) : tinted;
179
+ }
180
+ } else {
181
+ const tinted = uiTheme.fg("toolOutput", line);
182
+ const lineNumber = parseSearchDisplayLineNumber(line);
183
+ const filePath = ctx.filePath ?? urlFiles[index];
184
+ styled = filePath && lineNumber !== undefined ? fileHyperlink(filePath, tinted, { line: lineNumber }) : tinted;
185
+ }
186
+ styledLines[index] = styled;
187
+ return styled;
188
+ };
170
189
  }
171
190
 
172
- function compactSearchPreviewGroup(group: RenderedSearchLine[]): RenderedSearchLine[] {
173
- const compact = group.filter(line => isSearchHeaderLine(line.raw) || isSearchMatchLine(line.raw));
191
+ function compactSearchPreviewGroup(group: readonly number[], lines: readonly string[]): readonly number[] {
192
+ const compact = group.filter(index => isSearchHeaderLine(lines[index]!) || isSearchMatchLine(lines[index]!));
174
193
  return compact.length > 0 ? compact : group;
175
194
  }
176
195
 
177
- function countPreviewMatches(lines: readonly RenderedSearchLine[], hasMarkedMatches: boolean): number {
178
- if (hasMarkedMatches) return lines.reduce((count, line) => count + (isSearchMatchLine(line.raw) ? 1 : 0), 0);
179
- return lines.reduce((count, line) => count + (!isSearchHeaderLine(line.raw) && line.raw.length > 0 ? 1 : 0), 0);
196
+ function countPreviewMatches(group: readonly number[], lines: readonly string[], hasMarkedMatches: boolean): number {
197
+ let count = 0;
198
+ for (const index of group) {
199
+ const line = lines[index]!;
200
+ if (hasMarkedMatches ? isSearchMatchLine(line) : !isSearchHeaderLine(line) && line.length > 0) count++;
201
+ }
202
+ return count;
180
203
  }
181
204
 
182
205
  function renderBudgetedSearchGroups(
183
- groups: RenderedSearchLine[][],
206
+ groups: readonly (readonly number[])[],
207
+ lines: readonly string[],
208
+ styleLine: (index: number) => string,
184
209
  maxLines: number,
185
210
  matchCount: number,
186
211
  uiTheme: Theme,
@@ -188,7 +213,7 @@ function renderBudgetedSearchGroups(
188
213
  ): string[] {
189
214
  if (maxLines <= 0) return [];
190
215
  const renderedGroups = groups
191
- .map(group => (compact ? compactSearchPreviewGroup(group) : group))
216
+ .map(group => (compact ? compactSearchPreviewGroup(group, lines) : group))
192
217
  .filter(group => group.length > 0);
193
218
  if (renderedGroups.length === 0) return [];
194
219
 
@@ -197,13 +222,13 @@ function renderBudgetedSearchGroups(
197
222
  let totalFallbackMatches = 0;
198
223
  for (const group of renderedGroups) {
199
224
  totalLines += group.length;
200
- totalMarkedMatches += countPreviewMatches(group, true);
201
- totalFallbackMatches += countPreviewMatches(group, false);
225
+ totalMarkedMatches += countPreviewMatches(group, lines, true);
226
+ totalFallbackMatches += countPreviewMatches(group, lines, false);
202
227
  }
203
228
  const hasMarkedMatches = totalMarkedMatches > 0;
204
229
  const needsSummary = totalLines > maxLines;
205
230
  const contentBudget = needsSummary ? Math.max(maxLines - 1, 0) : maxLines;
206
- const visibleGroups: RenderedSearchLine[][] = [];
231
+ const visibleGroups: (readonly number[])[] = [];
207
232
  let visibleLineCount = 0;
208
233
  let visibleMatches = 0;
209
234
  for (const group of renderedGroups) {
@@ -214,30 +239,30 @@ function renderBudgetedSearchGroups(
214
239
  const visibleGroup = group.slice(0, take);
215
240
  visibleGroups.push(visibleGroup);
216
241
  visibleLineCount += visibleGroup.length;
217
- visibleMatches += countPreviewMatches(visibleGroup, hasMarkedMatches);
242
+ visibleMatches += countPreviewMatches(visibleGroup, lines, hasMarkedMatches);
218
243
  }
219
244
 
220
245
  const totalMatches = hasMarkedMatches ? totalMarkedMatches : Math.max(matchCount, totalFallbackMatches);
221
246
  const hiddenMatches = Math.max(totalMatches - visibleMatches, 0);
222
247
  const hiddenLines = Math.max(totalLines - visibleLineCount, 0);
223
248
  const hasSummary = needsSummary && (hiddenMatches > 0 || hiddenLines > 0);
224
- const lines: string[] = [];
249
+ const out: string[] = [];
225
250
  for (let i = 0; i < visibleGroups.length; i++) {
226
251
  const group = visibleGroups[i]!;
227
252
  const isLast = !hasSummary && i === visibleGroups.length - 1;
228
253
  const prefix = `${uiTheme.fg("dim", getTreeBranch(isLast, uiTheme))} `;
229
254
  const continuePrefix = uiTheme.fg("dim", getTreeContinuePrefix(isLast, uiTheme));
230
- lines.push(`${prefix}${replaceTabs(group[0]!.styled)}`);
255
+ out.push(`${prefix}${replaceTabs(styleLine(group[0]!))}`);
231
256
  for (let j = 1; j < group.length; j++) {
232
- lines.push(`${continuePrefix}${replaceTabs(group[j]!.styled)}`);
257
+ out.push(`${continuePrefix}${replaceTabs(styleLine(group[j]!))}`);
233
258
  }
234
259
  }
235
260
  if (hasSummary) {
236
261
  const hiddenLabel =
237
262
  hiddenMatches > 0 ? formatMoreItems(hiddenMatches, "match") : formatMoreItems(hiddenLines, "line");
238
- lines.push(`${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg("muted", hiddenLabel)}`);
263
+ out.push(`${uiTheme.fg("dim", uiTheme.tree.last)} ${uiTheme.fg("muted", hiddenLabel)}`);
239
264
  }
240
- return lines;
265
+ return out;
241
266
  }
242
267
 
243
268
  function grepStatusIcon(uiTheme: Theme): string {
@@ -363,14 +388,14 @@ export const grepToolRenderer = {
363
388
  // Header/match display paths are cwd-relative, so resolve them against cwd
364
389
  // (falling back to searchPath for legacy results that predate `cwd`); the
365
390
  // scoped file's absolute path seeds body lines in single-file searches.
366
- const renderedLines = renderSearchDisplayLines(
391
+ const styleLine = createSearchLineStyler(
367
392
  allLines,
368
393
  details?.cwd ?? details?.searchPath,
369
394
  details?.searchPath,
370
395
  uiTheme,
371
396
  details?.displayTargets,
372
397
  );
373
- const matchGroups = groupLineIndicesByBlank(allLines).map(indices => indices.map(i => renderedLines[i]!));
398
+ const matchGroups = groupLineIndicesByBlank(allLines);
374
399
 
375
400
  const extraLines: string[] = [];
376
401
  if (missingNote) extraLines.push(missingNote);
@@ -382,7 +407,15 @@ export const grepToolRenderer = {
382
407
  (options.expanded ? EXPANDED_TEXT_LIMIT : COLLAPSED_TEXT_LIMIT) - extraLines.length,
383
408
  0,
384
409
  );
385
- const matchLines = renderBudgetedSearchGroups(matchGroups, budget, matchCount, uiTheme, !options.expanded);
410
+ const matchLines = renderBudgetedSearchGroups(
411
+ matchGroups,
412
+ allLines,
413
+ styleLine,
414
+ budget,
415
+ matchCount,
416
+ uiTheme,
417
+ !options.expanded,
418
+ );
386
419
  return [header, ...matchLines, ...extraLines].map(l => truncateToWidth(l, width, Ellipsis.Omit));
387
420
  },
388
421
  { paddingX: 1 },