@justjoshn/pi-snoop-tui 0.1.0 → 0.1.1

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,9 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.1.1]
4
+
5
+ - Refactor TUI components, row layout, and tests to adhere verbatim to `AGENTS.md` (immutable patterns, closure state cells, `zod` input validation, named constants, and small functions) with no behavior changes.
6
+ - Port pure data and CLI benchmark scripts (`medium-fixture`, `mixed-fixture`, `mockup-fixture`, `report`, `summary`, `profile-summary`, and `capture`) to TypeScript under `AGENTS.md`.
7
+
3
8
  ## [0.1.0]
4
9
 
5
10
  - Add paired `snoop-dark` and `snoop-light` themes.
6
11
  - Add compact rows for read, edit, write, bash, grep, find, and ls.
7
12
  - Keep native tool detail rendering on expansion.
13
+ - Add compact rows for tools without renderers, with their arguments and plain output on expansion.
14
+ - Start every tool row's target in one column. Tool names longer than eight characters push only their own target.
8
15
  - Add a single-line footer, workspace header, and static working indicator.
16
+ - List theme files without a glob, so loading the package skips Node's first `fs.globSync` call at startup.
9
17
  - Cache rendered lines and tool summaries without extension-owned timers or render-time I/O.
18
+ - Pad and color expanded tool panels without a nested `Box`, and find blank edge lines without stripping every line, so Ctrl+O and typing with expanded rows do less work per row.
package/README.md CHANGED
@@ -1,10 +1,14 @@
1
1
  # pi-snoop-tui
2
2
 
3
- A compact look for Pi's interactive terminal UI. Paired light and dark themes use graphite neutrals and a soft blue accent.
3
+ A compact look for Pi's interactive terminal UI. Paired light and dark themes use graphite neutrals and a soft blue accent. The header, transcript, editor, and footer share one gutter on both sides, set by Pi's `outputPad` setting.
4
+
5
+ ![pi-snoop-tui in a Pi session](https://raw.githubusercontent.com/just-joshn/pi-customizations/main/extensions/pi-snoop-tui/docs/demo.gif)
4
6
 
5
7
  Tool rows show a status marker, tool name, target, and result summary. Successful calls collapse to one line. Running bash calls show up to three output lines. Errors show up to five lines. Expand tools with your configured shortcut, normally Ctrl+O, to see Pi's native detail rendering.
6
8
 
7
- The footer shows the workspace, branch, extension statuses, model, thinking level, and context usage on one line. The header shows `pi / workspace`. A static dot replaces the animated working indicator.
9
+ The footer shows the workspace, branch, extension statuses, model, thinking level, and context usage on one line. The header shows `pi / workspace`.
10
+
11
+ The editor sits between two thin rules. The top rule ends with `ready`, or `● working` while the agent runs. Pi's retry, compaction, and branch summary messages appear in the same place. A `›` prompt marks the first line, and the text starts in the same column as tool names. User messages in the transcript get the same `›`, unless they start with Markdown block syntax. In bash mode the rules take the theme's bash color.
8
12
 
9
13
  ## Install
10
14
 
@@ -22,7 +26,6 @@ Add these recommended native settings to `~/.pi/agent/settings.json`:
22
26
  "quietStartup": true,
23
27
  "hideThinkingBlock": true,
24
28
  "outputPad": 1,
25
- "editorPaddingX": 1,
26
29
  "collapseChangelog": true,
27
30
  "autocompleteMaxVisible": 5
28
31
  }
@@ -30,23 +33,25 @@ Add these recommended native settings to `~/.pi/agent/settings.json`:
30
33
 
31
34
  The theme pair follows your terminal's light or dark appearance. Use `snoop-dark` or `snoop-light` to choose one explicitly. The package never writes your settings.
32
35
 
33
- Run `pi config` to toggle `tool-rows.ts`, `footer.ts`, and `chrome.ts` independently. Chrome includes the header and working indicator. Tool rows also work with stock themes.
36
+ The editor layout replaces the `editorPaddingX` setting. If another extension already set a custom editor, this package leaves it in place and keeps its own header and footer. Pi assigns its callbacks, key handlers, and border color directly onto the editor instance, so a wrapper around another extension's editor cannot keep them in sync.
37
+
38
+ Run `pi config` to toggle `tool-rows.ts`, `footer.ts`, and `chrome.ts` independently. Chrome includes the header, the editor, the user prompt marker, and the working state. Tool rows also work with stock themes.
34
39
 
35
40
  ## Native limits
36
41
 
37
42
  Pi owns the blank line between tool rows. This package cannot remove it through the native renderer API.
38
43
 
39
- Your terminal owns the canvas background. For dark mode, set it near `okhsl(250 10% 9%)`. For light mode, use `okhsl(250 12% 97%)`.
44
+ Your terminal owns the canvas background. For dark mode, set it near `#14151a`. For light mode, use `okhsl(250 12% 97%)`.
40
45
 
41
- Expanded content stays native, including syntax highlighting, diffs, and truncation notices. Read detail does not add line numbers. Edit previews appear after execution, not before it. Successful writes have no expanded source preview because Pi puts that content in its call renderer, which this package does not invoke. Unknown tools keep their existing renderers.
46
+ Expanded content stays native, including syntax highlighting, diffs, and truncation notices. Read detail does not add line numbers. Edit previews appear after execution, not before it. Successful writes have no expanded source preview because Pi puts that content in its call renderer, which this package does not invoke. Other tools keep their own renderers. A tool with no renderer of its own, such as `codemode`, `pi_spawn`, or an MCP tool before its server connects, gets the same one-line row: its name, its main string argument, and the size of its output. Expanded, it shows the arguments as compact JSON and the full plain-text output.
42
47
 
43
48
  The footer replaces Pi's token and cost totals. It preserves other extensions' status messages, then shrinks or drops lower-priority segments when space is limited.
44
49
 
45
50
  ## Rendering work
46
51
 
47
- The package starts no timers and performs no file or process operations. Collapsed rows memoize output summaries and only style bounded previews. Header and footer lines cache their rendered output. Context usage refreshes on lifecycle events, not on terminal frames.
52
+ The package starts no timers and performs no file or process operations. Collapsed rows memoize output summaries and only style bounded previews. Header and footer lines and the editor rules cache their rendered output. Context usage refreshes on lifecycle events, not on terminal frames.
48
53
 
49
- A theme change clears component caches. The working dot takes the new theme color at the next agent start.
54
+ A theme change clears component caches.
50
55
 
51
56
  ## Develop
52
57
 
@@ -57,4 +62,4 @@ cd extensions/pi-snoop-tui
57
62
  bunx vitest run --coverage
58
63
  ```
59
64
 
60
- Tests cover Pi's call-before-result ordering, isolated native renderer state, cache invalidation, theme role parity, and terminal widths with CJK text and emoji.
65
+ Tests cover the shared gutter, editor rules and status labels at every width, the user prompt marker, Pi's call-before-result ordering, isolated native renderer state, cache invalidation, theme role parity, and terminal widths with CJK text and emoji.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@justjoshn/pi-snoop-tui",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
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",
@@ -28,7 +28,8 @@
28
28
  "./src/chrome.ts"
29
29
  ],
30
30
  "themes": [
31
- "./themes/*.json"
31
+ "./themes/snoop-dark.json",
32
+ "./themes/snoop-light.json"
32
33
  ]
33
34
  },
34
35
  "files": [
@@ -47,11 +48,15 @@
47
48
  "@earendil-works/pi-tui": "*"
48
49
  },
49
50
  "devDependencies": {
51
+ "@earendil-works/pi-ai": "1.5.2",
50
52
  "@earendil-works/pi-coding-agent": "1.5.2",
51
53
  "@earendil-works/pi-tui": "1.5.2",
52
54
  "@types/node": "^22.19.0",
53
55
  "@vitest/coverage-v8": "^5.0.2",
54
56
  "typescript": "^7.0.2",
55
57
  "vitest": "^5.0.2"
58
+ },
59
+ "dependencies": {
60
+ "zod": "^4"
56
61
  }
57
62
  }
package/src/cell.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** A single replaceable value. Holds mutable state in a closure, so owners never assign to their own fields. */
2
+ export interface Cell<T> {
3
+ readonly read: () => T;
4
+ readonly write: (next: T) => void;
5
+ }
6
+
7
+ export function cell<T>(initial: T): Cell<T> {
8
+ let value = initial;
9
+ return {
10
+ read: () => value,
11
+ write: (next) => {
12
+ value = next;
13
+ },
14
+ };
15
+ }
package/src/chrome.ts CHANGED
@@ -1,37 +1,51 @@
1
1
  import { basename } from 'node:path';
2
2
 
3
- import type { ExtensionAPI, ExtensionContext, Theme } from '@earendil-works/pi-coding-agent';
3
+ import type { ExtensionAPI, ExtensionUIContext, Theme } from '@earendil-works/pi-coding-agent';
4
4
  import type { Component } from '@earendil-works/pi-tui';
5
- import { fitPlain, sanitizeLine } from './text.ts';
5
+ import { cell } from './cell.ts';
6
+ import { createRuleEditor } from './editor.ts';
7
+ import { fitPlain, gutterAt, gutterOf, sanitizeLine } from './text.ts';
8
+
9
+ type EditorFactory = NonNullable<ReturnType<ExtensionUIContext['getEditorComponent']>>;
10
+ const HEADER_MIN_INNER = 5;
11
+ const MARKDOWN_START = /^(?: {4}|\t|\s*(?:[#>`~|*+-]|\d+[.)]))/;
12
+
13
+ export function markUserPrompt(markdown: string): string {
14
+ return !markdown.trim() || MARKDOWN_START.test(markdown) ? markdown : `› ${markdown}`;
15
+ }
6
16
 
7
17
  export default function chrome(pi: ExtensionAPI): void {
18
+ let ownEditor: EditorFactory | undefined;
19
+ pi.registerMarkdownTransformer(markUserPrompt, { messageTypes: ['user'] });
8
20
  pi.on('session_start', (_event, ctx) => {
9
21
  if (!ctx.hasUI) return;
10
- ctx.ui.setHeader((_tui, theme) => new HeaderLine(theme, basename(ctx.cwd) || ctx.cwd));
11
- setIndicator(ctx);
22
+ const gutter = gutterOf(pi);
23
+ ctx.ui.setHeader((_tui, theme) => headerLine(theme, basename(ctx.cwd) || ctx.cwd, gutter));
24
+ ctx.ui.setWorkingIndicator({ frames: [] });
25
+ ctx.ui.setWorkingMessage('working');
26
+ ctx.ui.setHiddenThinkingLabel('thinking');
27
+ // An editor from another extension wins: Pi assigns callbacks, handlers, and border color onto the instance, so it cannot be wrapped safely.
28
+ const previous = ctx.ui.getEditorComponent();
29
+ if (previous && previous !== ownEditor) return;
30
+ ownEditor = (tui, editorTheme, keybindings) => createRuleEditor(tui, editorTheme, keybindings, () => ctx.ui.theme, gutter);
31
+ ctx.ui.setEditorComponent(ownEditor);
12
32
  });
13
- pi.on('agent_start', (_event, ctx) => {
14
- if (ctx.hasUI) setIndicator(ctx);
15
- });
16
- }
17
- function setIndicator(ctx: ExtensionContext): void {
18
- ctx.ui.setWorkingIndicator({ frames: [ctx.ui.theme.fg('accent', '●')] });
19
33
  }
20
- export class HeaderLine implements Component {
21
- private cache: { width: number; line: string } | undefined;
22
- private readonly theme: Theme;
23
- private readonly workspace: string;
24
- constructor(theme: Theme, workspace: string) {
25
- this.theme = theme;
26
- this.workspace = workspace;
27
- }
28
- render(width: number): string[] {
29
- if (this.cache?.width === width) return [this.cache.line];
30
- const line = width < 5 ? this.theme.fg('accent', fitPlain('pi', width)) : this.theme.fg('accent', 'pi') + this.theme.fg('dim', ' / ') + this.theme.fg('muted', fitPlain(sanitizeLine(this.workspace), width - 5));
31
- this.cache = { width, line };
32
- return [line];
33
- }
34
- invalidate(): void {
35
- this.cache = undefined;
36
- }
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
+ };
37
51
  }
package/src/editor.ts ADDED
@@ -0,0 +1,120 @@
1
+ import { CustomEditor, type KeybindingsManager, type Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type EditorTheme, type TUI, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import { cell } from './cell.ts';
4
+ import { gutterAt } from './text.ts';
5
+
6
+ type Indicator = NonNullable<Parameters<CustomEditor['setWorkingStatusIndicator']>[0]>;
7
+ export type EditorStatus = { readonly kind: 'ready' } | { readonly kind: 'working' } | { readonly kind: 'pi'; readonly indicator: Indicator };
8
+ const READY: EditorStatus = { kind: 'ready' };
9
+ const WORKING: EditorStatus = { kind: 'working' };
10
+ export const PROMPT_INSET = 3;
11
+ const BORDER_LABEL_RESERVE = 5;
12
+
13
+ export function editorStatus(indicator: Indicator | undefined): EditorStatus {
14
+ if (!indicator) return READY;
15
+ return indicator.kind === 'working' ? WORKING : { kind: 'pi', indicator };
16
+ }
17
+
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
+ }
27
+
28
+ interface EditorConfig {
29
+ readonly theme: () => Theme;
30
+ readonly gutter: number;
31
+ }
32
+
33
+ abstract class RuleEditor extends CustomEditor {
34
+ protected abstract readonly config: EditorConfig;
35
+ 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);
39
+ override setPaddingX(_padding: number): void {
40
+ super.setPaddingX(this.config.gutter + PROMPT_INSET);
41
+ }
42
+ override setWorkingStatusIndicator(indicator: Indicator | undefined): void {
43
+ this.snoopStatus.write(editorStatus(indicator));
44
+ super.setWorkingStatusIndicator(indicator);
45
+ }
46
+ protected override renderTopBorder(width: number, hidden: number): string {
47
+ const theme = this.config.theme();
48
+ const status = this.snoopStatus.read();
49
+ 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;
56
+ }
57
+ 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;
64
+ }
65
+ private rule(width: number, left: string, right: string): string {
66
+ const g = gutterAt(this.config.gutter, width);
67
+ const inner = width - 2 * g;
68
+ const labels = visibleWidth(left) + visibleWidth(right);
69
+ 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);
71
+ return visibleWidth(line) <= width ? line : truncateToWidth(line, width, '');
72
+ }
73
+ override render(width: number): string[] {
74
+ const lines = super.render(width);
75
+ const inset = this.config.gutter + PROMPT_INSET;
76
+ const first = lines[1];
77
+ 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(PROMPT_INSET - 1)}`;
84
+ this.prompt.write({ theme, text });
85
+ return text;
86
+ }
87
+ override invalidate(): void {
88
+ super.invalidate();
89
+ this.topRule.write(undefined);
90
+ this.bottomRule.write(undefined);
91
+ this.prompt.write(undefined);
92
+ }
93
+ }
94
+
95
+ /** Builds a RuleEditor bound to `theme` and `gutter`. The config rides in a subclass field so no instance field is assigned. */
96
+ export function createRuleEditor(tui: TUI, editorTheme: EditorTheme, keybindings: KeybindingsManager, theme: () => Theme, gutter: number): CustomEditor {
97
+ const config: EditorConfig = { theme, gutter };
98
+ class ConfiguredEditor extends RuleEditor {
99
+ protected override readonly config = config;
100
+ constructor() {
101
+ super(tui, editorTheme, keybindings, { embedWorkingStatus: true, paddingX: gutter + PROMPT_INSET });
102
+ }
103
+ }
104
+ return new ConfiguredEditor();
105
+ }
106
+
107
+ function statusLabel(status: EditorStatus, theme: Theme, piLabel: string): string {
108
+ switch (status.kind) {
109
+ case 'ready':
110
+ return theme.fg('muted', 'ready');
111
+ case 'working':
112
+ return `${theme.fg('accent', '●')} ${theme.fg('muted', 'working')}`;
113
+ case 'pi':
114
+ return piLabel;
115
+ default: {
116
+ const unreachable: never = status;
117
+ return unreachable;
118
+ }
119
+ }
120
+ }
package/src/footer.ts CHANGED
@@ -2,7 +2,8 @@ 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 { fitPlain, sanitizeLine } from './text.ts';
5
+ import { cell } from './cell.ts';
6
+ import { fitPlain, gutterAt, gutterOf, sanitizeLine } from './text.ts';
6
7
 
7
8
  type ThinkingLevel = ReturnType<ExtensionAPI['getThinkingLevel']>;
8
9
  export interface FooterSnapshot {
@@ -11,6 +12,8 @@ export interface FooterSnapshot {
11
12
  readonly thinking: ThinkingLevel | undefined;
12
13
  readonly ctxPercent: number | null;
13
14
  }
15
+ const CTX_ERROR_PERCENT = 90;
16
+ const CTX_WARNING_PERCENT = 70;
14
17
  export const SEGMENT_ORDER = [
15
18
  { id: 'workspace', side: 'left', priority: 0, minWidth: 6 },
16
19
  { id: 'branch', side: 'left', priority: 4 },
@@ -39,16 +42,13 @@ export default function footer(pi: ExtensionAPI): void {
39
42
  pi.on('session_start', (_event, ctx) => {
40
43
  if (!ctx.hasUI) return;
41
44
  refresh(ctx);
45
+ const gutter = gutterOf(pi);
42
46
  ctx.ui.setFooter((tui, theme, data) => {
43
47
  mounted = tui;
44
- return new SnoopFooter(
45
- theme,
46
- data,
47
- () => snapshot,
48
- () => {
49
- if (mounted === tui) mounted = undefined;
50
- },
51
- );
48
+ const release = (): void => {
49
+ if (mounted === tui) mounted = undefined;
50
+ };
51
+ return snoopFooter(theme, data, () => snapshot, release, gutter);
52
52
  });
53
53
  });
54
54
  const onChange = (_event: unknown, ctx: ExtensionContext): void => {
@@ -78,74 +78,76 @@ function rowWidth(segments: readonly Segment[]): number {
78
78
  const right = joinSide(segments, 'right', (s) => s.text);
79
79
  return visibleWidth(left) + visibleWidth(right) + (left && right ? 2 : 0);
80
80
  }
81
+ 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));
88
+ }
81
89
  export function fitSegments(segments: readonly Segment[], width: number): readonly Segment[] {
82
- const fitted = segments.filter((s) => s.text).map((s) => ({ ...s, text: sanitizeLine(s.text) }));
83
- while (rowWidth(fitted) > Math.max(0, width)) {
84
- const lowest = fitted.reduce((a, b) => (a.priority > b.priority || (a.priority === b.priority && a.side === 'right') ? a : b));
85
- const size = visibleWidth(lowest.text);
86
- const min = lowest.priority === 0 ? 0 : lowest.minWidth;
87
- if (min !== undefined && size > min) {
88
- lowest.text = fitPlain(lowest.text, Math.max(min, size - (rowWidth(fitted) - Math.max(0, width))));
89
- } else {
90
- fitted.splice(fitted.indexOf(lowest), 1);
91
- }
92
- }
90
+ const target = Math.max(0, width);
91
+ let fitted: readonly Segment[] = segments.filter((s) => s.text).map((s) => ({ ...s, text: sanitizeLine(s.text) }));
92
+ while (rowWidth(fitted) > target) fitted = shrinkOnce(fitted, target);
93
93
  return fitted;
94
94
  }
95
95
  export function statusText(statuses: ReadonlyMap<string, string>): string {
96
96
  return [...statuses.entries()]
97
- .sort(([a], [b]) => a.localeCompare(b))
97
+ .toSorted(([a], [b]) => a.localeCompare(b))
98
98
  .map(([, text]) => sanitizeLine(text).trim())
99
99
  .filter(Boolean)
100
100
  .join(' · ');
101
101
  }
102
- export class SnoopFooter implements Component {
103
- private cache: { width: number; snapshot: FooterSnapshot | undefined; branch: string | null; statuses: string; line: string } | undefined;
104
- private readonly theme: Theme;
105
- private readonly data: ReadonlyFooterDataProvider;
106
- private readonly read: () => FooterSnapshot | undefined;
107
- private readonly onDispose: () => void;
108
- constructor(theme: Theme, data: ReadonlyFooterDataProvider, read: () => FooterSnapshot | undefined, onDispose: () => void) {
109
- this.theme = theme;
110
- this.data = data;
111
- this.read = read;
112
- this.onDispose = onDispose;
113
- }
114
- render(width: number): string[] {
115
- const snapshot = this.read();
116
- const branch = this.data.getGitBranch();
117
- const statuses = statusText(this.data.getExtensionStatuses());
118
- if (this.cache?.width === width && this.cache.snapshot === snapshot && this.cache.branch === branch && this.cache.statuses === statuses) return [this.cache.line];
119
- const texts: Record<SegmentId, string> = {
120
- workspace: snapshot?.workspace ?? '',
121
- branch: branch ?? '',
122
- statuses,
123
- model: snapshot?.model ?? '',
124
- thinking: snapshot?.thinking ?? '',
125
- ctx: snapshot?.ctxPercent == null ? 'ctx ?' : `ctx ${Math.round(snapshot.ctxPercent)}%`,
126
- };
127
- const fitted = fitSegments(
128
- SEGMENT_ORDER.map((s) => ({ ...s, text: texts[s.id] })),
129
- width,
130
- );
131
- const style = (s: Segment): string => {
132
- const percent = snapshot?.ctxPercent;
133
- const color = s.id === 'workspace' ? 'text' : s.id !== 'ctx' ? 'muted' : percent == null ? 'dim' : percent > 90 ? 'error' : percent > 70 ? 'warning' : 'accent';
134
- return this.theme.fg(color, s.text);
135
- };
136
- const separator = (text: string): string => this.theme.fg('dim', text);
137
- const left = joinSide(fitted, 'left', style, separator);
138
- const right = joinSide(fitted, 'right', style, separator);
139
- const gap = left && right ? Math.max(2, width - visibleWidth(left) - visibleWidth(right)) : 0;
140
- const line = left + ' '.repeat(gap) + right;
141
- this.cache = { width, snapshot, branch, statuses, line };
142
- return [line];
143
- }
144
- invalidate(): void {
145
- this.cache = undefined;
146
- }
147
- dispose(): void {
148
- this.cache = undefined;
149
- this.onDispose();
150
- }
102
+ function ctxColor(percent: number | null | undefined): 'dim' | 'error' | 'warning' | 'accent' {
103
+ if (percent == null) return 'dim';
104
+ if (percent > CTX_ERROR_PERCENT) return 'error';
105
+ return percent > CTX_WARNING_PERCENT ? 'warning' : 'accent';
106
+ }
107
+ function segmentTexts(snapshot: FooterSnapshot | undefined, branch: string | null, statuses: string): Record<SegmentId, string> {
108
+ return {
109
+ workspace: snapshot?.workspace ?? '',
110
+ branch: branch ?? '',
111
+ statuses,
112
+ model: snapshot?.model ?? '',
113
+ thinking: snapshot?.thinking ?? '',
114
+ ctx: snapshot?.ctxPercent == null ? 'ctx ?' : `ctx ${Math.round(snapshot.ctxPercent)}%`,
115
+ };
116
+ }
117
+ function footerLine(theme: Theme, snapshot: FooterSnapshot | undefined, branch: string | null, statuses: string, width: number, gutter: number): string {
118
+ const texts = segmentTexts(snapshot, branch, statuses);
119
+ const g = gutterAt(gutter, width);
120
+ const inner = width - 2 * g;
121
+ const fitted = fitSegments(
122
+ SEGMENT_ORDER.map((s) => ({ ...s, text: texts[s.id] })),
123
+ inner,
124
+ );
125
+ const style = (s: Segment): string => theme.fg(s.id === 'workspace' ? 'text' : s.id !== 'ctx' ? 'muted' : ctxColor(snapshot?.ctxPercent), s.text);
126
+ const separator = (text: string): string => theme.fg('dim', text);
127
+ const left = joinSide(fitted, 'left', style, separator);
128
+ const right = joinSide(fitted, 'right', style, separator);
129
+ const gap = left && right ? Math.max(2, inner - visibleWidth(left) - visibleWidth(right)) : 0;
130
+ return ' '.repeat(g) + left + ' '.repeat(gap) + right;
131
+ }
132
+ 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);
134
+ 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
+ },
148
+ dispose(): void {
149
+ cache.write(undefined);
150
+ onDispose();
151
+ },
152
+ };
151
153
  }
@@ -0,0 +1,84 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type Component, truncateToWidth } from '@earendil-works/pi-tui';
3
+ import { cell } from '../cell.ts';
4
+ import { fitPlain, sanitizeLine } from '../text.ts';
5
+ import type { Preview } from './specs.ts';
6
+ import { layoutHeader, ROW_INSET, type RowView } from './view.ts';
7
+
8
+ interface LinesCache {
9
+ readonly width: number;
10
+ readonly view: RowView;
11
+ readonly lines: string[];
12
+ }
13
+ const MARKERS = {
14
+ pending: ['dim', '·'],
15
+ running: ['accent', '•'],
16
+ done: ['success', '✓'],
17
+ failed: ['error', '✗'],
18
+ } as const;
19
+
20
+ export function createRowHeader(view: () => RowView, theme: Theme): Component {
21
+ const cache = cell<LinesCache | undefined>(undefined);
22
+ 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
+ },
45
+ };
46
+ }
47
+
48
+ function previewLines(theme: Theme, preview: Preview, hint: string | undefined, indent: number, width: number): string[] {
49
+ const line = (text: string, tone: 'error' | 'toolOutput' | 'dim'): string => ' '.repeat(indent) + theme.fg(tone, fitPlain(sanitizeLine(text), width - indent));
50
+ const lines = preview.lines.map((text) => line(text, preview.tone === 'error' ? 'error' : 'toolOutput'));
51
+ if (!hint) return lines;
52
+ switch (preview.from) {
53
+ case 'head':
54
+ return [...lines, line(`… ${preview.hidden} more · ${hint}`, 'dim')];
55
+ case 'tail':
56
+ return [line(`… ${preview.hidden} earlier · ${hint}`, 'dim'), ...lines];
57
+ default: {
58
+ const unreachable: never = preview.from;
59
+ return unreachable;
60
+ }
61
+ }
62
+ }
63
+
64
+ export function createRowBody(view: () => RowView, theme: Theme, invalidatePanel: () => void): Component {
65
+ const cache = cell<LinesCache | undefined>(undefined);
66
+ return {
67
+ render(width) {
68
+ const current = view();
69
+ const body = current.body;
70
+ if (body.kind === 'none') return [];
71
+ 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;
78
+ },
79
+ invalidate() {
80
+ cache.write(undefined);
81
+ invalidatePanel();
82
+ },
83
+ };
84
+ }