pi-ext
bugabingas pi extensions
owned by admin
fix(ui): honor native tool expansion
02750ae602ba66f6ddd9bcb13bed5be71b4237f9
Oliver Jan Krylow <oliver@bugabinga.net> ·
SSH signature · not checked
Browse filesCompare with HEAD
Changed files (22)
61 61 ###
Tool widget rendering 63 63 Tool widgets must match Pi built-ins: compact by default, expanded details on `app.tools.expand` (`ctrl+o` by default).
64 +Normal tool rows must rely on Pi-owned keyboard and mouse expansion; do not register extension shortcuts or mouse handlers for them.
65 +Every custom `renderCall` and `renderResult` must honor native expanded state, including progress, errors, and malformed-detail fallback paths.
64 66 Collapsed `renderResult` output may show status, counts, paths, IDs, and tiny bounded summaries only.
65 67 Full content, previews, snippets, verbose logs, structured bodies, and per-result lists require `expanded === true`.
66 -Expansion hints must use `keyHint("app.tools.expand", "to expand")`; do not use legacy `expandTools`.
68 +When content is hidden, show `keyHint("app.tools.expand", "to expand")`; do not use legacy `expandTools`.
69 +Focused custom overlays and non-tool widgets may handle their own expansion action because they do not inherit normal tool-row input handling.
68 71 ###
Cross-platform requirements extensions/angel/README.md
Modified105 105 The complete investigation remains in the child session and is inspected through Pi's normal session browser.
107 107 Tool progress uses native streaming updates.
108 -Collapsed tool output stays compact; expanded output shows provisional draft text and complete metadata.
108 +Collapsed tool output stays compact and shows the configured expansion shortcut.
109 +Expanded output shows the full assignment, provisional draft text, and complete metadata.
109 110 Human-directed consultations use a cancellable live view in TUI mode and emit plain text in print mode.
110 111 Session replacement and tree navigation cancel stale investigations before they can deliver into another parent context.
extensions/angel/__tests__/harness.test.ts
Modified 1 +import { createRequire }
from "node:module";
2 +import { pathToFileURL }
from "node:url";
3 +import { stripVTControlCharacters }
from "node:util";
1 4 import { fauxAssistantMessage, fauxToolCall }
from "@earendil-works/pi-ai";
2 -import { convertToLlm }
from "@earendil-works/pi-coding-agent";
3 -import { afterEach, describe, expect, it, vi }
from "vitest";
5 +import { convertToLlm, initTheme }
from "@earendil-works/pi-coding-agent";
6 +import type { KeybindingsManager }
from "@earendil-works/pi-tui";
76 + fg: (_style
: string, text
: string)
=> text,
77 + bg: (_style
: string, text
: string)
=> text,
78 + bold: (text
: string)
=> text,
79 + italic: (text
: string)
=> text,
80 + strikethrough: (text
: string)
=> text,
85 + component
: {
render(width
: number)
: string[] }
| undefined,
87 + if (
!component)
throw new Error(
"expected rendered component");
88 + return stripVTControlCharacters(component.
render(
120).
join(
"\n"))
89 + .
replaceAll(
/\s+/gu,
" ")
62 93 function dependencies() {
63 94 const runConsultation
= vi.fn
< 64 95 NonNullable
<AngelDependencies[
"runConsultation"]
> 81 112 describe(
"angel extension runtime", ()
=> {
82 113 let testSession
: TestSession | undefined;
114 + let testKeybindings
: KeybindingsManager;
115 + let restoreKeybindings = ()
=> {};
117 + beforeAll(
async ()
=> {
118 + initTheme(
"default",
false);
119 + const codingAgentEntry
= import.
meta.
resolve(
120 + "@earendil-works/pi-coding-agent",
122 + const piTuiEntry
= createRequire(codingAgentEntry).
resolve(
123 + "@earendil-works/pi-tui",
125 + const piTui
= (
await import(
126 + pathToFileURL(piTuiEntry).
href 127 + ))
as typeof import(
"@earendil-works/pi-tui");
128 + const previousKeybindings
= piTui.
getKeybindings();
129 + testKeybindings
= new piTui.
KeybindingsManager({
130 + "app.tools.expand": {
131 + defaultKeys:
"ctrl+o",
132 + description:
"Toggle tool output",
135 + piTui.
setKeybindings(testKeybindings);
136 + restoreKeybindings = ()
=> piTui.
setKeybindings(previousKeybindings);
139 + afterAll(()
=> restoreKeybindings());
85 142 testSession?.
dispose();
101 158 expect(runner.
hasHandlers(
"tool_call")).
toBe(
false);
161 + it(
"uses the brain icon and native tool expansion across consultation states",
async ()
=> {
162 + testSession
= await createTestSession({
163 + extensionFactories: [
createAngelExtension(
dependencies())],
166 + testSession.session.extensionRunner.extensions[
0]?.tools.
get(
169 + expect(tool).
toBeDefined();
171 + const question
= `Which explanation fits ${"the available evidence ".repeat(6)}?`;
172 + const context
= "Only the integration environment reproduces the failure.";
173 + const collapsedCall
= rendered(
174 + tool?.
renderCall?.({ question, context },
theme(), {
178 + const expandedCall
= rendered(
179 + tool?.
renderCall?.({ question, context },
theme(), {
183 + expect(collapsedCall).
toContain(
" angel");
184 + expect(collapsedCall).
toContain(
"ctrl+o to expand");
185 + testKeybindings.
setUserBindings({
"app.tools.expand":
"alt+o" });
188 + tool?.
renderCall?.({ question, context },
theme(), {
192 + ).
toContain(
"alt+o to expand");
193 + testKeybindings.
setUserBindings({});
194 + expect(collapsedCall).not.
toContain(context);
195 + expect(expandedCall).
toContain(question);
196 + expect(expandedCall).
toContain(context);
197 + expect(expandedCall).not.
toContain(
"to expand");
199 + tool?.
renderCall?.({},
theme(), { expanded:
false }
as any),
202 + const preview
= "Provisional investigation text";
204 + content: [{ type:
"text", text:
"Inspecting" }],
207 + progress: { stage:
"investigating", message:
"Inspecting", preview },
210 + const collapsedProgress
= rendered(
211 + tool?.
renderResult?.(
213 + { expanded:
false, isPartial:
true },
218 + const expandedProgress
= rendered(
219 + tool?.
renderResult?.(
221 + { expanded:
true, isPartial:
true },
226 + expect(collapsedProgress).
toContain(
" Inspecting");
227 + expect(collapsedProgress).not.
toContain(preview);
228 + expect(expandedProgress).
toContain(preview);
229 + expect(expandedProgress).not.
toContain(
"👼");
231 + const consultation
= result(
"executor");
233 + content: [{ type:
"text", text: consultation.advice }],
234 + details: { kind:
"complete", result: consultation },
236 + const collapsedComplete
= rendered(
237 + tool?.
renderResult?.(
239 + { expanded:
false, isPartial:
false },
244 + const expandedComplete
= rendered(
245 + tool?.
renderResult?.(
247 + { expanded:
true, isPartial:
false },
252 + expect(collapsedComplete).
toContain(
" Advice ready");
254 + `${collapsedCall}\n${collapsedComplete}`.
match(
/to expand/gu),
256 + expect(expandedComplete).
toContain(consultation.metadata.childSessionFile);
257 + expect(expandedComplete).not.
toContain(consultation.advice);
260 + content: [{ type:
"text", text:
"Angel process failed\nEND-DIAGNOSTIC" }],
263 + const collapsedFailure
= rendered(
264 + tool?.
renderResult?.(
266 + { expanded:
false, isPartial:
false },
271 + const expandedFailure
= rendered(
272 + tool?.
renderResult?.(
274 + { expanded:
true, isPartial:
false },
279 + expect(collapsedFailure).
toBe(
"Angel failed");
280 + expect(expandedFailure).
toContain(
"END-DIAGNOSTIC");
104 283 it(
"publishes and clears its fallback availability status",
async ()
=> {
105 284 testSession
= await createTestSession({
106 285 extensionFactories: [
createAngelExtension(
dependencies())],
extensions/angel/index.ts
Modified 375 -function questionSummary(question
: string)
: string {
375 +function questionSummary(question
: unknown)
: string {
376 + if (
typeof question
!== "string")
return "";
376 377 const normalized
= question.
replaceAll(
/\s+/g,
" ").
trim();
377 378 return normalized.
length <= 72 ? normalized
: `${normalized.slice(0, 69)}...`;
735 - ctx.ui.theme.
fg(
"accent",
"👼 Angel"),
736 + ctx.ui.theme.
fg(
"accent",
`${ANGEL_ICON} Angel`),
736 737 ctx.ui.theme.
fg(
"dim", update.message),
738 739 if (update.preview)
835 - renderCall(args, theme) {
837 - theme.
fg(
"toolTitle", theme.
bold(
"angel "))
+ 838 - theme.
fg(
"dim",
questionSummary(args.question)),
836 + renderCall(args, theme, context) {
837 + const question
= typeof args.question
=== "string" ? args.question
: "";
838 + const extraContext
= 839 + typeof args.context
=== "string" ? args.context
: "";
840 + let output
= theme.
fg(
"toolTitle", theme.
bold(
`${ANGEL_ICON} angel`));
841 + const summary
= questionSummary(question);
842 + if (summary) output
+= ` ${theme.fg("dim", summary)}`;
843 + if (context.expanded) {
845 + output
+= `\n${theme.fg("dim", "question: ")}${theme.fg("toolOutput", question)}`;
847 + output
+= `\n${theme.fg("dim", "context: ")}${theme.fg("toolOutput", extraContext)}`;
849 + output
+= theme.
fg(
851 + ` (${keyHint("app.tools.expand", "to expand")})`,
854 + return new Text(output,
0,
0);
843 856 renderResult(result, { expanded, isPartial }, theme) {
844 857 const details
= result.details
as ToolDetails | undefined;
846 859 const progress
= details?.progress;
847 860 let output
= theme.
fg(
849 - `👼 ${progress?.message ?? "Consulting Angel"}`,
862 + `${ANGEL_ICON} ${progress?.message ?? "Consulting Angel"}`,
851 864 if (expanded
&& progress?.preview) {
852 865 const preview
= progress.preview.
slice(
-PREVIEW_MAX_CHARS);
855 868 return new Text(output,
0,
0);
857 870 if (
!isCompleteToolDetails(details)) {
858 - return new Text(theme.
fg(
"error",
"Angel failed"),
0,
0);
871 + let output
= theme.
fg(
"error",
"Angel failed");
872 + const content
= result.
content[
0];
873 + if (expanded
&& content?.
type === "text" && content.
text.
trim())
874 + output
+= `\n${theme.fg("dim", content.text)}`;
875 + return new Text(output,
0,
0);
860 877 const metadata
= details.result.metadata;
861 - let output
= theme.
fg(
"success",
"👼 Advice ready");
878 + let output
= theme.
fg(
"success",
`${ANGEL_ICON} Advice ready`);
862 879 output
+= theme.
fg(
864 881 ` · ${metadata.tokens.total.toLocaleString("en-US")} tokens`,
867 - output
+= theme.
fg(
869 - ` (${keyHint("app.tools.expand", "to expand")})`,
872 884 output
+= `\n${theme.fg("dim", metadataDetailLines(metadata).join("\n"))}`;
873 885 output
+= `\n${theme.fg("dim", metadata.childSessionFile)}`;
extensions/git-safe/__tests__/harness.test.ts
Modified 11 11 import { tmpdir }
from "node:os";
12 12 import path
from "node:path";
13 -import { createBashTool }
from "@earendil-works/pi-coding-agent";
13 +import { createBashTool, initTheme }
from "@earendil-works/pi-coding-agent";
14 14 import { afterEach, describe, expect, it }
from "vitest";
149 + fg: (_style
: string, text
: string)
=> text,
150 + bold: (text
: string)
=> text,
154 +function render(component
: {
render(width
: number)
: string[] })
: string {
155 + return component.
render(
120).
join(
"\n");
147 158 describe(
"git-safe pi-test-harness", ()
=> {
148 159 let t
: TestSession | undefined;
149 160 let root
: string | undefined;
236 + it(
"reveals clone warnings only when expanded",
async ()
=> {
237 + initTheme(
"default",
false);
238 + t
= await createTestSession({ extensions: [
gitSafePath()] });
240 + t.session.extensionRunner.extensions[
0].tools.
get(
244 + content: [{ type:
"text", text:
"cloned" }],
246 + url:
"https://example.com/owner/repo.git",
247 + path:
"/tmp/owner/repo",
249 + totalSizeBytes:
128,
252 + warnings: [
"Submodules were not initialized"],
255 + const collapsed
= render(
256 + tool.
renderResult(result, { expanded:
false },
theme()),
258 + const expanded
= render(
259 + tool.
renderResult(result, { expanded:
true },
theme()),
261 + expect(collapsed).
toContain(
"to expand");
262 + expect(collapsed).not.
toContain(
"Submodules were not initialized");
263 + expect(expanded).
toContain(
"Submodules were not initialized");
264 + expect(expanded).not.
toContain(
"to expand");
270 + text:
"Clone failed\ncause\nnext step\nalternative\nEND-OF-DIAGNOSTIC",
275 + const collapsedError
= render(
276 + tool.
renderResult(error, { expanded:
false },
theme()),
278 + const expandedError
= render(
279 + tool.
renderResult(error, { expanded:
true },
theme()),
281 + expect(collapsedError).
toContain(
"to expand");
282 + expect(collapsedError).not.
toContain(
"END-OF-DIAGNOSTIC");
283 + expect(expandedError).
toContain(
"END-OF-DIAGNOSTIC");
285 + const longError
= {
289 + text:
`Clone failed: ${"diagnostic ".repeat(30)}END-OF-LONG-DIAGNOSTIC`,
294 + const collapsedLongError
= render(
295 + tool.
renderResult(longError, { expanded:
false },
theme()),
297 + const expandedLongError
= render(
298 + tool.
renderResult(longError, { expanded:
true },
theme()),
300 + expect(collapsedLongError).
toContain(
"to expand");
301 + expect(collapsedLongError).not.
toContain(
"END-OF-LONG-DIAGNOSTIC");
302 + expect(expandedLongError).
toContain(
"END-OF-LONG-DIAGNOSTIC");
225 305 it(
"recovers a marked clone lazily when read",
async ()
=> {
226 306 root = mkdtempSync(path.
join(
tmpdir(),
"pi-git-safe-read-"));
227 307 const clone
= path.
join(
root,
"owner",
"repo");
extensions/git-safe/index.ts
Modified 23 23 type ExtensionContext,
24 24 isToolCallEventType,
25 26 } from
"@earendil-works/pi-coding-agent";
26 27 import { Text }
from "@earendil-works/pi-tui";
27 28 import { Type }
from "typebox";
227 228 if ((result
as any).isError
|| !details?.url) {
228 229 const content
= result.
content[
0];
229 230 const msg
= content?.
type === "text" ? content.
text : "Clone failed";
230 - const lines
= msg.
split(
"\n").
slice(
0,
4);
231 + const lines
= msg.
split(
"\n");
232 + const firstLine
= lines[
0]
?? "Clone failed";
234 + firstLine.
length > 160 ? `${firstLine.slice(0, 159)}…` : firstLine;
231 235 let text
= theme.
fg(
"error",
"✗ ");
232 - text
+= lines.
map((l)
=> theme.
fg(
"error", l)).
join(
"\n ");
237 + ? lines.
map((line)
=> theme.
fg(
"error", line)).
join(
"\n ")
238 + : theme.
fg(
"error", summary);
239 + if (
!expanded
&& (lines.
length > 1 || summary
!== firstLine))
240 + text
+= `\n ${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
233 241 return new Text(text,
0,
0);
254 - if (expanded
&& details.warnings?.
length > 0) {
255 - for (
const w
of details.warnings) {
256 - text
+= `\n ${theme.fg("warning", "⚠")} ${theme.fg("dim", w)}`;
262 + if (details.warnings?.
length > 0) {
264 + for (
const w
of details.warnings) {
265 + text
+= `\n ${theme.fg("warning", "⚠")} ${theme.fg("dim", w)}`;
268 + text
+= `\n ${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
extensions/intellij/__tests__/harness.test.ts
Modified556 556 expect(collapsed).not.
toContain(
"Nullable result");
557 557 expect(expanded).
toContain(
"WARNING src/Main.java:7:2");
558 558 expect(expanded).
toContain(
"Nullable result is unchecked");
564 + text:
"IntelliJ progress: indexing END-PROGRESS-DIAGNOSTIC",
567 + details: { source:
"intellij", tool:
"get_file_problems" },
569 + const collapsedProgress
= definition
572 + { expanded:
false, isPartial:
true }
as never,
578 + const expandedProgress
= definition
581 + { expanded:
true, isPartial:
true }
as never,
587 + expect(collapsedProgress).
toContain(
"to expand");
588 + expect(collapsedProgress).not.
toContain(
"END-PROGRESS-DIAGNOSTIC");
589 + expect(expandedProgress).
toContain(
"END-PROGRESS-DIAGNOSTIC");
561 592 it(
"deactivates the live catalog before rejecting a replacement URL",
async ()
=> {
extensions/intellij/implementation.ts
Modified1357 1357 (context.lastComponent
as Text | undefined)
?? new Text(
"",
0,
0);
1358 1358 const bridgeResult
= result
as BridgeResult;
1359 1359 if (isPartial) {
1360 - const progress
= short(
1361 - firstText(bridgeResult).
replace(
/^IntelliJ progress:\s*/,
""),
1360 + const progress
= firstText(bridgeResult).
replace(
1361 + /^IntelliJ progress:\s*/,
1364 - component.
setText(theme.
fg(
"warning",
`… ${progress || "working"}`));
1364 + let text
= theme.
fg(
1366 + expanded
? `… ${progress || "working"}` : "… working",
1368 + if (
!expanded
&& progress)
1369 + text
+= ` ${theme.fg("dim", `(${keyHint("app.tools.expand", "to expand")})`)}`;
1370 + component.
setText(text);
1365 1371 return component;
1367 1373 const summary
= resultSummary(tool.
name, bridgeResult, context.isError);
extensions/the-system/__tests__/artifact-slot-tool.test.ts
Modified116 116 assert.
match(expanded,
/title Replace cache invalidation/);
117 117 assert.
ok(expanded.
includes(
`path ${slot.path}`));
119 + const errorResult
= {
121 + { type:
"text", text:
"reservation failed\nEND-RESERVATION-DETAILS" },
119 125 const error
= render(
120 126 tool.
renderResult(
121 - { content: [{ type:
"text", text:
"reservation failed" }] },
122 128 { expanded:
false, isPartial:
false },
124 130 {
...renderContext(
false), isError:
true }
as never,
127 - assert.
equal(error.
trimEnd(),
"reservation failed");
133 + const expandedError
= render(
136 + { expanded:
true, isPartial:
false },
138 + {
...renderContext(
true), isError:
true }
as never,
141 + assert.
match(error,
/^reservation failed/);
142 + assert.
match(error,
/to expand/);
143 + assert.
doesNotMatch(error,
/END-RESERVATION-DETAILS/);
144 + assert.
match(expandedError,
/END-RESERVATION-DETAILS/);
extensions/the-system/__tests__/board-runtime.test.ts
Modified 95 95 assert.
equal(empty.
trimEnd(),
"✓ no changes proposed");
97 + const errorResult
= {
99 + { type:
"text", text:
"proposal failed\nEND-PROPOSAL-DETAILS" },
97 102 const error
= render(
98 103 tool.
renderResult(
99 - { content: [{ type:
"text", text:
"proposal failed" }] },
100 105 { expanded:
false, isPartial:
false },
102 107 {
...renderContext(
false), isError:
true }
as never,
105 - assert.
equal(error.
trimEnd(),
"proposal failed");
110 + const expandedError
= render(
113 + { expanded:
true, isPartial:
false },
115 + {
...renderContext(
true), isError:
true }
as never,
118 + assert.
match(error,
/^proposal failed/);
119 + assert.
match(error,
/to expand/);
120 + assert.
doesNotMatch(error,
/END-PROPOSAL-DETAILS/);
121 + assert.
match(expandedError,
/END-PROPOSAL-DETAILS/);
extensions/the-system/__tests__/mockup-tool.test.ts
Modified204 204 assert.
match(accepted,
/^✓ accepted · selected none · 0 annotations/);
206 + const errorResult
= {
207 + content: [{ type:
"text", text:
"browser failed\nEND-BROWSER-DETAILS" }],
206 210 const error
= rendered(
207 211 tool.
renderResult(
208 - { content: [{ type:
"text", text:
"browser failed" }] },
209 213 { expanded:
false, isPartial:
false },
211 215 {
...renderContext(
false), isError:
true }
as never,
214 - assert.
strictEqual(error.
trimEnd(),
"browser failed");
218 + const expandedError
= rendered(
221 + { expanded:
true, isPartial:
false },
223 + {
...renderContext(
true), isError:
true }
as never,
226 + assert.
match(error,
/^browser failed/);
227 + assert.
match(error,
/to expand/);
228 + assert.
doesNotMatch(error,
/END-BROWSER-DETAILS/);
229 + assert.
match(expandedError,
/END-BROWSER-DETAILS/);
extensions/the-system/artifact-slot-tool.ts
Modified 3 3 import { StringEnum }
from "@earendil-works/pi-ai";
4 4 import { defineTool, keyHint }
from "@earendil-works/pi-coding-agent";
5 5 import { Text }
from "@earendil-works/pi-tui";
6 6 import { Type }
from "typebox";
7 7 import type { ArtifactSlot }
from "./artifact-slot.js";
8 +import { expandableFallback }
from "./tool-rendering.js";
10 11 "Reserve a unique System document ID and canonical bundle path from its type and semantic title.";
42 43 (context.lastComponent
as Text | undefined)
?? new Text(
"",
0,
0);
43 44 const slot
= result.details
as ArtifactSlot | undefined;
45 - const output
= result.
content 47 - (item)
: item
is { type:
"text"; text: string }
=> 48 - item.
type === "text",
50 - .
map((item)
=> item.
text)
52 - text.
setText(theme.
fg(context.isError
? "error" : "muted", output));
48 + typeof slot.
id !== "string" || 49 + typeof slot.slug
!== "string" || 50 + typeof slot.path
!== "string" 57 + context.isError
? "error" : "muted",
55 62 let output
= `${theme.fg("success", "✓ reserved")} ${theme.fg("accent", slot.id)}${theme.fg("dim", ` · ${bounded(slot.slug, 40)}`)}`;
extensions/the-system/board-runtime.ts
Modified 6 6 import { type BoardProposal, readBoardState }
from "./board-state.ts";
7 7 import { discoverProjectRoot }
from "./documents.ts";
8 8 import { loadProjectIndex }
from "./project-index.ts";
9 +import { expandableFallback }
from "./tool-rendering.ts";
10 11 const STATES
= [
"todo",
"done",
"open"]
as const;
11 12 const proposalParameters
= Type.
Object({
61 62 text.
setText(output);
64 - renderResult(result, _options, theme, context) {
65 + renderResult(result, { expanded }, theme, context) {
66 67 (context.lastComponent
as Text | undefined)
?? new Text(
"",
0,
0);
67 68 const items
= (result.details
as { items
?: BoardProposal[] }
| undefined)
70 - const output
= result.
content 72 - (item)
: item
is { type:
"text"; text: string }
=> 73 - item.
type === "text",
75 - .
map((item)
=> item.
text)
77 - text.
setText(theme.
fg(context.isError
? "error" : "muted", output));
76 + context.isError
? "error" : "muted",
80 81 const count
= items.
length;
extensions/the-system/mockup-tool.ts
Modified 25 25 validateMockupRequest,
26 26 } from
"./mockup.js";
27 +import { expandableFallback }
from "./tool-rendering.js";
28 29 const DESCRIPTION
= 29 30 "Show HTML-fragment mockups in a browser for visual review. Returns accept or iterate, selected option IDs, notes, and annotations.";
178 179 (context.lastComponent
as Text | undefined)
?? new Text(
"",
0,
0);
179 180 const details
= result.details
as Partial<
MockupToolDetails>
| undefined;
181 - const output
= result.
content 183 - (item)
: item
is { type:
"text"; text: string }
=> 184 - item.
type === "text",
186 - .
map((item)
=> item.
text)
188 - text.
setText(theme.
fg(context.isError
? "error" : "muted", output));
181 + if (context.isError
|| !details) {
183 + expandableFallback(
187 + context.isError
? "error" : "muted",
191 192 const action
= details.
action ?? "submitted";
extensions/the-system/tool-rendering.ts
Addednew file mode 100644 1 +import { keyHint }
from "@earendil-works/pi-coding-agent";
3 +interface TextContent {
8 +interface RenderTheme {
9 + fg(style
: string, text
: string)
: string;
12 +export function expandableFallback(
13 + content
: TextContent[],
16 + style
: "error" | "muted",
18 + const full
= content
20 + (item)
: item
is TextContent & { text
: string }
=> 21 + item.
type === "text" && typeof item.
text === "string",
23 + .
map((item)
=> item.
text)
26 + if (expanded)
return theme.
fg(style, full);
28 + const firstLine
= full.
split(
/\r?\n/,
1)[
0]
?? "";
29 + const normalized
= firstLine.
replace(
/\s+/g,
" ").
trim();
31 + normalized.
length > 160 ? `${normalized.slice(0, 159)}…` : normalized;
32 + let output
= theme.
fg(style, summary);
33 + if (full
!== firstLine
|| summary
!== normalized)
34 + output
+= `\n${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
extensions/tune/__tests__/harness.test.ts
Modified 1 1 import * as fs
from "node:fs";
2 2 import path
from "node:path";
3 +import { initTheme }
from "@earendil-works/pi-coding-agent";
7 8 import { afterEach, describe, expect, it }
from "vitest";
8 9 import { __test }
from "../index.ts";
13 + fg: (_style
: string, text
: string)
=> text,
14 + bold: (text
: string)
=> text,
18 +function render(component
: {
render(width
: number)
: string[] })
: string {
19 + return component.
render(
120).
join(
"\n");
10 22 describe(
"tune pi-test-harness", ()
=> {
11 23 let t
: TestSession | undefined;
40 52 expect(t.session.extensionRunner.extensions[
0].path).
toBe(extensionPath);
55 + it(
"keeps initialization details compact until expanded",
async ()
=> {
56 + initTheme(
"default",
false);
57 + const extensionPath
= path.
resolve(
import.
meta.dirname,
"../index.ts");
58 + t
= await createTestSession({ extensions: [extensionPath] });
60 + t.session.extensionRunner.extensions[
0].tools.
get(
67 + text:
"Experiment initialized\nMetric: score\nEND-INIT-DETAILS",
71 + const collapsed
= render(
72 + tool.
renderResult(result, { expanded:
false },
theme()),
74 + const expanded
= render(
75 + tool.
renderResult(result, { expanded:
true },
theme()),
77 + expect(collapsed).
toContain(
"to expand");
78 + expect(collapsed).not.
toContain(
"END-INIT-DETAILS");
79 + expect(expanded).
toContain(
"END-INIT-DETAILS");
43 82 it(
"exposes and runs the fixed benchmark without a command",
async ()
=> {
83 + initTheme(
"default",
false);
44 84 const extension
= await activeTune();
45 85 const tool
= extension.tools.
get(
"run_experiment").definition;
46 86 expect(tool.parameters.properties).not.
toHaveProperty(
"command");
64 104 parsedMetrics: {
score:
42,
bytes_kb:
7 },
66 106 expect(result.
content[
0].
text).
toContain(
"stderr");
108 + const collapsed
= render(
109 + tool.
renderResult(result, { expanded:
false },
theme()),
111 + const expanded
= render(
112 + tool.
renderResult(result, { expanded:
true },
theme()),
114 + expect(collapsed).
toContain(
"to expand");
115 + expect(collapsed).not.
toContain(
"Parsed metrics:");
116 + expect(collapsed).not.
toContain(
"stderr");
117 + expect(expanded).
toContain(
"Parsed metrics:");
118 + expect(expanded).
toContain(
"stderr");
119 + expect(expanded).not.
toContain(
"to expand");
121 + const partialResult
= {
122 + content: [{ type:
"text", text:
"live stderr marker" }],
123 + details: { elapsed:
"0.4s" },
125 + const collapsedPartial
= render(
128 + { expanded:
false, isPartial:
true },
132 + const expandedPartial
= render(
135 + { expanded:
true, isPartial:
true },
139 + expect(collapsedPartial).
toContain(
"to expand");
140 + expect(collapsedPartial).not.
toContain(
"live stderr marker");
141 + expect(expandedPartial).
toContain(
"live stderr marker");
144 + it(
"expands the complete log result",
async ()
=> {
145 + initTheme(
"default",
false);
146 + const extension
= await activeTune();
147 + const tool
= extension.tools.
get(
"log_experiment").definition;
148 + const result
= await tool.
execute(
154 + description:
`renderer contract\n${"detail ".repeat(30)}END-DESCRIPTION`,
156 + new AbortController().signal,
158 + t.session.extensionRunner.
createContext(),
161 + const collapsed
= render(
162 + tool.
renderResult(result, { expanded:
false },
theme()),
164 + const expanded
= render(
165 + tool.
renderResult(result, { expanded:
true },
theme()),
167 + expect(collapsed).
toContain(
"to expand");
168 + expect(collapsed).not.
toContain(
"Logged #1");
169 + expect(collapsed).not.
toContain(
"END-DESCRIPTION");
170 + expect(expanded).
toContain(
"Logged #1");
171 + expect(expanded).
toContain(
"END-DESCRIPTION");
172 + expect(expanded).not.
toContain(
"to expand");
178 + text:
`Cannot keep because checks failed\n${"diagnostic ".repeat(30)}END-CHECKS`,
183 + const collapsedRejection
= render(
184 + tool.
renderResult(rejected, { expanded:
false },
theme()),
186 + const expandedRejection
= render(
187 + tool.
renderResult(rejected, { expanded:
true },
theme()),
189 + expect(collapsedRejection).
toContain(
"to expand");
190 + expect(collapsedRejection).not.
toContain(
"END-CHECKS");
191 + expect(expandedRejection).
toContain(
"END-CHECKS");
69 194 it(
"fails before launch when benchmark.mjs is missing",
async ()
=> {
78 203 t.session.extensionRunner.
createContext(),
80 205 expect(result.
content[
0].
text).
toContain(
"Create .pi/tune/benchmark.mjs");
206 + const rendered
= render(
208 + .
get(
"run_experiment")
209 + .definition.
renderResult(result, { expanded:
false },
theme()),
211 + expect(rendered).
toContain(
"Create .pi/tune/benchmark.mjs");
83 214 it(
"runs checks with Pi's Node executable",
async ()
=> {
extensions/tune/index.ts
Modified 30 31 } from
"@earendil-works/pi-coding-agent";
781 782 return truncateToWidth(text, width,
"…",
true);
785 +function compactDisplayText(text
: string, width
= 120)
: string {
786 + return truncateDisplayText(text.
replace(
/\s+/g,
" ").
trim(), width);
789 +function expandableText(
793 + style
: "error" | "muted" | "success" = "muted",
795 + const full
= text.
trim();
796 + if (expanded)
return new Text(theme.
fg(style, full),
0,
0);
797 + const firstLine
= full.
split(
/\r?\n/,
1)[
0]
?? "";
798 + const summary
= compactDisplayText(firstLine);
799 + let output
= theme.
fg(style, summary);
800 + if (full
!== firstLine
|| summary
!== firstLine)
801 + output
+= `\n${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
802 + return new Text(output,
0,
0);
784 805 function joinPartsToWidth(parts
: string[], width
: number)
: string {
786 807 for (
const part
of parts) {
2017 - renderResult(result, _options, _theme) {
2038 + renderResult(result, { expanded }, theme) {
2018 2039 const t
= result.
content[
0];
2019 - return new Text(t?.
type === "text" ? t.
text : "",
0,
0);
2040 + return expandableText(
2041 + t?.
type === "text" ? t.
text : "",
2044 + (result
as { isError
?: boolean }).isError
? "error" : "success",
2408 2434 renderResult(result, { expanded, isPartial }, theme) {
2409 - const PREVIEW_LINES
= 5;
2435 + const resultText
= 2436 + result.
content[
0]?.
type === "text" ? result.
content[
0].
text : "";
2437 + const expansionHint = ()
=> 2438 + `\n${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
2411 2440 if (isPartial) {
2412 2441 const d
= result.details as
2413 2442 | { phase
?: string; elapsed
?: string }
2415 2444 const elapsed
= d?.elapsed
?? "";
2416 - const outputText
= 2417 - result.
content[
0]?.
type === "text" ? result.
content[
0].
text : "";
2418 2445 let text
= theme.
fg(
2420 2447 `⏳ Running${elapsed ? ` ${elapsed}` : ""}…`,
2423 - const lines
= outputText.
split(
"\n");
2424 - const maxLines
= expanded
? 20 : PREVIEW_LINES;
2425 - const tail
= lines.
slice(
-maxLines).
join(
"\n");
2426 - if (tail.
trim()) text
+= "\n" + theme.
fg(
"dim", tail);
2449 + if (resultText.
trim()) {
2451 + const tail
= resultText.
split(
"\n").
slice(
-20).
join(
"\n");
2452 + text
+= "\n" + theme.
fg(
"dim", tail);
2454 + text
+= expansionHint();
2428 2457 return new Text(text,
0,
0);
2431 2460 const d
= result.details as
2432 2461 | (RunDetails
& { truncation?: any; fullOutputPath
?: string })
2435 - const t
= result.
content[
0];
2436 - return new Text(t?.
type === "text" ? t.
text : "",
0,
0);
2463 + if (
!d
|| typeof d.durationSeconds
!== "number")
2464 + return expandableText(
2468 + (result
as { isError
?: boolean }).isError
? "error" : "muted",
2439 - const appendOutput = (text
: string, output
: string)
: string => {
2440 - if (
!output)
return text;
2441 - const lines
= output.
split(
"\n");
2443 - text
+= "\n" + theme.
fg(
"dim", output.
slice(
-2000));
2445 - const tail
= lines.
slice(
-PREVIEW_LINES).
join(
"\n");
2446 - if (tail.
trim()) {
2447 - const hidden
= lines.
length - PREVIEW_LINES;
2449 - text
+= "\n" + theme.
fg(
"muted",
`… ${hidden} more lines`);
2450 - text
+= "\n" + theme.
fg(
"dim", tail);
2471 + const appendOutput = (text
: string)
: string => {
2472 + if (
!resultText.
trim())
return text;
2474 + ? text
+ "\n" + theme.
fg(
"dim", resultText)
2475 + : text
+ expansionHint();
2456 2478 if (d.timedOut) {
2457 2479 return new Text(
2459 2481 theme.
fg(
"error",
`⏰ TIMEOUT ${d.durationSeconds.toFixed(1)}s`),
2475 2496 if (d.checksTimedOut) {
2476 2497 return new Text(
2477 - theme.
fg(
"success",
`✅ wall: ${d.durationSeconds.toFixed(1)}s`)
+ 2481 - ` ⏰ checks timeout ${d.checksDuration.toFixed(1)}s`,
2499 + theme.
fg(
"success",
`✅ wall: ${d.durationSeconds.toFixed(1)}s`)
+ 2503 + ` ⏰ checks timeout ${d.checksDuration.toFixed(1)}s`,
2488 2511 if (d.checksPass
=== false) {
2489 2512 return new Text(
2490 - theme.
fg(
"success",
`✅ wall: ${d.durationSeconds.toFixed(1)}s`)
+ 2494 - ` 💥 checks failed ${d.checksDuration.toFixed(1)}s`,
2514 + theme.
fg(
"success",
`✅ wall: ${d.durationSeconds.toFixed(1)}s`)
+ 2518 + ` 💥 checks failed ${d.checksDuration.toFixed(1)}s`,
2506 2531 `💥 FAIL exit=${d.exitCode} ${d.durationSeconds.toFixed(1)}s`,
2507 2532 )
+ parsedSuffix,
2525 2549 ` ✓ checks ${d.checksDuration.toFixed(1)}s`,
2528 - text
= appendOutput(text, d.tailOutput);
2552 + text
= appendOutput(text);
2529 2553 return new Text(text,
0,
0);
2820 2844 theme.
fg(
"toolTitle", theme.
bold(
"log_experiment "))
+ 2821 2845 theme.
fg(color, args.
status)
+ 2823 - theme.
fg(
"dim", args.
description),
2847 + theme.
fg(
"dim",
compactDisplayText(
String(args.
description ?? ""))),
2829 - renderResult(result, _options, theme) {
2853 + renderResult(result, { expanded }, theme) {
2830 2854 const d
= result.details
as LogDetails | undefined;
2855 + if (
!d?.experiment
|| !d.state) {
2832 2856 const t
= result.
content[
0];
2833 - return new Text(t?.
type === "text" ? t.
text : "",
0,
0);
2857 + return expandableText(
2858 + t?.
type === "text" ? t.
text : "",
2836 2865 const { experiment: exp, state: s }
= d;
2867 2896 theme.
fg(
"dim",
")");
2870 - text
+= " " + theme.
fg(
"muted", exp.
description);
2899 + text
+= " " + theme.
fg(
"muted",
compactDisplayText(exp.
description));
2872 2901 if (s.bestMetric
!== null) {
2873 2902 let best
= s.bestMetric;
2894 2923 text
+= theme.
fg(
"dim",
` ${parts.join(" ")}`);
2926 + const contentText
= 2927 + result.
content[
0]?.
type === "text" ? result.
content[
0].
text : "";
2928 + if (contentText.
trim()) {
2930 + ? `\n${theme.fg("dim", contentText)}` 2931 + : `\n${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
2897 2934 return new Text(text,
0,
0);
extensions/tune/mise.toml
Modified 2 +description =
"Format tune extension" 3 +depends = [
"//:install"]
5 + "biome check --write --config-path ../.. .",
6 + "rumdl fmt --config ../../.rumdl.toml .",
7 + "taplo format --config ../../.taplo.toml mise.toml",
2 11 description =
"Run tune dashboard browser E2E tests" 3 12 depends = [
"//:install"]
extensions/ultra/__tests__/call.test.ts
Modified 95 95 expect(text).
toContain(
"2 phases received · no agents running");
96 96 expect(text).
toContain(
"inspect · fanout · 3 items received · small");
97 97 expect(text).
toContain(
"Consolidate verified findings");
98 - expect(text).
toContain(
"Prompt tail · synthesize");
99 - expect(text).
toContain(
"Combine independent findings. Preserve evidence.▎");
98 + expect(text).not.
toContain(
"Prompt tail · synthesize");
99 + expect(text).not.
toContain(
100 + "Combine independent findings. Preserve evidence.",
100 102 expect(text).not.
toContain(
"0/0 done");
101 103 expect(text).not.
toContain(
"FIRST-PROMPT");
104 - it(
"follows arriving prompt chunks immediately and never schedules animation", ()
=> {
106 + it(
"keeps arriving prompt chunks expansion-only and never schedules animation", ()
=> {
105 107 const interval
= vi.
spyOn(globalThis,
"setInterval");
106 108 const timeout
= vi.
spyOn(globalThis,
"setTimeout");
108 110 const args
= { spec: { phases: [{ step: { prompt:
"Inspect" } }] } };
109 - expect(
lines(args).
join(
"\n")).
toContain(
"Inspect▎");
111 + expect(
lines(args).
join(
"\n")).not.
toContain(
"Inspect");
112 + expect(
lines(args, {
...drafting, expanded:
true }).
join(
"\n")).
toContain(
110 115 args.spec.phases[
0].step.
prompt += " authentication";
111 - const component
= renderUltraCall(args, theme, drafting);
116 + const component
= renderUltraCall(args, theme, {
112 120 expect(component.
render(
80).
join(
"\n")).
toContain(
113 - "Inspect authentication▎",
121 + "Inspect authentication",
115 123 component.
invalidate();
116 124 expect(component.
render(
80)).
toEqual(component.
render(
80));
202 210 expect(
screen(row)).
toContain(
"FIRST-PROMPT");
205 - it(
"bounds collapsed phases and prompt tails even on very wide terminals", ()
=> {
213 + it(
"bounds collapsed phases and keeps prompt bodies expansion-only", ()
=> {
206 214 const phases
= Array.
from({ length:
20 }, (_, index)
=> ({
207 215 id:
`phase_${index}`,
219 227 expect(text).not.
toContain(
"Summary 16");
220 228 expect(text).
toContain(
"Summary 17");
221 229 expect(text).
toContain(
"Summary 19");
222 - expect(text).
toContain(
"LATEST-TAIL▎");
230 + expect(text).not.
toContain(
"LATEST-TAIL");
223 231 expect(text).not.
toContain(
"OLD-PROMPT");
224 232 expect(text).
toContain(
"to expand");
225 233 const expanded
= lines(
230 238 expect(expanded).
toContain(
"Summary 0");
231 239 expect(expanded).
toContain(
"OLD-PROMPT-0");
232 240 expect(expanded).
toContain(
"OLD-PROMPT-19");
241 + expect(expanded).
toContain(
"LATEST-TAIL");
235 244 it(
"labels dynamic and conditional fanouts without evaluating selectors", ()
=> {
extensions/ultra/call.ts
Modified139 - if (
!options.expanded
&& !started) {
140 - for (
let index
= phases.
length - 1; index
>= 0; index
--) {
141 - const phase
= record(phases[index]);
142 - const prompt
= record(phase?.step)?.
prompt;
143 - if (
typeof prompt
!== "string" || !prompt)
continue;
145 - ` Prompt tail · ${line(phase?.id) || `phase ${index + 1}`} · ${prompt.length} chars received`,
149 - const tail
= plain(prompt.
slice(
-Math.
max(
256, w
* 4)));
150 - const cursor
= receiving
? "▎" : "";
151 - const lines
= wrapTextWithAnsi(
153 - Math.
max(
1, w
- 3),
155 - for (
const text
of lines)
add(
` ${text}`,
"toolOutput");
159 139 if (options.expanded
&& line(spec?.return))
160 140 block(
`return: ${line(spec?.return)}`);
161 141 if (
!options.expanded
&& phases.
length > 0)
extensions/web/__tests__/harness.test.ts
Modified384 384 const expanded
= renderToolResult(tool,
"search", result,
true);
385 385 expect(collapsed).
toContain(
"1 result");
386 386 expect(collapsed).
toContain(
"codex");
387 + expect(collapsed).
toContain(
"to expand");
387 388 expect(collapsed).not.
toContain(
"Quick Select Mode");
388 389 expect(expanded).
toContain(
"Quick Select Mode");
390 + expect(expanded).not.
toContain(
"to expand");
393 + it(
"reveals the saved map path only when expanded", ()
=> {
394 + const tool
= extension.tools.
get(
"web");
396 + content: [{ type:
"text", text:
"https://example.com/docs" }],
400 + responseId:
"saved-id",
401 + fullOutputPath:
"/tmp/web-map.json",
404 + const collapsed
= renderToolResult(tool,
"map", result,
false);
405 + const expanded
= renderToolResult(tool,
"map", result,
true);
406 + expect(collapsed).
toContain(
"to expand");
407 + expect(collapsed).not.
toContain(
"/tmp/web-map.json");
408 + expect(collapsed).not.
toContain(
"https://example.com/docs");
409 + expect(expanded).
toContain(
"/tmp/web-map.json");
410 + expect(expanded).
toContain(
"https://example.com/docs");
411 + expect(expanded).not.
toContain(
"to expand");
414 + it(
"keeps long errors compact until expanded", ()
=> {
415 + const tool
= extension.tools.
get(
"web").definition;
416 + const marker
= "END-OF-WEB-DIAGNOSTIC";
421 + text:
`Request failed: ${"detail ".repeat(40)}${marker}`,
425 + const collapsed
= renderLines(
426 + tool.
renderResult(result, { expanded:
false },
theme(), {
427 + args: { action:
"search" },
431 + const expanded
= renderLines(
432 + tool.
renderResult(result, { expanded:
true },
theme(), {
433 + args: { action:
"search" },
437 + expect(collapsed).
toContain(
"to expand");
438 + expect(collapsed).not.
toContain(marker);
439 + expect(expanded).
toContain(marker);
extensions/web/index.ts
Modified 710 710 return new Text(theme.
fg(style,
safeDisplayText(msg)),
0,
0);
713 +function expandableError(
714 + theme
: {
fg: (
...a
: any[])
=> string },
718 + const full
= safeTerminalText(msg).
trim();
719 + if (expanded)
return new Text(theme.
fg(
"error", full),
0,
0);
720 + const summary
= safeDisplayText(full);
721 + const clipped
= summary.
length > 160 ? `${summary.slice(0, 159)}…` : summary;
722 + let text
= theme.
fg(
"error", clipped);
723 + if (clipped
!== summary)
724 + text
+= `\n${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
725 + return new Text(text,
0,
0);
714 729 function errorMsg(result
: any, fallback
: string)
: string {
840 855 if ((result
as any).isError
|| details?.kind
=== "error") {
841 856 const content
= result.
content[
0];
842 - const msg
= safeDisplayText(
843 858 details?.error
|| 844 - (content?.
type === "text" ? content.
text : "Fetch failed"),
846 - return hintBox(theme,
"error",
`\u2717 ${msg}`);
859 + (content?.
type === "text" ? content.
text : "Fetch failed");
860 + return expandableError(theme,
`\u2717 ${msg}`, expanded);
849 863 const kind
= details?.kind
?? "text";
1182 1196 if ((result.details
as { kind
?: string }
| undefined)?.kind
=== "error") {
1183 1197 const content
= result.
content[
0];
1184 1198 const msg
= content?.
type === "text" ? content.
text : "Map failed";
1185 - return hintBox(theme,
"error",
`✗ ${safeDisplayText(msg)}`);
1199 + return expandableError(theme,
`✗ ${msg}`, expanded);
1187 1201 let text
= theme.
fg(
"success",
"✓ ");
1188 1202 text
+= theme.
fg(
"accent",
`${details?.urlCount ?? 0} URL(s)`);
1193 1207 if (details?.responseId)
1194 1208 text
+= theme.
fg(
"dim",
` · saved ${details.responseId}`);
1195 - if (expanded
&& details?.fullOutputPath) {
1196 - text
+= `\n ${theme.fg("muted", "full:")} ${theme.fg("dim", details.fullOutputPath)}`;
1209 + const content
= result.
content[
0];
1210 + const hasDetails
= 1211 + (content?.
type === "text" && !!content.
text?.
trim())
|| 1212 + !!details?.fullOutputPath;
1214 + if (details?.fullOutputPath)
1215 + text
+= `\n ${theme.fg("muted", "full:")} ${theme.fg("dim", details.fullOutputPath)}`;
1216 + const rendered
= expandedText(result, text, theme);
1217 + if (rendered
!== null) text
= rendered;
1218 + }
else if (hasDetails) {
1219 + text
+= `\n ${theme.fg("muted", "↳")} ${keyHint("app.tools.expand", "to expand")}`;
1198 1221 return new Text(text,
0,
0);
1295 1318 if ((result
as any).isError
|| (result.details
as any)?.error) {
1319 + return expandableError(
1299 1321 `\u2717 ${errorMsg(result, "Search failed")}`,
1317 1340 if (details?.
source)
1318 1341 text
+= ` ${theme.fg("muted", `(${details.source})`)}`;
1319 - if (resultCount
> 0)
1342 + if (
!expanded
&& resultCount
> 0)
1320 1343 text
+= ` ${theme.fg("muted", `(${keyHint("app.tools.expand", "to expand")})`)}`;
1321 1344 return new Text(text,
0,
0);
1471 1494 renderResult(result, options, theme, context) {
1472 1495 if (context.isError)
1473 - return hintBox(theme,
"error",
errorMsg(result,
"Web request failed"));
1496 + return expandableError(
1498 + errorMsg(result,
"Web request failed"),
1474 1501 const action
= context.args.
action as keyof typeof actions;
1475 1502 if (
Object.
hasOwn(actions, action))
1476 1503 return actions[action].
renderResult(result, options, theme);