@maheidem/pi-delegate 0.2.2 → 0.3.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/README.md CHANGED
@@ -45,6 +45,38 @@ is performed by this package.
45
45
 
46
46
  Any unrecognized first word is shorthand for `run general …`.
47
47
 
48
+ ### Terminal UI (v0.3.0)
49
+
50
+ One centralized experience built on the vendored canonical `SettingsPanel`
51
+ (never a bespoke panel). Everything reachable from the panel is also reachable
52
+ as a nested command and from headless stdout — the same application method.
53
+
54
+ - **Home dashboard** (`/delegate`, TUI) — health summary (version · mode,
55
+ active/idle, last run) + **Actions** (Run general/research, Peek, Cancel,
56
+ Resume, strict toggle, `Configure advanced… ›`, Doctor, Paths) + base
57
+ **Timeouts** (user & project). Keys: `↑↓/jk` move, `enter` select, `esc/q`
58
+ close; shortcuts `r run · p peek · x cancel · c configure · d doctor · s status`.
59
+ - **Live dashboard** — while a run is active the home panel mirrors it live
60
+ (`refresh` 1 s): phase · short model · fixed progress bar · tokens
61
+ `↑in ↓out` (primary) · `$cost` (secondary, dim) · in-flight tools · tail.
62
+ - **Inline execution (both paths).** Slash path shows a fixed-height strip
63
+ above the composer (`RunningView`) with progress, in-flight and a feed; the
64
+ model path renders the same liveness through the tool's `renderCall` /
65
+ `renderResult`. Terminal results render as a neutral card — `✓ done`,
66
+ `⊘ cancelled`, `⏱ timeout · idle/hard`, `✗ failed` — glyph+word (never a
67
+ bare `error:`), tokens primary, with a partial-handoff tail + resume hint
68
+ on cancel/timeout.
69
+ - **Peek** (`/delegate peek [runId]`) — detailed fixed-height overlay
70
+ (`PeekView`, full model id, relative-stamped event feed); `q` returns home.
71
+ - **Advanced config** (`Configure advanced… ›`) — queue limit, stuck-tool
72
+ watchdog, kill/handoff grace/enforce, max task/result bytes, default role —
73
+ edited through the same generic `patchConfig`; `esc` returns home.
74
+ - **Destructive actions** (cancel, strict on/off) require confirmation.
75
+
76
+ Headless (`pi -p` / child mode) prints the same status/doctor/paths text, so
77
+ panel ≡ command ≡ headless. Screens with pixel evidence live in
78
+ `.planning/ui-redesign-2026-09-04/evidence/` (see `manifest.json`).
79
+
48
80
  ### Timeouts
49
81
 
50
82
  Three levels, highest priority first:
package/application.ts CHANGED
@@ -30,9 +30,11 @@ import type {
30
30
  RunInspection,
31
31
  RunMetadataV1,
32
32
  RunnerOutcome,
33
+ RunStreamUpdate,
33
34
  TranscriptRecordV1,
34
35
  SessionEntryLike,
35
36
  } from "./types.ts";
37
+ import { FeedRing, type FeedEvent } from "./transcript-feed.ts";
36
38
  import { decodeTranscriptRecord } from "./types.ts";
37
39
  import { applyProjectOverlay, clampConfigField, formatDuration, normalizeConfig, parseDuration, projectConfigPath, resolveRunTimeouts, saveConfig, saveProjectConfig, type DelegateConfigV1 } from "./config.ts";
38
40
  import { EMPTY_USAGE } from "./types.ts";
@@ -62,6 +64,8 @@ interface ActiveRunReservation {
62
64
  role: RoleName;
63
65
  runner: DelegateRunner;
64
66
  startedAt: string;
67
+ /** Effective hard cap for the live progress bar (§ S2). */
68
+ hardMs: number;
65
69
  }
66
70
 
67
71
  /**
@@ -110,6 +114,9 @@ function errorResult(
110
114
 
111
115
  export class DelegateApplicationImpl implements DelegateApplication {
112
116
  private activeRun: ActiveRunReservation | null = null;
117
+ /** Live state of the active run, captured for the home dashboard (§ S2). */
118
+ private activeStream: RunStreamUpdate | null = null;
119
+ private activeRing: FeedRing = new FeedRing(120);
113
120
  private runQueue: QueuedRun[] = [];
114
121
  private readonly modeRuntime: ModeRuntime;
115
122
  private readonly ports: DelegateApplicationPorts;
@@ -195,6 +202,31 @@ export class DelegateApplicationImpl implements DelegateApplication {
195
202
  return { runId: this.activeRun.id, role: this.activeRun.role, startedAt: this.activeRun.startedAt };
196
203
  }
197
204
 
205
+ /** Live state of the active run (identity update + feed events + queue),
206
+ * for the home dashboard's Live block. Null when nothing is running. */
207
+ getActiveRunStream(): { update: RunStreamUpdate; events: readonly FeedEvent[]; queue: number; hardMs: number } | null {
208
+ if (!this.activeRun || !this.activeStream) return null;
209
+ return { update: this.activeStream, events: this.activeRing.all(), queue: this.runQueue.length, hardMs: this.activeRun.hardMs };
210
+ }
211
+
212
+ /** Advanced knobs for the dashboard's Configure-advanced screen (§ S7). */
213
+ panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "maxRuns" | "maxRunAgeDays"> {
214
+ const c = this.liveConfig;
215
+ return {
216
+ queueLimit: c.queueLimit,
217
+ killGraceMs: c.killGraceMs,
218
+ handoffGraceMs: c.handoffGraceMs,
219
+ handoffEnforceTimeoutMs: c.handoffEnforceTimeoutMs,
220
+ stuckToolTimeoutMs: c.stuckToolTimeoutMs,
221
+ maxTaskBytes: c.maxTaskBytes,
222
+ maxResultBytes: c.maxResultBytes,
223
+ updateThrottleMs: c.updateThrottleMs,
224
+ defaultRole: c.defaultRole,
225
+ maxRuns: c.maxRuns,
226
+ maxRunAgeDays: c.maxRunAgeDays,
227
+ };
228
+ }
229
+
198
230
  /**
199
231
  * Canonical entry point shared by tool and command. ONE child executes at
200
232
  * a time (POL-005): concurrent calls queue (bounded by `queueLimit`) and
@@ -351,6 +383,20 @@ export class DelegateApplicationImpl implements DelegateApplication {
351
383
  }
352
384
 
353
385
  // 8. Reservation NOW covers the child lifecycle.
386
+ // Capture live state for the home dashboard while forwarding the caller's hooks.
387
+ this.activeStream = null;
388
+ this.activeRing = new FeedRing(120);
389
+ const captureHooks: RunHooks = {
390
+ ...hooks,
391
+ onUpdate: (u: RunStreamUpdate) => {
392
+ this.activeStream = u;
393
+ hooks.onUpdate?.(u);
394
+ },
395
+ onEvent: (e: FeedEvent) => {
396
+ this.activeRing.push(e);
397
+ hooks.onEvent?.(e);
398
+ },
399
+ };
354
400
  const runner = new DelegateRunner(
355
401
  opened,
356
402
  {
@@ -368,7 +414,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
368
414
  ...(sessionDir ? { sessionDir } : {}),
369
415
  },
370
416
  cfg,
371
- hooks,
417
+ captureHooks,
372
418
  this.ports.resolveInvocation ?? resolvePiInvocation,
373
419
  );
374
420
  const reservation: ActiveRunReservation = {
@@ -376,6 +422,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
376
422
  role: role.name,
377
423
  runner,
378
424
  startedAt: opened.metadata.createdAt,
425
+ hardMs: timeouts.hardMs,
379
426
  };
380
427
  this.activeRun = reservation;
381
428
 
package/commands.ts CHANGED
@@ -43,7 +43,7 @@ export const DELEGATE_USAGE = [
43
43
  "/delegate help this help",
44
44
  ].join("\n");
45
45
 
46
- const RESERVED_FIRST_TOKENS = new Set([
46
+ export const RESERVED_FIRST_TOKENS = new Set([
47
47
  "on",
48
48
  "off",
49
49
  "status",
@@ -163,8 +163,8 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
163
163
  if (id.startsWith(p)) matches.push(`${id} `);
164
164
  }
165
165
  }
166
- // De-duplicate, keep order, cap for the TUI.
167
- return [...new Set(matches)].slice(0, 10);
166
+ // De-duplicate, keep order, cap for the TUI (all primary verbs fit).
167
+ return [...new Set(matches)].slice(0, 14);
168
168
  }
169
169
 
170
170
  /**
package/index.ts CHANGED
@@ -38,7 +38,8 @@ import type {
38
38
  RunStreamUpdate,
39
39
  SessionEntryLike,
40
40
  } from "./types.ts";
41
- import { SettingsPanel, type PanelSnapshot, type PanelActionResult } from "./ui/settings-panel.ts";
41
+ import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "./ui/settings-panel.ts";
42
+ import { shortModel, formatTokens, formatCost, stateGlyph, progressBar } from "./ui/format.ts";
42
43
  import { RunningView, type RunningViewState } from "./ui/running-view.ts";
43
44
  import { PeekView } from "./ui/peek-view.ts";
44
45
  import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
@@ -408,9 +409,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
408
409
  const hooks = {
409
410
  abortSignal: signal ?? undefined,
410
411
  onUpdate: (u: RunStreamUpdate) => {
411
- const modelBit = u.model ? ` · ${u.model}` : "";
412
+ const head = `[delegate v${delegateVersion()} ${shortModel(u.model) || u.role} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]`;
413
+ const tail = (u.lastActions ?? []).slice(-2).map((l) => ` ${l}`);
412
414
  onUpdate?.({
413
- content: [{ type: "text", text: `[delegate v${delegateVersion()} ${u.runId} · ${u.role}${modelBit} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
415
+ content: [{ type: "text", text: tail.length ? `${head}\n${tail.join("\n")}` : head }],
414
416
  details: { runId: u.runId, phase: u.phase },
415
417
  });
416
418
  },
@@ -435,7 +437,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
435
437
  renderCall(args: any, theme: any) {
436
438
  const role = typeof args.role === "string" ? args.role : config.defaultRole;
437
439
  const task = typeof args.task === "string" ? args.task : "";
438
- const text = `delegate(${role}): ${task.length > 70 ? `${task.slice(0, 67)}…` : task}`;
440
+ const modelBit = typeof args.model === "string" && args.model ? ` · ${shortModel(args.model)}` : "";
441
+ const text = `→ delegate · ${role}${modelBit}: ${task.length > 64 ? `${task.slice(0, 61)}…` : task}`;
439
442
  return new Text(theme?.fg ? theme.fg("accent", text) : text, 0, 0);
440
443
  },
441
444
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -446,22 +449,31 @@ export default function delegateExtension(pi: ExtensionAPI) {
446
449
  return new Text(text || "(no output)", 0, 0);
447
450
  }
448
451
  const fg = (kind: string, s: string) => (theme?.fg ? theme.fg(kind, s) : s);
449
- const u = d.usage ?? {};
450
- const bits: string[] = [`${d.role ?? "?"} · ${d.state ?? "?"}`];
451
- if (u.input) bits.push(`↑${u.input}`);
452
- if (u.output) bits.push(`↓${u.output}`);
453
- if (u.cost) bits.push(`$${u.cost.toFixed(4)}`);
454
- const header = `→ ${d.runId}`;
452
+ const u = d.usage ?? ({} as DelegateDetails["usage"]);
453
+ // Neutral, non-color-alone state word (cancelled ≠ failed ≠ timeout).
454
+ const g = stateGlyph(d.state);
455
+ const bits: string[] = [`${d.role} ${g.glyph} ${g.word}`, `${Math.round(d.durationMs / 1000)}s`];
456
+ if (d.model) bits.push(shortModel(d.model));
457
+ bits.push(`↑${formatTokens(u.input)} ↓${formatTokens(u.output)}`);
458
+ if (u.cost) bits.push(formatCost(u.cost));
459
+ const header = `→ ${d.runId.slice(-16)}`;
460
+ const color = g.color;
455
461
  if (!options?.expanded) {
456
- const body = bits.join(" ") + (d.outputTruncated && d.transcriptPath ? `\ntranscript: ${d.transcriptPath}` : "");
457
- return new Text(`${fg("accent", header)}\n${body}`, 0, 0);
462
+ const lines = [fg("accent", header), fg(color, bits.join(" "))];
463
+ // Inline tail ≤5 — partial handoff (timeout/cancel) or reason, never bare.
464
+ const tailSrc: string = d.partialHandoff ?? (d.state === "succeeded" ? "" : (result.content ?? []).map((c: { text?: string }) => c.text ?? "").join(" ").split("\n")[0] ?? "");
465
+ const tail = tailSrc ? tailSrc.split("\n").map((l: string) => l.trim()).filter(Boolean).slice(0, 5) : [];
466
+ for (const t of tail) lines.push(fg("muted", ` ${t}`));
467
+ if (d.outputTruncated && d.transcriptPath) lines.push(fg("muted", ` transcript: ${d.transcriptPath}`));
468
+ return new Text(lines.join("\n"), 0, 0);
458
469
  }
459
- // Expanded: compact summary — Outcome + key lines + last actions.
460
- const res = result as unknown as DelegateRunResult;
461
- const summary = formatRunSummary(res);
462
- const stateColor = d.state === "succeeded" ? "success" : d.state === "cancelled" ? "muted" : "warning";
463
- const body = bits.join(" ") + (summary ? `\n${summary}` : "");
464
- return new Text(`${fg("accent", header)}\n${fg(stateColor, body)}`, 0, 0);
470
+ // Expanded: identity + canonical summary + resume hint.
471
+ const summary = formatRunSummary(result as unknown as DelegateRunResult);
472
+ const lines = [fg("accent", header), fg(color, bits.join(" "))];
473
+ if (summary) for (const l of summary.split("\n")) lines.push(l);
474
+ if (d.sessionPath && d.state !== "succeeded") lines.push(fg("muted", ` resume: resumeFrom ${d.runId}`));
475
+ if (d.transcriptPath) lines.push(fg("muted", ` transcript: ${d.transcriptPath}`));
476
+ return new Text(lines.join("\n"), 0, 0);
465
477
  },
466
478
  });
467
479
 
@@ -524,7 +536,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
524
536
  return renderFeedEvents([...feed.all()], {
525
537
  startMs: feedStartMs || Date.now(),
526
538
  maxChars: 150,
527
- maxEvents: 14,
539
+ maxEvents: 6,
528
540
  });
529
541
  };
530
542
  const runPromise = app.run(request, {
@@ -741,55 +753,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
741
753
  say(ctx, "[delegate] no runs to peek at.", "warning");
742
754
  return;
743
755
  }
744
- let meta;
745
- try {
746
- meta = app.inspect(id).metadata;
747
- } catch {
748
- say(ctx, `[delegate] unknown run '${id}'.`, "error");
749
- return;
750
- }
751
- if (!fsSync.existsSync(meta.transcriptPath)) {
752
- say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
753
- return;
754
- }
755
- if (ctx.mode === "tui") {
756
- await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
757
- const state = () => {
758
- let live = false;
759
- try {
760
- live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
761
- } catch {
762
- live = false;
763
- }
764
- const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
765
- return {
766
- title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${meta.model}` : ""} · ${meta.state}`,
767
- summary: meta.transcriptPath,
768
- lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
769
- live,
770
- };
771
- };
772
- // Live-follow refresh timer; cleared the moment the
773
- // overlay closes (done wrapper) — never leaks.
774
- let timer: ReturnType<typeof setInterval> | undefined;
775
- const wrappedDone = (result: { closed?: boolean }) => {
776
- if (timer) clearInterval(timer);
777
- done(result);
778
- };
779
- const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
780
- timer = setInterval(() => tui.requestRender(), 1000);
781
- return view;
782
- });
783
- } else {
784
- const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
785
- const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
786
- say(
787
- ctx,
788
- `[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`,
789
- );
790
- }
756
+ await openPeek(ctx, id);
791
757
  return;
792
758
  }
759
+
793
760
  case "resume": {
794
761
  const runId = intent.runId?.trim();
795
762
  if (!runId || !intent.task) {
@@ -816,72 +783,200 @@ export default function delegateExtension(pi: ExtensionAPI) {
816
783
 
817
784
  // ── Dashboard (§12.2) ───────────────────────────────────────────────────
818
785
 
786
+ // ── 5b. Unified peek (shared by slash `peek` + dashboard `peek`) ────────
787
+
788
+ const openPeek = async (ctx: ExtensionCommandContext, runId?: string): Promise<void> => {
789
+ const id = runId?.trim() || app.mostRecentRunId();
790
+ if (!id) {
791
+ say(ctx, "[delegate] no runs to peek at.", "warning");
792
+ return;
793
+ }
794
+ let meta;
795
+ try {
796
+ meta = app.inspect(id).metadata;
797
+ } catch {
798
+ say(ctx, `[delegate] unknown run '${id}'.`, "error");
799
+ return;
800
+ }
801
+ if (!fsSync.existsSync(meta.transcriptPath)) {
802
+ say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
803
+ return;
804
+ }
805
+ if (ctx.mode === "tui") {
806
+ await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
807
+ const state = () => {
808
+ let live = false;
809
+ try {
810
+ live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
811
+ } catch {
812
+ live = false;
813
+ }
814
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
815
+ return {
816
+ title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${shortModel(meta.model)}` : ""} · ${meta.state}`,
817
+ summary: meta.transcriptPath,
818
+ lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
819
+ live,
820
+ };
821
+ };
822
+ // Live-follow refresh timer; cleared the moment the overlay
823
+ // closes (done wrapper) — never leaks past `q`/esc.
824
+ let timer: ReturnType<typeof setInterval> | undefined;
825
+ const wrappedDone = (result: { closed?: boolean }) => {
826
+ if (timer) clearInterval(timer);
827
+ done(result);
828
+ };
829
+ const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
830
+ timer = setInterval(() => tui.requestRender(), 1000);
831
+ return view;
832
+ }, {
833
+ overlay: true,
834
+ overlayOptions: { width: "92%", minWidth: 60, maxHeight: "80%", anchor: "center" },
835
+ });
836
+ } else {
837
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
838
+ const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
839
+ say(ctx, `[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`);
840
+ }
841
+ };
842
+
843
+ // ── 5c. Advanced configuration (secondary screen, opened from home) ──────
844
+
845
+ const openAdvanced = async (ctx: ExtensionCommandContext, projectRoot: string): Promise<void> => {
846
+ const buildRows = (): PanelRow[] => {
847
+ const c = app.panelConfig();
848
+ return [
849
+ { key: "cfg:user:queueLimit", label: "Queue limit", value: String(c.queueLimit), rawValue: String(c.queueLimit), kind: "input", inputHint: "concurrent calls that wait (1–10)" },
850
+ { key: "cfg:user:stuckToolTimeoutMs", label: "Stuck-tool watchdog", value: c.stuckToolTimeoutMs != null ? formatDuration(c.stuckToolTimeoutMs) : "hard (default)", rawValue: c.stuckToolTimeoutMs != null ? String(c.stuckToolTimeoutMs) : "", kind: "input", inputHint: "idle budget while a tool runs; leave hard blank to inherit" },
851
+ { key: "cfg:user:killGraceMs", label: "Kill grace", value: formatDuration(c.killGraceMs), rawValue: String(c.killGraceMs), kind: "input", inputHint: "SIGTERM→SIGKILL grace" },
852
+ { key: "cfg:user:handoffGraceMs", label: "Handoff grace", value: formatDuration(c.handoffGraceMs), rawValue: String(c.handoffGraceMs), kind: "input", inputHint: "wait for final handoff after a kill" },
853
+ { key: "cfg:user:handoffEnforceTimeoutMs", label: "Handoff enforce", value: formatDuration(c.handoffEnforceTimeoutMs), rawValue: String(c.handoffEnforceTimeoutMs), kind: "input", inputHint: "re-prompt until a schema handoff lands" },
854
+ { key: "cfg:user:maxTaskBytes", label: "Max task bytes", value: String(c.maxTaskBytes), rawValue: String(c.maxTaskBytes), kind: "input" },
855
+ { key: "cfg:user:maxResultBytes", label: "Max result bytes", value: String(c.maxResultBytes), rawValue: String(c.maxResultBytes), kind: "input" },
856
+ { key: "cfg:user:updateThrottleMs", label: "Update throttle", value: formatDuration(c.updateThrottleMs), rawValue: String(c.updateThrottleMs), kind: "input", inputHint: "live update cadence" },
857
+ { key: "info:defaultRole", label: "Default role", value: c.defaultRole, kind: "info" },
858
+ { key: "info:retention", label: "Retention", value: `${c.maxRuns} runs · ${c.maxRunAgeDays}d`, kind: "info" },
859
+ ];
860
+ };
861
+ try {
862
+ await ctx.ui.custom(
863
+ (tui, theme, keybindings, done) =>
864
+ new SettingsPanel({
865
+ theme,
866
+ keybindings,
867
+ initialKey: "cfg:user:queueLimit",
868
+ snapshot: () => ({
869
+ title: "Advanced configuration",
870
+ summaryLines: ["User-wide · ~/.pi/agent/delegate/config.json", "Esc or any action returns to Delegation"],
871
+ sections: [{ title: "Knobs", rows: buildRows() }],
872
+ }),
873
+ apply: (key: string, raw: string): string | null => {
874
+ const m = /^cfg:user:([A-Za-z0-9]+)$/.exec(key);
875
+ if (!m) return `Unknown setting '${key}'.`;
876
+ return app.patchConfig(m[1]!, raw);
877
+ },
878
+ activate: (): PanelActionResult => ({ kind: "close", action: "advanced-done" }),
879
+ requestRender: () => tui.requestRender(),
880
+ done,
881
+ }),
882
+ { onCancel: () => ({}) } as unknown as Record<string, never>,
883
+ );
884
+ } catch {
885
+ /* esc → back to home */
886
+ }
887
+ };
888
+
889
+ // ── 5d. Home dashboard snapshot (centralized live window) ───────────────
890
+
819
891
  const dashboardSnapshot = (projectRoot?: string): PanelSnapshot => {
820
892
  const s = app.getStatus(pi.getActiveTools(), projectRoot);
821
893
  const active = s.activeRun;
822
894
  const last = s.lastRun;
823
895
  const t = s.timeouts;
896
+ const live = app.getActiveRunStream();
897
+ const queued = app.queuedRunCount();
898
+
899
+ const summaryLines: string[] = [];
900
+ summaryLines.push(`Delegate v${delegateVersion()} · mode ${s.modeEnabled ? "strict (delegate-only)" : "normal"}`);
901
+ if (active && live) {
902
+ const phaseState = live.update.phase.startsWith("tool:") ? "running" : live.update.phase;
903
+ const g = stateGlyph(phaseState);
904
+ summaryLines.push(`Active ${shortModel(live.update.model) || live.update.role} ${g.glyph} ${Math.round(live.update.elapsedMs / 1000)}s / ${formatDuration(live.hardMs)}`);
905
+ } else if (active) {
906
+ summaryLines.push(`Active ${active.role} · ${active.runId.slice(-12)} · starting`);
907
+ } else {
908
+ summaryLines.push(`Idle no active run`);
909
+ }
910
+ if (queued > 0) summaryLines.push(`Queue ${queued} waiting (limit ${app.queueLimit()})`);
911
+ if (last) {
912
+ const g = stateGlyph(last.state);
913
+ summaryLines.push(`Last ${last.role} ${g.glyph} ${g.word}${last.durationMs != null ? ` in ${formatDuration(last.durationMs)}` : ""}`);
914
+ }
915
+
916
+ const sections: PanelSection[] = [];
917
+
918
+ if (live) {
919
+ const inflight = (live.update.openTools ?? []).slice(0, 3).join(", ");
920
+ const frac = live.hardMs ? Math.min(1, live.update.elapsedMs / live.hardMs) : 0;
921
+ const tail = renderFeedEvents([...live.events], { startMs: Date.now() - live.update.elapsedMs, maxChars: 96 }).slice(-3);
922
+ const rows: PanelRow[] = [
923
+ { key: "live-phase", label: "Phase", value: `${live.update.phase}${live.update.model ? ` · ${shortModel(live.update.model)}` : ""}`, kind: "info", valueStyle: "accent" },
924
+ { key: "live-progress", label: "Progress", value: progressBar(frac, 24), kind: "info" },
925
+ { key: "live-tokens", label: "Tokens", value: `↑${formatTokens(live.update.usage?.input)} ↓${formatTokens(live.update.usage?.output)} · ${formatCost(live.update.usage?.cost)}`, kind: "info", valueStyle: "muted" },
926
+ { key: "live-inflight", label: "In flight", value: inflight || "—", kind: "info" },
927
+ ];
928
+ tail.forEach((line, i) => rows.push({ key: `live-tail-${i}`, label: "", value: line, kind: "info", valueStyle: "muted" }));
929
+ sections.push({ title: "Live", rows });
930
+ }
931
+
932
+ sections.push({
933
+ title: "Actions",
934
+ rows: [
935
+ { key: "run-general", label: "Run general task…", value: "", kind: "action" },
936
+ { key: "run-research", label: "Run research task…", value: "", kind: "action" },
937
+ { key: "peek", label: "Peek live / final detail", value: "", kind: "action", disabled: !active && !last },
938
+ { key: "cancel", label: "Cancel active run", value: "", kind: "action", disabled: !active },
939
+ { key: "resume", label: "Resume last run…", value: "", kind: "action", disabled: !last },
940
+ { key: "strict-toggle", label: s.modeEnabled ? "Disable strict mode" : "Enable strict mode", value: "", kind: "action" },
941
+ { key: "configure-advanced", label: "Configure advanced…", value: "›", kind: "action" },
942
+ { key: "doctor", label: "Doctor", value: "", kind: "action" },
943
+ { key: "paths", label: "Paths", value: "", kind: "action" },
944
+ ],
945
+ });
946
+
947
+ sections.push({
948
+ title: "Timeouts (base)",
949
+ rows: [
950
+ { key: "cfg:user:hardTimeoutMs", label: "Hard · user-wide", value: formatDuration(t.userHardMs), rawValue: String(t.userHardMs), kind: "input", inputHint: "e.g. 30m / 2h / 1d — user config" },
951
+ { key: "cfg:user:inactivityTimeoutMs", label: "Idle · user-wide", value: formatDuration(t.userInactivityMs), rawValue: String(t.userInactivityMs), kind: "input", inputHint: "no-output watchdog; capped at ½ hard" },
952
+ { key: "cfg:project:hardTimeoutMs", label: "Hard · project", value: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "not set", rawValue: t.projectHardMs !== undefined ? String(t.projectHardMs) : "", kind: "input", inputHint: `merges into ${t.projectPath ?? ".pi/delegate/config.json"}` },
953
+ ...(t.projectCorrupt
954
+ ? [{ key: "project-corrupt", label: "Project config", value: "corrupt — user values used", kind: "info" as const, valueStyle: "warning" as const }]
955
+ : []),
956
+ ],
957
+ });
958
+
824
959
  return {
825
960
  title: "Delegation",
826
- summaryLines: [
827
- `Parent mode ${s.modeEnabled ? "strict" : "normal"}`,
828
- `Parent tools ${s.modeEnabled ? "delegate only" : "normal active set"}`,
829
- `Active run ${active ? `${active.runId.slice(0, 24)} (${active.role})` : "none"}`,
830
- `Last run ${last ? `${last.role} · ${last.state}${last.durationMs != null ? ` · ${Math.round(last.durationMs / 1000)}s` : ""}` : "none"}`,
831
- `Default role ${s.defaultRole}`,
832
- `Base timeout ${formatDuration(t.hardMs)} hard · ${formatDuration(t.inactivityMs)} idle (${t.source === "project" ? "project" : "user-wide"})`,
961
+ summaryLines,
962
+ sections,
963
+ shortcuts: [
964
+ { key: "r", label: "run", action: "run-general" },
965
+ { key: "p", label: "peek", action: "peek" },
966
+ { key: "x", label: "cancel", action: "cancel" },
967
+ { key: "c", label: "configure", action: "configure-advanced" },
968
+ { key: "d", label: "doctor", action: "doctor" },
969
+ { key: "s", label: "status", action: "status" },
833
970
  ],
834
- sections: [
835
- {
836
- title: "Actions",
837
- rows: [
838
- { key: "run-general", label: "Run general", value: "", kind: "action" },
839
- { key: "run-research", label: "Run research", value: "", kind: "action" },
840
- { key: "strict-toggle", label: s.modeEnabled ? "Disable strict mode" : "Enable strict mode", value: "", kind: "action" },
841
- { key: "inspect-last", label: "Inspect last run", value: "", kind: "action", disabled: !last && !active },
842
- { key: "paths", label: "Paths / diagnostics", value: "", kind: "action" },
843
- { key: "doctor", label: "Doctor", value: "", kind: "action" },
844
- ],
845
- },
846
- {
847
- title: "Timeouts (base)",
848
- rows: [
849
- {
850
- key: "timeout-user",
851
- label: "Hard · user-wide",
852
- value: formatDuration(t.userHardMs),
853
- rawValue: formatDuration(t.userHardMs),
854
- kind: "input",
855
- inputHint: "e.g. 30m / 2h / 1d — saves ~/.pi/agent/delegate/config.json",
856
- },
857
- {
858
- key: "timeout-project",
859
- label: "Hard · project",
860
- value: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "not set",
861
- rawValue: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "",
862
- kind: "input",
863
- inputHint: `merges into ${t.projectPath ?? ".pi/delegate/config.json"} (this key only)`,
864
- },
865
- {
866
- key: "idle-user",
867
- label: "Idle · user-wide",
868
- value: formatDuration(t.userInactivityMs),
869
- rawValue: formatDuration(t.userInactivityMs),
870
- kind: "input",
871
- inputHint: "no-output watchdog; capped at ½ of the hard timeout",
872
- },
873
- ...(t.projectCorrupt
874
- ? [{ key: "project-corrupt", label: "Project config", value: "corrupt — user values used", kind: "info" as const, valueStyle: "warning" as const }]
875
- : []),
876
- ],
877
- },
878
- ],
879
- detailLines: active ? [`elapsed updates refresh every 1s while a run is active`] : undefined,
971
+ detailLines: active
972
+ ? ["live refresh 1s · enter selects · peek / cancel in Actions"]
973
+ : ["enter selects · edit a timeout, or run a task"],
880
974
  };
881
975
  };
882
976
 
883
977
  const openDashboard = async (ctx: ExtensionCommandContext): Promise<void> => {
884
- let initialKey = app.isStrict() ? "strict-toggle" : "run-general";
978
+ const projectRoot = ctx.cwd ?? process.cwd();
979
+ let initialKey = app.isStrict() ? "run-general" : "run-general";
885
980
  for (;;) {
886
981
  let refreshTimer: ReturnType<typeof setInterval> | undefined;
887
982
  let result: { action?: string } | undefined;
@@ -892,18 +987,14 @@ export default function delegateExtension(pi: ExtensionAPI) {
892
987
  theme,
893
988
  keybindings,
894
989
  initialKey,
895
- snapshot: () => dashboardSnapshot(ctx.cwd ?? process.cwd()),
990
+ snapshot: () => dashboardSnapshot(projectRoot),
896
991
  apply: (key: string, raw: string): string | null => {
897
- switch (key) {
898
- case "timeout-user":
899
- return app.patchConfig("hardTimeoutMs", raw);
900
- case "idle-user":
901
- return app.patchConfig("inactivityTimeoutMs", raw);
902
- case "timeout-project":
903
- return app.patchProjectConfig(ctx.cwd ?? process.cwd(), "hardTimeoutMs", raw);
904
- default:
905
- return `Unknown setting '${key}'.`;
906
- }
992
+ const m = /^cfg:(user|project):([A-Za-z0-9]+)$/.exec(key);
993
+ if (!m) return `Unknown setting '${key}'.`;
994
+ const [, target, field] = m;
995
+ return target === "project"
996
+ ? app.patchProjectConfig(projectRoot, field, raw)
997
+ : app.patchConfig(field, raw);
907
998
  },
908
999
  activate: (key): PanelActionResult => ({ kind: "close", action: key }),
909
1000
  requestRender: () => tui.requestRender(),
@@ -934,18 +1025,44 @@ export default function delegateExtension(pi: ExtensionAPI) {
934
1025
  await runCommandForeground(task, role, ctx);
935
1026
  continue;
936
1027
  }
937
- if (action === "strict-toggle") {
938
- if (app.isStrict()) {
939
- const res = await app.disableStrict(modeCtx(ctx));
940
- say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
941
- } else {
942
- const res = await app.enableStrict(modeCtx(ctx));
1028
+ if (action === "peek") {
1029
+ await openPeek(ctx);
1030
+ continue;
1031
+ }
1032
+ if (action === "cancel") {
1033
+ const ok = await ctx.ui.confirm("Cancel active run?", "SIGTERM then SIGKILL; a partial handoff is returned if the child produced one.");
1034
+ if (ok) {
1035
+ const res = await app.cancel();
943
1036
  say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
944
1037
  }
945
1038
  continue;
946
1039
  }
947
- if (action === "inspect-last") {
948
- say(ctx, inspectText());
1040
+ if (action === "resume") {
1041
+ const target = app.getStatus(pi.getActiveTools(), projectRoot).lastRun;
1042
+ if (!target) {
1043
+ say(ctx, "[delegate] nothing to resume.", "warning");
1044
+ continue;
1045
+ }
1046
+ const task = await ctx.ui.editor(`Resume ${target.runId.slice(-12)} (${target.role})`, "");
1047
+ if (!task || !task.trim()) continue;
1048
+ await runCommandForeground(task, target.role === "research" ? "research" : "general", ctx, undefined, { resumeFrom: target.runId });
1049
+ continue;
1050
+ }
1051
+ if (action === "strict-toggle") {
1052
+ const res = app.isStrict() ? await app.disableStrict(modeCtx(ctx)) : await app.enableStrict(modeCtx(ctx));
1053
+ say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
1054
+ continue;
1055
+ }
1056
+ if (action === "configure-advanced") {
1057
+ await openAdvanced(ctx, projectRoot);
1058
+ continue;
1059
+ }
1060
+ if (action === "doctor") {
1061
+ say(ctx, doctorText());
1062
+ continue;
1063
+ }
1064
+ if (action === "status") {
1065
+ say(ctx, statusText(ctx));
949
1066
  continue;
950
1067
  }
951
1068
  if (action === "paths") {
@@ -953,8 +1070,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
953
1070
  say(ctx, [`[delegate paths]`, `config: ${p.configPath}`, `runs: ${p.runsDir}`].join("\n"));
954
1071
  continue;
955
1072
  }
956
- if (action === "doctor") {
957
- say(ctx, doctorText());
1073
+ if (action === "inspect-last") {
1074
+ say(ctx, inspectText());
958
1075
  continue;
959
1076
  }
960
1077
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/ui/format.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * delegate — shared formatting (reuse mandate, FIELDS.md §2).
3
+ *
4
+ * ONE module all views import so tokens/durations/sizes/model render
5
+ * identically across home, live strip, inline tool card, and peek. Wraps the
6
+ * canonical `formatDuration` (config.ts) rather than re-rolling it. Replaces
7
+ * the duplicate `fmtDuration`/`fmtTokens` that used to live in running-view.
8
+ */
9
+
10
+ import { formatDuration } from "../config.ts";
11
+
12
+ /** Canonical duration (ms → "41s"/"30m 22s"/"2h"). */
13
+ export { formatDuration };
14
+
15
+ /** Token count: 0 if falsy; raw <1000; else `X.Yk`; else `X.YM`. */
16
+ export function formatTokens(n: number | undefined): string {
17
+ if (!n || n < 0) return "0";
18
+ if (n < 1000) return String(n);
19
+ if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
20
+ return `${Math.round(n / 100_000) / 10}M`;
21
+ }
22
+
23
+ /** Cost as `$X.YZ` (2 dp) or `$0.00`. Never emoji. */
24
+ export function formatCost(cost: number | undefined): string {
25
+ return `$${(cost ?? 0).toFixed(2)}`;
26
+ }
27
+
28
+ /** Bytes → binary size, 0–1 decimal ("51200"→"50 KB"). */
29
+ export function formatSize(bytes: number | undefined): string {
30
+ const b = bytes ?? 0;
31
+ if (b < 1024) return `${b} B`;
32
+ const kb = b / 1024;
33
+ if (kb < 1024) return `${kb < 10 ? Math.round(kb * 10) / 10 : Math.round(kb)} KB`;
34
+ const mb = kb / 1024;
35
+ if (mb < 1024) return `${mb < 10 ? Math.round(mb * 10) / 10 : Math.round(mb)} MB`;
36
+ const gb = mb / 1024;
37
+ return `${gb < 10 ? Math.round(gb * 10) / 10 : Math.round(gb)} GB`;
38
+ }
39
+
40
+ /** "zai/glm-5.3" → "glm-5.3" for compact rows; full id for peek headers. */
41
+ export function shortModel(model: string | undefined): string {
42
+ if (!model) return "";
43
+ const slash = model.lastIndexOf("/");
44
+ return slash >= 0 ? model.slice(slash + 1) : model;
45
+ }
46
+
47
+ /**
48
+ * State glyph + word (never color-alone, FIELDS §3.6). Returns the glyph and
49
+ * the word separately so the caller colors them together.
50
+ */
51
+ export function stateGlyph(state: string): { glyph: string; word: string; color: "success" | "warning" | "error" | "muted" } {
52
+ switch (state) {
53
+ case "created":
54
+ case "starting":
55
+ return { glyph: "◐", word: "starting", color: "muted" };
56
+ case "running":
57
+ return { glyph: "●", word: "running", color: "success" };
58
+ case "succeeded":
59
+ return { glyph: "✓", word: "done", color: "success" };
60
+ case "cancelled":
61
+ return { glyph: "⊘", word: "cancelled", color: "muted" };
62
+ case "timed_out_idle":
63
+ return { glyph: "⏱", word: "timeout · idle", color: "warning" };
64
+ case "timed_out_hard":
65
+ return { glyph: "⏱", word: "timeout · hard", color: "warning" };
66
+ case "queued":
67
+ return { glyph: "○", word: "queued", color: "muted" };
68
+ default:
69
+ return { glyph: "✗", word: state || "unknown", color: "error" };
70
+ }
71
+ }
72
+
73
+ /** Progress bar: `filled(█) + empty(░)` + "NN%" text (never shape-alone). */
74
+ export function progressBar(frac: number, width: number): string {
75
+ const f = Math.max(0, Math.min(1, frac));
76
+ const w = Math.max(4, Math.floor(width));
77
+ const filled = Math.round(f * w);
78
+ return `${"█".repeat(filled)}${"░".repeat(Math.max(0, w - filled))} ${Math.round(f * 100)}%`;
79
+ }
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 += 1;
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 line = `│ ${truncateToWidth(text, inner)} │`;
76
- return color && theme?.fg ? theme.fg(color, line) : line;
83
+ const body = color && theme?.fg ? theme.fg(color, truncateToWidth(text, inner)) : truncateToWidth(text, inner);
84
+ return `│ ${body} │`;
77
85
  };
78
86
 
79
- // Viewport: keep the overlay in the 20–24 line budget.
80
- const maxFeed = Math.max(1, 20 - 4);
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 end = Math.max(0, total - this.offsetFromEnd);
85
- const start = Math.max(0, end - maxFeed);
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
- truncateToWidth(top, w),
90
- pad(s.summary, "muted"),
91
- pad(
92
- s.live
93
- ? fg("success", `● live — following (j/k scroll, f re-follow, q close)`)
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
- if (total === 0) {
99
- lines.push(pad("no activity captured", "muted"));
100
- } else {
101
- for (const line of window) lines.push(pad(line));
102
- if (start > 0) lines.push(pad(`… ${start} earlier event(s) — j to scroll up`, "dim"));
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
  }
@@ -4,12 +4,19 @@
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
- * Cancels via Escape twice (armed). Refresh cadence is owned by the host
8
- * (1 s); feed lines arrive pre-formatted from the adapter's event ring.
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";
12
18
  import type { Theme, KeybindingsManager, ThemeColor } from "@earendil-works/pi-coding-agent";
19
+ import { formatDuration, formatTokens, shortModel } from "./format.ts";
13
20
 
14
21
  export interface RunningViewState {
15
22
  runId: string;
@@ -25,7 +32,7 @@ export interface RunningViewState {
25
32
  tokens?: { input?: number; output?: number };
26
33
  /** Tools currently in flight. */
27
34
  openTools?: string[];
28
- /** Pre-formatted feed lines (newest last), already clipped. */
35
+ /** Pre-formatted feed lines (newest last); the panel slices/pads itself. */
29
36
  feedLines: string[];
30
37
  }
31
38
 
@@ -36,18 +43,10 @@ export interface RunningViewHost {
36
43
  done(result: { cancelled?: boolean }): void;
37
44
  }
38
45
 
39
- function fmtDuration(ms: number): string {
40
- const s = Math.max(0, Math.round(ms / 1000));
41
- if (s < 60) return `${s}s`;
42
- return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
43
- }
44
-
45
- function fmtTokens(n?: number): string {
46
- if (!n) return "0";
47
- if (n < 1000) return String(n);
48
- if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
49
- return `${Math.round(n / 100_000) / 10}M`;
50
- }
46
+ /** Constant panel height (top + header + progress + in-flight + FEED + footer + bottom). */
47
+ const PANEL_ROWS = 9;
48
+ /** Feed rows inside the fixed frame; the rest are the fixed scaffold. */
49
+ const FEED_ROWS = PANEL_ROWS - 5;
51
50
 
52
51
  export class RunningView implements Component {
53
52
  private readonly host: RunningViewHost;
@@ -82,66 +81,62 @@ export class RunningView implements Component {
82
81
  const s = this.host.state();
83
82
  const theme = this.host.theme;
84
83
  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
84
  const inner = Math.max(1, w - 4);
85
+
86
+ // Borders stay UNSTYLED so Pi's per-frame width/clear math is exact;
87
+ // color is applied to inner text only.
88
+ const title = " Delegating ";
89
+ const fill = Math.max(0, w - 2 - title.length - 2);
90
+ const top = truncateToWidth(`╭─${title}${"─".repeat(fill + 1)}╮`, w);
91
+ const bottom = truncateToWidth(`╰${"─".repeat(Math.max(0, w - 2))}╯`, w);
90
92
  const pad = (text: string, color?: ThemeColor) => {
91
- const line = `│ ${truncateToWidth(text, inner)} │`;
92
- return color && theme?.fg ? theme.fg(color, line) : line;
93
+ const body = color && theme?.fg ? theme.fg(color, truncateToWidth(text, inner)) : truncateToWidth(text, inner);
94
+ return `│ ${body} │`;
93
95
  };
94
-
95
96
  const fg = (kind: ThemeColor, text: string) => (theme?.fg ? theme.fg(kind, text) : text);
96
- const lines: string[] = [top];
97
97
 
98
- // Header: identity + elapsed + turns + tokens.
98
+ // Fixed scaffold rows — always exactly PANEL_ROWS - 2 inner rows.
99
99
  const head = [
100
100
  s.role,
101
- s.model,
102
- fg("accent", fmtDuration(s.elapsedMs)),
101
+ s.model ? shortModel(s.model) : undefined,
102
+ formatDuration(s.elapsedMs),
103
103
  ...(s.turns !== undefined ? [`turn ${s.turns}`] : []),
104
- ...(s.tokens ? [`↑${fmtTokens(s.tokens.input)} ↓${fmtTokens(s.tokens.output)}`] : []),
104
+ ...(s.tokens ? [`↑${formatTokens(s.tokens.input)} ↓${formatTokens(s.tokens.output)}`] : []),
105
105
  ]
106
106
  .filter(Boolean)
107
107
  .join(" · ");
108
- lines.push(pad(head));
109
108
 
110
- // Progress: elapsed vs hard cap (never color-only — text carries %).
109
+ let progress = "running…";
111
110
  if (s.hardMs && s.hardMs > 0) {
112
111
  const frac = Math.min(1, s.elapsedMs / s.hardMs);
113
112
  const barWidth = Math.max(4, Math.min(inner - 14, 24));
114
113
  const filled = Math.round(frac * barWidth);
115
- const bar = `${"█".repeat(filled)}${"░".repeat(Math.max(0, barWidth - filled))}`;
116
- lines.push(pad(`${bar} ${Math.round(frac * 100)}% of ${fmtDuration(s.hardMs)} hard`));
114
+ progress = `${"█".repeat(filled)}${"░".repeat(Math.max(0, barWidth - filled))} ${Math.round(frac * 100)}% of ${formatDuration(s.hardMs)} hard`;
117
115
  }
118
116
 
119
- // In-flight tools.
120
- if (s.openTools && s.openTools.length > 0) {
121
- lines.push(pad(fg("warning", `in flight: ${s.openTools.join(", ")}`)));
122
- }
117
+ const openTools = s.openTools ?? [];
118
+ const inFlight = openTools.length > 0 ? `in flight: ${openTools.join(", ")}` : "";
123
119
 
124
- // Feed: newest last; take as many as fit the budget.
125
- const feedBudget = Math.max(0, 16 - lines.length - 2);
126
- const feed = s.feedLines.slice(-feedBudget);
127
- if (feed.length > 0) {
128
- for (const line of feed) lines.push(pad(line, "text"));
129
- } else {
130
- lines.push(pad("starting — waiting for the child's first events…", "muted"));
131
- }
120
+ // Feed: newest last, right-aligned in a fixed block (blank-padded on top).
121
+ const feed = s.feedLines.slice(-FEED_ROWS);
122
+ const feedRows: string[] = [...Array<string>(Math.max(0, FEED_ROWS - feed.length)).fill(""), ...feed];
123
+
124
+ const footer = this.cancelArmed ? fg("error", "ESC again: CONFIRM cancel") : "esc/q cancel (press twice)";
125
+
126
+ // Assemble a fixed-height body: header, progress, in-flight, feed block, footer.
127
+ const body: Array<[string, ThemeColor?]> = [
128
+ [head],
129
+ [progress, "accent"],
130
+ [inFlight, inFlight ? "warning" : undefined],
131
+ ...feedRows.map((l): [string, ThemeColor?] => [l, l ? "text" : undefined]),
132
+ [footer, this.cancelArmed ? "error" : "dim"],
133
+ ];
134
+
135
+ const lines: string[] = [top, ...body.map(([t, c]) => pad(t, c)), bottom];
132
136
 
133
- // Footer.
134
- lines.push(
135
- pad(
136
- this.cancelArmed
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));
137
+ // Belt-and-braces: hard-clip to the exact height and width.
138
+ const clipped = lines.slice(0, PANEL_ROWS);
139
+ while (clipped.length < PANEL_ROWS) clipped.splice(clipped.length - 1, 0, pad(""));
140
+ return clipped.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
146
141
  }
147
142
  }