@william_jin/autobrowse 0.8.21 → 0.8.23

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.
@@ -7,8 +7,8 @@
7
7
  A sidebar of sessions and panes; each pane is an iframe of its session's viewer. Talks only to the app (ipc). -->
8
8
  <style>
9
9
  /* wren's workspace glass (wren packages/ui/src/theme.tsx: BASE + GLASS.light, night + GLASS.dark): wall on the desk, glass chrome, paper panes */
10
- :root{color-scheme:light;--accent:#2450c4;--hair:color-mix(in srgb,var(--fg) 11%,transparent);--fill:color-mix(in srgb,var(--fg) 5%,transparent);--raise:0 0 0 1px var(--hair),0 1px 2px rgb(0 0 0/.06),0 4px 14px rgb(20 30 60/.06);--wall:linear-gradient(rgb(244 246 250/.55),rgb(244 246 250/.55)),radial-gradient(70% 90% at 8% 8%,#adc6f4 0,transparent 62%),radial-gradient(60% 80% at 92% 18%,#f4c4d8 0,transparent 60%),radial-gradient(70% 70% at 58% 104%,#bfe3c6 0,transparent 62%) #e2e6ef;--glass:rgb(255 255 255/.62);--blur:blur(36px) saturate(1.6);--frost:linear-gradient(var(--glass),var(--glass)),var(--wall);--paper:#fff;--bg:var(--paper);--side:var(--glass);--sidebg:#f3f5fa;--fg:#16161a;--mut:color-mix(in srgb,#55555e 68%,#16161a);--rowh:color-mix(in srgb,var(--fg) 5%,transparent);--rowon:color-mix(in srgb,var(--fg) 8%,transparent);--line:color-mix(in srgb,var(--fg) 8%,transparent);--needs:#f9edd3;--needsfg:#74490a;--needsbtn:rgba(0,0,0,.08);--ring:var(--accent);--brand:var(--accent);--held:#8a5a00;--heldt:rgba(214,150,20,.17);--btn:color-mix(in srgb,var(--fg) 6%,transparent);--btnh:color-mix(in srgb,var(--fg) 10%,transparent);--seg:color-mix(in srgb,var(--fg) 6%,transparent);--segon:#fff;--mkf:#fff;--mkt:#6b4ee6;--drop:color-mix(in srgb,var(--accent) 14%,transparent);--scrim:rgb(20 24 40/.25);--lift:0 12px 40px rgb(40 50 90/.18);--tbar:var(--paper);--frame:0 0 0 1px rgb(20 30 60/.10),0 1px 2px rgb(0 0 0/.06),0 10px 30px -10px rgb(40 50 90/.24)}
11
- :root[data-theme=dark],:root[data-look=dark]{color-scheme:dark;--accent:#7f9dff;--raise:0 0 0 1px var(--hair),0 6px 18px -8px rgb(0 0 0/.6);--wall:linear-gradient(rgb(6 6 8/.3),rgb(6 6 8/.3)),radial-gradient(70% 90% at 8% 8%,#283f86 0,transparent 62%),radial-gradient(60% 80% at 92% 18%,#5c2a55 0,transparent 60%),radial-gradient(70% 70% at 58% 104%,#17503a 0,transparent 62%) #08080a;--glass:rgb(20 20 23/.78);--paper:#1c1c20;--sidebg:#141418;--fg:#f2f2f2;--mut:color-mix(in srgb,#9a9aa2 68%,#f2f2f2);--needs:#3e3216;--needsfg:#f3dfa8;--held:#f0c060;--heldt:rgba(240,192,96,.15);--btn:color-mix(in srgb,var(--fg) 7%,transparent);--btnh:color-mix(in srgb,var(--fg) 12%,transparent);--segon:color-mix(in srgb,#fff 14%,transparent);--mkf:#16161a;--mkt:#a996ff;--drop:color-mix(in srgb,var(--accent) 16%,transparent);--scrim:rgba(0,0,0,.55);--lift:0 12px 40px rgb(0 0 0/.55);--frame:0 0 0 1px rgba(255,255,255,.10),0 10px 28px -10px rgb(0 0 0/.75)}
10
+ :root{color-scheme:light;--accent:#2450c4;--hair:color-mix(in srgb,var(--fg) 11%,transparent);--fill:color-mix(in srgb,var(--fg) 5%,transparent);--raise:0 0 0 1px var(--hair),0 1px 2px rgb(0 0 0/.06),0 4px 14px rgb(20 30 60/.06);--wall:linear-gradient(rgb(244 246 250/.85),rgb(244 246 250/.85)),radial-gradient(70% 90% at 8% 8%,#adc6f4 0,transparent 62%),radial-gradient(60% 80% at 92% 18%,#f4c4d8 0,transparent 60%),radial-gradient(70% 70% at 58% 104%,#bfe3c6 0,transparent 62%) #e2e6ef;--glass:rgb(255 255 255/.62);--blur:blur(36px) saturate(1.6);--frost:linear-gradient(var(--glass),var(--glass)),var(--wall);--paper:#fff;--bg:var(--paper);--side:var(--glass);--sidebg:#f3f5fa;--fg:#16161a;--mut:color-mix(in srgb,#55555e 68%,#16161a);--rowh:color-mix(in srgb,var(--fg) 5%,transparent);--rowon:color-mix(in srgb,var(--fg) 8%,transparent);--line:color-mix(in srgb,var(--fg) 8%,transparent);--needs:#f9edd3;--needsfg:#74490a;--needsbtn:rgba(0,0,0,.08);--ring:var(--accent);--brand:var(--accent);--held:#8a5a00;--heldt:rgba(214,150,20,.17);--btn:color-mix(in srgb,var(--fg) 6%,transparent);--btnh:color-mix(in srgb,var(--fg) 10%,transparent);--seg:color-mix(in srgb,var(--fg) 6%,transparent);--segon:#fff;--mkf:#fff;--mkt:#6b4ee6;--drop:color-mix(in srgb,var(--accent) 14%,transparent);--scrim:rgb(20 24 40/.25);--lift:0 12px 40px rgb(40 50 90/.18);--tbar:var(--paper);--frame:0 0 0 1px rgb(20 30 60/.10),0 1px 2px rgb(0 0 0/.06),0 10px 30px -10px rgb(40 50 90/.24)}
11
+ :root[data-theme=dark],:root[data-look=dark]{color-scheme:dark;--accent:#7f9dff;--raise:0 0 0 1px var(--hair),0 6px 18px -8px rgb(0 0 0/.6);--wall:linear-gradient(rgb(6 6 8/.8),rgb(6 6 8/.8)),radial-gradient(70% 90% at 8% 8%,#283f86 0,transparent 62%),radial-gradient(60% 80% at 92% 18%,#5c2a55 0,transparent 60%),radial-gradient(70% 70% at 58% 104%,#17503a 0,transparent 62%) #08080a;--glass:rgb(20 20 23/.78);--paper:#1c1c20;--sidebg:#141418;--fg:#f2f2f2;--mut:color-mix(in srgb,#9a9aa2 68%,#f2f2f2);--needs:#3e3216;--needsfg:#f3dfa8;--held:#f0c060;--heldt:rgba(240,192,96,.15);--btn:color-mix(in srgb,var(--fg) 7%,transparent);--btnh:color-mix(in srgb,var(--fg) 12%,transparent);--segon:color-mix(in srgb,#fff 14%,transparent);--mkf:#16161a;--mkt:#a996ff;--drop:color-mix(in srgb,var(--accent) 16%,transparent);--scrim:rgba(0,0,0,.55);--lift:0 12px 40px rgb(0 0 0/.55);--frame:0 0 0 1px rgba(255,255,255,.10),0 10px 28px -10px rgb(0 0 0/.75)}
12
12
  @media (prefers-reduced-transparency:reduce){:root{--frost:linear-gradient(var(--sidebg),var(--sidebg))}}
13
13
  *{box-sizing:border-box}
14
14
  html,body{margin:0;height:100%;overflow:clip;background:var(--wall);color:var(--fg);font:13px/1.3 -apple-system,system-ui,sans-serif;-webkit-user-select:none;user-select:none;cursor:default}
@@ -64,6 +64,8 @@ button:focus-visible,.row:focus-visible{outline:2px solid var(--ring);outline-of
64
64
  .sh[aria-expanded]:hover{color:var(--fg)}
65
65
  .row{position:relative;display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:2px 10px;padding:7px 8px;margin-bottom:1px;border-radius:9px;transition:background-color .2s,opacity .15s,transform .2s cubic-bezier(.16,1,.3,1)}
66
66
  /* --rowfill tints the glass; --rowbg is the same colour opaque, for rings cut into the icon */
67
+ /* the entry fade on first style: a covered window runs no frame callback, and a row made there stayed clear */
68
+ @starting-style{.row{opacity:0}}
67
69
  .row{--rowfill:transparent;--rowbg:var(--sidebg);background:var(--rowfill)}
68
70
  .row:hover{--rowfill:var(--rowh);--rowbg:color-mix(in srgb,var(--fg) 5%,var(--sidebg))}
69
71
  .row.on{--rowfill:var(--rowon);--rowbg:color-mix(in srgb,var(--fg) 8%,var(--sidebg))}
@@ -158,9 +160,11 @@ kbd{display:inline-flex;align-items:center;justify-content:center;min-width:18px
158
160
  .pane{position:absolute;overflow:hidden;background:var(--bg);opacity:0;transform-origin:0 0;transition:opacity .15s cubic-bezier(.16,1,.3,1)}
159
161
  .pin{display:flex;flex-direction:column;width:100%;height:100%;transform-origin:0 0}
160
162
  .pane.in{opacity:1}
163
+ /* the entry fade on first style, not on a frame callback: a covered window runs none, and a pane made there stayed clear */
164
+ @starting-style{.pane.in{opacity:0}}
161
165
  .pane.off{visibility:hidden;pointer-events:none}
162
166
  /* §Hub windows: each run in Grid or Split is a window: frame, shadow, a raised title bar over the darker desk */
163
- .grid .pane{border-radius:var(--win-r);box-shadow:var(--frame)}
167
+ .grid .pane,.single .pane.hug{border-radius:var(--win-r);box-shadow:var(--frame)}
164
168
  .pane::after{content:"";position:absolute;inset:0;border-radius:inherit;box-shadow:inset 0 0 0 1.5px var(--ring);pointer-events:none;opacity:0;transition:opacity .15s}
165
169
  .pane.cur::after{opacity:1}
166
170
  .single .pane.cur::after{display:none}
@@ -415,7 +419,7 @@ function end(id) {
415
419
  el?.classList.add('out');
416
420
  setTimeout(() => {
417
421
  if (!rows.get(id)?.ended) return;
418
- rows.delete(id); order = order.filter((x) => x !== id); auto.delete(id);
422
+ rows.delete(id); pageBy.delete(id); order = order.filter((x) => x !== id); auto.delete(id);
419
423
  cells = cells.filter((k) => idOf(k) !== id);
420
424
  for (const k of [...panes.keys()]) if (idOf(k) === id) drop(k);
421
425
  fill(); render();
@@ -442,9 +446,10 @@ const auto = new Set();
442
446
  /** asked, never came up: a person's Watch only */
443
447
  const autoFailed = new Set();
444
448
  const AUTO_MS = 20_000;
445
- /** hub on screen and a pane free: watch lazy runs, in row order, one per free pane */
449
+ /** a pane free: watch lazy runs, in row order, one per free pane. Off screen too: a run streams no frame
450
+ * while the hub is hidden, and a switch to the hub then shows it in ~0.3 s, not ~1.5 s (WA-1500) */
446
451
  function autoOpen(cap) {
447
- if (!hubOn || !autoOn()) return;
452
+ if (!autoOn()) return;
448
453
  const asked = (id) => auto.has(id) || opening.has(id);
449
454
  let free = cap - cells.length - [...rows.keys()].filter((id) => asked(id) && !rows.get(id).url).length;
450
455
  for (const id of sorted()) {
@@ -467,7 +472,8 @@ function setLayout(l) {
467
472
  /** bento cells, in fractions of the stage */
468
473
  /** a page's usual shape (1280x800) */
469
474
  const PAGE = 1.6;
470
- function rects(n, W = stage.clientWidth, H = stage.clientHeight) {
475
+ /** the arrangement with no fixed run shown */
476
+ function baseRects(n, W, H) {
471
477
  if (n <= 1) return [[0, 0, 1, 1]];
472
478
  if (n === 2) return [[0, 0, .5, 1], [.5, 0, .5, 1]];
473
479
  if (n === 3) return [[0, 0, .6, 1], [.6, 0, .4, .5], [.6, .5, .4, .5]];
@@ -483,6 +489,10 @@ function rects(n, W = stage.clientWidth, H = stage.clientHeight) {
483
489
  }
484
490
  if (shown > best + 1) { best = shown; cols = c; }
485
491
  }
492
+ return evenGrid(n, cols);
493
+ }
494
+ /** n cells in rows of `cols`; a short last row spreads wide */
495
+ function evenGrid(n, cols) {
486
496
  const rowsN = Math.ceil(n / cols), out = [];
487
497
  for (let i = 0; i < n; i++) {
488
498
  const r = Math.floor(i / cols), inRow = Math.min(cols, n - r * cols), c = i - r * cols;
@@ -490,6 +500,88 @@ function rects(n, W = stage.clientWidth, H = stage.clientHeight) {
490
500
  }
491
501
  return out;
492
502
  }
503
+ // --- §Hub fit: a fixed run's pane is its page, scaled whole, plus its bar ------------------
504
+ /** the pane bar's height (.ph); a hugged pane is never narrower than its buttons need */
505
+ const PH = 28, HUG_MIN = 220;
506
+ /** another arrangement must show this much more page: a window drag never flips at a line */
507
+ const PICK_MARGIN = 1.04;
508
+ /** a lazy row before its viewer reports: a run's usual viewport */
509
+ const LAZY_PAGE = { w: 1280, h: 800, fixed: true, chrome: 0 };
510
+ /** run id → its viewer's last `page`: a new pane of the run fits at once */
511
+ const pageBy = new Map();
512
+ function pageOf(key) {
513
+ return panes.get(key)?.page ?? pageBy.get(idOf(key)) ?? (rows.get(idOf(key))?.lazy ? LAZY_PAGE : null);
514
+ }
515
+ /** the viewer's own fit (viewer.html zs): whole, never above 1:1 */
516
+ const fitScale = (w, h, pg) => Math.max(0, Math.min(1, w / pg.w, h / pg.h));
517
+ /** the page area a cell shows: a fixed page scaled whole; any other page fills its cell */
518
+ function pageArea([, , w, h], pg) {
519
+ const rh = h - PH - (pg?.chrome || 0);
520
+ if (!pg?.fixed) return w * Math.max(0, rh);
521
+ const s = fitScale(w, rh, pg);
522
+ return s * s * pg.w * pg.h;
523
+ }
524
+ /** the arrangements to weigh: Split side by side or stacked; Grid the bento, its stacked twin, 1 to 5 columns */
525
+ function arrangements(n) {
526
+ const out = [];
527
+ if (n === 3) out.push(['bento', [[0, 0, .6, 1], [.6, 0, .4, .5], [.6, .5, .4, .5]]], ['bento-stack', [[0, 0, 1, .6], [0, .6, .5, .4], [.5, .6, .5, .4]]]);
528
+ for (let c = 1; c <= Math.min(n, 5); c++) out.push([`g${c}`, evenGrid(n, c)]);
529
+ return out;
530
+ }
531
+ /** rows in order, one height per row, each pane as wide as its page needs at that height: mixed shapes pack tight */
532
+ const JUSTIFY_MAX = 6;
533
+ function justified(cuts, pg, W, H) {
534
+ const n = pg.length, Wu = W - GAP, Hu = H - GAP, rowsOf = [];
535
+ for (let i = 0, r = []; i < n; i++) { r.push(i); if (i === n - 1 || cuts & (1 << i)) { rowsOf.push(r); r = []; } }
536
+ const asp = (p) => (p?.fixed && p.w > 0 && p.h > 0 ? p.w / p.h : PAGE), ch = (p) => PH + (p?.chrome || 0);
537
+ // the height a row needs to fill the width: sum (h - bar) * aspect = room
538
+ const need = rowsOf.map((r) => (Wu - r.length * GAP + r.reduce((a, i) => a + ch(pg[i]) * asp(pg[i]), 0)) / r.reduce((a, i) => a + asp(pg[i]), 0));
539
+ const tall = need.reduce((a, h) => a + h + GAP, 0), k = Math.min(1, Hu / tall);
540
+ const out = [];
541
+ let y = (1 - Math.min(1, tall / Hu)) / 2;
542
+ rowsOf.forEach((r, ri) => {
543
+ const h = need[ri] * k - (1 - k) * GAP, g = (h + GAP) / Hu;
544
+ // a pane never narrower than its bar's buttons (hug's HUG_MIN); a row past the width shrinks its wider panes to fit
545
+ const floor = (HUG_MIN + GAP + 1) / Wu; // +1: boxOf rounds each edge
546
+ let fs = r.map((i) => Math.max(floor, (Math.max(0, h - ch(pg[i])) * asp(pg[i]) + GAP) / Wu));
547
+ const sum = fs.reduce((a, b) => a + b, 0);
548
+ for (let pass = 0; pass <= r.length && fs.reduce((a, b) => a + b, 0) > 1 + 1e-9; pass++) {
549
+ const low = fs.filter((f) => f <= floor + 1e-9).reduce((a, b) => a + b, 0), rest = fs.reduce((a, b) => a + b, 0) - low;
550
+ // every pane at the floor: all shrink alike
551
+ const s = rest > 0 ? Math.max(0, 1 - low) / rest : 1 / (low || 1);
552
+ fs = fs.map((f) => (rest > 0 && f <= floor + 1e-9 ? f : Math.max(rest > 0 ? floor : 0, f * s)));
553
+ }
554
+ let x = (1 - Math.min(1, sum)) / 2;
555
+ r.forEach((_, j) => { out.push([x, y, fs[j], g]); x += fs[j]; });
556
+ y += g;
557
+ });
558
+ return out;
559
+ }
560
+ /** the arrangement shown now (its key), and its cells: arrow keys move over what is drawn */
561
+ let pick = '', shownRects = [];
562
+ function rects(n, W = stage.clientWidth, H = stage.clientHeight, pg = []) {
563
+ if (n <= 1 || !pg.some((x) => x?.fixed)) { pick = ''; return baseRects(n, W, H); }
564
+ // justified rows first: a tie goes to the tightest packing
565
+ const all = [];
566
+ if (n <= JUSTIFY_MAX) for (let c = 0; c < 1 << (n - 1); c++) all.push([`j${c}`, justified(c, pg, W, H)]);
567
+ all.push(['base', baseRects(n, W, H)], ...arrangements(n));
568
+ const score = (R) => R.reduce((a, r, i) => a + pageArea(boxOf(r, W, H, GAP), pg[i]), 0);
569
+ const scored = all.map(([k, R]) => [k, R, score(R)]);
570
+ const now = scored.find(([k]) => k === pick) ?? scored[0];
571
+ const top = scored.reduce((a, b) => (b[2] > a[2] ? b : a));
572
+ const got = top[2] > now[2] * PICK_MARGIN ? top : now;
573
+ pick = got[0];
574
+ return got[1];
575
+ }
576
+ /** a fixed run's box: its page scaled whole plus its bar, centred in the cell; null: the whole cell */
577
+ function hug([l, t, w, h], pg, single) {
578
+ if (!pg?.fixed || !(pg.w > 0) || !(pg.h > 0)) return null;
579
+ const head = single ? 0 : PH, pad = single ? GAP : 0, ch = pg.chrome || 0;
580
+ const rw = w - 2 * pad, rh = h - 2 * pad - head - ch, s = fitScale(rw, rh, pg);
581
+ if (s <= 0) return null;
582
+ const bw = Math.min(rw, Math.max(HUG_MIN, Math.round(pg.w * s))), bh = Math.round(pg.h * s) + head + ch;
583
+ return [l + Math.round((w - bw) / 2), t + Math.round((h - bh) / 2), bw, bh];
584
+ }
493
585
  // --- §Hub motion: FLIP --------------------------------------------------------------
494
586
  // a pane takes its new box at once (one layout, one page resize); a transform plays from the old box
495
587
  const SWEEP_MS = 200, KF = 20;
@@ -538,10 +630,27 @@ function sweep(p, o, n, r) {
538
630
  /** desk between windows and their corners (§Hub windows); the CSS reads `--win-r` */
539
631
  const GAP = 10, RADIUS = 10;
540
632
  document.documentElement.style.setProperty('--win-r', `${RADIUS}px`);
541
- /** a cell in px: each edge rounds once, so neighbours share it and every gap is exactly `gap` */
633
+ /** a cell in px: fractions of the stage less one gap, each edge rounds once; every gap is exactly `gap`, equal fractions equal boxes */
542
634
  function boxOf([x, y, w, h], W, H, gap) {
543
- const l = Math.round(x * W), t = Math.round(y * H), r = Math.round((x + w) * W), b = Math.round((y + h) * H);
544
- return [l + gap, t + gap, r - l - gap * (x + w >= .999 ? 2 : 1), b - t - gap * (y + h >= .999 ? 2 : 1)];
635
+ const Wu = W - gap, Hu = H - gap;
636
+ const l = Math.round(x * Wu), t = Math.round(y * Hu), r = Math.round((x + w) * Wu), b = Math.round((y + h) * Hu);
637
+ return [l + gap, t + gap, r - l - gap, b - t - gap];
638
+ }
639
+ /** hugged panes in one row of cells sit together, centred in the row's span: no desk inside a row */
640
+ function packRows(items, gap) {
641
+ const byRow = new Map();
642
+ items.forEach((it) => { const k = `${it.cell[1]},${it.cell[3]}`; byRow.set(k, [...(byRow.get(k) ?? []), it]); });
643
+ for (const row of byRow.values()) {
644
+ // a pane that fills its cell holds the row as drawn
645
+ if (row.length < 2 || row.some((it) => !it.fit)) continue;
646
+ row.sort((a, b) => a.cell[0] - b.cell[0]);
647
+ const l = row[0].cell[0], r = Math.max(...row.map((it) => it.cell[0] + it.cell[2]));
648
+ const used = row.reduce((a, it) => a + it.fit[2], 0) + gap * (row.length - 1);
649
+ if (used >= r - l) continue;
650
+ let x = l + Math.round((r - l - used) / 2);
651
+ for (const it of row) { it.fit = [x, it.fit[1], it.fit[2], it.fit[3]]; x += it.fit[2] + gap; }
652
+ }
653
+ return items;
545
654
  }
546
655
  /** what a pane's viewer needs: tiles scale frames; one full pane sets the viewport; a narrow first pane zooms out */
547
656
  function embedOf(key) {
@@ -585,7 +694,7 @@ function pane(key) {
585
694
  stage.append(el);
586
695
  p = { el, frame, url: r.url, title: '', at: Date.now() };
587
696
  panes.set(key, p);
588
- requestAnimationFrame(() => el.classList.add('in'));
697
+ el.classList.add('in');
589
698
  return p;
590
699
  }
591
700
  function drop(key) {
@@ -663,13 +772,18 @@ function render() {
663
772
  renderRows(rowsWas);
664
773
  // panes
665
774
  const W = stage.clientWidth, H = stage.clientHeight, gap = single ? 0 : GAP;
666
- const R = rects(cells.length);
775
+ const R = rects(cells.length, W, H, cells.map(pageOf));
776
+ shownRects = R;
667
777
  // a window resize or a grip drag tracks the hand: no sweep; a sidebar mode change sweeps
668
778
  const resized = `${W}x${H}` !== stageWH; stageWH = `${W}x${H}`;
669
779
  // reduced motion: no sweep; a moved pane fades in at its new box
670
780
  const morph = (!resized || roomMoved) && !sizing && booted && motionOn(), moves = morph && !reduceQ.matches;
671
781
  roomMoved = false;
672
782
  const at = moves ? stage.getBoundingClientRect() : null, cuts = [];
783
+ const boxes = packRows(cells.map((key, i) => {
784
+ const cell = boxOf(max ? [0, 0, 1, 1] : R[i], W, H, gap);
785
+ return { cell, fit: hug(cell, pageOf(key), single) };
786
+ }), gap);
673
787
  cells.forEach((key, i) => {
674
788
  const p = pane(key);
675
789
  const r = rows.get(idOf(key));
@@ -689,7 +803,9 @@ function render() {
689
803
  if (morph && (back || (hidden && !off))) fade(p, back);
690
804
  const mb = p.el.querySelector('[data-a=max]'), mi = max ? 'min' : 'max';
691
805
  if (mb.dataset.i !== mi) { mb.dataset.i = mi; mb.innerHTML = icon(mi); }
692
- const [left, top, width, height] = boxOf(max ? [0, 0, 1, 1] : R[i], W, H, gap);
806
+ const { cell, fit } = boxes[i];
807
+ const [left, top, width, height] = fit ?? cell;
808
+ p.el.classList.toggle('hug', !!fit);
693
809
  const z = i === cur ? '1' : '0';
694
810
  if (p.el.style.zIndex !== z) p.el.style.zIndex = z;
695
811
  const box = `${left},${top},${width},${height}`;
@@ -700,7 +816,7 @@ function render() {
700
816
  p.box = box;
701
817
  Object.assign(p.el.style, { left: `${left}px`, top: `${top}px`, width: `${width}px`, height: `${height}px` });
702
818
  const o = moves && !hidden && !back ? was.get(key) : null;
703
- if (o) sweep(p, o, { left: at.left + left, top: at.top + top, width, height }, single ? 0 : RADIUS);
819
+ if (o) sweep(p, o, { left: at.left + left, top: at.top + top, width, height }, single && !fit ? 0 : RADIUS);
704
820
  else stopSweep(p);
705
821
  if (morph && !moves && !hidden && !back && was.has(key)) fade(p, true);
706
822
  }
@@ -838,8 +954,6 @@ function rowEl(id) {
838
954
  });
839
955
  el.addEventListener('keydown', (e) => { if (e.key === 'Enter' && e.target === el) enter(id); });
840
956
  el.addEventListener('dragstart', (e) => { e.dataTransfer.setData('text/plain', `row:${id}`); e.dataTransfer.effectAllowed = 'move'; });
841
- el.style.opacity = '0';
842
- requestAnimationFrame(() => { el.style.opacity = ''; });
843
957
  return el;
844
958
  }
845
959
  function secEl(sec, label) {
@@ -1106,7 +1220,7 @@ function focusPane() {
1106
1220
  function toggleMax() { if (cells.length > 1 || max) { max = !max; render(); focusPane(); } }
1107
1221
  function move(code) {
1108
1222
  if (cells.length < 2) return;
1109
- const R = rects(cells.length), [x, y, w, h] = R[cur], cx = x + w / 2, cy = y + h / 2;
1223
+ const R = shownRects.length === cells.length ? shownRects : rects(cells.length), [x, y, w, h] = R[cur], cx = x + w / 2, cy = y + h / 2;
1110
1224
  let best = -1, bd = Infinity;
1111
1225
  R.forEach(([x2, y2, w2, h2], i) => {
1112
1226
  if (i === cur) return;
@@ -1151,6 +1265,12 @@ addEventListener('message', (e) => {
1151
1265
  if (m.t === 'focus') { closeFlyout(); const i = cells.indexOf(k); if (i >= 0 && i !== cur) { cur = i; render(); } }
1152
1266
  else if (m.t === 'title' && typeof m.text === 'string') { p.title = m.text; p.el.querySelector('.tt').textContent = m.text; const ph = p.el.querySelector('.ph'); ph.title = `${ph.title.split(' · ')[0]} · ${m.text}`; }
1153
1267
  else if (m.t === 'close') { cells = cells.filter((x) => x !== k); render(); }
1268
+ else if (m.t === 'page' && m.w > 0 && m.h > 0) {
1269
+ const pg = { w: +m.w, h: +m.h, fixed: !!m.fixed, chrome: Math.max(0, +m.chrome || 0) };
1270
+ if (JSON.stringify(pg) === JSON.stringify(p.page)) return;
1271
+ p.page = pg; pageBy.set(idOf(k), pg);
1272
+ if (cells.includes(k)) render();
1273
+ }
1154
1274
  else if (m.t === 'key') key(m);
1155
1275
  });
1156
1276
 
@@ -282,6 +282,17 @@ function layout() {
282
282
  if (old) { g.drawImage(old, 0, 0); if (!tile && !fixed) edgeFill(old.width, old.height); }
283
283
  }
284
284
  fitOverlay();
285
+ pageOut();
286
+ }
287
+ /** the hub fits a fixed run's pane to its page (§Hub fit): the page size and our bars above the stage; only on change */
288
+ let pageSent = '';
289
+ function pageOut() {
290
+ // before the hub's embed the bars are a full viewer's: the pane would size twice
291
+ if (!embed || !placed || !view.w || !view.h) return;
292
+ const chrome = Math.max(0, $('app').clientHeight - stage.clientHeight);
293
+ const m = { t: 'page', w: view.w, h: view.h, fixed, chrome };
294
+ const j = JSON.stringify(m);
295
+ if (j !== pageSent) { pageSent = j; hub(m); }
285
296
  }
286
297
  function size(now) {
287
298
  layout();
@@ -334,6 +345,7 @@ function msg(m) {
334
345
  view = m.view; fixed = !!m.fixed; document.documentElement.classList.toggle('fixed', fixed); canWindow = !!m.window; $('win').hidden = !canWindow;
335
346
  if (m.readOnly) watchOnly();
336
347
  fitOverlay();
348
+ pageOut();
337
349
  needs(m.needs);
338
350
  signingAs(m.signing);
339
351
  return;
@@ -349,7 +361,7 @@ function msg(m) {
349
361
  case 'agent': return agentState(m);
350
362
  case 'ov-html': return ovHtml(m.html);
351
363
  case 'ov-js': return ovJs(m.js);
352
- case 'view': view = { w: m.w, h: m.h }; fitOverlay(); return;
364
+ case 'view': view = { w: m.w, h: m.h }; fitOverlay(); pageOut(); return;
353
365
  case 'ov-shown': ovShown = m.on; ovVisible(); return;
354
366
  case 'suggest': return suggested(m);
355
367
  }
@@ -27,11 +27,33 @@ export interface HubAdd {
27
27
  /** A scheduled job runs it (`hubJobOf`). */
28
28
  job?: HubJob | undefined;
29
29
  }
30
+ /**
31
+ * What a run does with the hub (`BrowserOptions.hub`). `join` (default): a lazy row in a hub that
32
+ * runs, and none is started. `start`: no hub answers, so one starts behind the front app, the
33
+ * same as `autobrowse hub`; it never takes focus.
34
+ */
35
+ export type HubMode = "join" | "start";
36
+ /** The hub's first line. `on` and `attended` are absent from hubs before 12-01. */
37
+ export interface HubHello {
38
+ pid: number;
39
+ build: string;
40
+ /** its window is on screen */
41
+ on?: boolean | undefined;
42
+ /** sessions a person may work in: own windows, interactive sessions (an auto-opened run: none) */
43
+ attended?: number | undefined;
44
+ }
30
45
  export interface HubOptions {
31
46
  /** The socket; default `hubSocket()`. Tests pass a short temp path. */
32
47
  sock?: string | undefined;
33
48
  /** Start a hub on `sock`; default the app bundle's `overlay-host hub`. */
34
49
  start?: ((sock: string) => Promise<void>) | undefined;
50
+ /** A lazy run starts a hub when none answers (`HubMode` `start`). */
51
+ boot?: boolean | undefined;
52
+ /**
53
+ * A lazy run that joins a hub of an older build replaces it (`renewStale`). Default on for the
54
+ * person's hub; off with `sock` (tests pass their own).
55
+ */
56
+ renew?: ((hello: HubHello) => Promise<unknown>) | null | undefined;
35
57
  log?: ((line: string) => void) | undefined;
36
58
  }
37
59
  export interface HubLink {
@@ -69,3 +91,20 @@ export declare function openHub(opts?: {
69
91
  /** starts the app (tests: a fake hub) */
70
92
  start?: (sock: string) => Promise<void>;
71
93
  }): Promise<HubOpened>;
94
+ /**
95
+ * A run of a later build (`buildAbove`) joined a stale hub: it restarts the hub behind the front
96
+ * app, and every run rejoins (careers 12-01: a hub from before auto-open ran for hours). Never
97
+ * while a person may look at it (`inUse`): then it logs. One run renews: a lock file, then a
98
+ * second look; and once per `RENEW_EVERY_MS` per process.
99
+ */
100
+ export declare function renewStale(hello: HubHello, o?: {
101
+ sock?: string;
102
+ log?: (line: string) => void;
103
+ /** this package's build (tests: a stamp) */
104
+ build?: () => Promise<string>;
105
+ /** starts the new hub (tests: a fake) */
106
+ start?: (sock: string) => Promise<void>;
107
+ front?: () => Promise<number>;
108
+ }): Promise<"renewed" | "current" | "in use" | "skipped">;
109
+ /** Tests: the next `renewStale` is not held back by the last one. */
110
+ export declare function resetRenew(): void;
@@ -3,14 +3,14 @@
3
3
  * user shows every session. JSON lines over a Unix socket; the hub never drives a page.
4
4
  *
5
5
  * out: add, url, state, attention, calm, clip, pick, front, moved; `autobrowse hub`: open
6
- * in: hello {v,pid,build}, watch, visible, picked, opened, later, pause, back, closed
6
+ * in: hello {v,pid,build,on,attended}, watch, visible, picked, opened, later, pause, back, closed
7
7
  */
8
- import { spawn } from "node:child_process";
9
- import { mkdirSync, statSync, watch } from "node:fs";
8
+ import { execFile, spawn } from "node:child_process";
9
+ import { closeSync, existsSync, mkdirSync, openSync, statSync, unlinkSync, watch, } from "node:fs";
10
10
  import { createConnection } from "node:net";
11
11
  import { homedir } from "node:os";
12
12
  import { basename, dirname, join } from "node:path";
13
- import { liveApp, liveBinary, stampOf, } from "../explore/overlay-host.js";
13
+ import { buildAbove, liveApp, liveBinary, liveBuild, stampOf, } from "../explore/overlay-host.js";
14
14
  import { jobOfEnv } from "./owner.js";
15
15
  /** The protocol version, in the socket's name: an older hub never serves a newer session. */
16
16
  export const HUB_VERSION = 1;
@@ -18,8 +18,14 @@ export const HUB_VERSION = 1;
18
18
  const SOCK_MAX = 103;
19
19
  /** One line past this is not a hub's: the link drops. */
20
20
  const LINE_MAX = 1_000_000;
21
- /** A hub we started that never answers in this time is dead. */
21
+ /** A hub we started that never answers in this time is dead; a lazy run seeks a new one this long. */
22
22
  const START_MS = 15_000;
23
+ /** A lazy run's dials while a hub launches (its socket is there before it answers). */
24
+ const SEEK_EVERY_MS = 200;
25
+ /** fs.watch can miss an event: a lazy run also tries a socket that is there this often. */
26
+ const BACKSTOP_MS = 30_000;
27
+ /** A run renews a stale hub at most this often (`renewStale`). */
28
+ const RENEW_EVERY_MS = 10 * 60_000;
23
29
  /** The runner's job (`job:<name>/<run>` in `AUTOBROWSE_JOB`), with its schedule; null for anything else. */
24
30
  export function hubJobOf(env = process.env) {
25
31
  const name = /^job:([^/]+)\//.exec(jobOfEnv(env) ?? "")?.[1];
@@ -89,13 +95,12 @@ function lines(sock, fn) {
89
95
  sock.destroy();
90
96
  });
91
97
  }
92
- /** One connection: resolves after the hub's `hello` (its pid), null when nobody answers. */
98
+ /** One connection: resolves after the hub's `hello`, null when nobody answers. */
93
99
  function dial(path, onEvent) {
94
100
  return new Promise((resolve) => {
95
101
  const s = createConnection(path);
96
102
  let done = false;
97
- let pid = 0;
98
- let build = "";
103
+ let hello = { pid: 0, build: "" };
99
104
  const end = (ok) => {
100
105
  if (done)
101
106
  return;
@@ -103,7 +108,7 @@ function dial(path, onEvent) {
103
108
  clearTimeout(timer);
104
109
  if (!ok)
105
110
  s.destroy();
106
- resolve(ok ? { s, pid, build } : null);
111
+ resolve(ok ? { s, ...hello } : null);
107
112
  };
108
113
  const timer = setTimeout(() => end(false), 2_000);
109
114
  timer.unref();
@@ -112,8 +117,12 @@ function dial(path, onEvent) {
112
117
  lines(s, (e) => {
113
118
  if (!done) {
114
119
  if (e.t === "hello" && e.v === HUB_VERSION) {
115
- pid = typeof e.pid === "number" ? e.pid : 0;
116
- build = typeof e.build === "string" ? e.build : "";
120
+ hello = {
121
+ pid: typeof e.pid === "number" ? e.pid : 0,
122
+ build: typeof e.build === "string" ? e.build : "",
123
+ ...(typeof e.on === "boolean" ? { on: e.on } : {}),
124
+ ...(typeof e.attended === "number" ? { attended: e.attended } : {}),
125
+ };
117
126
  end(true);
118
127
  }
119
128
  else
@@ -143,12 +152,21 @@ export function joinHub(add, opts = {}) {
143
152
  log(`live hub: ${no}`);
144
153
  return null;
145
154
  }
146
- const start = opts.start ?? startApp;
155
+ // a run's start is a person's open: the window behind the front app, there to ⌘Tab to
156
+ const start = opts.start ?? ((p) => startApp(p, !!opts.boot));
157
+ const renew = opts.renew === undefined
158
+ ? opts.sock
159
+ ? null
160
+ : (h) => renewStale(h, { sock: path, log })
161
+ : opts.renew;
147
162
  let sock = null;
148
163
  let pid = 0;
149
164
  let closed = false;
150
165
  let dialing = null;
151
166
  let watcher = null;
167
+ let backstop = null;
168
+ let seekUntil = 0;
169
+ let seeking = false;
152
170
  const always = [];
153
171
  /** This connection's listeners: the live view's, dropped with it. */
154
172
  let epoch = [];
@@ -200,6 +218,8 @@ export function joinHub(add, opts = {}) {
200
218
  }
201
219
  pid = got.pid;
202
220
  attach(got.s);
221
+ if (add.lazy && renew)
222
+ void renew(got).catch((e) => log(`live hub: ${e.message}`));
203
223
  return true;
204
224
  };
205
225
  if (await tryOnce())
@@ -234,6 +254,24 @@ export function joinHub(add, opts = {}) {
234
254
  // a lazy dial in flight, then a person asks: start one after it
235
255
  return dialing.then((ok) => (ok || !boot || closed ? ok : ready(true)));
236
256
  };
257
+ /**
258
+ * A hub's socket appeared: dial until it answers. Its socket is there before it says hello
259
+ * (AppKit launches first), and a later event while a dial is out would be lost.
260
+ */
261
+ const seek = () => {
262
+ seekUntil = Date.now() + START_MS;
263
+ if (seeking)
264
+ return;
265
+ seeking = true;
266
+ void (async () => {
267
+ while (!closed && !sock && Date.now() < seekUntil) {
268
+ if (await ready(false))
269
+ break;
270
+ await new Promise((r) => setTimeout(r, SEEK_EVERY_MS).unref());
271
+ }
272
+ seeking = false;
273
+ })();
274
+ };
237
275
  /** A lazy run: join when a hub's socket shows up. */
238
276
  const watchFor = () => {
239
277
  if (watcher || closed)
@@ -241,20 +279,31 @@ export function joinHub(add, opts = {}) {
241
279
  try {
242
280
  watcher = watch(dirname(path), (_ev, name) => {
243
281
  if (name === basename(path))
244
- void ready(false);
282
+ seek();
245
283
  });
246
284
  watcher.unref();
247
285
  }
248
286
  catch (e) {
249
287
  log(`live hub: ${e.message}`);
250
288
  }
289
+ backstop = setInterval(() => {
290
+ if (!sock && existsSync(path))
291
+ void ready(false);
292
+ }, BACKSTOP_MS);
293
+ backstop.unref();
294
+ // a socket made before the watch began
295
+ if (existsSync(path))
296
+ seek();
251
297
  };
252
298
  const stopWatch = () => {
253
299
  watcher?.close();
254
300
  watcher = null;
301
+ if (backstop)
302
+ clearInterval(backstop);
303
+ backstop = null;
255
304
  };
256
305
  if (add.lazy)
257
- void ready(false).then((ok) => {
306
+ void ready(!!opts.boot).then((ok) => {
258
307
  if (!ok)
259
308
  watchFor();
260
309
  });
@@ -344,20 +393,112 @@ export async function openHub(opts = {}) {
344
393
  up.s.end(`${JSON.stringify({ t: "open" })}\n`);
345
394
  return { how: "shown", stale };
346
395
  }
347
- if (up) {
348
- up.s.destroy();
349
- if (up.pid) {
350
- process.kill(up.pid, "SIGTERM");
351
- const end = Date.now() + 5_000;
352
- while (Date.now() < end && alive(up.pid))
353
- await new Promise((r) => setTimeout(r, 100));
354
- if (alive(up.pid))
355
- throw new Error(`the old hub (pid ${up.pid}) did not quit`);
356
- }
357
- }
396
+ if (up)
397
+ await quit(up);
358
398
  await start(path);
359
399
  return { how: up ? "restarted" : "started", stale: false };
360
400
  }
401
+ /** The hub on the line quits (SIGTERM); its runs rejoin the next. */
402
+ async function quit(up) {
403
+ up.s.destroy();
404
+ if (!up.pid)
405
+ return;
406
+ process.kill(up.pid, "SIGTERM");
407
+ const end = Date.now() + 5_000;
408
+ while (Date.now() < end && alive(up.pid))
409
+ await new Promise((r) => setTimeout(r, 100));
410
+ if (alive(up.pid))
411
+ throw new Error(`the old hub (pid ${up.pid}) did not quit`);
412
+ }
413
+ /** The front app's pid (`lsappinfo`); -1 when unknown. */
414
+ function frontPid() {
415
+ const ask = (args) => new Promise((res) => execFile("lsappinfo", args, { timeout: 2_000 }, (e, out) => res(e ? "" : out)));
416
+ return ask(["front"]).then(async (asn) => {
417
+ const id = asn.trim();
418
+ if (!id)
419
+ return -1;
420
+ const m = /"pid"=(\d+)/.exec(await ask(["info", "-only", "pid", id]));
421
+ return m ? Number(m[1]) : -1;
422
+ });
423
+ }
424
+ /** In use: on screen, or a person's session in it; a hub before 12-01 says neither, so: the front app. */
425
+ async function inUse(h, front) {
426
+ if (h.on !== undefined)
427
+ return h.on || (h.attended ?? 0) > 0;
428
+ const pid = await front();
429
+ return pid < 0 || pid === h.pid;
430
+ }
431
+ let renewedAt = 0;
432
+ /**
433
+ * A run of a later build (`buildAbove`) joined a stale hub: it restarts the hub behind the front
434
+ * app, and every run rejoins (careers 12-01: a hub from before auto-open ran for hours). Never
435
+ * while a person may look at it (`inUse`): then it logs. One run renews: a lock file, then a
436
+ * second look; and once per `RENEW_EVERY_MS` per process.
437
+ */
438
+ export async function renewStale(hello, o = {}) {
439
+ if (Date.now() - renewedAt < RENEW_EVERY_MS)
440
+ return "skipped";
441
+ const path = o.sock ?? hubSocket();
442
+ const log = o.log ?? (() => undefined);
443
+ const front = o.front ?? frontPid;
444
+ const mine = await (o.build ?? liveBuild)();
445
+ if (!buildAbove(mine, hello.build))
446
+ return "current";
447
+ renewedAt = Date.now();
448
+ if (await inUse(hello, front)) {
449
+ log(`live hub: pid ${hello.pid} runs an older build (${hello.build}); left up while in use`);
450
+ return "in use";
451
+ }
452
+ const lock = `${path}.renew`;
453
+ if (!takeLock(lock))
454
+ return "skipped";
455
+ try {
456
+ // another run may have renewed it, or a person opened it, since the first look
457
+ const up = await dial(path, () => undefined);
458
+ if (!up)
459
+ return "skipped";
460
+ if (!buildAbove(mine, up.build) || (await inUse(up, front))) {
461
+ up.s.destroy();
462
+ return "skipped";
463
+ }
464
+ await quit(up);
465
+ await (o.start ?? ((p) => startApp(p, true)))(path);
466
+ log(`live hub: restarted pid ${up.pid} (${up.build}) on ${mine}`);
467
+ return "renewed";
468
+ }
469
+ finally {
470
+ try {
471
+ unlinkSync(lock);
472
+ }
473
+ catch {
474
+ // gone
475
+ }
476
+ }
477
+ }
478
+ /** One holder at a time; a lock left by a run that died ages out after a minute. */
479
+ function takeLock(lock) {
480
+ for (let i = 0; i < 2; i++) {
481
+ try {
482
+ closeSync(openSync(lock, "wx", 0o600));
483
+ return true;
484
+ }
485
+ catch {
486
+ try {
487
+ if (Date.now() - statSync(lock).mtimeMs < 60_000)
488
+ return false;
489
+ unlinkSync(lock);
490
+ }
491
+ catch {
492
+ // gone since: try again
493
+ }
494
+ }
495
+ }
496
+ return false;
497
+ }
498
+ /** Tests: the next `renewStale` is not held back by the last one. */
499
+ export function resetRenew() {
500
+ renewedAt = 0;
501
+ }
361
502
  function alive(pid) {
362
503
  try {
363
504
  process.kill(pid, 0);