@justjoshn/pi-snoop-tui 0.1.2 → 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 +9 -0
- package/package.json +1 -1
- package/src/chrome.ts +8 -17
- package/src/editor.ts +16 -37
- package/src/footer.ts +36 -40
- package/src/memo.ts +28 -0
- package/src/rows/components.ts +28 -44
- package/src/rows/panel.ts +32 -50
- package/src/rows/row.ts +38 -47
- package/src/rows/specs.ts +37 -42
- package/src/rows/view.ts +20 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
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
|
+
|
|
8
|
+
## [0.1.3]
|
|
9
|
+
|
|
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.
|
|
11
|
+
|
|
3
12
|
## [0.1.2]
|
|
4
13
|
|
|
5
14
|
- Rewrite every test as a user behavior test. Tests load the extensions the way Pi does and assert the rendered tool rows, footer, header, and editor with the snoop themes. No behavior changes.
|
package/package.json
CHANGED
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
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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 =
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 +
|
|
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.
|
|
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(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.
|
|
90
|
-
this.bottomRule.
|
|
91
|
-
this.prompt.
|
|
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 {
|
|
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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
83
|
-
const size = visibleWidth(
|
|
84
|
-
const min =
|
|
85
|
-
if (min === undefined || size <= min) return fitted.filter((s) => s !==
|
|
86
|
-
const text = fitPlain(
|
|
87
|
-
return fitted.map((s) => (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
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
+
}
|
package/src/rows/components.ts
CHANGED
|
@@ -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 {
|
|
3
|
+
import { memoLast } from '../memo.ts';
|
|
4
4
|
import { fitPlain, sanitizeLine } from '../text.ts';
|
|
5
|
-
import type
|
|
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
|
-
|
|
21
|
-
const
|
|
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
|
-
|
|
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:
|
|
65
|
-
const
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
81
|
-
|
|
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 {
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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
|
|
49
|
-
const content = cell<PanelContent>({ child: new Text('', 0, 0),
|
|
50
|
-
const
|
|
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
|
-
|
|
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,
|
|
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,
|
|
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(
|
|
65
|
-
|
|
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
|
-
|
|
58
|
+
lines.reset();
|
|
77
59
|
content.read().child.invalidate();
|
|
78
60
|
},
|
|
79
61
|
};
|
package/src/rows/row.ts
CHANGED
|
@@ -1,64 +1,76 @@
|
|
|
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
|
|
7
|
+
import { createPanel } from './panel.ts';
|
|
7
8
|
import type { ResultSummary, ToolSpec } from './specs.ts';
|
|
8
|
-
import { type BodyView, derivePhase, type RowView,
|
|
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
|
-
|
|
12
|
-
|
|
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
|
-
|
|
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
|
}
|
|
29
25
|
|
|
26
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
27
|
+
return value !== null && typeof value === 'object';
|
|
28
|
+
}
|
|
30
29
|
function parseArgs(args: unknown): Record<string, unknown> {
|
|
31
|
-
return args
|
|
30
|
+
return isRecord(args) ? args : {};
|
|
31
|
+
}
|
|
32
|
+
function textOf(content: Content): string {
|
|
33
|
+
return content
|
|
34
|
+
.filter((c) => c.type === 'text')
|
|
35
|
+
.map((c) => c.text)
|
|
36
|
+
.join('\n');
|
|
32
37
|
}
|
|
33
38
|
function createRowState(spec: ToolSpec, theme: Theme, ctx: ToolRenderContext): RowState {
|
|
34
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 }));
|
|
35
|
-
const
|
|
40
|
+
const live = cell(theme);
|
|
36
41
|
return {
|
|
37
42
|
[ROW_STATE]: true,
|
|
38
43
|
view,
|
|
39
|
-
|
|
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 })),
|
|
40
46
|
native: {},
|
|
41
47
|
nativeResult: cell<Component | undefined>(undefined),
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
body: createRowBody(view.read, theme, () => panel.read()?.invalidate()),
|
|
48
|
+
header: createRowHeader(view.read, live.read),
|
|
49
|
+
body: createRowBody(view.read, live.read),
|
|
45
50
|
};
|
|
46
51
|
}
|
|
47
52
|
function isRowState(value: unknown): value is RowState {
|
|
48
53
|
return typeof value === 'object' && value !== null && ROW_STATE in value;
|
|
49
54
|
}
|
|
50
55
|
function rowState(ctx: ToolRenderContext, spec: ToolSpec, theme: Theme): RowState {
|
|
51
|
-
const
|
|
52
|
-
|
|
56
|
+
const bag: unknown = ctx.state;
|
|
57
|
+
const existing: unknown = isRecord(bag) ? Reflect.get(bag, 'snoop') : undefined;
|
|
58
|
+
if (isRowState(existing)) {
|
|
59
|
+
existing.theme.write(theme);
|
|
60
|
+
return existing;
|
|
61
|
+
}
|
|
53
62
|
const created = createRowState(spec, theme, ctx);
|
|
54
|
-
|
|
63
|
+
if (isRecord(bag)) Reflect.set(bag, 'snoop', created);
|
|
55
64
|
return created;
|
|
56
65
|
}
|
|
57
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
|
+
}
|
|
58
71
|
function expandedBody(state: RowState, native: ToolRenderers, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, theme: Theme, ctx: ToolRenderContext): BodyView {
|
|
59
72
|
const tone = ctx.isError ? 'error' : 'ok';
|
|
60
|
-
const panel =
|
|
61
|
-
state.panel.write(panel);
|
|
73
|
+
const panel = openPanel(state);
|
|
62
74
|
if (native.renderResult) {
|
|
63
75
|
// Native call renderers start timers and edit previews. Only delegate result detail.
|
|
64
76
|
const nativeResult = native.renderResult(result, options, theme, { ...ctx, state: state.native, lastComponent: state.nativeResult.read(), outputPad: 0 });
|
|
@@ -85,7 +97,7 @@ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRen
|
|
|
85
97
|
},
|
|
86
98
|
renderResult(result, options, theme, ctx) {
|
|
87
99
|
const state = rowState(ctx, spec, theme);
|
|
88
|
-
const summary =
|
|
100
|
+
const summary = state.summary.get(result.content, result.details, ctx.args, options.isPartial, ctx.isError);
|
|
89
101
|
const body = resultBody(state, native, summary, result, options, theme, ctx);
|
|
90
102
|
commit(state, { ...state.view.read(), phase: derivePhase(ctx), meta: summary.meta, body });
|
|
91
103
|
return state.body;
|
|
@@ -93,31 +105,10 @@ export function compactRenderers(spec: ToolSpec, native: ToolRenderers): ToolRen
|
|
|
93
105
|
};
|
|
94
106
|
}
|
|
95
107
|
function plainDetail(theme: Theme, args: unknown, result: AgentToolResult<unknown>): string {
|
|
96
|
-
const output = result.content
|
|
97
|
-
.filter((c) => c.type === 'text')
|
|
98
|
-
.map((c) => c.text)
|
|
99
|
-
.join('\n')
|
|
100
|
-
.split('\n')
|
|
101
|
-
.map(sanitizeLine)
|
|
102
|
-
.join('\n');
|
|
108
|
+
const output = textOf(result.content).split('\n').map(sanitizeLine).join('\n');
|
|
103
109
|
const json = sanitizeLine(JSON.stringify(args) ?? '');
|
|
104
110
|
return [json && theme.fg('dim', json), output && theme.fg('toolOutput', output)].filter(Boolean).join('\n\n');
|
|
105
111
|
}
|
|
106
112
|
function commit(state: RowState, next: RowView): void {
|
|
107
|
-
|
|
108
|
-
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;
|
|
109
|
-
if (prev.pad !== next.pad) state.panel.read()?.invalidate();
|
|
110
|
-
state.view.write(Object.freeze(next));
|
|
111
|
-
}
|
|
112
|
-
function summarizeOnce(state: RowState, spec: ToolSpec, result: AgentToolResult<unknown>, options: ToolRenderResultOptions, ctx: ToolRenderContext): ResultSummary {
|
|
113
|
-
const memo = state.summary.read();
|
|
114
|
-
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;
|
|
115
|
-
const text = result.content
|
|
116
|
-
.filter((c) => c.type === 'text')
|
|
117
|
-
.map((c) => c.text)
|
|
118
|
-
.join('\n');
|
|
119
|
-
const images = result.content.filter((c) => c.type === 'image').length;
|
|
120
|
-
const value = spec.summarize({ args: parseArgs(ctx.args), text, images, details: result.details, isError: ctx.isError, isPartial: options.isPartial });
|
|
121
|
-
state.summary.write({ content: result.content, details: result.details, args: ctx.args, isPartial: options.isPartial, isError: ctx.isError, value });
|
|
122
|
-
return value;
|
|
113
|
+
if (!sameView(state.view.read(), next)) state.view.write(Object.freeze(next));
|
|
123
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 {
|
|
3
|
-
import {
|
|
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,20 +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
|
|
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
|
-
const homeEnv = HomeEnv.parse(process.env);
|
|
43
|
-
const HOME = homeEnv.HOME ?? homeEnv.USERPROFILE;
|
|
44
35
|
const STATUS_TAIL_CHARS = 200;
|
|
45
36
|
|
|
46
37
|
function str(value: unknown): string {
|
|
@@ -52,11 +43,21 @@ function field(value: unknown, key: string): unknown {
|
|
|
52
43
|
function relPath(value: unknown, cwd: string): string {
|
|
53
44
|
const path = str(value);
|
|
54
45
|
if (path.startsWith(`${cwd}/`)) return path.slice(cwd.length + 1);
|
|
55
|
-
|
|
46
|
+
const home = homedir();
|
|
47
|
+
if (home && (path === home || path.startsWith(`${home}/`))) return `~${path.slice(home.length)}`;
|
|
56
48
|
return path;
|
|
57
49
|
}
|
|
58
|
-
function pathTarget(args: ToolArgs
|
|
59
|
-
return { kind: 'path', text: relPath(args
|
|
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;
|
|
60
61
|
}
|
|
61
62
|
function firstLine(text: string): string {
|
|
62
63
|
const end = text.indexOf('\n');
|
|
@@ -92,24 +93,30 @@ function countPatchLines(patch: string): { added: number; removed: number } {
|
|
|
92
93
|
}
|
|
93
94
|
function listing(input: ResultInput, unit: 'match' | 'file' | 'entry', limit: string, empty: string): ResultSummary {
|
|
94
95
|
return checked(input, () => {
|
|
95
|
-
const
|
|
96
|
-
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)));
|
|
97
97
|
return summary(units(count, unit, Boolean(field(input.details, limit))));
|
|
98
98
|
});
|
|
99
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
|
+
}
|
|
100
108
|
|
|
101
109
|
export const TOOL_SPECS = {
|
|
102
110
|
read: {
|
|
103
111
|
verb: 'read',
|
|
104
112
|
target: (args, cwd) => ({
|
|
105
113
|
kind: 'path',
|
|
106
|
-
text: relPath(args
|
|
114
|
+
text: relPath(args.path, cwd) + formatReadLineRange(typeof args.offset === 'number' ? args.offset : undefined, typeof args.limit === 'number' ? args.limit : undefined),
|
|
107
115
|
}),
|
|
108
116
|
summarize: (input) =>
|
|
109
117
|
checked(input, () => {
|
|
110
118
|
if (input.images > 0) return summary('image');
|
|
111
|
-
|
|
112
|
-
return summary(units(typeof total === 'number' ? total : countLines(withoutNotice(input.text)), 'line'));
|
|
119
|
+
return summary(units(totalLines(input.details) ?? countLines(withoutNotice(input.text)), 'line'));
|
|
113
120
|
}),
|
|
114
121
|
},
|
|
115
122
|
edit: {
|
|
@@ -129,38 +136,30 @@ export const TOOL_SPECS = {
|
|
|
129
136
|
},
|
|
130
137
|
bash: {
|
|
131
138
|
verb: 'bash',
|
|
132
|
-
target: (args) => ({ kind: 'plain', text: firstLine(str(args
|
|
139
|
+
target: (args) => ({ kind: 'plain', text: firstLine(str(args.command)) }),
|
|
133
140
|
summarize: (input) => {
|
|
134
141
|
if (input.isPartial) return { meta: undefined, preview: { ...tailLines(input.text, RUNNING_TAIL_LINES), tone: 'output', from: 'tail' } };
|
|
135
|
-
|
|
136
|
-
const rawTail = input.text.slice(-STATUS_TAIL_CHARS);
|
|
137
|
-
const tail = rawTail.trimEnd();
|
|
138
|
-
const exit = /Command exited with code (\d+)$/.exec(tail);
|
|
139
|
-
const meta = exit ? `exit ${exit[1]}` : /Command timed out/.test(tail) ? 'timeout' : /Command aborted$/.test(tail) ? 'aborted' : 'failed';
|
|
140
|
-
const status = /Command (?:exited with code \d+|timed out[^\n]*|aborted)$/.exec(tail);
|
|
141
|
-
const text = status ? input.text.slice(0, input.text.length - rawTail.length + status.index).trimEnd() : input.text;
|
|
142
|
-
return { meta, preview: { ...tailLines(text, ERROR_PREVIEW_LINES), tone: 'error', from: 'tail' } };
|
|
142
|
+
return input.isError ? bashFailure(input) : summary('exit 0');
|
|
143
143
|
},
|
|
144
144
|
},
|
|
145
145
|
grep: {
|
|
146
146
|
verb: 'grep',
|
|
147
|
-
target: (args) => ({ kind: 'plain', text: str(args
|
|
147
|
+
target: (args) => ({ kind: 'plain', text: str(args.pattern) + (typeof args.path === 'string' ? ` ${args.path}` : '') }),
|
|
148
148
|
summarize: (input) => (input.text === 'No matches found' && !input.isError ? summary('no matches') : listing(input, 'match', 'matchLimitReached', 'No matches found')),
|
|
149
149
|
},
|
|
150
150
|
find: {
|
|
151
151
|
verb: 'find',
|
|
152
|
-
target: (args) => ({ kind: 'plain', text: str(args
|
|
152
|
+
target: (args) => ({ kind: 'plain', text: str(args.pattern) }),
|
|
153
153
|
summarize: (input) => listing(input, 'file', 'resultLimitReached', 'No files found'),
|
|
154
154
|
},
|
|
155
155
|
ls: {
|
|
156
156
|
verb: 'ls',
|
|
157
|
-
target: (args, cwd) => pathTarget({ path: args
|
|
157
|
+
target: (args, cwd) => pathTarget({ path: args.path ?? '.' }, cwd),
|
|
158
158
|
summarize: (input) => listing(input, 'entry', 'entryLimitReached', '(empty directory)'),
|
|
159
159
|
},
|
|
160
160
|
} satisfies Record<string, ToolSpec>;
|
|
161
161
|
|
|
162
162
|
export type CompactToolName = keyof typeof TOOL_SPECS;
|
|
163
|
-
export const VERB_COLUMN = 8;
|
|
164
163
|
export function isCompactTool(name: string): name is CompactToolName {
|
|
165
164
|
return Object.hasOwn(TOOL_SPECS, name);
|
|
166
165
|
}
|
|
@@ -171,17 +170,13 @@ export function genericSpec(toolName: string): ToolSpec {
|
|
|
171
170
|
return {
|
|
172
171
|
verb: toolName,
|
|
173
172
|
target: (args, cwd) => {
|
|
174
|
-
const
|
|
175
|
-
const
|
|
176
|
-
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]);
|
|
177
175
|
return key === 'path' ? { kind: 'path', text: relPath(value, cwd) } : { kind: 'plain', text: firstLine(value) };
|
|
178
176
|
},
|
|
179
177
|
summarize: (input) => {
|
|
180
178
|
if (input.isPartial) return { meta: undefined, preview: undefined };
|
|
181
|
-
if (input.isError)
|
|
182
|
-
const exit = /exit(?:ed with)? code (\d+)\s*$/i.exec(input.text.slice(-STATUS_TAIL_CHARS));
|
|
183
|
-
return failed(input, exit ? `exit ${exit[1]}` : 'failed');
|
|
184
|
-
}
|
|
179
|
+
if (input.isError) return failed(input, parseExit(input.text) ?? 'failed');
|
|
185
180
|
return summary(input.images > 0 ? 'image' : units(countLines(input.text), 'line'));
|
|
186
181
|
},
|
|
187
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
|
|
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
|
-
|
|
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
|
+
}
|