@omercnet/paseo-shared-browser 4.1.11-next.500.1 → 4.1.11-next.501.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.
@@ -172,6 +172,7 @@ function setup(retainDocumentDisplay = false) {
172
172
  let active = true;
173
173
  let bitrate: 2_000_000 | 5_000_000 | 12_000_000 | 24_000_000 = 12_000_000;
174
174
  let fps: 15 | 30 | 60 = 30;
175
+ let hostVideoEnabled: boolean | undefined;
175
176
  const environment: BrowserVideoDecodeEnvironment = {
176
177
  createDecoder(callbacks) {
177
178
  return {
@@ -211,6 +212,7 @@ function setup(retainDocumentDisplay = false) {
211
212
  active,
212
213
  bitrate,
213
214
  fps,
215
+ ...(hostVideoEnabled === undefined ? {} : { hostVideoEnabled }),
214
216
  epoch: () => mutationEpoch,
215
217
  viewport: () => ({ width: 1280, height: 800 }),
216
218
  // The mounted panel's real source predicate, fed a fake panel context, so a drift
@@ -276,6 +278,9 @@ function setup(retainDocumentDisplay = false) {
276
278
  active(value: boolean) {
277
279
  active = value;
278
280
  },
281
+ hostVideo(value: boolean) {
282
+ hostVideoEnabled = value;
283
+ },
279
284
  token(value: string) {
280
285
  viewerToken = value;
281
286
  },
@@ -602,6 +607,23 @@ describe("video presentation lifecycle", () => {
602
607
  await vi.advanceTimersByTimeAsync(10_000);
603
608
  expect(harness.reads).toHaveLength(1);
604
609
  });
610
+ it("resumes reading after the host turns video on, without a new viewer or reload", async () => {
611
+ const f = setup();
612
+ f.disabled(0);
613
+ await drain();
614
+ f.render();
615
+ f.commit();
616
+ await vi.advanceTimersByTimeAsync(10_000);
617
+ const stopped = harness.reads.length;
618
+ f.hostVideo(true);
619
+ f.render();
620
+ f.commit();
621
+ await drain();
622
+ expect(stopped).toBe(1);
623
+ expect(harness.reads).toHaveLength(2);
624
+ expect(harness.reads.at(-1)!.input.viewerToken).toBe(harness.reads[0]!.input.viewerToken);
625
+ expect(harness.disposals).toBeGreaterThanOrEqual(1);
626
+ });
605
627
  it("hidden/unmounted viewers cancel the capacity retry timer and cannot restart background reads", async () => {
606
628
  const f = setup();
607
629
  f.capacity(0);
@@ -30,6 +30,11 @@ interface BrowserVideoOptions {
30
30
  fps?: import("../shared/video-settings").VideoEncoderSettings["fps"];
31
31
  /** Explicit host panel suspension, when supplied. Unmount also stops decoding. */
32
32
  active?: boolean;
33
+ /**
34
+ * The host's effective encoded-video setting, when known. A change restarts reading,
35
+ * so turning video on resumes it after a "video-disabled" stop without a reload.
36
+ */
37
+ hostVideoEnabled?: boolean;
33
38
  epoch(): number;
34
39
  viewport(): Viewport | null;
35
40
  isCurrent(packet: BrowserVideoPacket, epoch: number): boolean;
@@ -454,7 +459,15 @@ export function useBrowserVideo(options: BrowserVideoOptions) {
454
459
  runningCleanup?.();
455
460
  runningCleanup = null;
456
461
  };
457
- }, [node, options.viewerToken, options.quality, options.active, options.bitrate, options.fps]);
462
+ }, [
463
+ node,
464
+ options.viewerToken,
465
+ options.quality,
466
+ options.active,
467
+ options.bitrate,
468
+ options.fps,
469
+ options.hostVideoEnabled,
470
+ ]);
458
471
 
459
472
  return {
460
473
  active,
package/index.server.ts CHANGED
@@ -15,6 +15,8 @@ import {
15
15
  handleCreateBrowserTab,
16
16
  handleDetachBrowser,
17
17
  handleEndBrowserGesture,
18
+ handleGetBrowserVideoSettings,
19
+ handleKeepAliveBrowserGesture,
18
20
  handleListBrowserTabs,
19
21
  handleListOpenBrowserWorkspaces,
20
22
  handleNavigateBrowser,
@@ -23,6 +25,7 @@ import {
23
25
  handleReopenBrowser,
24
26
  handleResizeBrowser,
25
27
  handleSendBrowserInput,
28
+ handleSetBrowserVideoSettings,
26
29
  handleSetCaptureDensity,
27
30
  handleUpdateBrowserGesture,
28
31
  handleWorkspaceArchived,
@@ -41,6 +44,8 @@ import {
41
44
  createBrowserTabRpc,
42
45
  detachBrowserRpc,
43
46
  endBrowserGestureRpc,
47
+ getBrowserVideoSettingsRpc,
48
+ keepAliveBrowserGestureRpc,
44
49
  listBrowserTabsRpc,
45
50
  listOpenBrowserWorkspacesRpc,
46
51
  navigateBrowserRpc,
@@ -48,6 +53,7 @@ import {
48
53
  reopenBrowserRpc,
49
54
  resizeBrowserRpc,
50
55
  sendBrowserInputRpc,
56
+ setBrowserVideoSettingsRpc,
51
57
  setCaptureDensityRpc,
52
58
  updateBrowserGestureRpc,
53
59
  } from "./shared/browser";
@@ -105,6 +111,9 @@ export default function contribute(server: PluginServerContext) {
105
111
  server.handle(beginBrowserGestureRpc, handleBeginBrowserGesture);
106
112
  server.handle(updateBrowserGestureRpc, handleUpdateBrowserGesture);
107
113
  server.handle(endBrowserGestureRpc, handleEndBrowserGesture);
114
+ server.handle(keepAliveBrowserGestureRpc, handleKeepAliveBrowserGesture);
115
+ server.handle(getBrowserVideoSettingsRpc, handleGetBrowserVideoSettings);
116
+ server.handle(setBrowserVideoSettingsRpc, handleSetBrowserVideoSettings);
108
117
  server.handle(navigateBrowserRpc, handleNavigateBrowser);
109
118
  server.handle(resizeBrowserRpc, handleResizeBrowser);
110
119
  server.handle(applyDevicePresetRpc, handleApplyDevicePreset);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-shared-browser",
3
- "version": "4.1.11-next.500.1",
3
+ "version": "4.1.11-next.501.1",
4
4
  "description": "One real Chromium session per Paseo workspace, shared live across every connected client.",
5
5
  "keywords": [
6
6
  "browser",
@@ -113,6 +113,16 @@ export class BrowserGesture {
113
113
  this.idleUntil = now + GESTURE_IDLE_MS;
114
114
  }
115
115
 
116
+ /** Physical input that a quiet client still holds; only this justifies a keep-alive. */
117
+ isHeld(): boolean {
118
+ return this.buttons.size > 0 || this.touches.size > 0 || this.keys.size > 0;
119
+ }
120
+
121
+ /** Extend only the idle bound; the absolute lifetime and sequence are unchanged. */
122
+ renew(now: number): void {
123
+ this.idleUntil = Math.min(now + GESTURE_IDLE_MS, this.expiresAt);
124
+ }
125
+
116
126
  /** Only an unpressed mouse move leaves existing bounded frame authority usable for a new press. */
117
127
  isHover(event: BrowserGestureEvent): boolean {
118
128
  return (event.kind === "move" || event.kind === "leave") && this.buttons.size === 0;
@@ -20,6 +20,7 @@ import {
20
20
  type DevicePresetId,
21
21
  type endBrowserGestureRpc,
22
22
  FRAME_MAX_BYTES,
23
+ type keepAliveBrowserGestureRpc,
23
24
  MAX_VIEWPORT,
24
25
  MIN_VIEWPORT,
25
26
  mapDisplayedPoint,
@@ -67,6 +68,7 @@ type UpdateGestureReply = Omit<RpcOutput<typeof updateBrowserGestureRpc>, "state
67
68
  state: BrowserState;
68
69
  };
69
70
  type EndGestureInput = RpcInput<typeof endBrowserGestureRpc>;
71
+ type KeepAliveGestureInput = RpcInput<typeof keepAliveBrowserGestureRpc>;
70
72
 
71
73
  const VIEWER_TTL_MS = 45_000;
72
74
  const CONTROL_LEASE_MS = 30_000;
@@ -233,6 +235,10 @@ export class SessionManager {
233
235
  private readonly closedViewerTabs = new Map<string, number>();
234
236
  private readonly sessionCreations = new Map<string, Promise<BrowserSession>>();
235
237
  private readonly sessionClosures = new Map<string, Promise<void>>();
238
+ /** Relaunches run one at a time so each reads stale runtimes after the previous one finished. */
239
+ private relaunchTail: Promise<void> = Promise.resolve();
240
+ /** Advances on every workspace teardown; a creation that overlaps one is never published. */
241
+ private readonly closureGenerations = new Map<string, number>();
236
242
  private readonly archived = new Set<string>();
237
243
  private readonly deliberatelyClosed = new Set<string>();
238
244
  private bridgeEpoch = 0;
@@ -472,34 +478,113 @@ export class SessionManager {
472
478
  throw new Error("Browser session is stale");
473
479
 
474
480
  this.deliberatelyClosed.add(session.workspaceId);
475
- const workspaceSessions = [...this.sessions.values()].filter(
476
- (candidate) => candidate.workspaceId === session.workspaceId,
477
- );
478
- for (const candidate of workspaceSessions) {
479
- candidate.videoLifetime?.cancel();
480
- await this.cancelGesture(candidate);
481
- candidate.archived = true;
482
- for (const token of candidate.viewers.keys()) {
483
- this.viewerSessions.delete(token);
484
- this.closedViewerWorkspaces.set(token, session.workspaceId);
485
- }
486
- candidate.viewers.clear();
487
- candidate.controller = null;
488
- }
489
- try {
490
- await this.client.closeWorkspace(session.workspaceId, session.runtimeId);
491
- } finally {
492
- for (const candidate of workspaceSessions) this.sessions.delete(candidate.key);
493
- }
481
+ await this.stopWorkspaceSessions(session, true);
494
482
  });
495
- this.sessionClosures.set(session.workspaceId, closing);
483
+ await this.awaitWorkspaceClosure(session.workspaceId, closing);
484
+ return { closed: true };
485
+ }
486
+
487
+ /**
488
+ * Tear down every page session of one workspace runtime. A deliberate close fences
489
+ * the old viewer tokens as closed; a relaunch leaves them simply invalid, so viewers
490
+ * reattach through the one-shot expired-viewer recovery.
491
+ */
492
+ private async stopWorkspaceSessions(session: BrowserSession, fenceViewers: boolean) {
493
+ const workspaceSessions = [...this.sessions.values()].filter(
494
+ (candidate) => candidate.workspaceId === session.workspaceId,
495
+ );
496
+ for (const candidate of workspaceSessions) {
497
+ candidate.videoLifetime?.cancel();
498
+ await this.cancelGesture(candidate);
499
+ candidate.archived = true;
500
+ for (const token of candidate.viewers.keys()) {
501
+ this.viewerSessions.delete(token);
502
+ if (fenceViewers) this.closedViewerWorkspaces.set(token, session.workspaceId);
503
+ }
504
+ candidate.viewers.clear();
505
+ candidate.controller = null;
506
+ }
507
+ try {
508
+ await this.client.closeWorkspace(session.workspaceId, session.runtimeId);
509
+ } finally {
510
+ for (const candidate of workspaceSessions) this.sessions.delete(candidate.key);
511
+ }
512
+ }
513
+
514
+ /** Attach and reopen wait for a pending closure before creating the next runtime. */
515
+ private async awaitWorkspaceClosure(workspaceId: string, closing: Promise<void>) {
516
+ this.closureGenerations.set(workspaceId, (this.closureGenerations.get(workspaceId) ?? 0) + 1);
517
+ this.sessionClosures.set(workspaceId, closing);
496
518
  try {
497
519
  await closing;
498
- return { closed: true };
499
520
  } finally {
500
- if (this.sessionClosures.get(session.workspaceId) === closing)
501
- this.sessionClosures.delete(session.workspaceId);
521
+ if (this.sessionClosures.get(workspaceId) === closing)
522
+ this.sessionClosures.delete(workspaceId);
523
+ }
524
+ }
525
+
526
+ /**
527
+ * Apply a host-wide launch option for a current viewer, then relaunch every running
528
+ * workspace runtime that was launched with a different value. `staleRuntimes` is read
529
+ * from the runtime registry, not from policy sessions, so a runtime whose earlier stop
530
+ * failed is still found and retried by the next call even when the setting is unchanged.
531
+ * Profiles persist and nothing is replayed; open pages restart at the launch page.
532
+ * A runtime that cannot be stopped is reported to the caller.
533
+ */
534
+ async relaunchOpenBrowsers(
535
+ viewerToken: string,
536
+ apply: () => Promise<void>,
537
+ staleRuntimes: () => Promise<{ workspaceId: string; runtimeId: string }[]>,
538
+ ): Promise<void> {
539
+ this.assertOpen();
540
+ this.requireViewer(viewerToken);
541
+ const lifecycleGeneration = this.lifecycleGeneration;
542
+ const run = this.relaunchTail.then(() =>
543
+ this.relaunchStale(lifecycleGeneration, apply, staleRuntimes),
544
+ );
545
+ this.relaunchTail = run.catch(() => undefined);
546
+ return run;
547
+ }
548
+
549
+ private async relaunchStale(
550
+ lifecycleGeneration: number,
551
+ apply: () => Promise<void>,
552
+ staleRuntimes: () => Promise<{ workspaceId: string; runtimeId: string }[]>,
553
+ ): Promise<void> {
554
+ // The viewer authorized this request when it was accepted. A reset or close while it
555
+ // waited behind another relaunch voids it; that relaunch itself may expire the viewer.
556
+ this.assertOpen();
557
+ if (lifecycleGeneration !== this.lifecycleGeneration)
558
+ throw new Error("Shared browser manager was reset");
559
+ await apply();
560
+ // A first attachment that started before the write may still launch with the old
561
+ // value. Let it register its runtime so the staleness check below can see it.
562
+ await Promise.allSettled([...this.sessionCreations.values()]);
563
+ let failed = false;
564
+ for (const { workspaceId, runtimeId } of await staleRuntimes()) {
565
+ const session = [...this.sessions.values()].find(
566
+ (candidate) =>
567
+ candidate.workspaceId === workspaceId &&
568
+ candidate.runtimeId === runtimeId &&
569
+ !candidate.archived,
570
+ );
571
+ const closing = session
572
+ ? this.serialize(session, () => this.stopWorkspaceSessions(session, false))
573
+ : this.client.closeWorkspace(workspaceId, runtimeId);
574
+ try {
575
+ await this.awaitWorkspaceClosure(workspaceId, closing);
576
+ } catch {
577
+ failed = true;
578
+ continue;
579
+ }
580
+ // Keep an open browser open for agents and other devices, as before the change.
581
+ // A failed replacement is reported; the next attachment can still create it.
582
+ if (session)
583
+ await this.getOrCreateSession(workspaceId).catch(() => {
584
+ failed = true;
585
+ });
502
586
  }
587
+ if (failed) throw new Error("Some browsers could not be restarted; try again");
503
588
  }
504
589
 
505
590
  /** Only an explicit human reopen removes the close fence used by viewer and agent attach. */
@@ -1181,9 +1266,38 @@ export class SessionManager {
1181
1266
  });
1182
1267
  }
1183
1268
 
1269
+ /**
1270
+ * Renew a quiet held channel's idle bound after the same identity, sequence and
1271
+ * attachment checks as an update. Dispatches no input and revokes no receipt. A
1272
+ * channel with nothing held must end instead, so the idle bound still reclaims it.
1273
+ */
1274
+ async keepAliveGesture(input: KeepAliveGestureInput) {
1275
+ const session = this.requireViewer(input.viewerToken);
1276
+ return this.serialize(session, async () => {
1277
+ const gesture = this.requireGesture(session, input);
1278
+ try {
1279
+ this.assertGesturePacketContext(gesture, input.expected);
1280
+ gesture.assertSequence(input.sequence, this.now());
1281
+ await this.assertGestureCurrent(session, gesture);
1282
+ // The awaited check can outlast either deadline; never revive an expired channel.
1283
+ const now = this.now();
1284
+ if (now >= gesture.idleUntil || now >= gesture.expiresAt)
1285
+ throw new Error("Browser gesture expired");
1286
+ if (!gesture.isHeld()) throw new Error("Browser gesture has no held input");
1287
+ gesture.renew(now);
1288
+ this.renewController(session, input.viewerToken);
1289
+ this.scheduleGestureTimeout(session, gesture);
1290
+ return { gestureId: gesture.id, nextSequence: gesture.nextSequence };
1291
+ } catch (error) {
1292
+ await this.cancelGesture(session, gesture);
1293
+ throw error;
1294
+ }
1295
+ });
1296
+ }
1297
+
1184
1298
  private requireGesture(
1185
1299
  session: BrowserSession,
1186
- input: UpdateGestureInput | EndGestureInput,
1300
+ input: UpdateGestureInput | EndGestureInput | KeepAliveGestureInput,
1187
1301
  ): BrowserGesture {
1188
1302
  const gesture = session.gesture;
1189
1303
  if (
@@ -1334,6 +1448,7 @@ export class SessionManager {
1334
1448
  if (this.sessions.size + this.sessionCreations.size >= this.maxSessions)
1335
1449
  throw new Error(`Shared browser session limit (${this.maxSessions}) reached`);
1336
1450
  const lifecycleGeneration = this.lifecycleGeneration;
1451
+ const closureGeneration = this.closureGenerations.get(workspaceId) ?? 0;
1337
1452
  const creation = this.createSession(workspaceId, key, tabId, replaceLost);
1338
1453
  this.sessionCreations.set(key, creation);
1339
1454
  try {
@@ -1344,14 +1459,20 @@ export class SessionManager {
1344
1459
  if (lifecycleGeneration !== this.lifecycleGeneration) {
1345
1460
  throw new Error("Shared browser manager was reset");
1346
1461
  }
1347
- this.sessions.set(key, session);
1348
- return session;
1462
+ // A teardown that began while this page was being created missed it in its
1463
+ // snapshot, so its runtime may already be stopped. Drop it (it holds no viewer
1464
+ // yet) and create again once that teardown has finished.
1465
+ if ((this.closureGenerations.get(workspaceId) ?? 0) === closureGeneration) {
1466
+ this.sessions.set(key, session);
1467
+ return session;
1468
+ }
1349
1469
  } catch (error) {
1350
1470
  if (this.archived.has(workspaceId)) throw new Error("Workspace was archived");
1351
1471
  throw error;
1352
1472
  } finally {
1353
1473
  if (this.sessionCreations.get(key) === creation) this.sessionCreations.delete(key);
1354
1474
  }
1475
+ return this.getOrCreateSession(workspaceId, tabId, replaceLost);
1355
1476
  }
1356
1477
 
1357
1478
  private async createSession(
package/server/browser.ts CHANGED
@@ -16,6 +16,8 @@ import type {
16
16
  createBrowserTabRpc,
17
17
  detachBrowserRpc,
18
18
  endBrowserGestureRpc,
19
+ getBrowserVideoSettingsRpc,
20
+ keepAliveBrowserGestureRpc,
19
21
  listBrowserTabsRpc,
20
22
  listOpenBrowserWorkspacesRpc,
21
23
  navigateBrowserRpc,
@@ -23,6 +25,7 @@ import type {
23
25
  reopenBrowserRpc,
24
26
  resizeBrowserRpc,
25
27
  sendBrowserInputRpc,
28
+ setBrowserVideoSettingsRpc,
26
29
  setCaptureDensityRpc,
27
30
  updateBrowserGestureRpc,
28
31
  } from "../shared/browser";
@@ -75,6 +78,10 @@ type UpdateGestureInput = RpcInput<typeof updateBrowserGestureRpc>;
75
78
  type UpdateGestureOutput = RpcOutput<typeof updateBrowserGestureRpc>;
76
79
  type EndGestureInput = RpcInput<typeof endBrowserGestureRpc>;
77
80
  type EndGestureOutput = RpcOutput<typeof endBrowserGestureRpc>;
81
+ type KeepAliveGestureInput = RpcInput<typeof keepAliveBrowserGestureRpc>;
82
+ type KeepAliveGestureOutput = RpcOutput<typeof keepAliveBrowserGestureRpc>;
83
+ type VideoSettingsOutput = RpcOutput<typeof getBrowserVideoSettingsRpc>;
84
+ type SetVideoSettingsInput = RpcInput<typeof setBrowserVideoSettingsRpc>;
78
85
 
79
86
  function paseoHome(): string {
80
87
  return process.env.PASEO_HOME ?? join(homedir(), ".paseo");
@@ -187,6 +194,18 @@ class RemoteBrowserManager {
187
194
  return this.requestBrowser("gesture.end", input as unknown as JsonValue);
188
195
  }
189
196
 
197
+ keepAliveGesture(input: KeepAliveGestureInput): Promise<KeepAliveGestureOutput> {
198
+ return this.requestBrowser("gesture.keepalive", input as unknown as JsonValue);
199
+ }
200
+
201
+ videoSettings(): Promise<VideoSettingsOutput> {
202
+ return this.requestBrowser("video.settings", {});
203
+ }
204
+
205
+ setVideoSettings(input: SetVideoSettingsInput): Promise<VideoSettingsOutput> {
206
+ return this.requestBrowser("video.set", input as unknown as JsonValue);
207
+ }
208
+
190
209
  async listOpenWorkspaceIds(): Promise<string[]> {
191
210
  const result = await this.requestBrowser("list", {});
192
211
  if (
@@ -421,6 +440,23 @@ export async function handleEndBrowserGesture(input: EndGestureInput): Promise<E
421
440
  return (await getProductionManager()).endGesture(input);
422
441
  }
423
442
 
443
+ export async function handleKeepAliveBrowserGesture(
444
+ input: KeepAliveGestureInput,
445
+ ): Promise<KeepAliveGestureOutput> {
446
+ return (await getProductionManager()).keepAliveGesture(input);
447
+ }
448
+
449
+ export async function handleGetBrowserVideoSettings(): Promise<VideoSettingsOutput> {
450
+ return (await getProductionManager()).videoSettings();
451
+ }
452
+
453
+ /** Host-wide: any current viewer may flip it, and open browsers relaunch to apply it. */
454
+ export async function handleSetBrowserVideoSettings(
455
+ input: SetVideoSettingsInput,
456
+ ): Promise<VideoSettingsOutput> {
457
+ return (await getProductionManager()).setVideoSettings(input);
458
+ }
459
+
424
460
  export async function cleanupBrowserServer(): Promise<void> {
425
461
  productionStopped = true;
426
462
  if (productionStart) await productionStart.catch(() => undefined);
@@ -111,6 +111,7 @@ async function fixture(
111
111
  },
112
112
  end: async (cancel = false, overrideSequence?: number) =>
113
113
  manager.endGesture({ ...context, gestureId, sequence: overrideSequence ?? sequence, cancel }),
114
+ keepAlive: async () => manager.keepAliveGesture({ ...context, gestureId, sequence }),
114
115
  changeUrl: (value: string) => {
115
116
  url = value;
116
117
  },
@@ -837,6 +838,76 @@ describe("owned ordered live input", () => {
837
838
  }
838
839
  });
839
840
 
841
+ it("keep-alive holds a motionless pressed drag past the idle bound without dispatching input", async () => {
842
+ vi.useFakeTimers();
843
+ const state = await fixture();
844
+ await state.begin();
845
+ await state.update({ kind: "down", button: "left", clickCount: 1, point: point() }, true);
846
+ const before = state.calls.length;
847
+ for (let elapsed = 0; elapsed < 12_000; elapsed += 2_000) {
848
+ await vi.advanceTimersByTimeAsync(2_000);
849
+ const reply = await state.keepAlive();
850
+ // The sequence is not consumed, so the release continues the same order.
851
+ expect(reply.nextSequence).toBe(2);
852
+ }
853
+ // Only the attachment check runs; nothing reaches the page and nothing is released.
854
+ expect(new Set(state.calls.slice(before).map((call) => call.operation))).toEqual(
855
+ new Set(["input.check"]),
856
+ );
857
+ await state.update({ kind: "up", button: "left", clickCount: 1, point: point(80, 60) });
858
+ await state.end();
859
+ expect(state.calls.filter((call) => call.operation === "mouse.up")).toHaveLength(1);
860
+ expect(state.calls.filter((call) => call.operation === "input.end")).toHaveLength(1);
861
+ state.manager.disconnect();
862
+ });
863
+
864
+ it("keep-alive refuses an idle channel with nothing held and closes it", async () => {
865
+ const state = await fixture();
866
+ await state.begin();
867
+ await state.update({ kind: "move", point: point() });
868
+ await expect(state.keepAlive()).rejects.toThrow("Browser gesture has no held input");
869
+ expect(state.calls.filter((call) => call.operation === "input.end")).toHaveLength(1);
870
+ await expect(state.keepAlive()).rejects.toThrow("Browser gesture is unavailable");
871
+ state.manager.disconnect();
872
+ });
873
+
874
+ it("keep-alive rechecks the idle deadline after its awaited attachment check", async () => {
875
+ let now = 1_000;
876
+ const state = await fixture({ now: () => now });
877
+ await state.begin();
878
+ await state.update({ kind: "down", button: "left", clickCount: 1, point: point() }, true);
879
+ now += 4_900;
880
+ // The idle bound passes while input.check is in flight.
881
+ state.intercept(async (operation) => {
882
+ if (operation === "input.check") now += 200;
883
+ });
884
+ await expect(state.keepAlive()).rejects.toThrow("Browser gesture expired");
885
+ expect(state.calls.filter((call) => call.operation === "input.end")).toHaveLength(1);
886
+ state.manager.disconnect();
887
+ });
888
+
889
+ it("keep-alive cannot extend a held gesture past its absolute lifetime", async () => {
890
+ vi.useFakeTimers();
891
+ const state = await fixture();
892
+ await state.begin();
893
+ await state.update({ kind: "down", button: "left", clickCount: 1, point: point() }, true);
894
+ let elapsed = 0;
895
+ let failure: unknown = null;
896
+ while (!failure && elapsed <= 6 * 60_000) {
897
+ await vi.advanceTimersByTimeAsync(4_000);
898
+ elapsed += 4_000;
899
+ failure = await state.keepAlive().then(
900
+ () => null,
901
+ (error: unknown) => error,
902
+ );
903
+ }
904
+ expect(elapsed).toBeGreaterThanOrEqual(5 * 60_000);
905
+ expect(elapsed).toBeLessThan(5 * 60_000 + 8_000);
906
+ expect(String(failure)).toMatch(/Browser gesture (expired|is unavailable)/);
907
+ expect(state.calls.filter((call) => call.operation === "input.end")).toHaveLength(1);
908
+ state.manager.disconnect();
909
+ });
910
+
840
911
  it("viewer or lease expiry releases the held gesture and rejects its late events", async () => {
841
912
  for (const expiry of ["lease", "viewer"] as const) {
842
913
  let now = 1_000;
@@ -13,6 +13,7 @@ import { CdpUnknownOutcomeError } from "./cdp";
13
13
  import { resolveBrowserRuntimeRoot } from "./runtime-path";
14
14
  import type { JsonValue } from "./runtime-protocol";
15
15
  import type { RuntimeOwner } from "./supervisor";
16
+ import { readVideoSettings, writeVideoEnabled } from "./video-preference";
16
17
  import {
17
18
  createPrivateVirtualDisplay,
18
19
  PrivateDisplayError,
@@ -41,7 +42,11 @@ interface RuntimeOwnerOptions {
41
42
  * Explicit false overrides the environment.
42
43
  */
43
44
  virtualDisplay?: boolean;
44
- /** Encoded video is opt-in; defaults to PASEO_SHARED_BROWSER_VIDEO=1 in the daemon environment. */
45
+ /**
46
+ * Encoded video is opt-in. When omitted, each runtime creation reads the effective
47
+ * host setting: PASEO_SHARED_BROWSER_VIDEO=1 in this process's environment, or the
48
+ * persisted toggle. Image-only runtimes never load the capture extension.
49
+ */
45
50
  nativeVideo?: boolean;
46
51
  }
47
52
 
@@ -125,6 +130,9 @@ export async function createRuntimeOwner(
125
130
  process.env.PASEO_SHARED_BROWSER_CHROMIUM_EXECUTABLE ??
126
131
  join(runtimeRoot, "chromium", process.platform === "win32" ? "chrome.exe" : "chrome");
127
132
  return {
133
+ videoSettings: () => readVideoSettings(root),
134
+ setVideoEnabled: (enabled) => writeVideoEnabled(root, enabled),
135
+ videoLaunched: (owned) => owned.runtimeOptions.nativeVideo === true,
128
136
  async create(workspaceId) {
129
137
  const hash = createHash("sha256").update(workspaceId).digest("hex");
130
138
  // Explicit headed mode uses the caller's real display. An opted-in hidden Linux mode
@@ -157,7 +165,7 @@ export async function createRuntimeOwner(
157
165
  session: `ws-${hash.slice(0, 16)}`,
158
166
  initialUrl: options.initialUrl ?? DEFAULT_BROWSER_URL,
159
167
  headed: display ? true : (options.headed ?? false),
160
- nativeVideo: options.nativeVideo ?? process.env.PASEO_SHARED_BROWSER_VIDEO === "1",
168
+ nativeVideo: options.nativeVideo ?? (await readVideoSettings(root)).enabled,
161
169
  ...(display ? { launchEnvironment: display.launchEnvironment } : {}),
162
170
  };
163
171
  runtime = new AgentBrowserRuntime(runtimeOptions);
@@ -83,6 +83,7 @@ it("recovers a captured-before-wheel frame that decodes after invalidation witho
83
83
  transport: {
84
84
  begin: (input) => manager.beginGesture(input),
85
85
  end: (input) => manager.endGesture(input),
86
+ keepAlive: (input) => manager.keepAliveGesture(input),
86
87
  update: async (input) => {
87
88
  // A different capture is already issued before input; its slow decoder commits after the wheel reply.
88
89
  now++;