pal-code 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +9 -6
  2. package/SYSTEM.md +17 -2
  3. package/package.json +10 -5
  4. package/packages/cli/src/agent-panel.ts +1 -1
  5. package/packages/cli/src/agent-ui.ts +66 -0
  6. package/packages/cli/src/commands/ext-registry.ts +7 -0
  7. package/packages/cli/src/commands.ts +32 -102
  8. package/packages/cli/src/components/assistant-body.ts +4 -3
  9. package/packages/cli/src/components/message-box.ts +2 -2
  10. package/packages/cli/src/components/permission-prompt.ts +3 -3
  11. package/packages/cli/src/components/render-history.ts +13 -12
  12. package/packages/cli/src/components/run-view.ts +109 -33
  13. package/packages/cli/src/components/sidebar.ts +81 -14
  14. package/packages/cli/src/components/status-line.ts +3 -3
  15. package/packages/cli/src/config.ts +6 -129
  16. package/packages/cli/src/index.ts +194 -69
  17. package/packages/cli/src/overlays/key-input.ts +142 -121
  18. package/packages/cli/src/overlays/model-picker.ts +19 -56
  19. package/packages/cli/src/overlays/select.ts +102 -0
  20. package/packages/cli/src/overlays/session-picker.ts +14 -40
  21. package/packages/cli/src/overlays/wizard.ts +107 -42
  22. package/packages/cli/src/prompt/select.ts +181 -0
  23. package/packages/cli/src/slash-commands.ts +105 -0
  24. package/packages/cli/src/state.ts +32 -74
  25. package/packages/cli/src/theme.ts +13 -1
  26. package/packages/cli/src/themes/github-dark.ts +14 -3
  27. package/packages/cli/src/themes/types.ts +26 -2
  28. package/packages/cli/src/themes/vanilla-pi.ts +23 -9
  29. package/packages/cli/src/tui/components/text.ts +102 -0
  30. package/packages/cli/src/tui/render/code-block.ts +325 -0
  31. package/packages/cli/src/{utils → tui/render}/format.ts +31 -24
  32. package/packages/cli/src/{utils → tui/render}/highlight.ts +94 -2
  33. package/packages/cli/src/tui/render/markdown.ts +529 -0
  34. package/packages/cli/src/tui/surface/index.ts +9 -0
  35. package/packages/cli/src/tui/{paint-panel.ts → surface/paint-panel.ts} +1 -1
  36. package/packages/cli/src/tui/theme-types.ts +59 -0
  37. package/packages/cli/src/tui/tty-width.ts +20 -0
  38. package/packages/cli/src/tui/types.ts +53 -0
  39. package/packages/cli/src/turn.ts +0 -292
  40. package/packages/cli/src/utils/code-block.ts +0 -200
@@ -6,8 +6,8 @@
6
6
  * `syntax` and `surface` extend it with GitHub Dark syntax colours.
7
7
  */
8
8
 
9
- import type {EditorTheme, MarkdownTheme} from '@earendil-works/pi-tui';
10
- import {highlightCode} from '../utils/highlight.js';
9
+ import type {EditorTheme, MarkdownTheme} from '../tui/theme-types.js';
10
+ import {highlightCode} from '../tui/render/highlight.js';
11
11
  import type {CColors, CodeboxTokens, SurfaceTokens, SyntaxTokens, Theme} from './types.js';
12
12
 
13
13
  const c: CColors = {
@@ -40,6 +40,9 @@ const codebox: CodeboxTokens = {
40
40
  chipFgIdle: '\x1b[38;2;201;209;217m', // #c9d1d9 — GitHub primary text
41
41
  chipFgHover: '\x1b[38;2;240;246;252m', // #f0f6fc — GitHub bright text on hover
42
42
  successFg: '\x1b[38;2;63;185;80m', // #3fb950 — GitHub success green
43
+ gutterFg: '\x1b[38;2;72;79;88m', // #484f58 — dimmer shade of border #30363d
44
+ diffDelBg: '\x1b[48;2;61;26;30m', // #3d1a1e - GitHub red wash behind removed diff lines
45
+ diffAddBg: '\x1b[48;2;26;61;42m', // #1a3d2a - GitHub green wash behind added diff lines
43
46
  };
44
47
 
45
48
  const markdownTheme: MarkdownTheme = {
@@ -129,7 +132,8 @@ const surface: SurfaceTokens = {
129
132
  dim: c.dim, // SGR dim (sidebar.ts:72,85,92,102)
130
133
  },
131
134
  statusLine: {
132
- border: '\x1b[38;2;48;54;61m', // #30363d (reserved)
135
+ bg: '\x1b[48;2;1;4;9m', // #010409 — panel fill (same tone as sidebar)
136
+ border: '\x1b[38;2;48;54;61m', // #30363d — status-line.ts right-edge segment accent
133
137
  flash: c.green, // #3fb950 — index.ts:816
134
138
  error: c.red, // #f85149 (reserved — no error state today)
135
139
  warn: c.yellow, // #d29922 — index.ts:771,775,783,795
@@ -157,6 +161,13 @@ const surface: SurfaceTokens = {
157
161
  dim: c.dim, // SGR dim — format.ts:150,181
158
162
  roleFallback: c.cyan, // #39c5cf — format.ts:94
159
163
  },
164
+ runView: {
165
+ row: c.bright_black, // #8b949e — run-view.ts:111, render-history.ts:90,104
166
+ elapsed: c.bright_black, // #8b949e — run-view.ts:109
167
+ preview: c.bright_black, // #8b949e — run-view.ts:110, render-history.ts:90
168
+ summary: c.bright_black, // #8b949e — run-view.ts:226
169
+ border: c.bright_black, // #8b949e — run-view.ts:88,91,94
170
+ },
160
171
  };
161
172
 
162
173
  export const githubDark: Theme = {
@@ -14,7 +14,7 @@
14
14
  * or is marked `reserved`.
15
15
  */
16
16
 
17
- import type {EditorTheme, MarkdownTheme} from '@earendil-works/pi-tui';
17
+ import type {EditorTheme, MarkdownTheme} from '../tui/theme-types.js';
18
18
 
19
19
  /** The 17 raw ANSI SGR codes every renderer reads through the `c` facade. */
20
20
  export interface CColors {
@@ -47,6 +47,12 @@ export interface CodeboxTokens {
47
47
  chipFgIdle: string;
48
48
  chipFgHover: string;
49
49
  successFg: string;
50
+ /** consumed by utils/code-block.ts (line-number gutter) — dimmer shade of borderFg. */
51
+ gutterFg: string;
52
+ /** Full-row wash behind removed diff lines - utils/highlight.ts diffLineTint. */
53
+ diffDelBg: string;
54
+ /** Full-row wash behind added diff lines - utils/highlight.ts diffLineTint. */
55
+ diffAddBg: string;
50
56
  }
51
57
 
52
58
  /**
@@ -119,7 +125,13 @@ export interface SurfaceTokens {
119
125
  dim: string;
120
126
  };
121
127
  statusLine: {
122
- /** reserved — the status line paints no border (Phase B). */
128
+ /**
129
+ * Panel fill behind the status line via tui/paint-panel.ts —
130
+ * `''` = terminal default (passthrough, zero bytes). Consumed by
131
+ * components/status-line.ts render().
132
+ */
133
+ bg: string;
134
+ /** consumed by components/status-line.ts (right-edge segment accent). */
123
135
  border: string;
124
136
  /** consumed by index.ts:836 (flashCopied confirmation). */
125
137
  flash: string;
@@ -168,6 +180,18 @@ export interface SurfaceTokens {
168
180
  /** consumed by utils/format.ts:94 (unknown-role colour fallback). */
169
181
  roleFallback: string;
170
182
  };
183
+ runView: {
184
+ /** consumed by run-view.ts:111 + render-history.ts:90,104 (tool name / args). */
185
+ row: string;
186
+ /** consumed by run-view.ts:109 (finished-tool elapsed time). */
187
+ elapsed: string;
188
+ /** consumed by run-view.ts:110 + render-history.ts:90 (`→ preview` tail). */
189
+ preview: string;
190
+ /** consumed by run-view.ts:226 (collapsed one-line run summary). */
191
+ summary: string;
192
+ /** consumed by run-view.ts:88,91,94 (round/tool separators, model·secs meta). */
193
+ border: string;
194
+ };
171
195
  }
172
196
 
173
197
  /** A complete, self-contained theme. */
@@ -5,8 +5,8 @@
5
5
  * exactly what shipped before the theme system existed.
6
6
  */
7
7
 
8
- import type {EditorTheme, MarkdownTheme} from '@earendil-works/pi-tui';
9
- import {highlightCode} from '../utils/highlight.js';
8
+ import type {EditorTheme, MarkdownTheme} from '../tui/theme-types.js';
9
+ import {highlightCode} from '../tui/render/highlight.js';
10
10
  import type {CColors, CodeboxTokens, SurfaceTokens, SyntaxTokens, Theme} from './types.js';
11
11
 
12
12
  const c: CColors = {
@@ -29,15 +29,21 @@ const c: CColors = {
29
29
  bright_white: '\x1b[97m',
30
30
  };
31
31
 
32
+ /** Readable mid-gray for code text (#8b949e — github-dark's muted tone). */
33
+ const codeGray = '\x1b[38;2;139;148;158m';
34
+
32
35
  const codebox: CodeboxTokens = {
33
- surfaceBg: '', // earlier style: no fill — rows sit on the terminal default
34
- borderFg: `${c.dim}${c.cyan}`, // earlier two-tier border prefix (087e03e paint)
36
+ surfaceBg: '\x1b[48;2;24;27;31m', // subtle dark fill (#181b1f)
37
+ borderFg: c.cyan, // cyan hue kept; faint (SGR 2) removed for contrast
35
38
  langFg: c.cyan, // earlier language-tag color
36
39
  chipBgIdle: '', // no chip rectangle — label is plain fg text
37
40
  chipBgHover: '', // hover = brighter fg instead of a bg change
38
41
  chipFgIdle: c.green, // earlier green copy label
39
42
  chipFgHover: `${c.bold}${c.green}`, // hover: bold green label, still bg-free
40
43
  successFg: c.green, // success label `✓ copied` stays green, bg-free
44
+ gutterFg: '\x1b[38;2;74;118;120m', // muted teal — dimmer shade of cyan border (#4a7678)
45
+ diffDelBg: '\x1b[48;2;61;34;38m', // dark red wash behind removed diff lines (#3d2226)
46
+ diffAddBg: '\x1b[48;2;30;58;42m', // dark green wash behind added diff lines (#1e3a2a)
41
47
  };
42
48
 
43
49
  const markdownTheme: MarkdownTheme = {
@@ -45,8 +51,8 @@ const markdownTheme: MarkdownTheme = {
45
51
  link: (text: string) => `${c.underline}${c.cyan}${text}${c.reset}`,
46
52
  linkUrl: (text: string) => `${c.dim}${text}${c.reset}`,
47
53
  code: (text: string) => `${c.bold}${c.magenta}${text}${c.reset}`,
48
- codeBlock: (text: string) => `${c.bright_black}${text}${c.reset}`,
49
- codeBlockBorder: (text: string) => `${c.dim}${c.bright_black}${text}${c.reset}`,
54
+ codeBlock: (text: string) => `${codeGray}${text}${c.reset}`,
55
+ codeBlockBorder: (text: string) => `${codeGray}${text}${c.reset}`,
50
56
  quote: (text: string) => `${c.italic}${c.dim}${text}${c.reset}`,
51
57
  quoteBorder: (text: string) => `${c.bold}${c.cyan}${text}${c.reset}`,
52
58
  hr: (text: string) => `${c.dim}${text}${c.reset}`,
@@ -98,14 +104,14 @@ const agentLabels: Record<string, string> = {
98
104
  * unchanged: `keyword` is cyan+bold exactly as `${c.cyan}${c.bold}` painted it.
99
105
  */
100
106
  const syntax: SyntaxTokens = {
101
- comment: c.bright_black, // highlight.ts:268,274,282,286
107
+ comment: codeGray, // highlight.ts:268,274,282,286
102
108
  string: c.green, // highlight.ts:299,352
103
109
  number: c.magenta, // highlight.ts:308,356
104
110
  keyword: `${c.cyan}${c.bold}`, // highlight.ts:320
105
111
  method: c.yellow, // highlight.ts:323
106
112
  jsonKey: c.cyan, // highlight.ts:350
107
113
  jsonPrimitive: c.magenta, // highlight.ts:354
108
- plain: c.bright_black, // highlight.ts:236,248
114
+ plain: codeGray, // highlight.ts:236,248
109
115
  };
110
116
 
111
117
  /** Values equivalent to today's c.* reads in each component (no visual change). */
@@ -130,7 +136,8 @@ const surface: SurfaceTokens = {
130
136
  dim: c.dim, // sidebar.ts:72,85,92,102
131
137
  },
132
138
  statusLine: {
133
- border: c.dim, // reserved — no status-line border
139
+ bg: '\x1b[48;2;32;36;44m', // #20242c — status tier fill, a step lighter than code fill
140
+ border: c.dim, // consumed by status-line.ts right-edge segment accent
134
141
  flash: c.green, // index.ts:816
135
142
  error: c.red, // reserved — no error state today
136
143
  warn: c.yellow, // index.ts:771,775,783,795
@@ -158,6 +165,13 @@ const surface: SurfaceTokens = {
158
165
  dim: c.dim, // format.ts:150,181 timestamp
159
166
  roleFallback: c.cyan, // format.ts:94
160
167
  },
168
+ runView: {
169
+ row: c.dim, // run-view.ts:111, render-history.ts:90,104
170
+ elapsed: c.dim, // run-view.ts:109
171
+ preview: c.dim, // run-view.ts:110, render-history.ts:90
172
+ summary: c.dim, // run-view.ts:226
173
+ border: c.dim, // run-view.ts:88,91,94
174
+ },
161
175
  };
162
176
 
163
177
  export const vanillaPi: Theme = {
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Text — displays multi-line text with word wrapping.
3
+ *
4
+ * pi-tui-free replacement for `Text` from @earendil-works/pi-tui, matching
5
+ * its behaviour exactly: tabs become three spaces, padding shrinks rather than
6
+ * overflow when the viewport is narrow, every emitted line is padded to `width`
7
+ * so the engine's differential renderer sees a stable row width, and an empty
8
+ * or whitespace-only string renders nothing at all.
9
+ */
10
+
11
+ import {applyBackgroundToLine, visibleWidth, wrapTextWithAnsi} from '../tty-width.js';
12
+ import type {Component} from '../types.js';
13
+
14
+ /** Paints a whole line (content + trailing padding) with a background. */
15
+ export type BackgroundFn = (text: string) => string;
16
+
17
+ export class Text implements Component {
18
+ private text: string;
19
+ private paddingX: number;
20
+ private paddingY: number;
21
+ private customBgFn?: BackgroundFn;
22
+
23
+ private cachedText?: string;
24
+ private cachedWidth?: number;
25
+ private cachedLines?: string[];
26
+
27
+ constructor(text = '', paddingX = 1, paddingY = 1, customBgFn?: BackgroundFn) {
28
+ this.text = text;
29
+ this.paddingX = paddingX;
30
+ this.paddingY = paddingY;
31
+ this.customBgFn = customBgFn;
32
+ }
33
+
34
+ setText(text: string): void {
35
+ this.text = text;
36
+ this.invalidate();
37
+ }
38
+
39
+ setCustomBgFn(customBgFn?: BackgroundFn): void {
40
+ this.customBgFn = customBgFn;
41
+ this.invalidate();
42
+ }
43
+
44
+ invalidate(): void {
45
+ this.cachedText = undefined;
46
+ this.cachedWidth = undefined;
47
+ this.cachedLines = undefined;
48
+ }
49
+
50
+ render(width: number): string[] {
51
+ // Repaint only when the text or the viewport actually changed — this is
52
+ // what keeps a live TUI from reflowing on every streaming delta.
53
+ if (this.cachedLines && this.cachedText === this.text && this.cachedWidth === width) {
54
+ return this.cachedLines;
55
+ }
56
+
57
+ // Nothing to show: an empty line would otherwise occupy a row.
58
+ if (!this.text || this.text.trim() === '') {
59
+ const empty: string[] = [];
60
+ this.cachedText = this.text;
61
+ this.cachedWidth = width;
62
+ this.cachedLines = empty;
63
+ return empty;
64
+ }
65
+
66
+ const normalizedText = this.text.replace(/\t/g, ' ');
67
+
68
+ // Shrink the margins rather than let content overflow on a narrow viewport.
69
+ const paddingX = Math.min(this.paddingX, Math.max(0, Math.floor((width - 1) / 2)));
70
+ const contentWidth = Math.max(1, width - paddingX * 2);
71
+
72
+ // Wrap first (preserves ANSI, does not pad), then margin each row.
73
+ const wrappedLines = wrapTextWithAnsi(normalizedText, contentWidth);
74
+ const margin = ' '.repeat(paddingX);
75
+
76
+ const contentLines: string[] = [];
77
+ for (const line of wrappedLines) {
78
+ const withMargins = margin + line + margin;
79
+ if (this.customBgFn) {
80
+ // applyBackgroundToLine also pads to full width.
81
+ contentLines.push(applyBackgroundToLine(withMargins, width, this.customBgFn));
82
+ } else {
83
+ const pad = Math.max(0, width - visibleWidth(withMargins));
84
+ contentLines.push(withMargins + ' '.repeat(pad));
85
+ }
86
+ }
87
+
88
+ const blank = ' '.repeat(width);
89
+ const emptyLines: string[] = [];
90
+ for (let i = 0; i < this.paddingY; i++) {
91
+ emptyLines.push(
92
+ this.customBgFn ? applyBackgroundToLine(blank, width, this.customBgFn) : blank,
93
+ );
94
+ }
95
+
96
+ const result = [...emptyLines, ...contentLines, ...emptyLines];
97
+ this.cachedText = this.text;
98
+ this.cachedWidth = width;
99
+ this.cachedLines = result;
100
+ return result.length > 0 ? result : [''];
101
+ }
102
+ }
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Fenced code blocks in the transcript: segmentation + boxed rendering.
3
+ *
4
+ * Both exports are pure and deterministic — same input bytes → same output
5
+ * bytes, no clock or randomness. Hover/success paint arrives as explicit
6
+ * `opts` parameters, never as ambient state, so the TUI can repaint
7
+ * differentially and the components can cache by width without desyncing
8
+ * the screen from the cache.
9
+ */
10
+
11
+ import {truncateToWidth} from '../tty-width.js';
12
+ import {paintPanel} from '../surface/paint-panel.js';
13
+
14
+ import {c, codebox} from '../../theme.js';
15
+ import {buildHeader, displayWidth, wrapText} from './format.js';
16
+ import {highlightCode, highlightDiff, inferDiffCodeLang} from './highlight.js';
17
+ import {diffLineTint, tintLine} from './highlight.js';
18
+
19
+ /** One piece of an assistant message: prose, or a fenced code block. */
20
+ export type CodeSegment =
21
+ | {readonly kind: 'text'; readonly text: string}
22
+ | {readonly kind: 'code'; readonly lang: string; readonly lines: readonly string[]};
23
+
24
+ /** Right-edge copy affordance drawn in rendered code-block headers. */
25
+ export const COPY_LABEL = '⧉ copy';
26
+
27
+ /** Header label once the copy succeeded — wider than COPY_LABEL, so the
28
+ * dash run and copy zone must recompute from it. */
29
+ export const SUCCESS_LABEL = '✓ copied';
30
+
31
+ /**
32
+ * Screen geometry of the header copy zone: the rightmost columns of the
33
+ * header row — the label plus the closing corner (`⧉ copy╮`). Returns null
34
+ * when disabled or when the box is too narrow for the label plus at least
35
+ * one dash. Measured with `displayWidth` (=== `visibleWidth`), so the
36
+ * renderer and the click hit-test always agree on the same columns even if
37
+ * the label's ambiguous-width glyph is measured differently than expected.
38
+ * `label` defaults to COPY_LABEL; pass SUCCESS_LABEL while the success
39
+ * chip is painted so the hit-test follows the reflowed zone.
40
+ */
41
+ export function copyZoneRect(
42
+ W: number,
43
+ tag: string,
44
+ enabled: boolean,
45
+ label = COPY_LABEL,
46
+ ): {startCol: number; width: number} | null {
47
+ const tagW = displayWidth(tag.trim());
48
+ const tagged = tag.trim() !== '' && tagW + 6 <= W;
49
+ const dashes = tagged ? W - tagW - 5 : W - 2;
50
+ const labelW = displayWidth(label);
51
+ if (!enabled || dashes - labelW < 1) return null;
52
+ return {startCol: W - labelW - 1, width: labelW + 1};
53
+ }
54
+
55
+ // Opening fence: up to 3 leading spaces, 3+ backticks, then an info string
56
+ // that must not itself contain backticks (CommonMark) — so a line like
57
+ // "```code```" mid-paragraph stays prose.
58
+ const OPEN_FENCE = /^ {0,3}(`{3,})([^`]*)$/;
59
+ // Closing fence: backticks and whitespace only, and never shorter than the opener.
60
+ const CLOSE_FENCE = /^ {0,3}(`{3,})[ \t]*$/;
61
+
62
+ function trimBlankEdges(lines: readonly string[]): readonly string[] {
63
+ let start = 0;
64
+ let end = lines.length;
65
+ while (start < end && (lines[start] ?? '').trim() === '') start++;
66
+ while (end > start && (lines[end - 1] ?? '').trim() === '') end--;
67
+ return lines.slice(start, end);
68
+ }
69
+
70
+ /**
71
+ * Split markdown into prose and fenced code segments.
72
+ *
73
+ * Handles the edge cases that show up in real model output: an unclosed
74
+ * fence at the end of the message (runs to end), no language tag, padded or
75
+ * mixed-case tags, fences that interrupt a paragraph, CRLF endings, and
76
+ * longer (````) fences whose content contains triple backticks.
77
+ */
78
+ export function parseCodeSegments(text: string): CodeSegment[] {
79
+ const segments: CodeSegment[] = [];
80
+ let textLines: string[] = [];
81
+ let fence: {ticks: number; lang: string; lines: string[]} | null = null;
82
+
83
+ const flushText = (): void => {
84
+ const kept = trimBlankEdges(textLines);
85
+ textLines = [];
86
+ if (kept.length > 0) segments.push({kind: 'text', text: kept.join('\n')});
87
+ };
88
+
89
+ for (const line of text.split(/\r\n|\r|\n/)) {
90
+ if (fence) {
91
+ const close = CLOSE_FENCE.exec(line);
92
+ if (close && (close[1] ?? '').length >= fence.ticks) {
93
+ segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
94
+ fence = null;
95
+ } else {
96
+ fence.lines.push(line);
97
+ }
98
+ continue;
99
+ }
100
+
101
+ const open = OPEN_FENCE.exec(line);
102
+ if (open) {
103
+ flushText();
104
+ const info = (open[2] ?? '').trim();
105
+ fence = {
106
+ ticks: (open[1] ?? '').length,
107
+ lang: info.split(/\s+/)[0] ?? '',
108
+ lines: [],
109
+ };
110
+ continue;
111
+ }
112
+ textLines.push(line);
113
+ }
114
+
115
+ if (fence) segments.push({kind: 'code', lang: fence.lang, lines: fence.lines});
116
+ flushText();
117
+ return segments;
118
+ }
119
+
120
+ /**
121
+ * Side-by-side rendering kicks in for diff/patch blocks once the box is
122
+ * wide enough for two readable code columns; narrower boxes keep the
123
+ * unified single-column layout.
124
+ */
125
+ const SIDE_BY_SIDE_MIN_WIDTH = 90;
126
+
127
+ /** One rendered diff row: a full-width header/hunk, or a left/right pair. */
128
+ export type DiffRow =
129
+ | {readonly kind: 'full'; readonly text: string}
130
+ | {readonly kind: 'split'; readonly left: string | null; readonly right: string | null};
131
+
132
+ /**
133
+ * Pair unified-diff lines into side-by-side rows.
134
+ *
135
+ * File headers (`---`/`+++`) and hunk markers (`@@`) span both columns;
136
+ * context lines mirror on both sides; `-` runs zip against the `+` run
137
+ * that follows them, short side blank-paired.
138
+ */
139
+ export function pairDiffRows(lines: readonly string[]): DiffRow[] {
140
+ const rows: DiffRow[] = [];
141
+ let removals: string[] = [];
142
+ let additions: string[] = [];
143
+ const flush = (): void => {
144
+ const n = Math.max(removals.length, additions.length);
145
+ for (let i = 0; i < n; i++) {
146
+ rows.push({kind: 'split', left: removals[i] ?? null, right: additions[i] ?? null});
147
+ }
148
+ removals = [];
149
+ additions = [];
150
+ };
151
+ for (const line of lines) {
152
+ if (line.startsWith('---') || line.startsWith('+++') || line.startsWith('@@')) {
153
+ flush();
154
+ rows.push({kind: 'full', text: line});
155
+ } else if (line.startsWith('-')) {
156
+ removals.push(line);
157
+ } else if (line.startsWith('+')) {
158
+ additions.push(line);
159
+ } else {
160
+ flush();
161
+ rows.push({kind: 'split', left: line, right: line});
162
+ }
163
+ }
164
+ flush();
165
+ return rows;
166
+ }
167
+
168
+ /**
169
+ * Render paired diff rows as two columns separated by a border wall.
170
+ * Cells never wrap — overlong lines hard-truncate so the columns stay
171
+ * aligned at EN width; each cell keeps its own line-role color.
172
+ */
173
+ function sideBySideBody(
174
+ rawLines: readonly string[],
175
+ W: number,
176
+ paint: (s: string) => string,
177
+ ): string[] {
178
+ // Walls + padding + middle separator consume 7 columns; the rest splits
179
+ // into left/right code columns (left takes the odd column, if any).
180
+ const leftW = Math.floor((W - 7) / 2);
181
+ const rightW = W - 7 - leftW;
182
+ const inner = W - 4;
183
+ // Code language guessed from the ---/+++ headers so added/removed code
184
+ // gets syntax colors, not just the +/- role color.
185
+ const codeLang = inferDiffCodeLang(rawLines);
186
+ const cell = (text: string | null, w: number, tint: string | null): string => {
187
+ const safe = truncateToWidth(text ?? '', w, '');
188
+ const padded = `${safe}${' '.repeat(Math.max(0, w - displayWidth(safe)))}`;
189
+ return tint ? tintLine(padded, tint) : padded;
190
+ };
191
+ const rows: string[] = [];
192
+ for (const row of pairDiffRows(rawLines)) {
193
+ if (row.kind === 'full') {
194
+ // Content spans the full inner width (walls + padding account for
195
+ // the rest) — one short and paintPanel pads AFTER the closing wall,
196
+ // drifting it a column left of the split rows' walls.
197
+ const safe = truncateToWidth(highlightDiff(row.text), inner, '');
198
+ const pad = Math.max(0, inner - displayWidth(safe));
199
+ rows.push(`${paint('│')} ${safe}${' '.repeat(pad)} ${paint('│')}`);
200
+ continue;
201
+ }
202
+ const left = cell(
203
+ row.left ? highlightDiff(row.left, codeLang) : '',
204
+ leftW,
205
+ row.left ? diffLineTint(row.left) : null,
206
+ );
207
+ const right = cell(
208
+ row.right ? highlightDiff(row.right, codeLang) : '',
209
+ rightW,
210
+ row.right ? diffLineTint(row.right) : null,
211
+ );
212
+ rows.push(`${paint('│')} ${left} ${paint('│')} ${right} ${paint('│')}`);
213
+ }
214
+ return rows;
215
+ }
216
+
217
+ /**
218
+ * Render one fenced code segment as a bordered, language-tagged box:
219
+ *
220
+ * ╭─ typescript ────────╮
221
+ * │ 1 const x = 1; │
222
+ * │ 2 console.log(x); │
223
+ * ╰─────────────────────╯
224
+ *
225
+ * The header tier carries the language tag and copy affordance; body rows
226
+ * get an optional line-number gutter (dimmer than the border, shown once
227
+ * the box is wide enough to keep a usable code column). Every row is drawn
228
+ * first, then passed through `paintPanel` so the surface fill re-opens after
229
+ * any embedded reset — same isolation guarantee as the sidebar panel. Code
230
+ * is syntax-highlighted via the existing `highlightCode` helper, then
231
+ * wrapped and hard-truncated to the box — no row ever exceeds `width`.
232
+ */
233
+ export function codeBlockBox(
234
+ code: string,
235
+ width: number,
236
+ lang = '',
237
+ opts?: {copy?: boolean; hover?: boolean; success?: boolean},
238
+ ): string {
239
+ // One clamp before anything is derived, so header/body/footer agree.
240
+ const W = Math.max(6, Math.floor(width));
241
+ const inner = W - 4; // columns between "│ " and " │"
242
+
243
+ const tag = lang.trim();
244
+ const hover = opts?.hover === true;
245
+ const success = opts?.success === true;
246
+ // Rows are painted WITHOUT the fill: `paint` switches only the foreground
247
+ // role, and `paintPanel` at the end opens the surface fill once per row
248
+ // and re-opens it after any embedded reset (highlightCode emits them).
249
+ // Reset after each border glyph so code text never inherits the border
250
+ // foreground (e.g. faint+cyan).
251
+ const paint = (s: string): string => `${codebox.borderFg}${s}${c.reset}`;
252
+
253
+ // Copy affordance: pin the label at the right edge of the header (zone
254
+ // includes the closing ╮) while the visible width stays exactly W.
255
+ // Chip precedence: success > hover > idle — success swaps both the
256
+ // label and the fg, and the zone reflows from the wider label.
257
+ const labelText = success ? SUCCESS_LABEL : COPY_LABEL;
258
+ const zone = copyZoneRect(W, tag, opts?.copy === true, labelText);
259
+ const tagW = displayWidth(tag);
260
+ const labelW = displayWidth(labelText);
261
+ const chipBg = hover && !success ? codebox.chipBgHover : codebox.chipBgIdle;
262
+ const chipFg = success ? codebox.successFg : hover ? codebox.chipFgHover : codebox.chipFgIdle;
263
+ const chip = `${chipBg}${chipFg}${labelText}`;
264
+
265
+ let header: string;
266
+ if (!zone) {
267
+ header = tag
268
+ ? buildHeader(W, tag, tagW, codebox.langFg, paint, '')
269
+ : paint(`╭${'─'.repeat(W - 2)}╮`);
270
+ } else if (tag !== '' && tagW + 6 <= W) {
271
+ const dashes = W - tagW - 5 - labelW;
272
+ header =
273
+ `${paint('╭─')} ${codebox.langFg}${tag}${c.reset} ${paint('─'.repeat(dashes))}` +
274
+ `${chip}${paint('╮')}`;
275
+ } else {
276
+ const dashes = W - 2 - labelW;
277
+ header = `${paint(`╭${'─'.repeat(dashes)}`)}${chip}${paint('╮')}`;
278
+ }
279
+
280
+ // Line-number gutter: a right-aligned number column in a dimmer shade of
281
+ // the border, shown for multi-line blocks once the code column keeps at
282
+ // least 8 columns. Wrapped continuation rows get a blank gutter so the
283
+ // code column stays aligned at EN width.
284
+ // Diff/patch blocks render side-by-side once wide enough; the unified
285
+ // single-column path below stays the narrow fallback.
286
+ const isDiff = tag === 'diff' || tag === 'patch';
287
+ if (isDiff && W >= SIDE_BY_SIDE_MIN_WIDTH) {
288
+ const footer = paint(`╰${'─'.repeat(W - 2)}╯`);
289
+ return [header, ...sideBySideBody(code.split('\n'), W, paint), footer]
290
+ .map((line) => paintPanel(codebox.surfaceBg, line, W))
291
+ .join('\n');
292
+ }
293
+
294
+ const srcLines = highlightCode(code, tag || undefined);
295
+ const gutterW = String(srcLines.length).length;
296
+ const gutterOn = srcLines.length > 1 && inner - gutterW - 2 >= 8;
297
+ const available = inner - (gutterOn ? gutterW + 1 : 0); // columns for code + right pad
298
+ const textWidth = Math.max(1, available - 1); // reserve the last available column
299
+
300
+ const body: string[] = [];
301
+ // Raw lines run 1:1 with highlighted srcLines on the diff path (map, no
302
+ // expansion), so per-line role lookup stays aligned; other languages
303
+ // never consult rawLines.
304
+ const rawLines = code.split('\n');
305
+ for (let i = 0; i < srcLines.length; i++) {
306
+ const parts = wrapText(srcLines[i] ?? '', textWidth);
307
+ for (let j = 0; j < parts.length; j++) {
308
+ const safe = truncateToWidth((parts[j] ?? '').trimEnd(), textWidth, '');
309
+ const pad = Math.max(0, available - displayWidth(safe));
310
+ const gutter = gutterOn
311
+ ? j === 0
312
+ ? `${codebox.gutterFg}${String(i + 1).padStart(gutterW)}${c.reset}`
313
+ : ' '.repeat(gutterW)
314
+ : '';
315
+ const lead = gutterOn ? `${gutter} ` : '';
316
+ const content = `${lead}${safe}${c.reset}${' '.repeat(pad)}`;
317
+ const tint = isDiff ? diffLineTint(rawLines[i] ?? '') : null;
318
+ body.push(`${paint('│')} ${tint ? tintLine(content, tint) : content} ${paint('│')}`);
319
+ }
320
+ }
321
+
322
+ const footer = paint(`╰${'─'.repeat(W - 2)}╯`);
323
+
324
+ return [header, ...body, footer].map((line) => paintPanel(codebox.surfaceBg, line, W)).join('\n');
325
+ }