@notrico/pi-fold 3.0.0 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Release notes
2
2
 
3
+ ## 3.0.1 — Inspection paging and final thinking
4
+
5
+ - Make `more ↓` advance expanded tool, codemode, workflow, and thinking panes by one visible page. Preserve prompt typing after mouse inspection.
6
+ - Keep the overflow footer in place at the end as `more ↑`, so upward scrolling stays inside the pane. Clicking it pages backward.
7
+ - Keep leading thinking on a final answer with the preceding thinking rounds. Preserve visible-reply, error, and question boundaries.
8
+ - Preserve compact thinking while painting the final answer background and padding.
9
+
3
10
  ## 3.0.0 — Pi Fold
4
11
 
5
12
  - Rename the public interface to Pi Fold and combine display mode, collapse/expand, and shortcut controls under `/fold`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notrico/pi-fold",
3
- "version": "3.0.0",
3
+ "version": "3.0.1",
4
4
  "type": "module",
5
5
  "description": "Pi Fold: readable agent transcripts with collapsible work, inspectable details, and clear final replies",
6
6
  "license": "MIT",
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ // Isolated recorded-content preview; no model or tool execution.
3
+ import { createWorkStripPreview } from './preview-work-strip.mjs';
4
+ const preview = await createWorkStripPreview({ inspection: true });
5
+ let ui;
6
+ try {
7
+ ui = new preview.core.InteractiveMode(preview.runtime, { tuiMode: 'fullscreen' });
8
+ await ui.run();
9
+ } finally { ui?.stop(); await preview.cleanup(); }
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createPreview } from './preview.mjs';
7
7
 
8
- export async function createWorkStripPreview({ stepMs = 1000 } = {}) {
8
+ export async function createWorkStripPreview({ stepMs = 1000, inspection = false } = {}) {
9
9
  const old = process.env.PI_PREVIEW_WORK_STRIP;
10
10
  process.env.PI_PREVIEW_WORK_STRIP = '1';
11
11
  const preview = await createPreview();
@@ -32,6 +32,23 @@ export async function createWorkStripPreview({ stepMs = 1000 } = {}) {
32
32
  'This is a display fixture. Do not execute tools or access any external data.',
33
33
  ].join('\n'),timestamp:Date.now()});
34
34
  manager.appendMessage(assistant('This direct reply has no work strip. Expand the prompt above to inspect all ten recorded requirements.'));
35
+ if (inspection) {
36
+ manager.appendMessage({role:'user',content:'Inspection regression preview: expand the work, then click more in the recorded code output and the three-round thinking group.',timestamp:Date.now()});
37
+ const userId = manager.getBranch().at(-1).id;
38
+ for (let i = 1; i <= 2; i++) {
39
+ const name = i === 1 ? 'read' : 'codemode';
40
+ const args = i === 1 ? {path:'/fixture/recorded.txt'} : {code:'text(await tools.read({ path: "/fixture/recorded.txt" }));'};
41
+ const call = assistant(''); call.stopReason = 'toolUse';
42
+ call.content = [{type:'thinking',thinking:`Review recorded sample ${i}.\n\n` + Array.from({length:45},(_,n)=>`Round ${i}, recorded line ${n+1}. This is invented fixture text.`).join('\n')}, {type:'toolCall',id:`inspection-${i}`,name,arguments:args}];
43
+ manager.appendMessage(call);
44
+ manager.appendMessage({role:'toolResult',toolCallId:`inspection-${i}`,toolName:name,content:[{type:'text',text:Array.from({length:60},(_,n)=>`Recorded output ${n+1}`).join('\n')}],details:i===2?{calls:[{name:'read',args:JSON.stringify({path:'/fixture/recorded.txt'}),status:'ok',durationMs:1}]}:{},isError:false,timestamp:Date.now()});
45
+ }
46
+ const final = assistant('Inspection result: the final thinking belongs to the same three-round group. Clicking more advances the recorded output. This answer stays outside the group. No tools or model ran.');
47
+ final.content.unshift({type:'thinking',thinking:'Finalize the recorded result.\n\n' + Array.from({length:45},(_,n)=>`Final round, recorded line ${n+1}. This is invented fixture text.`).join('\n')});
48
+ manager.appendMessage(final);
49
+ const finalId = manager.getBranch().at(-1).id;
50
+ manager.appendCustomEntry('compact-renderer:work-settled:v1',{version:1,userId,finalId,endId:finalId,startedAt:base-90000,endedAt:base,outcome:'completed'});
51
+ }
35
52
  const emit = async event => {
36
53
  if (stopped) return;
37
54
  runtime.session._emit(event);
package/scripts/test.mjs CHANGED
@@ -7,7 +7,7 @@ import { spawnSync } from 'node:child_process';
7
7
  const directory = fileURLToPath(new URL('../tests/', import.meta.url));
8
8
  const required = ['action-intent.test.mjs', 'modern-workflows.test.mjs', 'display-mode.test.mjs', 'modern-tools.test.mjs', 'modern-subagent-messages.test.mjs', 'subagent-spacing.test.mjs', 'modern-subagent-groups.test.mjs', 'modern-thinking.test.mjs', 'modern-prompts.test.mjs', 'permission-presentation.test.mjs', 'input-focus.test.mjs', 'inspection.test.mjs', 'codemode.test.mjs', 'preview-example.test.mjs'];
9
9
  required.push('reload-lifecycle.test.mjs', 'ordinary-prompts.test.mjs', 'work-strip-hierarchy.test.mjs', 'work-strip-final-surface.test.mjs');
10
- required.push('modern-skill-prompts.test.mjs');
10
+ required.push('modern-skill-prompts.test.mjs', 'inspection-wheel.test.mjs');
11
11
  required.push('display-line-cache.test.mjs');
12
12
  required.push('display-cache-lifecycle.test.mjs');
13
13
  required.push('fold-command.test.mjs', 'fold-shortcut.test.mjs');
@@ -3,6 +3,8 @@ import { DisplayLineCache } from "./display-line-cache.ts";
3
3
 
4
4
  const lines = new DisplayLineCache();
5
5
  export const clearDisplayLineCache = () => lines.clear();
6
+ // Final reply projections retain native Markdown rather than workflow controls.
7
+ export const finalReplyRendering = Symbol.for("compact-renderer:final-reply-rendering:v1");
6
8
  // Key the actual styling bytes, not theme identity: themes can change in place.
7
9
  const memoLine = (kind: string, line: string, width: number, style: string, render: () => string) =>
8
10
  line.length > 4096 ? render() : lines.get(JSON.stringify([kind, width, style, line]), render);
@@ -9,7 +9,7 @@ export class CodePane {
9
9
  title = "codemode · Preparing"; theme?: any; tone = "syntaxVariable";
10
10
  content = new CodeContent();
11
11
  private rows: string[] = []; private iterator?: Iterator<string>; private done = false; private width = 0;
12
- private lastWidth = 0; private lastHeight = 0;
12
+ private lastWidth = 0; private lastHeight = 0; private lastBodyHeight = 0; private lastMore = false;
13
13
  private startedAt?: number; private endedAt?: number; private interval?: ReturnType<typeof setInterval>;
14
14
  private themeKey = "";
15
15
  private partial = false; private isError = false; private durationMs?: number;
@@ -59,7 +59,7 @@ export class CodePane {
59
59
  this.theme.fg(this.tone === "error" ? "error" : this.tone === "warning" && /^ · \d+ nested (?:errors?|cancelled|unresolved)$/.test(part) ? "warning" : "muted", part)).join("")
60
60
  : title;
61
61
  const header = activityRow(styled, width, this.theme, this.focused);
62
- if (!this.open) { this.lastHeight = 1; return [header]; }
62
+ if (!this.open) { this.lastHeight = 1; this.lastBodyHeight = 0; this.lastMore = false; return [header]; }
63
63
  const indent = contentWidth >= 4 ? " " : "";
64
64
  const nativeWidth = Math.max(1, contentWidth - indent.length);
65
65
  if (this.width !== nativeWidth) { this.reset(); this.width = nativeWidth; this.offset = 0; }
@@ -85,8 +85,9 @@ export class CodePane {
85
85
  // heading so a narrow terminal does not lose the timing information.
86
86
  if (!this.partial && this.durationMs !== undefined && visibleWidth(title) > contentWidth) timer = `Took ${duration(this.durationMs)}`;
87
87
  else if (this.durationMs === undefined && this.startedAt !== undefined) timer = `${this.partial ? "Elapsed" : "Took"} ${duration((this.endedAt ?? Date.now()) - this.startedAt)}`;
88
- const footer = [timer, this.focused ? `Enter collapse · ↑/↓ scroll · Home start · Esc release${more ? " · more ↓" : ""}` : more ? "more ↓" : ""].filter(Boolean).join(" · ");
88
+ const footer = [more ? "more ↓" : this.offset > 0 ? "more ↑" : "", timer, this.focused ? "Enter collapse · ↑/↓ scroll · Home start · Esc release" : ""].filter(Boolean).join(" · ");
89
89
  const visible = [header, ...body, ...(footer ? [activityRow(this.theme ? this.theme.fg("muted", truncateToWidth(footer, contentWidth)) : truncateToWidth(footer, contentWidth), width, this.theme)] : [])];
90
+ this.lastBodyHeight = body.length; this.lastMore = more;
90
91
  this.lastHeight = visible.length; return visible;
91
92
  }
92
93
  handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
@@ -95,6 +96,7 @@ export class CodePane {
95
96
  if (event.type !== "click" || event.button !== "left") return undefined;
96
97
  if (event.shift || event.alt || event.ctrl) return { handled: true, render: false };
97
98
  if (event.y === 0) { this.open = !this.open; this.offset = 0; return { handled: true }; }
99
+ if (this.open && (this.lastMore || this.offset > 0) && event.y === this.lastHeight - 1) { this.offset = Math.max(0, this.offset + (this.lastMore ? 1 : -1) * Math.max(1, this.lastBodyHeight)); return { handled: true }; }
98
100
  return { handled: true, render: false };
99
101
  }
100
102
  invalidate() { this.reset(); }
@@ -5,7 +5,7 @@ import { hiddenThinkingShape, mixedThinkingRegion, installModernThinkingAdapter
5
5
  import { recordedPaneHeight } from "./modern-recorded-pane.ts";
6
6
  import { ToolPane, type PaneAction } from "./modern-tool-pane.ts";
7
7
 
8
- type Round = { id: number; sources?: string[]; action?: PaneAction; message: any; hasThinking: boolean; component?: any; kind: "round" | "bridge" | "boundary"; group?: ThinkingGroup };
8
+ type Round = { id: number; sources?: string[]; action?: PaneAction; message: any; hasThinking: boolean; joinsPrevious: boolean; component?: any; kind: "round" | "bridge" | "boundary"; group?: ThinkingGroup };
9
9
  type ThinkingGroup = { members: Round[]; pane: ToolPane; activeEpoch?: number; activeResult?: boolean };
10
10
  /** The label is an extract from recorded text, never a generated summary.
11
11
  * Limit work even when the first line has millions of characters. */
@@ -19,6 +19,21 @@ export function recordedThinkingLabel(sources: readonly string[]): string {
19
19
  }
20
20
 
21
21
  const hasThinking = (message: any) => (message?.content || []).some((b: any) => b.type === "thinking" && typeof b.thinking === "string" && b.thinking.trim());
22
+ // A leading run can join earlier rounds only before the first visible reply.
23
+ // Track this separately from the broad boundary kind during streaming updates.
24
+ const joinsPreviousThinking = (message: any): boolean => {
25
+ if (["error", "aborted", "length"].includes(message?.stopReason)) return false;
26
+ let runs = 0, inRun = false, firstVisible: string | undefined, hasText = false;
27
+ for (const block of message?.content || []) {
28
+ if (!["thinking", "text", "toolCall"].includes(block.type) || block.type === "toolCall" && ["ask_user_question", "question"].includes(block.name)) return false;
29
+ if (block.type !== "thinking") inRun = false;
30
+ if (block.type === "thinking" && block.thinking?.trim()) {
31
+ firstVisible ??= "thinking";
32
+ if (!inRun) { runs++; inRun = true; }
33
+ } else if (block.type === "text" && block.text?.trim()) { firstVisible ??= "text"; hasText = true; }
34
+ }
35
+ return hasText && firstVisible === "thinking" && runs === 1;
36
+ };
22
37
  const supportedThinking = (component: any, message: any) => hiddenThinkingShape(component, message) || !!mixedThinkingRegion(component, message);
23
38
  const classify = (message: any): Round["kind"] => {
24
39
  if (["error", "aborted", "length"].includes(message?.stopReason) || (message?.content || []).some((b: any) => b.type === "text" && b.text?.trim() || b.type === "toolCall" && ["ask_user_question", "question"].includes(b.name))) return "boundary";
@@ -57,10 +72,12 @@ export class ModernThinkingGroups {
57
72
  return;
58
73
  }
59
74
  let record = this.aliases.get(message) || (phase === "start" ? undefined : this.live);
60
- if (!record) { record = { id: this.records.length, message, hasThinking: hasThinking(message), kind: classify(message) }; this.records.push(record); this.dirty = true; }
75
+ if (!record) { record = { id: this.records.length, message, hasThinking: hasThinking(message), joinsPrevious: joinsPreviousThinking(message), kind: classify(message) }; this.records.push(record); this.dirty = true; }
61
76
  // Native streaming messages can share a mutated content array.
62
77
  const thinking = hasThinking(message);
63
78
  if (record.hasThinking !== thinking) { record.hasThinking = thinking; this.dirty = true; }
79
+ const joinsPrevious = joinsPreviousThinking(message);
80
+ if (record.joinsPrevious !== joinsPrevious) { record.joinsPrevious = joinsPrevious; this.dirty = true; }
64
81
  record.message = message; this.aliases.set(message, record);
65
82
  const kind = classify(message);
66
83
  if (record.kind !== kind) { record.kind = kind; this.dirty = true; }
@@ -90,8 +107,13 @@ export class ModernThinkingGroups {
90
107
  for (const record of this.records) {
91
108
  if (record) record.group = undefined;
92
109
  if (!record || record.kind === "boundary") {
110
+ const message = record?.message;
111
+ const mixed = record && hasThinking(message) && message.content.some((block: any) => block.type === "text" && block.text?.trim());
112
+ // Leading thinking precedes this reply boundary and belongs with the
113
+ // previous rounds. Text-first runs and failed/question messages stay separate.
114
+ if (!record?.joinsPrevious) flush();
115
+ if (mixed) members.push(record);
93
116
  flush();
94
- if (record && hasThinking(record.message) && record.message.content.some((block: any) => block.type === "text" && block.text?.trim())) { members.push(record); flush(); }
95
117
  }
96
118
  else if (record.kind === "round") members.push(record);
97
119
  }
@@ -39,11 +39,14 @@ export class ToolPane {
39
39
  private lastWidth = 0;
40
40
  private lastHeight = 0;
41
41
  private lastBodyHeight = 0;
42
+ private lastMore = false;
43
+ private contentFocused = false;
44
+ private preserveFocusLayout = false;
42
45
  // Instrumentation also makes the large-output contract testable without wall-clock assertions.
43
46
  paintedRows = 0;
44
47
  constructor(public actions: PaneAction[], public title: string, private height = () => 12) {}
45
48
  private get directDetails() { return this.directContent || this.itemName === "action" && this.actions.length === 1; }
46
- reset() { this.anchor = Math.min(this.anchor, Math.max(0, this.actions.length - 1)); this.key = ""; this.rows = []; this.iterator = undefined; this.done = false; this.actionRows.clear(); this.detailsRows.clear(); this.rowKinds.clear(); }
49
+ reset() { this.preserveFocusLayout = false; this.anchor = Math.min(this.anchor, Math.max(0, this.actions.length - 1)); this.key = ""; this.rows = []; this.iterator = undefined; this.done = false; this.actionRows.clear(); this.detailsRows.clear(); this.rowKinds.clear(); }
47
50
  collapse() { this.open = false; this.focused = false; this.selected = 0; this.anchor = 0; this.offset = 0; this.expanded.clear(); this.detailsExpanded.clear(); this.detailsFocused = false; this.reset(); }
48
51
  releaseInspection() { if (this.detailsFocused) { this.detailsFocused = false; this.offset = 0; this.reset(); } }
49
52
  handle(data: string): boolean {
@@ -107,12 +110,12 @@ export class ToolPane {
107
110
  const emitRows = function* (this: ToolPane, rows: Iterable<{ text: string; kind?: RowKind }>) {
108
111
  for (const row of rows) { if (row.kind) this.rowKinds.set(this.rows.length, row.kind); yield row.text; }
109
112
  }.bind(this);
110
- const fullLabel = this.directDetails ? `▾ ${this.expandedTitle ?? this.title}${this.focused ? " · focused" : ""}` : prefix + action.label;
113
+ const fullLabel = this.directDetails ? `▾ ${this.expandedTitle ?? this.title}${this.contentFocused ? " · focused" : ""}` : prefix + action.label;
111
114
  const summary = visibleWidth(fullLabel) <= width ? action.repeatedSummary : undefined;
112
115
  if (this.detailsFocused && index === this.selected) {
113
116
  // Keep short output inline; probe at most one viewport before anchoring at Details.
114
117
  const primary = sectionRows(action.sections(), summary), preview = [];
115
- const budget = Math.max(1, Math.min(20, this.height()) - (this.focused ? 2 : 1) - (this.directDetails ? 0 : 1) - 1);
118
+ const budget = Math.max(1, Math.min(20, this.height()) - (this.contentFocused ? 2 : 1) - (this.directDetails ? 0 : 1) - 1);
116
119
  let complete = false;
117
120
  while (preview.length <= budget) { const row = primary.next(); if (row.done) { complete = true; break; } preview.push(row.value); }
118
121
  if (complete) yield* emitRows(preview);
@@ -136,10 +139,14 @@ export class ToolPane {
136
139
  return activityRow(line, outerWidth, this.theme, selected);
137
140
  };
138
141
  const header = this.styleHeader(`${this.open ? "▾" : "▸"} ${this.open ? this.expandedTitle ?? this.title : this.title}${this.focused ? " · focused" : ""}`);
139
- if (!this.open) { this.lastHeight = 1; this.lastBodyHeight = 0; return [paint(truncateToWidth(header, width), this.focused && !this.detailsFocused)]; }
142
+ if (!this.open) { this.lastHeight = 1; this.lastBodyHeight = 0; this.lastMore = false; return [paint(truncateToWidth(header, width), this.focused && !this.detailsFocused)]; }
140
143
  const height = Math.max(5, Math.min(20, this.height()));
141
- const key = `${width}:${this.focused}:${this.expandedTitle ?? this.title}:${this.directDetails}:${this.anchor}:${this.selected}:${[...this.expanded].join("|")}:${[...this.detailsExpanded].join("|")}:${this.detailsFocused}`;
142
- if (key !== this.key) { this.reset(); this.key = key; this.iterator = this.body(width); }
144
+ if (this.focused || this.offset === 0) this.preserveFocusLayout = false;
145
+ // Mouse scrolling releases keyboard focus. Keep the already visited source layout
146
+ // so that release cannot reset its offset or reformat an unbounded prefix.
147
+ const contentFocused = this.preserveFocusLayout ? this.contentFocused : this.focused;
148
+ const key = `${width}:${contentFocused}:${this.expandedTitle ?? this.title}:${this.directDetails}:${this.anchor}:${this.selected}:${[...this.expanded].join("|")}:${[...this.detailsExpanded].join("|")}:${this.detailsFocused}`;
149
+ if (key !== this.key) { this.reset(); this.key = key; this.contentFocused = contentFocused; this.iterator = this.body(width); }
143
150
  let bodyHeight = height - (this.focused ? 2 : 1);
144
151
  // Clamp a seek to one viewport beyond visited content; a key press cannot scan unbounded data.
145
152
  this.offset = Math.min(this.offset, this.rows.length);
@@ -148,14 +155,16 @@ export class ToolPane {
148
155
  if (next.done) this.done = true;
149
156
  else { this.rows.push(truncateToWidth(next.value, width)); this.paintedRows++; }
150
157
  }
158
+ // Keep the footer and body height stable after paging to the end. Otherwise
159
+ // the pointer can leave the pane when the downward control disappears.
160
+ if (!this.focused && (!this.done || this.rows.length > bodyHeight)) bodyHeight--;
151
161
  if (this.done) this.offset = Math.min(this.offset, Math.max(0, this.rows.length - bodyHeight));
152
- let more = !this.done || this.offset + bodyHeight < this.rows.length;
153
- if (!this.focused && more) { bodyHeight--; more = !this.done || this.offset + bodyHeight < this.rows.length; }
162
+ const more = !this.done || this.offset + bodyHeight < this.rows.length;
154
163
  const selectedAction = this.actions[this.selected];
155
164
  const detailsTarget = this.detailsFocused && !!selectedAction?.details;
156
165
  const isExpanded = detailsTarget ? this.detailsExpanded.has(selectedAction.id) : this.directDetails || this.expanded.has(selectedAction?.id);
157
166
  const controls = detailsTarget ? `Enter ${isExpanded ? "collapse" : "expand"} Details · Tab action` : `${this.directDetails ? "Enter collapse" : `←/→ ${this.itemName} · Enter ${isExpanded ? "collapse" : "expand"}`}${selectedAction?.details ? " · Tab Details" : ""}`;
158
- const footer = this.focused ? `${controls} · ↑/↓ scroll · Esc release${more ? " · more ↓" : ""}` : more ? "more ↓" : "";
167
+ const footer = [more ? "more ↓" : this.offset > 0 ? "more ↑" : "", this.focused ? `${controls} · ↑/↓ scroll · Esc release` : ""].filter(Boolean).join(" · ");
159
168
  const body = this.rows.slice(this.offset, this.offset + bodyHeight).map((line, index) => {
160
169
  const action = this.actionRows.get(this.offset + index);
161
170
  const details = this.detailsRows.get(this.offset + index);
@@ -168,7 +177,7 @@ export class ToolPane {
168
177
  return paint(line, selected);
169
178
  });
170
179
  const visible = [paint(truncateToWidth(header, width), this.focused && !this.detailsFocused), ...body, ...(footer ? [paint(truncateToWidth(this.theme ? this.theme.fg("dim", footer) : footer, width))] : [])];
171
- this.lastBodyHeight = body.length;
180
+ this.lastBodyHeight = body.length; this.lastMore = more;
172
181
  this.lastHeight = visible.length;
173
182
  return visible;
174
183
  }
@@ -176,6 +185,7 @@ export class ToolPane {
176
185
  if (event.x < 0 || event.x >= this.lastWidth || event.y < 0 || event.y >= this.lastHeight) return undefined;
177
186
  if (event.type === "wheel") {
178
187
  if (!this.open || !Number.isFinite(event.wheelDelta) || !event.wheelDelta) return undefined;
188
+ this.preserveFocusLayout = true;
179
189
  if (event.wheelDelta < 0 && this.contentAnchoredAbove && this.offset === 0) this.releaseInspection();
180
190
  else this.offset = Math.max(0, this.offset + Math.max(-20, Math.min(20, Math.trunc(event.wheelDelta))));
181
191
  return { handled: true };
@@ -183,7 +193,8 @@ export class ToolPane {
183
193
  if (event.type !== "click" || event.button !== "left") return undefined;
184
194
  // Keep text selection gestures and output clicks from falling through to native whole-row expansion.
185
195
  if (event.shift || event.alt || event.ctrl) return { handled: true, render: false };
186
- if (event.y === 0) { this.detailsFocused = false; this.open = !this.open; return { handled: true }; }
196
+ if (event.y === 0) { this.preserveFocusLayout = false; this.detailsFocused = false; this.open = !this.open; return { handled: true }; }
197
+ if (this.open && (this.lastMore || this.offset > 0) && event.y === this.lastHeight - 1) { this.preserveFocusLayout = true; this.offset = Math.max(0, this.offset + (this.lastMore ? 1 : -1) * Math.max(1, this.lastBodyHeight)); return { handled: true }; }
187
198
  const details = this.detailsRows.get(this.offset + event.y - 1);
188
199
  if (this.open && event.y >= 1 && event.y < 1 + this.lastBodyHeight && details !== undefined) {
189
200
  const id = this.actions[details]?.id;
@@ -1,7 +1,7 @@
1
1
  import type { DisplayMode } from './display-mode.ts';
2
2
  import { AssistantMessageComponent, VERSION, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
3
3
  import { Container, Markdown, MouseRegion, Spacer, Text, matchesKey, truncateToWidth } from '@earendil-works/pi-tui';
4
- import { activityRow, cardContentWidth } from './display-card.ts';
4
+ import { activityRow, cardContentWidth, finalReplyRendering } from './display-card.ts';
5
5
  import { richTextRows } from './modern-rich-text.ts';
6
6
  import { recordedPaneHeight } from './modern-recorded-pane.ts';
7
7
  import { chainNativeMethod } from './native-method-chain.ts';
@@ -45,7 +45,7 @@ export class WorkflowPane {
45
45
  open = false; focused = false; offset = 0; paintedRows = 0;
46
46
  theme?: any;
47
47
  private rows: string[] = []; private iterator?: Iterator<string>; private done = false;
48
- private width = 0; private themeKey = ''; private lastWidth = 0; private lastHeight = 0;
48
+ private width = 0; private themeKey = ''; private lastWidth = 0; private lastHeight = 0; private lastBodyHeight = 0; private lastMore = false;
49
49
  constructor(readonly source: string, readonly summary: string, private release: () => void = () => {}) {}
50
50
  collapse() { this.open = false; this.focused = false; this.offset = 0; this.invalidate(); }
51
51
  invalidate() { this.rows = []; this.iterator = undefined; this.done = false; this.width = 0; }
@@ -66,6 +66,7 @@ export class WorkflowPane {
66
66
  if (this.width !== sourceWidth || themeKey !== this.themeKey) { this.invalidate(); this.width = sourceWidth; this.themeKey = themeKey; this.offset = 0; }
67
67
  const label = `${this.open ? '▾' : '▸'} Subagent workflow`;
68
68
  const rows = [activityRow(theme ? theme.fg('mdLink', theme.bold(label)) + theme.fg('muted', ` · ${this.summary}`) : `${label} · ${this.summary}`, width, theme, this.focused)];
69
+ this.lastBodyHeight = 0; this.lastMore = false;
69
70
  if (this.open) {
70
71
  this.iterator ??= richTextRows(this.source, sourceWidth, { format: 'code', language: 'javascript' });
71
72
  const height = recordedPaneHeight();
@@ -78,7 +79,8 @@ export class WorkflowPane {
78
79
  if (this.done) this.offset = Math.min(this.offset, Math.max(0, this.rows.length - height));
79
80
  rows.push(...this.rows.slice(this.offset, this.offset + height).map(row => activityRow(indent + row, width, theme)));
80
81
  const more = !this.done || this.offset + height < this.rows.length;
81
- const hint = this.focused ? `Enter collapse · ↑/↓ scroll · Home start · Esc release${more ? ' · more ↓' : ''}` : more ? 'more ↓' : '';
82
+ this.lastBodyHeight = rows.length - 1; this.lastMore = more;
83
+ const hint = [more ? 'more ↓' : this.offset > 0 ? 'more ↑' : '', this.focused ? 'Enter collapse · ↑/↓ scroll · Home start · Esc release' : ''].filter(Boolean).join(' · ');
82
84
  if (hint) rows.push(activityRow(theme ? theme.fg('muted', hint) : hint, width, theme));
83
85
  }
84
86
  this.lastHeight = rows.length;
@@ -89,8 +91,9 @@ export class WorkflowPane {
89
91
  if (event.type === 'wheel' && this.open && Number.isFinite(event.wheelDelta) && event.wheelDelta) {
90
92
  this.release(); this.offset = Math.max(0, this.offset + Math.max(-20, Math.min(20, Math.trunc(event.wheelDelta)))); return { handled: true };
91
93
  }
92
- if (event.type === 'click' && event.button === 'left' && event.y === 0 && !event.ctrl && !event.alt && !event.shift) {
93
- this.release(); this.open = !this.open; this.offset = 0; return { handled: true };
94
+ if (event.type === 'click' && event.button === 'left' && !event.ctrl && !event.alt && !event.shift) {
95
+ if (event.y === 0) { this.release(); this.open = !this.open; this.offset = 0; return { handled: true }; }
96
+ if (this.open && (this.lastMore || this.offset > 0) && event.y === this.lastHeight - 1) { this.release(); this.offset = Math.max(0, this.offset + (this.lastMore ? 1 : -1) * Math.max(1, this.lastBodyHeight)); return { handled: true }; }
94
97
  }
95
98
  }
96
99
  }
@@ -113,7 +116,7 @@ export function registerModernWorkflows(pi: ExtensionAPI, mode: DisplayMode, ver
113
116
  const clear = () => { release(); cards.clear(); input?.(); input = undefined; redraw = undefined; active = false; };
114
117
  const supported = (component: any): any[] | undefined => {
115
118
  const message = component.lastMessage, container = component.contentContainer;
116
- if (component.isStreaming !== false || message?.role !== 'assistant' || !Array.isArray(message.content) || !Array.isArray(component.children) || component.children.length !== 1 || component.children[0] !== container || container?.constructor !== Container || !Array.isArray(container.children)) return;
119
+ if (component[finalReplyRendering] || component.isStreaming !== false || message?.role !== 'assistant' || !Array.isArray(message.content) || !Array.isArray(component.children) || component.children.length !== 1 || component.children[0] !== container || container?.constructor !== Container || !Array.isArray(container.children)) return;
117
120
  if (!container.children.every((child: any) => child instanceof Markdown || child instanceof Spacer || child instanceof Text || child instanceof MouseRegion && (child.child instanceof Markdown || child.child instanceof Text))) return;
118
121
  const text = message.content.filter((block: any) => block.type === 'text' && typeof block.text === 'string' && block.text.trim()).map((block: any) => block.text.trim());
119
122
  const markdown = container.children.filter((child: any) => child instanceof Markdown);
@@ -1,5 +1,5 @@
1
1
  import { Box, Markdown, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
2
- import { activityRow, cardContentWidth, fillBackground } from './display-card.ts';
2
+ import { activityRow, cardContentWidth, fillBackground, finalReplyRendering } from './display-card.ts';
3
3
 
4
4
  /** Shared with inspection. Canonical native children stay untouched. */
5
5
  export const projectedChildren = Symbol.for('compact-renderer:projected-children:v1');
@@ -13,17 +13,25 @@ export function renderFinalReply(row: any, width: number, theme: any): string[]
13
13
  const first = children?.findIndex((child: any) => child instanceof Markdown) ?? -1;
14
14
  if (first < 0) return row.render(width);
15
15
  const last = children.findLastIndex((child: any) => child instanceof Markdown);
16
- const padding = { invalidate() {}, render: (contentWidth: number) => [fillBackground('', contentWidth, theme, 'toolPendingBg')] };
17
16
  for (const child of children) {
18
17
  if (!(child instanceof Markdown)) continue;
19
18
  const native = child.render, own = Object.getOwnPropertyDescriptor(child, 'render');
20
19
  child.render = function(contentWidth: number) {
21
- return native.call(this, contentWidth).map((line: string) => line.includes('\x1b_G') || line.includes('\x1b]1337;File=') ? line : fillBackground(line, Math.max(contentWidth, visibleWidth(line)), theme, 'toolPendingBg'));
20
+ const lines = native.call(this, contentWidth).map((line: string) => line.includes('\x1b_G') || line.includes('\x1b]1337;File=') ? line : fillBackground(line, Math.max(contentWidth, visibleWidth(line)), theme, 'toolPendingBg'));
21
+ if (child === children[first]) lines.unshift(fillBackground('', contentWidth, theme, 'toolPendingBg'));
22
+ if (child === children[last]) lines.push(fillBackground('', contentWidth, theme, 'toolPendingBg'));
23
+ return lines;
22
24
  };
23
25
  restore.push(() => { if (own) Object.defineProperty(child, 'render', own); else delete (child as any).render; });
24
26
  }
25
- container.children = [...children.slice(0, first), padding, ...children.slice(first, last + 1), padding, ...children.slice(last + 1)];
26
- try { return row.render(width); } finally { container.children = children; restore.forEach(fn => fn()); }
27
+ // Add rows through Markdown rendering, preserving the native child shape
28
+ // used by the thinking adapter throughout this render.
29
+ const marker = Object.getOwnPropertyDescriptor(row, finalReplyRendering);
30
+ row[finalReplyRendering] = true;
31
+ try { return row.render(width); } finally {
32
+ if (marker) Object.defineProperty(row, finalReplyRendering, marker); else delete row[finalReplyRendering];
33
+ restore.forEach(fn => fn());
34
+ }
27
35
  }
28
36
  /** Native Box owns both rendering and mouse-coordinate translation. */
29
37
  export class WorkChild extends Box {
@@ -4,6 +4,7 @@ import { loadSource, loadAgent, themeModule, stripAnsi, tui, backgroundCells } f
4
4
  const { registerModernTools, toolStatus } = await loadSource('./modern-tools.ts');
5
5
  const { createDisplayMode } = await loadSource('./display-mode.ts');
6
6
  const { CodePane } = await loadSource('./modern-code-pane.ts');
7
+ const { WorkChild } = await loadSource('./work-strip-view.ts');
7
8
  const stylePane = new CodePane(() => 12);
8
9
  stylePane.heading = 'codemode · Read files';
9
10
  stylePane.title = `${stylePane.heading} · 2 nested calls · 1 nested error`;
@@ -120,8 +121,30 @@ try {
120
121
  for (const row of rows) assert.ok(tui.visibleWidth(row) <= width);
121
122
  }
122
123
  assert.match(paint(code), /text\(0\)/);
124
+ // Exercise native container routing, including the work group's horizontal inset.
125
+ const workChild = new WorkChild(code), work = new tui.Container();
126
+ work.addChild(new tui.Text('Work fixture', 0, 0)); work.addChild(workChild);
127
+ const moreRows = work.render(140).map(stripAnsi), moreY = moreRows.findIndex(row => row.includes('more ↓'));
128
+ assert.ok(moreY > 1); const moreX = moreRows[moreY].indexOf('more ↓'); assert.ok(moreX >= 3);
129
+ const beforeMore = pane.offset;
130
+ assert.equal(work.handleMouse({ type: 'click', button: 'left', x: moreX, y: moreY, screenX: moreX, screenY: moreY, width: 140, height: moreRows.length })?.handled, true);
131
+ const afterMore = work.render(140).map(stripAnsi).join('\n');
132
+ assert.ok(pane.offset > beforeMore, 'clicking overflow advances the rendered codemode viewport');
133
+ assert.ok(pane.offset - beforeMore <= 20, 'one click advances at most one bounded viewport');
134
+ assert.doesNotMatch(afterMore, /text\(0\)/); assert.equal(input('\r'), undefined, 'overflow click leaves Enter with the editor');
135
+ const focusedMore = []; pi.events.emit('compact-renderer:inspect:v1', { add: entry => focusedMore.push(entry) });
136
+ focusedMore.find(entry => entry.label.startsWith('codemode')).focus();
137
+ const rows = code.render(140).map(stripAnsi), footerY = rows.findIndex(row => row.includes('more ↓'));
138
+ assert.ok(footerY > 0); mouse(code, 'click', footerY);
139
+ assert.doesNotMatch(paint(code), /focused/); assert.equal(input('\r'), undefined, 'overflow click releases inspection');
123
140
  for (let index = 0; index < 120; index++) { mouse(code, 'wheel', 2, 20); code.render(140); }
124
141
  assert.match(paint(code), /Recorded script output/, 'bounded viewport can reach full native output');
142
+ assert.doesNotMatch(paint(code), /more ↓/, 'codemode stops offering downward paging at its final rows');
143
+ const endRows = code.render(140).map(stripAnsi), endOffset = pane.offset;
144
+ assert.match(endRows.at(-1), /more ↑/, 'the final footer retains its hit area');
145
+ mouse(code, 'click', endRows.length - 1); code.render(140);
146
+ assert.ok(pane.offset < endOffset, 'the upward footer pages back through the output');
147
+ assert.equal(code.render(140).length, endRows.length, 'paging back keeps the pane height');
125
148
  assert.equal(JSON.stringify(final), before);
126
149
  const running = create('codemode', 'code-clear', { code: 'text(1);' }, codemodeRenderers); running.markExecutionStarted(); running.updateResult({ ...result(''), details: { calls: [] } }, true);
127
150
  assert.equal(intervals.size, 1); event('session_before_switch'); assert.equal(intervals.size, 0, 'session switch clears native owned timer');
@@ -0,0 +1,73 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createWorkStripPreview } from '../scripts/preview-work-strip.mjs';
3
+
4
+ const preview = await createWorkStripPreview({ inspection: true });
5
+ const terminal = { columns: 110, rows: 45, kittyProtocolActive: false, start() {}, stop() {}, async drainInput() {} };
6
+ for (const name of ['write', 'moveBy', 'hideCursor', 'showCursor', 'clearLine', 'clearFromCursor', 'clearScreen', 'setTitle', 'setProgress', 'setProgramStatus']) terminal[name] = () => {};
7
+ const plain = rows => rows.join('\n').replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g, '');
8
+ let ui;
9
+ try {
10
+ ui = new preview.core.InteractiveMode(preview.runtime, { tuiMode: 'fullscreen', terminal });
11
+ await ui.init();
12
+ const runner = preview.runtime.session.extensionRunner;
13
+ await runner.getCommand('fold').handler('expand', runner.createContext());
14
+ const renderer = ui.renderer;
15
+ renderer.renderNow();
16
+ const screen = () => renderer.getScreenLines().map(row => plain([row]));
17
+ const click = (component, pattern) => {
18
+ const rows = component.render(110), y = rows.findIndex(row => pattern.test(plain([row])));
19
+ assert.ok(y >= 0, String(pattern));
20
+ assert.equal(component.handleMouse({ type: 'click', button: 'left', x: 8, y, width: 110, height: rows.length })?.handled, true);
21
+ renderer.renderNow();
22
+ };
23
+ const wheel = (y, down) => {
24
+ renderer.handleTerminalInput(`\x1b[<${down ? 65 : 64};15;${y + 1}M`);
25
+ renderer.renderNow();
26
+ };
27
+ const choices = [];
28
+ preview.eventBus.emit('compact-renderer:inspect:v1', { add: choice => choices.push(choice) });
29
+ const thinking = choices.find(choice => /Thinking · 3 rounds/.test(choice.label));
30
+ assert.ok(thinking);
31
+ thinking.focus(); renderer.renderNow();
32
+ const component = thinking.target();
33
+ click(component, /1\. Review recorded sample/);
34
+ const beforeThinking = plain(component.render(110));
35
+ click(component, /more ↓/);
36
+ assert.notEqual(plain(component.render(110)), beforeThinking);
37
+ assert.doesNotMatch(plain(component.render(110)), /Thinking\.\.\./);
38
+
39
+ const code = ui.chatContainer.children.find(row => row.toolName === 'codemode' && row.args?.code?.includes('/fixture/recorded.txt'));
40
+ const wrapper = ui.chatContainer[Symbol.for('compact-renderer:projected-children:v1')].find(row => row.children?.[0] === code);
41
+ assert.ok(wrapper);
42
+ click(wrapper, /▸ codemode/);
43
+ click(wrapper, /more ↓/);
44
+ preview.eventBus.emit('compact-renderer:focus:v1', { owner: 'tools', target: row => row === code });
45
+ renderer.renderNow();
46
+ const scroll = renderer.getPrimaryScrollView();
47
+ // At the transcript end, auto-clamping can mask a shrinking pane by moving
48
+ // it down under the pointer. Test away from that boundary.
49
+ scroll.scrollTo(scroll.scrollTop - 3, { disableFollow: true }); renderer.renderNow();
50
+ const top = scroll.scrollTop;
51
+ let footerY = -1;
52
+ for (let n = 0; n < 200; n++) {
53
+ const rows = screen(), headerY = rows.findIndex(row => /▾ codemode/.test(row));
54
+ assert.ok(headerY >= 0);
55
+ const nextY = rows.findIndex((row, i) => i > headerY && i < headerY + 21 && /more ↓/.test(row));
56
+ if (nextY < 0) break;
57
+ if (footerY >= 0) assert.equal(nextY, footerY, 'footer remains under the pointer');
58
+ footerY = nextY;
59
+ wheel(footerY, true);
60
+ assert.equal(scroll.scrollTop, top, 'downward wheel stays inside the pane');
61
+ }
62
+ const end = screen();
63
+ assert.ok(footerY >= 0);
64
+ assert.match(end[footerY], /more ↑/, 'end of pane retains its footer hit area');
65
+ wheel(footerY, false);
66
+ assert.equal(scroll.scrollTop, top, 'upward wheel at the unchanged footer stays inside the pane');
67
+ assert.notEqual(screen().join('\n'), end.join('\n'), 'upward wheel reveals earlier output');
68
+ assert.equal(renderer.getFocusedComponent(), ui.defaultEditor);
69
+ console.log('Native overflow footer retains wheel routing in both directions');
70
+ } finally {
71
+ ui?.stop();
72
+ await preview.cleanup();
73
+ }
@@ -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');
@@ -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
+ }