@maheidem/pi-delegate 0.2.1 → 0.2.3
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/README.md +11 -0
- package/application.ts +80 -14
- package/config.ts +5 -0
- package/index.ts +22 -1
- package/package.json +1 -1
- package/ui/peek-view.ts +37 -28
- package/ui/running-view.ts +49 -42
package/README.md
CHANGED
|
@@ -118,6 +118,17 @@ Consequences worth internalizing:
|
|
|
118
118
|
than blamed on the provider, and the stderr tail is no longer presented as
|
|
119
119
|
the cause.
|
|
120
120
|
|
|
121
|
+
### Concurrent calls queue (fan-out just works)
|
|
122
|
+
|
|
123
|
+
Models naturally issue several `delegate` calls in one turn. Pi executes
|
|
124
|
+
them truly in parallel; delegate runs **one child at a time** and places
|
|
125
|
+
concurrent calls in a bounded FIFO queue (`queueLimit`, default 3): a 4-way
|
|
126
|
+
fan-out becomes 4 back-to-back children and 4 real results — no error
|
|
127
|
+
storm. Aborting a still-queued call removes it (resolved as `cancelled`,
|
|
128
|
+
never spawned). Beyond the limit the call fails fast with an instructive
|
|
129
|
+
`E_DELEGATE_BUSY` ("wait for the in-flight results, then re-issue").
|
|
130
|
+
`/delegate status` shows the queue depth.
|
|
131
|
+
|
|
121
132
|
### Watching a child work: the live feed and `/delegate peek`
|
|
122
133
|
|
|
123
134
|
- **Foreground `/delegate run` (TUI)** opens a live feed panel: identity
|
package/application.ts
CHANGED
|
@@ -64,6 +64,18 @@ interface ActiveRunReservation {
|
|
|
64
64
|
startedAt: string;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* A concurrent delegate call waiting for the single child slot. Pi executes
|
|
69
|
+
* parallel tool calls truly in parallel and models routinely fan out — the
|
|
70
|
+
* queue serializes those calls on the one-child policy instead of failing
|
|
71
|
+
* them: a 4-way fan-out becomes 4 back-to-back children and 4 real results.
|
|
72
|
+
*/
|
|
73
|
+
interface QueuedRun {
|
|
74
|
+
request: DelegateRequest;
|
|
75
|
+
hooks: RunHooks;
|
|
76
|
+
resolve: (result: RunAttemptResult) => void;
|
|
77
|
+
}
|
|
78
|
+
|
|
67
79
|
function errorResult(
|
|
68
80
|
runId: string,
|
|
69
81
|
role: RoleName,
|
|
@@ -98,6 +110,7 @@ function errorResult(
|
|
|
98
110
|
|
|
99
111
|
export class DelegateApplicationImpl implements DelegateApplication {
|
|
100
112
|
private activeRun: ActiveRunReservation | null = null;
|
|
113
|
+
private runQueue: QueuedRun[] = [];
|
|
101
114
|
private readonly modeRuntime: ModeRuntime;
|
|
102
115
|
private readonly ports: DelegateApplicationPorts;
|
|
103
116
|
private liveConfig: DelegateConfigV1;
|
|
@@ -183,24 +196,57 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
183
196
|
}
|
|
184
197
|
|
|
185
198
|
/**
|
|
186
|
-
* Canonical
|
|
187
|
-
*
|
|
199
|
+
* Canonical entry point shared by tool and command. ONE child executes at
|
|
200
|
+
* a time (POL-005): concurrent calls queue (bounded by `queueLimit`) and
|
|
201
|
+
* run back-to-back — models fan out, and the queue turns that into
|
|
202
|
+
* serialized results instead of an error storm.
|
|
188
203
|
*/
|
|
189
204
|
async run(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
|
|
190
|
-
// 1. Synchronous reservation BEFORE any await.
|
|
191
205
|
if (this.activeRun) {
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
206
|
+
if (this.runQueue.length >= this.liveConfig.queueLimit) {
|
|
207
|
+
return {
|
|
208
|
+
ok: false,
|
|
209
|
+
busy: true,
|
|
210
|
+
runId: this.activeRun.id,
|
|
211
|
+
role: this.activeRun.role,
|
|
212
|
+
message: `Delegation queue is full (${this.runQueue.length} waiting) while run ${this.activeRun.id} (${this.activeRun.role}) executes.`,
|
|
213
|
+
error: {
|
|
214
|
+
code: "E_DELEGATE_BUSY",
|
|
215
|
+
message: `Queue full (${this.runQueue.length} waiting; limit ${this.liveConfig.queueLimit}); active run ${this.activeRun.id} (${this.activeRun.role}). Wait for the in-flight results, then re-issue.`,
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
return await new Promise<RunAttemptResult>((resolve) => {
|
|
220
|
+
const entry: QueuedRun = { request, hooks, resolve };
|
|
221
|
+
// Aborting a STILL-QUEUED call removes it (the runner wires
|
|
222
|
+
// the signal only once spawned); once started, the runner
|
|
223
|
+
// owns cancellation through the same signal.
|
|
224
|
+
const onAbort = () => {
|
|
225
|
+
const idx = this.runQueue.indexOf(entry);
|
|
226
|
+
if (idx >= 0) {
|
|
227
|
+
this.runQueue.splice(idx, 1);
|
|
228
|
+
resolve(
|
|
229
|
+
errorResult("", request.role, "E_CANCELLED", "aborted before start (queued call cancelled)", {
|
|
230
|
+
state: "cancelled",
|
|
231
|
+
}),
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
if (hooks.abortSignal) {
|
|
236
|
+
if (hooks.abortSignal.aborted) {
|
|
237
|
+
onAbort();
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
hooks.abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
241
|
+
}
|
|
242
|
+
this.runQueue.push(entry);
|
|
243
|
+
});
|
|
203
244
|
}
|
|
245
|
+
return await this.startRun(request, hooks);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Execute one run in the free slot (reservation stays synchronous). */
|
|
249
|
+
private async startRun(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
|
|
204
250
|
|
|
205
251
|
const agentDir = this.ports.agentDir;
|
|
206
252
|
// Config cascade: project .pi/delegate/config.json overlays the
|
|
@@ -346,9 +392,29 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
346
392
|
} catch (error) {
|
|
347
393
|
this.activeRun = null;
|
|
348
394
|
return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
|
|
395
|
+
} finally {
|
|
396
|
+
this.startNextQueuedRun();
|
|
349
397
|
}
|
|
350
398
|
}
|
|
351
399
|
|
|
400
|
+
/** Queued-call introspection for status views. */
|
|
401
|
+
queuedRunCount(): number {
|
|
402
|
+
return this.runQueue.length;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
queueLimit(): number {
|
|
406
|
+
return this.liveConfig.queueLimit;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Pop the next queued run (if any) into the free slot, fire-and-forget. */
|
|
410
|
+
private startNextQueuedRun(): void {
|
|
411
|
+
const next = this.runQueue.shift();
|
|
412
|
+
if (!next) return;
|
|
413
|
+
void this.startRun(next.request, next.hooks).then(next.resolve, (error: unknown) => {
|
|
414
|
+
next.resolve(errorResult("", next.request.role, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`));
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
352
418
|
/** Cancel the active run (default) or an exact run ID. */
|
|
353
419
|
async cancel(runId?: string): Promise<CancelResult> {
|
|
354
420
|
const active = this.activeRun;
|
package/config.ts
CHANGED
|
@@ -20,6 +20,8 @@ export interface DelegateConfigV1 {
|
|
|
20
20
|
handoffGraceMs: number;
|
|
21
21
|
/** Bounded wait for the mandatory-handoff enforcement answer (default 60 s). */
|
|
22
22
|
handoffEnforceTimeoutMs: number;
|
|
23
|
+
/** Concurrent calls beyond the active child wait in this FIFO queue. */
|
|
24
|
+
queueLimit: number;
|
|
23
25
|
/** R1: watchdog budget while a tool call is in flight (default: hard). */
|
|
24
26
|
stuckToolTimeoutMs?: number;
|
|
25
27
|
maxRuns: number;
|
|
@@ -37,6 +39,7 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
|
|
|
37
39
|
killGraceMs: 5_000,
|
|
38
40
|
handoffGraceMs: 90_000,
|
|
39
41
|
handoffEnforceTimeoutMs: 60_000,
|
|
42
|
+
queueLimit: 3,
|
|
40
43
|
stuckToolTimeoutMs: undefined,
|
|
41
44
|
maxRuns: 50,
|
|
42
45
|
maxRunAgeDays: 30,
|
|
@@ -51,6 +54,7 @@ const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
|
51
54
|
killGraceMs: 100,
|
|
52
55
|
handoffGraceMs: 1_000,
|
|
53
56
|
handoffEnforceTimeoutMs: 1_000,
|
|
57
|
+
queueLimit: 0,
|
|
54
58
|
stuckToolTimeoutMs: 1_000,
|
|
55
59
|
maxRuns: 1,
|
|
56
60
|
maxRunAgeDays: 1,
|
|
@@ -65,6 +69,7 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
|
65
69
|
killGraceMs: 60_000,
|
|
66
70
|
handoffGraceMs: 600_000,
|
|
67
71
|
handoffEnforceTimeoutMs: 600_000,
|
|
72
|
+
queueLimit: 20,
|
|
68
73
|
stuckToolTimeoutMs: 604_800_000,
|
|
69
74
|
maxRuns: 10_000,
|
|
70
75
|
maxRunAgeDays: 3650,
|
package/index.ts
CHANGED
|
@@ -303,6 +303,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
303
303
|
if (!res.ok) {
|
|
304
304
|
const parts = [head];
|
|
305
305
|
const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
|
|
306
|
+
if (d.state === "cancelled") {
|
|
307
|
+
// A cancellation is user intent, not a failure — neutral line,
|
|
308
|
+
// plus the resume path when a durable session exists.
|
|
309
|
+
parts.push(`cancelled — ${res.error?.message ?? "aborted"}; no handoff.`);
|
|
310
|
+
if (d.sessionPath) parts.push(`resume: re-issue with resumeFrom: ${d.runId} to continue in the same child context.`);
|
|
311
|
+
if (res.details.partialHandoff) parts.push("", "partial handoff (captured at kill):", res.details.partialHandoff);
|
|
312
|
+
if (res.modelNote) parts.push(`note: ${res.modelNote}`);
|
|
313
|
+
parts.push(`transcript: ${d.transcriptPath}`);
|
|
314
|
+
return parts.join("\n");
|
|
315
|
+
}
|
|
306
316
|
parts.push(`error: ${err}`);
|
|
307
317
|
// R2: the killed child's own account of its partial work.
|
|
308
318
|
if (res.details.partialHandoff) {
|
|
@@ -369,6 +379,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
369
379
|
"Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
|
|
370
380
|
"Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
|
|
371
381
|
"Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
|
|
382
|
+
"Parallel delegate calls are fine: they queue and run back-to-back (one child at a time) — every call gets a real result; do not re-issue on 'queue full', wait for the in-flight results instead.",
|
|
372
383
|
"A timed-out run leaves a partialHandoff, a git checkpoint and a resumable child session: pass resumeFrom: <runId> to continue in the same context instead of re-explaining, and inspect the receipt's gitDelta before repairing anything.",
|
|
373
384
|
"Pin model: 'provider/model-id' when the child must not silently follow the parent's current model (e.g. after a mid-session model fallback).",
|
|
374
385
|
"For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
|
|
@@ -513,7 +524,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
513
524
|
return renderFeedEvents([...feed.all()], {
|
|
514
525
|
startMs: feedStartMs || Date.now(),
|
|
515
526
|
maxChars: 150,
|
|
516
|
-
maxEvents:
|
|
527
|
+
maxEvents: 6,
|
|
517
528
|
});
|
|
518
529
|
};
|
|
519
530
|
const runPromise = app.run(request, {
|
|
@@ -602,6 +613,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
602
613
|
const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
|
|
603
614
|
lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
|
|
604
615
|
lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
|
|
616
|
+
const queued = app.queuedRunCount();
|
|
617
|
+
lines.push(`queue: ${queued} waiting (concurrent calls serialize; limit ${app.queueLimit()})`);
|
|
605
618
|
if (s.lastRun) {
|
|
606
619
|
const dur = s.lastRun.durationMs != null ? `${Math.round(s.lastRun.durationMs / 1000)}s` : "";
|
|
607
620
|
lines.push(`last run: ${s.lastRun.runId} ${s.lastRun.role} ${s.lastRun.state} ${dur}`.trimEnd());
|
|
@@ -766,6 +779,14 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
766
779
|
const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
|
|
767
780
|
timer = setInterval(() => tui.requestRender(), 1000);
|
|
768
781
|
return view;
|
|
782
|
+
}, {
|
|
783
|
+
overlay: true,
|
|
784
|
+
overlayOptions: {
|
|
785
|
+
width: "92%",
|
|
786
|
+
minWidth: 60,
|
|
787
|
+
maxHeight: "80%",
|
|
788
|
+
anchor: "center",
|
|
789
|
+
},
|
|
769
790
|
});
|
|
770
791
|
} else {
|
|
771
792
|
const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
|
package/package.json
CHANGED
package/ui/peek-view.ts
CHANGED
|
@@ -26,6 +26,11 @@ export interface PeekViewHost {
|
|
|
26
26
|
done(result: { closed?: boolean }): void;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
/** Fixed overlay height — rows never change between frames (smear guard). */
|
|
30
|
+
const PEEK_ROWS = 20;
|
|
31
|
+
/** Content rows inside the fixed frame (top + summary + status + bottom = 4). */
|
|
32
|
+
const CONTENT_ROWS = PEEK_ROWS - 4;
|
|
33
|
+
|
|
29
34
|
export class PeekView implements Component {
|
|
30
35
|
private readonly host: PeekViewHost;
|
|
31
36
|
private offsetFromEnd = 0;
|
|
@@ -44,11 +49,12 @@ export class PeekView implements Component {
|
|
|
44
49
|
(kb?.matches?.(data, "tui.select.cancel") ?? false) ||
|
|
45
50
|
matchesKey(data, "escape") ||
|
|
46
51
|
matchesKey(data, "q");
|
|
52
|
+
const maxOffset = Math.max(0, this.host.state().lines.length - CONTENT_ROWS);
|
|
47
53
|
if (cancel) {
|
|
48
54
|
this.host.done({ closed: true });
|
|
49
55
|
} else if (up) {
|
|
50
56
|
this.following = false;
|
|
51
|
-
this.offsetFromEnd
|
|
57
|
+
this.offsetFromEnd = Math.min(maxOffset, this.offsetFromEnd + 1);
|
|
52
58
|
} else if (down) {
|
|
53
59
|
this.offsetFromEnd = Math.max(0, this.offsetFromEnd - 1);
|
|
54
60
|
if (this.offsetFromEnd === 0) this.following = true;
|
|
@@ -66,43 +72,46 @@ export class PeekView implements Component {
|
|
|
66
72
|
const s = this.host.state();
|
|
67
73
|
const theme = this.host.theme;
|
|
68
74
|
const w = Math.max(1, Math.floor(width));
|
|
69
|
-
const fg = (kind: ThemeColor, text: string) => (theme?.fg ? theme.fg(kind, text) : text);
|
|
70
|
-
const title = ` Peek · ${s.title} `;
|
|
71
|
-
const top = `╭─${truncateToWidth(title, Math.max(4, w - 4))}${"─".repeat(Math.max(0, w - 3 - Math.min(title.length, Math.max(4, w - 4))))}─╮`;
|
|
72
|
-
const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`;
|
|
73
75
|
const inner = Math.max(1, w - 4);
|
|
76
|
+
|
|
77
|
+
// Borders stay UNSTYLED so Pi's per-frame width/clear math is exact;
|
|
78
|
+
// color is applied to inner text only.
|
|
79
|
+
const title = truncateToWidth(` Peek · ${s.title} `, Math.max(4, w - 4));
|
|
80
|
+
const top = truncateToWidth(`╭─${title}${"─".repeat(Math.max(0, w - 2 - title.length - 1))}╮`, w);
|
|
81
|
+
const bottom = truncateToWidth(`╰${"─".repeat(Math.max(0, w - 2))}╯`, w);
|
|
74
82
|
const pad = (text: string, color?: ThemeColor) => {
|
|
75
|
-
const
|
|
76
|
-
return
|
|
83
|
+
const body = color && theme?.fg ? theme.fg(color, truncateToWidth(text, inner)) : truncateToWidth(text, inner);
|
|
84
|
+
return `│ ${body} │`;
|
|
77
85
|
};
|
|
78
86
|
|
|
79
|
-
//
|
|
80
|
-
|
|
87
|
+
// Fixed-height viewport: exactly CONTENT_ROWS, newest at the bottom
|
|
88
|
+
// (blank-padded at the top) so the frame height never changes.
|
|
81
89
|
const total = s.lines.length;
|
|
82
90
|
if (total !== this.lastLineCount && this.following) this.offsetFromEnd = 0;
|
|
83
91
|
this.lastLineCount = total;
|
|
84
|
-
const
|
|
85
|
-
|
|
92
|
+
const maxOffset = Math.max(0, total - CONTENT_ROWS);
|
|
93
|
+
if (this.offsetFromEnd > maxOffset) this.offsetFromEnd = maxOffset;
|
|
94
|
+
const end = total - this.offsetFromEnd;
|
|
95
|
+
const start = Math.max(0, end - CONTENT_ROWS);
|
|
86
96
|
const window = s.lines.slice(start, end);
|
|
97
|
+
const content = [...Array<string>(Math.max(0, CONTENT_ROWS - window.length)).fill(""), ...window];
|
|
98
|
+
|
|
99
|
+
const counts = [start > 0 ? `↑${start}` : "", end < total ? `↓${total - end}` : ""].filter(Boolean).join(" ");
|
|
100
|
+
const status = s.live
|
|
101
|
+
? `● live — following · j/k scroll · f re-follow · q close${counts ? ` · ${counts}` : ""}`
|
|
102
|
+
: `final — ${total} event(s) · j/k scroll · q close${counts ? ` · ${counts}` : ""}`;
|
|
87
103
|
|
|
88
104
|
const lines: string[] = [
|
|
89
|
-
|
|
90
|
-
pad(s.summary, "muted"),
|
|
91
|
-
pad(
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
: `final — ${total} events (j/k scroll, q close)`,
|
|
95
|
-
s.live ? "success" : "dim",
|
|
96
|
-
),
|
|
105
|
+
top,
|
|
106
|
+
pad(truncateToWidth(s.summary, inner), "muted"),
|
|
107
|
+
pad(status, s.live ? "success" : "dim"),
|
|
108
|
+
...content.map((l) => pad(l, l ? "text" : undefined)),
|
|
109
|
+
bottom,
|
|
97
110
|
];
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
if (end < total) lines.push(pad(`… ${total - end} newer event(s) — k to scroll down`, "dim"));
|
|
104
|
-
}
|
|
105
|
-
lines.push(truncateToWidth(bottom, w));
|
|
106
|
-
return lines.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
|
|
111
|
+
|
|
112
|
+
// Belt-and-braces: exact height, exact width.
|
|
113
|
+
const clipped = lines.slice(0, PEEK_ROWS);
|
|
114
|
+
while (clipped.length < PEEK_ROWS) clipped.splice(clipped.length - 1, 0, pad(""));
|
|
115
|
+
return clipped.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
|
|
107
116
|
}
|
|
108
117
|
}
|
package/ui/running-view.ts
CHANGED
|
@@ -4,8 +4,14 @@
|
|
|
4
4
|
* A window into the running child: identity + budgets header, elapsed-vs-hard
|
|
5
5
|
* progress, in-flight tools, and a bounded scrolling feed of the child's
|
|
6
6
|
* activity (tool starts/ends, assistant lines, provider errors, handoff).
|
|
7
|
-
*
|
|
8
|
-
* (
|
|
7
|
+
*
|
|
8
|
+
* RENDER CONTRACT (hard-won): this runs as an inline `ctx.ui.custom`
|
|
9
|
+
* component, which REPLACES the composer region while a run is active. The
|
|
10
|
+
* panel MUST render a FIXED number of rows every frame — a height that
|
|
11
|
+
* changes between refreshes smears the previous frame over the input bar.
|
|
12
|
+
* So: constant height, blank-padded, and color ONLY inner text (never the
|
|
13
|
+
* border/padding structure, whose width Pi recomputes every frame).
|
|
14
|
+
* Cancels via Escape twice (armed). Refresh cadence is owned by the host.
|
|
9
15
|
*/
|
|
10
16
|
|
|
11
17
|
import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
|
|
@@ -25,7 +31,7 @@ export interface RunningViewState {
|
|
|
25
31
|
tokens?: { input?: number; output?: number };
|
|
26
32
|
/** Tools currently in flight. */
|
|
27
33
|
openTools?: string[];
|
|
28
|
-
/** Pre-formatted feed lines (newest last)
|
|
34
|
+
/** Pre-formatted feed lines (newest last); the panel slices/pads itself. */
|
|
29
35
|
feedLines: string[];
|
|
30
36
|
}
|
|
31
37
|
|
|
@@ -36,6 +42,11 @@ export interface RunningViewHost {
|
|
|
36
42
|
done(result: { cancelled?: boolean }): void;
|
|
37
43
|
}
|
|
38
44
|
|
|
45
|
+
/** Constant panel height (top + header + progress + in-flight + FEED + footer + bottom). */
|
|
46
|
+
const PANEL_ROWS = 9;
|
|
47
|
+
/** Feed rows inside the fixed frame; the rest are the fixed scaffold. */
|
|
48
|
+
const FEED_ROWS = PANEL_ROWS - 5;
|
|
49
|
+
|
|
39
50
|
function fmtDuration(ms: number): string {
|
|
40
51
|
const s = Math.max(0, Math.round(ms / 1000));
|
|
41
52
|
if (s < 60) return `${s}s`;
|
|
@@ -82,66 +93,62 @@ export class RunningView implements Component {
|
|
|
82
93
|
const s = this.host.state();
|
|
83
94
|
const theme = this.host.theme;
|
|
84
95
|
const w = Math.max(1, Math.floor(width));
|
|
85
|
-
const title = " Delegating ";
|
|
86
|
-
const border = "─".repeat(Math.max(0, w - title.length - 2));
|
|
87
|
-
const top = `╭─${title}${border.slice(0, Math.max(0, border.length))}─╮`.slice(0, w);
|
|
88
|
-
const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`.slice(0, w);
|
|
89
96
|
const inner = Math.max(1, w - 4);
|
|
97
|
+
|
|
98
|
+
// Borders stay UNSTYLED so Pi's per-frame width/clear math is exact;
|
|
99
|
+
// color is applied to inner text only.
|
|
100
|
+
const title = " Delegating ";
|
|
101
|
+
const fill = Math.max(0, w - 2 - title.length - 2);
|
|
102
|
+
const top = truncateToWidth(`╭─${title}${"─".repeat(fill + 1)}╮`, w);
|
|
103
|
+
const bottom = truncateToWidth(`╰${"─".repeat(Math.max(0, w - 2))}╯`, w);
|
|
90
104
|
const pad = (text: string, color?: ThemeColor) => {
|
|
91
|
-
const
|
|
92
|
-
return
|
|
105
|
+
const body = color && theme?.fg ? theme.fg(color, truncateToWidth(text, inner)) : truncateToWidth(text, inner);
|
|
106
|
+
return `│ ${body} │`;
|
|
93
107
|
};
|
|
94
|
-
|
|
95
108
|
const fg = (kind: ThemeColor, text: string) => (theme?.fg ? theme.fg(kind, text) : text);
|
|
96
|
-
const lines: string[] = [top];
|
|
97
109
|
|
|
98
|
-
//
|
|
110
|
+
// Fixed scaffold rows — always exactly PANEL_ROWS - 2 inner rows.
|
|
99
111
|
const head = [
|
|
100
112
|
s.role,
|
|
101
113
|
s.model,
|
|
102
|
-
|
|
114
|
+
fmtDuration(s.elapsedMs),
|
|
103
115
|
...(s.turns !== undefined ? [`turn ${s.turns}`] : []),
|
|
104
116
|
...(s.tokens ? [`↑${fmtTokens(s.tokens.input)} ↓${fmtTokens(s.tokens.output)}`] : []),
|
|
105
117
|
]
|
|
106
118
|
.filter(Boolean)
|
|
107
119
|
.join(" · ");
|
|
108
|
-
lines.push(pad(head));
|
|
109
120
|
|
|
110
|
-
|
|
121
|
+
let progress = "running…";
|
|
111
122
|
if (s.hardMs && s.hardMs > 0) {
|
|
112
123
|
const frac = Math.min(1, s.elapsedMs / s.hardMs);
|
|
113
124
|
const barWidth = Math.max(4, Math.min(inner - 14, 24));
|
|
114
125
|
const filled = Math.round(frac * barWidth);
|
|
115
|
-
|
|
116
|
-
lines.push(pad(`${bar} ${Math.round(frac * 100)}% of ${fmtDuration(s.hardMs)} hard`));
|
|
126
|
+
progress = `${"█".repeat(filled)}${"░".repeat(Math.max(0, barWidth - filled))} ${Math.round(frac * 100)}% of ${fmtDuration(s.hardMs)} hard`;
|
|
117
127
|
}
|
|
118
128
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
lines.push(pad(fg("warning", `in flight: ${s.openTools.join(", ")}`)));
|
|
122
|
-
}
|
|
129
|
+
const openTools = s.openTools ?? [];
|
|
130
|
+
const inFlight = openTools.length > 0 ? `in flight: ${openTools.join(", ")}` : "";
|
|
123
131
|
|
|
124
|
-
// Feed: newest last
|
|
125
|
-
const
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
+
// Feed: newest last, right-aligned in a fixed block (blank-padded on top).
|
|
133
|
+
const feed = s.feedLines.slice(-FEED_ROWS);
|
|
134
|
+
const feedRows: string[] = [...Array<string>(Math.max(0, FEED_ROWS - feed.length)).fill(""), ...feed];
|
|
135
|
+
|
|
136
|
+
const footer = this.cancelArmed ? fg("error", "ESC again: CONFIRM cancel") : "esc/q cancel (press twice)";
|
|
137
|
+
|
|
138
|
+
// Assemble a fixed-height body: header, progress, in-flight, feed block, footer.
|
|
139
|
+
const body: Array<[string, ThemeColor?]> = [
|
|
140
|
+
[head],
|
|
141
|
+
[progress, "accent"],
|
|
142
|
+
[inFlight, inFlight ? "warning" : undefined],
|
|
143
|
+
...feedRows.map((l): [string, ThemeColor?] => [l, l ? "text" : undefined]),
|
|
144
|
+
[footer, this.cancelArmed ? "error" : "dim"],
|
|
145
|
+
];
|
|
146
|
+
|
|
147
|
+
const lines: string[] = [top, ...body.map(([t, c]) => pad(t, c)), bottom];
|
|
132
148
|
|
|
133
|
-
//
|
|
134
|
-
lines.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
? fg("error", "ESC again: CONFIRM cancel")
|
|
138
|
-
: "esc/q cancel (press twice)",
|
|
139
|
-
this.cancelArmed ? "error" : "dim",
|
|
140
|
-
),
|
|
141
|
-
);
|
|
142
|
-
lines.push(bottom);
|
|
143
|
-
|
|
144
|
-
// Width safety: hard-clip rather than corrupt layout.
|
|
145
|
-
return lines.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
|
|
149
|
+
// Belt-and-braces: hard-clip to the exact height and width.
|
|
150
|
+
const clipped = lines.slice(0, PANEL_ROWS);
|
|
151
|
+
while (clipped.length < PANEL_ROWS) clipped.splice(clipped.length - 1, 0, pad(""));
|
|
152
|
+
return clipped.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
|
|
146
153
|
}
|
|
147
154
|
}
|