@marver-design/marver 0.25.1 → 0.26.1

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 (95) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/README.md +5 -3
  3. package/dist/{anchor-DVV732zR.mjs → anchor-5H1vnoLu.mjs} +6 -1
  4. package/dist/{anchor-check-DGZnYviN.mjs → anchor-check-l-ny3UzH.mjs} +1 -1
  5. package/dist/audio-Dw1lfMdb.mjs +443 -0
  6. package/dist/{auth-DdUKeVKt.mjs → auth-Dix8wrXV.mjs} +1 -1
  7. package/dist/{bake-BpxMZfij.mjs → bake-C-awKgLA.mjs} +1 -1
  8. package/dist/{boards-Csxj2WJn.mjs → boards-DYG22tOe.mjs} +2 -2
  9. package/dist/{build-DKaGhoVN.mjs → build-BDRiO_mP.mjs} +16 -9
  10. package/dist/capture-vadKjuCo.mjs +730 -0
  11. package/dist/cli.mjs +24 -18
  12. package/dist/{collab-gqNdScUE.mjs → collab-Dxg2trOK.mjs} +4 -3
  13. package/dist/{comments-Zoch254k.mjs → comments-0BSbb04K.mjs} +14 -3
  14. package/dist/{comments-pTLlhjh4.mjs → comments-BqXua-XL.mjs} +7 -7
  15. package/dist/{config-cKgZBRj0.mjs → config-Cf7EjAMf.mjs} +12 -1
  16. package/dist/{context-D2ugHqwO.mjs → context-HQ4Giw58.mjs} +1 -1
  17. package/dist/daemon-DL6Fwq6D.mjs +2569 -0
  18. package/dist/{dev-Diqx1Rt8.mjs → dev-Bw_qYWWq.mjs} +202 -18
  19. package/dist/dev-lock-DWSpa6nj.mjs +179 -0
  20. package/dist/{events-DnK_AnrW.mjs → events-CLH4ijKP.mjs} +14 -4
  21. package/dist/{init-DO4DhUt_.mjs → init-D8DtrK_F.mjs} +2 -2
  22. package/dist/{ledger-BNXW14Xw.mjs → ledger-D54iROST.mjs} +17 -1
  23. package/dist/{link-C-qUIuKU.mjs → link-BNzLvdhI.mjs} +2 -2
  24. package/dist/live-Cgzsicwi.mjs +4 -0
  25. package/dist/{manifest-DnAte_fB.mjs → manifest-Nl3KSVOk.mjs} +1 -1
  26. package/dist/{marks-koRsbHfe.mjs → marks-CKgzucHZ.mjs} +2 -2
  27. package/dist/{marks-DFuintmJ.mjs → marks-DyWMv_Z1.mjs} +23 -5
  28. package/dist/{marver-id-gate-DGANtVyC.mjs → marver-id-gate-BjF6v4bT.mjs} +4 -4
  29. package/dist/perf-C75MZ73h.mjs +167 -0
  30. package/dist/{perf-CCisg-ny.mjs → perf-DPbLGhhO.mjs} +1 -1
  31. package/dist/perf-jam-BU3TVrZu.mjs +239 -0
  32. package/dist/{plugin-dTF5reck.mjs → plugin-DkGmZs_r.mjs} +298 -38
  33. package/dist/{poster-D-zjYpgk.mjs → poster-BdtSKMDm.mjs} +2 -1
  34. package/dist/{profile-Do0nGkXO.mjs → profile-WU9qcbIo.mjs} +1 -1
  35. package/dist/{publish-bakes-C_9VZ-Mq.mjs → publish-bakes-9RzRToXV.mjs} +3 -3
  36. package/dist/queue-29ok5_eZ.mjs +1319 -0
  37. package/dist/reserve-BURNQ2Y3.mjs +53 -0
  38. package/dist/{rolldown-runtime-D7D4PA-g.mjs → rolldown-runtime-8H4AJuhK.mjs} +1 -0
  39. package/dist/{serve-wv2QWdxB.mjs → serve-C8rVheYk.mjs} +12 -12
  40. package/dist/session-BAaJsK5c.mjs +191 -0
  41. package/dist/{share-ScamJcks.mjs → share--oFJ1bCI.mjs} +2 -2
  42. package/dist/{shot-CUlmkqFX.mjs → shot-DQeR_Pfn.mjs} +339 -20
  43. package/dist/shot-XQV7HC9A.mjs +139 -0
  44. package/dist/speech-models-DomiLQcY.mjs +299 -0
  45. package/dist/speech-worker.mjs +354 -0
  46. package/dist/{summary-CrW88e3q.mjs → summary-Y8MY1Wuc.mjs} +2 -2
  47. package/dist/{sync-C3035OnJ.mjs → sync-DKk-yT1V.mjs} +9 -8
  48. package/dist/{work-GE88wb_3.mjs → work-F5u-twpJ.mjs} +28 -5
  49. package/dist/{work-CpJn1gwY.mjs → work-VvX_JIgl.mjs} +2 -2
  50. package/docs/jam-session.md +194 -0
  51. package/docs/live-jam.md +29 -3
  52. package/package.json +7 -1
  53. package/src/client/frame-host/bridge.js +20 -2
  54. package/src/client/frame-host/inspect.d.ts +4 -0
  55. package/src/client/frame-host/inspect.js +96 -6
  56. package/src/client/frame-host/keys.d.ts +6 -0
  57. package/src/client/frame-host/keys.js +59 -0
  58. package/src/client/frame-host/trail.d.ts +7 -0
  59. package/src/client/frame-host/trail.js +204 -0
  60. package/src/client/shell/App.tsx +52 -8
  61. package/src/client/shell/Comments.tsx +20 -6
  62. package/src/client/shell/JamSurface.tsx +346 -0
  63. package/src/client/shell/Play.tsx +32 -9
  64. package/src/client/shell/Tip.tsx +8 -3
  65. package/src/client/shell/Toolbar.tsx +5 -4
  66. package/src/client/shell/canvas/Canvas.tsx +12 -2
  67. package/src/client/shell/canvas/FrameNode.tsx +14 -4
  68. package/src/client/shell/comments-store.ts +23 -16
  69. package/src/client/shell/icons.tsx +17 -0
  70. package/src/client/shell/jam-capture.ts +1005 -0
  71. package/src/client/shell/jam-keys.ts +358 -0
  72. package/src/client/shell/jam-lane.tsx +249 -0
  73. package/src/client/shell/jam-lines.ts +115 -0
  74. package/src/client/shell/jam-panel.tsx +556 -0
  75. package/src/client/shell/jam-queue.ts +126 -0
  76. package/src/client/shell/jam-session.tsx +389 -0
  77. package/src/client/shell/jam-state.ts +103 -0
  78. package/src/client/shell/jam-surface-parts.tsx +106 -0
  79. package/src/client/shell/jam-ui.tsx +104 -0
  80. package/src/client/shell/jam-voice.ts +479 -0
  81. package/src/client/shell/sound.ts +22 -0
  82. package/src/client/shell/stage-size.ts +11 -0
  83. package/src/client/shell/store.ts +47 -17
  84. package/src/client/shell/styles.css +564 -2
  85. package/src/client/stage/main.tsx +18 -2
  86. package/src/shared/capture-frames.ts +41 -0
  87. package/src/shared/events.ts +19 -4
  88. package/src/shared/speech.ts +16 -0
  89. package/templates/AGENTS-embedded.md +10 -2
  90. package/templates/AGENTS-studio.md +10 -2
  91. package/templates/instructions/iterate.md +8 -6
  92. package/templates/instructions/jam.md +131 -59
  93. package/dist/daemon-Cl8KXGW4.mjs +0 -1523
  94. package/dist/perf-QJIWtTw1.mjs +0 -68
  95. package/dist/shot-jdO_B6Qw.mjs +0 -86
@@ -1,9 +1,11 @@
1
1
  import { a as ROUTE, o as slideSize } from "./cli.mjs";
2
+ import { t as logJam } from "./perf-jam-BU3TVrZu.mjs";
2
3
  import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { randomBytes } from "node:crypto";
5
6
  import { availableParallelism, tmpdir } from "node:os";
6
7
  import { execFileSync, spawn } from "node:child_process";
8
+ import { createInflate } from "node:zlib";
7
9
  //#region src/server/cdp.ts
8
10
  /**
9
11
  * A headless Chrome driven over CDP through Chrome's own debugging PIPE - fds 3 (we write,
@@ -104,13 +106,14 @@ var Browser = class Browser {
104
106
  }
105
107
  /** Spawn and handshake (`Browser.getVersion` within 15s), or throw with the reason. A Chrome
106
108
  * that starts but never brings up CDP is killed here - it can never hold a lane. */
107
- static async launch(prefix = "mv-shot-") {
109
+ static async launch(prefix = "mv-shot-", extra = []) {
108
110
  const bin = findChrome();
109
111
  if (!bin) throw new Error("no Chrome/Chromium found - install one or set MARVER_CHROME to a browser binary");
110
112
  const b = new Browser();
111
113
  b.profile = mkdtempSync(join(tmpdir(), prefix));
112
114
  b.proc = spawn(bin, [
113
115
  ...FLAGS,
116
+ ...extra,
114
117
  `--user-data-dir=${b.profile}`,
115
118
  "--remote-debugging-pipe",
116
119
  "about:blank"
@@ -258,6 +261,153 @@ var Browser = class Browser {
258
261
  }
259
262
  };
260
263
  //#endregion
264
+ //#region src/server/stale.ts
265
+ /**
266
+ * A guard for one known corruption of headless Chrome's screenshots (#14, #24) - not a proof that a picture is right.
267
+ *
268
+ * `Page.captureScreenshot` with a clip resizes the tab's native view to clip x scale, asks for a redraw and copies the
269
+ * view's surface; when the copy wins the race against the resize it gets the old surface, smaller than asked, and
270
+ * Chrome fills the request by tiling it (page_handler.cc: ScreenshotCaptured -> SkBitmapOperations::CreateTiledBitmap).
271
+ * So every pixel (x, y) of a stale picture equals pixel (x mod w0, y mod h0), w0 x h0 being the native view in device px.
272
+ *
273
+ * The image is streamed row by row - inflated, unfiltered, the last h0 rows kept - and the check stops at the first row
274
+ * that breaks the repeat: a real picture costs its first row or two, and only a true repeat is read to the end (two
275
+ * identical panels over different content are clean). What it reads is what Chrome writes: 8-bit RGB/RGBA, not
276
+ * interlaced, filters 0-4, alpha compared too; anything else, or a deadline passed, is 'unknown' - never 'clean'.
277
+ */
278
+ const SIG = Buffer.from([
279
+ 137,
280
+ 80,
281
+ 78,
282
+ 71,
283
+ 13,
284
+ 10,
285
+ 26,
286
+ 10
287
+ ]);
288
+ /** Is this PNG the native view's old surface (w0 x h0 device px) tiled to the requested size? `deadline` (epoch ms):
289
+ * past it the check gives up ('unknown'). */
290
+ async function staleSurface(png, w0, h0, deadline = Infinity) {
291
+ if (!(w0 > 0 && h0 > 0) || png.length < 33 || !png.subarray(0, 8).equals(SIG)) return "unknown";
292
+ let pos = 8;
293
+ let w = 0, h = 0, channels = 0, ended = false;
294
+ const idat = [];
295
+ while (pos + 12 <= png.length) {
296
+ const len = png.readUInt32BE(pos);
297
+ const type = png.toString("latin1", pos + 4, pos + 8);
298
+ if (pos + 12 + len > png.length) return "unknown";
299
+ const data = png.subarray(pos + 8, pos + 8 + len);
300
+ if (pos === 8) {
301
+ if (type !== "IHDR" || len !== 13) return "unknown";
302
+ w = data.readUInt32BE(0);
303
+ h = data.readUInt32BE(4);
304
+ const depth = data[8], colour = data[9], compression = data[10], filtering = data[11], interlace = data[12];
305
+ if (depth !== 8 || colour !== 2 && colour !== 6 || compression !== 0 || filtering !== 0 || interlace !== 0 || !w || !h) return "unknown";
306
+ channels = colour === 6 ? 4 : 3;
307
+ } else if (type === "IDAT") idat.push(data);
308
+ else if (type === "IEND") {
309
+ ended = len === 0 && pos + 12 === png.length;
310
+ break;
311
+ }
312
+ pos += 12 + len;
313
+ }
314
+ if (!channels || !idat.length || !ended) return "unknown";
315
+ if (w <= w0 && h <= h0) return "clean";
316
+ const stride = w * channels;
317
+ const wide = w > w0, tall = h > h0;
318
+ const th = Math.min(h, h0), tw = Math.min(w, w0), shift = w0 * channels, n = (w - w0) * channels;
319
+ const ring = tall ? Array.from({ length: h0 }, () => Buffer.alloc(stride)) : [];
320
+ let prev = Buffer.alloc(stride), cur = Buffer.alloc(stride);
321
+ const first = Buffer.alloc(channels);
322
+ let varied = false;
323
+ /** One unfiltered row: true to go on, a verdict to stop. */
324
+ const check = (y, row) => {
325
+ if (y === 0) row.copy(first, 0, 0, channels);
326
+ if (y < th && !varied) {
327
+ for (let x = 0; x < tw; x++) if (row.compare(first, 0, channels, x * channels, (x + 1) * channels) !== 0) {
328
+ varied = true;
329
+ break;
330
+ }
331
+ }
332
+ if (wide && row.compare(row, 0, n, shift, shift + n) !== 0) return "clean";
333
+ if (tall) {
334
+ const slot = ring[y % h0];
335
+ if (y >= h0 && !row.equals(slot)) return "clean";
336
+ row.copy(slot);
337
+ }
338
+ if (y === th - 1 && !varied) return "clean";
339
+ return y === h - 1 ? "stale" : true;
340
+ };
341
+ return new Promise((resolve) => {
342
+ const z = createInflate();
343
+ let done = false;
344
+ const finish = (v) => {
345
+ if (done) return;
346
+ done = true;
347
+ z.removeAllListeners();
348
+ z.on("error", () => {});
349
+ z.destroy();
350
+ resolve(v);
351
+ };
352
+ const raw = Buffer.alloc(stride + 1);
353
+ let fill = 0, y = 0;
354
+ z.on("data", (c) => {
355
+ if (done) return;
356
+ if (Date.now() > deadline) return finish("unknown");
357
+ let i = 0;
358
+ while (i < c.length && !done) {
359
+ const take = Math.min(stride + 1 - fill, c.length - i);
360
+ c.copy(raw, fill, i, i + take);
361
+ fill += take;
362
+ i += take;
363
+ if (fill < stride + 1) break;
364
+ fill = 0;
365
+ if (!unfilterRow(raw, prev, cur, channels)) return finish("unknown");
366
+ const v = check(y, cur);
367
+ if (v !== true) return finish(v);
368
+ const t = prev;
369
+ prev = cur;
370
+ cur = t;
371
+ y++;
372
+ }
373
+ });
374
+ z.on("end", () => finish("unknown"));
375
+ z.on("error", () => finish("unknown"));
376
+ let k = 0;
377
+ const feed = () => {
378
+ while (!done && k < idat.length) if (!z.write(idat[k++])) {
379
+ z.once("drain", feed);
380
+ return;
381
+ }
382
+ if (!done && k >= idat.length) z.end();
383
+ };
384
+ feed();
385
+ });
386
+ }
387
+ /** One row of PNG filter 0-4 (`raw[0]` the filter byte) into `out`, given the row above; false on any other filter. */
388
+ function unfilterRow(raw, up, out, bpp) {
389
+ const f = raw[0];
390
+ if (f > 4) return false;
391
+ const len = out.length;
392
+ for (let i = 0; i < len; i++) {
393
+ const x = raw[i + 1];
394
+ const a = i >= bpp ? out[i - bpp] : 0;
395
+ const b = up[i];
396
+ const c = i >= bpp ? up[i - bpp] : 0;
397
+ let v;
398
+ if (f === 0) v = x;
399
+ else if (f === 1) v = x + a;
400
+ else if (f === 2) v = x + b;
401
+ else if (f === 3) v = x + (a + b >> 1);
402
+ else {
403
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
404
+ v = x + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c);
405
+ }
406
+ out[i] = v & 255;
407
+ }
408
+ return true;
409
+ }
410
+ //#endregion
261
411
  //#region src/server/shot.ts
262
412
  /**
263
413
  * Frame screenshots without a dependency - the system's own Chrome, driven over CDP through
@@ -313,6 +463,17 @@ function planShot(frame, viewports, override = {}) {
313
463
  fullHeight: false
314
464
  };
315
465
  }
466
+ /** A shot's timing line (spec 27a Part D): its frame, scale, time, retakes - kept on a failure too - and an outcome code. */
467
+ function shotEvent(frameId, askedScale, result) {
468
+ return {
469
+ kind: "shot",
470
+ frame: frameId,
471
+ scale: result.ok ? result.scale : askedScale,
472
+ ms: result.ms,
473
+ recaptures: result.recaptures ?? 0,
474
+ outcome: result.ok ? /not checked for a stale surface/.test(result.note ?? "") ? "unchecked" : "ok" : result.error === STALE ? "stale" : /timed out/.test(result.error) ? "timeout" : "error"
475
+ };
476
+ }
316
477
  /** Resolve a frame from the manifest and screenshot it - the shared core behind BOTH
317
478
  * transports (the HTTP /api/shot endpoint and the file-drop inbox), so they validate and
318
479
  * name output identically. `origin` is the dev server's own base URL. */
@@ -333,8 +494,8 @@ async function shootFrame(opts) {
333
494
  };
334
495
  const plan = planShot(frame, viewports, size);
335
496
  if (frame.kind !== "html") try {
336
- const { scanAssetRefs } = await import("./build-DKaGhoVN.mjs");
337
- const { ensurePoster } = await import("./poster-D-zjYpgk.mjs");
497
+ const { scanAssetRefs } = await import("./build-BDRiO_mP.mjs");
498
+ const { ensurePoster } = await import("./poster-BdtSKMDm.mjs");
338
499
  const refs = scanAssetRefs(readFileSync(join(root, frame.file), "utf8"), frame.file);
339
500
  for (const r of refs) if (r.endsWith(".poster.png")) await ensurePoster(join(root, "design", "assets"), r.slice(0, -11));
340
501
  } catch {}
@@ -356,9 +517,13 @@ async function shootFrame(opts) {
356
517
  scale
357
518
  };
358
519
  const result = browser ? await captureIn(req, browser) : await capture(req);
520
+ logJam(root, shotEvent(frameId, scale, result));
359
521
  if (!result.ok) {
360
522
  rmSync(tmp, { force: true });
361
- return result;
523
+ return {
524
+ ok: false,
525
+ error: result.error
526
+ };
362
527
  }
363
528
  const rel = relFor(result.scale);
364
529
  try {
@@ -385,7 +550,8 @@ async function shootFrame(opts) {
385
550
  scale: result.scale,
386
551
  ...result.truncated ? { truncated: true } : {},
387
552
  ...result.unsettled ? { unsettled: true } : {},
388
- ...result.note ? { note: result.note } : {}
553
+ ...result.note ? { note: result.note } : {},
554
+ recaptures: result.recaptures
389
555
  };
390
556
  }
391
557
  function manifestFrame(root, frameId) {
@@ -672,13 +838,46 @@ const AREA = 64e6;
672
838
  const fits = (w, h, dsf) => w * dsf <= 16384 && h * dsf <= 16384 && w * h * dsf * dsf <= 64e6;
673
839
  /** The tallest CSS height a full-height capture of `width` can hold at `dsf`. */
674
840
  const capFor = (width, dsf) => Math.max(1, Math.min(Math.floor(SURFACE / dsf), Math.floor(AREA / (width * dsf * dsf))));
675
- async function captureIn({ url, width, height, out, fullHeight = false, timeoutMs = 3e4, scale: wantScale = 2, clip }, b) {
841
+ /** The windows live captures hold, per browser, until their tab is closed - and how many live captures have a window
842
+ * nobody could name. A capture sizes its window only when it is surely its own: no other live capture in it, and no
843
+ * live capture whose window is unknown. */
844
+ const live = /* @__PURE__ */ new WeakMap();
845
+ const liveFor = (b) => {
846
+ let l = live.get(b);
847
+ if (!l) {
848
+ l = {
849
+ windows: /* @__PURE__ */ new Map(),
850
+ unknown: 0
851
+ };
852
+ live.set(b, l);
853
+ }
854
+ return l;
855
+ };
856
+ /** Test seams - never set outside tests: what an attempt returns (to inject Chrome's stale surface), whether a capture
857
+ * gets its own window and may size it, each sizing seen, and a shorter watchdog. */
858
+ const shotSeams = {};
859
+ /** A retake, or the 1x attempt, starts only with this much of the shot's deadline left. */
860
+ const RETRY_LEFT = 3e3;
861
+ const STALE = "Chrome returned a stale surface (the picture came back tiled) - shoot it again";
862
+ /** One capture in a browser it may share; the result carries the capture's own time (`ms` - not its wait for a
863
+ * browser slot), which `shootFrame` logs and never passes on. */
864
+ async function captureIn(req, b) {
865
+ const t0 = performance.now();
866
+ return {
867
+ ...await captureOnce(req, b),
868
+ ms: Math.round(performance.now() - t0)
869
+ };
870
+ }
871
+ async function captureOnce({ url, width, height, out, fullHeight = false, timeoutMs = 3e4, scale: wantScale = 2, clip }, b) {
872
+ let recaptures = 0;
676
873
  let scale = Math.min(4, Math.max(1, Math.round(wantScale)));
677
874
  while (scale > 1 && !fits(width, height, scale)) scale--;
678
875
  const me = {};
679
876
  let watchdog;
680
877
  let targetId;
681
878
  let sessionId;
879
+ let windowId;
880
+ let registered = null;
682
881
  let off = () => {};
683
882
  try {
684
883
  let lastException = "";
@@ -689,15 +888,74 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
689
888
  timer = setTimeout(() => rej(/* @__PURE__ */ new Error(`${method} timed out`)), ms);
690
889
  })]).finally(() => clearTimeout(timer));
691
890
  };
692
- const hardBy = Date.now() + timeoutMs + 15e3;
693
- watchdog = setTimeout(() => b.abort(me, "the shot timed out"), timeoutMs + 15e3);
891
+ const watchMs = shotSeams.watchdogMs ?? timeoutMs + 15e3;
892
+ const hardBy = Date.now() + watchMs;
893
+ watchdog = setTimeout(() => b.abort(me, "the shot timed out"), watchMs);
894
+ const left = () => hardBy - Date.now();
895
+ const bounded = (p, ms) => {
896
+ let t;
897
+ return Promise.race([p.catch(() => null), new Promise((r) => {
898
+ t = setTimeout(() => r(null), Math.max(1, ms));
899
+ })]).finally(() => clearTimeout(t));
900
+ };
694
901
  const RESERVE = 21e3;
695
902
  const discretionary = () => hardBy - RESERVE - Date.now();
696
- targetId = (await send("Target.createTarget", { url: "about:blank" })).targetId;
903
+ targetId = (await send("Target.createTarget", {
904
+ url: "about:blank",
905
+ newWindow: shotSeams.newWindow ?? true
906
+ })).targetId;
697
907
  sessionId = (await send("Target.attachToTarget", {
698
908
  targetId,
699
909
  flatten: true
700
910
  })).sessionId;
911
+ const lv = liveFor(b);
912
+ const win = shotSeams.noWindow ? null : await bounded(send("Browser.getWindowForTarget", { targetId }), 1e3);
913
+ if (typeof win?.windowId === "number") {
914
+ windowId = win.windowId;
915
+ lv.windows.set(windowId, (lv.windows.get(windowId) ?? 0) + 1);
916
+ registered = "window";
917
+ } else {
918
+ lv.unknown++;
919
+ registered = "unknown";
920
+ }
921
+ let view = null;
922
+ const v0 = (await bounded(send("Runtime.evaluate", {
923
+ expression: "[innerWidth, innerHeight, devicePixelRatio]",
924
+ returnByValue: true
925
+ }, sessionId), 1e3))?.result?.value;
926
+ if (windowId !== void 0 && Array.isArray(v0) && v0.length === 3 && v0.every((x) => typeof x === "number" && x > 0) && typeof win?.bounds?.width === "number" && typeof win?.bounds?.height === "number") view = {
927
+ dpr: v0[2],
928
+ decoW: win.bounds.width - v0[0],
929
+ decoH: win.bounds.height - v0[1]
930
+ };
931
+ const viewNow = async () => {
932
+ if (!view || windowId === void 0) return null;
933
+ const r = await bounded(send("Browser.getWindowBounds", { windowId }), Math.min(1e3, left()));
934
+ const bw = r?.bounds?.width, bh = r?.bounds?.height;
935
+ return typeof bw === "number" && typeof bh === "number" ? {
936
+ w: Math.round((bw - view.decoW) * view.dpr),
937
+ h: Math.round((bh - view.decoH) * view.dpr)
938
+ } : null;
939
+ };
940
+ if (!fullHeight && !clip && view && windowId !== void 0 && shotSeams.resize !== false && lv.windows.get(windowId) === 1 && lv.unknown === 0) {
941
+ const cw = Math.round(width * scale / view.dpr), ch = Math.round(height * scale / view.dpr);
942
+ shotSeams.onResize?.(windowId);
943
+ const ok = await bounded(send("Browser.setWindowBounds", {
944
+ windowId,
945
+ bounds: {
946
+ width: cw + view.decoW,
947
+ height: ch + view.decoH
948
+ }
949
+ }).then(() => true), 1e3) === true;
950
+ for (const by = Date.now() + 500; ok && Date.now() < by;) {
951
+ const v = (await bounded(send("Runtime.evaluate", {
952
+ expression: "[innerWidth, innerHeight]",
953
+ returnByValue: true
954
+ }, sessionId), by - Date.now()))?.result?.value;
955
+ if (v && v[0] === cw && v[1] === ch) break;
956
+ await new Promise((r2) => setTimeout(r2, 20));
957
+ }
958
+ }
701
959
  off = b.on((m) => {
702
960
  if (m.sessionId === sessionId && m.method === "Runtime.exceptionThrown") {
703
961
  const d = m.params?.exceptionDetails;
@@ -896,18 +1154,71 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
896
1154
  capW = Math.max(1, Math.round(box.w));
897
1155
  capH = Math.max(1, Math.round(box.h));
898
1156
  }
899
- const shot = await sendD("Page.captureScreenshot", {
900
- format: "png",
901
- captureBeyondViewport: true,
902
- clip: {
903
- x: capX,
904
- y: capY,
1157
+ let attempt = 0;
1158
+ const take = async () => {
1159
+ const v = await viewNow();
1160
+ const shot = await sendD("Page.captureScreenshot", {
1161
+ format: "png",
1162
+ captureBeyondViewport: true,
1163
+ clip: {
1164
+ x: capX,
1165
+ y: capY,
1166
+ width: capW,
1167
+ height: capH,
1168
+ scale: 1
1169
+ }
1170
+ }, Math.max(1e3, Math.min(15e3, left() - 500)));
1171
+ let png = Buffer.from(String(shot.data), "base64");
1172
+ if (shotSeams.capture) png = shotSeams.capture(png, {
1173
+ attempt,
1174
+ view: v,
1175
+ windowId
1176
+ });
1177
+ attempt++;
1178
+ return {
1179
+ png,
1180
+ view: v
1181
+ };
1182
+ };
1183
+ const twoFrames = () => sendD("Runtime.evaluate", {
1184
+ expression: "new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true))))",
1185
+ awaitPromise: true,
1186
+ returnByValue: true
1187
+ }, Math.max(1, Math.min(1e3, left() - RETRY_LEFT))).catch(() => null);
1188
+ const judge = (a) => a.view ? staleSurface(a.png, a.view.w, a.view.h, hardBy - 1e3) : Promise.resolve("unknown");
1189
+ let shotNow = await take();
1190
+ let verdict = await judge(shotNow);
1191
+ const retryLeft = shotSeams.retryLeftMs ?? RETRY_LEFT;
1192
+ while (verdict === "stale" && recaptures < 2 && left() > retryLeft) {
1193
+ recaptures++;
1194
+ await twoFrames();
1195
+ shotNow = await take();
1196
+ verdict = await judge(shotNow);
1197
+ }
1198
+ if (verdict === "stale" && fullHeight && scale > 1 && left() > retryLeft) {
1199
+ const was = scale;
1200
+ await sendD("Emulation.setDeviceMetricsOverride", {
905
1201
  width: capW,
906
1202
  height: capH,
907
- scale: 1
1203
+ deviceScaleFactor: 1,
1204
+ mobile: false
1205
+ }, Math.max(1, Math.min(5e3, left() - 1e3)));
1206
+ await twoFrames();
1207
+ recaptures++;
1208
+ shotNow = await take();
1209
+ verdict = await judge(shotNow);
1210
+ if (verdict !== "stale") {
1211
+ scale = 1;
1212
+ note = `${note ? note + "; " : ""}came back tiled at ${was}x - captured at 1x`;
908
1213
  }
909
- }, 15e3);
910
- writeFileSync(out, Buffer.from(String(shot.data), "base64"));
1214
+ }
1215
+ if (verdict === "stale") return {
1216
+ ok: false,
1217
+ error: STALE,
1218
+ recaptures
1219
+ };
1220
+ if (verdict === "unknown") note = `${note ? note + "; " : ""}not checked for a stale surface`;
1221
+ writeFileSync(out, shotNow.png);
911
1222
  const unsettled = !settled;
912
1223
  if (unsettled) note = `${note ? note + "; " : ""}captured before the frame settled - images, charts or diagrams may be missing; shoot it alone or lower MARVER_SHOT_CONCURRENCY`;
913
1224
  return {
@@ -917,12 +1228,14 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
917
1228
  scale,
918
1229
  ...truncated ? { truncated: true } : {},
919
1230
  ...unsettled ? { unsettled: true } : {},
920
- ...note ? { note } : {}
1231
+ ...note ? { note } : {},
1232
+ recaptures
921
1233
  };
922
1234
  } catch (err) {
923
1235
  return {
924
1236
  ok: false,
925
- error: err.message
1237
+ error: err.message,
1238
+ ...recaptures ? { recaptures } : {}
926
1239
  };
927
1240
  } finally {
928
1241
  if (watchdog) clearTimeout(watchdog);
@@ -934,6 +1247,12 @@ async function captureIn({ url, width, height, out, fullHeight = false, timeoutM
934
1247
  })]);
935
1248
  clearTimeout(t);
936
1249
  }
1250
+ const lv = liveFor(b);
1251
+ if (registered === "window" && windowId !== void 0) {
1252
+ const n = (lv.windows.get(windowId) ?? 1) - 1;
1253
+ if (n > 0) lv.windows.set(windowId, n);
1254
+ else lv.windows.delete(windowId);
1255
+ } else if (registered === "unknown") lv.unknown = Math.max(0, lv.unknown - 1);
937
1256
  b.abort(me, "the shot finished");
938
1257
  }
939
1258
  }
@@ -0,0 +1,139 @@
1
+ import { r as NAME } from "./cli.mjs";
2
+ import { i as readDevInfo } from "./work-F5u-twpJ.mjs";
3
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { randomBytes } from "node:crypto";
6
+ //#region src/cli/shot.ts
7
+ /**
8
+ * `marver shot <scene/frame> [...]`, `--scene <name>`, `--all` - render frames headless and
9
+ * print the PNG paths, one per line, in the order asked.
10
+ *
11
+ * The shell-ful agents' door into the same verify loop jam teaches: build, shoot, LOOK. One
12
+ * frame goes through /api/shot; several, a scene or everything go through /api/shots as ONE
13
+ * operation (one browser, several frames at a time), so shooting a scene costs about what
14
+ * shooting a frame did. shot.ts (server) has the capture story.
15
+ */
16
+ /** The fetch never reached the server: refused, unreachable, or forbidden by a sandbox (Codex's blocks the network,
17
+ * localhost included). Only these move a shot to the file inbox - never an HTTP answer, never a failure after the
18
+ * request went out. */
19
+ const CONNECT = /* @__PURE__ */ new Set([
20
+ "ECONNREFUSED",
21
+ "EPERM",
22
+ "EACCES",
23
+ "EHOSTUNREACH",
24
+ "ENETUNREACH",
25
+ "EADDRNOTAVAIL"
26
+ ]);
27
+ function cannotConnect(err) {
28
+ const cause = err?.cause;
29
+ if (!cause) return false;
30
+ if (Array.isArray(cause.errors) && cause.errors.length) return cause.errors.every((e) => !!e?.code && CONNECT.has(e.code));
31
+ return !!cause.code && CONNECT.has(cause.code);
32
+ }
33
+ /** The same request through the file inbox the dev server watches (design/.local/shots): a name of its own, written
34
+ * whole, its own result read and both files removed. Waiting stops at `ms` - it does not cancel; a request still
35
+ * unclaimed then is removed, so it never runs later. */
36
+ async function viaInbox(root, spec, ms) {
37
+ const inbox = join(root, "design", ".local", "shots");
38
+ const name = `cli-${randomBytes(8).toString("hex")}`;
39
+ const request = join(inbox, `${name}.request.json`), result = join(inbox, `${name}.result.json`);
40
+ try {
41
+ const tmp = join(inbox, `.${name}.tmp`);
42
+ writeFileSync(tmp, JSON.stringify(spec));
43
+ renameSync(tmp, request);
44
+ } catch (err) {
45
+ throw new Error(`could not reach \`${NAME} dev\` (the network is blocked here) and could not write to design/.local/shots - ${err.message}`);
46
+ }
47
+ for (const by = Date.now() + ms; Date.now() < by;) {
48
+ if (existsSync(result)) try {
49
+ const data = JSON.parse(readFileSync(result, "utf8"));
50
+ rmSync(result, { force: true });
51
+ return data;
52
+ } catch {}
53
+ await new Promise((r) => setTimeout(r, 150));
54
+ }
55
+ rmSync(request, { force: true });
56
+ throw new Error(`stopped waiting for \`${NAME} dev\` after ${Math.round(ms / 1e3)} s (asked through design/.local/shots - the network is blocked here)`);
57
+ }
58
+ async function shotCommand(root, frames, opts) {
59
+ const usage = `${NAME} shot <scene/frame ...> | --scene <name> | --all [--theme <name>] [--scale 1-4] [--json]`;
60
+ if ([
61
+ frames.length > 0,
62
+ !!opts.scene,
63
+ !!opts.all
64
+ ].filter(Boolean).length !== 1) throw new Error(`name the frames, one way: ${usage}`);
65
+ const info = readDevInfo(root);
66
+ if (!info) throw new Error(`\`${NAME} dev\` is not running in this repo (design/.local/dev.json not found) - start it first.`);
67
+ const scale = opts.scale != null ? Number(opts.scale) : void 0;
68
+ const theme = opts.theme;
69
+ const single = frames.length === 1 && !opts.scene && !opts.all;
70
+ const sel = single ? { frame: frames[0] } : opts.all ? { all: true } : opts.scene ? { scene: opts.scene } : { frames };
71
+ let data;
72
+ try {
73
+ let res;
74
+ if (single) {
75
+ const qs = new URLSearchParams({
76
+ frame: frames[0],
77
+ ...theme ? { theme } : {},
78
+ ...scale != null ? { scale: String(scale) } : {}
79
+ });
80
+ res = await fetch(`http://localhost:${info.port}/__mv/api/shot?${qs}`, { headers: { "x-mv-work": info.token } });
81
+ } else res = await fetch(`http://localhost:${info.port}/__mv/api/shots`, {
82
+ method: "POST",
83
+ headers: {
84
+ "x-mv-work": info.token,
85
+ "content-type": "application/json"
86
+ },
87
+ body: JSON.stringify({
88
+ ...sel,
89
+ ...theme ? { theme } : {},
90
+ ...scale != null ? { scale } : {}
91
+ })
92
+ });
93
+ data = await res.json().catch(() => ({}));
94
+ if (!res.ok) throw Object.assign(new Error(data.error ?? `shot failed (${res.status})`), { answered: true });
95
+ } catch (err) {
96
+ if (err.answered) throw err;
97
+ if (!cannotConnect(err)) throw new Error(`could not reach \`${NAME} dev\` on port ${info.port} - is it still running?`);
98
+ const waitMs = Number(process.env.MARVER_SHOT_INBOX_WAIT_MS) > 0 ? Number(process.env.MARVER_SHOT_INBOX_WAIT_MS) : single ? 12e4 : 6e5;
99
+ data = await viaInbox(root, {
100
+ ...sel,
101
+ ...theme ? { theme } : {},
102
+ ...scale != null ? { scale } : {}
103
+ }, waitMs);
104
+ if (data.ok === false) throw new Error(String(data.error ?? "shot failed"));
105
+ }
106
+ const one = data;
107
+ const results = single ? [one.path ? {
108
+ frame: frames[0],
109
+ ok: true,
110
+ path: one.path,
111
+ width: one.width,
112
+ height: one.height,
113
+ scale: one.scale,
114
+ ...one.truncated ? { truncated: true } : {},
115
+ ...one.unsettled ? { unsettled: true } : {},
116
+ ...one.note ? { note: one.note } : {},
117
+ recaptures: one.recaptures ?? 0
118
+ } : {
119
+ frame: frames[0],
120
+ ok: false,
121
+ error: one.error ?? "shot failed"
122
+ }] : data.results ?? [];
123
+ if (opts.json) {
124
+ console.log(JSON.stringify({ results }, null, 2));
125
+ if (results.some((r) => !r.ok)) process.exitCode = 1;
126
+ return;
127
+ }
128
+ let failed = false;
129
+ for (const r of results) if (r.ok) {
130
+ console.log(r.path);
131
+ if (r.note) console.error(`${r.frame}: ${r.note}`);
132
+ } else {
133
+ failed = true;
134
+ console.error(`${r.frame}: ${r.error}`);
135
+ }
136
+ if (failed) process.exitCode = 1;
137
+ }
138
+ //#endregion
139
+ export { shotCommand };