@hncode/hncode 0.7.8 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/panels.js ADDED
@@ -0,0 +1,256 @@
1
+ // The stacked panels above the composer: the title strip, the todo list and the queue.
2
+ //
3
+ // Each pair of functions here is a HEIGHT and a RENDERER for the same panel. Keeping them in one module is what stops
4
+ // them disagreeing: a reserved height that does not match the drawn rows shifts every row below it by one.
5
+
6
+ import { C } from './colors.js';
7
+ import { col, fitAnsi, wrapWords } from './text.js';
8
+
9
+ // ---- title strip ----------------------------------------------------------
10
+
11
+ /**
12
+ * The title strip along the top of the screen.
13
+ *
14
+ * `maxRows` is how many rows of name to show. A name that fits on one row uses one; a longer one WRAPS, and the rows it
15
+ * needs are reserved for it — a terminal is narrow, and cutting a session name to its first forty characters loses the
16
+ * part that told them apart. The last visible row ends in `…` when the name continues below.
17
+ *
18
+ * `state.titleRows` is the height the user dragged the rule to. `0` or unset means "as many as the name needs", which
19
+ * is what a fresh session wants. The rule is always the LAST row, so it is always in the same place to grab.
20
+ */
21
+ export function renderTitleBar(state, w, hover, maxRows) {
22
+ const title = String(state.sessionTitle || '').trim();
23
+ // A NAMELESS SESSION IS NOT A BLANK BAND. `Untitled` says the strip is there and can be clicked; an empty row reads
24
+ // as a rendering gap.
25
+ const label = title || 'Untitled';
26
+ const out = [];
27
+ // ONE LEADING SPACE, matching the transcript's own left margin so the name lines up with the messages below.
28
+ const PAD = ' ';
29
+ const room = Math.max(1, w - PAD.length);
30
+ const rows = Math.max(1, Math.round(maxRows) || 1);
31
+ // Wrap the name to the width, keeping ANSI out of it — the colour is applied per row below.
32
+ const wrapped = wrapWords(label, room);
33
+ const shownRows = wrapped.slice(0, rows);
34
+ // A name with more rows than the band can show ends in `…` on its last visible row.
35
+ const more = wrapped.length > shownRows.length;
36
+ // THE PLACEHOLDER IS THE SAME COLOUR AS A REAL NAME. Dimming it made a fresh session's band look disabled — as if the
37
+ // strip were not there to be clicked. The word already says the session has no name.
38
+ const textColor = hover ? C.heading : C.cyan;
39
+ const ruleColor = hover ? C.cyan : C.border;
40
+ for (let i = 0; i < shownRows.length; i++) {
41
+ let line = shownRows[i];
42
+ if (i === shownRows.length - 1 && more) {
43
+ // Trim one column so the ellipsis fits inside the width instead of pushing the row over.
44
+ line = fitAnsi(line, room - 1).trimEnd() + '…';
45
+ }
46
+ out.push(fitAnsi(PAD + col(line, textColor + C.bold), w));
47
+ }
48
+ out.push(col('─'.repeat(w), ruleColor));
49
+ return out;
50
+ }
51
+
52
+ /** How many rows the title needs at this width, ignoring any drag. */
53
+ export function titleRowsNeeded(state, w) {
54
+ const title = String(state.sessionTitle || '').trim() || 'Untitled';
55
+ const room = Math.max(1, w - 1);
56
+ return Math.max(1, wrapWords(title, room).length);
57
+ }
58
+
59
+ /**
60
+ * Name rows currently shown: the dragged height when set, otherwise as many as the name needs.
61
+ *
62
+ * Reading it from `state.titleRows` rather than from the frame keeps the drag arithmetic independent of what was last
63
+ * painted.
64
+ */
65
+ export function titleRowCount(state) {
66
+ const need = titleRowsNeeded(state, state.cols || process.stdout.columns || 80);
67
+ const set = Math.round(Number(state.titleRows) || 0);
68
+ return set > 0 ? Math.min(set, need) : need;
69
+ }
70
+
71
+ // ---- todo panel -----------------------------------------------------------
72
+
73
+ /** How many todo rows the panel shows when nothing has been dragged. */
74
+ export const TODO_MAX_VISIBLE = 5;
75
+
76
+ /**
77
+ * The first `max` entries, in the order they were written.
78
+ *
79
+ * This used to RANK: in-progress first, then one done item, then pending. On a status change the panel therefore
80
+ * reshuffled — the item being worked on jumped to the top and a finished one followed it — and the list stopped
81
+ * describing the order the work was planned in. A task list is a sequence; a view that reorders it is showing something
82
+ * other than what was written.
83
+ */
84
+ export function selectVisibleTodos(todos, max = TODO_MAX_VISIBLE) {
85
+ const list = Array.isArray(todos) ? todos : [];
86
+ const limit = Number.isFinite(max) ? Math.max(0, Math.round(max)) : TODO_MAX_VISIBLE;
87
+ if (list.length <= limit) return { rows: list, hidden: 0, counts: {} };
88
+ const rows = list.slice(0, limit);
89
+ const counts = { done: 0, in_progress: 0, pending: 0 };
90
+ for (let i = limit; i < list.length; i++) {
91
+ const s = list[i] && list[i].status;
92
+ counts[s] = (counts[s] || 0) + 1;
93
+ }
94
+ return { rows, hidden: list.length - rows.length, counts };
95
+ }
96
+
97
+ /** One todo line: a status mark and the title, coloured by status. */
98
+ export function todoRow(todo, w) {
99
+ const mark = todo.status === 'in_progress' ? col('●', C.cyan + C.bold)
100
+ : todo.status === 'done' ? col('✓', C.green)
101
+ : col('○', C.gray);
102
+ const title = todo.status === 'in_progress' ? col(todo.title, C.white + C.bold)
103
+ : todo.status === 'done' ? col(todo.title, C.gray)
104
+ : col(todo.title, C.white);
105
+ return ' ' + mark + ' ' + fitAnsi(title, Math.max(1, w - 4));
106
+ }
107
+
108
+ /**
109
+ * Is this list FINISHED — every item done, and at least one item?
110
+ *
111
+ * A finished list is DROPPED, not merely hidden: it has stopped being a list of what is left to do, so the data goes as
112
+ * well as the panel. Hiding alone left the array to be persisted with the session and handed back to the model as
113
+ * `cfg.todoState`, which is a finished plan being described as current work.
114
+ *
115
+ * `every` on an EMPTY array is true, so the length check is load-bearing: this must not fire for "no todos", which is a
116
+ * different state with its own handling everywhere else.
117
+ */
118
+ export function todosAllComplete(list) {
119
+ const todos = Array.isArray(list) ? list : [];
120
+ return todos.length > 0 && todos.every((t) => t && t.status === 'done');
121
+ }
122
+
123
+ /** The same question, asked of a TUI state object rather than a bare array. */
124
+ export function todoListFinished(state) {
125
+ return todosAllComplete(state && state.todos);
126
+ }
127
+
128
+ /**
129
+ * How many todo ROWS the panel shows.
130
+ *
131
+ * `state.todoRows` (set by dragging the top rule) wins when present; otherwise the automatic heuristic decides. Always
132
+ * clamped to [1, todos.length]: at least ONE row, never more than exist.
133
+ */
134
+ export function todoRowCount(state) {
135
+ const todos = state.todos || [];
136
+ if (!todos.length) return 0;
137
+ // A finished list has no rows: see `todoListFinished`.
138
+ if (todoListFinished(state)) return 0;
139
+ const manual = state.todoRows;
140
+ let rows;
141
+ if (typeof manual === 'number' && Number.isFinite(manual)) {
142
+ rows = Math.round(manual);
143
+ } else {
144
+ rows = state.todosExpanded ? todos.length : selectVisibleTodos(todos).rows.length;
145
+ }
146
+ return Math.max(1, Math.min(todos.length, rows));
147
+ }
148
+
149
+ /** Height (in rows) the todo panel will occupy, for layout math. */
150
+ export function todoPanelHeight(state) {
151
+ const todos = state.todos || [];
152
+ if (!todos.length) return 0;
153
+ // Zero once everything is done, so the chrome shrinks by the panel's whole height rather than leaving a blank gap.
154
+ // Both this and the renderer ask the same predicate, so the reserved height and the drawn rows cannot disagree — a
155
+ // mismatch there shifts every row below.
156
+ if (todoListFinished(state)) return 0;
157
+ const rows = todoRowCount(state);
158
+ const extra = todos.length > rows ? 1 : 0; // the "… +N more" hint
159
+ return 2 + rows + extra; // rule + heading + rows (+ hint)
160
+ }
161
+
162
+ export function renderTodoPanel(state, w, hoverTop, dragTop) {
163
+ const todos = state.todos || [];
164
+ if (!todos.length) return [];
165
+ // A finished list draws NOTHING, matching `todoPanelHeight` returning 0 for the same state.
166
+ if (todoListFinished(state)) return [];
167
+ const out = [];
168
+ const ruleColor = dragTop ? C.scrollThumbActive : (hoverTop ? C.hover : C.border);
169
+ out.push(col('─'.repeat(w), ruleColor));
170
+ out.push(col(' Todo', C.cyan + C.bold));
171
+ const want = todoRowCount(state);
172
+ // CREATION ORDER, ALWAYS. Which rows fit is still the panel's decision — it takes the first `want` in order.
173
+ const rows = todos.slice(0, want);
174
+ for (const t of rows) out.push(todoRow(t, w));
175
+ const hidden = todos.length - rows.length;
176
+ if (hidden > 0) {
177
+ const counts = { done: 0, in_progress: 0, pending: 0 };
178
+ for (const t of todos) if (!rows.includes(t)) counts[t.status] = (counts[t.status] || 0) + 1;
179
+ const dist = [['done', 'done'], ['in_progress', 'in progress'], ['pending', 'pending']]
180
+ .filter(([k]) => counts[k] > 0).map(([k, label]) => `${counts[k]} ${label}`).join(', ');
181
+ // The hint appears exactly when rows are hidden — which is exactly when Ctrl+T is useful — so this is where the key
182
+ // has to be discoverable.
183
+ out.push(col(` … +${hidden} more${dist ? ` (${dist})` : ''} · ctrl+t to expand · drag the top rule to resize`, C.gray));
184
+ }
185
+ return out;
186
+ }
187
+
188
+ // ---- queue panel ----------------------------------------------------------
189
+
190
+ /** How many queued messages the panel shows when nothing has been dragged. */
191
+ export const QUEUE_MAX_VISIBLE = 5;
192
+
193
+ /**
194
+ * How many queue ROWS the panel shows.
195
+ *
196
+ * `state.queueRows` (set by dragging the top rule) wins when present; otherwise show all items up to the cap. Always
197
+ * clamped to [1, queued.length]: at least ONE row, never more than exist.
198
+ */
199
+ export function queueRowCount(state) {
200
+ const queued = state.queued || [];
201
+ if (!queued.length) return 0;
202
+ const manual = state.queueRows;
203
+ let rows;
204
+ if (typeof manual === 'number' && Number.isFinite(manual)) {
205
+ rows = Math.round(manual);
206
+ } else {
207
+ rows = Math.min(queued.length, QUEUE_MAX_VISIBLE);
208
+ }
209
+ return Math.max(1, Math.min(queued.length, rows));
210
+ }
211
+
212
+ /** Height (in rows) the queue panel will occupy, for layout math. */
213
+ export function queuePanelHeight(state) {
214
+ const queued = state.queued || [];
215
+ if (!queued.length) return 0;
216
+ const rows = queueRowCount(state);
217
+ const extra = queued.length > rows ? 1 : 0; // the "… +N more" hint
218
+ return 2 + rows + extra; // rule + heading + rows (+ hint)
219
+ }
220
+
221
+ /**
222
+ * The queue pane: one rule, one line per queued message, one dim hint line.
223
+ *
224
+ * Queued input is held while the agent is streaming and is injected by Ctrl+S (or by the agent itself at the next tool
225
+ * boundary). Supports auto-collapse and drag-to-resize like the todo panel.
226
+ */
227
+ export function renderQueuePanel(state, w, hoverTop, dragTop) {
228
+ const queued = state.queued || [];
229
+ if (!queued.length) return [];
230
+
231
+ const out = [];
232
+ const ruleColor = dragTop ? C.scrollThumbActive : (hoverTop ? C.hover : C.border);
233
+ out.push(col('─'.repeat(w), ruleColor));
234
+ out.push(col(' Queue', C.cyan + C.bold));
235
+
236
+ const want = queueRowCount(state);
237
+ const rows = queued.slice(0, want);
238
+ for (const text of rows) {
239
+ // Collapse to a single line, so one queued message is one row however it was typed.
240
+ const single = String(text).replace(/\s+/g, ' ').trim();
241
+ out.push(col(' ', C.cyan) + col('> ', C.cyan) + col(fitAnsi(single, Math.max(1, w - 6)), C.white));
242
+ }
243
+
244
+ const hidden = queued.length - rows.length;
245
+ if (hidden > 0) {
246
+ const hint = state.running
247
+ ? `… +${hidden} more · ↑ to edit · ctrl-s to steer immediately · drag top rule to resize`
248
+ : `… +${hidden} more · ↑ to edit · will send now · drag top rule to resize`;
249
+ out.push(col(' ' + hint, C.gray));
250
+ } else {
251
+ const hint = state.running ? '↑ to edit · ctrl-s to steer immediately' : '↑ to edit · will send now';
252
+ out.push(col(' ' + hint, C.gray));
253
+ }
254
+
255
+ return out;
256
+ }
@@ -0,0 +1,83 @@
1
+ // Two transcript row kinds that are self-contained: the Plan card and a background task's lifecycle card.
2
+ //
3
+ // Both turn one message into a list of `{ text, ind, raw }` rows. `raw: true` means the text already carries its own
4
+ // ANSI and must be painted verbatim.
5
+
6
+ import { C } from './colors.js';
7
+ import { col, fitAnsi, visualCol, wrapWords } from './text.js';
8
+ import { renderMdText } from './markdown.js';
9
+
10
+ /**
11
+ * A Plan, drawn as a bordered card.
12
+ *
13
+ * `width` is the transcript's inner width (the caller already removed the one-column margin); the card lands at
14
+ * `width - 2`.
15
+ *
16
+ * Rows must be `{text, ind, raw}` OBJECTS — that is the contract the caller's `rowToLine` reads. Pushing plain strings
17
+ * here made it read `undefined` and the whole block rendered as blank lines.
18
+ */
19
+ export function planRows(msg, width) {
20
+ const tableW = Math.max(12, width - 2);
21
+ const out = [];
22
+ const bar = (ch) => col(ch, C.border);
23
+ const inner = Math.max(1, tableW - 2);
24
+ const full = (l, r) => bar(l + '─'.repeat(inner) + r);
25
+ // Header: the card's single column is captioned "Plan".
26
+ out.push({ text: full('╭', '╮'), ind: '', raw: true });
27
+ out.push({ text: bar('│') + fitAnsi(col(' Plan', C.cyan + C.bold), inner) + bar('│'), ind: '', raw: true });
28
+ out.push({ text: bar('├' + '─'.repeat(inner) + '┤'), ind: '', raw: true });
29
+ const lines = String(msg.text || '').replace(/\r\n/g, '\n').split('\n');
30
+ while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
31
+ const textW = Math.max(1, inner - 2);
32
+ for (const raw of lines) {
33
+ if (raw.trim() === '') {
34
+ out.push({ text: bar('│') + ' '.repeat(inner) + bar('│'), ind: '', raw: true });
35
+ continue;
36
+ }
37
+ // Headings are emphasised; everything else renders as Markdown body text so **bold**, `code` and bullets work.
38
+ const isHead = /^\s*#{1,6}\s/.test(raw);
39
+ const shown = isHead ? raw.replace(/^\s*#{1,6}\s*/, '') : raw;
40
+ for (const r of renderMdText(shown, textW, isHead ? (C.cyan + C.bold) : C.white, C.cyan)) {
41
+ out.push({ text: bar('│') + ' ' + fitAnsi(r, textW) + ' ' + bar('│'), ind: '', raw: true });
42
+ }
43
+ }
44
+ out.push({ text: full('╰', '╯'), ind: '', raw: true });
45
+ return out;
46
+ }
47
+
48
+ /**
49
+ * A background task's lifecycle card:
50
+ *
51
+ * ● agent task completed in background (review the diff)
52
+ * ✗ bash task failed in background (npm test · exit 1)
53
+ *
54
+ * The bullet is `●` normally and `✗` for a failure; the colour follows the phase. The task's conclusion sits underneath,
55
+ * indented, and is capped like a tool result so one chatty subagent cannot flood the transcript.
56
+ */
57
+ export function bgTaskRows(msg, width, expanded) {
58
+ const card = msg.card || { phase: 'completed', headline: 'background task finished', detail: undefined };
59
+ const tone = card.phase === 'started' ? C.cyan : card.phase === 'completed' ? C.green : C.red;
60
+ const bullet = card.phase === 'failed' ? '✗ ' : '● ';
61
+ const out = [];
62
+ const detail = card.detail ? col(` (${card.detail})`, C.gray) : '';
63
+ out.push({ text: col(bullet, tone) + col(card.headline, tone) + detail, ind: '', raw: true });
64
+ const body = String(msg.text || '').trim();
65
+ if (body) {
66
+ const indent = ' ';
67
+ const avail = Math.max(1, width - visualCol(indent));
68
+ const lines = body.replace(/\r\n/g, '\n').split('\n');
69
+ // No cap once expanded: a silent ceiling left a long result stopping short with a hint telling the user to press
70
+ // the key they had already pressed.
71
+ const MAX = expanded ? lines.length : 6;
72
+ for (const ln of lines.slice(0, MAX)) {
73
+ for (const w of (ln === '' ? [''] : wrapWords(ln, avail))) {
74
+ out.push({ text: col(w, C.gray), ind: indent, raw: true });
75
+ }
76
+ }
77
+ if (lines.length > MAX) {
78
+ // Only reachable while COLLAPSED: expanded, `MAX` is the whole list and this cannot fire.
79
+ out.push({ text: col(`… ${lines.length - MAX} more lines, ctrl+o to expand`, C.gray), ind: indent, raw: true });
80
+ }
81
+ }
82
+ return out;
83
+ }
@@ -0,0 +1,104 @@
1
+ // Two status rows in the transcript: the compaction card and a reasoning ("thinking") block.
2
+ //
3
+ // Both return rows that may carry `color` instead of `raw: true` — the caller paints them by wrapping the text in that
4
+ // colour, which is what keeps a cached row cheap to re-render.
5
+
6
+ import { C } from './colors.js';
7
+ import { col, visualCol, wrapWords } from './text.js';
8
+ import { fmtTokens } from './format.js';
9
+ import { SPIN_PLACEHOLDER } from './animate.js';
10
+
11
+ /**
12
+ * The compaction card:
13
+ *
14
+ * running -> blinking bullet + "Compacting context…" (+ optional instruction)
15
+ * done -> solid green bullet + "Compaction complete (X → Y tokens)" + a Ctrl-O hint
16
+ * cancelled -> warning bullet + "Compaction cancelled"
17
+ *
18
+ * Expanded state is the SHARED Ctrl+O one, so one key reveals tool output and compaction summaries alike.
19
+ */
20
+ export function compactionRows(msg, width, expanded, spin) {
21
+ const INDENT = ' ';
22
+ const done = msg.phase === 'done';
23
+ const canceled = msg.phase === 'cancelled';
24
+ const bulletColor = done ? C.green : canceled ? C.yellow : C.white;
25
+ // Blink off `spin` — the same monotonic tick the tool-call bullets use. It has to be a STATE-driven phase, NOT
26
+ // `Date.now()`: the render cache is validated against the spin key, so a clock-derived phase changes without
27
+ // invalidating the cache and the bullet renders once and then freezes.
28
+ const on = ((spin || 0) >> 3) % 2 === 0;
29
+ const bullet = (!done && !canceled && !on) ? ' ' : col('● ', bulletColor);
30
+ let head;
31
+ if (done) {
32
+ const detail = (msg.tokensBefore != null && msg.tokensAfter != null)
33
+ ? col(` (${fmtTokens(msg.tokensBefore)} → ${fmtTokens(msg.tokensAfter)} tokens)`, C.gray) : '';
34
+ const hint = (msg.text || '').trim()
35
+ ? col(` (Ctrl-O to ${expanded ? 'hide' : 'show'} compaction summary)`, C.gray) : '';
36
+ head = bullet + col('Compaction complete', C.green + C.bold) + detail + hint;
37
+ } else if (canceled) {
38
+ head = bullet + col('Compaction cancelled', C.yellow + C.bold)
39
+ + (msg.reason ? col(' (' + msg.reason + ')', C.gray) : '');
40
+ } else {
41
+ head = bullet + col('Compacting context…', C.cyan + C.bold);
42
+ }
43
+ const out = [{ text: head, ind: '', raw: true }];
44
+ if (msg.instruction) {
45
+ out.push({ text: INDENT + col(String(msg.instruction), C.gray), ind: INDENT, raw: true });
46
+ }
47
+ if (done && expanded && (msg.text || '').trim()) {
48
+ const bodyW = Math.max(1, width - visualCol(INDENT));
49
+ for (const ln of String(msg.text).replace(/\r\n/g, '\n').split('\n')) {
50
+ if (ln === '') { out.push({ text: '', ind: INDENT, raw: true }); continue; }
51
+ for (const w of wrapWords(ln, bodyW)) {
52
+ out.push({ text: INDENT + col(w, C.gray), ind: INDENT, raw: true });
53
+ }
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * A reasoning block:
61
+ *
62
+ * live -> "<spinner> thinking…" then the LAST 2 content lines, indented
63
+ * finalized -> "● " marker on the first line, up to 2 preview lines, then a "… (N more lines)" hint
64
+ *
65
+ * All of it is dim text, and the body is italic.
66
+ */
67
+ export function thinkingRows(msg, width, expanded) {
68
+ const INDENT = ' ';
69
+ const bodyW = Math.max(1, width - visualCol(INDENT));
70
+ const contentLines = [];
71
+ for (const ln of String(msg.text || '').replace(/\r\n/g, '\n').split('\n')) {
72
+ if (ln === '') { contentLines.push(''); continue; }
73
+ for (const w of wrapWords(ln, bodyW)) contentLines.push(w);
74
+ }
75
+ // AN EMPTY REASONING BLOCK DRAWS NOTHING.
76
+ //
77
+ // A model may emit a `think` event with no text, and the block that spans a tool call can be left with nothing in it —
78
+ // the tool boundary finalises the block, so when the model reasons again it opens a NEW one. Either way the old code
79
+ // drew a bare `●` row (or a lone "thinking…" spinner), which reads as a rendering bug: there is no thought to show.
80
+ //
81
+ // Only the RENDERING is suppressed. The block stays in `state.chat`, so the next `think` event APPENDS to it rather
82
+ // than opening another one — the state machine, and the row cache that keys on it, is unchanged.
83
+ if (!contentLines.some((l) => l.trim() !== '')) return [];
84
+ const PREVIEW = expanded ? Infinity : 2;
85
+ // The reasoning BODY is italic; the "thinking…" label and the "N more lines" hint are NOT. Closed with endItalic
86
+ // rather than a reset, so the row keeps the dim grey it is drawn in.
87
+ const it = (s) => (s === '' ? s : C.italic + s + C.endItalic);
88
+ const out = [];
89
+ if (msg.pending) {
90
+ // The spinner frame is NOT baked in here: a glyph that changes every tick would invalidate this row's cache and
91
+ // re-wrap the whole reasoning block each time, which is what made long thinking look laggy. The caller substitutes
92
+ // the live frame outside the cache instead.
93
+ out.push({ text: SPIN_PLACEHOLDER + ' thinking…', ind: '', color: C.gray });
94
+ const vis = contentLines.length > PREVIEW ? contentLines.slice(-PREVIEW) : contentLines;
95
+ for (const l of vis) out.push({ text: it(l), ind: INDENT, color: C.gray });
96
+ } else {
97
+ const shown = contentLines.slice(0, PREVIEW);
98
+ shown.forEach((l, i) => out.push({ text: it(l), ind: i === 0 ? '● ' : INDENT, color: C.gray }));
99
+ if (contentLines.length > PREVIEW) {
100
+ out.push({ text: `… (${contentLines.length - PREVIEW} more lines, ctrl+o to expand)`, ind: INDENT, color: C.gray });
101
+ }
102
+ }
103
+ return out;
104
+ }
@@ -0,0 +1,208 @@
1
+ // A tool result row: the `↳` block under the tool line.
2
+ //
3
+ // The shape is the same for every tool, and the parts differ:
4
+ //
5
+ // ● Used Edit (a.js) +1 -1 <- the tool line, counts only
6
+ // ↳ 179 - old line <- ONE `↳` on the FIRST body row
7
+ // 179 + new line
8
+ // Edited a.js: replaced 1 occurrence(s). <- receipt LAST
9
+ //
10
+ // An Edit's DIFF is the body and carries the marker, with the receipt moved to the bottom; every other tool's output
11
+ // IS the body and carries the marker on its first line.
12
+
13
+ import { C } from './colors.js';
14
+ import { col, expandTabs, fitAnsi, sanitizeText, visualCol, wrapWords } from './text.js';
15
+ import { langForPath } from './highlight.js';
16
+ import { paintCode } from './diff.js';
17
+
18
+ export function toolResultRows(msg, width, expanded) {
19
+ // The marker sits in the SAME COLUMN as the tool bullet `●` (columns 0-1), so `↳ ` starts at column 0 and the output
20
+ // text is indented to the tool text column. ONE `↳` per result, however many lines it has.
21
+ const pre = '↳ ';
22
+ const cont = ' ';
23
+ const bodyW = Math.max(1, width - visualCol(cont));
24
+ // Strip escapes BEFORE splitting: a file or a command can emit raw cursor codes, and letting them through made the
25
+ // terminal OBEY them — recolouring the transcript, resetting styles mid-row, clearing the screen over the composer.
26
+ const rawLines = sanitizeText(msg.text).replace(/\r\n/g, '\n').split('\n');
27
+ // A TAB counts as ZERO columns in our width maths but advances to the next tab stop in a real terminal. A row
28
+ // containing one was therefore padded short and the terminal kept the old frame's glyphs in the gap — the "residue"
29
+ // under tool output. Read rows are the exception: their first tab is the line-number separator and is handled in the
30
+ // Read branch below, where the CONTENT half is expanded too.
31
+ if (!msg.readPath) for (let k = 0; k < rawLines.length; k++) rawLines[k] = expandTabs(rawLines[k]);
32
+ // Trim blank lines at BOTH ends: commands typically emit a trailing newline, and some tools emit a leading one. A
33
+ // stray blank line would render as a lone "↳ " with no content.
34
+ while (rawLines.length && rawLines[0].trim() === '') rawLines.shift();
35
+ while (rawLines.length && rawLines[rawLines.length - 1].trim() === '') rawLines.pop();
36
+ const MAX_RESULT_LINES = expanded ? Infinity : 12;
37
+ // The exit-code line is bookkeeping for the AGENT and is NEVER shown to the user — success or failure. A failure is
38
+ // already legible from the RED result text below. `[error: …]` is kept: it carries the message, not just a code.
39
+ const visible = rawLines.filter((ln) => !/^\[exit code:/.test(ln.trim()));
40
+ const failed = msg.failed === true;
41
+ // A silent Bash keeps the ONE empty output row it had while running. Only Bash has this area: an empty Read/Grep
42
+ // result must not grow a phantom line merely because the command itself printed nothing.
43
+ const shown = visible.length ? visible.slice(0, MAX_RESULT_LINES) : (msg.toolName === 'Bash' ? [''] : []);
44
+
45
+ const diffRows = [];
46
+ const receiptRows = [];
47
+ const hasDiff = Array.isArray(msg.diff); // empty array => receipt-only (Write)
48
+
49
+ if (hasDiff) {
50
+ // Same collapse rule as elsewhere: a short preview by default, everything once Ctrl+O expands. 16 rows (not 12)
51
+ // because a change renders as a PAIR: `- old` then `+ new`.
52
+ const MAX = expanded ? Infinity : 16;
53
+ // Show the unified diff WITH context rows (ctx = dim) so a change is not two orphaned blocks; `gap` rows mark where
54
+ // unchanged lines were elided.
55
+ const total = msg.diff.length;
56
+ const wNo = Math.max(1, ...msg.diff.map((d) => String(d.no || 0).length));
57
+ // THE COMMENT STATE TRAVELS BETWEEN THE ROWS of one diff, so a block comment that opens on a context row and closes
58
+ // on a changed one stays grey across both.
59
+ let inComment = false;
60
+ let emitted = 0;
61
+ for (const d of msg.diff) {
62
+ if (emitted >= MAX) break;
63
+ if (d.type === 'gap') {
64
+ diffRows.push({ text: col(' ⋮', C.gray), ind: cont, raw: true });
65
+ emitted++;
66
+ continue;
67
+ }
68
+ const no = String(d.no || 0).padStart(wNo);
69
+ const mark = d.type === 'add' ? '+' : d.type === 'del' ? '-' : ' ';
70
+ // TABS ARE EXPANDED FIRST: `visualCol` counts one as zero columns, so an indented row measured short and its
71
+ // background stopped before the right edge — the strip of page colour seen on Go diffs.
72
+ const text = expandTabs(sanitizeText(d.text));
73
+
74
+ // The sign, line number and content share the line's addition/deletion background; syntax highlighting changes
75
+ // only the foreground. The wash runs to the right edge so adjacent changed rows read as one block.
76
+ const isAdd = d.type === 'add';
77
+ const isDel = d.type === 'del';
78
+ const lineBg = isAdd ? C.diffAddBg : isDel ? C.diffDelBg : '';
79
+ const fg = isAdd ? C.diffAddFg : isDel ? C.diffDelFg : C.white;
80
+ const lead = col(`${no} ${mark} `, lineBg ? fg + lineBg : fg);
81
+
82
+ if (!lineBg) {
83
+ // CONTEXT LINES ARE CODE TOO. They are most of a diff and the part a reader scans to place the change, so they
84
+ // get the same highlighter, on the CODE SURFACE rather than the raw page — a changed block sits on one recessed
85
+ // field. The +/- rows around it keep their green/red wash.
86
+ const ctxPainted = paintCode(text, d.lang, '', inComment);
87
+ inComment = ctxPainted.inComment;
88
+ const ctxRow = (lead + ctxPainted.text).replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
89
+ diffRows.push({ text: C.codeBg + fitAnsi(ctxRow, bodyW) + C.bgReset, ind: cont, raw: true });
90
+ emitted++;
91
+ continue;
92
+ }
93
+
94
+ // Keep only the line-level wash and syntax foreground. Positional word pairing can highlight the wrong token when
95
+ // lines are reordered or punctuation changes, so no word tint is applied.
96
+ const painted = paintCode(text, d.lang, lineBg, inComment);
97
+ inComment = painted.inComment;
98
+ const used = visualCol(`${no} ${mark} `) + visualCol(painted.text);
99
+ const pad = ' '.repeat(Math.max(0, bodyW - used));
100
+ // The padding is INSIDE the wash, so it must not end with a bare reset: `col()` closes with ESC[0m, which would
101
+ // drop the background on the last column and leave a strip of page colour at the right edge.
102
+ diffRows.push({ text: lead + painted.text + lineBg + pad + '\x1b[39m', ind: cont, raw: true });
103
+ emitted++;
104
+ }
105
+ if (total > emitted) {
106
+ diffRows.push({
107
+ text: col(`… (${total - emitted} more lines, ctrl+o to expand)`, C.gray),
108
+ ind: cont, raw: true,
109
+ });
110
+ }
111
+ if (total === 0) diffRows.push({ text: col('(no changes)', C.gray), ind: cont, raw: true });
112
+ // The receipt: one line per source line of the tool's own message.
113
+ for (const ln of shown) {
114
+ const color = failed ? C.red : C.gray;
115
+ for (const t of (ln === '' ? [''] : wrapWords(ln, bodyW))) {
116
+ receiptRows.push({ text: t, ind: cont, color });
117
+ }
118
+ }
119
+ } else {
120
+ // No diff: the tool's own output is the body.
121
+ //
122
+ // A READ RESULT IS SOURCE CODE, so its numbered lines are syntax-coloured — the file's own language, carried on the
123
+ // message by the tool_result handler, which is the last place that still knows the path. The header and any error
124
+ // keep the plain grey: those are the tool's own words, not the file's.
125
+ const readLang = msg.readPath ? langForPath(msg.readPath) : null;
126
+ // THE GUTTER IS ONE WIDTH FOR THE WHOLE BLOCK. The tool sends `N<TAB>text`, and the tab is what used to place the
127
+ // code — so `1` and `10` started their text at different columns once the tab was expanded. Padding the NUMBER to
128
+ // the widest one in this block keeps the digits left-aligned and the code aligned under itself.
129
+ const numW = shown.reduce((w, ln) => {
130
+ const m = /^(\d+)\t/.exec(ln);
131
+ return m ? Math.max(w, m[1].length) : w;
132
+ }, 0);
133
+ let inComment = false;
134
+ shown.forEach((ln, idx) => {
135
+ const isErr = /^\[error:/.test(ln.trim());
136
+ // A failed run is red throughout so it cannot be skimmed past.
137
+ const color = isErr ? C.red : (failed ? C.red : C.gray);
138
+ // `N<TAB>text` is the Read tool's own line format; only those rows are file content.
139
+ const numbered = readLang && !isErr ? /^(\d+)\t([\s\S]*)$/.exec(ln) : null;
140
+ if (numbered) {
141
+ // A READ CAN START INSIDE A BLOCK COMMENT. The `/**` may sit above the first visible row, so no cross-row state
142
+ // can tell the highlighter the first row is a comment — it coloured `of`, `switch`, `from` in a JSDoc paragraph
143
+ // as keywords. A row that is plainly part of a block comment (` * …`, an opening `/**`, or the closing `*/`) is
144
+ // painted as a comment on its own merits; the opener also seeds the rows that follow.
145
+ const content = expandTabs(numbered[2]);
146
+ const isBlockCommentRow = /^\s*(?:\/\*|\*|\*\/|\*\*)/.test(content);
147
+ const painted = paintCode(content, readLang, '', inComment || isBlockCommentRow);
148
+ if (/\/\*/.test(content) && !/\*\//.test(content)) inComment = true;
149
+ else if (/\*\//.test(content)) inComment = false;
150
+ // The separator is a SPACE: the number is padded to the block's widest, so every row's code starts in the same
151
+ // column.
152
+ const text = `${col(numbered[1].padStart(numW), C.white)} ${painted.text}`;
153
+ // A Read row is TRUNCATED, not wrapped. Wrapping folded an overlong line onto a second row without a line
154
+ // number, and that second row was exactly what a differential painter could not reconcile with the previous
155
+ // frame: the leftover glyphs stayed under it as residue. One source line is one display row.
156
+ //
157
+ // The background has to survive the row's own resets: every syntax token closes with `ESC[0m`, and the padding
158
+ // `fitAnsi` adds sits AFTER the last one. Re-asserting after each reset — the same trick `paintCode` uses for a
159
+ // diff wash — keeps the surface on the padding too, so the block reads solid.
160
+ const surfaced = text.replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
161
+ diffRows.push({ text: C.codeBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 ? pre : cont, raw: true });
162
+ return;
163
+ }
164
+ const wrapped = ln === '' ? [''] : wrapWords(ln, bodyW);
165
+ // BASH OUTPUT SITS ON THE TERMINAL SURFACE, like text inside a real terminal emulator: the darkest recess on
166
+ // screen. Other tools keep the plain page background, so a command's output reads as "a terminal ran this" rather
167
+ // than as an ordinary result.
168
+ const termSurface = msg.toolName === 'Bash' || msg.toolName === 'Shell';
169
+ wrapped.forEach((t, i) => {
170
+ if (termSurface) {
171
+ const surfaced = t.replace(/\x1b\[0m/g, `\x1b[0m${C.termBg}`);
172
+ diffRows.push({ text: C.termBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 && i === 0 ? pre : cont, raw: true });
173
+ } else {
174
+ diffRows.push({ text: t, ind: idx === 0 && i === 0 ? pre : cont, color });
175
+ }
176
+ });
177
+ });
178
+ if (visible.length > MAX_RESULT_LINES) {
179
+ // The hint says HOW to see the rest: "… N more lines" alone gave the user no way to know Ctrl+O would reveal it.
180
+ // Only reachable while COLLAPSED: expanded, `MAX_RESULT_LINES` is Infinity.
181
+ diffRows.push({
182
+ text: `… ${visible.length - MAX_RESULT_LINES} more lines, ctrl+o to expand`,
183
+ ind: cont,
184
+ color: failed ? C.red : C.gray,
185
+ });
186
+ }
187
+ }
188
+
189
+ const out = [];
190
+ for (const r of diffRows) out.push(r);
191
+ for (const r of receiptRows) out.push(r);
192
+ // Put the `↳` on the FIRST rendered row (diff or output) — never on the receipt, which sits last.
193
+ if (out.length && out[0].ind === cont && Array.isArray(msg.diff) && msg.diff.length > 0) {
194
+ out[0] = { ...out[0], ind: pre };
195
+ }
196
+ // The TOOL ROW may already have drawn this result's body — a Write streams the file's content up there — in which
197
+ // case the receipt below is the whole result and must NOT open a second `↳` block:
198
+ // ● Used Write (a.txt) 1.3KB
199
+ // ↳ 1 <content> <- the body, marked on the tool row
200
+ // ↳ File written: a.txt (1372 bytes) <- the stray second `↳`, now plain
201
+ // One body, one marker. `bodyOnToolRow` is set by the tool_result handler, the only place that knows whether the tool
202
+ // row had content to show.
203
+ if (msg.bodyOnToolRow && out.length && out[0].ind === pre) {
204
+ out[0] = { ...out[0], ind: cont };
205
+ }
206
+ // Nothing to show (empty output) -> render no row at all rather than a dangling "↳ ".
207
+ return out;
208
+ }