@justjoshn/pi-snoop-tui 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ - Include indent, frame tone, and theme in the panel cache key so mid-session `outputPad` and theme changes re-render without manual invalidation.
6
+ - Replace the hand-written ANSI blank-line scanner with `stripTerminalSequences`, use `os.homedir()` in `rows/specs.ts`, make `footer.ts` table-driven, and share a `memoLast` cache helper.
7
+
3
8
  ## [0.1.3]
4
9
 
5
10
  - Fix every `bun lint` behavior error. The editor inset can no longer pass a negative count to `repeat()`, and the home directory is read when a path is shown instead of when the module loads.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@justjoshn/pi-snoop-tui",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "A calm, compact, fast look for Pi's interactive TUI: graphite themes, one-line tool rows, a single-row footer.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/chrome.ts CHANGED
@@ -2,8 +2,8 @@ import { basename } from 'node:path';
2
2
 
3
3
  import type { ExtensionAPI, ExtensionUIContext, Theme } from '@earendil-works/pi-coding-agent';
4
4
  import type { Component } from '@earendil-works/pi-tui';
5
- import { cell } from './cell.ts';
6
5
  import { createRuleEditor } from './editor.ts';
6
+ import { memoLast } from './memo.ts';
7
7
  import { fitPlain, gutterAt, gutterOf, sanitizeLine } from './text.ts';
8
8
 
9
9
  type EditorFactory = NonNullable<ReturnType<ExtensionUIContext['getEditorComponent']>>;
@@ -32,20 +32,11 @@ export default function chrome(pi: ExtensionAPI): void {
32
32
  });
33
33
  }
34
34
  export function headerLine(theme: Theme, workspace: string, gutter: number): Component {
35
- const cache = cell<{ width: number; lines: string[] } | undefined>(undefined);
36
- return {
37
- render(width: number): string[] {
38
- const cached = cache.read();
39
- if (cached?.width === width) return cached.lines;
40
- const g = gutterAt(gutter, width);
41
- const inner = width - 2 * g;
42
- const text = inner < HEADER_MIN_INNER ? theme.fg('accent', fitPlain('pi', inner)) : theme.fg('accent', 'pi') + theme.fg('dim', ' / ') + theme.fg('muted', fitPlain(sanitizeLine(workspace), inner - HEADER_MIN_INNER));
43
- const lines = ['', ' '.repeat(g) + text, ''];
44
- cache.write({ width, lines });
45
- return lines;
46
- },
47
- invalidate(): void {
48
- cache.write(undefined);
49
- },
50
- };
35
+ const lines = memoLast((width: number) => {
36
+ const g = gutterAt(gutter, width);
37
+ const inner = width - 2 * g;
38
+ const text = inner < HEADER_MIN_INNER ? theme.fg('accent', fitPlain('pi', inner)) : theme.fg('accent', 'pi') + theme.fg('dim', ' / ') + theme.fg('muted', fitPlain(sanitizeLine(workspace), inner - HEADER_MIN_INNER));
39
+ return ['', ' '.repeat(g) + text, ''];
40
+ });
41
+ return { render: lines.get, invalidate: lines.reset };
51
42
  }
package/src/editor.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { CustomEditor, type KeybindingsManager, type Theme } from '@earendil-works/pi-coding-agent';
2
2
  import { type EditorTheme, type TUI, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
3
  import { cell } from './cell.ts';
4
+ import { memoLast } from './memo.ts';
4
5
  import { gutterAt } from './text.ts';
5
6
 
6
7
  type Indicator = NonNullable<Parameters<CustomEditor['setWorkingStatusIndicator']>[0]>;
@@ -15,15 +16,7 @@ export function editorStatus(indicator: Indicator | undefined): EditorStatus {
15
16
  return indicator.kind === 'working' ? WORKING : { kind: 'pi', indicator };
16
17
  }
17
18
 
18
- interface RuleCache {
19
- readonly width: number;
20
- readonly hidden: number;
21
- readonly border: (text: string) => string;
22
- readonly theme: Theme;
23
- readonly status: EditorStatus | undefined;
24
- readonly piLabel: string;
25
- readonly line: string;
26
- }
19
+ type Border = (text: string) => string;
27
20
 
28
21
  interface EditorConfig {
29
22
  readonly theme: () => Theme;
@@ -33,9 +26,12 @@ interface EditorConfig {
33
26
  abstract class RuleEditor extends CustomEditor {
34
27
  protected abstract readonly config: EditorConfig;
35
28
  private readonly snoopStatus = cell<EditorStatus>(READY);
36
- private readonly topRule = cell<RuleCache | undefined>(undefined);
37
- private readonly bottomRule = cell<RuleCache | undefined>(undefined);
38
- private readonly prompt = cell<{ theme: Theme; text: string } | undefined>(undefined);
29
+ private readonly topRule = memoLast((width: number, hidden: number, border: Border, theme: Theme, status: EditorStatus, piLabel: string) => {
30
+ const left = hidden > 0 ? `${theme.fg('dim', `↑ ${hidden}`)} ` : '';
31
+ return this.rule(width, left, ` ${statusLabel(status, theme, piLabel)}`, border);
32
+ });
33
+ private readonly bottomRule = memoLast((width: number, hidden: number, border: Border, theme: Theme) => this.rule(width, '', hidden > 0 ? ` ${theme.fg('dim', `↓ ${hidden}`)}` : '', border));
34
+ private readonly prompt = memoLast((theme: Theme) => `${' '.repeat(this.config.gutter)}${theme.fg('accent', '›')}${' '.repeat(Math.max(0, PROMPT_INSET - 1))}`);
39
35
  override setPaddingX(_padding: number): void {
40
36
  super.setPaddingX(this.config.gutter + PROMPT_INSET);
41
37
  }
@@ -47,27 +43,17 @@ abstract class RuleEditor extends CustomEditor {
47
43
  const theme = this.config.theme();
48
44
  const status = this.snoopStatus.read();
49
45
  const piLabel = status.kind === 'pi' ? status.indicator.renderInBorder(Math.max(1, width - BORDER_LABEL_RESERVE)) : '';
50
- const cached = this.topRule.read();
51
- if (cached && cached.width === width && cached.hidden === hidden && cached.border === this.borderColor && cached.theme === theme && cached.status === status && cached.piLabel === piLabel) return cached.line;
52
- const left = hidden > 0 ? `${theme.fg('dim', `↑ ${hidden}`)} ` : '';
53
- const line = this.rule(width, left, ` ${statusLabel(status, theme, piLabel)}`);
54
- this.topRule.write({ width, hidden, border: this.borderColor, theme, status, piLabel, line });
55
- return line;
46
+ return this.topRule.get(width, hidden, this.borderColor, theme, status, piLabel);
56
47
  }
57
48
  protected override renderBottomBorder(width: number, hidden: number): string {
58
- const theme = this.config.theme();
59
- const cached = this.bottomRule.read();
60
- if (cached && cached.width === width && cached.hidden === hidden && cached.border === this.borderColor && cached.theme === theme) return cached.line;
61
- const line = this.rule(width, '', hidden > 0 ? ` ${theme.fg('dim', `↓ ${hidden}`)}` : '');
62
- this.bottomRule.write({ width, hidden, border: this.borderColor, theme, status: undefined, piLabel: '', line });
63
- return line;
49
+ return this.bottomRule.get(width, hidden, this.borderColor, this.config.theme());
64
50
  }
65
- private rule(width: number, left: string, right: string): string {
51
+ private rule(width: number, left: string, right: string, border: Border): string {
66
52
  const g = gutterAt(this.config.gutter, width);
67
53
  const inner = width - 2 * g;
68
54
  const labels = visibleWidth(left) + visibleWidth(right);
69
55
  const [start, end, fill] = labels < inner ? [left, right, inner - labels] : ['', '', inner];
70
- const line = ' '.repeat(g) + start + this.borderColor('─'.repeat(Math.max(0, fill))) + end + ' '.repeat(g);
56
+ const line = ' '.repeat(g) + start + border('─'.repeat(Math.max(0, fill))) + end + ' '.repeat(g);
71
57
  return visibleWidth(line) <= width ? line : truncateToWidth(line, width, '');
72
58
  }
73
59
  override render(width: number): string[] {
@@ -75,20 +61,13 @@ abstract class RuleEditor extends CustomEditor {
75
61
  const inset = this.config.gutter + PROMPT_INSET;
76
62
  const first = lines[1];
77
63
  if (first === undefined || gutterAt(inset, width) < inset) return lines;
78
- return lines.with(1, this.promptText(this.config.theme()) + first.slice(inset));
79
- }
80
- private promptText(theme: Theme): string {
81
- const cached = this.prompt.read();
82
- if (cached?.theme === theme) return cached.text;
83
- const text = `${' '.repeat(this.config.gutter)}${theme.fg('accent', '›')}${' '.repeat(Math.max(0, PROMPT_INSET - 1))}`;
84
- this.prompt.write({ theme, text });
85
- return text;
64
+ return lines.with(1, this.prompt.get(this.config.theme()) + first.slice(inset));
86
65
  }
87
66
  override invalidate(): void {
88
67
  super.invalidate();
89
- this.topRule.write(undefined);
90
- this.bottomRule.write(undefined);
91
- this.prompt.write(undefined);
68
+ this.topRule.reset();
69
+ this.bottomRule.reset();
70
+ this.prompt.reset();
92
71
  }
93
72
  }
94
73
 
package/src/footer.ts CHANGED
@@ -2,9 +2,10 @@ import { basename } from 'node:path';
2
2
 
3
3
  import type { ExtensionAPI, ExtensionContext, ReadonlyFooterDataProvider, Theme } from '@earendil-works/pi-coding-agent';
4
4
  import { type Component, type TUI, visibleWidth } from '@earendil-works/pi-tui';
5
- import { cell } from './cell.ts';
5
+ import { memoLast } from './memo.ts';
6
6
  import { fitPlain, gutterAt, gutterOf, sanitizeLine } from './text.ts';
7
7
 
8
+ type ThemeColor = Parameters<Theme['fg']>[0];
8
9
  type ThinkingLevel = ReturnType<ExtensionAPI['getThinkingLevel']>;
9
10
  export interface FooterSnapshot {
10
11
  readonly workspace: string;
@@ -14,22 +15,28 @@ export interface FooterSnapshot {
14
15
  }
15
16
  const CTX_ERROR_PERCENT = 90;
16
17
  const CTX_WARNING_PERCENT = 70;
17
- export const SEGMENT_ORDER = [
18
- { id: 'workspace', side: 'left', priority: 0, minWidth: 6 },
19
- { id: 'branch', side: 'left', priority: 4 },
20
- { id: 'statuses', side: 'right', priority: 3, minWidth: 8 },
21
- { id: 'model', side: 'right', priority: 2, minWidth: 8 },
22
- { id: 'thinking', side: 'right', priority: 5 },
23
- { id: 'ctx', side: 'right', priority: 1 },
24
- ] as const;
25
- export type SegmentId = (typeof SEGMENT_ORDER)[number]['id'];
26
- export interface Segment {
18
+ type SegmentId = 'workspace' | 'branch' | 'statuses' | 'model' | 'thinking' | 'ctx';
19
+ /** How one segment sits in the row. Segments with the highest `dropOrder` give way first, shrinking to `shrinkTo` columns, or vanishing when they cannot shrink. */
20
+ interface SegmentSpec {
27
21
  readonly id: SegmentId;
28
22
  readonly side: 'left' | 'right';
29
- readonly priority: number;
23
+ readonly dropOrder: number;
24
+ readonly shrinkTo?: number;
25
+ readonly separatorBefore: string;
26
+ readonly tone: (snapshot: FooterSnapshot | undefined) => ThemeColor;
27
+ }
28
+ interface Segment extends SegmentSpec {
30
29
  readonly text: string;
31
- readonly minWidth?: number;
32
30
  }
31
+ const DOT_SEPARATOR = ' · ';
32
+ const SEGMENT_ORDER: readonly SegmentSpec[] = [
33
+ { id: 'workspace', side: 'left', dropOrder: 0, shrinkTo: 0, separatorBefore: DOT_SEPARATOR, tone: () => 'text' },
34
+ { id: 'branch', side: 'left', dropOrder: 4, separatorBefore: DOT_SEPARATOR, tone: () => 'muted' },
35
+ { id: 'statuses', side: 'right', dropOrder: 3, shrinkTo: 8, separatorBefore: DOT_SEPARATOR, tone: () => 'muted' },
36
+ { id: 'model', side: 'right', dropOrder: 2, shrinkTo: 8, separatorBefore: DOT_SEPARATOR, tone: () => 'muted' },
37
+ { id: 'thinking', side: 'right', dropOrder: 5, separatorBefore: DOT_SEPARATOR, tone: () => 'muted' },
38
+ { id: 'ctx', side: 'right', dropOrder: 1, separatorBefore: ' ', tone: (snapshot) => ctxColor(snapshot?.ctxPercent) },
39
+ ];
33
40
  export default function footer(pi: ExtensionAPI): void {
34
41
  let snapshot: FooterSnapshot | undefined;
35
42
  let mounted: TUI | undefined;
@@ -61,16 +68,16 @@ export default function footer(pi: ExtensionAPI): void {
61
68
  pi.on('session_compact', onChange);
62
69
  pi.on('session_tree', onChange);
63
70
  }
64
- export function readSnapshot(ctx: Pick<ExtensionContext, 'cwd' | 'model' | 'getContextUsage'>, thinking: ThinkingLevel): FooterSnapshot {
71
+ function readSnapshot(ctx: Pick<ExtensionContext, 'cwd' | 'model' | 'getContextUsage'>, thinking: ThinkingLevel): FooterSnapshot {
65
72
  return { workspace: basename(ctx.cwd) || ctx.cwd, model: ctx.model?.id, thinking: ctx.model?.reasoning ? thinking : undefined, ctxPercent: ctx.getContextUsage()?.percent ?? null };
66
73
  }
67
- export function sameSnapshot(a: FooterSnapshot, b: FooterSnapshot): boolean {
74
+ function sameSnapshot(a: FooterSnapshot, b: FooterSnapshot): boolean {
68
75
  return a.workspace === b.workspace && a.model === b.model && a.thinking === b.thinking && a.ctxPercent === b.ctxPercent;
69
76
  }
70
77
  function joinSide(segments: readonly Segment[], side: Segment['side'], render: (segment: Segment) => string, separator: (text: string) => string = (text) => text): string {
71
78
  return segments
72
79
  .filter((segment) => segment.side === side)
73
- .map((segment, index) => (index ? separator(segment.id === 'ctx' ? ' ' : ' · ') : '') + render(segment))
80
+ .map((segment, index) => (index ? separator(segment.separatorBefore) : '') + render(segment))
74
81
  .join('');
75
82
  }
76
83
  function rowWidth(segments: readonly Segment[]): number {
@@ -79,20 +86,20 @@ function rowWidth(segments: readonly Segment[]): number {
79
86
  return visibleWidth(left) + visibleWidth(right) + (left && right ? 2 : 0);
80
87
  }
81
88
  function shrinkOnce(fitted: readonly Segment[], target: number): readonly Segment[] {
82
- const lowest = fitted.reduce((a, b) => (a.priority > b.priority || (a.priority === b.priority && a.side === 'right') ? a : b));
83
- const size = visibleWidth(lowest.text);
84
- const min = lowest.priority === 0 ? 0 : lowest.minWidth;
85
- if (min === undefined || size <= min) return fitted.filter((s) => s !== lowest);
86
- const text = fitPlain(lowest.text, Math.max(min, size - (rowWidth(fitted) - target)));
87
- return fitted.map((s) => (s === lowest ? { ...s, text } : s));
89
+ const next = fitted.reduce((a, b) => (b.dropOrder > a.dropOrder ? b : a));
90
+ const size = visibleWidth(next.text);
91
+ const min = next.shrinkTo;
92
+ if (min === undefined || size <= min) return fitted.filter((s) => s !== next);
93
+ const text = fitPlain(next.text, Math.max(min, size - (rowWidth(fitted) - target)));
94
+ return fitted.map((s) => (s === next ? { ...s, text } : s));
88
95
  }
89
- export function fitSegments(segments: readonly Segment[], width: number): readonly Segment[] {
96
+ function fitSegments(segments: readonly Segment[], width: number): readonly Segment[] {
90
97
  const target = Math.max(0, width);
91
98
  let fitted: readonly Segment[] = segments.filter((s) => s.text).map((s) => ({ ...s, text: sanitizeLine(s.text) }));
92
99
  while (rowWidth(fitted) > target) fitted = shrinkOnce(fitted, target);
93
100
  return fitted;
94
101
  }
95
- export function statusText(statuses: ReadonlyMap<string, string>): string {
102
+ function statusText(statuses: ReadonlyMap<string, string>): string {
96
103
  return [...statuses.entries()]
97
104
  .toSorted(([a], [b]) => a.localeCompare(b))
98
105
  .map(([, text]) => sanitizeLine(text).trim())
@@ -122,7 +129,7 @@ function footerLine(theme: Theme, snapshot: FooterSnapshot | undefined, branch:
122
129
  SEGMENT_ORDER.map((s) => ({ ...s, text: texts[s.id] })),
123
130
  inner,
124
131
  );
125
- const style = (s: Segment): string => theme.fg(s.id === 'workspace' ? 'text' : s.id !== 'ctx' ? 'muted' : ctxColor(snapshot?.ctxPercent), s.text);
132
+ const style = (s: Segment): string => theme.fg(s.tone(snapshot), s.text);
126
133
  const separator = (text: string): string => theme.fg('dim', text);
127
134
  const left = joinSide(fitted, 'left', style, separator);
128
135
  const right = joinSide(fitted, 'right', style, separator);
@@ -130,23 +137,12 @@ function footerLine(theme: Theme, snapshot: FooterSnapshot | undefined, branch:
130
137
  return ' '.repeat(g) + left + ' '.repeat(gap) + right;
131
138
  }
132
139
  export function snoopFooter(theme: Theme, data: ReadonlyFooterDataProvider, read: () => FooterSnapshot | undefined, onDispose: () => void, gutter: number): Component & { dispose(): void } {
133
- const cache = cell<{ width: number; snapshot: FooterSnapshot | undefined; branch: string | null; statuses: string; line: string } | undefined>(undefined);
140
+ const lines = memoLast((width: number, snapshot: FooterSnapshot | undefined, branch: string | null, statuses: string) => [footerLine(theme, snapshot, branch, statuses, width, gutter)]);
134
141
  return {
135
- render(width: number): string[] {
136
- const snapshot = read();
137
- const branch = data.getGitBranch();
138
- const statuses = statusText(data.getExtensionStatuses());
139
- const cached = cache.read();
140
- if (cached?.width === width && cached.snapshot === snapshot && cached.branch === branch && cached.statuses === statuses) return [cached.line];
141
- const line = footerLine(theme, snapshot, branch, statuses, width, gutter);
142
- cache.write({ width, snapshot, branch, statuses, line });
143
- return [line];
144
- },
145
- invalidate(): void {
146
- cache.write(undefined);
147
- },
142
+ render: (width: number): string[] => lines.get(width, read(), data.getGitBranch(), statusText(data.getExtensionStatuses())),
143
+ invalidate: lines.reset,
148
144
  dispose(): void {
149
- cache.write(undefined);
145
+ lines.reset();
150
146
  onDispose();
151
147
  },
152
148
  };
package/src/memo.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { cell } from './cell.ts';
2
+
3
+ /** A function that remembers its last call. `reset` forgets it, so the next call computes again. */
4
+ export interface Memo<A extends readonly unknown[], R> {
5
+ readonly get: (...args: A) => R;
6
+ readonly reset: () => void;
7
+ }
8
+
9
+ function sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {
10
+ return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
11
+ }
12
+
13
+ /** Reuses the last result while every argument is unchanged. Pass `same` when some argument needs a structural comparison. */
14
+ export function memoLast<A extends readonly unknown[], R>(compute: (...args: A) => R, same: (a: A, b: A) => boolean = sameArgs): Memo<A, R> {
15
+ const last = cell<{ readonly args: A; readonly value: R } | undefined>(undefined);
16
+ return {
17
+ get(...args) {
18
+ const hit = last.read();
19
+ if (hit && same(hit.args, args)) return hit.value;
20
+ const value = compute(...args);
21
+ last.write({ args, value });
22
+ return value;
23
+ },
24
+ reset() {
25
+ last.write(undefined);
26
+ },
27
+ };
28
+ }
@@ -1,15 +1,9 @@
1
1
  import type { Theme } from '@earendil-works/pi-coding-agent';
2
2
  import { type Component, truncateToWidth } from '@earendil-works/pi-tui';
3
- import { cell } from '../cell.ts';
3
+ import { memoLast } from '../memo.ts';
4
4
  import { fitPlain, sanitizeLine } from '../text.ts';
5
- import type { Preview } from './specs.ts';
6
- import { layoutHeader, ROW_INSET, type RowView } from './view.ts';
5
+ import { layoutHeader, type Preview, ROW_INSET, type RowView } from './view.ts';
7
6
 
8
- interface LinesCache {
9
- readonly width: number;
10
- readonly view: RowView;
11
- readonly lines: string[];
12
- }
13
7
  const MARKERS = {
14
8
  pending: ['dim', '·'],
15
9
  running: ['accent', '•'],
@@ -17,31 +11,26 @@ const MARKERS = {
17
11
  failed: ['error', '✗'],
18
12
  } as const;
19
13
 
20
- export function createRowHeader(view: () => RowView, theme: Theme): Component {
21
- const cache = cell<LinesCache | undefined>(undefined);
14
+ function headerLines(width: number, current: RowView, theme: Theme): string[] {
15
+ const pad = Math.min(current.pad, Math.max(0, width - 1));
16
+ const layout = layoutHeader(current, width - 2 * pad);
17
+ const [color, marker] = MARKERS[current.phase];
18
+ const line =
19
+ ' '.repeat(pad) +
20
+ theme.fg(color, marker) +
21
+ ' ' +
22
+ theme.fg(current.phase === 'pending' ? 'dim' : 'toolTitle', layout.verb) +
23
+ theme.fg(current.phase === 'pending' ? 'dim' : 'text', layout.target) +
24
+ ' '.repeat(layout.gap) +
25
+ theme.fg('dim', layout.meta);
26
+ return [width < pad + ROW_INSET ? truncateToWidth(line, width, '') : line];
27
+ }
28
+
29
+ export function createRowHeader(view: () => RowView, theme: () => Theme): Component {
30
+ const lines = memoLast(headerLines);
22
31
  return {
23
- render(width) {
24
- const current = view();
25
- const cached = cache.read();
26
- if (cached?.width === width && cached.view === current) return cached.lines;
27
- const pad = Math.min(current.pad, Math.max(0, width - 1));
28
- const layout = layoutHeader(current, width - 2 * pad);
29
- const [color, marker] = MARKERS[current.phase];
30
- const line =
31
- ' '.repeat(pad) +
32
- theme.fg(color, marker) +
33
- ' ' +
34
- theme.fg(current.phase === 'pending' ? 'dim' : 'toolTitle', layout.verb) +
35
- theme.fg(current.phase === 'pending' ? 'dim' : 'text', layout.target) +
36
- ' '.repeat(layout.gap) +
37
- theme.fg('dim', layout.meta);
38
- const lines = [width < pad + ROW_INSET ? truncateToWidth(line, width, '') : line];
39
- cache.write({ width, view: current, lines });
40
- return lines;
41
- },
42
- invalidate() {
43
- cache.write(undefined);
44
- },
32
+ render: (width) => lines.get(width, view(), theme()),
33
+ invalidate: lines.reset,
45
34
  };
46
35
  }
47
36
 
@@ -61,24 +50,19 @@ function previewLines(theme: Theme, preview: Preview, hint: string | undefined,
61
50
  }
62
51
  }
63
52
 
64
- export function createRowBody(view: () => RowView, theme: Theme, invalidatePanel: () => void): Component {
65
- const cache = cell<LinesCache | undefined>(undefined);
53
+ export function createRowBody(view: () => RowView, theme: () => Theme): Component {
54
+ const lines = memoLast((width: number, pad: number, preview: Preview, hint: string | undefined, current: Theme) => previewLines(current, preview, hint, Math.min(pad + ROW_INSET, Math.max(0, width - 1)), width));
66
55
  return {
67
56
  render(width) {
68
- const current = view();
69
- const body = current.body;
57
+ const { body, pad } = view();
70
58
  if (body.kind === 'none') return [];
71
59
  if (body.kind === 'panel') return body.panel.render(width);
72
- const cached = cache.read();
73
- if (cached?.width === width && cached.view === current) return cached.lines;
74
- const indent = Math.min(current.pad + ROW_INSET, Math.max(0, width - 1));
75
- const lines = previewLines(theme, body.preview, body.hint, indent, width);
76
- cache.write({ width, view: current, lines });
77
- return lines;
60
+ return lines.get(width, pad, body.preview, body.hint, theme());
78
61
  },
79
62
  invalidate() {
80
- cache.write(undefined);
81
- invalidatePanel();
63
+ lines.reset();
64
+ const { body } = view();
65
+ if (body.kind === 'panel') body.panel.invalidate();
82
66
  },
83
67
  };
84
68
  }
package/src/rows/panel.ts CHANGED
@@ -1,79 +1,61 @@
1
1
  import type { Theme } from '@earendil-works/pi-coding-agent';
2
2
  import { type Component, stripTerminalSequences, Text, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
3
  import { cell } from '../cell.ts';
4
- import { ROW_INSET, type Tone } from './view.ts';
4
+ import { memoLast } from '../memo.ts';
5
+ import { type Panel, ROW_INSET, type Tone } from './view.ts';
5
6
 
6
- export interface Panel extends Component {
7
- showChild(child: Component, tone: Tone): void;
8
- showText(text: string, tone: Tone): void;
9
- }
10
7
  interface PanelContent {
11
8
  readonly child: Component;
12
- readonly frame: ((text: string) => string) | undefined;
13
- }
14
- interface PanelCache {
15
- readonly width: number;
16
- readonly source: readonly string[];
17
- readonly lines: string[];
9
+ readonly tone: Tone;
10
+ readonly framed: boolean;
18
11
  }
19
- const SGR_PARAMS = /^[\d;]*$/;
12
+ /** Everything a panel's lines depend on. The memo reuses them only while all of it is unchanged. */
13
+ type Layout = readonly [width: number, indent: number, boxWidth: number, theme: Theme, frame: Tone | undefined, source: readonly string[]];
14
+ const SOURCE = 5;
15
+ const BACKGROUNDS = { ok: 'toolPendingBg', error: 'toolErrorBg' } as const satisfies Record<Tone, string>;
20
16
  const MIN_FRAMED_WIDTH = 3;
21
17
 
22
18
  function sameLines(a: readonly string[], b: readonly string[]): boolean {
23
19
  return a === b || (a.length === b.length && a.every((line, i) => line === b[i]));
24
20
  }
25
- // Skips color codes in place. `stripTerminalSequences` copies every line, so it only settles other escapes.
26
- function isBlank(line: string | undefined): boolean {
27
- const text = line ?? '';
28
- for (let i = 0; i < text.length; i++) {
29
- if (text[i] === '\x1b') {
30
- const end = text.indexOf('m', i);
31
- if (text[i + 1] !== '[' || end === -1 || !SGR_PARAMS.test(text.slice(i + 2, end))) return stripTerminalSequences(text).trim() === '';
32
- i = end;
33
- } else if (text[i]?.trim()) {
34
- return false;
35
- }
36
- }
37
- return true;
21
+ function sameLayout(a: Layout, b: Layout): boolean {
22
+ return a.every((value, i) => (i === SOURCE ? sameLines(a[SOURCE], b[SOURCE]) : Object.is(value, b[i])));
23
+ }
24
+ function isBlank(line: string): boolean {
25
+ return stripTerminalSequences(line).trim() === '';
38
26
  }
39
27
  function trimBlankEdges(source: readonly string[]): readonly string[] {
40
- let start = 0;
41
- let end = source.length;
42
- while (start < end && isBlank(source[start])) start++;
43
- while (end > start && isBlank(source[end - 1])) end--;
44
- return source.slice(start, end);
28
+ const start = source.findIndex((line) => !isBlank(line));
29
+ return start === -1 ? [] : source.slice(start, source.findLastIndex((line) => !isBlank(line)) + 1);
30
+ }
31
+ function layoutLines(...[width, indent, boxWidth, theme, frame, source]: Layout): string[] {
32
+ const prefix = ' '.repeat(indent);
33
+ return trimBlankEdges(source).map((line) => {
34
+ const framed = frame ? theme.bg(BACKGROUNDS[frame], ` ${line}${' '.repeat(Math.max(0, boxWidth - 1 - visibleWidth(line)))}`) : line;
35
+ return boxWidth < MIN_FRAMED_WIDTH ? truncateToWidth(prefix + framed, width, '') : prefix + framed;
36
+ });
45
37
  }
46
38
 
47
- export function createPanel(theme: Theme, pad: () => number): Panel {
48
- const backgrounds: Record<Tone, (text: string) => string> = { ok: (text) => theme.bg('toolPendingBg', text), error: (text) => theme.bg('toolErrorBg', text) };
49
- const content = cell<PanelContent>({ child: new Text('', 0, 0), frame: undefined });
50
- const cache = cell<PanelCache | undefined>(undefined);
39
+ export function createPanel(theme: () => Theme, pad: () => number): Panel {
40
+ const background = (tone: Tone) => (text: string) => theme().bg(BACKGROUNDS[tone], text);
41
+ const content = cell<PanelContent>({ child: new Text('', 0, 0), tone: 'ok', framed: false });
42
+ const lines = memoLast(layoutLines, sameLayout);
51
43
  return {
52
44
  showChild(child, tone) {
53
- if (content.read().frame !== backgrounds[tone]) cache.write(undefined);
54
- content.write({ child, frame: backgrounds[tone] });
45
+ content.write({ child, tone, framed: true });
55
46
  },
56
47
  showText(text, tone) {
57
- content.write({ child: new Text(text, 1, 0, backgrounds[tone]), frame: undefined });
58
- cache.write(undefined);
48
+ content.write({ child: new Text(text, 1, 0, background(tone)), tone, framed: false });
59
49
  },
60
50
  render(width) {
61
- const { child, frame } = content.read();
51
+ const { child, tone, framed } = content.read();
62
52
  const indent = Math.min(pad() + ROW_INSET, Math.max(0, width - 1));
63
53
  const boxWidth = Math.max(1, width - indent - pad());
64
- const source = child.render(frame ? Math.max(1, boxWidth - 2) : boxWidth);
65
- const cached = cache.read();
66
- if (cached?.width === width && sameLines(cached.source, source)) return cached.lines;
67
- const prefix = ' '.repeat(indent);
68
- const lines = trimBlankEdges(source).map((line) => {
69
- const framed = frame ? frame(` ${line}${' '.repeat(Math.max(0, boxWidth - 1 - visibleWidth(line)))}`) : line;
70
- return boxWidth < MIN_FRAMED_WIDTH ? truncateToWidth(prefix + framed, width, '') : prefix + framed;
71
- });
72
- cache.write({ width, source, lines });
73
- return lines;
54
+ const source = child.render(framed ? Math.max(1, boxWidth - 2) : boxWidth);
55
+ return lines.get(width, indent, boxWidth, theme(), framed ? tone : undefined, source);
74
56
  },
75
57
  invalidate() {
76
- cache.write(undefined);
58
+ lines.reset();
77
59
  content.read().child.invalidate();
78
60
  },
79
61
  };
package/src/rows/row.ts CHANGED
@@ -1,28 +1,24 @@
1
1
  import type { AgentToolResult, Theme, ToolRenderers, ToolRenderResultOptions } from '@earendil-works/pi-coding-agent';
2
2
  import type { Component } from '@earendil-works/pi-tui';
3
3
  import { type Cell, cell } from '../cell.ts';
4
+ import { type Memo, memoLast } from '../memo.ts';
4
5
  import { sanitizeLine } from '../text.ts';
5
6
  import { createRowBody, createRowHeader } from './components.ts';
6
- import { createPanel, type Panel } from './panel.ts';
7
+ import { createPanel } from './panel.ts';
7
8
  import type { ResultSummary, ToolSpec } from './specs.ts';
8
- import { type BodyView, derivePhase, type RowView, sameBody, type ToolRenderContext } from './view.ts';
9
+ import { type BodyView, derivePhase, type Panel, type RowView, sameView, type ToolRenderContext } from './view.ts';
9
10
 
10
11
  const ROW_STATE = Symbol('snoop.rowState');
11
- interface SummaryMemo {
12
- readonly content: AgentToolResult<unknown>['content'];
13
- readonly details: unknown;
14
- readonly args: unknown;
15
- readonly isPartial: boolean;
16
- readonly isError: boolean;
17
- readonly value: ResultSummary;
18
- }
12
+ type Content = AgentToolResult<unknown>['content'];
13
+ type SummaryArgs = [content: Content, details: unknown, args: unknown, isPartial: boolean, isError: boolean];
19
14
  interface RowState {
20
15
  readonly [ROW_STATE]: true;
21
16
  readonly view: Cell<RowView>;
22
- readonly summary: Cell<SummaryMemo | undefined>;
17
+ /** The theme of the latest render call, so a theme swap restyles rows that already exist. */
18
+ readonly theme: Cell<Theme>;
19
+ readonly summary: Memo<SummaryArgs, ResultSummary>;
23
20
  readonly native: Record<string, unknown>;
24
21
  readonly nativeResult: Cell<Component | undefined>;
25
- readonly panel: Cell<Panel | undefined>;
26
22
  readonly header: Component;
27
23
  readonly body: Component;
28
24
  }
@@ -33,18 +29,24 @@ function isRecord(value: unknown): value is Record<string, unknown> {
33
29
  function parseArgs(args: unknown): Record<string, unknown> {
34
30
  return isRecord(args) ? args : {};
35
31
  }
32
+ function textOf(content: Content): string {
33
+ return content
34
+ .filter((c) => c.type === 'text')
35
+ .map((c) => c.text)
36
+ .join('\n');
37
+ }
36
38
  function createRowState(spec: ToolSpec, theme: Theme, ctx: ToolRenderContext): RowState {
37
39
  const view = cell(Object.freeze<RowView>({ phase: derivePhase(ctx), verb: spec.verb, target: spec.target(parseArgs(ctx.args), ctx.cwd), meta: undefined, body: { kind: 'none' }, pad: ctx.outputPad }));
38
- const panel = cell<Panel | undefined>(undefined);
40
+ const live = cell(theme);
39
41
  return {
40
42
  [ROW_STATE]: true,
41
43
  view,
42
- summary: cell<SummaryMemo | undefined>(undefined),
44
+ theme: live,
45
+ summary: memoLast((content, details, args, isPartial, isError) => spec.summarize({ args: parseArgs(args), text: textOf(content), images: content.filter((c) => c.type === 'image').length, details, isError, isPartial })),
43
46
  native: {},
44
47
  nativeResult: cell<Component | undefined>(undefined),
45
- panel,
46
- header: createRowHeader(view.read, theme),
47
- body: createRowBody(view.read, theme, () => panel.read()?.invalidate()),
48
+ header: createRowHeader(view.read, live.read),
49
+ body: createRowBody(view.read, live.read),
48
50
  };
49
51
  }
50
52
  function isRowState(value: unknown): value is RowState {
@@ -53,16 +55,22 @@ function isRowState(value: unknown): value is RowState {
53
55
  function rowState(ctx: ToolRenderContext, spec: ToolSpec, theme: Theme): RowState {
54
56
  const bag: unknown = ctx.state;
55
57
  const existing: unknown = isRecord(bag) ? Reflect.get(bag, 'snoop') : undefined;
56
- if (isRowState(existing)) return existing;
58
+ if (isRowState(existing)) {
59
+ existing.theme.write(theme);
60
+ return existing;
61
+ }
57
62
  const created = createRowState(spec, theme, ctx);
58
63
  if (isRecord(bag)) Reflect.set(bag, 'snoop', created);
59
64
  return created;
60
65
  }
61
66
 
67
+ function openPanel(state: RowState): Panel {
68
+ const { body } = state.view.read();
69
+ return body.kind === 'panel' ? body.panel : createPanel(state.theme.read, () => state.view.read().pad);
70
+ }
62
71
  function expandedBody(state: RowState, native: ToolRenderers, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, theme: Theme, ctx: ToolRenderContext): BodyView {
63
72
  const tone = ctx.isError ? 'error' : 'ok';
64
- const panel = state.panel.read() ?? createPanel(theme, () => state.view.read().pad);
65
- state.panel.write(panel);
73
+ const panel = openPanel(state);
66
74
  if (native.renderResult) {
67
75
  // Native call renderers start timers and edit previews. Only delegate result detail.
68
76
  const nativeResult = native.renderResult(result, options, theme, { ...ctx, state: state.native, lastComponent: state.nativeResult.read(), outputPad: 0 });
@@ -89,7 +97,7 @@ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRen
89
97
  },
90
98
  renderResult(result, options, theme, ctx) {
91
99
  const state = rowState(ctx, spec, theme);
92
- const summary = summarizeOnce(state, spec, result, options, ctx);
100
+ const summary = state.summary.get(result.content, result.details, ctx.args, options.isPartial, ctx.isError);
93
101
  const body = resultBody(state, native, summary, result, options, theme, ctx);
94
102
  commit(state, { ...state.view.read(), phase: derivePhase(ctx), meta: summary.meta, body });
95
103
  return state.body;
@@ -97,31 +105,10 @@ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRen
97
105
  };
98
106
  }
99
107
  function plainDetail(theme: Theme, args: unknown, result: AgentToolResult<unknown>): string {
100
- const output = result.content
101
- .filter((c) => c.type === 'text')
102
- .map((c) => c.text)
103
- .join('\n')
104
- .split('\n')
105
- .map(sanitizeLine)
106
- .join('\n');
108
+ const output = textOf(result.content).split('\n').map(sanitizeLine).join('\n');
107
109
  const json = sanitizeLine(JSON.stringify(args) ?? '');
108
110
  return [json && theme.fg('dim', json), output && theme.fg('toolOutput', output)].filter(Boolean).join('\n\n');
109
111
  }
110
112
  function commit(state: RowState, next: RowView): void {
111
- const prev = state.view.read();
112
- if (prev.phase === next.phase && prev.verb === next.verb && prev.pad === next.pad && prev.target.text === next.target.text && prev.target.kind === next.target.kind && prev.meta === next.meta && sameBody(prev.body, next.body)) return;
113
- if (prev.pad !== next.pad) state.panel.read()?.invalidate();
114
- state.view.write(Object.freeze(next));
115
- }
116
- function summarizeOnce(state: RowState, spec: ToolSpec, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, ctx: ToolRenderContext): ResultSummary {
117
- const memo = state.summary.read();
118
- if (memo && memo.content === result.content && memo.details === result.details && memo.args === ctx.args && memo.isPartial === options.isPartial && memo.isError === ctx.isError) return memo.value;
119
- const text = result.content
120
- .filter((c) => c.type === 'text')
121
- .map((c) => c.text)
122
- .join('\n');
123
- const images = result.content.filter((c) => c.type === 'image').length;
124
- const value = spec.summarize({ args: parseArgs(ctx.args), text, images, details: result.details, isError: ctx.isError, isPartial: options.isPartial });
125
- state.summary.write({ content: result.content, details: result.details, args: ctx.args, isPartial: options.isPartial, isError: ctx.isError, value });
126
- return value;
113
+ if (!sameView(state.view.read(), next)) state.view.write(Object.freeze(next));
127
114
  }
package/src/rows/specs.ts CHANGED
@@ -1,11 +1,9 @@
1
+ import { homedir } from 'node:os';
2
+
1
3
  import { formatReadLineRange } from '@earendil-works/pi-coding-agent';
2
- import { z } from 'zod';
3
- import { countLines, headLines, type LineSlice, tailLines } from '../text.ts';
4
+ import { countLines, headLines, tailLines } from '../text.ts';
5
+ import type { Preview, TargetText } from './view.ts';
4
6
 
5
- export interface Preview extends LineSlice {
6
- readonly tone: 'output' | 'error';
7
- readonly from: 'head' | 'tail';
8
- }
9
7
  export interface ResultSummary {
10
8
  readonly meta: string | undefined;
11
9
  readonly preview: Preview | undefined;
@@ -27,22 +25,13 @@ export interface ResultInput {
27
25
  readonly isError: boolean;
28
26
  readonly isPartial: boolean;
29
27
  }
30
- export interface TargetText {
31
- readonly text: string;
32
- readonly kind: 'path' | 'plain';
33
- }
34
28
  export interface ToolSpec {
35
29
  readonly verb: string;
36
- target(args: ToolArgs | undefined, cwd: string): TargetText;
30
+ target(args: ToolArgs, cwd: string): TargetText;
37
31
  summarize(input: ResultInput): ResultSummary;
38
32
  }
39
33
  export const RUNNING_TAIL_LINES = 3;
40
34
  export const ERROR_PREVIEW_LINES = 5;
41
- const HomeEnv = z.object({ HOME: z.string().optional(), USERPROFILE: z.string().optional() });
42
- function homeDir(): string | undefined {
43
- const env = HomeEnv.parse(process.env);
44
- return env.HOME ?? env.USERPROFILE;
45
- }
46
35
  const STATUS_TAIL_CHARS = 200;
47
36
 
48
37
  function str(value: unknown): string {
@@ -54,12 +43,21 @@ function field(value: unknown, key: string): unknown {
54
43
  function relPath(value: unknown, cwd: string): string {
55
44
  const path = str(value);
56
45
  if (path.startsWith(`${cwd}/`)) return path.slice(cwd.length + 1);
57
- const home = homeDir();
46
+ const home = homedir();
58
47
  if (home && (path === home || path.startsWith(`${home}/`))) return `~${path.slice(home.length)}`;
59
48
  return path;
60
49
  }
61
- function pathTarget(args: ToolArgs | undefined, cwd: string): TargetText {
62
- return { kind: 'path', text: relPath(args?.path, cwd) };
50
+ function pathTarget(args: ToolArgs, cwd: string): TargetText {
51
+ return { kind: 'path', text: relPath(args.path, cwd) };
52
+ }
53
+ /** The exit status a failed command reports on its last line, such as `exit 2`. */
54
+ function parseExit(text: string): string | undefined {
55
+ const code = /exit(?:ed with)? code (\d+)\s*$/i.exec(text.slice(-STATUS_TAIL_CHARS))?.[1];
56
+ return code === undefined ? undefined : `exit ${code}`;
57
+ }
58
+ function totalLines(details: unknown): number | undefined {
59
+ const total = field(field(details, 'truncation'), 'totalLines');
60
+ return typeof total === 'number' ? total : undefined;
63
61
  }
64
62
  function firstLine(text: string): string {
65
63
  const end = text.indexOf('\n');
@@ -95,24 +93,30 @@ function countPatchLines(patch: string): { added: number; removed: number } {
95
93
  }
96
94
  function listing(input: ResultInput, unit: 'match' | 'file' | 'entry', limit: string, empty: string): ResultSummary {
97
95
  return checked(input, () => {
98
- const total = field(field(input.details, 'truncation'), 'totalLines');
99
- const count = input.text.startsWith(empty) ? 0 : typeof total === 'number' ? total : countLines(withoutNotice(input.text));
96
+ const count = input.text.startsWith(empty) ? 0 : (totalLines(input.details) ?? countLines(withoutNotice(input.text)));
100
97
  return summary(units(count, unit, Boolean(field(input.details, limit))));
101
98
  });
102
99
  }
100
+ function bashFailure(input: ResultInput): ResultSummary {
101
+ const rawTail = input.text.slice(-STATUS_TAIL_CHARS);
102
+ const tail = rawTail.trimEnd();
103
+ const meta = parseExit(input.text) ?? (/Command timed out/.test(tail) ? 'timeout' : /Command aborted$/.test(tail) ? 'aborted' : 'failed');
104
+ const status = /Command (?:exited with code \d+|timed out[^\n]*|aborted)$/.exec(tail);
105
+ const text = status ? input.text.slice(0, input.text.length - rawTail.length + status.index).trimEnd() : input.text;
106
+ return { meta, preview: { ...tailLines(text, ERROR_PREVIEW_LINES), tone: 'error', from: 'tail' } };
107
+ }
103
108
 
104
109
  export const TOOL_SPECS = {
105
110
  read: {
106
111
  verb: 'read',
107
112
  target: (args, cwd) => ({
108
113
  kind: 'path',
109
- text: relPath(args?.path, cwd) + formatReadLineRange(typeof args?.offset === 'number' ? args.offset : undefined, typeof args?.limit === 'number' ? args.limit : undefined),
114
+ text: relPath(args.path, cwd) + formatReadLineRange(typeof args.offset === 'number' ? args.offset : undefined, typeof args.limit === 'number' ? args.limit : undefined),
110
115
  }),
111
116
  summarize: (input) =>
112
117
  checked(input, () => {
113
118
  if (input.images > 0) return summary('image');
114
- const total = field(field(input.details, 'truncation'), 'totalLines');
115
- return summary(units(typeof total === 'number' ? total : countLines(withoutNotice(input.text)), 'line'));
119
+ return summary(units(totalLines(input.details) ?? countLines(withoutNotice(input.text)), 'line'));
116
120
  }),
117
121
  },
118
122
  edit: {
@@ -132,38 +136,30 @@ export const TOOL_SPECS = {
132
136
  },
133
137
  bash: {
134
138
  verb: 'bash',
135
- target: (args) => ({ kind: 'plain', text: firstLine(str(args?.command)) }),
139
+ target: (args) => ({ kind: 'plain', text: firstLine(str(args.command)) }),
136
140
  summarize: (input) => {
137
141
  if (input.isPartial) return { meta: undefined, preview: { ...tailLines(input.text, RUNNING_TAIL_LINES), tone: 'output', from: 'tail' } };
138
- if (!input.isError) return summary('exit 0');
139
- const rawTail = input.text.slice(-STATUS_TAIL_CHARS);
140
- const tail = rawTail.trimEnd();
141
- const exit = /Command exited with code (\d+)$/.exec(tail);
142
- const meta = exit ? `exit ${exit[1]}` : /Command timed out/.test(tail) ? 'timeout' : /Command aborted$/.test(tail) ? 'aborted' : 'failed';
143
- const status = /Command (?:exited with code \d+|timed out[^\n]*|aborted)$/.exec(tail);
144
- const text = status ? input.text.slice(0, input.text.length - rawTail.length + status.index).trimEnd() : input.text;
145
- return { meta, preview: { ...tailLines(text, ERROR_PREVIEW_LINES), tone: 'error', from: 'tail' } };
142
+ return input.isError ? bashFailure(input) : summary('exit 0');
146
143
  },
147
144
  },
148
145
  grep: {
149
146
  verb: 'grep',
150
- target: (args) => ({ kind: 'plain', text: str(args?.pattern) + (typeof args?.path === 'string' ? ` ${args.path}` : '') }),
147
+ target: (args) => ({ kind: 'plain', text: str(args.pattern) + (typeof args.path === 'string' ? ` ${args.path}` : '') }),
151
148
  summarize: (input) => (input.text === 'No matches found' && !input.isError ? summary('no matches') : listing(input, 'match', 'matchLimitReached', 'No matches found')),
152
149
  },
153
150
  find: {
154
151
  verb: 'find',
155
- target: (args) => ({ kind: 'plain', text: str(args?.pattern) }),
152
+ target: (args) => ({ kind: 'plain', text: str(args.pattern) }),
156
153
  summarize: (input) => listing(input, 'file', 'resultLimitReached', 'No files found'),
157
154
  },
158
155
  ls: {
159
156
  verb: 'ls',
160
- target: (args, cwd) => pathTarget({ path: args?.path ?? '.' }, cwd),
157
+ target: (args, cwd) => pathTarget({ path: args.path ?? '.' }, cwd),
161
158
  summarize: (input) => listing(input, 'entry', 'entryLimitReached', '(empty directory)'),
162
159
  },
163
160
  } satisfies Record<string, ToolSpec>;
164
161
 
165
162
  export type CompactToolName = keyof typeof TOOL_SPECS;
166
- export const VERB_COLUMN = 8;
167
163
  export function isCompactTool(name: string): name is CompactToolName {
168
164
  return Object.hasOwn(TOOL_SPECS, name);
169
165
  }
@@ -174,17 +170,13 @@ export function genericSpec(toolName: string): ToolSpec {
174
170
  return {
175
171
  verb: toolName,
176
172
  target: (args, cwd) => {
177
- const fields = args ?? {};
178
- const key = TARGET_KEYS.find((name) => typeof fields[name] === 'string') ?? Object.keys(fields).find((name) => typeof fields[name] === 'string');
179
- const value = key === undefined ? '' : str(fields[key]);
173
+ const key = TARGET_KEYS.find((name) => typeof args[name] === 'string') ?? Object.keys(args).find((name) => typeof args[name] === 'string');
174
+ const value = key === undefined ? '' : str(args[key]);
180
175
  return key === 'path' ? { kind: 'path', text: relPath(value, cwd) } : { kind: 'plain', text: firstLine(value) };
181
176
  },
182
177
  summarize: (input) => {
183
178
  if (input.isPartial) return { meta: undefined, preview: undefined };
184
- if (input.isError) {
185
- const exit = /exit(?:ed with)? code (\d+)\s*$/i.exec(input.text.slice(-STATUS_TAIL_CHARS));
186
- return failed(input, exit ? `exit ${exit[1]}` : 'failed');
187
- }
179
+ if (input.isError) return failed(input, parseExit(input.text) ?? 'failed');
188
180
  return summary(input.images > 0 ? 'image' : units(countLines(input.text), 'line'));
189
181
  },
190
182
  };
package/src/rows/view.ts CHANGED
@@ -1,13 +1,24 @@
1
1
  import type { ToolRenderers } from '@earendil-works/pi-coding-agent';
2
2
  import type { Component } from '@earendil-works/pi-tui';
3
3
  import { visibleWidth } from '@earendil-works/pi-tui';
4
- import { fitPath, fitPlain, sanitizeLine } from '../text.ts';
5
- import { type Preview, type TargetText, VERB_COLUMN } from './specs.ts';
4
+ import { fitPath, fitPlain, type LineSlice, sanitizeLine } from '../text.ts';
6
5
 
7
6
  export type ToolRenderContext = Parameters<NonNullable<ToolRenderers['renderCall']>>[2];
8
7
  export type RowPhase = 'pending' | 'running' | 'done' | 'failed';
9
8
  export type Tone = 'ok' | 'error';
10
- export type BodyView = { readonly kind: 'none' } | { readonly kind: 'preview'; readonly preview: Preview; readonly hint: string | undefined } | { readonly kind: 'panel'; readonly panel: Component; readonly tone: Tone };
9
+ export interface Preview extends LineSlice {
10
+ readonly tone: 'output' | 'error';
11
+ readonly from: 'head' | 'tail';
12
+ }
13
+ export interface TargetText {
14
+ readonly text: string;
15
+ readonly kind: 'path' | 'plain';
16
+ }
17
+ export interface Panel extends Component {
18
+ showChild(child: Component, tone: Tone): void;
19
+ showText(text: string, tone: Tone): void;
20
+ }
21
+ export type BodyView = { readonly kind: 'none' } | { readonly kind: 'preview'; readonly preview: Preview; readonly hint: string | undefined } | { readonly kind: 'panel'; readonly panel: Panel; readonly tone: Tone };
11
22
  export interface RowView {
12
23
  readonly phase: RowPhase;
13
24
  readonly verb: string;
@@ -18,6 +29,8 @@ export interface RowView {
18
29
  }
19
30
  /** Columns taken by the marker and its gap, and the indent of body lines under the header. */
20
31
  export const ROW_INSET = 3;
32
+ /** Columns the verb takes before the target starts. */
33
+ export const VERB_COLUMN = 8;
21
34
  const META_MIN_ROOM = 10;
22
35
 
23
36
  export function derivePhase(ctx: Pick<ToolRenderContext, 'executionStarted' | 'isPartial' | 'isError'>): RowPhase {
@@ -39,9 +52,12 @@ export function layoutHeader(view: Pick<RowView, 'verb' | 'target' | 'meta'>, wi
39
52
  const target = (view.target.kind === 'path' ? fitPath : fitPlain)(sanitizeLine(view.target.text), rest - (meta ? visibleWidth(meta) + 2 : 0));
40
53
  return { verb, target, meta, gap: meta ? rest - visibleWidth(target) - visibleWidth(meta) : 0 };
41
54
  }
42
- export function sameBody(a: BodyView, b: BodyView): boolean {
55
+ function sameBody(a: BodyView, b: BodyView): boolean {
43
56
  if (a.kind !== b.kind) return false;
44
57
  if (a.kind === 'none' && b.kind === 'none') return true;
45
58
  if (a.kind === 'preview' && b.kind === 'preview') return a.preview === b.preview && a.hint === b.hint;
46
59
  return a.kind === 'panel' && b.kind === 'panel' && a.panel === b.panel && a.tone === b.tone;
47
60
  }
61
+ export function sameView(a: RowView, b: RowView): boolean {
62
+ return a.phase === b.phase && a.verb === b.verb && a.pad === b.pad && a.target.text === b.target.text && a.target.kind === b.target.kind && a.meta === b.meta && sameBody(a.body, b.body);
63
+ }