@luxass/pi-subagents 0.0.0-stage → 0.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.
@@ -0,0 +1,298 @@
1
+ import {
2
+ AssistantMessageComponent,
3
+ createBashToolDefinition,
4
+ createEditToolDefinition,
5
+ createFindToolDefinition,
6
+ createGrepToolDefinition,
7
+ createLsToolDefinition,
8
+ createReadToolDefinition,
9
+ createWriteToolDefinition,
10
+ getMarkdownTheme,
11
+ ToolExecutionComponent,
12
+ UserMessageComponent,
13
+ type AgentSession,
14
+ type Theme,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import {
17
+ Text,
18
+ truncateToWidth,
19
+ visibleWidth,
20
+ type Component,
21
+ type TUI,
22
+ } from "@earendil-works/pi-tui";
23
+
24
+ import type { SubagentManager, SubagentRecord } from "../manager.ts";
25
+ import { subagentMessageText } from "../message-text.ts";
26
+ import { cleanSubagentText, cleanSubagentValue } from "./agent-status.ts";
27
+
28
+ type TranscriptMessage = AgentSession["messages"][number];
29
+ /** Whatever ToolExecutionComponent accepts to draw a call: a tool definition or its renderers. */
30
+ type ToolDrawing = ConstructorParameters<typeof ToolExecutionComponent>[4];
31
+
32
+ // Pi's chat marks some lines with OSC sequences. Inside a framed pane they break the frame.
33
+ // oxlint-disable-next-line no-control-regex -- removing OSC terminal sequences is the point.
34
+ const OSC_SEQUENCES = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g;
35
+
36
+ interface Block {
37
+ component: Component;
38
+ toolCallId?: string;
39
+ }
40
+
41
+ /** The transcript lines of one tool call, so the tool cursor can scroll to it. */
42
+ interface ToolRow {
43
+ start: number;
44
+ end: number;
45
+ toolCallId: string;
46
+ }
47
+
48
+ /**
49
+ * Read-only conversation of one agent, drawn with Pi's own message and tool components.
50
+ * It follows new output while at the bottom and counts what arrives while scrolled up.
51
+ */
52
+ export class SubagentConversation {
53
+ private blocks: Block[] = [];
54
+ private tools = new Map<string, ToolExecutionComponent>();
55
+ private toolRows: ToolRow[] = [];
56
+ private expanded = new Set<string>();
57
+ private allExpanded = false;
58
+ /** The tool call the keyboard cursor is on. */
59
+ private selectedToolId: string | undefined;
60
+ private recordId: string | undefined;
61
+ private version = "";
62
+ private messageCount = 0;
63
+ private seenMessages = 0;
64
+ private readonly builtinTools: Record<string, ToolDrawing>;
65
+
66
+ scrollTop = 0;
67
+ following = true;
68
+ private lineCount = 0;
69
+ page = 1;
70
+
71
+ constructor(
72
+ private readonly tui: TUI,
73
+ private readonly theme: Theme,
74
+ private readonly manager: SubagentManager,
75
+ private readonly cwd: string,
76
+ ) {
77
+ // Finished agents have no live tools, so their calls use Pi's built-in renderers when possible.
78
+ this.builtinTools = {
79
+ read: createReadToolDefinition(cwd),
80
+ bash: createBashToolDefinition(cwd),
81
+ edit: createEditToolDefinition(cwd),
82
+ write: createWriteToolDefinition(cwd),
83
+ grep: createGrepToolDefinition(cwd),
84
+ find: createFindToolDefinition(cwd),
85
+ ls: createLsToolDefinition(cwd),
86
+ };
87
+ }
88
+
89
+ /** New messages that arrived while scrolled up. */
90
+ get unseen(): number {
91
+ return Math.max(0, this.messageCount - this.seenMessages);
92
+ }
93
+
94
+ /** Rebuilds the components when the selected agent or its transcript changed. */
95
+ sync(record: SubagentRecord | undefined): void {
96
+ if (record?.id !== this.recordId) {
97
+ this.recordId = record?.id;
98
+ this.version = "";
99
+ this.following = true;
100
+ this.scrollTop = 0;
101
+ this.expanded.clear();
102
+ this.allExpanded = false;
103
+ this.selectedToolId = undefined;
104
+ }
105
+ if (!record) {
106
+ this.blocks = [];
107
+ this.messageCount = this.seenMessages = 0;
108
+ return;
109
+ }
110
+ const messages = this.manager.transcript(record);
111
+ const version = `${record.run}:${record.status}:${messages.length}:${record.turns}:${record.toolUses}`;
112
+ if (version === this.version) return;
113
+ this.version = version;
114
+ this.build(record, messages);
115
+ this.messageCount = messages.length;
116
+ if (this.following) this.seenMessages = this.messageCount;
117
+ }
118
+
119
+ private build(record: SubagentRecord, messages: readonly TranscriptMessage[]): void {
120
+ const markdownTheme = getMarkdownTheme();
121
+ this.blocks = [];
122
+ this.tools.clear();
123
+ for (const message of messages) {
124
+ if (message.role === "user") {
125
+ const text = cleanSubagentText(subagentMessageText(message.content));
126
+ if (text.trim())
127
+ this.blocks.push({ component: new UserMessageComponent(text, markdownTheme) });
128
+ } else if (message.role === "assistant") {
129
+ const content = message.content.map((part) =>
130
+ part.type === "text"
131
+ ? { ...part, text: cleanSubagentText(part.text) }
132
+ : part.type === "thinking"
133
+ ? { ...part, thinking: cleanSubagentText(part.thinking) }
134
+ : part,
135
+ );
136
+ if (content.some((part) => part.type !== "toolCall")) {
137
+ this.blocks.push({
138
+ component: new AssistantMessageComponent({ ...message, content }, false, markdownTheme),
139
+ });
140
+ }
141
+ for (const part of message.content) {
142
+ if (part.type !== "toolCall") continue;
143
+ const definition =
144
+ this.manager.toolDefinition(record, part.name) ?? this.builtinTools[part.name];
145
+ // Arguments come from the agent's model, and renderers print them as they are.
146
+ const tool = new ToolExecutionComponent(
147
+ cleanSubagentText(part.name),
148
+ part.id,
149
+ cleanSubagentValue(part.arguments),
150
+ {},
151
+ definition,
152
+ this.tui,
153
+ this.cwd,
154
+ );
155
+ tool.markExecutionStarted();
156
+ tool.setArgsComplete();
157
+ tool.setExpanded(this.allExpanded || this.expanded.has(part.id));
158
+ this.tools.set(part.id, tool);
159
+ this.blocks.push({ component: tool, toolCallId: part.id });
160
+ }
161
+ } else if (message.role === "toolResult") {
162
+ this.tools.get(message.toolCallId)?.updateResult(
163
+ {
164
+ content: message.content.map((part) =>
165
+ part.type === "text" ? { ...part, text: cleanSubagentText(part.text) } : part,
166
+ ),
167
+ details: cleanSubagentValue(message.details),
168
+ isError: message.isError,
169
+ durationMs: message.durationMs,
170
+ },
171
+ false,
172
+ );
173
+ } else if (message.role === "custom" && message.display) {
174
+ const text = cleanSubagentText(subagentMessageText(message.content));
175
+ if (text.trim())
176
+ this.blocks.push({ component: new Text(this.theme.fg("muted", text), 1, 0) });
177
+ }
178
+ }
179
+ }
180
+
181
+ /** Expands or collapses every tool call, from Pi's expand key. */
182
+ toggleAllTools(): void {
183
+ this.allExpanded = !this.allExpanded;
184
+ this.expanded.clear();
185
+ for (const tool of this.tools.values()) tool.setExpanded(this.allExpanded);
186
+ }
187
+
188
+ /** Moves the tool cursor to the next (1) or previous (-1) tool call and scrolls it into view. */
189
+ selectTool(delta: 1 | -1): void {
190
+ const ids = [...this.tools.keys()];
191
+ const current = this.selectedToolId ? ids.indexOf(this.selectedToolId) : -1;
192
+ let next = Math.max(0, Math.min(ids.length - 1, current + delta));
193
+ if (current < 0) {
194
+ // The cursor starts on the first tool call in view, where the reader is looking.
195
+ const inView = this.toolRows.find(
196
+ (row) => row.end > this.scrollTop && row.start < this.scrollTop + this.page,
197
+ );
198
+ next = inView ? ids.indexOf(inView.toolCallId) : delta > 0 ? 0 : ids.length - 1;
199
+ }
200
+ this.selectedToolId = ids[next];
201
+ const row = this.toolRows.find((candidate) => candidate.toolCallId === this.selectedToolId);
202
+ // The cursor mark is on the line above the call.
203
+ const hidden = row && (row.start - 1 < this.scrollTop || row.end > this.scrollTop + this.page);
204
+ if (row && hidden) this.scrollTo(row.start - 1);
205
+ }
206
+
207
+ /** Expands or collapses the tool call under the cursor. */
208
+ toggleSelectedTool(): boolean {
209
+ if (!this.selectedToolId) return false;
210
+ // Stop following, so the call stays in view while its height changes.
211
+ this.following = false;
212
+ return this.toggleTool(this.selectedToolId);
213
+ }
214
+
215
+ private toggleTool(toolCallId: string): boolean {
216
+ const tool = this.tools.get(toolCallId);
217
+ if (!tool) return false;
218
+ const open = this.allExpanded || this.expanded.has(toolCallId);
219
+ if (this.allExpanded) {
220
+ // Collapsing one call after expanding all keeps the others open.
221
+ this.allExpanded = false;
222
+ for (const id of this.tools.keys()) this.expanded.add(id);
223
+ }
224
+ if (open) this.expanded.delete(toolCallId);
225
+ else this.expanded.add(toolCallId);
226
+ tool.setExpanded(!open);
227
+ return true;
228
+ }
229
+
230
+ scrollTo(top: number): void {
231
+ const maxScroll = Math.max(0, this.lineCount - this.page);
232
+ this.scrollTop = Math.max(0, Math.min(maxScroll, top));
233
+ this.following = this.scrollTop >= maxScroll;
234
+ if (this.following) this.seenMessages = this.messageCount;
235
+ }
236
+
237
+ scrollBy(delta: number): void {
238
+ this.scrollTo(this.scrollTop + delta);
239
+ }
240
+
241
+ /** Jumps to the end and follows new output again (End). */
242
+ follow(): void {
243
+ this.following = true;
244
+ this.scrollTo(Number.MAX_SAFE_INTEGER);
245
+ }
246
+
247
+ /** Renders exactly `height` lines. The last column is the scrollbar. */
248
+ render(width: number, height: number): string[] {
249
+ const contentWidth = Math.max(1, width - 1);
250
+ const lines: string[] = [];
251
+ this.toolRows = [];
252
+ for (const block of this.blocks) {
253
+ // The line above a block separates it from the block before. On the selected tool call it
254
+ // holds the cursor mark.
255
+ const selected = block.toolCallId !== undefined && block.toolCallId === this.selectedToolId;
256
+ if (selected) lines.push(this.theme.fg("accent", "› selected tool call"));
257
+ else if (lines.length) lines.push("");
258
+ const start = lines.length;
259
+ lines.push(
260
+ ...block.component.render(contentWidth).map((line) => line.replace(OSC_SEQUENCES, "")),
261
+ );
262
+ if (block.toolCallId)
263
+ this.toolRows.push({ start, end: lines.length, toolCallId: block.toolCallId });
264
+ }
265
+ if (!lines.length) lines.push(this.theme.fg("dim", "No messages yet."));
266
+
267
+ const marker = !this.following && this.unseen > 0;
268
+ this.page = Math.max(1, height - (marker ? 1 : 0));
269
+ this.lineCount = lines.length;
270
+ const maxScroll = Math.max(0, this.lineCount - this.page);
271
+ this.scrollTop = this.following ? maxScroll : Math.min(this.scrollTop, maxScroll);
272
+ const thumbHeight = Math.max(
273
+ 1,
274
+ Math.floor((this.page * this.page) / Math.max(this.page, this.lineCount)),
275
+ );
276
+ const thumbTop =
277
+ maxScroll > 0 ? Math.round((this.scrollTop / maxScroll) * (this.page - thumbHeight)) : 0;
278
+
279
+ const visible = lines.slice(this.scrollTop, this.scrollTop + this.page);
280
+ while (visible.length < this.page) visible.push("");
281
+ const rows = visible.map((line, index) => {
282
+ const fitted = truncateToWidth(line, contentWidth, "");
283
+ const padding = " ".repeat(Math.max(0, contentWidth - visibleWidth(fitted)));
284
+ if (maxScroll === 0) return `${fitted}${padding} `;
285
+ const thumb = index >= thumbTop && index < thumbTop + thumbHeight;
286
+ return `${fitted}${padding}${this.theme.fg(thumb ? "scrollbarThumb" : "scrollbarTrack", thumb ? "┃" : "│")}`;
287
+ });
288
+ if (marker) {
289
+ const text = `↓ ${this.unseen} new message${this.unseen === 1 ? "" : "s"} (end to follow)`;
290
+ rows.push(truncateToWidth(this.theme.fg("accent", text), width, ""));
291
+ }
292
+ return rows;
293
+ }
294
+
295
+ invalidate(): void {
296
+ for (const block of this.blocks) block.component.invalidate();
297
+ }
298
+ }
@@ -0,0 +1,24 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ import type { SubagentManager } from "../manager.ts";
4
+
5
+ /** Key of the agent cost text in the footer's status line. */
6
+ export const SUBAGENT_COST_STATUS = "subagents";
7
+
8
+ /**
9
+ * Shows what this session's agents cost in the footer's status line, for example `agents $0.123`.
10
+ * Pi's own cost total counts only the main session, and an extension cannot add to it, so agent
11
+ * costs get their own number. It appears once an agent has used a model and follows running agents.
12
+ */
13
+ export function installSubagentCostStatus(ctx: ExtensionContext, manager: SubagentManager): void {
14
+ let shown: string | undefined;
15
+ const update = () => {
16
+ // Three decimals, like the cost in Pi's footer.
17
+ const text = manager.hasAgentUsage() ? `agents $${manager.agentCost().toFixed(3)}` : undefined;
18
+ if (text === shown) return;
19
+ shown = text;
20
+ ctx.ui.setStatus(SUBAGENT_COST_STATUS, text);
21
+ };
22
+ manager.subscribe(update);
23
+ update();
24
+ }
@@ -0,0 +1,29 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+
3
+ /** One line of exactly `width` columns: line breaks become spaces, and the text is cut or padded. */
4
+ export function fitLine(text: string, width: number): string {
5
+ const value = truncateToWidth(text.replace(/[\r\n\t]+/g, " "), Math.max(0, width));
6
+ return value + " ".repeat(Math.max(0, width - visibleWidth(value)));
7
+ }
8
+
9
+ /**
10
+ * Cuts unstyled text to `width` columns and ends a cut text with "…". Unlike `truncateToWidth`
11
+ * it adds no color reset, so the result can be colored and sit on a background.
12
+ */
13
+ export function cutPlainText(text: string, width: number): string {
14
+ const line = text.replace(/[\r\n\t]+/g, " ");
15
+ if (visibleWidth(line) <= width) return line;
16
+ if (width <= 0) return "";
17
+ let cut = "";
18
+ for (const character of line) {
19
+ if (visibleWidth(cut + character) > width - 1) break;
20
+ cut += character;
21
+ }
22
+ return `${cut}…`;
23
+ }
24
+
25
+ /** `left` and `right` at the two ends of a line. `left` is cut when both do not fit. */
26
+ export function lineEnds(left: string, right: string, width: number): string {
27
+ const room = Math.max(0, width - visibleWidth(right) - 2);
28
+ return `${fitLine(left, room)} ${right}`;
29
+ }
@@ -0,0 +1,224 @@
1
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ matchesKey,
4
+ truncateToWidth,
5
+ visibleWidth,
6
+ type Component,
7
+ type TuiMouseEvent,
8
+ } from "@earendil-works/pi-tui";
9
+
10
+ import type { SubagentManager } from "../manager.ts";
11
+ import { SubagentList } from "./agent-list.ts";
12
+ import { renderAgentPanel } from "./agent-panel.ts";
13
+ import { SubagentPreview } from "./agent-preview.ts";
14
+ import { cleanSubagentText, subagentStatusLabel } from "./agent-status.ts";
15
+ import { SubagentConversation } from "./conversation.ts";
16
+ import { fitLine, lineEnds } from "./text-layout.ts";
17
+
18
+ /** Reading view lines around the conversation: top border, header, two separators, footer, bottom border. */
19
+ const READING_FRAME_LINES = 6;
20
+
21
+ /**
22
+ * `/agents`. The first view is a panel with the agent list, its filter tabs, and the selected
23
+ * agent's answer. Enter opens the reading view: the agent's whole conversation. The viewer only
24
+ * reads and stops agents. There is no message input.
25
+ */
26
+ export async function openSubagentViewer(
27
+ ctx: ExtensionCommandContext,
28
+ manager: SubagentManager,
29
+ ): Promise<void> {
30
+ let fullscreen = false;
31
+ await ctx.ui.custom<void>(
32
+ (tui, theme, keybindings, done) => {
33
+ const list = new SubagentList(theme, manager);
34
+ const preview = new SubagentPreview(manager);
35
+ const conversation = new SubagentConversation(tui, theme, manager, ctx.cwd);
36
+ const redraw = () => tui.requestRender();
37
+ let reading = false;
38
+ let previewFocused = false;
39
+
40
+ const unsubscribe = manager.subscribe(redraw);
41
+ const border = (text: string) => theme.fg("borderAccent", text);
42
+
43
+ const edge = (left: string, right: string, label: string, width: number) => {
44
+ const fitted = truncateToWidth(label, Math.max(0, width - 4), "…");
45
+ return (
46
+ border(`${left}─`) +
47
+ fitted +
48
+ border(`${"─".repeat(Math.max(0, width - 3 - visibleWidth(fitted)))}${right}`)
49
+ );
50
+ };
51
+ const row = (content: string, inner: number) => {
52
+ const fitted = truncateToWidth(content, inner, "");
53
+ return `${border("│")}${fitted}${" ".repeat(Math.max(0, inner - visibleWidth(fitted)))}${border("│")}`;
54
+ };
55
+
56
+ const renderReading = (width: number): string[] => {
57
+ const inner = Math.max(10, width - 2);
58
+ const height = Math.max(
59
+ READING_FRAME_LINES + 3,
60
+ fullscreen ? tui.terminal.rows : Math.floor(tui.terminal.rows * 0.85),
61
+ );
62
+ const bodyHeight = height - READING_FRAME_LINES;
63
+ const record = list.selected();
64
+ conversation.sync(record);
65
+
66
+ const title = record ? ` ${record.name} · ${record.agentType} ` : " Agents ";
67
+ // One space of padding at each side of the header and the footer.
68
+ const textWidth = Math.max(1, inner - 2);
69
+ const dot = theme.fg("muted", "·");
70
+ // The status stays at the right. In a narrow terminal the model is what gets cut.
71
+ const header = record
72
+ ? lineEnds(
73
+ [
74
+ theme.bold(record.name),
75
+ ...(record.error
76
+ ? [theme.fg("error", cleanSubagentText(record.error).split("\n")[0] ?? "")]
77
+ : []),
78
+ record.model || "model pending",
79
+ `thinking ${record.thinking}`,
80
+ ].join(` ${dot} `),
81
+ subagentStatusLabel(record),
82
+ textWidth,
83
+ )
84
+ : fitLine(theme.fg("dim", "No agent selected."), textWidth);
85
+
86
+ // "Esc Back" stays at the right. The other hints are added while they fit, so a narrow
87
+ // terminal drops whole hints and never the way out.
88
+ const expand = keybindings.getKeys("app.tools.expand")[0] ?? "ctrl+o";
89
+ const back = textWidth < 28 ? "Esc" : "Esc Back";
90
+ const budget = Math.max(0, textWidth - visibleWidth(back) - 2);
91
+ let hints = "";
92
+ for (const hint of [
93
+ "↑↓ Scroll",
94
+ "t/T Tool",
95
+ "Enter Expand",
96
+ `${expand} All tools`,
97
+ fullscreen ? "f Floating" : "f Fullscreen",
98
+ ]) {
99
+ const gap = hints ? " " : "";
100
+ if (visibleWidth(hints + gap + hint) > budget) break;
101
+ hints += gap + hint;
102
+ }
103
+ return [
104
+ edge("┌", "┐", theme.fg("accent", title), width),
105
+ row(` ${header}`, inner),
106
+ border(`├${"─".repeat(inner)}┤`),
107
+ ...conversation.render(inner, bodyHeight).map((line) => row(line, inner)),
108
+ border(`├${"─".repeat(inner)}┤`),
109
+ row(` ${theme.fg("dim", lineEnds(hints, back, textWidth))}`, inner),
110
+ border(`└${"─".repeat(inner)}┘`),
111
+ ];
112
+ };
113
+
114
+ const openReading = () => {
115
+ if (!list.selected()) return;
116
+ reading = true;
117
+ // The conversation takes the whole terminal, and Esc gives the panel its size back.
118
+ fullscreen = true;
119
+ };
120
+
121
+ const handleReadingInput = (data: string) => {
122
+ if (keybindings.matches(data, "tui.select.cancel")) {
123
+ reading = false;
124
+ fullscreen = false;
125
+ previewFocused = false;
126
+ } else if (data === "f") fullscreen = !fullscreen;
127
+ else if (keybindings.matches(data, "app.tools.expand")) conversation.toggleAllTools();
128
+ else if (keybindings.matches(data, "tui.select.pageUp"))
129
+ conversation.scrollBy(-conversation.page);
130
+ else if (keybindings.matches(data, "tui.select.pageDown"))
131
+ conversation.scrollBy(conversation.page);
132
+ else if (matchesKey(data, "home")) conversation.scrollTo(0);
133
+ else if (matchesKey(data, "end")) conversation.follow();
134
+ else if (data === "t") conversation.selectTool(1);
135
+ else if (data === "T" || matchesKey(data, "shift+t")) conversation.selectTool(-1);
136
+ else if (keybindings.matches(data, "tui.select.confirm")) conversation.toggleSelectedTool();
137
+ else if (keybindings.matches(data, "tui.select.up")) conversation.scrollBy(-1);
138
+ else if (keybindings.matches(data, "tui.select.down")) conversation.scrollBy(1);
139
+ };
140
+
141
+ /** Scrolls the answer and stops following new output. */
142
+ const scrollPreview = (lines: number) => {
143
+ preview.scroll.scrollTo(preview.scroll.scrollTop + lines, { disableFollow: true });
144
+ };
145
+
146
+ const handlePanelInput = (data: string) => {
147
+ if (list.stopTarget()) {
148
+ const yes = data === "y" || keybindings.matches(data, "tui.select.confirm");
149
+ const no = data === "n" || keybindings.matches(data, "tui.select.cancel");
150
+ if (yes || no) void list.confirmStop(yes).then(redraw);
151
+ return;
152
+ }
153
+ const page = Math.max(1, preview.scroll.viewportHeight - 2);
154
+ if (keybindings.matches(data, "tui.select.cancel")) done();
155
+ else if (data === "f") fullscreen = !fullscreen;
156
+ else if (matchesKey(data, "tab")) previewFocused = !previewFocused;
157
+ else if (data === "1") list.setFilter("all");
158
+ else if (data === "2") list.setFilter("active");
159
+ else if (data === "3") list.setFilter("finished");
160
+ else if (keybindings.matches(data, "tui.select.confirm")) openReading();
161
+ else if (data === "x") list.askStop();
162
+ else if (keybindings.matches(data, "tui.select.up")) {
163
+ if (previewFocused) scrollPreview(-1);
164
+ else list.move(-1);
165
+ } else if (keybindings.matches(data, "tui.select.down")) {
166
+ if (previewFocused) scrollPreview(1);
167
+ else list.move(1);
168
+ } else if (keybindings.matches(data, "tui.select.pageUp")) scrollPreview(-page);
169
+ else if (keybindings.matches(data, "tui.select.pageDown")) scrollPreview(page);
170
+ else if (matchesKey(data, "end")) preview.scroll.scrollToEnd();
171
+ else if (matchesKey(data, "home")) preview.scroll.scrollToStart();
172
+ };
173
+
174
+ const handleInput = (data: string) => {
175
+ if (reading) handleReadingInput(data);
176
+ else handlePanelInput(data);
177
+ redraw();
178
+ };
179
+
180
+ const component: Component & { dispose(): void } = {
181
+ render(width) {
182
+ if (reading) return renderReading(width);
183
+ return renderAgentPanel(
184
+ { theme, tui, list, preview, fullscreen, previewFocused, redraw },
185
+ width,
186
+ );
187
+ },
188
+ handleInput,
189
+ // Pi sends mouse events here only in its fullscreen terminal mode. The wheel scrolls the
190
+ // answer or the conversation. Every other event is taken and ignored: an event that is
191
+ // not taken goes to the chat behind the viewer, and the wheel would scroll that.
192
+ handleMouse(event: TuiMouseEvent) {
193
+ if (event.type !== "wheel") return { handled: true, render: false };
194
+ if (reading) conversation.scrollBy(event.wheelDelta ?? 0);
195
+ else if (!list.stopTarget()) scrollPreview(event.wheelDelta ?? 0);
196
+ return { handled: true };
197
+ },
198
+ invalidate() {
199
+ preview.invalidate();
200
+ conversation.invalidate();
201
+ },
202
+ dispose() {
203
+ unsubscribe();
204
+ },
205
+ };
206
+ return component;
207
+ },
208
+ {
209
+ overlay: true,
210
+ // Pi reads these once, but the TUI reads the getters on every render, so `f` resizes the
211
+ // open overlay. The rendered line count sets the height.
212
+ overlayOptions: {
213
+ anchor: "center",
214
+ maxHeight: "100%",
215
+ get width() {
216
+ return fullscreen ? "100%" : 128;
217
+ },
218
+ get margin() {
219
+ return fullscreen ? 0 : 1;
220
+ },
221
+ },
222
+ },
223
+ );
224
+ }
@@ -0,0 +1,59 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth } from "@earendil-works/pi-tui";
3
+
4
+ import type { SubagentManager } from "../manager.ts";
5
+ import { showsBackgroundHint, subagentStatusMark } from "./agent-status.ts";
6
+
7
+ const ANIMATION_INTERVAL_MS = 120;
8
+
9
+ /**
10
+ * Shows one quiet line above the editor while agents work, such as "Agents · 3 running". What
11
+ * each agent is doing is in its `Agent` card and in `/agents`. The widget is always installed,
12
+ * so its timer also animates the cards when `widget` is "off".
13
+ */
14
+ export function installSubagentWidget(ctx: ExtensionContext, manager: SubagentManager): void {
15
+ ctx.ui.setWidget("subagents", (tui, theme) => {
16
+ const unsubscribe = manager.subscribe(() => tui.requestRender());
17
+ const timer = setInterval(() => {
18
+ if (manager.list().some((record) => record.status === "running")) tui.requestRender();
19
+ }, ANIMATION_INTERVAL_MS);
20
+ return {
21
+ render(width) {
22
+ const mode = manager.settings.widget;
23
+ if (mode === "off") return [];
24
+ const working = manager
25
+ .list()
26
+ .filter(
27
+ (record) =>
28
+ record.status === "running" ||
29
+ record.status === "queued" ||
30
+ record.status === "stopping",
31
+ )
32
+ .filter((record) => mode === "all" || record.background);
33
+ if (!working.length) return [];
34
+
35
+ const queued = working.filter((record) => record.status === "queued").length;
36
+ // An agent that is stopping still runs until its session has closed.
37
+ const running = working.length - queued;
38
+ const counts = [
39
+ ...(running ? [`${running} running`] : []),
40
+ ...(queued ? [`${queued} queued`] : []),
41
+ ].join(" · ");
42
+ // The spinner while any agent runs, the queued mark when all of them wait.
43
+ const lead = working.find((record) => record.status !== "queued") ?? working[0];
44
+ const mark = lead ? subagentStatusMark(lead, theme) : "";
45
+ const hint = working.some((record) => showsBackgroundHint(record))
46
+ ? theme.fg("dim", " (ctrl+b to run in background)")
47
+ : "";
48
+ // One column in, like the chat text above it.
49
+ const line = ` ${mark} Agents ${theme.fg("dim", `· ${counts}`)}${hint}`;
50
+ return [truncateToWidth(line, width, "…")];
51
+ },
52
+ invalidate() {},
53
+ dispose() {
54
+ clearInterval(timer);
55
+ unsubscribe();
56
+ },
57
+ };
58
+ });
59
+ }