my-durable 0.0.58 → 0.0.60

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 (36) hide show
  1. package/apps/dpi-backend/src/daemon.ts +48 -0
  2. package/apps/dpi-backend/src/doctor.ts +17 -4
  3. package/apps/dpi-backend/src/errors.ts +68 -1
  4. package/apps/dpi-backend/src/gc-cli.ts +52 -19
  5. package/apps/dpi-backend/src/gc.ts +3 -1
  6. package/apps/dpi-backend/src/main.ts +23 -3
  7. package/apps/dpi-backend/src/pi-config.ts +15 -6
  8. package/apps/dpi-backend/src/store.ts +220 -22
  9. package/apps/dpi-backend/src/tunnel.ts +24 -2
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-4Kyozhl0.js +81 -0
  11. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-DxGrKN6X.css → index-BkSQ2clA.css} +1 -1
  12. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  13. package/apps/dpi-playground/apps/dpi-playground-fe/src/App.vue +9 -2
  14. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/dialog-escape.ts +13 -0
  15. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/export-bundle.ts +70 -0
  16. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/state-draft.ts +72 -0
  17. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +15 -0
  18. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ContextBar.vue +14 -3
  19. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +82 -69
  20. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +22 -4
  21. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/PromptDialog.vue +3 -0
  22. package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +19 -0
  23. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +72 -30
  24. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +13 -2
  25. package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +38 -17
  26. package/apps/dpi-playground/apps/dpi-playground-hub/src/shares.ts +7 -1
  27. package/apps/dpi-tui/src/app.ts +108 -25
  28. package/apps/dpi-tui/src/commands.ts +16 -8
  29. package/apps/dpi-tui/src/main.ts +46 -19
  30. package/apps/dpi-tui/src/pickers.ts +4 -0
  31. package/apps/dpi-tui/src/scroll.ts +59 -0
  32. package/apps/dpi-tui/src/views.ts +17 -2
  33. package/apps/dpi-tui/src/wrap.ts +42 -0
  34. package/bin/dpi.mjs +83 -0
  35. package/package.json +1 -1
  36. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DC0Iicch.js +0 -81
@@ -56,11 +56,17 @@ const KEY =
56
56
 
57
57
  const invalidKey = () => Object.assign(Error("Invalid subscription key"), { status: 400 });
58
58
 
59
+ /** R5 cap mirror: the device's SUBSCRIBE_PATH_OK (dpi-backend/src/tunnel.ts) accepts at most 256
60
+ * characters after `?`. A docs list longer than that would open a subscription the device refuses —
61
+ * refuse it HERE (400 to the PUT caller) instead of signing the browser up for a silent starvation. */
62
+ const SUB_QUERY_MAX_CHARS = 256;
63
+
59
64
  export function parseSubKey(key: string) {
60
65
  const m = key.match(KEY);
61
66
  if (!m) throw invalidKey();
62
67
  const [, deviceId, scope, a, b, docs] = m;
63
68
  const q = docs ? `?docs=${docs}` : "";
69
+ if (q.length - 1 > SUB_QUERY_MAX_CHARS) throw invalidKey();
64
70
  const enc = (part: string) => {
65
71
  try {
66
72
  return encodeURIComponent(decodeURIComponent(part));
@@ -182,6 +188,12 @@ export class StreamMux {
182
188
  const wanted = new Map(
183
189
  (keys as string[]).filter((k) => k !== "network").map((k) => [k, parseSubKey(k)]),
184
190
  );
191
+ // All-or-nothing like the parse above (R5): every device the PUT names must exist BEFORE
192
+ // anything is closed or opened, so an unknown device cannot leave upstreams opened and
193
+ // reader slots acquired by earlier keys in the same PUT dangling behind a 404.
194
+ for (const [key, sub] of wanted)
195
+ if (!stream.upstreams.has(key) && !this.registry.get(sub.deviceId))
196
+ throw Object.assign(Error(`No device ${sub.deviceId}`), { status: 404 });
185
197
  for (const [key, ctl] of stream.upstreams)
186
198
  if (!wanted.has(key)) {
187
199
  ctl.abort();
@@ -190,10 +202,9 @@ export class StreamMux {
190
202
  }
191
203
  for (const [key, sub] of wanted)
192
204
  if (!stream.upstreams.has(key)) {
193
- if (!this.registry.get(sub.deviceId))
194
- throw Object.assign(Error(`No device ${sub.deviceId}`), { status: 404 });
195
205
  // Reader caps (04 §8): 128/device incl. the monitor's reader, 1024
196
206
  // hub-wide. A rejected NEW reader must not disturb existing readers.
207
+ // (The registry check ran before any mutation — see above.)
197
208
  if (
198
209
  this.readerCount(sub.deviceId) >= READERS_PER_DEVICE ||
199
210
  this.hubReaderCount() >= READERS_PER_HUB
@@ -557,10 +557,17 @@ export class PairingService {
557
557
  });
558
558
  }
559
559
 
560
- /** POST /api/pair/verify — proof, poll, and (post-approval) issuance. */
560
+ /** POST /api/pair/verify — proof, poll, and (post-approval) issuance.
561
+ * `requestOrigin` is the origin the device DIALED (`${protocol}://${host}` of
562
+ * the HTTP request), best-effort from the route. The wire proof carries no
563
+ * declared origin (the signing payload binds one, but it is never sent), so
564
+ * this is the only signal that separates "wrong key" from "the hub signs as
565
+ * a different origin than the device dialed" — see the mismatch branch in
566
+ * the first-proof path (R6 cli finding 5). */
561
567
  async verify(
562
568
  body: unknown,
563
569
  address: string,
570
+ requestOrigin?: string,
564
571
  ): Promise<{ ok: true; value: PairPendingOut | TokenIssue; status: number } | PairingFailure> {
565
572
  const now = this.now();
566
573
  const ip = ipKey(address);
@@ -724,27 +731,34 @@ export class PairingService {
724
731
  }
725
732
  if (now >= code.expiresAt) return this.fail(410, "code_expired", "Pairing code expired");
726
733
 
727
- const payload = pairingSigningPayload({
728
- hubOrigin: this.deps.hubOrigin,
729
- hubId: this.deps.hubId,
730
- enrollmentId: enrollment.enrollmentId,
731
- nonce: enrollment.nonce,
732
- issuedAt: enrollment.nonceIssuedAt,
733
- deviceUid: enrollment.deviceUid,
734
- keyFingerprint: enrollment.computedFingerprint,
735
- });
736
734
  let valid = false;
737
735
  try {
738
- valid = cryptoVerify(
739
- null,
740
- Buffer.from(payload, "utf8"),
741
- createPublicKey(enrollment.publicKeyPem),
742
- Buffer.from(req.signature, "base64url"),
743
- );
736
+ valid = this.verifySignature(enrollment, req.signature, this.deps.hubOrigin);
744
737
  } catch {
745
738
  valid = false;
746
739
  }
747
740
  if (!valid) {
741
+ // R6 cli finding 5: a hub started WITHOUT DPI_HUB_ORIGIN signs as
742
+ // https://<hostname> while a LAN device signs the origin it dialed —
743
+ // every proof then "fails" and reads like an attack. When the same
744
+ // signature verifies under the request's origin, this is a misconfigured
745
+ // origin, not a bad key: say so and do NOT count it toward the cancel limit.
746
+ if (
747
+ requestOrigin &&
748
+ requestOrigin !== this.deps.hubOrigin &&
749
+ this.verifySignature(enrollment, req.signature, requestOrigin)
750
+ ) {
751
+ this.deps.audit.denied("auth.denied", ip, {
752
+ stage: "pair.verify",
753
+ enrollmentId: enrollment.enrollmentId,
754
+ originMismatch: `device=${requestOrigin} hub=${this.deps.hubOrigin}`,
755
+ });
756
+ return this.fail(
757
+ 409,
758
+ "origin_mismatch",
759
+ `origin mismatch: device signed for ${requestOrigin}, hub signs as ${this.deps.hubOrigin} — set DPI_HUB_ORIGIN on the hub`,
760
+ );
761
+ }
748
762
  enrollment.badSignatures += 1;
749
763
  this.noteFailure(ip); // sliding-window IP counter (S-1): code/UID change does not reset
750
764
  this.deps.audit.denied("auth.denied", ip, {
@@ -782,8 +796,15 @@ export class PairingService {
782
796
 
783
797
  /** Proof check shared by first-verify and every receipt poll (F02). */
784
798
  private signatureOk(enrollment: Enrollment, signature: string): boolean {
799
+ return this.verifySignature(enrollment, signature, this.deps.hubOrigin);
800
+ }
801
+
802
+ /** Ed25519 proof check for a given hub origin — the signing payload binds it,
803
+ * so the SAME signature can be retried under the request's origin (F02 + R6
804
+ * cli finding 5: origin-mismatch detection without a protocol change). */
805
+ private verifySignature(enrollment: Enrollment, signature: string, hubOrigin: string): boolean {
785
806
  const payload = pairingSigningPayload({
786
- hubOrigin: this.deps.hubOrigin,
807
+ hubOrigin,
787
808
  hubId: this.deps.hubId,
788
809
  enrollmentId: enrollment.enrollmentId,
789
810
  nonce: enrollment.nonce,
@@ -203,8 +203,14 @@ export class Shares {
203
203
  // Rendered server-side: the share page is public and must not load the app
204
204
  // shell (which holds credentials), any script, or any external asset.
205
205
 
206
+ // Text nodes get the entity treatment for the HTML metacharacters, and C0/C1
207
+ // controls are STRIPPED (except tab/newline/carriage-return, which transcript
208
+ // text legitimately carries): a U+0001 or U+0007 in a markdown paste lands in
209
+ // the page raw otherwise — layout damage a reader cannot see or edit.
206
210
  const escapeHtml = (text: string) =>
207
- text.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
211
+ text
212
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "")
213
+ .replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
208
214
 
209
215
  const PAGE_STYLE = `:root{color-scheme:dark}body{margin:0;background:#16181d;color:#e6e6e6;font:16px/1.6 ui-sans-serif,system-ui,sans-serif}
210
216
  main{max-width:52rem;margin:0 auto;padding:2rem 1rem}h1{font-size:1.3rem;margin:0 0 .25rem}
@@ -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,
@@ -43,6 +46,8 @@ import {
43
46
  import { appendFileSync } from "node:fs";
44
47
  import { fetchHubNetwork } from "./hub-feed.ts";
45
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). */
@@ -300,7 +318,7 @@ export class App {
300
318
  this.handle = this.client.agent(sessionId, agentId);
301
319
  this.model.clear();
302
320
  if (!sameSession) this.session.clear();
303
- this.scrollOffset = 0;
321
+ this.scrollState = FOLLOW_TAIL;
304
322
  void this.refreshSessions();
305
323
  const handle = this.handle;
306
324
  // Hub-routed devices stream through the mux (same upstreams the web rides);
@@ -419,6 +437,16 @@ export class App {
419
437
  // Frames flow again: re-fetch the network rows that froze with the old
420
438
  // connection (R4 finding 6 — the view stayed empty through every switch).
421
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(() => {});
422
450
  }
423
451
  this.requestRender();
424
452
  }
@@ -446,7 +474,7 @@ export class App {
446
474
  setView(view: View) {
447
475
  this.view = view;
448
476
  this.cursor = 0;
449
- this.scrollOffset = 0;
477
+ this.scrollState = FOLLOW_TAIL;
450
478
  if (view === "herd") void this.refreshSessions();
451
479
  if (view === "herd") this.refreshBranches();
452
480
  if (view === "network") {
@@ -863,7 +891,12 @@ export class App {
863
891
  private move(delta: number) {
864
892
  if (this.view === "agent" && this.tab === "transcript") {
865
893
  // Scroll the transcript instead of moving a cursor (herdr H04's lesson).
866
- 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);
867
900
  this.requestRender();
868
901
  return;
869
902
  }
@@ -910,7 +943,7 @@ export class App {
910
943
  }
911
944
  const index = AGENT_TABS.findIndex((t) => t.id === this.tab);
912
945
  this.tab = AGENT_TABS[(index + delta + AGENT_TABS.length) % AGENT_TABS.length]!.id;
913
- this.scrollOffset = 0;
946
+ this.scrollState = FOLLOW_TAIL;
914
947
  this.requestRender();
915
948
  }
916
949
 
@@ -1175,11 +1208,17 @@ export class App {
1175
1208
  const filled = ctx === undefined ? 0 : Math.round((ctx / 100) * barW);
1176
1209
  const g = this.gitOf(session?.cwd);
1177
1210
  if (session?.cwd) this.refreshGit(session.cwd);
1178
- 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
+ : "";
1179
1217
  lines.push(
1180
1218
  `${c.muted(this.device.id)} ${c.muted("›")} ${c.text(session?.name ?? "—")} ${c.muted("›")} ${c.bold(`#${this.agentId ?? 1}`)}${gitChip} ` +
1181
1219
  `${STATE_COLOR[state](STATE_GLYPH[state] + " " + (this.busy() ? "working" : "idle"))} ` +
1182
- `${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}%`)}`,
1183
1222
  );
1184
1223
  lines.push(
1185
1224
  AGENT_TABS.map((t) => (t.id === this.tab ? c.inverse(c.bold(` ${t.label} `)) : c.muted(` ${t.label} `))).join(
@@ -1189,19 +1228,44 @@ export class App {
1189
1228
  lines.push(c.muted(rep(box.h, w)));
1190
1229
  const inner = h - 3;
1191
1230
  const content = this.agentContent(w);
1192
- const from = Math.max(0, content.length - inner - this.scrollOffset);
1193
- 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
+ }
1194
1249
  return lines.slice(0, h);
1195
1250
  }
1196
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
+
1197
1263
  /** The transcript/tasks/tools/state/config tabs, from the REAL model state. */
1198
1264
  private agentContent(w: number): string[] {
1199
1265
  const s = this.model.state;
1200
- const wrap = (text: string, indent = " ") =>
1201
- text
1202
- .split("\n")
1203
- .flatMap((l) => (l.length > w - 4 ? [l.slice(0, w - 4), l.slice(w - 4)] : [l]))
1204
- .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);
1205
1269
  if (this.tab === "transcript") {
1206
1270
  const lines: string[] = [];
1207
1271
  let turn = 0;
@@ -1375,20 +1439,39 @@ export class App {
1375
1439
 
1376
1440
  private helpPanel(w: number, h: number): string[] {
1377
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
+ };
1378
1471
  const rows = [
1379
1472
  `${c.accent("▲")} ${c.bold("dpi keymap (herdr template)")}`,
1380
1473
  "",
1381
- `${c.accent("j k ↑ ↓")} move/scroll ${c.accent("1-4")} views: net/herd/agent/log`,
1382
- `${c.accent("↵")} open ${c.accent("g N L")} same views, aliases`,
1383
- `${c.accent("[ ] t")} agent tabs ${c.accent("m")} message (enter sends)`,
1384
- `${c.accent("esc")} back/interrupt ${c.accent("i")} interrupt ≠ kill`,
1385
- `${c.accent("F")} fork ${c.accent("c")} compact context`,
1386
- `${c.accent("y")} thinking level ${c.accent("x")} reset (y/n confirm)`,
1387
- `${c.muted("alt+↵")} send now, no steer ${c.muted("ctrl+l")} model picker`,
1388
- `${c.muted("tab")} complete /command ${c.muted("↑")} recall sent`,
1389
- `${c.muted("ctrl+o")} expand tool output`,
1390
- `${c.accent(":")} palette ${c.accent("f")} filter rows`,
1391
- `${c.accent("n")} new session ${c.accent("/")} message // commands`,
1474
+ ...keys.map(keyRow),
1392
1475
  "",
1393
1476
  c.muted("Durability"),
1394
1477
  `${c.muted("·")} every turn is checkpointed on the device`,
@@ -4,6 +4,7 @@ import { THINKING_LEVELS, type ThinkingLevel } from "../../dpi-sdk/src/api.ts";
4
4
  import type { App } from "./app.ts";
5
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"],
@@ -30,30 +30,55 @@ const USAGE = `usage: dpi-tui [device[:session[:agent]]] [options]
30
30
  --url, --token connect to any dpi-backend directly (also DPI_URL, DPI_TOKEN)
31
31
  --save <id> store a --url device in ~/.dpi/network.sqlite under <id>`;
32
32
 
33
+ /** Run a parser whose failure is a usage error (exit 2), never a raw
34
+ * ERR_PARSE_ARGS_UNKNOWN_OPTION stack — the convention of the other subcommands
35
+ * (R6 cli finding 4: `dpi tui --bogus` used to throw). */
36
+ function parseOrUsage<T>(parse: () => T): T {
37
+ try {
38
+ return parse();
39
+ } catch (e) {
40
+ process.stderr.write(`dpi tui: ${(e as Error).message}\n\n${USAGE}\n`);
41
+ process.exit(2);
42
+ }
43
+ }
44
+
45
+ /** A connect URL must be absolute http(s) — checked at the door so a typo is a
46
+ * one-line error, not `TypeError: Invalid URL` deep in startup (R6 cli finding 3). */
47
+ export function isValidConnectUrl(candidate: string): boolean {
48
+ try {
49
+ const u = new URL(candidate);
50
+ return u.protocol === "http:" || u.protocol === "https:";
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
33
56
  function fail(message: string): never {
34
57
  process.stderr.write(`${message}\n`);
35
58
  process.exit(1);
36
59
  }
37
60
 
38
- const { values, positionals } = parseArgs({
39
- allowPositionals: true,
40
- options: {
41
- url: { type: "string" },
42
- token: { type: "string" },
43
- save: { type: "string" },
44
- session: { type: "string", short: "s" },
45
- agent: { type: "string", short: "a" },
46
- new: { type: "string" },
47
- cwd: { type: "string" },
48
- model: { type: "string" },
49
- pair: { type: "string" },
50
- hub: { type: "string" },
51
- "hub-url": { type: "string" },
52
- "hub-token": { type: "string" },
53
- force: { type: "boolean" },
54
- help: { type: "boolean", short: "h" },
55
- },
56
- });
61
+ const { values, positionals } = parseOrUsage(() =>
62
+ parseArgs({
63
+ allowPositionals: true,
64
+ options: {
65
+ url: { type: "string" },
66
+ token: { type: "string" },
67
+ save: { type: "string" },
68
+ session: { type: "string", short: "s" },
69
+ agent: { type: "string", short: "a" },
70
+ new: { type: "string" },
71
+ cwd: { type: "string" },
72
+ model: { type: "string" },
73
+ pair: { type: "string" },
74
+ hub: { type: "string" },
75
+ "hub-url": { type: "string" },
76
+ "hub-token": { type: "string" },
77
+ force: { type: "boolean" },
78
+ help: { type: "boolean", short: "h" },
79
+ },
80
+ }),
81
+ );
57
82
  if (values.help) {
58
83
  process.stdout.write(`${USAGE}\n`);
59
84
  process.exit(0);
@@ -64,6 +89,8 @@ const config = tryLoadNetworkConfig(process.env.INIT_CWD ?? process.cwd());
64
89
  if (config) syncConfigToRegistry(config, registry);
65
90
 
66
91
  const url = values.url ?? process.env.DPI_URL;
92
+ // R6 cli finding 3: a bogus --url/DPI_URL crashed later at `new URL(url)` — fail here.
93
+ if (url !== undefined && !isValidConnectUrl(url)) fail("--url must be a valid http(s) URL");
67
94
  const [deviceRef = "", sessionRef = values.session, agentRef = values.agent] = (
68
95
  positionals[0] ?? (url ? "" : (process.env.DPI_DEVICE ?? ""))
69
96
  ).split(":");
@@ -100,6 +100,10 @@ export class Picker extends Box {
100
100
  // arrow sequences it already understands.
101
101
  if (data === "j") return this.list.handleInput("\x1b[B");
102
102
  if (data === "k") return this.list.handleInput("\x1b[A");
103
+ // Enter on a ZERO-match list closes the picker (R5 finding 6): SelectList
104
+ // drops the key when nothing is selected — a silent no-op that stranded
105
+ // the user on a dead overlay with only esc as a way out.
106
+ if (matchesKey(data, "enter") && !this.list.getSelectedItem()) return this.onCancel();
103
107
  if (matchesKey(data, "up") || matchesKey(data, "down") || matchesKey(data, "enter") || matchesKey(data, "escape"))
104
108
  return this.list.handleInput(data);
105
109
  if (matchesKey(data, "backspace")) {
@@ -0,0 +1,59 @@
1
+ // Transcript viewport math (R5 findings 2+3). Pure — no TTY, no timers — so
2
+ // the scroll model is unit-testable exactly like the views.
3
+ //
4
+ // The old model stored ONLY an offset counted back from the END of the
5
+ // content and recomputed the top as `content.length - inner - offset` every
6
+ // frame. Two bugs fell out of that:
7
+ // • j/k deltas added straight onto the offset, so j scrolled INTO history
8
+ // and k clamped dead at the bottom (the offset's direction was inverted
9
+ // relative to the keys);
10
+ // • every new frame grew content.length, which SLID a scrolled-back viewport
11
+ // down through history (top row AGENT #10 → #11) — autoscroll fighting the
12
+ // user who had explicitly scrolled away from the tail.
13
+ // ScrollState fixes both: `top` is an ABSOLUTE line index pinned while
14
+ // offset > 0, and scrollBy()'s delta moves the top line, not the tail
15
+ // distance — j/↓ = +1 = toward newer, k/↑ = -1 = toward older.
16
+
17
+ export interface ScrollState {
18
+ /** Lines back from the tail; 0 = follow the tail (top is ignored). */
19
+ offset: number;
20
+ /** Absolute top line of the viewport while offset > 0. */
21
+ top: number;
22
+ }
23
+
24
+ /** Following the tail: offset 0, newest content visible. */
25
+ export const FOLLOW_TAIL: ScrollState = { offset: 0, top: 0 };
26
+
27
+ const tailTopOf = (contentLen: number, inner: number) => Math.max(0, contentLen - inner);
28
+
29
+ /**
30
+ * Step the viewport. `deltaTop > 0` moves the top line DOWN the document
31
+ * (toward newer content — the j/↓ direction), `deltaTop < 0` moves it UP
32
+ * (toward older — k/↑). From the follow-tail state, scrolling up first pins
33
+ * the anchor at the tail top, then steps it; scrolling back down to the tail
34
+ * releases the anchor (offset 0 again).
35
+ */
36
+ export function scrollBy(s: ScrollState, deltaTop: number, contentLen: number, inner: number): ScrollState {
37
+ const tailTop = tailTopOf(contentLen, inner);
38
+ const base = s.offset === 0 ? tailTop : s.top;
39
+ const top = Math.max(0, Math.min(tailTop, base + deltaTop));
40
+ return top >= tailTop ? FOLLOW_TAIL : { offset: tailTop - top, top };
41
+ }
42
+
43
+ /**
44
+ * The viewport's absolute top line for a render, with the state to persist.
45
+ * While offset > 0 the anchor is honored as-is (clamped into range): content
46
+ * growth must NOT slide the viewport. While offset = 0 the tail is followed.
47
+ * The returned state is re-clamped, so a shrunken transcript falls back to the
48
+ * tail instead of pinning past the end.
49
+ */
50
+ export function viewportTop(
51
+ s: ScrollState,
52
+ contentLen: number,
53
+ inner: number,
54
+ ): { from: number; state: ScrollState } {
55
+ const tailTop = tailTopOf(contentLen, inner);
56
+ if (s.offset === 0) return { from: tailTop, state: FOLLOW_TAIL };
57
+ const from = Math.max(0, Math.min(tailTop, s.top));
58
+ return from >= tailTop ? { from, state: FOLLOW_TAIL } : { from, state: { offset: tailTop - from, top: from } };
59
+ }
@@ -4,6 +4,7 @@
4
4
  // unit-testable exactly like the reference's frame(w, h).
5
5
  import { truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
6
6
  import type { SessionSummary } from "../../dpi-sdk/src/api.ts";
7
+ import type { GitStatus } from "../../dpi-sdk/src/client.ts";
7
8
  import type { DeviceRow } from "../../dpi-sdk/src/node/registry.ts";
8
9
  import { c, STATE_COLOR, STATE_GLYPH, type RowState } from "./theme.ts";
9
10
 
@@ -55,6 +56,18 @@ export const ageOf = (createdAt: number, now = Date.now()) => {
55
56
 
56
57
  export const sessionState = (s: SessionSummary): RowState =>
57
58
  s.error ? "error" : s.busy ? "busy" : "idle";
59
+
60
+ /**
61
+ * The state suffix the /git toast and the agent-header chip append after
62
+ * branch ±dirty (R5 finding 4): a merge in progress and a detached HEAD used
63
+ * to be invisible in the TUI while the backend already reported both — the
64
+ * web's GitPanel has carried a merge banner all along. Mirrors the FE text.
65
+ */
66
+ export function gitStateSuffix(g: Pick<GitStatus, "merge" | "conflicts" | "detached">): string {
67
+ if (g.merge) return ` · merging (${g.conflicts ?? 0} conflicts)`;
68
+ if (g.detached) return " (detached)";
69
+ return "";
70
+ }
58
71
  export const deviceState = (d: DeviceRow): RowState =>
59
72
  d.lastStatus === "online"
60
73
  ? "busy"
@@ -259,7 +272,9 @@ export function renderStatusbar(
259
272
  : opts.view === "agent"
260
273
  ? ["g herd", "N network", "L log", "[ ] tabs", "m message"]
261
274
  : ["j/k move", "↵ open", "1-4 views", "⇥ tabs", "esc agent"];
262
- const right = `${c.muted("ctx")} ${opts.ctxLeft === undefined ? c.muted("—") : c.text(`${opts.ctxLeft}%`)}${opts.background ? c.muted(` · ${opts.background} bg`) : ""} ${c.muted("dev")} ${c.text(fit(opts.device, 18))}`;
275
+ // Catalog miss degrades to "?" (R5 finding 5): "—" read as "no usage yet",
276
+ // when it actually means the window is unknown — a different problem.
277
+ const right = `${c.muted("ctx")} ${opts.ctxLeft === undefined ? c.muted("?") : c.text(`${opts.ctxLeft}%`)}${opts.background ? c.muted(` · ${opts.background} bg`) : ""} ${c.muted("dev")} ${c.text(fit(opts.device, 18))}`;
263
278
  const left = `${chip} ${keys.map((k) => c.muted(k)).join(c.muted(" • "))}`;
264
279
  const gap = Math.max(1, w - visibleWidth(left) - visibleWidth(right));
265
280
  return c.inverse(padTo(fit(`${left}${rep(" ", gap)}${right}`, w), w));
@@ -338,7 +353,7 @@ export function renderHerdPanel(
338
353
  ` ${c.muted("agents")} ${agents.length ? agents[0] : "—"}`,
339
354
  ...agents.slice(1, 8).map((a) => ` ${c.muted(a)}`),
340
355
  "",
341
- ` ${c.muted("ctx")} ${ctxLeft === undefined ? c.muted("—") : c.text(`${ctxLeft}% left`)}`,
356
+ ` ${c.muted("ctx")} ${ctxLeft === undefined ? c.muted("?") : c.text(`${ctxLeft}% left`)}`,
342
357
  ` ${c.muted("age")} ${c.muted(ageOf(s.createdAt))}`,
343
358
  ` ${c.muted("tokens")} ${c.muted(compact(s.agents.reduce((n, a) => n + a.background, 0)) + " bg")}`,
344
359
  ];