@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,209 @@
|
|
|
1
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
2
|
+
import { AssistantMessageComponent, VERSION, type ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { Container, Markdown, MouseRegion, Spacer, Text, matchesKey, truncateToWidth } from '@earendil-works/pi-tui';
|
|
4
|
+
import { activityRow, cardContentWidth } from './display-card.ts';
|
|
5
|
+
import { richTextRows } from './modern-rich-text.ts';
|
|
6
|
+
import { recordedPaneHeight } from './modern-recorded-pane.ts';
|
|
7
|
+
import { chainNativeMethod } from './native-method-chain.ts';
|
|
8
|
+
|
|
9
|
+
export type WorkflowFence = { start: number; end: number; source: string; summary: string };
|
|
10
|
+
const summaryText = (value: string) => truncateToWidth(value.slice(0, 1024).replace(/[\p{Cc}\p{Cf}]/gu, ' ').replace(/\s+/g, ' ').trim(), 90, '…');
|
|
11
|
+
|
|
12
|
+
/** Recognize complete, top-level tagged fences only. Other fences shield their bodies.
|
|
13
|
+
* Scan once per recorded text revision; formatting is separate and viewport-bounded. */
|
|
14
|
+
export function modernWorkflowFences(text: string): WorkflowFence[] {
|
|
15
|
+
const fences: WorkflowFence[] = [];
|
|
16
|
+
let offset = 0, open: { marker: string; start: number; body: number; workflow: boolean } | undefined;
|
|
17
|
+
while (offset < text.length) {
|
|
18
|
+
const newline = text.indexOf('\n', offset), end = newline < 0 ? text.length : newline;
|
|
19
|
+
const line = text.slice(offset, end).replace(/\r$/, '');
|
|
20
|
+
if (!open) {
|
|
21
|
+
const marker = /^(`{3,}|~{3,})/.exec(line);
|
|
22
|
+
if (marker) open = { marker: marker[1], start: offset, body: newline < 0 ? end : end + 1, workflow: /^```(?:js|javascript) workflow[ \t]*$/.test(line) };
|
|
23
|
+
} else {
|
|
24
|
+
const close = /^(`{3,}|~{3,})[ \t]*$/.exec(line);
|
|
25
|
+
if (close && close[1][0] === open.marker[0] && close[1].length >= open.marker.length) {
|
|
26
|
+
if (open.workflow && close[1] === '```') {
|
|
27
|
+
const source = text.slice(open.body, offset);
|
|
28
|
+
if (source.trim()) {
|
|
29
|
+
const comment = /^\s*\/\/[^\S\r\n]*([^\r\n]+)/.exec(source.slice(0, 1024))?.[1];
|
|
30
|
+
const prose = text.slice(Math.max(0, open.start - 1024), open.start).trim().split(/\r?\n\s*\r?\n/).at(-1) || '';
|
|
31
|
+
fences.push({ start: open.start, end: newline < 0 ? end : end + 1, source, summary: summaryText(comment || prose) || 'Recorded JavaScript' });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
open = undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (newline < 0) break;
|
|
38
|
+
offset = end + 1;
|
|
39
|
+
}
|
|
40
|
+
return fences;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Lazy source viewport. Neither highlighting nor wrapping receives the full script. */
|
|
44
|
+
export class WorkflowPane {
|
|
45
|
+
open = false; focused = false; offset = 0; paintedRows = 0;
|
|
46
|
+
theme?: any;
|
|
47
|
+
private rows: string[] = []; private iterator?: Iterator<string>; private done = false;
|
|
48
|
+
private width = 0; private themeKey = ''; private lastWidth = 0; private lastHeight = 0;
|
|
49
|
+
constructor(readonly source: string, readonly summary: string, private release: () => void = () => {}) {}
|
|
50
|
+
collapse() { this.open = false; this.focused = false; this.offset = 0; this.invalidate(); }
|
|
51
|
+
invalidate() { this.rows = []; this.iterator = undefined; this.done = false; this.width = 0; }
|
|
52
|
+
handle(data: string) {
|
|
53
|
+
if (matchesKey(data, 'enter')) { this.open = !this.open; this.offset = 0; return true; }
|
|
54
|
+
if (matchesKey(data, 'home')) { this.open = true; this.offset = 0; return true; }
|
|
55
|
+
for (const key of ['up', 'down', 'pageUp', 'pageDown'] as const) if (matchesKey(data, key)) {
|
|
56
|
+
const distance = key === 'pageUp' || key === 'pageDown' ? recordedPaneHeight() : 1;
|
|
57
|
+
this.open = true; this.offset = Math.max(0, this.offset + (key === 'down' || key === 'pageDown' ? distance : -distance)); return true;
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
render(width: number) {
|
|
62
|
+
this.lastWidth = width;
|
|
63
|
+
const theme = this.theme;
|
|
64
|
+
const inner = cardContentWidth(width), indent = inner >= 4 ? ' ' : '', sourceWidth = Math.max(1, inner - indent.length);
|
|
65
|
+
const themeKey = ['syntaxKeyword', 'syntaxString', 'syntaxComment', 'syntaxNumber', 'syntaxFunction', 'syntaxOperator', 'syntaxPunctuation', 'syntaxType', 'syntaxVariable', 'mdCodeBlock'].map(token => theme?.fg(token, 'x') ?? 'x').join('');
|
|
66
|
+
if (this.width !== sourceWidth || themeKey !== this.themeKey) { this.invalidate(); this.width = sourceWidth; this.themeKey = themeKey; this.offset = 0; }
|
|
67
|
+
const label = `${this.open ? '▾' : '▸'} Subagent workflow`;
|
|
68
|
+
const rows = [activityRow(theme ? theme.fg('mdLink', theme.bold(label)) + theme.fg('muted', ` · ${this.summary}`) : `${label} · ${this.summary}`, width, theme, this.focused)];
|
|
69
|
+
if (this.open) {
|
|
70
|
+
this.iterator ??= richTextRows(this.source, sourceWidth, { format: 'code', language: 'javascript' });
|
|
71
|
+
const height = recordedPaneHeight();
|
|
72
|
+
this.offset = Math.min(this.offset, this.rows.length);
|
|
73
|
+
while (!this.done && this.rows.length <= this.offset + height) {
|
|
74
|
+
const row = this.iterator.next();
|
|
75
|
+
if (row.done) this.done = true;
|
|
76
|
+
else { this.rows.push(row.value); this.paintedRows++; }
|
|
77
|
+
}
|
|
78
|
+
if (this.done) this.offset = Math.min(this.offset, Math.max(0, this.rows.length - height));
|
|
79
|
+
rows.push(...this.rows.slice(this.offset, this.offset + height).map(row => activityRow(indent + row, width, theme)));
|
|
80
|
+
const more = !this.done || this.offset + height < this.rows.length;
|
|
81
|
+
const hint = this.focused ? `Enter collapse · ↑/↓ scroll · Home start · Esc release${more ? ' · more ↓' : ''}` : more ? 'more ↓' : '';
|
|
82
|
+
if (hint) rows.push(activityRow(theme ? theme.fg('muted', hint) : hint, width, theme));
|
|
83
|
+
}
|
|
84
|
+
this.lastHeight = rows.length;
|
|
85
|
+
return rows;
|
|
86
|
+
}
|
|
87
|
+
handleMouse(event: any) {
|
|
88
|
+
if (event.x < 0 || event.x >= this.lastWidth || event.y < 0 || event.y >= this.lastHeight) return;
|
|
89
|
+
if (event.type === 'wheel' && this.open && Number.isFinite(event.wheelDelta) && event.wheelDelta) {
|
|
90
|
+
this.release(); this.offset = Math.max(0, this.offset + Math.max(-20, Math.min(20, Math.trunc(event.wheelDelta)))); return { handled: true };
|
|
91
|
+
}
|
|
92
|
+
if (event.type === 'click' && event.button === 'left' && event.y === 0 && !event.ctrl && !event.alt && !event.shift) {
|
|
93
|
+
this.release(); this.open = !this.open; this.offset = 0; return { handled: true };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
type Card = { id: number; component: any; sources: string[]; fences: WorkflowFence[][]; panes: Map<string, WorkflowPane>; displays: Map<any, Container> };
|
|
99
|
+
|
|
100
|
+
/** The public Markdown transformer cannot return components or identify a card.
|
|
101
|
+
* This isolated 1.3.0 seam substitutes display children only during native render.
|
|
102
|
+
* Native messages, Markdown sources, updateContent, and execution remain untouched. */
|
|
103
|
+
export function registerModernWorkflows(pi: ExtensionAPI, mode: DisplayMode, version = VERSION): () => void {
|
|
104
|
+
const owner = Symbol.for('compact-renderer:workflow-registration:v1'), shared = globalThis as any;
|
|
105
|
+
shared[owner]?.();
|
|
106
|
+
const proto = AssistantMessageComponent.prototype as any;
|
|
107
|
+
if (version !== '1.3.0' || typeof proto.render !== 'function' || typeof proto.updateContent !== 'function') return () => {};
|
|
108
|
+
const cards = new Map<any, Card>();
|
|
109
|
+
let active = false, disposed = false, selected: WorkflowPane | undefined, uiTheme: any, nextCard = 0;
|
|
110
|
+
let input: (() => void) | undefined, redraw: (() => void) | undefined;
|
|
111
|
+
const release = () => { if (selected) selected.focused = false; selected = undefined; };
|
|
112
|
+
const mouseRelease = () => { release(); pi.events.emit('compact-renderer:focus:v1', { owner: 'editor' }); };
|
|
113
|
+
const clear = () => { release(); cards.clear(); input?.(); input = undefined; redraw = undefined; active = false; };
|
|
114
|
+
const supported = (component: any): any[] | undefined => {
|
|
115
|
+
const message = component.lastMessage, container = component.contentContainer;
|
|
116
|
+
if (component.isStreaming !== false || message?.role !== 'assistant' || !Array.isArray(message.content) || !Array.isArray(component.children) || component.children.length !== 1 || component.children[0] !== container || container?.constructor !== Container || !Array.isArray(container.children)) return;
|
|
117
|
+
if (!container.children.every((child: any) => child instanceof Markdown || child instanceof Spacer || child instanceof Text || child instanceof MouseRegion && (child.child instanceof Markdown || child.child instanceof Text))) return;
|
|
118
|
+
const text = message.content.filter((block: any) => block.type === 'text' && typeof block.text === 'string' && block.text.trim()).map((block: any) => block.text.trim());
|
|
119
|
+
const markdown = container.children.filter((child: any) => child instanceof Markdown);
|
|
120
|
+
if (text.length !== markdown.length || markdown.some((child: any, index: number) => child.text !== text[index] || typeof child.options?.transform !== 'function' || child.paddingY !== 0)) return;
|
|
121
|
+
return markdown;
|
|
122
|
+
};
|
|
123
|
+
const renderWrapper = function(this: any, nativeRender: (...args: any[]) => any, width: number) {
|
|
124
|
+
const markdown = !disposed && active && mode.isEnabled() ? supported(this) : undefined;
|
|
125
|
+
if (!markdown) { const old = cards.get(this); if (old && [...old.panes.values()].includes(selected!)) release(); cards.delete(this); return nativeRender.call(this, width); }
|
|
126
|
+
const sources = markdown.map((child: any) => child.text);
|
|
127
|
+
let card = cards.get(this);
|
|
128
|
+
if (!card || sources.length !== card.sources.length || sources.some((source: string, index: number) => source !== card!.sources[index])) {
|
|
129
|
+
if (card && [...card.panes.values()].includes(selected!)) release();
|
|
130
|
+
card = { id: nextCard++, component: this, sources, fences: sources.map(modernWorkflowFences), panes: new Map(), displays: new Map() };
|
|
131
|
+
cards.set(this, card);
|
|
132
|
+
}
|
|
133
|
+
if ([...card.displays.keys()].some(child => !markdown.includes(child))) card.displays.clear();
|
|
134
|
+
for (const [blockIndex, child] of markdown.entries()) if (!card.displays.has(child)) {
|
|
135
|
+
const fences = card.fences[blockIndex];
|
|
136
|
+
if (!fences.length) continue;
|
|
137
|
+
const display = new Container(); let offset = 0;
|
|
138
|
+
fences.forEach((fence, index) => {
|
|
139
|
+
const prose = child.text.slice(offset, fence.start);
|
|
140
|
+
if (prose.trim()) display.addChild(new Markdown(prose, child.paddingX, 0, child.theme, child.defaultTextStyle, child.options));
|
|
141
|
+
// Native redraws rebuild Markdown children. Preserve per-fence UI state.
|
|
142
|
+
const key = `${blockIndex}:${index}`;
|
|
143
|
+
let pane = card!.panes.get(key);
|
|
144
|
+
if (!pane) { pane = new WorkflowPane(fence.source, fence.summary, mouseRelease); card!.panes.set(key, pane); }
|
|
145
|
+
display.addChild(pane); offset = fence.end;
|
|
146
|
+
});
|
|
147
|
+
const tail = child.text.slice(offset);
|
|
148
|
+
if (tail.trim()) display.addChild(new Markdown(tail, child.paddingX, 0, child.theme, child.defaultTextStyle, child.options));
|
|
149
|
+
card.displays.set(child, display);
|
|
150
|
+
}
|
|
151
|
+
const container = this.contentContainer, original = container.children;
|
|
152
|
+
for (const pane of card.panes.values()) pane.theme = uiTheme;
|
|
153
|
+
for (const [native, display] of card.displays) for (const child of display.children) if (child instanceof Markdown) {
|
|
154
|
+
const padding = Math.min(native.paddingX, Math.max(0, Math.floor((width - 1) / 2)));
|
|
155
|
+
if ((child as any).paddingX !== padding) { (child as any).paddingX = padding; child.invalidate(); }
|
|
156
|
+
}
|
|
157
|
+
container.children = original.map((child: any) => card!.displays.get(child) || child);
|
|
158
|
+
try { return nativeRender.call(this, width); }
|
|
159
|
+
finally { container.children = original; }
|
|
160
|
+
};
|
|
161
|
+
const mouseWrapper = function(this: any, nativeMouse: (...args: any[]) => any, event: any) {
|
|
162
|
+
if (!disposed && active && mode.isEnabled() && supported(this)) return nativeMouse?.call(this, event);
|
|
163
|
+
// Do not dispatch stale temporary display children after a native fallback.
|
|
164
|
+
if (this.contentContainer) this.contentContainer.mouseLayout = undefined;
|
|
165
|
+
return nativeMouse?.call(this, event);
|
|
166
|
+
};
|
|
167
|
+
const detachRender = chainNativeMethod(proto, 'render', renderWrapper);
|
|
168
|
+
const detachMouse = chainNativeMethod(proto, 'handleMouse', mouseWrapper);
|
|
169
|
+
const reset = (_event: any, ctx: any) => {
|
|
170
|
+
clear(); if (disposed || ctx.mode !== 'tui') return;
|
|
171
|
+
active = true;
|
|
172
|
+
uiTheme = ctx.ui.theme;
|
|
173
|
+
redraw = typeof ctx.ui.setHiddenThinkingLabel === 'function' ? () => ctx.ui.setHiddenThinkingLabel() : undefined;
|
|
174
|
+
input = ctx.ui.onTerminalInput?.((data: string) => {
|
|
175
|
+
if (!selected || !mode.isEnabled()) { release(); return; }
|
|
176
|
+
if (matchesKey(data, 'escape')) { release(); pi.events.emit('compact-renderer:inspection-ended:v1', {}); redraw?.(); return { consume: true }; }
|
|
177
|
+
if (selected.handle(data)) { redraw?.(); return { consume: true }; }
|
|
178
|
+
release(); pi.events.emit('compact-renderer:inspection-ended:v1', {}); redraw?.();
|
|
179
|
+
});
|
|
180
|
+
redraw?.();
|
|
181
|
+
};
|
|
182
|
+
const subscriptions: (() => void)[] = [];
|
|
183
|
+
for (const event of ['session_start', 'session_tree', 'session_compact'] as const) subscriptions.push(pi.on(event, reset));
|
|
184
|
+
subscriptions.push(pi.on('session_before_switch', clear), pi.on('session_shutdown', clear), pi.on('ui_prompt_start', release));
|
|
185
|
+
subscriptions.push(pi.events.on('compact-renderer:focus:v1', (event: any) => { if (event?.owner !== 'workflows') release(); }));
|
|
186
|
+
subscriptions.push(pi.events.on('compact-renderer:disclosures:v1', (request: any) => {
|
|
187
|
+
if (disposed || !active || !mode.isEnabled()) return;
|
|
188
|
+
for (const card of cards.values()) for (const pane of card.panes.values()) request?.add?.((component: any) => component === card.component, pane.open, () => {
|
|
189
|
+
if (selected === pane) release();
|
|
190
|
+
pane.collapse();
|
|
191
|
+
});
|
|
192
|
+
}));
|
|
193
|
+
subscriptions.push(pi.events.on('compact-renderer:inspect:v1', (request: any) => {
|
|
194
|
+
if (disposed || !active || !mode.isEnabled()) return;
|
|
195
|
+
for (const card of cards.values()) card.panes.forEach((pane, index) => request?.add?.({ id: `workflow-${card.id}-${index}`, kind: 'Workflow', label: pane.summary, focus() {
|
|
196
|
+
if (disposed || !active || !mode.isEnabled() || cards.get(card.component) !== card || !supported(card.component)) return;
|
|
197
|
+
release(); selected = pane; pane.focused = true; pane.open = true; redraw?.();
|
|
198
|
+
pi.events.emit('compact-renderer:focus:v1', { owner: 'workflows', label: 'Subagent workflow', target: (component: any) => component === card.component });
|
|
199
|
+
} }));
|
|
200
|
+
}));
|
|
201
|
+
subscriptions.push(mode.onChange(() => { release(); redraw?.(); }));
|
|
202
|
+
const dispose = () => {
|
|
203
|
+
if (disposed) return; disposed = true; clear(); subscriptions.forEach(off => off?.());
|
|
204
|
+
detachMouse(); detachRender();
|
|
205
|
+
if (shared[owner] === dispose) delete shared[owner];
|
|
206
|
+
};
|
|
207
|
+
shared[owner] = dispose;
|
|
208
|
+
return dispose;
|
|
209
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const link = Symbol.for('compact-renderer:previous-native-method:v1');
|
|
2
|
+
type Method = (this: any, ...args: any[]) => any;
|
|
3
|
+
type Link = { previous: Method; descriptor?: PropertyDescriptor };
|
|
4
|
+
|
|
5
|
+
/** Cooperating native adapters can detach in either order, including when a
|
|
6
|
+
* session reset replaces a wrapper underneath another active adapter. */
|
|
7
|
+
export function chainNativeMethod(proto: any, key: string, around: (this: any, previous: Method, ...args: any[]) => any): () => void {
|
|
8
|
+
const previousLink = proto[key]?.[link] as Link | undefined;
|
|
9
|
+
const descriptor = previousLink ? previousLink.descriptor : Object.getOwnPropertyDescriptor(proto, key);
|
|
10
|
+
const state: Link = { previous: proto[key], descriptor };
|
|
11
|
+
let disposed = false;
|
|
12
|
+
const wrapped: Method = function(...args) { return disposed ? state.previous?.apply(this, args) : around.call(this, state.previous, ...args); };
|
|
13
|
+
Object.defineProperty(wrapped, link, { value: state });
|
|
14
|
+
proto[key] = wrapped;
|
|
15
|
+
return () => {
|
|
16
|
+
if (disposed) return; disposed = true;
|
|
17
|
+
if (proto[key] === wrapped) {
|
|
18
|
+
if (!descriptor && state.previous === Object.getPrototypeOf(proto)?.[key]) delete proto[key];
|
|
19
|
+
else Object.defineProperty(proto, key, { ...(descriptor || { configurable: true, writable: true }), value: state.previous });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
let method = proto[key]; const seen = new Set<Method>();
|
|
23
|
+
while (typeof method === 'function' && !seen.has(method)) {
|
|
24
|
+
seen.add(method);
|
|
25
|
+
const parent = (method as any)[link] as Link | undefined;
|
|
26
|
+
if (!parent) return;
|
|
27
|
+
if (parent.previous === wrapped) { parent.previous = state.previous; return; }
|
|
28
|
+
method = parent.previous;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { getKeybindings, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from '@earendil-works/pi-tui';
|
|
2
|
+
import type { DisplayMode } from './display-mode.ts';
|
|
3
|
+
import { cardContentWidth, cardRow } from './display-card.ts';
|
|
4
|
+
|
|
5
|
+
/** Shared with approval owners. This channel carries presentation, never policy. */
|
|
6
|
+
export const PERMISSION_PRESENTATION_EVENT = 'pi:permission-presentation:v1';
|
|
7
|
+
export interface PermissionPresentationRequest {
|
|
8
|
+
version: 1;
|
|
9
|
+
action: string;
|
|
10
|
+
target: string;
|
|
11
|
+
reason: string;
|
|
12
|
+
/** Complete caller-provided input, including its existing redaction. */
|
|
13
|
+
details: string;
|
|
14
|
+
ui: { custom: (factory: (...args: any[]) => Component) => Promise<unknown> };
|
|
15
|
+
mode: 'tui';
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
/** Only the first synchronous offer wins; offering must not open a dialog. */
|
|
18
|
+
offer(present: () => Promise<boolean>): boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// JSON details already escape input controls. Escape any actual terminal controls
|
|
22
|
+
// in labels or future callers, so untrusted text cannot inject terminal commands.
|
|
23
|
+
const safe = (text: string) => text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g,
|
|
24
|
+
value => `\\u${value.charCodeAt(0).toString(16).padStart(4, '0')}`).replace(/\t/g, ' ');
|
|
25
|
+
|
|
26
|
+
type Cursor = { offset: number; fragment: number };
|
|
27
|
+
/** An offset viewport, not an eagerly wrapped document. Chunk segmentation and
|
|
28
|
+
* painting depend on viewport size. Full arguments remain reachable by paging. */
|
|
29
|
+
export class PermissionDetailsViewport {
|
|
30
|
+
readonly length: number;
|
|
31
|
+
workUnits = 0;
|
|
32
|
+
private cursor: Cursor = { offset: 0, fragment: 0 };
|
|
33
|
+
private next: Cursor = this.cursor;
|
|
34
|
+
private previous: Array<{ cursor: Cursor; next: Cursor; width: number; height: number }> = [];
|
|
35
|
+
private layout = { width: 80, height: 8 };
|
|
36
|
+
private tokens = new Map<number, string>();
|
|
37
|
+
private cached?: { key: string; rows: string[] };
|
|
38
|
+
private readonly segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
|
39
|
+
constructor(private parts: string[]) { this.length = parts.reduce((sum, part) => sum + part.length, 0); }
|
|
40
|
+
private slice(start: number, length: number) {
|
|
41
|
+
let result = '';
|
|
42
|
+
for (const part of this.parts) {
|
|
43
|
+
if (start >= part.length) { start -= part.length; continue; }
|
|
44
|
+
const piece = part.slice(start, start + length - result.length);
|
|
45
|
+
result += piece;
|
|
46
|
+
start = 0;
|
|
47
|
+
if (result.length >= length) break;
|
|
48
|
+
}
|
|
49
|
+
this.workUnits += result.length;
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
private token(offset: number) {
|
|
53
|
+
if (!this.tokens.has(offset)) {
|
|
54
|
+
let chunk = this.slice(offset, 256);
|
|
55
|
+
if (/[\uD800-\uDBFF]$/.test(chunk) && offset + chunk.length < this.length) chunk = chunk.slice(0, -1);
|
|
56
|
+
this.tokens.clear();
|
|
57
|
+
for (const item of this.segmenter.segment(chunk)) {
|
|
58
|
+
if (item.segment === '\r\n') {
|
|
59
|
+
this.tokens.set(offset + item.index, '\r'); this.tokens.set(offset + item.index + 1, '\n');
|
|
60
|
+
} else this.tokens.set(offset + item.index, item.segment);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return this.tokens.get(offset) ?? '';
|
|
64
|
+
}
|
|
65
|
+
render(width: number, height: number) {
|
|
66
|
+
width = Math.max(1, width); height = Math.max(1, height);
|
|
67
|
+
this.layout = { width, height };
|
|
68
|
+
const key = `${width}/${height}/${this.cursor.offset}/${this.cursor.fragment}`;
|
|
69
|
+
if (this.cached?.key === key) return this.cached.rows;
|
|
70
|
+
const cursor = { ...this.cursor }, rows: string[] = [];
|
|
71
|
+
let line = '', columns = 0, consumed = 0;
|
|
72
|
+
const budget = Math.max(256, Math.min(8192, width * height * 4));
|
|
73
|
+
while (cursor.offset < this.length && rows.length < height && consumed < budget) {
|
|
74
|
+
const token = this.token(cursor.offset);
|
|
75
|
+
if (!token) break;
|
|
76
|
+
if (token === '\n') {
|
|
77
|
+
rows.push(line); line = ''; columns = 0; cursor.offset++; consumed++; continue;
|
|
78
|
+
}
|
|
79
|
+
const escaped = safe(token), text = escaped.slice(cursor.fragment), size = visibleWidth(text);
|
|
80
|
+
if (size > width && escaped !== token) {
|
|
81
|
+
const piece = text.slice(0, width - columns);
|
|
82
|
+
line += piece; columns += piece.length; cursor.fragment += piece.length;
|
|
83
|
+
if (cursor.fragment === escaped.length) { cursor.offset += token.length; consumed += token.length; cursor.fragment = 0; }
|
|
84
|
+
} else {
|
|
85
|
+
if (size > width - columns && columns > 0) { rows.push(line); line = ''; columns = 0; continue; }
|
|
86
|
+
// A one-column terminal cannot paint a two-column glyph. Keep its exact
|
|
87
|
+
// source and use a visible marker; widening restores the recorded glyph.
|
|
88
|
+
line += size > width ? '…' : text;
|
|
89
|
+
columns += Math.min(size, width); cursor.offset += token.length; consumed += token.length; cursor.fragment = 0;
|
|
90
|
+
}
|
|
91
|
+
if (columns >= width) {
|
|
92
|
+
rows.push(line); line = ''; columns = 0;
|
|
93
|
+
if (cursor.offset < this.length && this.token(cursor.offset) === '\n') { cursor.offset++; consumed++; }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (line || !rows.length) rows.push(line);
|
|
97
|
+
this.next = cursor;
|
|
98
|
+
this.cached = { key, rows };
|
|
99
|
+
return rows;
|
|
100
|
+
}
|
|
101
|
+
get range() { return { start: this.cursor.offset, end: this.next.offset, total: this.length }; }
|
|
102
|
+
pageDown() {
|
|
103
|
+
if (this.next.offset >= this.length || this.next.offset === this.cursor.offset && this.next.fragment === this.cursor.fragment) return;
|
|
104
|
+
this.previous.push({ cursor: { ...this.cursor }, next: { ...this.next }, ...this.layout }); this.cursor = { ...this.next };
|
|
105
|
+
}
|
|
106
|
+
pageUp() {
|
|
107
|
+
const previous = this.previous.at(-1);
|
|
108
|
+
if (previous && previous.width === this.layout.width && previous.height === this.layout.height
|
|
109
|
+
&& previous.next.offset === this.cursor.offset && previous.next.fragment === this.cursor.fragment) {
|
|
110
|
+
this.cursor = this.previous.pop()!.cursor;
|
|
111
|
+
} else {
|
|
112
|
+
this.previous = [];
|
|
113
|
+
this.cursor = this.seekBackward(this.cursor, this.layout.width, this.layout.height);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
home() { this.cursor = { offset: 0, fragment: 0 }; this.previous = []; }
|
|
117
|
+
private seekBackward(from: Cursor, width: number, height: number): Cursor {
|
|
118
|
+
let offset = from.offset, fragment = 0, rows = 1, columns = 0, scanned = 0;
|
|
119
|
+
if (from.fragment) {
|
|
120
|
+
if (from.fragment >= width * height) return { offset, fragment: from.fragment - width * height };
|
|
121
|
+
rows = Math.floor((from.fragment - 1) / width) + 1;
|
|
122
|
+
columns = (from.fragment - 1) % width + 1;
|
|
123
|
+
} else if (offset > 0 && this.slice(offset - 1, 1) === '\n') {
|
|
124
|
+
// The newline terminates the preceding row; it is not an empty row at
|
|
125
|
+
// the beginning of the current viewport.
|
|
126
|
+
offset--; scanned++;
|
|
127
|
+
}
|
|
128
|
+
const budget = Math.max(256, Math.min(8192, width * height * 4));
|
|
129
|
+
while (offset > 0 && scanned < budget) {
|
|
130
|
+
const tail = this.slice(Math.max(0, offset - 2), Math.min(2, offset));
|
|
131
|
+
const chars = [...tail], char = chars.at(-1)!;
|
|
132
|
+
scanned += char.length;
|
|
133
|
+
if (char === '\n') { if (rows >= height) break; rows++; columns = 0; }
|
|
134
|
+
else {
|
|
135
|
+
const size = Math.max(0, visibleWidth(safe(char)));
|
|
136
|
+
if (size > width && safe(char) !== char) {
|
|
137
|
+
const addedRows = Math.floor((columns + size - 1) / width);
|
|
138
|
+
if (rows + addedRows > height) {
|
|
139
|
+
fragment = size - ((height - rows + 1) * width - columns);
|
|
140
|
+
offset -= char.length;
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
rows += addedRows; columns = (columns + size - 1) % width + 1;
|
|
144
|
+
}
|
|
145
|
+
else if (columns + size > width) { if (rows >= height) break; rows++; columns = Math.min(size, width); }
|
|
146
|
+
else columns += size;
|
|
147
|
+
}
|
|
148
|
+
offset -= char.length;
|
|
149
|
+
}
|
|
150
|
+
return { offset, fragment };
|
|
151
|
+
}
|
|
152
|
+
end(width: number, height: number) {
|
|
153
|
+
this.layout = { width: Math.max(1, width), height: Math.max(1, height) };
|
|
154
|
+
this.previous = [];
|
|
155
|
+
this.cursor = this.seekBackward({ offset: this.length, fragment: 0 }, this.layout.width, this.layout.height);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export class PermissionDialog implements Component {
|
|
160
|
+
private selected = 1; // Explicit denial is the safe default for Enter.
|
|
161
|
+
private detailsOpen = false;
|
|
162
|
+
readonly detailsViewport: PermissionDetailsViewport;
|
|
163
|
+
private width = 80;
|
|
164
|
+
private settled = false;
|
|
165
|
+
private pageSize = 8;
|
|
166
|
+
constructor(private request: Pick<PermissionPresentationRequest, 'action' | 'target' | 'reason' | 'details'>,
|
|
167
|
+
private theme: any, private redraw: () => void, private done: (allow: boolean) => void,
|
|
168
|
+
private availableRows: () => number = () => 24) {
|
|
169
|
+
this.detailsViewport = new PermissionDetailsViewport([request.details, '\n\nFull action:\n', request.action,
|
|
170
|
+
'\n\nFull target:\n', request.target, '\n\nFull reason:\n', request.reason]);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
finish(allow: boolean) {
|
|
174
|
+
if (this.settled) return;
|
|
175
|
+
this.settled = true;
|
|
176
|
+
this.done(allow);
|
|
177
|
+
}
|
|
178
|
+
dispose() { this.finish(false); }
|
|
179
|
+
invalidate() {}
|
|
180
|
+
render(width: number) {
|
|
181
|
+
width = Math.max(1, Math.floor(width));
|
|
182
|
+
const outerWidth = width;
|
|
183
|
+
width = cardContentWidth(width);
|
|
184
|
+
this.width = width;
|
|
185
|
+
const fg = (color: string, value: string) => this.theme.fg(color, value);
|
|
186
|
+
const lines = (value: string) => wrapTextWithAnsi(safe(value), width).map(row => truncateToWidth(row, width, ''));
|
|
187
|
+
let shortened = false;
|
|
188
|
+
const field = (label: string, value: string) => {
|
|
189
|
+
const limit = Math.min(256, width * 2);
|
|
190
|
+
const wrapped = lines(`${label}: ${value.slice(0, limit)}`);
|
|
191
|
+
const cut = value.length > limit || wrapped.length > 2;
|
|
192
|
+
shortened ||= cut;
|
|
193
|
+
const result = wrapped.slice(0, 2);
|
|
194
|
+
if (cut) result[result.length - 1] = truncateToWidth(result.at(-1)!, Math.max(0, width - 1), '') + '…';
|
|
195
|
+
return result;
|
|
196
|
+
};
|
|
197
|
+
const rows = [fg('accent', truncateToWidth('Approval required', width)),
|
|
198
|
+
...field('Action', this.request.action), ...field('Target', this.request.target), ...field('Reason', this.request.reason)];
|
|
199
|
+
let selectedRow = -1;
|
|
200
|
+
if (shortened) rows.push(...lines('Summary shortened; full text in Details.'));
|
|
201
|
+
for (const [index, title] of ['Allow once', 'Deny', `${this.detailsOpen ? 'Hide' : 'Show'} Details`].entries()) {
|
|
202
|
+
if (index === this.selected) selectedRow = rows.length;
|
|
203
|
+
const label = truncateToWidth(`${index === this.selected ? '→' : ' '} ${title}`, width, '');
|
|
204
|
+
rows.push(fg(index === this.selected ? 'accent' : 'text', index === this.selected && this.theme.bold ? this.theme.bold(label) : label));
|
|
205
|
+
}
|
|
206
|
+
const hints = lines('↑↓ choose · Enter select · Esc deny · d Details');
|
|
207
|
+
if (this.detailsOpen) hints.push(...lines('←/→ page Details · Home/End'));
|
|
208
|
+
this.pageSize = Math.max(1, Math.min(8, this.availableRows() - rows.length - hints.length - 1));
|
|
209
|
+
if (this.detailsOpen) {
|
|
210
|
+
const body = this.detailsViewport.render(width, this.pageSize);
|
|
211
|
+
const range = this.detailsViewport.range;
|
|
212
|
+
rows.push(fg('muted', truncateToWidth(`Details · text offset ${range.start}–${range.end}/${range.total}`, width)), ...body);
|
|
213
|
+
}
|
|
214
|
+
rows.push(...hints);
|
|
215
|
+
return rows.map((row, index) => cardRow(fg('text', row), outerWidth, this.theme, index === selectedRow ? 'selectedBg' : 'toolPendingBg'));
|
|
216
|
+
}
|
|
217
|
+
handleInput(data: string) {
|
|
218
|
+
if (this.settled) return;
|
|
219
|
+
const kb = getKeybindings();
|
|
220
|
+
if (kb.matches(data, 'tui.select.cancel') || matchesKey(data, 'ctrl+c')) { this.finish(false); return; }
|
|
221
|
+
if (data === 'd') this.detailsOpen = !this.detailsOpen;
|
|
222
|
+
else if (kb.matches(data, 'tui.select.up') || data === 'k') this.selected = Math.max(0, this.selected - 1);
|
|
223
|
+
else if (kb.matches(data, 'tui.select.down') || data === 'j') this.selected = Math.min(2, this.selected + 1);
|
|
224
|
+
else if (kb.matches(data, 'tui.select.confirm') || data === '\n') {
|
|
225
|
+
if (this.selected === 2) this.detailsOpen = !this.detailsOpen;
|
|
226
|
+
else { this.finish(this.selected === 0); return; }
|
|
227
|
+
// Fullscreen Pi consumes PgUp/PgDn in its first input listener, before any
|
|
228
|
+
// extension listener or custom component. Plain arrows reach this dialog.
|
|
229
|
+
} else if (this.detailsOpen && (matchesKey(data, 'left') || matchesKey(data, 'pageup'))) this.detailsViewport.pageUp();
|
|
230
|
+
else if (this.detailsOpen && (matchesKey(data, 'right') || matchesKey(data, 'pagedown'))) this.detailsViewport.pageDown();
|
|
231
|
+
else if (this.detailsOpen && matchesKey(data, 'home')) this.detailsViewport.home();
|
|
232
|
+
else if (this.detailsOpen && matchesKey(data, 'end')) this.detailsViewport.end(this.width, this.pageSize);
|
|
233
|
+
else return;
|
|
234
|
+
this.redraw();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function compatible(value: any): value is PermissionPresentationRequest {
|
|
239
|
+
return value?.version === 1 && value.mode === 'tui' && ['action', 'target', 'reason', 'details'].every(key => typeof value[key] === 'string')
|
|
240
|
+
&& typeof value.offer === 'function' && typeof value.ui?.custom === 'function'
|
|
241
|
+
&& (!value.signal || (typeof value.signal.addEventListener === 'function' && typeof value.signal.removeEventListener === 'function'));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function registerPermissionPresentation(pi: any, mode: DisplayMode): () => void {
|
|
245
|
+
if (typeof pi.events?.on !== 'function') return () => {};
|
|
246
|
+
let disposed = false;
|
|
247
|
+
const active = new Set<() => void>();
|
|
248
|
+
const cancelAll = () => { for (const cancel of [...active]) cancel(); };
|
|
249
|
+
const unsubscribe = pi.events.on(PERMISSION_PRESENTATION_EVENT, (request: unknown) => {
|
|
250
|
+
if (disposed || !mode.isEnabled() || !compatible(request)) return;
|
|
251
|
+
request.offer(async () => {
|
|
252
|
+
if (disposed || !mode.isEnabled() || request.signal?.aborted) return false;
|
|
253
|
+
let dialog: PermissionDialog | undefined;
|
|
254
|
+
let cancelled = false;
|
|
255
|
+
const cancel = () => { cancelled = true; dialog?.finish(false); };
|
|
256
|
+
active.add(cancel);
|
|
257
|
+
request.signal?.addEventListener('abort', cancel, { once: true });
|
|
258
|
+
try {
|
|
259
|
+
const result = await request.ui.custom((tui, theme, _keys, done) => {
|
|
260
|
+
dialog = new PermissionDialog(request, theme, () => tui.requestRender(), done, () => tui.terminal?.rows ?? 24);
|
|
261
|
+
if (cancelled || request.signal?.aborted || disposed || !mode.isEnabled()) dialog.finish(false);
|
|
262
|
+
return dialog;
|
|
263
|
+
});
|
|
264
|
+
return result === true && !cancelled && !request.signal?.aborted && !disposed;
|
|
265
|
+
} finally {
|
|
266
|
+
active.delete(cancel);
|
|
267
|
+
request.signal?.removeEventListener('abort', cancel);
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
const unsubscribeMode = mode.onChange(() => { if (!mode.isEnabled()) cancelAll(); });
|
|
272
|
+
for (const event of ['session_switch', 'session_tree', 'session_compact', 'session_shutdown']) pi.on?.(event, cancelAll);
|
|
273
|
+
return () => {
|
|
274
|
+
if (disposed) return;
|
|
275
|
+
disposed = true;
|
|
276
|
+
unsubscribe?.();
|
|
277
|
+
unsubscribeMode();
|
|
278
|
+
cancelAll();
|
|
279
|
+
};
|
|
280
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Remove only a complete repeated opening line from the compact presentation.
|
|
2
|
+
* Recorded sources remain untouched; clipped summaries and sole content stay intact. */
|
|
3
|
+
export function suppressRepeatedSummary(source: string, summary: string): string {
|
|
4
|
+
if (!summary || summary.endsWith("…")) return source;
|
|
5
|
+
const opening = /^(?:[ \t]*\r?\n)*([^\r\n]+)\r?\n/.exec(source.slice(0, 1024));
|
|
6
|
+
if (!opening) return source;
|
|
7
|
+
const title = opening[1].replace(/^ {0,3}#{1,6}[ \t]+/, "").replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_match, bold, underlined) => bold || underlined).replace(/`([^`]+)`/g, "$1").trim();
|
|
8
|
+
if (title !== summary) return source;
|
|
9
|
+
const probe = source.slice(opening[0].length, opening[0].length + 1024);
|
|
10
|
+
if (!/\S/.test(probe)) return source;
|
|
11
|
+
const gap = /^(?:[ \t]*\r?\n)+/.exec(probe)?.[0].length || 0;
|
|
12
|
+
return source.slice(opening[0].length + gap);
|
|
13
|
+
}
|