@omercnet/paseo-shared-browser 4.1.11 → 4.1.12

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.
@@ -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;
@@ -23,7 +23,7 @@ vi.mock("node:child_process", () => ({
23
23
  callback: (error: null, result: { stdout: string }) => void,
24
24
  ) => {
25
25
  exec.calls.push({ file, args, env: options.env });
26
- callback(null, { stdout: args.includes("--version") ? "0.42.0\n" : "{}\n" });
26
+ callback(null, { stdout: args.includes("--version") ? "0.43.0\n" : "{}\n" });
27
27
  },
28
28
  }));
29
29
 
@@ -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);
@@ -15,7 +15,7 @@ vi.mock("node:child_process", async (importOriginal) => ({
15
15
  _args: string[],
16
16
  _options: unknown,
17
17
  callback: (error: null, result: { stdout: string }) => void,
18
- ) => callback(null, { stdout: "0.42.0\n" }),
18
+ ) => callback(null, { stdout: "0.43.0\n" }),
19
19
  }));
20
20
 
21
21
  const temporary: string[] = [];
@@ -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++;
@@ -5,16 +5,18 @@ import { createServer, type Socket } from "node:net";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import type { ZodType } from "zod";
8
- import type { BrowserFrame, BrowserState } from "../shared/browser";
8
+ import type { BrowserFrame, BrowserState, BrowserVideoSettings } from "../shared/browser";
9
9
  import {
10
10
  beginBrowserGestureRpc,
11
11
  captureBrowserRpc,
12
12
  closeBrowserRpc,
13
13
  endBrowserGestureRpc,
14
+ keepAliveBrowserGestureRpc,
14
15
  MAX_BROWSER_TABS,
15
16
  navigateBrowserRpc,
16
17
  resizeBrowserRpc,
17
18
  sendBrowserInputRpc,
19
+ setBrowserVideoSettingsRpc,
18
20
  setCaptureDensityRpc,
19
21
  updateBrowserGestureRpc,
20
22
  } from "../shared/browser";
@@ -65,6 +67,12 @@ export interface RuntimeOwner<Runtime extends RuntimeInstance = RuntimeInstance>
65
67
  create(workspaceId: string): Promise<Runtime>;
66
68
  request(runtime: Runtime, operation: string, input: JsonValue): Promise<JsonValue>;
67
69
  stop(runtime: Runtime): Promise<void>;
70
+ /** Effective host-wide encoded-video launch option, read fresh on every call. */
71
+ videoSettings?(): Promise<BrowserVideoSettings>;
72
+ /** Persist the choice; it applies to runtimes created afterwards. */
73
+ setVideoEnabled?(enabled: boolean): Promise<void>;
74
+ /** Encoded-video option this runtime was launched with. */
75
+ videoLaunched?(runtime: Runtime): boolean;
68
76
  }
69
77
 
70
78
  export interface RuntimeSupervisorOptions<Runtime extends RuntimeInstance> {
@@ -406,6 +414,14 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
406
414
  throw new RuntimeProtocolError("RUNTIME_FAILURE", "Browser runtime was replaced");
407
415
  this.invalidateAgentObservations(workspaceId);
408
416
  this.revokeAgentControl(workspaceId);
417
+ // The runtime's viewers and targets die with it. Agents reattach to the next runtime's
418
+ // default page; advancing the revision rejects completions begun on the old tab.
419
+ for (const binding of this.agentBindings.values()) {
420
+ if (binding.workspaceId !== workspaceId) continue;
421
+ binding.viewerToken = null;
422
+ binding.tabId = null;
423
+ binding.selectionRevision++;
424
+ }
409
425
  await this.owner.stop(entry.runtime);
410
426
  if (this.workspaces.get(workspaceId) === entry) this.workspaces.delete(workspaceId);
411
427
  });
@@ -495,6 +511,11 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
495
511
  result = await this.browserPolicy.endGesture(endBrowserGestureRpc.input.parse(data));
496
512
  this.invalidateAgentObservationsForState(result);
497
513
  break;
514
+ case "gesture.keepalive":
515
+ result = await this.browserPolicy.keepAliveGesture(
516
+ keepAliveBrowserGestureRpc.input.parse(data),
517
+ );
518
+ break;
498
519
  case "list":
499
520
  result = { workspaceIds: await this.browserPolicy.listOpenWorkspaceIds() };
500
521
  break;
@@ -524,6 +545,25 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
524
545
  result = { archived: true };
525
546
  break;
526
547
  }
548
+ case "video.settings":
549
+ result = await this.videoSettings();
550
+ break;
551
+ case "video.set": {
552
+ const input = setBrowserVideoSettingsRpc.input.parse(data);
553
+ const setVideoEnabled = this.owner.setVideoEnabled?.bind(this.owner);
554
+ if (!setVideoEnabled)
555
+ throw new RuntimeProtocolError(
556
+ "INVALID_REQUEST",
557
+ "Encoded video settings are unavailable",
558
+ );
559
+ await this.browserPolicy.relaunchOpenBrowsers(
560
+ input.viewerToken,
561
+ () => setVideoEnabled(input.enabled),
562
+ () => this.staleVideoRuntimes(),
563
+ );
564
+ result = await this.videoSettings();
565
+ break;
566
+ }
527
567
  default:
528
568
  throw new RuntimeProtocolError(
529
569
  "INVALID_REQUEST",
@@ -534,6 +574,20 @@ export class RuntimeSupervisor<Runtime extends RuntimeInstance = RuntimeInstance
534
574
  return result as JsonValue;
535
575
  }
536
576
 
577
+ private async videoSettings(): Promise<BrowserVideoSettings> {
578
+ return (await this.owner.videoSettings?.()) ?? { enabled: false, forcedByHost: false };
579
+ }
580
+
581
+ /** Live runtimes launched with an encoded-video option that differs from the effective one. */
582
+ private async staleVideoRuntimes(): Promise<{ workspaceId: string; runtimeId: string }[]> {
583
+ const launched = this.owner.videoLaunched?.bind(this.owner);
584
+ if (!launched) return [];
585
+ const { enabled } = await this.videoSettings();
586
+ return [...this.workspaces]
587
+ .filter(([, entry]) => !entry.lost && launched(entry.runtime) !== enabled)
588
+ .map(([workspaceId, entry]) => ({ workspaceId, runtimeId: entry.runtime.runtimeId }));
589
+ }
590
+
537
591
  private issueAgentTicket(bridgeId: string, epoch: number, ticket: string): JsonValue {
538
592
  this.assertActiveBridge(bridgeId, epoch);
539
593
  this.expireUnboundTickets();