@notrico/pi-fold 0.0.0-stage → 3.0.0
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 +129 -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-work-strip.mjs +84 -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 +64 -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 +101 -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 +236 -0
- package/src/modern-tool-content.ts +28 -0
- package/src/modern-tool-images.ts +63 -0
- package/src/modern-tool-pane.ts +208 -0
- package/src/modern-tools.ts +509 -0
- package/src/modern-workflows.ts +209 -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 +104 -0
- package/src/work-strip.ts +443 -0
- package/tests/action-intent.test.mjs +44 -0
- package/tests/codemode.test.mjs +365 -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.test.mjs +50 -0
- package/tests/mixed-thinking.test.mjs +319 -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 +908 -0
- package/tests/modern-workflows.test.mjs +147 -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 +271 -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,443 @@
|
|
|
1
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
2
|
+
import { AssistantMessageComponent, CustomMessageComponent, InteractiveMode, SkillInvocationMessageComponent, ToolExecutionComponent, UserMessageComponent, VERSION, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { Container, Spacer, matchesKey } from '@earendil-works/pi-tui';
|
|
4
|
+
import { chainNativeMethod } from './native-method-chain.ts';
|
|
5
|
+
import { ToolPane } from './modern-tool-pane.ts';
|
|
6
|
+
import { recordedPaneHeight } from './modern-recorded-pane.ts';
|
|
7
|
+
import { monitorWorkStripSubagents } from './work-strip-subagents.ts';
|
|
8
|
+
import { mixedThinkingRegion } from './modern-thinking-adapter.ts';
|
|
9
|
+
import { actionIntent } from './action-intent.ts';
|
|
10
|
+
import { projectedChildren, recordedWorkEvidence, renderFinalReply, workEvidenceType, workSummary, WorkChild, WorkStripHeader, type WorkEvidence } from './work-strip-view.ts';
|
|
11
|
+
|
|
12
|
+
type Turn = { user: any; header: WorkStripHeader; rows: any[]; activity?: boolean; evidence?: WorkEvidence; startedAt?: number; settled?: boolean; final?: any; finalReply?: any; outcome?: WorkEvidence['outcome']; completedAt?: number; persisted?: boolean; noFinal?: boolean; children: Set<string> };
|
|
13
|
+
const text = (message: any) => typeof message?.content === 'string' ? message.content : Array.isArray(message?.content) ? message.content.filter((b: any) => b?.type === 'text' && typeof b.text === 'string').map((b: any) => b.text).join('\n') : '';
|
|
14
|
+
const visibleText = (message: any) => typeof message?.content === 'string' ? message.content : message?.content?.find((b: any) => b?.type === 'text' && typeof b.text === 'string' && /\S/.test(b.text))?.text || '';
|
|
15
|
+
const shortName = (name: string) => name.split(/[/:]/).at(-1) || name;
|
|
16
|
+
/** Thinking, commentary and a response clock alone are not execution activity. */
|
|
17
|
+
export function isWorkActivity(row: any): boolean {
|
|
18
|
+
if (row instanceof ToolExecutionComponent) return true;
|
|
19
|
+
if (row instanceof AssistantMessageComponent) return row.lastMessage?.content?.some((b: any) => b.type === 'toolCall') === true;
|
|
20
|
+
const message = row.message || row.entry;
|
|
21
|
+
return message?.role === 'bashExecution' || /^subagent(?:s?[-_]|$)/.test(message?.customType || '');
|
|
22
|
+
}
|
|
23
|
+
const descendant = (component: any, target: (c: any) => boolean, seen = new Set<any>()): boolean => {
|
|
24
|
+
if (!component || seen.has(component)) return false;
|
|
25
|
+
seen.add(component);
|
|
26
|
+
return target(component) || (Array.isArray(component.children) && component.children.some((c: any) => descendant(c, target, seen))) || !!component.child && descendant(component.child, target, seen);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** Known decision records always remain outside the work fold, even after an answer. */
|
|
30
|
+
export function keepWorkRowVisible(row: any, completed: boolean): boolean {
|
|
31
|
+
if (row instanceof ToolExecutionComponent) {
|
|
32
|
+
const name = shortName(row.toolName);
|
|
33
|
+
if (['ask_user_question', 'contact_supervisor'].includes(name)) return true;
|
|
34
|
+
if (['subagent_supervision', 'subagent_supervisor'].includes(name)) {
|
|
35
|
+
// Recorded reply content remains in the decision entry. Successful tool
|
|
36
|
+
// receipts/status checks are routine activity; unknown operations stay out.
|
|
37
|
+
if (row.result && !row.isPartial && !row.result.isError &&
|
|
38
|
+
['reply', 'pending', 'status', 'list'].includes(row.args?.action) &&
|
|
39
|
+
(!row.result.details?.status || ['success', 'ok', 'completed'].includes(row.result.details.status))) return false;
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
return !row.result || row.isPartial || !completed && !!row.result.isError;
|
|
43
|
+
}
|
|
44
|
+
if (row instanceof AssistantMessageComponent) return ['error', 'aborted', 'length'].includes(row.lastMessage?.stopReason);
|
|
45
|
+
const message = row.message || row.entry;
|
|
46
|
+
if (message?.customType) {
|
|
47
|
+
const kind = message.customType;
|
|
48
|
+
if (kind === 'ddd') return message.details?.severity !== 'notice';
|
|
49
|
+
if (kind === 'subagent_supervisor_request') return message.details?.reason !== 'progress_update';
|
|
50
|
+
if (kind === 'subagent_supervisor_reply' || /unanswered|blocked|unhandled|failed|clarification/.test(kind)) return true;
|
|
51
|
+
if (kind === 'subagent-notify') return message.details?.runs?.some((r: any) => r.status !== 'completed') ?? true;
|
|
52
|
+
return !['subagent-incremental-child-notify', 'subagent-wait-subscription'].includes(kind);
|
|
53
|
+
}
|
|
54
|
+
// Native notifications, summaries, unknown extensions and user shell output
|
|
55
|
+
// are not classified from their prose or concealed by this adapter.
|
|
56
|
+
return !(row instanceof Spacer);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface WorkStripControls {
|
|
60
|
+
dispose(): void;
|
|
61
|
+
setExpanded(open: boolean): boolean;
|
|
62
|
+
isShortcutEnabled(): boolean;
|
|
63
|
+
setShortcutEnabled(enabled: boolean): void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Pi 1.3 display seam. The native tree, transcript, execution and Fleet remain
|
|
67
|
+
* authoritative. Only chatContainer's rendered child list is projected. */
|
|
68
|
+
export function registerWorkStrip(pi: ExtensionAPI, mode: DisplayMode, version = VERSION): WorkStripControls {
|
|
69
|
+
const owner = Symbol.for('compact-renderer:work-registration:v1'), shared = globalThis as any;
|
|
70
|
+
shared[owner]?.();
|
|
71
|
+
const proto = InteractiveMode.prototype as any;
|
|
72
|
+
if (version !== '1.3.0' || !['addMessageToChat', 'handleEvent', 'renderSessionItems'].every(k => typeof proto[k] === 'function')) return { dispose() {}, setExpanded: () => false, isShortcutEnabled: () => false, setShortcutEnabled() {} };
|
|
73
|
+
let disposed = false, ctx: any, host: any, attached: any, detachChat: (() => void) | undefined;
|
|
74
|
+
let turns = new Map<any, Turn>(), sources = new WeakMap<any, any>(), hooks = new Map<any, ToolPane>();
|
|
75
|
+
let selected: WorkStripHeader | ToolPane | undefined, input: (() => void) | undefined, timer: ReturnType<typeof setTimeout> | undefined;
|
|
76
|
+
let ticker: ReturnType<typeof setInterval> | undefined, running = false, pendingStart: number | undefined;
|
|
77
|
+
let records: any[] = [], evidence = new Map<string, WorkEvidence>(), messageIds = new Map<any, string>();
|
|
78
|
+
let entryIds = new Set<string>();
|
|
79
|
+
const aliases = new WeakMap<object, string>();
|
|
80
|
+
let ownership = false, replaying = 0;
|
|
81
|
+
let liveStarts = new WeakMap<any, number>();
|
|
82
|
+
const finalViews = new WeakMap<any, any>();
|
|
83
|
+
const childViews = new WeakMap<any, WorkChild>();
|
|
84
|
+
const hookViews = new WeakMap<any, Container>();
|
|
85
|
+
const redraw = () => host?.ui?.requestRender?.();
|
|
86
|
+
const release = () => { if (selected) selected.focused = false; selected = undefined; };
|
|
87
|
+
const publishOwnership = (force = false) => {
|
|
88
|
+
const active = !disposed && !!ctx && !!attached && mode.isEnabled() && current()?.activity === true;
|
|
89
|
+
if (force || active !== ownership) {
|
|
90
|
+
ownership = active;
|
|
91
|
+
pi.events.emit('compact-renderer:work-strip:v1', { version: 1, ownsExecutionStatus: active });
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
const readRecords = () => {
|
|
95
|
+
records = ctx?.sessionManager?.getBranch?.() || [];
|
|
96
|
+
messageIds = new Map(records.filter(e => e.type === 'message').map(e => [e.message, e.id]));
|
|
97
|
+
entryIds = new Set(records.map(e => e.id));
|
|
98
|
+
evidence = recordedWorkEvidence(records);
|
|
99
|
+
};
|
|
100
|
+
const idFor = (message: any) => {
|
|
101
|
+
if (!message || typeof message !== 'object') return;
|
|
102
|
+
const known = messageIds.get(message) || aliases.get(message);
|
|
103
|
+
if (known && entryIds.has(known)) return known;
|
|
104
|
+
const sameContent = (a: any, b: any) => a === b || Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((part: any, i: number) => part === b[i] || part?.type === b[i]?.type &&
|
|
105
|
+
(part.type === 'text' ? part.text === b[i].text : part.type === 'thinking' ? part.thinking === b[i].thinking : false));
|
|
106
|
+
const entry = records.find(e => e.type === 'message' && e.message?.role === message.role && Number.isFinite(message.timestamp) && e.message.timestamp === message.timestamp && sameContent(e.message.content, message.content));
|
|
107
|
+
if (entry) aliases.set(message, entry.id);
|
|
108
|
+
return entry?.id;
|
|
109
|
+
};
|
|
110
|
+
const follow = () => host?.ui?.isFollowingOutput === true;
|
|
111
|
+
let latestTurn: Turn | undefined;
|
|
112
|
+
const current = () => latestTurn;
|
|
113
|
+
const monitor = monitorWorkStripSubagents(pi, () => { scheduleFinish(); redraw(); });
|
|
114
|
+
const select = (item: WorkStripHeader | ToolPane, target: any) => {
|
|
115
|
+
release(); selected = item; item.focused = true;
|
|
116
|
+
if (item instanceof WorkStripHeader) item.expand(); else item.open = true;
|
|
117
|
+
redraw();
|
|
118
|
+
pi.events.emit('compact-renderer:focus:v1', { owner: 'work', target: (c: any) => c === target });
|
|
119
|
+
};
|
|
120
|
+
const hookPane = (row: any) => {
|
|
121
|
+
let pane = hooks.get(row);
|
|
122
|
+
if (!pane) {
|
|
123
|
+
const content = text(row.message);
|
|
124
|
+
const summary = workSummary(content);
|
|
125
|
+
pane = new ToolPane([{ id: 'notice', label: 'DDD', repeatedSummary: summary, sections: () => [{ text: content, format: 'markdown' }] }], `DDD · ${summary || 'Recorded notice'}`, recordedPaneHeight);
|
|
126
|
+
pane.directContent = true; pane.headingTone = row.message.details?.severity === 'blocking' ? 'error' : 'muted';
|
|
127
|
+
hooks.set(row, pane);
|
|
128
|
+
}
|
|
129
|
+
pane.theme = ctx?.ui?.theme;
|
|
130
|
+
pane.styleHeader = value => pane!.theme ? pane!.theme.fg(pane!.headingTone, pane!.theme.bold(value)) : value;
|
|
131
|
+
return pane;
|
|
132
|
+
};
|
|
133
|
+
const finalView = (row: any, foldThinking: boolean) => {
|
|
134
|
+
let view = finalViews.get(row);
|
|
135
|
+
if (!view) {
|
|
136
|
+
view = { children: [row], theme: undefined, foldThinking: false, invalidate: () => row.invalidate(), handleMouse: (event: any) => row.handleMouse(event), render(width: number) {
|
|
137
|
+
// Only the known hidden-thinking region is folded. Native reply Markdown,
|
|
138
|
+
// OSC markers, explicit Ctrl+T expansion and unknown shapes are retained.
|
|
139
|
+
const region = this.foldThinking && mixedThinkingRegion(row, row.lastMessage);
|
|
140
|
+
if (!region) return renderFinalReply(row, width, this.theme);
|
|
141
|
+
const container = row.contentContainer, children = container.children;
|
|
142
|
+
const index = children.indexOf(region);
|
|
143
|
+
// The validated native shape places a spacer after hidden thinking
|
|
144
|
+
// when text follows. Remove both, retaining the initial message gap.
|
|
145
|
+
container.children = children.filter((child: any, i: number) => child !== region && !(i === index + 1 && child instanceof Spacer));
|
|
146
|
+
try { return renderFinalReply(row, width, this.theme); } finally { container.children = children; }
|
|
147
|
+
} };
|
|
148
|
+
finalViews.set(row, view);
|
|
149
|
+
}
|
|
150
|
+
view.theme = ctx?.ui?.theme; view.foldThinking = foldThinking;
|
|
151
|
+
return view;
|
|
152
|
+
};
|
|
153
|
+
const childView = (row: any) => {
|
|
154
|
+
let view = childViews.get(row);
|
|
155
|
+
if (!view) { view = new WorkChild(row); childViews.set(row, view); }
|
|
156
|
+
return view;
|
|
157
|
+
};
|
|
158
|
+
const hookView = (row: any) => {
|
|
159
|
+
const pane = hookPane(row);
|
|
160
|
+
let view = hookViews.get(row);
|
|
161
|
+
if (!view || !view.children.includes(pane)) {
|
|
162
|
+
// Preserve CustomMessageComponent's internal leading gap in its compact
|
|
163
|
+
// replacement. Outer transcript spacers are handled independently.
|
|
164
|
+
view = new Container(); view.addChild(new Spacer(1)); view.addChild(pane);
|
|
165
|
+
hookViews.set(row, view);
|
|
166
|
+
}
|
|
167
|
+
return view;
|
|
168
|
+
};
|
|
169
|
+
const scan = (rows: any[]) => {
|
|
170
|
+
let turn: Turn | undefined;
|
|
171
|
+
const present = new Set<any>();
|
|
172
|
+
for (const row of rows) {
|
|
173
|
+
if ((row instanceof UserMessageComponent || row instanceof SkillInvocationMessageComponent) && sources.has(row)) {
|
|
174
|
+
const user = sources.get(row);
|
|
175
|
+
turn = turns.get(user);
|
|
176
|
+
if (!turn) {
|
|
177
|
+
const header = new WorkStripHeader(mouse => { if (mouse) { release(); pi.events.emit('compact-renderer:focus:v1', { owner: 'editor' }); } redraw(); });
|
|
178
|
+
turn = { user, rows: [], header, children: new Set(), startedAt: liveStarts.get(user) };
|
|
179
|
+
turns.set(user, turn);
|
|
180
|
+
}
|
|
181
|
+
turn.rows = []; present.add(user);
|
|
182
|
+
const saved = evidence.get(idFor(user));
|
|
183
|
+
if (saved && !turn.startedAt) { turn.evidence = saved; turn.completedAt = saved.endedAt; turn.outcome = saved.outcome; }
|
|
184
|
+
} else if (turn) {
|
|
185
|
+
turn.rows.push(row);
|
|
186
|
+
if (row instanceof ToolExecutionComponent && ['subagent', 'subagents'].includes(shortName(row.toolName))) {
|
|
187
|
+
const id = row.result?.details?.asyncId || row.args?.async === true && row.result?.details?.runId;
|
|
188
|
+
if (typeof id === 'string') turn.children.add(id);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
latestTurn = turn;
|
|
193
|
+
for (const key of turns.keys()) if (!present.has(key)) turns.delete(key);
|
|
194
|
+
for (const turn of turns.values()) turn.activity = turn.children.size > 0 || turn.rows.some(isWorkActivity);
|
|
195
|
+
publishOwnership();
|
|
196
|
+
};
|
|
197
|
+
const project = (rows: any[]) => {
|
|
198
|
+
scan(rows);
|
|
199
|
+
const starts = new Map<any, Turn>();
|
|
200
|
+
for (const turn of turns.values()) if (turn.rows.length) {
|
|
201
|
+
starts.set(turn.rows[0], turn);
|
|
202
|
+
turn.final = turn.evidence ? turn.rows.find(r => r instanceof AssistantMessageComponent && idFor(r.lastMessage) === turn.evidence!.finalId) : turn.rows.findLast(r => r instanceof AssistantMessageComponent);
|
|
203
|
+
// Replayed terminal replies can use their native turn boundary. Live
|
|
204
|
+
// replies wait for settlement; a text-bearing tool call is still work.
|
|
205
|
+
const settled = !!turn.evidence || (turn.startedAt ? turn.settled && (current() !== turn || !running) &&
|
|
206
|
+
monitor.statusFor([...turn.children]) === 'idle' : true);
|
|
207
|
+
const message = turn.final?.lastMessage;
|
|
208
|
+
turn.finalReply = settled && !turn.final?.isStreaming && visibleText(message) &&
|
|
209
|
+
['stop', 'error', 'aborted', 'length'].includes(message?.stopReason) &&
|
|
210
|
+
!message.content.some((block: any) => block.type === 'toolCall') ? turn.final : undefined;
|
|
211
|
+
}
|
|
212
|
+
const output: any[] = [];
|
|
213
|
+
let spacing: Spacer[] = [];
|
|
214
|
+
const append = (row: any) => { output.push(...spacing, row); spacing = []; };
|
|
215
|
+
let turn: Turn | undefined;
|
|
216
|
+
for (const row of rows) {
|
|
217
|
+
if (row instanceof UserMessageComponent || row instanceof SkillInvocationMessageComponent) {
|
|
218
|
+
turn = undefined; append(row); continue;
|
|
219
|
+
}
|
|
220
|
+
if (starts.has(row)) {
|
|
221
|
+
turn = starts.get(row)!;
|
|
222
|
+
}
|
|
223
|
+
if (starts.has(row) && turn?.activity) {
|
|
224
|
+
const h = turn.header, saved = turn.evidence;
|
|
225
|
+
h.theme = ctx?.ui?.theme;
|
|
226
|
+
h.state = turn.completedAt ? turn.noFinal ? 'stopped' : turn.outcome || 'completed' : turn.startedAt ? turn.outcome === 'interrupted' ? 'interrupted' : running && current() === turn ? 'working' : 'waiting' : saved?.outcome || 'history';
|
|
227
|
+
// Completed/history titles do not display a summary. Live titles follow
|
|
228
|
+
// the last operation without copying and reversing the turn twice.
|
|
229
|
+
if (h.state !== 'completed' && h.state !== 'history') {
|
|
230
|
+
const operation = turn.rows.findLast(r => r instanceof ToolExecutionComponent || r instanceof AssistantMessageComponent && visibleText(r.lastMessage));
|
|
231
|
+
const assistant = turn.rows.findLast(r => r instanceof AssistantMessageComponent);
|
|
232
|
+
h.summary = operation instanceof ToolExecutionComponent ? actionIntent(operation.toolName, operation.args) : workSummary(visibleText(assistant?.lastMessage));
|
|
233
|
+
}
|
|
234
|
+
h.elapsedMs = saved ? saved.endedAt - saved.startedAt : turn.startedAt ? (turn.completedAt ?? Date.now()) - turn.startedAt : 0;
|
|
235
|
+
h.finish(follow());
|
|
236
|
+
output.push(h);
|
|
237
|
+
}
|
|
238
|
+
// Native outer spacing belongs to the immediately following block, not
|
|
239
|
+
// to the previous turn. Keep it with visible skills, prompts, summaries,
|
|
240
|
+
// and unknown cards; discard it with hidden content. Do not accumulate
|
|
241
|
+
// gaps across hidden blocks or add gaps to internally spaced components.
|
|
242
|
+
if (row instanceof Spacer) { spacing.push(row); continue; }
|
|
243
|
+
if (!turn?.activity || turn.header.open || row === turn.final || keepWorkRowVisible(row, turn.header.state === 'completed')) {
|
|
244
|
+
let view = row instanceof CustomMessageComponent && row.message?.customType === 'ddd' ? hookView(row) : turn && row === turn.finalReply ? finalView(row, !!turn.activity && !turn.header.open) : row;
|
|
245
|
+
// The newest assistant row is only a final candidate until settlement.
|
|
246
|
+
// Keep it and attention rows in the work gutter until final confirmation.
|
|
247
|
+
if (turn?.activity && row !== turn.finalReply && (row instanceof AssistantMessageComponent || isWorkActivity(row) ||
|
|
248
|
+
row instanceof CustomMessageComponent && row.message?.customType === 'ddd')) view = childView(view);
|
|
249
|
+
append(view);
|
|
250
|
+
} else spacing = [];
|
|
251
|
+
}
|
|
252
|
+
if (!turn?.activity || turn.header.open) output.push(...spacing);
|
|
253
|
+
return output;
|
|
254
|
+
};
|
|
255
|
+
const attach = (candidate: any) => {
|
|
256
|
+
if (disposed || !(candidate?.chatContainer instanceof Container) || !candidate.ui) return;
|
|
257
|
+
if (host !== candidate) { detachChat?.(); host = candidate; attached = undefined; }
|
|
258
|
+
if (attached) return;
|
|
259
|
+
const chat = candidate.chatContainer;
|
|
260
|
+
detachChat = chainNativeMethod(chat, 'render', function(native, width) {
|
|
261
|
+
if (disposed || !ctx || !mode.isEnabled()) { delete this[projectedChildren]; return native.call(this, width); }
|
|
262
|
+
const canonical = this.children;
|
|
263
|
+
this[projectedChildren] = project(canonical);
|
|
264
|
+
this.children = this[projectedChildren];
|
|
265
|
+
try { return native.call(this, width); } finally { this.children = canonical; }
|
|
266
|
+
});
|
|
267
|
+
attached = chat;
|
|
268
|
+
};
|
|
269
|
+
const detachAdd = chainNativeMethod(proto, 'addMessageToChat', function(native, message, ...args) {
|
|
270
|
+
attach(this); const before = this.chatContainer?.children.length || 0;
|
|
271
|
+
const result = native.call(this, message, ...args);
|
|
272
|
+
for (const row of this.chatContainer?.children.slice(before) || []) if (!(row instanceof Spacer)) sources.set(row, message);
|
|
273
|
+
if (!replaying && running && message.role === 'user') liveStarts.set(message, Date.now());
|
|
274
|
+
return result;
|
|
275
|
+
});
|
|
276
|
+
const detachReplay = chainNativeMethod(proto, 'renderSessionItems', function(native, ...args) { attach(this); replaying++; try { return native.apply(this, args); } finally { replaying--; } });
|
|
277
|
+
const detachEvent = chainNativeMethod(proto, 'handleEvent', function(native, event, ...args) { attach(this); return native.call(this, event, ...args); });
|
|
278
|
+
|
|
279
|
+
function scheduleFinish() {
|
|
280
|
+
if (disposed || !ctx) return;
|
|
281
|
+
if (timer) clearTimeout(timer);
|
|
282
|
+
timer = setTimeout(() => {
|
|
283
|
+
timer = undefined;
|
|
284
|
+
if (disposed || !ctx) return;
|
|
285
|
+
if (attached) scan(attached.children);
|
|
286
|
+
readRecords();
|
|
287
|
+
for (const turn of turns.values()) {
|
|
288
|
+
if (!turn.settled || !turn.startedAt || turn.persisted || current() === turn && (running || ctx.isIdle?.() === false)) continue;
|
|
289
|
+
if (!turn.activity) continue;
|
|
290
|
+
if (monitor.statusFor([...turn.children]) !== 'idle') continue;
|
|
291
|
+
const userId = idFor(turn.user), startIndex = records.findIndex(e => e.id === userId);
|
|
292
|
+
if (!userId || startIndex < 0) continue;
|
|
293
|
+
const nextUser = records.findIndex((e, i) => i > startIndex && e.message?.role === 'user');
|
|
294
|
+
const span = records.slice(startIndex + 1, nextUser < 0 ? undefined : nextUser);
|
|
295
|
+
const final = [...span].reverse().find(e => e.type === 'message' && e.message.role === 'assistant');
|
|
296
|
+
if (!final || !visibleText(final.message) || !['stop', 'error', 'aborted', 'length'].includes(final.message.stopReason)) {
|
|
297
|
+
turn.noFinal = true; turn.completedAt = Date.now(); turn.persisted = true;
|
|
298
|
+
continue; // Never promote earlier commentary to a final response.
|
|
299
|
+
}
|
|
300
|
+
const outcome = turn.outcome || (final.message.stopReason === 'error' || final.message.stopReason === 'length' ? 'error' : final.message.stopReason === 'aborted' ? 'interrupted' : 'completed');
|
|
301
|
+
const data: WorkEvidence = { version: 1, userId, finalId: final.id, endId: span.at(-1).id, startedAt: turn.startedAt, endedAt: Date.now(), outcome };
|
|
302
|
+
turn.completedAt = data.endedAt; turn.outcome = outcome; turn.evidence = data; turn.persisted = true;
|
|
303
|
+
// Presentation metadata is excluded from model context. Original messages
|
|
304
|
+
// and tool results are not rewritten.
|
|
305
|
+
pi.appendEntry(workEvidenceType, data);
|
|
306
|
+
}
|
|
307
|
+
readRecords(); redraw();
|
|
308
|
+
}, 100);
|
|
309
|
+
}
|
|
310
|
+
const reset = (_event: any, context: any) => {
|
|
311
|
+
release(); input?.(); input = undefined; ctx = context.mode === 'tui' ? context : undefined;
|
|
312
|
+
running = false; pendingStart = undefined;
|
|
313
|
+
turns.clear(); latestTurn = undefined; hooks.clear(); liveStarts = new WeakMap(); readRecords(); monitor.reset();
|
|
314
|
+
if (timer) clearTimeout(timer); timer = undefined;
|
|
315
|
+
if (ticker) clearInterval(ticker); ticker = undefined;
|
|
316
|
+
if (ctx) {
|
|
317
|
+
input = ctx.ui.onTerminalInput?.((data: string) => {
|
|
318
|
+
if (!selected || !mode.isEnabled()) return;
|
|
319
|
+
if (matchesKey(data, 'escape')) { release(); pi.events.emit('compact-renderer:inspection-ended:v1', {}); redraw(); return { consume: true }; }
|
|
320
|
+
if (selected instanceof WorkStripHeader && matchesKey(data, 'enter')) {
|
|
321
|
+
const header = selected; header.manual = true; header.open = !header.open; redraw(); return { consume: true };
|
|
322
|
+
}
|
|
323
|
+
if (selected instanceof ToolPane && selected.handle(data)) { redraw(); return { consume: true }; }
|
|
324
|
+
release(); pi.events.emit('compact-renderer:inspection-ended:v1', {}); redraw();
|
|
325
|
+
});
|
|
326
|
+
ticker = setInterval(() => { if (running || current()?.header.state === 'waiting') redraw(); }, 1000);
|
|
327
|
+
ticker.unref?.();
|
|
328
|
+
}
|
|
329
|
+
publishOwnership(true); redraw();
|
|
330
|
+
};
|
|
331
|
+
const subscriptions = [
|
|
332
|
+
pi.on('session_start', reset), pi.on('session_tree', (event, context) => { if (running) { readRecords(); redraw(); } else reset(event, context); }), pi.on('session_compact', () => { readRecords(); redraw(); }),
|
|
333
|
+
pi.on('session_before_switch', () => { reset({}, { mode: 'none' }); detachChat?.(); detachChat = undefined; attached = undefined; host = undefined; sources = new WeakMap(); }),
|
|
334
|
+
pi.on('agent_start', () => {
|
|
335
|
+
running = true; pendingStart = Date.now();
|
|
336
|
+
monitor.refresh(); redraw();
|
|
337
|
+
}),
|
|
338
|
+
pi.on('message_start', (event: any) => {
|
|
339
|
+
if (event.message?.role !== 'assistant' || !running || !attached) return;
|
|
340
|
+
scan(attached.children);
|
|
341
|
+
const turn = current();
|
|
342
|
+
if (turn) {
|
|
343
|
+
turn.startedAt ??= pendingStart ?? Date.now(); turn.settled = false;
|
|
344
|
+
turn.completedAt = undefined; turn.evidence = undefined; turn.persisted = false; turn.outcome = undefined; turn.noFinal = false;
|
|
345
|
+
}
|
|
346
|
+
redraw();
|
|
347
|
+
}),
|
|
348
|
+
pi.on('message_end', () => { readRecords(); redraw(); }),
|
|
349
|
+
pi.on('agent_settled', (event: any) => {
|
|
350
|
+
running = false; readRecords(); if (attached) scan(attached.children);
|
|
351
|
+
for (const turn of turns.values()) if (turn.startedAt && !turn.completedAt) turn.settled = true;
|
|
352
|
+
if (event.aborted && current()) current()!.outcome = 'interrupted';
|
|
353
|
+
monitor.refresh(); scheduleFinish(); redraw();
|
|
354
|
+
}),
|
|
355
|
+
pi.events.on('subagent:async-started', (event: any) => {
|
|
356
|
+
if (!ctx || !attached || typeof event?.id !== 'string' || event.parentWorkflowRunId) return;
|
|
357
|
+
const sessionId = ctx.sessionManager?.getSessionId?.();
|
|
358
|
+
if (event.sessionId && sessionId && event.sessionId !== sessionId) return;
|
|
359
|
+
scan(attached.children); current()?.children.add(event.id); redraw();
|
|
360
|
+
}),
|
|
361
|
+
pi.on('ui_prompt_start', release),
|
|
362
|
+
mode.onChange(() => { release(); if (attached && !mode.isEnabled()) delete attached[projectedChildren]; publishOwnership(); redraw(); }),
|
|
363
|
+
pi.events.on('compact-renderer:work-strip-query:v1', () => publishOwnership(true)),
|
|
364
|
+
pi.events.on('compact-renderer:focus:v1', (event: any) => {
|
|
365
|
+
if (event?.owner !== 'work') release();
|
|
366
|
+
if (typeof event?.target === 'function' && mode.isEnabled()) {
|
|
367
|
+
for (const turn of turns.values()) if (turn.activity && turn.rows.some(row => descendant(row, event.target))) turn.header.expand();
|
|
368
|
+
redraw();
|
|
369
|
+
}
|
|
370
|
+
}),
|
|
371
|
+
pi.events.on('compact-renderer:inspect:v1', (request: any) => {
|
|
372
|
+
if (!ctx || !mode.isEnabled()) return;
|
|
373
|
+
for (const [index, turn] of [...turns.values()].entries()) if (turn.activity) request?.add?.({ id: `work-${index}`, kind: 'Work', label: turn.header.title, focus: () => select(turn.header, turn.header) });
|
|
374
|
+
for (const [row, pane] of hooks) request?.add?.({ id: `hook-${[...hooks.keys()].indexOf(row)}`, kind: 'Hook', label: pane.title, focus: () => select(pane, pane) });
|
|
375
|
+
}),
|
|
376
|
+
];
|
|
377
|
+
// Use native shortcut dispatch so dialogs and editor input keep their owners.
|
|
378
|
+
// The command remains available on terminals that do not send modified keys.
|
|
379
|
+
let shortcut = true;
|
|
380
|
+
const nestedDisclosures = (eligible: Turn[]) => {
|
|
381
|
+
const resets = new Set<() => void>();
|
|
382
|
+
let visibleOpen = false;
|
|
383
|
+
const add = (target: (component: any) => boolean, open: boolean, collapse: () => void) => {
|
|
384
|
+
for (const turn of eligible) for (const row of turn.rows) if (descendant(row, target)) {
|
|
385
|
+
resets.add(collapse);
|
|
386
|
+
if (open && (turn.header.open || row === turn.final || keepWorkRowVisible(row, turn.header.state === 'completed'))) visibleOpen = true;
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
// Owners identify and reset their own panes. Never alter native disclosure properties.
|
|
390
|
+
pi.events.emit('compact-renderer:disclosures:v1', { add });
|
|
391
|
+
for (const [row, pane] of hooks) add(component => component === row, pane.open, () => pane.collapse());
|
|
392
|
+
return { visibleOpen, collapse: () => resets.forEach(reset => reset()) };
|
|
393
|
+
};
|
|
394
|
+
const setAll = (open: boolean) => {
|
|
395
|
+
if (disposed || !ctx || !mode.isEnabled() || !attached) return false;
|
|
396
|
+
project(attached.children);
|
|
397
|
+
release();
|
|
398
|
+
const eligible = [...turns.values()].filter(turn => turn.activity && !['working', 'waiting'].includes(turn.header.state));
|
|
399
|
+
if (!open) nestedDisclosures(eligible).collapse();
|
|
400
|
+
for (const turn of turns.values()) {
|
|
401
|
+
if (!turn.activity || !open && ['working', 'waiting'].includes(turn.header.state)) continue;
|
|
402
|
+
turn.header.manual = true; turn.header.open = open;
|
|
403
|
+
}
|
|
404
|
+
pi.events.emit('compact-renderer:inspection-ended:v1', {});
|
|
405
|
+
redraw();
|
|
406
|
+
return true;
|
|
407
|
+
};
|
|
408
|
+
const toggleCompleted = () => {
|
|
409
|
+
if (disposed || !ctx || !mode.isEnabled() || !attached) return false;
|
|
410
|
+
project(attached.children);
|
|
411
|
+
const eligible = [...turns.values()].filter(turn => turn.activity && !['working', 'waiting'].includes(turn.header.state));
|
|
412
|
+
if (!eligible.length) return true;
|
|
413
|
+
const nested = nestedDisclosures(eligible);
|
|
414
|
+
const open = !eligible.some(turn => turn.header.open) && !nested.visibleOpen;
|
|
415
|
+
release();
|
|
416
|
+
if (!open) nested.collapse();
|
|
417
|
+
for (const turn of eligible) { turn.header.manual = true; turn.header.open = open; }
|
|
418
|
+
pi.events.emit('compact-renderer:inspection-ended:v1', {});
|
|
419
|
+
redraw();
|
|
420
|
+
return true;
|
|
421
|
+
};
|
|
422
|
+
pi.registerShortcut?.('ctrl+alt+w', {
|
|
423
|
+
description: 'Toggle completed work sections (enabled with /fold shortcut)',
|
|
424
|
+
handler: () => { if (shortcut) toggleCompleted(); },
|
|
425
|
+
});
|
|
426
|
+
const dispose = () => {
|
|
427
|
+
if (disposed) return; disposed = true;
|
|
428
|
+
release(); input?.(); if (timer) clearTimeout(timer); if (ticker) clearInterval(ticker);
|
|
429
|
+
monitor.dispose(); subscriptions.forEach(off => off?.());
|
|
430
|
+
if (attached) delete attached[projectedChildren];
|
|
431
|
+
detachChat?.(); detachEvent(); detachReplay(); detachAdd();
|
|
432
|
+
publishOwnership(true); redraw(); turns.clear(); latestTurn = undefined; hooks.clear(); ctx = undefined;
|
|
433
|
+
if (shared[owner] === dispose) delete shared[owner];
|
|
434
|
+
};
|
|
435
|
+
subscriptions.push(pi.on('session_shutdown', dispose));
|
|
436
|
+
shared[owner] = dispose;
|
|
437
|
+
return {
|
|
438
|
+
dispose,
|
|
439
|
+
setExpanded: setAll,
|
|
440
|
+
isShortcutEnabled: () => shortcut,
|
|
441
|
+
setShortcutEnabled: enabled => { if (!disposed) shortcut = enabled; },
|
|
442
|
+
};
|
|
443
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { loadSource } from './test-runtime.mjs';
|
|
3
|
+
const { actionIntent, groupIntent, codeIntent } = await loadSource('./action-intent.ts');
|
|
4
|
+
const bash = command => ({ name: 'bash', args: { command } });
|
|
5
|
+
|
|
6
|
+
assert.equal(actionIntent('read', { path: '/secret/project' }), 'Read files');
|
|
7
|
+
assert.equal(actionIntent('mcp__filesystem__read_file', {}), 'Read files');
|
|
8
|
+
assert.equal(actionIntent('bash', { command: "jq '.records[] | .name' records.json" }), 'Inspect JSON records');
|
|
9
|
+
assert.equal(actionIntent('bash', { command: 'gh pr list --json number,title' }), 'Check pull requests');
|
|
10
|
+
assert.equal(actionIntent('bash', { command: 'gh pr checks 19' }), 'Check pull requests');
|
|
11
|
+
assert.equal(actionIntent('bash', { command: 'git status --short && git diff --stat' }), 'Check Git changes');
|
|
12
|
+
assert.equal(actionIntent('bash', { command: "cd /project && cat README.md && npm test" }), 'Read files and run checks');
|
|
13
|
+
assert.equal(actionIntent('bash', { command: 'node action-intent.test.mjs' }), 'Run checks');
|
|
14
|
+
assert.equal(groupIntent([bash("jq '.records' records.json"), bash('gh pr checks 19')]), 'Inspect JSON records and check pull requests');
|
|
15
|
+
assert.equal(groupIntent([bash('git status'), bash('git diff')]), 'Check Git changes');
|
|
16
|
+
assert.equal(groupIntent([bash('cat README.md'), bash('git status'), bash('npm test')]), 'Read files and check Git changes; and other actions');
|
|
17
|
+
assert.equal(groupIntent([bash('cat README.md && git status'), bash('git diff && npm test')]), 'Read files and check Git changes; and other actions', 'combine and deduplicate operations across shell groups');
|
|
18
|
+
assert.equal(groupIntent([bash('cat README.md'), { name: 'unknown-secret-tool', args: {} }]), 'Read files and run tool actions');
|
|
19
|
+
|
|
20
|
+
const nested = [{ name: 'bash', args: JSON.stringify({ command: "jq '.records' records.json" }), status: 'ok' }, { name: 'bash', args: JSON.stringify({ command: 'gh pr checks 19' }), status: 'ok' }];
|
|
21
|
+
assert.equal(codeIntent({ code: 'arbitrary JavaScript' }, nested), 'Inspect JSON records and check pull requests');
|
|
22
|
+
assert.equal(codeIntent({ code: 'text("gh pr checks");' }, []), 'Run code');
|
|
23
|
+
assert.equal(codeIntent({}, [{ name: 'bash', args: '{"command":"jq .records ...', status: 'ok' }]), 'Run shell commands');
|
|
24
|
+
assert.equal(codeIntent({}, [{ name: 'read', args: 'truncated preview...' }]), 'Read files');
|
|
25
|
+
assert.equal(actionIntent('bash', JSON.stringify({ command: 'npm run typecheck' })), 'Run checks');
|
|
26
|
+
|
|
27
|
+
// Argument contents, quoted commands, control characters, and source are never labels.
|
|
28
|
+
for (const command of ["echo 'git status'", "node -e 'gh pr checks 19'", 'echo $(git status)', 'cat <<EOF\ngit status\nEOF', "jq 'unterminated", 'echo SECRET\u001b[31m\u202e', 'x'.repeat(1000000)]) {
|
|
29
|
+
assert.equal(actionIntent('bash', { command }), 'Run shell commands');
|
|
30
|
+
}
|
|
31
|
+
assert.equal(actionIntent('bash', { command: "echo 'private; gh pr checks 19'" }), 'Run shell commands');
|
|
32
|
+
assert.equal(actionIntent('unknown\u001b[31m\u202e', { label: 'Reveal SECRET', description: 'secret purpose' }), 'Run tool actions');
|
|
33
|
+
assert.equal(actionIntent('bash', { command: 'gh pr merge 19' }), 'Run shell commands', 'do not call a write operation a check');
|
|
34
|
+
assert.equal(actionIntent('bash', { command: 'git reset --hard' }), 'Run shell commands');
|
|
35
|
+
assert.equal(actionIntent('bash', { command: 'find . -delete' }), 'Run shell commands');
|
|
36
|
+
assert.equal(groupIntent([]), 'Run tool actions');
|
|
37
|
+
assert.equal(groupIntent(Array.from({ length: 65 }, () => ({ name: 'read', args: {} }))), 'Read files; and other actions');
|
|
38
|
+
let reads = 0;
|
|
39
|
+
const args = Object.defineProperty({}, 'command', { get() { reads++; throw new Error('not recorded data'); } });
|
|
40
|
+
assert.equal(actionIntent('bash', args), 'Run shell commands');
|
|
41
|
+
const calls = Object.defineProperty([], 0, { get() { reads++; throw new Error('not recorded data'); } });
|
|
42
|
+
assert.equal(codeIntent({}, calls), 'Run tool actions');
|
|
43
|
+
assert.equal(reads, 0);
|
|
44
|
+
console.log('Action intent checks passed');
|