pi-better-background-tasks 0.1.16 → 0.1.18

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/runtime.ts CHANGED
@@ -305,6 +305,15 @@ async function notifyTerminal(
305
305
  if (meta.callback === false || meta.callbackSentAt || meta.callbackSuppressedAt) return;
306
306
  const latest = readMeta(meta.id) ?? meta;
307
307
  if (latest.callback === false || latest.callbackSentAt || latest.callbackSuppressedAt) return;
308
+ // Cancellation is an explicit action by the agent or user, so a completion
309
+ // wakeup would be noise. Record the suppression durably so the session_start
310
+ // replay path never fires a callback for a cancelled task either.
311
+ if (latest.status === "cancelled") {
312
+ latest.callbackSuppressedAt = Date.now();
313
+ latest.callbackSuppressedReason = "task was cancelled; no completion callback is needed";
314
+ writeMeta(latest);
315
+ return;
316
+ }
308
317
  const label = latest.name ? `${latest.name} (${latest.id})` : latest.id;
309
318
  getCallbackBatcher(pi).enqueue({
310
319
  source: "background-task",
@@ -39,6 +39,11 @@ export type BackgroundWorkDetail = {
39
39
  metadata: Array<{ label: string; value: string }>;
40
40
  foldedSections?: Array<{ id: string; label: string; text: string; collapsedText?: string; expandedByDefault?: boolean }>;
41
41
  evidence: { label: string; text: string };
42
+ transcript?: Array<
43
+ | { type: "assistant"; content: Array<{ type: string; text?: string; thinking?: string }>; streaming: boolean }
44
+ | { type: "tool"; id?: string; name: string; args?: unknown; result?: unknown; isError: boolean; state: "running" | "completed" }
45
+ >;
46
+ transcriptDiagnostic?: string;
42
47
  footerActions?: string[];
43
48
  };
44
49
 
@@ -54,6 +59,7 @@ export type BackgroundWorkProvider = {
54
59
  label: string;
55
60
  priority: number;
56
61
  visibleCount(): number;
62
+ showSection?(rows: BackgroundWorkRow[], now: number): boolean;
57
63
  parentRow?(now: number): BackgroundWorkRow | null;
58
64
  listRows(now: number): BackgroundWorkRow[];
59
65
  detail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null;
@@ -67,6 +73,7 @@ type HostDeps = {
67
73
  isOpenTrigger: (data: string) => boolean;
68
74
  matchKey: (data: string, keyId: string) => boolean;
69
75
  truncate: (s: string, width: number) => string;
76
+ createTranscriptComponent?: (detail: BackgroundWorkDetail, theme: unknown) => Component;
70
77
  };
71
78
 
72
79
  type NavigatorState = {
@@ -83,6 +90,7 @@ type NavigatorState = {
83
90
  mainListCloseArm?: { id: string; armedAt: number };
84
91
  mainListCloseArmTimer?: ReturnType<typeof setTimeout>;
85
92
  mainListDeadlineScheduler?: RenderScheduler;
93
+ editorComponent?: Component;
86
94
  detailOverlayRows?: number;
87
95
  dispose?: () => void;
88
96
  };
@@ -99,8 +107,7 @@ export const CLOSE_ARM_MS = 3000;
99
107
  export const DEFAULT_LOG_TAIL_ROWS = 10;
100
108
  export const LOG_TAIL_ROW_CHOICES = [10, 25] as const;
101
109
  const MAIN_LIST_FALLBACK_WIDTH = 100;
102
- const DETAIL_OVERLAY_HEADER_MARGIN_ROWS = 5;
103
- const DETAIL_OVERLAY_FOOTER_MARGIN_ROWS = 3;
110
+ const DETAIL_OVERLAY_FOOTER_ROWS = 3;
104
111
  const EVIDENCE_SECTION_ID = "__evidence__";
105
112
  const RUNNING_DOT_GLYPH = "●";
106
113
  const RUNNING_DOT_FRAMES = ["dim", "accent", "accent", "dim"] as const;
@@ -315,7 +322,7 @@ function renderWidth(width: number): number {
315
322
  return Number.isFinite(width) && width > 0 ? Math.floor(width) : MAIN_LIST_FALLBACK_WIDTH;
316
323
  }
317
324
 
318
- type InternalRow = BackgroundWorkRow & { navigatorId: string; providerLabel: string };
325
+ type InternalRow = BackgroundWorkRow & { navigatorId: string; providerLabel: string; parentRow?: boolean };
319
326
 
320
327
  function rowKey(providerId: string, id: string): string {
321
328
  return `${providerId}:${id}`;
@@ -333,6 +340,19 @@ function listRows(now = Date.now()): InternalRow[] {
333
340
  let providerRows: BackgroundWorkRow[] = [];
334
341
  try { providerRows = provider.listRows(now) ?? []; } catch { providerRows = []; }
335
342
  const orderedProviderRows = [...providerRows].sort((a, b) => b.sortStartedAt - a.sortStartedAt || rowDisplayName(a).localeCompare(rowDisplayName(b)));
343
+ let showSection = orderedProviderRows.length > 0 || provider.parentRow !== undefined;
344
+ try { showSection = provider.showSection?.(orderedProviderRows, now) ?? showSection; } catch { showSection = false; }
345
+ if (!showSection) continue;
346
+ let parentRow: BackgroundWorkRow | null = null;
347
+ try { parentRow = provider.parentRow?.(now) ?? null; } catch { parentRow = null; }
348
+ if (parentRow) {
349
+ rows.push({
350
+ ...parentRow,
351
+ navigatorId: rowKey(parentRow.providerId, parentRow.id),
352
+ providerLabel: provider.label,
353
+ parentRow: true,
354
+ });
355
+ }
336
356
  for (const row of orderedProviderRows) {
337
357
  rows.push({ ...row, navigatorId: rowKey(provider.id, row.id), providerLabel: provider.label });
338
358
  }
@@ -378,7 +398,7 @@ function focusMainList(): void {
378
398
  const rows = listRows();
379
399
  if (rows.length === 0) return;
380
400
  const s = state();
381
- syncMainListSelection(rows);
401
+ s.mainListSelectedId = rows.find((row) => row.parentRow && row.id === "main")?.navigatorId ?? rows[0]!.navigatorId;
382
402
  s.mainListFocused = true;
383
403
  refreshMainListWidget();
384
404
  }
@@ -412,16 +432,6 @@ function buildMainListLines(
412
432
  const group = grouped.get(label)!;
413
433
  if (i > 0) lines.push("");
414
434
  lines.push(providerGroupLabel(label, fg));
415
- const provider = state().providers.get(group[0]!.providerId);
416
- let parentRow: BackgroundWorkRow | null = null;
417
- try { parentRow = provider?.parentRow?.(Date.now()) ?? null; } catch { parentRow = null; }
418
- if (parentRow) {
419
- lines.push(formatMainListRow({
420
- ...parentRow,
421
- navigatorId: rowKey(parentRow.providerId, parentRow.id),
422
- providerLabel: label,
423
- }, false, fg, width));
424
- }
425
435
  for (const row of group) {
426
436
  const selected = options.focused && row.navigatorId === options.selectedId;
427
437
  lines.push(formatMainListRow(row, selected === true, fg, width));
@@ -433,13 +443,13 @@ function buildMainListLines(
433
443
  }
434
444
 
435
445
  function shortcutsLine(focused: boolean, fg: (color: string, value: string) => string): string {
436
- const keys = focused ? "↑↓ select · Enter detail · x stop · Esc unfocus" : "← to navigate";
446
+ const keys = focused ? "↑↓ switch · Enter detail · x stop · Esc unfocus" : "← to navigate";
437
447
  return dim(keys, fg);
438
448
  }
439
449
 
440
450
  function providerGroupLabel(label: string, fg: (color: string, value: string) => string): string {
441
451
  const normalized = singleLine(label).toLowerCase();
442
- return `${dim("▸", fg)} ${fg("warning", normalized)}`;
452
+ return fg("warning", normalized);
443
453
  }
444
454
 
445
455
  function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: string, value: string) => string, width: number): string {
@@ -527,13 +537,14 @@ function detailFor(navigatorId: string, now = Date.now(), options?: { logTailLin
527
537
  }
528
538
 
529
539
  function closeFor(row: InternalRow): BackgroundWorkCloseOutcome {
540
+ if (row.parentRow) return { action: "not-closable", providerId: row.providerId, id: row.id };
530
541
  const provider = state().providers.get(row.providerId);
531
542
  if (!provider) return { action: "missing", providerId: row.providerId, id: row.id };
532
543
  try { return provider.close(row.id); } catch { return { action: "missing", providerId: row.providerId, id: row.id }; }
533
544
  }
534
545
 
535
546
  function closeHintFor(row: InternalRow | undefined): string | null {
536
- if (!row) return null;
547
+ if (!row || row.parentRow) return null;
537
548
  const provider = state().providers.get(row.providerId);
538
549
  if (!provider) return null;
539
550
  try { return `${provider.armCloseLabel(row)} ${row.name || row.id}`; } catch { return null; }
@@ -558,6 +569,7 @@ function installNavigatorEditor(ui: any, deps: HostDeps): unknown {
558
569
  }
559
570
 
560
571
  function wrapEditor(inner: any, deps: HostDeps): unknown {
572
+ if (inner && typeof inner.render === "function") state().editorComponent = inner as Component;
561
573
  return new Proxy(inner, {
562
574
  get(target, prop) {
563
575
  if (prop === "handleInput") {
@@ -588,16 +600,24 @@ function handleMainListInput(data: string, deps: HostDeps): boolean {
588
600
  }
589
601
  if (deps.matchKey(data, "up")) {
590
602
  clearMainListCloseArm();
591
- if (moveMainListSelection(-1)) refreshMainListWidget();
603
+ if (moveMainListSelection(-1)) {
604
+ refreshMainListWidget();
605
+ if (!selectedMainListRow()?.parentRow) openNavigator();
606
+ }
592
607
  return true;
593
608
  }
594
609
  if (deps.matchKey(data, "down")) {
595
610
  clearMainListCloseArm();
596
- if (moveMainListSelection(1)) refreshMainListWidget();
611
+ if (moveMainListSelection(1)) {
612
+ refreshMainListWidget();
613
+ if (!selectedMainListRow()?.parentRow) openNavigator();
614
+ }
597
615
  return true;
598
616
  }
599
617
  if (deps.matchKey(data, "enter")) {
600
- openNavigator();
618
+ const selected = selectedMainListRow();
619
+ if (selected?.parentRow) unfocusMainList();
620
+ else openNavigator();
601
621
  return true;
602
622
  }
603
623
  if (data === "x" || data === "X" || deps.matchKey(data, "x") || deps.matchKey(data, "X")) {
@@ -613,7 +633,7 @@ function handleMainListInput(data: string, deps: HostDeps): boolean {
613
633
 
614
634
  function handleMainListCloseKey(): void {
615
635
  const row = selectedMainListRow();
616
- if (!row) return;
636
+ if (!row || row.parentRow) return;
617
637
  const s = state();
618
638
  const now = Date.now();
619
639
  const arm = s.mainListCloseArm;
@@ -689,6 +709,8 @@ function createOverlayComponent(
689
709
  let closeArm: { id: string; armedAt: number } | undefined;
690
710
  let closeArmTimer: ReturnType<typeof setTimeout> | undefined;
691
711
  let closed = false;
712
+ let transcriptDetail: BackgroundWorkDetail | null = null;
713
+ let transcriptComponent: Component | null = null;
692
714
 
693
715
  const fg = (color: string, value: string) => theme?.fg ? theme.fg(color, value) : value;
694
716
 
@@ -704,12 +726,24 @@ function createOverlayComponent(
704
726
  });
705
727
 
706
728
  function refreshRows(): void {
707
- const selectedId = overlayState.rows[overlayState.selected]?.navigatorId;
729
+ const selectedId = state().mainListSelectedId ?? overlayState.rows[overlayState.selected]?.navigatorId;
708
730
  overlayState.rows = listRows();
709
731
  const nextIdx = selectedId ? overlayState.rows.findIndex((row) => row.navigatorId === selectedId) : -1;
710
732
  overlayState.selected = nextIdx >= 0 ? nextIdx : Math.min(overlayState.selected, Math.max(0, overlayState.rows.length - 1));
711
733
  }
712
734
 
735
+ function selectOverlayRow(next: number): void {
736
+ overlayState.selected = Math.min(Math.max(0, overlayState.rows.length - 1), Math.max(0, next));
737
+ state().mainListSelectedId = overlayState.rows[overlayState.selected]?.navigatorId;
738
+ clearCloseArm();
739
+ refreshMainListWidget();
740
+ }
741
+
742
+ function activateSelectedRow(): void {
743
+ if (selectedRow()?.parentRow) close();
744
+ else openDetail();
745
+ }
746
+
713
747
  function clearCloseArm(): void {
714
748
  if (closeArmTimer) clearTimeout(closeArmTimer);
715
749
  closeArmTimer = undefined;
@@ -731,13 +765,16 @@ function createOverlayComponent(
731
765
  }
732
766
 
733
767
  function selectedRow(): InternalRow | undefined {
734
- if (mode === "detail" && detailId) return overlayState.rows.find((row) => row.navigatorId === detailId);
735
768
  return overlayState.rows[overlayState.selected];
736
769
  }
737
770
 
738
771
  function openDetail(): void {
739
772
  const row = selectedRow();
740
773
  if (!row) return;
774
+ if (row.parentRow) {
775
+ close();
776
+ return;
777
+ }
741
778
  clearCloseArm();
742
779
  detailId = row.navigatorId;
743
780
  expandedSections.clear();
@@ -808,10 +845,43 @@ function createOverlayComponent(
808
845
 
809
846
  return {
810
847
  render(width: number) {
811
- const lines = mode === "detail"
812
- ? buildDetailLines(detail, width, deps.truncate, fg, { expandedSections, logTailRows, minRows: state().detailOverlayRows })
813
- : buildListLines(overlayState, width, deps.truncate, fg);
814
- return lines;
848
+ refreshRows();
849
+ const railLines = mode === "detail"
850
+ ? buildMainListLines(overlayState.rows, width, deps.truncate, fg, {
851
+ selectedId: selectedRow()?.navigatorId,
852
+ focused: true,
853
+ })
854
+ : [];
855
+ const editorLines = mode === "detail" ? renderEditorLines(width) : [];
856
+ const bottomLines = [...railLines, ...editorLines];
857
+ const overlayRows = state().detailOverlayRows;
858
+ const detailRows = overlayRows === undefined ? undefined : Math.max(1, overlayRows - bottomLines.length);
859
+ let contentLines: string[];
860
+ if (mode === "detail" && detail?.transcript && deps.createTranscriptComponent) {
861
+ if (transcriptDetail !== detail || !transcriptComponent) {
862
+ transcriptDetail = detail;
863
+ transcriptComponent = deps.createTranscriptComponent(detail, theme);
864
+ }
865
+ contentLines = buildTranscriptDetailLines(
866
+ detail,
867
+ transcriptComponent.render(width),
868
+ width,
869
+ deps.truncate,
870
+ fg,
871
+ { minRows: detailRows },
872
+ );
873
+ } else {
874
+ transcriptDetail = null;
875
+ transcriptComponent = null;
876
+ contentLines = mode === "detail"
877
+ ? buildDetailLines(detail, width, deps.truncate, fg, { expandedSections, logTailRows, minRows: detailRows })
878
+ : buildListLines(overlayState, width, deps.truncate, fg);
879
+ }
880
+ if (mode !== "detail") return contentLines;
881
+ if (detailRows === undefined) return [...contentLines, ...bottomLines];
882
+ const fittedContent = contentLines.slice(0, detailRows);
883
+ while (fittedContent.length < detailRows) fittedContent.push("");
884
+ return [...fittedContent, ...bottomLines];
815
885
  },
816
886
  handleInput(data: string) {
817
887
  if (closed) return;
@@ -820,10 +890,25 @@ function createOverlayComponent(
820
890
  return;
821
891
  }
822
892
  if (mode === "detail") {
823
- if (deps.matchKey(data, "left")) close();
893
+ if (deps.matchKey(data, "up")) {
894
+ selectOverlayRow(overlayState.selected - 1);
895
+ activateSelectedRow();
896
+ }
897
+ else if (deps.matchKey(data, "down")) {
898
+ selectOverlayRow(overlayState.selected + 1);
899
+ activateSelectedRow();
900
+ }
901
+ else if (deps.matchKey(data, "left")) {
902
+ const mainIdx = overlayState.rows.findIndex((row) => row.parentRow && row.id === "main");
903
+ if (mainIdx >= 0) selectOverlayRow(mainIdx);
904
+ close();
905
+ }
824
906
  else if (deps.matchKey(data, "enter")) {
825
- const sectionId = firstToggleableSectionId(detail);
826
- if (sectionId) {
907
+ const row = selectedRow();
908
+ if (row?.parentRow || row?.navigatorId !== detailId) openDetail();
909
+ else {
910
+ const sectionId = firstToggleableSectionId(detail);
911
+ if (!sectionId) return;
827
912
  if (expandedSections.has(sectionId)) expandedSections.delete(sectionId);
828
913
  else expandedSections.add(sectionId);
829
914
  requestRender();
@@ -834,7 +919,10 @@ function createOverlayComponent(
834
919
  if (detailId) detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
835
920
  requestRender();
836
921
  }
837
- else if (deps.matchKey(data, "escape")) close();
922
+ else if (deps.matchKey(data, "escape")) {
923
+ unfocusMainList();
924
+ close();
925
+ }
838
926
  return;
839
927
  }
840
928
  if (deps.matchKey(data, "up")) {
@@ -851,7 +939,7 @@ function createOverlayComponent(
851
939
  close();
852
940
  }
853
941
  },
854
- invalidate() {},
942
+ invalidate() { transcriptComponent?.invalidate(); },
855
943
  dispose() {
856
944
  clearCloseArm();
857
945
  detailScheduler.dispose();
@@ -859,26 +947,61 @@ function createOverlayComponent(
859
947
  };
860
948
  }
861
949
 
950
+ function buildTranscriptDetailLines(
951
+ detail: BackgroundWorkDetail,
952
+ transcriptLines: string[],
953
+ width: number,
954
+ truncate: (s: string, width: number) => string,
955
+ fg: (color: string, value: string) => string,
956
+ options: { minRows?: number } = {},
957
+ ): string[] {
958
+ const actions = [...(detail.footerActions ?? ["x close"]), "Esc close"].join(" · ");
959
+ const lines: string[] = [
960
+ fg("accent", rule(detail.title, width)),
961
+ dim(` ← main · ${actions}`, fg),
962
+ "",
963
+ ` status ${fg(toneColor(detail.statusTone, detail.status), detail.status)}`,
964
+ ];
965
+ if (detail.subtitle) lines.push(` summary ${detail.subtitle}`);
966
+ for (const item of detail.metadata) lines.push(` ${item.label.padEnd(8, " ").slice(0, 8)} ${item.value}`);
967
+ lines.push("", dim(section("transcript", width), fg));
968
+ if (detail.transcriptDiagnostic) lines.push(` ${dim(detail.transcriptDiagnostic, fg)}`);
969
+ lines.push(...(transcriptLines.length ? transcriptLines : [" (no transcript yet)"]));
970
+ lines.push("");
971
+ const footerLines = [dim(` ← main · ${actions}`, fg), dim(rule("", width), fg)];
972
+ padBeforeFooter(lines, footerLines.length, options.minRows);
973
+ lines.push(...footerLines);
974
+ return lines.map((line) => safeTruncate(line, width, truncate));
975
+ }
976
+
862
977
  function detailOverlayOptions() {
863
- const navigatorRows = state().lastMainListLines?.length ?? 0;
864
- const marginBottom = DETAIL_OVERLAY_FOOTER_MARGIN_ROWS + navigatorRows;
978
+ const marginBottom = DETAIL_OVERLAY_FOOTER_ROWS;
865
979
  return {
866
980
  anchor: "top-left" as const,
867
981
  width: "100%" as const,
868
982
  maxHeight: "100%" as const,
869
983
  margin: {
870
- top: DETAIL_OVERLAY_HEADER_MARGIN_ROWS,
984
+ top: 0,
871
985
  right: 0,
872
986
  bottom: marginBottom,
873
987
  left: 0,
874
988
  },
875
989
  visible: (_termWidth: number, termHeight: number) => {
876
- state().detailOverlayRows = Math.max(1, termHeight - DETAIL_OVERLAY_HEADER_MARGIN_ROWS - marginBottom);
990
+ state().detailOverlayRows = Math.max(1, termHeight - marginBottom);
877
991
  return true;
878
992
  },
879
993
  };
880
994
  }
881
995
 
996
+ function renderEditorLines(width: number): string[] {
997
+ try {
998
+ const lines = state().editorComponent?.render(width);
999
+ if (lines?.length) return lines;
1000
+ } catch { /* use an empty editor-shaped fallback */ }
1001
+ const border = "─".repeat(Math.max(1, width));
1002
+ return [border, "", border];
1003
+ }
1004
+
882
1005
  function fallbackDetail(row: InternalRow): BackgroundWorkDetail {
883
1006
  return {
884
1007
  providerId: row.providerId,