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
@@ -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")) {
@@ -269,7 +273,13 @@ export async function pickSession(app: App) {
269
273
  const s = tree.sessions.find((x) => x.id === item.value)!;
270
274
  const root = s.agents.find((a) => a.kind === "root") ?? s.agents[0];
271
275
  void app.attach(s.id, root?.id ?? 1);
272
- }, () => app.closeOverlay(!app.sessionId)),
276
+ }, () => {
277
+ // Esc must never surprise-quit (0.0.52): with no attached session the
278
+ // cancel used to pass exitIfNothing=true and picker→Esc→Esc killed the
279
+ // whole process (R4 finding 1). Landing in the herd/network view is the
280
+ // honest cancel; quitting stays on q / ctrl+c / /quit.
281
+ app.closeOverlay();
282
+ }),
273
283
  );
274
284
  }
275
285
 
@@ -278,7 +288,12 @@ export async function newSession(app: App, presetName?: string) {
278
288
  const name = presetName !== undefined ? presetName : await app.prompt("Session name", "");
279
289
  if (name === undefined) return app.sessionId ? undefined : pickSession(app);
280
290
  const cwd = await walkDirs(app, "");
281
- if (!cwd) return app.sessionId ? undefined : pickSession(app);
291
+ // undefined = esc (back to the sessions picker when detached); null = the
292
+ // device could not list directories — the error is already flashed, so
293
+ // dead-end HERE instead of silently swapping to the unrelated "Sessions on…"
294
+ // picker (R4 finding 8).
295
+ if (cwd === undefined) return app.sessionId ? undefined : pickSession(app);
296
+ if (cwd === null) return;
282
297
  // A device without a provider key (the Windows default) lists ZERO models —
283
298
  // the picker would be empty and creation dead-ends. Fall back to the device's
284
299
  // own default exactly like the web dialog's "(device default)" option.
@@ -289,26 +304,44 @@ export async function newSession(app: App, presetName?: string) {
289
304
  if (!model) return;
290
305
  // Thinking rides the create call: pick a level up front instead of paying
291
306
  // for "high" on a scratch session the device default never asked for.
292
- const thinking = await chooseThinking(app);
307
+ const thinking = await pickThinking(app);
293
308
  if (!thinking) return;
294
309
  await app.run(async () => {
295
- const s = await app.client.createSession({
296
- name: name || "New session",
297
- cwd,
298
- model: { provider: model.provider, modelId: model.id },
299
- thinkingLevel: thinking,
300
- });
301
- await app.attach(s.id, s.agents.find((a) => a.kind === "root")?.id ?? 1);
302
- app.flash(`Session created in ${cwd}`);
303
- if (!models.length) app.flash(`no model catalog on the device — using its default (${app.info.defaultModel})`);
310
+ // The create+attach round-trip is the silent 2-20s dead-air on a cold
311
+ // tunnel (R4 finding 8) — hold the message line while it flies.
312
+ app.setPending(`creating ${name || "New session"} on ${app.device.name}…`);
313
+ try {
314
+ const s = await app.client.createSession({
315
+ name: name || "New session",
316
+ cwd,
317
+ model: { provider: model.provider, modelId: model.id },
318
+ thinkingLevel: thinking,
319
+ });
320
+ await app.attach(s.id, s.agents.find((a) => a.kind === "root")?.id ?? 1);
321
+ app.flash(`Session created in ${cwd}`);
322
+ if (!models.length) app.flash(`no model catalog on the device — using its default (${app.info.defaultModel})`);
323
+ } finally {
324
+ app.setPending(null);
325
+ }
304
326
  });
305
327
  }
306
328
 
307
- function walkDirs(app: App, path: string): Promise<string | undefined> {
329
+ /**
330
+ * The directory walk for a new session's working folder. Resolves:
331
+ * string — the chosen directory;
332
+ * undefined — the user canceled (esc);
333
+ * null — the device RPC failed (the error is already flashed).
334
+ * Exported for the busy-note / failure-path unit tests.
335
+ */
336
+ export function walkDirs(app: App, path: string): Promise<string | undefined | null> {
308
337
  return new Promise((done) => {
309
338
  const step = async (at: string) => {
339
+ // A cold tunnel lists in 2-20s — hold the message line so the silence
340
+ // never reads as a dead app (R4 finding 8).
341
+ app.setPending(`listing ${at || "start dirs"} on ${app.device.name}…`);
310
342
  const listing = await app.client.dirs(at).catch((e: Error) => (app.flash(e.message, true), undefined));
311
- if (!listing) return done(undefined);
343
+ app.setPending(null);
344
+ if (!listing) return done(null);
312
345
  const items: SelectItem[] = [
313
346
  ...(listing.path ? [{ value: `use:${listing.path}`, label: `✓ Use ${listing.path}` }] : []),
314
347
  ...(listing.path ? [{ value: listing.parent ?? "", label: listing.parent ? ".." : "⌂ start dirs" }] : []),
@@ -356,8 +389,12 @@ function chooseModel(app: App, current?: string) {
356
389
  });
357
390
  }
358
391
 
359
- /** The new-session thinking step: the same levels `y` cycles in-session. */
360
- function chooseThinking(app: App) {
392
+ /**
393
+ * The thinking-level picker: the new-session step AND the /thinking command
394
+ * door (R4 finding 2 — the palette entry used to dead-end in a usage flash).
395
+ * Preselects the agent's current level, else the backend create default.
396
+ */
397
+ export function pickThinking(app: App, current?: string) {
361
398
  return new Promise<ThinkingLevel | undefined>((done) => {
362
399
  const picker = new Picker(
363
400
  "Thinking level",
@@ -371,8 +408,8 @@ function chooseThinking(app: App) {
371
408
  done(undefined);
372
409
  },
373
410
  );
374
- // Preselect the backend's create default, so a bare enter keeps "medium".
375
- const index = THINKING_LEVELS.indexOf("medium");
411
+ const wanted = current && THINKING_LEVELS.includes(current as ThinkingLevel) ? current : "medium";
412
+ const index = THINKING_LEVELS.indexOf(wanted as ThinkingLevel);
376
413
  if (index >= 0) picker.list.setSelectedIndex(index);
377
414
  app.overlay(picker);
378
415
  });
@@ -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
  ];
@@ -0,0 +1,42 @@
1
+ // Display-width transcript wrapping (R5 finding 1). Pure — unit-testable like
2
+ // the views.
3
+ //
4
+ // The old wrap split each line exactly ONCE on UTF-16 code units
5
+ // (`[l.slice(0, w-4), l.slice(w-4)]`): the remainder was never re-wrapped, so
6
+ // pi-tui hard-clipped the tail of every overlong row — a 400-char message
7
+ // showed ~154 chars at 80 columns. And `l.length` counts UTF-16 units, not
8
+ // terminal columns, so CJK/emoji (2 cells each) overflowed their budget and
9
+ // got clipped too.
10
+ //
11
+ // wrapByColumn walks grapheme COLUMNS instead, pi-tui sliceByColumn/truncate
12
+ // semantics (the 0.0.53 panelLine lesson): every visible column lands on some
13
+ // row (no content loss), and a wide char that would straddle the budget moves
14
+ // whole to the next row (strict slice) instead of being clipped mid-glyph.
15
+ import { sliceByColumn, visibleWidth } from "@earendil-works/pi-tui";
16
+
17
+ /**
18
+ * Hard-wrap `text` on newlines, then to a display-column budget per row, and
19
+ * indent every row. Budget = width - 4 - indent, the old `w - 4` margin kept
20
+ * (with the indent now counted) so wrapped rows can never reach the frame's
21
+ * hard-clip edge even if a grapheme measures one cell wide in practice.
22
+ */
23
+ export function wrapByColumn(text: string, width: number, indent = " "): string[] {
24
+ const budget = Math.max(4, width - 4 - visibleWidth(indent));
25
+ const out: string[] = [];
26
+ for (const line of text.split("\n")) {
27
+ const total = visibleWidth(line);
28
+ if (total <= budget) {
29
+ out.push(line);
30
+ continue;
31
+ }
32
+ let col = 0;
33
+ while (col < total) {
34
+ const part = sliceByColumn(line, col, budget, true);
35
+ const partWidth = visibleWidth(part);
36
+ if (partWidth <= 0) break; // only zero-width columns remain — nothing visible lost
37
+ out.push(part);
38
+ col += partWidth;
39
+ }
40
+ }
41
+ return out.map((l) => indent + l);
42
+ }
package/bin/update.mjs CHANGED
@@ -159,6 +159,7 @@ export function spawnNpm(args) {
159
159
  const child = spawn(onWindows ? "npm.cmd" : "npm", args, {
160
160
  stdio: ["ignore", "pipe", "pipe"],
161
161
  shell: onWindows,
162
+ windowsHide: true,
162
163
  });
163
164
  let output = "";
164
165
  child.stdout?.on("data", (x) => {
@@ -191,7 +192,7 @@ export async function fetchLatestVersion() {
191
192
  export function daemonControl(dpiPath, port) {
192
193
  const call = (args) =>
193
194
  new Promise((resolve) => {
194
- const child = spawn(process.execPath, [dpiPath, ...args], { stdio: "ignore" });
195
+ const child = spawn(process.execPath, [dpiPath, ...args], { stdio: "ignore", windowsHide: true });
195
196
  child.on("error", () => resolve(1));
196
197
  child.on("exit", (code) => resolve(code ?? 1));
197
198
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.57",
3
+ "version": "0.0.59",
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": {
@@ -185,12 +185,19 @@ function run(name, suite) {
185
185
  const cwd = join(ROOT, suite.cwd);
186
186
  process.stdout.write(`\n▶ ${name} — ${suite.title}\n cwd: ${suite.cwd}\n cmd: ${suite.cmd.join(" ")}\n`);
187
187
  const t0 = Date.now();
188
+ // Bare npm/npx are .cmd shims on Windows — a shell-less spawn cannot find
189
+ // them and fails with ENOENT. The suite commands are fixed arrays with no
190
+ // user input, so a shell is safe there; windowsHide keeps the runner
191
+ // console-free on both platforms.
192
+ const onWindows = process.platform === "win32";
188
193
  const r = spawnSync(suite.cmd[0], suite.cmd.slice(1), {
189
194
  cwd,
190
195
  env: { ...process.env, DPI_TEST: "1", NO_COLOR: "1" },
191
196
  encoding: "utf8",
192
197
  timeout: 1_800_000,
193
198
  maxBuffer: 256 * 1024 * 1024,
199
+ shell: onWindows,
200
+ windowsHide: true,
194
201
  });
195
202
  const secs = ((Date.now() - t0) / 1000).toFixed(1);
196
203
  const out = `${r.stdout ?? ""}${r.stderr ?? ""}`;