@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,189 @@
1
+ import assert from 'node:assert/strict';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { loadSource, core, tui, runtime, themeModule, stripAnsi, backgroundCells } from './test-runtime.mjs';
5
+ const { modernWorkflowFences, WorkflowPane, registerModernWorkflows } = await loadSource('./modern-workflows.ts');
6
+ const { registerModernThinking } = await loadSource('./modern-thinking.ts');
7
+ const { renderFinalReply } = await loadSource('./work-strip-view.ts');
8
+ const { default: piFold } = await loadSource('../index.ts');
9
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
10
+ const { readReplyWorkflowScript } = await import(pathToFileURL(path.join(runtime, 'node_modules/pi-subagents/src/extension/reply-workflow-script.js')).href);
11
+ const { AssistantMessageComponent } = core;
12
+ const plain = rows => rows.map(stripAnsi).join('\n');
13
+ const script = '// Inspect fixture files and record findings\nconst label = "original 行🙂";\n' + Array.from({ length: 500 }, (_, n) => `const step${n} = ${n};`).join('\n') + '\nreturn label;\n';
14
+ const text = `Visible prose **before** the workflow.\n\n\`\`\`js workflow\n${script}\`\`\`\n\nVisible prose **after** the workflow.`;
15
+ const message = Object.freeze({ role: 'assistant', content: Object.freeze([Object.freeze({ type: 'text', text }), Object.freeze({ type: 'toolCall', id: 'workflow-call', name: 'subagent', arguments: Object.freeze({ workflow: true }) })]), stopReason: 'toolUse' });
16
+ const entry = { type: 'message', message };
17
+ const branch = [entry], exactMessage = JSON.stringify(branch);
18
+ const sessionManager = { getBranch: () => branch };
19
+ const scriptBefore = readReplyWorkflowScript(sessionManager, 'workflow-call');
20
+ assert.equal(scriptBefore.script, script.replace(/\n$/, ''));
21
+ const listeners = new Map(), bus = new Map(), terminal = new Set(), mounted = [];
22
+ const on = (map, key, fn) => { const set = map.get(key) || new Set(); map.set(key, set); set.add(fn); return () => set.delete(fn); };
23
+ 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); } } };
24
+ const ctx = { mode: 'tui', sessionManager, ui: { theme: themeModule.theme, setHiddenThinkingLabel() { for (const card of mounted) card.setHiddenThinkingLabel('Thinking...'); }, onTerminalInput(fn) { terminal.add(fn); return () => terminal.delete(fn); } } };
25
+ const emit = (event, value = {}) => { for (const fn of [...listeners.get(event) || []]) fn(value, ctx); };
26
+ const key = data => [...terminal].some(fn => fn(data)?.consume);
27
+ const choices = () => { const result = []; pi.events.emit('compact-renderer:inspect:v1', { add: choice => result.push(choice) }); return result.filter(choice => choice.kind === 'Workflow'); };
28
+ const mode = createDisplayMode();
29
+ const native = { render: AssistantMessageComponent.prototype.render, mouse: AssistantMessageComponent.prototype.handleMouse, update: AssistantMessageComponent.prototype.updateContent };
30
+ const nativeDescriptors = Object.fromEntries(['render', 'handleMouse', 'updateContent'].map(key => [key, Object.getOwnPropertyDescriptor(AssistantMessageComponent.prototype, key)]));
31
+ const disposeThinking = registerModernThinking(pi, mode);
32
+ let dispose = registerModernWorkflows(pi, mode);
33
+ const make = (value = message) => { const card = new AssistantMessageComponent(value, true, themeModule.getMarkdownTheme()); mounted.push(card); return card; };
34
+ const mouse = (card, y, type = 'click') => card.handleMouse({ type, button: type === 'click' ? 'left' : 'none', x: 2, y, width: 100, height: card.render(100).length, wheelDelta: 1, ctrl: false, alt: false, shift: false });
35
+ try {
36
+ const card = make();
37
+ assert.match(plain(card.render(100)), /const step499/, 'before startup stays native');
38
+ emit('session_start');
39
+ const nativeChildren = card.contentContainer.children;
40
+ const rows = card.render(100);
41
+ assert.equal(card.contentContainer.children, nativeChildren, 'display substitutions restore the native child array');
42
+ assert.match(plain(rows), /Subagent workflow · Inspect fixture files and record findings/);
43
+ assert.match(plain(rows), /Visible prose before/); assert.match(plain(rows), /Visible prose after/);
44
+ assert.doesNotMatch(plain(rows), /const step0/);
45
+ assert.equal(key('\x1b[B'), false); assert.equal(key('\r'), false);
46
+ assert.equal(choices().length, 1);
47
+ choices()[0].focus();
48
+ const expanded = card.render(100);
49
+ assert.match(plain(expanded), /const label = "original 行🙂"/);
50
+ assert.ok(expanded.find(row => stripAnsi(row).includes('const label')).includes(themeModule.theme.getFgAnsi('syntaxKeyword')), 'expanded source uses native JavaScript syntax colors');
51
+ assert.ok(expanded.length < 30, 'expanded source viewport remains bounded');
52
+ assert.match(plain(expanded), /Esc release/);
53
+ assert.equal(key('\x1b[B'), true); assert.equal(key('\x1b[H'), true);
54
+ assert.equal(key('x'), false, 'ordinary editor input passes through and releases inspection');
55
+ assert.equal(key('\r'), false);
56
+ let header = card.render(100).findIndex(row => stripAnsi(row).includes('Subagent workflow'));
57
+ assert.equal(mouse(card, header).handled, true);
58
+ assert.doesNotMatch(plain(card.render(100)), /const step0/);
59
+ assert.equal(key('\r'), false, 'mouse expansion never captures editor Enter');
60
+ mouse(card, header); assert.match(plain(card.render(100)), /const label/);
61
+ assert.equal(mouse(card, header + 2, 'wheel').handled, true);
62
+ assert.equal(key('\r'), false);
63
+ choices()[0].focus();
64
+ const beforeMore = plain(card.render(100));
65
+ const moreRows = card.render(100).map(stripAnsi), moreY = moreRows.findIndex(row => row.includes('more ↓'));
66
+ assert.ok(moreY > header);
67
+ assert.equal(mouse(card, moreY)?.handled, true);
68
+ const afterMore = plain(card.render(100));
69
+ assert.notEqual(afterMore, beforeMore, 'overflow click advances the rendered workflow source');
70
+ assert.doesNotMatch(afterMore, /const label/);
71
+ assert.match(afterMore, /Visible prose before/); assert.match(afterMore, /Visible prose after/);
72
+ assert.equal(key('\r'), false, 'overflow click releases inspection to the editor');
73
+ choices()[0].focus(); assert.equal(key('\x1b'), true); assert.equal(key('\r'), false);
74
+ choices()[0].focus(); emit('ui_prompt_start'); assert.equal(key('\r'), false);
75
+ choices()[0].focus(); pi.events.emit('compact-renderer:focus:v1', { owner: 'tools' }); assert.equal(key('\r'), false);
76
+ const originalChildren = [...card.contentContainer.children];
77
+ for (let n = 0; n < 20; n++) card.render(100);
78
+ assert.deepEqual(card.contentContainer.children, originalChildren);
79
+ for (const width of [1, 2, 3, 8, 24, 70]) for (const row of card.render(width)) assert.ok(tui.visibleWidth(row) <= width, `width ${width}`);
80
+ mode.setEnabled(false);
81
+ assert.match(plain(card.render(100)), /const step499/);
82
+ assert.doesNotMatch(plain(card.render(100)), /Subagent workflow/);
83
+ assert.equal(choices().length, 0);
84
+ mode.setEnabled(true); assert.doesNotMatch(plain(card.render(100)), /const step499/);
85
+ // Native rebuilding for theme/hidden-thinking changes retains each fence's state.
86
+ choices()[0].focus(); card.setHideThinkingBlock(false); assert.match(plain(card.render(100)), /const label/);
87
+ assert.equal(choices().length, 1);
88
+ const pair = make({ ...message, content: [{ type: 'text', text: `\`\`\`js workflow\n// First workflow\nconst first = 1;\n\`\`\`\n\nBetween workflows.\n\n\`\`\`javascript workflow\n// Second workflow\nconst second = 2;\n\`\`\`` }] });
89
+ pair.render(100);
90
+ const secondChoice = choices().find(choice => choice.label === 'Second workflow'); secondChoice.focus();
91
+ assert.match(plain(pair.render(100)), /const second/); assert.doesNotMatch(plain(pair.render(100)), /const first/);
92
+ pair.setHiddenThinkingLabel('Thinking...'); assert.match(plain(pair.render(100)), /const second/); assert.equal(choices().filter(choice => /First|Second/.test(choice.label)).length, 2);
93
+ assert.equal(new Set(choices().map(choice => choice.id)).size, choices().length, 'inspection IDs are unique across separate messages and fences');
94
+ const editor = new tui.Editor({ requestRender() {}, terminal: { columns: 100, rows: 30 } }, themeModule.getEditorTheme());
95
+ const submitted = []; editor.onSubmit = value => submitted.push(value);
96
+ for (const chunks of [['density'], ['©', '†'], ['\x1b[200~', 'pasted status', '\x1b[201~'], ['statux', '\x7f', 's']]) {
97
+ editor.setText(''); choices()[0].focus();
98
+ for (const chunk of chunks) if (!key(chunk)) editor.handleInput(chunk);
99
+ const expected = editor.getText(); assert.equal(key('\r'), false); editor.handleInput('\r'); assert.equal(submitted.at(-1), expected);
100
+ }
101
+ const mixed = make({ ...message, content: [{ type: 'thinking', thinking: 'Exact native thinking' }, { type: 'text', text }] });
102
+ mixed.render(100); mixed.setHideThinkingBlock(false);
103
+ assert.match(plain(mixed.render(100)), /Exact native thinking/); assert.match(plain(mixed.render(100)), /Subagent workflow/);
104
+ const ordinary = make({ ...message, content: [{ type: 'text', text: '```js\nconst ordinary = 1;\n```' }] });
105
+ assert.match(plain(ordinary.render(100)), /const ordinary/); assert.doesNotMatch(plain(ordinary.render(100)), /Subagent workflow/);
106
+ const streaming = make(); streaming.updateContent(message, true);
107
+ assert.match(plain(streaming.render(100)), /const step499/);
108
+ streaming.updateContent(message, false); assert.match(plain(streaming.render(100)), /Subagent workflow/);
109
+ const unknown = make(); unknown.contentContainer.children.push({ render: () => ['unknown'], invalidate() {} });
110
+ assert.match(plain(unknown.render(100)), /const step499/); assert.doesNotMatch(plain(unknown.render(100)), /Subagent workflow/);
111
+ const stale = choices()[0]; emit('session_tree'); card.render(100); stale.focus(); assert.equal(key('\r'), false);
112
+ for (const event of ['session_tree', 'session_compact']) { emit(event); assert.match(plain(card.render(100)), /Subagent workflow/); assert.equal(terminal.size, 2); }
113
+ emit('session_before_switch'); assert.equal(terminal.size, 1); assert.match(plain(card.render(100)), /const step499/);
114
+ for (const reason of ['reload', 'new', 'resume', 'fork', 'startup']) { emit('session_start', { reason }); assert.match(plain(card.render(100)), /Subagent workflow/); assert.equal(terminal.size, 2); }
115
+ emit('session_shutdown'); assert.equal(terminal.size, 0); assert.match(plain(card.render(100)), /const step499/);
116
+ emit('session_start'); card.render(100);
117
+ const activeThinkingRender = AssistantMessageComponent.prototype.render;
118
+ dispose(); dispose(); assert.equal(terminal.size, 1); assert.equal(AssistantMessageComponent.prototype.render, activeThinkingRender, 'detaching an inner workflow wrapper preserves the active thinking wrapper');
119
+ assert.match(plain(card.render(100)), /const step499/);
120
+ dispose = registerModernWorkflows(pi, mode); emit('session_start'); assert.match(plain(card.render(100)), /Subagent workflow/);
121
+ const oldDispose = dispose; dispose = registerModernWorkflows(pi, mode); emit('session_start'); oldDispose(); assert.equal(terminal.size, 2);
122
+ assert.match(plain(card.render(100)), /Subagent workflow/);
123
+ // Final replies retain their native fenced source and padded neutral surface.
124
+ const finalWorkflow = make({ role: 'assistant', stopReason: 'stop', content: [{ type: 'text', text: 'Final prose before.\n\n```js workflow\n// Final native fence\nconst finalValue = 42;\n```\n\nFinal prose after.' }] });
125
+ mode.setEnabled(false); const nativeFinal = finalWorkflow.render(100).map(stripAnsi); mode.setEnabled(true);
126
+ assert.match(plain(finalWorkflow.render(100)), /Subagent workflow/);
127
+ const staleFinalChoice = choices().find(choice => choice.label === 'Final native fence'); staleFinalChoice.focus();
128
+ const finalRows = renderFinalReply(finalWorkflow, 100, themeModule.theme);
129
+ assert.deepEqual(finalRows.map(stripAnsi), [nativeFinal[0], ' '.repeat(100), ...nativeFinal.slice(1), ' '.repeat(100)], 'final workflow replies add exactly the native padding pair');
130
+ assert.match(plain(finalRows), /const finalValue = 42/); assert.doesNotMatch(plain(finalRows), /Subagent workflow/);
131
+ const finalBg = backgroundCells(themeModule.theme.bg('toolPendingBg', ' '))[0];
132
+ for (const row of finalRows.slice(1)) assert.ok(backgroundCells(row.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')).every(cell => cell === finalBg), 'final workflow text and gaps keep the neutral fill');
133
+ assert.ok(!choices().some(choice => choice.label === 'Final native fence'), 'final rendering clears the old workflow inspection control');
134
+ staleFinalChoice.focus(); assert.equal(key('\r'), false, 'stale final workflow inspection cannot reclaim editor input');
135
+ assert.equal(mouse(finalWorkflow, 2), undefined, 'native fenced text cannot dispatch the old workflow disclosure');
136
+ assert.match(plain(card.render(100)), /Subagent workflow/, 'ordinary workflow cards remain compact after final rendering');
137
+ dispose(); disposeThinking(); assert.deepEqual({ render: AssistantMessageComponent.prototype.render, mouse: AssistantMessageComponent.prototype.handleMouse, update: AssistantMessageComponent.prototype.updateContent }, native);
138
+ assert.equal(JSON.stringify(branch), exactMessage, 'recorded assistant message and transcript stay exact');
139
+ assert.deepEqual(readReplyWorkflowScript(sessionManager, 'workflow-call'), scriptBefore, 'installed workflow executor reads the same original script after display interactions');
140
+ const unsupported = registerModernWorkflows(pi, mode, '9.0.0'); assert.equal(AssistantMessageComponent.prototype.render, native.render); unsupported();
141
+ // The opposite disposal order also restores the complete native method chain.
142
+ const reverseThinking = registerModernThinking(pi, mode), reverseWorkflow = registerModernWorkflows(pi, mode);
143
+ emit('session_start'); card.render(100); reverseThinking(); reverseWorkflow();
144
+ assert.deepEqual({ render: AssistantMessageComponent.prototype.render, mouse: AssistantMessageComponent.prototype.handleMouse, update: AssistantMessageComponent.prototype.updateContent }, native);
145
+ // Exercise the actual entry point, including every sibling renderer, resets,
146
+ // session shutdown, and a second load. No stale wrapper may survive teardown.
147
+ pi.registerToolRenderer = () => {}; pi.registerMarkdownTransformer = () => {}; pi.registerCommand = () => {}; pi.getCommands = () => [];
148
+ ctx.hasUI = true; ctx.ui.setWidget = () => {}; ctx.ui.setStatus = () => {};
149
+ const nativeContainerRender = tui.Container.prototype.render;
150
+ for (let run = 0; run < 2; run++) {
151
+ piFold(pi); emit('session_start');
152
+ for (const event of ['session_tree', 'session_compact', 'session_start']) { emit(event); assert.match(plain(card.render(100)), /Subagent workflow/); }
153
+ emit('session_shutdown');
154
+ assert.equal(terminal.size, 0);
155
+ assert.deepEqual({ render: AssistantMessageComponent.prototype.render, mouse: AssistantMessageComponent.prototype.handleMouse, update: AssistantMessageComponent.prototype.updateContent }, native, 'entry-point shutdown restores native assistant methods');
156
+ assert.deepEqual(Object.fromEntries(['render', 'handleMouse', 'updateContent'].map(key => [key, Object.getOwnPropertyDescriptor(AssistantMessageComponent.prototype, key)])), nativeDescriptors, 'entry-point shutdown restores native own/inherited method descriptors');
157
+ assert.equal(tui.Container.prototype.render, nativeContainerRender, 'entry-point shutdown restores native container rendering');
158
+ }
159
+ assert.equal(modernWorkflowFences('```js workflow\nconst unfinished = 1;').length, 0);
160
+ assert.equal(modernWorkflowFences('````markdown\n```js workflow\nconst nested = 1;\n```\n````').length, 0);
161
+ assert.equal(modernWorkflowFences('```js workflow\n\n```').length, 0);
162
+ assert.equal(modernWorkflowFences('```js workflow extra\nconst untouched = 1;\n```').length, 0);
163
+ const crlf = modernWorkflowFences('Prose\r\n\r\n```javascript workflow\r\n// CRLF summary\r\nconst x = 1;\r\n```\r\nTail');
164
+ assert.equal(crlf[0].source, '// CRLF summary\r\nconst x = 1;\r\n'); assert.equal(crlf[0].summary, 'CRLF summary');
165
+ const huge = new WorkflowPane('const first = 1;\n' + 'const next = "x";\n'.repeat(500000), 'Large recorded workflow');
166
+ huge.render(80); assert.equal(huge.paintedRows, 0, 'closed panes never format source');
167
+ huge.open = true; const hugeRows = huge.render(80); assert.ok(hugeRows.length <= 15); assert.ok(huge.paintedRows <= 15);
168
+ const firstPaint = huge.paintedRows; huge.render(80); assert.equal(huge.paintedRows, firstPaint, 'redraw reuses formatted rows');
169
+ const pagedWorkflow = new WorkflowPane(Array.from({ length: 31 }, (_, n) => `const page${n} = ${n};`).join('\n'), 'Paged source');
170
+ pagedWorkflow.open = true;
171
+ let pageRows = pagedWorkflow.render(80).map(stripAnsi);
172
+ const workflowClick = extra => pagedWorkflow.handleMouse({ type: 'click', button: 'left', x: 3, y: pageRows.findIndex(row => row.includes('more ↓')), ...extra });
173
+ workflowClick({ ctrl: true }); assert.equal(pagedWorkflow.offset, 0, 'modified workflow overflow click keeps source position');
174
+ for (let n = 0; n < 40 && pageRows.some(row => row.includes('more ↓')); n++) {
175
+ const before = pagedWorkflow.paintedRows; workflowClick(); pageRows = pagedWorkflow.render(80).map(stripAnsi);
176
+ assert.ok(pagedWorkflow.paintedRows - before <= 12, 'one overflow click formats at most one source viewport');
177
+ }
178
+ assert.match(pageRows.join('\n'), /const page30/);
179
+ assert.doesNotMatch(pageRows.join('\n'), /more ↓/, 'downward paging stops after the final rows');
180
+ const workflowEndOffset = pagedWorkflow.offset, workflowEndHeight = pageRows.length;
181
+ assert.match(pageRows.at(-1), /more ↑/);
182
+ pagedWorkflow.handleMouse({ type: 'click', button: 'left', x: 3, y: pageRows.length - 1 });
183
+ pageRows = pagedWorkflow.render(80).map(stripAnsi);
184
+ assert.ok(pagedWorkflow.offset < workflowEndOffset, 'upward footer pages back through the source');
185
+ assert.equal(pageRows.length, workflowEndHeight, 'workflow footer remains in place');
186
+ const longLine = new WorkflowPane('const value = "' + '🙂'.repeat(200000) + '";', 'Long line'); longLine.open = true;
187
+ assert.ok(longLine.render(12).length <= 15); assert.ok(longLine.paintedRows <= 15);
188
+ console.log('modern workflows: exact executor source, bounded native syntax, surrounding prose, independent fences, native thinking, mouse/editor/inspection, lifecycle, and fallback passed');
189
+ } finally { dispose(); disposeThinking(); }
@@ -0,0 +1,167 @@
1
+ import assert from 'node:assert/strict';
2
+ import { loadSource, loadAgent, core, themeModule, stripAnsi, tui, assertCardBackground } from './test-runtime.mjs';
3
+
4
+ const { registerModernPrompts } = await loadSource('./modern-prompts.ts');
5
+ const { createDisplayMode } = await loadSource('./display-mode.ts');
6
+ const { SkillInvocationMessageComponent } = await loadAgent('modes/interactive/components/skill-invocation-message.js');
7
+ const { UserMessageComponent, VERSION } = core;
8
+ assert.equal(VERSION, '1.3.0', 'prompt seam is verified against the actual supported runtime');
9
+ const nativeRender = UserMessageComponent.prototype.render;
10
+ const listeners = new Map(), bus = new Map(), terminal = new Set(), transformers = [];
11
+ const subscribe = (map, event, fn) => {
12
+ const set = map.get(event) || new Set(); map.set(event, set); set.add(fn); return () => set.delete(fn);
13
+ };
14
+ const pi = {
15
+ on: (event, fn) => subscribe(listeners, event, fn),
16
+ events: { on: (event, fn) => subscribe(bus, event, fn), emit(event, data) { for (const fn of [...bus.get(event) || []]) fn(data); } },
17
+ getCommands: () => [], registerMarkdownTransformer: fn => transformers.push(fn),
18
+ };
19
+ const ctx = { mode: 'tui', ui: { theme: themeModule.theme, setHiddenThinkingLabel() {}, onTerminalInput(fn) { terminal.add(fn); return () => terminal.delete(fn); } } };
20
+ const emit = event => { for (const fn of [...listeners.get(event) || []]) fn({}, ctx); };
21
+ const key = data => [...terminal].some(fn => fn(data)?.consume);
22
+ const plain = (card, width = 80) => card.render(width).map(stripAnsi).join('\n');
23
+ const source = count => Array.from({ length: count }, (_, n) => `Recorded row ${n + 1} 行🙂`).join(' \n');
24
+ const card = text => new UserMessageComponent(text, themeModule.getMarkdownTheme(), 1, transformers);
25
+ const collapsedControl = (component, width) => {
26
+ const rows = component.render(width), text = rows.map(stripAnsi);
27
+ const start = text.findIndex(row => row.trim().startsWith('⋯'));
28
+ assert.ok(start > 0, 'collapsed prompt has a generic Show more control');
29
+ let end = start + 1;
30
+ while (end < text.length && text[end].trim()) end++;
31
+ assert.equal(text.slice(start, end).map(row => row.trim()).join(' '), '⋯ Show more', 'control has no prompt-specific heading or inspection suffix');
32
+ assert.equal(text[start - 1].trim(), '', 'one blank row precedes the control');
33
+ assert.notEqual(text[start - 2].trim(), '', 'opening has no trailing blank boundary');
34
+ assert.equal(text[end].trim(), '', 'one blank row follows the complete wrapped control');
35
+ assert.notEqual(text[end + 1].trim(), '', 'ending has no leading blank boundary');
36
+ assert.ok(rows[start].includes(themeModule.theme.getFgAnsi('muted')), 'control uses the native muted foreground');
37
+ assert.doesNotMatch(rows.slice(start, end).join(''), /\x1b\[1m/, 'control is not bold');
38
+ assertCardBackground(rows.map(row => row.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')), width, 'userMessageBg');
39
+ return { rows, start, end };
40
+ };
41
+ const mode = createDisplayMode();
42
+ const skill = new SkillInvocationMessageComponent({ name: 'recorded-skill', content: source(12) });
43
+ const skillCollapsed = skill.render(80);
44
+ const dispose = registerModernPrompts(pi, mode);
45
+ try {
46
+ emit('session_start');
47
+ assert.deepEqual(skill.render(80), skillCollapsed, 'native skill card stays unchanged');
48
+ skill.setExpanded(true); assert.match(plain(skill), /Recorded row 12/); assert.doesNotMatch(plain(skill), /Show less/);
49
+ const eight = card(source(8)), nine = card(source(9));
50
+ assert.equal(nativeRender.call(eight, 80).length, 10, 'fixture has eight native body rows');
51
+ assert.equal(nativeRender.call(nine, 80).length, 11, 'fixture has nine native body rows');
52
+ assert.doesNotMatch(plain(eight), /Show more/, 'eight rendered lines stay open');
53
+ const full = nativeRender.call(nine, 80);
54
+ const folded = nine.render(80);
55
+ assert.deepEqual(folded.slice(0, 4), full.slice(0, 4), 'excerpt preserves exactly three native rendered rows and top padding');
56
+ assert.deepEqual(folded.slice(-3), full.slice(-3), 'ending retains exactly the last two native body rows and terminal padding');
57
+ assert.equal((plain(nine).match(/Recorded row 1 /g) || []).length, 1, 'opening is not duplicated');
58
+ assert.equal((plain(nine).match(/Recorded row 9 /g) || []).length, 1, 'ending is not duplicated');
59
+ collapsedControl(nine, 80);
60
+ assert.match(plain(nine), /Show more/);
61
+ assert.doesNotMatch(plain(nine), /Recorded row 4/);
62
+ assert.deepEqual(folded.at(-1), full.at(-1), 'native prompt-zone end and padding remain intact');
63
+ assert.equal(nine.text, source(9), 'folding does not change recorded text');
64
+ assert.equal(nine.handleMouse({ type: 'click', button: 'left', x: 3, y: 4, width: 80, height: 20 })?.handled, undefined, 'the opening-to-control gap does not toggle the card');
65
+ assert.ok(nine.handleMouse({ type: 'click', button: 'left', x: 3, y: 5, width: 80, height: 20 })?.handled);
66
+ const expanded = nine.render(80);
67
+ assert.deepEqual(expanded.slice(0, full.length - 1), full.slice(0, -1), 'expanded body retains every native formatted row');
68
+ assert.match(plain(nine), /Recorded row 9/);
69
+ assert.match(plain(nine), /Show less/);
70
+ assert.equal(expanded.at(-2).includes(themeModule.theme.getFgAnsi('muted')), true, 'bottom Show less control uses muted text');
71
+ assert.equal(stripAnsi(expanded.at(-3)).trim(), '', 'one filled gap precedes the expanded control');
72
+ assert.notEqual(stripAnsi(expanded.at(-4)).trim(), '', 'expanded control gap does not duplicate trailing body spacing');
73
+ assertCardBackground(expanded.slice(-3).map(row => row.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')), 80, 'userMessageBg');
74
+ assert.equal(nine.handleMouse({ type: 'click', button: 'left', x: 3, y: 10, width: 80, height: 20 })?.handled, undefined, 'expanded gap is outside the disclosure target');
75
+ assert.ok(nine.handleMouse({ type: 'click', button: 'left', x: 3, y: 11, width: 80, height: 20 })?.handled);
76
+ assert.doesNotMatch(plain(nine), /Recorded row 5/);
77
+ assert.equal(key('\r'), false, 'clicking leaves editor input native');
78
+ const choices = [];
79
+ pi.events.emit('compact-renderer:inspect:v1', { add: choice => choices.push(choice) });
80
+ assert.equal(choices.length, 1, 'only the long ordinary prompt enters inspection');
81
+ assert.match(choices[0].label, /^Submitted prompt — Recorded row 1/);
82
+ choices[0].focus();
83
+ assert.match(plain(nine), /Recorded row 9/);
84
+ assert.match(plain(nine), /▴ Show less/);
85
+ assert.match(plain(nine), /Esc returns/, 'keyboard hints appear only during explicit inspection');
86
+ assert.equal(key('\r'), true); assert.match(plain(nine), /Show more/);
87
+ assert.equal(key('\x1b'), true); assert.equal(key('\r'), false);
88
+ assert.equal(key('\x1bi'), true); assert.equal(key('x'), false); assert.equal(key('\r'), false, 'typing releases inspection');
89
+ const paragraphs = card('OPENING_PARAGRAPH\n\n' + Array.from({ length: 10 }, (_, n) => `- MIDDLE_ITEM_${n + 1}`).join('\n') + '\n\nENDING_LINE_ONE \nENDING_LINE_TWO \nENDING_LINE_THREE');
90
+ const paragraphNative = nativeRender.call(paragraphs, 80), paragraphCollapsed = collapsedControl(paragraphs, 80);
91
+ assert.deepEqual(paragraphCollapsed.rows.slice(0, 2), paragraphNative.slice(0, 2), 'opening stops before the first paragraph separator');
92
+ assert.deepEqual(paragraphCollapsed.rows.slice(-3), paragraphNative.slice(-3), 'ending takes the last two rows of the last paragraph');
93
+ assert.doesNotMatch(plain(paragraphs), /MIDDLE_ITEM_|ENDING_LINE_ONE/, 'collapsed opening does not append a partial list and tail stays bounded');
94
+ assert.match(plain(paragraphs), /OPENING_PARAGRAPH[\s\S]*ENDING_LINE_TWO[\s\S]*ENDING_LINE_THREE/);
95
+ paragraphs.handleMouse({ type: 'click', button: 'left', x: 3, y: paragraphCollapsed.start, width: 80, height: paragraphCollapsed.rows.length });
96
+ assert.deepEqual(paragraphs.render(80).slice(0, -3), paragraphNative.slice(0, -1), 'expanded prompt retains all native paragraphs and list formatting');
97
+ assert.match(plain(paragraphs), /MIDDLE_ITEM_1[\s\S]*MIDDLE_ITEM_10[\s\S]*ENDING_LINE_ONE/);
98
+ const singleParagraph = card('HEAD_TOKEN ' + 'recorded middle words '.repeat(80) + ' TAIL_TOKEN');
99
+ for (const width of [8, 16, 24, 80]) {
100
+ const native = nativeRender.call(singleParagraph, width), view = collapsedControl(singleParagraph, width);
101
+ assert.deepEqual(view.rows.slice(0, 4), native.slice(0, 4), `width ${width} preserves three opening native rows`);
102
+ assert.deepEqual(view.rows.slice(-3), native.slice(-3), `width ${width} preserves two ending native rows`);
103
+ assert.ok(view.rows.length < native.length, 'long single paragraphs use disjoint bounded head/tail excerpts');
104
+ }
105
+ assert.equal((plain(singleParagraph).match(/HEAD_TOKEN/g) || []).length, 1);
106
+ assert.equal((plain(singleParagraph).match(/TAIL_TOKEN/g) || []).length, 1);
107
+ const nativeTheme = nine.children[0].theme;
108
+ nine.children[0].theme = Object.assign(Object.create(nativeTheme), { bold: text => `\x1b[1m${text}\x1b[22m` });
109
+ try { nine.invalidate(); collapsedControl(nine, 80); }
110
+ finally { nine.children[0].theme = nativeTheme; nine.invalidate(); }
111
+ const wrapped = card('漢🙂 word '.repeat(30));
112
+ assert.doesNotMatch(plain(wrapped, 160), /Show more/, 'wide prompt stays open at eight lines or fewer');
113
+ assert.match(plain(wrapped, 24), /Show more/, 'narrow viewport remeasures native wrapping');
114
+ assert.doesNotMatch(plain(wrapped, 160), /Show more/, 'returning to wide viewport restores short native presentation');
115
+ for (const width of [1, 2, 8, 24]) {
116
+ const rows = wrapped.render(width);
117
+ const nativeLimit = Math.max(width, ...nativeRender.call(wrapped, width).map(tui.visibleWidth));
118
+ assert.ok(rows.every(row => tui.visibleWidth(row) <= nativeLimit), `width ${width} stays within the native Unicode/padding limit`);
119
+ }
120
+ const resizable = card('RESIZABLE_PROMPT ' + 'word '.repeat(100));
121
+ const promptChoices = () => { const choices = []; pi.events.emit('compact-renderer:inspect:v1', { add: choice => choices.push(choice) }); return choices; };
122
+ assert.match(plain(resizable, 24), /Show more/);
123
+ const resizeChoice = promptChoices().find(choice => choice.label.includes('RESIZABLE_PROMPT'));
124
+ resizeChoice.focus();
125
+ assert.match(plain(resizable, 24), /Show less/, 'inspection manually expands the narrow prompt');
126
+ assert.doesNotMatch(plain(resizable, 160), /Show more|Show less/, 'a temporarily short prompt uses native display');
127
+ assert.ok(!promptChoices().some(choice => choice.label.includes('RESIZABLE_PROMPT')), 'temporarily short cards are omitted from the picker');
128
+ resizeChoice.focus(); assert.equal(key('\r'), false, 'a stale picker choice cannot focus a temporarily short card');
129
+ assert.equal(resizable.handleMouse({ type: 'click', button: 'left', x: 3, y: 4, width: 160, height: 20 })?.handled, undefined, 'old control coordinates cannot toggle native short display');
130
+ assert.equal(key('\x1bi'), true); assert.match(plain(wrapped, 24), /Show more/, 'Alt+I skips the most recent inactive card'); assert.equal(key('\r'), true, 'Alt+I selected another eligible prompt');
131
+ assert.equal(key('\x1b'), true);
132
+ assert.match(plain(resizable, 24), /Show less/, 'manual expansion survives growing below the threshold and narrowing again');
133
+ const resizeRows = resizable.render(24).map(stripAnsi);
134
+ const collapseRow = resizeRows.findIndex(row => row.includes('Show less'));
135
+ resizable.handleMouse({ type: 'click', button: 'left', x: 3, y: collapseRow, width: 24, height: resizeRows.length });
136
+ assert.match(plain(resizable, 24), /Show more/);
137
+ plain(resizable, 160);
138
+ assert.match(plain(resizable, 24), /Show more/, 'manual collapse also survives a short-width interval');
139
+ const narrowChoice = promptChoices().find(choice => choice.label.includes('RESIZABLE_PROMPT'));
140
+ narrowChoice.focus(); assert.equal(key('\r'), true);
141
+ const focusedRows = resizable.render(24), focusedText = focusedRows.map(stripAnsi);
142
+ const focusedStart = focusedText.findIndex(row => row.includes('⋯ Show more'));
143
+ let focusedEnd = focusedStart + 1;
144
+ while (focusedEnd < focusedText.length && focusedText[focusedEnd].trim()) focusedEnd++;
145
+ assert.ok(focusedEnd - focusedStart > 1, 'narrow focused control wraps its keyboard hints');
146
+ assert.match(focusedText.slice(focusedStart, focusedEnd).join('\n'), /Esc\s+returns/);
147
+ assert.equal(resizable.handleMouse({ type: 'click', button: 'left', x: 3, y: focusedEnd - 1, width: 24, height: focusedRows.length })?.handled, true, 'last wrapped control row retains the disclosure mouse target');
148
+ assert.match(plain(resizable, 24), /▴ Show less/);
149
+ assert.doesNotMatch(plain(resizable, 24), /Esc\s+returns/, 'mouse expansion returns the control to its generic label');
150
+ assert.equal(key('\r'), false, 'mouse expansion releases keyboard inspection');
151
+ mode.setEnabled(false); assert.match(plain(nine), /Recorded row 9/); assert.doesNotMatch(plain(nine), /Show more/);
152
+ mode.setEnabled(true); assert.match(plain(nine), /Show more/);
153
+ const formatting = card('# A recorded heading\n\n```js\n' + Array.from({ length: 12 }, (_, n) => `const n${n} = ${n};`).join('\n') + '\n```\n\n[attachment: recorded.txt]');
154
+ plain(formatting);
155
+ const formattingChoice = [];
156
+ pi.events.emit('compact-renderer:inspect:v1', { add: choice => formattingChoice.push(choice) });
157
+ formattingChoice.find(choice => choice.label.includes('A recorded heading')).focus();
158
+ assert.match(plain(formatting), /const n11 = 11;/);
159
+ assert.match(plain(formatting), /attachment: recorded.txt/);
160
+ assert.equal(formatting.text.endsWith('[attachment: recorded.txt]'), true);
161
+ const unknown = card(source(9)); plain(unknown); unknown.children.push({ render: () => ['external attachment'], invalidate() {} });
162
+ assert.match(plain(unknown), /Recorded row 9/, 'unsupported user-component shapes retain native text and attachments');
163
+ assert.match(plain(unknown), /external attachment/);
164
+ emit('session_tree'); assert.match(plain(nine), /Show more/); assert.equal(key('\r'), false);
165
+ emit('session_shutdown'); assert.match(plain(nine), /Recorded row 9/); assert.equal(terminal.size, 0);
166
+ console.log('ordinary prompts: actual Pi 1.3.0 rendered-line threshold, exact excerpt/full source, native formatting, width changes, click/inspection, mode and lifecycle passed');
167
+ } finally { dispose(); }
@@ -0,0 +1,257 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createRequire } from 'node:module';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { assertCardBackground, themeModule as nativeTheme, stripAnsi } from './test-runtime.mjs';
7
+
8
+ const runtime = process.env.PI_RUNTIME || path.join(homedir(), '.local/state/pi-config/current/runtime');
9
+ const root = process.env.PI_INSTALL_ROOT || path.join(runtime, 'node_modules/@earendil-works/pi-coding-agent');
10
+ const require = createRequire(path.join(root, 'package.json'));
11
+ const tuiPath = require.resolve('@earendil-works/pi-tui');
12
+ const { visibleWidth, TuiAltScreen, Container, Text, getKeybindings, setKeybindings } = await import(pathToFileURL(tuiPath));
13
+ const { createEventBus } = await import(pathToFileURL(path.join(root, 'dist/core/event-bus.js')));
14
+ const { createJiti } = require('jiti');
15
+ const jiti = createJiti(import.meta.url, { fsCache: false, alias: { '@earendil-works/pi-tui': tuiPath } });
16
+ const { PermissionDialog, PermissionDetailsViewport, registerPermissionPresentation, PERMISSION_PRESENTATION_EVENT } = await jiti.import('../src/permission-presentation.ts');
17
+ const theme = { fg: (_color, value) => value };
18
+ const description = { version: 1, mode: 'tui', action: 'Run MCP operation', target: 'fixture/query',
19
+ reason: 'Fixture policy requires approval.', details: JSON.stringify({ query: "SELECT '完整 SQL'", text: 'full exact input' }, null, 2) };
20
+ const styled = new PermissionDialog(description, nativeTheme.theme, () => {}, () => {});
21
+ for (const details of [false, true]) {
22
+ if (details) styled.handleInput('d');
23
+ for (const width of [1, 2, 20, 100]) {
24
+ const rows = styled.render(width);
25
+ const selected = rows.findIndex(row => stripAnsi(row).includes('→'));
26
+ assert.ok(selected >= 0, 'native permission selection stays visible at narrow widths');
27
+ assertCardBackground([rows[selected]], width, 'selectedBg');
28
+ assertCardBackground(rows.filter((_, index) => index !== selected), width, 'toolPendingBg');
29
+ }
30
+ }
31
+
32
+ // Native keybindings, safe default, single resolution and bounded Details.
33
+ let resolutions = [];
34
+ const dialog = new PermissionDialog(description, theme, () => {}, value => resolutions.push(value));
35
+ assert.match(dialog.render(80).join('\n'), /→ Deny/);
36
+ assert.ok(!dialog.render(80).join('\n').includes('SELECT'));
37
+ dialog.handleInput('d');
38
+ assert.match(dialog.render(80).join('\n'), /SELECT '完整 SQL'/);
39
+ for (const width of [1, 2, 10, 20, 40, 80]) {
40
+ assert.ok(dialog.render(width).every(row => visibleWidth(row) <= width), `fits width ${width}`);
41
+ }
42
+ dialog.handleInput('\r'); dialog.handleInput('\x1b[A'); dialog.handleInput('\r'); dialog.dispose();
43
+ assert.deepEqual(resolutions, [false], 'Enter defaults to deny and can only settle once');
44
+ const allow = new PermissionDialog(description, theme, () => {}, value => resolutions.push(value));
45
+ allow.handleInput('\x1b[A'); allow.handleInput('\r');
46
+ assert.deepEqual(resolutions, [false, true], 'native up + Enter permits once');
47
+ const cancel = new PermissionDialog(description, theme, () => {}, value => resolutions.push(value));
48
+ cancel.handleInput('\x1b'); cancel.dispose();
49
+ assert.deepEqual(resolutions, [false, true, false], 'native Escape denies once');
50
+ const big = new PermissionDialog({ ...description, details: Array.from({ length: 1000 }, (_, i) => `exact line ${i}`).join('\n') }, theme, () => {}, () => {});
51
+ big.handleInput('d');
52
+ let painted = big.render(40);
53
+ assert.ok(painted.length < 25 && !painted.join('\n').includes('exact line 999'), 'paint only the bounded Details viewport');
54
+ big.handleInput('\x1b[F');
55
+ assert.match(big.render(40).join('\n'), /Full reason:/, 'End reaches the complete Details source including full summary fields');
56
+ big.handleInput('\x1b[H'); big.render(40); big.handleInput('\x1b[6~');
57
+ assert.match(big.render(40).join('\n'), /exact line 8/, 'PageDown scrolls Details');
58
+ big.handleInput('\x1b[5~');
59
+ assert.match(big.render(40).join('\n'), /exact line 0/, 'PageUp returns to first page');
60
+ big.handleInput('\x1b[C');
61
+ assert.match(big.render(40).join('\n'), /exact line 8/, 'Right pages Details without relying on fullscreen transcript keys');
62
+ big.handleInput('\x1b[D');
63
+ assert.match(big.render(40).join('\n'), /exact line 0/, 'Left pages Details backwards');
64
+ const controls = new PermissionDialog({ ...description, target: '\x1b]52;c;unsafe\x07' }, theme, () => {}, () => {});
65
+ assert.ok(!controls.render(80).join('\n').includes('\x1b'), 'labels cannot inject terminal controls');
66
+ const unicode = new PermissionDialog({ ...description, action: '处理😀', target: '文件/目录' }, theme, () => {}, () => {});
67
+ unicode.handleInput('d');
68
+ for (const width of [1, 2, 10, 20, 80]) assert.ok(unicode.render(width).every(row => visibleWidth(row) <= width));
69
+ const huge = new PermissionDetailsViewport(['x'.repeat(4_000_000), '\nEXACT END']);
70
+ let work = huge.workUnits;
71
+ assert.ok(huge.render(40, 8).length <= 8);
72
+ assert.ok(huge.workUnits - work < 4096, 'opening scans only viewport chunks');
73
+ work = huge.workUnits;
74
+ huge.render(40, 8);
75
+ assert.equal(huge.workUnits, work, 'unchanged paint reuses the viewport');
76
+ huge.pageDown(); huge.render(40, 8);
77
+ assert.ok(huge.workUnits - work < 4096, 'PageDown scans only the next viewport');
78
+ work = huge.workUnits;
79
+ huge.render(1, 8);
80
+ assert.ok(huge.workUnits - work < 4096, 'narrow resize does not wrap the full source');
81
+ work = huge.workUnits;
82
+ huge.end(40, 8);
83
+ assert.match(huge.render(40, 8).join('\n'), /EXACT END/);
84
+ assert.ok(huge.workUnits - work < 4096, 'End scans only a bounded suffix');
85
+ work = huge.workUnits;
86
+ const beforeBackward = huge.range.start;
87
+ huge.pageUp(); huge.render(40, 8);
88
+ assert.ok(huge.range.start > 0 && huge.range.start < beforeBackward && huge.range.end <= beforeBackward, 'PageUp after End seeks adjacent preceding content');
89
+ assert.ok(huge.workUnits - work < 4096, 'PageUp scans only a bounded predecessor viewport');
90
+ huge.render(1, 8);
91
+ work = huge.workUnits;
92
+ const beforeNarrowBackward = huge.range.start;
93
+ huge.pageUp(); huge.render(1, 8);
94
+ assert.equal(huge.range.start, beforeNarrowBackward - 8, 'narrow resize changes the preceding page length');
95
+ assert.equal(huge.range.end, beforeNarrowBackward);
96
+ assert.ok(huge.workUnits - work < 4096, 'PageUp after narrow resize stays bounded');
97
+ const exact = new PermissionDetailsViewport([Array.from({ length: 1000 }, (_, i) => `exact line ${i}`).join('\n')]);
98
+ exact.end(40, 8);
99
+ assert.match(exact.render(40, 8).join('\n'), /exact line 999/, 'the exact arguments tail remains reachable');
100
+ exact.pageUp();
101
+ assert.deepEqual(exact.render(40, 8), Array.from({ length: 8 }, (_, i) => `exact line ${984 + i}`), 'End then PageUp shows the preceding page, not navigation history');
102
+ exact.pageUp();
103
+ assert.deepEqual(exact.render(40, 8), Array.from({ length: 8 }, (_, i) => `exact line ${976 + i}`), 'backward paging continues through the source');
104
+ exact.pageDown();
105
+ assert.deepEqual(exact.render(40, 8), Array.from({ length: 8 }, (_, i) => `exact line ${984 + i}`), 'forward paging after backward seek preserves exact adjacency');
106
+ exact.end(40, 8); exact.render(40, 4); exact.pageUp();
107
+ assert.deepEqual(exact.render(40, 4), Array.from({ length: 4 }, (_, i) => `exact line ${988 + i}`), 'PageUp uses the resized viewport height');
108
+ for (const source of ['\x1b'.repeat(100), '\t'.repeat(100), '😀x'.repeat(100), 'line\n'.repeat(100)]) {
109
+ for (const width of [1, 2, 3, 5, 20]) for (const height of [1, 2, 8]) {
110
+ const tail = new PermissionDetailsViewport([source]);
111
+ tail.end(width, height); tail.render(width, height);
112
+ assert.equal(tail.range.end, tail.range.total, 'End includes the final source unit even when control escapes wrap');
113
+ }
114
+ }
115
+ const giantSummary = new PermissionDialog({ ...description, target: 't'.repeat(4_000_000) }, theme, () => {}, () => {});
116
+ assert.match(giantSummary.render(40).join('\n'), /Summary shortened/);
117
+ giantSummary.handleInput('d');
118
+ assert.ok(giantSummary.render(40).length <= 24, 'large labels do not expand the summary unboundedly');
119
+ assert.ok(giantSummary.detailsViewport.workUnits < 4096, 'full summary fields are lazy Details sources');
120
+ giantSummary.handleInput('\x1b[F');
121
+ assert.ok(giantSummary.render(40).length <= 24, 'bounded suffix access works with huge full summary fields');
122
+
123
+ function fixture() {
124
+ const events = createEventBus();
125
+ const hooks = new Map();
126
+ let enabled = true;
127
+ const listeners = new Set();
128
+ const mode = { isEnabled: () => enabled, onChange: callback => { listeners.add(callback); return () => listeners.delete(callback); } };
129
+ const pi = { events, on(event, callback) { hooks.set(event, [...hooks.get(event) || [], callback]); } };
130
+ let customCalls = 0, fallbackCalls = 0, component;
131
+ const ui = { custom(factory) {
132
+ customCalls++;
133
+ return new Promise(resolve => { component = factory({ requestRender() {} }, theme, {}, resolve); });
134
+ } };
135
+ const request = (overrides = {}) => {
136
+ let presenter;
137
+ let accepting = true;
138
+ const value = { ...description, ui, ...overrides, offer(candidate) {
139
+ if (presenter || !accepting) return false;
140
+ presenter = candidate; return true;
141
+ } };
142
+ events.emit(PERMISSION_PRESENTATION_EVENT, value);
143
+ accepting = false;
144
+ return { value, result: presenter ? presenter() : (fallbackCalls++, Promise.resolve(false)) };
145
+ };
146
+ return { pi, mode, ui, request, hooks, get component() { return component; },
147
+ get customCalls() { return customCalls; }, get fallbackCalls() { return fallbackCalls; },
148
+ setEnabled(value) { enabled = value; for (const callback of [...listeners]) callback(); } };
149
+ }
150
+
151
+ const f = fixture();
152
+ const dispose = registerPermissionPresentation(f.pi, f.mode);
153
+ const disposeDuplicate = registerPermissionPresentation(f.pi, f.mode);
154
+ let pending = f.request();
155
+ assert.equal(f.customCalls, 1, 'only the first synchronous offer creates UI');
156
+ f.component.handleInput('\x1b[A'); f.component.handleInput('\r');
157
+ assert.equal(await pending.result, true);
158
+ assert.equal(f.fallbackCalls, 0);
159
+ assert.equal(await f.request({ version: 2 }).result, false);
160
+ assert.equal(await f.request({ mode: 'rpc' }).result, false, 'RPC keeps native confirm');
161
+ assert.equal(await f.request({ ui: {} }).result, false, 'incompatible UI keeps native confirm');
162
+ f.setEnabled(false);
163
+ assert.equal(await f.request().result, false, 'disabled renderer keeps native confirm');
164
+ assert.equal(f.customCalls, 1);
165
+ f.setEnabled(true);
166
+ const abort = new AbortController();
167
+ pending = f.request({ signal: abort.signal }); abort.abort();
168
+ assert.equal(await pending.result, false, 'abort denies and closes pending dialog');
169
+ pending = f.request(); f.setEnabled(false);
170
+ assert.equal(await pending.result, false, 'disable cancels a pending dialog without fallback');
171
+ f.setEnabled(true);
172
+ for (const event of ['session_switch', 'session_tree', 'session_compact', 'session_shutdown']) {
173
+ pending = f.request();
174
+ for (const callback of f.hooks.get(event)) callback();
175
+ assert.equal(await pending.result, false, `${event} closes pending approval`);
176
+ }
177
+ pending = f.request(); dispose(); disposeDuplicate();
178
+ assert.equal(await pending.result, false, 'dispose cancels pending approval');
179
+ assert.equal(await f.request().result, false, 'dispose removes provider');
180
+ assert.equal(f.fallbackCalls, 5, 'cancellation never reopens a fallback prompt');
181
+
182
+ const failed = fixture();
183
+ registerPermissionPresentation(failed.pi, failed.mode);
184
+ failed.ui.custom = () => { throw new Error('UI unavailable'); };
185
+ await assert.rejects(failed.request().result, /UI unavailable/);
186
+ assert.equal(failed.fallbackCalls, 0, 'claimed failure never asks twice');
187
+ const before = new AbortController(); before.abort();
188
+ assert.equal(await failed.request({ signal: before.signal }).result, false, 'pre-aborted request creates no UI');
189
+
190
+ // Exercise the native fullscreen listener chain and InteractiveMode's actual
191
+ // custom-component mounting, input focus and restoration. No terminal process,
192
+ // session, network, credentials or model is needed for this UI boundary.
193
+ const { InteractiveMode, initTheme } = await import(pathToFileURL(path.join(root, 'dist/index.js')));
194
+ const { KeybindingsManager } = await import(pathToFileURL(path.join(root, 'dist/core/keybindings.js')));
195
+ initTheme('dark', false);
196
+ const previousKeys = getKeybindings();
197
+ const nativeKeys = new KeybindingsManager();
198
+ setKeybindings(nativeKeys);
199
+ let input;
200
+ const terminal = { columns: 80, rows: 30, kittyProtocolActive: false,
201
+ start(onInput) { input = onInput; }, stop() {}, write() {}, hideCursor() {}, showCursor() {},
202
+ clearLine() {}, clearFromCursor() {}, clearScreen() {}, moveBy() {}, setTitle() {}, setProgress() {}, setProgramStatus() {} };
203
+ const fullscreen = new TuiAltScreen(terminal, false, undefined, { mouse: false });
204
+ const editor = { text: 'preserved draft', getText() { return this.text; }, setText(value) { this.text = value; },
205
+ render() { return [this.text]; }, invalidate() {}, handleInput() {} };
206
+ const editorContainer = new Container(); editorContainer.addChild(editor);
207
+ fullscreen.addChild(new Text(Array.from({ length: 120 }, (_, i) => `Background transcript ${i}`).join('\n'), 0, 0));
208
+ fullscreen.addChild(editorContainer);
209
+ const nativeUI = Object.assign(Object.create(InteractiveMode.prototype), {
210
+ ui: fullscreen, editor, editorContainer, keybindings: nativeKeys,
211
+ extensionTerminalInputSubscriptions: new Set(),
212
+ });
213
+ const pipeline = fixture();
214
+ const disposePipeline = registerPermissionPresentation(pipeline.pi, pipeline.mode);
215
+ try {
216
+ fullscreen.start(); fullscreen.renderNow();
217
+ const pending = pipeline.request({ ui: nativeUI.createExtensionUIContext(),
218
+ details: Array.from({ length: 1000 }, (_, i) => `Pipeline exact line ${i}`).join('\n') });
219
+ await new Promise(resolve => setImmediate(resolve));
220
+ fullscreen.renderNow();
221
+ const card = fullscreen.getFocusedComponent();
222
+ assert.ok(card instanceof PermissionDialog, 'native custom UI focuses the permission component');
223
+ input('d'); fullscreen.renderNow();
224
+ assert.match(card.render(80).join('\n'), /←\/→ page Details/, 'show the usable fullscreen controls');
225
+ input('\x1b[F'); fullscreen.renderNow();
226
+ const atEnd = card.detailsViewport.range.start;
227
+ const backgroundBeforePageUp = fullscreen.viewportTop;
228
+ let extensionPagingCalls = 0;
229
+ const removeProbe = nativeUI.addExtensionTerminalInputListener(() => { extensionPagingCalls++; });
230
+ input('\x1b[5~'); fullscreen.renderNow();
231
+ assert.equal(card.detailsViewport.range.start, atEnd, 'native fullscreen consumes PageUp before the custom dialog');
232
+ assert.ok(fullscreen.viewportTop < backgroundBeforePageUp, 'the original failure scrolls the native transcript');
233
+ assert.equal(extensionPagingCalls, 0, 'a public extension listener runs too late to override transcript PageUp');
234
+ removeProbe();
235
+ const background = fullscreen.viewportTop;
236
+ input('\x1b[D'); fullscreen.renderNow();
237
+ const preceding = card.detailsViewport.range.start;
238
+ assert.ok(preceding < atEnd && preceding > 0, 'Left after End reaches adjacent preceding Details');
239
+ assert.equal(fullscreen.viewportTop, background, 'Left leaves the background transcript in place');
240
+ input('\x1b[C'); fullscreen.renderNow();
241
+ assert.ok(card.detailsViewport.range.start > preceding, 'Right pages Details forward through the native input pipeline');
242
+ assert.equal(fullscreen.viewportTop, background);
243
+ input('\x1b[H'); fullscreen.renderNow();
244
+ assert.equal(card.detailsViewport.range.start, 0, 'Home remains reachable in fullscreen');
245
+ input('\x1b[A'); fullscreen.renderNow();
246
+ assert.match(card.render(80).join('\n'), /→ Allow once/, 'plain Up still reaches native permission choice navigation');
247
+ input('\x1b[B'); fullscreen.renderNow();
248
+ assert.match(card.render(80).join('\n'), /→ Deny/, 'plain Down still reaches native permission choice navigation');
249
+ input('\x1b');
250
+ assert.equal(await pending.result, false, 'native Escape denies and closes the one prompt');
251
+ assert.equal(fullscreen.getFocusedComponent(), editor, 'native close restores editor focus');
252
+ assert.equal(editor.text, 'preserved draft');
253
+ assert.equal(pipeline.fallbackCalls, 0, 'fullscreen paging never starts another approval');
254
+ } finally {
255
+ disposePipeline(); nativeUI.clearExtensionTerminalInputListeners(); fullscreen.stop(); setKeybindings(previousKeys);
256
+ }
257
+ console.log('Permission presentation: native fullscreen input pipeline, keyboard, exact Details, bounded viewport, narrow Unicode, fallback, single resolution, abort, mode and session lifecycle passed.');