@notrico/pi-fold 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +129 -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-work-strip.mjs +84 -0
  11. package/scripts/preview.mjs +232 -0
  12. package/scripts/retained-memory-review.mjs +46 -0
  13. package/scripts/test.mjs +21 -0
  14. package/src/action-intent.ts +93 -0
  15. package/src/display-card.ts +64 -0
  16. package/src/display-line-cache.ts +26 -0
  17. package/src/display-mode.ts +33 -0
  18. package/src/fold-command.ts +61 -0
  19. package/src/inspection.ts +87 -0
  20. package/src/modern-code-content.ts +131 -0
  21. package/src/modern-code-pane.ts +101 -0
  22. package/src/modern-native-tools.ts +79 -0
  23. package/src/modern-prompts-adapter.ts +41 -0
  24. package/src/modern-prompts.ts +185 -0
  25. package/src/modern-recorded-pane.ts +68 -0
  26. package/src/modern-rich-text.ts +48 -0
  27. package/src/modern-skill-prompts.ts +152 -0
  28. package/src/modern-subagent-groups.ts +158 -0
  29. package/src/modern-subagent-messages.ts +176 -0
  30. package/src/modern-subagent-spacing.ts +35 -0
  31. package/src/modern-subagents.ts +52 -0
  32. package/src/modern-thinking-adapter.ts +85 -0
  33. package/src/modern-thinking.ts +236 -0
  34. package/src/modern-tool-content.ts +28 -0
  35. package/src/modern-tool-images.ts +63 -0
  36. package/src/modern-tool-pane.ts +208 -0
  37. package/src/modern-tools.ts +509 -0
  38. package/src/modern-workflows.ts +209 -0
  39. package/src/native-method-chain.ts +31 -0
  40. package/src/permission-presentation.ts +280 -0
  41. package/src/recorded-summary.ts +13 -0
  42. package/src/work-strip-subagents.ts +221 -0
  43. package/src/work-strip-view.ts +104 -0
  44. package/src/work-strip.ts +443 -0
  45. package/tests/action-intent.test.mjs +44 -0
  46. package/tests/codemode.test.mjs +365 -0
  47. package/tests/display-cache-lifecycle.test.mjs +55 -0
  48. package/tests/display-line-cache.test.mjs +48 -0
  49. package/tests/display-mode.test.mjs +25 -0
  50. package/tests/fixtures/preview-fixture.ts +81 -0
  51. package/tests/fold-command.test.mjs +150 -0
  52. package/tests/fold-shortcut.test.mjs +143 -0
  53. package/tests/input-focus.test.mjs +95 -0
  54. package/tests/inspection.test.mjs +50 -0
  55. package/tests/mixed-thinking.test.mjs +319 -0
  56. package/tests/modern-prompts.test.mjs +84 -0
  57. package/tests/modern-skill-prompts.test.mjs +174 -0
  58. package/tests/modern-subagent-groups.test.mjs +132 -0
  59. package/tests/modern-subagent-messages.test.mjs +137 -0
  60. package/tests/modern-thinking.test.mjs +202 -0
  61. package/tests/modern-tools.test.mjs +908 -0
  62. package/tests/modern-workflows.test.mjs +147 -0
  63. package/tests/ordinary-prompts.test.mjs +167 -0
  64. package/tests/permission-presentation.test.mjs +257 -0
  65. package/tests/preview-example.test.mjs +171 -0
  66. package/tests/reload-lifecycle.test.mjs +161 -0
  67. package/tests/subagent-spacing.test.mjs +34 -0
  68. package/tests/test-runtime.mjs +58 -0
  69. package/tests/work-strip-final-surface.test.mjs +271 -0
  70. package/tests/work-strip-hierarchy.test.mjs +258 -0
  71. package/tests/work-strip-preview.test.mjs +120 -0
  72. package/tests/work-strip-spacing.test.mjs +208 -0
  73. package/tests/work-strip-subagents.test.mjs +236 -0
  74. package/tests/work-strip.test.mjs +148 -0
@@ -0,0 +1,132 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadSource, loadAgent, core, tui, themeModule, stripAnsi } from './test-runtime.mjs';
3
+ const { SubagentProjection } = await loadSource('./modern-subagent-groups.ts');
4
+ const { registerModernTools } = await loadSource('./modern-tools.ts');
5
+ const { registerModernSubagentMessages } = await loadSource('./modern-subagent-messages.ts');
6
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
7
+ const { ToolExecutionComponent } = await loadAgent('modes/interactive/components/tool-execution.js');
8
+ const { CustomEntryComponent } = await loadAgent('modes/interactive/components/custom-entry.js');
9
+ const plain = c => c.render(95).map(stripAnsi).join('\n');
10
+ const result = (id, name, details = {}, error = false) => ({ role: 'toolResult', toolCallId: id, toolName: name, content: [{ type: 'text', text: 'Exact delivery receipt' }], details, isError: error, timestamp: 2 });
11
+ const call = (id, name, args) => ({ type: 'message', id: `call-${id}`, message: { role: 'assistant', content: [{ type: 'toolCall', id, name, arguments: args }], timestamp: 1 } });
12
+ const tool = (id, agent = 'worker') => [call(id, 'subagent', { agent, action: 'status' }), { type: 'message', id: `result-${id}`, message: result(id, 'subagent', { agent }) }];
13
+ const guideTool = (id, topic, { error = false, content = [{ type: 'text', text: 'Guide result details' }] } = {}) => [call(id, 'subagent', { action: 'guide', options: { topic } }), { type: 'message', id: `result-${id}`, message: { ...result(id, 'subagent', { mode: 'management', results: [] }), content, isError: error } }];
14
+ const notice = (id, agent = 'worker', status = 'completed') => ({ type: 'custom_message', id, customType: 'subagent-notify', display: true, content: 'Exact completion text', details: { runs: [{ agent, status }] }, timestamp: id });
15
+ const decision = (id = 'request-1') => ({ type: 'custom_message', id: `ask-${id}`, customType: 'subagent_supervisor_request', display: true, content: 'Original request framing', details: { id, requestId: id, reason: 'need_decision', agent: 'worker', runId: 'run-1', requestBody: 'Which exact option?' }, timestamp: id });
16
+ const answer = (id = 'request-1') => ({ type: 'custom', id: `entry-${id}`, customType: 'subagent_supervisor_reply', data: { requestId: id, agent: 'worker', runId: 'run-1', message: 'Use option A once.' } });
17
+ const exchange = (id = 'request-1', error = false) => [decision(id), call(`reply-${id}`, 'subagent_supervisor', { action: 'reply', replyTo: id }), answer(id), { type: 'message', id: `reply-result-${id}`, message: result(`reply-${id}`, 'subagent_supervisor', { replyTo: id }, error) }];
18
+ const message = entry => ({ role: 'custom', customType: entry.customType, details: entry.details, content: entry.content, timestamp: entry.timestamp, display: true });
19
+ const projection = new SubagentProjection();
20
+ const view = entry => projection.viewSource(entry.type === 'custom_message' ? message(entry) : entry);
21
+ let entries = [...tool('a'), notice('n', 'scout'), ...tool('b', 'scout')];
22
+ projection.rebuild(entries);
23
+ assert.match(projection.viewTool('a').pane.title, /^Subagents · 3 updates · worker, scout$/);
24
+ assert.equal(view(entries[2]).hidden, true);
25
+ assert.equal(projection.viewTool('b').hidden, true);
26
+ for (const boundary of [{ type: 'message', message: { role: 'user', content: 'Visible user text' } }, { type: 'message', message: { role: 'assistant', content: [{ type: 'text', text: 'Visible assistant text' }] } }, call('ordinary', 'read', {})]) {
27
+ projection.rebuild([...tool('a'), boundary, ...tool('b')]); assert.equal(projection.viewTool('a'), undefined); assert.equal(projection.viewTool('b'), undefined);
28
+ }
29
+ entries = exchange(); projection.rebuild(entries);
30
+ assert.equal(view(entries[0]).answered, true, 'call chronology allows reply entry to persist before result');
31
+ assert.equal(projection.viewTool('reply-request-1').hidden, true); assert.equal(view(entries[2]).hidden, true);
32
+ for (const broken of [exchange('bad', true), [decision('unmatched'), ...exchange('other').slice(1)], [decision('duplicate'), ...exchange('duplicate')], [decision('boundary'), { type: 'message', message: { role: 'user', content: 'Stop here' } }, ...exchange('boundary').slice(1)], [decision('pending')], [decision('bad-ack'), { ...call('ack', 'subagent_supervisor', { action: 'reply', replyTo: 'other' }) }, answer('bad-ack'), { type: 'message', message: result('ack', 'subagent_supervisor', { replyTo: 'bad-ack' }) }]]) {
33
+ projection.rebuild(broken); assert.equal(view(broken[0]), undefined, 'unresolved, failed, repeated or interrupted exchange stays separate');
34
+ }
35
+ for (const repeated of [[...exchange('repeat-answer'), { ...answer('repeat-answer'), id: 'second-answer' }], [...exchange('repeat-ack'), call('second-ack', 'subagent_supervisor', { action: 'reply', replyTo: 'repeat-ack' }), { type: 'message', message: result('second-ack', 'subagent_supervisor', { replyTo: 'repeat-ack' }) }], [decision('failed-status'), call('failed-status-ack', 'subagent_supervisor', { action: 'reply' }), answer('failed-status'), { type: 'message', message: result('failed-status-ack', 'subagent_supervisor', { replyTo: 'failed-status', status: 'failed' }) }]]) { projection.rebuild(repeated); assert.equal(view(repeated[0]), undefined); }
36
+ const imageAck = exchange('image-ack'); imageAck.at(-1).message.content.push({ type: 'image', data: 'exact-image', mimeType: 'image/png' }); projection.rebuild(imageAck); assert.equal(view(imageAck[0]), undefined, 'acknowledgement images preserve native standalone rendering');
37
+ projection.rebuild([notice('error', 'worker', 'failed'), ...tool('a'), notice('unknown', 'worker', 'future')]); assert.equal(projection.viewTool('a'), undefined);
38
+ for (const attention of [{ results: [{ exitCode: 2 }] }, { results: [{ interrupted: true }] }, { results: [{ detached: true }] }, { results: [{ execution: { status: 'running' } }] }]) {
39
+ projection.rebuild([...tool('a'), call('attention', 'subagent', { agent: 'worker' }), { type: 'message', message: result('attention', 'subagent', attention) }, ...tool('b')]); assert.equal(projection.viewTool('a'), undefined); assert.equal(projection.viewTool('attention'), undefined); assert.equal(projection.viewTool('b'), undefined);
40
+ }
41
+ const guideTopics = ['tool-reference/parameter-reference', 'tool-reference/execution-parameters', 'tool-reference/fork-context-details'];
42
+ const guideEntries = guideTopics.flatMap((topic, index) => guideTool(`guide-${index + 1}`, topic, { content: [{ type: 'text', text: `Exact guide response ${index + 1}` }] }));
43
+ projection.rebuild(guideEntries);
44
+ const guideView = projection.viewTool('guide-1');
45
+ assert.ok(guideView); assert.equal(guideView.pane.title, 'Subagents · 3 guide lookups');
46
+ assert.equal(projection.viewTool('guide-2').hidden, true); assert.equal(projection.viewTool('guide-3').hidden, true);
47
+ assert.deepEqual(guideView.pane.actions.map(item => item.label), guideTopics.map(topic => `Subagent · guide · ${topic}`));
48
+ guideView.pane.open = true; guideView.pane.actions.forEach(item => guideView.pane.expanded.add(item.id));
49
+ for (const [index, topic] of guideTopics.entries()) {
50
+ const action = guideView.pane.actions[index];
51
+ assert.ok(Array.from(action.sections()).some(item => item.text === `Exact guide response ${index + 1}`));
52
+ const exactDetails = Array.from(action.details());
53
+ assert.ok(exactDetails.some(item => JSON.stringify(item).includes(topic)));
54
+ assert.ok(exactDetails.some(item => JSON.stringify(item).includes('management')));
55
+ }
56
+ const longTopic = 't'.repeat(80);
57
+ projection.rebuild(guideTool('long-guide', longTopic));
58
+ assert.equal(projection.viewTool('long-guide'), undefined, 'a singleton guide remains standalone');
59
+ const runningGuide = [call('running-guide', 'subagent', { action: 'guide', options: { topic: 'running-topic' } })];
60
+ projection.rebuild(runningGuide); assert.equal(projection.viewTool('running-guide'), undefined);
61
+ for (const invalid of [
62
+ [...guideTool('failed-guide', 'failed-topic', { error: true }), ...guideTool('after-failure', 'after-topic')],
63
+ [...guideTool('nontext-guide', 'image-topic', { content: [{ type: 'text', text: 'text' }, { type: 'image', data: 'exact-image', mimeType: 'image/png' }] }), ...guideTool('after-image', 'after-topic')],
64
+ [...guideTool('guide-before-status', 'before-topic'), ...tool('runtime-status'), ...guideTool('guide-after-status', 'after-topic')],
65
+ [...guideTool('guide-before-running', 'before-topic'), call('running-guide-boundary', 'subagent', { action: 'guide', options: { topic: 'running-topic' } }), ...guideTool('guide-after-running', 'after-topic')],
66
+ [...guideTool('guide-before-user', 'before-topic'), { type: 'message', message: { role: 'user', content: 'Visible user text' } }, ...guideTool('guide-after-user', 'after-topic')],
67
+ [...guideTool('guide-before-assistant', 'before-topic'), { type: 'message', message: { role: 'assistant', content: [{ type: 'text', text: 'Visible assistant text' }] } }, ...guideTool('guide-after-assistant', 'after-topic')],
68
+ ]) {
69
+ projection.rebuild(invalid);
70
+ for (const id of ['failed-guide', 'after-failure', 'nontext-guide', 'after-image', 'guide-before-status', 'runtime-status', 'guide-after-status', 'guide-before-running', 'running-guide-boundary', 'guide-after-running', 'guide-before-user', 'guide-after-user', 'guide-before-assistant', 'guide-after-assistant']) assert.equal(projection.viewTool(id), undefined, 'failed, running, non-text, visible, or runtime boundaries keep guide rows standalone');
71
+ }
72
+ for (const custom of [notice('paused', 'worker', 'paused'), notice('stopped', 'worker', 'stopped'), { ...notice('future'), customType: 'future-subagent-event' }]) { projection.rebuild([...tool('a'), custom, ...tool('b')]); assert.equal(projection.viewTool('a'), undefined); assert.equal(view(custom), undefined); }
73
+ projection.rebuild([...tool('a'), call('future', 'subagent_future', { agent: 'worker' }), { type: 'message', message: result('future', 'subagent_future') }, ...tool('b')]); assert.equal(projection.viewTool('a'), undefined); assert.equal(projection.viewTool('future'), undefined);
74
+ projection.clear(); projection.start('live-a', 'subagent', { agent: 'worker' }); projection.end('live-a', 'subagent', result('live-a', 'subagent')); projection.observe({ role: 'custom', customType: 'invisible-housekeeping', display: false, content: 'invisible' }); projection.start('live-b', 'subagent', { agent: 'scout' }); projection.end('live-b', 'subagent', result('live-b', 'subagent'));
75
+ const livePane = projection.viewTool('live-a').pane; livePane.open = true; livePane.expanded.add('tool:live-a'); livePane.render(95);
76
+ projection.end('live-a', 'subagent', { ...result('live-a', 'subagent'), content: [{ type: 'text', text: 'Updated exact receipt' }] });
77
+ projection.viewTool('live-a');
78
+ assert.match(livePane.render(95).map(stripAnsi).join('\n'), /Updated exact receipt/, 'changed results invalidate existing bounded pane');
79
+
80
+ const hooks = new Map(), bus = new Map(), inputs = new Set(), mounted = []; let resolver;
81
+ const on = (map, key, fn) => { const set = map.get(key) || new Set(); map.set(key, set); set.add(fn); return () => set.delete(fn); };
82
+ const pi = { on: (key, fn) => on(hooks, key, fn), registerToolRenderer(fn) { resolver = fn; }, events: { on: (key, fn) => on(bus, key, fn), emit(key, value) { for (const fn of [...bus.get(key) || []]) fn(value); } } };
83
+ const mode = createDisplayMode();
84
+ const disposeTools = registerModernTools(pi, mode), disposeMessages = registerModernSubagentMessages(pi, mode);
85
+ const nativeMessage = () => new tui.Text('Exact native custom rows', 0, 0), nativeEntry = () => new tui.Text('Exact native entry rows', 0, 0);
86
+ const runner = new core.ExtensionRunner([{ messageRenderers: new Map(['subagent-notify', 'subagent_supervisor_request'].map(t => [t, nativeMessage])), entryRenderers: new Map([['subagent_supervisor_reply', nativeEntry]]) }], {}, '/synthetic', {}, {});
87
+ const session = core.SessionManager.inMemory('/synthetic');
88
+ for (const entry of [...tool('mounted-a'), notice('mounted-notice', 'scout'), ...tool('mounted-b', 'scout'), ...exchange(), notice('failure', 'worker', 'failed'), decision('pending')]) {
89
+ if (entry.type === 'message') session.appendMessage(entry.message);
90
+ else if (entry.type === 'custom_message') session.appendCustomMessageEntry(entry.customType, entry.content, true, entry.details);
91
+ else session.appendCustomEntry(entry.customType, entry.data);
92
+ }
93
+ const saved = JSON.stringify(session.getEntries()); let reads = 0;
94
+ const ctx = { mode: 'tui', hasUI: true, sessionManager: { getLeafId: () => session.getLeafId(), buildContextEntries() { reads++; return session.buildContextEntries(); } }, ui: { theme: themeModule.theme, setHiddenThinkingLabel() { for (const c of mounted) c.invalidate(); }, onTerminalInput(fn) { inputs.add(fn); return () => inputs.delete(fn); } } };
95
+ const emit = (key, value = {}) => { for (const fn of [...hooks.get(key) || []]) fn(value, ctx); };
96
+ const choices = () => { const out = []; pi.events.emit('compact-renderer:inspect:v1', { add: c => out.push(c) }); return out; };
97
+ const key = text => [...inputs].some(fn => fn(text)?.consume);
98
+ function mount() {
99
+ mounted.length = 0; let projected;
100
+ core.InteractiveMode.prototype.renderSessionEntries.call({ renderer: undefined, renderSessionItems(items) { projected = items; } }, session.buildContextEntries());
101
+ const tools = new Map();
102
+ for (const item of projected) {
103
+ if (item.role === 'assistant') for (const call of item.content || []) if (call.type === 'toolCall') {
104
+ const native = { renderCall: () => new tui.Text('Exact native call', 0, 0), renderResult: () => new tui.Text('Exact native result', 0, 0) };
105
+ const c = new ToolExecutionComponent(call.name, call.id, call.arguments, { showImages: false, outputPad: 0 }, resolver(call.name, () => native), { requestRender() {} }, '/synthetic'); c.setArgsComplete(); tools.set(call.id, c); mounted.push(c);
106
+ }
107
+ if (item.role === 'toolResult') tools.get(item.toolCallId).updateResult(item);
108
+ if (item.role === 'custom') mounted.push(new core.CustomMessageComponent(item, runner.getMessageRenderer(item.customType), themeModule.getMarkdownTheme()));
109
+ if (item.type === 'custom') mounted.push(new CustomEntryComponent(item, runner.getEntryRenderer(item.customType)));
110
+ }
111
+ }
112
+ try {
113
+ emit('session_start'); mount();
114
+ assert.match(plain(mounted[0]), /Subagents · 3 updates · worker, scout/);
115
+ assert.deepEqual(mounted[1].render(95), [], 'native custom follower has zero spacer rows'); assert.deepEqual(mounted[2].render(95), []);
116
+ assert.match(plain(mounted[3]), /worker · Decision answered/); assert.deepEqual(mounted[4].render(95), []); assert.deepEqual(mounted[5].render(95), [], 'native entry follower has zero spacer rows');
117
+ assert.match(plain(mounted[6]), /failed/); assert.match(plain(mounted[7]), /needs a decision/);
118
+ assert.equal(key('\x1b[B'), false, 'editor owns arrows before focus');
119
+ const decisionChoice = choices().find(c => c.label.includes('Decision answered')); assert.ok(decisionChoice); decisionChoice.focus();
120
+ assert.match(plain(mounted[3]), /Which exact option\?/); assert.equal((plain(mounted[3]).match(/Use option A once\./g) || []).length, 1); assert.match(plain(mounted[3]), /Supervisor reply/); assert.doesNotMatch(plain(mounted[3]), /User reply|request-1|Exact delivery receipt/);
121
+ assert.ok(mounted[3].render(95).join('').includes(themeModule.theme.getFgAnsi('customMessageLabel')));
122
+ assert.equal(key('\t'), true); assert.equal(key('\r'), true); let details = plain(mounted[3]);
123
+ for (let i = 0; i < 80 && !details.includes('Reply delivery'); i++) { key('\x1b[B'); details = plain(mounted[3]); }
124
+ assert.match(details, /Reply delivery/); assert.equal(key('x'), false); assert.equal(key('\r'), false);
125
+ const beforeReads = reads; for (let i = 0; i < 100; i++) mounted.forEach(c => c.render(95)); assert.equal(reads, beforeReads, 'unchanged leaf paints do not rebuild whole history');
126
+ mode.setEnabled(false);
127
+ assert.match(plain(mounted[0]), /Exact native call/); assert.match(plain(mounted[1]), /Exact native custom rows/); assert.match(plain(mounted[5]), /Exact native entry rows/); assert.equal(choices().length, 0);
128
+ mode.setEnabled(true); assert.deepEqual(mounted[1].render(95), []); assert.deepEqual(mounted[5].render(95), []);
129
+ for (const event of ['session_tree', 'session_compact']) { emit(event); mount(); assert.match(plain(mounted[0]), /3 updates/); assert.match(plain(mounted[3]), /Decision answered/); }
130
+ assert.equal(JSON.stringify(session.getEntries()), saved, 'all exact transcript entries remain unchanged');
131
+ console.log('subagent groups: mixed native hosts, live/replay chronology, decision IDs, boundaries, exact off, focus and bounded paints passed');
132
+ } finally { disposeMessages(); disposeTools(); mode.dispose(); }
@@ -0,0 +1,137 @@
1
+ import assert from 'node:assert/strict';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { loadSource, loadAgent, runtime, core, tui, themeModule, stripAnsi } from './test-runtime.mjs';
5
+ const { registerModernSubagentMessages, installSubagentMessageAdapter, subagentMessageSummary } = await loadSource('./modern-subagent-messages.ts');
6
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
7
+ const { CustomEntryComponent } = await loadAgent('modes/interactive/components/custom-entry.js');
8
+ const stock = await import(pathToFileURL(path.join(runtime, 'node_modules/pi-subagents/src/tui/subagent-messages.js')).href);
9
+ const plain = rows => rows.map(stripAnsi).join('\n');
10
+ const listeners = new Map(), bus = new Map(), terminal = new Set(), mounted = [];
11
+ const on = (map, key, fn) => { const set = map.get(key) || new Set(); map.set(key, set); set.add(fn); return () => set.delete(fn); };
12
+ const pi = { on: (event, fn) => on(listeners, event, fn), events: { on: (event, fn) => on(bus, event, fn), emit: (event, value) => { for (const fn of [...bus.get(event) || []]) fn(value); } } };
13
+ const ctx = { mode: 'tui', ui: { theme: themeModule.theme, setHiddenThinkingLabel() { for (const c of mounted) c.invalidate(); }, onTerminalInput(fn) { terminal.add(fn); return () => terminal.delete(fn); } } };
14
+ const emit = (event, value = {}) => { for (const fn of [...listeners.get(event) || []]) fn(value, ctx); };
15
+ const key = data => [...terminal].some(fn => fn(data)?.consume);
16
+ const mode = createDisplayMode();
17
+ const notice = (customType, details, content = 'Original child content\nExact recorded second line 行🙂') => ({ role: 'custom', customType, display: true, content, details, timestamp: 1 });
18
+ const ask = notice('subagent_supervisor_request', { id: 'req-1', requestId: 'req-1', reason: 'need_decision', expectsReply: true, runId: 'run-1', agent: 'worker', childIndex: 0, requestBody: 'Choose one', replyHint: 'reply req-1' });
19
+ const completion = notice('subagent-notify', { runs: [{ agent: 'worker', status: 'completed', runId: 'run-1' }] });
20
+ const failed = notice('subagent-notify', { runs: [{ agent: 'worker', status: 'failed', runId: 'run-2' }] });
21
+ const reply = { type: 'custom', customType: 'subagent_supervisor_reply', data: { requestId: 'req-1', reason: 'need_decision', runId: 'run-1', agent: 'worker', childIndex: 0, message: 'Exact supervisor answer', createdAt: 2 } };
22
+ const originalData = JSON.stringify([ask, completion, failed, reply]);
23
+ const nativeMessage = source => new tui.Text(`native message ${source.customType}`, 0, 0);
24
+ const nativeEntry = source => new tui.Text(`native entry ${source.customType}`, 0, 0);
25
+ const types = ['subagent_supervisor_request', 'subagent-notify', 'subagent_steering_notice', 'unrelated'];
26
+ const extension = { messageRenderers: new Map(types.map(t => [t, nativeMessage])), entryRenderers: new Map([['subagent_supervisor_reply', nativeEntry]]) };
27
+ const empty = { messageRenderers: new Map(), entryRenderers: new Map() };
28
+ const runner = entries => new core.ExtensionRunner(entries, {}, '/synthetic', {}, {});
29
+ const runners = [runner([extension, empty]), runner([empty, extension])];
30
+ const originalMethods = { message: core.ExtensionRunner.prototype.getMessageRenderer, entry: core.ExtensionRunner.prototype.getEntryRenderer };
31
+ let dispose = registerModernSubagentMessages(pi, mode);
32
+ const choices = () => { const result = []; pi.events.emit('compact-renderer:inspect:v1', { add: c => result.push(c) }); return result; };
33
+ const make = (source, r = runners[0]) => new core.CustomMessageComponent(source, r.getMessageRenderer(source.customType), themeModule.getMarkdownTheme());
34
+ try {
35
+ const beforeStartup = runners[0].getMessageRenderer(ask.customType);
36
+ assert.match(plain(beforeStartup(ask, { expanded: false }, themeModule.theme).render(90)), /native message/, 'before TUI startup rendering remains native');
37
+ emit('session_start'); assert.equal(terminal.size, 1);
38
+ for (const r of runners) assert.notEqual(r.getMessageRenderer(ask.customType), nativeMessage, 'native renderer resolution works in either load order');
39
+ assert.equal(runners[0].getMessageRenderer('unrelated'), nativeMessage);
40
+ assert.equal(runners[0].getMessageRenderer('absent'), undefined);
41
+ mounted.push(make(ask), make(completion), make(failed));
42
+ const askCard = mounted[0], completionCard = mounted[1], failedCard = mounted[2];
43
+ assert.match(plain(askCard.render(90)), /worker · needs a decision/);
44
+ assert.doesNotMatch(plain(askCard.render(90)), /Original child content/);
45
+ assert.ok(askCard.render(90).join('').includes(themeModule.theme.getFgAnsi('customMessageLabel')));
46
+ assert.ok(failedCard.render(90).join('').includes(themeModule.theme.getFgAnsi('error')));
47
+ assert.ok(completionCard.render(90).join('').includes(themeModule.theme.getFgAnsi('mdLink')));
48
+ const boldTheme = Object.assign(Object.create(themeModule.theme), { bold: text => `\x1b[1m${text}\x1b[22m` });
49
+ const styledHeader = source => runners[0].getMessageRenderer(source.customType)(source, { expanded: false }, boldTheme).render(90)[0];
50
+ assert.doesNotMatch(styledHeader(completion), /\x1b\[1m/, 'routine subagent completion has normal weight');
51
+ assert.ok(styledHeader(completion).includes(themeModule.theme.getFgAnsi('muted')), 'subagent metadata uses muted text');
52
+ assert.match(styledHeader(ask), /\x1b\[1m/, 'subagent decision retains its weight');
53
+ assert.match(styledHeader(failed), /\x1b\[1m/, 'subagent failure retains its weight');
54
+ assert.equal(key('\x1b[B'), false, 'editor keeps arrows before inspection');
55
+ let focus; const off = pi.events.on('compact-renderer:focus:v1', event => focus = event);
56
+ const askChoice = choices().find(c => /needs a decision/.test(c.label));
57
+ askChoice.focus(); assert.equal(focus.owner, 'subagents');
58
+ assert.ok(focus.target(askCard.customComponent)); off();
59
+ assert.match(plain(askCard.render(90)), /Original child content/);
60
+ assert.match(plain(askCard.render(90)), /Exact recorded second line 行🙂/);
61
+ assert.doesNotMatch(plain(askCard.render(90)), /reply req-1/, 'metadata starts collapsed');
62
+ assert.equal(key('\t'), true); assert.equal(key('\r'), true);
63
+ let detailRows = plain(askCard.render(90));
64
+ for (let i = 0; i < 8 && !detailRows.includes('reply req-1'); i++) { key('\x1b[B'); detailRows = plain(askCard.render(90)); }
65
+ assert.match(detailRows, /reply req-1/, 'Details retains exact structured fields');
66
+ assert.equal(key('x'), false, 'ordinary input returns to the editor without consumption');
67
+ assert.equal(key('\x1b[B'), false);
68
+ choices()[0].focus(); emit('ui_prompt_start'); assert.equal(key('\r'), false);
69
+ choices()[0].focus(); pi.events.emit('compact-renderer:focus:v1', { owner: 'tools' }); assert.equal(key('\r'), false);
70
+ choices()[0].focus(); assert.equal(key('\x1b'), true); assert.equal(key('\r'), false);
71
+ const replyCard = new CustomEntryComponent(reply, runners[0].getEntryRenderer(reply.customType)); mounted.push(replyCard);
72
+ assert.match(plain(replyCard.render(90)), /reply sent to worker/);
73
+ choices().find(c => /reply sent/.test(c.label)).focus(); assert.match(plain(replyCard.render(90)), /Exact supervisor answer/);
74
+ mode.setEnabled(false);
75
+ const resolvedWhileOff = runners[0].getMessageRenderer(ask.customType);
76
+ assert.match(plain(resolvedWhileOff(ask, { expanded: false }, themeModule.theme).render(90)), /native message/, 'off delegates to original renderer');
77
+ assert.match(plain(runners[0].getEntryRenderer(reply.customType)(reply, { expanded: false }, themeModule.theme).render(90)), /native entry/);
78
+ assert.match(plain(askCard.render(90)), /native message/);
79
+ assert.match(plain(replyCard.render(90)), /native entry/);
80
+ assert.equal(choices().length, 0); assert.equal(key('\r'), false);
81
+ mode.setEnabled(true); assert.match(plain(askCard.render(90)), /needs a decision/);
82
+ assert.match(plain(resolvedWhileOff(ask, { expanded: false }, themeModule.theme).render(90)), /needs a decision/, 'a renderer resolved while off supports subsequent activation');
83
+ assert.match(plain(beforeStartup(ask, { expanded: false }, themeModule.theme).render(90)), /needs a decision/, 'a renderer resolved before startup supports transcript replay');
84
+ const stockRunner = runner([{ messageRenderers: new Map([[ask.customType, stock.renderSubagentMessage]]), entryRenderers: new Map([[reply.customType, stock.renderSubagentEntry]]) }]);
85
+ mode.setEnabled(false);
86
+ const offCard = make(ask); mounted.push(offCard); assert.match(plain(offCard.render(90)), /native message/);
87
+ const stockOff = make(ask, stockRunner), exactStock = new core.CustomMessageComponent(ask, stock.renderSubagentMessage, themeModule.getMarkdownTheme());
88
+ assert.deepEqual(stockOff.render(90), exactStock.render(90), 'off preserves exact installed native renderer rows');
89
+ const stockReplyOff = new CustomEntryComponent(reply, stockRunner.getEntryRenderer(reply.customType));
90
+ assert.deepEqual(stockReplyOff.render(90), new CustomEntryComponent(reply, stock.renderSubagentEntry).render(90), 'off preserves exact installed native reply renderer');
91
+ mode.setEnabled(true); assert.match(plain(offCard.render(90)), /needs a decision/, 'native CustomMessageComponent invalidation uses its cached dynamic renderer after enabling');
92
+ const malformed = make(notice('subagent-notify', { runs: [{ status: 'mystery' }] }));
93
+ assert.match(plain(malformed.render(90)), /native message/);
94
+ assert.match(plain(make({ ...completion, content: [{ type: 'text', text: 'text' }, { type: 'image', data: 'synthetic' }] }).render(90)), /native message/, 'unsupported content arrays preserve the full native renderer');
95
+ assert.equal(subagentMessageSummary(notice('future-subagent-type', {})), undefined);
96
+ assert.equal(subagentMessageSummary(notice('subagent_steering_notice', { runId: 'run-1', state: 'queued' })), undefined, 'unrecognized state must not imply delivery');
97
+ assert.match(subagentMessageSummary(notice('subagent_steering_notice', { runId: 'run-1', state: 'partial' })).title, /partial/);
98
+ // Restored native projection recreates message objects; no content matching or transcript mutation is needed.
99
+ mounted.length = 0; emit('session_start', { reason: 'resume' });
100
+ mounted.push(make(JSON.parse(JSON.stringify(ask)))); assert.match(plain(mounted[0].render(90)), /needs a decision/); assert.equal(choices().length, 1);
101
+ const recorded = core.SessionManager.inMemory('/synthetic');
102
+ recorded.appendCustomMessageEntry(ask.customType, ask.content, true, ask.details);
103
+ recorded.appendCustomEntry(reply.customType, reply.data);
104
+ const saved = JSON.stringify(recorded.getEntries());
105
+ const resumed = core.SessionManager.inMemory('/synthetic', undefined, JSON.parse(saved));
106
+ mounted.length = 0; emit('session_start', { reason: 'resume' });
107
+ let projected;
108
+ core.InteractiveMode.prototype.renderSessionEntries.call({ renderer: undefined, renderSessionItems(items) { projected = items; } }, resumed.buildContextEntries());
109
+ const restoredAsk = projected.find(item => item.role === 'custom');
110
+ const restoredReply = projected.find(item => item.type === 'custom');
111
+ assert.ok(restoredAsk); assert.ok(restoredReply);
112
+ mounted.push(make(restoredAsk), new CustomEntryComponent(restoredReply, runners[0].getEntryRenderer(restoredReply.customType)));
113
+ assert.match(plain(mounted[0].render(90)), /needs a decision/); assert.match(plain(mounted[1].render(90)), /reply sent to worker/);
114
+ assert.equal(JSON.stringify(resumed.getEntries()), saved, 'native resumed session entries remain unchanged');
115
+ for (const event of ['session_tree', 'session_compact']) { emit(event); assert.equal(terminal.size, 1); assert.equal(choices().length, 0); mounted.length = 0; mounted.push(make(ask)); }
116
+ // Large primary content and metadata are lazy: later metadata getters stay untouched.
117
+ let visited = 0;
118
+ const large = notice('subagent_supervisor_request', { ...ask.details, get hiddenPayload() { visited++; return 'never reached on first paint'; } }, 'Original long recorded content 行🙂\n'.repeat(100000));
119
+ const largeCard = make(large); mounted.push(largeCard); largeCard.setExpanded(true);
120
+ const rows = largeCard.render(60); assert.ok(rows.length <= 14); assert.equal(visited, 0);
121
+ assert.match(plain(rows), /Original long recorded content/);
122
+ const cardChoices = choices(); cardChoices.at(-1).focus(); largeCard.render(60); assert.equal(key('\t'), true); assert.equal(key('\r'), true);
123
+ assert.match(plain(largeCard.render(60)), /content above ↑/); assert.ok(largeCard.render(60).length <= 14);
124
+ // Mouse inspection never captures editor keys.
125
+ const inner = mounted[0].customComponent; inner.render(90); inner.handleMouse({ type: 'click', button: 'left', x: 2, y: 0 }); assert.equal(key('\r'), false);
126
+ assert.equal(JSON.stringify([ask, completion, failed, reply]), originalData);
127
+ emit('session_before_switch'); assert.equal(terminal.size, 0); assert.match(plain(runners[0].getMessageRenderer(ask.customType)(ask, { expanded: false }, themeModule.theme).render(90)), /native message/);
128
+ emit('session_start'); assert.equal(terminal.size, 1);
129
+ emit('session_shutdown'); assert.equal(terminal.size, 0);
130
+ dispose(); dispose(); assert.equal(core.ExtensionRunner.prototype.getMessageRenderer, originalMethods.message); assert.equal(core.ExtensionRunner.prototype.getEntryRenderer, originalMethods.entry);
131
+ assert.match(plain(largeCard.render(60)), /native message/);
132
+ assert.equal(installSubagentMessageAdapter(() => {}, '9.0.0'), undefined);
133
+ assert.equal(installSubagentMessageAdapter(() => {}, '1.1.0'), undefined);
134
+ dispose = registerModernSubagentMessages(pi, mode); emit('session_start');
135
+ const staleDispose = dispose; dispose = registerModernSubagentMessages(pi, mode); assert.equal(terminal.size, 0); emit('session_start'); staleDispose(); assert.equal(terminal.size, 1);
136
+ console.log('modern subagent messages: native resolution, exact fallback, replies, lifecycle, inspection and bounded content passed');
137
+ } finally { dispose(); mode.dispose(); }
@@ -0,0 +1,202 @@
1
+ import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import { loadSource, core, tui, themeModule, stripAnsi, assertCardBackground } from './test-runtime.mjs';
4
+ const { registerModernThinking, recordedThinkingLabel } = await loadSource('./modern-thinking.ts');
5
+ const { installModernThinkingAdapter } = await loadSource('./modern-thinking-adapter.ts');
6
+ const { RecordedTextPane } = await loadSource('./modern-recorded-pane.ts');
7
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
8
+ const { AssistantMessageComponent } = core;
9
+ const plain = lines => lines.map(stripAnsi).join('\n');
10
+ const round = n => ({ role: 'assistant', content: [{type:'thinking',thinking:`Round-${n} original first\nsecond original ${n}\n最后🙂`},{type:'toolCall',id:`c${n}`,name:'read',arguments:{path:'/fixture'}}], stopReason:'toolUse' });
11
+ const result = n => ({role:'toolResult',toolName:'read',toolCallId:`c${n}`,isError:false,content:[{type:'text',text:'fixture'}]});
12
+ const entry = message => ({type:'message',message});
13
+ const rounds = [round(1), round(2), round(3)];
14
+ let branch = rounds.flatMap((m,i) => [entry(m),entry(result(i+1))]);
15
+ const originalBranch = JSON.stringify(branch);
16
+ const listeners = new Map(), bus = new Map(), terminal = new Set(), cards = [];
17
+ const subscribe = (map,key,fn) => { const set = map.get(key)||new Set();map.set(key,set);set.add(fn);return()=>set.delete(fn); };
18
+ const pi = { on:(event,fn)=>subscribe(listeners,event,fn), events:{on:(event,fn)=>subscribe(bus,event,fn),emit:(event,data)=>{for(const fn of [...bus.get(event)||[]])fn(data);}} };
19
+ const mode = createDisplayMode();
20
+ const ctx = {mode:'tui',sessionManager:{getBranch:()=>branch},ui:{theme:themeModule.theme,setHiddenThinkingLabel(){for(const c of cards)c.setHiddenThinkingLabel('Thinking...');},onTerminalInput(fn){terminal.add(fn);return()=>terminal.delete(fn);}}};
21
+ const emit = (event,data={}) => { for(const fn of [...listeners.get(event)||[]])fn(data,ctx); };
22
+ const key = data => [...terminal].some(fn => fn(data)?.consume);
23
+ const native = {update:AssistantMessageComponent.prototype.updateContent,render:AssistantMessageComponent.prototype.render,mouse:AssistantMessageComponent.prototype.handleMouse};
24
+ let dispose = registerModernThinking(pi,mode);
25
+ emit('session_start',{type:'session_start',reason:'startup'});
26
+ try {
27
+ cards.push(...rounds.map(m => new AssistantMessageComponent(m,true,themeModule.getMarkdownTheme())));
28
+ assert.deepEqual(cards.slice(0,2).map(c=>c.render(70)),[[],[]]);
29
+ assert.match(plain(cards[2].render(70)),/Thinking · 3 rounds/);
30
+ const collapsedThinking = cards[2].render(100);
31
+ assert.ok(collapsedThinking.find(row => stripAnsi(row).includes('Thinking ·')).includes(themeModule.theme.getFgAnsi('thinkingText')), 'thinking heading uses native muted neutral tone');
32
+ assert.equal(collapsedThinking.length, 2, 'one native spacer plus one neutral summary');
33
+ assert.match(stripAnsi(collapsedThinking[1]), /^ ▸ Thinking/);
34
+ assert.doesNotMatch(collapsedThinking.join(''), /\x1b\[(?:4[0-8]|10[0-7])(?:[;m])/, 'unfocused summary has no filled surface');
35
+ assert.doesNotMatch(plain(cards[2].render(100)), /Alt\+T/, 'collapsed thinking omits repeated key hints');
36
+ assert.equal(key('\x1b[B'),false,'arrows stay with editor until focused');
37
+ const choices = []; pi.events.emit('compact-renderer:inspect:v1', {add: choice => choices.push(choice)});
38
+ assert.equal(choices.length, 1); assert.equal(choices[0].kind, 'Thinking');
39
+ let focusEvent; const unsubFocus = pi.events.on('compact-renderer:focus:v1', event => focusEvent = event);
40
+ choices[0].focus(); assert.ok(focusEvent.target(cards[2])); assert.ok(!focusEvent.target(cards[0])); unsubFocus();
41
+ const roundList = cards[2].render(100);
42
+ assert.match(plain(roundList), /1\. Round-1 original first/);
43
+ assert.match(plain(roundList), /2\. Round-2 original first/);
44
+ assert.match(plain(roundList), /3\. Round-3 original first/);
45
+ assert.doesNotMatch(plain(roundList), /second original/, 'opening a group shows excerpts with each round still collapsed');
46
+ assert.equal(key('\r'),true);
47
+ const expandedThinking = cards[2].render(100);
48
+ const selectedHeading = expandedThinking.find(line => stripAnsi(line).includes('Thinking ·'));
49
+ assertCardBackground([selectedHeading], 100, 'selectedBg');
50
+ const thinkingBody = expandedThinking.find(row => stripAnsi(row).includes('second original 1'));
51
+ assert.ok(thinkingBody.includes(themeModule.theme.getFgAnsi('text')), 'recorded thinking uses readable native text');
52
+ assert.ok(!thinkingBody.includes(themeModule.theme.getFgAnsi('thinkingText')), 'body does not inherit dim thinking foreground');
53
+ assert.match(stripAnsi(thinkingBody), /^ +second original 1/, 'recorded thinking sits inside its round heading');
54
+ assert.match(stripAnsi(expandedThinking.at(-1)), /^ ←\/→ round/, 'footer describes round selection');
55
+ for(let n=2;n<=3;n++){key('\x1b[C');key('\r');assert.match(plain(cards[2].render(100)),new RegExp(`second original ${n}`));}
56
+ key('\x1b[D'); assert.match(plain(cards[2].render(100)), /▾ 2\. Round-2/, 'round expansion survives selection changes');
57
+ assert.equal(key('\x1b'),true);assert.equal(key('\x1b[B'),false);
58
+ key('\x1bt');pi.events.emit('compact-renderer:focus:v1',{owner:'tools'});assert.equal(key('\r'),false);
59
+ key('\x1bt');emit('ui_prompt_start');assert.equal(key('\r'),false);
60
+ const mouseThinking = (y, type = 'click') => cards[2].handleMouse({ type, button: type === 'click' ? 'left' : 'none', x: 2, y, screenX: 2, screenY: y, width: 100, height: cards[2].render(100).length, wheelDelta: 1, shift: false, alt: false, ctrl: false });
61
+ assert.equal(mouseThinking(1).handled, true);
62
+ assert.doesNotMatch(plain(cards[2].render(100)), /Round-1 original first/);
63
+ assert.equal(key('\r'), false, 'mouse collapse leaves Enter with editor');
64
+ mouseThinking(1);
65
+ assert.match(plain(cards[2].render(100)), /Round-2 original first/);
66
+ assert.doesNotMatch(plain(cards[2].render(100)), /focused/);
67
+ assert.equal(key('\r'), false, 'mouse expansion leaves Enter with editor');
68
+ for(const width of [1,2,3,8,24,70]) for(const row of cards[2].render(width))assert.ok(tui.visibleWidth(row)<=width);
69
+ for(const c of cards)c.setHideThinkingBlock(false);
70
+ for(let i=0;i<3;i++)assert.match(plain(cards[i].render(70)),new RegExp(`Round-${i+1} original first`));
71
+ for(const c of cards)c.setHideThinkingBlock(true);
72
+ cards[0].thinkingVisibilityOverrides.set(0,false);cards[0].updateContent(rounds[0]);
73
+ assert.ok(cards.every(c=>c.render(70).length>0),'one native override restores every member');
74
+ cards[0].setHideThinkingBlock(true);
75
+ mode.setEnabled(false);assert.ok(cards.every(c=>c.render(70).length>0));mode.setEnabled(true);assert.equal(cards[0].render(70).length,0);
76
+ // Actual resumed/rebuilt native components, with public lifecycle boundaries.
77
+ for(const event of ['session_tree','session_compact']) {
78
+ emit(event);assert.match(plain(cards[2].render(70)),/Thinking · 3 rounds/);assert.equal(terminal.size,1);
79
+ }
80
+ const error = {...result(3),isError:true};
81
+ const visible = {role:'assistant',content:[{type:'text',text:'Visible answer'}],stopReason:'stop'};
82
+ for(const boundary of [visible,error,{role:'user',content:'question'},{type:'toolResult',role:'toolResult',toolName:'ask_user_question',content:[],isError:false}]) {
83
+ const a=round(8), b=round(9);branch=[entry(a),entry(boundary),entry(b)];cards.length=0;emit('session_start',{type:'session_start',reason:'resume'});
84
+ cards.push(new AssistantMessageComponent(a,true,themeModule.getMarkdownTheme()),new AssistantMessageComponent(b,true,themeModule.getMarkdownTheme()));
85
+ assert.ok(cards.every(c=>/Thinking · Round-[89] original first/.test(plain(c.render(70)))));
86
+ }
87
+ // Public streaming events may replace message objects; preserve recorded order.
88
+ branch=[];cards.length=0;emit('session_start',{type:'session_start',reason:'resume'});
89
+ const start=round(10);emit('message_start',{message:start});cards.push(new AssistantMessageComponent(start,true,themeModule.getMarkdownTheme()));
90
+ const update={...start,content:[{type:'thinking',thinking:'Updated exact recorded text'},start.content[1]]};emit('message_update',{message:update});cards[0].updateContent(update);emit('message_end',{message:update});
91
+ assert.match(plain(cards[0].render(70)),/▸ Thinking · Updated exact recorded text/);
92
+ key('\x1bt');key('\r');assert.match(plain(cards[0].render(70)),/▾ Thinking · Updated exact recorded text/);
93
+ const singleRows = cards[0].render(70).map(stripAnsi);
94
+ assert.match(singleRows[2], /^ Updated exact recorded text/, 'thinking content follows its header without an added gap; sole content remains visible');
95
+ const repeatedSource = '# Exact thinking title\n\nFirst thinking paragraph.\n\nSecond thinking paragraph.';
96
+ const repeated = {...round(12), content:[{type:'thinking', thinking:repeatedSource}, round(12).content[1]]};
97
+ branch=[entry(repeated)]; cards.length=0; emit('session_start');
98
+ cards.push(new AssistantMessageComponent(repeated,true,themeModule.getMarkdownTheme()));
99
+ cards[0].render(100); key('\x1bt'); key('\r');
100
+ const deduplicated = cards[0].render(100).map(stripAnsi);
101
+ assert.equal(deduplicated.filter(line => line.includes('Exact thinking title')).length, 1);
102
+ assert.match(deduplicated[2], /First thinking paragraph/);
103
+ assert.equal(deduplicated[3].trim(), '');
104
+ assert.equal(repeated.content[0].thinking, repeatedSource, 'compact suppression preserves the recorded thinking source');
105
+ mode.setEnabled(false); cards[0].setHideThinkingBlock(false);
106
+ assert.match(plain(cards[0].render(100)), /Exact thinking title/, 'native thinking keeps the repeated title');
107
+ mode.setEnabled(true);
108
+ // A very large recorded block still paints a bounded native assistant surface.
109
+ const hugeRound={...round(11),content:[{type:'thinking',thinking:'Large exact recorded line 行🙂\n'.repeat(100000)},round(11).content[1]]};
110
+ branch=[entry(hugeRound)];cards.length=0;emit('session_start',{type:'session_start',reason:'resume'});cards.push(new AssistantMessageComponent(hugeRound,true,themeModule.getMarkdownTheme()));
111
+ const markdownRender=tui.Markdown.prototype.render;let markdownPaints=0;
112
+ tui.Markdown.prototype.render=function(...args){markdownPaints++;return markdownRender.apply(this,args);};
113
+ try{assert.match(plain(cards[0].render(60)),/▸ Thinking · Large exact recorded line/);key('\x1bt');key('\r');assert.ok(cards[0].render(60).length<=17);assert.match(plain(cards[0].render(60)),/Large exact recorded line/);assert.equal(markdownPaints,0,'bounded thinking never eagerly paints native full Markdown');}
114
+ finally{tui.Markdown.prototype.render=markdownRender;}
115
+ // Long recorded rounds remain a concise list until each is opened. Labels
116
+ // identify their source; the original thinking stays available without edits.
117
+ const longTexts = [
118
+ '# Compare the parser and native transcript paths\nI need to check whether the transcript projection keeps the recorded message identity.\n' + 'The parser returns recorded messages in order; I will inspect the native component association before changing membership. 行🙂\n'.repeat(20000) + 'First round final recorded line.',
119
+ 'Check the adapter lifecycle before adding a focus hook. The previous registration must release its listener.\n' + 'I should exercise reload, resume, fork, compaction, and shutdown with the native component rather than infer cleanup from a mock.\n'.repeat(2000) + 'Second round final recorded line.',
120
+ '## Verify narrow terminal rendering\nThe excerpt is a display label taken from this recorded heading.\n' + '检查中英文、emoji 🙂 和很窄的终端;原始记录保留换行和标点。\n'.repeat(2000) + 'Third round final recorded line.',
121
+ ];
122
+ const longRounds = longTexts.map((thinking, index) => ({...round(index + 20), content: [{type:'thinking', thinking}, round(index + 20).content[1]]}));
123
+ const longOriginal = JSON.stringify(longRounds);
124
+ branch = longRounds.flatMap((message, index) => [entry(message), entry(result(index + 20))]); cards.length = 0;
125
+ emit('session_start', {type:'session_start', reason:'resume'});
126
+ cards.push(...longRounds.map(message => new AssistantMessageComponent(message,true,themeModule.getMarkdownTheme())));
127
+ const evidence = [{label:'Collapsed recorded thinking group · native dark theme · 100 columns', lines: cards[2].render(100)}];
128
+ const longChoices=[];pi.events.emit('compact-renderer:inspect:v1',{add: choice=>longChoices.push(choice)});longChoices[0].focus();
129
+ const concise = cards[2].render(100);evidence.push({label:'Inspection opens a concise round list · first round selected',lines:concise});
130
+ assert.match(plain(concise), /Compare the parser and native transcript paths/);
131
+ assert.match(plain(concise), /Check the adapter lifecycle before adding a focus hook\./);
132
+ assert.match(plain(concise), /Verify narrow terminal rendering/);
133
+ assert.doesNotMatch(plain(concise), /parser returns|previous registration|检查中英文/);
134
+ assert.doesNotMatch(plain(concise), /Alt\+T|Alt\+G/, 'inspection has no unreliable Option shortcut hints');
135
+ const headingRow = concise.find(line => stripAnsi(line).includes('Compare'));
136
+ const boldPrefix = themeModule.theme.bold('MARK').split('MARK')[0];
137
+ if (boldPrefix) assert.ok(headingRow.includes(boldPrefix), 'round heading uses native bold');
138
+ assertCardBackground([headingRow],100,'selectedBg');
139
+ key('\r');const longFirst=cards[2].render(100);assert.ok(longFirst.length<=14);assert.match(plain(longFirst), /I need to check whether/);
140
+ evidence.push({label:'First recorded round independently expanded · bounded text viewport',lines:longFirst});
141
+ key('\x1b[C');key('\r');const longSecond=cards[2].render(100);
142
+ assert.match(plain(longSecond),/previous registration|exercise reload/,'selection reaches a later round without scanning a long earlier body');
143
+ evidence.push({label:'Second recorded round independently expanded · later-round selection',lines:longSecond});
144
+ key('\x1b[H');assert.match(plain(cards[2].render(100)), /▾ 1\. Compare/, 'Home returns to the independently expanded first round');
145
+ let ended=0;const unsubEnded=pi.events.on('compact-renderer:inspection-ended:v1',()=>ended++);
146
+ assert.equal(key('typed input'),false);assert.equal(ended,1);assert.equal(key('\r'),false,'typing releases inspection to the editor');
147
+ longChoices[0].focus();assert.equal(key('\x14'),false,'Ctrl+T remains available to native Pi');assert.equal(ended,2);unsubEnded();
148
+ assert.equal(JSON.stringify(longRounds),longOriginal,'long raw recorded transcript remains exact');
149
+ assert.equal(recordedThinkingLabel(['# Existing recorded title\nLong body']), 'Existing recorded title');
150
+ assert.equal(recordedThinkingLabel(['**Inspect recorded fields**\nLong body']), 'Inspect recorded fields');
151
+ assert.equal(recordedThinkingLabel(['# **Inspect recorded fields**\nLong body']), 'Inspect recorded fields');
152
+ assert.equal(recordedThinkingLabel(['First recorded sentence. Another thought.']), 'First recorded sentence.');
153
+ assert.ok(!recordedThinkingLabel(['\x1b]52;c;secret\x07\u202eunsafe']).includes('\x1b'),'labels cannot execute terminal controls');
154
+ for (const width of [1,2,3,8,24,70]) for (const line of cards[2].render(width)) assert.ok(tui.visibleWidth(line)<=width);
155
+ if (process.env.WRITE_THINKING_EVIDENCE) { fs.writeFileSync(process.env.WRITE_THINKING_EVIDENCE, JSON.stringify(evidence,null,2)+'\n'); }
156
+ // Exercise the real SessionManager and native initial transcript projection.
157
+ // bindExtensions emits session_start before InteractiveMode.renderInitialMessages.
158
+ const recorded=core.SessionManager.inMemory('/synthetic');
159
+ for(const item of JSON.parse(originalBranch))recorded.appendMessage(item.message);
160
+ const resumed=core.SessionManager.inMemory('/synthetic',undefined,JSON.parse(JSON.stringify(recorded.getEntries())));
161
+ const originalManager=ctx.sessionManager;ctx.sessionManager=resumed;cards.length=0;
162
+ emit('session_start',{type:'session_start',reason:'resume',previousSessionFile:'/synthetic/previous.jsonl'});
163
+ const nativeDisplay=()=>{
164
+ let messages;
165
+ core.InteractiveMode.prototype.renderSessionEntries.call({renderer:undefined,renderSessionItems(items){messages=items;}},resumed.buildContextEntries());
166
+ return messages;
167
+ };
168
+ const projected=nativeDisplay().filter(m=>m.role==='assistant');
169
+ const branchMessages=resumed.getBranch().filter(e=>e.type==='message'&&e.message.role==='assistant').map(e=>e.message);
170
+ assert.deepEqual(projected,branchMessages);projected.forEach((m,i)=>assert.equal(m,branchMessages[i],'native resume projection preserves recorded message identity'));
171
+ cards.push(...projected.map(m=>new AssistantMessageComponent(m,true,themeModule.getMarkdownTheme())));
172
+ assert.deepEqual(cards.slice(0,2).map(c=>c.render(70)),[[],[]]);assert.match(plain(cards[2].render(70)),/Thinking · 3 rounds/);
173
+ for(const reason of ['reload','fork','new','startup','resume']){
174
+ emit('session_start',{type:'session_start',reason});assert.equal(terminal.size,1);assert.match(plain(cards[2].render(70)),/Thinking · 3 rounds/);
175
+ }
176
+ // Native context entries omit pre-compaction rounds, so those missing cards
177
+ // must not prevent retained thinking from grouping after compaction/resume.
178
+ const kept=resumed.getBranch().find(e=>e.type==='message'&&e.message===branchMessages[1]);
179
+ resumed.appendCompaction('Recorded fixture summary',kept.id,100);
180
+ cards.length=0;emit('session_compact',{type:'session_compact',compactionEntry:resumed.getLeafEntry(),fromExtension:false,reason:'manual',willRetry:false});
181
+ cards.push(...nativeDisplay().filter(m=>m.role==='assistant').map(m=>new AssistantMessageComponent(m,true,themeModule.getMarkdownTheme())));
182
+ assert.equal(cards.length,2);assert.equal(cards[0].render(70).length,0);assert.match(plain(cards[1].render(70)),/Thinking · 2 rounds/);
183
+ emit('session_start',{type:'session_start',reason:'resume'});assert.match(plain(cards[1].render(70)),/Thinking · 2 rounds/);
184
+ ctx.sessionManager=originalManager;
185
+ // Shutdown releases hooks/listeners; subsequent resume reinstalls one listener.
186
+ emit('session_shutdown');assert.equal(terminal.size,0);assert.equal(AssistantMessageComponent.prototype.render,native.render);
187
+ branch=rounds.map(entry);cards.length=0;emit('session_start',{type:'session_start',reason:'startup'});cards.push(...rounds.map(m=>new AssistantMessageComponent(m,true,themeModule.getMarkdownTheme())));
188
+ assert.match(plain(cards[2].render(70)),/Thinking · 3 rounds/);
189
+ dispose();dispose();assert.equal(terminal.size,0);assert.deepEqual({update:AssistantMessageComponent.prototype.updateContent,render:AssistantMessageComponent.prototype.render,mouse:AssistantMessageComponent.prototype.handleMouse},native);
190
+ assert.ok(cards.every(c=>c.render(70).length>0));
191
+ dispose=registerModernThinking(pi,mode);emit('session_start',{type:'session_start',reason:'startup'});assert.equal(terminal.size,1);
192
+ const staleDispose=dispose;dispose=registerModernThinking(pi,mode);assert.equal(terminal.size,0,'replacement registration disposes the prior input listener');emit('session_start',{type:'session_start',reason:'startup'});assert.equal(terminal.size,1);staleDispose();assert.equal(terminal.size,1);dispose();
193
+ assert.equal(JSON.stringify(rounds.flatMap((m,i)=>[entry(m),entry(result(i+1))])),originalBranch,'transcript objects remain exact');
194
+ assert.equal(installModernThinkingAdapter({clear(){},associate(){},render(){},mouse(){}},'1.1.0'),undefined,'legacy gate is not widened');
195
+ assert.equal(installModernThinkingAdapter({clear(){},associate(){},render(){},mouse(){}},'9.0.0'),undefined);
196
+ const pane=new RecordedTextPane();const huge='Large exact recorded line 行🙂\n'.repeat(100000);pane.setSources([huge]);pane.open=true;
197
+ const first=pane.view(60,9);assert.equal(first.length,9);assert.ok(pane.visitedCharacters<1000,'first paint visits only viewport and one lookahead');
198
+ const visits=pane.visitedCharacters;for(let i=0;i<50;i++)pane.view(60,9);assert.equal(pane.visitedCharacters,visits,'stable paints do not reprocess source');
199
+ pane.move('down',9);pane.view(60,9);assert.ok(pane.visitedCharacters-visits<100);
200
+ pane.setSources(['\x1b]52;c;secret\x07\noriginal']);assert.ok(!pane.view(60,9).join('').includes('\x1b'),'recorded controls cannot execute');
201
+ console.log('modern thinking: native grouping, keyboard, lifecycle, fallback, exact transcripts, and bounded painting passed');
202
+ } finally { dispose(); }