Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(browser): a person's hold follows the person, and ends when they leave (#3726)

Milind Soni60bfe50bf1c5
diff --git a/docs/verification/browser-live.md b/docs/verification/browser-live.md
index bb9882b999..2626298c86 100644
--- a/docs/verification/browser-live.md
+++ b/docs/verification/browser-live.md
@@ -38,7 +38,10 @@ UI and harness, then removes its temporary data; the server log remains.
A Cmd shortcut such as Cmd+C must not delay that. Keep **Type or paste
text…** open past 8 seconds: control stays yours until it closes. Press
**Take control**, then wait a minute: it stays yours until **Hand back**,
- which returns it at once. **Type a password or code…** shows a masked
+ which returns it at once. Leave it untouched for 5 minutes: control goes
+ back to the bot by itself, kept or not. Close the panel while you hold it:
+ the bot gets it back 2 minutes later, unless you open the panel again
+ first, on any device, which carries on with your hold. **Type a password or code…** shows a masked
field; its text reaches the selected page field and appears in no log,
response or other view.
Holding a mouse button or key down must never hand back. Reconnect the
@@ -51,9 +54,12 @@ UI and harness, then removes its temporary data; the server log remains.
switch to it (a clean browser), then back to Own browser. The previous page
remains. Rename a shared profile without changing its identity. Confirmed
deletion clears its bot references without deleting another profile's data.
-5. Open a second isolated browser tab on the preview. Interact in one; the
- other must not receive new page frames or accept input. Hand-back and
- disconnect must never release another viewer's control lease. Hide the app's
+5. Open the panel in a second window signed in as you, then take control in
+ the first: the second shows the page and says the bot is paused for you,
+ and its **Hand back** returns the browser at once. Interacting in the second
+ moves your hold there; the first takes no more input. Open it as a
+ different person (another member's session): that view gets no page frames
+ and no input, and its hand-back or disconnect never ends your hold. Hide the app's
window or tab while a panel only watches: its view must leave (the browser
stops streaming and may idle-close) and reconnect on its own when the app
shows again. A panel holding the browser keeps its view while hidden.
diff --git a/server/browser-live.test.ts b/server/browser-live.test.ts
index 855b1f5bb9..5d94682e7d 100644
--- a/server/browser-live.test.ts
+++ b/server/browser-live.test.ts
@@ -2,6 +2,7 @@ import { EventEmitter } from "node:events";
import type { ServerResponse } from "node:http";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BrowserRuntime } from "./browser-runtime.ts";
+import { HOLD_LIMITS } from "./browser/hold.ts";
import { BrowserActionFailedError, BrowserLive, browserRestartRefusal, browserStreamPort, normalizeBrowserLiveMessage, parseBrowserLiveAction } from "./browser-live.ts";
import type { Cdp, CdpListeners } from "./browser-sites.ts";
@@ -474,14 +475,15 @@ describe("authenticated browser viewer relay", () => {
])("refuses a batch with %s", (_name, events) => {
expect(() => parseBrowserLiveAction({ type: "input_batch", events })).toThrow("Invalid browser action.");
});
- it("requires a viewer-specific human lease and releases only its own control on disconnect", async () => {
- const a = await open(); const b = await open({ botId: "bot-b" });
+ it("requires the person's own human lease and releases only theirs on disconnect", async () => {
+ const a = await open(); const b = await open({ botId: "bot-b", owner: "admin-b" });
await expect(a.action({ type: "navigate", url: "https://example.com" })).rejects.toThrow("Browser control changed");
await a.action({ type: "take" });
await expect(b.action({ type: "take" })).rejects.toThrow("Another window or device controls this browser. Hand control back there");
await expect(b.action({ type: "back" })).rejects.toThrow("Another window or device controls this browser");
+ await b.action({ type: "release" });
b.socket.close();
- expect(held.get("profile-a")).toBe(a.res.id);
+ expect(held.get("profile-a")).toBe("admin-a");
await a.action({ type: "input_keyboard", eventType: "keyDown", key: "a", text: "a" });
expect(nativeInput.mock.calls[0]?.[0]).toBe("http://127.0.0.1:43210/api/command");
expect(nativeInput.mock.calls[0]?.[1]).toMatchObject({ method: "POST", redirect: "error", headers: { Origin: "http://127.0.0.1:43210" } });
@@ -490,8 +492,8 @@ describe("authenticated browser viewer relay", () => {
a.socket.close(); expect(held.has("profile-a")).toBe(false);
expect(execute).toHaveBeenCalledTimes(2); // No close command: logins/browser survive viewers.
});
- it("withholds login frames/tabs/URLs from other views, advances their upstream ACK and restores the newest frame on release", async () => {
- const a = await open(); const b = await open({ botId: "bot-b" });
+ it("withholds login frames/tabs/URLs from another person's views, advances their upstream ACK and restores the newest frame on release", async () => {
+ const a = await open(); const b = await open({ botId: "bot-b", owner: "admin-b" });
await a.action({ type: "take" });
a.socket.receive(frame); b.socket.receive(frame);
b.socket.receive({ type: "url", url: "https://private.example/login" });
@@ -532,7 +534,8 @@ describe("authenticated browser viewer relay", () => {
live.closeForBot("bot-a");
expect(a.res.writableEnded).toBe(true);
expect(b.res.writableEnded).toBe(false);
- expect(held.get("profile-a")).toBe(b.res.id);
+ expect(held.get("profile-a")).toBe("admin-a");
+ expect(b.res.events("control").at(-1)).toEqual({ held: true, owned: true, controlling: true });
});
it("sends a typed password to the page only: never logged, echoed or sent to another view", async () => {
const secret = "hunter2-correct-horse";
@@ -553,14 +556,14 @@ describe("authenticated browser viewer relay", () => {
const a = await open(); const b = await open({ botId: "bot-b" });
await a.action({ type: "take" });
live.handBack("profile-b");
- expect(held.get("profile-a")).toBe(a.res.id);
+ expect(held.get("profile-a")).toBe("admin-a");
live.handBack("profile-a");
expect(held.has("profile-a")).toBe(false);
expect(a.res.events("control").at(-1)).toEqual({ held: false, owned: false, controlling: false });
expect(b.res.events("control").at(-1)).toEqual({ held: false, owned: false, controlling: false });
expect(a.res.writableEnded).toBe(false);
await a.action({ type: "take" });
- expect(held.get("profile-a")).toBe(a.res.id);
+ expect(held.get("profile-a")).toBe("admin-a");
});
it("inserts pasted text literally and preserves modifier shortcuts via native acknowledged actions", async () => {
const a = await open(); await a.action({ type: "take" });
@@ -779,7 +782,7 @@ describe("authenticated browser viewer relay", () => {
it("shows the page's question to the view holding the browser, not to another, and its answer lets the input it held through", async () => {
const tools = devTools();
live = new BrowserLive({ runtime, devTools: { url: tools.url, connect: tools.connect } });
- const a = await open(); const b = await open({ botId: "bot-b" });
+ const a = await open(); const b = await open({ botId: "bot-b", owner: "admin-b" });
expect(tools.connect).toHaveBeenCalledOnce();
expect(tools.connect.mock.calls[0]![0]).toBe(URL);
expect(tools.sent[0]).toMatchObject({ method: "Target.setAutoAttach", params: { autoAttach: true, flatten: true } });
@@ -922,13 +925,13 @@ describe("authenticated browser viewer relay", () => {
});
it("does not clear uncertain input or other owners when native restart fails", async () => {
runtime = new BrowserRuntime(); live = new BrowserLive({ runtime });
- const a = await open(); const b = await open({ botId: "bot-b" });
+ const a = await open(); const b = await open({ botId: "bot-b", owner: "admin-b" });
await a.action({ type: "take" });
await expect(b.action({ type: "restart" })).rejects.toThrow("could not restart");
nativeClose.mockResolvedValueOnce(false);
await expect(a.action({ type: "restart" })).rejects.toThrow("could not restart");
- expect(runtime.heldBy("profile-a")).toBe(a.res.id);
- expect(runtime.canControl("profile-a", a.res.id)).toBe(false);
+ expect(runtime.heldBy("profile-a")).toBe("admin-a");
+ expect(runtime.canControl("profile-a", "admin-a")).toBe(false);
await expect(runtime.withAgentAction("profile-a", async () => true)).rejects.toThrow();
await a.action({ type: "restart" });
await expect(runtime.withAgentAction("profile-a", async () => true)).resolves.toBe(true);
@@ -956,6 +959,16 @@ describe("a person's view whose stream drops while they hold the browser", () =>
expect(runtime.interrupted("profile-a")).toBe(false);
});
+ it("gives the hold to the same person's next view, which can hand it back, though it never named the view that dropped", async () => {
+ const phone = await open(); await phone.action({ type: "take" });
+ // The phone leaves the browser, or the app is closed: its stream ends.
+ phone.res.destroy();
+ const reopened = await open();
+ expect(reopened.res.events("control").at(-1)).toEqual({ held: true, owned: true, controlling: true });
+ await reopened.action({ type: "release" });
+ await expect(botWorks()).resolves.toBe(true);
+ });
+
it("lets go of a key and button it held in the page instead of asking for a restart", async () => {
const a = await open(); await a.action({ type: "take" });
// Alt+Tab to another app: Alt went down here, its key-up never reached the server.
@@ -1031,16 +1044,18 @@ describe("a person's view whose stream drops while they hold the browser", () =>
await expect(botWorks()).resolves.toBe(true);
});
- it("gives the hold to no other view, and lets the same person take it back with an explicit take", async () => {
+ it("gives the hold to no other person, even one naming the view that dropped", async () => {
const a = await open(); await a.action({ type: "take" });
a.res.destroy();
const stranger = await open({ owner: "other", resume: a.res.id });
expect(stranger.res.events("control").at(-1)).toEqual({ held: true, owned: false, controlling: false });
await expect(stranger.action({ type: "take" })).rejects.toThrow("Another window or device controls this browser");
+ await expect(stranger.action({ type: "release" })).resolves.toEqual({ ok: true });
+ await expect(botWorks()).rejects.toThrow("paused while a person controls");
const reloaded = await open({ botId: "bot-a" });
- expect(reloaded.res.events("control").at(-1)).toEqual({ held: true, owned: false, controlling: false });
+ expect(reloaded.res.events("control").at(-1)).toEqual({ held: true, owned: true, controlling: true });
await expect(reloaded.action({ type: "take" })).resolves.toEqual({ ok: true, waited: false });
- expect(runtime.canControl("profile-a", reloaded.res.id)).toBe(true);
+ expect(runtime.canControl("profile-a", "admin-a")).toBe(true);
});
it("does not keep a hold for a view closed on purpose: a revoked owner, a deleted profile, a changed session", async () => {
@@ -1059,6 +1074,68 @@ describe("a person's view whose stream drops while they hold the browser", () =>
});
});
+describe("one person's hold, across their views and devices", () => {
+ const bodies = () => nativeInput.mock.calls.map(([, init]) => JSON.parse(init.body));
+ const botWorks = () => runtime.withAgentAction("profile-a", async () => true);
+ const control = (view: { res: ResponseFixture }) => view.res.events("control").at(-1);
+ beforeEach(() => { runtime = new BrowserRuntime(); live = new BrowserLive({ runtime }); });
+
+ it("lets their other view see the hold, take it over and hand it back while the first is still open", async () => {
+ const phone = await open(); await phone.action({ type: "take" });
+ const laptop = await open({ botId: "bot-b" });
+ expect(control(laptop)).toEqual({ held: true, owned: true, controlling: false });
+ await expect(laptop.action({ type: "input_keyboard", eventType: "char", text: "x" })).rejects.toThrow("Browser control changed");
+ expect(await laptop.action({ type: "take" })).toEqual({ ok: true, waited: false });
+ expect(control(laptop)).toEqual({ held: true, owned: true, controlling: true });
+ expect(control(phone)).toEqual({ held: true, owned: true, controlling: false });
+ await expect(phone.action({ type: "input_keyboard", eventType: "char", text: "y" })).rejects.toThrow("Browser control changed");
+ await expect(botWorks()).rejects.toThrow("paused while a person controls");
+ await phone.action({ type: "release" });
+ expect(runtime.heldBy("profile-a")).toBeNull();
+ expect(control(laptop)).toEqual({ held: false, owned: false, controlling: false });
+ await expect(botWorks()).resolves.toBe(true);
+ });
+
+ it("lets go of what the view it was taken from pressed before the new one types", async () => {
+ const phone = await open(); await phone.action({ type: "take" });
+ await phone.action({ type: "input_keyboard", eventType: "keyDown", key: "Shift", code: "ShiftLeft", modifiers: 8 });
+ const laptop = await open({ botId: "bot-b" });
+ nativeInput.mockClear();
+ await laptop.action({ type: "take" });
+ await laptop.action({ type: "input_keyboard", eventType: "char", text: "a" });
+ expect(bodies()).toEqual([
+ { action: "input_keyboard", type: "keyUp", key: "Shift", code: "ShiftLeft" },
+ { action: "keyboard", subaction: "insertText", text: "a" },
+ ]);
+ expect(runtime.interrupted("profile-a")).toBe(false);
+ });
+
+ it("ends a hold its person stopped using, kept or not, while every key they type keeps it", async () => {
+ vi.useFakeTimers();
+ // A view the person left open, whose stream the server never sees end.
+ const phone = await open(); await phone.action({ type: "take" });
+ await vi.advanceTimersByTimeAsync(HOLD_LIMITS.idleMs - 10_000);
+ await phone.action({ type: "input_keyboard", eventType: "char", text: "still typing" });
+ await vi.advanceTimersByTimeAsync(HOLD_LIMITS.idleMs - 10_000);
+ expect(runtime.heldBy("profile-a")).toBe("admin-a");
+ await expect(botWorks()).rejects.toThrow("paused while a person controls");
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(runtime.heldBy("profile-a")).toBeNull();
+ expect(control(phone)).toEqual({ held: false, owned: false, controlling: false });
+ await expect(botWorks()).resolves.toBe(true);
+ });
+
+ it("still refuses another person, from any view", async () => {
+ const phone = await open(); await phone.action({ type: "take" });
+ phone.res.destroy();
+ const someoneElse = await open({ owner: "admin-b" });
+ expect(control(someoneElse)).toEqual({ held: true, owned: false, controlling: false });
+ await expect(someoneElse.action({ type: "take" })).rejects.toThrow("Another window or device controls this browser");
+ await someoneElse.action({ type: "release" });
+ await expect(botWorks()).rejects.toThrow("paused while a person controls");
+ });
+});
+
describe("opening a view while the bot holds the browser", () => {
const busy = () => Object.assign(new Error("Command failed: agent-browser stream status --json --no-webmcp"), { killed: true, signal: "SIGKILL", code: null });
const start = () => {
@@ -1123,7 +1200,8 @@ describe("opening a view while the bot holds the browser", () => {
expect(res.events("control")).toHaveLength(0);
await vi.advanceTimersByTimeAsync(1_000);
await opening;
- expect(res.events("control").at(-1)).toMatchObject({ held: true, owned: false });
+ // The same person's other view has their hold: this one watches it, and may take it over or hand it back.
+ expect(res.events("control").at(-1)).toEqual({ held: true, owned: true, controlling: false });
});
it("stops waiting, and stops asking the browser, when the viewer leaves", async () => {
diff --git a/server/browser-live.ts b/server/browser-live.ts
index 76acdacbed..152aca1e3a 100644
--- a/server/browser-live.ts
+++ b/server/browser-live.ts
@@ -9,6 +9,7 @@ import { closeBrowserSession } from "./browser-engine.ts";
import { DialogWatch, localDevToolsUrl } from "./browser-dialogs.ts";
import type { Cdp, CdpListeners } from "./browser-sites.ts";
import { relay } from "./browser-relay.ts";
+import { HOLD_LIMITS, HoldClock, type HoldLimits } from "./browser/hold.ts";
import { BROWSER_HELD_ELSEWHERE } from "../shared/browser-held.ts";
const execute = promisify(execFile);
@@ -32,8 +33,6 @@ const FRAME_WINDOW = 2;
/** Inputs one request may carry, so a remote panel's typing does not wait a round trip per key. */
export const INPUT_BATCH_LIMIT = 64;
const ENDED_PROBE = { timeoutMs: 5_000, maxBytes: 65_536 };
-/** How long a person's hold outlives their view's dropped stream, for that panel to reconnect and carry on. */
-const RESUME_MS = 2 * 60_000;
/** What a view hears when its browser closed unused: it stops, where reconnecting would start the browser again. */
export const BROWSER_ASLEEP_ERROR = { type: "error", retryable: false, asleep: true, message: "This browser closed after it sat unused, to save memory. Reconnect to open it again." };
/** What a view hears while its browser cannot show it yet; it keeps waiting. */
@@ -252,16 +251,20 @@ interface OpenOptions {
botId: string;
session: string;
spec: { command: string; args?: readonly string[]; env?: NodeJS.ProcessEnv };
+ /** The session the view was opened with, or local-owner. */
owner: string;
+ /** The person watching: whose hold this view shares. Their account's key; the owner when there is none. */
+ person?: string;
isCurrent: () => boolean;
res: ServerResponse;
- /** The id of the view this panel had before its stream dropped: the one view that may carry on with its hold. */
+ /** The id of the view this panel had before its stream dropped: that view, if the server still has it open, is replaced. */
resume?: string | null;
/** The panel's size in CSS pixels, which the page fills from the start. */
size?: PageSize | null;
}
interface Viewer extends OpenOptions {
id: string;
+ person: string;
socket?: WebSocket;
closed: boolean;
blocked: boolean;
@@ -288,10 +291,10 @@ interface Viewer extends OpenOptions {
/** The panel size this view asked for last, and when, among all views. */
requested?: PageSize & { order: number };
}
-/** A person's hold whose view's stream dropped. Agents stay paused until that panel reconnects, the person hands back, or it expires. */
-interface Parked {
+/** The view a person's hold was used from, gone with its stream dropped. Its late hand-back still counts, and the view of
+ * theirs that carries on with the hold waits until what it pressed is let go. */
+interface Left {
viewer: Viewer;
- timer?: NodeJS.Timeout;
/** Resolves once its in-flight input finished and the keys and buttons it held are let go. */
settled: Promise<void>;
done: boolean;
@@ -307,15 +310,20 @@ export interface BrowserLiveDevTools {
export class BrowserLive {
private readonly runtime: BrowserRuntime;
private readonly viewers = new Map<string, Viewer>();
- private readonly parked = new Map<string, Parked>();
+ /** By browser session: the person's view their hold is used from. Their other views watch it; any may take it over. */
+ private readonly drivers = new Map<string, string>();
+ private readonly left = new Map<string, Left>();
+ private readonly clocks = new Map<string, HoldClock>();
+ private readonly holdLimits: HoldLimits;
private readonly sessionResets = new Map<string, Promise<boolean>>();
/** Each watched browser's page dialogs, and the views that watch them. */
private readonly dialogs = new Map<string, { watch: DialogWatch; views: Set<string> }>();
private readonly devTools?: BrowserLiveDevTools;
private order = 0;
- constructor({ runtime, devTools }: { runtime: BrowserRuntime; devTools?: BrowserLiveDevTools }) {
+ constructor({ runtime, devTools, holdLimits = HOLD_LIMITS }: { runtime: BrowserRuntime; devTools?: BrowserLiveDevTools; holdLimits?: HoldLimits }) {
this.runtime = runtime;
this.devTools = devTools;
+ this.holdLimits = holdLimits;
runtime.onIdleClose((session) => this.asleep(session));
}
@@ -346,23 +354,27 @@ export class BrowserLive {
}
}
+ /** Every view hears who holds the browser: `owned` when its person does, from this view or another of theirs, and
+ * `controlling` when it is the view their hold is used from and their input runs now. */
private control(session: string): void {
+ const holder = this.runtime.heldBy(session) ?? null;
+ // A hold that ended, whichever way, leaves nothing behind for the next one.
+ if (holder === null) this.forgetHold(session);
for (const viewer of this.viewers.values()) {
if (viewer.session !== session) continue;
- const held = Boolean(this.runtime.heldBy(session));
- if (held && this.runtime.heldBy(session) !== viewer.id && (viewer.frameSeq || viewer.unacked.size)) {
+ const hidden = holder !== null && holder !== viewer.person;
+ if (hidden && (viewer.frameSeq || viewer.unacked.size)) {
viewer.unacked.clear();
try { this.release(viewer); } catch { this.close(viewer); continue; }
}
- if (held && this.runtime.heldBy(session) !== viewer.id && viewer.pendingFrame) {
+ if (hidden && viewer.pendingFrame) {
const pending = viewer.pendingFrame; viewer.pendingFrame = undefined;
this.frame(viewer, pending);
}
- const owned = this.runtime.heldBy(session) === viewer.id;
- // Like its frames, the page's question is withheld from views while another view holds the browser.
- const dialog = !held || owned ? this.dialogs.get(session)?.watch.dialog ?? null : null;
- this.send(viewer, { type: "control", held, owned, controlling: this.runtime.canControl(session, viewer.id), ...(dialog ? { dialog } : {}) });
- if (!held && viewer.hiddenFrame) {
+ // Like its frames, the page's question is withheld from views while another person holds the browser.
+ const dialog = hidden ? null : this.dialogs.get(session)?.watch.dialog ?? null;
+ this.send(viewer, { type: "control", held: holder !== null, owned: holder !== null && !hidden, controlling: this.controlling(viewer), ...(dialog ? { dialog } : {}) });
+ if (!hidden && viewer.hiddenFrame) {
const frame = viewer.hiddenFrame; viewer.hiddenFrame = undefined;
this.frame(viewer, frame);
}
@@ -372,7 +384,7 @@ export class BrowserLive {
private frame(viewer: Viewer, frame: ObjectValue): void {
if (!this.current(viewer)) { this.close(viewer, true, true); return; }
const holder = this.runtime.heldBy(viewer.session);
- if (holder && holder !== viewer.id) {
+ if (holder && holder !== viewer.person) {
viewer.hiddenFrame = frame;
try { this.sendSocket(viewer, { type: "ack", seq: frame.seq }); } catch { this.close(viewer); }
return;
@@ -423,13 +435,7 @@ export class BrowserLive {
viewer.socket?.close();
viewer.hiddenFrame = undefined; viewer.pendingFrame = undefined; viewer.unacked.clear();
this.unwatchDialogs(viewer);
- if (!viewer.restarting) {
- if (dropped && this.holds(viewer)) this.park(viewer);
- else {
- this.abandonPressedInput(viewer);
- this.runtime.release(viewer.session, viewer.id);
- }
- }
+ if (!viewer.restarting) this.leave(viewer, dropped);
if (endResponse && !viewer.res.writableEnded && !viewer.res.destroyed) {
if (viewer.blocked || viewer.res.writableLength > MAX_BUFFER) viewer.res.destroy();
else viewer.res.end();
@@ -444,24 +450,89 @@ export class BrowserLive {
void this.runtime.pageSizes.resize(session, latest ? { width: latest.width, height: latest.height } : null, fresh).catch(() => undefined);
}
- /** It holds the browser and is still this person's view of this bot's session (not signed out or switched away). */
- private holds(viewer: Viewer): boolean {
- try { return this.runtime.heldBy(viewer.session) === viewer.id && viewer.isCurrent(); } catch { return false; }
+ /** Its person holds the browser, from this view or another of theirs. */
+ private ownedBy(viewer: Viewer): boolean {
+ return this.runtime.heldBy(viewer.session) === viewer.person;
+ }
+
+ /** It is the view its person's hold is used from, and their input runs now. */
+ private controlling(viewer: Viewer): boolean {
+ return this.drivers.get(viewer.session) === viewer.id && this.runtime.canControl(viewer.session, viewer.person);
+ }
+
+ private viewsOf(session: string, person: string): Viewer[] {
+ return [...this.viewers.values()].filter((viewer) => viewer.session === session && viewer.person === person);
+ }
+
+ private clock(session: string): HoldClock {
+ let clock = this.clocks.get(session);
+ if (!clock) {
+ clock = new HoldClock(() => {
+ const person = this.runtime.heldBy(session);
+ if (person) this.end(session, person);
+ }, this.holdLimits);
+ this.clocks.set(session, clock);
+ }
+ return clock;
}
- private park(viewer: Viewer): void {
- const stale = this.parked.get(viewer.session);
- if (stale) this.forget(stale);
+ /**
+ * A view of the person holding the browser went. What it pressed is let go once its input on the way has run. If its
+ * stream dropped while it was still theirs, the hold carries on in their other views, or waits the grace for their next
+ * one. A view closed on purpose, or no longer theirs (signed out, switched away), ends a hold no view of theirs has.
+ */
+ private leave(viewer: Viewer, dropped: boolean): void {
+ const session = viewer.session;
+ const used = this.drivers.get(session) === viewer.id;
+ if (used) this.drivers.delete(session);
+ if (!this.ownedBy(viewer)) return;
+ const open = this.viewsOf(session, viewer.person).length > 0;
+ let theirs = false;
+ try { theirs = dropped && viewer.isCurrent(); } catch {}
+ if (!theirs) {
+ this.abandonPressedInput(viewer);
+ if (!open) this.end(session, viewer.person);
+ return;
+ }
let finish!: () => void;
- const parked: Parked = { viewer, settled: new Promise<void>((resolve) => { finish = resolve; }), done: false };
- parked.timer = setTimeout(() => this.releaseParked(parked), RESUME_MS);
- parked.timer.unref?.();
- this.parked.set(viewer.session, parked);
+ const left: Left = { viewer, settled: new Promise<void>((resolve) => { finish = resolve; }), done: false };
+ if (used) this.left.set(session, left);
viewer.idle = () => {
viewer.idle = undefined;
- void this.releaseHeld(viewer).finally(() => { parked.done = true; finish(); });
+ void this.releaseHeld(viewer).finally(() => { left.done = true; finish(); });
};
if (viewer.pendingActions === 0) viewer.idle();
+ this.clock(session).watched(open);
+ }
+
+ /** The person's hold ends as a hand-back does, once what their view that dropped pressed is let go. */
+ private end(session: string, person: string): void {
+ const left = this.left.get(session);
+ const finish = () => {
+ if (this.runtime.heldBy(session) !== person) return;
+ for (const viewer of this.viewsOf(session, person)) this.abandonPressedInput(viewer);
+ this.runtime.release(session, person);
+ this.control(session);
+ };
+ if (left && !left.done) void left.settled.then(finish); else finish();
+ }
+
+ private forgetHold(session: string): void {
+ this.drivers.delete(session);
+ this.left.delete(session);
+ this.clocks.get(session)?.stop();
+ }
+
+ /** Its person holds the browser and none of their views uses it: this one carries on with their hold, but never before
+ * what the view they used pressed is let go, nor replays that view's input. */
+ private async carryOn(viewer: Viewer): Promise<void> {
+ const session = viewer.session;
+ const free = () => this.ownedBy(viewer) && !this.viewers.has(this.drivers.get(session) ?? "");
+ if (!free()) return;
+ await this.left.get(session)?.settled;
+ if (!this.current(viewer) || !free()) return;
+ this.drivers.set(session, viewer.id);
+ this.left.delete(session);
}
/** Lets go in the page of keys and buttons a dropped view still held, as the panel does when its window loses focus.
@@ -469,8 +540,8 @@ export class BrowserLive {
private async releaseHeld(viewer: Viewer): Promise<void> {
if (!viewer.pressedKeys.size && !viewer.pressedButtons.size) return;
const port = viewer.port;
- if (!port || !this.runtime.canControl(viewer.session, viewer.id)) { this.abandonPressedInput(viewer); return; }
- await this.runtime.withHumanAction(viewer.session, viewer.id, async () => {
+ if (!port || !this.runtime.canControl(viewer.session, viewer.person)) { this.abandonPressedInput(viewer); return; }
+ await this.runtime.withHumanAction(viewer.session, viewer.person, async () => {
const unconfirmed = () => new BrowserInputUnconfirmedError();
for (const [code, key] of viewer.pressedKeys) {
if (!await this.sendInput(viewer, port, { action: "input_keyboard", type: "keyUp", key, ...(code === key ? {} : { code }) }, true)) throw unconfirmed();
@@ -484,39 +555,9 @@ export class BrowserLive {
}).catch(() => undefined);
}
- private forget(parked: Parked): void {
- clearTimeout(parked.timer);
- if (this.parked.get(parked.viewer.session) === parked) this.parked.delete(parked.viewer.session);
- }
-
- /** The person's dropped hold ends, as a hand-back does, once what its view held is let go. */
- private releaseParked(parked: Parked): void {
- const release = () => {
- if (this.parked.get(parked.viewer.session) !== parked) return;
- this.forget(parked);
- this.runtime.release(parked.viewer.session, parked.viewer.id);
- this.control(parked.viewer.session);
- };
- if (parked.done) release(); else void parked.settled.then(release);
- }
-
- /** A dropped hold of this person in this bot's panel. */
- private parkedFor(viewer: Viewer): Parked | undefined {
- const parked = this.parked.get(viewer.session);
- return parked && parked.viewer.owner === viewer.owner && parked.viewer.botId === viewer.botId ? parked : undefined;
- }
-
- /** Moves a dropped hold to the same person's new view; never replays the old view's input. */
- private async claim(viewer: Viewer, parked: Parked): Promise<void> {
- await parked.settled;
- if (this.parked.get(viewer.session) !== parked || !this.current(viewer)) return;
- this.forget(parked);
- this.runtime.transfer(viewer.session, parked.viewer.id, viewer.id);
- }
-
private abandonPressedInput(viewer: Viewer): void {
// A disconnect may lose the matching key-up/mouse-up; an agent must never inherit held input.
- if (viewer.pressedKeys.size || viewer.pressedButtons.size) this.runtime.abandonHumanInput(viewer.session, viewer.id);
+ if (viewer.pressedKeys.size || viewer.pressedButtons.size) this.runtime.abandonHumanInput(viewer.session, viewer.person);
}
private async command(viewer: Viewer, args: string[], timeout = COMMAND_TIMEOUT_MS, person = false): Promise<ObjectValue> {
@@ -713,7 +754,7 @@ export class BrowserLive {
if (viewer.restarting) return false;
viewer.restarting = true;
try {
- await this.runtime.restart(viewer.session, viewer.id, async () => {
+ await this.runtime.restart(viewer.session, viewer.person, async () => {
const env = browserRuntimeEnv({ ...viewer.spec.env, AGENT_BROWSER_SESSION: viewer.session });
if (!await closeBrowserSession(viewer.spec.command, env)) throw new Error("browser close failed");
});
@@ -722,7 +763,7 @@ export class BrowserLive {
this.closeForSession(viewer.session);
return true;
} catch { return false; }
- finally { viewer.restarting = false; if (viewer.closed) this.runtime.release(viewer.session, viewer.id); this.control(viewer.session); }
+ finally { viewer.restarting = false; if (viewer.closed) this.runtime.release(viewer.session, viewer.person); this.control(viewer.session); }
}
/** The daemon runs one command per session at a time, so an answer to a read sent after an unanswered command proves it ended. */
@@ -731,23 +772,26 @@ export class BrowserLive {
}
async open(options: OpenOptions): Promise<void> {
+ // The view this panel had before its stream dropped, if the server still has it open, never comes back.
+ const replaced = options.resume ? this.viewers.get(options.resume) : undefined;
+ if (replaced && replaced.owner === options.owner && replaced.botId === options.botId) this.close(replaced, true, true);
if (this.viewers.size >= 8 || [...this.viewers.values()].filter((v) => v.session === options.session).length >= 2) {
throw new BrowserLiveError("Too many browser views are open. Close another browser panel first.", 429);
}
- const viewer: Viewer = { ...options, id: randomUUID(), closed: false, blocked: false, pendingActions: 0, restarting: false, pressedKeys: new Map(), pressedButtons: new Set(), pointer: { x: 0, y: 0 }, unacked: new Map(), waiting: false, abort: new AbortController(), unwatch: () => {} };
+ const viewer: Viewer = { ...options, id: randomUUID(), person: options.person ?? options.owner, closed: false, blocked: false, pendingActions: 0, restarting: false, pressedKeys: new Map(), pressedButtons: new Set(), pointer: { x: 0, y: 0 }, unacked: new Map(), waiting: false, abort: new AbortController(), unwatch: () => {} };
if (!this.current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);
// A view that opens while another holds the browser leaves the holder's page as it is.
if (options.size && !this.runtime.heldBy(options.session)) viewer.requested = { ...options.size, order: ++this.order };
viewer.unwatch = this.runtime.watch(viewer.session, viewer.spec);
this.viewers.set(viewer.id, viewer);
+ if (this.ownedBy(viewer)) this.clock(viewer.session).watched(true);
options.res.once("close", () => this.close(viewer, true, true));
options.res.once("error", () => this.close(viewer, true, true));
try {
const port = await this.connectWhenFree(viewer);
if (!this.current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);
- // Before its frames flow: the person's own panel, reconnecting after its stream dropped, still holds the browser.
- const parked = this.parkedFor(viewer);
- if (parked && viewer.resume === parked.viewer.id) await this.claim(viewer, parked);
+ // Before its frames flow: the person's next view carries on with their hold, after a dropped stream or a reopened app.
+ await this.carryOn(viewer);
if (!this.current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);
viewer.port = port;
this.fit(viewer.session, true);
@@ -767,7 +811,7 @@ export class BrowserLive {
try { raw = object(JSON.parse(event.data)); message = normalizeBrowserLiveMessage(raw); } catch { this.close(viewer); return; }
if (!message) { if (raw?.type === "frame") this.close(viewer); return; }
const heldBy = this.runtime.heldBy(viewer.session);
- if (heldBy && heldBy !== viewer.id && ["tabs", "url"].includes(String(message.type))) return;
+ if (heldBy && heldBy !== viewer.person && ["tabs", "url"].includes(String(message.type))) return;
if (message.type === "frame") this.frame(viewer, message);
else this.send(viewer, message);
});
@@ -808,22 +852,19 @@ export class BrowserLive {
if (!viewer || viewer.botId !== botId || viewer.owner !== owner || !this.current(viewer)) {
if (viewer && viewer.botId === botId && viewer.owner === owner) this.close(viewer, true, true);
// A hand-back sent as its own stream dropped still hands back.
- const parked = [...this.parked.values()].find((entry) => entry.viewer.id === viewerId);
- if (parked && parked.viewer.botId === botId && parked.viewer.owner === owner && object(body)?.type === "release") {
- this.releaseParked(parked);
+ const left = [...this.left.values()].find((entry) => entry.viewer.id === viewerId);
+ if (left && left.viewer.botId === botId && left.viewer.owner === owner && object(body)?.type === "release") {
+ this.end(left.viewer.session, left.viewer.person);
return { ok: true };
}
throw new BrowserLiveError("This browser view is no longer available. Reopen the browser panel.", 404);
}
const action = parseBrowserLiveAction(body);
- // An explicit take or restart by the same person in this bot's panel, after a reload lost the dropped view, carries on with its hold.
- const parked = action.type === "take" || action.type === "restart" ? this.parkedFor(viewer) : undefined;
- if (parked) await this.claim(viewer, parked);
if (action.type === "restart") {
if (viewer.restarting) throw new BrowserLiveError("The browser is already restarting.", 409);
viewer.restarting = true;
try {
- const restarting = this.runtime.restart(viewer.session, viewer.id, async () => {
+ const restarting = this.runtime.restart(viewer.session, viewer.person, async () => {
if (!this.current(viewer)) throw new Error("stale viewer");
const env = browserRuntimeEnv({ ...viewer.spec.env, AGENT_BROWSER_SESSION: viewer.session });
if (!await closeBrowserSession(viewer.spec.command, env)) throw new Error("browser close failed");
@@ -833,7 +874,7 @@ export class BrowserLive {
this.closeForSession(viewer.session);
return { ok: true };
} catch { throw new BrowserLiveError("The browser could not restart. Wait for active work to finish and try again.", 409); }
- finally { viewer.restarting = false; if (viewer.closed) this.runtime.release(viewer.session, viewer.id); this.control(viewer.session); }
+ finally { viewer.restarting = false; if (viewer.closed) this.runtime.release(viewer.session, viewer.person); this.control(viewer.session); }
}
if (action.type === "ack") {
this.rendered(viewer, action.seq);
@@ -841,29 +882,40 @@ export class BrowserLive {
}
if (action.type === "resize") {
const holder = this.runtime.heldBy(viewer.session);
- if (action.size && (!holder || holder === viewer.id)) {
+ if (action.size && (!holder || (holder === viewer.person && this.drivers.get(viewer.session) === viewer.id))) {
viewer.requested = { ...action.size, order: ++this.order };
this.fit(viewer.session);
}
return { ok: true };
}
+ // Any view of the person hands their hold back, whichever of their views it is used from.
if (action.type === "release") {
- this.abandonPressedInput(viewer);
- this.runtime.release(viewer.session, viewer.id); this.control(viewer.session);
+ this.end(viewer.session, viewer.person);
return { ok: true };
}
if (action.type === "take") {
try {
- const taking = this.runtime.take(viewer.session, viewer.id);
+ const taking = this.runtime.take(viewer.session, viewer.person);
this.control(viewer.session);
// The bot's own action finished first, so input aimed before the grant may no longer fit the page.
const waited = await taking;
+ // Taken over from another view of theirs: what that view pressed is let go first, and never replayed here.
+ const before = this.viewers.get(this.drivers.get(viewer.session) ?? "");
+ if (before && before !== viewer) await this.releaseHeld(before);
+ await this.left.get(viewer.session)?.settled;
if (!this.current(viewer)) { this.close(viewer, true, true); throw new BrowserLiveError("This browser view closed.", 409); }
+ if (this.ownedBy(viewer)) {
+ this.drivers.set(viewer.session, viewer.id);
+ this.left.delete(viewer.session);
+ this.clock(viewer.session).used();
+ this.clock(viewer.session).watched(true);
+ }
return { ok: true, waited: waited === true };
} catch { throw this.refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly."); }
finally { this.control(viewer.session); }
}
- if (!this.runtime.canControl(viewer.session, viewer.id)) throw this.refusal(viewer, "Browser control changed. Try again.");
+ if (!this.controlling(viewer)) throw this.refusal(viewer, "Browser control changed. Try again.");
+ this.clock(viewer.session).used();
if (action.type === "dialog") {
const watch = this.dialogs.get(viewer.session)?.watch;
if (!watch?.dialog) throw new BrowserLiveError("The page's question is no longer open.", 409);
@@ -874,7 +926,7 @@ export class BrowserLive {
viewer.pendingActions += 1;
let refused = false;
try {
- await this.runtime.withHumanAction(viewer.session, viewer.id, async () => {
+ await this.runtime.withHumanAction(viewer.session, viewer.person, async () => {
if (!this.current(viewer)) throw new BrowserLiveError("This browser view closed.", 409);
const take = async (message: ObjectValue) => {
try { await this.input(viewer, message); }
@@ -902,20 +954,14 @@ export class BrowserLive {
private refusal(viewer: Viewer, otherwise: string): BrowserLiveError {
const holder = this.runtime.heldBy(viewer.session);
- if (holder && holder !== viewer.id) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409);
+ if (holder && holder !== viewer.person) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409);
return new BrowserLiveError(this.runtime.interrupted(viewer.session) ? RESTART_NEEDED : otherwise, 409);
}
- /** Done on a sign-in card, from any window or device: whichever view holds this browser hands it back. */
+ /** Done on a sign-in card, from any window or device: whoever holds this browser hands it back. */
handBack(session: string): void {
- const holder = this.runtime.heldBy(session);
- const parked = this.parked.get(session);
- if (holder && parked?.viewer.id === holder) { this.releaseParked(parked); return; }
- const viewer = holder ? this.viewers.get(holder) : undefined;
- if (!viewer || viewer.session !== session) return;
- this.abandonPressedInput(viewer);
- this.runtime.release(session, viewer.id);
- this.control(session);
+ const person = this.runtime.heldBy(session);
+ if (person) this.end(session, person);
}
/** Every view of a browser about to close unused stops, while its stream still answers. */
@@ -932,9 +978,11 @@ export class BrowserLive {
closeForBot(botId: string): void { this.closeWhere((viewer) => viewer.botId === botId); }
closeAll(): void { this.closeWhere(() => true); }
- /** Closed on purpose: their holds end now, a dropped view's included. */
+ /** Closed on purpose: a hold none of its person's views still has ends now, a dropped view's included. */
private closeWhere(match: (viewer: Viewer) => boolean): void {
for (const viewer of this.viewers.values()) if (match(viewer)) this.close(viewer);
- for (const parked of this.parked.values()) if (match(parked.viewer)) this.releaseParked(parked);
+ for (const { viewer } of this.left.values()) {
+ if (match(viewer) && !this.viewsOf(viewer.session, viewer.person).length) this.end(viewer.session, viewer.person);
+ }
}
}
diff --git a/server/browser-runtime.ts b/server/browser-runtime.ts
index 706bf9942e..0ef09488e1 100644
--- a/server/browser-runtime.ts
+++ b/server/browser-runtime.ts
@@ -780,15 +780,6 @@ export class BrowserRuntime {
this.changed(gate);
}
- /** The same person's hold, moved to their view that replaced one whose stream dropped; agents stay paused throughout. */
- transfer(session: string, from: string, to: string): boolean {
- const gate = this.gates.get(session);
- if (!from || !to || !gate || gate.owner !== from || gate.releasing || gate.closing) return false;
- gate.owner = to;
- this.changed(gate);
- return true;
- }
-
release(session: string, owner: string): void {
const gate = this.gates.get(session);
if (!owner || !gate || gate.owner !== owner) return;
diff --git a/server/browser/control.ts b/server/browser/control.ts
index 67749a715f..01ab6f7abc 100644
--- a/server/browser/control.ts
+++ b/server/browser/control.ts
@@ -121,15 +121,12 @@ export class ProfileControl<T extends ControlledTab = ControlledTab> {
this.releasing = true;
this.changed();
let clean = true;
- let timer: ReturnType<typeof setTimeout> | undefined;
try {
- const drained = Promise.all(this.#tabs().map((tab) => tab.control.disconnect(owner, async () => {
- if (!await releaseInput(tab).catch(() => false)) clean = false;
- }).catch(() => undefined))).then(() => true);
- const late = new Promise<false>((resolve) => { timer = setTimeout(() => resolve(false), this.#takeoverMs); timer.unref?.(); });
- if (!await Promise.race([drained, late])) clean = false;
+ clean = await this.#drain((tab) => {
+ let released = true;
+ return tab.control.disconnect(owner, async () => { released = await releaseInput(tab).catch(() => false); }).then(() => released, () => true);
+ });
} finally {
- clearTimeout(timer);
if (this.owner === owner) {
this.owner = null;
this.stale = false;
@@ -143,6 +140,31 @@ export class ProfileControl<T extends ControlledTab = ControlledTab> {
}
}
+ /**
+ * One of the person's views went while they keep the browser: what it pressed is let go once the input queued on each
+ * tab has run, as on a hand-back. A page that never takes it leaves the browser uncertain.
+ */
+ async letGo(owner: string, releaseInput: (tab: T) => Promise<boolean>): Promise<void> {
+ if (!owner || this.owner !== owner) return;
+ const clean = await this.#drain((tab) => tab.control.system(() => releaseInput(tab)).catch(() => true));
+ if (clean || this.uncertain) return;
+ this.uncertain = true;
+ this.lostCall = null;
+ this.changed();
+ }
+
+ /** `work` on every tab, false when one failed or outlasted the drain. */
+ async #drain(work: (tab: T) => Promise<boolean>): Promise<boolean> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const drained = Promise.all(this.#tabs().map(work)).then((results) => results.every(Boolean));
+ const late = new Promise<false>((resolve) => { timer = setTimeout(() => resolve(false), this.#takeoverMs); timer.unref?.(); });
+ return await Promise.race([drained, late]);
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
async human<R>(owner: string, tab: ControlledTab, run: () => Promise<R>): Promise<R> {
if (!this.canControl(owner)) throw new Error("Take control of this browser before interacting.");
this.humans++;
diff --git a/server/browser/hold.ts b/server/browser/hold.ts
new file mode 100644
index 0000000000..d940a15073
--- /dev/null
+++ b/server/browser/hold.ts
@@ -0,0 +1,57 @@
+// How long a person's hold on a bot's browser lasts without a hand-back, the same on both engines. The hold is the
+// person's, not one view's: any of their views may hand it back or take it over, and their next view carries on with
+// it when the one they used went. It ends `graceMs` after the last of their views went (a dropped stream or a phone in
+// the background gets that long to come back), and `idleMs` after they last took control or sent input, kept or not,
+// so a held browser never outlives the person. Every key they type starts the idle time again: the bots stay paused
+// while they really type.
+export interface HoldLimits {
+ readonly graceMs: number;
+ readonly idleMs: number;
+}
+
+export const HOLD_LIMITS: HoldLimits = { graceMs: 2 * 60_000, idleMs: 5 * 60_000 };
+
+/** One browser's two hold timers. `end` runs when either passes, and checks that the hold is still the one timed. */
+export class HoldClock {
+ #idle: ReturnType<typeof setTimeout> | undefined;
+ #grace: ReturnType<typeof setTimeout> | undefined;
+ readonly #end: () => void;
+ readonly #limits: HoldLimits;
+
+ constructor(end: () => void, limits: HoldLimits = HOLD_LIMITS) {
+ this.#end = end;
+ this.#limits = limits;
+ }
+
+ /** The person took control or sent input. */
+ used(): void {
+ clearTimeout(this.#idle);
+ this.#idle = this.#after(this.#limits.idleMs);
+ }
+
+ /** Whether one of the person's views of the browser is open; with none, the grace runs. */
+ watched(open: boolean): void {
+ if (open) {
+ clearTimeout(this.#grace);
+ this.#grace = undefined;
+ } else {
+ this.#grace ??= this.#after(this.#limits.graceMs);
+ }
+ }
+
+ stop(): void {
+ clearTimeout(this.#idle);
+ clearTimeout(this.#grace);
+ this.#idle = undefined;
+ this.#grace = undefined;
+ }
+
+ #after(ms: number): ReturnType<typeof setTimeout> {
+ const timer = setTimeout(() => {
+ this.stop();
+ this.#end();
+ }, ms);
+ timer.unref?.();
+ return timer;
+ }
+}
diff --git a/server/browser/service.test.ts b/server/browser/service.test.ts
index 751a799d79..6aa58eb8af 100644
--- a/server/browser/service.test.ts
+++ b/server/browser/service.test.ts
@@ -219,7 +219,7 @@ describe("a person and the bot sharing one browser", () => {
await call("agent_browser_open", { url: "https://example.com/form" });
const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 2560, maxHeight: 1600 }, () => {});
await viewer.input({ type: "takeControl" });
- expect(service.heldBy("bot-a")).toBe(viewer.id);
+ expect(service.heldBy("bot-a")).toBe("local-owner");
for (const name of ["agent_browser_status", "agent_browser_snapshot", "agent_browser_click", "agent_browser_eval", "agent_browser_dialog"]) {
await expect(call(name, name === "agent_browser_click" ? { ref: "e2" } : name === "agent_browser_eval" ? { expression: "1" } : name === "agent_browser_dialog" ? { accept: true } : {})).rejects.toThrow(BROWSER_CONTROL_REFUSAL);
}
@@ -237,10 +237,10 @@ describe("a person and the bot sharing one browser", () => {
const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 2560, maxHeight: 1600 }, () => {});
const taking = viewer.input({ type: "takeControl" });
await new Promise((resolve) => setTimeout(resolve, 30));
- expect(service.heldBy("bot-a")).toBe(viewer.id);
- expect(service.canControl("bot-a", viewer.id)).toBe(false);
+ expect(service.heldBy("bot-a")).toBe("local-owner");
+ expect(viewer.controlState().controlling).toBe(false);
await taking;
- expect(service.canControl("bot-a", viewer.id)).toBe(true);
+ expect(viewer.controlState().controlling).toBe(true);
expect(service.interrupted("bot-a")).toBe(false);
expect(String(await snapshot)).toContain(BROWSER_CONTROL_REFUSAL);
});
@@ -253,7 +253,7 @@ describe("a person and the bot sharing one browser", () => {
await sleep(20);
const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 2560, maxHeight: 1600 }, () => {});
await viewer.input({ type: "takeControl" });
- expect(service.canControl("bot-a", viewer.id)).toBe(true);
+ expect(viewer.controlState().controlling).toBe(true);
expect(service.interrupted("bot-a")).toBe(true);
await viewer.input({ type: "releaseControl" });
expect(service.heldBy("bot-a")).toBeNull();
diff --git a/server/browser/service.ts b/server/browser/service.ts
index 1d94bcecca..b4d1b5e53e 100644
--- a/server/browser/service.ts
+++ b/server/browser/service.ts
@@ -24,6 +24,7 @@ import { browserRoot, profileDir, profileHash, profileKind, removeProfile, works
import { BROWSER_CONTROL_REFUSAL, ProfileControl, type TakeResult } from "./control.ts";
import { executeTool, personUrl, toolFailure, type ToolContext } from "./dispatch.ts";
import { HealthShown, pageHealthLine } from "./health.ts";
+import type { HoldLimits } from "./hold.ts";
import { errorResult, shapeResult, textResult, withParts, type ToolResult } from "./shape.ts";
import { TabRegistry, type Tab } from "./tabs.ts";
import { parseToolCall, RESTART_TOOL, TOOL_LIST } from "./tools.ts";
@@ -57,6 +58,8 @@ export interface BrowserServiceOptions {
laneWaitMs?: number;
takeoverMs?: number;
capacityWaitMs?: number;
+ /** How long a person's hold lasts without a hand-back; the standard limits when unset. */
+ holdLimits?: HoldLimits;
log?: (line: string) => void;
}
@@ -638,10 +641,6 @@ export class BrowserService {
return download?.state === "completed" && download.path ? download : undefined;
}
- canControl(session: string, owner: string): boolean {
- return this.#bySession(session)?.control.canControl(owner) ?? false;
- }
-
interrupted(session: string): boolean {
return this.#bySession(session)?.control.uncertain === true;
}
@@ -652,12 +651,7 @@ export class BrowserService {
/** Done on a sign-in card, from any window or device: whoever holds this browser hands it back. */
async handBack(session: string): Promise<void> {
- const profile = this.#bySession(session);
- const owner = profile?.control.owner;
- if (!profile || !owner) return;
- const viewer = [...profile.hub.viewers].find((candidate) => candidate.id === owner);
- await profile.control.release(owner, () => viewer?.releaseInput() ?? Promise.resolve(true));
- profile.hub.broadcastControl();
+ await this.#bySession(session)?.hub.handBack();
}
/** A person's restart: every tab closes and the browser comes back on one blank tab. */
@@ -679,6 +673,7 @@ export class BrowserService {
#hubHost(profile: ProfileState) {
return {
control: profile.control,
+ ...(this.#options.holdLimits ? { holdLimits: this.#options.holdLimits } : {}),
browser: () => (profile.run && !profile.run.closing ? profile.run.browser : null),
active: () => profile.active(),
tabs: () => profile.tabs.list(),
diff --git a/server/browser/viewers/core.test.ts b/server/browser/viewers/core.test.ts
index 0066c070fd..2738b61d45 100644
--- a/server/browser/viewers/core.test.ts
+++ b/server/browser/viewers/core.test.ts
@@ -5,6 +5,7 @@ import { afterAll, afterEach, describe, expect, it } from "vitest";
import { removeTempDir } from "../../testing/cleanup.ts";
import { BrowserService } from "../service.ts";
+import type { HoldLimits } from "../hold.ts";
import { FakeBackend, FakeChrome, type FakeDocument } from "../testing/fake-chrome.ts";
import { personUrl } from "../dispatch.ts";
import { ACK_PACE_MS, SETTLE_MS, type ViewerOutput } from "./core.ts";
@@ -31,20 +32,20 @@ const same = (expected: unknown) => (actual: unknown) => JSON.stringify(actual)
const PAGE: FakeDocument = { title: "Page", text: "hello", elements: [{ role: "textbox", name: "Name", selector: "#name", editable: true, box: [10, 10, 200, 30] }] };
-type WatchOptions = { size?: { width: number; height: number }; maxWidth?: number; maxHeight?: number; pace?: "hi" | "lo"; ack?: boolean; authPrompts?: boolean; pointer?: boolean };
+type WatchOptions = { owner?: string; size?: { width: number; height: number }; maxWidth?: number; maxHeight?: number; pace?: "hi" | "lo"; ack?: boolean; authPrompts?: boolean; pointer?: boolean };
-async function setup({ pageLimit = null, document = PAGE }: { pageLimit?: { width: number; height: number } | null; document?: FakeDocument } = {}) {
+async function setup({ pageLimit = null, document = PAGE, holdLimits }: { pageLimit?: { width: number; height: number } | null; document?: FakeDocument; holdLimits?: HoldLimits } = {}) {
const dataDir = mkdtempSync(join(tmpdir(), "omb-viewers-"));
folders.push(dataDir);
const backend = new FakeBackend(() => new FakeChrome({ documents: () => ({ ...document, elements: document.elements.map((element) => ({ ...element })) }) }), { pageLimit });
- const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, takeoverMs: 200 });
+ const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, takeoverMs: 200, ...(holdLimits ? { holdLimits } : {}) });
services.push(service);
const target = { session: "bot-a", key: "bot:a" };
const call = (name: string, args: Record<string, unknown> = {}) => service.agentRpc(target, "tools/call", { name, arguments: args }) as Promise<{ content: Array<{ type: string; text?: string }>; isError?: boolean }>;
await call("agent_browser_open", { url: "https://example.com/" });
const watch = async (options: WatchOptions = {}) => {
const outputs: ViewerOutput[] = [];
- const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: options.maxWidth ?? 3200, maxHeight: options.maxHeight ?? 2000, pace: options.pace ?? "hi", authPrompts: options.authPrompts === true, ...(options.pointer === false ? { pointer: false } : {}), ...(options.size ? { size: options.size } : {}) }, (output) => {
+ const viewer = await service.attachViewer(target, { owner: options.owner ?? "local-owner", canOperate: true, maxWidth: options.maxWidth ?? 3200, maxHeight: options.maxHeight ?? 2000, pace: options.pace ?? "hi", authPrompts: options.authPrompts === true, ...(options.pointer === false ? { pointer: false } : {}), ...(options.size ? { size: options.size } : {}) }, (output) => {
outputs.push(output);
if (output.type === "frame" && options.ack !== false) output.ack();
});
@@ -255,7 +256,7 @@ describe("a viewer's screencast", () => {
const lastStart = () => chrome().sent.filter((sent) => sent.method === "Page.startScreencast").at(-1)?.params;
expect(lastStart()).toMatchObject({ maxWidth: 3024, maxHeight: 1800 });
expect(stills()).toBe(before + 1);
- expect(service.heldBy(target.session)).toBe(viewer.id);
+ expect(service.heldBy(target.session)).toBe("local-owner");
await viewer.input({ type: "frameCap", maxWidth: 99_999, maxHeight: 99_999 });
expect(lastStart()).toMatchObject({ maxWidth: 7680, maxHeight: 4320 });
});
@@ -275,7 +276,7 @@ describe("viewers of one browser", () => {
it("shows a viewer that does not hold the browser no frames, tabs or address while another holds it, and ignores its sizes", async () => {
const { watch, chrome } = await setup();
const holder = await watch({ size: { width: 1400, height: 900 } });
- const other = await watch({ size: { width: 1000, height: 700 } });
+ const other = await watch({ owner: "phone-session", size: { width: 1000, height: 700 } });
const beforeTake = other.outputs.length;
await holder.viewer.input({ type: "takeControl" });
expect(other.outputs.slice(beforeTake)).toContainEqual(expect.objectContaining({ type: "control", controller: "another-viewer", held: true, owned: false }));
@@ -325,7 +326,7 @@ describe("viewers of one browser", () => {
expect(prompt).toMatchObject({ id: "auth-1", origin: "https://intranet.example", realm: "Staff" });
await viewer.input({ type: "authAnswer", tabId: prompt!.tabId, id: prompt!.id, username: "ada", password: "secret" });
expect(chrome().sentTo(page())).toContainEqual(expect.objectContaining({ method: "Fetch.continueWithAuth", params: { requestId: "auth-1", authChallengeResponse: { response: "ProvideCredentials", username: "ada", password: "secret" } } }));
- expect(service.heldBy(target.session)).toBe(viewer.id);
+ expect(service.heldBy(target.session)).toBe("local-owner");
});
it("names each HTTP sign-in by tab and challenge, and gives the person's answer only to the one they were shown", async () => {
@@ -374,6 +375,53 @@ describe("viewers of one browser", () => {
});
});
+describe("one person's hold, across their views", () => {
+ it("carries on in their next view after their stream dropped, and ends when none comes back in time", async () => {
+ const { service, target, watch } = await setup({ holdLimits: { graceMs: 150, idleMs: 60_000 } });
+ const phone = await watch();
+ await phone.viewer.input({ type: "takeControl" });
+ await phone.viewer.close({ dropped: true });
+ expect(service.heldBy(target.session)).toBe("local-owner");
+ const reopened = await watch();
+ expect(reopened.viewer.controlState()).toMatchObject({ controller: "you", held: true, owned: true, controlling: true });
+ await reopened.viewer.close({ dropped: true });
+ await sleep(60);
+ expect(service.heldBy(target.session)).toBe("local-owner");
+ await until(() => service.heldBy(target.session), (owner) => owner === null);
+ });
+
+ it("lets another view of theirs take it over or hand it back, and refuses another person both", async () => {
+ const { service, target, watch } = await setup();
+ const phone = await watch();
+ const laptop = await watch();
+ const stranger = await watch({ owner: "someone-else" });
+ await phone.viewer.input({ type: "takeControl" });
+ expect(laptop.viewer.controlState()).toMatchObject({ controller: "agent", held: true, owned: true, controlling: false });
+ expect(stranger.viewer.controlState()).toMatchObject({ controller: "another-viewer", held: true, owned: false, controlling: false });
+ await stranger.viewer.input({ type: "takeControl" });
+ await stranger.viewer.input({ type: "releaseControl" });
+ expect(service.heldBy(target.session)).toBe("local-owner");
+ await laptop.viewer.input({ type: "takeControl" });
+ expect(laptop.viewer.controlState()).toMatchObject({ controller: "you", controlling: true });
+ expect(phone.viewer.controlState()).toMatchObject({ controller: "agent", owned: true, controlling: false });
+ await phone.viewer.input({ type: "releaseControl" });
+ expect(service.heldBy(target.session)).toBeNull();
+ });
+
+ it("ends a kept hold its person stopped using, while every key they type keeps it", async () => {
+ const { service, target, watch } = await setup({ holdLimits: { graceMs: 60_000, idleMs: 250 } });
+ const { viewer } = await watch();
+ await viewer.input({ type: "takeControl" });
+ await sleep(150);
+ await viewer.input({ type: "key", action: "down", key: "a", code: "KeyA", text: "a", modifiers: 0 });
+ await viewer.input({ type: "key", action: "up", key: "a", code: "KeyA", modifiers: 0 });
+ await sleep(150);
+ expect(service.heldBy(target.session)).toBe("local-owner");
+ await until(() => service.heldBy(target.session), (owner) => owner === null);
+ expect(viewer.controlState()).toMatchObject({ controller: "unclaimed", held: false });
+ });
+});
+
describe("what the panel shows besides the page", () => {
const mainSession = (sent: Array<{ method: string; sessionId: string | null }>) => sent.find((entry) => entry.method === "Page.enable" && entry.sessionId?.startsWith("S"))?.sessionId ?? null;
@@ -483,7 +531,7 @@ describe("what the panel shows besides the page", () => {
it("shows a page's dialog only to the person holding the browser while someone holds it", async () => {
const { watch, chrome, page } = await setup();
const holder = await watch();
- const other = await watch();
+ const other = await watch({ owner: "phone-session" });
await holder.viewer.input({ type: "takeControl" });
chrome().event("Page.javascriptDialogOpening", { type: "alert", message: "Your one-time code is 918273", defaultPrompt: "", url: "https://example.com/" }, mainSession(chrome().sentTo(page()))!);
await sleep(20);
diff --git a/server/browser/viewers/core.ts b/server/browser/viewers/core.ts
index 13d15a4142..be74ddf6ee 100644
--- a/server/browser/viewers/core.ts
+++ b/server/browser/viewers/core.ts
@@ -19,8 +19,10 @@ import type { OpenFileChooser } from "../cdp/files.ts";
import { editingCommands, keyDescription, US_KEYBOARD } from "../cdp/keyboard.ts";
import type { ProfileControl, TakeResult } from "../control.ts";
import { personUrl } from "../dispatch.ts";
+import type { HoldLimits } from "../hold.ts";
import type { Tab } from "../tabs.ts";
import { ACCEPT_OF, chooseOption, cursorAt, editableAt, selectAt, type SelectPopup } from "./popups.ts";
+import { ViewerHold } from "./hold.ts";
import { fitsScreen, MIN_WINDOW_WIDTH, requestedSize, VIEWPORT_PRESETS, viewportFor, ZOOM_LIMITS, zoomedLayout, type ViewportSetting } from "./viewport.ts";
/** Chromium keeps three frames unacknowledged, so acking 100 ms after arrival caps a viewer near 30 fps. */
@@ -75,8 +77,10 @@ export type ViewerOutput =
| { type: "gone"; reason: string };
export interface ViewerOptions {
- /** Who is watching: a session id, or local-owner. */
+ /** The session watching, or local-owner. */
owner: string;
+ /** Whose hold this view shares, on any device: their account's key, the owner when unset. */
+ person?: string;
canOperate: boolean;
/** The largest frame this viewer can use, in device pixels. */
maxWidth: number;
@@ -96,6 +100,7 @@ export interface ViewerOptions {
/** What a hub needs from the browser service. */
export interface HubHost {
readonly control: ProfileControl<Tab>;
+ readonly holdLimits?: HoldLimits;
browser(): CdpBrowser | null;
active(): Tab | null;
tabs(): Tab[];
@@ -157,6 +162,7 @@ export class Viewer {
this.#push = push;
this.options = {
owner: options.owner,
+ person: options.person ?? options.owner,
canOperate: options.canOperate,
maxWidth: Math.max(1, Math.round(options.maxWidth)),
maxHeight: Math.max(1, Math.round(options.maxHeight)),
@@ -394,6 +400,9 @@ export class Viewer {
this.#hub.pushTabs(this);
}
+ /** Who holds the browser, as this viewer's control message tells it. */
+ controlState(): Extract<ViewerOutput, { type: "control" }> { return this.#hub.controlFor(this); }
+
/** Everything a viewer that just started listening needs: who controls, the size, the tabs, and a picture. */
async refresh(): Promise<void> {
this.push(this.#hub.statusFor());
@@ -402,9 +411,9 @@ export class Viewer {
await this.pushStill();
}
- async close(): Promise<void> {
+ async close({ dropped = false }: { dropped?: boolean } = {}): Promise<void> {
if (this.closed) return;
- await this.#hub.detach(this);
+ await this.#hub.detach(this, { dropped });
}
async teardown(): Promise<void> {
@@ -431,11 +440,15 @@ export class ViewerHub {
#shown: { width: number; height: number; zoom: number } | null = null;
#emulated = false;
#applying: Promise<void> = Promise.resolve();
+ readonly #hold: ViewerHold;
constructor(host: HubHost) {
this.host = host;
+ this.#hold = new ViewerHold(host, this.viewers, () => this.broadcastControl());
}
+ handBack(): Promise<void> { return this.#hold.handBack(); }
+
get size(): number {
return this.viewers.size;
}
@@ -517,11 +530,13 @@ export class ViewerHub {
if (size && options.canOperate && this.host.control.owner === null) viewer.requested = { ...size, order: ++this.#order };
this.viewers.add(viewer);
this.host.used();
+ this.#hold.opened(viewer);
try {
viewer.push({ type: "starting" });
await this.host.running();
if (viewer.closed) return viewer;
- await viewer.hide(this.#hides(viewer));
+ await this.#hold.carryOn(viewer);
+ await viewer.hide(this.#hold.hides(viewer));
void this.#resizeForViewers().catch(() => undefined);
viewer.push(this.controlFor(viewer));
viewer.push({ type: "viewport", ...(this.#shown ?? { ...zoomedLayout(this.viewport(), this.zoom), zoom: this.zoom }), setting: this.setting });
@@ -537,46 +552,38 @@ export class ViewerHub {
}
}
- async detach(viewer: Viewer): Promise<void> {
+ async detach(viewer: Viewer, { dropped = false }: { dropped?: boolean } = {}): Promise<void> {
if (!this.viewers.has(viewer)) return;
this.viewers.delete(viewer);
- if (this.host.control.owner === viewer.id) await this.host.release(viewer.id, () => viewer.releaseInput()).catch(() => {});
- else await viewer.releaseInput();
+ await this.#hold.left(viewer, dropped);
await viewer.teardown();
this.broadcastControl();
if (viewer.requested) void this.#resizeForViewers().catch(() => undefined);
}
broadcast(output: ViewerOutput, { holderOnly = false }: { holderOnly?: boolean } = {}): void {
- const owner = this.host.control.owner;
for (const viewer of this.viewers) {
- if (holderOnly && owner !== viewer.id) continue;
- if (!holderOnly && owner !== null && owner !== viewer.id && (output.type === "tabs" || output.type === "url" || output.type === "nav" || output.type === "pointer")) continue;
+ if (holderOnly && !this.#hold.drives(viewer)) continue;
+ if (!holderOnly && this.#hold.hides(viewer) && (output.type === "tabs" || output.type === "url" || output.type === "nav" || output.type === "pointer")) continue;
viewer.push(output);
}
}
- /** Another person holds the browser: this viewer sees none of it, unless it only watches for that same person (their picture in picture). */
- #hides(viewer: Viewer): boolean {
- const owner = this.host.control.owner;
- if (owner === null || owner === viewer.id) return false;
- const holder = [...this.viewers].find((candidate) => candidate.id === owner);
- return viewer.options.canOperate || holder?.options.owner !== viewer.options.owner;
- }
-
- controlFor(viewer: Viewer): ViewerOutput {
+ controlFor(viewer: Viewer): Extract<ViewerOutput, { type: "control" }> {
const control = this.host.control;
const owner = control.owner;
+ const owned = this.#hold.owns(viewer);
+ const controlling = this.#hold.controls(viewer);
// Security: a dialog's text can be a code meant for the person holding the browser.
- const dialog = owner === null || owner === viewer.id ? this.host.active()?.page.dialogs.pending ?? null : null;
+ const dialog = owner === null || owned ? this.host.active()?.page.dialogs.pending ?? null : null;
return {
type: "control",
canOperate: viewer.options.canOperate,
// "you" means this viewer's input runs now: while a takeover waits for the bot's work, the bot still has it.
- controller: owner === viewer.id ? (control.canControl(viewer.id) ? "you" : "agent") : owner !== null ? "another-viewer" : control.agents > 0 ? "agent" : "unclaimed",
+ controller: controlling ? "you" : owned ? "agent" : owner !== null ? "another-viewer" : control.agents > 0 ? "agent" : "unclaimed",
held: owner !== null,
- owned: owner === viewer.id,
- controlling: control.canControl(viewer.id),
+ owned,
+ controlling,
stale: control.stale,
generation: this.host.active()?.control.generation ?? 0,
dialog: dialog ? { type: dialog.type, message: dialog.message, defaultValue: dialog.defaultPrompt } : null,
@@ -585,7 +592,7 @@ export class ViewerHub {
broadcastControl(): void {
for (const viewer of this.viewers) {
- void viewer.hide(this.#hides(viewer));
+ void viewer.hide(this.#hold.hides(viewer));
viewer.push(this.controlFor(viewer));
}
void this.offerFileChooser();
@@ -594,8 +601,7 @@ export class ViewerHub {
/** The newest HTTP sign-in a tab waits on goes to the person holding the browser, named by tab and challenge, so their answer reaches that one only. */
offerAuthPrompt(): void {
- const owner = this.host.control.owner;
- const holder = [...this.viewers].find((viewer) => viewer.id === owner && viewer.options.authPrompts && !viewer.closed);
+ const holder = this.#hold.driver?.options.authPrompts ? this.#hold.driver : undefined;
const asking = holder ? newestChallenge(this.host.tabs()) : null;
const offered = this.#authOffered;
if (offered && offered.viewer === holder && offered.id === asking?.challenge.id) return;
@@ -611,8 +617,7 @@ export class ViewerHub {
}
async #offer(): Promise<void> {
- const owner = this.host.control.owner;
- const holder = owner === null ? null : [...this.viewers].find((viewer) => viewer.id === owner && !viewer.closed) ?? null;
+ const holder = this.#hold.driver;
const tab = this.host.active();
const open = tab?.page.fileChoosers.open ?? null;
const offered = this.#chooser;
@@ -624,7 +629,7 @@ export class ViewerHub {
if (!holder || !tab || !open) return;
const accept = await callOnNode<string>(tab.page.frames, open, ACCEPT_OF).catch(() => "");
// Whatever changed meanwhile queued its own offer.
- if (tab.page.fileChoosers.open !== open || this.host.control.owner !== holder.id || holder.closed || this.#chooser) return;
+ if (tab.page.fileChoosers.open !== open || this.#hold.driver !== holder || this.#chooser) return;
const chooser = { id: randomUUID(), tab, viewer: holder, open };
this.#chooser = chooser;
holder.push({ type: "fileChooser", id: chooser.id, multiple: open.multiple, accept: typeof accept === "string" ? accept : "" });
@@ -640,7 +645,8 @@ export class ViewerHub {
async answerFileChooser(owner: string, id: string, paths: readonly string[]): Promise<boolean> {
const chooser = this.#chooser;
if (!chooser || !this.fileChooserOffered(owner, id)) return false;
- await this.host.control.human(chooser.viewer.id, chooser.tab, () => chooser.tab.page.fileChoosers.answer(paths, { waitMs: 0 }));
+ this.#hold.used();
+ await this.host.control.human(chooser.viewer.options.person, chooser.tab, () => chooser.tab.page.fileChoosers.answer(paths, { waitMs: 0 }));
return true;
}
@@ -650,8 +656,7 @@ export class ViewerHub {
}
pushTabs(viewer: Viewer): void {
- const owner = this.host.control.owner;
- if (owner !== null && owner !== viewer.id) return;
+ if (this.#hold.hides(viewer)) return;
viewer.push(this.tabsMessage());
const active = this.host.active();
if (active) viewer.push({ type: "url", url: active.page.url() });
@@ -778,26 +783,26 @@ export class ViewerHub {
await this.host.running().catch(() => viewer.push({ type: "asleep" }));
return;
case "takeControl": {
- const taking = this.host.take(viewer.id);
+ const taking = this.host.take(viewer.options.person);
this.broadcastControl();
- await taking.finally(() => this.broadcastControl());
+ await taking.then(() => this.#hold.took(viewer)).finally(() => this.broadcastControl());
return;
}
case "releaseControl": {
- const releasing = this.host.release(viewer.id, () => viewer.releaseInput());
+ const releasing = this.#hold.release(viewer);
this.broadcastControl();
await releasing.finally(() => this.broadcastControl());
return;
}
case "resize": {
const size = requestedSize(message.width, message.height);
- if (!size || (control.owner !== null && control.owner !== viewer.id)) return;
+ if (!size || (control.owner !== null && !this.#hold.drives(viewer))) return;
viewer.requested = { ...size, order: ++this.#order };
if (this.setting.mode === "fill") await this.#resizeForViewers();
return;
}
case "viewport": {
- if (!control.canControl(viewer.id)) return;
+ if (!this.#hold.controls(viewer)) return;
const setting = parseSetting(message.setting);
if (!setting) return;
this.setting = setting;
@@ -806,7 +811,7 @@ export class ViewerHub {
}
case "zoom": {
const factor = num(message.factor, 0);
- if (!control.canControl(viewer.id) || !(factor > 0)) return;
+ if (!this.#hold.controls(viewer) || !(factor > 0)) return;
this.zoom = Math.round(Math.min(ZOOM_LIMITS.max, Math.max(ZOOM_LIMITS.min, factor)) * 100) / 100;
await this.#resizeForViewers();
return;
@@ -816,10 +821,11 @@ export class ViewerHub {
return;
}
const tab = this.host.active();
- if (!tab || !control.canControl(viewer.id)) {
+ if (!tab || !this.#hold.controls(viewer)) {
this.broadcastControl();
return;
}
+ this.#hold.used();
switch (message.type) {
case "dialog":
if (typeof message.accept === "boolean") await tab.page.answerDialog({ accept: message.accept, ...(typeof message.promptText === "string" ? { promptText: message.promptText.slice(0, 4_000) } : {}) });
@@ -839,11 +845,11 @@ export class ViewerHub {
}
case "tabSelect": {
const next = typeof message.tabId === "string" ? this.host.tab(message.tabId) : undefined;
- if (next) await control.human(viewer.id, next, () => this.host.showTab(next));
+ if (next) await control.human(viewer.options.person, next, () => this.host.showTab(next));
return;
}
case "tabNew":
- await this.host.openTab(typeof message.url === "string" ? message.url : null, viewer.id);
+ await this.host.openTab(typeof message.url === "string" ? message.url : null, viewer.options.person);
return;
case "tabClose": {
const closing = typeof message.tabId === "string" ? this.host.tab(message.tabId) : undefined;
@@ -855,11 +861,11 @@ export class ViewerHub {
viewer.select = null;
const index = num(message.index, -1);
if (!select || select.id !== message.id || select.tab !== tab || !Number.isInteger(index) || index < 0) return;
- await control.human(viewer.id, tab, () => chooseOption(tab.page, select.id, index));
+ await control.human(viewer.options.person, tab, () => chooseOption(tab.page, select.id, index));
return;
}
}
- await control.human(viewer.id, tab, () => this.#dispatch(viewer, tab, message));
+ await control.human(viewer.options.person, tab, () => this.#dispatch(viewer, tab, message));
}
/** A press on a dropdown list: the viewer draws its options, since no frame shows Chrome's own popup. */
diff --git a/server/browser/viewers/hold.ts b/server/browser/viewers/hold.ts
new file mode 100644
index 0000000000..906a39afb9
--- /dev/null
+++ b/server/browser/viewers/hold.ts
@@ -0,0 +1,123 @@
+// A person's hold of a bot's browser as its viewers share it on the new engine. The hold is the person's: every view of
+// theirs sees it, any of them may take it over or hand it back, and their next view carries on with it when the view it
+// was used from went. Input runs only from that one view. How long it lasts unasked is in ../hold.ts.
+import { HoldClock } from "../hold.ts";
+import type { HubHost, Viewer } from "./core.ts";
+
+export class ViewerHold {
+ readonly #host: HubHost;
+ readonly #viewers: ReadonlySet<Viewer>;
+ readonly #changed: () => void;
+ readonly #clock: HoldClock;
+ /** The view the hold is used from. */
+ #driver: Viewer | null = null;
+ /** What the view it was used from pressed, being let go after that view went. */
+ #letGo: Promise<void> = Promise.resolve();
+
+ constructor(host: HubHost, viewers: ReadonlySet<Viewer>, changed: () => void) {
+ this.#host = host;
+ this.#viewers = viewers;
+ this.#changed = changed;
+ this.#clock = new HoldClock(() => void this.handBack(), host.holdLimits);
+ // A hold that ended, whichever way, leaves nothing behind for the next one.
+ host.control.onChange(() => {
+ if (host.control.owner !== null) return;
+ this.#driver = null;
+ this.#clock.stop();
+ });
+ }
+
+ /** The viewer's person holds the browser, from this view or another of theirs. */
+ owns(viewer: Viewer): boolean {
+ const owner = this.#host.control.owner;
+ return owner !== null && owner === viewer.options.person;
+ }
+
+ /** Another person holds the browser: the viewer sees none of it. Every view of the holder, their picture in picture
+ * too, sees it all. */
+ hides(viewer: Viewer): boolean {
+ return this.#host.control.owner !== null && !this.owns(viewer);
+ }
+
+ /** The viewer is the one its person's hold is used from. */
+ drives(viewer: Viewer): boolean {
+ return this.#driver === viewer && this.owns(viewer);
+ }
+
+ /** It drives the hold, and its person's input runs now. */
+ controls(viewer: Viewer): boolean {
+ return this.drives(viewer) && this.#host.control.canControl(viewer.options.person);
+ }
+
+ /** The open view the hold is used from: the one a page's file picker or sign-in prompt goes to. */
+ get driver(): Viewer | null {
+ const driver = this.#driver;
+ return driver && this.drives(driver) && !driver.closed ? driver : null;
+ }
+
+ /** The person took control or sent input. */
+ used(): void {
+ this.#clock.used();
+ }
+
+ opened(viewer: Viewer): void {
+ if (this.owns(viewer)) this.#clock.watched(true);
+ }
+
+ /** Their view carries on with their hold when no view of theirs uses it, once what the last one pressed is let go. */
+ async carryOn(viewer: Viewer): Promise<void> {
+ const free = () => !viewer.closed && viewer.options.canOperate && this.owns(viewer) && (this.#driver === null || !this.#viewers.has(this.#driver));
+ if (!free()) return;
+ await this.#letGo;
+ if (free()) this.#driver = viewer;
+ }
+
+ /** The person's take was granted: their hold is used from this view now, never with what the view before it pressed. */
+ async took(viewer: Viewer): Promise<void> {
+ const person = viewer.options.person;
+ const before = this.#driver;
+ if (before && before !== viewer && this.#viewers.has(before)) await this.#host.control.letGo(person, () => before.releaseInput());
+ await this.#letGo;
+ if (viewer.closed || !this.owns(viewer)) return;
+ this.#driver = viewer;
+ this.#clock.used();
+ this.#clock.watched(true);
+ }
+
+ /** Any view of the person hands their hold back, whichever of their views it is used from. */
+ async release(viewer: Viewer): Promise<void> {
+ if (this.owns(viewer)) await this.#end(viewer.options.person);
+ }
+
+ /**
+ * A view went. What it pressed is let go once the input it queued has run. The hold carries on in the person's other
+ * views; with none left, a dropped stream's hold waits the grace for their next view, and any other ends now.
+ */
+ async left(viewer: Viewer, dropped: boolean): Promise<void> {
+ const person = viewer.options.person;
+ if (this.drives(viewer)) {
+ const letGo = this.#host.control.letGo(person, () => viewer.releaseInput());
+ this.#letGo = letGo;
+ await letGo;
+ if (this.#driver === viewer) this.#driver = null;
+ } else {
+ await viewer.releaseInput();
+ }
+ if (!this.owns(viewer) || [...this.#viewers].some((other) => other.options.person === person)) return;
+ if (dropped) this.#clock.watched(false);
+ else await this.#end(person).catch(() => undefined);
+ }
+
+ /** Done on a sign-in card, from any window or device, or when a limit passed: whoever holds the browser hands it back. */
+ async handBack(): Promise<void> {
+ const person = this.#host.control.owner;
+ if (person !== null) await this.#end(person).catch(() => undefined);
+ this.#changed();
+ }
+
+ /** The person's hold ends as a hand-back does: what their views pressed is let go once their queued input has run. */
+ async #end(person: string): Promise<void> {
+ const views = [...this.#viewers].filter((viewer) => viewer.options.person === person);
+ await this.#host.release(person, async () => (await Promise.all(views.map((viewer) => viewer.releaseInput()))).every(Boolean));
+ }
+}
diff --git a/server/browser/viewers/live-v1.test.ts b/server/browser/viewers/live-v1.test.ts
index f5625cc619..8d01328d65 100644
--- a/server/browser/viewers/live-v1.test.ts
+++ b/server/browser/viewers/live-v1.test.ts
@@ -5,6 +5,7 @@ import { afterAll, afterEach, describe, expect, it } from "vitest";
import { BROWSER_HELD_ELSEWHERE } from "../../../shared/browser-held.ts";
import { removeTempDir } from "../../testing/cleanup.ts";
+import type { HoldLimits } from "../hold.ts";
import { BrowserService } from "../service.ts";
import { FakeBackend, FakeChrome } from "../testing/fake-chrome.ts";
import { LiveV1 } from "./live-v1.ts";
@@ -19,11 +20,11 @@ afterAll(async () => { for (const folder of folders) await removeTempDir(folder)
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const ORIGIN = "http://127.0.0.1:43210";
-function setup() {
+function setup({ holdLimits }: { holdLimits?: HoldLimits } = {}) {
const dataDir = mkdtempSync(join(tmpdir(), "omb-live-v1-"));
folders.push(dataDir);
const backend = new FakeBackend(() => new FakeChrome({ documents: (url) => ({ title: url.endsWith("/b") ? "Page B" : url.endsWith("/a") ? "Page A" : "", text: url, elements: [{ role: "textbox", name: "Field", editable: true, box: [20, 20, 300, 40] }] }) }));
- const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 10, idleMs: () => 600_000, takeoverMs: 200 });
+ const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 10, idleMs: () => 600_000, takeoverMs: 200, ...(holdLimits ? { holdLimits } : {}) });
const live = new LiveV1({ service, target: (session) => ({ session, key: `bot:${session}` }) });
cleanups.push(async () => { live.closeAll(); await service.closeAll(); });
const open = async (session = "a", owner = "local-owner", size: { width: number; height: number } | null = null) => {
@@ -111,6 +112,42 @@ describe("the v1 live view on the new browser", () => {
expect(await mac.action({ type: "take" })).toEqual({ ok: true, waited: false });
});
+ it("gives a phone's hold back to it when the app reopens, and ends it when the phone does not come back", async () => {
+ const { open, service } = setup({ holdLimits: { graceMs: 150, idleMs: 60_000 } });
+ const phone = await open();
+ await phone.action({ type: "take" });
+ // The person leaves the browser, or closes the app: the phone's stream ends.
+ phone.sse.destroy();
+ await sleep(20);
+ expect(service.heldBy("a")).toBe("local-owner");
+ const reopened = await open();
+ const control = () => [...reopened.sse.events].reverse().find((event) => event.type === "control")?.data;
+ expect(control()).toEqual({ held: true, owned: true, controlling: true });
+ expect(await reopened.action({ type: "input_keyboard", eventType: "char", text: "x" })).toEqual({ ok: true });
+ reopened.sse.destroy();
+ await sleep(60);
+ expect(service.heldBy("a")).toBe("local-owner");
+ await sleep(200);
+ expect(service.heldBy("a")).toBeNull();
+ const result = await service.agentRpc({ session: "a", key: "bot:a" }, "tools/call", { name: "agent_browser_status", arguments: {} }) as { isError?: boolean };
+ expect(result.isError).toBeUndefined();
+ });
+
+ it("lets the person hand back from another of their views, or take over, while the first stays open", async () => {
+ const { open, service } = setup();
+ const phone = await open();
+ const laptop = await open();
+ const control = (view: { sse: { events: Array<{ type: string; data: Record<string, unknown> }> } }) => [...view.sse.events].reverse().find((event) => event.type === "control")?.data;
+ await phone.action({ type: "take" });
+ expect(control(laptop)).toEqual({ held: true, owned: true, controlling: false });
+ expect(await laptop.action({ type: "take" })).toEqual({ ok: true, waited: false });
+ expect(control(laptop)).toEqual({ held: true, owned: true, controlling: true });
+ expect(control(phone)).toEqual({ held: true, owned: true, controlling: false });
+ await phone.action({ type: "release" });
+ expect(service.heldBy("a")).toBeNull();
+ expect(control(laptop)).toEqual({ held: false, owned: false, controlling: false });
+ });
+
it("turns a phone's keys into real key events, with Enter's text from the US layout", async () => {
const { open, backend } = setup();
const { action } = await open();
diff --git a/server/browser/viewers/live-v1.ts b/server/browser/viewers/live-v1.ts
index 463983d934..17180a6f14 100644
--- a/server/browser/viewers/live-v1.ts
+++ b/server/browser/viewers/live-v1.ts
@@ -25,6 +25,8 @@ export interface LiveOpenOptions {
botId: string;
session: string;
owner: string;
+ /** The person watching, whose hold this view shares on any device; the owner when unset. */
+ person?: string;
isCurrent: () => boolean;
res: ServerResponse;
/** The panel's size in CSS pixels, which the page fills from the start. */
@@ -36,6 +38,7 @@ interface V1Viewer {
readonly botId: string;
readonly session: string;
readonly owner: string;
+ readonly person: string;
readonly isCurrent: () => boolean;
readonly res: ServerResponse;
core: Viewer | null;
@@ -106,10 +109,11 @@ export class LiveV1 {
}
}
+ /** `owned` when the view's person holds the browser, from this view or another of theirs; `controlling` when their hold is used from this one. */
#control(viewer: V1Viewer): void {
- const session = viewer.session;
- const held = this.#service.heldBy(session);
- this.#send(viewer, { type: "control", held: held !== null, owned: held === viewer.id, controlling: this.#service.canControl(session, viewer.id) });
+ const state = viewer.core?.controlState();
+ if (!state) return;
+ this.#send(viewer, { type: "control", held: state.held, owned: state.owned, controlling: state.controlling });
}
#controlAll(session: string): void {
@@ -183,7 +187,7 @@ export class LiveV1 {
}
const target = this.#target(options.session);
if (!target) throw new BrowserLiveError("The browser could not start on this server. Reconnect to retry with a fresh browser session.", 503);
- const viewer: V1Viewer = { ...options, id: "", core: null, closed: false, blocked: false, ready: false, seq: 0, sent: null, pending: null, pendingActions: 0, restarting: false };
+ const viewer: V1Viewer = { ...options, person: options.person ?? options.owner, id: "", core: null, closed: false, blocked: false, ready: false, seq: 0, sent: null, pending: null, pendingActions: 0, restarting: false };
if (!this.#current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);
options.res.once("close", () => this.#close(viewer));
options.res.once("error", () => this.#close(viewer));
@@ -194,10 +198,15 @@ export class LiveV1 {
}, WAITING_AFTER_MS);
waiting.unref?.();
try {
- const core = await this.#service.attachViewer(target, { owner: options.owner, canOperate: true, ...LO_TIER, pace: "lo", pointer: false, ...(options.size ? { size: options.size } : {}) }, (output) => this.#output(viewer, output));
+ const core = await this.#service.attachViewer(target, { owner: options.owner, person: viewer.person, canOperate: true, ...LO_TIER, pace: "lo", pointer: false, ...(options.size ? { size: options.size } : {}) }, (output) => this.#output(viewer, output));
(viewer as { id: string }).id = core.id;
viewer.core = core;
- if (!this.#current(viewer)) { this.#close(viewer); return; }
+ if (!this.#current(viewer)) {
+ // It went while the browser started: what it opened goes too.
+ if (viewer.closed) void core.close({ dropped: this.#theirs(viewer) }).catch(() => undefined);
+ else this.#close(viewer);
+ return;
+ }
this.#viewers.set(viewer.id, viewer);
this.#startEvents(viewer);
viewer.ready = true;
@@ -224,7 +233,13 @@ export class LiveV1 {
}
}
- #close(viewer: V1Viewer, endResponse = true): void {
+ /** Still the view of a person allowed to see this browser: its stream went, not its sign-in. */
+ #theirs(viewer: V1Viewer): boolean {
+ try { return viewer.isCurrent(); } catch { return false; }
+ }
+
+ /** `purposeful`: the server closed it; otherwise a hold of its person waits the grace for their next view. */
+ #close(viewer: V1Viewer, endResponse = true, purposeful = false): void {
if (viewer.closed) return;
viewer.closed = true;
if (viewer.id) this.#viewers.delete(viewer.id);
@@ -234,7 +249,7 @@ export class LiveV1 {
viewer.sent?.ack();
viewer.pending = null;
viewer.sent = null;
- void viewer.core?.close().catch(() => undefined).then(() => this.#controlAll(viewer.session));
+ void viewer.core?.close({ dropped: !purposeful && this.#theirs(viewer) }).catch(() => undefined).then(() => this.#controlAll(viewer.session));
if (endResponse && !viewer.res.writableEnded && !viewer.res.destroyed) {
if (viewer.blocked || viewer.res.writableLength > MAX_BUFFER) viewer.res.destroy();
else viewer.res.end();
@@ -243,7 +258,7 @@ export class LiveV1 {
#refusal(viewer: V1Viewer, otherwise: string): BrowserLiveError {
const holder = this.#service.heldBy(viewer.session);
- if (holder && holder !== viewer.id) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409);
+ if (holder && holder !== viewer.person) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409);
return new BrowserLiveError(this.#service.interrupted(viewer.session) ? RESTART_NEEDED : otherwise, 409);
}
@@ -271,7 +286,7 @@ export class LiveV1 {
if (viewer.restarting) throw new BrowserLiveError("The browser is already restarting.", 409);
viewer.restarting = true;
try {
- await this.#service.restart(viewer.session, viewer.id);
+ await this.#service.restart(viewer.session, viewer.person);
this.closeForSession(viewer.session);
return { ok: true };
} catch {
@@ -287,21 +302,21 @@ export class LiveV1 {
}
if (action.type === "take") {
const before = this.#service.heldBy(viewer.session);
- if (before !== null && before !== viewer.id) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.");
+ if (before !== null && before !== viewer.person) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.");
const busy = this.#service.profiles().find((profile) => profile.session === viewer.session)?.control.agents ?? 0;
await core.input({ type: "takeControl" });
this.#controlAll(viewer.session);
- if (this.#service.heldBy(viewer.session) !== viewer.id) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.");
+ if (!core.controlState().controlling) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.");
if (!this.#current(viewer)) { this.#close(viewer); throw new BrowserLiveError("This browser view closed.", 409); }
return { ok: true, waited: busy > 0 };
}
- if (!this.#service.canControl(viewer.session, viewer.id)) throw this.#refusal(viewer, "Browser control changed. Try again.");
+ if (!core.controlState().controlling) throw this.#refusal(viewer, "Browser control changed. Try again.");
if (viewer.pendingActions >= 32) throw new BrowserLiveError("Too many browser actions are pending. Try again shortly.", 429);
viewer.pendingActions++;
try {
if (action.type === "command") await core.input(commandMessage(action.args));
else if (action.type === "input") await core.input(inputMessage(action.message));
- if (!this.#service.canControl(viewer.session, viewer.id)) throw this.#refusal(viewer, "Browser control changed. Try again.");
+ if (!core.controlState().controlling) throw this.#refusal(viewer, "Browser control changed. Try again.");
core.pushTabs();
return { ok: true };
} finally {
@@ -318,10 +333,10 @@ export class LiveV1 {
void this.#service.handBack(session).then(() => this.#controlAll(session), () => undefined);
}
- closeForSession(session: string): void { for (const viewer of this.#viewers.values()) if (viewer.session === session) this.#close(viewer); }
- closeForOwner(owner: string): void { for (const viewer of this.#viewers.values()) if (viewer.owner === owner) this.#close(viewer); }
- closeForBot(botId: string): void { for (const viewer of this.#viewers.values()) if (viewer.botId === botId) this.#close(viewer); }
- closeAll(): void { for (const viewer of this.#viewers.values()) this.#close(viewer); }
+ closeForSession(session: string): void { for (const viewer of this.#viewers.values()) if (viewer.session === session) this.#close(viewer, true, true); }
+ closeForOwner(owner: string): void { for (const viewer of this.#viewers.values()) if (viewer.owner === owner) this.#close(viewer, true, true); }
+ closeForBot(botId: string): void { for (const viewer of this.#viewers.values()) if (viewer.botId === botId) this.#close(viewer, true, true); }
+ closeAll(): void { for (const viewer of this.#viewers.values()) this.#close(viewer, true, true); }
}
/** The fixed v1 verbs, as the viewer messages the new browser takes. */
diff --git a/server/browser/viewers/stream-v2.e2e.test.ts b/server/browser/viewers/stream-v2.e2e.test.ts
index 6be7c773ec..3faffe1169 100644
--- a/server/browser/viewers/stream-v2.e2e.test.ts
+++ b/server/browser/viewers/stream-v2.e2e.test.ts
@@ -63,6 +63,7 @@ suite("the v2 stream on real Chrome", () => {
const route = createBrowserViewerRoutes({
upgrades,
dataDir: real.dataDir,
+ person: () => "local-owner",
viewers: {
open: async () => {},
action: async () => ({ ok: true }),
@@ -190,8 +191,9 @@ suite("the v2 stream on real Chrome", () => {
const holder = await connect("width=1200&height=800&maxWidth=2400&maxHeight=1600");
await takeControl(holder);
await until(pageSize, same([1280, 853, 2]));
+ // The same person's second panel watches their hold: the page keeps the size of the one it is used from.
const other = await connect("width=700&height=1000&maxWidth=1400&maxHeight=2000");
- await until(() => other.messages.filter((message) => message.type === "control").at(-1), (control) => control?.controller === "another-viewer");
+ await until(() => other.messages.filter((message) => message.type === "control").at(-1), (control) => control?.controller === "agent" && control.owned === true && control.controlling === false);
await sleep(1_000);
expect(await pageSize()).toEqual([1280, 853, 2]);
await other.close();
diff --git a/server/browser/viewers/stream-v2.ts b/server/browser/viewers/stream-v2.ts
index 1c5117204f..52f734d1fd 100644
--- a/server/browser/viewers/stream-v2.ts
+++ b/server/browser/viewers/stream-v2.ts
@@ -42,6 +42,8 @@ const RECHECK_MS = 5_000;
const CLOSE_GRACE_MS = 2_000;
const GONE = "This browser view is no longer available.";
const PING_MS = 15_000;
+/** The close code of a connection that broke without a close frame. */
+const ABNORMAL_CLOSE = 1006;
/** Input that arrives while the viewer is still attaching (its control state is already on the wire) waits for it. */
const EARLY_INPUT_LIMIT = 64;
@@ -50,6 +52,8 @@ export interface StreamRequest {
botId: string;
/** A session id, or local-owner. */
owner: string;
+ /** The person watching, whose hold this view shares on any device; the owner when unset. */
+ person?: string;
/** False for a passive view (picture in picture): it never takes control. */
canOperate: boolean;
params: URLSearchParams;
@@ -98,6 +102,8 @@ class StreamSession {
readonly unacknowledged: Array<() => void> = [];
viewer: Viewer | null = null;
closed = false;
+ /** Its connection broke, rather than the panel closing it. */
+ lost = false;
/** The server is closing this view: nothing the client sends reaches the browser any more. */
closing = false;
#early: unknown[] = [];
@@ -134,7 +140,7 @@ class StreamSession {
return;
}
if (output.type === "gone") {
- this.close(STREAM_CLOSE.reconnect, "reconnect");
+ this.close(STREAM_CLOSE.reconnect, "reconnect", { dropped: true });
return;
}
const message = wireMessage(output);
@@ -198,7 +204,7 @@ class StreamSession {
if (this.#restarting || !this.viewer || this.closing) return;
this.#restarting = true;
try {
- await service.restart(this.request.target.session, this.viewer.id);
+ await service.restart(this.request.target.session, this.viewer.options.person);
} catch {
this.notice("The browser could not restart. Wait for active work to finish and try again.");
} finally {
@@ -206,21 +212,29 @@ class StreamSession {
}
}
- /** Lets the viewer go at once, releasing any control and held input, then tells the client why and cuts it off. */
- close(code: number, reason: string): void {
+ /** Lets the viewer go at once, and its held input, then tells the client why and cuts it off. `dropped`: the client comes
+ * straight back, so a hold of its person waits for it. */
+ close(code: number, reason: string, { dropped = false }: { dropped?: boolean } = {}): void {
if (this.closed || this.closing) return;
this.closing = true;
- void this.viewer?.close().catch(() => undefined);
+ void this.viewer?.close({ dropped }).catch(() => undefined);
try { this.ws.close(code, reason.slice(0, 120)); } catch { this.kill(); return; }
setTimeout(() => this.kill(), CLOSE_GRACE_MS).unref();
}
- /** Releases Chromium from every frame still in flight and lets the viewer go. */
- ended(): void {
+ /** Releases Chromium from every frame still in flight and lets the viewer go. `lost`: the connection broke rather
+ * than the panel closing it, so a hold of its person waits the grace for their next view. */
+ ended(lost: boolean): void {
if (this.closed) return;
this.closed = true;
+ this.lost = lost;
for (const ack of this.unacknowledged.splice(0)) ack();
- void this.viewer?.close().catch(() => undefined);
+ void this.viewer?.close({ dropped: lost && this.theirs() }).catch(() => undefined);
+ }
+
+ /** Still the view of a person allowed to see this browser: its stream went, not its sign-in. */
+ theirs(): boolean {
+ try { return this.request.isCurrent(); } catch { return false; }
}
}
@@ -266,16 +280,18 @@ export class StreamV2 {
ws.on("pong", () => { alive = true; });
ws.on("message", (data, binary) => session.receive(data, binary, this.#service));
ws.on("error", () => session.kill());
- ws.once("close", () => {
+ // 1006: no close frame came, as when a phone goes to the background or the network drops; a panel that closes says so.
+ ws.once("close", (code) => {
clearInterval(ping);
clearInterval(recheck);
this.#sessions.delete(session);
- session.ended();
+ session.ended(code === ABNORMAL_CLOSE);
});
const params = request.params;
const size = requestedSize(Number(params.get("width")), Number(params.get("height")));
const options: ViewerOptions = {
owner: request.owner,
+ ...(request.person ? { person: request.person } : {}),
canOperate: request.canOperate,
maxWidth: intParam(params, "maxWidth", 1280, FRAME_CAP_LIMITS.maxWidth),
maxHeight: intParam(params, "maxHeight", 800, FRAME_CAP_LIMITS.maxHeight),
@@ -287,7 +303,7 @@ export class StreamV2 {
};
try {
const viewer = await this.#service.attachViewer(request.target, options, (output) => session.push(output));
- if (session.closed || session.closing) await viewer.close();
+ if (session.closed || session.closing) await viewer.close({ dropped: session.lost && session.theirs() });
else session.attached(viewer, this.#service);
} catch (error) {
if (error instanceof BrowserHostError) session.close(STREAM_CLOSE.hostSetup, JSON.stringify({ need: error.kind, command: SETUP_COMMAND }));
diff --git a/server/index.ts b/server/index.ts
index ece0b882f6..7161a045fd 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12812,7 +12812,7 @@ ROUTES.push(createStatusRoutes({
ROUTES.push(desktopViewer.route);
ROUTES.push(createBrowserViewerRoutes({
- upgrades, viewers: browserLive, dataDir: DATA_DIR,
+ upgrades, viewers: browserLive, dataDir: DATA_DIR, person: (auth) => (auth.kind === "session" ? actorKey(auth) : "local-owner"),
audience: (auth, threadId) => teamHost.viewerBrowserAudience({ threadId, sees: (id) => visibleTo(viewerFor(auth)).thread(id), person: auth.kind === "session" ? actorKey(auth) : null }),
browser: async (botId, audience) => {
const bot = store.bot(botId);
diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.ts
index 596a4d830e..35c32644a5 100644
--- a/server/routes/browser-viewers.test.ts
+++ b/server/routes/browser-viewers.test.ts
@@ -52,6 +52,8 @@ interface Fixture {
pickerChecks: number;
/** The v1 views opened, by the view each asked to carry on from. */
resumes: Array<string | null | undefined>;
+ /** The person each v1 view was opened for. */
+ people: Array<string | undefined>;
/** The panel size each v1 view opened at. */
sizes: Array<{ width: number; height: number } | null | undefined>;
/** Whose browser each view was opened on, and each check that the view still shows it. */
@@ -76,7 +78,7 @@ async function serve({ attach, current = () => true, download, audience = () =>
download?: (id: string) => Download | undefined;
audience?: (threadId: string | null) => Audience | null;
} = {}): Promise<Fixture> {
- const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], sizes: [], opened: [], checked: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;
+ const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], people: [], sizes: [], opened: [], checked: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;
folders.push(fixture.dataDir);
const viewer = { id: "viewer", input: async (message: unknown) => { fixture.inputs.push(message); }, close: async () => {} } as unknown as Viewer;
const service = {
@@ -92,9 +94,11 @@ async function serve({ attach, current = () => true, download, audience = () =>
const deps: BrowserViewerRouteDeps = {
upgrades,
dataDir: fixture.dataDir,
+ person: (auth) => (auth.kind === "session" ? `person-of-${auth.session.id}` : "local-owner"),
viewers: {
open: async (options) => {
fixture.resumes.push(options.resume);
+ fixture.people.push(options.person);
fixture.sizes.push(options.size);
fixture.isCurrent = options.isCurrent;
options.res.writeHead(204).end();
@@ -204,7 +208,7 @@ describe("the v2 stream", () => {
expect(texts).toEqual([{ type: "viewport", width: 1280, height: 800, setting: { mode: "fill" }, zoom: 1 }]);
expect(fixture.inputs).toEqual(interactive ? [...mutations, null] : []);
expect(fixture.attachments).toEqual([{
- owner: "local-owner", canOperate: interactive, maxWidth: 1280, maxHeight: 800, quality: 70, pace: "hi", authPrompts: true, pagePopups: true,
+ owner: "local-owner", person: "local-owner", canOperate: interactive, maxWidth: 1280, maxHeight: 800, quality: 70, pace: "hi", authPrompts: true, pagePopups: true,
...(interactive ? { size: { width: 1600, height: 1000 } } : {}),
}]);
});
@@ -260,6 +264,25 @@ describe("the v2 stream", () => {
expect(fixture.inputs).toEqual([{ type: "takeControl" }]);
});
+ it("ends a hold at once when the panel closes its socket, and waits the grace when the connection breaks", async () => {
+ const closes: Array<{ dropped?: boolean } | undefined> = [];
+ const fixture = await serve({
+ attach: async () => ({ id: "viewer", input: async () => {}, close: async (options?: { dropped?: boolean }) => { closes.push(options); } }) as unknown as Viewer,
+ });
+ const panel = new WebSocket(`ws://${fixture.origin}/api/bots/pepper/browser/stream`);
+ await new Promise((resolve) => panel.addEventListener("open", resolve));
+ await until(() => fixture.attachments.length === 1);
+ panel.close();
+ await until(() => closes.length === 1);
+ expect(closes[0]).toEqual({ dropped: false });
+ const phone = await stubbornStream(fixture);
+ await until(() => fixture.attachments.length === 2);
+ // No close frame: a phone in the background or a network that dropped.
+ phone.destroy();
+ await until(() => closes.length === 2);
+ expect(closes[1]).toEqual({ dropped: true });
+ });
+
it("checks each message as each v1 action is checked: a person who may no longer see the bot is cut off at once", async () => {
let current = true;
const fixture = await serve({ current: () => current });
@@ -297,11 +320,12 @@ describe("the v2 stream", () => {
});
describe("the v1 live view", () => {
- it("passes on the view a reconnecting panel had, so its dropped hold can be returned", async () => {
+ it("passes on the view a reconnecting panel had, and the person watching, whose hold every view of theirs shares", async () => {
const fixture = await serve();
expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/live?resume=old-viewer`)).status).toBe(204);
expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/live`)).status).toBe(204);
expect(fixture.resumes).toEqual(["old-viewer", null]);
+ expect(fixture.people).toEqual(["local-owner", "local-owner"]);
});
it("opens the view at the panel's size, and leaves a collapsed or missing one to the page", async () => {
diff --git a/server/routes/browser-viewers.ts b/server/routes/browser-viewers.ts
index 3657b448f0..9521e866db 100644
--- a/server/routes/browser-viewers.ts
+++ b/server/routes/browser-viewers.ts
@@ -33,6 +33,8 @@ type Failure = { status: number; error: string };
export interface BrowserViewerRouteDeps {
upgrades: Upgrades;
viewers: Pick<LiveRouter, "open" | "action" | "stream" | "fileChooserOffered" | "answerFileChooser" | "download">;
+ /** Who is watching, as a hold of the browser knows them: every view and device of one person shares their hold. */
+ person(auth: RequestAuth): string;
/** Whose browser of the bot this person's view shows (`threadId` names the conversation they look at); null when
* they may not see that conversation. */
audience(auth: RequestAuth, threadId: string | null): Audience | null;
@@ -123,13 +125,14 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHa
const failure = await deps.authorize(req, auth);
if (failure) return json(res, failure.status, { error: failure.error });
const owner = ownerOf(auth);
+ const person = deps.person(auth);
const isCurrent = () => deps.audience(auth, threadId) === audience && deps.current(browser.botId, browser.session, auth, audience);
if (live) {
if (method === "GET" && live[2] === "live") {
req.socket.setTimeout(0);
const size = requestedSize(Number(url.searchParams.get("width")), Number(url.searchParams.get("height")));
- return await deps.viewers.open({ botId: browser.botId, session: browser.session, spec: browser.spec, owner, isCurrent, res, resume: url.searchParams.get("resume"), size });
+ return await deps.viewers.open({ botId: browser.botId, session: browser.session, spec: browser.spec, owner, person, isCurrent, res, resume: url.searchParams.get("resume"), size });
}
if (method === "POST" && live[2] === "action") {
const body = await readBody(req, 32_768);
@@ -147,7 +150,7 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHa
if (!isCurrent()) return json(res, 409, { error: "This browser session changed. Reopen the browser panel." });
pending.release();
const opened = deps.viewers.stream({
- session: browser.session, spec: browser.spec, botId: browser.botId, owner,
+ session: browser.session, spec: browser.spec, botId: browser.botId, owner, person,
canOperate: url.searchParams.get("interactive") !== "false",
params: url.searchParams, req, socket: pending.socket, head: pending.head,
isCurrent, restartRefusal: () => deps.restartRefusal(browser.session),
diff --git a/src/components/BrowserPanel.test.ts b/src/components/BrowserPanel.test.ts
index f4085f18ce..b8fa8b3f03 100644
--- a/src/components/BrowserPanel.test.ts
+++ b/src/components/BrowserPanel.test.ts
@@ -273,6 +273,29 @@ describe("who holds the browser", () => {
expect(socket.sent.at(-1)).toEqual({ type: "releaseControl" });
});
+ it("says what keeping the browser means while the person has it", async () => {
+ const socket = await streaming("agent");
+ await act(async () => pill().click());
+ await act(async () => socket.control("you"));
+ await flush();
+ expect(pill().title).toBe(t("browser.control.keptHint", { name: "Pepper" }));
+ expect(pill().title).toContain("5 minutes");
+ });
+
+ it("shows the person their hold from another of their views, and hands it back from here", async () => {
+ const socket = await streaming("agent");
+ await act(async () => socket.control("agent", { owned: true }));
+ await flush();
+ expect(pill().dataset.pill).toBe("held");
+ expect(pill().textContent).toContain("Pepper is paused for you");
+ expect(pill().textContent).toContain(t("browser.control.handBack"));
+ expect(pill().disabled).toBe(false);
+ expect(host.textContent).not.toContain(BROWSER_HELD_ELSEWHERE);
+ await act(async () => pill().click());
+ await flush();
+ expect(socket.sent).toEqual([{ type: "releaseControl" }]);
+ });
+
it("takes the browser on the first click and then sends that click, once", async () => {
const socket = await streaming("unclaimed");
const canvas = host.querySelector("canvas")!;
diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsx
index 388cc51c7e..e5f674af70 100644
--- a/src/components/BrowserPanel.tsx
+++ b/src/components/BrowserPanel.tsx
@@ -34,8 +34,8 @@ function tabsOf(value: unknown): BrowserTab[] {
/**
* A bot's browser: the page fills the panel on either engine, streamed over the v2 WebSocket when the new engine runs
- * it, else over the v1 live view. Security: a new connection never silently restores permission to type and never
- * replays old input. Only the server returns a hold, and only to this panel's reconnect after its own v1 stream dropped.
+ * it, else over the v1 live view. Security: a new connection never replays old input. Only the server gives this view a
+ * hold: one of the same person's, when none of their views uses it or when they take it over here.
*/
export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserSignIn; page?: BrowserPage }) {
const { state } = useStore();
@@ -137,6 +137,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
const created = createBrowserControl({
transport,
owned: () => controlRef.current?.controller === "you",
+ mine: () => controlRef.current?.owned === true,
onTakeStatus: setTakeStatus,
onError: setError,
onHalted: () => setError(t("browser.input.tooSlow")),
@@ -276,6 +277,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
connected={connected}
control={control}
takeStatus={takeStatus}
+ hint={t(kept || signInOpen ? "browser.control.keptHint" : "browser.control.yoursHint", { name: bot.name })}
commandsReady={commandsReady}
profileName={profileName}
fullscreen={fullscreen}
diff --git a/src/components/browser/ChromeRow.tsx b/src/components/browser/ChromeRow.tsx
index dd752bca01..fed40f7a56 100644
--- a/src/components/browser/ChromeRow.tsx
+++ b/src/components/browser/ChromeRow.tsx
@@ -24,7 +24,7 @@ export interface BrowserNav {
const button = "rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink disabled:cursor-not-allowed disabled:opacity-40";
-export type PillState = "connecting" | "watching" | "bot" | "yours" | "elsewhere" | "taking" | "waiting";
+export type PillState = "connecting" | "watching" | "bot" | "yours" | "held" | "elsewhere" | "taking" | "waiting";
/** What the pill says: who has the browser now, from this viewer's side. */
export function controlPill(connected: boolean, control: PreviewStreamControl | null, takeStatus: BrowserTakeStatus): PillState {
@@ -32,6 +32,8 @@ export function controlPill(connected: boolean, control: PreviewStreamControl |
if (takeStatus === "pending") return "taking";
if (takeStatus === "slow") return "waiting";
if (control.controller === "you") return "yours";
+ // The person's hold, used from another view of theirs or not granted yet: they can hand it back from here.
+ if (control.owned) return "held";
if (control.controller === "another-viewer") return "elsewhere";
return control.controller === "agent" ? "bot" : "watching";
}
@@ -41,6 +43,7 @@ const PILL_TEXT: Record<PillState, (bot: string) => string> = {
watching: () => "Watching",
bot: (bot) => `${bot} has control`,
yours: () => "You have control",
+ held: (bot) => `${bot} is paused for you`,
elsewhere: () => "Held on another device",
taking: () => "Taking control…",
waiting: (bot) => t("browser.control.waiting", { name: bot }),
@@ -53,6 +56,8 @@ export const ChromeRow = forwardRef<HTMLInputElement, {
connected: boolean;
control: PreviewStreamControl | null;
takeStatus: BrowserTakeStatus;
+ /** What holding the browser means for the bot, while this view has control. */
+ hint?: string;
/** Toolbar commands are open while connected and the browser is not held on another device. */
commandsReady: boolean;
profileName: string;
@@ -73,6 +78,8 @@ export const ChromeRow = forwardRef<HTMLInputElement, {
const [editing, setEditing] = useState(false);
const pill = controlPill(connected, control, takeStatus);
const yours = pill === "yours";
+ // Whenever the person holds the browser, from this view or another, the pill hands it back.
+ const handsBack = yours || pill === "held";
const shown = nav.url === "about:blank" ? "" : nav.url;
return (
<div className="shrink-0 border-b border-hairline/40">
@@ -89,17 +96,18 @@ export const ChromeRow = forwardRef<HTMLInputElement, {
</div>
<button
type="button"
- aria-pressed={yours}
- aria-label={yours ? `${PILL_TEXT[pill](botName)}. ${t("browser.control.handBack")}` : `${PILL_TEXT[pill](botName)}. ${t("browser.control.take")}`}
- title={yours ? t("browser.control.handBack") : t("browser.control.take")}
+ aria-pressed={handsBack}
+ aria-label={`${PILL_TEXT[pill](botName)}. ${t(handsBack ? "browser.control.handBack" : "browser.control.take")}`}
+ aria-description={yours ? props.hint : undefined}
+ title={yours && props.hint ? props.hint : t(handsBack ? "browser.control.handBack" : "browser.control.take")}
disabled={!connected || pill === "elsewhere" || pill === "connecting" || pill === "taking" || pill === "waiting"}
- onClick={yours ? props.onHandBack : props.onTake}
- className={`flex max-w-56 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border px-2.5 py-1 text-[11px] disabled:cursor-default ${yours ? "border-accent-border bg-accent/15 text-accent-text" : "border-hairline text-ink-secondary hover:bg-inset hover:text-ink"}`}
+ onClick={handsBack ? props.onHandBack : props.onTake}
+ className={`flex max-w-56 shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border px-2.5 py-1 text-[11px] disabled:cursor-default ${handsBack ? "border-accent-border bg-accent/15 text-accent-text" : "border-hairline text-ink-secondary hover:bg-inset hover:text-ink"}`}
data-pill={pill}
>
{pill === "taking" || pill === "waiting" || pill === "connecting" ? <Loader2 size={12} className="shrink-0 animate-spin" aria-hidden="true" /> : <Hand size={12} className="shrink-0" aria-hidden="true" />}
<span className="truncate">{PILL_TEXT[pill](botName)}</span>
- {pill === "bot" || pill === "watching" ? <span className="shrink-0 text-ink">· {t("browser.control.take")}</span> : yours ? <span className="shrink-0">· {t("browser.control.handBack")}</span> : null}
+ {pill === "bot" || pill === "watching" ? <span className="shrink-0 text-ink">· {t("browser.control.take")}</span> : handsBack ? <span className="shrink-0">· {t("browser.control.handBack")}</span> : null}
</button>
<button className={button} title={props.maximized ? "Restore size" : "Maximize"} aria-label={props.maximized ? "Restore size" : "Maximize"} onClick={props.onMaximize}>{props.maximized ? <Shrink size={15} /> : <Expand size={15} />}</button>
<button className={button} title={props.fullscreen ? "Exit full screen" : "Full screen"} aria-label={props.fullscreen ? "Exit full screen" : "Full screen"} onClick={props.onFullscreen}>{props.fullscreen ? <Minimize2 size={15} /> : <Maximize2 size={15} />}</button>
diff --git a/src/components/browser/StreamSurface.test.ts b/src/components/browser/StreamSurface.test.ts
index 4f3b3d3776..0423ef56a8 100644
--- a/src/components/browser/StreamSurface.test.ts
+++ b/src/components/browser/StreamSurface.test.ts
@@ -272,6 +272,7 @@ describe("who has the browser", () => {
expect(controlPill(true, control("agent"), "")).toBe("bot");
expect(controlPill(true, control("you"), "")).toBe("yours");
expect(controlPill(true, control("another-viewer"), "")).toBe("elsewhere");
+ expect(controlPill(true, control("agent", { owned: true }), "")).toBe("held");
expect(controlPill(true, control("agent"), "pending")).toBe("taking");
expect(controlPill(true, control("agent"), "slow")).toBe("waiting");
});
diff --git a/src/lib/browser-control.test.ts b/src/lib/browser-control.test.ts
index 4485518f49..c98e32e678 100644
--- a/src/lib/browser-control.test.ts
+++ b/src/lib/browser-control.test.ts
@@ -431,6 +431,17 @@ describe("holding the browser on purpose", () => {
expect(h.transport.release).toHaveBeenCalledOnce();
});
+ it("hands back at once a hold the person has from another view, which this one never took", async () => {
+ const h = harness();
+ h.control.handBack();
+ await settle();
+ expect(h.transport.release).not.toHaveBeenCalled();
+ const mine = createBrowserControl({ ...h.options, mine: () => true });
+ mine.handBack();
+ await settle();
+ expect(h.transport.release).toHaveBeenCalledOnce();
+ });
+
it("after a hand-back from elsewhere, the next interaction takes control again", async () => {
const h = harness();
h.interact(press, lift);
diff --git a/src/lib/browser-control.ts b/src/lib/browser-control.ts
index 0337d67e13..0f7b7016e0 100644
--- a/src/lib/browser-control.ts
+++ b/src/lib/browser-control.ts
@@ -52,7 +52,10 @@ function heldUntilReleased(input: PreviewStreamInput): boolean {
*/
export function createBrowserControl(options: {
transport: ControlTransport;
+ /** This view's input runs now. */
owned: () => boolean;
+ /** The person holds the browser, from this view or another of theirs. */
+ mine?: () => boolean;
onTakeStatus: (status: BrowserTakeStatus) => void;
onError: (message: string) => void;
onHalted: () => void;
@@ -183,7 +186,13 @@ export function createBrowserControl(options: {
kept = on;
if (!on) arm();
},
- handBack() { if (!closed) { soon = true; arm(); } },
+ handBack() {
+ if (closed) return;
+ // Their hold is used from another view of theirs: this one has nothing of its own to send first.
+ if (state === "bot" && !options.owned() && options.mine?.()) { release(); return; }
+ soon = true;
+ arm();
+ },
hold(on: boolean) {
if (closed || pinned === on) return;
pinned = on;
diff --git a/src/lib/browser-stream-client.ts b/src/lib/browser-stream-client.ts
index 5ad2b28239..09e0163091 100644
--- a/src/lib/browser-stream-client.ts
+++ b/src/lib/browser-stream-client.ts
@@ -62,6 +62,8 @@ export interface PreviewStreamControl {
};
/** The bot's work outlasted the person's takeover and was cut off. */
readonly stale?: boolean;
+ /** The person watching holds the browser, from this view or another of theirs: they may hand it back from here. */
+ readonly owned?: boolean;
}
/** Status line shown above a viewer; `null` control means the socket is not connected. */
@@ -265,9 +267,11 @@ export interface PreviewStreamClient {
readonly stop: () => void;
}
-/** A viewer that may operate sizes the page while it watches, and may restart or wake it; everything else needs control. */
+/** A viewer that may operate sizes the page while it watches, and may restart or wake it; the person holding the browser
+ * hands it back from any of their views; everything else needs control. */
const allowed = (input: PreviewStreamInput, control: PreviewStreamControl): boolean =>
- input.type === "takeControl" || input.type === "resize" || input.type === "frameCap" || input.type === "restart" || input.type === "wake" || control.controller === "you";
+ input.type === "takeControl" || input.type === "resize" || input.type === "frameCap" || input.type === "restart" || input.type === "wake"
+ || (input.type === "releaseControl" && control.owned === true) || control.controller === "you";
const ACK_MESSAGE = JSON.stringify({ type: "ack" });
export function createPreviewStreamClient(
@@ -335,6 +339,7 @@ export function createPreviewStreamClient(
generation,
dialog,
stale,
+ owned,
text,
id,
fileName,
@@ -412,6 +417,7 @@ export function createPreviewStreamClient(
generation,
dialog,
...(stale === true ? { stale: true } : {}),
+ ...(owned === true ? { owned: true } : {}),
};
const first = control === null;
control = nextControl;
diff --git a/src/lib/browser-stream-v1.test.ts b/src/lib/browser-stream-v1.test.ts
index dc0f8f8928..01ee727e01 100644
--- a/src/lib/browser-stream-v1.test.ts
+++ b/src/lib/browser-stream-v1.test.ts
@@ -74,10 +74,11 @@ describe("the v1 view in the stream's words", () => {
}
});
- it("names who holds the browser as v2 does", () => {
- expect(liveControl({ held: true, owned: true, controlling: true }, 3)).toEqual({ canOperate: true, controller: "you", generation: 3, dialog: null });
- expect(liveControl({ held: true, owned: true, controlling: false }, 1).controller).toBe("agent");
+ it("names who holds the browser as v2 does, and that the person holds it from another view of theirs", () => {
+ expect(liveControl({ held: true, owned: true, controlling: true }, 3)).toEqual({ canOperate: true, controller: "you", generation: 3, dialog: null, owned: true });
+ expect(liveControl({ held: true, owned: true, controlling: false }, 1)).toMatchObject({ controller: "agent", owned: true });
expect(liveControl({ held: true, owned: false }, 1).controller).toBe("another-viewer");
+ expect(liveControl({ held: true, owned: false }, 1)).not.toHaveProperty("owned");
expect(liveControl({ held: false }, 1).controller).toBe("unclaimed");
expect(liveControl({ held: true, owned: true, controlling: true, dialog: { type: "confirm", message: "Leave?", defaultValue: "" } }, 1).dialog)
.toEqual({ type: "confirm", message: "Leave?", defaultValue: "" });
diff --git a/src/lib/browser-stream-v1.ts b/src/lib/browser-stream-v1.ts
index a1f50221a1..ad447714b5 100644
--- a/src/lib/browser-stream-v1.ts
+++ b/src/lib/browser-stream-v1.ts
@@ -162,7 +162,7 @@ export function liveControl(value: { held?: unknown; owned?: unknown; controllin
const dialog = value.dialog as { type?: unknown; message?: unknown; defaultValue?: unknown } | null | undefined;
const shown = dialog && typeof dialog.type === "string" && typeof dialog.message === "string" && typeof dialog.defaultValue === "string"
? { type: dialog.type, message: dialog.message, defaultValue: dialog.defaultValue } : null;
- return { canOperate: true, controller, generation, dialog: shown };
+ return { canOperate: true, controller, generation, dialog: shown, ...(value.owned === true ? { owned: true } : {}) };
}
/**
@@ -293,7 +293,7 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEvent
});
listen("control", (data) => {
const next = liveControl(data, generation);
- if (control && next.controller === control.controller && JSON.stringify(next.dialog) === JSON.stringify(control.dialog)) return;
+ if (control && next.controller === control.controller && next.owned === control.owned && JSON.stringify(next.dialog) === JSON.stringify(control.dialog)) return;
control = next.controller === control?.controller ? next : liveControl(data, ++generation);
events.onControl?.(control);
});
diff --git a/src/locales/en.json b/src/locales/en.json
index 05c2297eab..93f419122f 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2947,7 +2947,7 @@
"browser.control.yoursHint": "{name}’s browser tools are paused while you use it. Control goes back to {name} after a few seconds without input.",
"browser.control.waiting": "Waiting for {name} to finish…",
"browser.control.stale": "{name} was busy, so that wasn’t sent. Try again.",
- "browser.control.keptHint": "{name}’s browser tools are paused until you hand back.",
+ "browser.control.keptHint": "{name}’s browser tools are paused until you hand back. Control goes back to {name} by itself after 5 minutes without input, or 2 minutes after you close the browser.",
"browser.control.take": "Take control",
"browser.control.handBack": "Hand back",
"browser.typeSecret": "Type a password or code…",
diff --git a/src/locales/es.json b/src/locales/es.json
index 3c2dd72815..f5850113fa 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -2493,7 +2493,7 @@
"browser.control.yoursHint": "Las herramientas de navegador de {name} están en pausa mientras lo usas. El control vuelve a {name} tras unos segundos sin actividad.",
"browser.control.waiting": "Esperando a que {name} termine…",
"browser.control.stale": "{name} estaba ocupado, así que no se envió. Inténtalo de nuevo.",
- "browser.control.keptHint": "Las herramientas de navegador de {name} están en pausa hasta que le devuelvas el control.",
+ "browser.control.keptHint": "Las herramientas de navegador de {name} están en pausa hasta que le devuelvas el control. El control vuelve solo a {name} tras 5 minutos sin actividad, o 2 minutos después de que cierres el navegador.",
"browser.control.take": "Tomar el control",
"browser.control.handBack": "Devolver el control",
"browser.typeSecret": "Escribe una contraseña o un código…",
diff --git a/src/locales/it.json b/src/locales/it.json
index dfba584c87..2ebbe5756f 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -2686,7 +2686,7 @@
"browser.control.yoursHint": "Gli strumenti del browser di {name} sono in pausa mentre lo usi. Il controllo torna a {name} dopo qualche secondo di inattività.",
"browser.control.waiting": "In attesa che {name} finisca…",
"browser.control.stale": "{name} era occupato, quindi non è stato inviato. Riprova.",
- "browser.control.keptHint": "Gli strumenti del browser di {name} restano in pausa finché non restituisci il controllo.",
+ "browser.control.keptHint": "Gli strumenti del browser di {name} restano in pausa finché non restituisci il controllo. Il controllo torna da solo a {name} dopo 5 minuti di inattività, o 2 minuti dopo che chiudi il browser.",
"browser.control.take": "Prendi il controllo",
"browser.control.handBack": "Restituisci",
"browser.typeSecret": "Digita una password o un codice…",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 5fd2e04493..0c5499d007 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -2816,7 +2816,7 @@
"browser.control.yoursHint": "あなたの操作中は {name} のブラウザーツールが一時停止します。数秒間入力がなければ、操作権は {name} に戻ります。",
"browser.control.waiting": "{name} の操作が終わるのを待っています…",
"browser.control.stale": "{name} が操作中のため、送信できませんでした。もう一度お試しください。",
- "browser.control.keptHint": "{name}のブラウザツールは、操作を戻すまで一時停止しています。",
+ "browser.control.keptHint": "{name}のブラウザツールは、操作を戻すまで一時停止しています。入力がないまま5分たつか、ブラウザを閉じて2分たつと、操作権は自動で{name}に戻ります。",
"browser.control.take": "操作を引き継ぐ",
"browser.control.handBack": "操作を戻す",
"browser.typeSecret": "パスワードまたはコードを入力…",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 73327f89b6..2810628f36 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -2759,7 +2759,7 @@
"browser.control.yoursHint": "Narzędzia przeglądarki bota {name} są wstrzymane, gdy jej używasz. Kontrola wróci do {name} po kilku sekundach bezczynności.",
"browser.control.waiting": "Czekanie, aż {name} zakończy…",
"browser.control.stale": "Nie wysłano tego, bo {name} jest zajęty. Spróbuj ponownie.",
- "browser.control.keptHint": "Narzędzia przeglądarki bota {name} są wstrzymane, dopóki nie oddasz kontroli.",
+ "browser.control.keptHint": "Narzędzia przeglądarki bota {name} są wstrzymane, dopóki nie oddasz kontroli. Kontrola sama wróci do {name} po 5 minutach bezczynności albo 2 minuty po zamknięciu przeglądarki.",
"browser.control.take": "Przejmij kontrolę",
"browser.control.handBack": "Oddaj kontrolę",
"browser.typeSecret": "Wpisz hasło lub kod…",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 6368fbaaf2..67494e0881 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2662,7 +2662,7 @@
"browser.control.yoursHint": "As ferramentas de navegador de {name} ficam pausadas enquanto você usa. O controle volta para {name} depois de alguns segundos sem interação.",
"browser.control.waiting": "Esperando {name} terminar…",
"browser.control.stale": "{name} estava ocupado, então isso não foi enviado. Tente novamente.",
- "browser.control.keptHint": "As ferramentas de navegador de {name} ficam pausadas até você devolver o controle.",
+ "browser.control.keptHint": "As ferramentas de navegador de {name} ficam pausadas até você devolver o controle. O controle volta sozinho para {name} depois de 5 minutos sem interação, ou 2 minutos depois que você fechar o navegador.",
"browser.control.take": "Assumir o controle",
"browser.control.handBack": "Devolver o controle",
"browser.typeSecret": "Digitar uma senha ou código…",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 168f84bb35..bb87ad25cd 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -2786,7 +2786,7 @@
"browser.control.yoursHint": "Инструменты браузера {name} приостановлены, пока вы им пользуетесь. Управление вернётся к {name} через несколько секунд без ввода.",
"browser.control.waiting": "Ожидаем, пока {name} закончит…",
"browser.control.stale": "{name} был занят, поэтому это не отправлено. Попробуйте ещё раз.",
- "browser.control.keptHint": "Инструменты браузера {name} приостановлены, пока вы не вернёте управление.",
+ "browser.control.keptHint": "Инструменты браузера {name} приостановлены, пока вы не вернёте управление. Управление само вернётся к {name} через 5 минут без ввода или через 2 минуты после того, как вы закроете браузер.",
"browser.control.take": "Взять управление",
"browser.control.handBack": "Вернуть управление",
"browser.typeSecret": "Введите пароль или код…",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 4b1880ef2d..56e091d9cd 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -4824,7 +4824,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -15436,7 +15436,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -21650,7 +21650,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -37828,7 +37828,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -42735,7 +42735,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -48146,7 +48146,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -54449,7 +54449,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
@@ -60710,7 +60710,7 @@
"browser.control.yoursHint": "885d6f765308ca994113676f2aa2ff4f3322781640ed412ad19bf972bbd8e9df",
"browser.control.waiting": "6a7a34d4c108e13007baba82886fc89a838e7eca096edca1920eda685ee73144",
"browser.control.stale": "a92ba78900569151aef980e6cb493c1ca4bdff6effb0e697388c9241e6d0cc8c",
- "browser.control.keptHint": "c83eca152b6fb88c4319059708dae1da3537bbe65908250fd9ed18ff58b59a9f",
+ "browser.control.keptHint": "107e9e7abb6ef2ced1ef41437b678f93e5de088cb79d293b2208f25bfdec2d76",
"browser.control.take": "fbf728c3c3bbd9166ea4557fb267479b842217ac50573a3d11ed1b2ce6b354cb",
"browser.control.handBack": "b8f8c1ec2f9aa8078a62a4e3be7af090edf6ed18fca3b49a97693ee7e7e33876",
"browser.typeSecret": "ebfdd1ea18ca82cf67b0a62d7db735a40f88055814337786d728879abf9dd766",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 13c7f16f54..01bba3176b 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -2219,7 +2219,7 @@
"browser.control.yoursHint": "Siz kullanırken {name} adlı botun tarayıcı araçları duraklatılır. Girdi olmadan birkaç saniye geçtikten sonra kontrol tekrar {name} adlı bota geçer.",
"browser.control.waiting": "{name} adlı botun bitirmesi bekleniyor…",
"browser.control.stale": "{name} meşguldü, bu yüzden gönderilmedi. Tekrar deneyin.",
- "browser.control.keptHint": "Siz geri verene kadar {name} adlı botun tarayıcı araçları duraklatıldı.",
+ "browser.control.keptHint": "Siz geri verene kadar {name} adlı botun tarayıcı araçları duraklatıldı. Girdi olmadan 5 dakika geçince veya tarayıcıyı kapattıktan 2 dakika sonra kontrol kendiliğinden {name} adlı bota geçer.",
"browser.control.take": "Kontrolü devral",
"browser.control.handBack": "Geri ver",
"browser.typeSecret": "Bir parola veya kod yazın…",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 81ff0124c2..c468e906b7 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -2219,7 +2219,7 @@
"browser.control.yoursHint": "Các công cụ trình duyệt của {name} bị tạm dừng khi bạn sử dụng. Quyền điều khiển sẽ quay lại với {name} sau vài giây không có hoạt động nhập.",
"browser.control.waiting": "Đang chờ {name} hoàn tất…",
"browser.control.stale": "{name} đang bận nên yêu cầu chưa được gửi. Vui lòng thử lại.",
- "browser.control.keptHint": "Các công cụ trình duyệt của {name} bị tạm dừng cho đến khi bạn trao lại quyền.",
+ "browser.control.keptHint": "Các công cụ trình duyệt của {name} bị tạm dừng cho đến khi bạn trao lại quyền. Quyền điều khiển sẽ tự quay lại với {name} sau 5 phút không có hoạt động nhập, hoặc 2 phút sau khi bạn đóng trình duyệt.",
"browser.control.take": "Nhận quyền điều khiển",
"browser.control.handBack": "Trao lại quyền",
"browser.typeSecret": "Nhập mật khẩu hoặc mã…",