@william_jin/autobrowse 0.8.25 → 0.8.27

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.
@@ -0,0 +1,341 @@
1
+ /**
2
+ * The Claude terminal beside the live view (designs/2026-12-01-agent-task.md §The terminal in the hub).
3
+ * A `/term` socket per open panel: `tmux attach` in a pty, bytes out, keys in. The 2-line strip of a
4
+ * bare pane comes from `tmux capture-pane`, with no pty.
5
+ */
6
+ import { execFile } from "node:child_process";
7
+ import { chmodSync, existsSync, readFileSync, statSync } from "node:fs";
8
+ import { createRequire } from "node:module";
9
+ import { dirname, join } from "node:path";
10
+ let ptyLoad = null;
11
+ /** node-pty, on first use (optional dependency). Its prebuilt spawn-helper ships with no exec bit. Text: why not. */
12
+ export function loadPty() {
13
+ ptyLoad ??= (async () => {
14
+ try {
15
+ const root = dirname(dirname(createRequire(import.meta.url).resolve("node-pty")));
16
+ for (const dir of [
17
+ join("prebuilds", `${process.platform}-${process.arch}`),
18
+ "build/Release",
19
+ ]) {
20
+ const helper = join(root, dir, "spawn-helper");
21
+ if (existsSync(helper) && !(statSync(helper).mode & 0o100))
22
+ chmodSync(helper, 0o755);
23
+ }
24
+ const pty = await import("node-pty");
25
+ return (file, args, o) => pty.spawn(file, args, o);
26
+ }
27
+ catch (err) {
28
+ ptyLoad = null;
29
+ return `node-pty did not load: ${(err instanceof Error ? err.message : String(err)).split("\n")[0]}`;
30
+ }
31
+ })();
32
+ return ptyLoad;
33
+ }
34
+ /** The viewer's terminal files, served from node_modules: path → package file, type. */
35
+ const ASSETS = {
36
+ "/x/xterm.js": ["@xterm/xterm/lib/xterm.js", "text/javascript; charset=utf-8"],
37
+ "/x/xterm.css": ["@xterm/xterm/css/xterm.css", "text/css; charset=utf-8"],
38
+ "/x/fit.js": ["@xterm/addon-fit/lib/addon-fit.js", "text/javascript; charset=utf-8"],
39
+ };
40
+ const assetCache = new Map();
41
+ /** A terminal file for the viewer, or null (not ours, or not installed). */
42
+ export function termAsset(path) {
43
+ const a = ASSETS[path];
44
+ if (!a)
45
+ return null;
46
+ if (!assetCache.has(path)) {
47
+ try {
48
+ assetCache.set(path, readFileSync(createRequire(import.meta.url).resolve(a[0])));
49
+ }
50
+ catch {
51
+ assetCache.set(path, null);
52
+ }
53
+ }
54
+ const body = assetCache.get(path);
55
+ return body ? { body, type: a[1] } : null;
56
+ }
57
+ /** A horizontal rule of Claude Code's input box (`────`, or the older `╭───`). */
58
+ const RULE = /^\s*[╭─]─{7,}/;
59
+ /** The input line under that rule. */
60
+ const PROMPT = /^\s*(❯|>|│\s*>)/;
61
+ /** A right-aligned notice over the box (`● high · /effort`): never Claude's words. */
62
+ const NOTICE = /^ {16,}\S/;
63
+ /** Claude's last 2 lines on a screen: above the input box, else the screen's last 2. */
64
+ export function stripLines(screen) {
65
+ const lines = screen.split("\n").map((l) => l.trimEnd());
66
+ let end = lines.length;
67
+ for (let i = lines.length - 1; i > 0; i--)
68
+ if (PROMPT.test(lines[i]) && RULE.test(lines[i - 1])) {
69
+ end = i - 1;
70
+ break;
71
+ }
72
+ return lines
73
+ .slice(0, end)
74
+ .filter((l) => l.trim() && !NOTICE.test(l) && !RULE.test(l))
75
+ .slice(-2)
76
+ .map((l) => l.trim());
77
+ }
78
+ /** `open` argv: a new Ghostty on the same session, opened behind the front app (`-g`). */
79
+ export const ghosttyArgv = (t) => [
80
+ "-g",
81
+ "-na",
82
+ "Ghostty",
83
+ "--args",
84
+ "-e",
85
+ t.tmux,
86
+ "-u",
87
+ "attach-session",
88
+ "-t",
89
+ `=${t.name}`,
90
+ ];
91
+ /** The pty's env: no TMUX (a nested attach refuses), a UTF-8 locale (else tmux draws `_`). */
92
+ export function ptyEnv(env) {
93
+ const out = {};
94
+ for (const [k, v] of Object.entries(env))
95
+ if (v !== undefined && k !== "TMUX" && k !== "TMUX_PANE")
96
+ out[k] = v;
97
+ out.TERM = "xterm-256color";
98
+ out.COLORTERM = "truecolor";
99
+ if (!/utf-?8/i.test(out.LC_ALL ?? out.LC_CTYPE ?? out.LANG ?? ""))
100
+ out.LANG = "en_US.UTF-8";
101
+ return out;
102
+ }
103
+ const run = (bin, args) => new Promise((ok) => execFile(bin, args, { timeout: 5_000 }, (err, _out, errText) => ok(err ? (String(errText).trim() || err.message).split("\n")[0] || "failed" : null)));
104
+ const capture = (t) => new Promise((ok) => execFile(t.tmux, ["capture-pane", "-p", "-t", `=${t.name}:`], { timeout: 5_000 }, (err, out) => ok(err ? null : String(out))));
105
+ /** A socket's frames past this: the pty pauses until the viewer drains. */
106
+ const BACKLOG = 1_000_000;
107
+ const COLS = { min: 20, max: 500 };
108
+ const ROWS = { min: 5, max: 200 };
109
+ const clamp = (n, r) => Math.max(r.min, Math.min(r.max, Math.round(Number(n)) || r.min));
110
+ /** The session's terminal: the state every viewer sees, the strip poll, one pty per `/term` socket. */
111
+ export function liveTerms(d) {
112
+ const spawnPty = d.spawn ?? loadPty;
113
+ const tmuxRun = d.run ?? run;
114
+ const grab = d.capture ?? capture;
115
+ let term = null;
116
+ let lines = [];
117
+ let ended = false;
118
+ let watchers = 0;
119
+ let poll;
120
+ const socks = new Set();
121
+ /** What a viewer gets: no tmux path, no socket target. */
122
+ const state = () => (term ? { name: term.name, ended } : null);
123
+ const tick = async () => {
124
+ const t = term;
125
+ if (!t)
126
+ return;
127
+ const screen = await grab(t);
128
+ if (term !== t)
129
+ return;
130
+ const next = screen === null ? [] : stripLines(screen);
131
+ const gone = screen === null;
132
+ if (gone !== ended) {
133
+ ended = gone;
134
+ d.send({ t: "term", term: state() });
135
+ }
136
+ if (JSON.stringify(next) !== JSON.stringify(lines)) {
137
+ lines = next;
138
+ d.send({ t: "term-line", lines });
139
+ }
140
+ };
141
+ const polling = () => {
142
+ clearInterval(poll);
143
+ poll = undefined;
144
+ if (!term || !watchers)
145
+ return;
146
+ void tick();
147
+ poll = setInterval(() => void tick(), d.pollMs ?? 1_000);
148
+ poll.unref();
149
+ };
150
+ /** One open panel: `tmux attach` in a pty from its first size; closes with the socket. */
151
+ const accept = (ws) => {
152
+ const t = term;
153
+ if (!t) {
154
+ ws.close(4404, "no terminal");
155
+ return;
156
+ }
157
+ socks.add(ws);
158
+ let pty = null;
159
+ let starting = false;
160
+ let gone = false;
161
+ /** In tmux copy mode from a wheel: the next key leaves it first. */
162
+ let scrolled = false;
163
+ /** Keys and tmux commands, in order. */
164
+ let chain = Promise.resolve();
165
+ const later = (fn) => {
166
+ chain = chain.then(fn, fn);
167
+ };
168
+ const target = `=${t.name}:`;
169
+ const json = (m) => {
170
+ if (ws.readyState === ws.OPEN)
171
+ ws.send(JSON.stringify(m));
172
+ };
173
+ const start = async (cols, rows) => {
174
+ const spawn = await spawnPty();
175
+ // a gone session: attach would print tmux's error on the panel
176
+ const missing = await tmuxRun(t.tmux, ["has-session", "-t", `=${t.name}`]);
177
+ if (gone)
178
+ return;
179
+ if (missing) {
180
+ ws.close(4000, "ended");
181
+ return;
182
+ }
183
+ if (typeof spawn === "string") {
184
+ json({ t: "err", why: spawn });
185
+ ws.close(4500, "no pty");
186
+ return;
187
+ }
188
+ try {
189
+ pty = spawn(t.tmux, ["-u", "attach-session", "-t", `=${t.name}`], {
190
+ name: "xterm-256color",
191
+ cols,
192
+ rows,
193
+ cwd: process.env.HOME ?? "/",
194
+ env: ptyEnv(process.env),
195
+ });
196
+ }
197
+ catch (err) {
198
+ json({ t: "err", why: `tmux attach: ${err instanceof Error ? err.message : String(err)}` });
199
+ ws.close(4500, "no pty");
200
+ return;
201
+ }
202
+ const p = pty;
203
+ p.onData((s) => {
204
+ if (ws.readyState !== ws.OPEN)
205
+ return;
206
+ ws.send(Buffer.from(s, "utf8"));
207
+ if (ws.bufferedAmount <= BACKLOG)
208
+ return;
209
+ p.pause();
210
+ const wait = setInterval(() => {
211
+ if (gone || ws.bufferedAmount < BACKLOG / 4) {
212
+ clearInterval(wait);
213
+ if (!gone)
214
+ p.resume();
215
+ }
216
+ }, 50);
217
+ });
218
+ p.onExit(() => {
219
+ pty = null;
220
+ if (!gone)
221
+ ws.close(4000, "ended");
222
+ });
223
+ };
224
+ ws.on("message", (raw, binary) => {
225
+ if (binary)
226
+ return;
227
+ let m;
228
+ try {
229
+ m = JSON.parse(String(raw));
230
+ }
231
+ catch {
232
+ return;
233
+ }
234
+ if (m.t === "size") {
235
+ const cols = clamp(m.c, COLS);
236
+ const rows = clamp(m.r, ROWS);
237
+ if (pty)
238
+ pty.resize(cols, rows);
239
+ else if (!starting) {
240
+ starting = true;
241
+ later(() => start(cols, rows));
242
+ }
243
+ else
244
+ later(() => pty?.resize(cols, rows));
245
+ }
246
+ else if (m.t === "in" && typeof m.d === "string" && m.d) {
247
+ const data = m.d;
248
+ later(async () => {
249
+ if (scrolled) {
250
+ scrolled = false;
251
+ await tmuxRun(t.tmux, ["send-keys", "-t", target, "-X", "cancel"]);
252
+ }
253
+ pty?.write(data);
254
+ });
255
+ }
256
+ else if (m.t === "scroll" && typeof m.n === "number" && m.n) {
257
+ const n = String(Math.min(200, Math.abs(Math.round(m.n))) || 1);
258
+ // up: into copy mode (-e: back out at the bottom); down: only inside it
259
+ if (m.n < 0) {
260
+ scrolled = true;
261
+ later(() => tmuxRun(t.tmux, [
262
+ "copy-mode",
263
+ "-e",
264
+ "-t",
265
+ target,
266
+ ";",
267
+ "send-keys",
268
+ "-t",
269
+ target,
270
+ "-X",
271
+ "-N",
272
+ n,
273
+ "scroll-up",
274
+ ]));
275
+ }
276
+ else if (scrolled)
277
+ later(() => tmuxRun(t.tmux, ["send-keys", "-t", target, "-X", "-N", n, "scroll-down"]));
278
+ }
279
+ });
280
+ ws.on("close", () => {
281
+ gone = true;
282
+ socks.delete(ws);
283
+ try {
284
+ pty?.kill();
285
+ }
286
+ catch {
287
+ // gone already
288
+ }
289
+ pty = null;
290
+ // copy mode outlives the client: Ghostty or the next panel would open in it
291
+ if (scrolled)
292
+ later(() => tmuxRun(t.tmux, ["send-keys", "-t", target, "-X", "cancel"]));
293
+ });
294
+ };
295
+ return {
296
+ /** For `hello`: the terminal, its strip. */
297
+ hello: () => ({ term: state(), termLines: lines }),
298
+ /** Sets the session's terminal; null closes every panel. */
299
+ set(next) {
300
+ if (next?.name === term?.name && next?.tmux === term?.tmux)
301
+ return;
302
+ term = next;
303
+ lines = [];
304
+ ended = false;
305
+ for (const ws of socks)
306
+ ws.close(4000, "ended");
307
+ d.send({ t: "term", term: state() });
308
+ d.send({ t: "term-line", lines });
309
+ polling();
310
+ },
311
+ /** Viewer count: the strip polls only while one looks. */
312
+ watchers(n) {
313
+ const was = watchers > 0;
314
+ watchers = n;
315
+ if (was !== n > 0)
316
+ polling();
317
+ },
318
+ accept,
319
+ /** The panel's copy: the app's clipboard. */
320
+ copy(text) {
321
+ if (term && typeof text === "string" && text)
322
+ d.clip(text.slice(0, 1_000_000));
323
+ },
324
+ /** Open in Ghostty: no pty needed, so it works from a failed panel too. */
325
+ async ghostty() {
326
+ if (!term)
327
+ return { ok: false, why: "no terminal" };
328
+ const why = await tmuxRun("/usr/bin/open", ghosttyArgv(term));
329
+ if (why)
330
+ d.log(`open in Ghostty: ${why}`);
331
+ return why ? { ok: false, why } : { ok: true };
332
+ },
333
+ close() {
334
+ term = null;
335
+ clearInterval(poll);
336
+ for (const ws of socks)
337
+ ws.close(4000, "ended");
338
+ },
339
+ };
340
+ }
341
+ //# sourceMappingURL=live-term.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-term.js","sourceRoot":"","sources":["../../src/browser/live-term.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAyB1C,IAAI,OAAO,GAAsC,IAAI,CAAC;A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AI,EAAE,OAAO,CAAC,CAAC;QAClD,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import type { BrowserContext, Page } from "playwright";
2
2
  import type { OverlayHost } from "../explore/overlay-host.js";
3
3
  import { type HubAdd, type HubKind, type HubOptions } from "./live-hub.js";
4
+ import { type LiveTerm } from "./live-term.js";
4
5
  import type { RunType } from "./run-type.js";
5
6
  export type LiveViewTheme = "dark" | "light" | "system";
6
7
  export interface LiveViewOptions {
@@ -99,6 +100,8 @@ export interface LiveView {
99
100
  geometry(page: Page): Promise<LiveGeometry | null>;
100
101
  /** The hub's Pause: true holds the agent, false lets it go, none flips it. */
101
102
  pause(held?: boolean): void;
103
+ /** The task's Claude session beside the page (`browser/live-term`); null takes it away. A watched run has none. */
104
+ terminal(t: LiveTerm | null): void;
102
105
  close(): Promise<void>;
103
106
  }
104
107
  export interface LiveGeometry {
@@ -15,6 +15,7 @@ import { addressSuggest, addressTarget } from "./address-suggest.js";
15
15
  import { askDialogsWith } from "./dialogs.js";
16
16
  import { paceOf, setPace } from "./human/index.js";
17
17
  import { hubJobOf, joinHub, } from "./live-hub.js";
18
+ import { liveTerms, termAsset } from "./live-term.js";
18
19
  import { tabFocusOf } from "./tab-focus.js";
19
20
  /** The isolated world the viewer's page script runs in: the page's own scripts never see it. */
20
21
  const WORLD = "autobrowse-live";
@@ -101,6 +102,8 @@ const INPUT = new Set([
101
102
  "window",
102
103
  "pause",
103
104
  "signin",
105
+ "term-copy",
106
+ "ghostty",
104
107
  ]);
105
108
  const byContext = new WeakMap();
106
109
  /** The live view on a context, if one runs. */
@@ -216,6 +219,8 @@ export async function startLiveView(context, opts) {
216
219
  };
217
220
  // --- the app -------------------------------------------------------------
218
221
  let host = null;
222
+ /** The Claude terminal: its state, the strip, a pty per open panel. */
223
+ const terms = liveTerms({ send, clip: (text) => host?.send({ t: "clip", text }), log });
219
224
  let hostDead = false;
220
225
  let starting = null;
221
226
  const picks = new Map();
@@ -968,6 +973,15 @@ export async function startLiveView(context, opts) {
968
973
  const t = tabOf(v);
969
974
  const page = t?.page;
970
975
  switch (m.t) {
976
+ case "term-copy":
977
+ terms.copy(m.text);
978
+ return;
979
+ case "ghostty":
980
+ void terms.ghostty().then((r) => {
981
+ if (from.readyState === from.OPEN)
982
+ from.send(JSON.stringify({ t: "ghostty", ...r }));
983
+ });
984
+ return;
971
985
  // a split pane: its own tab, the first one the front pane does not show
972
986
  case "own":
973
987
  v.own = true;
@@ -1267,10 +1281,19 @@ export async function startLiveView(context, opts) {
1267
1281
  res.end();
1268
1282
  return;
1269
1283
  }
1270
- res.setHeader("content-type", "text/html; charset=utf-8");
1271
1284
  res.setHeader("cache-control", "no-store");
1272
1285
  res.setHeader("referrer-policy", "no-referrer");
1273
- res.setHeader("content-security-policy", `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src ws://127.0.0.1:${port}; frame-src about:`);
1286
+ const path = new URL(req.url ?? "/", `http://127.0.0.1:${port}`).pathname;
1287
+ if (path.startsWith("/x/")) {
1288
+ const a = opts.readOnly ? null : termAsset(path);
1289
+ res.statusCode = a ? 200 : 404;
1290
+ if (a)
1291
+ res.setHeader("content-type", a.type);
1292
+ res.end(a?.body);
1293
+ return;
1294
+ }
1295
+ res.setHeader("content-type", "text/html; charset=utf-8");
1296
+ res.setHeader("content-security-policy", `default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src ws://127.0.0.1:${port}; frame-src about:`);
1274
1297
  res.end(viewerHtml);
1275
1298
  });
1276
1299
  let idleT;
@@ -1286,15 +1309,26 @@ export async function startLiveView(context, opts) {
1286
1309
  idleT.unref();
1287
1310
  };
1288
1311
  const wss = new WebSocketServer({ noServer: true, maxPayload: 4_000_000 });
1312
+ const termWss = new WebSocketServer({ noServer: true, maxPayload: 1_000_000 });
1289
1313
  server.on("upgrade", (req, socket, head) => {
1290
1314
  // a page in the person's own browser cannot connect: its Origin is not ours
1291
1315
  if (!allowed(req) || req.headers.origin !== `http://127.0.0.1:${port}`) {
1292
1316
  socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
1293
1317
  return;
1294
1318
  }
1319
+ // a panel's pty: a shell on the task's tmux; never a watched run's, never counted as a viewer
1320
+ if (new URL(req.url ?? "/", `http://127.0.0.1:${port}`).pathname === "/term") {
1321
+ if (opts.readOnly || closed) {
1322
+ socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");
1323
+ return;
1324
+ }
1325
+ termWss.handleUpgrade(req, socket, head, (ws) => terms.accept(ws));
1326
+ return;
1327
+ }
1295
1328
  wss.handleUpgrade(req, socket, head, (ws) => {
1296
1329
  const v = { ws, own: false, tab: null, tile: null, on: true };
1297
1330
  views.set(ws, v);
1331
+ terms.watchers(views.size);
1298
1332
  clearTimeout(idleT);
1299
1333
  ws.on("message", (d, binary) => {
1300
1334
  if (binary)
@@ -1308,6 +1342,7 @@ export async function startLiveView(context, opts) {
1308
1342
  });
1309
1343
  ws.on("close", () => {
1310
1344
  views.delete(ws);
1345
+ terms.watchers(views.size);
1311
1346
  syncViewed();
1312
1347
  void stream();
1313
1348
  if (!views.size)
@@ -1323,6 +1358,7 @@ export async function startLiveView(context, opts) {
1323
1358
  window: !!opts.onWindow && !opts.readOnly,
1324
1359
  readOnly: !!opts.readOnly,
1325
1360
  signing: signingAs,
1361
+ ...terms.hello(),
1326
1362
  }));
1327
1363
  if (ov.html) {
1328
1364
  ov.loaded = false;
@@ -1378,6 +1414,10 @@ export async function startLiveView(context, opts) {
1378
1414
  },
1379
1415
  overlayHost: () => overlayHost(),
1380
1416
  pause: (held) => hold(held),
1417
+ terminal(t) {
1418
+ if (!opts.readOnly && !closed)
1419
+ terms.set(t);
1420
+ },
1381
1421
  flow(f) {
1382
1422
  flowNow = f;
1383
1423
  hub();
@@ -1412,7 +1452,9 @@ export async function startLiveView(context, opts) {
1412
1452
  done(null);
1413
1453
  for (const v of views.values())
1414
1454
  v.ws.close();
1455
+ terms.close();
1415
1456
  wss.close();
1457
+ termWss.close();
1416
1458
  server.close();
1417
1459
  // moved with Bring back: the row ("In Chrome") stays until the next close
1418
1460
  if (!rowKept) {
@@ -1435,7 +1477,7 @@ const RUN_IDLE_MS = 30_000;
1435
1477
  * DPR; without --force-device-scale-factor frames come at 1x (measured 11-28).
1436
1478
  */
1437
1479
  async function paintScale(context, page, fallback) {
1438
- const s = await context.newCDPSession(page).catch(() => null);
1480
+ const s = await within(context.newCDPSession(page).catch(() => null), BUSY_MS);
1439
1481
  if (!s)
1440
1482
  return fallback;
1441
1483
  try {
@@ -1473,7 +1515,32 @@ export function watchRun(context, view, row, hubOpts = {}) {
1473
1515
  let lv = null;
1474
1516
  let opening = null;
1475
1517
  let closed = false;
1518
+ /**
1519
+ * The hub asked and no view is up yet. The ask holds: an open that brings no view tries again
1520
+ * on the run's own next page event (a page opens or loads), never on a timer, and never with a
1521
+ * call into the page. The view's `url` is the run's answer to the hub.
1522
+ */
1523
+ let wanted = false;
1524
+ let armed = false;
1525
+ const retry = () => void tryOpen();
1526
+ const arm = (on) => {
1527
+ if (armed === on)
1528
+ return;
1529
+ armed = on;
1530
+ if (on) {
1531
+ context.on("page", retry);
1532
+ for (const p of context.pages())
1533
+ p.on("load", retry);
1534
+ }
1535
+ else {
1536
+ context.off("page", retry);
1537
+ for (const p of context.pages())
1538
+ p.off("load", retry);
1539
+ }
1540
+ };
1476
1541
  const stop = async () => {
1542
+ wanted = false;
1543
+ arm(false);
1477
1544
  const v = lv;
1478
1545
  lv = null;
1479
1546
  await v?.close();
@@ -1486,8 +1553,11 @@ export function watchRun(context, view, row, hubOpts = {}) {
1486
1553
  const vp = main.viewportSize();
1487
1554
  const fixed = view.fixed ?? (vp ? { w: vp.width, h: vp.height } : null);
1488
1555
  // the run's size is the run's: a view with no fixed size would resize it
1489
- if (!fixed)
1556
+ if (!fixed) {
1557
+ // for good: no page event changes it
1558
+ wanted = false;
1490
1559
  return log(`${view.site}: a run with no viewport cannot be watched`);
1560
+ }
1491
1561
  const v = await startLiveView(context, {
1492
1562
  ...view,
1493
1563
  main,
@@ -1504,16 +1574,25 @@ export function watchRun(context, view, row, hubOpts = {}) {
1504
1574
  else
1505
1575
  lv = v;
1506
1576
  };
1577
+ function tryOpen() {
1578
+ if (!wanted || lv || opening || closed)
1579
+ return;
1580
+ opening = open()
1581
+ .catch((err) => log(`${view.site}: ${err.message}`))
1582
+ .finally(() => {
1583
+ opening = null;
1584
+ // no view: wait for the run's next page event
1585
+ arm(wanted && !lv && !closed);
1586
+ });
1587
+ }
1507
1588
  link.on((e) => {
1508
1589
  // the hub's speed: the run's hands read it, watched or not (WA-1503)
1509
1590
  if (e.t === "pace")
1510
1591
  setPace(context, typeof e.k === "number" ? e.k : null);
1511
- else if (e.t === "watch" && !lv && !opening && !closed)
1512
- opening = open()
1513
- .catch((err) => log(`${view.site}: ${err.message}`))
1514
- .finally(() => {
1515
- opening = null;
1516
- });
1592
+ else if (e.t === "watch") {
1593
+ wanted = true;
1594
+ tryOpen();
1595
+ }
1517
1596
  // the hub went away: its pane with it
1518
1597
  else if (e.t === "exit")
1519
1598
  void stop();
@@ -1521,7 +1600,9 @@ export function watchRun(context, view, row, hubOpts = {}) {
1521
1600
  return {
1522
1601
  async close() {
1523
1602
  closed = true;
1524
- await opening;
1603
+ arm(false);
1604
+ // an open in flight never holds the run's close; it closes its own view when it lands
1605
+ await within(opening ?? Promise.resolve(), BUSY_MS * 2);
1525
1606
  await stop();
1526
1607
  link.close();
1527
1608
  },