@notrico/pi-fold 3.0.1 → 3.0.3
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 +9 -0
- package/docs/renderer-reference.md +4 -2
- package/package.json +1 -1
- package/scripts/preview-actions.mjs +9 -0
- package/scripts/preview-work-strip.mjs +22 -1
- package/scripts/preview.mjs +3 -1
- package/scripts/test.mjs +1 -0
- package/src/modern-code-content.ts +8 -1
- package/src/modern-code-pane.ts +15 -3
- package/src/modern-tool-pane.ts +10 -6
- package/src/modern-tools.ts +35 -6
- package/src/permission-presentation.ts +12 -6
- package/tests/action-group-preview.test.mjs +43 -0
- package/tests/codemode.test.mjs +8 -6
- package/tests/fold-shortcut.test.mjs +1 -1
- package/tests/inspection-wheel.test.mjs +7 -5
- package/tests/mixed-action-groups.test.mjs +201 -0
- package/tests/permission-presentation.test.mjs +15 -2
- package/tests/preview-example.test.mjs +1 -1
- package/tests/reload-lifecycle.test.mjs +5 -5
- package/tests/test-runtime.mjs +3 -1
- package/tests/work-strip-preview.test.mjs +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Release notes
|
|
2
2
|
|
|
3
|
+
## 3.0.3 — Approval layout
|
|
4
|
+
|
|
5
|
+
- Match approval dialogs to the quieter prompt layout: add spacing around the content and choices, mute keyboard hints, and fill only the selected choice. Keep approval decisions and Details controls unchanged.
|
|
6
|
+
|
|
7
|
+
## 3.0.2 — Mixed action groups
|
|
8
|
+
|
|
9
|
+
- Group successful completed codemode calls with adjacent bash and file actions. Count each outer call once and retain nested source, calls, and output on expansion.
|
|
10
|
+
- Keep running calls, failures, nested warnings, images, and unsupported records separate. Preserve visible conversation boundaries and native display when folding is disabled.
|
|
11
|
+
|
|
3
12
|
## 3.0.1 — Inspection paging and final thinking
|
|
4
13
|
|
|
5
14
|
- Make `more ↓` advance expanded tool, codemode, workflow, and thinking panes by one visible page. Preserve prompt typing after mouse inspection.
|
|
@@ -19,13 +19,13 @@ pi remove git:github.com/rrrrrrrrrricoxi/pi-fold@v3.0.0
|
|
|
19
19
|
## Display
|
|
20
20
|
|
|
21
21
|
- Questions use a bold purple heading, aligned with ordinary action headings, without a background or vertical rail. Recorded answers use a green checkmark inline with the options. Ordinary action headings stay blue. The `codemode` label uses native teal (`syntaxVariable`), while counts and timing stay muted; handled nested problems retain warning color; thinking headings stay muted and failures stay red. Expanded content remains unfilled. Keyboard focus has its own selection highlight. User prompts keep their blue surface. Subagent transcript activity uses the same compact headings and inspection controls.
|
|
22
|
-
- Running actions remain separate.
|
|
22
|
+
- Running actions remain separate. Successful completed bash, file, and codemode calls can share one action group within visible conversation boundaries. Each outer codemode call counts as one action; nested calls stay inside its inspectable content. Nested errors, cancellations, unresolved calls, images, and unsupported codemode records stay separate. Pure thinking does not split an action group; visible assistant replies and user messages do.
|
|
23
23
|
- Successful group headings use “4 actions”; singleton headings show only the operation. Shell interpreter scripts use labels such as “Run Node.js script,” with a literal script filename when reliably available. Inline source stays in Arguments. Known errors show a short category such as “Path too long”; exact errors stay in Output/Details. Labels describe recorded operations and do not infer a script’s purpose.
|
|
24
24
|
- Expanded source and diffs use Pi’s syntax colors. Recorded thinking and Markdown files use bounded Markdown rendering; shell stdout and unknown text remain literal. Formatting reads at most 2,048 source characters per block. Markdown uses one source line per block, so multiline tables, paragraphs, and cross-line inline formatting are not fully reconstructed. Very long code blocks can lose lexer context at block boundaries. The original recorded source remains unchanged.
|
|
25
25
|
- A single-action card opens directly to useful content without repeating a numbered action row. Successful native `write` actions show submitted content with syntax colors from the path. Only the exact standard acknowledgement is moved under Details. Reads and unknown tools keep their output visible. Known ordinary-tool OS diagnostics can show a short code/category while Details retains the exact error; unknown/custom failures keep full visible output. Status marks follow the title.
|
|
26
26
|
- Open a group to see tightly stacked actions without blank rows between siblings. Several actions and their inline Details can remain expanded independently in the same scrollable pane. Details contains exact arguments, secondary diagnostics, and any acknowledgement/error moved from the main content. Short scalar fields share a line; null and empty values remain explicit. Empty diagnostic objects do not add a section.
|
|
27
27
|
- Errors, cancellations, unanswered questions, and background notices stay separate. Expanded question cards show the full question, nonempty context, and tight option rows with descriptions inline. A checkmark, native success color, and bold text mark recorded selections; custom or unmatched answers remain visible on their own marked row. Only answered records receive answer marks. Other states appear once in the header, with meaningful diagnostics retained; the exact standard cancellation message is omitted. Question cards omit duplicate headings and raw Arguments/Details objects; stored transcripts retain the original data.
|
|
28
|
-
- Consecutive completed subagent guide lookups form a separate guide group, with each requested topic shown on expansion. Consecutive routine subagent calls and recognized asynchronous notices form one compact update group. Failures and pending decisions stay separate. A decision request, successful supervisor reply, and acknowledgement combine only when their explicit request identity matches within the same uninterrupted exchange. Expansion shows the question and highlights the supervisor reply; this is not attributed to the user. Visible assistant replies, user messages, unrelated decisions, errors, and other actions stop grouping. Launch acknowledgements, queued steering, decision requests, replies, and completion notices retain their recorded meanings. Decision requests use purple headings; failures use red headings. Expansion shows recorded content first; Details retains exact arguments and identifiers. Unknown notification shapes and compact mode off retain native rendering. Fleet, execution, scheduling, and steering controls remain native. codemode has its own collapsible card,
|
|
28
|
+
- Consecutive completed subagent guide lookups form a separate guide group, with each requested topic shown on expansion. Consecutive routine subagent calls and recognized asynchronous notices form one compact update group. Failures and pending decisions stay separate. A decision request, successful supervisor reply, and acknowledgement combine only when their explicit request identity matches within the same uninterrupted exchange. Expansion shows the question and highlights the supervisor reply; this is not attributed to the user. Visible assistant replies, user messages, unrelated decisions, errors, and other actions stop grouping. Launch acknowledgements, queued steering, decision requests, replies, and completion notices retain their recorded meanings. Decision requests use purple headings; failures use red headings. Expansion shows recorded content first; Details retains exact arguments and identifiers. Unknown notification shapes and compact mode off retain native rendering. Fleet, execution, scheduling, and steering controls remain native. A standalone codemode call has its own collapsible card. In a mixed action group, expand its action row to inspect the same recorded content. Its expanded body uses bounded chunks with native JavaScript colors, nested-call status colors, durations, and model cost in USD. Source, recorded call arguments/errors, output, and metadata remain scroll-accessible. Long multiline code can have different syntax colors across chunk boundaries. Shape validation and scalar call/count/cost aggregation run once per explicit update revision; they are separate from bounded viewport painting. Valid image results retain the compact codemode summary and bounded text inspection, with image counts. Image previews appear only when the compact block is expanded, using Pi's native image objects and terminal capability checks. See Inline images below. Unsupported shapes and compact mode off retain the stock native renderer. Standalone image reads stay separate and use one compact heading.
|
|
29
29
|
- Recorded thinking rounds can group across tools. Replies, questions, errors, and other visible boundaries separate groups. Each round has a short title taken from its recorded heading or first sentence and expands independently. The pane shows the full recorded text on demand; it does not generate summaries or make model calls.
|
|
30
30
|
- Recognized prompt templates show their command and authored description, or a bounded excerpt when no description is available. Expansion reveals the original text inline. Ordinary submitted prompts longer than eight rendered lines show a bounded opening and ending, separated by a muted “⋯ Show more” control. The opening stops at its first paragraph break; the ending uses the last paragraph. Long paragraphs use bounded excerpts. A blank row separates each excerpt from the control. Expansion preserves all recorded text and formatting and places “▴ Show less” at the bottom; short prompts stay open. Skill invocations share the blue prompt card, with click, `/inspect`, and native Ctrl+O expansion.
|
|
31
31
|
|
|
@@ -108,3 +108,5 @@ In compact mode, expanding an image read or image-bearing codemode reveals the r
|
|
|
108
108
|
The renderer respects Pi's show-images setting and terminal capability detection. Pi 1.3.0 supports Kitty images in compatible terminals and disables image protocols under tmux. On that route, or when images are disabled, the expanded block shows a short fallback. A direct image read retains its recorded path; Pi makes absolute paths clickable only when native hyperlink support is available. Remote paths still refer to the remote host. codemode does not invent a file path for an in-memory image.
|
|
109
109
|
|
|
110
110
|
Compact mode off preserves native image display and sizing. The image adapter is gated to Pi 1.3.0 and restores the native component's options after each compact paint. It does not alter image data, terminal settings, tmux settings, or saved transcripts.
|
|
111
|
+
|
|
112
|
+
To inspect mixed bash/codemode groups in the isolated fixture, run `node scripts/preview-actions.mjs`. The final work section includes both bash-led and codemode-led groups and a separate nested-error card. No tools or model run.
|
package/package.json
CHANGED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Recorded mixed action groups in an isolated Pi session. No tools or model run.
|
|
3
|
+
import { createWorkStripPreview } from './preview-work-strip.mjs';
|
|
4
|
+
const preview = await createWorkStripPreview({ actionGroups: true });
|
|
5
|
+
let ui;
|
|
6
|
+
try {
|
|
7
|
+
ui = new preview.core.InteractiveMode(preview.runtime, { tuiMode: 'fullscreen' });
|
|
8
|
+
await ui.run();
|
|
9
|
+
} finally { ui?.stop(); await preview.cleanup(); }
|
|
@@ -5,7 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { createPreview } from './preview.mjs';
|
|
7
7
|
|
|
8
|
-
export async function createWorkStripPreview({ stepMs = 1000, inspection = false } = {}) {
|
|
8
|
+
export async function createWorkStripPreview({ stepMs = 1000, inspection = false, actionGroups = false } = {}) {
|
|
9
9
|
const old = process.env.PI_PREVIEW_WORK_STRIP;
|
|
10
10
|
process.env.PI_PREVIEW_WORK_STRIP = '1';
|
|
11
11
|
const preview = await createPreview();
|
|
@@ -49,6 +49,27 @@ export async function createWorkStripPreview({ stepMs = 1000, inspection = false
|
|
|
49
49
|
const finalId = manager.getBranch().at(-1).id;
|
|
50
50
|
manager.appendCustomEntry('compact-renderer:work-settled:v1',{version:1,userId,finalId,endId:finalId,startedAt:base-90000,endedAt:base,outcome:'completed'});
|
|
51
51
|
}
|
|
52
|
+
if (actionGroups) {
|
|
53
|
+
manager.appendMessage({role:'user',content:'Compare mixed action groups: successful bash, codemode, and file calls belong together. Keep nested failures visible.',timestamp:Date.now()});
|
|
54
|
+
const userId = manager.getBranch().at(-1).id;
|
|
55
|
+
const recorded = (id, name, args, text, calls = []) => {
|
|
56
|
+
const call = assistant(''); call.stopReason = 'toolUse';
|
|
57
|
+
call.content = [{type:'toolCall',id,name,arguments:args}];
|
|
58
|
+
manager.appendMessage(call);
|
|
59
|
+
manager.appendMessage({role:'toolResult',toolCallId:id,toolName:name,content:[{type:'text',text}],details:name==='codemode'?{calls}:{},isError:false,durationMs:12,timestamp:Date.now()});
|
|
60
|
+
};
|
|
61
|
+
const code = (id, status = 'ok') => recorded(id, 'codemode', {code:'text(await tools.read({ path: "/fixture/units.txt" }));'}, 'Recorded units: kg/L. No file was read.', [{name:'read',args:'{"path":"/fixture/units.txt"}',status,durationMs:3,...(status==='error'?{error:'Invented missing-file warning, handled by the script.'}:{})}]);
|
|
62
|
+
recorded('mixed-bash', 'bash', {command:'printf "recorded sample"'}, 'Recorded shell output. No command ran.');
|
|
63
|
+
code('mixed-code-a'); code('mixed-code-b');
|
|
64
|
+
recorded('mixed-read', 'read', {path:'/fixture/summary.txt'}, 'Recorded summary.');
|
|
65
|
+
manager.appendMessage(assistant('The four calls above form one group. Each codemode counts once and retains its nested source, calls, and output. This reply separates the next group, which starts with codemode.'));
|
|
66
|
+
code('mixed-code-first');
|
|
67
|
+
recorded('mixed-write', 'write', {path:'/fixture/report.txt',content:'Recorded report.'}, 'Successfully wrote to /fixture/report.txt');
|
|
68
|
+
code('mixed-nested-warning', 'error');
|
|
69
|
+
manager.appendMessage(assistant('Mixed-action preview: expand the work, then the 4-action and 2-action groups. Open codemode to inspect its recorded content. The nested-error card stays separate. Test /fold collapse, Ctrl+Alt+W, /inspect, and Esc. All content is invented; no tool or model ran.'));
|
|
70
|
+
const finalId = manager.getBranch().at(-1).id;
|
|
71
|
+
manager.appendCustomEntry('compact-renderer:work-settled:v1',{version:1,userId,finalId,endId:finalId,startedAt:base-45000,endedAt:base,outcome:'completed'});
|
|
72
|
+
}
|
|
52
73
|
const emit = async event => {
|
|
53
74
|
if (stopped) return;
|
|
54
75
|
runtime.session._emit(event);
|
package/scripts/preview.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Actual Pi TUI with invented records and an isolated temporary home. No credentials or live services.
|
|
3
3
|
import fs from 'node:fs/promises';
|
|
4
4
|
import os from 'node:os';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
5
6
|
import path from 'node:path';
|
|
6
7
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
8
|
|
|
@@ -9,6 +10,7 @@ const source = fileURLToPath(new URL('../', import.meta.url));
|
|
|
9
10
|
export async function createPreview() {
|
|
10
11
|
const hostHome = os.homedir();
|
|
11
12
|
const runtimePath = path.resolve(process.env.PI_RUNTIME || path.join(hostHome, '.local/state/pi-config/current/runtime'));
|
|
13
|
+
const tuiPath = createRequire(path.join(runtimePath, 'node_modules/@earendil-works/pi-coding-agent/package.json')).resolve('@earendil-works/pi-tui');
|
|
12
14
|
const promptJump = process.env.PI_PROMPT_JUMP_PATH ? path.resolve(process.env.PI_PROMPT_JUMP_PATH) : undefined;
|
|
13
15
|
const questionCandidates = process.env.PI_QUESTIONS_PATH ? [path.resolve(process.env.PI_QUESTIONS_PATH)] : [
|
|
14
16
|
path.join(hostHome, '.local/state/pi-config/current/packages/pi-questions/index.ts'),
|
|
@@ -218,7 +220,7 @@ export async function createPreview() {
|
|
|
218
220
|
runtime = await core.createAgentSessionRuntime(factory, { cwd, agentDir, sessionManager: manager });
|
|
219
221
|
const diagnostics = runtime.services.resourceLoader.getExtensions().errors;
|
|
220
222
|
if (runtime.diagnostics.some(item => item.type === 'error') || diagnostics.length) throw new Error(JSON.stringify([...runtime.diagnostics, ...diagnostics]));
|
|
221
|
-
return { core, runtime, manager, temporary, agentDir, cwd, runtimePath, questionsPath, eventBus, cleanup };
|
|
223
|
+
return { core, runtime, manager, temporary, agentDir, cwd, runtimePath, tuiPath, questionsPath, eventBus, cleanup };
|
|
222
224
|
} catch (error) { await cleanup(); throw error; }
|
|
223
225
|
}
|
|
224
226
|
|
package/scripts/test.mjs
CHANGED
|
@@ -12,6 +12,7 @@ required.push('display-line-cache.test.mjs');
|
|
|
12
12
|
required.push('display-cache-lifecycle.test.mjs');
|
|
13
13
|
required.push('fold-command.test.mjs', 'fold-shortcut.test.mjs');
|
|
14
14
|
required.push('mixed-thinking.test.mjs', 'work-strip.test.mjs', 'work-strip-subagents.test.mjs', 'work-strip-preview.test.mjs', 'work-strip-spacing.test.mjs');
|
|
15
|
+
required.push('mixed-action-groups.test.mjs', 'action-group-preview.test.mjs');
|
|
15
16
|
for (const name of required) {
|
|
16
17
|
if (!fs.existsSync(path.join(directory, name))) throw new Error(`Missing required regression suite: ${name}`);
|
|
17
18
|
const result = spawnSync(process.execPath, [path.join(directory, name)], { cwd: directory, env: process.env, stdio: 'inherit' });
|
|
@@ -31,6 +31,8 @@ function* metadataValues(value: any, ancestors = new Set<object>()): Generator<s
|
|
|
31
31
|
* rendering visits bounded chunks and the nested calls reached by the viewport. */
|
|
32
32
|
export class CodeContent {
|
|
33
33
|
supported = true;
|
|
34
|
+
clean = true;
|
|
35
|
+
hasScriptHeader = false;
|
|
34
36
|
calls: any[] = [];
|
|
35
37
|
content: any[] = [];
|
|
36
38
|
code = "";
|
|
@@ -43,12 +45,15 @@ export class CodeContent {
|
|
|
43
45
|
private revision = -1;
|
|
44
46
|
update(args: any, result: any, revision: number) {
|
|
45
47
|
if (revision === this.revision) return false;
|
|
46
|
-
this.revision = revision; this.supported = true;
|
|
48
|
+
this.revision = revision; this.supported = true; this.clean = true; this.hasScriptHeader = false;
|
|
47
49
|
this.errors = this.cancelled = this.unresolved = this.priced = this.totalCost = this.images = 0;
|
|
48
50
|
const code = data(args, "code"), content = result ? data(result, "content") : [], details = result ? data(result, "details") : undefined;
|
|
49
51
|
const calls = details == null ? [] : data(details, "calls");
|
|
50
52
|
if (typeof code !== "string" || !Array.isArray(content) || details === missing || calls === missing || calls != null && !Array.isArray(calls)) { this.supported = false; return true; }
|
|
51
53
|
this.code = code; this.content = content; this.calls = calls ?? []; this.details = details; this.visibleContent = [];
|
|
54
|
+
const status = data(details, "status"), warning = data(details, "warning"), warnings = data(details, "warnings");
|
|
55
|
+
const hasWarnings = Array.isArray(warnings) ? warnings.length > 0 : !!warnings;
|
|
56
|
+
this.clean = !warning && !hasWarnings && (status === undefined || ["success", "ok", "completed"].includes(status));
|
|
52
57
|
for (let i = 0; i < content.length; i++) {
|
|
53
58
|
this.aggregateBlocks++;
|
|
54
59
|
const block = data(content, String(i));
|
|
@@ -56,6 +61,7 @@ export class CodeContent {
|
|
|
56
61
|
if (type === "image" && typeof data(block, "mimeType") === "string" && typeof data(block, "data") === "string") {
|
|
57
62
|
this.images++; this.visibleContent.push({ block, index: i });
|
|
58
63
|
} else if (type === "text" && typeof data(block, "text") === "string") {
|
|
64
|
+
if (i === 0) this.hasScriptHeader = data(block, "text").length < 160 && scriptHeader.test(data(block, "text"));
|
|
59
65
|
if (data(block, "text").length) this.visibleContent.push({ block, index: i });
|
|
60
66
|
} else { this.supported = false; return true; }
|
|
61
67
|
}
|
|
@@ -68,6 +74,7 @@ export class CodeContent {
|
|
|
68
74
|
if (status === "error") this.errors++;
|
|
69
75
|
if (status === "cancelled") this.cancelled++;
|
|
70
76
|
if (status === "running") this.unresolved++;
|
|
77
|
+
if (status !== "ok" || data(call, "error")) this.clean = false;
|
|
71
78
|
if (cost) { this.priced++; this.totalCost += cost; }
|
|
72
79
|
}
|
|
73
80
|
this.intent = codeIntent(args, this.calls);
|
package/src/modern-code-pane.ts
CHANGED
|
@@ -13,8 +13,10 @@ export class CodePane {
|
|
|
13
13
|
private startedAt?: number; private endedAt?: number; private interval?: ReturnType<typeof setInterval>;
|
|
14
14
|
private themeKey = "";
|
|
15
15
|
private partial = false; private isError = false; private durationMs?: number;
|
|
16
|
+
private revision = -1;
|
|
16
17
|
paintedRows = 0;
|
|
17
18
|
constructor(private height: () => number) {}
|
|
19
|
+
get duration() { return this.durationMs; }
|
|
18
20
|
get clock() { return { startedAt: this.startedAt, endedAt: this.endedAt }; }
|
|
19
21
|
adoptClock(clock: { startedAt?: number; endedAt?: number }) { this.startedAt ??= clock.startedAt; this.endedAt ??= clock.endedAt; }
|
|
20
22
|
suspend() { if (this.interval !== undefined) clearInterval(this.interval); this.interval = undefined; }
|
|
@@ -24,11 +26,14 @@ export class CodePane {
|
|
|
24
26
|
setTheme(theme: any) {
|
|
25
27
|
const tokens = ["text", "toolTitle", "toolOutput", "mdCodeBlock", "muted", "dim", "warning", "error", "success", "syntaxKeyword", "syntaxString", "syntaxComment", "syntaxNumber", "syntaxFunction", "syntaxOperator", "syntaxPunctuation", "syntaxType", "syntaxVariable", "toolDiffAdded", "toolDiffRemoved"];
|
|
26
28
|
const key = tokens.map(token => theme?.fg(token, "x") ?? "x").join("") + (theme?.bg("selectedBg", "x") ?? "x") + (theme?.bold("x") ?? "x");
|
|
27
|
-
|
|
29
|
+
const changed = key !== this.themeKey;
|
|
30
|
+
if (changed) { this.themeKey = key; this.reset(); }
|
|
28
31
|
this.theme = theme;
|
|
32
|
+
return changed;
|
|
29
33
|
}
|
|
30
34
|
update(args: any, result: any, revision: number, context: any) {
|
|
31
|
-
|
|
35
|
+
this.content.update(args, result, revision);
|
|
36
|
+
if (revision !== this.revision) { this.revision = revision; this.reset(); }
|
|
32
37
|
if (context.executionStarted) this.startedAt ??= Date.now();
|
|
33
38
|
if (this.durationMs !== context.durationMs || this.isError !== context.isError) this.reset();
|
|
34
39
|
this.partial = context.isPartial; this.isError = context.isError; this.durationMs = context.durationMs;
|
|
@@ -46,6 +51,13 @@ export class CodePane {
|
|
|
46
51
|
}
|
|
47
52
|
return false;
|
|
48
53
|
}
|
|
54
|
+
*contentRows(width: number, theme = this.theme, grouped = false): Generator<string> {
|
|
55
|
+
if (grouped && this.durationMs !== undefined && !this.content.hasScriptHeader) {
|
|
56
|
+
const timing = `Took ${(this.durationMs / 1000).toFixed(2)}s`;
|
|
57
|
+
yield theme ? theme.fg("muted", timing) : timing;
|
|
58
|
+
}
|
|
59
|
+
yield* this.content.rows(width, theme, this.isError, !grouped && (this.durationMs !== undefined || this.startedAt !== undefined));
|
|
60
|
+
}
|
|
49
61
|
render(width: number): string[] {
|
|
50
62
|
this.lastWidth = width;
|
|
51
63
|
const contentWidth = cardContentWidth(width);
|
|
@@ -63,7 +75,7 @@ export class CodePane {
|
|
|
63
75
|
const indent = contentWidth >= 4 ? " " : "";
|
|
64
76
|
const nativeWidth = Math.max(1, contentWidth - indent.length);
|
|
65
77
|
if (this.width !== nativeWidth) { this.reset(); this.width = nativeWidth; this.offset = 0; }
|
|
66
|
-
this.iterator ??= this.
|
|
78
|
+
this.iterator ??= this.contentRows(nativeWidth);
|
|
67
79
|
const bodyHeight = Math.max(1, Math.min(20, this.height()) - 2);
|
|
68
80
|
this.offset = Math.min(this.offset, this.rows.length);
|
|
69
81
|
while (!this.done && this.rows.length <= this.offset + bodyHeight) {
|
package/src/modern-tool-pane.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { activityRow, cardContentWidth } from "./display-card.ts";
|
|
|
5
5
|
|
|
6
6
|
type RowKind = "section" | "field" | "answer";
|
|
7
7
|
export type PaneContent = string | { text: string; kind?: RowKind; indent?: number; label?: string } & TextFormat;
|
|
8
|
-
export type PaneAction = { id: string; label: string; repeatedSummary?: string; sections: () => Iterable<PaneContent>; details?: () => Iterable<PaneContent> };
|
|
8
|
+
export type PaneAction = { id: string; label: string; repeatedSummary?: string; sections: () => Iterable<PaneContent>; rows?: (width: number, theme: any) => Iterable<string>; details?: () => Iterable<PaneContent> };
|
|
9
9
|
// Render only visited text chunks. Never split/highlight an entire result to paint a viewport.
|
|
10
10
|
export function* textRows(text: string, width: number): Generator<string> {
|
|
11
11
|
yield* richTextRows(text, width);
|
|
@@ -49,8 +49,9 @@ export class ToolPane {
|
|
|
49
49
|
reset() { this.preserveFocusLayout = false; this.anchor = Math.min(this.anchor, Math.max(0, this.actions.length - 1)); this.key = ""; this.rows = []; this.iterator = undefined; this.done = false; this.actionRows.clear(); this.detailsRows.clear(); this.rowKinds.clear(); }
|
|
50
50
|
collapse() { this.open = false; this.focused = false; this.selected = 0; this.anchor = 0; this.offset = 0; this.expanded.clear(); this.detailsExpanded.clear(); this.detailsFocused = false; this.reset(); }
|
|
51
51
|
releaseInspection() { if (this.detailsFocused) { this.detailsFocused = false; this.offset = 0; this.reset(); } }
|
|
52
|
+
select(index: number) { this.selected = Math.max(0, Math.min(index, this.actions.length - 1)); this.detailsFocused = false; this.anchor = this.selected; this.open = true; this.offset = 0; this.reset(); }
|
|
52
53
|
handle(data: string): boolean {
|
|
53
|
-
if (matchesKey(data, "home")) { this.
|
|
54
|
+
if (matchesKey(data, "home")) { this.select(0); return true; }
|
|
54
55
|
if (matchesKey(data, "enter")) {
|
|
55
56
|
const action = this.actions[this.selected];
|
|
56
57
|
if (this.detailsFocused && action?.details) {
|
|
@@ -68,8 +69,7 @@ export class ToolPane {
|
|
|
68
69
|
}
|
|
69
70
|
if (matchesKey(data, "right") || matchesKey(data, "tab") || matchesKey(data, "left") || matchesKey(data, "shift+tab")) {
|
|
70
71
|
const direction = matchesKey(data, "left") || matchesKey(data, "shift+tab") ? -1 : 1;
|
|
71
|
-
this.
|
|
72
|
-
this.detailsFocused = false; this.anchor = this.selected; this.open = true; this.offset = 0; this.reset(); return true;
|
|
72
|
+
this.select((this.selected + direction + this.actions.length) % Math.max(1, this.actions.length)); return true;
|
|
73
73
|
}
|
|
74
74
|
if (["up", "down", "pageUp", "pageDown"].some(key => matchesKey(data, key as any))) {
|
|
75
75
|
const distance = matchesKey(data, "pageUp") || matchesKey(data, "pageDown") ? Math.max(1, this.height() - 4) : 1;
|
|
@@ -112,15 +112,19 @@ export class ToolPane {
|
|
|
112
112
|
}.bind(this);
|
|
113
113
|
const fullLabel = this.directDetails ? `▾ ${this.expandedTitle ?? this.title}${this.contentFocused ? " · focused" : ""}` : prefix + action.label;
|
|
114
114
|
const summary = visibleWidth(fullLabel) <= width ? action.repeatedSummary : undefined;
|
|
115
|
+
const primaryRows = function* (this: ToolPane) {
|
|
116
|
+
if (action.rows) for (const row of action.rows(Math.max(1, width - detailsIndent.length), this.theme)) yield { text: detailsIndent + row };
|
|
117
|
+
else yield* sectionRows(action.sections(), summary);
|
|
118
|
+
}.bind(this);
|
|
115
119
|
if (this.detailsFocused && index === this.selected) {
|
|
116
120
|
// Keep short output inline; probe at most one viewport before anchoring at Details.
|
|
117
|
-
const primary =
|
|
121
|
+
const primary = primaryRows(), preview = [];
|
|
118
122
|
const budget = Math.max(1, Math.min(20, this.height()) - (this.contentFocused ? 2 : 1) - (this.directDetails ? 0 : 1) - 1);
|
|
119
123
|
let complete = false;
|
|
120
124
|
while (preview.length <= budget) { const row = primary.next(); if (row.done) { complete = true; break; } preview.push(row.value); }
|
|
121
125
|
if (complete) yield* emitRows(preview);
|
|
122
126
|
else { this.contentAnchoredAbove = true; yield detailsIndent + (this.theme ? this.theme.fg("dim", "content above ↑") : "content above ↑"); }
|
|
123
|
-
} else yield* emitRows(
|
|
127
|
+
} else yield* emitRows(primaryRows());
|
|
124
128
|
if (action.details) {
|
|
125
129
|
this.detailsRows.set(this.rows.length, index);
|
|
126
130
|
yield detailsIndent + `${this.detailsExpanded.has(action.id) ? "▾" : "▸"} Details`;
|
package/src/modern-tools.ts
CHANGED
|
@@ -254,12 +254,18 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
254
254
|
pi.events.emit("compact-renderer:focus:v1", { owner: "tools", label: pane.title,
|
|
255
255
|
target: (component: any) => component instanceof DynamicComponent && (component.owner && subagentView(component.owner)?.pane || component.owner?.group?.pane || component.owner?.code || component.owner?.pane) === pane });
|
|
256
256
|
};
|
|
257
|
-
const action = (node: Node): PaneAction =>
|
|
257
|
+
const action = (node: Node): PaneAction => node.code ? {
|
|
258
|
+
id: node.id, label: `codemode · ${node.code.content.intent}${node.code.content.calls.length ? ` · ${node.code.content.calls.length} nested call${node.code.content.calls.length === 1 ? "" : "s"}` : ""}` + indicators(node),
|
|
259
|
+
sections: () => [], rows: (width, theme) => node.code!.contentRows(width, theme, true),
|
|
260
|
+
} : ({ id: node.id, label: toolLabel(node.name, node.args) + indicators(node), sections: () => sections(node), ...(question(node.name) ? {} : { details: () => actionDetails(node) }) });
|
|
258
261
|
const refreshGroups = () => {
|
|
259
262
|
let run: Node[] = [];
|
|
263
|
+
let transferredFocus: ToolPane | undefined;
|
|
260
264
|
const next = new Map<string, Group>();
|
|
261
265
|
const finish = () => {
|
|
262
266
|
if (!run.length) return;
|
|
267
|
+
// A lone codemode keeps its native-style CodePane and timing/inspection UI.
|
|
268
|
+
if (run.length === 1 && run[0].code) { run = []; return; }
|
|
263
269
|
const id = run[0].id;
|
|
264
270
|
const signature = run.map(node => `${node.id}@${node.revision}`).join("|");
|
|
265
271
|
let group = groups.get(id);
|
|
@@ -270,16 +276,27 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
270
276
|
if (run.some(node => node.result?.details?.truncation?.truncated || node.result?.details?.truncated)) group.pane.title += " · output truncated";
|
|
271
277
|
if (run.some(node => node.result?.details?.fullOutputPath)) group.pane.title += " · full output saved";
|
|
272
278
|
if (run.some(node => node.result?.details?.warning || node.result?.details?.warnings?.length)) group.pane.title += " · warning recorded";
|
|
273
|
-
for (const node of run)
|
|
279
|
+
for (const [index, node] of run.entries()) {
|
|
280
|
+
node.group = group;
|
|
281
|
+
if (node.code?.open) {
|
|
282
|
+
group.pane.open = true; group.pane.expanded.add(node.id);
|
|
283
|
+
if (focused === node.code) { group.pane.select(index); transferredFocus = group.pane; }
|
|
284
|
+
// The shared pane now owns expansion; collapse-all must not leave a
|
|
285
|
+
// hidden singleton state that can reopen after a later regroup.
|
|
286
|
+
node.code.collapse();
|
|
287
|
+
}
|
|
288
|
+
}
|
|
274
289
|
next.set(id, group); run = [];
|
|
275
290
|
};
|
|
276
291
|
for (const node of nodes.values()) {
|
|
277
292
|
node.group = undefined;
|
|
278
|
-
|
|
293
|
+
const code = node.code?.content;
|
|
294
|
+
if (compactSubagent(node.name) || node.status !== "success" || node.images || code && (!code.supported || !code.clean)) { finish(); continue; }
|
|
279
295
|
if (run.length && node.epoch !== run[0].epoch) finish();
|
|
280
296
|
run.push(node);
|
|
281
297
|
}
|
|
282
298
|
finish(); groups = next;
|
|
299
|
+
if (transferredFocus) focusPane(transferredFocus);
|
|
283
300
|
if (focused && ![...groups.values()].some(group => group.pane === focused) && ![...nodes.values()].some(node => !node.group && (node.code || node.pane) === focused)) release();
|
|
284
301
|
};
|
|
285
302
|
const ensure = (id: string, name: string, args?: any, stock?: ToolRenderers) => {
|
|
@@ -298,6 +315,9 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
298
315
|
if (!changed) return;
|
|
299
316
|
node.images = Array.isArray(result?.content) ? result.content.reduce((count: number, block: any) => count + (block?.type === "image" ? 1 : 0), 0) : 0;
|
|
300
317
|
node.revision++; node.pane?.reset();
|
|
318
|
+
// Running code cannot join a group. Defer its aggregate until the renderer
|
|
319
|
+
// receives the final argument revision, as native streaming may replace args.
|
|
320
|
+
if (!partial) node.code?.content.update(node.args, node.result, node.revision);
|
|
301
321
|
if (!rebuilding) refreshGroups();
|
|
302
322
|
};
|
|
303
323
|
const observeMessage = (message: any) => {
|
|
@@ -447,6 +467,8 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
447
467
|
const codePane = (node: Node, theme: any, context: Context) => {
|
|
448
468
|
const pane = node.code!;
|
|
449
469
|
node.native.suspend(); pane.adoptClock(node.native.clock);
|
|
470
|
+
if (pane.content.update(node.args, node.result, node.revision) && !rebuilding) refreshGroups();
|
|
471
|
+
const duration = pane.duration;
|
|
450
472
|
const supported = pane.update(node.args, node.result, node.revision, context);
|
|
451
473
|
if (!supported) { pane.suspend(); node.native.adoptClock(pane.clock); return false; }
|
|
452
474
|
const calls = pane.content.calls;
|
|
@@ -454,9 +476,16 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
454
476
|
const status = node.status === "failed" ? "✗ Failed" : context.isPartial ? context.executionStarted ? "… Running" : "Preparing" : "";
|
|
455
477
|
pane.heading = `codemode${status ? ` · ${status}` : ""} · ${pane.content.intent}`;
|
|
456
478
|
pane.title = `${pane.heading}${calls.length ? ` · ${calls.length} nested call${calls.length === 1 ? "" : "s"}` : ""}${pane.content.images ? ` · ${pane.content.images} image${pane.content.images === 1 ? "" : "s"}` : ""}${errors ? ` · ${errors} nested error${errors === 1 ? "" : "s"}` : ""}${cancelled ? ` · ${cancelled} nested cancelled` : ""}${unresolved ? ` · ${unresolved} nested unresolved` : ""}${typeof context.durationMs === "number" ? ` · ${(context.durationMs / 1000).toFixed(2)}s` : ""}${indicators(node)}`;
|
|
457
|
-
pane.setTheme(theme)
|
|
479
|
+
if (pane.setTheme(theme) || duration !== pane.duration) node.group?.pane.reset();
|
|
480
|
+
pane.tone = node.status === "failed" ? "error" : errors || cancelled || unresolved && !context.isPartial ? "warning" : "syntaxVariable";
|
|
458
481
|
return true;
|
|
459
482
|
};
|
|
483
|
+
const groupPane = (node: Node, theme: any) => {
|
|
484
|
+
const group = node.group;
|
|
485
|
+
if (!group || group.members[0] !== node) return;
|
|
486
|
+
group.pane.theme = theme; group.pane.styleHeader = text => activityHeading(text, theme);
|
|
487
|
+
return group.pane;
|
|
488
|
+
};
|
|
460
489
|
return {
|
|
461
490
|
renderShell: "self",
|
|
462
491
|
[compactToolImages](component: any, width: number): ToolImageView | undefined {
|
|
@@ -477,7 +506,7 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
477
506
|
if (node.code) {
|
|
478
507
|
if (!codePane(node, theme, context)) node.native.renderCall(args, theme, context);
|
|
479
508
|
syncExpansion(node, context.expanded);
|
|
480
|
-
return new DynamicComponent(width => node.code!.content.supported ? node.code!.render(width) : node.native.renderCurrent(width), event => node.code!.content.supported ?
|
|
509
|
+
return new DynamicComponent(width => node.group ? groupPane(node, theme)?.render(width) ?? [] : node.code!.content.supported ? node.code!.render(width) : node.native.renderCurrent(width), event => mouse(node.group ? groupPane(node, theme) : node.code!.content.supported ? node.code : undefined, event), node);
|
|
481
510
|
}
|
|
482
511
|
node.native.suspend(); syncExpansion(node, context.expanded);
|
|
483
512
|
return new DynamicComponent(width => {
|
|
@@ -498,7 +527,7 @@ export function registerModernTools(pi: ExtensionAPI, mode: DisplayMode): () =>
|
|
|
498
527
|
node.native.suspend(); syncExpansion(node, context.expanded);
|
|
499
528
|
return new DynamicComponent(width => {
|
|
500
529
|
if (subagentView(node)?.hidden) return [];
|
|
501
|
-
if (node.group)
|
|
530
|
+
if (node.group) return groupPane(node, theme)?.render(width) ?? [];
|
|
502
531
|
if (singleCard(node)) return [];
|
|
503
532
|
return individual(node, theme).render(width);
|
|
504
533
|
}, event => mouse(node.group ? node.group.members[0] === node ? node.group.pane : undefined : !singleCard(node) ? individual(node, theme) : undefined, event), node);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from '@earendil-works/pi-tui';
|
|
2
2
|
import type { DisplayMode } from './display-mode.ts';
|
|
3
|
-
import { cardContentWidth,
|
|
3
|
+
import { cardContentWidth, activityRow } from './display-card.ts';
|
|
4
4
|
|
|
5
5
|
/** Shared with approval owners. This channel carries presentation, never policy. */
|
|
6
6
|
export const PERMISSION_PRESENTATION_EVENT = 'pi:permission-presentation:v1';
|
|
@@ -198,21 +198,27 @@ export class PermissionDialog implements Component {
|
|
|
198
198
|
...field('Action', this.request.action), ...field('Target', this.request.target), ...field('Reason', this.request.reason)];
|
|
199
199
|
let selectedRow = -1;
|
|
200
200
|
if (shortened) rows.push(...lines('Summary shortened; full text in Details.'));
|
|
201
|
+
const hints = lines('↑↓ choose · Enter select · Esc deny · d Details');
|
|
202
|
+
if (this.detailsOpen) hints.push(...lines('←/→ page Details · Home/End'));
|
|
203
|
+
const availableRows = this.availableRows();
|
|
204
|
+
// Leave room for the choices and at least one Details row before adding space.
|
|
205
|
+
const padded = rows.length + 3 + hints.length + (this.detailsOpen ? 2 : 0) + 4 <= availableRows;
|
|
206
|
+
if (padded) { rows.unshift(''); rows.push(''); }
|
|
201
207
|
for (const [index, title] of ['Allow once', 'Deny', `${this.detailsOpen ? 'Hide' : 'Show'} Details`].entries()) {
|
|
202
208
|
if (index === this.selected) selectedRow = rows.length;
|
|
203
209
|
const label = truncateToWidth(`${index === this.selected ? '→' : ' '} ${title}`, width, '');
|
|
204
210
|
rows.push(fg(index === this.selected ? 'accent' : 'text', index === this.selected && this.theme.bold ? this.theme.bold(label) : label));
|
|
205
211
|
}
|
|
206
|
-
|
|
207
|
-
if (this.detailsOpen) hints.push(...lines('←/→ page Details · Home/End'));
|
|
208
|
-
this.pageSize = Math.max(1, Math.min(8, this.availableRows() - rows.length - hints.length - 1));
|
|
212
|
+
this.pageSize = Math.max(1, Math.min(8, availableRows - rows.length - hints.length - 1 - (padded ? 2 : 0)));
|
|
209
213
|
if (this.detailsOpen) {
|
|
210
214
|
const body = this.detailsViewport.render(width, this.pageSize);
|
|
211
215
|
const range = this.detailsViewport.range;
|
|
212
216
|
rows.push(fg('muted', truncateToWidth(`Details · text offset ${range.start}–${range.end}/${range.total}`, width)), ...body);
|
|
213
217
|
}
|
|
214
|
-
rows.push(
|
|
215
|
-
|
|
218
|
+
if (padded) rows.push('');
|
|
219
|
+
rows.push(...hints.map(row => fg('muted', row)));
|
|
220
|
+
if (padded) rows.push('');
|
|
221
|
+
return rows.map((row, index) => activityRow(fg('text', row), outerWidth, this.theme, index === selectedRow));
|
|
216
222
|
}
|
|
217
223
|
handleInput(data: string) {
|
|
218
224
|
if (this.settled) return;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { createWorkStripPreview } from '../scripts/preview-work-strip.mjs';
|
|
5
|
+
|
|
6
|
+
const preview = await createWorkStripPreview({ actionGroups: true });
|
|
7
|
+
const { core, runtime, manager } = preview;
|
|
8
|
+
const { theme, initTheme } = await import(pathToFileURL(path.join(preview.runtimePath, 'node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js')));
|
|
9
|
+
initTheme('dark', false);
|
|
10
|
+
const plain = value => value.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g, '');
|
|
11
|
+
const errors = [];
|
|
12
|
+
runtime.session.extensionRunner.onError(error => errors.push(error));
|
|
13
|
+
const ui = new core.InteractiveMode(runtime, { tuiMode: 'fullscreen' });
|
|
14
|
+
ui.updateTerminalTitle = () => {};
|
|
15
|
+
Object.defineProperty(ui.ui, 'isFollowingOutput', { get: () => true });
|
|
16
|
+
runtime.session.extensionRunner.setUIContext({ ...ui.createExtensionUIContext(), theme, onTerminalInput() { return () => {}; }, setHiddenThinkingLabel() {}, setStatus() {}, setWidget() {}, notify() {} }, 'tui');
|
|
17
|
+
const paint = () => plain(ui.chatContainer.render(140).join('\n'));
|
|
18
|
+
try {
|
|
19
|
+
ui.renderSessionEntries(manager.getBranch());
|
|
20
|
+
await runtime.session.extensionRunner.emit({ type: 'session_start', reason: 'resume' });
|
|
21
|
+
ui.chatContainer.invalidate();
|
|
22
|
+
assert.match(paint(), /Mixed-action preview:/, 'final reply remains visible while work is folded');
|
|
23
|
+
const projected = ui.chatContainer[Symbol.for('compact-renderer:projected-children:v1')];
|
|
24
|
+
const work = projected.findLast(row => row.constructor.name === 'WorkStripHeader');
|
|
25
|
+
work.render(140);
|
|
26
|
+
work.handleMouse({ type: 'click', button: 'left', x: 4, y: 1, width: 140 });
|
|
27
|
+
const tools = ui.chatContainer.children.filter(row => row instanceof core.ToolExecutionComponent && row.toolCallId?.startsWith('mixed-'));
|
|
28
|
+
assert.equal(tools.length, 7, 'all recorded calls survive replay');
|
|
29
|
+
const rows = tools.map(row => plain(row.render(140).join('\n')));
|
|
30
|
+
assert.match(rows[0], /4 actions/);
|
|
31
|
+
assert.ok(rows.slice(1, 4).every(row => !row.trim()), 'mixed group followers do not duplicate cards');
|
|
32
|
+
assert.match(rows[4], /2 actions/, 'codemode can lead an action group');
|
|
33
|
+
assert.equal(rows[5].trim(), '');
|
|
34
|
+
assert.match(rows[6], /codemode.*1 nested error/, 'handled nested error remains a separate warning card');
|
|
35
|
+
tools[0].setExpanded(true);
|
|
36
|
+
tools[4].setExpanded(true);
|
|
37
|
+
const expanded = paint();
|
|
38
|
+
assert.match(expanded, /codemode/);
|
|
39
|
+
assert.match(expanded, /Mixed-action preview:/);
|
|
40
|
+
assert.deepEqual(runtime.session.getActiveToolNames(), [], 'preview cannot execute tools');
|
|
41
|
+
assert.deepEqual(errors, []);
|
|
42
|
+
console.log('Mixed action groups replay through native Pi, retain warning cards, and preserve work-strip inspection');
|
|
43
|
+
} finally { ui.ui.stop(); await preview.cleanup(); ui.footerDataProvider.dispose(); }
|
package/tests/codemode.test.mjs
CHANGED
|
@@ -31,7 +31,9 @@ assert.equal(ToolExecutionComponent.prototype.render,originalToolRender);
|
|
|
31
31
|
const mode = createDisplayMode(), dispose = registerModernTools(pi, mode);
|
|
32
32
|
const ctx = { hasUI: true, sessionManager: { getBranch: () => [] }, ui: { onTerminalInput(fn) { input = fn; return () => { input = undefined; }; } } };
|
|
33
33
|
const event = (name, data = {}) => { for (const fn of hooks.get(name) || []) fn(data, ctx); };
|
|
34
|
-
const create = (name, id, args, native) => {
|
|
34
|
+
const create = (name, id, args, native, adjacent = false) => {
|
|
35
|
+
// These fixtures inspect independent panes. Mixed adjacency has its own assertions below.
|
|
36
|
+
if (!adjacent) event('message_end', { message: { role: 'assistant', content: [{ type: 'text', text: `Fixture ${id}` }] } });
|
|
35
37
|
const component = new ToolExecutionComponent(name, id, args, { showImages: false, outputPad: 0 }, resolver(name, () => native), { requestRender() {} }, '/tmp'); component.setArgsComplete(); return component;
|
|
36
38
|
};
|
|
37
39
|
const result = text => ({ content: [{ type: 'text', text }] });
|
|
@@ -376,13 +378,13 @@ try {
|
|
|
376
378
|
assert.ok(restoredChoices.length>fallbackChoices.length,'supported result restores compact inspection');
|
|
377
379
|
|
|
378
380
|
const unsupported=create('codemode','bounded-invalid-fallback',{code:42},codemodeRenderers);assert.match(paint(unsupported),/invalid arg/);
|
|
379
|
-
//
|
|
381
|
+
// Adjacent successful code shares the outer action group with ordinary tools.
|
|
380
382
|
const replayFirst = create('read', 'replay-before', { path: '/fixture/replay-before' }, readRenderers); replayFirst.updateResult(result('first'));
|
|
381
383
|
event('message_end', { message: { role: 'assistant', content: [{ type: 'toolCall', id: 'replay-code', name: 'codemode', arguments: { code: 'text(1)' } }] } });
|
|
382
|
-
const replayCode = create('codemode', 'replay-code', { code: 'text(1)' }, codemodeRenderers); replayCode.updateResult(result('done'));
|
|
383
|
-
const last = create('read', 'after-code', { path: '/fixture/after' }, readRenderers); last.updateResult(result('last'));
|
|
384
|
-
assert.
|
|
384
|
+
const replayCode = create('codemode', 'replay-code', { code: 'text(1)' }, codemodeRenderers, true); replayCode.updateResult(result('done'));
|
|
385
|
+
const last = create('read', 'after-code', { path: '/fixture/after' }, readRenderers, true); last.updateResult(result('last'));
|
|
386
|
+
assert.equal(paint(last), '');
|
|
385
387
|
assert.doesNotMatch(paint(replayCode), /successful action/);
|
|
386
|
-
assert.match(paint(replayFirst), /
|
|
388
|
+
assert.match(paint(replayFirst), /3 actions/); assert.equal(paint(replayCode), '');
|
|
387
389
|
console.log('codemode: collapsed summary, bounded details, native images, single image-read headings, nested outcome, timer, inspection/editor and transcript checks passed');
|
|
388
390
|
} finally { dispose(); assert.equal(ToolExecutionComponent.prototype.render,originalToolRender,'disposing restores the native render method'); }
|
|
@@ -8,7 +8,7 @@ import { createWorkStripPreview } from '../scripts/preview-work-strip.mjs';
|
|
|
8
8
|
const preview = await createWorkStripPreview();
|
|
9
9
|
let ui;
|
|
10
10
|
try {
|
|
11
|
-
const { matchesKey, setKittyProtocolActive } = await import(pathToFileURL(
|
|
11
|
+
const { matchesKey, setKittyProtocolActive } = await import(pathToFileURL(preview.tuiPath));
|
|
12
12
|
let receive, kitty = true;
|
|
13
13
|
const terminal = {
|
|
14
14
|
columns: 110,
|
|
@@ -36,12 +36,14 @@ try {
|
|
|
36
36
|
assert.notEqual(plain(component.render(110)), beforeThinking);
|
|
37
37
|
assert.doesNotMatch(plain(component.render(110)), /Thinking\.\.\./);
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
const
|
|
39
|
+
// The recorded read and codemode now share an action pane owned by the read.
|
|
40
|
+
const leader = ui.chatContainer.children.find(row => row.toolCallId === 'inspection-1');
|
|
41
|
+
const wrapper = ui.chatContainer[Symbol.for('compact-renderer:projected-children:v1')].find(row => row.children?.[0] === leader);
|
|
41
42
|
assert.ok(wrapper);
|
|
42
|
-
click(wrapper, /▸
|
|
43
|
+
click(wrapper, /▸ 2 actions/);
|
|
44
|
+
click(wrapper, /2\. codemode/);
|
|
43
45
|
click(wrapper, /more ↓/);
|
|
44
|
-
preview.eventBus.emit('compact-renderer:focus:v1', { owner: 'tools', target: row => row ===
|
|
46
|
+
preview.eventBus.emit('compact-renderer:focus:v1', { owner: 'tools', target: row => row === leader });
|
|
45
47
|
renderer.renderNow();
|
|
46
48
|
const scroll = renderer.getPrimaryScrollView();
|
|
47
49
|
// At the transcript end, auto-clamping can mask a shrinking pane by moving
|
|
@@ -50,7 +52,7 @@ try {
|
|
|
50
52
|
const top = scroll.scrollTop;
|
|
51
53
|
let footerY = -1;
|
|
52
54
|
for (let n = 0; n < 200; n++) {
|
|
53
|
-
const rows = screen(), headerY = rows.findIndex(row => /▾
|
|
55
|
+
const rows = screen(), headerY = rows.findIndex(row => /▾ 2 actions/.test(row));
|
|
54
56
|
assert.ok(headerY >= 0);
|
|
55
57
|
const nextY = rows.findIndex((row, i) => i > headerY && i < headerY + 21 && /more ↓/.test(row));
|
|
56
58
|
if (nextY < 0) break;
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { loadSource, loadAgent, stripAnsi, tui } from './test-runtime.mjs';
|
|
3
|
+
const { registerModernTools } = await loadSource('./modern-tools.ts');
|
|
4
|
+
const { CodeContent } = await loadSource('./modern-code-content.ts');
|
|
5
|
+
const { ToolExecutionComponent } = await loadAgent('modes/interactive/components/tool-execution.js');
|
|
6
|
+
const { codemodeRenderers } = await loadAgent('extensions/codemode/renderer.js');
|
|
7
|
+
const { createShellRenderers } = await loadAgent('core/tools/renderers/bash.js');
|
|
8
|
+
const { readRenderers } = await loadAgent('core/tools/renderers/read.js');
|
|
9
|
+
const hooks = new Map(), bus = new Map(); let resolver, input;
|
|
10
|
+
const pi = {
|
|
11
|
+
registerToolRenderer(fn) { resolver = fn; },
|
|
12
|
+
on(name, fn) { const set = hooks.get(name) || new Set(); set.add(fn); hooks.set(name, set); return () => set.delete(fn); },
|
|
13
|
+
events: { on(name, fn) { bus.set(name, fn); return () => bus.delete(name); }, emit(name, data) { bus.get(name)?.(data); } },
|
|
14
|
+
};
|
|
15
|
+
const dispose = registerModernTools(pi, { isEnabled: () => true, onChange: () => () => {} });
|
|
16
|
+
let history = [];
|
|
17
|
+
const ctx = { hasUI: true, sessionManager: { getBranch: () => history }, ui: { onTerminalInput(fn) { input = fn; return () => { input = undefined; }; } } };
|
|
18
|
+
const event = (name, data = {}) => { for (const fn of hooks.get(name) || []) fn(data, ctx); };
|
|
19
|
+
const reset = () => { history = []; event('session_start'); };
|
|
20
|
+
const native = new Map([['codemode', codemodeRenderers], ['bash', createShellRenderers('$')], ['read', readRenderers]]);
|
|
21
|
+
const make = (name, id, args = name === 'codemode' ? { code: `text("source-${id}");` } : name === 'bash' ? { command: 'git status' } : { path: `/fixture/${id}` }) => {
|
|
22
|
+
const component = new ToolExecutionComponent(name, id, args, { showImages: false, outputPad: 0 }, resolver(name, () => native.get(name)), { requestRender() {} }, '/tmp');
|
|
23
|
+
component.setArgsComplete(); return component;
|
|
24
|
+
};
|
|
25
|
+
const success = (id, calls = [{ name: 'read', args: `/nested/${id}`, status: 'ok' }], details = {}) => ({ content: [{ type: 'text', text: `output-${id}` }], details: { calls, ...details } });
|
|
26
|
+
const done = (name, id, result = name === 'codemode' ? success(id) : { content: [{ type: 'text', text: `output-${id}` }] }) => {
|
|
27
|
+
const component = make(name, id); component.updateResult(result); return component;
|
|
28
|
+
};
|
|
29
|
+
const owner = component => component.callRendererComponent.owner;
|
|
30
|
+
const paint = (component, width = 140) => stripAnsi(component.render(width).join('\n'));
|
|
31
|
+
const all = components => components.map(component => paint(component)).filter(Boolean).join('\n');
|
|
32
|
+
const choices = () => { const found = []; pi.events.emit('compact-renderer:inspect:v1', { add: entry => found.push(entry) }); return found; };
|
|
33
|
+
const click = (component, y) => component.handleMouse({ type: 'click', button: 'left', x: 2, y, screenX: 2, screenY: y, width: 140, height: component.render(140).length });
|
|
34
|
+
try {
|
|
35
|
+
const accessorDetails = { calls: [] };
|
|
36
|
+
Object.defineProperty(accessorDetails, 'warning', { enumerable: true, get() { throw new Error('recorded warning accessor must not be evaluated'); } });
|
|
37
|
+
const accessorContent = new CodeContent();
|
|
38
|
+
accessorContent.update({ code: 'text(1);' }, { content: [], details: accessorDetails }, 1);
|
|
39
|
+
assert.equal(accessorContent.supported, true); assert.equal(accessorContent.clean, false, 'recorded accessors cannot establish clean grouping eligibility');
|
|
40
|
+
reset();
|
|
41
|
+
const shell = done('bash', 'shell'), codeA = done('codemode', 'code-a'), codeB = done('codemode', 'code-b'), read = done('read', 'read');
|
|
42
|
+
const components = [shell, codeA, codeB, read], group = owner(shell).group;
|
|
43
|
+
assert.deepEqual(group.members.map(node => node.id), ['shell', 'code-a', 'code-b', 'read'], 'each outer call contributes one ordered action');
|
|
44
|
+
assert.match(paint(shell), /4 actions/);
|
|
45
|
+
for (const follower of components.slice(1)) assert.equal(paint(follower), '', 'follower slots contribute no duplicate rows');
|
|
46
|
+
assert.equal(choices().length, 1, 'mixed group has one inspector entry');
|
|
47
|
+
choices()[0].focus();
|
|
48
|
+
assert.match(paint(shell), /2\. codemode · Read files · 1 nested call/);
|
|
49
|
+
input('\x1b[C'); input('\r');
|
|
50
|
+
let visible = paint(shell);
|
|
51
|
+
for (let index = 0; index < 4; index++) { input('\x1b[B'); visible += '\n' + paint(shell); }
|
|
52
|
+
for (const text of ['source-code-a', '✓ read /nested/code-a', 'output-code-a']) assert.ok(visible.includes(text), `group retains code source/calls/output: ${text}`);
|
|
53
|
+
input('\x1b');
|
|
54
|
+
const disclosures = []; pi.events.emit('compact-renderer:disclosures:v1', { add: (...entry) => disclosures.push(entry) });
|
|
55
|
+
assert.equal(disclosures.length, 1); assert.equal(disclosures[0][0](codeA.callRendererComponent), true);
|
|
56
|
+
disclosures[0][2](); assert.equal(group.pane.open, false, 'collapse-all closes mixed group');
|
|
57
|
+
click(shell, 1); assert.equal(group.pane.open, true, 'mouse opens leader group');
|
|
58
|
+
shell.setExpanded(false); shell.setExpanded(true); assert.equal(group.pane.open, true, 'native expansion opens shared group');
|
|
59
|
+
assert.equal(all(components).match(/4 actions/g)?.length, 1);
|
|
60
|
+
// Ordinary Details retain their existing keyboard behavior in mixed groups.
|
|
61
|
+
group.pane.handle('home'); group.pane.handle('\t'); group.pane.handle('\r');
|
|
62
|
+
assert.match(paint(shell), /Arguments/); assert.match(paint(shell), /git status/);
|
|
63
|
+
|
|
64
|
+
reset();
|
|
65
|
+
const firstCode = done('codemode', 'first-code'), nextRead = done('read', 'next-read');
|
|
66
|
+
assert.match(paint(firstCode), /2 actions/); assert.equal(paint(nextRead), '');
|
|
67
|
+
assert.equal(firstCode.resultRendererComponent.render(140).length, 0, 'code-first group stays in its original call slot');
|
|
68
|
+
assert.equal(choices().length, 1);
|
|
69
|
+
choices()[0].focus(); input('\r');
|
|
70
|
+
assert.match(paint(firstCode), /source-first-code/);
|
|
71
|
+
// An unsupported shape must remove membership before native fallback paints.
|
|
72
|
+
firstCode.updateResult({ content: [{ type: 'unknown', text: 'future native shape' }], details: { calls: [] } });
|
|
73
|
+
assert.equal(owner(firstCode).group, undefined); assert.equal(owner(nextRead).group.members.length, 1);
|
|
74
|
+
assert.doesNotMatch(paint(firstCode), /2 actions/); assert.match(paint(nextRead), /next-read/);
|
|
75
|
+
firstCode.updateResult(success('restored'));
|
|
76
|
+
assert.match(paint(firstCode), /2 actions/); assert.equal(paint(nextRead), '', 'supported completion restores code-first ownership');
|
|
77
|
+
|
|
78
|
+
for (const focused of [false, true]) {
|
|
79
|
+
reset();
|
|
80
|
+
const opened = done('codemode', `opened-${focused}`), originalPane = owner(opened).code;
|
|
81
|
+
if (focused) choices()[0].focus(); else click(opened, 1);
|
|
82
|
+
assert.match(paint(opened), /source-opened/);
|
|
83
|
+
done('read', `append-${focused}`);
|
|
84
|
+
const transferred = owner(opened).group.pane;
|
|
85
|
+
assert.equal(transferred.open, true); assert.equal(transferred.expanded.has(`opened-${focused}`), true);
|
|
86
|
+
assert.equal(originalPane.open, false, 'group transfer clears orphan singleton expansion');
|
|
87
|
+
assert.match(paint(opened), /source-opened/, 'appending an action retains the open code content');
|
|
88
|
+
assert.equal(transferred.focused, focused, 'inspection focus follows the transferred content');
|
|
89
|
+
if (focused) { assert.equal(input('\x1b[B').consume, true); assert.match(paint(opened), /focused/); }
|
|
90
|
+
const collapse = []; pi.events.emit('compact-renderer:disclosures:v1', { add: (...entry) => collapse.push(entry) });
|
|
91
|
+
assert.equal(collapse.length, 1); collapse[0][2]();
|
|
92
|
+
assert.equal(transferred.open, false); assert.equal(originalPane.open, false); assert.equal(transferred.expanded.size, 0);
|
|
93
|
+
click(opened, 1);
|
|
94
|
+
assert.match(paint(opened), /1\. codemode/); assert.doesNotMatch(paint(opened), /source-opened/, 'reopening the group starts with closed actions');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
reset();
|
|
98
|
+
const earlier = done('read', 'earlier-large', { content: [{ type: 'text', text: 'earlier-output\n'.repeat(1000) }] });
|
|
99
|
+
done('read', 'earlier-second');
|
|
100
|
+
const earlierGroup = owner(earlier).group.pane;
|
|
101
|
+
choices()[0].focus(); input('\r'); input('\x1b[B'); paint(earlier);
|
|
102
|
+
assert.match(paint(earlier), /earlier-output/);
|
|
103
|
+
const joining = make('codemode', 'anchored-code');
|
|
104
|
+
joining.markExecutionStarted(); joining.updateResult(success('anchored-code', [{ name: 'read', args: '/anchored', status: 'running' }]), true);
|
|
105
|
+
choices().find(choice => choice.label.startsWith('codemode')).focus();
|
|
106
|
+
joining.updateResult(success('anchored-code'));
|
|
107
|
+
assert.equal(owner(earlier).group.pane, earlierGroup, 'completion reuses the prior ordinary group');
|
|
108
|
+
assert.equal(earlierGroup.selected, 2); assert.equal(earlierGroup.offset, 0);
|
|
109
|
+
assert.match(paint(earlier), /source-anchored-code/, 'focus handoff anchors at code beyond a large earlier output');
|
|
110
|
+
assert.doesNotMatch(paint(earlier), /earlier-output/); assert.equal(paint(joining), '');
|
|
111
|
+
|
|
112
|
+
for (const envelope of [true, false]) {
|
|
113
|
+
reset();
|
|
114
|
+
const timed = make('codemode', `timed-${envelope}`, { code: 'text(1);' });
|
|
115
|
+
timed.updateResult({ durationMs: 73250, content: [...(envelope ? [{ type: 'text', text: 'Script completed\nWall time 73.25 seconds\nOutput:\n' }] : []), { type: 'text', text: 'timed output' }], details: { calls: [] } });
|
|
116
|
+
done('read', `after-timed-${envelope}`);
|
|
117
|
+
choices()[0].focus(); input('\r');
|
|
118
|
+
const timing = paint(timed);
|
|
119
|
+
assert.match(timing, envelope ? /Wall time 73\.25 seconds/ : /Took 73\.25s/, 'mixed code retains recorded or context-only duration');
|
|
120
|
+
if (envelope) assert.doesNotMatch(timing, /Took 73\.25s/, 'the recorded envelope does not get duplicate timing');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
reset();
|
|
124
|
+
const before = done('bash', 'before'), live = make('codemode', 'live');
|
|
125
|
+
live.markExecutionStarted(); live.updateResult(success('live', [{ name: 'read', args: '/live', status: 'running' }]), true);
|
|
126
|
+
const after = done('read', 'after');
|
|
127
|
+
assert.equal(owner(live).group, undefined); assert.match(paint(live), /Running/);
|
|
128
|
+
assert.match(paint(before), /bash/); assert.match(paint(after), /after/);
|
|
129
|
+
event('tool_execution_end', { toolCallId: 'live', toolName: 'codemode', result: success('live') });
|
|
130
|
+
live.updateResult(success('live'));
|
|
131
|
+
assert.match(paint(before), /3 actions/); assert.equal(paint(live), ''); assert.equal(paint(after), '');
|
|
132
|
+
const mutable = success('live'); live.updateResult(mutable);
|
|
133
|
+
mutable.details.calls[0].status = 'error'; mutable.details.calls[0].error = 'nested recorded error';
|
|
134
|
+
event('tool_execution_end', { toolCallId: 'live', toolName: 'codemode', result: mutable }); live.updateResult(mutable);
|
|
135
|
+
assert.equal(owner(live).group, undefined, 'in-place final revision removes stale successful membership');
|
|
136
|
+
assert.match(paint(live), /1 nested error/); assert.match(paint(after), /after/); assert.doesNotMatch(paint(before), /3 actions/);
|
|
137
|
+
mutable.details.calls[0].status = 'ok'; delete mutable.details.calls[0].error;
|
|
138
|
+
event('tool_execution_end', { toolCallId: 'live', toolName: 'codemode', result: mutable }); live.updateResult(mutable);
|
|
139
|
+
assert.match(paint(before), /3 actions/); assert.equal(paint(live), '');
|
|
140
|
+
|
|
141
|
+
const blockers = [
|
|
142
|
+
['nested-error', success('bad', [{ name: 'read', args: '', status: 'error', error: 'failed' }])],
|
|
143
|
+
['nested-cancelled', success('bad', [{ name: 'read', args: '', status: 'cancelled' }])],
|
|
144
|
+
['nested-unresolved', success('bad', [{ name: 'read', args: '', status: 'running' }])],
|
|
145
|
+
['unknown-status', success('bad', [{ name: 'read', args: '', status: 'unavailable' }])],
|
|
146
|
+
['recorded-error', success('bad', [{ name: 'read', args: '', status: 'ok', error: 'recorded diagnostic' }])],
|
|
147
|
+
['warning', success('bad', [], { warning: 'inspect this warning' })],
|
|
148
|
+
['warnings', success('bad', [], { warnings: ['inspect this warning'] })],
|
|
149
|
+
['outer-status', success('bad', [], { status: 'cancelled' })],
|
|
150
|
+
['outer-error', { ...success('bad'), isError: true }],
|
|
151
|
+
['image', { content: [{ type: 'image', mimeType: 'image/png', data: '' }], details: { calls: [] } }],
|
|
152
|
+
];
|
|
153
|
+
for (const [id, record] of blockers) {
|
|
154
|
+
reset(); const left = done('read', `left-${id}`), blocked = done('codemode', id, record), right = done('read', `right-${id}`);
|
|
155
|
+
assert.equal(owner(blocked).group, undefined, `${id} remains standalone`);
|
|
156
|
+
assert.equal(owner(left).group.members.length, 1); assert.equal(owner(right).group.members.length, 1);
|
|
157
|
+
assert.ok(paint(blocked), `${id} keeps a visible compact or native row`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Visible commentary, users, questions, and subagents remain boundaries; pure thinking does not.
|
|
161
|
+
for (const [label, message] of [
|
|
162
|
+
['commentary', { role: 'assistant', content: [{ type: 'text', text: 'Visible commentary' }] }],
|
|
163
|
+
['user', { role: 'user', content: [{ type: 'text', text: 'Continue' }] }],
|
|
164
|
+
['question', { role: 'assistant', content: [{ type: 'toolCall', id: 'question', name: 'ask_user_question', arguments: {} }] }],
|
|
165
|
+
['subagent', { role: 'assistant', content: [{ type: 'toolCall', id: 'agent', name: 'subagent', arguments: {} }] }],
|
|
166
|
+
]) {
|
|
167
|
+
reset(); const left = done('codemode', `boundary-${label}`); event('message_end', { message }); const right = done('read', `after-${label}`);
|
|
168
|
+
assert.equal(owner(left).group, undefined, `${label} separates code from ordinary actions`); assert.equal(owner(right).group.members.length, 1);
|
|
169
|
+
}
|
|
170
|
+
reset(); const thinkingCode = done('codemode', 'thinking-code');
|
|
171
|
+
event('message_end', { message: { role: 'assistant', content: [{ type: 'thinking', thinking: 'Private reasoning' }] } });
|
|
172
|
+
const thinkingRead = done('read', 'thinking-read'); assert.match(paint(thinkingCode), /2 actions/); assert.equal(paint(thinkingRead), '');
|
|
173
|
+
|
|
174
|
+
// History derives eligibility before renderers attach, including code-first order.
|
|
175
|
+
for (const names of [['bash', 'codemode', 'codemode', 'read'], ['codemode', 'read']]) {
|
|
176
|
+
reset();
|
|
177
|
+
const calls = names.map((name, index) => ({ type: 'toolCall', id: `replay-${index}`, name, arguments: name === 'codemode' ? { code: `text(${index});` } : name === 'bash' ? { command: 'git status' } : { path: '/fixture/replay' } }));
|
|
178
|
+
history = [{ type: 'message', message: { role: 'assistant', content: calls } }, ...calls.map(call => ({ type: 'message', message: { role: 'toolResult', toolCallId: call.id, toolName: call.name, ...(call.name === 'codemode' ? success(call.id) : { content: [{ type: 'text', text: 'replay output' }] }) } }))];
|
|
179
|
+
event('session_tree');
|
|
180
|
+
const replayed = calls.map(call => { const component = make(call.name, call.id, call.arguments); component.updateResult(call.name === 'codemode' ? success(call.id) : { content: [{ type: 'text', text: 'replay output' }] }); return component; });
|
|
181
|
+
assert.deepEqual(owner(replayed[0]).group.members.map(node => node.id), calls.map(call => call.id));
|
|
182
|
+
assert.equal(all(replayed).match(new RegExp(`${names.length} actions`, 'g'))?.length, 1, 'replay has one owner and no dropped summary');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
reset();
|
|
186
|
+
const huge = make('codemode', 'huge', { code: 'const longSource = 1;\n'.repeat(500000) });
|
|
187
|
+
const manyCalls = Array.from({ length: 20000 }, (_, index) => ({ name: 'read', args: `/nested/${index}`, status: 'ok' }));
|
|
188
|
+
huge.updateResult(success('huge', manyCalls)); const tail = done('read', 'tail');
|
|
189
|
+
const content = owner(huge).code.content, bounded = owner(huge).group.pane;
|
|
190
|
+
assert.equal(content.aggregateEntries, 20000); assert.equal(content.sourceCharacters, 0); assert.equal(content.paintedCalls, 0);
|
|
191
|
+
choices()[0].focus(); input('\r'); huge.render(100);
|
|
192
|
+
assert.ok(content.sourceCharacters <= 2048, 'group expansion formats one bounded code viewport');
|
|
193
|
+
assert.equal(content.paintedCalls, 0, 'group does not visit nested calls beyond the source viewport');
|
|
194
|
+
const characters = content.sourceCharacters, painted = bounded.paintedRows;
|
|
195
|
+
for (let index = 0; index < 5; index++) { huge.invalidate(); huge.render(100); }
|
|
196
|
+
assert.equal(content.aggregateEntries, 20000, 'unchanged redraws do not rescan nested records');
|
|
197
|
+
assert.equal(content.sourceCharacters, characters); assert.equal(bounded.paintedRows, painted, 'group reuses visited row cache');
|
|
198
|
+
for (const width of [1, 8, 40, 100]) for (const row of huge.render(width)) assert.ok(tui.visibleWidth(row) <= width);
|
|
199
|
+
assert.equal(paint(tail), '');
|
|
200
|
+
console.log('mixed action groups: order, slots, inspection, transitions, exceptions, replay and bounded formatting passed');
|
|
201
|
+
} finally { dispose(); }
|
|
@@ -3,7 +3,7 @@ import { createRequire } from 'node:module';
|
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { pathToFileURL } from 'node:url';
|
|
6
|
-
import { assertCardBackground, themeModule as nativeTheme, stripAnsi } from './test-runtime.mjs';
|
|
6
|
+
import { assertCardBackground, backgroundCells, themeModule as nativeTheme, stripAnsi } from './test-runtime.mjs';
|
|
7
7
|
|
|
8
8
|
const runtime = process.env.PI_RUNTIME || path.join(homedir(), '.local/state/pi-config/current/runtime');
|
|
9
9
|
const root = process.env.PI_INSTALL_ROOT || path.join(runtime, 'node_modules/@earendil-works/pi-coding-agent');
|
|
@@ -25,9 +25,22 @@ for (const details of [false, true]) {
|
|
|
25
25
|
const selected = rows.findIndex(row => stripAnsi(row).includes('→'));
|
|
26
26
|
assert.ok(selected >= 0, 'native permission selection stays visible at narrow widths');
|
|
27
27
|
assertCardBackground([rows[selected]], width, 'selectedBg');
|
|
28
|
-
|
|
28
|
+
assert.ok(rows.filter((_, index) => index !== selected).every(row => backgroundCells(row).every(color => color === '')),
|
|
29
|
+
'only the selected choice has a filled background');
|
|
30
|
+
if (width === 100) {
|
|
31
|
+
assert.equal(stripAnsi(rows[0]).trim(), '', 'approval has top breathing room');
|
|
32
|
+
assert.equal(stripAnsi(rows.at(-1)).trim(), '', 'approval has bottom breathing room');
|
|
33
|
+
}
|
|
29
34
|
}
|
|
30
35
|
}
|
|
36
|
+
const approvalLines = styled.render(100).map(stripAnsi);
|
|
37
|
+
const firstChoice = approvalLines.findIndex(row => row.includes('Allow once'));
|
|
38
|
+
assert.equal(approvalLines[firstChoice - 1].trim(), '', 'summary and choices are separated');
|
|
39
|
+
for (const width of [16, 18, 20, 40, 80]) {
|
|
40
|
+
const shortScreen = new PermissionDialog(description, theme, () => {}, () => {}, () => 24);
|
|
41
|
+
shortScreen.handleInput('d');
|
|
42
|
+
assert.ok(shortScreen.render(width).length <= 24, 'optional spacing yields to approval controls on a narrow screen');
|
|
43
|
+
}
|
|
31
44
|
|
|
32
45
|
// Native keybindings, safe default, single resolution and bounded Details.
|
|
33
46
|
let resolutions = [];
|
|
@@ -10,7 +10,7 @@ const { core, runtime, manager, temporary, runtimePath, cwd } = preview;
|
|
|
10
10
|
const load = file => import(pathToFileURL(path.join(runtimePath, 'node_modules/@earendil-works/pi-coding-agent/dist', file)).href);
|
|
11
11
|
const { initTheme, theme } = await load('modes/interactive/theme/theme.js');
|
|
12
12
|
const { codemodeRenderers } = await load('extensions/codemode/renderer.js');
|
|
13
|
-
const { Text } = await import(pathToFileURL(
|
|
13
|
+
const { Text } = await import(pathToFileURL(preview.tuiPath).href);
|
|
14
14
|
const strip = value => value.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g, '');
|
|
15
15
|
const paint = (component, width = 100) => strip(component.render(width).join('\n'));
|
|
16
16
|
initTheme('dark', false);
|
|
@@ -70,11 +70,10 @@ const replay = () => {
|
|
|
70
70
|
return display.chatContainer.children.filter(row => row instanceof ToolExecutionComponent);
|
|
71
71
|
};
|
|
72
72
|
const assertCompactHistory = (rows, label) => {
|
|
73
|
-
assert.match(paint(rows[0]), /▸
|
|
73
|
+
assert.match(paint(rows[0]), /▸ 3 actions/, `${label}: historical bash, namespaced MCP and clean codemode results stay grouped`);
|
|
74
74
|
assert.doesNotMatch(paint(rows[0]), /EXACT_RECORDED_BASH_OUTPUT|EXACT_RECORDED_MCP_OUTPUT/, `${label}: grouped output stays collapsed`);
|
|
75
75
|
assert.equal(paint(rows[1]), '', `${label}: the second historical action does not duplicate the group`);
|
|
76
|
-
assert.
|
|
77
|
-
assert.doesNotMatch(paint(rows[2]), /RECORDED_CODE_SOURCE|EXACT_RECORDED_CODE_OUTPUT/, `${label}: codemode source and output stay collapsed`);
|
|
76
|
+
assert.equal(paint(rows[2]), '', `${label}: historical codemode does not duplicate the mixed group`);
|
|
78
77
|
assert.match(paint(rows[3]), /▸ read .*1 image/, `${label}: direct image read keeps its compact heading and image count`);
|
|
79
78
|
assert.match(paint(rows[4]), /▸ codemode.*2 images/, `${label}: image-bearing codemode keeps its compact heading and image count`);
|
|
80
79
|
for (const [row, count] of [[rows[3], 1], [rows[4], 2]]) {
|
|
@@ -129,7 +128,8 @@ try {
|
|
|
129
128
|
assert.equal(paint(freshMcp), '');
|
|
130
129
|
assert.doesNotMatch(paint(freshBash), /EXACT_RECORDED_BASH_OUTPUT|EXACT_RECORDED_MCP_OUTPUT/);
|
|
131
130
|
const freshCode = create({ ...fixture[2], id: 'fresh-code' });
|
|
132
|
-
assert.match(paint(
|
|
131
|
+
assert.match(paint(freshBash), /▸ 3 actions/);
|
|
132
|
+
assert.equal(paint(freshCode), '');
|
|
133
133
|
assert.doesNotMatch(paint(freshCode), /RECORDED_CODE_SOURCE|EXACT_RECORDED_CODE_OUTPUT/);
|
|
134
134
|
assertCompactHistory(rows, 'fresh calls preserve historical groups');
|
|
135
135
|
|
|
@@ -146,7 +146,7 @@ try {
|
|
|
146
146
|
invalidate(rows);
|
|
147
147
|
assert.match(paint(rows[0]), /EXACT_RECORDED_BASH_OUTPUT/, 'detached old bash row uses native fallback after switch');
|
|
148
148
|
assert.match(paint(rows[1]), /EXACT_RECORDED_MCP_OUTPUT/, 'detached old MCP row uses native fallback after switch');
|
|
149
|
-
assert.doesNotMatch(paint(rows[0]), /▸
|
|
149
|
+
assert.doesNotMatch(paint(rows[0]), /▸ 3 actions/, 'detached row cannot adopt the new session group');
|
|
150
150
|
assertCompactHistory(replacementRows, 'late detached-row invalidation');
|
|
151
151
|
|
|
152
152
|
event('session_shutdown', { reason: 'shutdown' });
|
package/tests/test-runtime.mjs
CHANGED
|
@@ -6,8 +6,10 @@ import assert from 'node:assert/strict';
|
|
|
6
6
|
|
|
7
7
|
export const runtime = path.resolve(process.env.PI_RUNTIME || path.join(homedir(), '.local/state/pi-config/current/runtime'));
|
|
8
8
|
export const agentRoot = path.resolve(process.env.PI_INSTALL_ROOT || path.join(runtime, 'node_modules/@earendil-works/pi-coding-agent'));
|
|
9
|
-
export const tuiRoot = path.join(path.dirname(agentRoot), 'pi-tui');
|
|
10
9
|
const require = createRequire(path.join(agentRoot, 'package.json'));
|
|
10
|
+
// Use Pi's own TUI dependency even when another extension installs a newer
|
|
11
|
+
// version at the runtime root; native component identity must match the aliases.
|
|
12
|
+
export const tuiRoot = path.dirname(path.dirname(require.resolve('@earendil-works/pi-tui')));
|
|
11
13
|
const { createJiti } = require('jiti');
|
|
12
14
|
const sourceOptions = { fsCache: false, alias: {
|
|
13
15
|
'@earendil-works/pi-coding-agent': path.join(agentRoot, 'dist/index.js'),
|
|
@@ -4,7 +4,7 @@ import {pathToFileURL} from 'node:url';
|
|
|
4
4
|
import {createWorkStripPreview} from '../scripts/preview-work-strip.mjs';
|
|
5
5
|
const preview=await createWorkStripPreview({stepMs:20});
|
|
6
6
|
const {core,runtime,manager}=preview;
|
|
7
|
-
const {visibleWidth}=await import(pathToFileURL(
|
|
7
|
+
const {visibleWidth}=await import(pathToFileURL(preview.tuiPath));
|
|
8
8
|
const {theme,initTheme}=await import(pathToFileURL(path.join(preview.runtimePath,'node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js')));
|
|
9
9
|
initTheme('dark',false);
|
|
10
10
|
const strip=s=>s.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]/g,'');
|