@notrico/pi-fold 0.0.0-stage → 3.0.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +71 -2
  4. package/docs/implementation.md +47 -0
  5. package/docs/performance.md +118 -0
  6. package/docs/renderer-reference.md +110 -0
  7. package/index.ts +53 -0
  8. package/package.json +55 -4
  9. package/scripts/performance-review.mjs +273 -0
  10. package/scripts/preview-inspection.mjs +9 -0
  11. package/scripts/preview-work-strip.mjs +101 -0
  12. package/scripts/preview.mjs +232 -0
  13. package/scripts/retained-memory-review.mjs +46 -0
  14. package/scripts/test.mjs +21 -0
  15. package/src/action-intent.ts +93 -0
  16. package/src/display-card.ts +66 -0
  17. package/src/display-line-cache.ts +26 -0
  18. package/src/display-mode.ts +33 -0
  19. package/src/fold-command.ts +61 -0
  20. package/src/inspection.ts +87 -0
  21. package/src/modern-code-content.ts +131 -0
  22. package/src/modern-code-pane.ts +103 -0
  23. package/src/modern-native-tools.ts +79 -0
  24. package/src/modern-prompts-adapter.ts +41 -0
  25. package/src/modern-prompts.ts +185 -0
  26. package/src/modern-recorded-pane.ts +68 -0
  27. package/src/modern-rich-text.ts +48 -0
  28. package/src/modern-skill-prompts.ts +152 -0
  29. package/src/modern-subagent-groups.ts +158 -0
  30. package/src/modern-subagent-messages.ts +176 -0
  31. package/src/modern-subagent-spacing.ts +35 -0
  32. package/src/modern-subagents.ts +52 -0
  33. package/src/modern-thinking-adapter.ts +85 -0
  34. package/src/modern-thinking.ts +258 -0
  35. package/src/modern-tool-content.ts +28 -0
  36. package/src/modern-tool-images.ts +63 -0
  37. package/src/modern-tool-pane.ts +219 -0
  38. package/src/modern-tools.ts +509 -0
  39. package/src/modern-workflows.ts +212 -0
  40. package/src/native-method-chain.ts +31 -0
  41. package/src/permission-presentation.ts +280 -0
  42. package/src/recorded-summary.ts +13 -0
  43. package/src/work-strip-subagents.ts +221 -0
  44. package/src/work-strip-view.ts +112 -0
  45. package/src/work-strip.ts +443 -0
  46. package/tests/action-intent.test.mjs +44 -0
  47. package/tests/codemode.test.mjs +388 -0
  48. package/tests/display-cache-lifecycle.test.mjs +55 -0
  49. package/tests/display-line-cache.test.mjs +48 -0
  50. package/tests/display-mode.test.mjs +25 -0
  51. package/tests/fixtures/preview-fixture.ts +81 -0
  52. package/tests/fold-command.test.mjs +150 -0
  53. package/tests/fold-shortcut.test.mjs +143 -0
  54. package/tests/input-focus.test.mjs +95 -0
  55. package/tests/inspection-wheel.test.mjs +73 -0
  56. package/tests/inspection.test.mjs +50 -0
  57. package/tests/mixed-thinking.test.mjs +371 -0
  58. package/tests/modern-prompts.test.mjs +84 -0
  59. package/tests/modern-skill-prompts.test.mjs +174 -0
  60. package/tests/modern-subagent-groups.test.mjs +132 -0
  61. package/tests/modern-subagent-messages.test.mjs +137 -0
  62. package/tests/modern-thinking.test.mjs +202 -0
  63. package/tests/modern-tools.test.mjs +961 -0
  64. package/tests/modern-workflows.test.mjs +189 -0
  65. package/tests/ordinary-prompts.test.mjs +167 -0
  66. package/tests/permission-presentation.test.mjs +257 -0
  67. package/tests/preview-example.test.mjs +171 -0
  68. package/tests/reload-lifecycle.test.mjs +161 -0
  69. package/tests/subagent-spacing.test.mjs +34 -0
  70. package/tests/test-runtime.mjs +58 -0
  71. package/tests/work-strip-final-surface.test.mjs +321 -0
  72. package/tests/work-strip-hierarchy.test.mjs +258 -0
  73. package/tests/work-strip-preview.test.mjs +120 -0
  74. package/tests/work-strip-spacing.test.mjs +208 -0
  75. package/tests/work-strip-subagents.test.mjs +236 -0
  76. package/tests/work-strip.test.mjs +148 -0
@@ -0,0 +1,961 @@
1
+ import assert from 'node:assert/strict';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { existsSync, writeFileSync } from 'node:fs';
5
+ import { loadSource, loadAgent, tui, themeModule, stripAnsi, core, runtime, assertCardBackground, backgroundCells } from './test-runtime.mjs';
6
+ const { cardRow, activityHeading } = await loadSource('./display-card.ts');
7
+ const headingTheme = { fg: (tone, text) => `<${tone}>${text}</${tone}>`, bold: text => `<bold>${text}</bold>` };
8
+ assert.equal(activityHeading('▸ 4 actions · Read files · 2s', headingTheme), '<mdLink>▸ 4 actions</mdLink><muted> · Read files · 2s</muted>');
9
+ assert.equal(activityHeading('▸ read', headingTheme), '<mdLink>▸ read</mdLink>');
10
+ for (const tone of ['accent', 'customMessageLabel', 'error', 'warning']) assert.equal(activityHeading('▸ Decision · recorded', headingTheme, tone), `<${tone}><bold>▸ Decision · recorded</bold></${tone}>`);
11
+ for (const width of [1, 2, 8, 30]) assertCardBackground([cardRow('a\x1b[0mb\x1b[49mc\x1b[38;2;0;49;0md', width, themeModule.theme, 'toolSuccessBg')], width, 'toolSuccessBg');
12
+ const nested = cardRow('a\x1b[48;5;0mb\x1b[49mc', 12, themeModule.theme, 'toolSuccessBg');
13
+ assert.equal(backgroundCells(nested)[2], '48;5;0', 'an explicit nested surface stays intact');
14
+ assert.equal(backgroundCells(nested)[3], backgroundCells(nested)[0], 'base surface resumes after a nested background reset');
15
+ const { registerModernTools, toolStatus, toolLabel, isNativeSubagent } = await loadSource('./modern-tools.ts');
16
+ const { ToolPane, textRows } = await loadSource('./modern-tool-pane.ts');
17
+ const { recordedValues } = await loadSource('./modern-tool-content.ts');
18
+ const { ToolExecutionComponent } = await loadAgent('modes/interactive/components/tool-execution.js');
19
+ const { createShellRenderers } = await loadAgent('core/tools/renderers/bash.js');
20
+ const { readRenderers } = await loadAgent('core/tools/renderers/read.js');
21
+ const { codemodeRenderers } = await loadAgent('extensions/codemode/renderer.js');
22
+ const hooks = new Map();
23
+ const bus = new Map();
24
+ let resolver, input, enabled = true, modeChange, redraws = 0;
25
+ const pi = {
26
+ registerToolRenderer(fn) { resolver = fn; },
27
+ on(name, fn) { const list = hooks.get(name) || []; list.push(fn); hooks.set(name, list); return () => hooks.set(name, (hooks.get(name) || []).filter(item => item !== fn)); },
28
+ events: { on(name, fn) { bus.set(name, fn); return () => bus.delete(name); }, emit(name, value) { bus.get(name)?.(value); } },
29
+ };
30
+ const mode = { isEnabled: () => enabled, onChange(fn) { modeChange = fn; return () => { modeChange = undefined; }; } };
31
+ const dispose = registerModernTools(pi, mode);
32
+ const ctx = { hasUI: true, sessionManager: { getBranch: () => [] }, ui: { onTerminalInput(fn) { input = fn; return () => { input = undefined; }; } } };
33
+ const event = (name, value = {}) => { for (const fn of [...(hooks.get(name) || [])]) fn(value, ctx); };
34
+ const toggle = (value) => { enabled = value; modeChange(); };
35
+ event('session_start');
36
+ const native = new Map([['bash', createShellRenderers('$')], ['read', readRenderers], ['codemode', codemodeRenderers]]);
37
+ const stockCalls = [];
38
+ const make = (name, id, args) => {
39
+ const original = native.get(name) || { renderCall: () => new tui.Text('native call', 0, 0), renderResult: () => new tui.Text('native result', 0, 0) };
40
+ const renderer = resolver(name, () => original);
41
+ const wrapped = { ...renderer,
42
+ renderCall(...args) { const result = renderer.renderCall(...args); stockCalls.push(result); return result; },
43
+ renderResult(...args) { return renderer.renderResult(...args); },
44
+ };
45
+ const component = new ToolExecutionComponent(name, id, args, { showImages: false, outputPad: 0 }, wrapped, { requestRender() { redraws++; assert.ok(redraws < 1000, 'bounded native redraw'); } }, '/tmp');
46
+ component.setArgsComplete();
47
+ return component;
48
+ };
49
+ const paint = (component, width = 120) => stripAnsi(component.render(width).join('\n'));
50
+ const result = (text, details = {}) => ({ content: [{ type: 'text', text }], details });
51
+ const evidence = [];
52
+ const capture = (label, component) => { const lines = component.render(120); evidence.push({ label, width: 120, lines, plain: lines.map(stripAnsi) }); };
53
+ const read = make('read', 'a', { path: '/tmp/first.txt' });
54
+ read.markExecutionStarted(); read.updateResult(result('first output'));
55
+ capture('Single successful action collapsed', read);
56
+ assert.match(read.render(120).map(stripAnsi)[1], /^ ▸ read · /, 'tool name starts after the common disclosure column');
57
+ const clickSingle = (component, y) => {
58
+ const lines = component.render(120);
59
+ return component.handleMouse({ type: 'click', button: 'left', x: 2, y, screenX: 2, screenY: y, width: 120, height: lines.length, shift: false, alt: false, ctrl: false });
60
+ };
61
+ clickSingle(read, 1);
62
+ assert.match(paint(read), /first output/, 'one header click reveals singleton details');
63
+ assert.doesNotMatch(paint(read), /1\. read|Arguments|\{\}/, 'singleton shows content before exact arguments');
64
+ assert.match(paint(read), /▸ Details/);
65
+ clickSingle(read, 3); assert.match(paint(read), /Arguments/);
66
+ clickSingle(read, 3);
67
+ capture('Single successful action opened by header click', read);
68
+ clickSingle(read, 1);
69
+ assert.doesNotMatch(paint(read), /first output/);
70
+ read.setExpanded(true);
71
+ assert.match(paint(read), /first output/, 'native expansion opens singleton details directly');
72
+ read.setExpanded(false);
73
+ const inspectRead = [];
74
+ pi.events.emit('compact-renderer:inspect:v1', { add: entry => inspectRead.push(entry) });
75
+ inspectRead[0].focus();
76
+ assert.match(paint(read), /first output/, 'inspection focus opens singleton details directly');
77
+ assertCardBackground([read.render(100)[1]], 100, 'selectedBg');
78
+ assert.match(paint(read), /Enter collapse/);
79
+ capture('Single successful action focused through inspection', read);
80
+ input('\r'); assert.doesNotMatch(paint(read), /first output/, 'Enter collapses a focused singleton');
81
+ input('\r'); assert.match(paint(read), /first output/, 'Enter opens a focused singleton in one step');
82
+ input('\x1b'); clickSingle(read, 1);
83
+ const shell = make('bash', 'b', { command: 'printf hello' }); shell.markExecutionStarted(); shell.updateResult(result('streaming'), true);
84
+ assert.match(paint(read), /read · \/tmp\/first\.txt/);
85
+ assert.match(paint(shell), /Running/);
86
+ assert.equal(read.render(100).length, 2, 'collapsed activity uses one summary plus native spacer');
87
+ const assertNeutral = rows => { for (const row of rows) assert.ok(backgroundCells(row).every(value => value === ''), 'compact activity keeps terminal surface'); };
88
+ assertNeutral(read.render(100));
89
+ assertNeutral(shell.render(100));
90
+ assert.ok(shell.render(100)[1].includes(themeModule.theme.getFgAnsi('mdLink')), 'ordinary running action heading uses native blue');
91
+ assert.ok(shell.render(100)[1].includes(themeModule.theme.getFgAnsi('muted')), 'running intent and metadata use muted text');
92
+ assert.doesNotMatch(paint(read), /Alt\+G/, 'unfocused collapsed cards omit repeated key hints');
93
+ shell.updateResult(result('hello', { exitCode: 0 }));
94
+ assert.match(paint(read), /2 actions/);
95
+ assert.ok(read.render(100)[1].includes(themeModule.theme.getFgAnsi('mdLink')), 'completed action group heading uses native blue');
96
+ assert.ok(read.render(100)[1].includes(themeModule.theme.getFgAnsi('muted')), 'group intent uses muted text');
97
+ assert.equal(paint(shell), '');
98
+ assert.equal(input('\x1b[A'), undefined, 'editor arrows remain untouched until pane focus');
99
+ assert.equal(input('\x1bg').consume, true);
100
+ assert.match(paint(read), /first.txt/);
101
+ const focusedAction = read.render(100).find(row => stripAnsi(row).includes('1. read'));
102
+ assertCardBackground([focusedAction], 100, 'selectedBg');
103
+ assert.ok(focusedAction.includes(themeModule.theme.getFgAnsi('accent')), 'selection has a clear native foreground');
104
+ input('\r');
105
+ assert.doesNotMatch(paint(read), /Arguments/);
106
+ input('\t'); input('\r'); input('\t');
107
+ assert.match(paint(read), /Arguments/);
108
+ assert.match(paint(read), /first output/);
109
+ assert.doesNotMatch(paint(read), /arguments \(object\)|arguments\.path|\(string\)/, 'recorded values use local field labels');
110
+ const detailLayout = read.render(100).map(stripAnsi);
111
+ assert.match(detailLayout[1], /^ ▾ /, 'header uses the native one-cell gutter');
112
+ assert.match(detailLayout.find(row => row.includes('1. read')), /^ › ▾ /, 'actions sit inside the group heading');
113
+ assert.equal(detailLayout.find(row => row.includes('first output')).indexOf('first output'), detailLayout.find(row => row.includes('1. read')).indexOf('read'), 'recorded output aligns with the expanded action label');
114
+ assert.match(detailLayout.at(-1), /^ ←\/→ action/, 'focused hint shares the header gutter');
115
+ assertCardBackground([read.render(100)[1]], 100, 'selectedBg');
116
+ assert.ok(detailLayout.findIndex(row => row.includes('first output')) < detailLayout.findIndex(row => row.trim() === 'Arguments'), 'output appears before arguments');
117
+ assert.doesNotMatch(detailLayout.join('\n'), /c collapse/);
118
+ input('\x1b[C'); input('\r');
119
+ input('\t'); input('\r'); input('\t');
120
+ assert.match(paint(read), /printf hello/);
121
+ assert.match(paint(read), /hello/);
122
+ input('\x1b[D');
123
+ assert.match(paint(read), /first output/, 'first action remains expanded');
124
+ input('\x1b'); assert.equal(input('\x1b[B'), undefined);
125
+ assertNeutral(read.render(100));
126
+ assert.doesNotMatch(paint(read), /Enter details|Alt\+G|to inspect/, 'unfocused open cards omit keyboard hints');
127
+ // Mode changes synchronously rerender the actual native component and preserve slot ownership.
128
+ for (let iteration = 0; iteration < 8; iteration++) {
129
+ toggle(false);
130
+ assert.match(paint(shell), /\$ printf hello/);
131
+ assert.match(paint(shell), /hello/);
132
+ read.setExpanded(true);
133
+ assert.match(paint(read), /first output/);
134
+ assert.equal(read.callRendererComponent.constructor.name, 'Box');
135
+ assert.deepEqual(read.callRendererComponent.children.map(child => child.constructor.name), ['Text', 'Text']);
136
+ assert.deepEqual(shell.callRendererComponent.children.map(child => child.constructor.name), ['Text', 'Container']);
137
+ assert.equal(shell.resultRendererComponent.render(120).length, 0, 'one Box owns both stock render slots');
138
+ toggle(true);
139
+ assert.match(paint(read), /2 actions/);
140
+ }
141
+ // Mode off reproduces the full default native shell, including ANSI backgrounds and padding.
142
+ toggle(false);
143
+ const actualNow = Date.now; Date.now = () => 100000;
144
+ try {
145
+ for (const outputPad of [0, 1, 3]) for (const name of ['bash', 'read', 'native-generic', 'subagent', 'subagent_supervisor', 'contact_supervisor']) {
146
+ const args = name === 'bash' ? { command: 'printf safe' } : { path: '/tmp/shell-fixture' };
147
+ const originalDefinition = native.get(name) || {};
148
+ const wrappedDefinition = resolver(name, () => originalDefinition);
149
+ const create = (definition, id) => new ToolExecutionComponent(name, id, args, { showImages: false, outputPad }, definition, { requestRender() {} }, '/tmp');
150
+ const original = create(originalDefinition, `appearance-original-${name}-${outputPad}`);
151
+ const wrapped = create(wrappedDefinition, `appearance-wrapped-${name}-${outputPad}`);
152
+ try {
153
+ original.markExecutionStarted(); wrapped.markExecutionStarted();
154
+ for (const phase of ['running', 'completed', 'error']) {
155
+ const final = { ...result(`native ${phase} output`), isError: phase === 'error', durationMs: phase === 'running' ? undefined : 500 };
156
+ original.updateResult(final, phase === 'running'); wrapped.updateResult(final, phase === 'running');
157
+ for (const expanded of [false, true]) {
158
+ original.setExpanded(expanded); wrapped.setExpanded(expanded);
159
+ for (const width of [20, 90]) assert.deepEqual(wrapped.render(width), original.render(width), `${name}/${phase}/pad=${outputPad}/expanded=${expanded}/width=${width}`);
160
+ const background = phase === 'running' ? 'toolPendingBg' : phase === 'error' ? 'toolErrorBg' : 'toolSuccessBg';
161
+ assert.ok(wrapped.render(90).some(line => line.includes(themeModule.theme.getBgAnsi(background))), 'effective native background ANSI is retained');
162
+ }
163
+ }
164
+ } finally { original.updateResult(result('final cleanup')); wrapped.updateResult(result('final cleanup')); }
165
+ }
166
+ // Tools that frame themselves keep their existing renderShell semantics.
167
+ const selfStock = { renderShell: 'self', renderCall: () => new tui.Text('own call', 0, 0), renderResult: () => new tui.Text('own result', 0, 0) };
168
+ const selfOriginal = new ToolExecutionComponent('self-tool', 'self-original', {}, { outputPad: 3, showImages: false }, selfStock, { requestRender() {} }, '/tmp');
169
+ const selfWrapped = new ToolExecutionComponent('self-tool', 'self-wrapped', {}, { outputPad: 3, showImages: false }, resolver('self-tool', () => selfStock), { requestRender() {} }, '/tmp');
170
+ selfOriginal.updateResult(result('own')); selfWrapped.updateResult(result('own'));
171
+ assert.deepEqual(selfWrapped.render(80), selfOriginal.render(80));
172
+ } finally { Date.now = actualNow; toggle(true); }
173
+ // A failed row remains conspicuous and breaks adjacent success groups.
174
+ const fail = make('bash', 'c', { command: 'false' });
175
+ fail.updateResult({ ...result('failure', { exitCode: 1 }), isError: true });
176
+ const after = make('read', 'd', { path: '/tmp/after.txt' }); after.updateResult(result('after'));
177
+ assert.match(paint(fail), /bash · false · ✗ Failed/); assert.match(paint(after), /read · \/tmp\/after\.txt/);
178
+ assert.equal(paint(fail).split('\n').filter(line => line.includes('bash · false')).length, 1, 'failure uses one exceptional header');
179
+ assert.match(paint(fail), /Failed · Command failed \(exit 1\)/, 'header includes a bounded recorded failure excerpt');
180
+ assert.match(fail.render(120).map(stripAnsi)[1], /^ ▸ bash · /, 'failure status does not shift the tool name');
181
+ capture('Single failed action collapsed with status after command', fail);
182
+ const failedHeader = fail.render(120).find(line => stripAnsi(line).includes('Failed'));
183
+ assert.ok(failedHeader.includes(themeModule.theme.getFgAnsi('error')), 'failed header uses native error color');
184
+ assertNeutral([failedHeader]);
185
+ const partialFailureOutput = 'partial failure output\nexact second failure line';
186
+ fail.updateResult({ ...result(partialFailureOutput, { error: 'Recorded denial: ' + 'x'.repeat(5000) }), isError: true }, true);
187
+ assert.match(paint(fail), /Failed · Command failed/, 'partial errors remain visible as exceptional cards');
188
+ assert.equal(paint(fail).split('\n').filter(line => line.includes('bash · false')).length, 1);
189
+ assert.ok(paint(fail, 500).split('\n').map(row => row.trim()).join('').length < 400, 'collapsed failure reason has a bounded length before the full-width card gutter');
190
+ const failureMouse = (y) => fail.handleMouse({ type: 'click', button: 'left', x: 2, y, screenX: 2, screenY: y, width: 120, height: fail.render(120).length, shift: false, alt: false, ctrl: false });
191
+ failureMouse(1); failureMouse(2);
192
+ assert.match(paint(fail), /partial failure output/);
193
+ assert.match(paint(fail), /exact second failure line/, 'full recorded failure output remains inline');
194
+ assert.doesNotMatch(paint(fail), /1\. bash/, 'failed action opens without a numbered duplicate');
195
+ capture('Single failed action opened directly', fail);
196
+ input('\x1b');
197
+ assert.equal(toolStatus('read', result('Error is a word in successful recorded output')).status, 'success', 'prose never determines failure status');
198
+ // Visible transcript boundaries and native Fleet control presentation.
199
+ event('message_end', { message: { role: 'user', content: 'next task' } });
200
+ const next = make('read', 'e', { path: '/tmp/next.txt' }); next.updateResult(result('next'));
201
+ assert.match(paint(next), /read · \/tmp\/next\.txt/);
202
+ for (const name of ['fleet_status', 'mcp__fleet_status']) {
203
+ assert.equal(isNativeSubagent(name), true);
204
+ const stock = {}; assert.equal(resolver(name, () => stock), stock);
205
+ }
206
+ for (const name of ['subagent', 'subagent_message', 'subagents', 'subagent_supervisor']) {
207
+ assert.equal(isNativeSubagent(name), true);
208
+ const stock = {}; assert.notEqual(resolver(name, () => stock), stock, 'subagent TOOL transcripts use compact rows');
209
+ }
210
+ assert.equal(toolStatus('bash', result('error'), true, true).status, 'failed', 'partial errors remain failed');
211
+ for (const status of ['started', 'running', 'unavailable', 'cancelled']) assert.notEqual(toolStatus('custom', result('notice', { status })).status, 'success');
212
+ for (const status of ['cancelled', 'unavailable']) assert.equal(toolStatus('ask_user_question', result('', { status })).status, status);
213
+ assert.equal(toolStatus('ask_user_question', result('', { status: 'answered', answers: [] })).status, 'unanswered');
214
+ const ask = make('ask_user_question', 'q', { question: 'Which host?' });
215
+ assert.match(paint(ask), /Question · Pending · Which host/);
216
+ assert.match(ask.render(120).map(stripAnsi)[1], /^ ▸ Question · /, 'question heading aligns with ordinary action headings');
217
+ const assertDecision = (component, width = 100, focused = false) => {
218
+ const rows = component.render(width).slice(1);
219
+ if (focused) assertCardBackground([rows[0]], width, 'selectedBg');
220
+ else assertNeutral([rows[0]]);
221
+ assert.ok(rows[0].includes(themeModule.theme.getFgAnsi('accent')), 'question heading uses the native purple accent');
222
+ for (const row of rows) assert.doesNotMatch(stripAnsi(row), /^│/, 'question has no decorative rail');
223
+ assertNeutral(rows.slice(1));
224
+ };
225
+ assertDecision(ask);
226
+ assert.ok(ask.render(100)[1].includes(themeModule.theme.getFgAnsi('accent')), 'question heading uses purple accent');
227
+ assert.notEqual(themeModule.theme.getFgAnsi('accent'), themeModule.theme.getFgAnsi('mdLink'), 'questions and actions have distinct native tones');
228
+ capture('Question pending with aligned purple heading', ask);
229
+ ask.updateResult(result('User answered: Laptop', { question: 'Which host?', status: 'answered', answers: [{ label: 'Laptop', value: 'local' }] }));
230
+ assert.match(paint(ask), /Question · Answered · Which host\? · Laptop/);
231
+ assertDecision(ask);
232
+ assert.equal((paint(ask).match(/Question ·/g) || []).length, 1);
233
+ ask.setExpanded(true);
234
+ assert.match(paint(ask), /✓ Laptop/);
235
+ assert.equal((paint(ask).match(/Which host\?/g) || []).length, 1, 'expanded question shows its prompt once');
236
+ assert.equal((paint(ask).match(/Laptop/g) || []).length, 1, 'expanded question shows its answer once');
237
+ assert.doesNotMatch(paint(ask), /^ +(?:Question|Options|Answer)\s*$/m);
238
+ assert.doesNotMatch(paint(ask), /1\. ask_user_question/);
239
+ capture('Answered question opened directly with readable answer', ask);
240
+ ask.setExpanded(false);
241
+ for (const [status, expected, isError] of [['unavailable', 'Unavailable', false], ['cancelled', 'Cancelled', false], ['answered', 'Unanswered', false], ['failed', 'Failed', true]]) {
242
+ ask.updateResult({ ...result('No recorded answer', { question: 'Which host?', status, answers: [] }), isError });
243
+ assert.match(paint(ask), new RegExp(`Question · ${expected}`));
244
+ assert.doesNotMatch(paint(ask), /Laptop/, 'prior answers cannot leak into a later unresolved interaction');
245
+ ask.setExpanded(true);
246
+ assert.equal((paint(ask).match(new RegExp(expected, 'g')) || []).length, 1, 'unresolved state appears in the header once');
247
+ assert.doesNotMatch(paint(ask), /✓|^ +Answer\s*$/m, 'unresolved states cannot imply a recorded answer');
248
+ assert.doesNotMatch(paint(ask), /Laptop|Arguments|Details|Output/);
249
+ assert.match(paint(ask), /No recorded answer/, 'unresolved question retains its readable recorded message');
250
+ ask.setExpanded(false);
251
+ }
252
+ ask.updateResult(result('unnecessary raw output', { status: 'unavailable', question: 'Which host?', message: 'Question UI is unavailable in this session.' }));
253
+ ask.setExpanded(true);
254
+ assert.match(paint(ask), /Question UI is unavailable in this session/);
255
+ assert.doesNotMatch(paint(ask), /unnecessary raw output|Arguments|Details|Output/);
256
+ ask.setExpanded(false);
257
+ const detailedArgs = { question: 'Choose a host?', details: 'Use the machine that owns the checkout.', options: [
258
+ { label: 'Laptop (Recommended)', value: 'local', description: 'Use the local checkout.' },
259
+ { label: 'Server', value: 'remote' },
260
+ ] };
261
+ const detailedResult = result('User selected: 1. Laptop (Recommended)', { status: 'answered', question: detailedArgs.question, context: detailedArgs.details, mode: 'single-select', answers: [{ type: 'option', index: 1, label: 'Laptop (Recommended)', value: 'local' }] });
262
+ const detailedSource = JSON.stringify({ args: detailedArgs, result: detailedResult });
263
+ const detailedAsk = make('ask_user_question', 'q-details', detailedArgs);
264
+ detailedAsk.updateResult(detailedResult); detailedAsk.setExpanded(true);
265
+ assert.match(paint(detailedAsk), /\n +Choose a host\?/);
266
+ assert.match(paint(detailedAsk), /✓ 1\. Laptop \(Recommended\) — Use the local checkout\./);
267
+ assert.match(paint(detailedAsk), /\n +2\. Server/);
268
+ assert.doesNotMatch(paint(detailedAsk), /^ +(?:Question|Options|Answer)\s*$/m);
269
+ assert.ok(detailedAsk.render(120).map(stripAnsi).slice(2).every(row => row.trim()), 'compact question body adds no blank section gaps');
270
+ assert.doesNotMatch(paint(detailedAsk), /1\. ask_user_question/);
271
+ capture('Detailed question with recorded options and descriptions', detailedAsk);
272
+ assert.equal((paint(detailedAsk).match(/✓ 1\. Laptop/g) || []).length, 1, 'selected option is the answer, without a duplicate answer section');
273
+ assertDecision(detailedAsk);
274
+ const questionChoices = []; pi.events.emit('compact-renderer:inspect:v1', { add: entry => questionChoices.push(entry) });
275
+ questionChoices.find(entry => entry.label.includes('Choose a host?')).focus();
276
+ assertDecision(detailedAsk, 100, true);
277
+ assert.match(paint(detailedAsk), /focused/);
278
+ input('\x1b');
279
+ assertDecision(detailedAsk);
280
+ const selectedQuestionRow = detailedAsk.render(120).find(row => stripAnsi(row).includes('✓ 1.'));
281
+ assert.ok(selectedQuestionRow.includes(themeModule.theme.getFgAnsi('success')), 'recorded selection uses native success color');
282
+ assertNeutral([selectedQuestionRow]);
283
+ // Native theme.bold can omit ANSI in a non-TTY test process. Verify the style seam explicitly.
284
+ const answerStylePane = new ToolPane([{ id: 'answer-style', label: '', sections: function* () { yield { text: '✓ 2. Beta', kind: 'answer' }; } }], 'Question');
285
+ answerStylePane.open = true;
286
+ answerStylePane.theme = Object.assign(Object.create(themeModule.theme), { bold: text => `\x1b[1m${text}\x1b[22m` });
287
+ assert.ok(answerStylePane.render(80).find(row => stripAnsi(row).includes('✓ 2. Beta')).includes('\x1b[1m'), 'answer rows request bold styling independently of keyboard focus');
288
+ capture('Detailed question with selected option inline', detailedAsk);
289
+ assert.doesNotMatch(paint(detailedAsk), /Arguments|Details|Output|mode:|value:/, 'question history omits raw duplicate records');
290
+ assert.equal(JSON.stringify({ args: detailedArgs, result: detailedResult }), detailedSource, 'question presentation preserves all stored source');
291
+ const choiceArgs = { question: 'Which option?', details: ' ', options: [
292
+ { label: 'Alpha', value: 'a', description: 'First choice' },
293
+ { label: 'Beta', value: 'b', description: 'Second choice' },
294
+ { label: 'Other', value: 'other' },
295
+ ] };
296
+ const choiceAsk = make('ask_user_question', 'q-choice', choiceArgs);
297
+ const updateChoice = (answers, status = 'answered', message) => {
298
+ choiceAsk.updateResult(result(message ?? 'User selected a recorded answer', { status, question: choiceArgs.question, answers, ...(message === undefined ? {} : { message }) }));
299
+ choiceAsk.setExpanded(true);
300
+ return paint(choiceAsk);
301
+ };
302
+ assert.match(updateChoice([{ type: 'option', index: 2, label: 'Beta', value: 'b' }]), /✓ 2\. Beta — Second choice/);
303
+ assert.doesNotMatch(paint(choiceAsk), /✓ 1\.|✓ 3\.|User selected/);
304
+ assert.match(updateChoice([{ type: 'other', label: 'Gamma', value: 'Gamma' }]), /✓ Other: Gamma/);
305
+ assert.doesNotMatch(paint(choiceAsk), /✓ \d\./);
306
+ assert.match(updateChoice([{ type: 'other', label: 'Other', value: 'other' }]), /✓ Other: Other/);
307
+ assert.doesNotMatch(paint(choiceAsk), /✓ 3\./, 'custom Other never selects a regular option with that label or value');
308
+ assert.match(updateChoice([{ type: 'option', index: 7, label: 'Historical choice', value: 'a' }]), /✓ 7\. Historical choice/);
309
+ assert.doesNotMatch(paint(choiceAsk), /✓ 1\./, 'unmatched recorded indices remain standalone instead of selecting a conflicting value');
310
+ for (const status of ['cancelled', 'unavailable']) {
311
+ const output = updateChoice([{ type: 'option', index: 2, label: 'Beta', value: 'b' }], status, status === 'cancelled' ? 'User cancelled the question' : 'Question UI unavailable: no terminal');
312
+ assert.doesNotMatch(output, /✓/, 'only answered status can highlight recorded options');
313
+ assert.equal((output.match(new RegExp(status === 'cancelled' ? 'Cancelled' : 'Unavailable', 'g')) || []).length, 1);
314
+ if (status === 'cancelled') assert.doesNotMatch(output, /User cancelled the question/);
315
+ else assert.match(output, /Question UI unavailable: no terminal/);
316
+ }
317
+ assert.match(updateChoice([], 'cancelled', 'User cancelled the question\nConnection closed during selection'), /Connection closed during selection/, 'nonstandard cancellation diagnostics remain intact');
318
+ choiceAsk.updateResult(result('Connection closed during selection', { status: 'cancelled', message: 'User cancelled the question', answers: [] }));
319
+ assert.match(paint(choiceAsk), /Connection closed during selection/, 'suppressing exact boilerplate still retains a separate recorded diagnostic');
320
+ const duplicateAsk = make('ask_user_question', 'q-duplicates', { question: 'Choose repeated labels', options: [
321
+ { label: 'Same', value: 'first' }, { label: 'Same', value: 'second' }, { label: 'Final', value: 'last' },
322
+ ] });
323
+ duplicateAsk.updateResult(result('', { status: 'answered', answers: [{ type: 'option', index: 2, label: 'Same', value: 'second' }, { type: 'option', label: 'Final', value: 'last' }] }));
324
+ duplicateAsk.setExpanded(true);
325
+ assert.match(paint(duplicateAsk), /✓ 2\. Same/);
326
+ assert.match(paint(duplicateAsk), /✓ 3\. Final/);
327
+ assert.doesNotMatch(paint(duplicateAsk), /✓ 1\./, 'multi-select matches recorded indices and values, not all duplicate labels');
328
+ duplicateAsk.updateResult(result('', { status: 'answered', answers: [{ type: 'option', label: 'Same', value: 'second' }] }));
329
+ assert.match(paint(duplicateAsk), /✓ 2\. Same/);
330
+ assert.doesNotMatch(paint(duplicateAsk), /✓ 1\./, 'value disambiguates duplicate labels without an index');
331
+ const normalizedArgs = { question: 'Choose a normalized option', options: [
332
+ { label: ' ' }, { label: ' Same ', value: ' first ' }, { label: '' }, { label: ' Same ', value: ' second ', description: ' Recorded description ' },
333
+ ] };
334
+ const normalizedSource = JSON.stringify(normalizedArgs);
335
+ const normalizedAsk = make('ask_user_question', 'q-normalized', normalizedArgs);
336
+ normalizedAsk.updateResult(result('User selected: 2. Same', { status: 'answered', answers: [{ type: 'option', index: 2, label: 'Same', value: 'second' }] }));
337
+ normalizedAsk.setExpanded(true);
338
+ assert.match(paint(normalizedAsk), /✓ 2\. Same — Recorded description/);
339
+ assert.doesNotMatch(paint(normalizedAsk), /✓ 1\.|3\.|4\./, 'blank options do not occupy native answer indices');
340
+ normalizedAsk.updateResult(result('', { status: 'answered', answers: [{ type: 'option', label: 'Same', value: 'second' }] }));
341
+ assert.match(paint(normalizedAsk), /✓ 2\. Same — Recorded description/);
342
+ assert.doesNotMatch(paint(normalizedAsk), /✓ 1\./, 'normalized values still disambiguate duplicate labels without an index');
343
+ assert.equal(JSON.stringify(normalizedArgs), normalizedSource, 'native option normalization leaves recorded arguments intact');
344
+ const escapedAsk = make('ask_user_question', 'q-controls', { question: 'Recorded\x1b[31m question', options: [{ label: 'Safe\x07', description: 'Literal\u202e detail' }] });
345
+ escapedAsk.updateResult(result('', { status: 'answered', answers: [{ type: 'option', index: 1, label: 'Safe\x07' }] }));
346
+ escapedAsk.setExpanded(true);
347
+ assert.match(paint(escapedAsk), /Recorded\\u001b\[31m question/);
348
+ assert.match(paint(escapedAsk), /✓ 1\. Safe\\u0007 — Literal\\u202e detail/);
349
+ assert.ok(!escapedAsk.render(120).join('\n').includes('\x1b[31m'), 'recorded ANSI cannot inject terminal formatting');
350
+ for (const width of [1, 2, 3, 4, 8, 16, 30]) {
351
+ assert.ok(escapedAsk.render(width).every(row => tui.visibleWidth(row) <= width), `question wraps within ${width} columns`);
352
+ }
353
+ const { activityRow, cardContentWidth } = await loadSource('./display-card.ts');
354
+ for (const appearance of ['dark', 'light']) {
355
+ themeModule.initTheme(appearance, false);
356
+ for (const width of [1, 2, 3, 4, 8, 30]) {
357
+ const line = themeModule.theme.fg('accent', 'Question') + '\x1b[0m' + ' 中文🙂';
358
+ const header = activityRow(line, width, themeModule.theme, false);
359
+ const focusedHeader = activityRow(line, width, themeModule.theme, true);
360
+ assertNeutral([header]);
361
+ if (width >= 2) {
362
+ assert.doesNotMatch(stripAnsi(header), /^│/);
363
+ }
364
+ assertCardBackground([focusedHeader], width, 'selectedBg');
365
+ assert.ok(tui.visibleWidth(header) <= width);
366
+ assert.ok(tui.visibleWidth(activityRow(line, width, themeModule.theme)) <= width);
367
+ assert.ok(cardContentWidth(width) >= 1, 'narrow decisions retain a text cell');
368
+ }
369
+ }
370
+ themeModule.initTheme('dark', false);
371
+ const longFields = { question: 'QUESTION_START ' + 'question '.repeat(180) + 'QUESTION_END', details: 'CONTEXT_START ' + 'context '.repeat(100) + 'CONTEXT_END', options: [{ label: 'LABEL_START ' + 'label '.repeat(100) + 'LABEL_END', description: 'DESCRIPTION_START ' + 'description '.repeat(150) + 'DESCRIPTION_END' }] };
372
+ const longQuestionSource = JSON.stringify(longFields);
373
+ const longAsk = make('ask_user_question', 'q-long', longFields);
374
+ const longOther = 'OTHER_START ' + 'other '.repeat(120) + 'OTHER_END';
375
+ longAsk.updateResult(result('', { status: 'answered', answers: [{ type: 'other', label: longOther, value: longOther }] }));
376
+ longAsk.setExpanded(true);
377
+ let longQuestionPaint = '';
378
+ for (let iteration = 0; iteration < 20; iteration++) {
379
+ const rows = longAsk.render(60);
380
+ longQuestionPaint += rows.map(stripAnsi).join('\n');
381
+ longAsk.handleMouse({ type: 'wheel', button: 'none', wheelDelta: 8, x: 2, y: 3, screenX: 2, screenY: 3, width: 60, height: rows.length, shift: false, alt: false, ctrl: false });
382
+ }
383
+ for (const field of ['QUESTION', 'CONTEXT', 'LABEL', 'DESCRIPTION', 'OTHER']) {
384
+ assert.ok(longQuestionPaint.includes(`${field}_START`) && longQuestionPaint.includes(`${field}_END`), `full ${field.toLowerCase()} remains scroll-accessible`);
385
+ }
386
+ assert.equal(JSON.stringify(longFields), longQuestionSource, 'long question source remains unchanged');
387
+ let laterOptionReads = 0;
388
+ const lazyOptions = [{ label: 'Large recorded option '.repeat(100000) }];
389
+ Object.defineProperty(lazyOptions, 1, { enumerable: true, get() { laterOptionReads++; return { label: 'Later choice' }; } });
390
+ const lazyAsk = make('ask_user_question', 'q-lazy', { question: 'Which recorded option?', options: lazyOptions });
391
+ lazyAsk.updateResult(result('', { status: 'answered', answers: [{ type: 'option', index: 2, label: 'Later choice' }] }));
392
+ lazyAsk.setExpanded(true); lazyAsk.render(40);
393
+ assert.equal(laterOptionReads, 0, 'a long first option does not read later choices while painting one viewport');
394
+ lazyAsk.setExpanded(false);
395
+ const recorded = { role: 'user', content: [{ type: 'text', text: 'unchanged source' }] };
396
+ const sourceBefore = JSON.stringify(recorded); event('message_end', { message: recorded });
397
+ assert.equal(JSON.stringify(recorded), sourceBefore, 'event observation does not mutate model/history messages');
398
+ // Prompt focus and mutual focus return arrows to the editor.
399
+ input('\x1bg'); event('ui_prompt_start'); assert.equal(input('\x1b[A'), undefined);
400
+ input('\x1bg'); pi.events.emit('compact-renderer:focus:v1', { owner: 'thinking' }); assert.equal(input('\x1b[A'), undefined);
401
+ // Mouse coordinates pass through real native self-render shells and MouseRegion routing.
402
+ event('message_end', { message: { role: 'user', content: 'mouse fixture' } });
403
+ const mouseFirst = make('read', 'mouse-first', { path: '/tmp/mouse-first' }); mouseFirst.updateResult(result('mouse first output'));
404
+ const mouseSecond = make('read', 'mouse-second', { path: '/tmp/mouse-second' }); mouseSecond.updateResult(result('mouse second output'));
405
+ const mouseAt = (component, type, y, extra = {}) => {
406
+ const lines = component.render(120);
407
+ return component.handleMouse({ type, button: type === 'wheel' ? 'none' : 'left', x: 2, y, screenX: 2, screenY: y, width: 120, height: lines.length, shift: false, alt: false, ctrl: false, ...extra });
408
+ };
409
+ const rowAt = (component, fragment) => component.render(120).findIndex(line => stripAnsi(line).includes(fragment));
410
+ assert.equal(mouseAt(mouseFirst, 'click', 0), undefined, 'native spacer cannot focus a pane');
411
+ assert.equal(input('\x1b[A'), undefined);
412
+ assert.equal(mouseAt(mouseFirst, 'wheel', 1, { wheelDelta: 3 }), undefined, 'closed pane preserves transcript wheel scrolling');
413
+ assert.equal(mouseAt(mouseFirst, 'click', 1, { x: -1 }).handled, true);
414
+ assert.equal(input('\x1b[A'), undefined, 'outside x suppresses native toggle without focus');
415
+ assert.equal(mouseAt(mouseFirst, 'click', 1).handled, true, 'single summary header opens details');
416
+ assert.doesNotMatch(paint(mouseFirst), /focused/);
417
+ assert.equal(input('\r'), undefined, 'mouse expansion leaves Enter with the editor');
418
+ assert.match(paint(mouseFirst), /1\. read/);
419
+ mouseAt(mouseFirst, 'click', rowAt(mouseFirst, '1. read'));
420
+ assert.match(paint(mouseFirst), /mouse first output/);
421
+ mouseAt(mouseFirst, 'wheel', 3, { wheelDelta: 2 });
422
+ const secondActionRow = rowAt(mouseFirst, '2. read'); assert.ok(secondActionRow > 0);
423
+ mouseAt(mouseFirst, 'click', secondActionRow);
424
+ assert.match(paint(mouseFirst), /mouse first output/, 'clicking second action preserves the earlier inline output');
425
+ mouseAt(mouseFirst, 'wheel', 3, { wheelDelta: 9 });
426
+ assert.match(paint(mouseFirst), /▾ 2\. read/, 'second action expands independently');
427
+ assert.match(paint(mouseFirst), /mouse second output/);
428
+ input('\x1b');
429
+ const outputRow = rowAt(mouseFirst, 'mouse second output');
430
+ mouseAt(mouseFirst, 'click', outputRow);
431
+ assert.equal(input('\x1b[A'), undefined, 'output text click does not take keyboard focus');
432
+ assert.match(paint(mouseFirst), /mouse second output/, 'output click cannot trigger native whole-row collapse');
433
+ mouseAt(mouseFirst, 'wheel', 3, { wheelDelta: -20 });
434
+ assert.match(paint(mouseFirst), /mouse first output/);
435
+ mouseAt(mouseFirst, 'click', 1);
436
+ assert.doesNotMatch(paint(mouseFirst), /1\. read/, 'group header closes the inline pane');
437
+ input('\x1b');
438
+ assert.equal(input('\x1b[A'), undefined);
439
+ assert.equal(mouseAt(mouseFirst, 'click', 10000), undefined);
440
+ redraws = 0; // Bound each additional replay batch independently.
441
+ // Content-first replay: exact native write contract, tight siblings, separate errors.
442
+ event('message_end', { message: { role: 'user', content: 'density fixture' } });
443
+ const densityWriteA = make('write', 'density-write-a', { path: '/fixture/sample-a.txt', content: 'alpha' });
444
+ densityWriteA.updateResult(result('Successfully wrote to /fixture/sample-a.txt'));
445
+ const densityWriteB = make('write', 'density-write-b', { path: '/fixture/sample-b.txt', content: 'beta' });
446
+ densityWriteB.updateResult(result('Successfully wrote to /fixture/sample-b.txt'));
447
+ const densityReadA = make('read', 'density-read-a', { path: '/fixture/sample-a.txt', offset: null, limit: null }); densityReadA.updateResult(result('alpha'));
448
+ const densityReadB = make('read', 'density-read-b', { path: '/fixture/sample-b.txt', offset: null, limit: null }); densityReadB.updateResult(result('beta'));
449
+ densityWriteA.setExpanded(true);
450
+ let tightRows = densityWriteA.render(120).map(stripAnsi);
451
+ assert.equal(tightRows.length, 6, 'native spacer plus group header and four adjacent action headings');
452
+ assert.ok(tightRows.slice(1).every(row => row.trim()), 'no blank rows between sibling actions');
453
+ clickSingle(densityWriteA, 2);
454
+ assert.match(paint(densityWriteA), /Content alpha/);
455
+ assert.doesNotMatch(paint(densityWriteA), /Successfully wrote|Arguments|Output|content:/);
456
+ const densityChoices = []; pi.events.emit('compact-renderer:inspect:v1', { add: choice => densityChoices.push(choice) });
457
+ densityChoices.find(choice => choice.label.includes('Edit files and read files')).focus();
458
+ input('\t');
459
+ let detailsRows = densityWriteA.render(120);
460
+ assert.match(stripAnsi(detailsRows.at(-1)), /Enter expand Details · Tab action/);
461
+ assertCardBackground([detailsRows.find(row => stripAnsi(row).includes('▸ Details'))], 120, 'selectedBg');
462
+ assertNeutral([detailsRows.find(row => stripAnsi(row).includes('4 actions'))]);
463
+ assert.doesNotMatch(paint(densityWriteA), /Arguments/, 'focusing Details does not expand it');
464
+ input('\r');
465
+ assert.match(paint(densityWriteA), /Successfully wrote to \/fixture\/sample-a.txt/);
466
+ assert.match(paint(densityWriteA), /path: "\/fixture\/sample-a.txt"/);
467
+ assert.match(paint(densityWriteA), /content:/);
468
+ assert.match(paint(densityWriteA), /Enter collapse Details/);
469
+ input('\x1b[Z'); assert.match(paint(densityWriteA), /Content alpha/, 'Shift+Tab returns to content target');
470
+ input('\x1b[C'); input('\r'); input('\t'); input('\r');
471
+ const densityPane = densityWriteA.resultRendererComponent.owner.group.pane;
472
+ assert.ok(densityPane.detailsExpanded.has('density-write-a') && densityPane.detailsExpanded.has('density-write-b'), 'Details expansion is independent for each action');
473
+ assert.ok(densityPane.expanded.has('density-write-a') && densityPane.expanded.has('density-write-b'), 'content expansion is independent');
474
+ input('\x1b[C'); input('\r');
475
+ assert.match(paint(densityWriteA), /alpha/); assert.doesNotMatch(paint(densityWriteA), /offset:|limit:/, 'read content omits repeated arguments');
476
+ input('\t'); input('\r');
477
+ assert.match(paint(densityWriteA), /offset: null/); assert.match(paint(densityWriteA), /limit: null/);
478
+ input('\x1b'); assert.equal(input('\t'), undefined, 'editor Tab is not captured');
479
+ const nonstandardWrite = make('write', 'density-extra-output', { path: '/fixture/source.js', content: 'const count = 2;' });
480
+ nonstandardWrite.updateResult(result('Successfully wrote to /fixture/source.js\nRecorded extra diagnostic', { warning: 'Keep this warning', truncated: true }));
481
+ nonstandardWrite.setExpanded(true);
482
+ assert.match(paint(densityWriteA), /warning recorded|output truncated/);
483
+ // The new write belongs to the same successful group; use its selected action anchor.
484
+ const extraPane = densityWriteA.resultRendererComponent.owner.group.pane;
485
+ extraPane.selected = extraPane.actions.length - 1; extraPane.handle('\x1b[C'); extraPane.handle('\x1b[D'); extraPane.handle('\r');
486
+ const extraPaint = densityWriteA.render(120).join('\n');
487
+ assert.match(stripAnsi(extraPaint), /Recorded extra diagnostic/, 'only full exact native write acknowledgement is suppressed');
488
+ assert.ok(extraPaint.includes(themeModule.theme.getFgAnsi('syntaxKeyword')), 'submitted source keeps path-based syntax colors');
489
+ event('message_end', { message: { role: 'user', content: 'unknown tool boundary' } });
490
+ const customContent = make('custom-tool', 'density-custom', { path: '/fixture/custom', option: null });
491
+ customContent.updateResult(result('# literal custom output **keep**\nunknown diagnostic', null)); customContent.setExpanded(true);
492
+ assert.match(paint(customContent), /# literal custom output \*\*keep\*\*/);
493
+ assert.match(paint(customContent), /unknown diagnostic/);
494
+ assert.doesNotMatch(paint(customContent), /Arguments/);
495
+ clickSingle(customContent, 4);
496
+ assert.match(paint(customContent), /Metadata[\s\S]*null/, 'explicit null diagnostics remain accessible');
497
+ const missing = make('read', 'density-missing', { path: '/fixture/missing.txt', offset: null, limit: null });
498
+ const missingText = "ENOENT: no such file or directory, access '/fixture/missing.txt'";
499
+ missing.updateResult({ ...result(missingText), isError: true }); missing.setExpanded(true);
500
+ assert.match(paint(missing), /ENOENT · File not found/);
501
+ assert.doesNotMatch(paint(missing), /access '/);
502
+ clickSingle(missing, 3); assert.match(paint(missing), /no such file or directory, access/);
503
+ const customFailure = make('custom-tool', 'density-custom-failure', {});
504
+ customFailure.updateResult({ ...result('Unknown failure with full useful context'), isError: true }); customFailure.setExpanded(true);
505
+ assert.match(paint(customFailure), /Unknown failure with full useful context/, 'unknown failure output remains visible');
506
+ const customKnownCode = make('custom-tool', 'density-custom-os-error', {});
507
+ customKnownCode.updateResult({ ...result("ENOENT: custom tool's exact diagnostic and context"), isError: true }); customKnownCode.setExpanded(true);
508
+ assert.match(paint(customKnownCode), /custom tool's exact diagnostic and context/, 'custom failure output is never replaced by an OS category');
509
+ redraws = 0;
510
+ // Details focus on a later mouse-selected action must bypass earlier huge output.
511
+ event('message_end', { message: { role: 'user', content: 'large inline focus fixture' } });
512
+ const earlierLarge = make('read', 'density-earlier-large', { path: '/fixture/large.txt' }); earlierLarge.updateResult(result('primary first line\n' + 'x'.repeat(1000000)));
513
+ const laterSmall = make('read', 'density-later-small', { path: '/fixture/later.txt', offset: null }); laterSmall.updateResult(result('later small output'));
514
+ earlierLarge.setExpanded(true);
515
+ const inlinePane = earlierLarge.resultRendererComponent.owner.group.pane;
516
+ const laterHeadingRow = earlierLarge.render(120).findIndex(row => stripAnsi(row).includes('2. read'));
517
+ clickSingle(earlierLarge, laterHeadingRow);
518
+ inlinePane.expanded.add('density-earlier-large'); inlinePane.reset(); // Simulate another independently open sibling before the clicked action.
519
+ const laterChoices = []; pi.events.emit('compact-renderer:inspect:v1', { add: choice => laterChoices.push(choice) });
520
+ laterChoices.find(choice => choice.label === '2 actions · Read files' && choice.id === laterChoices.at(-1).id).focus();
521
+ input('\t');
522
+ assert.match(paint(earlierLarge), /later small output[\s\S]*▸ Details/);
523
+ assert.doesNotMatch(paint(earlierLarge), /primary first line/, 'Tab anchors at the mouse-selected sibling');
524
+ input('\x1b[D'); input('\r'); // Select first action, whose primary content is already open; toggle closed then open for inspection.
525
+ input('\r'); input('\t');
526
+ assert.match(paint(earlierLarge), /content above ↑/);
527
+ input('\x1b[A'); assert.match(paint(earlierLarge), /primary first line/, 'Up returns from long-content Details anchor');
528
+ input('\t'); assert.match(paint(earlierLarge), /content above ↑/);
529
+ input('\x1b'); assert.match(paint(earlierLarge), /primary first line/, 'Escape restores primary content after Details inspection');
530
+ laterChoices.at(-1).focus(); input('\t');
531
+ assert.equal(input('typed editor text'), undefined);
532
+ assert.match(paint(earlierLarge), /primary first line/, 'typing also restores primary content before returning to editor');
533
+ redraws = 0;
534
+ // Replay script-shaped shell fallbacks without running any command.
535
+ const nodeScripts = [
536
+ `node -e 'const paths = ["/fixture/a", "/fixture/b"]; console.log(paths.map(path => ({ path })));'`,
537
+ `node - <<'NODE'\nconst paths = ["/fixture/a", "/fixture/b"];\nconsole.log(paths.map(path => ({ path })));\nNODE`,
538
+ ];
539
+ for (const command of nodeScripts) {
540
+ assert.equal(toolLabel('bash', { command }), 'bash · Run Node.js script');
541
+ assert.doesNotMatch(toolLabel('bash', { command }), /paths|fixture|console|codemode/);
542
+ }
543
+ assert.equal(toolLabel('bash', { command: 'node --version' }), 'bash · node --version', 'non-script interpreter operations stay truthful');
544
+ assert.equal(toolLabel('bash', { command: 'python3 -c "print(1)"' }), 'bash · Run Python script');
545
+ assert.equal(toolLabel('bash', { command: 'node /fixture/check.mjs' }), 'bash · Run Node.js script · /fixture/check.mjs');
546
+ assert.ok(toolLabel('bash', { command: 'custom-command ' + 'x'.repeat(10000) }).length < 80);
547
+ event('message_end', { message: { role: 'user', content: 'synthetic script replay' } });
548
+ const scripted = make('bash', 'script-label', { command: nodeScripts[1] });
549
+ scripted.updateResult(result('# literal stdout **unchanged** _log_\nSynthetic script output', { exitCode: 0 }));
550
+ assert.equal(paint(scripted).trim(), '▸ bash · Run Node.js script');
551
+ assert.doesNotMatch(paint(scripted), /successful|Completed|✓|const paths/);
552
+ scripted.setExpanded(true);
553
+ let scriptPaint = scripted.render(120).join('\n');
554
+ assert.match(stripAnsi(scriptPaint), /# literal stdout \*\*unchanged\*\* _log_/, 'Bash stdout remains literal');
555
+ assert.doesNotMatch(stripAnsi(scriptPaint), /const paths/);
556
+ clickSingle(scripted, 4);
557
+ scriptPaint = scripted.render(120).join('\n');
558
+ assert.match(stripAnsi(scriptPaint), /const paths/);
559
+ assert.ok(scriptPaint.includes(themeModule.theme.getFgAnsi('syntaxKeyword')), 'heredoc source uses native JavaScript keyword colors');
560
+ scripted.setExpanded(false);
561
+ const exactError = `Error: ENAMETOOLONG: name too long, lstat '${'\"/fixture/very-long-path\",'.repeat(10000)}'`;
562
+ const scriptFailure = make('bash', 'script-failure', { command: nodeScripts[0] });
563
+ const failureRecording = { ...result(exactError, { error: exactError, exitCode: 1 }), isError: true };
564
+ scriptFailure.updateResult(failureRecording);
565
+ assert.equal(paint(scriptFailure).trim(), '▸ bash · Run Node.js script · ✗ Failed · Path too long');
566
+ assert.ok(paint(scriptFailure, 500).trim().length < 100);
567
+ scriptFailure.setExpanded(true);
568
+ assert.doesNotMatch(paint(scriptFailure), /name too long, lstat/);
569
+ clickSingle(scriptFailure, 3);
570
+ assert.match(paint(scriptFailure), /ENAMETOOLONG: name too long, lstat/);
571
+ event('message_end', { message: { role: 'user', content: 'focused overflow fixture' } });
572
+ const focusedOverflow = make('read', 'focused-overflow', { path: '/fixture/focused-overflow' });
573
+ focusedOverflow.updateResult(result(Array.from({ length: 60 }, (_, n) => `Focused output ${n}`).join('\n')));
574
+ paint(focusedOverflow);
575
+ const overflowChoices = []; pi.events.emit('compact-renderer:inspect:v1', { add: choice => overflowChoices.push(choice) });
576
+ overflowChoices.find(choice => choice.label.includes('/fixture/focused-overflow')).focus();
577
+ const focusedOverflowRows = focusedOverflow.render(120).map(stripAnsi);
578
+ assert.match(focusedOverflowRows.join('\n'), /Focused output 0\b/);
579
+ clickSingle(focusedOverflow, focusedOverflowRows.findIndex(row => row.includes('more ↓')));
580
+ assert.doesNotMatch(paint(focusedOverflow), /Focused output 0\b/, 'overflow paging survives mouse release of inspection');
581
+ assert.doesNotMatch(paint(focusedOverflow), / · focused/);
582
+ assert.equal(input('\r'), undefined, 'tool overflow returns Enter to the editor');
583
+ const styled = new ToolPane([{ id: 'styles', label: 'read', sections: function* () {
584
+ yield { text: '# Recorded heading\n**Emphasis** and `inline` code.\n```javascript\nconst paths = ["/fixture/a"];\n```', format: 'markdown' };
585
+ yield { text: '-const before = 1;\n+const after = 2;', format: 'code', language: 'diff' };
586
+ } }], 'Styles', () => 20);
587
+ styled.open = true; styled.theme = themeModule.theme;
588
+ const styledRows = styled.render(120).join('\n');
589
+ assert.match(stripAnsi(styledRows), /Recorded heading/);
590
+ assert.doesNotMatch(stripAnsi(styledRows), /# Recorded heading|\*\*Emphasis\*\*/);
591
+ assert.ok(styledRows.includes(themeModule.theme.getFgAnsi('syntaxKeyword')), 'fenced code uses native syntax colors');
592
+ assert.ok(styledRows.includes(themeModule.theme.getFgAnsi('syntaxString')), 'code strings use their native token color');
593
+ assert.ok(styledRows.includes(themeModule.theme.getFgAnsi('toolDiffAdded')), 'diff additions use native highlighting');
594
+ assert.equal(failureRecording.content[0].text, exactError, 'expanded formatting leaves exact recorded output unchanged');
595
+ assert.equal(failureRecording.details.error, exactError, 'expanded formatting leaves exact recorded details unchanged');
596
+ // Track actual native shell intervals, without leaking a real clock if an assertion fails.
597
+ const actualSetInterval = globalThis.setInterval, actualClearInterval = globalThis.clearInterval;
598
+ const intervals = new Set();
599
+ globalThis.setInterval = (...args) => { const handle = actualSetInterval(...args); intervals.add(handle); return handle; };
600
+ globalThis.clearInterval = (handle) => { intervals.delete(handle); return actualClearInterval(handle); };
601
+ try {
602
+ for (const finish of ['success', 'error', 'cancel']) {
603
+ toggle(false);
604
+ const running = make('bash', `clock-${finish}`, { command: 'printf safe' });
605
+ running.markExecutionStarted(); running.updateResult(result('partial'), true);
606
+ assert.equal(intervals.size, 1);
607
+ toggle(true); assert.equal(intervals.size, 0, 'collapse releases native timer');
608
+ running.updateResult({ ...result('done', finish === 'cancel' ? { status: 'cancelled' } : {}), isError: finish === 'error' });
609
+ assert.equal(intervals.size, 0);
610
+ }
611
+ toggle(false);
612
+ const running = make('bash', 'clock-switch', { command: 'printf safe' });
613
+ running.markExecutionStarted(); running.updateResult(result('partial'), true);
614
+ assert.equal(intervals.size, 1);
615
+ event('session_before_switch'); assert.equal(intervals.size, 0); assert.equal(input, undefined);
616
+ event('session_start', { reason: 'resume' }); assert.equal(typeof input, 'function');
617
+ running.invalidate(); assert.equal(intervals.size, 0, 'late old-session invalidation does not restart a timer');
618
+ const resumed = make('read', 'resumed', { path: '/tmp/resumed' }); resumed.updateResult(result('resumed output'));
619
+ toggle(true); assert.match(paint(resumed), /read · \/tmp\/resumed/);
620
+ event('session_compact'); event('session_tree');
621
+ toggle(false);
622
+ const shutdownRunning = make('bash', 'clock-shutdown', { command: 'printf safe' });
623
+ shutdownRunning.markExecutionStarted(); shutdownRunning.updateResult(result('partial', { calls: [] }), true);
624
+ assert.equal(intervals.size, 1, 'wrapped tools retain the native timer contract');
625
+ dispose(); dispose(); assert.equal(intervals.size, 0); assert.equal(input, undefined); assert.equal(modeChange, undefined);
626
+ } finally { for (const handle of intervals) actualClearInterval(handle); globalThis.setInterval = actualSetInterval; globalThis.clearInterval = actualClearInterval; }
627
+ // A 10 MB output is not eagerly split or painted. Stored source remains unchanged.
628
+ const huge = '漢字🙂 exact\x1b[31m\n'.repeat(400000);
629
+ const simplePane = new ToolPane([{ id: 'simple', label: 'read · exact.txt', sections: function* () { yield { text: 'Output', kind: 'section' }; yield 'exact output'; } }], '1 successful action', () => 20);
630
+ simplePane.theme = themeModule.theme; simplePane.open = true; simplePane.expanded.add('simple');
631
+ const simpleRows = simplePane.render(80);
632
+ assert.equal(simpleRows.length, 3, 'an unfocused complete pane has no footer row');
633
+ assert.doesNotMatch(stripAnsi(simpleRows.join('\n')), /to inspect|Alt\+G|more ↓/);
634
+ assert.doesNotMatch(stripAnsi(simpleRows.join('\n')), /1\. read/, 'a singleton has no duplicate action heading');
635
+ assert.equal(stripAnsi(simpleRows.find(row => stripAnsi(row).includes('exact output'))).indexOf('exact output'), 3, 'singleton details align after the disclosure column');
636
+ assert.ok(simpleRows.find(row => stripAnsi(row).trim() === 'Output').includes(themeModule.theme.getFgAnsi('muted')), 'section headings use the native muted color');
637
+ const singleRound = new ToolPane([{ id: 'round', label: 'Recorded first line', sections: function* () { yield 'Full recorded round'; } }], 'Thinking · 1 round');
638
+ singleRound.itemName = 'round'; singleRound.open = true;
639
+ assert.match(stripAnsi(singleRound.render(80).join('\n')), /1\. Recorded first line/);
640
+ assert.doesNotMatch(stripAnsi(singleRound.render(80).join('\n')), /Full recorded round/);
641
+ singleRound.handle('\r');
642
+ assert.match(stripAnsi(singleRound.render(80).join('\n')), /Full recorded round/, 'single thinking rounds keep independent expansion');
643
+ // Thinking uses the same compact expansion and disclosure coordinates as tools.
644
+ const narrative = new ToolPane([
645
+ { id: 'first', label: 'First round', sections: () => ['First body'] },
646
+ { id: 'second', label: 'Second round', sections: () => ['Second body'] },
647
+ ], 'Thinking', () => 12);
648
+ narrative.itemName = 'round'; narrative.open = true; narrative.expanded.add('first');
649
+ const narrativeRows = narrative.render(80).map(stripAnsi);
650
+ assert.match(narrativeRows[2], /First body/, 'expanded round body immediately follows its heading');
651
+ const clickNarrative = y => narrative.handleMouse({ type: 'click', button: 'left', x: 3, y });
652
+ clickNarrative(2);
653
+ assert.deepEqual([...narrative.expanded], ['first'], 'clicking the body does not toggle an action');
654
+ clickNarrative(narrativeRows.findIndex(line => line.includes('Second round')));
655
+ assert.ok(narrative.expanded.has('second'), 'later round disclosure uses its compact rendered row');
656
+ assert.match(narrative.render(80).map(stripAnsi).join('\n'), /Second body/);
657
+ narrative.detailsExpanded.add('first'); narrative.offset = 4; narrative.focused = true;
658
+ narrative.collapse();
659
+ assert.equal(narrative.open, false); assert.equal(narrative.focused, false); assert.equal(narrative.offset, 0);
660
+ assert.equal(narrative.expanded.size, 0); assert.equal(narrative.detailsExpanded.size, 0);
661
+ narrative.open = true;
662
+ assert.doesNotMatch(narrative.render(80).map(stripAnsi).join('\n'), /First body|Second body/, 'explicit reset reopens with all actions closed');
663
+ // Content that already fits must not lose a row just because the user wheels down.
664
+ const fittingPane = new ToolPane([{ id: 'fits', label: 'Read', sections: () => Array.from({ length: 7 }, (_, n) => `Fitting row ${n}`) }], 'Read', () => 8);
665
+ fittingPane.open = true;
666
+ const fittingRows = fittingPane.render(80);
667
+ fittingPane.handleMouse({ type: 'wheel', button: 'none', x: 3, y: 2, wheelDelta: 1 });
668
+ assert.deepEqual(fittingPane.render(80), fittingRows, 'a fully visible result does not create artificial overflow');
669
+ assert.equal(fittingPane.offset, 0);
670
+ // The rendered overflow footer pages the existing inline viewport and preserves Details state.
671
+ const overflowPane = new ToolPane([{ id: 'overflow', label: 'Read', sections: function* () {
672
+ for (let n = 0; n < 60; n++) yield `Recorded output ${n}`;
673
+ }, details: () => ['Exact arguments'] }], 'Read', () => 8);
674
+ overflowPane.open = true; overflowPane.detailsExpanded.add('overflow');
675
+ let overflowRows = overflowPane.render(80).map(stripAnsi);
676
+ const clickOverflow = extra => overflowPane.handleMouse({ type: 'click', button: 'left', x: 3, y: overflowRows.findIndex(row => row.includes('more ↓')), ...extra });
677
+ assert.equal(clickOverflow({ shift: true })?.render, false); assert.equal(overflowPane.offset, 0, 'modified overflow clicks preserve text selection');
678
+ assert.equal(clickOverflow()?.handled, true);
679
+ overflowRows = overflowPane.render(80).map(stripAnsi);
680
+ assert.ok(overflowPane.offset > 0 && overflowPane.offset <= 8, 'overflow click advances one bounded tool viewport');
681
+ assert.doesNotMatch(overflowRows.join('\n'), /Recorded output 0\b/);
682
+ assert.ok(overflowPane.detailsExpanded.has('overflow'), 'paging preserves Details expansion');
683
+ for (let n = 0; n < 20 && overflowRows.some(row => row.includes('more ↓')); n++) {
684
+ clickOverflow(); overflowRows = overflowPane.render(80).map(stripAnsi);
685
+ }
686
+ assert.match(overflowRows.join('\n'), /Recorded output 59/);
687
+ assert.doesNotMatch(overflowRows.join('\n'), /more ↓/, 'downward paging stops at the end');
688
+ const overflowEndOffset = overflowPane.offset, overflowEndHeight = overflowRows.length;
689
+ assert.match(overflowRows.at(-1), /more ↑/);
690
+ overflowPane.handleMouse({ type: 'click', button: 'left', x: 3, y: overflowRows.length - 1 });
691
+ overflowRows = overflowPane.render(80).map(stripAnsi);
692
+ assert.ok(overflowPane.offset < overflowEndOffset, 'the final footer pages back');
693
+ assert.equal(overflowRows.length, overflowEndHeight, 'tool and thinking panes retain their height at the end');
694
+ assert.ok(overflowPane.paintedRows < 80, 'paging only formats the bounded visited output');
695
+ const { suppressRepeatedSummary } = await loadSource('./recorded-summary.ts');
696
+ const originalSummary = '# **Check inputs**\n\nFirst paragraph.\n\nSecond paragraph.';
697
+ assert.equal(suppressRepeatedSummary(originalSummary, 'Check inputs'), 'First paragraph.\n\nSecond paragraph.');
698
+ assert.equal(originalSummary, '# **Check inputs**\n\nFirst paragraph.\n\nSecond paragraph.', 'presentation helper preserves recorded source');
699
+ for (const [source, summary] of [
700
+ ['Different title\nBody', 'Check inputs'],
701
+ ['Check inputs. More content in this paragraph.\nBody', 'Check inputs.'],
702
+ ['# Check inputs\n\n', 'Check inputs'],
703
+ ['A long complete title\nBody', 'A long…'],
704
+ ['Exact title\n' + '\n'.repeat(100000) + 'Distant body', 'Exact title'],
705
+ ]) assert.equal(suppressRepeatedSummary(source, summary), source, 'nonmatch, paragraph prefix, sole content and clipped summary stay exact');
706
+ const summaryPane = new ToolPane([{ id: 'summary', label: 'Exact title', repeatedSummary: 'Exact title', sections: () => [{text: '# Exact title\n\nVisible body\n\nNext paragraph', format: 'markdown'}] }], 'Thinking · Exact title');
707
+ summaryPane.directContent = true; summaryPane.open = true;
708
+ assert.doesNotMatch(summaryPane.render(80).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'full repeated heading is omitted from compact body');
709
+ assert.match(summaryPane.render(12).map(stripAnsi).slice(1).join('\n'), /Exact/, 'clipped display summary keeps the recorded heading in the body');
710
+ summaryPane.focused = false;
711
+ assert.doesNotMatch(summaryPane.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/);
712
+ summaryPane.focused = true;
713
+ assert.match(summaryPane.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'focus suffix clipping restores the repeated heading after a cached render');
714
+ summaryPane.focused = false;
715
+ assert.doesNotMatch(summaryPane.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'removing focus updates suppression without a width change');
716
+ const clippedOverflow = new ToolPane([{ id: 'clipped-overflow', label: 'Exact title', repeatedSummary: 'Exact title', sections: () => [{ text: '# Exact title\n\n' + Array.from({ length: 50 }, (_, n) => `Body ${n}`).join('\n'), format: 'markdown' }] }], 'Thinking · Exact title', () => 8);
717
+ clippedOverflow.open = true; clippedOverflow.focused = true;
718
+ let clippedRows = clippedOverflow.render(30).map(stripAnsi);
719
+ assert.match(clippedRows.slice(1).join('\n'), /Exact title/);
720
+ clippedOverflow.handleMouse({ type: 'click', button: 'left', x: 3, y: clippedRows.findIndex(row => row.includes('more ↓')) });
721
+ clippedOverflow.focused = false; clippedRows = clippedOverflow.render(30).map(stripAnsi);
722
+ assert.ok(clippedOverflow.offset > 0, 'a focus-clipped heading also preserves the paged position');
723
+ clippedOverflow.handle('\x1b[H');
724
+ assert.doesNotMatch(clippedOverflow.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'Home resets the cache using the current complete heading');
725
+ const exactValues = { command: 'printf "hello"\nnext exact line', options: { paths: ['a', 'b'], empty: '', nullable: null } };
726
+ const valueRows = [...recordedValues(exactValues)];
727
+ assert.ok(valueRows.some(row => row.text === exactValues.command), 'multiline string values remain exact');
728
+ assert.ok(valueRows.some(row => row.text === '[1]: \"b\"'), 'array positions and values remain accessible');
729
+ assert.ok(valueRows.some(row => row.text === 'empty: \"\"') && valueRows.some(row => row.text === 'nullable: null'), 'empty strings and null remain distinct');
730
+ let laterFieldReads = 0;
731
+ const largeArguments = { command: huge };
732
+ Object.defineProperty(largeArguments, 'later', { enumerable: true, get() { laterFieldReads++; return 'later recorded value'; } });
733
+ const argumentPane = new ToolPane([{ id: 'args', label: 'bash', sections: () => recordedValues(largeArguments) }], 'Arguments', () => 8);
734
+ argumentPane.open = true; argumentPane.expanded.add('args'); argumentPane.render(30);
735
+ assert.equal(laterFieldReads, 0, 'painting a large argument does not visit later fields');
736
+ // Details has its own bounded viewport anchor and does not read late metadata early.
737
+ let primaryVisits = 0, metadataReads = 0, lateMetadataReads = 0;
738
+ const lazyMetadata = { source: huge };
739
+ Object.defineProperty(lazyMetadata, 'late', { enumerable: true, get() { lateMetadataReads++; return 'late exact diagnostic'; } });
740
+ const lazyDetails = new ToolPane([{ id: 'lazy', label: 'large', sections: function* () { primaryVisits++; yield huge; }, details: function* () { metadataReads++; yield* recordedValues(lazyMetadata); } }], 'Lazy', () => 8);
741
+ lazyDetails.open = true; lazyDetails.focused = true; lazyDetails.theme = themeModule.theme;
742
+ lazyDetails.render(30);
743
+ assert.equal(metadataReads, 0, 'opening useful content does not invoke Details factory');
744
+ const beforeFocusVisits = primaryVisits;
745
+ lazyDetails.handle('\t');
746
+ assert.match(stripAnsi(lazyDetails.render(30).join('\n')), /▸ Details/);
747
+ assert.ok(primaryVisits <= beforeFocusVisits + 1, 'Tab probes at most a bounded viewport of primary output');
748
+ assert.match(stripAnsi(lazyDetails.render(30).join('\n')), /content above ↑/);
749
+ assert.equal(metadataReads, 0, 'focusing Details does not traverse metadata');
750
+ lazyDetails.handle('\r'); lazyDetails.render(30);
751
+ assert.equal(metadataReads, 1); assert.equal(lateMetadataReads, 0, 'expanding huge metadata only visits a bounded prefix');
752
+ assert.ok(lazyDetails.paintedRows < 35, 'content, Details focus and expansion paint bounded rows');
753
+ for (const width of [1, 2, 8, 20, 80]) for (const row of lazyDetails.render(width)) assert.ok(tui.visibleWidth(row) <= width);
754
+ assert.equal(largeArguments.command, huge, 'argument formatting does not change stored source');
755
+ assert.equal([...textRows('\x1b[31m\u202eexact\u{e0001}', 80)].join(''), '\\u001b[31m\\u202eexact\\u{e0001}', 'terminal and bidi controls are visible text');
756
+ // Compact summaries retain the native gutter without colored Box padding.
757
+ const referencePane = new ToolPane([], 'Ref'); referencePane.theme = themeModule.theme;
758
+ for (const width of [8, 30, 80]) {
759
+ const rows = referencePane.render(width);
760
+ assert.equal(rows.length, 1); assert.match(stripAnsi(rows[0]), /^ ▸ Ref/); assertNeutral(rows);
761
+ }
762
+ const multiDigit = new ToolPane(Array.from({ length: 10 }, (_, index) => ({ id: String(index), label: 'read', sections: function* () { yield 'tenth output'; } })), 'Ten actions');
763
+ multiDigit.open = true;
764
+ for (let index = 0; index < 9; index++) multiDigit.handle('\x1b[C');
765
+ multiDigit.expanded.add('9');
766
+ const tenthRows = multiDigit.render(80).map(stripAnsi);
767
+ assert.equal(tenthRows.find(row => row.includes('tenth output')).indexOf('tenth output'), tenthRows.find(row => row.includes('10. read')).indexOf('read'), 'detail alignment includes the full multi-digit action prefix');
768
+ const pane = new ToolPane([{ id: 'large', label: 'large', sections: function* () { yield huge; } }], 'Large', () => 10);
769
+ pane.open = true; pane.expanded.add('large');
770
+ for (const width of [1, 8, 20, 80]) {
771
+ const rows = pane.render(width); assert.ok(rows.length <= 10);
772
+ for (const row of rows) assert.ok(tui.visibleWidth(row) <= width);
773
+ }
774
+ assert.ok(pane.paintedRows < 100, 'painting cost follows viewports rather than output size');
775
+ pane.handle('\x1b[6~'); pane.render(80); assert.ok(pane.paintedRows < 120);
776
+ assert.ok(huge.includes('\x1b[31m'), 'source escapes remain untouched');
777
+ const longLinePane = new ToolPane([{ id: 'line', label: 'long line', sections: function* () { yield 'x'.repeat(10000000); } }], 'Long line', () => 8);
778
+ longLinePane.open = true; longLinePane.expanded.add('line'); longLinePane.render(20);
779
+ assert.ok(longLinePane.paintedRows <= 8, 'one long line paints a bounded prefix');
780
+ // History reconstruction groups once, and repeated ordinary paints do not rescan old records.
781
+ let historyReads = 0;
782
+ const history = [];
783
+ for (let index = 0; index < 1500; index++) {
784
+ const args = { path: `/tmp/history-${index}` };
785
+ history.push({ type: 'message', message: { role: 'assistant', content: [{ type: 'toolCall', id: `history-${index}`, name: 'read', arguments: args }] } });
786
+ const entry = { role: 'toolResult', toolCallId: `history-${index}`, toolName: 'read', content: [{ type: 'text', text: 'recorded' }] };
787
+ Object.defineProperty(entry, 'details', { get() { historyReads++; return undefined; } });
788
+ history.push({ type: 'message', message: entry });
789
+ }
790
+ ctx.sessionManager.getBranch = () => history;
791
+ enabled = true;
792
+ const disposeHistory = registerModernTools(pi, mode);
793
+ event('session_start', { reason: 'reload' });
794
+ assert.ok(historyReads < 1500 * 12, `history rebuild reads grow linearly: ${historyReads}`);
795
+ const historyRow = make('read', 'history-0', history[0].message.content[0].arguments);
796
+ historyRow.updateResult({ content: history[1].message.content, details: undefined });
797
+ const readsAfterAttach = historyReads;
798
+ for (let iteration = 0; iteration < 20; iteration++) { historyRow.invalidate(); paint(historyRow); }
799
+ assert.equal(historyReads, readsAfterAttach, 'unchanged paints never walk history');
800
+ const noResultRenderer = resolver('no-result-renderer', () => ({ renderCall: () => new tui.Text('native call', 0, 0) }));
801
+ const noResultContext = { toolCallId: 'no-result-context', args: {}, state: {}, cwd: '/tmp', expanded: true, executionStarted: false, isPartial: false, isError: false, outputPad: 1, invalidate() {} };
802
+ noResultRenderer.renderCall({}, themeModule.theme, noResultContext);
803
+ event('session_start', { reason: 'reload' });
804
+ assert.match(stripAnsi(noResultRenderer.renderResult(result('stale recorded output'), { expanded: true, isPartial: false }, themeModule.theme, noResultContext).render(80).join('\n')), /stale recorded output/);
805
+ const unsupportedContext = { ...noResultContext, state: undefined };
806
+ assert.match(stripAnsi(noResultRenderer.renderResult(result('unsupported recorded output'), { expanded: false, isPartial: false }, themeModule.theme, unsupportedContext).render(80).join('\n')), /unsupported recorded output/);
807
+ disposeHistory();
808
+ // Use Pi's actual compaction-aware initial display projection. Hidden earlier tools cannot own a visible group.
809
+ const recordedSession = core.SessionManager.inMemory('/synthetic-tools');
810
+ const recordedArgs = [];
811
+ for (let index = 0; index < 3; index++) {
812
+ const args = { path: `/tmp/retained-${index}` }; recordedArgs.push(args);
813
+ recordedSession.appendMessage({ role: 'assistant', content: [{ type: 'toolCall', id: `retained-${index}`, name: 'read', arguments: args }] });
814
+ recordedSession.appendMessage({ role: 'toolResult', toolCallId: `retained-${index}`, toolName: 'read', ...result(`retained output ${index}`) });
815
+ }
816
+ const retainedEntry = recordedSession.getBranch().find(entry => entry.type === 'message' && entry.message.content?.[0]?.id === 'retained-1');
817
+ recordedSession.appendCompaction('Fixture summary before retained tools', retainedEntry.id, 100);
818
+ ctx.sessionManager = recordedSession;
819
+ const disposeProjection = registerModernTools(pi, mode);
820
+ event('session_start', { reason: 'resume' });
821
+ let nativeMessages;
822
+ core.InteractiveMode.prototype.renderSessionEntries.call({ renderer: undefined, renderSessionItems(items) { nativeMessages = items; } }, recordedSession.buildContextEntries());
823
+ const retainedRows = [];
824
+ for (const message of nativeMessages) {
825
+ if (message.role === 'assistant') for (const call of message.content ?? []) if (call.type === 'toolCall') retainedRows.push(make(call.name, call.id, call.arguments));
826
+ if (message.role === 'toolResult') retainedRows.at(-1).updateResult(message);
827
+ }
828
+ assert.equal(retainedRows.length, 2);
829
+ assert.match(paint(retainedRows[0]), /2 actions/);
830
+ assert.equal(paint(retainedRows[1]), '');
831
+ event('session_compact'); assert.match(paint(retainedRows[0]), /2 actions/);
832
+ // Old native rows are stale after rebuild; newly replayed rows use the retained projection again.
833
+ const replayed = make('read', 'retained-1', recordedArgs[1]); replayed.updateResult(result('retained output 1'));
834
+ assert.match(paint(replayed), /2 actions/);
835
+ // Isolate redraw accounting for the separate subagent lifecycle fixture session.
836
+ redraws = 0;
837
+ // Native pi-subagents contracts: receipts describe the operation, not an inferred child outcome.
838
+ event('message_end', { message: { role: 'user', content: 'subagent fixtures' } });
839
+ const beforeLaunch = make('read', 'before-launch', { path: '/tmp/before-launch' }); beforeLaunch.updateResult(result('before'));
840
+ const launchArgs = { agent: 'worker', task: 'Keep this exact task\nincluding its second line.', async: true };
841
+ const launchDetails = { mode: 'single', runId: 'run-raw-uuid', results: [], asyncId: 'run-raw-uuid', asyncDir: '/tmp/native-run' };
842
+ const launchRecorded = JSON.stringify({ args: launchArgs, details: launchDetails });
843
+ const launchOutput = 'Async: worker [run-raw-uuid]\nExact recorded launch receipt.';
844
+ const launch = make('subagent', 'sub-launch', launchArgs);
845
+ assert.match(paint(launch), /Subagent · launch · worker · Preparing/);
846
+ launch.markExecutionStarted(); assert.match(paint(launch), /worker · Running/);
847
+ launch.updateResult(result(launchOutput, launchDetails));
848
+ assert.match(paint(launch), /Subagent · launch · worker · Started asynchronously/);
849
+ assert.doesNotMatch(paint(launch), /Completed|run-raw-uuid|Exact recorded/);
850
+ assert.equal(launch.render(100).length, 2); assertNeutral(launch.render(100));
851
+ capture('Subagent asynchronous launch compact receipt', launch);
852
+ const afterLaunch = make('read', 'after-launch', { path: '/tmp/after-launch' }); afterLaunch.updateResult(result('after'));
853
+ assert.doesNotMatch(paint(beforeLaunch), /2 actions/); assert.doesNotMatch(paint(afterLaunch), /2 actions/, 'subagent lifecycle rows separate action groups');
854
+ launch.setExpanded(true);
855
+ assert.match(paint(launch), /Async: worker \[run-raw-uuid\]/);
856
+ assert.match(paint(launch), /Exact recorded launch receipt/);
857
+ assert.doesNotMatch(paint(launch), /Arguments|asyncDir|1\. subagent/, 'subagent expansion starts with recorded content');
858
+ const subInspection = []; pi.events.emit('compact-renderer:inspect:v1', { add: item => subInspection.push(item) });
859
+ subInspection.find(item => item.label.includes('Started asynchronously')).focus();
860
+ input('\t'); input('\r');
861
+ assert.match(paint(launch), /Arguments/); assert.match(paint(launch), /Keep this exact task/);
862
+ assert.match(paint(launch), /including its second line/);
863
+ // Details can exceed the body viewport; navigation reaches the exact native detail fields.
864
+ for (let i = 0; i < 30; i++) input('\x1b[B');
865
+ assert.match(paint(launch), /asyncDir|native-run/);
866
+ input('\x1b'); launch.setExpanded(false);
867
+ assert.equal(JSON.stringify({ args: launchArgs, details: launchDetails }), launchRecorded, 'subagent rendering leaves native arguments and details intact');
868
+ const steer = make('subagent', 'sub-steer', { action: 'steer', id: 'run-raw-uuid', message: 'Exact steering instruction.' });
869
+ const queuedDetails = { mode: 'management', results: [], steering: { requestId: 'request-raw-uuid', state: 'pending', deliveryStatus: 'queued', sourceRunId: 'run-raw-uuid', targets: [{ index: 0, state: 'queued' }] } };
870
+ steer.updateResult(result('Steering queued for async run run-raw-uuid.\nExact steering instruction.', queuedDetails));
871
+ assert.match(paint(steer), /Subagent · steer · Queued/);
872
+ assert.doesNotMatch(paint(steer), /Delivered|Completed|steered|raw-uuid/);
873
+ steer.setExpanded(true); assert.match(paint(steer), /Exact steering instruction/); steer.setExpanded(false);
874
+ steer.updateResult(result('Steering delivered.', { ...queuedDetails, steering: { ...queuedDetails.steering, state: 'delivered', deliveryStatus: 'delivered', targets: [{ index: 0, state: 'delivered' }] } }));
875
+ assert.match(paint(steer), /steer · Delivered/); assert.doesNotMatch(paint(steer), /Completed|Consumed/);
876
+ for (const [state, tone, expected] of [['failed', 'error', '✗ Failed · Steering failed'], ['partial', 'warning', 'Partial steering result']]) {
877
+ steer.updateResult(result('Exact structured steering outcome.', { ...queuedDetails, steering: { ...queuedDetails.steering, state } }));
878
+ assert.ok(paint(steer).includes(expected));
879
+ assert.ok(steer.render(100)[1].includes(themeModule.theme.getFgAnsi(tone)), 'structured failure and partial receipts remain conspicuous without isError');
880
+ }
881
+ steer.updateResult({ ...result('Steering not delivered or queued: answer supervisor request request-raw-uuid first.', { mode: 'management', results: [] }), isError: true });
882
+ assert.match(paint(steer), /✗ Failed · Steering rejected/); assert.doesNotMatch(paint(steer), /raw-uuid|answer supervisor|Delivered/);
883
+ assert.ok(steer.render(100)[1].includes(themeModule.theme.getFgAnsi('error')));
884
+ steer.setExpanded(true); assert.match(paint(steer), /Steering not delivered or queued: answer supervisor request request-raw-uuid first/); steer.setExpanded(false);
885
+ capture('Subagent rejected steering compact failure', steer);
886
+ const rejected = make('subagent', 'sub-rejected', { agent: 'worker', async: true });
887
+ rejected.updateResult({ ...result('Capacity policy denied launch; raw-uuid. Exact policy explanation.', { mode: 'single', results: [], activeAsyncCapacity: { limit: 3, active: 3 } }), isError: true });
888
+ assert.match(paint(rejected), /✗ Failed · Capacity reached/); assert.doesNotMatch(paint(rejected), /Started|Completed|raw-uuid/);
889
+ rejected.setExpanded(true); assert.match(paint(rejected), /Exact policy explanation/); rejected.setExpanded(false);
890
+ const foreground = make('subagent', 'sub-foreground', { agent: 'worker' });
891
+ foreground.updateResult(result('Exact unresolved child result.', { mode: 'single', results: [{ agent: 'worker' }] }));
892
+ assert.match(paint(foreground), /worker · Result recorded/); assert.doesNotMatch(paint(foreground), /Completed/);
893
+ foreground.updateResult(result('Exact child result.', { mode: 'single', results: [{ agent: 'worker', exitCode: 0 }] }));
894
+ assert.match(paint(foreground), /worker · Completed/);
895
+ foreground.updateResult(result('Detached for supervisor coordination.', { mode: 'single', results: [{ agent: 'worker', exitCode: 0, detached: true }] }));
896
+ assert.match(paint(foreground), /worker · Detached/); assert.doesNotMatch(paint(foreground), /Completed/);
897
+ for (const [field, state] of [['stopped', 'Stopped'], ['timedOut', 'Timed out']]) {
898
+ foreground.updateResult(result('Exact halted child output.', { mode: 'single', results: [{ exitCode: 0, [field]: true }] }));
899
+ assert.match(paint(foreground), new RegExp(`worker · ${state}`)); assert.doesNotMatch(paint(foreground), /Completed/);
900
+ }
901
+ const statusCard = make('subagent', 'sub-status', { action: 'status', id: 'raw-run-id' });
902
+ statusCard.updateResult(result('Run: raw-run-id\nState: running', { mode: 'management', results: [] }));
903
+ assert.match(paint(statusCard), /Subagent · status · Status recorded/); assert.doesNotMatch(paint(statusCard), /Completed|raw-run-id/);
904
+ const standaloneGuideTopic = 't'.repeat(80);
905
+ const standaloneGuide = make('subagent', 'sub-standalone-guide', { action: 'guide', options: { topic: standaloneGuideTopic } });
906
+ standaloneGuide.updateResult(result('Exact standalone guide response.', { mode: 'management', results: [] }));
907
+ assert.equal(paint(standaloneGuide).split('\n').find(line => line.includes('Subagent · guide')), ` ▸ Subagent · guide · ${standaloneGuideTopic.slice(0, 72)}`, 'standalone guide titles include the sanitized, bounded topic');
908
+ assert.doesNotMatch(paint(standaloneGuide), /Result recorded/);
909
+ standaloneGuide.setExpanded(true); assert.match(paint(standaloneGuide), /Exact standalone guide response/);
910
+ const enableCard = make('subagents_enable', 'sub-enable', {});
911
+ enableCard.updateResult(result('Enabled the native subagent tools.', { enabled: true }));
912
+ assert.match(paint(enableCard), /Subagent · enable · Result recorded/); assert.doesNotMatch(paint(enableCard), /launch|Started|Completed/);
913
+ enableCard.setExpanded(true); assert.match(paint(enableCard), /Enabled the native subagent tools/); enableCard.setExpanded(false);
914
+ const supervisor = make('subagent_supervisor', 'sub-reply', { action: 'reply', replyTo: 'request-raw-uuid', message: 'Exact supervisor answer.' });
915
+ supervisor.updateResult(result('Replied to supervisor request request-raw-uuid.', { replyTo: 'request-raw-uuid', runId: 'run-raw-uuid', agent: 'worker' }));
916
+ assert.match(paint(supervisor), /Supervisor · reply · worker · Reply recorded/); assert.doesNotMatch(paint(supervisor), /raw-uuid|Consumed|Completed/);
917
+ supervisor.setExpanded(true); assert.match(paint(supervisor), /Replied to supervisor request request-raw-uuid/); supervisor.setExpanded(false);
918
+ const decisionCard = make('contact_supervisor', 'sub-decision', { reason: 'need_decision', message: 'Which route should I use?' });
919
+ assert.match(paint(decisionCard), /Supervisor decision · Pending/);
920
+ assert.ok(decisionCard.render(100)[1].includes(themeModule.theme.getFgAnsi('accent')));
921
+ decisionCard.updateResult(result('**Reply from supervisor:**\nUse route B.', { requestId: 'request-raw-uuid', reason: 'need_decision' }));
922
+ assert.match(paint(decisionCard), /Supervisor decision · Reply recorded/);
923
+ decisionCard.setExpanded(true); assert.match(paint(decisionCard), /Use route B/); decisionCard.setExpanded(false);
924
+ const unknownSubagent = make('subagent', 'sub-unknown', { workflow: true });
925
+ unknownSubagent.updateResult(result('Unknown future recorded payload.\nSecond exact line.', { mode: 'future-shape', results: { unexpected: true }, asyncId: 'raw-uuid', status: 'future-state' }));
926
+ assert.match(paint(unknownSubagent), /Result recorded/); assert.doesNotMatch(paint(unknownSubagent), /Started|Completed/);
927
+ unknownSubagent.setExpanded(true); assert.match(paint(unknownSubagent), /Unknown future recorded payload/); assert.match(paint(unknownSubagent), /Second exact line/);
928
+ unknownSubagent.updateResult({ ...result('Exact unknown error with raw-uuid.', { unrecognized: { native: 'keep me' } }), isError: true });
929
+ assert.match(paint(unknownSubagent), /✗ Failed · Launch failed/); assert.match(paint(unknownSubagent), /Exact unknown error with raw-uuid/);
930
+ const unknownInspection = []; pi.events.emit('compact-renderer:inspect:v1', { add: item => unknownInspection.push(item) });
931
+ unknownInspection.find(item => item.label === 'Subagent · launch · ✗ Failed · Launch failed').focus();
932
+ input('\t'); input('\r');
933
+ assert.match(paint(unknownSubagent), /Metadata/); assert.match(paint(unknownSubagent), /keep me/, 'unknown native fields remain accessible in Details');
934
+ input('\x1b');
935
+ unknownSubagent.setExpanded(false);
936
+ // Import only installed presentation functions; never initialize extension execution/watchers or launch an agent.
937
+ const subagentRenderFile = path.join(runtime, 'node_modules/pi-subagents/src/tui/render.js');
938
+ if (existsSync(subagentRenderFile)) {
939
+ const { renderSubagentResult, renderSubagentSummary } = await import(pathToFileURL(subagentRenderFile));
940
+ const fixture = result('stock subagent fixture output', { mode: 'single', results: [] });
941
+ for (const renderResult of [renderSubagentResult, renderSubagentSummary]) {
942
+ const installedRenderer = { renderResult };
943
+ toggle(false);
944
+ const original = new ToolExecutionComponent('subagent', 'native-original', { agent: 'fixture' }, { showImages: false }, installedRenderer, { requestRender() {} }, '/synthetic-tools');
945
+ const exempted = new ToolExecutionComponent('subagent', `native-wrapped-${renderResult.name}`, { agent: 'fixture' }, { showImages: false }, resolver('subagent', () => installedRenderer), { requestRender() {} }, '/synthetic-tools');
946
+ for (const expanded of [false, true]) {
947
+ original.updateResult(fixture); original.setExpanded(expanded);
948
+ exempted.updateResult(fixture); exempted.setExpanded(expanded);
949
+ assert.deepEqual(exempted.render(120), original.render(120));
950
+ assert.doesNotMatch(paint(exempted), /successful action/);
951
+ toggle(true);
952
+ assert.match(paint(exempted), /Subagent · launch · fixture · Result recorded/);
953
+ assertNeutral(exempted.render(120));
954
+ toggle(false);
955
+ }
956
+ }
957
+ toggle(true);
958
+ } else console.log('installed pi-subagents presentation check skipped: package unavailable');
959
+ disposeProjection();
960
+ if (process.env.PI_CARD_EVIDENCE_PATH) writeFileSync(process.env.PI_CARD_EVIDENCE_PATH, JSON.stringify({ runtime, evidence }, null, 2) + '\n');
961
+ console.log('modern tools: native lifecycle, grouping, questions, focus and bounded output passed');