my-durable 0.0.119 → 0.0.121

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.
@@ -12,8 +12,9 @@ import {
12
12
  type SelectItem,
13
13
  } from "@earendil-works/pi-tui";
14
14
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
15
- import type { EnvFileView, NotifySinkView, ScheduleView } from "../../dpi-sdk/src/api.ts";
15
+ import type { ArchivedView, DeviceTree, EnvFileView, GraphRecord, GraphRunRecord, NotifySinkView, ScheduleView } from "../../dpi-sdk/src/api.ts";
16
16
  import { agentTree, type TreeNode } from "../../dpi-sdk/src/models.ts";
17
+ import { fmtBytes, fmtDur } from "./commands.ts";
17
18
  import { oneLine, sanitizeTerminal } from "./sanitize.ts";
18
19
  import type { App } from "./app.ts";
19
20
  import { c, selectTheme } from "./theme.ts";
@@ -290,34 +291,72 @@ export class Panel extends Box {
290
291
 
291
292
  // ------------------------------------------------------------------ flows
292
293
 
293
- export async function pickSession(app: App) {
294
- const tree = await app.client.tree();
295
- const items: SelectItem[] = [
296
- { value: "+new", label: "+ New session", description: `choose a directory on ${oneLine(app.device.id)}` },
297
- ...tree.sessions.map((s) => {
298
- const agents = Array.isArray(s.agents) ? s.agents : [];
299
- return {
300
- value: s.id,
301
- label: oneLine(String(s.name ?? "")),
302
- description: `${oneLine(String(s.cwd ?? "").split("/").slice(-2).join("/"))} │ ${agents.length} agent${agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
294
+ /**
295
+ * The session picker. run-13: resolves with the picked session's id
296
+ * (undefined on esc or +New) so /export can reuse this same door — every
297
+ * existing caller ignores the value, and attach-on-pick is unchanged. A
298
+ * failed tree() now lands in an error toast like the other ops pickers
299
+ * (through /sessions it used to surface as an unhandled rejection).
300
+ */
301
+ export function pickSession(app: App): Promise<string | undefined> {
302
+ return new Promise((done) => {
303
+ void (async () => {
304
+ let tree: DeviceTree;
305
+ try {
306
+ tree = await app.client.tree();
307
+ } catch (e) {
308
+ app.notify(`sessions: ${(e as Error).message.slice(0, 80)}`, true);
309
+ return done(undefined);
310
+ }
311
+ const items: SelectItem[] = [
312
+ { value: "+new", label: "+ New session", description: `choose a directory on ${oneLine(app.device.id)}` },
313
+ ...tree.sessions.map((s) => {
314
+ const agents = Array.isArray(s.agents) ? s.agents : [];
315
+ return {
316
+ value: s.id,
317
+ label: oneLine(String(s.name ?? "")),
318
+ description: `${oneLine(String(s.cwd ?? "").split("/").slice(-2).join("/"))} │ ${agents.length} agent${agents.length === 1 ? "" : "s"}${s.busy ? " │ working" : ""}`,
319
+ };
320
+ }),
321
+ ];
322
+ // r13 NIT (fixed run-14): a pick* promise used to hang FOREVER when its
323
+ // overlay was dismissed outside the picker's esc path — app-level ctrl+c
324
+ // closes overlays through closeOverlay() (app.ts:1060), which fires the
325
+ // overlay's onClose and never the picker's onCancel. The onClose below
326
+ // settles the same promise. Promise resolution is first-wins, so every
327
+ // pick path must settle BEFORE closeOverlay — otherwise the close's
328
+ // onClose undefined would win over the picked id. Double-resolve is
329
+ // harmless; order is everything.
330
+ const settle = (value: string | undefined) => {
331
+ done(value);
332
+ app.closeOverlay();
303
333
  };
304
- }),
305
- ];
306
- app.overlay(
307
- new Picker(`Sessions on ${oneLine(app.device.id)}`, items, (item) => {
308
- app.closeOverlay();
309
- if (item.value === "+new") return void newSession(app);
310
- const s = tree.sessions.find((x) => x.id === item.value)!;
311
- const root = s.agents.find((a) => a.kind === "root") ?? s.agents[0];
312
- void app.attach(s.id, root?.id ?? 1);
313
- }, () => {
314
- // Esc must never surprise-quit (0.0.52): with no attached session the
315
- // cancel used to pass exitIfNothing=true and picker→Esc→Esc killed the
316
- // whole process (R4 finding 1). Landing in the herd/network view is the
317
- // honest cancel; quitting stays on q / ctrl+c / /quit.
318
- app.closeOverlay();
319
- }),
320
- );
334
+ app.overlay(
335
+ new Picker(`Sessions on ${oneLine(app.device.id)}`, items, (item) => {
336
+ // +New hands the flow to the new-session chain — resolve undefined so
337
+ // a waiting /export stays quiet instead of flashing "cancelled" over
338
+ // a flow that is telling its own story.
339
+ if (item.value === "+new") {
340
+ settle(undefined);
341
+ return void newSession(app);
342
+ }
343
+ const s = tree.sessions.find((x) => x.id === item.value)!;
344
+ const root = s.agents.find((a) => a.kind === "root") ?? s.agents[0];
345
+ settle(s.id);
346
+ void app.attach(s.id, root?.id ?? 1);
347
+ }, () => {
348
+ // Esc must never surprise-quit (0.0.52): with no attached session the
349
+ // cancel used to pass exitIfNothing=true and picker→Esc→Esc killed the
350
+ // whole process (R4 finding 1). Landing in the herd/network view is the
351
+ // honest cancel; quitting stays on q / ctrl+c / /quit.
352
+ settle(undefined);
353
+ }),
354
+ // The external-dismissal door (ctrl+c at app level): see the r13 NIT
355
+ // note above — resolves undefined, never hangs.
356
+ () => done(undefined),
357
+ );
358
+ })();
359
+ });
321
360
  }
322
361
 
323
362
  export async function newSession(app: App, presetName?: string) {
@@ -372,27 +411,50 @@ export async function newSession(app: App, presetName?: string) {
372
411
  */
373
412
  export function walkDirs(app: App, path: string): Promise<string | undefined | null> {
374
413
  return new Promise((done) => {
414
+ // r13 NIT (fixed run-14): the external-dismissal settle — see pickSession.
415
+ // One wrinkle unique to this flow: stepping DOWN a level legitimately
416
+ // closes this step's overlay to mount the next, and that close must NOT
417
+ // settle the walk (the promise stays pending across steps). The per-step
418
+ // `handoff` mark tells the overlay onClose "a successor owns the keyboard
419
+ // now"; only a dismissal with no successor resolves undefined.
420
+ let settled = false;
421
+ const settle = (v: string | undefined | null) => {
422
+ if (settled) return;
423
+ settled = true;
424
+ done(v);
425
+ };
375
426
  const step = async (at: string) => {
376
427
  // A cold tunnel lists in 2-20s — hold the message line so the silence
377
428
  // never reads as a dead app (R4 finding 8).
378
429
  app.setPending(`listing ${at || "start dirs"} on ${app.device.name}…`);
379
430
  const listing = await app.client.dirs(at).catch((e: Error) => (app.flash(e.message, true), undefined));
380
431
  app.setPending(null);
381
- if (!listing) return done(null);
432
+ if (!listing) return settle(null);
382
433
  const items: SelectItem[] = [
383
434
  ...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${oneLine(String(listing.path ?? ""))}` }] : []),
384
435
  ...(listing.path ? [{ value: listing.parent ?? "", label: listing.parent ? ".." : "⌂ start dirs" }] : []),
385
436
  ...listing.dirs.map((d) => ({ value: d.path, label: `${oneLine(String(d.name ?? ""))}/` })),
386
437
  ];
438
+ let handoff = false;
387
439
  app.overlay(
388
440
  new Picker(`Working directory on ${oneLine(String(app.device.name ?? ""))}`, items, (item) => {
389
- app.closeOverlay();
390
- if (item.value.startsWith("use:")) done(item.value.slice(4));
391
- else void step(item.value);
441
+ if (item.value.startsWith("use:")) {
442
+ // Settle BEFORE the close: the close fires the overlay onClose,
443
+ // and first-wins resolution must let the PICKED path win.
444
+ settle(item.value.slice(4));
445
+ app.closeOverlay();
446
+ } else {
447
+ handoff = true;
448
+ app.closeOverlay();
449
+ void step(item.value);
450
+ }
392
451
  }, () => {
393
452
  app.closeOverlay();
394
- done(undefined);
453
+ settle(undefined);
395
454
  }),
455
+ () => {
456
+ if (!handoff) settle(undefined);
457
+ },
396
458
  );
397
459
  };
398
460
  void step(path);
@@ -402,17 +464,19 @@ export function walkDirs(app: App, path: string): Promise<string | undefined | n
402
464
  function chooseModel(app: App, current?: string) {
403
465
  return new Promise<(typeof app.info.models)[number] | undefined>((done) => {
404
466
  const models = app.info.models;
467
+ // r13 NIT (fixed run-14): the overlay onClose settles the promise on
468
+ // external dismissal (app-level ctrl+c bypasses the picker's onCancel —
469
+ // see pickSession). Pick paths settle BEFORE closeOverlay so the picked
470
+ // model wins the first-wins resolution.
471
+ const settle = (m: (typeof app.info.models)[number] | undefined) => {
472
+ done(m);
473
+ app.closeOverlay();
474
+ };
405
475
  const picker = new Picker(
406
476
  `Model (${oneLine(String(app.device.name ?? ""))})`,
407
477
  models.map((m) => ({ value: `${m.provider}/${m.id}`, label: oneLine(String(m.name ?? "")), description: `${oneLine(String(m.tier ?? ""))} │ ${oneLine(String(m.provider ?? ""))}` })),
408
- (item) => {
409
- app.closeOverlay();
410
- done(models.find((m) => `${m.provider}/${m.id}` === item.value));
411
- },
412
- () => {
413
- app.closeOverlay();
414
- done(undefined);
415
- },
478
+ (item) => settle(models.find((m) => `${m.provider}/${m.id}` === item.value)),
479
+ () => settle(undefined),
416
480
  undefined,
417
481
  // The keyless device still lists the built-in catalog — say why chat
418
482
  // will fail, instead of letting the first request be the messenger.
@@ -422,7 +486,7 @@ function chooseModel(app: App, current?: string) {
422
486
  );
423
487
  const index = models.findIndex((m) => m.id === current);
424
488
  if (index >= 0) picker.list.setSelectedIndex(index);
425
- app.overlay(picker);
489
+ app.overlay(picker, () => done(undefined));
426
490
  });
427
491
  }
428
492
 
@@ -433,22 +497,23 @@ function chooseModel(app: App, current?: string) {
433
497
  */
434
498
  export function pickThinking(app: App, current?: string) {
435
499
  return new Promise<ThinkingLevel | undefined>((done) => {
500
+ // r13 NIT (fixed run-14): same settle-before-close wiring as pickSession —
501
+ // an externally dismissed overlay (ctrl+c at app level) resolves undefined
502
+ // instead of hanging the /thinking chain.
503
+ const settle = (level: ThinkingLevel | undefined) => {
504
+ done(level);
505
+ app.closeOverlay();
506
+ };
436
507
  const picker = new Picker(
437
508
  "Thinking level",
438
509
  THINKING_LEVELS.map((level) => ({ value: level, label: level })),
439
- (item) => {
440
- app.closeOverlay();
441
- done(item.value as ThinkingLevel);
442
- },
443
- () => {
444
- app.closeOverlay();
445
- done(undefined);
446
- },
510
+ (item) => settle(item.value as ThinkingLevel),
511
+ () => settle(undefined),
447
512
  );
448
513
  const wanted = current && THINKING_LEVELS.includes(current as ThinkingLevel) ? current : "medium";
449
514
  const index = THINKING_LEVELS.indexOf(wanted as ThinkingLevel);
450
515
  if (index >= 0) picker.list.setSelectedIndex(index);
451
- app.overlay(picker);
516
+ app.overlay(picker, () => done(undefined));
452
517
  });
453
518
  }
454
519
 
@@ -827,3 +892,293 @@ export async function pickNotify(app: App) {
827
892
  ),
828
893
  );
829
894
  }
895
+
896
+ // ---------------------------------------------- run-13: :archive
897
+ // The SDK's archive surface (policy #3): list bundles, read a transcript,
898
+ // restore. NO delete door — the SDK exposes no endpoint, and the palette does
899
+ // not invent one (run-13 scope). fmtBytes/fmtDur come from commands.ts (their
900
+ // home since run-12); the import is function-referenced only, so the benign
901
+ // pickers↔commands cycle is safe under ESM live bindings.
902
+
903
+ /** Transcript dump caps (run-13 A2, the r9 diagnostics-caps pattern): the log
904
+ * view is a 500-entry ring, so one :archive enter may add at most 400 lines /
905
+ * 100 KiB, with a LEADING marker naming what was cut — never a silent crop.
906
+ * Each surviving line is sanitizeTerminal'd HERE: logEvent writes its text
907
+ * verbatim (no normalizer downstream), so this helper is the chokepoint. */
908
+ const TRANSCRIPT_MAX_LINES = 400;
909
+ const TRANSCRIPT_MAX_BYTES = 100 * 1024;
910
+
911
+ export function capTranscriptLines(
912
+ text: string,
913
+ opts?: { maxLines?: number; maxBytes?: number },
914
+ ): string[] {
915
+ // run-14: :graphs detail rides the same helper with a tighter line budget;
916
+ // the defaults keep the r13 :archive contract byte-for-byte (the r13 tests
917
+ // pin the marker format AND both caps — do not shift them silently).
918
+ const maxLines = opts?.maxLines ?? TRANSCRIPT_MAX_LINES;
919
+ const maxBytes = opts?.maxBytes ?? TRANSCRIPT_MAX_BYTES;
920
+ const raw = String(text ?? "");
921
+ let cut = false;
922
+ let body = raw;
923
+ if (Buffer.byteLength(body, "utf8") > maxBytes) {
924
+ // Byte-boundary cut on the UTF-8 encoding (a char-count slice could leave
925
+ // up to 4× the budget for multibyte text); toString drops any dangling
926
+ // multibyte fragment as U+FFFD.
927
+ cut = true;
928
+ body = Buffer.from(body, "utf8").subarray(0, maxBytes).toString("utf8");
929
+ }
930
+ const total = raw.split("\n").length;
931
+ const all = body.split("\n");
932
+ const lines = all.slice(0, maxLines);
933
+ if (all.length > maxLines) cut = true;
934
+ const out = lines.map((l) => sanitizeTerminal(l));
935
+ if (cut) {
936
+ // The count names the lines the operator will not see (a byte cut can hide
937
+ // more than the count shows — it is a lower bound, still honest).
938
+ const dropped = Math.max(1, total - lines.length);
939
+ out.unshift(`... truncated (${dropped} line${dropped === 1 ? "" : "s"})`);
940
+ }
941
+ return out;
942
+ }
943
+
944
+ /** /archive (run-13 A2): archived sessions, newest first. Every device-
945
+ * authored field goes through oneLine INCLUDING the label path — pi-tui
946
+ * LF-normalizes descriptions only, so label strings must be collapsed at
947
+ * compose time (the r12 m1 lesson, pinned by test). Enter keeps the list up
948
+ * (reading is read-only, the pickNotify pattern) and dumps the markdown
949
+ * transcript into the log view through the caps above; r restores behind the
950
+ * same y/n gate /reset uses, then the list refetches without the row. */
951
+ export async function pickArchived(app: App) {
952
+ let list: ArchivedView[];
953
+ try {
954
+ list = (await app.client.archived()).sessions;
955
+ } catch (e) {
956
+ return app.notify(`archive: ${(e as Error).message.slice(0, 80)}`, true);
957
+ }
958
+ if (!list.length) return app.notify("no archived sessions on this device");
959
+ // archivedAt is relay-borne — coerce (a string/garbage field must not break
960
+ // the sort, R19 discipline) and sort newest-first.
961
+ const sessions = [...list].sort((a, b) => (Number(b.archivedAt) || 0) - (Number(a.archivedAt) || 0));
962
+ const items: SelectItem[] = sessions.map((s) => ({
963
+ // value is never rendered (filter matches label+description only) — keep
964
+ // the RAW id so transcript/restore hit the device's true session.
965
+ value: String(s.sessionId ?? ""),
966
+ label: `${s.hasManifest === true ? "◈" : "◇"} ${oneLine(String(s.name ?? ""))}`,
967
+ description: `${oneLine(String(s.cwd ?? ""))} · ${oneLine(String(Number(s.turns) || 0))} turns · ${fmtBytes(Number(s.bytes) || 0)} · archived ${fmtDur(Math.max(0, (Date.now() - (Number(s.archivedAt) || 0)) / 1000))} ago`,
968
+ }));
969
+ const showTranscript = async (item: SelectItem) => {
970
+ const s = sessions.find((x) => x.sessionId === item.value);
971
+ const label = oneLine(String(s?.name ?? item.value));
972
+ try {
973
+ const view = await app.client.archivedTranscript(item.value, "markdown");
974
+ const raw = String(view.text ?? "");
975
+ if (!raw.trim()) return app.notify(`transcript: ${label} is empty`);
976
+ const lines = capTranscriptLines(raw);
977
+ // Raw markdown is fine — the TUI does not render md, it prints lines.
978
+ for (const line of lines) app.logEvent("arch", line);
979
+ app.notify(`${label} — transcript, ${lines.length} line${lines.length === 1 ? "" : "s"} (log view: L)`);
980
+ } catch (e) {
981
+ app.notify(`transcript: ${(e as Error).message.slice(0, 80)}`, true);
982
+ }
983
+ };
984
+ const restore = async (item: SelectItem) => {
985
+ const s = sessions.find((x) => x.sessionId === item.value);
986
+ const label = oneLine(String(s?.name ?? item.value));
987
+ // The same y/n gate /reset and /schedules d ask (R4 finding 4): a
988
+ // state-changing door confirms; esc or anything not starting with y keeps
989
+ // the bundle archived.
990
+ const ok = await app.prompt(`Restore ${label}? y/n`, "");
991
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
992
+ return app.flash("restore cancelled"), undefined;
993
+ app.closeOverlay();
994
+ await app.run(async () => {
995
+ const restored = await app.client.restoreArchived(item.value);
996
+ const name = oneLine(String((restored as { name?: string })?.name ?? label));
997
+ // The app's session list refetches on its next view entry — no hook
998
+ // needed; the toast points the operator at g.
999
+ app.notify(`restored ${name} — press g to open it`);
1000
+ app.logEvent("arch", `restored ${name}`);
1001
+ });
1002
+ // The row is gone on the device — refetch instead of showing a stale list
1003
+ // (the pickSchedules d pattern).
1004
+ void pickArchived(app);
1005
+ };
1006
+ app.overlay(
1007
+ new ActionPicker(
1008
+ `Archived on ${oneLine(app.device.id)}`,
1009
+ items,
1010
+ (item) => void showTranscript(item),
1011
+ () => app.closeOverlay(),
1012
+ "enter transcript · r restore · esc close",
1013
+ { r: restore },
1014
+ "◈ manifest · ◇ bundle only",
1015
+ ),
1016
+ );
1017
+ }
1018
+
1019
+ // ---------------------------------------------- run-14: :graphs
1020
+ // The last uncovered SDK surface (client.graphs/graph/runGraph/removeGraph).
1021
+ // The palette is a keyboard, not a DAG editor: NO create/update door — the
1022
+ // web FE owns graph authoring (run-14 Unit A scope). The TUI lists, dumps
1023
+ // detail, fires a run and removes behind the same y/n gate the other
1024
+ // destructive doors use. Every device-authored field (graph name, cwd, task
1025
+ // names/ids/deps, run ids/status) goes through oneLine INCLUDING the label
1026
+ // path — pi-tui never LF-normalizes labels (the r12 m1 lesson, pinned by
1027
+ // test in tui-graphs-r14.test.ts).
1028
+
1029
+ /** Detail cap (run-14): the :archive convention — the dump adds at most this
1030
+ * many body lines to the 500-entry log ring, plus the LEADING truncation
1031
+ * marker when it cut (same counting :archive's 400 uses). */
1032
+ const GRAPH_DETAIL_MAX_LINES = 200;
1033
+
1034
+ /** Runs the detail view shows — the newest 10; older ones stay on the device
1035
+ * (a 100-run graph would flood the log ring for no reading value). */
1036
+ const GRAPH_DETAIL_MAX_RUNS = 10;
1037
+
1038
+ /** lastRun glyph for the row label — the status IS the vocabulary:
1039
+ * ✓ ok · ✗ failed · ● running · ⏸ interrupted · ◇ never ran. */
1040
+ const graphRunGlyph = (status: string) =>
1041
+ status === "ok" ? "✓" : status === "failed" ? "✗" : status === "running" ? "●" : status === "interrupted" ? "⏸" : "◇";
1042
+
1043
+ /** The lastRun half of a row: "ok 1m ago" / "never run". Age is measured
1044
+ * from finishedAt when the run closed, else startedAt (a running graph has
1045
+ * no finish yet); a garbage timestamp degrades to no age, never a NaN row. */
1046
+ const graphRunState = (run: GraphRunRecord | undefined, now: number): string => {
1047
+ if (!run) return "never run";
1048
+ const t = Date.parse(String(run.finishedAt ?? run.startedAt ?? ""));
1049
+ const age = Number.isFinite(t) && t > 0 ? ` ${fmtDur(Math.max(0, (now - t) / 1000))} ago` : "";
1050
+ return `${oneLine(String(run.status ?? "?"))}${age}`;
1051
+ };
1052
+
1053
+ /**
1054
+ * The :graphs detail dump — pure for tests (now is injectable). Graph meta,
1055
+ * one line per task (id · name · deps · model), then the last ≤10 runs with
1056
+ * per-run ok/total counts. Every field is device-authored: logEvent writes
1057
+ * verbatim, so a task name must never split its own log line (r12 m1). The
1058
+ * caller caps the joined text through capTranscriptLines.
1059
+ */
1060
+ export function graphDetailLines(graph: GraphRecord, runs: GraphRunRecord[], now = Date.now()): string[] {
1061
+ const tasks = Array.isArray(graph.tasks) ? graph.tasks : [];
1062
+ const age = (iso: unknown) => {
1063
+ const t = Date.parse(String(iso ?? ""));
1064
+ return Number.isFinite(t) && t > 0 ? fmtDur(Math.max(0, (now - t) / 1000)) : "?";
1065
+ };
1066
+ const lines: string[] = [
1067
+ `${oneLine(String(graph.name ?? "?"))} — ${tasks.length} task${tasks.length === 1 ? "" : "s"} · ${oneLine(String(graph.cwd ?? ""))}`,
1068
+ `created ${age(graph.createdAt)} ago · updated ${age(graph.updatedAt)} ago${graph.archivedAt ? " · archived" : ""}`,
1069
+ ];
1070
+ for (const t of tasks)
1071
+ lines.push(
1072
+ ` ${oneLine(String(t?.id ?? "?"))} ${oneLine(String(t?.name ?? "?"))} · deps [${(Array.isArray(t?.dependsOn) ? t.dependsOn : [])
1073
+ .map((d) => oneLine(String(d)))
1074
+ .join(", ")}]${t?.model ? ` · ${oneLine(String(t.model?.provider ?? "?"))}/${oneLine(String(t.model?.modelId ?? "?"))}` : ""}`,
1075
+ );
1076
+ lines.push("");
1077
+ const recent = (Array.isArray(runs) ? runs : []).slice(-GRAPH_DETAIL_MAX_RUNS);
1078
+ if (!recent.length) {
1079
+ lines.push("no runs yet");
1080
+ return lines;
1081
+ }
1082
+ lines.push(`last ${recent.length} run${recent.length === 1 ? "" : "s"}:`);
1083
+ for (const run of recent) {
1084
+ const states = Object.values(run?.tasks ?? {});
1085
+ const total = states.length;
1086
+ const ok = states.filter((s) => s?.status === "ok").length;
1087
+ const failed = states.filter((s) => s?.status === "failed").length;
1088
+ lines.push(
1089
+ ` run ${oneLine(String(run?.id ?? "?"))} · ${oneLine(String(run?.status ?? "?"))} · ${ok}/${total} ok${failed ? ` · ${failed} failed` : ""} · started ${age(run?.startedAt)} ago${run?.finishedAt ? ` · finished ${age(run?.finishedAt)} ago` : ""}`,
1090
+ );
1091
+ }
1092
+ return lines;
1093
+ }
1094
+
1095
+ /** /graphs (run-14): list · enter detail · r run · d delete. No create door —
1096
+ * DAG editing belongs to the web FE. Enter keeps the list up (reading is
1097
+ * read-only, the pickArchived pattern) and dumps the capped detail into the
1098
+ * log view; r/d close + refetch on fresh device state. */
1099
+ export async function pickGraphs(app: App) {
1100
+ let list: Array<GraphRecord & { lastRun?: GraphRunRecord }>;
1101
+ try {
1102
+ list = (await app.client.graphs()).graphs;
1103
+ } catch (e) {
1104
+ return app.notify(`graphs: ${(e as Error).message.slice(0, 80)}`, true);
1105
+ }
1106
+ if (!list.length)
1107
+ return app.notify("no task-graphs on this device — create one in the web FE");
1108
+ // Sort by name — the oneLine'd name, so hostile whitespace cannot reorder
1109
+ // the rows either (the rows are composed from the same fold).
1110
+ const graphs = [...list].sort((a, b) =>
1111
+ oneLine(String(a.name ?? "")).localeCompare(oneLine(String(b.name ?? ""))),
1112
+ );
1113
+ const now = Date.now();
1114
+ const items: SelectItem[] = graphs.map((g) => {
1115
+ const n = Array.isArray(g.tasks) ? g.tasks.length : 0;
1116
+ return {
1117
+ // value is never rendered — keep the RAW id so detail/run/remove hit the
1118
+ // device's true graph (same rule as pickArchived's session ids).
1119
+ value: String(g.id ?? ""),
1120
+ label: `${graphRunGlyph(String(g.lastRun?.status ?? ""))} ${oneLine(String(g.name ?? ""))}`,
1121
+ description: `${n} task${n === 1 ? "" : "s"} · ${oneLine(String(g.cwd ?? ""))} · last ${graphRunState(g.lastRun, now)}`,
1122
+ };
1123
+ });
1124
+ // r14 review n7: a graph whose name is "" falls through to the id — the
1125
+ // ?? only catches nullish, and an empty toast ("removed ") reads as a bug.
1126
+ const labelOf = (id: string) => {
1127
+ const name = oneLine(String(graphs.find((x) => x.id === id)?.name ?? ""));
1128
+ return name || oneLine(id);
1129
+ };
1130
+ const showDetail = async (item: SelectItem) => {
1131
+ const label = labelOf(item.value);
1132
+ try {
1133
+ const { graph, runs } = await app.client.graph(item.value);
1134
+ const lines = capTranscriptLines(graphDetailLines(graph, runs).join("\n"), {
1135
+ maxLines: GRAPH_DETAIL_MAX_LINES,
1136
+ });
1137
+ for (const line of lines) app.logEvent("graph", line);
1138
+ app.notify(`${label} — detail, ${lines.length} line${lines.length === 1 ? "" : "s"} (log view: L)`);
1139
+ } catch (e) {
1140
+ app.notify(`graph: ${(e as Error).message.slice(0, 80)}`, true);
1141
+ }
1142
+ };
1143
+ app.overlay(
1144
+ new ActionPicker(
1145
+ `Graphs on ${oneLine(app.device.id)}`,
1146
+ items,
1147
+ (item) => void showDetail(item),
1148
+ () => app.closeOverlay(),
1149
+ "enter detail · r run · d delete · esc close",
1150
+ {
1151
+ // Fire-and-forget by design (run-14): the device owns the run; the TUI
1152
+ // toasts "started" and does NOT poll or attach — results land in this
1153
+ // same detail view on the next visit (or the tasks tab).
1154
+ r: async (item) => {
1155
+ const label = labelOf(item.value);
1156
+ app.closeOverlay();
1157
+ await app.run(async () => {
1158
+ await app.client.runGraph(item.value);
1159
+ app.notify(`graph ${label} started`);
1160
+ app.logEvent("graph", `${label} run fired by hand`);
1161
+ });
1162
+ void pickGraphs(app);
1163
+ },
1164
+ d: async (item) => {
1165
+ const label = labelOf(item.value);
1166
+ // The same y/n gate /reset and /schedules d ask (R4 finding 4): a
1167
+ // destructive door confirms; esc or anything not starting with y
1168
+ // keeps the graph.
1169
+ const ok = await app.prompt(`Remove graph ${label}? y/n`, "");
1170
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
1171
+ return app.flash("remove cancelled"), undefined;
1172
+ app.closeOverlay();
1173
+ await app.run(async () => {
1174
+ await app.client.removeGraph(item.value);
1175
+ app.notify(`removed ${label}`);
1176
+ app.logEvent("graph", `removed ${label}`);
1177
+ });
1178
+ void pickGraphs(app);
1179
+ },
1180
+ },
1181
+ "run/remove only — DAG editing lives in the web FE",
1182
+ ),
1183
+ );
1184
+ }
@@ -311,13 +311,21 @@ export function renderHeader(
311
311
  devicesTotal?: number;
312
312
  conn: string;
313
313
  connOk: boolean;
314
+ /**
315
+ * run-14 (hub resilience): a countdown to the next reconnect attempt
316
+ * (`↻12s`), appended to the conn chip while the hub is OFFLINE so the
317
+ * operator sees WHEN the retry fires instead of a dead `hub offline`.
318
+ * Absent (live, connecting, direct devices) → byte-identical to the
319
+ * pre-run-14 render — the r12/r13 header tests pin those bytes.
320
+ */
321
+ retry?: string;
314
322
  },
315
323
  ): string {
316
324
  const left = [
317
325
  `${c.accent("▲")} ${c.bold("dpi")}`,
318
326
  c.muted("tui"),
319
327
  c.muted("│"),
320
- `${opts.connOk ? c.ok("●") : c.err("○")} ${c.text(opts.conn)}`,
328
+ `${opts.connOk ? c.ok("●") : c.err("○")} ${c.text(opts.conn)}${opts.retry ? c.muted(` · ${opts.retry}`) : ""}`,
321
329
  c.muted(`${opts.sessions} session${opts.sessions === 1 ? "" : "s"}`),
322
330
  opts.devicesTotal !== undefined
323
331
  ? c.muted(`${opts.devicesOnline ?? 0}/${opts.devicesTotal} devices`)
@@ -492,7 +500,7 @@ export function renderOps(
492
500
  // loadavg cannot express, and gitSpawns' queued(+high) is the number
493
501
  // that says "a status fan-out is stalling the panel" (run-11 h2-2).
494
502
  ` ${c.muted("evlag")} ${c.text(`${Math.round(Number(v.eventLoop?.lagMsLast) || 0)}ms`)} ${c.muted("last")} ${c.text(`${Math.round(Number(v.eventLoop?.lagMsMax1m) || 0)}ms`)} ${c.muted("max 1m")} ${c.muted(`${Number(v.eventLoop?.samples) || 0} samples`)}`,
495
- ` ${c.muted("git")} ${c.text(`${Number(v.gitSpawns?.live) || 0} live`)} ${c.muted("·")} ${c.text(`${Number(v.gitSpawns?.queued) || 0} queued`)}${Number(v.gitSpawns?.queuedHigh) > 0 ? c.warn(` · ${Number(v.gitSpawns.queuedHigh)} high`) : ""}`,
503
+ ` ${c.muted("git")} ${c.text(`${Number(v.gitSpawns?.live) || 0} live`)} ${c.muted("·")} ${c.text(`${Number(v.gitSpawns?.queued) || 0} queued`)}${Number(v.gitSpawns?.queuedHigh) > 0 ? c.warn(` · ${Number(v.gitSpawns.queuedHigh)} high`) : ""}${Number(v.gitSpawns?.queuedAged) > 0 ? c.warn(` · ${Number(v.gitSpawns.queuedAged)} aged`) : ""}`,
496
504
  ];
497
505
  if (v.counts)
498
506
  out.push(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.119",
3
+ "version": "0.0.121",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {