pi-stereo-view 0.1.11 → 0.1.13

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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.1.13 - 2026-11-06
6
+
7
+ ### Changed
8
+
9
+ - Show native inline extension dialogs below Activity history alongside widgets. Keep message editors full width, explicit overlays unchanged and native placement available when the surface does not fit.
10
+ - Preserve an inline dialog's keyboard focus when pressing the panel search shortcut.
11
+
12
+ ## 0.1.12 - 2026-11-04
13
+
14
+ ### Changed
15
+
16
+ - Keep extension widgets at the bottom of Activity while its history scrolls independently. Widgets return to Pi's normal placement when they cannot fit safely.
17
+ - Restore the nested Codemode call tree with independent controls and original native result panels, including shared results and saved sessions.
18
+
19
+ ### Fixed
20
+
21
+ - Keep committed editor batch results visible under their originating nested calls.
22
+
3
23
  ## 0.1.11 - 2026-10-29
4
24
 
5
25
  ### Added
package/README.md CHANGED
@@ -27,9 +27,11 @@ Unrecognized content stays in Conversation unless its metadata links it to a kno
27
27
 
28
28
  Late output linked to a tool call appears directly below that call in Activity, even if other work has happened since. Combined history keeps its original order.
29
29
 
30
- Calls made inside Codemode and other tools appear beneath their parent in Activity. While running, their arguments, status and available results are shown; compact mode gives each nested call its own expandable row. After reopening a session, Pi restores recorded call metadata and any saved error excerpt. Pi Agent IDE may also restore its saved native result panels; full results are not always available. Activity marks incomplete records and omitted arguments. Older sessions without nested records remain unchanged.
30
+ Expand a parent tool such as Codemode to browse its nested call tree. Adjacent calls of the same tool form a group with individual call headers. Each independent native result opens under its call. A combined result covering several calls stays whole inside their group. Panels without child execution identities remain available inside the parent's output disclosure. Session restoration uses Pi's saved nested-call metadata and the original saved panels.
31
31
 
32
- Messages and tools keep their familiar appearance. The input stays full width below both panels.
32
+ Messages and tools keep their familiar appearance. Extension widgets and inline dialogs appear at the bottom of Activity, below its independently scrolling history. Standard select, confirm, input and editor dialogs and non-overlay custom components keep Pi's native input, focus and completion behavior. The message editor, including extension-provided replacements, stays full width whenever Pi displays it. Explicit overlays keep their native placement.
33
+
34
+ If the Activity surface cannot fit without clipping, the view temporarily returns to combined history and Pi's normal placement. Combined history, zoomed Conversation and unsupported native layouts also leave dialogs and widgets in Pi's dock. Open forms stay live as layouts change and disappear when their producer closes them; they are not added to history.
33
35
 
34
36
  ## Features
35
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-stereo-view",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "type": "module",
5
5
  "description": "Keep Pi conversation separate from tool output and agent activity.",
6
6
  "license": "MIT",
@@ -23,6 +23,7 @@ export function toolDescription(args: unknown): string {
23
23
  }
24
24
 
25
25
  interface CompactToolOptions {
26
+ alignControl?: boolean;
26
27
  clock?(): string;
27
28
  gutter?(): number;
28
29
  count?(): number;
@@ -42,7 +43,7 @@ export class CompactTool implements Component {
42
43
  const dot = theme.fg(status === "running" ? "warning" : status === "unknown" ? "dim" : status, "●");
43
44
  const count = this.options.count?.();
44
45
  const description = count ? "" : toolDescription(args);
45
- const control = this.options.toggle ? theme.fg("muted", this.options.expanded?.() ? "▾" : "▸") + " " : "";
46
+ const control = this.options.toggle ? theme.fg("muted", this.options.expanded?.() ? "▾" : "▸") + " " : this.options.alignControl ? " " : "";
46
47
  const text = `${dot} ${control}${singleLine(name)}${count ? ` ×${count}` : ""}${description ? " " + theme.fg("muted", description) : ""}`;
47
48
  const label = this.options.clock?.() ?? "";
48
49
  const clock = label && width >= visibleWidth(label) + 8 ? label : "";
package/src/content.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Container, Markdown, Text, stripTerminalSequences, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
1
+ import { Container, Markdown, Text, stripTerminalSequences, type Component } from "@earendil-works/pi-tui";
2
2
  import { searchText, type SearchEntry } from "./search.js";
3
- import type { NestedActivity } from "./nested-activity.js";
3
+ import { NestedCalls } from "./nested-calls.js";
4
4
 
5
5
  export type Pane = "activity" | "chat";
6
6
  export type ContentKind = "dialogue" | "system" | "thinking" | "tool" | "shell";
@@ -12,7 +12,7 @@ const panes: Record<ContentKind, Pane> = {
12
12
  interface NativeContent extends Component {
13
13
  text?: string;
14
14
  message?: { content?: unknown; summary?: string; details?: { parentToolCallId?: unknown } };
15
- entry?: { customType?: string; data?: { parentToolCallId?: unknown; calls?: { id?: unknown }[] } };
15
+ entry?: { data?: { parentToolCallId?: unknown } };
16
16
  toolCallId?: string;
17
17
  toolName?: string;
18
18
  args?: unknown;
@@ -45,7 +45,6 @@ export interface ContentEntry {
45
45
  kind: ContentKind;
46
46
  spacing: Component[];
47
47
  compact: boolean;
48
- nested?: boolean;
49
48
  search(width: number): Omit<SearchEntry, "source">;
50
49
  /** Live execution metadata exists only on calls, never on linked output. */
51
50
  tool?(): ToolSummary;
@@ -89,33 +88,49 @@ const nativeKinds: Record<string, { kind: ContentKind; accepts(content: NativeCo
89
88
  },
90
89
  };
91
90
 
92
- /** Show the IDE-owned native child when its saved panel contains this call. */
93
- class SavedNativePanel implements Component {
94
- constructor(private readonly fallback: Component, private readonly group: NativeContent, private readonly id: string) {}
95
- private native(): Component | undefined {
96
- this.group.setExpanded?.(true);
97
- const find = (component: Component | undefined): Component | undefined => {
98
- if (!component) return undefined;
99
- const node = component as NativeContent & { children?: Component[] };
100
- if (nameOf(component) === "ToolExecutionComponent" && node.toolCallId === this.id) return component;
101
- for (const child of node.children ?? []) { const found = find(child); if (found) return found; }
102
- return undefined;
103
- };
104
- return find(this.group.customComponent);
105
- }
106
- render(width: number): string[] { return (this.native() ?? this.fallback).render(width); }
107
- invalidate(): void { this.fallback.invalidate(); this.group.invalidate(); }
108
- handleMouse(event: TuiMouseEvent): ReturnType<NonNullable<Component["handleMouse"]>> { return (this.native() ?? this.fallback).handleMouse?.(event); }
91
+ /** Traverse the same component links as the native render cache, including wrappers. */
92
+ export function componentTree(root: Component | undefined): NativeContent[] {
93
+ const seen = new Set<Component>();
94
+ const nodes: NativeContent[] = [];
95
+ const visit = (component: Component | undefined): void => {
96
+ if (!component || seen.has(component) || typeof component.render !== "function") return;
97
+ seen.add(component);
98
+ const node = component as NativeContent & { children?: Component[]; child?: Component; component?: Component };
99
+ nodes.push(node);
100
+ if (Array.isArray(node.children)) for (const child of node.children) visit(child);
101
+ visit(node.child); visit(node.component); visit(node.customComponent);
102
+ };
103
+ visit(root);
104
+ return nodes;
105
+ }
106
+
107
+ /** Preserve searchable tool-result text even when a custom renderer abbreviates it. */
108
+ function nestedResultText(component: Component | undefined): string[] {
109
+ return componentTree(component).flatMap(node => nameOf(node) === "ToolExecutionComponent" ? [contentText(node.result?.content)] : []).filter(Boolean);
109
110
  }
110
111
 
112
+ /** Unwrap layout-only containers while retaining each original renderer and shared note. */
113
+ function nativePanelParts(source: NativeContent): Component[] | undefined {
114
+ if (!source.customComponent) return undefined;
115
+ const parts: Component[] = [];
116
+ const seen = new Set<Component>();
117
+ const visit = (component: Component): void => {
118
+ if (seen.has(component)) return;
119
+ seen.add(component);
120
+ if (component.constructor === Container) for (const child of (component as Container).children) visit(child);
121
+ else if (nameOf(component) !== "Spacer") parts.push(component);
122
+ };
123
+ visit(source.customComponent);
124
+ return parts.filter(part => nameOf(part) === "ToolExecutionComponent").length > 1 ? parts : undefined;
125
+ }
111
126
  /** Shared semantic index for painting and search, independent of wording, severity and lifecycle. */
112
127
  export class NativeContentIndex {
113
128
  private signature: unknown[] = [];
114
129
  private content: ContentEntry[] = [];
130
+ private readonly expandedPanels = new WeakMap<Component, Component>();
115
131
  private readonly views = new WeakMap<NativeAssistant, Partial<Record<Pane, Container>>>();
116
- private readonly savedPanels = new WeakMap<Component, { group: NativeContent; panel: Component }>();
117
132
 
118
- constructor(private readonly source: Container, private readonly nested?: NestedActivity) {}
133
+ constructor(private readonly source: Container, readonly nested = new NestedCalls()) {}
119
134
 
120
135
  /** Return the same classification until native ownership or assistant content changes. */
121
136
  entries(pane?: Pane): ContentEntry[] {
@@ -143,21 +158,21 @@ export class NativeContentIndex {
143
158
  private refresh(): void {
144
159
  const history = this.source.children[2] as Container;
145
160
  if (!Array.isArray(history?.children)) throw new Error("Pi's history document is not supported");
146
- const signature: unknown[] = [this.nested?.revision, ...this.source.children, ...history.children];
147
- for (const component of history.children) {
148
- const metadata = component as NativeContent;
149
- signature.push(metadata.toolCallId, metadata.entry?.data?.parentToolCallId, metadata.message?.details?.parentToolCallId);
150
- const native = assistant(component);
151
- if (native) signature.push(native.lastMessage, ...native.contentContainer.children);
152
- }
161
+ const makeSignature = (): unknown[] => {
162
+ const values: unknown[] = [this.nested.revision, ...this.source.children, ...history.children];
163
+ for (const component of history.children) {
164
+ const metadata = component as NativeContent;
165
+ values.push(metadata.toolCallId, metadata.entry?.data?.parentToolCallId, metadata.message?.details?.parentToolCallId, metadata.customComponent);
166
+ if (metadata.entry?.data?.parentToolCallId || metadata.message?.details?.parentToolCallId)
167
+ values.push(...(nativePanelParts(metadata) ?? []));
168
+ const native = assistant(component);
169
+ if (native) values.push(native.lastMessage, ...native.contentContainer.children);
170
+ }
171
+ return values;
172
+ };
173
+ const signature = makeSignature();
153
174
  if (signature.length === this.signature.length && signature.every((value, index) => value === this.signature[index])) return;
154
175
  const owners = new Map<string, NativeContent>();
155
- const panels = new Map<string, NativeContent>();
156
- for (const component of history.children) {
157
- const entry = (component as NativeContent).entry;
158
- if (entry?.customType !== "ide-nested-results" || !Array.isArray(entry.data?.calls)) continue;
159
- for (const call of entry.data.calls) if (typeof call.id === "string") panels.set(call.id, component as NativeContent);
160
- }
161
176
  for (const component of history.children) {
162
177
  const adapter = nativeKinds[nameOf(component)];
163
178
  const native = component as NativeContent;
@@ -180,28 +195,16 @@ export class NativeContentIndex {
180
195
  const kind = adapter?.accepts(native) ? adapter.kind : "system";
181
196
  const parentId = native.entry?.data?.parentToolCallId ?? native.message?.details?.parentToolCallId;
182
197
  const owner = kind === "system" && typeof parentId === "string" ? owners.get(parentId) : undefined;
183
- entries.push(this.entry(component, kind, spacing, true, owner));
184
- if (kind === "tool" && typeof native.toolCallId === "string") {
185
- for (const child of this.nested?.entries(native.toolCallId) ?? []) {
186
- const entry = this.entry(child, "system", [], true, native);
187
- entry.nested = true;
188
- if (this.nested?.summary(child)) {
189
- const id = this.nested.id(child);
190
- const group = id && this.nested.isSaved(child) ? panels.get(id) : undefined;
191
- if (group && id && group.entry?.data?.parentToolCallId === native.toolCallId) {
192
- let cached = this.savedPanels.get(child);
193
- if (!cached || cached.group !== group) {
194
- cached = { group, panel: new SavedNativePanel(child, group, id) };
195
- this.savedPanels.set(child, cached);
196
- }
197
- entry.component = cached.panel;
198
- }
199
- entry.tool = () => this.nested!.summary(child)!;
200
- entry.search = () => ({ label: this.nested!.summary(child)!.name, text: this.nested!.search(child) });
201
- }
202
- entries.push(entry);
203
- }
204
- }
198
+ if (owner && this.expandedPanels.get(component) !== owner) {
199
+ native.setExpanded?.(true);
200
+ this.expandedPanels.set(component, owner);
201
+ } else if (!owner) this.expandedPanels.delete(component);
202
+ const parts = owner && this.nested.entries(owner.toolCallId!).length ? nativePanelParts(native) : undefined;
203
+ if (parts) for (const part of parts) {
204
+ const adapter = nativeKinds[nameOf(part)];
205
+ const partKind = adapter?.accepts(part as NativeContent) ? adapter.kind : "system";
206
+ entries.push(this.entry(part, partKind, [], true, owner));
207
+ } else entries.push(this.entry(component, kind, spacing, true, owner));
205
208
  }
206
209
  spacing = [];
207
210
  }
@@ -215,7 +218,7 @@ export class NativeContentIndex {
215
218
  }
216
219
  this.content = entries.flatMap(entry => entry.owner === entry.source
217
220
  ? [entry, ...(linked.get(entry.source) ?? [])] : []);
218
- this.signature = signature;
221
+ this.signature = makeSignature();
219
222
  }
220
223
 
221
224
  private entry(source: Component, kind: ContentKind, spacing: Component[], compact: boolean, owner?: NativeContent): ContentEntry {
@@ -232,7 +235,7 @@ export class NativeContentIndex {
232
235
  if (typeof native.toolName !== "string") throw new Error("Pi's tool metadata is not supported");
233
236
  return {
234
237
  label: native.toolName,
235
- text: [native.toolName, JSON.stringify(native.args, null, 2), contentText(native.result?.content)].filter(Boolean).join("\n"),
238
+ text: [native.toolName, JSON.stringify(native.args, null, 2), contentText(native.result?.content), this.nested.search(native.toolCallId ?? "")].filter(Boolean).join("\n"),
236
239
  reveal: () => {
237
240
  if (typeof native.setExpanded !== "function") throw new Error("Pi's tool reveal is not supported");
238
241
  native.setExpanded(true);
@@ -247,10 +250,15 @@ export class NativeContentIndex {
247
250
  if (typeof native.text !== "string") throw new Error("Pi's user text metadata is not supported");
248
251
  return { label: "User", text: native.text };
249
252
  }
253
+ const saved = contentText(native.message?.content) || native.message?.summary || "";
254
+ const rendered = componentText(native.customComponent ?? source) ||
255
+ searchText(source.render(width).join("\n")).split("\n").map(line => line.trimEnd()).join("\n").replace(/^\n+|\n+$/g, "");
256
+ const text = [saved || rendered];
257
+ if (native.customComponent && rendered && !text.some(part => part.includes(rendered))) text.push(rendered);
258
+ for (const result of nestedResultText(native.customComponent)) if (!text.some(part => part.includes(result))) text.push(result);
250
259
  return {
251
260
  label: owner?.toolName ?? (native.message?.summary !== undefined ? "Summary" : "System"),
252
- text: contentText(native.message?.content) || native.message?.summary || componentText(native.customComponent ?? source) ||
253
- searchText(source.render(width).join("\n")).split("\n").map(line => line.trimEnd()).join("\n").replace(/^\n+|\n+$/g, ""),
261
+ text: text.filter(Boolean).join("\n"),
254
262
  reveal: typeof native.setExpanded === "function" ? () => native.setExpanded!(true) : undefined,
255
263
  };
256
264
  } };
package/src/index.ts CHANGED
@@ -2,19 +2,19 @@ import path from "node:path";
2
2
  import { copyToClipboard, getAgentDir, getSettingsListTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { Box, Container, isKeyRelease, matchesKey, SettingsList, Text, type TUI } from "@earendil-works/pi-tui";
4
4
  import { TranscriptLayout } from "./layout.js";
5
- import { NestedActivity } from "./nested-activity.js";
6
5
  import { TOOL_START_ENTRY, TranscriptTimestamps } from "./timestamps.js";
7
6
  import { defaults, loadPreferences, savePreferences, type Preferences } from "./preferences.js";
8
- import { beforeFirstFrame, captureToolRenderers } from "./startup.js";
7
+ import { beforeFirstFrame } from "./startup.js";
8
+ import { observeNativeEditor } from "./native-editor.js";
9
+ import { NestedCalls } from "./nested-calls.js";
9
10
 
10
11
  /** Split native fullscreen history without changing message content or the input dock. */
11
12
  export default async function transcript(pi: ExtensionAPI): Promise<void> {
12
13
  let layout: TranscriptLayout | undefined;
13
14
  let host: TUI | undefined;
14
15
  let timestamps: TranscriptTimestamps | undefined;
15
- let nested: NestedActivity | undefined;
16
- const renderers = captureToolRenderers();
17
- renderers.install();
16
+ const nested = new NestedCalls();
17
+ const nativeEditor = observeNativeEditor();
18
18
  let unsubscribeInput: (() => void) | undefined;
19
19
  let writes = Promise.resolve();
20
20
  let preferences: Preferences = { ...defaults };
@@ -98,7 +98,6 @@ export default async function transcript(pi: ExtensionAPI): Promise<void> {
98
98
  const createLayout = (tui: TUI, ui: ExtensionContext["ui"], session: ExtensionContext["sessionManager"]): void => {
99
99
  host = tui;
100
100
  timestamps = new TranscriptTimestamps(session);
101
- nested = new NestedActivity(tui, session.getCwd(), renderers.resolve);
102
101
  nested.restore(session.getBranch());
103
102
  layout = new TranscriptLayout(preferences, () => ui.theme,
104
103
  message => ui.notify(message, "warning"), () => persist(ui), timestamps,
@@ -113,7 +112,7 @@ export default async function transcript(pi: ExtensionAPI): Promise<void> {
113
112
  }
114
113
  void copyToClipboard(text).then(() => ui.notify("Block sent to clipboard.", "info"),
115
114
  error => ui.notify("Could not copy block: " + String(error), "error"));
116
- }, () => pi.getAllTools(), nested);
115
+ }, () => pi.getAllTools(), nested, () => nativeEditor.get(tui));
117
116
  try { ensureLayout(); }
118
117
  catch (error) {
119
118
  layout.dispose();
@@ -132,7 +131,6 @@ export default async function transcript(pi: ExtensionAPI): Promise<void> {
132
131
  });
133
132
 
134
133
  pi.on("session_start", async (event, ctx) => {
135
- renderers.install();
136
134
  releaseStartup();
137
135
  if (ctx.mode !== "tui") return;
138
136
  const early = event.reason === "startup" && earlySession === ctx.sessionManager.getSessionId() && layout !== undefined;
@@ -170,7 +168,6 @@ export default async function transcript(pi: ExtensionAPI): Promise<void> {
170
168
  });
171
169
  pi.on("message_start", event => {
172
170
  timestamps?.observe(event.message);
173
- if (event.message.role === "toolResult") nested?.absorb(event.message);
174
171
  layout?.refreshSearch();
175
172
  });
176
173
  pi.on("message_update", event => {
@@ -179,38 +176,40 @@ export default async function transcript(pi: ExtensionAPI): Promise<void> {
179
176
  ensureLayout();
180
177
  });
181
178
  pi.on("message_end", event => {
179
+ nested.absorb(event.message);
182
180
  timestamps?.observe(event.message, true);
183
181
  layout?.refreshSearch();
184
182
  });
185
- pi.on("tool_execution_update", event => {
186
- if (event.parentToolCallId) { nested?.update(event); host?.requestRender(); }
183
+ pi.on("tool_execution_update", () => {
187
184
  layout?.refreshSearch();
188
185
  });
189
186
  pi.on("tool_execution_end", event => {
190
- if (event.parentToolCallId) { nested?.end({ ...event, parentToolCallId: event.parentToolCallId }); host?.requestRender(); }
187
+ nested.end(event);
191
188
  layout?.refreshSearch();
189
+ host?.requestRender();
192
190
  });
193
191
  pi.on("tool_execution_start", event => {
194
192
  if (event.parentToolCallId) {
195
- nested?.start({ ...event, parentToolCallId: event.parentToolCallId });
196
- layout?.refreshSearch(); host?.requestRender(); return;
193
+ nested.start(event);
194
+ layout?.refreshSearch();
195
+ host?.requestRender();
196
+ return;
197
197
  }
198
198
  if (!timestamps) return;
199
199
  pi.appendEntry(TOOL_START_ENTRY, { toolCallId: event.toolCallId, time: Date.now() });
200
200
  host?.requestRender();
201
201
  });
202
- pi.on("session_tree", (_event, ctx) => { closeSearch(); timestamps?.reset(); nested?.restore(ctx.sessionManager.getBranch()); host?.requestRender(); });
203
- pi.on("session_compact", (_event, ctx) => { closeSearch(); timestamps?.reset(); nested?.restore(ctx.sessionManager.getBranch()); host?.requestRender(); });
202
+ pi.on("session_tree", (_event, ctx) => { closeSearch(); nested.restore(ctx.sessionManager.getBranch()); timestamps?.reset(); host?.requestRender(); });
203
+ pi.on("session_compact", (_event, ctx) => { closeSearch(); nested.restore(ctx.sessionManager.getBranch()); timestamps?.reset(); host?.requestRender(); });
204
204
  pi.on("session_shutdown", async () => {
205
- renderers.dispose();
206
205
  releaseStartup();
206
+ nativeEditor.dispose();
207
207
  closeSearch();
208
208
  unsubscribeInput?.();
209
209
  unsubscribeInput = undefined;
210
210
  layout?.dispose();
211
211
  layout = undefined;
212
212
  timestamps = undefined;
213
- nested = undefined;
214
213
  host = undefined;
215
214
  await writes;
216
215
  });
package/src/layout.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  } from "@earendil-works/pi-tui";
7
7
  import { NativeDocument, type Pane } from "./native.js";
8
8
  import { NativeContentIndex } from "./content.js";
9
- import type { NestedActivity } from "./nested-activity.js";
9
+ import { NestedCalls } from "./nested-calls.js";
10
10
  import type { Preferences } from "./preferences.js";
11
11
  import type { TranscriptTimestamps } from "./timestamps.js";
12
12
  import { PANEL_SEARCH_ROWS, PanelSearch, PanelSearchShortcut, type SearchHit } from "./search.js";
@@ -35,6 +35,15 @@ class PanelScrollView extends ScrollView {
35
35
  return undefined;
36
36
  }
37
37
  }
38
+ class NativeSurfaceScrollView extends ScrollView {
39
+ override handleMouse(event: TuiMouseEvent): ReturnType<Container["handleMouse"]> {
40
+ if (event.type !== "wheel" || !event.wheelDelta) return undefined;
41
+ this.scrollBy(event.wheelDelta);
42
+ return { handled: true, target: { component: this, originX: event.screenX - event.x,
43
+ originY: event.screenY - event.y, width: event.width, height: event.height } };
44
+ }
45
+ }
46
+
38
47
  class TranscriptColumns extends HStack {
39
48
  /** Reserve a fixed width for Conversation, independent of its content. */
40
49
  sizeConversation(component: Component, width: number): void {
@@ -75,10 +84,13 @@ class TranscriptRoot extends VStack {
75
84
  }
76
85
 
77
86
  class TranscriptPane extends VStack {
78
- constructor(private readonly header: Component, private readonly view: ScrollView, private readonly height: () => number) {
87
+ constructor(private readonly header: Component, private readonly view: ScrollView, private readonly height: () => number,
88
+ private readonly widgets?: ScrollView, private readonly widgetsVisible: () => boolean = () => false) {
79
89
  super([
80
90
  { component: header, basis: "auto", shrink: 0 },
81
91
  { component: view, basis: 0, grow: 1, minSize: 1 },
92
+ ...(widgets ? [{ component: widgets, basis: "auto" as const, minSize: 0,
93
+ visible: () => widgetsVisible() }] : []),
82
94
  ]);
83
95
  }
84
96
 
@@ -98,12 +110,13 @@ class TranscriptPane extends VStack {
98
110
  // Empty preview rows avoid composing colored history text in ancestor measurements.
99
111
  const headerRows = this.header.render(width).length;
100
112
  const contentRows = this.view.children[0].render(this.view.getContentWidth(width)).length;
113
+ const widgetRows = this.widgets && this.widgetsVisible() ? this.widgets.render(width).length : 0;
101
114
  const available = Math.max(1, this.height() - headerRows);
102
- return Array<string>(headerRows + Math.min(contentRows, available)).fill("");
115
+ return Array<string>(headerRows + Math.min((widgetRows ? Math.max(1, contentRows) : contentRows) + widgetRows, available)).fill("");
103
116
  }
104
117
  }
105
118
 
106
- /** Own only guarded fullscreen history controls; never replace the input dock. */
119
+ /** Project native fullscreen history and transient surfaces without taking ownership of their lifecycle. */
107
120
  export class TranscriptLayout {
108
121
  private host?: NativeTui;
109
122
  private original?: Container;
@@ -137,7 +150,8 @@ export class TranscriptLayout {
137
150
  private readonly openSettings: () => void,
138
151
  private readonly copy?: (text: string | undefined) => void,
139
152
  private readonly getTools: () => readonly ToolInfo[] = () => [],
140
- private readonly nested?: NestedActivity,
153
+ private readonly nested = new NestedCalls(),
154
+ private readonly getEditor: () => Component | undefined = () => undefined,
141
155
  ) {}
142
156
 
143
157
  private button(icon: () => string, action: () => void, enabled = (): boolean => true, background?: () => Color): Component {
@@ -197,6 +211,34 @@ export class TranscriptLayout {
197
211
  this.warn("pi-stereo-view split is unavailable: Pi's history document is not supported.");
198
212
  return;
199
213
  }
214
+ // Route only the known native dock shape. Keep the original untouched for fallback.
215
+ const nativeDock = dock as unknown as { entries: Array<Exclude<StackChild, Component>>; children: Component[] };
216
+ const entries = Array.isArray(nativeDock.entries) ? nativeDock.entries.map(entry => ({ ...entry })) : [];
217
+ const supportedDock = entries.length === 6 && entries.every((entry, i) => entry.component === nativeDock.children[i]) &&
218
+ [2, 4].every(i => entries[i].component.constructor.name === "Container") &&
219
+ entries[3].minSize === 3;
220
+ const above = supportedDock ? entries[2].component as Container : undefined;
221
+ const below = supportedDock ? entries[4].component as Container : undefined;
222
+ const editorSlot = supportedDock && entries[3].component.constructor.name === "Container"
223
+ ? entries[3].component as Container : undefined;
224
+ let projectDialog = false;
225
+ const dialogPresent = (): boolean => {
226
+ const editor = this.getEditor();
227
+ return !!editor && !!editorSlot && editorSlot.children.length === 1 && editorSlot.children[0] !== editor;
228
+ };
229
+ const projectedDock = supportedDock ? new VStack(entries.filter((_, i) => i !== 2 && i !== 4).map(entry =>
230
+ entry.component === editorSlot ? { ...entry, visible: () => !projectDialog } : entry)) : undefined;
231
+ // Preserve the original containers and Pi's above/editor/below order. Pi still owns their lifecycle.
232
+ const surfaceTree = above && below ? new VStack([
233
+ above, ...(editorSlot ? [{ component: editorSlot, visible: () => projectDialog }] : []), below,
234
+ ]) : undefined;
235
+ const surfaceView = surfaceTree ? new NativeSurfaceScrollView(surfaceTree, { overscroll: "contain" }) : undefined;
236
+ const widgetsPresent = (): boolean => !!above && !!below && (above.children.length > 1 || below.children.length > 0);
237
+ const surfacePresent = (): boolean => widgetsPresent() || projectDialog;
238
+ const dockUnchanged = (): boolean => supportedDock && nativeDock.entries.length === 6 &&
239
+ nativeDock.entries.every((entry, i) => entry.component === nativeDock.children[i] &&
240
+ Object.keys({ ...entry, ...entries[i] }).every(key =>
241
+ entry[key as keyof typeof entry] === entries[i][key as keyof typeof entry]));
200
242
  this.host = host;
201
243
  this.original = root;
202
244
  this.failed = false;
@@ -227,9 +269,13 @@ export class TranscriptLayout {
227
269
  () => this.searchPane() === "activity");
228
270
  this.chat = new PanelScrollView(chatDocument, scrollOptions, () => this.activate("chat"), () => this.searchPane() === "chat");
229
271
  let historyHeight = 0;
272
+ let projectSurface = false;
230
273
  const shown = ({ width, height }: { width: number; height: number }): boolean => {
231
274
  const previousHeight = historyHeight;
232
- historyHeight = Math.max(0, height - dock.render(width).length - 1);
275
+ const candidate = !!projectedDock && (widgetsPresent() || dialogPresent()) && dockUnchanged() && !this.failed &&
276
+ this.preferences.mode === "split" && this.preferences.zoom !== "chat";
277
+ projectDialog = candidate && dialogPresent();
278
+ historyHeight = Math.max(0, height - (candidate ? projectedDock : dock).render(width).length - 1);
233
279
  const search = this.search;
234
280
  if (search && previousHeight !== historyHeight) queueMicrotask(() => {
235
281
  if (this.search === search) search.bar.reposition();
@@ -240,6 +286,7 @@ export class TranscriptLayout {
240
286
  this.preferences.layout === "columns" ? width >= MIN_CHAT + MIN_ACTIVITY + 1 && historyHeight >= MIN_ROWS + searchRows :
241
287
  width >= MIN_CHAT && historyHeight >= MIN_ROWS * 2 + 1 + searchRows;
242
288
  this.fallback = this.preferences.mode === "split" && !fits;
289
+ projectSurface = candidate && fits;
243
290
  if (this.search && (this.fallback || this.failed || this.preferences.mode !== "split" ||
244
291
  (this.preferences.zoom && this.preferences.zoom !== this.search.pane))) this.closeSearch(false);
245
292
  this.searchShortcut.sync(!this.failed && this.preferences.mode === "split" && fits);
@@ -248,6 +295,28 @@ export class TranscriptLayout {
248
295
  if (this.preferences.mode !== "split" || !fits) return false;
249
296
  // Both panels project the same native history and supported content kinds.
250
297
  activityDocument.check();
298
+ if (projectSurface && surfaceTree && surfacePresent()) {
299
+ const chatWidth = Math.min(width - MIN_ACTIVITY - 1,
300
+ Math.max(MIN_CHAT, this.preferences.chatWidth ?? this.defaultWidth(width)));
301
+ const widgetWidth = this.preferences.zoom === "activity" || this.preferences.layout === "rows"
302
+ ? width : width - chatWidth - 1;
303
+ const chatSearch = this.search?.pane === "chat" ? PANEL_SEARCH_ROWS : 0;
304
+ const activitySearch = this.search?.pane === "activity" ? PANEL_SEARCH_ROWS : 0;
305
+ const chatMin = MIN_ROWS + chatSearch;
306
+ const activityMin = MIN_ROWS + activitySearch;
307
+ const chatLimit = Math.max(chatMin, Math.min((this.preferences.chatHeight ?? this.automaticHeight) + chatSearch,
308
+ historyHeight - activityMin - 1));
309
+ const activityHeight = this.preferences.zoom || this.preferences.layout === "columns" ? historyHeight :
310
+ historyHeight - 1 - Math.min(chatLimit, Math.max(chatMin, chatPane.render(width).length));
311
+ // Do not clip opaque interactive surfaces: their own wheel handlers may consume scrolling.
312
+ // If the entire surface cannot fit, leave Pi's original dock available instead.
313
+ const budget = Math.max(0, activityHeight - 3 - activitySearch);
314
+ if (surfaceTree.render(widgetWidth).length > budget) {
315
+ projectSurface = false;
316
+ this.fallback = true;
317
+ return false;
318
+ }
319
+ }
251
320
  this.activity?.setScrollbar(scroll.scrollbar);
252
321
  this.chat?.setScrollbar(scroll.scrollbar);
253
322
  columns.sizeConversation(chatPane, this.preferences.chatWidth ?? this.defaultWidth(width));
@@ -260,6 +329,7 @@ export class TranscriptLayout {
260
329
  historyHeight - activityMinimum - 1)), chatMinimum, activityMinimum);
261
330
  return true;
262
331
  } catch (error) {
332
+ projectSurface = false;
263
333
  this.failed = true;
264
334
  this.searchShortcut.dispose();
265
335
  this.disposeDocuments?.();
@@ -334,7 +404,8 @@ export class TranscriptLayout {
334
404
  { component: this.searchRows[target], basis: "auto", shrink: 0,
335
405
  visible: () => this.search?.pane === target },
336
406
  ]);
337
- return new TranscriptPane(header, view, () => historyHeight);
407
+ return new TranscriptPane(header, view, () => historyHeight,
408
+ target === "activity" ? surfaceView : undefined, () => projectSurface && surfacePresent());
338
409
  };
339
410
  const activityPane = pane("Activity", "activity", this.activity);
340
411
  const chatPane = pane("Conversation", "chat", this.chat);
@@ -410,7 +481,9 @@ export class TranscriptLayout {
410
481
  { component: chatPane, basis: "auto", minSize: MIN_ROWS,
411
482
  visible: viewport => shown(viewport) && this.preferences.zoom === "chat" },
412
483
  { component: transcript, basis: 0, grow: 1, minSize: 1, visible: viewport => !shown(viewport) },
413
- { component: dock, basis: "auto", shrink: 0, minSize: 1 },
484
+ ...(projectedDock ? [{ component: projectedDock, basis: "auto" as const, shrink: 0, minSize: 1,
485
+ visible: () => projectSurface }] : []),
486
+ { component: dock, basis: "auto", shrink: 0, minSize: 1, visible: () => !projectSurface },
414
487
  ]);
415
488
  this.mounted = mounted;
416
489
  host.setLayoutRoot(mounted);
@@ -438,6 +511,8 @@ export class TranscriptLayout {
438
511
  private canFocusSearch(): boolean {
439
512
  const focused = this.host?.getFocusedComponent();
440
513
  if (!focused || focused === this.search?.bar.input) return true;
514
+ const editor = this.getEditor();
515
+ if (editor) return focused === editor;
441
516
  const dock = this.original?.children[1];
442
517
  const pending = dock ? [dock] : [];
443
518
  const visited = new Set<Component>();
@@ -0,0 +1,41 @@
1
+ import { InteractiveMode } from "@earendil-works/pi-coding-agent";
2
+ import type { Component, TUI } from "@earendil-works/pi-tui";
3
+
4
+ type Host = { ui?: unknown; renderer?: unknown; editor?: Component };
5
+ type Boundary = "createExtensionUIContext" | "rebuildChatFromMessages";
6
+ type Prototype = Partial<Record<Boundary, (this: Host, ...args: unknown[]) => unknown>>;
7
+
8
+ /**
9
+ * Observe the native editor identity at UI binding or reload's history rebuild.
10
+ * No dialog APIs, factories, components or focus are wrapped. Unknown hosts stay native.
11
+ */
12
+ export function observeNativeEditor(): { get(tui: TUI): Component | undefined; dispose(): void } {
13
+ const prototype = InteractiveMode.prototype as unknown as Prototype;
14
+ const restorers: Array<() => void> = [];
15
+ let owner: Host | undefined;
16
+ let active = true;
17
+ const restore = (): void => { for (const release of restorers) release(); };
18
+ for (const name of ["createExtensionUIContext", "rebuildChatFromMessages"] as const) {
19
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
20
+ const original = prototype[name];
21
+ if (typeof original !== "function" || !descriptor?.writable) continue;
22
+ function observe(this: Host, ...args: unknown[]): unknown {
23
+ const result = original!.apply(this, args);
24
+ // A later wrapper can retain this trampoline after cancellation.
25
+ if (active && this.editor && typeof this.editor.render === "function" &&
26
+ typeof this.editor.invalidate === "function" && (this.ui || this.renderer)) {
27
+ owner = this;
28
+ restore();
29
+ }
30
+ return result;
31
+ }
32
+ restorers.push(() => {
33
+ if (prototype[name] === observe) Object.defineProperty(prototype, name, descriptor);
34
+ });
35
+ prototype[name] = observe;
36
+ }
37
+ return {
38
+ get: tui => active && owner && (owner.ui === tui || owner.renderer === tui) ? owner.editor : undefined,
39
+ dispose: () => { active = false; owner = undefined; restore(); },
40
+ };
41
+ }
package/src/native.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Theme, ToolInfo } from "@earendil-works/pi-coding-agent";
2
- import { Container, Spacer, Text, truncateToWidth, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
2
+ import { Container, Spacer, Text, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
3
  import { searchText, type SearchEntry, type SearchHit } from "./search.js";
4
4
  import { highlightSearchRows, searchHitRow, type SearchClock } from "./search-highlight.js";
5
5
  import { CompactMessage, type TranscriptTimestamps } from "./timestamps.js";
@@ -7,6 +7,8 @@ import { NativeContentIndex, type ContentEntry, type Pane } from "./content.js";
7
7
  import { CompactTool } from "./compact-tools.js";
8
8
  import { toolPresentations, type ToolPresentation } from "./tool-presentation.js";
9
9
  import { toolGroups, groupSummary, type ToolGroup } from "./tool-groups.js";
10
+ import { ToolIndent } from "./tool-indent.js";
11
+ import { NestedTree, type NativeTreeBody } from "./nested-tree.js";
10
12
  export type { Pane } from "./content.js";
11
13
 
12
14
  /** Decorate one selected block without changing native text or mouse coordinates. */
@@ -41,28 +43,6 @@ class SearchHighlight implements Component {
41
43
  }
42
44
  }
43
45
 
44
- /** Keep hierarchy guides outside native rendering, search and pointer coordinates. */
45
- class ToolIndent extends Container {
46
- private readonly prefix: string;
47
-
48
- constructor(component: Component, depth: number, body: boolean, private readonly theme: () => Theme) {
49
- super();
50
- this.addChild(component);
51
- this.prefix = " │".repeat(depth) + (body ? " " : "");
52
- }
53
-
54
- override render(width: number): string[] {
55
- const inset = Math.min(width, this.prefix.length);
56
- const prefix = this.theme().fg("dim", this.prefix.slice(0, inset));
57
- return super.render(Math.max(0, width - inset)).map(line => truncateToWidth(prefix + line, width, ""));
58
- }
59
-
60
- override handleMouse(event: TuiMouseEvent): ReturnType<Container["handleMouse"]> {
61
- const inset = Math.min(event.width, this.prefix.length);
62
- if (event.x < inset) return undefined;
63
- return super.handleMouse({ ...event, x: event.x - inset, width: Math.max(0, event.width - inset) });
64
- }
65
- }
66
46
  /**
67
47
  * Project the live native component tree, not messages or renderer strings.
68
48
  * Assistant shells keep the native render method and original content components.
@@ -72,6 +52,7 @@ class ToolIndent extends Container {
72
52
  export class NativeDocument extends Container {
73
53
  private readonly stamped = new WeakMap<Component, CompactMessage>();
74
54
  private readonly toolRows = new WeakMap<Component, CompactTool>();
55
+ private readonly nestedTrees = new WeakMap<Component, NestedTree>();
75
56
  private readonly groupRows = new WeakMap<Component, CompactTool>();
76
57
  private readonly indented = new WeakMap<Component, ToolIndent[]>();
77
58
  private readonly openGroups = new WeakSet<Component>();
@@ -283,6 +264,29 @@ export class NativeDocument extends Container {
283
264
  }
284
265
  return row;
285
266
  }
267
+ private nativeBlock(entry: ContentEntry): CompactMessage {
268
+ const component = entry.source;
269
+ const routed = entry.component;
270
+ this.clockOwners.set(component, entry.owner);
271
+ let stamped = this.stamped.get(routed);
272
+ if (!stamped) {
273
+ stamped = new CompactMessage(routed, () => this.timestamps.label(this.clockOwners.get(component) ?? component),
274
+ this.theme, this.timestampGutter, () => this.showTimestamps() && !(this.pane === "activity" && this.compactTools() && entry.kind === "tool"),
275
+ this.copy ? () => this.copyBlock(component) : undefined, this.showCopy);
276
+ this.stamped.set(routed, stamped);
277
+ }
278
+ this.compactBlocks.set(component, stamped);
279
+ return stamped;
280
+ }
281
+ private searchExcerpt(): Component {
282
+ return this.highlighted(new Text(this.theme().fg("accent", "Search match: ") + searchText(this.excerpt!.text), 1, 0), true);
283
+ }
284
+ private treeBody(entry: ContentEntry): NativeTreeBody {
285
+ const block = this.nativeBlock(entry);
286
+ return { entry, component: this.searchAnchor?.entry.source === entry.source && !this.excerpt ? this.highlighted(block) : block,
287
+ clock: () => block.searchClock(),
288
+ excerpt: this.excerpt?.entry.source === entry.source && entry.owner !== entry.source ? this.searchExcerpt() : undefined };
289
+ }
286
290
  override render(width: number): string[] {
287
291
  if (this.frameActive && this.frameWidth === width && this.frameLines) return this.frameLines;
288
292
  const chat = this.source.children[2] as Container;
@@ -317,8 +321,27 @@ export class NativeDocument extends Container {
317
321
  for (const source of opening) this.openGroups.add(source);
318
322
  this.groups = groups;
319
323
  const searched = this.searchAnchor ? this.index.entries(this.pane).find(entry => entry.source === this.searchAnchor!.entry.source) : undefined;
320
- this.searchTool = searched?.nested ? searched.source : searched?.owner;
321
- for (const entry of this.index.entries(this.pane)) {
324
+ this.searchTool = searched?.owner;
325
+ const entries = this.index.entries(this.pane);
326
+ const trees = new Map<Component, NestedTree>();
327
+ if (this.pane === "activity") for (const entry of entries) {
328
+ if (!entry.tool) continue;
329
+ const id = Reflect.get(entry.source, "toolCallId") as string | undefined;
330
+ if (!id || (!this.index.nested.entries(id).length && !this.index.nested.isIncomplete(id))) continue;
331
+ let tree = this.nestedTrees.get(entry.source);
332
+ if (!tree) {
333
+ tree = new NestedTree(id, this.index.nested, this.theme, name => this.present(name), this.compactTools, () => {
334
+ this.beforeExpand(); if (this.searchAnchor) this.clearSearch(); this.frameWidth = undefined;
335
+ }, () => {
336
+ const clock = this.showTimestamps() && this.compactTools() ? this.timestamps.label(entry.source) : "";
337
+ return clock ? clock.length + 1 : 0;
338
+ });
339
+ this.nestedTrees.set(entry.source, tree);
340
+ }
341
+ trees.set(entry.source, tree);
342
+ }
343
+ for (const entry of entries) {
344
+ if (entry.owner !== entry.source && trees.has(entry.owner)) continue;
322
345
  const component = entry.source;
323
346
  const routed = entry.component;
324
347
  this.clockOwners.set(component, entry.owner);
@@ -329,39 +352,38 @@ export class NativeDocument extends Container {
329
352
  let bodyDepth = 0;
330
353
  const compactTool = compactTools && entry.kind === "tool";
331
354
  if (compactTool) {
332
- const group = entry.nested ? undefined : this.groups.get(entry.owner);
355
+ const group = this.groups.get(entry.owner);
333
356
  const grouped = group !== undefined && group.calls.length > 1;
334
- bodyDepth = entry.nested || grouped ? 2 : 1;
357
+ bodyDepth = grouped ? 2 : 1;
335
358
  const members = !grouped || this.groupOpen(group);
336
359
  if (entry.tool) {
337
360
  if (visibleBlock && !toolRun) result.push(new Spacer(1));
338
361
  if (grouped && group.calls[0].source === component) result.push(this.groupRow(group));
339
- if (members) result.push(this.indent(this.compactRow(entry), entry.nested || grouped ? 1 : 0));
362
+ if (members) result.push(this.indent(this.compactRow(entry), grouped ? 1 : 0));
340
363
  toolRun = true;
341
364
  visibleBlock = true;
342
365
  }
343
- nativeBody = entry.nested && !entry.tool ? true : members && this.toolOpen(entry.nested ? component : entry.owner);
366
+ nativeBody = members && this.toolOpen(entry.owner);
344
367
  }
368
+ const tree = trees.get(component);
345
369
  const contentStart = result.length;
346
370
  const bodyWidth = Math.max(0, width - (bodyDepth ? bodyDepth * 2 + 1 : 0));
347
- if (nativeBody && !entry.compact) {
371
+ if (nativeBody && tree) {
372
+ const panels = entries.filter(panel => panel.owner === component && panel.source !== component);
373
+ tree.setBodies(this.treeBody(entry), panels.map(panel => this.treeBody(panel)), this.searchAnchor?.entry.source);
374
+ result.push(tree);
375
+ visibleBlock = true;
376
+ } else if (nativeBody && !entry.compact) {
348
377
  toolRun = false;
349
378
  result.push(...entry.spacing, routed);
350
379
  } else if (nativeBody) {
351
380
  if (!compactTool) toolRun = false;
352
- let stamped = this.stamped.get(routed);
353
- if (!stamped) {
354
- stamped = new CompactMessage(routed, () => this.timestamps.label(this.clockOwners.get(component) ?? component),
355
- this.theme, this.timestampGutter, () => this.showTimestamps() && !(this.pane === "activity" && this.compactTools() && entry.kind === "tool"),
356
- this.copy ? () => this.copyBlock(component) : undefined, this.showCopy);
357
- this.stamped.set(routed, stamped);
358
- }
359
- this.compactBlocks.set(component, stamped);
381
+ const stamped = this.nativeBlock(entry);
360
382
  visibleBlock = stamped.prepare(bodyWidth, compactTool ? false : visibleBlock) || visibleBlock;
361
383
  result.push(stamped);
362
384
  clock = stamped.searchClock();
363
385
  }
364
- if (this.searchAnchor?.entry.source === component && !this.excerpt && result.length > start) {
386
+ if (!tree && this.searchAnchor?.entry.source === component && !this.excerpt && result.length > start) {
365
387
  const last = result.length - 1;
366
388
  result[last] = this.highlighted(result[last]);
367
389
  }
@@ -370,20 +392,25 @@ export class NativeDocument extends Container {
370
392
  const lines = [...prefix, ...result.slice(contentStart).flatMap(child => child.render(bodyWidth))];
371
393
  let excerptRow: number | undefined;
372
394
  if (this.excerpt?.entry.source === component) {
373
- const fragment = new Text(this.theme().fg("accent", "Search match: ") + searchText(this.excerpt.text), 1, 0);
374
395
  if (!lines.length && wasVisible) {
375
396
  result.push(new Spacer(1));
376
397
  lines.push("");
377
398
  }
378
399
  excerptRow = row + lines.length;
379
- const decorated = this.highlighted(fragment, true);
400
+ const decorated = this.searchExcerpt();
380
401
  result.push(decorated);
381
402
  lines.push(...decorated.render(bodyWidth));
382
403
  visibleBlock = true;
383
404
  }
384
405
  // Compact controls/clocks are not saved text. Search the original body only.
385
406
  const prefixRows = prefix.length;
386
- this.positions.set(component, { row: row + prefixRows, lines: lines.slice(prefixRows), clock, excerptRow });
407
+ if (tree && nativeBody) {
408
+ for (const [source, position] of tree.positions) this.positions.set(source, {
409
+ ...position, row: row + prefixRows + position.row,
410
+ excerptRow: position.excerptRow === undefined ? undefined : row + prefixRows + position.excerptRow,
411
+ });
412
+ if (excerptRow !== undefined) this.positions.set(component, { row, lines: [], excerptRow });
413
+ } else this.positions.set(component, { row: row + prefixRows, lines: lines.slice(prefixRows), clock, excerptRow });
387
414
  row += lines.length;
388
415
  }
389
416
  for (let child = contentStart; child < result.length; child++) result[child] = this.indent(result[child], bodyDepth, true);
@@ -0,0 +1,61 @@
1
+ import type { ToolSummary } from "./content.js";
2
+
3
+ type Start = { parentToolCallId?: string; toolCallId: string; toolName: string; args: unknown };
4
+ type End = { toolCallId: string; isError: boolean };
5
+ type SavedCall = { id: string; name: string; status: string; arguments?: unknown; error?: string };
6
+ type SavedMessage = { role: string; toolCallId?: string; nestedCalls?: { calls: SavedCall[]; complete: boolean } };
7
+
8
+ export interface NestedCall extends ToolSummary { id: string; parent: string; root: string; error?: string }
9
+
10
+ /** Execution identities only. Native tools and extensions retain ownership of all result UI. */
11
+ export class NestedCalls {
12
+ private readonly calls = new Map<string, NestedCall>();
13
+ private readonly roots = new Map<string, NestedCall[]>();
14
+ private readonly incomplete = new Set<string>();
15
+ revision = 0;
16
+
17
+ entries(root: string): readonly NestedCall[] { return this.roots.get(root) ?? []; }
18
+ private put(call: NestedCall): void {
19
+ const existing = this.calls.get(call.id);
20
+ if (existing) { Object.assign(existing, call); return; }
21
+ this.calls.set(call.id, call);
22
+ const list = this.roots.get(call.root) ?? [];
23
+ list.push(call); this.roots.set(call.root, list);
24
+ }
25
+ isIncomplete(root: string): boolean { return this.incomplete.has(root); }
26
+ search(root: string): string {
27
+ return this.entries(root).map(call => [call.name, JSON.stringify(call.args, null, 2), call.error].filter(Boolean).join("\n")).join("\n");
28
+ }
29
+ start(event: Start): void {
30
+ if (!event.parentToolCallId) return;
31
+ const parent = this.calls.get(event.parentToolCallId);
32
+ this.put({ id: event.toolCallId, parent: event.parentToolCallId, root: parent?.root ?? event.parentToolCallId,
33
+ name: event.toolName, args: event.args, status: "running" });
34
+ this.revision++;
35
+ }
36
+ end(event: End): void {
37
+ const call = this.calls.get(event.toolCallId);
38
+ if (!call) return;
39
+ call.status = event.isError ? "error" : "success";
40
+ this.revision++;
41
+ }
42
+ absorb(message: SavedMessage): void {
43
+ if (message.role !== "toolResult" || !message.toolCallId || !Array.isArray(message.nestedCalls?.calls)) return;
44
+ const root = message.toolCallId;
45
+ const ids = new Set(message.nestedCalls.calls.map(call => call.id));
46
+ for (const record of message.nestedCalls.calls) {
47
+ const existing = this.calls.get(record.id);
48
+ // Pi records nested identities as <caller-id>/<ordinal>, including deeper calls.
49
+ const parent = record.id.slice(0, record.id.lastIndexOf("/"));
50
+ this.put({ id: record.id, root, parent: existing?.parent ?? (ids.has(parent) ? parent : root),
51
+ name: record.name, args: record.arguments, error: record.error,
52
+ status: record.status === "ok" ? "success" : record.status === "error" ? "error" : "unknown" });
53
+ }
54
+ if (message.nestedCalls.complete) this.incomplete.delete(root); else this.incomplete.add(root);
55
+ this.revision++;
56
+ }
57
+ restore(branch: readonly { type: string; message?: unknown }[]): void {
58
+ this.calls.clear(); this.roots.clear(); this.incomplete.clear(); this.revision++;
59
+ for (const entry of branch) if (entry.type === "message" && entry.message && typeof entry.message === "object") this.absorb(entry.message as SavedMessage);
60
+ }
61
+ }
@@ -0,0 +1,161 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { Container, Text, type Component } from "@earendil-works/pi-tui";
3
+ import { componentTree, type ContentEntry, type ToolSummary } from "./content.js";
4
+ import { CompactTool } from "./compact-tools.js";
5
+ import type { SearchClock } from "./search-highlight.js";
6
+ import type { NestedCall, NestedCalls } from "./nested-calls.js";
7
+ import type { ToolPresentation } from "./tool-presentation.js";
8
+ import { ToolIndent } from "./tool-indent.js";
9
+
10
+ export interface NativeTreeBody { entry: ContentEntry; component: Component; excerpt?: Component; clock?(): SearchClock | undefined }
11
+ interface Node { key: string; summary: ToolSummary; children: Node[]; count?: number }
12
+
13
+ /** Structural disclosure only: every result body is the original native component. */
14
+ export class NestedTree extends Container {
15
+ readonly positions = new Map<Component, { row: number; lines: string[]; clock?: SearchClock; excerptRow?: number }>();
16
+ private parent?: NativeTreeBody;
17
+ private panels: NativeTreeBody[] = [];
18
+ private reveal?: Component;
19
+ private readonly open = new Map<string, boolean>();
20
+ private readonly revealed = new Set<string>();
21
+ private readonly rows = new Map<string, CompactTool>();
22
+ private readonly indents = new WeakMap<Component, Map<string, ToolIndent>>();
23
+ private buckets = new Map<string, string>();
24
+ private nodes = new Map<string, Node>();
25
+ private mode?: boolean;
26
+
27
+ constructor(readonly rootId: string, private readonly calls: NestedCalls, private readonly theme: () => Theme,
28
+ private readonly present: (name: string) => ToolPresentation, private readonly compact: () => boolean, private readonly changed: () => void, private readonly gutter: () => number = () => 0) { super(); }
29
+
30
+ setBodies(parent: NativeTreeBody, panels: NativeTreeBody[], reveal?: Component): void {
31
+ this.parent = parent; this.panels = panels; this.reveal = reveal;
32
+ }
33
+ private isOpen(key: string): boolean { return this.revealed.has(key) || (this.open.get(key) ?? !this.compact()); }
34
+ private indent(component: Component, depth: number, body = false): Component {
35
+ const gutter = this.gutter();
36
+ if (!depth && !gutter) return component;
37
+ let levels = this.indents.get(component);
38
+ if (!levels) { levels = new Map(); this.indents.set(component, levels); }
39
+ const key = `${gutter}:${depth}:${body}`;
40
+ let view = levels.get(key);
41
+ if (!view) { view = new ToolIndent(component, depth, body, this.theme, gutter); levels.set(key, view); }
42
+ return view;
43
+ }
44
+ private header(node: Node, expandable: boolean): CompactTool {
45
+ // Include expandability in the key: late native output can turn a leaf into a disclosure.
46
+ const key = node.key + (expandable ? ":open" : ":leaf");
47
+ let row = this.rows.get(key);
48
+ if (!row) {
49
+ row = new CompactTool(() => this.nodes.get(node.key)!.summary, this.theme, {
50
+ alignControl: true,
51
+ count: node.count ? () => this.nodes.get(node.key)!.count! : undefined,
52
+ expanded: () => this.isOpen(node.key),
53
+ toggle: expandable ? () => { this.open.set(node.key, !this.isOpen(node.key)); this.changed(); } : undefined,
54
+ });
55
+ this.rows.set(key, row);
56
+ }
57
+ return row;
58
+ }
59
+ override render(width: number): string[] {
60
+ if (!this.parent) return [];
61
+ if (this.mode !== this.compact()) { this.open.clear(); this.mode = this.compact(); }
62
+ this.revealed.clear();
63
+ const records = this.calls.entries(this.rootId);
64
+ const siblings = new Map<string, NestedCall[]>();
65
+ for (const call of records) {
66
+ const list = siblings.get(call.parent) ?? []; list.push(call); siblings.set(call.parent, list);
67
+ }
68
+ this.nodes = new Map();
69
+ const buckets = new Map<string, string>();
70
+ const paths = new Map<string, string[]>();
71
+ const make = (parent: string, ancestors: string[], visiting = new Set<string>()): Node[] => {
72
+ if (visiting.has(parent)) return [];
73
+ const seen = new Set(visiting); seen.add(parent);
74
+ const runs: NestedCall[][] = [];
75
+ for (const call of siblings.get(parent) ?? []) {
76
+ const last = runs.at(-1);
77
+ if (last && this.present(last[0].name).key === this.present(call.name).key) last.push(call); else runs.push([call]);
78
+ }
79
+ return runs.map(run => {
80
+ const grouped = run.length > 1;
81
+ const key = grouped ? "group:" + run[0].id : run[0].id;
82
+ const path = [...ancestors, key]; paths.set(key, path);
83
+ const children = run.map(call => {
84
+ buckets.set(call.id, key);
85
+ const callPath = grouped ? [...path, call.id] : path; paths.set(call.id, callPath);
86
+ const node: Node = { key: call.id, summary: { ...call, name: this.present(call.name).name }, children: make(call.id, callPath, seen) };
87
+ this.nodes.set(node.key, node);
88
+ return node;
89
+ });
90
+ if (!grouped) return children[0];
91
+ const status = run.some(call => call.status === "error") ? "error" : run.some(call => call.status === "running") ? "running" :
92
+ run.some(call => call.status === "unknown") ? "unknown" : "success";
93
+ const group: Node = { key, count: run.length, summary: { name: this.present(run[0].name).name, args: undefined, status }, children };
94
+ this.nodes.set(key, group);
95
+ return group;
96
+ });
97
+ };
98
+ const roots = make(this.rootId, []);
99
+ // A late sibling can turn an open singleton into a group. Carry only the
100
+ // immediately visible state; an explicitly closed group must remain closed.
101
+ for (const [id, key] of buckets) {
102
+ const previous = this.buckets.get(id);
103
+ if (previous && previous !== key && !this.open.has(key) && this.isOpen(previous)) this.open.set(key, true);
104
+ }
105
+ this.buckets = buckets;
106
+ const attached = new Map<string, NativeTreeBody[]>();
107
+ const identified = this.panels.map(panel => ({ panel, ids: [...new Set(componentTree(panel.entry.source)
108
+ .filter(node => node.constructor.name === "ToolExecutionComponent" && typeof node.toolCallId === "string").map(node => node.toolCallId!))] }));
109
+ const independent = new Map<string, Set<string>>();
110
+ for (const { ids } of identified) {
111
+ const bucket = ids.length === 1 ? buckets.get(ids[0]) : undefined;
112
+ if (!bucket) continue;
113
+ const group = independent.get(bucket) ?? new Set<string>();
114
+ group.add(ids[0]); independent.set(bucket, group);
115
+ }
116
+ for (const { panel, ids } of identified) {
117
+ const locations = ids.map(id => buckets.get(id));
118
+ // Independent native results belong to their calls. One shared result for
119
+ // several siblings stays whole at the group; opaque bodies stay at the caller.
120
+ const bucket = locations.length && locations[0] && locations.every(location => location === locations[0]) ? locations[0] : "";
121
+ const key = ids.length === 1 && (independent.get(bucket)?.size ?? 0) > 1 ? ids[0] : bucket;
122
+ const list = attached.get(key) ?? []; list.push(panel); attached.set(key, list);
123
+ if (this.reveal === panel.entry.source) for (const ancestor of paths.get(key) ?? ["output"]) this.revealed.add(ancestor);
124
+ }
125
+ const output: Node = { key: "output", summary: { ...this.parent.entry.tool!(), name: this.present(this.parent.entry.tool!().name).name + " output", args: undefined }, children: [] };
126
+ this.nodes.set(output.key, output);
127
+ if (this.reveal === this.parent.entry.source) this.revealed.add(output.key);
128
+ const result: Component[] = [];
129
+ this.positions.clear();
130
+ let row = 0;
131
+ const append = (component: Component, depth: number, body = false): string[] => {
132
+ const view = this.indent(component, depth, body);
133
+ result.push(view);
134
+ const lines = view.render(width); row += lines.length; return lines;
135
+ };
136
+ const appendBody = (body: NativeTreeBody, depth: number): void => {
137
+ const start = row;
138
+ const lines = append(body.component, depth, depth > 0);
139
+ const excerptRow = body.excerpt ? row : undefined;
140
+ if (body.excerpt) append(body.excerpt, depth, depth > 0);
141
+ this.positions.set(body.entry.source, { row: start, lines, clock: body.clock?.(), excerptRow });
142
+ };
143
+ const paint = (node: Node, depth: number): void => {
144
+ const panels = attached.get(node.key) ?? [];
145
+ const expandable = node.children.length > 0 || panels.length > 0;
146
+ append(this.header(node, expandable), depth);
147
+ if (!expandable || !this.isOpen(node.key)) return;
148
+ for (const child of node.children) paint(child, depth + 1);
149
+ for (const panel of panels) appendBody(panel, depth + 1);
150
+ };
151
+ for (const root of roots) paint(root, 0);
152
+ if (this.calls.isIncomplete(this.rootId)) append(new Text(this.theme().fg("dim", "Nested call record incomplete"), 0, 0), 0);
153
+ append(this.header(output, true), 0);
154
+ if (this.isOpen(output.key)) {
155
+ for (const panel of attached.get("") ?? []) appendBody(panel, 1);
156
+ appendBody(this.parent, 1);
157
+ }
158
+ this.children = result;
159
+ return super.render(width);
160
+ }
161
+ }
package/src/startup.ts CHANGED
@@ -1,33 +1,6 @@
1
- import { InteractiveMode, type ExtensionContext, type ToolRenderers } from "@earendil-works/pi-coding-agent";
1
+ import { InteractiveMode, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { isViewportTUI, type TUI } from "@earendil-works/pi-tui";
3
3
 
4
- /** Resolve nested tools through the same interactive host that renders ordinary calls. */
5
- export function captureToolRenderers(): { install(): void; resolve(name: string): ToolRenderers | undefined; dispose(): void } {
6
- const prototype = InteractiveMode.prototype as unknown as Record<string, unknown>;
7
- let owner: unknown;
8
- let original: ((this: unknown, name: string) => ToolRenderers | undefined) | undefined;
9
- let wrapper: ((this: unknown, name: string) => ToolRenderers | undefined) | undefined;
10
- let stop = (): void => {};
11
- return {
12
- install() {
13
- if (wrapper) return;
14
- const descriptor = Object.getOwnPropertyDescriptor(prototype, "getRegisteredToolDefinition");
15
- if (!descriptor?.writable || typeof descriptor.value !== "function") return;
16
- const previous = descriptor.value as (this: unknown, name: string) => ToolRenderers | undefined;
17
- original = previous;
18
- let active = true;
19
- stop = () => { active = false; };
20
- wrapper = function (this: unknown, name: string) { if (active) owner = this; return previous.call(this, name); };
21
- prototype.getRegisteredToolDefinition = wrapper;
22
- },
23
- resolve(name) { return owner && original ? original.call(owner, name) : undefined; },
24
- dispose() {
25
- stop();
26
- if (wrapper && prototype.getRegisteredToolDefinition === wrapper) prototype.getRegisteredToolDefinition = original;
27
- owner = undefined; wrapper = undefined; original = undefined;
28
- },
29
- };
30
- }
31
4
  type Ui = ExtensionContext["ui"];
32
5
  type Session = ExtensionContext["sessionManager"];
33
6
  type StartupHost = {
@@ -0,0 +1,21 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { Container, truncateToWidth, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
+
4
+ /** Keep hierarchy guides outside native rendering and pointer coordinates. */
5
+ export class ToolIndent extends Container {
6
+ private readonly prefix: string;
7
+ constructor(component: Component, depth: number, body: boolean, private readonly theme: () => Theme, gutter = 0) {
8
+ super(); this.addChild(component);
9
+ this.prefix = " ".repeat(gutter) + " │".repeat(depth) + (body ? " " : "");
10
+ }
11
+ override render(width: number): string[] {
12
+ const inset = Math.min(width, this.prefix.length);
13
+ const prefix = this.theme().fg("dim", this.prefix.slice(0, inset));
14
+ return super.render(Math.max(0, width - inset)).map(line => truncateToWidth(prefix + line, width, ""));
15
+ }
16
+ override handleMouse(event: TuiMouseEvent): ReturnType<Container["handleMouse"]> {
17
+ const inset = Math.min(event.width, this.prefix.length);
18
+ if (event.x < inset) return undefined;
19
+ return super.handleMouse({ ...event, x: event.x - inset, width: Math.max(0, event.width - inset) });
20
+ }
21
+ }
@@ -1,110 +0,0 @@
1
- import { ToolExecutionComponent, type ToolRenderers } from "@earendil-works/pi-coding-agent";
2
- import { Text, stripTerminalSequences, type Component, type TUI } from "@earendil-works/pi-tui";
3
-
4
- type Start = { parentToolCallId: string; toolCallId: string; toolName: string; args: unknown };
5
- type End = { parentToolCallId: string; toolCallId: string; toolName: string; result: { content?: unknown }; isError: boolean; durationMs?: number };
6
- type RecordCall = { id: string; name: string; status: "ok" | "error" | "unfinished"; arguments?: unknown; argumentsBytes?: number; error?: string };
7
- type SavedMessage = { role: string; toolCallId?: string; nestedCalls?: { complete: boolean; calls: RecordCall[] } };
8
- type Call = { root: string; id: string; name: string; args: unknown; status: string; result?: string; saved?: boolean; bytes?: number; parallel?: boolean; view: Component };
9
-
10
- const clean = (value: string): string => stripTerminalSequences(value).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "");
11
- const resultText = (content: unknown): string => Array.isArray(content) ? content.map(block =>
12
- block?.type === "text" && typeof block.text === "string" ? clean(block.text.replace(/^<system-result\b[^>]*><uuid>[a-f\d-]{36}<\/uuid><\/system-result>\n/iu, "")) : block?.type === "image" ? "[image]" : "").filter(Boolean).join("\n") : "";
13
-
14
- /** Display-only nested call state. Saved records never imply that a result was saved. */
15
- export class NestedActivity {
16
- private calls = new Map<string, Call>();
17
- private roots = new Map<string, Component[]>();
18
- private byView = new WeakMap<Component, Call>();
19
- private notices = new Map<string, Text>();
20
- revision = 0;
21
-
22
- constructor(private readonly tui?: TUI, private readonly cwd = "", private readonly renderer?: (name: string) => ToolRenderers | undefined) {}
23
-
24
- entries(parent: string): readonly Component[] { return this.roots.get(parent) ?? []; }
25
-
26
- summary(view: Component): { name: string; args: unknown; status: "running" | "success" | "error" | "unknown" } | undefined {
27
- const call = this.byView.get(view);
28
- return call ? { name: call.name, args: call.args, status: call.status === "error" ? "error" : call.status === "ok" ? "success" : call.status === "running" ? "running" : "unknown" } : undefined;
29
- }
30
-
31
- id(view: Component): string | undefined { return this.byView.get(view)?.id; }
32
- isSaved(view: Component): boolean { return this.byView.get(view)?.saved === true; }
33
- search(view: Component): string {
34
- const call = this.byView.get(view);
35
- return call ? [call.name, JSON.stringify(call.args, null, 2), call.result].filter(Boolean).join("\n") : "";
36
- }
37
-
38
- private paint(call: Call): void {
39
- const depth = Math.max(1, call.id.slice(call.root.length).split("/").length - 1);
40
- const prefix = " ".repeat(Math.min(depth, 8));
41
- const args = call.args === undefined ? (call.bytes === undefined ? "" : `Arguments omitted (${call.bytes} bytes)`) : JSON.stringify(call.args, null, 2);
42
- const details = [args, call.result, call.saved ? "Result not saved" : ""].filter(Boolean).join("\n");
43
- if (!(call.view instanceof Text)) return;
44
- call.view.setText(`${prefix}↳ ${clean(call.name)} [${call.status}${call.parallel ? ", overlapping" : ""}]\n${details.split("\n").map(line => prefix + clean(line)).join("\n")}`);
45
- }
46
-
47
- start(event: Start): void {
48
- const root = this.calls.get(event.parentToolCallId)?.root ?? event.parentToolCallId;
49
- const running = [...this.calls.values()].filter(call => call.root === root && call.status === "running" && !event.parentToolCallId.startsWith(call.id + "/") && event.parentToolCallId !== call.id);
50
- const native = this.tui ? new ToolExecutionComponent(event.toolName, event.toolCallId, event.args, { showImages: true }, this.renderer?.(event.toolName), this.tui, this.cwd) : undefined;
51
- native?.markExecutionStarted();
52
- native?.setArgsComplete();
53
- native?.setExpanded(true);
54
- const call: Call = { root, id: event.toolCallId, name: event.toolName, args: event.args, status: "running", parallel: running.length > 0, view: native ?? new Text("", 0, 0) };
55
- for (const other of running) { other.parallel = true; this.paint(other); }
56
- this.calls.set(call.id, call);
57
- this.byView.set(call.view, call);
58
- const entries = this.roots.get(root) ?? [];
59
- entries.push(call.view);
60
- this.roots.set(root, entries);
61
- this.paint(call);
62
- this.revision++;
63
- }
64
-
65
- update(event: { toolCallId: string; partialResult: { content?: unknown } }): void {
66
- const call = this.calls.get(event.toolCallId);
67
- if (!call) return;
68
- call.result = resultText(event.partialResult.content);
69
- if (call.view instanceof ToolExecutionComponent) call.view.updateResult({ ...event.partialResult, content: Array.isArray(event.partialResult.content) ? event.partialResult.content : [], isError: false }, true);
70
- this.paint(call);
71
- }
72
-
73
- end(event: End): void {
74
- const call = this.calls.get(event.toolCallId);
75
- if (!call) return;
76
- call.status = event.isError ? "error" : "ok";
77
- call.result = resultText(event.result.content);
78
- if (call.view instanceof ToolExecutionComponent) call.view.updateResult({ ...event.result, content: Array.isArray(event.result.content) ? event.result.content : [], isError: event.isError, durationMs: event.durationMs });
79
- this.paint(call);
80
- }
81
-
82
- absorb(message: SavedMessage): void {
83
- const root = message.toolCallId;
84
- const nested = message.nestedCalls;
85
- if (message.role !== "toolResult" || !root || !nested || !Array.isArray(nested.calls)) return;
86
- let entries = this.roots.get(root);
87
- if (!entries) { entries = []; this.roots.set(root, entries); }
88
- for (const record of nested.calls) {
89
- if (this.calls.has(record.id)) continue;
90
- const call: Call = { root, id: record.id, name: record.name, args: record.arguments, status: record.status,
91
- bytes: record.argumentsBytes, result: record.error, saved: true, view: new Text("", 0, 0) };
92
- this.calls.set(record.id, call);
93
- this.byView.set(call.view, call);
94
- entries.push(call.view);
95
- this.paint(call);
96
- this.revision++;
97
- }
98
- if (!nested.complete && !this.notices.has(root)) {
99
- const notice = new Text(" Nested call record incomplete", 0, 0);
100
- this.notices.set(root, notice);
101
- entries.push(notice);
102
- this.revision++;
103
- }
104
- }
105
-
106
- restore(branch: readonly { type: string; message?: unknown }[]): void {
107
- this.calls.clear(); this.roots.clear(); this.notices.clear(); this.revision++;
108
- for (const entry of branch) if (entry.type === "message" && entry.message && typeof entry.message === "object") this.absorb(entry.message as SavedMessage);
109
- }
110
- }