@notrico/pi-fold 3.0.0 → 3.0.2

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.
@@ -3,6 +3,7 @@ import test from 'node:test';
3
3
  import { loadSource, core, tui, themeModule, stripAnsi } from './test-runtime.mjs';
4
4
 
5
5
  const { registerModernThinking } = await loadSource('./modern-thinking.ts');
6
+ const { renderFinalReply } = await loadSource('./work-strip-view.ts');
6
7
  const { createDisplayMode } = await loadSource('./display-mode.ts');
7
8
  const { AssistantMessageComponent } = core;
8
9
  const native = Object.fromEntries(['updateContent', 'render', 'handleMouse'].map(key => [key, AssistantMessageComponent.prototype[key]]));
@@ -184,22 +185,24 @@ test('pure failed tool calls and user questions retain native thinking fallback'
184
185
  }
185
186
  });
186
187
 
187
- test('mixed singleton isolates neighboring pure groups', () => {
188
+ test('leading final thinking joins preceding rounds and ends the group at visible text', () => {
188
189
  const f = fixture([
189
190
  message([thinking('Previous source'), tool('a')]),
190
- message([thinking('Mixed source'), text('Visible reply')]),
191
+ message([thinking('Final source'), text('Visible reply')]),
191
192
  message([thinking('Following source'), tool('b')]),
192
193
  ]);
193
194
  try {
194
- assert.equal(f.choices().length, 3);
195
- f.cards.forEach(card => assert.match(plain(card.render(80)), /Thinking ·/));
196
- assert.match(plain(f.cards[0].render(80)), /Previous source/);
197
- assert.match(plain(f.cards[1].render(80)), /Mixed source/);
198
- assert.match(plain(f.cards[2].render(80)), /Following source/);
195
+ assert.equal(f.choices().length, 2);
196
+ assert.equal(f.cards[0].render(80).length, 0);
197
+ assert.match(plain(f.cards[1].render(80)), /Thinking · 2 rounds/);
198
+ assert.match(plain(f.cards[2].render(80)), /Thinking · Following source/);
199
+ f.choices()[0].focus();
200
+ assert.match(plain(assertNativeReply(f.cards[1])), /Previous source/);
201
+ assert.match(plain(assertNativeReply(f.cards[1])), /Final source/);
199
202
  } finally { f.dispose(); }
200
203
  });
201
204
 
202
- test('streaming pure thinking becomes an isolated mixed singleton', () => {
205
+ test('streaming final answer preserves its preceding thinking group', () => {
203
206
  const prior = message([thinking('Previous tool round'), tool('prior')]);
204
207
  const f = fixture([prior]);
205
208
  try {
@@ -211,9 +214,26 @@ test('streaming pure thinking becomes an isolated mixed singleton', () => {
211
214
  const update = { ...start, content: [...start.content, text('Visible streaming answer')] };
212
215
  f.emit('message_update', { message: update }); card.updateContent(update, true);
213
216
  f.emit('message_end', { message: update });
214
- assert.match(plain(f.cards[0].render(80)), /Thinking · Previous tool round/);
215
- assert.match(plain(assertNativeReply(card)), /Thinking · Streaming source\./);
216
- assert.equal(f.choices().length, 2);
217
+ assert.equal(f.cards[0].render(80).length, 0);
218
+ assert.match(plain(assertNativeReply(card)), /Thinking · 2 rounds/);
219
+ assert.equal(f.choices().length, 1);
220
+ } finally { f.dispose(); }
221
+ });
222
+
223
+ test('final reply padding preserves compact thinking and native child identity', () => {
224
+ const original = message([thinking('Final thinking summary.\nRecorded final body.'), text('Final visible answer')]);
225
+ const f = fixture([original]);
226
+ try {
227
+ const card = f.cards[0], children = [...card.contentContainer.children];
228
+ const rows = renderFinalReply(card, 80, themeModule.theme);
229
+ assert.match(plain(rows), /Thinking · Final thinking summary/);
230
+ assert.doesNotMatch(plain(rows), /Thinking\.\.\./);
231
+ assert.deepEqual(card.contentContainer.children, children);
232
+ const replyIndex = rows.findIndex(row => stripAnsi(row).includes('Final visible answer'));
233
+ assert.equal(stripAnsi(rows[replyIndex - 1]), ' '.repeat(80));
234
+ assert.equal(stripAnsi(rows[replyIndex + 1]), ' '.repeat(80));
235
+ assert.equal(mouse(card, rows.findIndex(row => stripAnsi(row).includes('Thinking ·')))?.handled, true);
236
+ assert.match(plain(renderFinalReply(card, 80, themeModule.theme)), /Recorded final body/);
217
237
  } finally { f.dispose(); }
218
238
  });
219
239
 
@@ -317,3 +337,35 @@ test('large mixed thinking uses a bounded viewport across narrow widths', () =>
317
337
  assert.equal(JSON.stringify(original), saved);
318
338
  } finally { tui.Markdown.prototype.render = render; f.dispose(); }
319
339
  });
340
+
341
+ test('visible preambles and unsupported multiple runs do not absorb preceding thinking', () => {
342
+ for (const content of [
343
+ [text('Visible preamble'), thinking('Later source'), text('Answer')],
344
+ [thinking('First run'), text('Visible boundary'), thinking('Second run'), text('Answer')],
345
+ ]) {
346
+ const f = fixture([message([thinking('Earlier round'), tool('earlier')]), message(content)]);
347
+ try {
348
+ assert.match(plain(f.cards[0].render(80)), /Thinking · Earlier round/);
349
+ assert.match(plain(f.cards[1].render(80)), /Answer/);
350
+ } finally { f.dispose(); }
351
+ }
352
+ });
353
+
354
+ test('streaming boundary changes split earlier rounds even when the broad message kind is unchanged', () => {
355
+ for (const extra of [thinking('Second separated run'), { type: 'toolCall', id: 'question', name: 'ask_user_question', arguments: {} }]) {
356
+ const earlier = message([thinking('Earlier source'), tool('earlier')]);
357
+ const f = fixture([earlier]);
358
+ try {
359
+ const current = message([thinking('Initial leading run'), text('Visible reply')]);
360
+ f.emit('message_start', {message: current});
361
+ const card = nativeCard(current); f.cards.push(card);
362
+ assert.equal(f.cards[0].render(80).length, 0);
363
+ assert.match(plain(card.render(80)), /Thinking · 2 rounds/);
364
+ current.content.push(extra);
365
+ const update = {...current};
366
+ f.emit('message_update', {message:update}); card.updateContent(update, true);
367
+ assert.match(plain(f.cards[0].render(80)), /Thinking · Earlier source/);
368
+ assert.doesNotMatch(plain(card.render(80)), /Thinking · 2 rounds/);
369
+ } finally { f.dispose(); }
370
+ }
371
+ });
@@ -568,6 +568,18 @@ scriptFailure.setExpanded(true);
568
568
  assert.doesNotMatch(paint(scriptFailure), /name too long, lstat/);
569
569
  clickSingle(scriptFailure, 3);
570
570
  assert.match(paint(scriptFailure), /ENAMETOOLONG: name too long, lstat/);
571
+ event('message_end', { message: { role: 'user', content: 'focused overflow fixture' } });
572
+ const focusedOverflow = make('read', 'focused-overflow', { path: '/fixture/focused-overflow' });
573
+ focusedOverflow.updateResult(result(Array.from({ length: 60 }, (_, n) => `Focused output ${n}`).join('\n')));
574
+ paint(focusedOverflow);
575
+ const overflowChoices = []; pi.events.emit('compact-renderer:inspect:v1', { add: choice => overflowChoices.push(choice) });
576
+ overflowChoices.find(choice => choice.label.includes('/fixture/focused-overflow')).focus();
577
+ const focusedOverflowRows = focusedOverflow.render(120).map(stripAnsi);
578
+ assert.match(focusedOverflowRows.join('\n'), /Focused output 0\b/);
579
+ clickSingle(focusedOverflow, focusedOverflowRows.findIndex(row => row.includes('more ↓')));
580
+ assert.doesNotMatch(paint(focusedOverflow), /Focused output 0\b/, 'overflow paging survives mouse release of inspection');
581
+ assert.doesNotMatch(paint(focusedOverflow), / · focused/);
582
+ assert.equal(input('\r'), undefined, 'tool overflow returns Enter to the editor');
571
583
  const styled = new ToolPane([{ id: 'styles', label: 'read', sections: function* () {
572
584
  yield { text: '# Recorded heading\n**Emphasis** and `inline` code.\n```javascript\nconst paths = ["/fixture/a"];\n```', format: 'markdown' };
573
585
  yield { text: '-const before = 1;\n+const after = 2;', format: 'code', language: 'diff' };
@@ -648,6 +660,38 @@ assert.equal(narrative.open, false); assert.equal(narrative.focused, false); ass
648
660
  assert.equal(narrative.expanded.size, 0); assert.equal(narrative.detailsExpanded.size, 0);
649
661
  narrative.open = true;
650
662
  assert.doesNotMatch(narrative.render(80).map(stripAnsi).join('\n'), /First body|Second body/, 'explicit reset reopens with all actions closed');
663
+ // Content that already fits must not lose a row just because the user wheels down.
664
+ const fittingPane = new ToolPane([{ id: 'fits', label: 'Read', sections: () => Array.from({ length: 7 }, (_, n) => `Fitting row ${n}`) }], 'Read', () => 8);
665
+ fittingPane.open = true;
666
+ const fittingRows = fittingPane.render(80);
667
+ fittingPane.handleMouse({ type: 'wheel', button: 'none', x: 3, y: 2, wheelDelta: 1 });
668
+ assert.deepEqual(fittingPane.render(80), fittingRows, 'a fully visible result does not create artificial overflow');
669
+ assert.equal(fittingPane.offset, 0);
670
+ // The rendered overflow footer pages the existing inline viewport and preserves Details state.
671
+ const overflowPane = new ToolPane([{ id: 'overflow', label: 'Read', sections: function* () {
672
+ for (let n = 0; n < 60; n++) yield `Recorded output ${n}`;
673
+ }, details: () => ['Exact arguments'] }], 'Read', () => 8);
674
+ overflowPane.open = true; overflowPane.detailsExpanded.add('overflow');
675
+ let overflowRows = overflowPane.render(80).map(stripAnsi);
676
+ const clickOverflow = extra => overflowPane.handleMouse({ type: 'click', button: 'left', x: 3, y: overflowRows.findIndex(row => row.includes('more ↓')), ...extra });
677
+ assert.equal(clickOverflow({ shift: true })?.render, false); assert.equal(overflowPane.offset, 0, 'modified overflow clicks preserve text selection');
678
+ assert.equal(clickOverflow()?.handled, true);
679
+ overflowRows = overflowPane.render(80).map(stripAnsi);
680
+ assert.ok(overflowPane.offset > 0 && overflowPane.offset <= 8, 'overflow click advances one bounded tool viewport');
681
+ assert.doesNotMatch(overflowRows.join('\n'), /Recorded output 0\b/);
682
+ assert.ok(overflowPane.detailsExpanded.has('overflow'), 'paging preserves Details expansion');
683
+ for (let n = 0; n < 20 && overflowRows.some(row => row.includes('more ↓')); n++) {
684
+ clickOverflow(); overflowRows = overflowPane.render(80).map(stripAnsi);
685
+ }
686
+ assert.match(overflowRows.join('\n'), /Recorded output 59/);
687
+ assert.doesNotMatch(overflowRows.join('\n'), /more ↓/, 'downward paging stops at the end');
688
+ const overflowEndOffset = overflowPane.offset, overflowEndHeight = overflowRows.length;
689
+ assert.match(overflowRows.at(-1), /more ↑/);
690
+ overflowPane.handleMouse({ type: 'click', button: 'left', x: 3, y: overflowRows.length - 1 });
691
+ overflowRows = overflowPane.render(80).map(stripAnsi);
692
+ assert.ok(overflowPane.offset < overflowEndOffset, 'the final footer pages back');
693
+ assert.equal(overflowRows.length, overflowEndHeight, 'tool and thinking panes retain their height at the end');
694
+ assert.ok(overflowPane.paintedRows < 80, 'paging only formats the bounded visited output');
651
695
  const { suppressRepeatedSummary } = await loadSource('./recorded-summary.ts');
652
696
  const originalSummary = '# **Check inputs**\n\nFirst paragraph.\n\nSecond paragraph.';
653
697
  assert.equal(suppressRepeatedSummary(originalSummary, 'Check inputs'), 'First paragraph.\n\nSecond paragraph.');
@@ -669,6 +713,15 @@ summaryPane.focused = true;
669
713
  assert.match(summaryPane.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'focus suffix clipping restores the repeated heading after a cached render');
670
714
  summaryPane.focused = false;
671
715
  assert.doesNotMatch(summaryPane.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'removing focus updates suppression without a width change');
716
+ const clippedOverflow = new ToolPane([{ id: 'clipped-overflow', label: 'Exact title', repeatedSummary: 'Exact title', sections: () => [{ text: '# Exact title\n\n' + Array.from({ length: 50 }, (_, n) => `Body ${n}`).join('\n'), format: 'markdown' }] }], 'Thinking · Exact title', () => 8);
717
+ clippedOverflow.open = true; clippedOverflow.focused = true;
718
+ let clippedRows = clippedOverflow.render(30).map(stripAnsi);
719
+ assert.match(clippedRows.slice(1).join('\n'), /Exact title/);
720
+ clippedOverflow.handleMouse({ type: 'click', button: 'left', x: 3, y: clippedRows.findIndex(row => row.includes('more ↓')) });
721
+ clippedOverflow.focused = false; clippedRows = clippedOverflow.render(30).map(stripAnsi);
722
+ assert.ok(clippedOverflow.offset > 0, 'a focus-clipped heading also preserves the paged position');
723
+ clippedOverflow.handle('\x1b[H');
724
+ assert.doesNotMatch(clippedOverflow.render(30).map(stripAnsi).slice(1).join('\n'), /Exact title/, 'Home resets the cache using the current complete heading');
672
725
  const exactValues = { command: 'printf "hello"\nnext exact line', options: { paths: ['a', 'b'], empty: '', nullable: null } };
673
726
  const valueRows = [...recordedValues(exactValues)];
674
727
  assert.ok(valueRows.some(row => row.text === exactValues.command), 'multiline string values remain exact');
@@ -1,9 +1,10 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import path from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
- import { loadSource, core, tui, runtime, themeModule, stripAnsi } from './test-runtime.mjs';
4
+ import { loadSource, core, tui, runtime, themeModule, stripAnsi, backgroundCells } from './test-runtime.mjs';
5
5
  const { modernWorkflowFences, WorkflowPane, registerModernWorkflows } = await loadSource('./modern-workflows.ts');
6
6
  const { registerModernThinking } = await loadSource('./modern-thinking.ts');
7
+ const { renderFinalReply } = await loadSource('./work-strip-view.ts');
7
8
  const { default: piFold } = await loadSource('../index.ts');
8
9
  const { createDisplayMode } = await loadSource('./display-mode.ts');
9
10
  const { readReplyWorkflowScript } = await import(pathToFileURL(path.join(runtime, 'node_modules/pi-subagents/src/extension/reply-workflow-script.js')).href);
@@ -59,6 +60,16 @@ try {
59
60
  mouse(card, header); assert.match(plain(card.render(100)), /const label/);
60
61
  assert.equal(mouse(card, header + 2, 'wheel').handled, true);
61
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');
62
73
  choices()[0].focus(); assert.equal(key('\x1b'), true); assert.equal(key('\r'), false);
63
74
  choices()[0].focus(); emit('ui_prompt_start'); assert.equal(key('\r'), false);
64
75
  choices()[0].focus(); pi.events.emit('compact-renderer:focus:v1', { owner: 'tools' }); assert.equal(key('\r'), false);
@@ -109,6 +120,20 @@ try {
109
120
  dispose = registerModernWorkflows(pi, mode); emit('session_start'); assert.match(plain(card.render(100)), /Subagent workflow/);
110
121
  const oldDispose = dispose; dispose = registerModernWorkflows(pi, mode); emit('session_start'); oldDispose(); assert.equal(terminal.size, 2);
111
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');
112
137
  dispose(); disposeThinking(); assert.deepEqual({ render: AssistantMessageComponent.prototype.render, mouse: AssistantMessageComponent.prototype.handleMouse, update: AssistantMessageComponent.prototype.updateContent }, native);
113
138
  assert.equal(JSON.stringify(branch), exactMessage, 'recorded assistant message and transcript stay exact');
114
139
  assert.deepEqual(readReplyWorkflowScript(sessionManager, 'workflow-call'), scriptBefore, 'installed workflow executor reads the same original script after display interactions');
@@ -141,6 +166,23 @@ try {
141
166
  huge.render(80); assert.equal(huge.paintedRows, 0, 'closed panes never format source');
142
167
  huge.open = true; const hugeRows = huge.render(80); assert.ok(hugeRows.length <= 15); assert.ok(huge.paintedRows <= 15);
143
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');
144
186
  const longLine = new WorkflowPane('const value = "' + '🙂'.repeat(200000) + '";', 'Long line'); longLine.open = true;
145
187
  assert.ok(longLine.render(12).length <= 15); assert.ok(longLine.paintedRows <= 15);
146
188
  console.log('modern workflows: exact executor source, bounded native syntax, surrounding prose, independent fences, native thinking, mouse/editor/inspection, lifecycle, and fallback passed');
@@ -10,7 +10,7 @@ const { core, runtime, manager, temporary, runtimePath, cwd } = preview;
10
10
  const load = file => import(pathToFileURL(path.join(runtimePath, 'node_modules/@earendil-works/pi-coding-agent/dist', file)).href);
11
11
  const { initTheme, theme } = await load('modes/interactive/theme/theme.js');
12
12
  const { codemodeRenderers } = await load('extensions/codemode/renderer.js');
13
- const { Text } = await import(pathToFileURL(path.join(runtimePath, 'node_modules/@earendil-works/pi-tui/dist/index.js')).href);
13
+ const { Text } = await import(pathToFileURL(preview.tuiPath).href);
14
14
  const strip = value => value.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g, '');
15
15
  const paint = (component, width = 100) => strip(component.render(width).join('\n'));
16
16
  initTheme('dark', false);
@@ -70,11 +70,10 @@ const replay = () => {
70
70
  return display.chatContainer.children.filter(row => row instanceof ToolExecutionComponent);
71
71
  };
72
72
  const assertCompactHistory = (rows, label) => {
73
- assert.match(paint(rows[0]), /▸ 2 actions/, `${label}: historical bash and namespaced MCP results stay grouped`);
73
+ assert.match(paint(rows[0]), /▸ 3 actions/, `${label}: historical bash, namespaced MCP and clean codemode results stay grouped`);
74
74
  assert.doesNotMatch(paint(rows[0]), /EXACT_RECORDED_BASH_OUTPUT|EXACT_RECORDED_MCP_OUTPUT/, `${label}: grouped output stays collapsed`);
75
75
  assert.equal(paint(rows[1]), '', `${label}: the second historical action does not duplicate the group`);
76
- assert.match(paint(rows[2]), /▸ codemode/, `${label}: historical codemode retains its compact card`);
77
- assert.doesNotMatch(paint(rows[2]), /RECORDED_CODE_SOURCE|EXACT_RECORDED_CODE_OUTPUT/, `${label}: codemode source and output stay collapsed`);
76
+ assert.equal(paint(rows[2]), '', `${label}: historical codemode does not duplicate the mixed group`);
78
77
  assert.match(paint(rows[3]), /▸ read .*1 image/, `${label}: direct image read keeps its compact heading and image count`);
79
78
  assert.match(paint(rows[4]), /▸ codemode.*2 images/, `${label}: image-bearing codemode keeps its compact heading and image count`);
80
79
  for (const [row, count] of [[rows[3], 1], [rows[4], 2]]) {
@@ -129,7 +128,8 @@ try {
129
128
  assert.equal(paint(freshMcp), '');
130
129
  assert.doesNotMatch(paint(freshBash), /EXACT_RECORDED_BASH_OUTPUT|EXACT_RECORDED_MCP_OUTPUT/);
131
130
  const freshCode = create({ ...fixture[2], id: 'fresh-code' });
132
- assert.match(paint(freshCode), /▸ codemode/);
131
+ assert.match(paint(freshBash), /▸ 3 actions/);
132
+ assert.equal(paint(freshCode), '');
133
133
  assert.doesNotMatch(paint(freshCode), /RECORDED_CODE_SOURCE|EXACT_RECORDED_CODE_OUTPUT/);
134
134
  assertCompactHistory(rows, 'fresh calls preserve historical groups');
135
135
 
@@ -146,7 +146,7 @@ try {
146
146
  invalidate(rows);
147
147
  assert.match(paint(rows[0]), /EXACT_RECORDED_BASH_OUTPUT/, 'detached old bash row uses native fallback after switch');
148
148
  assert.match(paint(rows[1]), /EXACT_RECORDED_MCP_OUTPUT/, 'detached old MCP row uses native fallback after switch');
149
- assert.doesNotMatch(paint(rows[0]), /▸ 2 actions/, 'detached row cannot adopt the new session group');
149
+ assert.doesNotMatch(paint(rows[0]), /▸ 3 actions/, 'detached row cannot adopt the new session group');
150
150
  assertCompactHistory(replacementRows, 'late detached-row invalidation');
151
151
 
152
152
  event('session_shutdown', { reason: 'shutdown' });
@@ -6,8 +6,10 @@ import assert from 'node:assert/strict';
6
6
 
7
7
  export const runtime = path.resolve(process.env.PI_RUNTIME || path.join(homedir(), '.local/state/pi-config/current/runtime'));
8
8
  export const agentRoot = path.resolve(process.env.PI_INSTALL_ROOT || path.join(runtime, 'node_modules/@earendil-works/pi-coding-agent'));
9
- export const tuiRoot = path.join(path.dirname(agentRoot), 'pi-tui');
10
9
  const require = createRequire(path.join(agentRoot, 'package.json'));
10
+ // Use Pi's own TUI dependency even when another extension installs a newer
11
+ // version at the runtime root; native component identity must match the aliases.
12
+ export const tuiRoot = path.dirname(path.dirname(require.resolve('@earendil-works/pi-tui')));
11
13
  const { createJiti } = require('jiti');
12
14
  const sourceOptions = { fsCache: false, alias: {
13
15
  '@earendil-works/pi-coding-agent': path.join(agentRoot, 'dist/index.js'),
@@ -1,6 +1,8 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { backgroundCells, core, loadSource, stripAnsi, themeModule, tui } from './test-runtime.mjs';
3
3
 
4
+ const { finalReplyRendering } = await loadSource('./display-card.ts');
5
+ const { registerModernThinking } = await loadSource('./modern-thinking.ts');
4
6
  const { registerWorkStrip } = await loadSource('./work-strip.ts');
5
7
  const { registerFoldCommand } = await loadSource('./fold-command.ts');
6
8
  const { createDisplayMode } = await loadSource('./display-mode.ts');
@@ -38,6 +40,7 @@ for (const appearance of ['dark', 'light']) {
38
40
  assertReplySurface(painted, theme);
39
41
  assert.deepEqual(painted.join('\n').match(/\x1b\]133;[ABC]\x07/g), native.join('\n').match(/\x1b\]133;[ABC]\x07/g), 'native OSC zones remain exact');
40
42
  assert.equal(markdown.render, originalRender);
43
+ assert.equal(Object.hasOwn(row, finalReplyRendering), false, 'successful final rendering removes its scoped marker');
41
44
  assert.deepEqual(Object.getOwnPropertyDescriptor(markdown, 'render'), ownRender, 'render projection restores the native property shape');
42
45
  }
43
46
  }
@@ -55,6 +58,10 @@ for (const appearance of ['dark', 'light']) {
55
58
  const render = markdown.render;
56
59
  assert.throws(() => renderFinalReply(row, 40, themeModule.theme), /synthetic Markdown failure/);
57
60
  assert.equal(markdown.render, render, 'a failed native render also restores the method');
61
+ assert.equal(Object.hasOwn(row, finalReplyRendering), false, 'failed final rendering also removes its scoped marker');
62
+ row[finalReplyRendering] = 'outer render';
63
+ assert.throws(() => renderFinalReply(row, 40, themeModule.theme), /synthetic Markdown failure/);
64
+ assert.equal(row[finalReplyRendering], 'outer render', 'nested final rendering restores an existing marker');
58
65
  }
59
66
 
60
67
  // Multiple text blocks share one padding pair. A later thinking region keeps
@@ -75,7 +82,7 @@ for (const appearance of ['dark', 'light']) {
75
82
  assert.match(stripAnsi(renderFinalReply(row, 60, themeModule.theme).join('\n')), /CLICKED_NATIVE_THINKING/);
76
83
  }
77
84
 
78
- function fixture() {
85
+ function fixture({ thinking = false } = {}) {
79
86
  const hooks = new Map(), bus = new Map(), commands = new Map();
80
87
  const subscribe = (map, name, fn) => {
81
88
  const set = map.get(name) || new Set(); map.set(name, set); set.add(fn); return () => set.delete(fn);
@@ -87,9 +94,12 @@ function fixture() {
87
94
  getAllTools: () => [], appendEntry: (kind, data) => manager.appendCustomEntry(kind, data),
88
95
  registerCommand: (name, definition) => commands.set(name, definition),
89
96
  };
90
- const mode = createDisplayMode(), workControls = registerWorkStrip(pi, mode), dispose = workControls.dispose;
97
+ const mode = createDisplayMode(), workControls = registerWorkStrip(pi, mode);
98
+ const stopThinking = thinking ? registerModernThinking(pi, mode) : () => {};
99
+ const dispose = () => { stopThinking(); workControls.dispose(); };
91
100
  registerFoldCommand(pi, mode, workControls);
92
101
  const ui = { theme: themeModule.theme, isFollowingOutput: true, notify() {}, requestRender() {} };
102
+ if (thinking) ui.setHiddenThinkingLabel = () => { for (const row of display.chatContainer.children) if (row instanceof core.AssistantMessageComponent) row.setHiddenThinkingLabel('Thinking...'); };
93
103
  const ctx = { mode: 'tui', hasUI: true, ui, sessionManager: manager, isIdle: () => true };
94
104
  const display = {
95
105
  chatContainer: new tui.Container(), ui, pendingTools: new Map(), outputPad: 1,
@@ -269,3 +279,43 @@ for (const stopReason of ['stop', 'toolUse', 'error', 'aborted', 'length']) {
269
279
  }
270
280
 
271
281
  console.log('Final reply padded neutral card: native Markdown, one padding pair, outer gaps, resets, images, themes, settlement, direct replies, folding, mouse coordinates and compact-off passed');
282
+
283
+ // Restored transcript: two tool rounds and leading thinking on the final answer.
284
+ // Both adapters must cooperate while final padding and work folding are active.
285
+ {
286
+ const f = fixture({ thinking: true });
287
+ try {
288
+ const user = f.add({ role: 'user', content: 'Inspect the recorded samples.' });
289
+ for (let n = 1; n <= 2; n++) {
290
+ f.add({ role: 'assistant', stopReason: 'toolUse', content: [
291
+ { type: 'thinking', thinking: `Round ${n} summary.\nRecorded round ${n} body.` },
292
+ { type: 'toolCall', id: `round-${n}`, name: 'read', arguments: {} },
293
+ ] });
294
+ f.tool();
295
+ }
296
+ const final = f.add({ role: 'assistant', stopReason: 'stop', content: [
297
+ { type: 'thinking', thinking: 'Final source summary.\nRecorded final body.' },
298
+ { type: 'text', text: 'GROUPED_FINAL_REPLY' },
299
+ ] });
300
+ f.manager.appendCustomEntry(workEvidenceType, { version: 1, userId: user.entry.id,
301
+ finalId: final.entry.id, endId: final.entry.id, startedAt: 1000, endedAt: 2000, outcome: 'completed' });
302
+ const transcript = JSON.stringify(f.manager.getBranch());
303
+ f.event('session_start');
304
+ assert.doesNotMatch(stripAnsi(f.paint().join('\n')), /Thinking/);
305
+ for (let repeat = 0; repeat < 3; repeat++) {
306
+ await f.commands.get('fold').handler('expand', f.ctx);
307
+ const rendered = stripAnsi(f.paint().join('\n'));
308
+ assert.match(rendered, /Thinking · 3 rounds/);
309
+ assert.doesNotMatch(rendered, /Thinking\.\.\./);
310
+ assert.equal((rendered.match(/Thinking ·/g) || []).length, 1);
311
+ const surface = f.view(final.row), rows = surface.render(60);
312
+ const y = rows.findIndex(line => stripAnsi(line).includes('Thinking ·'));
313
+ assert.equal(surface.handleMouse({ type: 'click', button: 'left', x: 2, y, width: 60, height: rows.length })?.handled, true);
314
+ assert.match(stripAnsi(f.paint().join('\n')), /3\. Final source summary/);
315
+ await f.commands.get('fold').handler('collapse', f.ctx);
316
+ assert.doesNotMatch(stripAnsi(f.paint().join('\n')), /Thinking|Recorded final body/);
317
+ assert.match(stripAnsi(f.paint().join('\n')), /GROUPED_FINAL_REPLY/);
318
+ }
319
+ assert.equal(JSON.stringify(f.manager.getBranch()), transcript);
320
+ } finally { f.dispose(); f.mode.dispose(); }
321
+ }
@@ -4,7 +4,7 @@ import {pathToFileURL} from 'node:url';
4
4
  import {createWorkStripPreview} from '../scripts/preview-work-strip.mjs';
5
5
  const preview=await createWorkStripPreview({stepMs:20});
6
6
  const {core,runtime,manager}=preview;
7
- const {visibleWidth}=await import(pathToFileURL(path.join(preview.runtimePath,'node_modules/@earendil-works/pi-tui/dist/index.js')));
7
+ const {visibleWidth}=await import(pathToFileURL(preview.tuiPath));
8
8
  const {theme,initTheme}=await import(pathToFileURL(path.join(preview.runtimePath,'node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js')));
9
9
  initTheme('dark',false);
10
10
  const strip=s=>s.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g,'');