@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,321 @@
1
+ import assert from 'node:assert/strict';
2
+ import { backgroundCells, core, loadSource, stripAnsi, themeModule, tui } from './test-runtime.mjs';
3
+
4
+ const { finalReplyRendering } = await loadSource('./display-card.ts');
5
+ const { registerModernThinking } = await loadSource('./modern-thinking.ts');
6
+ const { registerWorkStrip } = await loadSource('./work-strip.ts');
7
+ const { registerFoldCommand } = await loadSource('./fold-command.ts');
8
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
9
+ const { projectedChildren, renderFinalReply, workEvidenceType } = await loadSource('./work-strip-view.ts');
10
+ const replyText = 'FINAL **bold** and `code`\n\nSecond paragraph.\n\n- First item\n- Second item';
11
+ const message = (text = replyText, stopReason = 'stop') => ({ role: 'assistant', content: [{ type: 'text', text }], stopReason });
12
+ const token = theme => backgroundCells(theme.bg('toolPendingBg', ' '))[0];
13
+ const cells = line => backgroundCells(line.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, ''));
14
+ const withoutZones = line => line.replace(/\x1b\]133;[ABC]\x07/g, '');
15
+ const paddedNativeText = (native, width, first = 1, last = native.length - 1) => [
16
+ ...native.slice(0, first).map(stripAnsi), ' '.repeat(width),
17
+ ...native.slice(first, last + 1).map(stripAnsi), ' '.repeat(width), ...native.slice(last + 1).map(stripAnsi),
18
+ ];
19
+ function assertReplySurface(lines, theme) {
20
+ assert.equal(cells(lines[0]).length, 0, 'native leading spacer has no filled cells');
21
+ assert.ok(!/\x1b\[(?:48|4[0-7]|10[0-7])/.test(lines[0]), 'leading spacer is not tinted');
22
+ for (const line of lines.slice(1)) {
23
+ assert.ok(cells(line).length > 0, 'reply paragraphs and internal gaps retain native width');
24
+ assert.ok(cells(line).every(cell => cell === token(theme)), 'neutral surface survives nested Markdown resets');
25
+ }
26
+ }
27
+
28
+ // The native component owns wrapping, Markdown, OSC zones and the leading gap.
29
+ // Add exactly two padding rows; keep native reply wrapping and narrow overflow.
30
+ for (const appearance of ['dark', 'light']) {
31
+ themeModule.initTheme(appearance, false);
32
+ const theme = themeModule.theme;
33
+ const row = new core.AssistantMessageComponent(message(), true);
34
+ const markdown = row.contentContainer.children.find(child => child instanceof tui.Markdown);
35
+ const originalRender = markdown.render;
36
+ const ownRender = Object.getOwnPropertyDescriptor(markdown, 'render');
37
+ for (const width of [1, 7, 30, 100]) {
38
+ const native = row.render(width), painted = renderFinalReply(row, width, theme);
39
+ assert.deepEqual(painted.map(stripAnsi), paddedNativeText(native, width), `only two filled padding rows are added at width ${width}`);
40
+ assertReplySurface(painted, theme);
41
+ assert.deepEqual(painted.join('\n').match(/\x1b\]133;[ABC]\x07/g), native.join('\n').match(/\x1b\]133;[ABC]\x07/g), 'native OSC zones remain exact');
42
+ assert.equal(markdown.render, originalRender);
43
+ assert.equal(Object.hasOwn(row, finalReplyRendering), false, 'successful final rendering removes its scoped marker');
44
+ assert.deepEqual(Object.getOwnPropertyDescriptor(markdown, 'render'), ownRender, 'render projection restores the native property shape');
45
+ }
46
+ }
47
+
48
+ // Image payloads and their cursor controls must pass through byte for byte.
49
+ {
50
+ const row = new core.AssistantMessageComponent(message('Image placeholder.'), true);
51
+ const markdown = row.contentContainer.children.find(child => child instanceof tui.Markdown);
52
+ const imageLines = ['\x1b_Ga=T,f=100;AAAA\x1b\\', '\x1b[2A\x1b]1337;File=inline=1:AAAA\x07'];
53
+ markdown.render = () => [...imageLines];
54
+ const rendered = renderFinalReply(row, 40, themeModule.theme);
55
+ assert.deepEqual(rendered.slice(2, -1).map(withoutZones), imageLines, 'graphics payloads stay exact between the added padding rows');
56
+ assert.deepEqual(rendered.join('\n').match(/\x1b\]133;[ABC]\x07/g), row.render(40).join('\n').match(/\x1b\]133;[ABC]\x07/g), 'native OSC zones include the padded reply');
57
+ markdown.render = () => { throw new Error('synthetic Markdown failure'); };
58
+ const render = markdown.render;
59
+ assert.throws(() => renderFinalReply(row, 40, themeModule.theme), /synthetic Markdown failure/);
60
+ assert.equal(markdown.render, render, 'a failed native render also restores the method');
61
+ assert.equal(Object.hasOwn(row, finalReplyRendering), false, 'failed final rendering also removes its scoped marker');
62
+ row[finalReplyRendering] = 'outer render';
63
+ assert.throws(() => renderFinalReply(row, 40, themeModule.theme), /synthetic Markdown failure/);
64
+ assert.equal(row[finalReplyRendering], 'outer render', 'nested final rendering restores an existing marker');
65
+ }
66
+
67
+ // Multiple text blocks share one padding pair. A later thinking region keeps
68
+ // its native mouse target after the added top row shifts its screen position.
69
+ {
70
+ const row = new core.AssistantMessageComponent({ role: 'assistant', stopReason: 'stop', content: [
71
+ { type: 'text', text: 'FIRST_TEXT_BLOCK' }, { type: 'thinking', thinking: 'CLICKED_NATIVE_THINKING' },
72
+ { type: 'text', text: 'SECOND_TEXT_BLOCK' },
73
+ ] }, true);
74
+ const native = row.render(60), children = [...row.contentContainer.children];
75
+ const rendered = renderFinalReply(row, 60, themeModule.theme);
76
+ const first = native.findIndex(line => stripAnsi(line).includes('FIRST_TEXT_BLOCK'));
77
+ const last = native.findIndex(line => stripAnsi(line).includes('SECOND_TEXT_BLOCK'));
78
+ assert.deepEqual(rendered.map(stripAnsi), paddedNativeText(native, 60, first, last), 'multiple native text blocks receive exactly one padding pair');
79
+ assert.deepEqual(row.contentContainer.children, children, 'padded rendering restores native child identity and order');
80
+ const y = rendered.findIndex(line => stripAnsi(line).includes('Thinking'));
81
+ assert.ok(row.handleMouse({ type: 'click', button: 'left', x: 2, y, width: 60, height: rendered.length, screenX: 2, screenY: y })?.handled, 'native container maps a thinking click shifted by top padding');
82
+ assert.match(stripAnsi(renderFinalReply(row, 60, themeModule.theme).join('\n')), /CLICKED_NATIVE_THINKING/);
83
+ }
84
+
85
+ function fixture({ thinking = false } = {}) {
86
+ const hooks = new Map(), bus = new Map(), commands = new Map();
87
+ const subscribe = (map, name, fn) => {
88
+ const set = map.get(name) || new Set(); map.set(name, set); set.add(fn); return () => set.delete(fn);
89
+ };
90
+ const manager = core.SessionManager.inMemory('/synthetic-final-surface');
91
+ const pi = {
92
+ on: (name, fn) => subscribe(hooks, name, fn),
93
+ events: { on: (name, fn) => subscribe(bus, name, fn), emit(name, value) { for (const fn of [...bus.get(name) || []]) fn(value); } },
94
+ getAllTools: () => [], appendEntry: (kind, data) => manager.appendCustomEntry(kind, data),
95
+ registerCommand: (name, definition) => commands.set(name, definition),
96
+ };
97
+ const mode = createDisplayMode(), workControls = registerWorkStrip(pi, mode);
98
+ const stopThinking = thinking ? registerModernThinking(pi, mode) : () => {};
99
+ const dispose = () => { stopThinking(); workControls.dispose(); };
100
+ registerFoldCommand(pi, mode, workControls);
101
+ const ui = { theme: themeModule.theme, isFollowingOutput: true, notify() {}, requestRender() {} };
102
+ if (thinking) ui.setHiddenThinkingLabel = () => { for (const row of display.chatContainer.children) if (row instanceof core.AssistantMessageComponent) row.setHiddenThinkingLabel('Thinking...'); };
103
+ const ctx = { mode: 'tui', hasUI: true, ui, sessionManager: manager, isIdle: () => true };
104
+ const display = {
105
+ chatContainer: new tui.Container(), ui, pendingTools: new Map(), outputPad: 1,
106
+ toolOutputExpanded: false, hideThinkingBlock: true, sessionManager: manager,
107
+ session: { extensionRunner: { getMessageRenderer() {} } },
108
+ getUserMessageText: value => value.content,
109
+ getMarkdownThemeWithSettings: () => themeModule.getMarkdownTheme(), getMarkdownTransformers: () => [],
110
+ editor: { addToHistory() {} },
111
+ };
112
+ const event = (name, value = {}) => { for (const fn of [...hooks.get(name) || []]) fn(value, ctx); };
113
+ const add = value => {
114
+ value.timestamp ??= 1000 + manager.getBranch().length;
115
+ manager.appendMessage(value);
116
+ const entry = manager.getBranch().at(-1);
117
+ core.InteractiveMode.prototype.addMessageToChat.call(display, value);
118
+ return { row: display.chatContainer.children.at(-1), entry };
119
+ };
120
+ const tool = () => {
121
+ const row = new core.ToolExecutionComponent('read', 'surface-read', {}, { outputPad: 1 }, undefined, ui, '/synthetic-final-surface');
122
+ row.setArgsComplete(); row.updateResult({ content: [{ type: 'text', text: 'READ_RESULT' }], isError: false });
123
+ display.chatContainer.addChild(row); return row;
124
+ };
125
+ const paint = () => display.chatContainer.render(60);
126
+ const view = row => { paint(); return display.chatContainer[projectedChildren].find(item => item === row || item.children?.[0] === row); };
127
+ return { add, tool, event, emit: pi.events.emit, paint, view, mode, dispose, ui, display, manager, ctx, commands };
128
+ }
129
+
130
+ // A direct answer gets a final surface without introducing a Work header.
131
+ {
132
+ const f = fixture();
133
+ try {
134
+ f.add({ role: 'user', content: 'Answer directly.' });
135
+ const commentary = f.add(message('Intermediate reply.'));
136
+ const final = f.add(message());
137
+ const canonical = [...f.display.chatContainer.children], native = final.row.render(60);
138
+ const transcript = JSON.stringify(f.manager.getBranch());
139
+ f.event('session_start'); f.paint();
140
+ assert.equal(f.view(commentary.row), commentary.row, 'earlier commentary stays plain');
141
+ assert.ok(!f.display.chatContainer[projectedChildren].some(row => row.constructor.name === 'WorkStripHeader'));
142
+ const surface = f.view(final.row);
143
+ assert.notEqual(surface, final.row);
144
+ assertReplySurface(surface.render(60), f.ui.theme);
145
+ assert.deepEqual(surface.render(60).map(stripAnsi), paddedNativeText(native, 60));
146
+ const dark = surface.render(60);
147
+ themeModule.initTheme('dark', false); f.ui.theme = themeModule.theme;
148
+ const changed = f.view(final.row).render(60);
149
+ assert.notDeepEqual(changed, dark, 'the cached final view reads the current theme');
150
+ assertReplySurface(changed, f.ui.theme);
151
+ f.mode.setEnabled(false);
152
+ assert.deepEqual(f.paint(), canonical.flatMap(row => row.render(60)), 'compact-off retains native bytes');
153
+ f.mode.setEnabled(true); f.paint();
154
+ assert.deepEqual(f.display.chatContainer.children, canonical);
155
+ assert.equal(JSON.stringify(f.manager.getBranch()), transcript, 'direct final styling adds no transcript metadata');
156
+ } finally { f.dispose(); f.mode.dispose(); }
157
+ }
158
+
159
+ // A stop reason alone cannot turn a live intermediate response into a final.
160
+ for (const stopReason of ['stop', 'toolUse', 'error', 'aborted', 'length']) {
161
+ const f = fixture();
162
+ try {
163
+ f.event('session_start'); f.event('agent_start');
164
+ f.add({ role: 'user', content: 'Live response.' });
165
+ const final = f.add(message('LIVE_REPLY', stopReason));
166
+ assert.equal(f.view(final.row), final.row, 'live replies retain native rendering before settlement');
167
+ f.event('agent_settled');
168
+ assert.equal(f.view(final.row) !== final.row, stopReason !== 'toolUse', 'only a settled terminal reply receives a surface');
169
+ assert.match(stripAnsi(f.paint().join('\n')), /LIVE_REPLY/, 'terminal errors and interruptions retain their reply');
170
+ const failure = { error: 'Error: Unknown error', aborted: 'Operation aborted', length: 'Response was truncated before completion.' }[stopReason];
171
+ if (failure) assert.ok(stripAnsi(f.paint().join('\n')).includes(failure), 'native failure details remain distinct and visible');
172
+ final.row.isStreaming = true;
173
+ assert.equal(f.view(final.row), final.row, 'a streaming component is never styled as settled');
174
+ } finally { f.dispose(); f.mode.dispose(); }
175
+ }
176
+
177
+ // Execution commentary keeps one gutter through streaming and later replies.
178
+ // Only the settled terminal reply moves out of the work section.
179
+ {
180
+ const f = fixture();
181
+ try {
182
+ f.event('session_start'); f.event('agent_start');
183
+ f.add({ role: 'user', content: 'Follow the live reply lifecycle.' });
184
+ const first = f.add(message('FIRST_LIVE_COMMENTARY')).row;
185
+ assert.equal(f.view(first), first, 'commentary alone does not introduce a work section');
186
+ f.tool();
187
+ const firstView = f.view(first);
188
+ assert.equal(firstView.constructor.name, 'WorkChild', 'execution activity indents the current commentary immediately');
189
+ assert.match(stripAnsi(firstView.render(60).join('\n')), /\n FIRST_LIVE_COMMENTARY/);
190
+ const nextMessage = message('NEXT_LIVE_COMMENTARY');
191
+ f.event('message_start', { message: nextMessage });
192
+ const next = f.add(nextMessage).row;
193
+ next.updateContent(nextMessage, true);
194
+ assert.equal(f.view(first), firstView, 'a newer reply does not shift the preceding commentary');
195
+ const nextView = f.view(next);
196
+ assert.equal(nextView.constructor.name, 'WorkChild', 'streaming commentary uses the same child gutter');
197
+ next.updateContent(nextMessage, false); f.event('message_end', { message: nextMessage });
198
+ assert.equal(f.view(next), nextView, 'message_end and stop alone do not promote commentary');
199
+ const canonical = [...f.display.chatContainer.children];
200
+ f.mode.setEnabled(false);
201
+ assert.deepEqual(f.paint(), canonical.flatMap(row => row.render(60)), 'compact-off keeps native live rendering byte for byte');
202
+ f.mode.setEnabled(true);
203
+ assert.equal(f.view(next), nextView, 'compact-on restores the same commentary gutter');
204
+
205
+ const finalMessage = message('CONFIRMED_FINAL_REPLY');
206
+ f.event('message_start', { message: finalMessage });
207
+ const final = f.add(finalMessage).row;
208
+ final.updateContent(finalMessage, true);
209
+ f.event('agent_settled');
210
+ assert.equal(f.view(final).constructor.name, 'WorkChild', 'a streaming reply remains a work child even after agent settlement');
211
+ final.updateContent(finalMessage, false); f.event('message_end', { message: finalMessage });
212
+ const surface = f.view(final);
213
+ assert.notEqual(surface.constructor.name, 'WorkChild', 'confirmed final reply leaves the work gutter');
214
+ assertReplySurface(surface.render(60), f.ui.theme);
215
+ assert.match(stripAnsi(surface.render(60).join('\n')), /\n CONFIRMED_FINAL_REPLY/);
216
+ assert.equal(f.view(first), firstView, 'earlier commentary retains its gutter after final confirmation');
217
+ assert.deepEqual(f.display.chatContainer.children, [...canonical, final], 'projection preserves the native child tree');
218
+ } finally { f.dispose(); f.mode.dispose(); }
219
+ }
220
+
221
+ // Parent settlement cannot style a reply as final while its descendants run.
222
+ {
223
+ const f = fixture();
224
+ try {
225
+ f.event('session_start'); f.event('agent_start');
226
+ f.add({ role: 'user', content: 'Wait for the owned child.' }); f.tool();
227
+ f.emit('subagent:async-started', { id: 'surface-child' });
228
+ const final = f.add(message('WAITING_REPLY')).row;
229
+ f.event('agent_settled');
230
+ assert.equal(f.view(final).constructor.name, 'WorkChild', 'waiting reply remains inside the work section');
231
+ assert.match(stripAnsi(f.paint().join('\n')), /Waiting/);
232
+ f.emit('subagent:async-complete', { id: 'surface-child', state: 'complete', success: true });
233
+ assertReplySurface(f.view(final).render(60), f.ui.theme);
234
+ } finally { f.dispose(); f.mode.dispose(); }
235
+ }
236
+
237
+ {
238
+ const f = fixture();
239
+ try {
240
+ f.add({ role: 'user', content: 'Tool call with commentary.' });
241
+ const intermediate = message('Tool commentary.', 'stop');
242
+ intermediate.content.push({ type: 'toolCall', id: 'surface-tool', name: 'read', arguments: {} });
243
+ const row = f.add(intermediate).row;
244
+ f.event('session_start');
245
+ assert.equal(f.view(row).constructor.name, 'WorkChild', 'text accompanying a tool call stays inside the work section');
246
+ assert.deepEqual(f.view(row).children, [row], 'tool-call text retains its native component');
247
+ } finally { f.dispose(); f.mode.dispose(); }
248
+ }
249
+
250
+ // Folding and unfolding use the same final surface at the native main margin.
251
+ {
252
+ const f = fixture();
253
+ try {
254
+ const user = f.add({ role: 'user', content: 'Inspect a file.' });
255
+ f.add(message('Checking the file.')); f.tool();
256
+ const final = f.add({ role: 'assistant', stopReason: 'stop', content: [
257
+ { type: 'thinking', thinking: 'Native thinking remains inspectable.' }, { type: 'text', text: 'FINAL_REPLY' },
258
+ ] });
259
+ f.manager.appendCustomEntry(workEvidenceType, {
260
+ version: 1, userId: user.entry.id, finalId: final.entry.id, endId: final.entry.id,
261
+ startedAt: 1000, endedAt: 2000, outcome: 'completed',
262
+ });
263
+ f.event('session_start');
264
+ const folded = f.view(final.row).render(60);
265
+ assert.equal(folded.length, 4, 'one outer gap and a three-row final card remain after thinking folds');
266
+ assertReplySurface(folded, f.ui.theme);
267
+ await f.commands.get('fold').handler('expand', f.ctx);
268
+ const surface = f.view(final.row), expanded = surface.render(60);
269
+ assert.match(stripAnsi(expanded.join('\n')), /Thinking/);
270
+ const thinkingIndex = expanded.findIndex(line => stripAnsi(line).includes('Thinking'));
271
+ assert.ok(cells(expanded[thinkingIndex]).every(cell => !cell), 'native thinking stays on the plain surface');
272
+ const finalLine = expanded.find(line => stripAnsi(line).includes('FINAL_REPLY'));
273
+ assert.match(stripAnsi(finalLine), /^ FINAL_REPLY/, 'final text retains the native main margin');
274
+ assert.ok(cells(finalLine).every(cell => cell === token(f.ui.theme)));
275
+ const click = { type: 'click', button: 'left', x: 2, y: thinkingIndex, width: 60, height: expanded.length, screenX: 2, screenY: thinkingIndex };
276
+ assert.ok(surface.handleMouse(click)?.handled, 'native thinking mouse coordinates remain valid');
277
+ assert.match(stripAnsi(surface.render(60).join('\n')), /Native thinking remains inspectable/);
278
+ } finally { f.dispose(); f.mode.dispose(); }
279
+ }
280
+
281
+ console.log('Final reply padded neutral card: native Markdown, one padding pair, outer gaps, resets, images, themes, settlement, direct replies, folding, mouse coordinates and compact-off passed');
282
+
283
+ // Restored transcript: two tool rounds and leading thinking on the final answer.
284
+ // Both adapters must cooperate while final padding and work folding are active.
285
+ {
286
+ const f = fixture({ thinking: true });
287
+ try {
288
+ const user = f.add({ role: 'user', content: 'Inspect the recorded samples.' });
289
+ for (let n = 1; n <= 2; n++) {
290
+ f.add({ role: 'assistant', stopReason: 'toolUse', content: [
291
+ { type: 'thinking', thinking: `Round ${n} summary.\nRecorded round ${n} body.` },
292
+ { type: 'toolCall', id: `round-${n}`, name: 'read', arguments: {} },
293
+ ] });
294
+ f.tool();
295
+ }
296
+ const final = f.add({ role: 'assistant', stopReason: 'stop', content: [
297
+ { type: 'thinking', thinking: 'Final source summary.\nRecorded final body.' },
298
+ { type: 'text', text: 'GROUPED_FINAL_REPLY' },
299
+ ] });
300
+ f.manager.appendCustomEntry(workEvidenceType, { version: 1, userId: user.entry.id,
301
+ finalId: final.entry.id, endId: final.entry.id, startedAt: 1000, endedAt: 2000, outcome: 'completed' });
302
+ const transcript = JSON.stringify(f.manager.getBranch());
303
+ f.event('session_start');
304
+ assert.doesNotMatch(stripAnsi(f.paint().join('\n')), /Thinking/);
305
+ for (let repeat = 0; repeat < 3; repeat++) {
306
+ await f.commands.get('fold').handler('expand', f.ctx);
307
+ const rendered = stripAnsi(f.paint().join('\n'));
308
+ assert.match(rendered, /Thinking · 3 rounds/);
309
+ assert.doesNotMatch(rendered, /Thinking\.\.\./);
310
+ assert.equal((rendered.match(/Thinking ·/g) || []).length, 1);
311
+ const surface = f.view(final.row), rows = surface.render(60);
312
+ const y = rows.findIndex(line => stripAnsi(line).includes('Thinking ·'));
313
+ assert.equal(surface.handleMouse({ type: 'click', button: 'left', x: 2, y, width: 60, height: rows.length })?.handled, true);
314
+ assert.match(stripAnsi(f.paint().join('\n')), /3\. Final source summary/);
315
+ await f.commands.get('fold').handler('collapse', f.ctx);
316
+ assert.doesNotMatch(stripAnsi(f.paint().join('\n')), /Thinking|Recorded final body/);
317
+ assert.match(stripAnsi(f.paint().join('\n')), /GROUPED_FINAL_REPLY/);
318
+ }
319
+ assert.equal(JSON.stringify(f.manager.getBranch()), transcript);
320
+ } finally { f.dispose(); f.mode.dispose(); }
321
+ }
@@ -0,0 +1,258 @@
1
+ import assert from 'node:assert/strict';
2
+ import { core, loadSource, themeModule, tui, stripAnsi } from './test-runtime.mjs';
3
+
4
+ const { registerWorkStrip } = await loadSource('./work-strip.ts');
5
+ const { registerFoldCommand } = await loadSource('./fold-command.ts');
6
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
7
+ const { projectedChildren, workEvidenceType, recordedWorkEvidence } = await loadSource('./work-strip-view.ts');
8
+ assert.equal(core.VERSION, '1.3.0', 'hierarchy integration runs against the supported native runtime');
9
+
10
+ function fixture() {
11
+ const hooks = new Map(), bus = new Map(), commands = new Map(), shortcuts = new Map(), inputs = new Set(), notices = [];
12
+ const subscribe = (map, name, fn) => {
13
+ const set = map.get(name) || new Set(); map.set(name, set); set.add(fn); return () => set.delete(fn);
14
+ };
15
+ const manager = core.SessionManager.inMemory('/synthetic-hierarchy');
16
+ let ownership;
17
+ const pi = {
18
+ on: (name, fn) => subscribe(hooks, name, fn),
19
+ events: { on: (name, fn) => subscribe(bus, name, fn), emit(name, value) { for (const fn of [...bus.get(name) || []]) fn(value); } },
20
+ getAllTools: () => [], appendEntry: (kind, data) => manager.appendCustomEntry(kind, data),
21
+ registerCommand: (name, definition) => commands.set(name, definition),
22
+ registerShortcut: (name, definition) => shortcuts.set(name, definition),
23
+ };
24
+ pi.events.on('compact-renderer:work-strip:v1', value => { ownership = value.ownsExecutionStatus; });
25
+ const mode = createDisplayMode(), workControls = registerWorkStrip(pi, mode), dispose = workControls.dispose;
26
+ registerFoldCommand(pi, mode, workControls);
27
+ const ui = {
28
+ isFollowingOutput: true, theme: themeModule.theme, requestRender() {},
29
+ onTerminalInput(fn) { inputs.add(fn); return () => inputs.delete(fn); },
30
+ notify(message, tone) { notices.push({ message, tone }); },
31
+ };
32
+ const ctx = { mode: 'tui', hasUI: true, ui, sessionManager: manager, isIdle: () => true };
33
+ const display = {
34
+ chatContainer: new tui.Container(), ui, pendingTools: new Map(), outputPad: 1,
35
+ toolOutputExpanded: false, hideThinkingBlock: true, sessionManager: manager,
36
+ session: { extensionRunner: { getMessageRenderer() {} } },
37
+ getUserMessageText: message => message.content,
38
+ getMarkdownThemeWithSettings: () => themeModule.getMarkdownTheme(), getMarkdownTransformers: () => [],
39
+ editor: { addToHistory() {} },
40
+ };
41
+ const event = (name, value = {}) => { for (const fn of [...hooks.get(name) || []]) fn(value, ctx); };
42
+ const add = message => {
43
+ message.timestamp ??= 1000 + manager.getBranch().length;
44
+ manager.appendMessage(message);
45
+ const entry = manager.getBranch().at(-1);
46
+ core.InteractiveMode.prototype.addMessageToChat.call(display, message);
47
+ return { row: display.chatContainer.children.at(-1), entry };
48
+ };
49
+ const assistant = content => add({ role: 'assistant', content: typeof content === 'string' ? [{ type: 'text', text: content }] : content, stopReason: 'stop' });
50
+ const tool = () => {
51
+ const row = new core.ToolExecutionComponent('read', 'hierarchy-read', { path: '/synthetic/file.txt' }, { outputPad: 1 }, undefined, ui, '/synthetic-hierarchy');
52
+ row.setArgsComplete(); row.updateResult({ content: [{ type: 'text', text: 'HIDDEN_TOOL_CONTENT' }], isError: false });
53
+ display.chatContainer.addChild(row); return row;
54
+ };
55
+ const save = (user, final) => manager.appendCustomEntry(workEvidenceType, {
56
+ version: 1, userId: user.entry.id, finalId: final.entry.id, endId: final.entry.id,
57
+ startedAt: 1000, endedAt: 3000, outcome: 'completed',
58
+ });
59
+ const paint = (width = 100) => {
60
+ const rendered = display.chatContainer.render(width);
61
+ return { rows: display.chatContainer[projectedChildren], lines: rendered.map(stripAnsi), text: stripAnsi(rendered.join('\n')) };
62
+ };
63
+ const choices = () => { const items = []; pi.events.emit('compact-renderer:inspect:v1', { add: item => items.push(item) }); return items; };
64
+ const work = args => commands.get('fold').handler(args, ctx);
65
+ return { manager, mode, dispose, display, event, add, assistant, tool, save, paint, choices, work, shortcuts, notices, get ownership() { return ownership; } };
66
+ }
67
+
68
+ // Valid completion metadata cannot create execution activity where none occurred.
69
+ for (const saved of [false, true]) for (const thought of ['none', 'separate', 'mixed']) {
70
+ const f = fixture();
71
+ try {
72
+ const user = f.add({ role: 'user', content: `Direct answer ${thought}.` });
73
+ if (thought === 'separate') f.assistant([{ type: 'thinking', thinking: 'Recorded reasoning without tools.' }]);
74
+ const final = f.assistant([
75
+ ...(thought === 'mixed' ? [{ type: 'thinking', thinking: 'Recorded mixed reasoning without tools.' }] : []),
76
+ { type: 'text', text: 'DIRECT_FIRST_PARAGRAPH\n\nDIRECT_SECOND_PARAGRAPH' },
77
+ ]);
78
+ if (saved) f.save(user, final);
79
+ const native = f.paint().lines;
80
+ assert.equal(recordedWorkEvidence(f.manager.getBranch()).size, saved ? 1 : 0, 'saved fixture evidence is valid');
81
+ f.event('session_start');
82
+ const projected = f.paint();
83
+ const first = native.findIndex(line => line.includes('DIRECT_FIRST_PARAGRAPH'));
84
+ const padded = [...native.slice(0, first), ' '.repeat(100), ...native.slice(first), ' '.repeat(100)];
85
+ assert.deepEqual(projected.lines, padded, `${thought} response adds exactly two final padding rows with saved=${saved}`);
86
+ assert.ok(!projected.rows.some(row => row.constructor.name === 'WorkStripHeader'), 'response and thinking alone receive no work strip');
87
+ assert.equal(f.choices().filter(item => item.kind === 'Work').length, 0, 'nonactivity does not enter Work inspection');
88
+ assert.equal(f.ownership, false, 'nonactivity leaves execution-status ownership native');
89
+ f.shortcuts.get('ctrl+alt+w').handler();
90
+ assert.ok(!f.paint().rows.some(row => row.constructor.name === 'WorkStripHeader'), 'shortcut with no work sections is a no-op');
91
+ await f.work('collapse'); assert.deepEqual(f.paint().lines, padded, '/fold cannot fold a direct response');
92
+ } finally { f.dispose(); f.mode.dispose(); }
93
+ }
94
+
95
+ {
96
+ const f = fixture();
97
+ try {
98
+ const user = f.add({ role: 'user', content: 'Review the recorded decisions.' });
99
+ f.tool();
100
+ const question = new core.ToolExecutionComponent('ask_user_question', 'hierarchy-question', { question: 'Recorded question?' }, { outputPad: 1 }, undefined, f.display.ui, '/synthetic-hierarchy');
101
+ question.setArgsComplete(); question.updateResult({ content: [{ type: 'text', text: 'RECORDED_ANSWER' }], isError: false });
102
+ f.display.chatContainer.addChild(question);
103
+ const notices = [
104
+ ['subagent_supervisor_request', 'PENDING_DECISION'],
105
+ ['subagent_supervisor_reply', 'ANSWERED_DECISION'],
106
+ ['subagent-failed', 'FAILED_CHILD'],
107
+ ['ddd', 'RECORDED_HOOK'],
108
+ ].map(([customType, content]) => f.add({ role: 'custom', customType, content, display: true }).row);
109
+ const final = f.assistant('VISIBLE_FINAL_REPLY');
110
+ f.save(user, final);
111
+ const canonical = [...f.display.chatContainer.children];
112
+ f.event('session_start');
113
+ for (const action of ['collapse', 'expand', 'collapse']) {
114
+ await f.work(action);
115
+ const view = f.paint();
116
+ for (const original of [question, ...notices]) {
117
+ const child = view.rows.find(row => row.constructor.name === 'WorkChild' &&
118
+ (row.children[0] === original || original.message?.customType === 'ddd' && row.render(100).some(line => stripAnsi(line).includes('RECORDED_HOOK'))));
119
+ assert.ok(child, `${original.toolName || original.message?.customType} stays visible and indented during ${action}`);
120
+ assert.ok(child.render(100).map(stripAnsi).filter(line => line.trim()).every(line => line.startsWith(' ')), 'attention content stays inside the child gutter');
121
+ }
122
+ assert.match(view.lines.find(line => line.includes('VISIBLE_FINAL_REPLY')), /^ VISIBLE_FINAL_REPLY/, 'final reply remains at the main margin');
123
+ assert.ok(!view.rows.some(row => row.constructor.name === 'WorkChild' && row.children[0] === final.row));
124
+ assert.deepEqual(f.display.chatContainer.children, canonical, 'visibility and indentation preserve canonical row identity');
125
+ }
126
+ } finally { f.dispose(); f.mode.dispose(); }
127
+ }
128
+
129
+ {
130
+ const f = fixture();
131
+ try {
132
+ f.event('session_start'); f.event('agent_start');
133
+ f.add({ role: 'user', content: 'Give a direct answer without tools.' });
134
+ f.assistant([{ type: 'thinking', thinking: 'LIVE_RECORDED_REASONING' }]);
135
+ assert.ok(!f.paint().rows.some(row => row.constructor.name === 'WorkStripHeader'), 'a live response clock and thinking do not create a strip');
136
+ f.assistant('LIVE_DIRECT_ANSWER'); f.paint(); f.event('agent_settled');
137
+ await new Promise(resolve => setTimeout(resolve, 130));
138
+ assert.match(f.paint().text, /LIVE_DIRECT_ANSWER/);
139
+ assert.ok(!f.paint().rows.some(row => row.constructor.name === 'WorkStripHeader'), 'settlement keeps a direct response outside work strips');
140
+ assert.equal(recordedWorkEvidence(f.manager.getBranch()).size, 0, 'no-tool settlement adds no work completion evidence');
141
+ assert.equal(f.ownership, false);
142
+ } finally { f.dispose(); f.mode.dispose(); }
143
+ }
144
+
145
+ {
146
+ const f = fixture();
147
+ try {
148
+ const user = f.add({ role: 'user', content: 'Inspect the recorded file.' });
149
+ const commentary = f.assistant('HIDDEN_COMMENTARY');
150
+ const activity = f.tool();
151
+ const final = f.assistant([
152
+ { type: 'thinking', thinking: 'EXACT_FINAL_RECORDED_THINKING' },
153
+ { type: 'text', text: 'FINAL_FIRST_PARAGRAPH\n\nFINAL_SECOND_PARAGRAPH\n\n- retained first item\n- retained second item' },
154
+ ]);
155
+ f.save(user, final);
156
+ const canonical = [...f.display.chatContainer.children];
157
+ const messages = JSON.stringify(f.manager.getBranch());
158
+ f.event('session_start');
159
+ const collapsed = f.paint(), header = collapsed.rows.find(row => row.constructor.name === 'WorkStripHeader');
160
+ assert.ok(header, 'recorded tool activity receives a work strip');
161
+ assert.equal(header.open, false, 'completed activity folds automatically');
162
+ assert.doesNotMatch(collapsed.text, /HIDDEN_COMMENTARY|HIDDEN_TOOL_CONTENT|Thinking|EXACT_FINAL_RECORDED_THINKING/);
163
+ const heading = collapsed.lines.findIndex(line => line.includes('Worked for'));
164
+ const first = collapsed.lines.findIndex(line => line.includes('FINAL_FIRST_PARAGRAPH'));
165
+ const second = collapsed.lines.findIndex(line => line.includes('FINAL_SECOND_PARAGRAPH'));
166
+ assert.equal(first, heading + 3, 'collapsed strip keeps one outer gap and one filled top padding row before final text');
167
+ assert.equal(collapsed.lines[heading + 1].trim(), '');
168
+ assert.equal(collapsed.lines[heading + 2], ' '.repeat(100), 'final card owns one filled top padding row');
169
+ assert.equal(collapsed.lines.at(-1), ' '.repeat(100), 'final card owns one filled bottom padding row');
170
+ assert.equal(second, first + 2, 'native final paragraph gap remains intact');
171
+ assert.equal(collapsed.lines[first + 1].trim(), '');
172
+ assert.match(collapsed.text, /retained first item[\s\S]*retained second item/);
173
+ const finalChildren = [...final.row.contentContainer.children];
174
+ f.paint();
175
+ assert.deepEqual(final.row.contentContainer.children, finalChildren, 'folded final view restores the native thinking/text tree after painting');
176
+ assert.deepEqual(f.display.chatContainer.children, canonical, 'projection preserves canonical row identity');
177
+ await f.work('expand');
178
+ const expanded = f.paint();
179
+ assert.equal(header.open, true);
180
+ assert.match(expanded.text, /HIDDEN_COMMENTARY/);
181
+ assert.match(expanded.text, /HIDDEN_TOOL_CONTENT/);
182
+ for (const original of [commentary.row, activity]) {
183
+ const child = expanded.rows.find(row => row.constructor.name === 'WorkChild' && row.children[0] === original);
184
+ assert.ok(child, 'activity children retain identity inside a native indentation wrapper');
185
+ for (const width of [7, 20, 100]) {
186
+ const inset = width >= 8 ? 2 : 0;
187
+ const expected = original.render(Math.max(1, width - inset * 2)).map(stripAnsi).map(line => (' '.repeat(inset) + line).trimEnd());
188
+ assert.deepEqual(child.render(width).map(stripAnsi).map(line => line.trimEnd()), expected, `child indentation follows native wrapping at width ${width}`);
189
+ }
190
+ }
191
+ assert.match(expanded.lines.find(line => line.includes('HIDDEN_COMMENTARY')), /^ {3}HIDDEN_COMMENTARY/, 'commentary is indented beneath the work heading');
192
+ assert.match(expanded.lines.find(line => line.includes('FINAL_FIRST_PARAGRAPH')), /^ FINAL_FIRST_PARAGRAPH/, 'terminal reply keeps its native column');
193
+ assert.ok(!expanded.rows.some(row => row.constructor.name === 'WorkChild' && row.children[0] === final.row), 'final reply is outside the activity child indentation');
194
+ await f.work('collapse');
195
+ assert.doesNotMatch(f.paint().text, /HIDDEN_COMMENTARY|HIDDEN_TOOL_CONTENT/);
196
+ await f.work('expand'); await f.work('shortcut off');
197
+ f.shortcuts.get('ctrl+alt+w').handler();
198
+ assert.equal(header.open, true, 'disabled session shortcut leaves work expanded');
199
+ await f.work('shortcut on'); f.shortcuts.get('ctrl+alt+w').handler();
200
+ assert.equal(header.open, false, 'enabled native shortcut toggles completed work closed');
201
+ f.shortcuts.get('ctrl+alt+w').handler();
202
+ assert.equal(header.open, true, 'repeated shortcut toggles completed work open');
203
+ assert.ok(f.notices.some(notice => notice.message === 'Toggle work shortcut: off'));
204
+ assert.ok(f.notices.some(notice => notice.message === 'Toggle work shortcut: on'));
205
+ f.shortcuts.get('ctrl+alt+w').handler();
206
+ assert.equal(header.open, false, 'return to the folded state before checking native thinking visibility');
207
+ final.row.setHideThinkingBlock(false);
208
+ assert.match(f.paint().text, /EXACT_FINAL_RECORDED_THINKING/, 'explicit native thinking expansion remains visible even when the strip is folded');
209
+ f.mode.setEnabled(false);
210
+ assert.equal(f.paint().text, stripAnsi(canonical.flatMap(row => row.render(100)).join('\n')), 'compact-off retains complete native rendering');
211
+ assert.equal(JSON.stringify(f.manager.getBranch()), messages, 'hierarchy and command controls leave recorded messages and evidence unchanged');
212
+ } finally { f.dispose(); f.mode.dispose(); }
213
+ }
214
+
215
+ {
216
+ const f = fixture();
217
+ try {
218
+ f.event('session_start');
219
+ for (const label of ['First completed turn.', 'Second completed turn.']) {
220
+ const user = f.add({ role: 'user', content: label });
221
+ f.tool(); const final = f.assistant(`DONE ${label}`); f.save(user, final);
222
+ }
223
+ f.event('session_start');
224
+ const headers = f.paint().rows.filter(row => row.constructor.name === 'WorkStripHeader');
225
+ assert.equal(headers.length, 2, 'fixture contains two completed work sections');
226
+ headers[0].manual = true; headers[0].open = true;
227
+ headers[1].manual = true; headers[1].open = false;
228
+ f.shortcuts.get('ctrl+alt+w').handler();
229
+ assert.deepEqual(headers.map(header => header.open), [false, false], 'any expanded eligible section makes the toggle collapse all eligible sections');
230
+ f.shortcuts.get('ctrl+alt+w').handler();
231
+ assert.deepEqual(headers.map(header => header.open), [true, true], 'when all eligible sections are collapsed, the toggle expands all');
232
+
233
+ f.event('agent_start');
234
+ f.add({ role: 'user', content: 'Waiting work.' }); f.tool();
235
+ f.event('message_start', { message: { role: 'assistant' } });
236
+ f.event('agent_settled');
237
+ const waiting = f.paint().rows.findLast(row => row.constructor.name === 'WorkStripHeader');
238
+ assert.equal(waiting.state, 'waiting', 'fixture contains a waiting work section');
239
+ waiting.open = true;
240
+ f.shortcuts.get('ctrl+alt+w').handler();
241
+ assert.equal(waiting.open, true, 'toggle leaves waiting work expanded while collapsing completed sections');
242
+ assert.deepEqual(headers.map(header => header.open), [false, false]);
243
+ } finally { f.dispose(); f.mode.dispose(); }
244
+ }
245
+
246
+ {
247
+ const f = fixture();
248
+ try {
249
+ f.event('session_start'); f.event('agent_start');
250
+ f.add({ role: 'user', content: 'Active recorded work.' }); f.tool();
251
+ const header = f.paint().rows.find(row => row.constructor.name === 'WorkStripHeader');
252
+ assert.equal(header.state, 'working');
253
+ await f.work('collapse'); f.shortcuts.get('ctrl+alt+w').handler();
254
+ assert.equal(header.open, true, 'bulk collapse controls preserve active work visibility');
255
+ } finally { f.dispose(); f.mode.dispose(); }
256
+ }
257
+
258
+ console.log('Work hierarchy: no strip for direct/thinking-only responses, saved evidence, native child indentation, mixed final spacing, commands and shortcut preference passed');