@saifymatteo/pi-cell-actions 0.0.0-stage → 0.1.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 +10 -0
- package/LICENSE +661 -0
- package/NOTICE.md +3 -0
- package/README.md +44 -2
- package/package.json +36 -4
- package/src/cells.ts +163 -0
- package/src/index.ts +479 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cell actions: hover a block of a message (paragraph, list, heading, code block,
|
|
3
|
+
* table) or a tool call in the fullscreen transcript for a ⋯ badge; click it for a menu that
|
|
4
|
+
* copies the cell (tables as Markdown, TSV or CSV; tools as input or output) and
|
|
5
|
+
* runs shell code blocks after a confirmation.
|
|
6
|
+
*
|
|
7
|
+
* Works on stock Pi and Pi-Bolt through APIs both share:
|
|
8
|
+
* - hover: the three transcript component prototypes get a `handleMouse` wrapper
|
|
9
|
+
* that only observes events (location and bounds), never handles them;
|
|
10
|
+
* - drawing: one non-capturing overlay, so no renderer or render cache is patched;
|
|
11
|
+
* - the overlay counts as "visible" only between mouse events, so selection,
|
|
12
|
+
* scrollbars and wheel routing (which check `hasOverlay()`) behave as without it.
|
|
13
|
+
* Regular (non-fullscreen) mode has no mouse events, so nothing shows there.
|
|
14
|
+
*/
|
|
15
|
+
import {
|
|
16
|
+
AssistantMessageComponent,
|
|
17
|
+
copyToClipboard,
|
|
18
|
+
ToolExecutionComponent,
|
|
19
|
+
UserMessageComponent,
|
|
20
|
+
type ExtensionAPI,
|
|
21
|
+
type ExtensionContext,
|
|
22
|
+
} from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import {
|
|
24
|
+
isViewportTUI,
|
|
25
|
+
matchesKey,
|
|
26
|
+
stripTerminalSequences,
|
|
27
|
+
Text,
|
|
28
|
+
truncateToWidth,
|
|
29
|
+
visibleWidth,
|
|
30
|
+
type Component,
|
|
31
|
+
type OverlayHandle,
|
|
32
|
+
type OverlayOptions,
|
|
33
|
+
type TUI,
|
|
34
|
+
type TuiMouseEvent,
|
|
35
|
+
} from "@earendil-works/pi-tui";
|
|
36
|
+
import { locateBlocks, parseBlocks, RUNNABLE, toCsv, toTsv, type LocatedBlock } from "./cells.ts";
|
|
37
|
+
|
|
38
|
+
type Theme = {
|
|
39
|
+
fg(color: string, text: string): string;
|
|
40
|
+
bg(color: string, text: string): string;
|
|
41
|
+
bold(text: string): string;
|
|
42
|
+
inverse(text: string): string;
|
|
43
|
+
};
|
|
44
|
+
type Action = { label: string; run: () => void | Promise<void>; primary?: boolean };
|
|
45
|
+
/** A hovered cell: its first screen row and its columns left..right-1. */
|
|
46
|
+
type Cell = { key: string; name: string; top: number; left: number; right: number; actions: () => Action[] };
|
|
47
|
+
type ToolLike = { toolCallId?: string; toolName?: string; args?: unknown; result?: { content?: unknown } };
|
|
48
|
+
type MouseHandler = (this: Component, event: TuiMouseEvent) => unknown;
|
|
49
|
+
type RawMouse = { button: number; x: number; y: number; release: boolean };
|
|
50
|
+
type LayoutBox = { clip: { y: number; height: number }; scrollView?: unknown; children: LayoutBox[] };
|
|
51
|
+
type MouseTui = TUI & {
|
|
52
|
+
handleMouseEvent?(raw: RawMouse): void;
|
|
53
|
+
routeWheel?(...args: unknown[]): unknown;
|
|
54
|
+
currentLayout?: { root: LayoutBox };
|
|
55
|
+
getPrimaryScrollView?(): unknown;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const RUN_TYPE = "cell-run";
|
|
59
|
+
const PATCHED = Symbol.for("pi-cell-actions.handleMouse");
|
|
60
|
+
/** Set by pi-compact-tools: the toolCallIds a group card draws, keyed by its head call. */
|
|
61
|
+
const TOOL_GROUP = Symbol.for("pi-cell-actions.toolGroup");
|
|
62
|
+
/** Set here, called by pi-compact-tools: which call of a group card the pointer is on. */
|
|
63
|
+
const TOOL_HOVER = Symbol.for("pi-cell-actions.toolHover");
|
|
64
|
+
type ToolHover = { head: string; id?: string; top?: number; height?: number };
|
|
65
|
+
const COPIED_MS = 1500;
|
|
66
|
+
const RUN_TIMEOUT_MS = 120_000;
|
|
67
|
+
|
|
68
|
+
const textOf = (content: unknown): string =>
|
|
69
|
+
typeof content === "string" ? content
|
|
70
|
+
: Array.isArray(content) ? content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n") : "";
|
|
71
|
+
|
|
72
|
+
export default function (pi: ExtensionAPI) {
|
|
73
|
+
let ctx: ExtensionContext | undefined;
|
|
74
|
+
let tui: MouseTui | undefined;
|
|
75
|
+
let theme: Theme | undefined;
|
|
76
|
+
let handle: OverlayHandle | undefined;
|
|
77
|
+
let hovered: Cell | undefined;
|
|
78
|
+
let open = false;
|
|
79
|
+
let copied: string | undefined;
|
|
80
|
+
/** The button under the pointer: drawn as yellow text without its box, to show it is clickable. */
|
|
81
|
+
let pressable: string | undefined;
|
|
82
|
+
let copiedTimer: ReturnType<typeof setTimeout> | undefined;
|
|
83
|
+
// True while Pi handles a mouse event outside our overlay: hasOverlay() is then false.
|
|
84
|
+
let suppressed = false;
|
|
85
|
+
let sawCell = false;
|
|
86
|
+
let toolHover: ToolHover | undefined;
|
|
87
|
+
const restores: (() => void)[] = [];
|
|
88
|
+
const layoutCache = new WeakMap<object, { width: number; lines: string[]; text: string; blocks: LocatedBlock[] }>();
|
|
89
|
+
|
|
90
|
+
const options: OverlayOptions = { row: 0, col: 0, width: 3, nonCapturing: true, visible: () => !!hovered && !suppressed };
|
|
91
|
+
let buttons: { start: number; end: number; action: Action }[] = [];
|
|
92
|
+
|
|
93
|
+
function setHover(cell: Cell | undefined) {
|
|
94
|
+
if (cell?.key === hovered?.key && cell?.top === hovered?.top && cell?.right === hovered?.right) {
|
|
95
|
+
if (cell) hovered = cell;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
hovered = cell;
|
|
99
|
+
open = false;
|
|
100
|
+
pressable = undefined;
|
|
101
|
+
copied = undefined;
|
|
102
|
+
tui?.requestRender();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function flash(label: string) {
|
|
106
|
+
copied = label;
|
|
107
|
+
if (copiedTimer) clearTimeout(copiedTimer);
|
|
108
|
+
copiedTimer = setTimeout(() => {
|
|
109
|
+
copied = undefined;
|
|
110
|
+
place();
|
|
111
|
+
tui?.requestRender();
|
|
112
|
+
}, COPIED_MS);
|
|
113
|
+
place(); // "✓ copied" can be wider than the label it replaces
|
|
114
|
+
tui?.requestRender();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function copy(label: string, text: () => string): Action {
|
|
118
|
+
return {
|
|
119
|
+
label,
|
|
120
|
+
run: async () => {
|
|
121
|
+
try {
|
|
122
|
+
await copyToClipboard(text());
|
|
123
|
+
flash(label);
|
|
124
|
+
} catch (error) {
|
|
125
|
+
ctx?.ui.notify(`Copy failed: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function runBlock(lang: string, code: string) {
|
|
132
|
+
const shell = RUNNABLE[lang];
|
|
133
|
+
const context = ctx;
|
|
134
|
+
if (!shell || !context) return;
|
|
135
|
+
setHover(undefined);
|
|
136
|
+
if (!(await context.ui.confirm(`Run this ${lang} block?`, code))) return;
|
|
137
|
+
const result = await pi.exec(shell, ["-c", code], { cwd: context.cwd, timeout: RUN_TIMEOUT_MS }).catch((error: unknown) => ({
|
|
138
|
+
stdout: "", stderr: error instanceof Error ? error.message : String(error), code: -1, killed: false,
|
|
139
|
+
}));
|
|
140
|
+
const output = [result.stdout, result.stderr].filter((s) => s.trim()).join("\n").trimEnd();
|
|
141
|
+
const status = result.killed ? "timed out" : `exit ${result.code}`;
|
|
142
|
+
pi.sendMessage({
|
|
143
|
+
customType: RUN_TYPE,
|
|
144
|
+
content: `Ran a ${lang} block from the chat (${status}):\n$ ${code}\n\n${output || "(no output)"}`,
|
|
145
|
+
display: true,
|
|
146
|
+
details: { lang, code, output, status, failed: result.killed || result.code !== 0 },
|
|
147
|
+
}, { triggerTurn: false }); // never steer a running turn; the model sees it next turn
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function blockActions(block: LocatedBlock): Action[] {
|
|
151
|
+
if (block.kind === "text") return [{ ...copy("copy", () => block.markdown), primary: true }];
|
|
152
|
+
if (block.kind === "table") {
|
|
153
|
+
return [
|
|
154
|
+
{ ...copy("copy markdown", () => block.markdown), primary: true },
|
|
155
|
+
copy("copy TSV", () => toTsv(block.rows)),
|
|
156
|
+
copy("copy CSV", () => toCsv(block.rows)),
|
|
157
|
+
];
|
|
158
|
+
}
|
|
159
|
+
const actions: Action[] = [{ ...copy("copy", () => block.code), primary: true }];
|
|
160
|
+
if (RUNNABLE[block.lang]) actions.push({ label: "run", run: () => runBlock(block.lang, block.code) });
|
|
161
|
+
return actions;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Code blocks and tables of a message, with the rows they occupy. Cached per render. */
|
|
165
|
+
function blocksOf(component: Component, width: number, text: string): LocatedBlock[] {
|
|
166
|
+
// Pi-Bolt's render() returns a fresh copy each call, so compare by content, not identity.
|
|
167
|
+
const lines = component.render(width);
|
|
168
|
+
const cached = layoutCache.get(component);
|
|
169
|
+
if (cached && cached.width === width && cached.text === text && cached.lines.length === lines.length &&
|
|
170
|
+
cached.lines.every((line, i) => line === lines[i])) return cached.blocks;
|
|
171
|
+
const blocks = locateBlocks(lines.map((line) => stripTerminalSequences(line)), parseBlocks(text));
|
|
172
|
+
layoutCache.set(component, { width, lines, text, blocks });
|
|
173
|
+
return blocks;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The first non-blank row from `top`, so the badge sits on the cell's text, not its padding. */
|
|
177
|
+
function firstText(lines: string[], top: number): number {
|
|
178
|
+
let row = top;
|
|
179
|
+
while (row < lines.length - 1 && !stripTerminalSequences(lines[row] ?? "").trim()) row++;
|
|
180
|
+
return row;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The block under the pointer: a paragraph, list, heading, code block or table. */
|
|
184
|
+
function messageCell(component: Component, event: TuiMouseEvent, name: string, text: string): Cell | undefined {
|
|
185
|
+
const top = event.screenY - event.y;
|
|
186
|
+
const left = event.screenX - event.x;
|
|
187
|
+
const right = left + event.width;
|
|
188
|
+
const blocks = blocksOf(component, event.width, text);
|
|
189
|
+
const block = blocks.find((b) => event.y >= b.top && event.y <= b.bottom);
|
|
190
|
+
const lines = layoutCache.get(component)?.lines ?? [];
|
|
191
|
+
if (block) {
|
|
192
|
+
return { key: `${name}:${block.top}`, name: `${block.kind} cell`, top: top + firstText(lines, block.top), left, right, actions: () => blockActions(block) };
|
|
193
|
+
}
|
|
194
|
+
// Rows above the first block (padding, thinking) have no menu, unless no block
|
|
195
|
+
// could be located at all: then the whole message is one cell.
|
|
196
|
+
if (blocks.length) return undefined;
|
|
197
|
+
return { key: name, name: `${name} cell`, top: top + firstText(lines, 0), left, right, actions: () => [{ ...copy("copy", () => text), primary: true }] };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function toolCalls(component: ToolLike): { id?: string; name: string; input: unknown; output: string }[] {
|
|
201
|
+
const head = component.toolCallId;
|
|
202
|
+
const members = (globalThis as Record<symbol, ((id: string) => string[] | undefined) | undefined>)[TOOL_GROUP]?.(head ?? "") ?? [head];
|
|
203
|
+
const branch = (ctx?.sessionManager.getBranch() ?? []) as { type: string; message?: { role: string; content?: unknown; toolCallId?: string } }[];
|
|
204
|
+
const calls = new Map<string, { name: string; input: unknown }>();
|
|
205
|
+
const results = new Map<string, string>();
|
|
206
|
+
for (const entry of branch) {
|
|
207
|
+
const message = entry.type === "message" ? entry.message : undefined;
|
|
208
|
+
if (message?.role === "assistant" && Array.isArray(message.content)) {
|
|
209
|
+
for (const block of message.content) if (block?.type === "toolCall") calls.set(block.id, { name: block.name, input: block.arguments });
|
|
210
|
+
} else if (message?.role === "toolResult" && message.toolCallId) {
|
|
211
|
+
results.set(message.toolCallId, textOf(message.content));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return members.flatMap((id) => {
|
|
215
|
+
if (id === head) return [{ id, name: component.toolName ?? "tool", input: component.args, output: textOf(component.result?.content) }];
|
|
216
|
+
const call = id ? calls.get(id) : undefined;
|
|
217
|
+
return call ? [{ id, ...call, output: results.get(id!) ?? "" }] : [];
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* A tool card. On a pi-compact-tools group, the header row is the whole group,
|
|
223
|
+
* and an expanded call's rows are that call, with the group's copies after its own.
|
|
224
|
+
*/
|
|
225
|
+
function toolCell(component: ToolLike, event: TuiMouseEvent): Cell {
|
|
226
|
+
const top = event.screenY - event.y;
|
|
227
|
+
const left = event.screenX - event.x;
|
|
228
|
+
const right = left + event.width;
|
|
229
|
+
type Call = { id?: string; name: string; input: unknown; output: string };
|
|
230
|
+
const join = (pick: (call: Call) => string, only?: string) => () => {
|
|
231
|
+
const calls = toolCalls(component).filter((call) => !only || call.id === only);
|
|
232
|
+
return calls.length === 1 ? pick(calls[0]) : calls.map((call) => `# ${call.name}\n${pick(call)}`).join("\n\n");
|
|
233
|
+
};
|
|
234
|
+
const input = (call: Call) => JSON.stringify(call.input ?? {}, null, 2);
|
|
235
|
+
const output = (call: Call) => call.output;
|
|
236
|
+
const hover = toolHover?.head === component.toolCallId ? toolHover : undefined;
|
|
237
|
+
if (hover?.id && hover.top !== undefined) {
|
|
238
|
+
const id = hover.id;
|
|
239
|
+
return {
|
|
240
|
+
key: `tool:${component.toolCallId}:${id}`,
|
|
241
|
+
name: "tool call",
|
|
242
|
+
top: hover.top,
|
|
243
|
+
left,
|
|
244
|
+
right,
|
|
245
|
+
actions: () => [
|
|
246
|
+
copy("copy output", join(output, id)),
|
|
247
|
+
{ ...copy("copy input", join(input, id)), primary: true },
|
|
248
|
+
copy("all output", join(output)),
|
|
249
|
+
copy("all input", join(input)),
|
|
250
|
+
],
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
return {
|
|
254
|
+
key: `tool:${component.toolCallId}`,
|
|
255
|
+
name: toolCalls(component).length > 1 ? "tool group" : "tool call",
|
|
256
|
+
top: top + firstText((component as unknown as Component).render(event.width), 0),
|
|
257
|
+
left,
|
|
258
|
+
right,
|
|
259
|
+
actions: () => [copy("copy output", join(output)), { ...copy("copy input", join(input)), primary: true }],
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Observe (never handle) mouse events on one transcript component class. */
|
|
264
|
+
function observe(proto: { handleMouse?: MouseHandler } & Record<symbol, unknown>, cellAt: (component: any, event: TuiMouseEvent) => Cell | undefined) {
|
|
265
|
+
if (proto[PATCHED]) return;
|
|
266
|
+
const own = Object.hasOwn(proto, "handleMouse");
|
|
267
|
+
const original = proto.handleMouse;
|
|
268
|
+
let active = true;
|
|
269
|
+
const wrapper: MouseHandler = function (event) {
|
|
270
|
+
// Pi's handler first: a pi-compact-tools card reports the hovered call during it.
|
|
271
|
+
const result = original?.call(this, event);
|
|
272
|
+
if (active && (event.type === "move" || event.type === "press") && event.height > 0) {
|
|
273
|
+
try {
|
|
274
|
+
const cell = cellAt(this, event);
|
|
275
|
+
if (cell) {
|
|
276
|
+
sawCell = true;
|
|
277
|
+
setHover(cell);
|
|
278
|
+
}
|
|
279
|
+
} catch {
|
|
280
|
+
// Never break Pi's own mouse handling.
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return result;
|
|
284
|
+
};
|
|
285
|
+
proto.handleMouse = wrapper;
|
|
286
|
+
proto[PATCHED] = true;
|
|
287
|
+
restores.push(() => {
|
|
288
|
+
active = false; // stays in place, inert, if another extension wrapped it since
|
|
289
|
+
delete proto[PATCHED];
|
|
290
|
+
if (proto.handleMouse !== wrapper) return;
|
|
291
|
+
if (own) proto.handleMouse = original;
|
|
292
|
+
else delete proto.handleMouse;
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The badge, or the open menu's button row and cell label, right-aligned to the wider one. */
|
|
297
|
+
function menuLines(): string[] {
|
|
298
|
+
const t = theme;
|
|
299
|
+
buttons = [];
|
|
300
|
+
if (!t || !hovered) return [];
|
|
301
|
+
// Yellow boxes (inverted warning color): visible on any background, user messages included.
|
|
302
|
+
const yellow = (text: string, bold = false) => t.inverse(t.fg("warning", bold ? t.bold(text) : text));
|
|
303
|
+
if (!open) return [yellow(" ⋯ ", true)];
|
|
304
|
+
// A leading space separates the menu from whatever it covers (a table border, a rule).
|
|
305
|
+
let row = " ";
|
|
306
|
+
let col = 1;
|
|
307
|
+
for (const action of hovered.actions()) {
|
|
308
|
+
const label = ` ${copied === action.label ? "✓ copied" : action.label} `;
|
|
309
|
+
const w = visibleWidth(label);
|
|
310
|
+
buttons.push({ start: col, end: col + w, action });
|
|
311
|
+
row += (pressable === action.label ? t.fg("warning", t.bold(label)) : yellow(label, action.primary)) + " ";
|
|
312
|
+
col += w + 1;
|
|
313
|
+
}
|
|
314
|
+
const lines = [row + t.fg("dim", "esc "), t.fg("dim", ` ─ ${hovered.name} ─ `)];
|
|
315
|
+
// Shift here, not in render(): a mouse event between render and click rebuilds the buttons.
|
|
316
|
+
const width = Math.max(...lines.map((line) => visibleWidth(line)));
|
|
317
|
+
const shift = width - visibleWidth(lines[0]);
|
|
318
|
+
for (const button of buttons) { button.start += shift; button.end += shift; }
|
|
319
|
+
return lines.map((line) => " ".repeat(width - visibleWidth(line)) + line);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const overlay: Component = {
|
|
323
|
+
render(width: number): string[] {
|
|
324
|
+
// place() sized the box to the lines, so they fill it exactly.
|
|
325
|
+
return menuLines().map((line) => truncateToWidth(line, width, ""));
|
|
326
|
+
},
|
|
327
|
+
handleMouse(event: TuiMouseEvent) {
|
|
328
|
+
if (event.type === "move") {
|
|
329
|
+
// Hovering the badge opens the menu; hovering a button dims it. Pi doesn't redraw for moves, so ask.
|
|
330
|
+
const over = open && event.y === 0 ? buttons.find((b) => event.x >= b.start && event.x < b.end)?.action.label : undefined;
|
|
331
|
+
if (!open || over !== pressable) { open = true; pressable = over; place(); tui?.requestRender(); }
|
|
332
|
+
return { handled: true };
|
|
333
|
+
}
|
|
334
|
+
if (event.type !== "click" || event.button !== "left") return { handled: true, render: false };
|
|
335
|
+
if (!open) {
|
|
336
|
+
open = true;
|
|
337
|
+
place();
|
|
338
|
+
return { handled: true };
|
|
339
|
+
}
|
|
340
|
+
const hit = event.y === 0 ? buttons.find((b) => event.x >= b.start && event.x < b.end) : undefined;
|
|
341
|
+
if (hit) void hit.action.run();
|
|
342
|
+
else if (event.y === 0 && event.x >= (buttons.at(-1)?.end ?? 0)) open = false; // esc
|
|
343
|
+
place();
|
|
344
|
+
return { handled: true };
|
|
345
|
+
},
|
|
346
|
+
invalidate() {},
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
/** Overlay geometry follows the hovered cell; read by Pi on every render. */
|
|
350
|
+
function place() {
|
|
351
|
+
if (!hovered || !tui) return;
|
|
352
|
+
const width = Math.max(1, ...menuLines().map((line) => visibleWidth(line)));
|
|
353
|
+
options.width = width;
|
|
354
|
+
options.col = Math.max(hovered.left, hovered.right - width - 1);
|
|
355
|
+
// On the cell's first row; kept inside the transcript, off the editor.
|
|
356
|
+
const view = transcriptRows();
|
|
357
|
+
options.row = Math.max(view.top, Math.min(hovered.top, view.bottom - 1));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Screen rows of the scrolling transcript, so the menu never covers the editor or footer. */
|
|
361
|
+
function transcriptRows(): { top: number; bottom: number } {
|
|
362
|
+
const all = { top: 0, bottom: Number.MAX_SAFE_INTEGER };
|
|
363
|
+
const scrollView = tui?.getPrimaryScrollView?.();
|
|
364
|
+
const visit = (box: LayoutBox | undefined): LayoutBox | undefined =>
|
|
365
|
+
!box ? undefined : box.scrollView === scrollView ? box : box.children?.map(visit).find(Boolean);
|
|
366
|
+
const clip = scrollView ? visit(tui?.currentLayout?.root)?.clip : undefined;
|
|
367
|
+
return clip ? { top: clip.y, bottom: clip.y + clip.height - 1 } : all;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function attach(next: TUI) {
|
|
371
|
+
const target = next as MouseTui;
|
|
372
|
+
if (tui === target || !isViewportTUI(next) || typeof target.handleMouseEvent !== "function") return;
|
|
373
|
+
tui = target;
|
|
374
|
+
const handleMouseEvent = target.handleMouseEvent!;
|
|
375
|
+
const ownMouse = Object.hasOwn(target, "handleMouseEvent");
|
|
376
|
+
const ownWheel = Object.hasOwn(target, "routeWheel");
|
|
377
|
+
const mouseWrapper = function (this: MouseTui, raw: RawMouse) {
|
|
378
|
+
const motion = (raw.button & 32) !== 0;
|
|
379
|
+
const inside = (bounds?: { row: number; col: number; width: number; height: number }) =>
|
|
380
|
+
!!bounds && raw.y >= bounds.row && raw.y < bounds.row + bounds.height && raw.x >= bounds.col && raw.x < bounds.col + bounds.width;
|
|
381
|
+
const overOverlay = inside(handle?.getBounds?.());
|
|
382
|
+
if (!overOverlay) pressable = undefined;
|
|
383
|
+
suppressed = !overOverlay;
|
|
384
|
+
sawCell = false;
|
|
385
|
+
toolHover = undefined;
|
|
386
|
+
try {
|
|
387
|
+
return handleMouseEvent.call(this, raw);
|
|
388
|
+
} finally {
|
|
389
|
+
suppressed = false;
|
|
390
|
+
const moved = motion && (raw.button & 3) === 3; // pointer motion with no button held
|
|
391
|
+
if (moved && !overOverlay && !sawCell) setHover(undefined);
|
|
392
|
+
place();
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
target.handleMouseEvent = mouseWrapper;
|
|
396
|
+
restores.push(() => {
|
|
397
|
+
if (target.handleMouseEvent !== mouseWrapper) return;
|
|
398
|
+
if (ownMouse) target.handleMouseEvent = handleMouseEvent;
|
|
399
|
+
else delete (target as { handleMouseEvent?: unknown }).handleMouseEvent;
|
|
400
|
+
});
|
|
401
|
+
const routeWheel = target.routeWheel;
|
|
402
|
+
if (typeof routeWheel === "function") {
|
|
403
|
+
// Scrolling moves cells under a still pointer: drop the badge until the next move.
|
|
404
|
+
const wheelWrapper = function (this: MouseTui, ...args: unknown[]) {
|
|
405
|
+
setHover(undefined);
|
|
406
|
+
return routeWheel.apply(this, args);
|
|
407
|
+
};
|
|
408
|
+
target.routeWheel = wheelWrapper;
|
|
409
|
+
restores.push(() => {
|
|
410
|
+
if (target.routeWheel !== wheelWrapper) return;
|
|
411
|
+
if (ownWheel) target.routeWheel = routeWheel;
|
|
412
|
+
else delete (target as { routeWheel?: unknown }).routeWheel;
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
handle = next.showOverlay(overlay, options);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function detach() {
|
|
419
|
+
if (copiedTimer) clearTimeout(copiedTimer);
|
|
420
|
+
handle?.hide();
|
|
421
|
+
handle = undefined;
|
|
422
|
+
hovered = undefined;
|
|
423
|
+
tui = undefined;
|
|
424
|
+
for (const restore of restores.splice(0).reverse()) restore();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
pi.registerMessageRenderer(RUN_TYPE, (message, { expanded }, t) => {
|
|
428
|
+
const details = message.details as { lang?: string; code?: string; output?: string; status?: string; failed?: boolean } | undefined;
|
|
429
|
+
const lines = (details?.output || "(no output)").split("\n");
|
|
430
|
+
const shown = expanded ? lines : lines.slice(-12);
|
|
431
|
+
const header = t.fg(details?.failed ? "error" : "success", t.bold("▶ ran")) + t.fg("dim", ` ${details?.lang ?? ""} block · ${details?.status ?? ""}`);
|
|
432
|
+
const command = (details?.code ?? "").split("\n").map((line) => t.fg("bashMode", `$ ${line}`)).join("\n");
|
|
433
|
+
const more = shown.length < lines.length ? `\n${t.fg("dim", `… ${lines.length - shown.length} earlier lines (Ctrl+O to expand)`)}` : "";
|
|
434
|
+
return new Text(`${header}\n${command}\n${t.fg("toolOutput", shown.join("\n"))}${more}`, 1, 1);
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
pi.on("session_start", (_event, context) => {
|
|
438
|
+
ctx = context;
|
|
439
|
+
if (context.mode !== "tui") return;
|
|
440
|
+
observe(UserMessageComponent.prototype as never, (component: { text?: string }, event) =>
|
|
441
|
+
typeof component.text === "string" ? messageCell(component as never, event, "user", component.text) : undefined);
|
|
442
|
+
observe(AssistantMessageComponent.prototype as never, (component: { lastMessage?: { content?: unknown } }, event) => {
|
|
443
|
+
const content = component.lastMessage?.content;
|
|
444
|
+
const text = Array.isArray(content)
|
|
445
|
+
? content.filter((c) => c?.type === "text" && c.text?.trim()).map((c) => c.text.trim()).join("\n\n") : "";
|
|
446
|
+
return text ? messageCell(component as never, event, "assistant", text) : undefined;
|
|
447
|
+
});
|
|
448
|
+
observe(ToolExecutionComponent.prototype as never, (component: ToolLike, event) => toolCell(component, event));
|
|
449
|
+
const report = (hover: ToolHover) => { toolHover = hover; };
|
|
450
|
+
(globalThis as Record<symbol, unknown>)[TOOL_HOVER] = report;
|
|
451
|
+
restores.push(() => {
|
|
452
|
+
if ((globalThis as Record<symbol, unknown>)[TOOL_HOVER] === report) delete (globalThis as Record<symbol, unknown>)[TOOL_HOVER];
|
|
453
|
+
});
|
|
454
|
+
// Esc closes an open menu; otherwise it reaches Pi untouched (abort, clear).
|
|
455
|
+
restores.push(context.ui.onTerminalInput((data) => {
|
|
456
|
+
if (!open || !matchesKey(data, "escape")) return undefined;
|
|
457
|
+
open = false;
|
|
458
|
+
place();
|
|
459
|
+
tui?.requestRender();
|
|
460
|
+
return { consume: true };
|
|
461
|
+
}));
|
|
462
|
+
// An empty widget: its factory is the public way to reach the TUI and theme.
|
|
463
|
+
context.ui.setWidget("pi-cell-actions", (next, t) => {
|
|
464
|
+
theme = t as Theme;
|
|
465
|
+
attach(next);
|
|
466
|
+
return { render: () => [], invalidate: () => {} };
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
// New rows can scroll the transcript under a still pointer: drop a stale badge.
|
|
471
|
+
const dropStale = () => { if (hovered && !open) setHover(undefined); };
|
|
472
|
+
pi.on("message_start", dropStale);
|
|
473
|
+
pi.on("tool_execution_start", dropStale);
|
|
474
|
+
|
|
475
|
+
pi.on("session_shutdown", () => {
|
|
476
|
+
detach();
|
|
477
|
+
ctx = undefined;
|
|
478
|
+
});
|
|
479
|
+
}
|