@lune_99/pi-subagent 0.0.0-stage → 0.2.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/LICENSE +21 -0
  3. package/README.md +185 -2
  4. package/docs/capture.json +30 -0
  5. package/docs/previews.md +22 -0
  6. package/docs/reference.md +264 -0
  7. package/docs/subagent-auto-tiers.png +0 -0
  8. package/docs/subagent-inspector.png +0 -0
  9. package/docs/subagent-overview.png +0 -0
  10. package/package.json +82 -5
  11. package/skills/create-lune-subagent/SKILL.md +190 -0
  12. package/src/auto-model.ts +601 -0
  13. package/src/catalog.ts +111 -0
  14. package/src/definition-file.ts +147 -0
  15. package/src/definitions.ts +330 -0
  16. package/src/dock/dock-alert.ts +78 -0
  17. package/src/dock/dock-contribution.ts +328 -0
  18. package/src/extension-tools.ts +46 -0
  19. package/src/index.ts +194 -0
  20. package/src/inspector/details.ts +119 -0
  21. package/src/inspector/inspector.ts +677 -0
  22. package/src/inspector/layout.ts +119 -0
  23. package/src/inspector/transcript.ts +735 -0
  24. package/src/inspector/viewport.ts +62 -0
  25. package/src/inspector/wrap.ts +136 -0
  26. package/src/models.ts +69 -0
  27. package/src/notify/notification-box.ts +408 -0
  28. package/src/notify/notifier.ts +586 -0
  29. package/src/paths.ts +34 -0
  30. package/src/render/lune-theme.ts +68 -0
  31. package/src/render/text.ts +121 -0
  32. package/src/run/guide.ts +31 -0
  33. package/src/run/report-tool.ts +90 -0
  34. package/src/run/run-file.ts +194 -0
  35. package/src/run/run-manager.ts +935 -0
  36. package/src/run/run-session.ts +307 -0
  37. package/src/run/run.ts +773 -0
  38. package/src/run/session-start.ts +283 -0
  39. package/src/run/types.ts +175 -0
  40. package/src/run/worktree.ts +138 -0
  41. package/src/schema.ts +9 -0
  42. package/src/settings/agents-menu.ts +376 -0
  43. package/src/settings/panel.ts +221 -0
  44. package/src/settings/schema.ts +75 -0
  45. package/src/settings/thinking-choices.ts +92 -0
  46. package/src/tools/format.ts +397 -0
  47. package/src/tools/subagent-tools.ts +355 -0
@@ -0,0 +1,677 @@
1
+ import type { ExtensionContext, Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Input,
4
+ Key,
5
+ matchesKey,
6
+ truncateToWidth,
7
+ visibleWidth,
8
+ wrapTextWithAnsi,
9
+ type Component,
10
+ type TuiMouseEvent,
11
+ type TuiMouseEventResult,
12
+ } from "@earendil-works/pi-tui";
13
+
14
+ import { displayedStatus, reportColor, stateColor } from "../notify/notification-box.ts";
15
+ import { clipToWidth, displayLine, fitRanked, type RankedPart } from "../render/text.ts";
16
+ import type { RunManager } from "../run/run-manager.ts";
17
+ import type { Run } from "../run/run.ts";
18
+ import { formatPercent } from "../tools/format.ts";
19
+ import { detailRows } from "./details.ts";
20
+ import {
21
+ assembleFrame,
22
+ BODY_TOP,
23
+ cell,
24
+ listWindowStart,
25
+ paintScrollbar,
26
+ paneGeometry,
27
+ type PaneGeometry,
28
+ } from "./layout.ts";
29
+ import { TranscriptRenderer } from "./transcript.ts";
30
+ import { Viewport } from "./viewport.ts";
31
+
32
+ const REFRESH_INTERVAL_MS = 1000;
33
+ const NOTICE_MS = 2500;
34
+ const ERROR_NOTICE_MS = 6000;
35
+
36
+ export interface InspectorOptions {
37
+ ctx: ExtensionContext;
38
+ manager: RunManager;
39
+ /** The user saw the run's outcome; the Dock stops marking it. */
40
+ onSeen: (run: Run) => void;
41
+ }
42
+
43
+ export async function openSubagentInspector(options: InspectorOptions): Promise<void> {
44
+ await options.ctx.ui.custom<void>(
45
+ (tui, _theme, _keybindings, done) =>
46
+ new SubagentInspector(
47
+ options,
48
+ () => tui.requestRender(),
49
+ () => done(),
50
+ () => tui.terminal.rows,
51
+ ),
52
+ {
53
+ overlay: true,
54
+ overlayOptions: {
55
+ anchor: "center",
56
+ width: "90%",
57
+ minWidth: 72,
58
+ maxHeight: "85%",
59
+ margin: 1,
60
+ },
61
+ },
62
+ );
63
+ }
64
+
65
+ interface FrameLayout {
66
+ geometry: PaneGeometry;
67
+ listStart: number;
68
+ /** Run IDs as the list showed them, so a click selects the run the user saw in that row. */
69
+ order: readonly string[];
70
+ }
71
+
72
+ /**
73
+ * The `/agents` panel: runs on the left, the selected run's live transcript on the right.
74
+ *
75
+ * Runs of the current branch come first; runs of other branches follow, dimmed, so their reports
76
+ * can be copied over. Running runs lead each group. Every write goes through the manager, which
77
+ * enforces read-only runs.
78
+ */
79
+ export class SubagentInspector implements Component {
80
+ private readonly ctx: ExtensionContext;
81
+ private readonly manager: RunManager;
82
+ private readonly onSeen: (run: Run) => void;
83
+ private readonly requestRender: () => void;
84
+ private readonly close: () => void;
85
+ private readonly terminalRows: () => number;
86
+ private readonly theme: Theme;
87
+ private readonly transcripts: TranscriptRenderer;
88
+ private readonly viewport = new Viewport();
89
+
90
+ private selectedId: string | undefined;
91
+ private details = false;
92
+ private chat: Input | undefined;
93
+ private notice: { text: string; color: ThemeColor } | undefined;
94
+ private noticeTimer: ReturnType<typeof setTimeout> | undefined;
95
+ private refreshTimer: ReturnType<typeof setInterval> | undefined;
96
+ private unsubscribe: (() => void) | undefined;
97
+ private layout: FrameLayout | undefined;
98
+ private disposed = false;
99
+
100
+ constructor(
101
+ options: InspectorOptions,
102
+ requestRender: () => void,
103
+ close: () => void,
104
+ terminalRows: () => number,
105
+ ) {
106
+ this.ctx = options.ctx;
107
+ this.manager = options.manager;
108
+ this.onSeen = options.onSeen;
109
+ this.requestRender = requestRender;
110
+ this.close = close;
111
+ this.terminalRows = terminalRows;
112
+ this.theme = options.ctx.ui.theme;
113
+ this.transcripts = new TranscriptRenderer(this.theme);
114
+ // A remembered run that is no longer listed falls back to the first one on render.
115
+ this.selectedId = this.manager.inspectorRunId ?? this.entries()[0]?.run.id;
116
+ // The list shows states only, so another run's streamed tokens change nothing on screen.
117
+ this.unsubscribe = this.manager.subscribe((change, run) => {
118
+ if (change === "state" || run?.id === this.selectedId) {
119
+ this.requestRender();
120
+ }
121
+ });
122
+ }
123
+
124
+ handleInput(data: string): void {
125
+ if (this.chat) {
126
+ if (matchesKey(data, Key.escape)) {
127
+ this.chat = undefined;
128
+ this.requestRender();
129
+ return;
130
+ }
131
+
132
+ this.chat.handleInput(data);
133
+ this.requestRender();
134
+ return;
135
+ }
136
+
137
+ if (matchesKey(data, Key.escape)) {
138
+ this.dispose();
139
+ this.close();
140
+ return;
141
+ }
142
+
143
+ const entry = this.selected();
144
+
145
+ if (matchesKey(data, Key.shift("up")) || data === "K") {
146
+ this.scroll(-1);
147
+ } else if (matchesKey(data, Key.shift("down")) || data === "J") {
148
+ this.scroll(1);
149
+ } else if (matchesKey(data, Key.up) || data === "k") {
150
+ this.moveSelection(-1);
151
+ } else if (matchesKey(data, Key.down) || data === "j") {
152
+ this.moveSelection(1);
153
+ } else if (matchesKey(data, Key.home)) {
154
+ this.viewport.jumpToOldest();
155
+ this.requestRender();
156
+ } else if (matchesKey(data, Key.end)) {
157
+ this.viewport.follow();
158
+ this.requestRender();
159
+ } else if (matchesKey(data, Key.enter) && entry) {
160
+ this.startChat(entry);
161
+ } else if (data === "d" && entry) {
162
+ this.details = !this.details;
163
+ this.viewport.follow();
164
+ this.requestRender();
165
+ } else if (data === "x" && entry) {
166
+ this.stop(entry.run);
167
+ } else if (data === "c" && entry) {
168
+ this.copy(entry);
169
+ }
170
+ }
171
+
172
+ /** Fullscreen mode routes the mouse here; every action also has a key. */
173
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
174
+ const layout = this.layout;
175
+
176
+ if (!layout) {
177
+ return undefined;
178
+ }
179
+
180
+ const { bodyHeight, rightStart } = layout.geometry;
181
+ const row = event.y - BODY_TOP;
182
+
183
+ if (event.type === "wheel") {
184
+ const delta = event.wheelDelta ?? 0;
185
+
186
+ if (event.x >= rightStart) {
187
+ this.scroll(delta);
188
+ } else {
189
+ this.moveSelection(delta);
190
+ }
191
+
192
+ return { handled: true };
193
+ }
194
+
195
+ // Presses on the transcript stay with the TUI's text selection, which copies text out.
196
+ if (
197
+ row < 0 ||
198
+ row >= bodyHeight ||
199
+ event.x >= rightStart ||
200
+ event.type !== "press" ||
201
+ event.button !== "left" ||
202
+ event.x < 1
203
+ ) {
204
+ return undefined;
205
+ }
206
+
207
+ const runId = layout.order[layout.listStart + row];
208
+
209
+ if (runId === undefined) {
210
+ return undefined;
211
+ }
212
+
213
+ this.select(runId);
214
+
215
+ return { handled: true };
216
+ }
217
+
218
+ render(width: number): string[] {
219
+ const entries = this.entries();
220
+ let index = entries.findIndex((entry) => entry.run.id === this.selectedId);
221
+
222
+ if (index === -1 && entries.length > 0) {
223
+ index = 0;
224
+ this.selectedId = entries[0]!.run.id;
225
+ }
226
+
227
+ const selected = entries[index];
228
+
229
+ this.syncRefreshTimer(selected?.run);
230
+
231
+ if (selected) {
232
+ this.onSeen(selected.run);
233
+ }
234
+
235
+ const geometry = paneGeometry(width, this.terminalRows());
236
+ const { bodyHeight, leftWidth, rightWidth } = geometry;
237
+ const listStart = listWindowStart(Math.max(0, index), entries.length, bodyHeight);
238
+ const left = this.listRows(entries, listStart, index, leftWidth, bodyHeight);
239
+ let right: string[];
240
+
241
+ if (selected) {
242
+ const contentWidth = Math.max(1, rightWidth - 2);
243
+ const transcript = this.details
244
+ ? detailRows(selected.run, this.theme, contentWidth)
245
+ : this.transcriptOf(selected.run, contentWidth);
246
+ const modelRows = this.modelRows(selected.run, contentWidth);
247
+ const capacity = Math.max(1, bodyHeight - 1 - modelRows.length);
248
+ const view = this.viewport.window(transcript.length, capacity);
249
+ const rows = transcript
250
+ .slice(view.start, view.start + capacity)
251
+ .map((row) => cell(row, rightWidth));
252
+
253
+ while (rows.length < capacity) {
254
+ rows.push(" ".repeat(rightWidth));
255
+ }
256
+
257
+ right = [
258
+ cell(this.title(selected, view.newestHidden, contentWidth), rightWidth),
259
+ ...modelRows.map((row) => cell(row, rightWidth)),
260
+ ...paintScrollbar(this.theme, rows, view.start, capacity, transcript.length),
261
+ ];
262
+ } else {
263
+ right = [cell(this.theme.fg("muted", "No subagent runs in this session."), rightWidth)];
264
+ }
265
+
266
+ this.layout = { geometry, listStart, order: entries.map((entry) => entry.run.id) };
267
+
268
+ return assembleFrame(this.theme, geometry, {
269
+ header: cell(this.header(entries), geometry.innerWidth),
270
+ left,
271
+ right,
272
+ footer: this.footer(geometry.innerWidth, selected),
273
+ });
274
+ }
275
+
276
+ invalidate(): void {
277
+ this.transcripts.clear();
278
+ }
279
+
280
+ /** A run file that cannot be read shows its error in place of the transcript. */
281
+ private transcriptOf(run: Run, width: number): readonly string[] {
282
+ try {
283
+ return this.transcripts.render(run, width);
284
+ } catch (error) {
285
+ const text = `The run transcript cannot be read: ${error instanceof Error ? error.message : String(error)}`;
286
+
287
+ return wrapTextWithAnsi(displayLine(text), width).map((row) =>
288
+ this.theme.fg("error", row),
289
+ );
290
+ }
291
+ }
292
+
293
+ dispose(): void {
294
+ if (this.disposed) {
295
+ return;
296
+ }
297
+
298
+ this.disposed = true;
299
+ this.manager.inspectorRunId = this.selectedId;
300
+ clearInterval(this.refreshTimer);
301
+ clearTimeout(this.noticeTimer);
302
+ this.unsubscribe?.();
303
+ this.unsubscribe = undefined;
304
+ }
305
+
306
+ private entries(): Entry[] {
307
+ const { here, elsewhere } = this.manager.runsByBranch();
308
+
309
+ return [
310
+ ...runningFirst(here).map((run) => ({ run, elsewhere: false })),
311
+ ...runningFirst(elsewhere).map((run) => ({ run, elsewhere: true })),
312
+ ];
313
+ }
314
+
315
+ private selected(): Entry | undefined {
316
+ return this.entries().find((entry) => entry.run.id === this.selectedId);
317
+ }
318
+
319
+ private listRows(
320
+ entries: readonly Entry[],
321
+ start: number,
322
+ selected: number,
323
+ width: number,
324
+ height: number,
325
+ ): string[] {
326
+ const rows: string[] = [];
327
+ const contentWidth = width - 2;
328
+
329
+ for (let index = start; index < Math.min(entries.length, start + height); index++) {
330
+ const { run, elsewhere } = entries[index]!;
331
+ // One status per run, as in the Dock, so that it fits whole in the narrowest list.
332
+ const report =
333
+ run.state === "idle" && run.lastTurn
334
+ ? displayedStatus(run.state, run.lastTurn.report?.status, run.lastTurn.cutShort)
335
+ : undefined;
336
+ const status = report ?? run.state;
337
+ const marker = elsewhere ? "↪" : run.state === "running" ? "◐" : "●";
338
+ // The cursor and marker take four columns, and one more separates title and status.
339
+ const name = clipToWidth(run.title, Math.max(0, contentWidth - 5 - status.length));
340
+ const title = this.theme.fg(elsewhere ? "muted" : "text", name);
341
+ const gap = Math.max(1, contentWidth - 4 - visibleWidth(name) - status.length);
342
+ const text =
343
+ (index === selected ? this.theme.fg("accent", "›") : " ") +
344
+ " " +
345
+ this.theme.fg(elsewhere ? "dim" : stateColor(run.state), marker) +
346
+ " " +
347
+ (index === selected ? this.theme.bold(title) : title) +
348
+ " ".repeat(gap) +
349
+ this.theme.fg(report ? reportColor(report) : stateColor(run.state), status);
350
+ rows.push(cell(text, width));
351
+ }
352
+
353
+ return paintScrollbar(this.theme, rows, start, height, entries.length);
354
+ }
355
+
356
+ private header(entries: readonly Entry[]): string {
357
+ const running = entries.filter((entry) => entry.run.state === "running").length;
358
+ const here = entries.filter((entry) => !entry.elsewhere).length;
359
+ const elsewhere = entries.length - here;
360
+ const counts = [
361
+ `${here} on this branch`,
362
+ elsewhere > 0 ? `${elsewhere} on other branches` : undefined,
363
+ running > 0 ? this.theme.fg("warning", `${running} running`) : undefined,
364
+ ]
365
+ .filter((part) => part !== undefined)
366
+ .join(this.theme.fg("dim", " · "));
367
+
368
+ return `${this.theme.bold("Subagents")} ${this.theme.fg("muted", counts)}`;
369
+ }
370
+
371
+ /** The run's title and every label that fits; a narrow pane leaves out the least useful first. */
372
+ private title(entry: Entry, newestHidden: number, width: number): string {
373
+ const { run } = entry;
374
+ const report =
375
+ run.lastTurn &&
376
+ displayedStatus(run.state, run.lastTurn.report?.status, run.lastTurn.cutShort);
377
+ const title = this.theme.bold(run.title);
378
+ const parts: Array<RankedPart | undefined> = [
379
+ // A run without a readable snapshot is already named by its ID.
380
+ run.title !== run.id ? { text: this.theme.fg("dim", run.id), rank: 1 } : undefined,
381
+ { text: this.theme.fg(stateColor(run.state), run.state), rank: 5 },
382
+ report && run.state !== "running"
383
+ ? { text: this.theme.fg(reportColor(report), report), rank: 4 }
384
+ : undefined,
385
+ entry.elsewhere ? { text: this.theme.fg("muted", "other branch"), rank: 3 } : undefined,
386
+ run.readOnly ? { text: this.theme.fg("muted", "read-only"), rank: 3 } : undefined,
387
+ this.details ? { text: this.theme.fg("accent", "details"), rank: 2 } : undefined,
388
+ newestHidden > 0
389
+ ? { text: this.theme.fg("accent", `↓ ${newestHidden} newer · End`), rank: 6 }
390
+ : undefined,
391
+ ];
392
+
393
+ return (
394
+ fitRanked(
395
+ parts.filter((part) => part !== undefined),
396
+ width,
397
+ (texts) => [title, ...texts].join(this.theme.fg("dim", " · ")),
398
+ ) ?? title
399
+ );
400
+ }
401
+
402
+ /**
403
+ * `Model provider/id · high · auto 82%`, from the live session when there is one. A narrow pane
404
+ * drops the `Model` label, then gives the model its own rows; nothing is cut.
405
+ */
406
+ private modelRows(run: Run, width: number): string[] {
407
+ const model = run.model;
408
+ const thinking = run.thinkingLevel;
409
+
410
+ // A run whose file cannot be read has neither.
411
+ if (model === undefined || thinking === undefined) {
412
+ return [];
413
+ }
414
+
415
+ const label = `${this.theme.fg("muted", "Model")} `;
416
+ const separator = this.theme.fg("dim", " · ");
417
+ const parts = [thinking, ...this.autoMarks(run)];
418
+ const settings = parts.join(separator);
419
+ const row = [
420
+ `${label}${model}${separator}${settings}`,
421
+ `${model}${separator}${settings}`,
422
+ ].find((candidate) => visibleWidth(candidate) <= width);
423
+
424
+ if (row !== undefined) {
425
+ return [row];
426
+ }
427
+
428
+ // The settings go below the model, as many whole parts on a row as fit.
429
+ const rows = [...wrapTextWithAnsi(model, width)];
430
+ let current = "";
431
+
432
+ for (const part of parts) {
433
+ const joined = current === "" ? part : current + separator + part;
434
+
435
+ if (visibleWidth(joined) <= width) {
436
+ current = joined;
437
+ continue;
438
+ }
439
+
440
+ if (current !== "") {
441
+ rows.push(current);
442
+ }
443
+
444
+ current = part;
445
+ }
446
+
447
+ return [...rows, ...wrapTextWithAnsi(current, width)];
448
+ }
449
+
450
+ /**
451
+ * `auto complex 71%`: `model: auto` rated the task complex with that share. An unsure rating
452
+ * moved up a tier shows the tier alone, and a run without a rating shows `auto`. A task rated
453
+ * high risk adds `high risk`.
454
+ */
455
+ private autoMarks(run: Run): string[] {
456
+ const auto = run.snapshot?.autoModel;
457
+
458
+ if (!auto) {
459
+ return [];
460
+ }
461
+
462
+ if (auto.by === "classifier-failed") {
463
+ return [this.theme.fg("warning", "auto failed")];
464
+ }
465
+
466
+ if (auto.by !== "rating") {
467
+ return [this.theme.fg("accent", "auto")];
468
+ }
469
+
470
+ const { tier, risk } = auto;
471
+ const share = tier.used === tier.rated ? tier.probabilities[tier.used] : undefined;
472
+
473
+ return [
474
+ this.theme.fg(
475
+ "accent",
476
+ `auto ${tier.used}${share === undefined ? "" : ` ${formatPercent(share)}`}`,
477
+ ),
478
+ ...(risk?.high ? [this.theme.fg("warning", "high risk")] : []),
479
+ ];
480
+ }
481
+
482
+ private footer(width: number, entry: Entry | undefined): string {
483
+ if (this.chat) {
484
+ const targetWidth = Math.max(0, Math.floor((width - 2) / 2) - 5);
485
+ const target = clipToWidth(entry?.run.title ?? "run", targetWidth);
486
+ const prompt = this.theme.fg("accent", `To ${target}: `);
487
+ const input = this.chat.render(Math.max(1, width - 2 - visibleWidth(prompt)))[0] ?? "";
488
+
489
+ return ` ${prompt}${input}`;
490
+ }
491
+
492
+ if (this.notice) {
493
+ return cell(this.theme.fg(this.notice.color, this.notice.text), width);
494
+ }
495
+
496
+ const hints = [
497
+ "↑↓ run",
498
+ "⇧↑↓ scroll",
499
+ "Home/End",
500
+ "Enter chat",
501
+ "d details",
502
+ "x stop",
503
+ entry?.elsewhere ? "c copy report" : undefined,
504
+ "Esc close",
505
+ ];
506
+
507
+ return cell(
508
+ this.theme.fg("dim", hints.filter((hint) => hint !== undefined).join(" · ")),
509
+ width,
510
+ );
511
+ }
512
+
513
+ private moveSelection(step: number): void {
514
+ const entries = this.entries();
515
+ const index = entries.findIndex((entry) => entry.run.id === this.selectedId);
516
+ const next = entries[Math.min(entries.length - 1, Math.max(0, index + step))];
517
+
518
+ if (next) {
519
+ this.select(next.run.id);
520
+ }
521
+ }
522
+
523
+ private select(runId: string): void {
524
+ if (runId === this.selectedId) {
525
+ return;
526
+ }
527
+
528
+ this.selectedId = runId;
529
+ this.details = false;
530
+ this.viewport.follow();
531
+ this.requestRender();
532
+ }
533
+
534
+ private scroll(step: number): void {
535
+ if (this.viewport.scrollBy(step)) {
536
+ this.requestRender();
537
+ }
538
+ }
539
+
540
+ private startChat(entry: Entry): void {
541
+ const { run } = entry;
542
+
543
+ if (entry.elsewhere) {
544
+ this.showNotice(
545
+ `${run.title} belongs to another branch; switch to it to write to the run.`,
546
+ "warning",
547
+ );
548
+ return;
549
+ }
550
+
551
+ if (run.readOnly) {
552
+ this.showNotice(
553
+ `${run.title} is read-only: it came here through /fork or /clone.`,
554
+ "warning",
555
+ );
556
+ return;
557
+ }
558
+
559
+ const input = new Input({ prompt: "" });
560
+
561
+ input.focused = true;
562
+ input.onSubmit = (value) => {
563
+ this.chat = undefined;
564
+
565
+ if (value.trim() === "") {
566
+ this.requestRender();
567
+ return;
568
+ }
569
+
570
+ this.send(run, value);
571
+ };
572
+ this.chat = input;
573
+ this.requestRender();
574
+ }
575
+
576
+ private send(run: Run, text: string): void {
577
+ this.showNotice(`Sending to ${run.title}…`, "muted");
578
+
579
+ this.manager.send(run, text, "user").then(
580
+ (outcome) => {
581
+ this.showNotice(
582
+ outcome === "steered"
583
+ ? `Sent to ${run.title}; it steers the running turn.`
584
+ : outcome === "deferred"
585
+ ? `Sent to ${run.title}; it starts the next turn.`
586
+ : `Sent to ${run.title}; a new turn started.`,
587
+ "success",
588
+ );
589
+ this.viewport.follow();
590
+ },
591
+ (error: unknown) => this.showError(`Sending to ${run.title} failed`, error),
592
+ );
593
+ }
594
+
595
+ private stop(run: Run): void {
596
+ if (run.state !== "running") {
597
+ this.showNotice(`${run.title} is not running.`, "muted");
598
+ return;
599
+ }
600
+
601
+ if (run.readOnly || !this.manager.isOnBranch(run)) {
602
+ this.showNotice(`${run.title} cannot be stopped from here.`, "warning");
603
+ return;
604
+ }
605
+
606
+ this.showNotice(`Stopping ${run.title}…`, "muted");
607
+ this.manager.stop(run, "user").then(
608
+ () => this.showNotice(`Stopped ${run.title}.`, "success"),
609
+ (error: unknown) => this.showError(`Stopping ${run.title} failed`, error),
610
+ );
611
+ }
612
+
613
+ private copy(entry: Entry): void {
614
+ if (!entry.elsewhere) {
615
+ this.showNotice("Only a run of another branch has a report to copy here.", "muted");
616
+ return;
617
+ }
618
+
619
+ try {
620
+ this.manager.copyReport(entry.run);
621
+ this.showNotice(
622
+ `Copied the last turn of ${entry.run.title} to this branch.`,
623
+ "success",
624
+ );
625
+ } catch (error) {
626
+ this.showError(`Copying ${entry.run.title} failed`, error);
627
+ }
628
+ }
629
+
630
+ /** A failure shows in the footer and stays in Pi's notifications after the panel closes. */
631
+ private showError(prefix: string, error: unknown): void {
632
+ const message = `${prefix}: ${error instanceof Error ? error.message : String(error)}`;
633
+
634
+ this.showNotice(message, "error", ERROR_NOTICE_MS);
635
+ this.ctx.ui.notify(message, "error");
636
+ }
637
+
638
+ private showNotice(text: string, color: ThemeColor, durationMs = NOTICE_MS): void {
639
+ if (this.disposed) {
640
+ return;
641
+ }
642
+
643
+ this.notice = { text: truncateToWidth(displayLine(text), 400), color };
644
+ clearTimeout(this.noticeTimer);
645
+ this.noticeTimer = setTimeout(() => {
646
+ this.notice = undefined;
647
+ this.requestRender();
648
+ }, durationMs);
649
+ this.requestRender();
650
+ }
651
+
652
+ /** A running tool shows its elapsed time, so the panel redraws while the selected run has one. */
653
+ private syncRefreshTimer(selected: Run | undefined): void {
654
+ const running = !this.details && (selected?.runningTools.size ?? 0) > 0;
655
+
656
+ if (running && !this.refreshTimer && !this.disposed) {
657
+ this.refreshTimer = setInterval(() => this.requestRender(), REFRESH_INTERVAL_MS);
658
+ } else if (!running && this.refreshTimer) {
659
+ clearInterval(this.refreshTimer);
660
+ this.refreshTimer = undefined;
661
+ }
662
+ }
663
+ }
664
+
665
+ /** Both parts keep start order, so a row moves only when its run starts or ends a turn. */
666
+ function runningFirst(runs: readonly Run[]): Run[] {
667
+ return [
668
+ ...runs.filter((run) => run.state === "running"),
669
+ ...runs.filter((run) => run.state !== "running"),
670
+ ];
671
+ }
672
+
673
+ interface Entry {
674
+ run: Run;
675
+ /** The run belongs to another branch: read it, copy its report, nothing else. */
676
+ elsewhere: boolean;
677
+ }