my-durable 0.0.57 → 0.0.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/apps/dpi-backend/scripts/check-contract.mjs +9 -2
  2. package/apps/dpi-backend/src/env-vars.ts +10 -1
  3. package/apps/dpi-backend/src/errors.ts +71 -2
  4. package/apps/dpi-backend/src/gc-cli.ts +24 -17
  5. package/apps/dpi-backend/src/gc.ts +3 -1
  6. package/apps/dpi-backend/src/git.ts +26 -6
  7. package/apps/dpi-backend/src/idempotency.ts +47 -1
  8. package/apps/dpi-backend/src/notify-sinks.ts +42 -8
  9. package/apps/dpi-backend/src/pi-config.ts +43 -8
  10. package/apps/dpi-backend/src/routes.ts +6 -2
  11. package/apps/dpi-backend/src/store.ts +285 -18
  12. package/apps/dpi-backend/src/tunnel.ts +24 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C9ulm0b-.js → index-DC0Iicch.js} +7 -7
  14. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-C8I93zWz.css → index-DxGrKN6X.css} +1 -1
  15. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +28 -4
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +13 -4
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/OfflinePanel.vue +6 -6
  19. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +20 -6
  20. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +67 -29
  21. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
  22. package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +7 -1
  23. package/apps/dpi-sdk/src/node/ops.ts +1 -0
  24. package/apps/dpi-tui/src/app.ts +217 -49
  25. package/apps/dpi-tui/src/commands.ts +57 -22
  26. package/apps/dpi-tui/src/pickers.ts +55 -18
  27. package/apps/dpi-tui/src/scroll.ts +59 -0
  28. package/apps/dpi-tui/src/views.ts +17 -2
  29. package/apps/dpi-tui/src/wrap.ts +42 -0
  30. package/bin/update.mjs +2 -1
  31. package/package.json +1 -1
  32. package/scripts/verify.mjs +7 -0
@@ -8,7 +8,9 @@ import {
8
8
  ProcessTerminal,
9
9
  TuiAltScreen,
10
10
  matchesKey,
11
+ sliceByColumn,
11
12
  truncateToWidth,
13
+ visibleWidth,
12
14
  type Component,
13
15
  type OverlayHandle,
14
16
  type TuiInputListenerResult,
@@ -35,6 +37,7 @@ import {
35
37
  renderNetwork,
36
38
  renderStatusbar,
37
39
  renderViewbar,
40
+ gitStateSuffix,
38
41
  herdRows,
39
42
  joinPanel,
40
43
  networkRows,
@@ -42,7 +45,9 @@ import {
42
45
  } from "./views.ts";
43
46
  import { appendFileSync } from "node:fs";
44
47
  import { fetchHubNetwork } from "./hub-feed.ts";
45
- import { HubMux } from "./hub-mux.ts";
48
+ import { HubMux, type MuxState } from "./hub-mux.ts";
49
+ import { FOLLOW_TAIL, scrollBy, viewportTop, type ScrollState } from "./scroll.ts";
50
+ import { wrapByColumn } from "./wrap.ts";
46
51
  import { box, c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
47
52
 
48
53
  export interface DeviceRef {
@@ -162,7 +167,20 @@ export class App {
162
167
  helpOpen = false;
163
168
  toast = "";
164
169
  toastTicks = 0;
165
- scrollOffset = 0;
170
+ /** Transcript viewport (R5 findings 2+3): offset counts lines BACK from the
171
+ * tail (0 = follow it); scroll.ts holds the absolute-anchor math. */
172
+ private scrollState: ScrollState = FOLLOW_TAIL;
173
+ /** Public read for tests/debug: lines back from the tail. */
174
+ get scrollOffset(): number {
175
+ return this.scrollState.offset;
176
+ }
177
+ /** Last rendered transcript content length / inner height — scrollBy needs
178
+ * them at keypress time, when no frame width is known. */
179
+ private lastContentLen = 0;
180
+ private lastInner = 0;
181
+ /** Transcript length when last following the tail — content growth beyond
182
+ * this while scrolled up lights the "↓ new output" indicator (R5 finding 3). */
183
+ private followLen = 0;
166
184
  /** ctrl+o: show full tool output instead of the first lines. */
167
185
  expand = false;
168
186
  /** Slash autocomplete: which suggestion row is selected (0 = first). */
@@ -175,6 +193,10 @@ export class App {
175
193
  }
176
194
  /** The hub's /api/stream mux — tunnel-device attach (same transport as the web). */
177
195
  private mux?: HubMux;
196
+ /** Last mux state, surfaced in the header (R4 finding 5: the loss used to be silent). */
197
+ private muxState?: MuxState;
198
+ /** One-shot disconnect toast: shown once per outage, echoed by the reconnect note. */
199
+ private muxToastShown = false;
178
200
  /** True while the current device is reached through the hub proxy. */
179
201
  private viaHub = false;
180
202
  private hubRows: DeviceRow[] = [];
@@ -240,6 +262,8 @@ export class App {
240
262
  private deviceOnline = false;
241
263
  private events: { at: string; glyph: string; text: string }[] = [];
242
264
  private selectedId?: string;
265
+ /** Long-running fetch note (dirs on a cold tunnel, R4 finding 8): message line. */
266
+ private pendingNote: string | null = null;
243
267
 
244
268
  constructor(
245
269
  device: DeviceRef,
@@ -265,10 +289,7 @@ export class App {
265
289
  this.model.subscribe(() => this.requestRender());
266
290
  this.session.subscribe(() => this.requestRender());
267
291
  this.ticker = setInterval(() => this.tick(), 120);
268
- if (this.hub)
269
- void fetchHubNetwork(this.hub.url, this.hub.token).then((rows) => {
270
- if (rows) (this.hubRows = rows), this.requestRender();
271
- });
292
+ this.refreshHubNetwork();
272
293
  this.tui.start();
273
294
  void this.refreshSessions();
274
295
  this.requestRender();
@@ -297,7 +318,7 @@ export class App {
297
318
  this.handle = this.client.agent(sessionId, agentId);
298
319
  this.model.clear();
299
320
  if (!sameSession) this.session.clear();
300
- this.scrollOffset = 0;
321
+ this.scrollState = FOLLOW_TAIL;
301
322
  void this.refreshSessions();
302
323
  const handle = this.handle;
303
324
  // Hub-routed devices stream through the mux (same upstreams the web rides);
@@ -338,7 +359,7 @@ export class App {
338
359
  // (REST) + the hub's stream mux (events), exactly like the web FE.
339
360
  if (!this.hub) return this.notify(`${row.name} is tunnel-only — start the TUI with --hub-url/--hub-token`, true);
340
361
  const client = new DpiClient(`${this.hub.url}/api/devices/${row.id}`, this.hub.token);
341
- this.mux ??= new HubMux(this.hub);
362
+ this.mux ??= new HubMux(this.hub, (state) => this.onMuxState(state));
342
363
  return void this.run(async () => {
343
364
  this.info = await client.device({ timeoutMs: 10_000 });
344
365
  this.streams?.abort();
@@ -384,6 +405,52 @@ export class App {
384
405
  }
385
406
  }
386
407
 
408
+ /** One /api/network poll — boot, tick, mux reconnect and network entry all ride this. */
409
+ private refreshHubNetwork() {
410
+ if (!this.hub) return;
411
+ void fetchHubNetwork(this.hub.url, this.hub.token).then((rows) => {
412
+ if (rows) {
413
+ this.hubRows = rows;
414
+ if (this.view === "network") this.devicesCache = this.networkDevices();
415
+ this.requestRender();
416
+ }
417
+ });
418
+ }
419
+
420
+ /**
421
+ * Hub mux state → header chip + one-shot toast. Live-caught (R4 finding 5):
422
+ * killing the hub left the header at stale `● live` with zero feedback — the
423
+ * agent stream never errors, it just stops delivering frames.
424
+ */
425
+ private onMuxState(state: MuxState) {
426
+ this.muxState = state;
427
+ if (state === "offline") {
428
+ if (!this.muxToastShown) {
429
+ this.muxToastShown = true;
430
+ this.notify("hub offline — reconnecting…", true);
431
+ }
432
+ } else if (state === "live") {
433
+ if (this.muxToastShown) {
434
+ this.muxToastShown = false;
435
+ this.notify("hub back online");
436
+ }
437
+ // Frames flow again: re-fetch the network rows that froze with the old
438
+ // connection (R4 finding 6 — the view stayed empty through every switch).
439
+ this.refreshHubNetwork();
440
+ // …and re-fetch the device info (R5 finding 5): the model catalog rode
441
+ // the boot-time /device fetch, so after a reconnect the cached catalog
442
+ // could miss the session's model and the ctx bar died ("ctx —").
443
+ void this.client
444
+ .device({ timeoutMs: 10_000 })
445
+ .then((info) => {
446
+ this.info = info;
447
+ this.requestRender();
448
+ })
449
+ .catch(() => {});
450
+ }
451
+ this.requestRender();
452
+ }
453
+
387
454
  /** The open session's working folder — what /git operates on. */
388
455
  cwd(): string | undefined {
389
456
  return this.sessionSummary()?.cwd ?? undefined;
@@ -407,10 +474,15 @@ export class App {
407
474
  setView(view: View) {
408
475
  this.view = view;
409
476
  this.cursor = 0;
410
- this.scrollOffset = 0;
477
+ this.scrollState = FOLLOW_TAIL;
411
478
  if (view === "herd") void this.refreshSessions();
412
479
  if (view === "herd") this.refreshBranches();
413
- if (view === "network") this.devicesCache = this.networkDevices();
480
+ if (view === "network") {
481
+ this.devicesCache = this.networkDevices();
482
+ // Entering an empty network view while the mux is live means the rows were
483
+ // lost with a reconnecting hub — poll once instead of waiting out the tick.
484
+ if (!this.devicesCache.length && this.mux?.live) this.refreshHubNetwork();
485
+ }
414
486
  this.requestRender();
415
487
  }
416
488
 
@@ -418,11 +490,14 @@ export class App {
418
490
  // The hub feed is the same source the web sidebar renders; fall back to
419
491
  // the local registry when no hub is configured or before the first poll.
420
492
  let rows = this.hubRows.length ? this.hubRows : this.registry ? this.registry.list() : [];
421
- // The current device also appears as a hub row (same deviceUid) — drop
422
- // that one and keep the direct LAN row, but inherit the hub's tree so its
423
- // sessions still list here.
493
+ // The current device also appears as a hub row (same deviceUid) — drop that
494
+ // one ONLY when a sibling row for the same device survives (the direct LAN
495
+ // row, whose tree the hub row was enriching). A tunnel-only current device
496
+ // must keep its hub row: dropping the only row emptied the network view
497
+ // through every view switch (R4 finding 6).
424
498
  const mine = this.info?.uid ? rows.find((r) => r.deviceUid === this.info!.uid) : undefined;
425
- if (mine) rows = rows.filter((r) => r !== mine);
499
+ if (mine && rows.some((r) => r !== mine && r.deviceUid === mine.deviceUid))
500
+ rows = rows.filter((r) => r !== mine);
426
501
  if (this.device.id !== "adhoc" || rows.some((r) => r.id === "adhoc")) return rows;
427
502
  return [
428
503
  ...rows,
@@ -562,6 +637,25 @@ export class App {
562
637
  this.notify(`thinking: ${next}`);
563
638
  }
564
639
 
640
+ /**
641
+ * Shared reset tail. The x key lands here AFTER its own y/n line; the /reset
642
+ * command door asks its own confirm first (R4 finding 4 — the command used to
643
+ * wipe the context with no question at all).
644
+ */
645
+ resetContext(note?: string) {
646
+ if (!this.handle) return Promise.resolve(this.notify("Pick a session first (g, then ↵).", true));
647
+ return this.run(async () => {
648
+ await this.handle!.reset(note);
649
+ this.notify("New context started; history stays stored");
650
+ });
651
+ }
652
+
653
+ /** A long fetch (dirs on a cold tunnel) holds the message line with a ◌ note. */
654
+ setPending(text: string | null) {
655
+ this.pendingNote = text;
656
+ this.requestRender();
657
+ }
658
+
565
659
  // ------------------------------------------------------------------- input
566
660
 
567
661
  handleInput(data: string): TuiInputListenerResult {
@@ -742,7 +836,9 @@ export class App {
742
836
  if (cmd) cmd.run(this);
743
837
  else this.notify(`no command “${value.trim()}”`);
744
838
  } else if (input.kind === "kill") {
745
- if (value.trim().toLowerCase().startsWith("y")) void this.command("reset");
839
+ // The x line IS the confirm — run the shared tail, not the command door
840
+ // (which asks its own y/n and would double-prompt).
841
+ if (value.trim().toLowerCase().startsWith("y")) void this.resetContext();
746
842
  else this.notify("reset cancelled");
747
843
  } else if (input.kind === "new") void newSession(this, value);
748
844
  return true;
@@ -795,7 +891,12 @@ export class App {
795
891
  private move(delta: number) {
796
892
  if (this.view === "agent" && this.tab === "transcript") {
797
893
  // Scroll the transcript instead of moving a cursor (herdr H04's lesson).
798
- this.scrollOffset = Math.max(0, this.scrollOffset + delta);
894
+ // R5 finding 2: the offset counts lines BACK from the tail, so adding the
895
+ // raw movement delta scrolled INTO history on j and clamped k dead at the
896
+ // bottom — exactly inverted. scrollBy's delta moves the absolute top
897
+ // line instead: j/↓ = +1 = toward newer, k/↑ = -1 = toward older — the
898
+ // directions the help panel has always promised.
899
+ this.scrollState = scrollBy(this.scrollState, delta, this.lastContentLen, this.lastInner);
799
900
  this.requestRender();
800
901
  return;
801
902
  }
@@ -842,15 +943,19 @@ export class App {
842
943
  }
843
944
  const index = AGENT_TABS.findIndex((t) => t.id === this.tab);
844
945
  this.tab = AGENT_TABS[(index + delta + AGENT_TABS.length) % AGENT_TABS.length]!.id;
845
- this.scrollOffset = 0;
946
+ this.scrollState = FOLLOW_TAIL;
846
947
  this.requestRender();
847
948
  }
848
949
 
849
950
  // ------------------------------------------------------------- overlays
850
951
 
851
952
  overlay(component: Component, onClose?: () => void) {
953
+ // minWidth 60 fits the widest picker hint ("↑↓/j/k move │ enter select │
954
+ // type to filter │ esc close" = 55 visible cols + padding) at a bare 80-col
955
+ // terminal — at the old 40 the hint's operative verb clipped to `esc c…`
956
+ // (R4 finding 7).
852
957
  this.overlays.push({
853
- handle: this.tui.showOverlay(component, { width: "70%", minWidth: 40, maxHeight: "80%" }),
958
+ handle: this.tui.showOverlay(component, { width: "70%", minWidth: 60, maxHeight: "80%" }),
854
959
  onClose,
855
960
  });
856
961
  this.tui.requestRender();
@@ -860,12 +965,17 @@ export class App {
860
965
  return this.overlays.length;
861
966
  }
862
967
 
863
- closeOverlay(exitIfNothing = false) {
968
+ /**
969
+ * Esc must never surprise-quit (the 0.0.52 decision): closing the last
970
+ * overlay lands on the live view, and quitting stays on q / ctrl+c / /quit.
971
+ * Live-caught (R4 finding 1): the session picker passed `exitIfNothing` so
972
+ * picker→Esc→Esc with no attached session silently killed the process.
973
+ */
974
+ closeOverlay() {
864
975
  const overlay = this.overlays.pop();
865
976
  overlay?.handle.hide();
866
977
  overlay?.onClose?.();
867
978
  if (!this.overlays.length) this.tui.setFocus(this.root);
868
- if (exitIfNothing) return this.exit();
869
979
  this.tui.requestRender();
870
980
  }
871
981
 
@@ -974,13 +1084,7 @@ export class App {
974
1084
  // paired from the CLI shows up while the operator is looking at the list.
975
1085
  if (this.hub && ++this.hubTick >= 42) {
976
1086
  this.hubTick = 0;
977
- void fetchHubNetwork(this.hub.url, this.hub.token).then((rows) => {
978
- if (rows) {
979
- this.hubRows = rows;
980
- if (this.view === "network") this.devicesCache = this.networkDevices();
981
- this.requestRender();
982
- }
983
- });
1087
+ this.refreshHubNetwork();
984
1088
  }
985
1089
  this.requestRender();
986
1090
  }
@@ -1014,6 +1118,18 @@ export class App {
1014
1118
 
1015
1119
  private header(w: number): string {
1016
1120
  const devices = this.registry ? this.networkDevices() : [];
1121
+ // A hub-routed device reports the MUX truth first: when the SSE died the
1122
+ // agent stream stays nominally "live" while frames stop (R4 finding 5).
1123
+ const hubDown = this.viaHub && this.mux && this.muxState !== "live";
1124
+ const conn = hubDown
1125
+ ? this.muxState === "offline"
1126
+ ? "hub offline"
1127
+ : "hub connecting"
1128
+ : this.connection === "live"
1129
+ ? "live"
1130
+ : this.connection === "idle"
1131
+ ? "no agent"
1132
+ : String(this.connection);
1017
1133
  return (
1018
1134
  " " +
1019
1135
  renderHeader(w - 2, {
@@ -1021,8 +1137,8 @@ export class App {
1021
1137
  sessions: this.sessions.length,
1022
1138
  devicesOnline: devices.filter((d) => d.lastStatus === "online").length,
1023
1139
  devicesTotal: devices.length || undefined,
1024
- conn: this.connection === "live" ? "live" : this.connection === "idle" ? "no agent" : String(this.connection),
1025
- connOk: this.connection === "live",
1140
+ conn,
1141
+ connOk: hubDown ? false : this.connection === "live",
1026
1142
  })
1027
1143
  );
1028
1144
  }
@@ -1092,11 +1208,17 @@ export class App {
1092
1208
  const filled = ctx === undefined ? 0 : Math.round((ctx / 100) * barW);
1093
1209
  const g = this.gitOf(session?.cwd);
1094
1210
  if (session?.cwd) this.refreshGit(session.cwd);
1095
- const gitChip = g?.repo ? ` ${c.muted("⎇")} ${c.text(g.branch ?? g.head ?? "")}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}` : "";
1211
+ // Merge/detached join the chip (R5 finding 4): the backend reports both,
1212
+ // the web shows a banner — the TUI used to show a healthy branch chip
1213
+ // while the repo was mid-merge with conflicts.
1214
+ const gitChip = g?.repo
1215
+ ? ` ${c.muted("⎇")} ${c.text(g.branch ?? g.head ?? "")}${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0) ? c.warn(` ±${(g.staged ?? 0) + (g.unstaged ?? 0) + (g.untracked ?? 0)}`) : ""}${g.merge ? c.err(gitStateSuffix(g)) : g.detached ? c.warn(gitStateSuffix(g)) : ""}`
1216
+ : "";
1096
1217
  lines.push(
1097
1218
  `${c.muted(this.device.id)} ${c.muted("›")} ${c.text(session?.name ?? "—")} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
1098
1219
  `${STATE_COLOR[state](STATE_GLYPH[state] + " " + (this.busy() ? "working" : "idle"))} ` +
1099
- `${c.muted("ctx")} ${ctx === undefined ? c.muted("—") : c.accent(rep("█", filled)) + c.muted(rep("░", barW - filled)) + " " + c.muted(`${ctx}%`)}`,
1220
+ // Catalog miss renders "?" not "—" (R5 finding 5): unknown window ≠ no usage.
1221
+ `${c.muted("ctx")} ${ctx === undefined ? c.muted("?") : c.accent(rep("█", filled)) + c.muted(rep("░", barW - filled)) + " " + c.muted(`${ctx}%`)}`,
1100
1222
  );
1101
1223
  lines.push(
1102
1224
  AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
@@ -1106,19 +1228,44 @@ export class App {
1106
1228
  lines.push(c.muted(rep(box.h, w)));
1107
1229
  const inner = h - 3;
1108
1230
  const content = this.agentContent(w);
1109
- const from = Math.max(0, content.length - inner - this.scrollOffset);
1110
- for (const line of content.slice(from, from + inner)) lines.push(line);
1231
+ // R5 finding 3: the viewport top is an ABSOLUTE anchor while scrolled up —
1232
+ // new frames must not slide the page under the user. Only offset 0 (tail)
1233
+ // follows the growth.
1234
+ const view = viewportTop(this.scrollState, content.length, inner);
1235
+ this.scrollState = view.state;
1236
+ const newBelow = this.scrollState.offset > 0 && content.length > this.followLen;
1237
+ if (this.scrollState.offset === 0) this.followLen = content.length;
1238
+ this.lastContentLen = content.length;
1239
+ this.lastInner = inner;
1240
+ for (const line of content.slice(view.from, view.from + inner)) lines.push(line);
1241
+ if (newBelow) {
1242
+ // The "↓ new output" hint configured on the TuiAltScreen never renders —
1243
+ // pi-tui draws it only for its own scroll views, and ours is app-owned
1244
+ // (R5 finding 3). Center it on the last body row while scrolled up and
1245
+ // frames landed below.
1246
+ const at = lines.length - 1;
1247
+ lines[at] = this.composeIndicator(lines[at] ?? "", w);
1248
+ }
1111
1249
  return lines.slice(0, h);
1112
1250
  }
1113
1251
 
1252
+ /** Overlay the "↓ new output" label onto a body row, centered, content kept. */
1253
+ private composeIndicator(row: string, width: number): string {
1254
+ const label = truncateToWidth(c.muted(" ↓ new output "), Math.max(0, width - 2), "");
1255
+ const labelWidth = visibleWidth(label);
1256
+ if (!labelWidth) return row;
1257
+ const col = Math.max(0, Math.floor((width - labelWidth) / 2));
1258
+ const left = truncateToWidth(row, col, "");
1259
+ const right = sliceByColumn(row, col + labelWidth, Math.max(0, width - col - labelWidth), true);
1260
+ return left + label + right;
1261
+ }
1262
+
1114
1263
  /** The transcript/tasks/tools/state/config tabs, from the REAL model state. */
1115
1264
  private agentContent(w: number): string[] {
1116
1265
  const s = this.model.state;
1117
- const wrap = (text: string, indent = " ") =>
1118
- text
1119
- .split("\n")
1120
- .flatMap((l) => (l.length > w - 4 ? [l.slice(0, w - 4), l.slice(w - 4)] : [l]))
1121
- .map((l) => indent + l);
1266
+ // Display-width loop wrap (R5 finding 1): the old single-split leaked the
1267
+ // remainder of every overlong line to pi-tui's hard clip. See wrap.ts.
1268
+ const wrap = (text: string, indent = " ") => wrapByColumn(text, w, indent);
1122
1269
  if (this.tab === "transcript") {
1123
1270
  const lines: string[] = [];
1124
1271
  let turn = 0;
@@ -1245,6 +1392,7 @@ export class App {
1245
1392
  return " " + `${c.muted(this.toast)}${c.text(shown)}${c.accent("▌")}`.slice(0, w);
1246
1393
  }
1247
1394
  if (this.toast) return " " + `${this.toast.startsWith("✗") ? c.err(this.toast) : c.accent("◆") + " " + c.text(this.toast)}`.slice(0, w);
1395
+ if (this.pendingNote) return " " + c.warn(`◌ ${this.pendingNote}`).slice(0, w);
1248
1396
  if (this.view === "agent") {
1249
1397
  const hint =
1250
1398
  this.tab === "transcript"
@@ -1291,25 +1439,45 @@ export class App {
1291
1439
 
1292
1440
  private helpPanel(w: number, h: number): string[] {
1293
1441
  const width = Math.min(76, w - 4);
1442
+ // Column-aligned by MEASURED visible width (R5 finding 6): the hand-spaced
1443
+ // rows drifted every time a label changed — "↵"-style keys made raw
1444
+ // padding lie, so pad on visibleWidth before styling.
1445
+ const keys: { k1: string; d1: string; k2?: string; d2?: string; muted?: boolean }[] = [
1446
+ { k1: "j k ↑ ↓", d1: "move/scroll", k2: "1-4", d2: "views: net/herd/agent/log" },
1447
+ { k1: "↵", d1: "open", k2: "g N L", d2: "same views, aliases" },
1448
+ { k1: "[ ] t", d1: "agent tabs", k2: "m", d2: "message (enter sends)" },
1449
+ // esc is BACK only (R5 finding 7): it never interrupts (the 0.0.52/0.0.58
1450
+ // invariant — interrupting a running turn is destructive and keeps its
1451
+ // own key, `i`). The old "back/interrupt" label taught a key that does
1452
+ // nothing and hid the one that does.
1453
+ { k1: "esc", d1: "back", k2: "i", d2: "interrupt ≠ kill" },
1454
+ { k1: "F", d1: "fork", k2: "c", d2: "compact context" },
1455
+ { k1: "y", d1: "thinking level", k2: "x", d2: "reset (y/n confirm)" },
1456
+ { k1: "alt+↵", d1: "send now, no steer", k2: "ctrl+l", d2: "model picker", muted: true },
1457
+ { k1: "tab", d1: "complete /command", k2: "↑", d2: "recall sent", muted: true },
1458
+ { k1: "ctrl+o", d1: "expand tool output", muted: true },
1459
+ { k1: ":", d1: "palette", k2: "f", d2: "filter rows" },
1460
+ { k1: "n", d1: "new session", k2: "/", d2: "message // commands" },
1461
+ ];
1462
+ const padCell = (s: string, n: number) => s + rep(" ", Math.max(0, n - visibleWidth(s)));
1463
+ const k1w = Math.max(...keys.map((r) => visibleWidth(r.k1))) + 2;
1464
+ const d1w = Math.max(...keys.map((r) => visibleWidth(r.d1))) + 3;
1465
+ const k2w = Math.max(...keys.filter((r) => r.k2).map((r) => visibleWidth(r.k2!))) + 2;
1466
+ const keyRow = (r: (typeof keys)[number]) => {
1467
+ const key = r.muted ? c.muted : c.accent;
1468
+ const desc = r.muted ? c.muted : (s: string) => s;
1469
+ return key(padCell(r.k1, k1w)) + desc(padCell(r.d1, d1w)) + (r.k2 ? key(padCell(r.k2, k2w)) + desc(r.d2 ?? "") : "");
1470
+ };
1294
1471
  const rows = [
1295
1472
  `${c.accent("▲")} ${c.bold("dpi keymap (herdr template)")}`,
1296
1473
  "",
1297
- `${c.accent("j k ↑ ↓")} move/scroll ${c.accent("1-4")} views: net/herd/agent/log`,
1298
- `${c.accent("↵")} open ${c.accent("g N L")} same views, aliases`,
1299
- `${c.accent("[ ] t")} agent tabs ${c.accent("m")} message (enter sends)`,
1300
- `${c.accent("esc")} back/interrupt ${c.accent("i")} interrupt ≠ kill`,
1301
- `${c.accent("F")} fork ${c.accent("c")} compact context`,
1302
- `${c.accent("y")} thinking level ${c.accent("x")} reset (y/n confirm)`,
1303
- `${c.muted("alt+↵")} send now, no steer ${c.muted("ctrl+l")} model picker`,
1304
- `${c.muted("tab")} complete /command ${c.muted("↑")} recall sent`,
1305
- `${c.muted("ctrl+o")} expand tool output`,
1306
- `${c.accent(":")} palette ${c.accent("f")} filter rows`,
1307
- `${c.accent("n")} new session ${c.accent("/")} message // commands`,
1474
+ ...keys.map(keyRow),
1308
1475
  "",
1309
1476
  c.muted("Durability"),
1310
1477
  `${c.muted("·")} every turn is checkpointed on the device`,
1311
1478
  `${c.muted("·")} interrupt leaves the run resumable; only reset starts fresh`,
1312
1479
  `${c.muted("·")} sends retry by requestId — the device admits each exactly once`,
1480
+ `${c.muted("·")} a lost hub shows ○ hub offline in the header and reconnects alone`,
1313
1481
  `${c.muted("·")} /commands still work: type them in the message line`,
1314
1482
  ];
1315
1483
  const height = Math.min(rows.length + 2, h);
@@ -2,8 +2,9 @@
2
2
  import type { SlashCommand } from "@earendil-works/pi-tui";
3
3
  import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
4
4
  import type { App } from "./app.ts";
5
- import { Panel, pickAgent, pickDevice, pickModel, pickSession } from "./pickers.ts";
5
+ import { Panel, pickAgent, pickDevice, pickModel, pickSession, pickThinking } from "./pickers.ts";
6
6
  import { parsePairArgs, runPairing } from "./pairing.ts";
7
+ import { gitStateSuffix } from "./views.ts";
7
8
  import { c } from "./theme.ts";
8
9
  import { basename, dirname, isAbsolute, join } from "node:path";
9
10
 
@@ -28,10 +29,10 @@ export const COMMANDS: SlashCommand[] = [
28
29
  { name: "pair", description: "pair THIS device with a hub", argumentHint: "<CODE|PAIR_URL> [--hub ORIGIN] [--force]" },
29
30
  {
30
31
  name: "git",
31
- description: "git on the session's folder: status, diff, log, pull, fetch, branch, switch, commit, worktree",
32
- argumentHint: "[status|diff|log|fetch|pull|branch|switch <b>|commit <msg>|worktree [new <b>|remove <path>]]",
32
+ description: "git on the session's folder: status, diff, log, pull, fetch, branch, switch, commit, worktree, merge-abort",
33
+ argumentHint: "[status|diff|log|fetch|pull|branch|switch <b>|commit <msg>|worktree [new <b>|remove <path>]|merge-abort]",
33
34
  getArgumentCompletions: (prefix) =>
34
- ["status", "diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree"]
35
+ ["status", "diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree", "merge-abort"]
35
36
  .filter((s) => s.startsWith(prefix))
36
37
  .map((s) => ({ value: s, label: s })),
37
38
  },
@@ -39,7 +40,7 @@ export const COMMANDS: SlashCommand[] = [
39
40
  { name: "quit", description: "exit (the agent keeps running)" },
40
41
  ];
41
42
 
42
- const GIT_OPS = new Set(["diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree", "status", "wt"]);
43
+ const GIT_OPS = new Set(["diff", "log", "fetch", "pull", "branch", "switch", "commit", "worktree", "status", "wt", "merge-abort"]);
43
44
 
44
45
  /** /git — the device's own git, spoken through its whitelisted API. */
45
46
  async function gitCommand(app: App, arg: string) {
@@ -52,8 +53,13 @@ async function gitCommand(app: App, arg: string) {
52
53
  const s = await app.client.gitStatus(cwd);
53
54
  if (!s.repo) return app.notify(`${cwd} is not a git repository`);
54
55
  const dirty = (s.staged ?? 0) + (s.unstaged ?? 0) + (s.untracked ?? 0);
55
- app.notify(`⎇ ${s.branch ?? s.head} ±${dirty}${s.ahead ? ` ↑${s.ahead}` : ""}${s.behind ? ` ↓${s.behind}` : ""}`);
56
- app.logEvent("git", `${cwd} · ${s.branch ?? s.head}${s.upstream ? ` → ${s.upstream}` : ""} · +${s.staged ?? 0}/~${s.unstaged ?? 0}/?${s.untracked ?? 0}${s.worktreeOf ? ` · worktree of ${s.worktreeOf}` : ""}`);
56
+ // Merge/detached ride the toast (R5 finding 4): a mid-merge repo with
57
+ // conflicts used to show a healthy branch line, same blind spot the
58
+ // header chip had — the web's GitPanel has banner'd this state all along.
59
+ app.notify(
60
+ `⎇ ${s.branch ?? s.head} ±${dirty}${s.ahead ? ` ↑${s.ahead}` : ""}${s.behind ? ` ↓${s.behind}` : ""}${gitStateSuffix(s)}`,
61
+ );
62
+ app.logEvent("git", `${cwd} · ${s.branch ?? s.head}${s.merge ? " · MERGING" : s.detached ? " · detached" : ""}${s.upstream ? ` → ${s.upstream}` : ""} · +${s.staged ?? 0}/~${s.unstaged ?? 0}/?${s.untracked ?? 0}${s.worktreeOf ? ` · worktree of ${s.worktreeOf}` : ""}`);
57
63
  for (const w of s.worktrees ?? []) app.logEvent("git", ` ${w.path} ${w.branch ? `⎇ ${w.branch}` : w.head}`);
58
64
  return;
59
65
  }
@@ -81,7 +87,8 @@ async function gitCommand(app: App, arg: string) {
81
87
  app.notify(`${s.worktrees?.length ?? 0} worktree${s.worktrees?.length === 1 ? "" : "s"} (log view)`);
82
88
  return;
83
89
  }
84
- if (!GIT_OPS.has(op)) return app.notify(`unknown git op "${op}" — status diff log fetch pull branch switch commit worktree`);
90
+ if (!GIT_OPS.has(op))
91
+ return app.notify(`unknown git op "${op}" — status diff log fetch pull branch switch commit worktree merge-abort`);
85
92
  if (op === "switch" && !a1) return app.notify("usage: /git switch <branch>");
86
93
  if (op === "commit" && !rest.length) return app.notify("usage: /git commit <message>");
87
94
  const out = await app.client.gitOp(cwd, op as never, {
@@ -98,7 +105,8 @@ async function gitCommand(app: App, arg: string) {
98
105
  const KEYS: [string, string][] = [
99
106
  ["enter", "send; steers the agent while it works"],
100
107
  ["alt+enter", "queue as a follow-up"],
101
- ["esc", "interrupt foreground work"],
108
+ ["esc", "back — it never interrupts"],
109
+ ["i", "interrupt the running turn"],
102
110
  ["shift+tab", "cycle thinking level"],
103
111
  ["ctrl+l", "model picker"],
104
112
  ["ctrl+o", "expand tool output and thinking"],
@@ -155,11 +163,23 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
155
163
  break;
156
164
  }
157
165
  case "thinking": {
158
- if (!THINKING_LEVELS.includes(arg as ThinkingLevel))
159
- return app.flash(`Levels: ${THINKING_LEVELS.join(", ")}`, true), true;
160
- await app.run(async () => {
161
- await handle!.configure({ thinkingLevel: arg as ThinkingLevel });
162
- });
166
+ // A bare /thinking (the palette door) opens the same picker the
167
+ // new-session flow uses — it used to dead-end in a "Levels: …" flash
168
+ // (R4 finding 2). A valid argument still sets directly.
169
+ const apply = async (level: ThinkingLevel) => {
170
+ if (!handle) return app.flash("Pick a session first (g, then ↵).", true);
171
+ await app.run(async () => {
172
+ await handle!.configure({ thinkingLevel: level });
173
+ app.flash(`thinking: ${level}`);
174
+ });
175
+ };
176
+ if (!THINKING_LEVELS.includes(arg as ThinkingLevel)) {
177
+ const picked = await pickThinking(app, String(app.model.state.agent.thinkingLevel ?? "low"));
178
+ if (!picked) break;
179
+ await apply(picked);
180
+ break;
181
+ }
182
+ await apply(arg as ThinkingLevel);
163
183
  break;
164
184
  }
165
185
  case "compact":
@@ -169,18 +189,33 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
169
189
  });
170
190
  break;
171
191
  case "reset":
172
- await app.run(async () => {
173
- await handle!.reset(arg || undefined);
174
- app.flash("New context started; history stays stored");
175
- });
192
+ // The x key confirms y/n before reset (app.ts) — the command door must
193
+ // not skip that gate (R4 finding 4: the palette entry used to wipe the
194
+ // context unconditionally). A typed handoff note carries its own intent.
195
+ if (!arg) {
196
+ const ok = await app.prompt(`Reset ${app.sessionSummary()?.name ?? "context"}? y/n`, "");
197
+ if (ok === undefined || !ok.trim().toLowerCase().startsWith("y"))
198
+ return app.flash("reset cancelled"), true;
199
+ }
200
+ await app.resetContext(arg || undefined);
176
201
  break;
177
- case "name":
178
- if (!arg) return app.flash("Usage: /name <name>", true), true;
202
+ case "name": {
203
+ // A bare /name (the palette door) opens the rename Prompt instead of the
204
+ // dead-end usage flash (R4 finding 2).
205
+ let value = arg;
206
+ if (!value) {
207
+ const current = app.sessionSummary()?.agents.find((a) => a.id === app.agentId)?.name ?? "";
208
+ const typed = await app.prompt("Agent name", current && current !== "main" ? current : "");
209
+ value = (typed ?? "").trim();
210
+ if (!value) return app.flash("rename cancelled"), true;
211
+ }
212
+ if (!handle) return app.flash("Pick a session first (g, then ↵).", true), true;
179
213
  await app.run(async () => {
180
- await handle!.rename(arg);
181
- app.flash(`Agent renamed to ${arg}`);
214
+ await handle!.rename(value);
215
+ app.flash(`Agent renamed to ${value}`);
182
216
  });
183
217
  break;
218
+ }
184
219
  case "git":
185
220
  await gitCommand(app, arg);
186
221
  break;