@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,388 @@
1
+ import assert from 'node:assert/strict';
2
+ import { deflateSync } from 'node:zlib';
3
+ import { loadSource, loadAgent, themeModule, stripAnsi, tui, backgroundCells } from './test-runtime.mjs';
4
+ const { registerModernTools, toolStatus } = await loadSource('./modern-tools.ts');
5
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
6
+ const { CodePane } = await loadSource('./modern-code-pane.ts');
7
+ const { WorkChild } = await loadSource('./work-strip-view.ts');
8
+ const stylePane = new CodePane(() => 12);
9
+ stylePane.heading = 'codemode · Read files';
10
+ stylePane.title = `${stylePane.heading} · 2 nested calls · 1 nested error`;
11
+ stylePane.theme = Object.assign(Object.create(themeModule.theme), { bold: text => `\x1b[1m${text}\x1b[22m` });
12
+ stylePane.tone = 'warning';
13
+ assert.doesNotMatch(stylePane.render(100)[0], /\x1b\[1m/, 'codemode category and intent use normal weight beside a warning');
14
+ assert.ok(stylePane.render(100)[0].includes(themeModule.theme.fg('syntaxVariable', '▸ codemode')), 'only codemode category retains teal');
15
+ assert.ok(stylePane.render(100)[0].includes(themeModule.theme.fg('muted', ' · Read files')), 'codemode intent uses muted text');
16
+ assert.ok(stylePane.render(100)[0].includes(themeModule.theme.fg('warning', ' · 1 nested error')), 'nested warning keeps its distinct color');
17
+ stylePane.tone = 'error'; assert.match(stylePane.render(100)[0], /\x1b\[1m/, 'failed codemode retains its weight');
18
+ const { ToolExecutionComponent } = await loadAgent('modes/interactive/components/tool-execution.js');
19
+ const { installModernToolImages } = await loadSource('./modern-tool-images.ts');
20
+ const { codemodeRenderers } = await loadAgent('extensions/codemode/renderer.js');
21
+ const { readRenderers } = await loadAgent('core/tools/renderers/read.js');
22
+ const hooks = new Map(), bus = new Map(); let resolver, input;
23
+ const pi = {
24
+ registerToolRenderer(fn) { resolver = fn; },
25
+ on(event, fn) { const set = hooks.get(event) || new Set(); set.add(fn); hooks.set(event, set); return () => set.delete(fn); },
26
+ events: { on(name, fn) { bus.set(name, fn); return () => bus.delete(name); }, emit(name, data) { bus.get(name)?.(data); } },
27
+ };
28
+ const originalToolRender=ToolExecutionComponent.prototype.render;
29
+ assert.equal(installModernToolImages('1.3.1'),undefined,'unknown native versions do not install the private image seam');
30
+ assert.equal(ToolExecutionComponent.prototype.render,originalToolRender);
31
+ const mode = createDisplayMode(), dispose = registerModernTools(pi, mode);
32
+ const ctx = { hasUI: true, sessionManager: { getBranch: () => [] }, ui: { onTerminalInput(fn) { input = fn; return () => { input = undefined; }; } } };
33
+ const event = (name, data = {}) => { for (const fn of hooks.get(name) || []) fn(data, ctx); };
34
+ const create = (name, id, args, native) => {
35
+ const component = new ToolExecutionComponent(name, id, args, { showImages: false, outputPad: 0 }, resolver(name, () => native), { requestRender() {} }, '/tmp'); component.setArgsComplete(); return component;
36
+ };
37
+ const result = text => ({ content: [{ type: 'text', text }] });
38
+ const paint = component => stripAnsi(component.render(140).join('\n'));
39
+ const mouse = (component, type, y, wheelDelta) => component.handleMouse({ type, button: type === 'wheel' ? 'none' : 'left', x: 2, y, screenX: 2, screenY: y, width: 140, height: component.render(140).length, shift: false, alt: false, ctrl: false, wheelDelta });
40
+ // Valid grayscale PNGs exercise native dimension parsing and protocol encoding.
41
+ const pngFixture = (width, height) => {
42
+ const chunk = (name, data) => {
43
+ const type = Buffer.from(name), crcData = Buffer.concat([type,data]);let crc=0xffffffff;
44
+ for(const byte of crcData){crc^=byte;for(let bit=0;bit<8;bit++)crc=(crc>>>1)^((crc&1)?0xedb88320:0);}
45
+ const size=Buffer.alloc(4), checksum=Buffer.alloc(4);size.writeUInt32BE(data.length);checksum.writeUInt32BE((crc^0xffffffff)>>>0);
46
+ return Buffer.concat([size,type,data,checksum]);
47
+ };
48
+ const header=Buffer.alloc(13);header.writeUInt32BE(width);header.writeUInt32BE(height,4);header[8]=8;
49
+ return Buffer.concat([Buffer.from('89504e470d0a1a0a','hex'),chunk('IHDR',header),chunk('IDAT',deflateSync(Buffer.alloc((width+1)*height))),chunk('IEND',Buffer.alloc(0))]).toString('base64');
50
+ };
51
+ const kittySize = line => {
52
+ const fields=Object.fromEntries(line.match(/\x1b_G([^;]+);/)[1].split(',').map(field=>field.split('=')));
53
+ return {columns:Number(fields.c),rows:Number(fields.r)};
54
+ };
55
+ event('session_start');
56
+ try {
57
+ assert.notEqual(resolver('codemode', () => codemodeRenderers), codemodeRenderers, 'code gets its own compact wrapper');
58
+ const first = create('read', 'before-code', { path: '/fixture/before' }, readRenderers); first.updateResult(result('first'));
59
+ event('message_end', { message: { role: 'assistant', content: [{ type: 'toolCall', id: 'code', name: 'codemode', arguments: { code: 'text(1);' } }] } });
60
+ const code = create('codemode', 'code', { code: 'const value = await tools.read({path: "/fixture"});\ntext(value);' }, codemodeRenderers);
61
+ const originalSetInterval = globalThis.setInterval, originalClearInterval = globalThis.clearInterval, intervals = new Set();
62
+ globalThis.setInterval = (...args) => { const handle = originalSetInterval(...args); intervals.add(handle); return handle; };
63
+ globalThis.clearInterval = handle => { intervals.delete(handle); return originalClearInterval(handle); };
64
+ try {
65
+ code.markExecutionStarted();
66
+ code.updateResult({ ...result(''), details: { calls: [{ name: 'read', args: '/fixture', status: 'running' }] } }, true);
67
+ assert.equal(intervals.size, 1, 'collapsed execution retains one native timer');
68
+ assert.match(paint(code), /▸ codemode · … Running · Read files · 1 nested call/);
69
+ assert.equal(code.render(100).length, 2, 'native spacer plus one compact summary');
70
+ assert.ok(code.render(100)[1].includes(themeModule.theme.getFgAnsi('syntaxVariable')), 'running codemode label uses native teal');
71
+ assert.ok(code.render(100)[1].includes(themeModule.theme.getFgAnsi('muted')), 'counts and timing are secondary');
72
+ assert.ok(backgroundCells(code.render(100)[1]).every(value => value === ''), 'running codemode leaves the terminal surface clear');
73
+ assert.doesNotMatch(paint(code), /const value|… read/);
74
+ mouse(code, 'click', 1);
75
+ assert.match(paint(code), /const value/); assert.match(paint(code), /… read/);
76
+ assert.equal(input('\r'), undefined, 'mouse does not take editor focus');
77
+ mouse(code, 'click', 1);
78
+ const final = { durationMs: 750, content: [{ type: 'text', text: 'Script completed\nWall time 0.75 seconds\nOutput:\n' }, { type: 'text', text: 'Recorded script output' }], details: { calls: [{ name: 'read', args: '/fixture', status: 'ok', durationMs: 250 }, { name: 'model', args: 'fixture', status: 'error', durationMs: 500, cost: 0.02, error: 'Recorded nested failure' }] } };
79
+ const before = JSON.stringify(final);
80
+ code.updateResult(final);
81
+ assert.equal(intervals.size, 0, 'native completion stops its timer');
82
+ assert.match(paint(code), /▸ codemode · .+ · 2 nested calls · 1 nested error · 0.75s/);
83
+ assert.doesNotMatch(paint(code), /✓|Completed/, 'successful code-mode summary omits redundant status');
84
+ assert.doesNotMatch(paint(code), /✗ Failed|Recorded script output|Recorded nested failure/);
85
+ assert.equal(toolStatus('codemode', final).status, 'success', 'handled nested errors do not fail the script');
86
+ const header = code.render(140).find(row => stripAnsi(row).includes('nested error'));
87
+ assert.ok(header.includes(themeModule.theme.getFgAnsi('syntaxVariable')), 'handled nested failure retains codemode category');
88
+ assert.ok(header.includes(themeModule.theme.getFgAnsi('muted')), 'normal counts stay muted beside warning');
89
+ assert.ok(header.includes(themeModule.theme.getFgAnsi('warning')), 'nested failure warns on a completed script');
90
+ assert.ok(backgroundCells(header).every(value => value === ''), 'collapsed summary uses neutral terminal surface');
91
+ code.setExpanded(true);
92
+ const pane = code.callRendererComponent.owner.code;
93
+ assert.equal(pane.content.supported, true);
94
+ assert.ok(code.render(140).some(row => row.includes(themeModule.theme.getFgAnsi('syntaxKeyword'))), 'native keyword colors remain');
95
+ let visible = paint(code);
96
+ assert.doesNotMatch(visible, /^\s*codemode\s*$/m, 'outer summary is the only codemode heading');
97
+ for (let index = 0; index < 12; index++) { mouse(code, 'wheel', 2, 2); visible += '\n' + paint(code); }
98
+ for (const pattern of [/const value/, /✓ read/, /250ms/, /✗ model/, /500ms/, /\$0\.02/, /Recorded nested failure/, /Recorded script output/, /0\.75s/]) assert.match(visible, pattern);
99
+ assert.doesNotMatch(visible, /arguments\.code|successful action/);
100
+ assert.equal(JSON.stringify(final), before, 'rendering leaves stored transcript exact');
101
+ const choices = []; pi.events.emit('compact-renderer:inspect:v1', { add: entry => choices.push(entry) });
102
+ const choice = choices.find(entry => entry.label.startsWith('codemode')); assert.ok(choice); choice.focus();
103
+ assert.match(paint(code), /focused/);
104
+ const focused = code.render(100).find(row => stripAnsi(row).includes('codemode'));
105
+ assert.ok(focused.includes(themeModule.theme.getBgAnsi('selectedBg')), 'inspection visibly selects header');
106
+ assert.equal(input('\x1b[A').consume, true); assert.equal(pane.offset >= 0, true);
107
+ assert.equal(input('\x1b').consume, true); assert.doesNotMatch(paint(code), /focused/);
108
+ choice.focus(); assert.equal(input('x'), undefined); assert.doesNotMatch(paint(code), /focused/); assert.equal(input('\r'), undefined, 'typing releases inspection before next Enter');
109
+ code.setExpanded(false); assert.doesNotMatch(paint(code), /Recorded script output/);
110
+ code.setExpanded(true); assert.match(paint(code), /const value/, 'native Ctrl+O expansion sync opens native details');
111
+ mode.setEnabled(false);
112
+ assert.match(paint(code), /Recorded script output/); assert.equal(code.callRendererComponent.constructor.name, 'Box');
113
+ mode.setEnabled(true); code.setExpanded(false); assert.equal(code.render(100).length, 2);
114
+ const failed = { ...final, isError: true }; code.updateResult(failed); assert.match(paint(code), /✗ Failed · .+ · 2 nested calls · 1 nested error/);
115
+ assert.ok(code.render(100)[1].includes(themeModule.theme.getFgAnsi('error')), 'failed codemode summary uses native red');
116
+ code.updateResult(final);
117
+ code.updateArgs({ code: Array.from({ length: 100 }, (_, index) => `text(${index});`).join('\n') });
118
+ code.setExpanded(true);
119
+ for (const width of [1, 8, 40, 100]) {
120
+ const rows = code.render(width); assert.ok(rows.length <= 21, 'expanded native content has bounded viewport');
121
+ for (const row of rows) assert.ok(tui.visibleWidth(row) <= width);
122
+ }
123
+ assert.match(paint(code), /text\(0\)/);
124
+ // Exercise native container routing, including the work group's horizontal inset.
125
+ const workChild = new WorkChild(code), work = new tui.Container();
126
+ work.addChild(new tui.Text('Work fixture', 0, 0)); work.addChild(workChild);
127
+ const moreRows = work.render(140).map(stripAnsi), moreY = moreRows.findIndex(row => row.includes('more ↓'));
128
+ assert.ok(moreY > 1); const moreX = moreRows[moreY].indexOf('more ↓'); assert.ok(moreX >= 3);
129
+ const beforeMore = pane.offset;
130
+ assert.equal(work.handleMouse({ type: 'click', button: 'left', x: moreX, y: moreY, screenX: moreX, screenY: moreY, width: 140, height: moreRows.length })?.handled, true);
131
+ const afterMore = work.render(140).map(stripAnsi).join('\n');
132
+ assert.ok(pane.offset > beforeMore, 'clicking overflow advances the rendered codemode viewport');
133
+ assert.ok(pane.offset - beforeMore <= 20, 'one click advances at most one bounded viewport');
134
+ assert.doesNotMatch(afterMore, /text\(0\)/); assert.equal(input('\r'), undefined, 'overflow click leaves Enter with the editor');
135
+ const focusedMore = []; pi.events.emit('compact-renderer:inspect:v1', { add: entry => focusedMore.push(entry) });
136
+ focusedMore.find(entry => entry.label.startsWith('codemode')).focus();
137
+ const rows = code.render(140).map(stripAnsi), footerY = rows.findIndex(row => row.includes('more ↓'));
138
+ assert.ok(footerY > 0); mouse(code, 'click', footerY);
139
+ assert.doesNotMatch(paint(code), /focused/); assert.equal(input('\r'), undefined, 'overflow click releases inspection');
140
+ for (let index = 0; index < 120; index++) { mouse(code, 'wheel', 2, 20); code.render(140); }
141
+ assert.match(paint(code), /Recorded script output/, 'bounded viewport can reach full native output');
142
+ assert.doesNotMatch(paint(code), /more ↓/, 'codemode stops offering downward paging at its final rows');
143
+ const endRows = code.render(140).map(stripAnsi), endOffset = pane.offset;
144
+ assert.match(endRows.at(-1), /more ↑/, 'the final footer retains its hit area');
145
+ mouse(code, 'click', endRows.length - 1); code.render(140);
146
+ assert.ok(pane.offset < endOffset, 'the upward footer pages back through the output');
147
+ assert.equal(code.render(140).length, endRows.length, 'paging back keeps the pane height');
148
+ assert.equal(JSON.stringify(final), before);
149
+ const running = create('codemode', 'code-clear', { code: 'text(1);' }, codemodeRenderers); running.markExecutionStarted(); running.updateResult({ ...result(''), details: { calls: [] } }, true);
150
+ assert.equal(intervals.size, 1); event('session_before_switch'); assert.equal(intervals.size, 0, 'session switch clears native owned timer');
151
+ running.invalidate(); assert.equal(intervals.size, 0, 'stale renderer cannot restart owned timer'); event('session_start');
152
+ } finally { for (const handle of intervals) originalClearInterval(handle); globalThis.setInterval = originalSetInterval; globalThis.clearInterval = originalClearInterval; }
153
+ // Giant fixtures count actual formatted characters/calls, separately from revision aggregation.
154
+ const hugeScript = 'const paths = ["/fixture/a", "/fixture/b"];\n'.repeat(250000);
155
+ const hugeOutput = 'stdout value 中文🙂 '.repeat(400000);
156
+ const hugeCalls = Array.from({length: 20000}, (_, index) => ({name:'read',args:`/fixture/${index}`,status:'ok',durationMs:1}));
157
+ Object.defineProperty(hugeCalls[19999], 'irrelevant', {get(){throw new Error('unused metadata getter must not be visited');}});
158
+ const huge = create('codemode', 'bounded-giant', {code:hugeScript}, codemodeRenderers);
159
+ const hugeResult = {content:[{type:'text',text:hugeOutput}],details:{calls:hugeCalls},durationMs:81234};
160
+ huge.updateResult(hugeResult);
161
+ const giantPane = huge.callRendererComponent.owner.code;
162
+ assert.equal(giantPane.content.sourceCharacters,0,'collapsed construction/update formats zero source characters');
163
+ assert.equal(giantPane.content.paintedCalls,0,'collapsed construction/update formats zero nested calls');
164
+ assert.equal(giantPane.content.aggregateEntries,20000,'one aggregate pass for the result revision');
165
+ for(let i=0;i<3;i++){huge.invalidate();huge.render(100);}
166
+ assert.equal(giantPane.content.aggregateEntries,20000,'redraw/invalidation does not rescan nested-call aggregate');
167
+ huge.setExpanded(true);huge.render(100);
168
+ assert.ok(giantPane.content.sourceCharacters<=2048,'first viewport formats only bounded source chunks, not the 10 MB script');
169
+ assert.equal(giantPane.content.paintedCalls,0,'viewport does not visit later nested calls');
170
+ const initialCharacters=giantPane.content.sourceCharacters;
171
+ huge.render(100);huge.render(100);assert.equal(giantPane.content.sourceCharacters,initialCharacters,'repeated paint uses visited row cache');
172
+ huge.invalidate();huge.render(100);assert.equal(giantPane.content.sourceCharacters,initialCharacters,'unchanged native invalidation preserves body cache');
173
+ const beforeAggregate=giantPane.content.aggregateEntries;
174
+ hugeCalls[0].status='error';hugeCalls[0].error='in-place recorded error';
175
+ event('tool_execution_update',{toolCallId:'bounded-giant',toolName:'codemode',args:{code:hugeScript},partialResult:hugeResult});
176
+ huge.updateResult(hugeResult,true);
177
+ assert.equal(giantPane.content.errors,1,'explicit update revision detects in-place status mutation');
178
+ assert.equal(giantPane.content.aggregateEntries-beforeAggregate,20000,'in-place update aggregates once, not once per renderer slot');
179
+ hugeCalls.push({name:'read',args:'/fixture/new',status:'cancelled'});
180
+ event('tool_execution_update',{toolCallId:'bounded-giant',toolName:'codemode',args:{code:hugeScript},partialResult:hugeResult});huge.updateResult(hugeResult,true);
181
+ assert.equal(giantPane.content.calls.length,20001);assert.equal(giantPane.content.cancelled,1,'same array identity can gain a cancelled call');
182
+ huge.updateResult(hugeResult); // No execution start, so this synthetic partial replay owns no clock.
183
+ const stdoutOnly=create('codemode','bounded-stdout',{code:''},codemodeRenderers);stdoutOnly.updateResult({content:[{type:'text',text:hugeOutput}],details:{calls:[]}});stdoutOnly.setExpanded(true);stdoutOnly.render(100);
184
+ assert.ok(stdoutOnly.callRendererComponent.owner.code.content.sourceCharacters<=2048,'giant stdout has bounded formatting');
185
+ const hugeError=create('codemode','bounded-nested-error',{code:'text(1);'},codemodeRenderers);
186
+ hugeError.updateResult({content:[],details:{calls:[{name:'read',args:'/fixture',status:'error',error:'recorded error '.repeat(500000)}]}});hugeError.setExpanded(true);hugeError.render(100);
187
+ assert.ok(hugeError.callRendererComponent.owner.code.content.sourceCharacters<=4096,'giant nested errors are chunked too');
188
+ const tailCalls=Array.from({length:80},(_,index)=>({name:'read',args:`tail-call-${index}`,status:'ok'}));
189
+ const tailRecord={content:[{type:'text',text:'tail-output-start\n'+('recorded output row\n'.repeat(70))+'LAST-OUTPUT🙂'}],details:{calls:tailCalls,fullOutputPath:'/fixture/exact-full-output.log'}};
190
+ const tailBefore=JSON.stringify(tailRecord);
191
+ const tail=create('codemode','bounded-tail',{code:('const value = 1;\n'.repeat(80))+'// LAST-SOURCE🙂'},codemodeRenderers);tail.updateResult(tailRecord);tail.setExpanded(true);
192
+ const tailPane=tail.callRendererComponent.owner.code;let visited=paint(tail);
193
+ for(let i=0;i<100;i++){tailPane.offset+=10;visited+='\n'+paint(tail);}
194
+ for(const text of ['LAST-SOURCE🙂','tail-call-79','LAST-OUTPUT🙂','/fixture/exact-full-output.log'])assert.ok(visited.includes(text),`all recorded sections remain reachable: ${text}`);
195
+ assert.equal(JSON.stringify(tailRecord),tailBefore,'full traversal leaves original record unchanged');
196
+ const safe=create('codemode','bounded-unicode',{code:'const 中文 = "🙂";\n// \u202e'},codemodeRenderers);safe.updateResult(result('exact\x1b[31m\u202e\u0000end'));safe.setExpanded(true);
197
+ const safeText=paint(safe);assert.match(safeText,/\\u001b\[31m\\u202e\\u0000end/);assert.doesNotMatch(safeText,/\u202e/);
198
+ for(const width of [1,2,8,40])for(const line of safe.render(width))assert.ok(tui.visibleWidth(line)<=width);
199
+ const replay=create('codemode','bounded-duration-replay',{code:''},codemodeRenderers);replay.updateResult({content:[{type:'text',text:'Script completed\nWall time 73.25 seconds\nOutput:\n'},{type:'text',text:'replay output'}],details:{calls:[]}});replay.setExpanded(true);
200
+ assert.match(paint(replay),/Wall time 73.25 seconds/,'replay without duration keeps its recorded envelope');
201
+ replay.updateResult({...result('replay output'),durationMs:73250});assert.match(paint(replay),/73\.25s/,'recorded duration remains in the heading');assert.doesNotMatch(paint(replay),/Took /,'recorded duration is not repeated below');assert.match(stripAnsi(replay.render(24).join('\n')),/Took 1m 13s/,'a clipped heading retains duration in the footer');
202
+ const themeFixture=create('codemode','bounded-theme',{code:'const themeValue = 1;'},codemodeRenderers);themeFixture.updateResult(result('theme output'));themeFixture.setExpanded(true);themeFixture.render(140);
203
+ const themePane=themeFixture.callRendererComponent.owner.code, themed=themePane.content.sourceCharacters;
204
+ const activeTheme=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")], originalFg=activeTheme.fg;
205
+ try{
206
+ activeTheme.fg=function(token,text){return ['toolOutput','syntaxKeyword'].includes(token)?'\x1b[38;5;201m'+text+'\x1b[39m':originalFg.call(this,token,text);};
207
+ themeFixture.invalidate();assert.ok(themeFixture.render(140).some(row=>row.includes('\x1b[38;5;201m')),'theme mutation invalidates cached ANSI');
208
+ assert.ok(themePane.content.sourceCharacters>themed);
209
+ }finally{activeTheme.fg=originalFg;themeFixture.invalidate();}
210
+ const emptyBlocks=Array.from({length:100000},()=>({type:'text',text:''}));emptyBlocks.push({type:'text',text:'nonempty tail output'});
211
+ const empties=create('codemode','bounded-empty-blocks',{code:''},codemodeRenderers);empties.updateResult({content:emptyBlocks,details:{calls:[]}});
212
+ const emptyPane=empties.callRendererComponent.owner.code;
213
+ assert.equal(emptyPane.content.aggregateBlocks,100001,'empty block indexing is once-per-update work');
214
+ empties.setExpanded(true);assert.match(paint(empties),/nonempty tail output/);
215
+ assert.equal(emptyPane.content.aggregateBlocks,100001,'paint does not rescan empty output blocks');
216
+ assert.ok(emptyPane.content.sourceCharacters<100,'only the visible nonempty output is formatted');
217
+ // Compact images follow their pane; native Pi keeps image ownership and sources.
218
+ const png='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=';
219
+ const imageRecord={content:[{type:'text',text:'Script completed\nWall time 0.75 seconds\nOutput:\n'},...Array.from({length:3},()=>({type:'image',mimeType:'image/png',data:png})),{type:'text',text:'Image saved to /var/tmp/pi-codemode-fixture.png\n'+hugeOutput}],details:{calls:[{name:'read',args:'/fixture/image.png',status:'ok'},{name:'read',args:'/fixture/record.json',status:'ok'}]}};
220
+ const imageSnapshot=JSON.stringify(imageRecord);
221
+ const imageCode=create('codemode','bounded-images',{code:'const images = await tools.read({path:"/fixture/image.png"});\ntext(images);'},codemodeRenderers);imageCode.updateResult(imageRecord);
222
+ assert.match(paint(imageCode),/▸ codemode.*3 images/);
223
+ assert.equal(imageCode.render(100).length,2,'image-bearing code has one collapsed text heading');
224
+ assert.doesNotMatch(paint(imageCode),/Image saved|const images|image\/png/);
225
+ const imagePane=imageCode.callRendererComponent.owner.code;
226
+ assert.equal(imagePane.content.sourceCharacters,0,'collapsed images do not format script or giant JSON output');
227
+ const imageChoices=[];pi.events.emit('compact-renderer:inspect:v1',{add:choice=>imageChoices.push(choice)});
228
+ assert.ok(imageChoices.some(choice=>choice.label.includes('3 images')),'image-bearing code remains inspectable');
229
+ imageCode.setExpanded(true);
230
+ assert.doesNotMatch(paint(imageCode),/Recorded image:/,'image placeholders do not repeat the heading count');
231
+ assert.ok(imageCode.render(100).length<=22,'expanded text and unavailable-preview fallback stay bounded');
232
+ assert.ok(imagePane.content.sourceCharacters<=4096,'images do not bypass bounded formatting');
233
+ for(const width of [1,8,40])for(const row of imageCode.render(width))assert.ok(tui.visibleWidth(row)<=width);
234
+ assert.equal(JSON.stringify(imageRecord),imageSnapshot,'image and text records remain exact');
235
+ const savedCapabilities=tui.getCapabilities();
236
+ try {
237
+ tui.setCapabilities({...savedCapabilities,images:'kitty'});
238
+ imageCode.setShowImages(true);imageCode.setExpanded(false);
239
+ assert.equal(imageCode.imageComponents.length,3,'native Pi retains all image components outside the text pane');
240
+ const nativeImages=[...imageCode.imageComponents];
241
+ assert.deepEqual(imageCode.imageSources.map(source=>source.data),[png,png,png]);
242
+ assert.ok(!imageCode.render(100).some(row=>row.includes('\x1b_G')),'collapsed compact code emits no image protocol');
243
+ imageCode.setExpanded(true);
244
+ assert.equal(imageCode.render(100).filter(row=>row.includes('\x1b_G')).length,3,'expanded code renders all native inline images');
245
+ assert.ok(imageCode.render(100).filter(row=>row.includes('\x1b_G')).every(row=>row.startsWith(' \x1b_G')),'codemode images align with its indented expanded body');
246
+ mouse(imageCode,'click',1);assert.ok(!imageCode.render(100).some(row=>row.includes('\x1b_G')),'mouse collapse hides every image');
247
+ const imageInspection=[];pi.events.emit('compact-renderer:inspect:v1',{add:choice=>imageInspection.push(choice)});
248
+ imageInspection.find(choice=>choice.label.includes('3 images')).focus();
249
+ assert.equal(imageCode.render(100).filter(row=>row.includes('\x1b_G')).length,3,'inspection expansion renders images');
250
+ input('\r');assert.ok(!imageCode.render(100).some(row=>row.includes('\x1b_G')),'inspection Enter collapse hides images');input('\x1b');
251
+ const readRecord={content:[{type:'text',text:'Exact native image-read output'},{type:'image',mimeType:'image/png',data:png}]};
252
+ const protocolRead=create('read','protocol-image-read',{path:'/fixture/protocol-image.png'},readRenderers);protocolRead.setShowImages(true);protocolRead.updateResult(readRecord);
253
+ assert.equal(protocolRead.imageComponents.length,1,'individual image reads retain native image ownership');
254
+ assert.ok(!protocolRead.render(100).some(row=>row.includes('\x1b_G')),'collapsed direct read emits no image protocol');
255
+ protocolRead.setExpanded(true);assert.ok(protocolRead.render(100).some(row=>row.includes('\x1b_G')),'expanded direct read renders a native image');
256
+ const readRows=protocolRead.render(100), imageRow=readRows.find(row=>row.includes('\x1b_G'));
257
+ const outputIndent=stripAnsi(readRows.find(row=>row.includes('Exact native image-read output'))).match(/^ */)[0];
258
+ const detailsIndent=stripAnsi(readRows.find(row=>row.includes('▸ Details'))).match(/^ */)[0];
259
+ assert.equal(imageRow.slice(0,imageRow.indexOf('\x1b_G')),outputIndent,'image aligns with expanded read text');
260
+ assert.equal(outputIndent,detailsIndent,'image and Details share the expanded content column');
261
+ protocolRead.setExpanded(false);assert.ok(!protocolRead.render(100).some(row=>row.includes('\x1b_G')),'native collapse hides a direct read image');
262
+ assert.equal(paint(protocolRead).split('\n').filter(row=>row.includes('read · /fixture/protocol-image.png')).length,1);
263
+ imageCode.setExpanded(true);imageCode.render(100);imageCode.invalidate();
264
+ assert.deepEqual(imageCode.imageComponents,nativeImages,'expansion and redraw reuse native images');
265
+ const savedCells=tui.getCellDimensions();
266
+ try {
267
+ tui.setCellDimensions({widthPx:9,heightPx:18});
268
+ for(const [widthPx,heightPx] of [[640,320],[320,1600]]){
269
+ const sized=create('read',`sized-${widthPx}`,{path:`/fixture/${widthPx}.png`},readRenderers);
270
+ sized.setShowImages(true);sized.updateResult({content:[{type:'image',mimeType:'image/png',data:pngFixture(widthPx,heightPx)}]});sized.setExpanded(true);
271
+ const image=sized.imageComponents[0],options=image.options;
272
+ assert.deepEqual(image.dimensions,{widthPx,heightPx});
273
+ for(const width of [1,8,40,100]){
274
+ const line=sized.render(width).find(row=>row.includes('\x1b_G')),size=kittySize(line);
275
+ assert.ok(size.columns>=1&&size.columns<=Math.min(60,Math.max(1,width-2)),'inline preview respects terminal width and 60-column limit');
276
+ assert.ok(size.rows>=1&&size.rows<=12,'inline preview respects 12-row height limit');
277
+ assert.ok(line.indexOf('\x1b_G')+size.columns<=width,'image and left indent fit the terminal together');
278
+ assert.equal(image.options,options,'temporary compact dimensions never leak into native options');
279
+ }
280
+ sized.setImageWidthCells(18);assert.ok(kittySize(sized.render(100).find(row=>row.includes('\x1b_G'))).columns<=18,'native configured image width stays authoritative');
281
+ const nativeImage=sized.imageComponents[0],nativeImageRender=nativeImage.render,nativeImageOptions=nativeImage.options;
282
+ try{
283
+ nativeImage.render=()=>{throw new Error('fixture image render failure');};
284
+ assert.throws(()=>sized.render(100),/fixture image render failure/);
285
+ assert.equal(nativeImage.options,nativeImageOptions,'image render failure restores native options');
286
+ assert.equal(sized.imageComponents[0],nativeImage,'image render failure restores native image ownership');
287
+ }finally{nativeImage.render=nativeImageRender;}
288
+ sized.setImageWidthCells(60);sized.render(100);mode.setEnabled(false);
289
+ const nativeRows=sized.imageComponents[0].render(100),stockSize=kittySize(nativeRows.find(row=>row.includes('\x1b_G')));
290
+ assert.ok(stockSize.rows>12,'native render does not reuse compact height cache');
291
+ assert.ok(sized.render(100).some(row=>row.includes('\x1b_G')),'native mode keeps image protocol output');
292
+ mode.setEnabled(true);
293
+ }
294
+ } finally {tui.setCellDimensions(savedCells);}
295
+ for(const Screen of [tui.TuiMainScreen,tui.TuiAltScreen]){
296
+ const writes=[];
297
+ const terminal={columns:100,rows:50,kittyProtocolActive:false,start(){},stop(){},write(value){writes.push(value);},hideCursor(){},showCursor(){},clearLine(){},clearFromCursor(){},clearScreen(){},moveBy(){},setTitle(){},setProgress(){},setProgramStatus(){}};
298
+ const screen=new Screen(terminal,false,undefined,{mouse:false});
299
+ protocolRead.setExpanded(true);screen.addChild(protocolRead);
300
+ try{
301
+ screen.start();screen.renderNow();assert.ok(writes.join('').includes('\x1b_G'),'native TUI emits expanded image protocol');
302
+ writes.length=0;protocolRead.setExpanded(false);screen.renderNow();
303
+ assert.match(writes.join(''),/\x1b_Ga=d,d=[IaA]/,'native TUI removes image placements after collapse');
304
+ }finally{screen.stop();}
305
+ }
306
+ mode.setEnabled(false);
307
+ const original=new ToolExecutionComponent('codemode','original-images',imageCode.args,{showImages:true,outputPad:0},codemodeRenderers,{requestRender(){}},'/tmp');original.setArgsComplete();original.updateResult(imageRecord);original.setExpanded(true);
308
+ // Image IDs differ by owner; compare the exact native text surface and image sources.
309
+ assert.deepEqual(imageCode.selfRenderContainer.render(100),original.contentBox.render(100),'native-off code text stays stock');
310
+ assert.deepEqual(imageCode.imageSources,original.imageSources,'native-off image sources stay stock');
311
+ const originalRead=new ToolExecutionComponent('read','original-read-images',protocolRead.args,{showImages:true,outputPad:0},readRenderers,{requestRender(){}},'/tmp');originalRead.setArgsComplete();originalRead.updateResult(readRecord);
312
+ for(const expanded of [false,true]){
313
+ protocolRead.setExpanded(expanded);originalRead.setExpanded(expanded);
314
+ assert.deepEqual(protocolRead.selfRenderContainer.render(100),originalRead.contentBox.render(100),'native-off image read text stays stock');
315
+ assert.deepEqual(protocolRead.imageSources,originalRead.imageSources,'native-off image read sources stay stock');
316
+ }
317
+ mode.setEnabled(true);imageCode.setExpanded(false);
318
+ imageCode.setShowImages(false);assert.equal(imageCode.imageComponents.length,0,'native showImages preference stays authoritative');
319
+ imageCode.setExpanded(true);assert.match(paint(imageCode),/Inline preview unavailable: images are disabled/);
320
+ assert.doesNotMatch(paint(imageCode),/file:\/\//,'codemode fallback does not invent a source link');
321
+ tui.setCapabilities({...savedCapabilities,images:null});imageCode.setShowImages(true);
322
+ assert.equal(imageCode.imageComponents.length,0,'unsupported transport does not get synthetic image support');
323
+ assert.match(paint(imageCode),/3 images/,'summary still identifies recorded images without transport support');
324
+ assert.match(paint(imageCode),/Inline preview unavailable: terminal has no image protocol/);
325
+ protocolRead.setExpanded(true);assert.match(paint(protocolRead),/protocol-image\.png/);
326
+ tui.setCapabilities({...savedCapabilities,images:null,hyperlinks:true});
327
+ const fallbackRows=protocolRead.render(140),sourceRow=fallbackRows.find(row=>row.includes('Inline preview unavailable'));
328
+ assert.ok(stripAnsi(sourceRow).startsWith(' '),'fallback stays aligned with expanded content');
329
+ assert.match(sourceRow,/\x1b\]8;;file:\/\/\/fixture\/protocol-image\.png/,'known absolute source uses native OSC 8 support');
330
+ tui.setCapabilities({...savedCapabilities,images:null,hyperlinks:false});assert.ok(!protocolRead.render(140).some(row=>row.includes('\x1b]8;;')),'unsupported hyperlinks remain plain paths');
331
+ protocolRead.setExpanded(false);assert.equal(protocolRead.render(100).length,2,'unsupported collapsed read stays one heading');
332
+ tui.setCapabilities({...savedCapabilities,images:'iterm2'});protocolRead.setShowImages(true);protocolRead.setExpanded(true);
333
+ assert.ok(protocolRead.render(100).some(row=>row.includes('\x1b]1337;File=')),'native iTerm2 protocol remains available');
334
+ assert.ok(protocolRead.render(100).find(row=>row.includes('\x1b]1337;File=')).startsWith(' '),'iTerm2 image anchor retains the expanded indent');
335
+ protocolRead.setExpanded(false);assert.ok(!protocolRead.render(100).some(row=>row.includes('\x1b]1337;File=')),'iTerm2 protocol also follows compact collapse');
336
+ const stockRead=new ToolExecutionComponent('read','unwrapped-native-image',protocolRead.args,{showImages:true,outputPad:0},readRenderers,{requestRender(){}},'/tmp');stockRead.setArgsComplete();stockRead.updateResult(readRecord);
337
+ assert.ok(stockRead.render(100).some(row=>row.includes('\x1b]1337;File=')),'unwrapped stock components keep native collapsed image behavior');
338
+ const absent=create('codemode','absent-image-data',{code:'text("image");'},codemodeRenderers);absent.setShowImages(true);absent.updateResult({content:[{type:'image',mimeType:'image/png',data:''}],details:{calls:[]}});absent.setExpanded(true);
339
+ assert.match(paint(absent),/Inline preview unavailable: image data is unavailable/);
340
+ const unsafe=create('read','unsafe-image-source',{path:'/fixture/unsafe\x1b]8;;evil.png'},readRenderers);unsafe.updateResult(readRecord);unsafe.setExpanded(true);unsafe.setShowImages(false);
341
+ assert.ok(!unsafe.render(140).some(row=>row.includes('\x1b]8;;evil')),'untrusted controls never enter fallback links');
342
+ assert.equal(JSON.stringify(imageRecord),imageSnapshot,'all image controls preserve recorded content and payloads');
343
+ } finally {tui.setCapabilities(savedCapabilities);}
344
+ const beforeImage=create('read','before-image',{path:'/fixture/before-image.txt'},readRenderers);beforeImage.updateResult(result('before image'));
345
+ const imageRead=create('read','individual-image',{path:'/fixture/direct-image.png'},readRenderers);
346
+ const directImageRecord={content:[{type:'text',text:'Exact image read output'},{type:'image',mimeType:'image/png',data:png}]};imageRead.updateResult(directImageRecord,true);
347
+ assert.equal(paint(imageRead).split('\n').filter(row=>row.includes('read · /fixture/direct-image.png')).length,1,'partial image read has one heading');
348
+ assert.match(paint(imageRead),/Running/);imageRead.updateResult(directImageRecord);
349
+ assert.equal(paint(imageRead).split('\n').filter(row=>row.includes('read · /fixture/direct-image.png')).length,1,'individual image read has one heading');
350
+ assert.match(paint(imageRead),/▸ read · \/fixture\/direct-image.png/);
351
+ mouse(imageRead,'click',1);assert.match(paint(imageRead),/Exact image read output/);assert.doesNotMatch(paint(imageRead),/Recorded image:/);
352
+ imageRead.setExpanded(true);imageRead.setExpanded(false);assert.doesNotMatch(paint(imageRead),/Exact image read output/);
353
+ const standardImage=create('read','standard-image',{path:'/fixture/standard.png'},readRenderers);
354
+ const standardRecord={content:[{type:'text',text:'Read image file [image/png]'},{type:'image',mimeType:'image/png',data:png}]};
355
+ const standardSnapshot=JSON.stringify(standardRecord);
356
+ standardImage.updateResult(standardRecord);standardImage.setExpanded(true);
357
+ assert.doesNotMatch(paint(standardImage),/Read image file|Recorded image:/,'standard image announcements do not crowd the preview');
358
+ const standardPane=standardImage.callRendererComponent.owner.pane;
359
+ standardPane.detailsExpanded.add('standard-image');standardPane.reset();
360
+ assert.match(paint(standardImage),/Read image file \[image\/png\]/,'exact native acknowledgement remains in Details');
361
+ assert.equal(JSON.stringify(standardRecord),standardSnapshot,'display cleanup leaves recorded image data unchanged');
362
+ const afterImage=create('read','after-image',{path:'/fixture/after-image.txt'},readRenderers);afterImage.updateResult(result('after image'));
363
+ for(const component of [beforeImage,imageRead,afterImage])assert.doesNotMatch(paint(component),/2 actions|3 actions/,'image reads stay standalone and split adjacent action groups');
364
+ // Other nontext/new native shapes use stock rendering, including both native slots.
365
+ const preFallbackChoices=[];pi.events.emit('compact-renderer:inspect:v1',{add:choice=>preFallbackChoices.push(choice)});
366
+ const image=create('codemode','bounded-image-fallback',{code:'text("image");'},codemodeRenderers);image.updateResult({content:[{type:'image',mimeType:'image/png',data:''},{type:'unknown',text:'future native output'}],details:{calls:[]}});
367
+ assert.doesNotMatch(paint(image),/▸ codemode/,'unsupported nontext result retains native fallback');
368
+ assert.match(paint(image),/image\/png|image/);
369
+ const fallbackChoices=[];pi.events.emit('compact-renderer:inspect:v1',{add:choice=>fallbackChoices.push(choice)});
370
+ assert.equal(fallbackChoices.length,preFallbackChoices.length,'unsupported native fallback is absent from compact inspector');
371
+ image.updateResult(result('supported again'));image.setExpanded(true);
372
+ assert.match(paint(image),/supported again/,'fallback to supported is visible immediately');assert.doesNotMatch(paint(image),/image\/png/);
373
+ image.updateResult({content:[{type:'image',mimeType:'image/png',data:''},{type:'unknown',text:'future native output'}],details:{calls:[]}});assert.match(paint(image),/image/,'supported to native fallback is visible immediately');
374
+ image.updateResult(result('supported again'));
375
+ const restoredChoices=[];pi.events.emit('compact-renderer:inspect:v1',{add:choice=>restoredChoices.push(choice)});
376
+ assert.ok(restoredChoices.length>fallbackChoices.length,'supported result restores compact inspection');
377
+
378
+ const unsupported=create('codemode','bounded-invalid-fallback',{code:42},codemodeRenderers);assert.match(paint(unsupported),/invalid arg/);
379
+ // Replay preserves script boundaries between adjacent successes.
380
+ const replayFirst = create('read', 'replay-before', { path: '/fixture/replay-before' }, readRenderers); replayFirst.updateResult(result('first'));
381
+ event('message_end', { message: { role: 'assistant', content: [{ type: 'toolCall', id: 'replay-code', name: 'codemode', arguments: { code: 'text(1)' } }] } });
382
+ const replayCode = create('codemode', 'replay-code', { code: 'text(1)' }, codemodeRenderers); replayCode.updateResult(result('done'));
383
+ const last = create('read', 'after-code', { path: '/fixture/after' }, readRenderers); last.updateResult(result('last'));
384
+ assert.match(paint(last), /read · \/fixture\/after/); assert.doesNotMatch(paint(last), /2 actions/);
385
+ assert.doesNotMatch(paint(replayCode), /successful action/);
386
+ assert.match(paint(replayFirst), /read · \/fixture\/replay-before/); assert.doesNotMatch(paint(replayFirst), /2 actions/);
387
+ console.log('codemode: collapsed summary, bounded details, native images, single image-read headings, nested outcome, timer, inspection/editor and transcript checks passed');
388
+ } finally { dispose(); assert.equal(ToolExecutionComponent.prototype.render,originalToolRender,'disposing restores the native render method'); }
@@ -0,0 +1,55 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadSharedSource, themeModule } from './test-runtime.mjs';
3
+
4
+ const { DisplayLineCache } = await loadSharedSource('./display-line-cache.ts');
5
+ const { fillBackground } = await loadSharedSource('./display-card.ts');
6
+ const { default: register } = await loadSharedSource('../index.ts');
7
+ const nativeGet = DisplayLineCache.prototype.get;
8
+ let formats = 0;
9
+ DisplayLineCache.prototype.get = function(key, render) {
10
+ return nativeGet.call(this, key, () => {
11
+ if (key.includes('CACHE_PROBE')) formats++;
12
+ return render();
13
+ });
14
+ };
15
+ const probe = () => fillBackground('CACHE_PROBE', 80, themeModule.theme, 'toolPendingBg');
16
+ const expectCold = () => {
17
+ const before = formats, output = probe();
18
+ assert.equal(formats, before + 1, 'the shared display cache was cleared');
19
+ assert.equal(probe(), output);
20
+ assert.equal(formats, before + 1, 'the second render reuses the same cache');
21
+ };
22
+ const hooks = new Map(), bus = new Map();
23
+ const subscribe = (map, event, fn) => {
24
+ const set = map.get(event) || new Set(); set.add(fn); map.set(event, set);
25
+ return () => set.delete(fn);
26
+ };
27
+ const pi = {
28
+ on: (event, fn) => subscribe(hooks, event, fn),
29
+ events: { on: (event, fn) => subscribe(bus, event, fn), emit: (event, data) => {
30
+ for (const fn of [...bus.get(event) || []]) fn(data);
31
+ } },
32
+ registerToolRenderer() {}, registerMarkdownTransformer() {}, registerCommand() {},
33
+ registerShortcut() {}, getCommands: () => [], getAllTools: () => [],
34
+ };
35
+ const ctx = { mode: 'none', hasUI: false, ui: {}, sessionManager: { getBranch: () => [], buildContextEntries: () => [] } };
36
+ const emit = event => { for (const fn of [...hooks.get(event) || []]) fn({}, ctx); };
37
+ try {
38
+ expectCold();
39
+ register(pi);
40
+ expectCold(); // Registration also removes text retained by a previous load.
41
+ for (const event of ['session_start', 'session_tree', 'session_compact', 'session_before_switch', 'session_shutdown']) {
42
+ emit(event); expectCold();
43
+ }
44
+ const before = formats;
45
+ for (const event of ['session_start', 'session_tree', 'session_shutdown']) emit(event);
46
+ probe();
47
+ assert.equal(formats, before, 'disposed root callbacks do not clear a later cache');
48
+ // A registration failure before any feature starts must still release shared text.
49
+ assert.throws(() => register({ ...pi, on() { probe(); throw new Error('registration fixture'); } }), /registration fixture/);
50
+ expectCold();
51
+ console.log('Shared display cache lifecycle: registration, session transitions, shutdown, stale callbacks and failed startup passed');
52
+ } finally {
53
+ emit('session_shutdown');
54
+ DisplayLineCache.prototype.get = nativeGet;
55
+ }
@@ -0,0 +1,48 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadSource, tui, backgroundCells } from './test-runtime.mjs';
3
+
4
+ const { DisplayLineCache } = await loadSource('./display-line-cache.ts');
5
+ const { activityRow, fillBackground, clearDisplayLineCache } = await loadSource('./display-card.ts');
6
+
7
+ // Reuse, eviction, oversized bypass and clearing must never change the result.
8
+ const cache = new DisplayLineCache(512, 2);
9
+ let calculations = 0;
10
+ const get = key => cache.get(key, () => { calculations++; return `formatted:${key}`; });
11
+ assert.equal(get('a'), get('a')); assert.equal(calculations, 1);
12
+ get('b'); get('a'); get('c'); // b is the least recently used entry.
13
+ get('a'); assert.equal(calculations, 3);
14
+ get('b'); assert.equal(calculations, 4);
15
+ for (let i = 0; i < 1000; i++) {
16
+ const key = `${i}:${'x'.repeat(i % 300)}`;
17
+ assert.equal(get(key), `formatted:${key}`);
18
+ assert.ok(cache.chargedBytes <= 512);
19
+ }
20
+ cache.clear(); assert.equal(cache.chargedBytes, 0);
21
+ const prior = calculations;
22
+ get('x'.repeat(1000)); get('x'.repeat(1000));
23
+ assert.equal(calculations, prior + 2, 'oversized entries are not retained');
24
+ assert.equal(cache.chargedBytes, 0);
25
+
26
+ // A theme can change its colors without changing object identity.
27
+ let color = 42;
28
+ const theme = { bg: (_token, text) => `\x1b[${color}m${text}\x1b[49m` };
29
+ for (const line of ['Read files', '检查结果 🧪 e\u0301', '\x1b[1mBold\x1b[0m and \x1b[48;5;49mcolored\x1b[49m', 'x'.repeat(5000)]) {
30
+ for (const width of [1, 7, 80]) {
31
+ for (color of [42, 44, 42]) {
32
+ for (const selected of [false, true]) {
33
+ const warm = activityRow(line, width, theme, selected);
34
+ assert.equal(activityRow(line, width, theme, selected), warm);
35
+ clearDisplayLineCache();
36
+ assert.equal(activityRow(line, width, theme, selected), warm, 'eviction preserves Unicode, ANSI and selection');
37
+ assert.ok(tui.visibleWidth(warm) <= width);
38
+ }
39
+ const filled = fillBackground('sample', width, theme, 'ignored');
40
+ assert.ok(backgroundCells(filled).every(cell => cell === String(color)), 'in-place theme change uses current color');
41
+ assert.equal(tui.visibleWidth(filled), width);
42
+ }
43
+ }
44
+ }
45
+ assert.notEqual(fillBackground('old', 10, theme, ''), fillBackground('new', 10, theme, ''));
46
+ assert.equal(fillBackground('text', 8, undefined, ''), 'text ');
47
+ assert.equal(fillBackground('text', 8, { bg: () => '' }, ''), 'text \x1b[49m');
48
+ console.log('Display-line cache: reuse, bounds, eviction, clearing, Unicode, ANSI, themes, widths and selection passed');
@@ -0,0 +1,25 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadSource } from './test-runtime.mjs';
3
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
4
+ const mode = createDisplayMode();
5
+ let count = 0, unsubscribe;
6
+ const redraw = () => { count++; unsubscribe(); unsubscribe = mode.onChange(redraw); };
7
+ unsubscribe = mode.onChange(redraw);
8
+ for (const enabled of [false, true, false, true]) {
9
+ const before = count;
10
+ assert.equal(mode.setEnabled(enabled), true);
11
+ assert.equal(count, before + 1, 'synchronous re-registration redraws once and remains registered');
12
+ }
13
+ assert.equal(mode.setEnabled(true), false);
14
+ assert.equal(count, 4);
15
+ let afterFailure = 0;
16
+ const removeFailure = mode.onChange(() => { throw new Error('fixture'); });
17
+ mode.onChange(() => afterFailure++);
18
+ assert.throws(() => mode.setEnabled(false), AggregateError);
19
+ assert.equal(afterFailure, 1, 'one refresh failure does not prevent remaining cleanup/refresh');
20
+ removeFailure();
21
+ mode.dispose();
22
+ assert.equal(mode.isEnabled(), false);
23
+ assert.equal(mode.setEnabled(true), false);
24
+ assert.equal(count, 5);
25
+ console.log('display mode synchronous redraw and disposal passed');
@@ -0,0 +1,81 @@
1
+ // Harmless controls for the isolated native preview. Never loaded by the package entry point.
2
+ import { createCodemodeExtension } from '@earendil-works/pi-coding-agent';
3
+
4
+ export const fixtureQuestion = {
5
+ question: 'Which synthetic sample should the preview compare?',
6
+ details: 'Display exercise only. Your answer does not start an analysis or approve an operation.',
7
+ options: [
8
+ { label: 'Sample A (Recommended)', value: 'sample-a', description: 'Inspect a complete invented record with explicit units.' },
9
+ { label: 'Sample B', value: 'sample-b', description: 'Inspect an invented record with a missing-value warning.' },
10
+ ],
11
+ };
12
+ export const fixtureTextQuestion = {
13
+ question: 'What label should this invented comparison use?',
14
+ details: 'Free-text display example. The label is not saved to a report.',
15
+ };
16
+
17
+ export default async function preview(pi: any) {
18
+ if (process.env.PI_PREVIEW_WORK_STRIP === '1') pi.registerCommand('fixture-work', {
19
+ description: 'Play an invented work-strip recording; no model or tool runs',
20
+ handler(_args: string, ctx: any) {
21
+ pi.events.emit('preview:work-strip-run:v1', { notify: (value: string) => ctx.ui.notify(value, 'info') });
22
+ },
23
+ });
24
+ // Import only native presentation helpers; never initialize the subagent runtime.
25
+ if (process.env.PI_PREVIEW_SUBAGENT_RENDERERS) {
26
+ const native = await import(process.env.PI_PREVIEW_SUBAGENT_RENDERERS);
27
+ for (const type of native.SUBAGENT_MESSAGE_TYPES) pi.registerMessageRenderer(type, native.renderSubagentMessage);
28
+ for (const type of native.SUBAGENT_ENTRY_TYPES) pi.registerEntryRenderer(type, native.renderSubagentEntry);
29
+ }
30
+ // Keep Pi's exact native renderers and schema, but never retain its script executor.
31
+ createCodemodeExtension()({
32
+ ...pi,
33
+ registerTool(definition: any) {
34
+ pi.registerTool({ ...definition, execute: async () => { throw new Error('Code execution is disabled in this preview.'); } });
35
+ },
36
+ });
37
+ let questionUI: any;
38
+ // The launcher supplies the existing pi-questions UI definition before replacing its registered executor.
39
+ pi.events.on('preview:question-ui:v1', (definition: any) => { questionUI = definition; });
40
+ pi.on('input', (_event: any, ctx: any) => {
41
+ ctx.ui.notify('Fixture prompt received. No model or tool was called.', 'info');
42
+ return { action: 'handled' };
43
+ });
44
+ pi.on('tool_call', () => ({ block: true, reason: 'This preview never executes tools.' }));
45
+ pi.on('user_bash', () => ({ result: { output: 'Shell execution is disabled in this preview.', exitCode: 1, cancelled: false, truncated: false } }));
46
+ pi.on('session_start', (_event: any, ctx: any) => ctx.ui.setStatus('preview', 'FIXTURE · no model, shell, or database calls'));
47
+ pi.registerCommand('fixture-question', {
48
+ description: 'Open the existing question UI without running the agent or a tool',
49
+ async handler(args: string, ctx: any) {
50
+ if (!questionUI) {
51
+ ctx.ui.notify('Native question UI unavailable. Set PI_QUESTIONS_PATH to pi-questions/index.ts and restart. Recorded question cards remain available.', 'warning');
52
+ return;
53
+ }
54
+ if (args.trim() && args.trim() !== 'text') {
55
+ ctx.ui.notify('Use /fixture-question for choices, or /fixture-question text for free text.', 'info');
56
+ return;
57
+ }
58
+ // Call only the captured UI logic, directly. Do not use ctx.executeTool or the tool pipeline.
59
+ const result = await questionUI.execute('fixture-ui-only', args.trim() === 'text' ? fixtureTextQuestion : fixtureQuestion, undefined, undefined, ctx);
60
+ const details = result.details;
61
+ const answer = details?.answers?.map((item: any) => item.type === 'other' ? `Other: ${item.label}` : item.label).join(', ');
62
+ ctx.ui.notify(`Fixture question: ${details?.status || 'unavailable'}${answer ? ` · ${answer}` : ''}. Nothing was executed or approved.`, details?.status === 'answered' ? 'info' : 'warning');
63
+ },
64
+ });
65
+ pi.registerCommand('fixture-permission', {
66
+ description: 'Preview approval controls; no operation runs',
67
+ async handler(_args: string, ctx: any) {
68
+ let present: undefined | (() => Promise<boolean>), accepting = true;
69
+ pi.events.emit('pi:permission-presentation:v1', {
70
+ version: 1, mode: ctx.mode, ui: ctx.ui,
71
+ action: 'Write a sample report', target: '/fixture/report.txt',
72
+ reason: 'Preview only. Allow once and Deny both perform no operation.',
73
+ details: JSON.stringify({ path: '/fixture/report.txt', content: Array.from({ length: 100 }, (_, i) => `Recorded example line ${i + 1} — 中文 and kg/L`).join('\n') }, null, 2),
74
+ offer(callback: () => Promise<boolean>) { if (!accepting || present) return false; present = callback; return true; },
75
+ });
76
+ accepting = false;
77
+ if (!present) { ctx.ui.notify('No compact permission presenter available.', 'warning'); return; }
78
+ ctx.ui.notify(`Fixture decision: ${await present() ? 'Allow once' : 'Deny'}. Nothing was executed.`, 'info');
79
+ },
80
+ });
81
+ }