@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
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@notrico/pi-fold",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "3.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Pi Fold: readable agent transcripts with collapsible work, inspectable details, and clear final replies",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/rrrrrrrrrricoxi/pi-fold.git"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "node scripts/test.mjs",
|
|
13
|
+
"preview": "node scripts/preview.mjs",
|
|
14
|
+
"preview:work": "node scripts/preview-work-strip.mjs",
|
|
15
|
+
"benchmark": "node --expose-gc scripts/performance-review.mjs",
|
|
16
|
+
"benchmark:memory": "node --expose-gc scripts/retained-memory-review.mjs"
|
|
17
|
+
},
|
|
18
|
+
"pi": {
|
|
19
|
+
"extensions": [
|
|
20
|
+
"./index.ts"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
25
|
+
"@earendil-works/pi-tui": "*"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"index.ts",
|
|
29
|
+
"src/*.ts",
|
|
30
|
+
"tests/*.mjs",
|
|
31
|
+
"tests/fixtures/*.ts",
|
|
32
|
+
"scripts/*.mjs",
|
|
33
|
+
"docs/*.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"README.md",
|
|
36
|
+
"CHANGELOG.md"
|
|
37
|
+
],
|
|
38
|
+
"keywords": [
|
|
39
|
+
"pi-package",
|
|
40
|
+
"pi-extension",
|
|
41
|
+
"terminal",
|
|
42
|
+
"tui",
|
|
43
|
+
"pi-fold",
|
|
44
|
+
"transcript"
|
|
45
|
+
],
|
|
46
|
+
"homepage": "https://github.com/rrrrrrrrrricoxi/pi-fold#readme",
|
|
47
|
+
"bugs": {
|
|
48
|
+
"url": "https://github.com/rrrrrrrrrricoxi/pi-fold/issues"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=22.19.0"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public",
|
|
55
|
+
"registry": "https://registry.npmjs.org/"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Synthetic layout benchmark for the native Pi 1.3.0 tool renderer and Pi Fold.
|
|
3
|
+
// It never runs an agent, model, tool, shell command, or network request.
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { performance } from 'node:perf_hooks';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { loadAgent, loadSharedSource as loadSource, core, runtime, themeModule, tui } from '../tests/test-runtime.mjs';
|
|
9
|
+
|
|
10
|
+
const { ToolExecutionComponent } = await loadAgent('modes/interactive/components/tool-execution.js');
|
|
11
|
+
const { createShellRenderers } = await loadAgent('core/tools/renderers/bash.js');
|
|
12
|
+
const { readRenderers } = await loadAgent('core/tools/renderers/read.js');
|
|
13
|
+
const { codemodeRenderers } = await loadAgent('extensions/codemode/renderer.js');
|
|
14
|
+
const { registerModernTools } = await loadSource('./modern-tools.ts');
|
|
15
|
+
const { clearDisplayLineCache } = await loadSource('./display-card.ts');
|
|
16
|
+
const { createDisplayMode } = await loadSource('./display-mode.ts');
|
|
17
|
+
const { registerWorkStrip } = await loadSource('./work-strip.ts');
|
|
18
|
+
const { registerFoldCommand } = await loadSource('./fold-command.ts');
|
|
19
|
+
const { WorkStripHeader, WorkChild, workEvidenceType, projectedChildren } = await loadSource('./work-strip-view.ts');
|
|
20
|
+
const { VERSION } = core;
|
|
21
|
+
|
|
22
|
+
function options(argv) {
|
|
23
|
+
const result = { samples: 5, warm: 8, scales: [8, 48, 160], longChars: 50000, nestedCalls: 500, width: 100 };
|
|
24
|
+
for (let i = 0; i < argv.length; i++) {
|
|
25
|
+
const key = argv[i];
|
|
26
|
+
const value = argv[++i];
|
|
27
|
+
if (key === '--samples') result.samples = Number(value);
|
|
28
|
+
else if (key === '--warm') result.warm = Number(value);
|
|
29
|
+
else if (key === '--scales') result.scales = value.split(',').map(Number);
|
|
30
|
+
else if (key === '--long-chars') result.longChars = Number(value);
|
|
31
|
+
else if (key === '--nested-calls') result.nestedCalls = Number(value);
|
|
32
|
+
else if (key === '--width') result.width = Number(value);
|
|
33
|
+
else if (key === '--help') {
|
|
34
|
+
console.log('Usage: node scripts/performance-review.mjs [--samples N] [--warm N] [--scales 8,48,160] [--long-chars N] [--nested-calls N] [--width N]');
|
|
35
|
+
process.exit(0);
|
|
36
|
+
} else throw new Error(`Unknown option: ${key}`);
|
|
37
|
+
}
|
|
38
|
+
for (const key of ['samples', 'warm', 'longChars', 'nestedCalls', 'width']) if (!Number.isSafeInteger(result[key]) || result[key] < 1) throw new Error(`--${key} must be a positive integer`);
|
|
39
|
+
if (!result.scales.length || result.scales.some(n => !Number.isSafeInteger(n) || n < 1)) throw new Error('--scales must be comma-separated positive integers');
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
const config = options(process.argv.slice(2));
|
|
43
|
+
if (VERSION !== '1.3.0') throw new Error(`Expected native Pi 1.3.0, found ${VERSION}; set PI_RUNTIME to the pinned runtime.`);
|
|
44
|
+
|
|
45
|
+
const hooks = new Map(), bus = new Map();
|
|
46
|
+
let resolveRenderer;
|
|
47
|
+
const pi = {
|
|
48
|
+
registerToolRenderer(fn) { resolveRenderer = fn; },
|
|
49
|
+
on(name, fn) { const set = hooks.get(name) || new Set(); set.add(fn); hooks.set(name, set); return () => set.delete(fn); },
|
|
50
|
+
events: { on(name, fn) { const set = bus.get(name) || new Set(); set.add(fn); bus.set(name, set); return () => set.delete(fn); }, emit(name, value) { for (const fn of bus.get(name) || []) fn(value); } },
|
|
51
|
+
};
|
|
52
|
+
const mode = createDisplayMode(true);
|
|
53
|
+
const disposeRenderer = registerModernTools(pi, mode);
|
|
54
|
+
const ctx = { hasUI: true, sessionManager: { getBranch: () => [] }, ui: { onTerminalInput() { return () => {}; } } };
|
|
55
|
+
const emit = (name, event = {}) => { for (const fn of hooks.get(name) || []) fn(event, ctx); };
|
|
56
|
+
const native = new Map([
|
|
57
|
+
['bash', createShellRenderers('$')],
|
|
58
|
+
['read', readRenderers],
|
|
59
|
+
['codemode', codemodeRenderers],
|
|
60
|
+
]);
|
|
61
|
+
const ui = { requestRender() {} };
|
|
62
|
+
const width = config.width;
|
|
63
|
+
const resultText = value => ({ content: [{ type: 'text', text: value }], details: {} });
|
|
64
|
+
let idSequence = 0;
|
|
65
|
+
function makeTool(name, args, result) {
|
|
66
|
+
const id = `perf-${++idSequence}`;
|
|
67
|
+
const stock = native.get(name);
|
|
68
|
+
const definition = resolveRenderer(name, () => stock);
|
|
69
|
+
const component = new ToolExecutionComponent(name, id, args, { showImages: false, outputPad: 0 }, definition, ui, os.tmpdir());
|
|
70
|
+
component.setArgsComplete();
|
|
71
|
+
component.markExecutionStarted();
|
|
72
|
+
component.updateResult(result);
|
|
73
|
+
return component;
|
|
74
|
+
}
|
|
75
|
+
function beginGroupedCalls(count) {
|
|
76
|
+
const ids = Array.from({ length: count }, () => `perf-${++idSequence}`);
|
|
77
|
+
emit('message_end', { message: { role: 'assistant', content: ids.map(id => ({ type: 'toolCall', id, name: 'read', arguments: { path: `/fixture/sample-${id}.txt` } })) } });
|
|
78
|
+
return ids;
|
|
79
|
+
}
|
|
80
|
+
function makeGrouped(count, output = 'Synthetic recorded output.') {
|
|
81
|
+
const ids = beginGroupedCalls(count), components = [];
|
|
82
|
+
for (const id of ids) {
|
|
83
|
+
const definition = resolveRenderer('read', () => readRenderers);
|
|
84
|
+
const component = new ToolExecutionComponent('read', id, { path: `/fixture/sample-${id}.txt` }, { showImages: false, outputPad: 0 }, definition, ui, os.tmpdir());
|
|
85
|
+
component.setArgsComplete(); component.markExecutionStarted(); component.updateResult(resultText(output)); components.push(component);
|
|
86
|
+
}
|
|
87
|
+
return components;
|
|
88
|
+
}
|
|
89
|
+
function paintAll(components) { let rows = 0; for (const component of components) rows += component.render(width).length; return rows; }
|
|
90
|
+
function reset() { emit('session_start'); }
|
|
91
|
+
function summarize(values) {
|
|
92
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
93
|
+
const percentile = p => sorted[Math.max(0, Math.ceil(p * sorted.length) - 1)];
|
|
94
|
+
return { p50: percentile(0.5), p95: percentile(0.95), min: sorted[0], max: sorted.at(-1) };
|
|
95
|
+
}
|
|
96
|
+
function measure(label, scenario, operation, samples = config.samples) {
|
|
97
|
+
const wallMs = [], cpuUserMs = [], cpuSystemMs = [], heapDelta = [], rssDelta = [], externalDelta = [];
|
|
98
|
+
for (let i = 0; i < samples; i++) {
|
|
99
|
+
globalThis.gc?.();
|
|
100
|
+
const before = process.memoryUsage(), cpuBefore = process.cpuUsage(), start = performance.now();
|
|
101
|
+
operation();
|
|
102
|
+
wallMs.push(performance.now() - start);
|
|
103
|
+
const cpu = process.cpuUsage(cpuBefore), after = process.memoryUsage();
|
|
104
|
+
cpuUserMs.push(cpu.user / 1000); cpuSystemMs.push(cpu.system / 1000);
|
|
105
|
+
heapDelta.push(after.heapUsed - before.heapUsed); rssDelta.push(after.rss - before.rss); externalDelta.push(after.external - before.external);
|
|
106
|
+
}
|
|
107
|
+
return { label, scenario, samples, wallMs: summarize(wallMs), cpuUserMs: summarize(cpuUserMs), cpuSystemMs: summarize(cpuSystemMs), memoryDeltaBytes: { heapUsed: summarize(heapDelta), rss: summarize(rssDelta), external: summarize(externalDelta) } };
|
|
108
|
+
}
|
|
109
|
+
function measurePrepared(label, scenario, prepare, operation, samples = config.samples) {
|
|
110
|
+
const wallMs = [], cpuUserMs = [], cpuSystemMs = [], heapDelta = [], rssDelta = [], externalDelta = [];
|
|
111
|
+
for (let i = 0; i < samples; i++) {
|
|
112
|
+
globalThis.gc?.();
|
|
113
|
+
const fixture = prepare();
|
|
114
|
+
const before = process.memoryUsage(), cpuBefore = process.cpuUsage(), start = performance.now();
|
|
115
|
+
try { operation(fixture); }
|
|
116
|
+
finally {
|
|
117
|
+
wallMs.push(performance.now() - start);
|
|
118
|
+
const cpu = process.cpuUsage(cpuBefore), after = process.memoryUsage();
|
|
119
|
+
cpuUserMs.push(cpu.user / 1000); cpuSystemMs.push(cpu.system / 1000);
|
|
120
|
+
heapDelta.push(after.heapUsed - before.heapUsed); rssDelta.push(after.rss - before.rss); externalDelta.push(after.external - before.external);
|
|
121
|
+
fixture.dispose();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { label, scenario, samples, wallMs: summarize(wallMs), cpuUserMs: summarize(cpuUserMs), cpuSystemMs: summarize(cpuSystemMs), memoryDeltaBytes: { heapUsed: summarize(heapDelta), rss: summarize(rssDelta), external: summarize(externalDelta) } };
|
|
125
|
+
}
|
|
126
|
+
function scenarioForMode(modeName, enabled, scale) {
|
|
127
|
+
mode.setEnabled(enabled);
|
|
128
|
+
const cold = measure('cold-mount-and-first-paint', `${modeName}/transcript-${scale}`, () => {
|
|
129
|
+
reset(); const components = makeGrouped(scale); paintAll(components);
|
|
130
|
+
});
|
|
131
|
+
reset(); const components = makeGrouped(scale); paintAll(components);
|
|
132
|
+
const warm = measure(`warm-redraw-${config.warm}-iterations`, `${modeName}/transcript-${scale}`, () => {
|
|
133
|
+
for (let i = 0; i < config.warm; i++) paintAll(components);
|
|
134
|
+
});
|
|
135
|
+
const header = new WorkStripHeader();
|
|
136
|
+
header.state = 'completed'; header.summary = 'Synthetic recorded work completed.'; header.elapsedMs = 42000; header.open = false;
|
|
137
|
+
const children = components.map(component => new WorkChild(component));
|
|
138
|
+
const paintFold = () => { let rows = header.render(width).length; if (header.open) for (const child of children) rows += child.render(width).length; return rows; };
|
|
139
|
+
const workHeader = measure('synthetic-work-header-child-expand-collapse', `${modeName}/transcript-${scale}`, () => {
|
|
140
|
+
if (enabled) { header.toggle(); paintFold(); header.toggle(); paintFold(); }
|
|
141
|
+
else { paintAll(components); paintAll(components); }
|
|
142
|
+
});
|
|
143
|
+
const expanded = measure('tool-group-expand-collapse-and-paint', `${modeName}/transcript-${scale}`, () => {
|
|
144
|
+
for (const component of components) component.setExpanded(true);
|
|
145
|
+
paintAll(components);
|
|
146
|
+
for (const component of components) component.setExpanded(false);
|
|
147
|
+
paintAll(components);
|
|
148
|
+
});
|
|
149
|
+
reset();
|
|
150
|
+
return [cold, warm, workHeader, expanded];
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function makeProjectionFixture(turnCount, enabled) {
|
|
154
|
+
const manager = core.SessionManager.inMemory('/synthetic-work-strip-performance');
|
|
155
|
+
const hooks = new Map(), bus = new Map(), commands = new Map(), inputs = new Set();
|
|
156
|
+
const subscribe = (map, name, fn) => { const set = map.get(name) || new Set(); map.set(name, set); set.add(fn); return () => set.delete(fn); };
|
|
157
|
+
const piProjection = {
|
|
158
|
+
on: (name, fn) => subscribe(hooks, name, fn),
|
|
159
|
+
events: { on: (name, fn) => subscribe(bus, name, fn), emit(name, value) { for (const fn of [...bus.get(name) || []]) fn(value); } },
|
|
160
|
+
appendEntry: (kind, data) => manager.appendCustomEntry(kind, data),
|
|
161
|
+
getAllTools: () => [], registerCommand: (name, definition) => commands.set(name, definition), registerShortcut() {},
|
|
162
|
+
};
|
|
163
|
+
const modeProjection = createDisplayMode(enabled);
|
|
164
|
+
const workControls = registerWorkStrip(piProjection, modeProjection, VERSION), dispose = workControls.dispose;
|
|
165
|
+
registerFoldCommand(piProjection, modeProjection, workControls);
|
|
166
|
+
// This partial-registration benchmark supplies the cache boundary owned by index.ts.
|
|
167
|
+
clearDisplayLineCache?.();
|
|
168
|
+
const uiProjection = { isFollowingOutput: true, theme: themeModule.theme, notify() {}, requestRender() {}, onTerminalInput(fn) { inputs.add(fn); return () => inputs.delete(fn); } };
|
|
169
|
+
const context = { mode: 'tui', hasUI: true, ui: uiProjection, sessionManager: manager, isIdle: () => true };
|
|
170
|
+
const display = {
|
|
171
|
+
chatContainer: new tui.Container(), ui: uiProjection, pendingTools: new Map(), outputPad: 0,
|
|
172
|
+
toolOutputExpanded: false, hideThinkingBlock: true, sessionManager: manager,
|
|
173
|
+
session: { extensionRunner: { getMessageRenderer() {} } },
|
|
174
|
+
getUserMessageText: message => message.content,
|
|
175
|
+
getMarkdownThemeWithSettings: () => themeModule.getMarkdownTheme(), getMarkdownTransformers: () => [],
|
|
176
|
+
editor: { addToHistory() {} },
|
|
177
|
+
};
|
|
178
|
+
const add = message => {
|
|
179
|
+
message.timestamp = 1000 + manager.getBranch().length;
|
|
180
|
+
manager.appendMessage(message);
|
|
181
|
+
core.InteractiveMode.prototype.addMessageToChat.call(display, message);
|
|
182
|
+
return manager.getBranch().at(-1);
|
|
183
|
+
};
|
|
184
|
+
for (let index = 0; index < turnCount; index++) {
|
|
185
|
+
const user = add({ role: 'user', content: `Synthetic task ${index + 1}: inspect the recorded fixture.` });
|
|
186
|
+
add({ role: 'assistant', content: [{ type: 'text', text: `Synthetic intermediate note ${index + 1}.` }], stopReason: 'stop' });
|
|
187
|
+
const tool = new core.ToolExecutionComponent('read', `work-fixture-${index}`, { path: `/fixture/turn-${index + 1}.txt` }, { outputPad: 0 }, undefined, uiProjection, '/fixture');
|
|
188
|
+
tool.setArgsComplete(); tool.updateResult({ content: [{ type: 'text', text: `Synthetic hidden tool result ${index + 1}.` }], isError: false });
|
|
189
|
+
display.chatContainer.addChild(tool);
|
|
190
|
+
const final = add({ role: 'assistant', content: [{ type: 'text', text: `Synthetic final response ${index + 1}.` }], stopReason: 'stop' });
|
|
191
|
+
manager.appendCustomEntry(workEvidenceType, { version: 1, userId: user.id, finalId: final.id, endId: final.id, startedAt: 1000 + index, endedAt: 3000 + index, outcome: 'completed' });
|
|
192
|
+
}
|
|
193
|
+
// Reload/resume creates completed work strips from saved evidence.
|
|
194
|
+
for (const fn of hooks.get('session_start') || []) fn({}, context);
|
|
195
|
+
const paint = () => display.chatContainer.render(width).length;
|
|
196
|
+
const work = action => commands.get('fold').handler(action, context);
|
|
197
|
+
return {
|
|
198
|
+
manager, mode: modeProjection, display, paint, work,
|
|
199
|
+
rows: () => display.chatContainer[projectedChildren] || display.chatContainer.children,
|
|
200
|
+
dispose() { dispose(); modeProjection.dispose(); clearDisplayLineCache?.(); if (inputs.size) throw new Error('Projection fixture leaked terminal input handlers.'); },
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function workProjectionScenarios(turnCount, enabled) {
|
|
205
|
+
const modeName = enabled ? 'compact-on' : 'native-off';
|
|
206
|
+
const scenario = `${modeName}/registered-work-projection-${turnCount}-turns`;
|
|
207
|
+
const first = measurePrepared('first-work-projection-paint', scenario, () => makeProjectionFixture(turnCount, enabled), fixture => {
|
|
208
|
+
const rows = fixture.paint();
|
|
209
|
+
if (enabled && !fixture.rows().some(row => row.constructor?.name === 'WorkStripHeader')) throw new Error('Registered work-strip projection produced no synthetic headers.');
|
|
210
|
+
if (!enabled && fixture.rows().some(row => row.constructor?.name === 'WorkStripHeader')) throw new Error('Native-off mode retained work-strip headers.');
|
|
211
|
+
if (rows < turnCount) throw new Error('Synthetic transcript did not render all turns.');
|
|
212
|
+
});
|
|
213
|
+
const warm = measurePrepared(`registered-warm-redraw-${config.warm}-iterations`, scenario, () => {
|
|
214
|
+
const fixture = makeProjectionFixture(turnCount, enabled); fixture.paint(); return fixture;
|
|
215
|
+
}, fixture => {
|
|
216
|
+
for (let index = 0; index < config.warm; index++) fixture.paint();
|
|
217
|
+
});
|
|
218
|
+
const disclosure = measurePrepared('registered-work-collapse-expand-and-paint', scenario, () => {
|
|
219
|
+
const fixture = makeProjectionFixture(turnCount, enabled); fixture.paint(); return fixture;
|
|
220
|
+
}, fixture => {
|
|
221
|
+
void fixture.work('collapse'); fixture.paint();
|
|
222
|
+
void fixture.work('expand'); fixture.paint();
|
|
223
|
+
});
|
|
224
|
+
return [first, warm, disclosure];
|
|
225
|
+
}
|
|
226
|
+
function longResultScenario(modeName, enabled) {
|
|
227
|
+
mode.setEnabled(enabled); reset();
|
|
228
|
+
const longToolOutput = 'Synthetic tool output with a stable fixture marker.\n'.repeat(Math.ceil(config.longChars / 53)).slice(0, config.longChars);
|
|
229
|
+
const tool = makeTool('read', { path: '/fixture/long-result.txt' }, resultText(longToolOutput));
|
|
230
|
+
const longCode = 'const sample = "synthetic";\n'.repeat(Math.ceil(config.longChars / 29)).slice(0, config.longChars);
|
|
231
|
+
const codeResult = { content: [{ type: 'text', text: `Script completed\nOutput:\n${longToolOutput}` }], details: { calls: Array.from({ length: config.nestedCalls }, (_, index) => ({ name: 'read', args: `/fixture/record-${index}.txt`, status: 'ok', durationMs: 1 })) }, durationMs: 1000 };
|
|
232
|
+
const code = makeTool('codemode', { code: longCode }, codeResult);
|
|
233
|
+
const collapsed = measure('long-tool-and-codemode-collapsed', `${modeName}/long-results`, () => { tool.setExpanded(false); code.setExpanded(false); paintAll([tool, code]); });
|
|
234
|
+
const expanded = measure('long-tool-and-codemode-expanded', `${modeName}/long-results`, () => { tool.setExpanded(true); code.setExpanded(true); paintAll([tool, code]); });
|
|
235
|
+
code.callRendererComponent?.owner?.code?.dispose?.();
|
|
236
|
+
return [collapsed, expanded];
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function disposePerformanceReview() {
|
|
240
|
+
mode.setEnabled(true); emit('session_shutdown'); disposeRenderer(); mode.dispose(); clearDisplayLineCache?.();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
244
|
+
const results = [];
|
|
245
|
+
try {
|
|
246
|
+
emit('session_start');
|
|
247
|
+
for (const scale of config.scales) {
|
|
248
|
+
results.push(...scenarioForMode('compact-on', true, scale));
|
|
249
|
+
results.push(...scenarioForMode('native-off', false, scale));
|
|
250
|
+
results.push(...workProjectionScenarios(scale, true));
|
|
251
|
+
results.push(...workProjectionScenarios(scale, false));
|
|
252
|
+
}
|
|
253
|
+
results.push(...longResultScenario('compact-on', true));
|
|
254
|
+
results.push(...longResultScenario('native-off', false));
|
|
255
|
+
console.log(JSON.stringify({
|
|
256
|
+
schema: 'compact-renderer-performance-review/v1',
|
|
257
|
+
runtime: { version: VERSION, path: runtime, width, platform: process.platform, arch: process.arch, node: process.version },
|
|
258
|
+
fixture: { source: 'synthetic in-memory records only', transcriptScales: config.scales, workTurnsPerProjection: config.scales, workProjectionRowsPerTurn: 'user + intermediate assistant + tool component + final assistant, plus native spacing', samples: config.samples, warmIterations: config.warm, longResultCharacters: config.longChars, nestedCalls: config.nestedCalls },
|
|
259
|
+
metrics: { wallMs: 'elapsed per operation; warm scenario includes the configured redraw iteration count', cpuMs: 'process CPU consumed per operation', memoryDeltaBytes: 'process memory delta around each operation; allocator/GC noise applies' },
|
|
260
|
+
results,
|
|
261
|
+
limits: [
|
|
262
|
+
'Measures synchronous layout and painting in the native Pi renderer component tree only.',
|
|
263
|
+
'Work-strip cases use registered WorkStrip hooks, native InteractiveMode addMessageToChat and chatContainer.render projection, saved completion evidence, and the /fold collapse/expand handlers; fixture construction is outside measured intervals.',
|
|
264
|
+
'The native-off work-strip arm disables those handlers and measures the unprojected native transcript redraw as its comparison.',
|
|
265
|
+
'Does not measure terminal transport, terminal emulator painting, input latency, model latency, tool execution, network, or full interactive-session startup.',
|
|
266
|
+
'Synthetic fixtures contain no user transcript, credentials, or business data.',
|
|
267
|
+
'Memory deltas are process-wide snapshots, not per-component retained-size measurements; run with --expose-gc for optional pre-sample collection.',
|
|
268
|
+
],
|
|
269
|
+
}, null, 2));
|
|
270
|
+
} finally {
|
|
271
|
+
disposePerformanceReview();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Isolated recorded-content preview; no model or tool execution.
|
|
3
|
+
import { createWorkStripPreview } from './preview-work-strip.mjs';
|
|
4
|
+
const preview = await createWorkStripPreview({ inspection: true });
|
|
5
|
+
let ui;
|
|
6
|
+
try {
|
|
7
|
+
ui = new preview.core.InteractiveMode(preview.runtime, { tuiMode: 'fullscreen' });
|
|
8
|
+
await ui.run();
|
|
9
|
+
} finally { ui?.stop(); await preview.cleanup(); }
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Synthetic playback through native UI/lifecycle events. This never invokes an
|
|
3
|
+
// agent loop, tool executor, model, shell, network, or another user's session.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { createPreview } from './preview.mjs';
|
|
7
|
+
|
|
8
|
+
export async function createWorkStripPreview({ stepMs = 1000, inspection = false } = {}) {
|
|
9
|
+
const old = process.env.PI_PREVIEW_WORK_STRIP;
|
|
10
|
+
process.env.PI_PREVIEW_WORK_STRIP = '1';
|
|
11
|
+
const preview = await createPreview();
|
|
12
|
+
const { manager, runtime, eventBus } = preview;
|
|
13
|
+
let stopped = false, playing = false;
|
|
14
|
+
const waits = new Map();
|
|
15
|
+
const delay = ms => new Promise(resolve => { const id = setTimeout(() => { waits.delete(id); resolve(); }, ms); waits.set(id, resolve); });
|
|
16
|
+
const base = Date.now();
|
|
17
|
+
const assistant = value => ({role:'assistant',content:[{type:'text',text:value}],timestamp:Date.now(),stopReason:'stop',api:'openai-codex-responses',provider:'openai-codex',model:'gpt-6-luna',usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}});
|
|
18
|
+
manager.appendCustomMessageEntry('ddd', 'Five recorded maintenance reminders.\n\nThis invented notice has no severity metadata. It stays visible as a compact row. Expand it to inspect this complete text.', true);
|
|
19
|
+
manager.appendMessage(assistant('Work-strip preview: intermediate content is folded; final replies and decisions remain visible. /inspect or a click opens a strip. Use /fold collapse or /fold expand for explicit control; Ctrl+Alt+W toggles completed work. Run /fixture-work to play 10 seconds of invented progress. Each live reply stays indented until the final reply is confirmed. Scroll up before it finishes to test deferred folding, or manually open its strip to keep it open. /prompt-jump end returns to the latest output. No model or tool runs.'));
|
|
20
|
+
const entries = manager.getBranch();
|
|
21
|
+
const users = entries.map((entry,index)=>entry.message?.role==='user'?index:-1).filter(index=>index>=0);
|
|
22
|
+
for (const [number,start] of users.entries()) {
|
|
23
|
+
const end = (users[number+1] ?? entries.length)-1;
|
|
24
|
+
const final = entries.slice(start+1,end+1).findLast(entry=>entry.message?.role==='assistant' && entry.message.content.some(block=>block.type==='text' && block.text.trim()));
|
|
25
|
+
if (final) manager.appendCustomEntry('compact-renderer:work-settled:v1',{version:1,userId:entries[start].id,finalId:final.id,endId:entries[end].id,startedAt:base-90000,endedAt:base-30000+number*1000,outcome:'completed'});
|
|
26
|
+
}
|
|
27
|
+
manager.appendMessage({role:'user',content:[
|
|
28
|
+
'Long submitted prompt: inspect these invented renderer requirements.',
|
|
29
|
+
'',
|
|
30
|
+
...Array.from({length:10},(_,i)=>`${i+1}. Preserve recorded sample ${i+1}, its unit, and its original wording.`),
|
|
31
|
+
'',
|
|
32
|
+
'This is a display fixture. Do not execute tools or access any external data.',
|
|
33
|
+
].join('\n'),timestamp:Date.now()});
|
|
34
|
+
manager.appendMessage(assistant('This direct reply has no work strip. Expand the prompt above to inspect all ten recorded requirements.'));
|
|
35
|
+
if (inspection) {
|
|
36
|
+
manager.appendMessage({role:'user',content:'Inspection regression preview: expand the work, then click more in the recorded code output and the three-round thinking group.',timestamp:Date.now()});
|
|
37
|
+
const userId = manager.getBranch().at(-1).id;
|
|
38
|
+
for (let i = 1; i <= 2; i++) {
|
|
39
|
+
const name = i === 1 ? 'read' : 'codemode';
|
|
40
|
+
const args = i === 1 ? {path:'/fixture/recorded.txt'} : {code:'text(await tools.read({ path: "/fixture/recorded.txt" }));'};
|
|
41
|
+
const call = assistant(''); call.stopReason = 'toolUse';
|
|
42
|
+
call.content = [{type:'thinking',thinking:`Review recorded sample ${i}.\n\n` + Array.from({length:45},(_,n)=>`Round ${i}, recorded line ${n+1}. This is invented fixture text.`).join('\n')}, {type:'toolCall',id:`inspection-${i}`,name,arguments:args}];
|
|
43
|
+
manager.appendMessage(call);
|
|
44
|
+
manager.appendMessage({role:'toolResult',toolCallId:`inspection-${i}`,toolName:name,content:[{type:'text',text:Array.from({length:60},(_,n)=>`Recorded output ${n+1}`).join('\n')}],details:i===2?{calls:[{name:'read',args:JSON.stringify({path:'/fixture/recorded.txt'}),status:'ok',durationMs:1}]}:{},isError:false,timestamp:Date.now()});
|
|
45
|
+
}
|
|
46
|
+
const final = assistant('Inspection result: the final thinking belongs to the same three-round group. Clicking more advances the recorded output. This answer stays outside the group. No tools or model ran.');
|
|
47
|
+
final.content.unshift({type:'thinking',thinking:'Finalize the recorded result.\n\n' + Array.from({length:45},(_,n)=>`Final round, recorded line ${n+1}. This is invented fixture text.`).join('\n')});
|
|
48
|
+
manager.appendMessage(final);
|
|
49
|
+
const finalId = manager.getBranch().at(-1).id;
|
|
50
|
+
manager.appendCustomEntry('compact-renderer:work-settled:v1',{version:1,userId,finalId,endId:finalId,startedAt:base-90000,endedAt:base,outcome:'completed'});
|
|
51
|
+
}
|
|
52
|
+
const emit = async event => {
|
|
53
|
+
if (stopped) return;
|
|
54
|
+
runtime.session._emit(event);
|
|
55
|
+
await runtime.session.extensionRunner.emit(event);
|
|
56
|
+
};
|
|
57
|
+
const message = async value => {
|
|
58
|
+
if (stopped) return;
|
|
59
|
+
await emit({type:'message_start',message:value});
|
|
60
|
+
manager.appendMessage(value);
|
|
61
|
+
await emit({type:'message_end',message:value});
|
|
62
|
+
};
|
|
63
|
+
const play = async notify => {
|
|
64
|
+
if (playing) { notify?.('The invented recording is already playing.'); return; }
|
|
65
|
+
playing = true;
|
|
66
|
+
try {
|
|
67
|
+
await emit({type:'agent_start'});
|
|
68
|
+
await message({role:'user',content:'Invented playback: inspect the recorded samples.',timestamp:Date.now()});
|
|
69
|
+
const call = assistant('');
|
|
70
|
+
const toolCallId = `fixture-read-${Date.now()}`;
|
|
71
|
+
call.content = [{type:'toolCall',id:toolCallId,name:'read',arguments:{path:'/fixture/sample-a.txt'}}]; call.stopReason = 'toolUse';
|
|
72
|
+
await message(call);
|
|
73
|
+
await message({role:'toolResult',toolCallId,toolName:'read',content:[{type:'text',text:'Synthetic sample: 3 kg'}],isError:false,timestamp:Date.now()});
|
|
74
|
+
await message(assistant('Reading the recorded sample labels.'));
|
|
75
|
+
await delay(3 * stepMs); if(stopped)return;
|
|
76
|
+
await message(assistant('Comparing the recorded units.'));
|
|
77
|
+
await delay(3 * stepMs); if(stopped)return;
|
|
78
|
+
await message(assistant('Checking the recorded result.'));
|
|
79
|
+
await delay(3 * stepMs); if(stopped)return;
|
|
80
|
+
const final = assistant('The invented samples agree. This final reply remains visible after the work strip folds. Nothing was executed.');
|
|
81
|
+
final.content.unshift({type:'thinking',thinking:'Compare the invented samples. This recorded reasoning belongs inside the completed work strip.'});
|
|
82
|
+
await message(final);
|
|
83
|
+
await delay(stepMs); if(stopped)return;
|
|
84
|
+
await emit({type:'agent_end',messages:[]});
|
|
85
|
+
await emit({type:'agent_settled',aborted:false});
|
|
86
|
+
} catch (error) { notify?.(`Preview playback stopped: ${error.message}`); }
|
|
87
|
+
finally {playing=false;}
|
|
88
|
+
};
|
|
89
|
+
const off = eventBus.on('preview:work-strip-run:v1', request=>{void play(request?.notify);});
|
|
90
|
+
return {...preview, play, cleanup:async()=>{
|
|
91
|
+
stopped=true; off(); for(const [id,resolve] of waits){clearTimeout(id);resolve();} waits.clear();
|
|
92
|
+
await preview.cleanup();
|
|
93
|
+
if(old===undefined)delete process.env.PI_PREVIEW_WORK_STRIP;else process.env.PI_PREVIEW_WORK_STRIP=old;
|
|
94
|
+
}};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if(process.argv[1] && path.resolve(process.argv[1])===fileURLToPath(import.meta.url)) {
|
|
98
|
+
const preview=await createWorkStripPreview(); let ui;
|
|
99
|
+
try { ui=new preview.core.InteractiveMode(preview.runtime,{tuiMode:'fullscreen'}); await ui.run(); }
|
|
100
|
+
finally { ui?.stop(); await preview.cleanup(); }
|
|
101
|
+
}
|