@notrico/pi-fold 0.0.0-stage → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/LICENSE +21 -0
- package/README.md +71 -2
- package/docs/implementation.md +47 -0
- package/docs/performance.md +118 -0
- package/docs/renderer-reference.md +110 -0
- package/index.ts +53 -0
- package/package.json +55 -4
- package/scripts/performance-review.mjs +273 -0
- package/scripts/preview-inspection.mjs +9 -0
- package/scripts/preview-work-strip.mjs +101 -0
- package/scripts/preview.mjs +232 -0
- package/scripts/retained-memory-review.mjs +46 -0
- package/scripts/test.mjs +21 -0
- package/src/action-intent.ts +93 -0
- package/src/display-card.ts +66 -0
- package/src/display-line-cache.ts +26 -0
- package/src/display-mode.ts +33 -0
- package/src/fold-command.ts +61 -0
- package/src/inspection.ts +87 -0
- package/src/modern-code-content.ts +131 -0
- package/src/modern-code-pane.ts +103 -0
- package/src/modern-native-tools.ts +79 -0
- package/src/modern-prompts-adapter.ts +41 -0
- package/src/modern-prompts.ts +185 -0
- package/src/modern-recorded-pane.ts +68 -0
- package/src/modern-rich-text.ts +48 -0
- package/src/modern-skill-prompts.ts +152 -0
- package/src/modern-subagent-groups.ts +158 -0
- package/src/modern-subagent-messages.ts +176 -0
- package/src/modern-subagent-spacing.ts +35 -0
- package/src/modern-subagents.ts +52 -0
- package/src/modern-thinking-adapter.ts +85 -0
- package/src/modern-thinking.ts +258 -0
- package/src/modern-tool-content.ts +28 -0
- package/src/modern-tool-images.ts +63 -0
- package/src/modern-tool-pane.ts +219 -0
- package/src/modern-tools.ts +509 -0
- package/src/modern-workflows.ts +212 -0
- package/src/native-method-chain.ts +31 -0
- package/src/permission-presentation.ts +280 -0
- package/src/recorded-summary.ts +13 -0
- package/src/work-strip-subagents.ts +221 -0
- package/src/work-strip-view.ts +112 -0
- package/src/work-strip.ts +443 -0
- package/tests/action-intent.test.mjs +44 -0
- package/tests/codemode.test.mjs +388 -0
- package/tests/display-cache-lifecycle.test.mjs +55 -0
- package/tests/display-line-cache.test.mjs +48 -0
- package/tests/display-mode.test.mjs +25 -0
- package/tests/fixtures/preview-fixture.ts +81 -0
- package/tests/fold-command.test.mjs +150 -0
- package/tests/fold-shortcut.test.mjs +143 -0
- package/tests/input-focus.test.mjs +95 -0
- package/tests/inspection-wheel.test.mjs +73 -0
- package/tests/inspection.test.mjs +50 -0
- package/tests/mixed-thinking.test.mjs +371 -0
- package/tests/modern-prompts.test.mjs +84 -0
- package/tests/modern-skill-prompts.test.mjs +174 -0
- package/tests/modern-subagent-groups.test.mjs +132 -0
- package/tests/modern-subagent-messages.test.mjs +137 -0
- package/tests/modern-thinking.test.mjs +202 -0
- package/tests/modern-tools.test.mjs +961 -0
- package/tests/modern-workflows.test.mjs +189 -0
- package/tests/ordinary-prompts.test.mjs +167 -0
- package/tests/permission-presentation.test.mjs +257 -0
- package/tests/preview-example.test.mjs +171 -0
- package/tests/reload-lifecycle.test.mjs +161 -0
- package/tests/subagent-spacing.test.mjs +34 -0
- package/tests/test-runtime.mjs +58 -0
- package/tests/work-strip-final-surface.test.mjs +321 -0
- package/tests/work-strip-hierarchy.test.mjs +258 -0
- package/tests/work-strip-preview.test.mjs +120 -0
- package/tests/work-strip-spacing.test.mjs +208 -0
- package/tests/work-strip-subagents.test.mjs +236 -0
- package/tests/work-strip.test.mjs +148 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Actual Pi TUI with invented records and an isolated temporary home. No credentials or live services.
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const source = fileURLToPath(new URL('../', import.meta.url));
|
|
9
|
+
export async function createPreview() {
|
|
10
|
+
const hostHome = os.homedir();
|
|
11
|
+
const runtimePath = path.resolve(process.env.PI_RUNTIME || path.join(hostHome, '.local/state/pi-config/current/runtime'));
|
|
12
|
+
const promptJump = process.env.PI_PROMPT_JUMP_PATH ? path.resolve(process.env.PI_PROMPT_JUMP_PATH) : undefined;
|
|
13
|
+
const questionCandidates = process.env.PI_QUESTIONS_PATH ? [path.resolve(process.env.PI_QUESTIONS_PATH)] : [
|
|
14
|
+
path.join(hostHome, '.local/state/pi-config/current/packages/pi-questions/index.ts'),
|
|
15
|
+
path.join(runtimePath, 'node_modules/pi-questions/index.ts'),
|
|
16
|
+
path.join(hostHome, 'Code/pi-config/packages/pi-questions/index.ts'),
|
|
17
|
+
];
|
|
18
|
+
let questionsPath;
|
|
19
|
+
for (const candidate of questionCandidates) {
|
|
20
|
+
if (await fs.stat(candidate).then(stat => stat.isFile(), () => false)) { questionsPath = candidate; break; }
|
|
21
|
+
}
|
|
22
|
+
if (process.env.PI_QUESTIONS_PATH && !questionsPath) throw new Error('PI_QUESTIONS_PATH must point to an existing pi-questions/index.ts.');
|
|
23
|
+
const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-fold-preview-'));
|
|
24
|
+
const agentDir = path.join(temporary, '.pi/agent'), cwd = path.join(temporary, 'fixture');
|
|
25
|
+
const savedEnv = new Map();
|
|
26
|
+
const setEnv = (key, value) => { savedEnv.set(key, process.env[key]); if (value === undefined) delete process.env[key]; else process.env[key] = value; };
|
|
27
|
+
const originalFetch = globalThis.fetch;
|
|
28
|
+
let runtime;
|
|
29
|
+
const cleanup = async () => {
|
|
30
|
+
try { await runtime?.dispose(); }
|
|
31
|
+
finally {
|
|
32
|
+
globalThis.fetch = originalFetch;
|
|
33
|
+
for (const [key, value] of savedEnv) { if (value === undefined) delete process.env[key]; else process.env[key] = value; }
|
|
34
|
+
await fs.rm(temporary, { recursive: true, force: true });
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
try {
|
|
38
|
+
await fs.mkdir(agentDir, { recursive: true }); await fs.mkdir(cwd);
|
|
39
|
+
setEnv('PI_PREVIEW_SUBAGENT_RENDERERS', pathToFileURL(path.join(runtimePath, 'node_modules/pi-subagents/src/tui/subagent-messages.js')).href);
|
|
40
|
+
setEnv('HOME', temporary); setEnv('PI_CODING_AGENT_DIR', agentDir); setEnv('PI_OFFLINE', '1');
|
|
41
|
+
for (const key of Object.keys(process.env)) if (/(?:API_KEY|ACCESS_TOKEN|AUTH_TOKEN)$/.test(key)) setEnv(key, undefined);
|
|
42
|
+
globalThis.fetch = async () => { throw new Error('Network disabled in renderer preview'); };
|
|
43
|
+
const core = await import(pathToFileURL(path.join(runtimePath, 'node_modules/@earendil-works/pi-coding-agent/dist/index.js')).href);
|
|
44
|
+
const template = 'This is an invented long prompt template used only to inspect display behavior. Review the recorded examples, expand the tool groups, and compare native display. No commands should run and no services should be contacted.';
|
|
45
|
+
await fs.mkdir(path.join(agentDir, 'prompts'));
|
|
46
|
+
await fs.writeFile(path.join(agentDir, 'prompts/fixture.md'), `---\ndescription: Inspect synthetic tool, question, and skill display examples.\n---\n${template}`);
|
|
47
|
+
const skillDir = path.join(agentDir, 'skills/fixture-review');
|
|
48
|
+
const skillBody = '# Review the synthetic preview\n\nRead the invented sample identifiers and units. Expand the recorded tool outputs and retain missing-value warnings. This skill text is a display fixture; it performs no operation.';
|
|
49
|
+
await fs.mkdir(skillDir, { recursive: true });
|
|
50
|
+
await fs.writeFile(path.join(skillDir, 'SKILL.md'), `---\nname: fixture-review\ndescription: Review invented sample records for a display exercise.\n---\n${skillBody}\n`);
|
|
51
|
+
await fs.writeFile(path.join(agentDir, 'settings.json'), JSON.stringify({
|
|
52
|
+
packages: [source, ...(promptJump ? [promptJump] : [])],
|
|
53
|
+
extensions: [path.join(source, 'tests/fixtures/preview-fixture.ts'), ...(questionsPath ? [questionsPath] : []), ...(process.env.PI_PREVIEW_STATUSLINE ? [path.resolve(process.env.PI_PREVIEW_STATUSLINE)] : [])],
|
|
54
|
+
hideThinkingBlock: true, theme: 'dark', compaction: { enabled: false }, terminal: { showImages: true },
|
|
55
|
+
}));
|
|
56
|
+
const manager = core.SessionManager.inMemory(cwd);
|
|
57
|
+
const now = Date.now(); let sequence = 0;
|
|
58
|
+
const append = message => manager.appendMessage({ ...message, timestamp: now + sequence++ });
|
|
59
|
+
const assistant = (content, stopReason = 'stop') => append({ role: 'assistant', content, api: 'openai-codex-responses', provider: 'openai-codex', model: 'gpt-6-luna', stopReason,
|
|
60
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });
|
|
61
|
+
const call = (id, name, args, output, details = {}, isError = false, thinking = '', durationMs) => {
|
|
62
|
+
assistant([...(thinking ? [{ type: 'thinking', thinking }] : []), { type: 'toolCall', id, name, arguments: args }], 'toolUse');
|
|
63
|
+
append({ role: 'toolResult', toolCallId: id, toolName: name, content: Array.isArray(output) ? output : [{ type: 'text', text: output }], details, isError, ...(durationMs === undefined ? {} : { durationMs }) });
|
|
64
|
+
};
|
|
65
|
+
append({ role: 'user', content: template });
|
|
66
|
+
call('write-1', 'write', { path: '/fixture/sample-a.txt', content: 'alpha' }, 'Successfully wrote to /fixture/sample-a.txt', {}, false, '**Inspect the sample fields**\n\n' + Array.from({ length: 70 }, (_, i) => `Synthetic paragraph ${i + 1}: compare the sample identifier, recorded units, and required fields. This is invented preview text, not model reasoning.`).join('\n\n'));
|
|
67
|
+
call('write-2', 'write', { path: '/fixture/sample-b.txt', content: 'beta' }, 'Successfully wrote to /fixture/sample-b.txt', {}, false, '# Compare the recorded output\n\n' + Array.from({ length: 70 }, (_, i) => `Synthetic paragraph ${i + 1}: inspect the fixture output and retain missing-value warnings. This is invented preview text for scrolling tests.`).join('\n\n'));
|
|
68
|
+
call('read-1', 'read', { path: '/fixture/sample-a.txt', offset: null, limit: null }, 'alpha');
|
|
69
|
+
call('read-density-2', 'read', { path: '/fixture/sample-b.txt', offset: null, limit: null }, 'beta');
|
|
70
|
+
call('missing-density', 'read', { path: '/fixture/missing.txt', offset: null, limit: null }, "ENOENT: no such file or directory, access '/fixture/missing.txt'", {}, true);
|
|
71
|
+
assistant([{ type: 'text', text: 'Visible reply: the four actions above form one group. The missing-file error stays separate. Expand an action for content, then its Details for exact arguments and diagnostics. /fixture above is a prompt template; the native [skill] example appears below.' }]);
|
|
72
|
+
append({ role: 'user', content: 'Show the recorded native JavaScript, detailed questions, and failure examples.' });
|
|
73
|
+
const code = [
|
|
74
|
+
'// Synthetic recording only. This script is never executed.',
|
|
75
|
+
'const reads = await Promise.allSettled([',
|
|
76
|
+
' tools.read({ path: "/fixture/sample-a.json" }),',
|
|
77
|
+
' tools.read({ path: "/fixture/missing.json" }),',
|
|
78
|
+
']);',
|
|
79
|
+
'const classifier = { provider: "fixture", id: "synthetic-classifier" };',
|
|
80
|
+
'const checks = await Promise.all(["sample-a", "sample-b"].map(sample =>',
|
|
81
|
+
' models.classify(classifier, {',
|
|
82
|
+
' state: { sample, units: "kg/L" },',
|
|
83
|
+
' questions: { complete: { type: "bool", instructions: "Are units recorded?",',
|
|
84
|
+
' criteria: { true: "Units present", false: "Units missing" } } },',
|
|
85
|
+
' })',
|
|
86
|
+
'));',
|
|
87
|
+
'text({ available: reads.filter(item => item.status === "fulfilled").length,',
|
|
88
|
+
' checks: checks.map(item => item.answers.complete) });',
|
|
89
|
+
].join('\n');
|
|
90
|
+
call('code-1', 'codemode', { code }, [
|
|
91
|
+
{ type: 'text', text: 'Script completed\nWall time 1.48 seconds\nOutput:\n' },
|
|
92
|
+
{ type: 'text', text: 'Invented recording: 1 sample available; 2 checks retained. The missing-file error was handled.\nAll calls, durations, and costs shown here are synthetic. Nothing ran.' },
|
|
93
|
+
], { calls: [
|
|
94
|
+
{ name: 'read', args: '{"path":"/fixture/sample-a.json"}', status: 'ok', durationMs: 125 },
|
|
95
|
+
{ name: 'read', args: '{"path":"/fixture/missing.json"}', status: 'error', durationMs: 48, error: 'Invented missing file. No file was accessed.' },
|
|
96
|
+
{ name: 'models.classify', args: 'fixture/synthetic-classifier · sample-a', status: 'ok', durationMs: 690, cost: 0.0012 },
|
|
97
|
+
{ name: 'models.classify', args: 'fixture/synthetic-classifier · sample-b', status: 'ok', durationMs: 880, cost: 0.0018 },
|
|
98
|
+
] }, false, '', 1480);
|
|
99
|
+
call('code-inspect', 'codemode', { code: 'text(await tools.bash({command: "jq .status /fixture/record.json"}));\ntext(await tools.bash({command: "gh pr checks 327"}));' }, 'Synthetic inspection only. No files or pull requests were accessed.', { calls: [
|
|
100
|
+
{ name: 'bash', args: '{"command":"jq .status /fixture/record.json"}', status: 'ok', durationMs: 12 },
|
|
101
|
+
{ name: 'bash', args: '{"command":"gh pr checks 327"}', status: 'ok', durationMs: 21 },
|
|
102
|
+
] }, false, '', 33);
|
|
103
|
+
assistant([{ type: 'text', text: 'The next card is an ordinary Bash fallback carrying a long Node script. It is separate from native codemode above. Expand it to inspect the exact recorded command and JavaScript colors.' }]);
|
|
104
|
+
const shellScript = [
|
|
105
|
+
"node - <<'NODE'",
|
|
106
|
+
'// Synthetic recording only. This script is never executed.',
|
|
107
|
+
'const paths = ["/fixture/sample-a.json", "/fixture/sample-b.json"];',
|
|
108
|
+
'const records = paths.map((path, index) => ({ path, index, available: true }));',
|
|
109
|
+
'console.log(JSON.stringify({ records, count: records.length }, null, 2));',
|
|
110
|
+
'NODE',
|
|
111
|
+
].join('\n');
|
|
112
|
+
call('bash-node-singleton', 'bash', { command: shellScript }, 'Recorded JSON output: { "count": 2, "available": true }', { exitCode: 0 }, false,
|
|
113
|
+
'**Inspect the recorded script**\n\nCompare **path fields** and `count`.\n\n```javascript\nconst count = 2;\n```');
|
|
114
|
+
assistant([{ type: 'text', text: 'The previous script is one action. The next failure stays separate and keeps its exact long error inside the expanded card.' }]);
|
|
115
|
+
const longPathError = `Error: ENAMETOOLONG: name too long, lstat '${'/fixture/invented-long-path/'.repeat(180)}'`;
|
|
116
|
+
call('bash-node-path-failure', 'bash', { command: shellScript }, longPathError, { exitCode: 1, error: longPathError }, true);
|
|
117
|
+
assistant([{ type: 'text', text: 'The following four ordinary actions form a group. Expand them to compare source, diff, Markdown, and interpreter arguments with native syntax colors.' }]);
|
|
118
|
+
call('source-read', 'read', { path: '/fixture/source.js' }, 'const paths = ["/fixture/a", "/fixture/b"];\nexport const count = paths.length;');
|
|
119
|
+
call('source-edit', 'edit', { path: '/fixture/source.js', oldText: 'const count = 1;', newText: 'const count = 2;' }, 'Synthetic edit recorded.', { diff: '-const count = 1;\n+const count = 2;' });
|
|
120
|
+
call('markdown-read', 'read', { path: '/fixture/notes.md' }, '# Recorded notes\n\n**Complete:** both samples have `kg/L` units.\n\n- Keep the warning.\n- Compare the recorded count.\n\n```javascript\nconst count = 2;\n```');
|
|
121
|
+
call('bash-node-inline', 'bash', { command: `node -e 'const paths = ["/fixture/a", "/fixture/b"]; console.log(paths.length);'` }, '2', { exitCode: 0 });
|
|
122
|
+
const question = {
|
|
123
|
+
question: 'Which synthetic sample should the preview compare?',
|
|
124
|
+
details: 'Display exercise only. Your answer does not start an analysis or approve an operation.',
|
|
125
|
+
options: [
|
|
126
|
+
{ label: 'Sample A (Recommended)', value: 'sample-a', description: 'Inspect a complete invented record with explicit units.' },
|
|
127
|
+
{ label: 'Sample B', value: 'sample-b', description: 'Inspect an invented record with a missing-value warning.' },
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
call('question-1', 'ask_user_question', question, 'User selected: 1. Sample A (Recommended)', {
|
|
131
|
+
status: 'answered', question: question.question, context: question.details, mode: 'single-select',
|
|
132
|
+
answers: [{ type: 'option', label: 'Sample A (Recommended)', value: 'sample-a', index: 1 }],
|
|
133
|
+
});
|
|
134
|
+
call('question-other', 'ask_user_question', question, 'User selected: Other: Compare both samples and keep the warning', {
|
|
135
|
+
status: 'answered', question: question.question, context: question.details, mode: 'single-select',
|
|
136
|
+
answers: [{ type: 'other', label: 'Compare both samples and keep the warning', value: 'Compare both samples and keep the warning' }],
|
|
137
|
+
});
|
|
138
|
+
const textQuestion = { question: 'What label should this invented comparison use?', details: 'Free-text display example. The label is not saved to a report.' };
|
|
139
|
+
call('question-text', 'ask_user_question', textQuestion, 'User answered: Synthetic comparison · 中文', {
|
|
140
|
+
status: 'answered', question: textQuestion.question, context: textQuestion.details, mode: 'text',
|
|
141
|
+
answers: [{ type: 'text', label: 'Synthetic comparison · 中文', value: 'Synthetic comparison · 中文' }],
|
|
142
|
+
});
|
|
143
|
+
call('failed-1', 'bash', { command: 'fixture-failure' }, 'Invented failure: sample file not found. No command ran.', { exitCode: 1 }, true);
|
|
144
|
+
call('question-2', 'ask_user_question', question, 'User cancelled the question', {
|
|
145
|
+
status: 'cancelled', question: question.question, context: question.details, mode: 'single-select', answers: [], message: 'User cancelled the question',
|
|
146
|
+
});
|
|
147
|
+
if (process.env.PI_PREVIEW_WORK_STRIP === '1') assistant([{ type: 'text', text: 'Recorded preview decisions are shown above. The missing-input examples are preserved for inspection; no command ran.' }]);
|
|
148
|
+
// This is the same envelope Pi writes for /skill:fixture-review, including its optional user message.
|
|
149
|
+
append({ role: 'user', content: `<skill name="fixture-review" location="${path.join(skillDir, 'SKILL.md')}">\nReferences are relative to ${skillDir}.\n\n${skillBody}\n</skill>\n\nShow the native skill card and one final successful action.` });
|
|
150
|
+
call('read-2', 'read', { path: '/fixture/last.txt' }, 'Recorded final output.');
|
|
151
|
+
assistant([{ type: 'text', text: 'Preview controls: /inspect selects a compact block. Left/Right selects an action or thinking round; Enter expands it; Up/Down scrolls. Esc or typing returns to the editor. Ctrl+O expands native codemode and [skill] cards. /fixture-question opens the existing question UI; /fixture-question text opens free text. /fixture-permission opens a harmless approval dialog. /fold switches display. Ctrl+D exits. All records and prices are invented; no script or model ran.' }]);
|
|
152
|
+
if (!questionsPath) assistant([{ type: 'text', text: 'Native question UI is unavailable on this host. Recorded question cards still show schema-shaped examples. Set PI_QUESTIONS_PATH to an existing pi-questions/index.ts to enable /fixture-question.' }]);
|
|
153
|
+
if (promptJump) assistant([{ type: 'text', text: 'Prompt navigation: /prompt-jump list selects one of the three invented user prompts; /prompt-jump back returns; /prompt-jump end follows the latest output.' }]);
|
|
154
|
+
assistant([{ type: 'text', text: 'Subagent display examples follow. These records are invented. No child or workflow was launched.' }]);
|
|
155
|
+
for (const topic of ['tool-reference/parameter-reference', 'tool-reference/execution-parameters', 'tool-reference/fork-context-details']) {
|
|
156
|
+
call(`guide-${topic}`, 'subagent', { action: 'guide', options: { topic } }, `# ${topic}\n\nSynthetic guide content for inspection. No guide was fetched and no task was started.`, { mode: 'management', results: [] });
|
|
157
|
+
}
|
|
158
|
+
const workflow = [
|
|
159
|
+
'// Review the synthetic sample records',
|
|
160
|
+
'const brief = `Read /fixture/AGENTS.md before inspecting the samples.',
|
|
161
|
+
...Array.from({ length: 70 }, (_, i) => `Synthetic instruction ${i + 1}: retain recorded units and missing-field warnings.`),
|
|
162
|
+
'`;',
|
|
163
|
+
'return await runs.all([',
|
|
164
|
+
' { agent: "scout", task: brief + " Inspect sample A." },',
|
|
165
|
+
' { agent: "scout", task: brief + " Inspect sample B." },',
|
|
166
|
+
']);',
|
|
167
|
+
].join('\n');
|
|
168
|
+
assistant([{ type: 'text', text: 'The recorded workflow below is a display example. Nothing will execute.\n\n```js workflow\n' + workflow + '\n```\n\nThe following subagent records remain separate from this script.' }]);
|
|
169
|
+
call('child-launch', 'subagent', { agent: 'worker', task: 'Review the synthetic sample', async: true }, 'Async: worker [fixture-worker]', { mode: 'single', asyncId: 'fixture-worker', runId: 'fixture-worker', results: [] });
|
|
170
|
+
call('child-scout-launch', 'subagent', { agent: 'scout', task: 'Check the synthetic field names', async: true }, 'Async: scout [fixture-scout]', { mode: 'single', asyncId: 'fixture-scout', runId: 'fixture-scout', results: [] });
|
|
171
|
+
call('child-status', 'subagent', { action: 'status', id: 'fixture-worker' }, 'Synthetic worker is running. This status does not establish completion.', { mode: 'management', agent: 'worker', results: [] });
|
|
172
|
+
call('child-steer-error', 'subagent', { action: 'steer', id: 'fixture-workflow', message: 'Retain the units.' }, "Workflow 'fixture-workflow' has no live foreground child. Choose an exact child ID.", { mode: 'management', results: [] }, true);
|
|
173
|
+
call('child-steer', 'subagent', { action: 'steer', id: 'fixture-worker', message: 'Retain the units.' }, 'Steering queued for async run fixture-worker. Queued does not mean consumed.', { mode: 'management', results: [], steering: { requestId: 'fixture-steer', state: 'pending', deliveryStatus: 'queued', sourceRunId: 'fixture-worker', targets: [{ index: 0, state: 'pending' }] } });
|
|
174
|
+
manager.appendCustomMessageEntry('subagent_supervisor_request', 'Should the synthetic report retain records with missing units?\n\nKeep the warning visible. No business data is involved.', true, { id: 'fixture-request', requestId: 'fixture-request', reason: 'need_decision', expectsReply: true, runId: 'fixture-worker', agent: 'worker', childIndex: 0, requestBody: 'Should the synthetic report retain records with missing units?', replyHint: 'Reply to fixture-request.' });
|
|
175
|
+
call('child-reply', 'subagent_supervisor', { action: 'reply', replyTo: 'fixture-request', message: 'Retain the record and its missing-unit warning.' }, 'Replied to supervisor request fixture-request.', { replyTo: 'fixture-request', runId: 'fixture-worker', agent: 'worker' });
|
|
176
|
+
manager.appendCustomEntry('subagent_supervisor_reply', { requestId: 'fixture-request', runId: 'fixture-worker', agent: 'worker', childIndex: 0, message: 'Retain the record and its missing-unit warning.' });
|
|
177
|
+
manager.appendCustomMessageEntry('subagent-notify', 'Synthetic worker completed. The report retains the missing-unit warning. Nothing was executed.', true, { runs: [{ agent: 'worker', status: 'completed' }] });
|
|
178
|
+
manager.appendCustomMessageEntry('subagent-notify', 'Synthetic researcher failed because the fixture input is unavailable. No external source was accessed.', true, { runs: [{ agent: 'researcher', status: 'failed' }] });
|
|
179
|
+
assistant([{ type: 'text', text: 'This visible reply separates the next activity. The decision below has no recorded reply and must stay pending.' }]);
|
|
180
|
+
manager.appendCustomMessageEntry('subagent_supervisor_request', 'Which synthetic sample should the scout inspect next?', true, { id: 'fixture-pending', requestId: 'fixture-pending', reason: 'need_decision', expectsReply: true, runId: 'fixture-scout', agent: 'scout', childIndex: 1, requestBody: 'Which synthetic sample should the scout inspect next?', replyHint: 'Reply to fixture-pending.' });
|
|
181
|
+
assistant([{ type: 'text', text: 'Image-output regression preview: the next codemode contains three recorded PNGs plus a long text result. It should keep one compact heading; the separate image read should also have only one heading. Expand to show the cyan, purple and green test chart; collapse to hide it. Native terminal support controls image display; tmux shows a fallback. No tools or scripts run.' }]);
|
|
182
|
+
// Deterministic 640×320 test chart: cyan, purple and green bars on a checkerboard.
|
|
183
|
+
const pixel = { type: 'image', mimeType: 'image/png', data: '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' };
|
|
184
|
+
const sampleImagePath = path.join(cwd, 'sample-a.png');
|
|
185
|
+
await fs.writeFile(sampleImagePath, Buffer.from(pixel.data, 'base64'));
|
|
186
|
+
const imageCode = 'for (const name of ["sample-a.png", "sample-b.png", "sample-c.png"]) {\n image(await tools.read({ path: "/fixture/" + name }));\n}\ntext(await tools.read({ path: "/fixture/result.json" }));';
|
|
187
|
+
call('code-images', 'codemode', { code: imageCode }, [
|
|
188
|
+
{ type: 'text', text: 'Script completed\nWall time 1.9 seconds\nOutput:\n' },
|
|
189
|
+
{ ...pixel }, { ...pixel }, { ...pixel },
|
|
190
|
+
{ type: 'text', text: JSON.stringify({ outcome: 'ok', records: Array.from({ length: 90 }, (_, i) => ({ sample: i + 1, status: 'synthetic' })) }, null, 2) },
|
|
191
|
+
], { calls: ['sample-a.png', 'sample-b.png', 'sample-c.png', 'result.json'].map(name => ({ name: 'read', args: JSON.stringify({ path: '/fixture/' + name }), status: 'ok', durationMs: 1 })) }, false, '', 1900);
|
|
192
|
+
assistant([{ type: 'text', text: 'Separate image read: expand this row to inspect the recorded content and Details. Esc should return to normal prompt typing.' }]);
|
|
193
|
+
call('read-image', 'read', { path: sampleImagePath }, [{ type: 'text', text: 'Read image file [image/png]' }, { ...pixel }]);
|
|
194
|
+
manager.appendSessionInfo('pi-fold-preview');
|
|
195
|
+
const eventBus = core.createEventBus();
|
|
196
|
+
assistant([
|
|
197
|
+
{ type: 'thinking', thinking: '**Compare the recorded samples**\n\nSynthetic preview only: compare the two recorded sample labels and retain their units. This text is invented, not model reasoning.' },
|
|
198
|
+
{ type: 'text', text: 'Single-round example: this reply stays outside the thinking block. Expand the summary above in one step; collapse it and check that the arrow aligns with the action rows.' },
|
|
199
|
+
]);
|
|
200
|
+
call('single-thinking-read', 'read', { path: '/fixture/summary.txt' }, 'Recorded sample summary.', {}, false, '# Check the recorded units\n\nSynthetic preview only: the sample units are present in the fixture. This is invented text for the single-round tool-call example.');
|
|
201
|
+
assistant([{ type: 'text', text: 'The single-round tool example above uses the same summary and disclosure. /inspect opens either thinking block; Esc or typing returns to the editor. No model or tool executed.' }]);
|
|
202
|
+
const factory = async ({ sessionManager, sessionStartEvent }) => {
|
|
203
|
+
const modelRuntime = await core.ModelRuntime.create({ authPath: path.join(agentDir, 'auth.json'), modelsPath: null, allowModelNetwork: false, refreshOnCreate: false });
|
|
204
|
+
const services = await core.createAgentSessionServices({ cwd, agentDir, modelRuntime,
|
|
205
|
+
resourceLoaderOptions: { eventBus, disabledBuiltinExtensions: ['codemode', 'mcp', 'tool-search', 'llama.cpp'], noContextFiles: true } });
|
|
206
|
+
for (const extension of services.resourceLoader.getExtensions().extensions) {
|
|
207
|
+
const question = extension.tools.get('ask_user_question');
|
|
208
|
+
if (question) {
|
|
209
|
+
eventBus.emit('preview:question-ui:v1', question.definition);
|
|
210
|
+
question.definition = { ...question.definition, execute: async () => { throw new Error('Tool execution is disabled in this preview.'); } };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const result = await core.createAgentSessionFromServices({ services, sessionManager, sessionStartEvent, noTools: 'builtin', model: modelRuntime.getModel('openai-codex', 'gpt-6-luna') });
|
|
214
|
+
result.session.setActiveToolsByName([]);
|
|
215
|
+
result.session.agent.streamFn = () => { throw new Error('Model calls disabled in renderer preview'); };
|
|
216
|
+
return { ...result, services, diagnostics: services.diagnostics };
|
|
217
|
+
};
|
|
218
|
+
runtime = await core.createAgentSessionRuntime(factory, { cwd, agentDir, sessionManager: manager });
|
|
219
|
+
const diagnostics = runtime.services.resourceLoader.getExtensions().errors;
|
|
220
|
+
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 };
|
|
222
|
+
} catch (error) { await cleanup(); throw error; }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
226
|
+
const preview = await createPreview();
|
|
227
|
+
let ui;
|
|
228
|
+
try {
|
|
229
|
+
ui = new preview.core.InteractiveMode(preview.runtime, { tuiMode: 'fullscreen' });
|
|
230
|
+
await ui.run();
|
|
231
|
+
} finally { ui?.stop(); await preview.cleanup(); }
|
|
232
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Retained heap after GC, not temporary allocations. Synthetic sessions only.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { makeProjectionFixture, disposePerformanceReview } from './performance-review.mjs';
|
|
5
|
+
import { loadSharedSource as loadSource, themeModule } from '../tests/test-runtime.mjs';
|
|
6
|
+
|
|
7
|
+
if (!globalThis.gc) throw new Error('Run with node --expose-gc');
|
|
8
|
+
const { fillBackground, clearDisplayLineCache } = await loadSource('./display-card.ts');
|
|
9
|
+
const heap = () => { for (let i = 0; i < 3; i++) globalThis.gc(); return process.memoryUsage().heapUsed; };
|
|
10
|
+
const releaseStack = () => new Promise(resolve => setImmediate(resolve));
|
|
11
|
+
const median = values => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];
|
|
12
|
+
const results = [];
|
|
13
|
+
try {
|
|
14
|
+
// Warm native classes before measuring fixture retention.
|
|
15
|
+
for (const enabled of [false, true]) {
|
|
16
|
+
let warm = makeProjectionFixture(8, enabled); warm.paint(); warm.dispose(); warm = undefined;
|
|
17
|
+
}
|
|
18
|
+
for (const turns of [48, 400]) for (const enabled of [false, true]) {
|
|
19
|
+
const retained = [], released = [], hashes = new Set();
|
|
20
|
+
for (let sample = 0; sample < 5; sample++) {
|
|
21
|
+
await releaseStack();
|
|
22
|
+
const before = heap();
|
|
23
|
+
let fixture = makeProjectionFixture(turns, enabled);
|
|
24
|
+
for (let i = 0; i < 3; i++) fixture.paint();
|
|
25
|
+
retained.push(heap() - before);
|
|
26
|
+
hashes.add(createHash('sha256').update(fixture.display.chatContainer.render(100).join('\n')).digest('hex'));
|
|
27
|
+
fixture.dispose(); fixture = undefined;
|
|
28
|
+
await releaseStack();
|
|
29
|
+
released.push(heap() - before);
|
|
30
|
+
}
|
|
31
|
+
results.push({ turns, enabled, retainedHeapBytes: median(retained), afterDisposeBytes: median(released), samples: retained, outputHashes: [...hashes] });
|
|
32
|
+
}
|
|
33
|
+
// Warm this formatting path and release previous fixture stacks before the
|
|
34
|
+
// saturation measurement; otherwise late collection obscures cache retention.
|
|
35
|
+
for (let i = 0; i < 20000; i++) fillBackground(`warm/${i} 检查 ${'x'.repeat(100)}`, 120, themeModule.theme, 'toolPendingBg');
|
|
36
|
+
clearDisplayLineCache?.(); await releaseStack();
|
|
37
|
+
const before = heap(), churn = [];
|
|
38
|
+
for (const count of [10000, 20000]) {
|
|
39
|
+
for (let i = 0; i < count; i++) fillBackground(`${count}/${i} 检查 ${'x'.repeat(100)}`, 120, themeModule.theme, 'toolPendingBg');
|
|
40
|
+
await releaseStack();
|
|
41
|
+
churn.push({ formattedRows: count, retainedHeapBytes: heap() - before });
|
|
42
|
+
}
|
|
43
|
+
clearDisplayLineCache?.(); await releaseStack();
|
|
44
|
+
console.log(JSON.stringify({ results, cacheChurn: churn, afterCacheClearBytes: heap() - before,
|
|
45
|
+
limits: ['Process heap deltas after explicit GC; allocator/JIT noise applies.', 'Fixtures include native components and renderer state; compare identical scripts against baseline source.', 'Cache accounting is not a JavaScript heap limit. No model, tools, terminal transport or user data.'] }, null, 2));
|
|
46
|
+
} finally { disposePerformanceReview(); }
|
package/scripts/test.mjs
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Every test runs in a fresh process: native prototype adapters cannot mask cleanup failures in other suites.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
const directory = fileURLToPath(new URL('../tests/', import.meta.url));
|
|
8
|
+
const required = ['action-intent.test.mjs', 'modern-workflows.test.mjs', 'display-mode.test.mjs', 'modern-tools.test.mjs', 'modern-subagent-messages.test.mjs', 'subagent-spacing.test.mjs', 'modern-subagent-groups.test.mjs', 'modern-thinking.test.mjs', 'modern-prompts.test.mjs', 'permission-presentation.test.mjs', 'input-focus.test.mjs', 'inspection.test.mjs', 'codemode.test.mjs', 'preview-example.test.mjs'];
|
|
9
|
+
required.push('reload-lifecycle.test.mjs', 'ordinary-prompts.test.mjs', 'work-strip-hierarchy.test.mjs', 'work-strip-final-surface.test.mjs');
|
|
10
|
+
required.push('modern-skill-prompts.test.mjs', 'inspection-wheel.test.mjs');
|
|
11
|
+
required.push('display-line-cache.test.mjs');
|
|
12
|
+
required.push('display-cache-lifecycle.test.mjs');
|
|
13
|
+
required.push('fold-command.test.mjs', 'fold-shortcut.test.mjs');
|
|
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
|
+
for (const name of required) {
|
|
16
|
+
if (!fs.existsSync(path.join(directory, name))) throw new Error(`Missing required regression suite: ${name}`);
|
|
17
|
+
const result = spawnSync(process.execPath, [path.join(directory, name)], { cwd: directory, env: process.env, stdio: 'inherit' });
|
|
18
|
+
if (result.error) throw result.error;
|
|
19
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
20
|
+
}
|
|
21
|
+
console.log('Pi Fold native regression suites passed');
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
type Action = { name: string; args: unknown };
|
|
2
|
+
const limit = 8192;
|
|
3
|
+
// Read recorded data without invoking accessors. Never include source values in a phrase.
|
|
4
|
+
function field(value: unknown, key: string): any {
|
|
5
|
+
if (!value || typeof value !== "object") return undefined;
|
|
6
|
+
try { return Object.getOwnPropertyDescriptor(value, key)?.value; } catch { return undefined; }
|
|
7
|
+
}
|
|
8
|
+
function argumentsObject(args: unknown): unknown {
|
|
9
|
+
if (typeof args !== "string") return args;
|
|
10
|
+
if (args.length > limit) return undefined;
|
|
11
|
+
try { return JSON.parse(args); } catch { return undefined; }
|
|
12
|
+
}
|
|
13
|
+
function combine(intents: string[], more = false): string {
|
|
14
|
+
const unique = [...new Set(intents)];
|
|
15
|
+
const first = unique[0] || "Run tool actions";
|
|
16
|
+
return first + (unique[1] ? ` and ${unique[1][0].toLowerCase()}${unique[1].slice(1)}` : "") +
|
|
17
|
+
(more || unique.length > 2 ? "; and other actions" : "");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A small shell lexer, not a shell interpreter. Quoted arguments cannot become commands.
|
|
21
|
+
* Reject substitutions, redirection, and unclosed quotes rather than interpreting scripts. */
|
|
22
|
+
function shellIntents(command: unknown): string[] {
|
|
23
|
+
if (typeof command !== "string" || command.length > limit || !command.trim()) return ["Run shell commands"];
|
|
24
|
+
const commands: string[][] = []; let words: string[] = [], word = "", quote = "", started = false;
|
|
25
|
+
const pushWord = () => { if (started) words.push(word); word = ""; started = false; };
|
|
26
|
+
const pushCommand = () => { pushWord(); if (words.length) commands.push(words); words = []; };
|
|
27
|
+
for (let i = 0; i < command.length; i++) {
|
|
28
|
+
const char = command[i];
|
|
29
|
+
if (char === "`" || char === "$" && command[i + 1] === "(" || !quote && /[<>()[\]{}]/.test(char)) return ["Run shell commands"];
|
|
30
|
+
if (char === "\\" && quote !== "'") { if (++i >= command.length) return ["Run shell commands"]; word += command[i]; started = true; continue; }
|
|
31
|
+
if (quote) { if (char === quote) quote = ""; else word += char; continue; }
|
|
32
|
+
if (char === "'" || char === '"') { quote = char; started = true; continue; }
|
|
33
|
+
if (char === "#" && !started) return ["Run shell commands"];
|
|
34
|
+
if (/[;|&\n]/.test(char)) pushCommand();
|
|
35
|
+
else if (/\s/.test(char)) pushWord();
|
|
36
|
+
else { word += char; started = true; }
|
|
37
|
+
if (commands.length > 32 || words.length > 128) return ["Run shell commands"];
|
|
38
|
+
}
|
|
39
|
+
if (quote) return ["Run shell commands"];
|
|
40
|
+
pushCommand();
|
|
41
|
+
const intents = commands.map(words => {
|
|
42
|
+
// Environment assignments and cd establish context; they do not supply an intent.
|
|
43
|
+
while (/^[A-Za-z_]\w*=/.test(words[0] || "")) words.shift();
|
|
44
|
+
const executable = (words[0] || "").split("/").at(-1), operation = words[1];
|
|
45
|
+
if (executable === "cd") return "";
|
|
46
|
+
if (executable === "git" && ["status", "diff", "log", "show", "ls-files", "rev-parse"].includes(operation)) return "Check Git changes";
|
|
47
|
+
if (executable === "gh" && ["pr", "checks"].includes(operation) && ["list", "view", "status", "checks", "diff", undefined].includes(words[2])) return "Check pull requests";
|
|
48
|
+
if (executable === "jq") return "Inspect JSON records";
|
|
49
|
+
if (["cat", "head", "tail"].includes(executable || "")) return "Read files";
|
|
50
|
+
if (["rg", "grep"].includes(executable || "")) return "Search files";
|
|
51
|
+
if (["ls", "pwd"].includes(executable || "") || executable === "find" && !words.some(word => ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf"].includes(word))) return "Inspect files";
|
|
52
|
+
if (["npm", "pnpm", "yarn", "bun"].includes(executable || "") &&
|
|
53
|
+
(["test", "check", "lint", "typecheck"].includes(operation) || operation === "run" && ["test", "check", "lint", "typecheck"].includes(words[2]))) return "Run checks";
|
|
54
|
+
if (["pytest", "vitest", "jest", "tsc"].includes(executable || "") || executable === "node" && (operation === "--test" || /\.(?:test|spec)\.[cm]?js$/.test(operation || ""))) return "Run checks";
|
|
55
|
+
return "Run shell commands";
|
|
56
|
+
}).filter(Boolean);
|
|
57
|
+
return intents.length ? intents : ["Run shell commands"];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Describe recorded operations, without inferring a business goal or exposing arguments. */
|
|
61
|
+
function actionIntents(name: string, args: unknown): string[] {
|
|
62
|
+
if (typeof name !== "string" || name.length > 256) return ["Run tool actions"];
|
|
63
|
+
const short = name.split("__").at(-1)?.toLowerCase();
|
|
64
|
+
if (["bash", "powershell", "exec_command"].includes(short || "")) {
|
|
65
|
+
const value = argumentsObject(args);
|
|
66
|
+
return shellIntents(field(value, "command") ?? field(value, "cmd"));
|
|
67
|
+
}
|
|
68
|
+
if (["read", "read_file"].includes(short || "")) return ["Read files"];
|
|
69
|
+
if (["write", "write_file", "edit", "apply_patch"].includes(short || "")) return ["Edit files"];
|
|
70
|
+
if (["grep", "rg", "search", "glob", "find"].includes(short || "")) return ["Search files"];
|
|
71
|
+
if (["ls", "list_directory"].includes(short || "")) return ["Inspect files"];
|
|
72
|
+
if (short === "ask_user_question") return ["Ask a question"];
|
|
73
|
+
return [short === "codemode" ? "Run code" : "Run tool actions"];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function actionIntent(name: string, args: unknown): string {
|
|
77
|
+
return combine(actionIntents(name, args));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function groupIntent(actions: Action[]): string {
|
|
81
|
+
if (!Array.isArray(actions)) return "Run tool actions";
|
|
82
|
+
const intents: string[] = [];
|
|
83
|
+
for (let i = 0; i < Math.min(actions.length, 64); i++) {
|
|
84
|
+
const action = field(actions, String(i));
|
|
85
|
+
intents.push(...actionIntents(field(action, "name"), field(action, "args")));
|
|
86
|
+
}
|
|
87
|
+
return combine(intents, actions.length > 64);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Recorded nested calls are evidence. Arbitrary JavaScript is not parsed or evaluated. */
|
|
91
|
+
export function codeIntent(_args: unknown, calls: Action[]): string {
|
|
92
|
+
return Array.isArray(calls) && calls.length ? groupIntent(calls) : "Run code";
|
|
93
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
2
|
+
import { DisplayLineCache } from "./display-line-cache.ts";
|
|
3
|
+
|
|
4
|
+
const lines = new DisplayLineCache();
|
|
5
|
+
export const clearDisplayLineCache = () => lines.clear();
|
|
6
|
+
// Final reply projections retain native Markdown rather than workflow controls.
|
|
7
|
+
export const finalReplyRendering = Symbol.for("compact-renderer:final-reply-rendering:v1");
|
|
8
|
+
// Key the actual styling bytes, not theme identity: themes can change in place.
|
|
9
|
+
const memoLine = (kind: string, line: string, width: number, style: string, render: () => string) =>
|
|
10
|
+
line.length > 4096 ? render() : lines.get(JSON.stringify([kind, width, style, line]), render);
|
|
11
|
+
|
|
12
|
+
export const cardPadding = (width: number) => width >= 4 ? 1 : 0;
|
|
13
|
+
export const cardContentWidth = (width: number) => Math.max(1, width - cardPadding(width) * 2);
|
|
14
|
+
|
|
15
|
+
/** Routine headings keep only their category colored; recorded intent is secondary. */
|
|
16
|
+
export function activityHeading(line: string, theme: any, tone = "mdLink"): string {
|
|
17
|
+
if (!theme) return line;
|
|
18
|
+
if (tone !== "mdLink" && tone !== "syntaxVariable") return theme.fg(tone, theme.bold(line));
|
|
19
|
+
const separator = line.indexOf(" · ");
|
|
20
|
+
return separator < 0 ? theme.fg(tone, line) : theme.fg(tone, line.slice(0, separator)) + theme.fg("muted", line.slice(separator));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Match Pi's default Box(1, 1): one filled row above and below the content. */
|
|
24
|
+
export function cardBlock(rows: string[], width: number, theme: any, background: string): string[] {
|
|
25
|
+
const blank = fillBackground("", width, theme, background);
|
|
26
|
+
return [blank, ...rows, blank];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The legacy card fill: keep the base surface after nested ANSI resets.
|
|
30
|
+
* Extended color payloads are data, not SGR reset codes. */
|
|
31
|
+
export function fillBackground(line: string, width: number, theme: any, background: string): string {
|
|
32
|
+
const base = typeof theme?.bg === "function" ? theme.bg(background, "").replace(/\x1b\[49m$/, "") : undefined;
|
|
33
|
+
return memoLine(base === undefined ? "pad" : "fill", line, width, base ?? "", () => paintBackground(line, width, base));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function paintBackground(line: string, width: number, base: string | undefined): string {
|
|
37
|
+
const content = truncateToWidth(line, width, "");
|
|
38
|
+
const padded = content + " ".repeat(Math.max(0, width - visibleWidth(content)));
|
|
39
|
+
if (base === undefined) return padded;
|
|
40
|
+
const restored = padded.replace(/\x1b\[([0-9;:]*)m/g, (escape, parameters: string) => {
|
|
41
|
+
const codes = parameters.split(";");
|
|
42
|
+
let reset = false;
|
|
43
|
+
for (let i = 0; i < codes.length; i++) {
|
|
44
|
+
const code = Number(codes[i].split(":")[0]);
|
|
45
|
+
if (code === 0 || code === 49) reset = true;
|
|
46
|
+
else if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === 48) reset = false;
|
|
47
|
+
if ((code === 38 || code === 48 || code === 58) && !codes[i].includes(":")) {
|
|
48
|
+
const mode = Number(codes[++i]);
|
|
49
|
+
i += mode === 2 ? 3 : mode === 5 ? 1 : 0;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return escape + (reset ? base : "");
|
|
53
|
+
});
|
|
54
|
+
return base + restored + "\x1b[49m";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Callers lay out within cardContentWidth; fill includes both horizontal gutters. */
|
|
58
|
+
export function cardRow(line: string, width: number, theme: any, background: string): string {
|
|
59
|
+
return fillBackground(" ".repeat(cardPadding(width)) + truncateToWidth(line, cardContentWidth(width), ""), width, theme, background);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Compact activity stays on the terminal surface; only keyboard selection is filled. */
|
|
63
|
+
export function activityRow(line: string, width: number, theme: any, selected = false): string {
|
|
64
|
+
const row = memoLine("activity", line, width, "", () => " ".repeat(cardPadding(width)) + truncateToWidth(line, cardContentWidth(width), ""));
|
|
65
|
+
return selected ? fillBackground(row, width, theme, "selectedBg") : row;
|
|
66
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Bounded formatted text only: never retain components, sessions or themes.
|
|
2
|
+
* The charge includes both strings at two bytes per code unit plus an allowance
|
|
3
|
+
* for each Map entry. This bounds cache contents, not the JavaScript heap. */
|
|
4
|
+
export class DisplayLineCache {
|
|
5
|
+
private entries = new Map<string, string>();
|
|
6
|
+
chargedBytes = 0;
|
|
7
|
+
constructor(private budget = 2 * 1024 * 1024, private maxEntries = 4096) {}
|
|
8
|
+
clear() { this.entries.clear(); this.chargedBytes = 0; }
|
|
9
|
+
private charge(key: string, value: string) { return 2 * (key.length + value.length) + 128; }
|
|
10
|
+
get(key: string, render: () => string): string {
|
|
11
|
+
const saved = this.entries.get(key);
|
|
12
|
+
if (saved !== undefined) {
|
|
13
|
+
this.entries.delete(key); this.entries.set(key, saved);
|
|
14
|
+
return saved;
|
|
15
|
+
}
|
|
16
|
+
const value = render(), charge = this.charge(key, value);
|
|
17
|
+
if (charge > this.budget) return value;
|
|
18
|
+
while (this.entries.size && (this.chargedBytes + charge > this.budget || this.entries.size >= this.maxEntries)) {
|
|
19
|
+
const oldest = this.entries.keys().next().value!;
|
|
20
|
+
this.chargedBytes -= this.charge(oldest, this.entries.get(oldest)!);
|
|
21
|
+
this.entries.delete(oldest);
|
|
22
|
+
}
|
|
23
|
+
this.entries.set(key, value); this.chargedBytes += charge;
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Session-local display state. No settings, messages, or model inputs are changed. */
|
|
2
|
+
export interface DisplayMode {
|
|
3
|
+
isEnabled(): boolean;
|
|
4
|
+
onChange(callback: () => void): () => void;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function createDisplayMode(initial = true) {
|
|
8
|
+
let enabled = initial;
|
|
9
|
+
let disposed = false;
|
|
10
|
+
const listeners = new Set<() => void>();
|
|
11
|
+
const mode: DisplayMode & { setEnabled(value: boolean): boolean; dispose(): void } = {
|
|
12
|
+
isEnabled: () => enabled && !disposed,
|
|
13
|
+
onChange(callback) {
|
|
14
|
+
if (disposed) return () => {};
|
|
15
|
+
listeners.add(callback);
|
|
16
|
+
return () => { listeners.delete(callback); };
|
|
17
|
+
},
|
|
18
|
+
setEnabled(value) {
|
|
19
|
+
if (disposed || enabled === value) return false;
|
|
20
|
+
enabled = value;
|
|
21
|
+
// A native redraw may synchronously unregister and register itself again.
|
|
22
|
+
// Snapshot first so one redraw cannot extend this iteration indefinitely.
|
|
23
|
+
const errors: unknown[] = [];
|
|
24
|
+
for (const callback of [...listeners]) {
|
|
25
|
+
try { callback(); } catch (error) { errors.push(error); }
|
|
26
|
+
}
|
|
27
|
+
if (errors.length) throw new AggregateError(errors, 'Pi Fold display refresh failed');
|
|
28
|
+
return true;
|
|
29
|
+
},
|
|
30
|
+
dispose() { disposed = true; listeners.clear(); },
|
|
31
|
+
};
|
|
32
|
+
return mode;
|
|
33
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
3
|
+
import type { WorkStripControls } from './work-strip.ts';
|
|
4
|
+
|
|
5
|
+
type FoldMode = DisplayMode & { setEnabled(enabled: boolean): boolean };
|
|
6
|
+
|
|
7
|
+
/** One session-local command owns display mode, work expansion, and its shortcut. */
|
|
8
|
+
export function registerFoldCommand(pi: ExtensionAPI, mode: FoldMode, work: WorkStripControls): () => void {
|
|
9
|
+
let disposed = false;
|
|
10
|
+
pi.registerCommand('fold', {
|
|
11
|
+
description: 'Choose Pi Fold display, collapse or expand work, or set its shortcut',
|
|
12
|
+
async handler(args, ctx) {
|
|
13
|
+
if (disposed) return;
|
|
14
|
+
let choice = args.trim().toLowerCase().split(/\s+/).filter(Boolean).join(' ');
|
|
15
|
+
if (!choice && ctx.hasUI) {
|
|
16
|
+
const current = mode.isEnabled() ? 'on' : 'off';
|
|
17
|
+
const choices = [
|
|
18
|
+
`on${current === 'on' ? ' (current)' : ''} — fold work and recorded thinking`,
|
|
19
|
+
`off${current === 'off' ? ' (current)' : ''} — native display`,
|
|
20
|
+
'collapse — collapse completed work sections',
|
|
21
|
+
'expand — expand all work sections',
|
|
22
|
+
'shortcut — choose Ctrl+Alt+W shortcut',
|
|
23
|
+
];
|
|
24
|
+
const selected = await ctx.ui.select('Pi Fold — this session', choices);
|
|
25
|
+
if (disposed || selected === undefined) return;
|
|
26
|
+
const index = choices.indexOf(selected);
|
|
27
|
+
if (index < 0) return;
|
|
28
|
+
choice = ['on', 'off', 'collapse', 'expand', 'shortcut'][index];
|
|
29
|
+
if (choice === current) return;
|
|
30
|
+
}
|
|
31
|
+
if (['', 'status', 'on', 'off', 'toggle'].includes(choice)) {
|
|
32
|
+
if (choice === 'on' || choice === 'off' || choice === 'toggle') {
|
|
33
|
+
mode.setEnabled(choice === 'toggle' ? !mode.isEnabled() : choice === 'on');
|
|
34
|
+
}
|
|
35
|
+
ctx.ui.notify(`Pi Fold ${mode.isEnabled() ? 'on' : 'off'}`, 'info');
|
|
36
|
+
} else if (choice === 'collapse' || choice === 'expand') {
|
|
37
|
+
if (!mode.isEnabled()) {
|
|
38
|
+
ctx.ui.notify(`Turn Pi Fold on with /fold on before you ${choice} work sections.`, 'info');
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const changed = work.setExpanded(choice === 'expand');
|
|
42
|
+
ctx.ui.notify(changed ? `Work sections ${choice === 'expand' ? 'expanded' : 'collapsed'}` : 'Work sections are unavailable in this session.', 'info');
|
|
43
|
+
} else if (['shortcut', 'shortcut on', 'shortcut off'].includes(choice)) {
|
|
44
|
+
let enabled = choice === 'shortcut' ? undefined : choice === 'shortcut on';
|
|
45
|
+
if (enabled === undefined && ctx.hasUI) {
|
|
46
|
+
const current = work.isShortcutEnabled() ? 'on' : 'off';
|
|
47
|
+
const choices = ['on', 'off'].map(value => `${value}${value === current ? ' (current)' : ''}`);
|
|
48
|
+
const selected = await ctx.ui.select('Toggle work shortcut — Ctrl+Alt+W', choices);
|
|
49
|
+
if (disposed || selected === undefined || !choices.includes(selected)) return;
|
|
50
|
+
enabled = selected === choices[0];
|
|
51
|
+
if (enabled === work.isShortcutEnabled()) return;
|
|
52
|
+
}
|
|
53
|
+
if (enabled !== undefined) work.setShortcutEnabled(enabled);
|
|
54
|
+
ctx.ui.notify(`Toggle work shortcut: ${work.isShortcutEnabled() ? 'on' : 'off'}`, 'info');
|
|
55
|
+
} else {
|
|
56
|
+
ctx.ui.notify('Use /fold [on|off|toggle|status|collapse|expand|shortcut [on|off]]', 'info');
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
return () => { disposed = true; };
|
|
61
|
+
}
|