Skip to content

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

A panel's Take control names the desktop it shows, and each panel or viewer window gives back only the hold its own take owns

Xiaolei Shi5e972efad4c7
diff --git a/src/App.tsx b/src/App.tsx
index 64fd708794..54a06dded6 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -15,6 +15,7 @@ import { LiveCallHost } from "@/components/LiveCallHost";
import { ThreadRefsProvider } from "@/components/ThreadRefs";
import { initAnalytics } from "@/lib/analytics";
import { parseComputerHelp } from "@/lib/computer-control";
+import { viewerClosedRelease } from "@/components/computer-takeover";
import { Sidebar } from "@/components/Sidebar";
import { ChatView } from "@/components/ChatView";
import { GroupView } from "@/components/GroupView";
@@ -300,11 +301,11 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
useEffect(() => {
return window.ogb?.desktopViewer?.onState((viewer) => {
if (viewer.open || !viewer.contextId) return;
- const botId = viewer.contextId;
- void fetch(`/api/bots/${botId}/computer/control`, {
+ const botId = viewer.contextId, release = viewerClosedRelease(botId);
+ if (release) void fetch(`/api/bots/${botId}/computer/control`, {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ action: "release" }),
+ body: JSON.stringify(release),
})
.then((res) => (res.ok ? res.json() : null))
.then((snap) => {
diff --git a/src/App.viewer-close.test.ts b/src/App.viewer-close.test.ts
new file mode 100644
index 0000000000..7671eff8b2
--- /dev/null
+++ b/src/App.viewer-close.test.ts
@@ -0,0 +1,37 @@
+// @vitest-environment happy-dom
+import { createElement, type ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+import { initialState } from "./state/store";
+
+vi.mock("./state/store", async (original) => ({
+ ...await original<typeof import("./state/store")>(),
+ StoreProvider: ({ children }: { children: ReactNode }) => children,
+ useStore: () => ({ state: { ...initialState, connected: true, hydrated: true }, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} }),
+}));
+vi.mock("./lib/analytics", () => ({ initAnalytics: () => {}, track: () => {}, emailGateDone: () => true }));
+const { default: App } = await import("./App");
+
+afterEach(() => { vi.unstubAllGlobals(); });
+
+it.each([
+ { row: "the app", remote: false },
+ { row: "the remote client", remote: true },
+])("closing a viewer window no open recorded in $row posts its close and gives back no one's control", ({ remote }) => {
+ const posts: Array<{ url: string; body: string }> = [];
+ vi.stubGlobal("fetch", (url: string, init?: RequestInit) => { posts.push({ url, body: String(init?.body) }); return new Promise(() => {}); });
+ let closed: (viewer: { open: boolean; contextId: string | null }) => void = () => {};
+ vi.stubGlobal("ogb", { ...(remote ? { remoteClient: { active: true } } : {}), desktopViewer: { onState: (listener: typeof closed) => { closed = listener; return () => {}; } } });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ try {
+ flushSync(() => root.render(createElement(App)));
+ closed({ open: false, contextId: "scout" });
+ expect(posts.filter((post) => post.url.startsWith("/api/bots/scout/"))).toEqual([{ url: "/api/bots/scout/computer/viewer-close", body: "{}" }]);
+ } finally {
+ root.unmount();
+ container.remove();
+ }
+});
diff --git a/src/components/ComputerPanel.takeover.test.ts b/src/components/ComputerPanel.takeover.test.ts
index 9dd81603ba..bc00beb2c1 100644
--- a/src/components/ComputerPanel.takeover.test.ts
+++ b/src/components/ComputerPanel.takeover.test.ts
@@ -5,6 +5,7 @@ import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Action, AppState, Bot, InstanceInfo } from "@/state/store";
+import { viewerClosedRelease } from "./computer-takeover";
const fixture = vi.hoisted(() => ({
held: false,
@@ -13,6 +14,7 @@ const fixture = vi.hoisted(() => ({
/** True plays a take the server turns down. */
refuse: false,
controls: [] as Array<{ action?: string; controlLeaseId?: string }>,
+ controlPaths: [] as string[],
posts: [] as string[],
beacons: [] as Array<{ url: string; body: Record<string, unknown>; keepalive: boolean }>,
live: null as null | { target: string; expanded: boolean; onUnreachable: () => void },
@@ -51,6 +53,7 @@ vi.mock("@/state/store", async (importOriginal) => ({
const route = path.split("?")[0]!;
if (init?.method === "POST") fixture.posts.push(route);
if (route === "/api/bots/scout/computer/control") {
+ fixture.controlPaths.push(path);
if (init?.method !== "POST") return { held: fixture.held, helpReason: null };
const body = JSON.parse(String(init.body));
fixture.controls.push(body);
@@ -153,6 +156,7 @@ beforeEach(() => {
fixture.owned = true;
fixture.refuse = false;
fixture.controls = [];
+ fixture.controlPaths = [];
fixture.posts = [];
fixture.beacons = [];
fixture.live = null;
@@ -191,20 +195,31 @@ describe("taking control of a Local VM", () => {
expect(liveDesktop()!.dataset.target).toBe(`local/bot-${"a".repeat(64)}`);
expect(window.ogb!.desktopViewer!.open, "nothing may open in another window").not.toHaveBeenCalled();
expect(window.open).not.toHaveBeenCalled();
- expect(fixture.controls).toEqual([{ action: "take", controlLeaseId: expect.stringMatching(/^[0-9a-f]{36}$/) }]);
+ expect(fixture.controls).toEqual([{ action: "take", controlLeaseId: expect.stringMatching(/^[0-9a-f]{36}$/), target: `local/bot-${"a".repeat(64)}` }]);
expect(document.body.textContent).toContain("You're in control");
expect(button("Hand control back")).toBeDefined();
});
- it("hands back at once and returns to watching", async () => {
+ it("hands back the hold it took with its own lease, at once, and returns to watching", async () => {
await open(makeBot({ computer: "vm" }));
await press("Take control");
await press("Hand control back");
- expect(fixture.controls.at(-1)).toEqual({ action: "release" });
+ expect(fixture.controls.at(-1)).toEqual({ action: "release", controlLeaseId: fixture.controls[0]!.controlLeaseId, target: `local/bot-${"a".repeat(64)}` });
expect(liveDesktop()).toBeNull();
expect(button("Take control")).toBeDefined();
});
+ it("hands back a hold another viewer has without a lease, naming the desktop it shows", async () => {
+ fixture.held = true;
+ fixture.owned = false;
+ heldElsewhere(true);
+ await open(makeBot({ computer: "vm" }));
+ await press("Full screen");
+ await shownLive();
+ await press("Hand control back");
+ expect(fixture.controls.at(-1)).toEqual({ action: "release", target: `local/bot-${"a".repeat(64)}` });
+ });
+
it("Full screen only watches: the bot keeps working until the person takes control from there", async () => {
await open(makeBot({ computer: "vm" }));
await press("Full screen");
@@ -336,6 +351,24 @@ describe("taking control of a Local VM", () => {
expect(releases()).toEqual([]);
});
+ it("asks about and takes the conversation's own computer", async () => {
+ await open(makeBot({ computer: "vm" }));
+ await press("Take control");
+ await press("Hand control back");
+ expect(fixture.controlPaths).toHaveLength(3);
+ expect(new Set(fixture.controlPaths)).toEqual(new Set(["/api/bots/scout/computer/control?threadId=thread"]));
+ });
+
+ it("says another viewer has paused the bots while a hold this panel did not take lasts, and still offers the hand-back", async () => {
+ fixture.held = true;
+ fixture.owned = false;
+ heldElsewhere(true);
+ await open(makeBot({ computer: "vm" }));
+ expect(document.body.textContent).toContain("Another viewer has paused bot control on this desktop");
+ expect(document.body.textContent).not.toContain("You're in control");
+ expect(button("Hand control back")).toBeDefined();
+ });
+
it("a hand-back from elsewhere ends the live view once it lasts, and a flicker does not", async () => {
await open(makeBot({ computer: "vm" }));
await press("Take control");
@@ -370,6 +403,7 @@ describe("taking control of other computers", () => {
await press("Take control");
await shownLive();
expect(liveDesktop()!.dataset.target).toBe("vps/scout");
+ expect(fixture.controls[0]).toMatchObject({ action: "take", target: "vps/scout" });
expect(window.ogb!.desktopViewer!.open).not.toHaveBeenCalled();
await press("Hand control back");
expect(fixture.beacons.some((beacon) => beacon.url.startsWith("/api/bots/scout/computer/viewer-close"))).toBe(true);
@@ -382,4 +416,20 @@ describe("taking control of other computers", () => {
expect(fixture.posts).toContain("/api/bots/scout/computer/join");
expect(window.ogb!.desktopViewer!.open).toHaveBeenCalledWith("https://desktop.invalid/scout", "Scout's live desktop", "scout");
});
+
+ it("closing a cloud computer's viewer window gives back the hold its open took, by that lease", async () => {
+ await open(makeBot({ computer: "cloud" }));
+ await press("Take control");
+ expect(viewerClosedRelease("scout")).toEqual({ action: "release", controlLeaseId: fixture.controls[0]!.controlLeaseId });
+ });
+
+ it("a cloud computer's desktop is taken before it opens even while the bot shows a hold another device has elsewhere", async () => {
+ fixture.held = true;
+ heldElsewhere(true);
+ await open(makeBot({ computer: "cloud" }));
+ await press("Full screen");
+ expect(fixture.controls).toEqual([{ action: "take", controlLeaseId: expect.stringMatching(/^[0-9a-f]{36}$/) }]);
+ expect(fixture.controlPaths.at(-1)).toContain("threadId=thread");
+ expect(window.ogb!.desktopViewer!.open).toHaveBeenCalledWith("https://desktop.invalid/scout", "Scout's live desktop", "scout");
+ });
});
diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsx
index 708f50dae9..991d2501d1 100644
--- a/src/components/ComputerPanel.tsx
+++ b/src/components/ComputerPanel.tsx
@@ -630,10 +630,13 @@ export function ComputerPanel({
}, [phase, threadPath, profileBot.busy, livePlace]);
const control = state.computerControl[bot.id] ?? { held: false, helpReason: null };
+ const liveTarget = !computerStatusCurrent ? null
+ : phase === "vm" && vmStatus?.viewer_url && vmStatus.target_key ? viewerTargetId({ key: vmStatus.target_key })
+ : cloudPreviewReady && cloudBackend === "vps" ? `vps/${bot.id}` : null;
const requestControl = useCallback(async (action: ComputerControlAction, controlLeaseId?: string) => {
- const snap = computerControlSnapshotSchema.parse(await api(`/api/bots/${bot.id}/computer/control`, {
+ const snap = computerControlSnapshotSchema.parse(await api(threadPath("computer/control"), {
method: "POST",
- body: JSON.stringify({ action, ...(controlLeaseId ? { controlLeaseId } : {}) }),
+ body: JSON.stringify({ action, ...(controlLeaseId ? { controlLeaseId } : {}), ...(liveTarget ? { target: liveTarget } : {}) }),
}));
dispatch({
type: "computerControl",
@@ -643,10 +646,7 @@ export function ComputerPanel({
help: snap.help,
});
return snap;
- }, [bot.id, dispatch]);
- const liveTarget = !computerStatusCurrent ? null
- : phase === "vm" && vmStatus?.viewer_url && vmStatus.target_key ? viewerTargetId({ key: vmStatus.target_key })
- : cloudPreviewReady && cloudBackend === "vps" ? `vps/${bot.id}` : null;
+ }, [bot.id, dispatch, threadPath, liveTarget]);
const takeover = useComputerTakeover({
botId: bot.id, session: `${viewerConnectionKey}:${panelView}`, held: control.held, request: requestControl,
viewerClose: liveTarget?.startsWith("vps/") ? threadPath("computer/viewer-close") : null,
@@ -805,7 +805,7 @@ export function ComputerPanel({
const signInAsker = signInHelp ? state.bots.find((candidate) => candidate.id === signInHelp.botId)?.name ?? bot.name : bot.name;
useEffect(() => {
let alive = true;
- api(`/api/bots/${bot.id}/computer/control`)
+ api(threadPath("computer/control"))
.then((raw) => {
if (!alive) return;
const snap = computerControlSnapshotSchema.parse(raw);
@@ -822,7 +822,7 @@ export function ComputerPanel({
alive = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [bot.id]);
+ }, [bot.id, threadPath]);
const setNativeBrowserControl = useCallback(async (): Promise<boolean> => true, []);
@@ -871,7 +871,7 @@ export function ComputerPanel({
setError(null);
try {
await openProviderDesktop({
- botId: bot.id, title: t("computer.viewerTitle", { name: bot.name }), held: control.held, request: requestControl,
+ botId: bot.id, title: t("computer.viewerTitle", { name: bot.name }), request: requestControl,
join: (signal) => api(threadPath("computer/join"), { method: "POST", signal: AbortSignal.any([controller.signal, signal]) }),
current: ownsConnection,
});
@@ -1557,7 +1557,7 @@ export function ComputerPanel({
{(cloudPreviewReady || phase === "vm" || currentTeamComputer) && control.held && (
<div className="mt-3 rounded-xl border border-accent/25 bg-accent/10 p-4">
<div className="text-[13px] leading-relaxed text-ink">
- {t("computer.youHaveWheel")}
+ {t(phase === "vm" && !takeover.here ? "canvasComputers.inUseTitle" : "computer.youHaveWheel")}
{cloudPreviewReady && !liveTarget && ` ${t(advanced ? "computer.useOpenDesktop" : "computer.simple.useFullScreen")}`}
</div>
<button
diff --git a/src/components/computer-takeover.test.ts b/src/components/computer-takeover.test.ts
index 8725404e58..6f3104ac10 100644
--- a/src/components/computer-takeover.test.ts
+++ b/src/components/computer-takeover.test.ts
@@ -1,19 +1,22 @@
// @vitest-environment happy-dom
// A provider-hosted desktop opened from plain web lives in its own tab, which the app can only watch from outside.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { openProviderDesktop } from "./computer-takeover";
+import { openProviderDesktop, viewerClosedRelease } from "./computer-takeover";
type FakeTab = { closed: boolean; opener: unknown; location: { replace: ReturnType<typeof vi.fn> }; close: () => void };
let tab: FakeTab;
let requests: Array<{ action: string; lease?: string }>;
+/** Whether a take's lease holds the computer: false while another device's hold sits on it. */
+let owns: boolean;
const request = async (action: "take" | "release", lease?: string) => {
requests.push({ action, lease });
- return { held: action === "take", owned: true };
+ return { held: action === "take", owned: owns };
};
beforeEach(() => {
vi.useFakeTimers();
requests = [];
+ owns = true;
tab = { closed: false, opener: window, location: { replace: vi.fn() }, close: () => { tab.closed = true; } };
vi.stubGlobal("ogb", undefined);
vi.spyOn(window, "open").mockImplementation(() => tab as unknown as Window);
@@ -27,7 +30,7 @@ afterEach(() => {
describe("a provider desktop's own tab", () => {
it("opens inside the click, cut off from the app, and closing it gives the computer back", async () => {
await openProviderDesktop({
- botId: "scout", title: "Scout's live desktop", held: false, request, current: () => true,
+ botId: "scout", title: "Scout's live desktop", request, current: () => true,
join: async () => ({ joinUrl: "https://desktop.invalid/scout" }),
});
expect(window.open).toHaveBeenCalledWith("", "_blank");
@@ -47,7 +50,7 @@ describe("a provider desktop's own tab", () => {
it("a join that fails closes the tab and gives the computer back", async () => {
await expect(openProviderDesktop({
- botId: "scout", title: "Scout's live desktop", held: false, request, current: () => true,
+ botId: "scout", title: "Scout's live desktop", request, current: () => true,
join: async () => { throw new Error("The cloud computer did not answer"); },
})).rejects.toThrow("did not answer");
expect(tab.closed).toBe(true);
@@ -55,13 +58,94 @@ describe("a provider desktop's own tab", () => {
expect(requests[1]!.lease).toBe(requests[0]!.lease);
});
- it("a computer the person already holds is not taken again, nor given back by this tab", async () => {
+ it("a take whose answer is lost is given back with the lease it sent", async () => {
+ const lost = async (action: "take" | "release", lease?: string) => {
+ await request(action, lease);
+ if (action === "take") throw new Error("The connection dropped");
+ return { held: false };
+ };
+ await expect(openProviderDesktop({
+ botId: "scout", title: "Scout's live desktop", request: lost, current: () => true,
+ join: async () => ({ joinUrl: "https://desktop.invalid/scout" }),
+ })).rejects.toThrow("connection dropped");
+ expect(requests.map((entry) => entry.action)).toEqual(["take", "release"]);
+ expect(requests[1]!.lease).toBe(requests[0]!.lease);
+ });
+
+ it("a take the server does not grant opens nothing", async () => {
+ const join = vi.fn(async () => ({ joinUrl: "https://desktop.invalid/scout" }));
+ const refused = async (action: "take" | "release", lease?: string) => {
+ requests.push({ action, lease });
+ return { held: false, owned: false };
+ };
+ await expect(openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request: refused, current: () => true, join }))
+ .rejects.toMatchObject({ key: "computer.err.confirmControl" });
+ expect(join).not.toHaveBeenCalled();
+ expect(tab.location.replace).not.toHaveBeenCalled();
+ expect(tab.closed).toBe(true);
+ });
+
+ it("a computer another device holds is taken with this tab's own lease, and not given back by this tab", async () => {
+ owns = false;
await openProviderDesktop({
- botId: "scout", title: "Scout's live desktop", held: true, request, current: () => true,
+ botId: "scout", title: "Scout's live desktop", request, current: () => true,
join: async () => ({ joinUrl: "https://desktop.invalid/scout" }),
});
+ expect(requests).toEqual([{ action: "take", lease: expect.stringMatching(/^[0-9a-f]{36}$/) }]);
tab.closed = true;
await vi.advanceTimersByTimeAsync(2_000);
- expect(requests).toEqual([]);
+ expect(requests).toHaveLength(1);
+ });
+});
+
+describe("the app's viewer window", () => {
+ it.each([
+ { row: "a provider desktop's open took the hold", opens: [true], lease: 0 },
+ { row: "its open found another device's hold", opens: [false], lease: null },
+ { row: "a reopen found another device's hold after an open that took it", opens: [true, false], lease: 0 },
+ { row: "no open recorded it", opens: [], lease: null },
+ ] as Array<{ row: string; opens: boolean[]; lease: number | null }>)("gives back, when it closes, only a hold its open's take owned: $row", async ({ opens, lease }) => {
+ vi.stubGlobal("ogb", { desktopViewer: { open: vi.fn(async () => true) } });
+ for (const owned of opens) {
+ owns = owned;
+ await openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join: async () => ({ joinUrl: "https://desktop.invalid/scout" }) });
+ }
+ expect(viewerClosedRelease("scout")).toEqual(lease === null ? null : { action: "release", controlLeaseId: requests[lease]!.lease });
+ expect(viewerClosedRelease("scout"), "a close gives its lease back once").toBeNull();
+ });
+
+ it("gives back, after a reload of the page, the hold its open took before it", async () => {
+ vi.stubGlobal("ogb", { desktopViewer: { open: vi.fn(async () => true) } });
+ await openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join: async () => ({ joinUrl: "https://desktop.invalid/scout" }) });
+ vi.resetModules();
+ const reloaded = await import("./computer-takeover");
+ expect(reloaded.viewerClosedRelease("scout")).toEqual({ action: "release", controlLeaseId: requests[0]!.lease });
+ });
+
+ it("gives back, once the reopened viewer closes, the hold of an open a reload of the page cut off during its join", async () => {
+ vi.stubGlobal("ogb", { desktopViewer: { open: vi.fn(async () => true) } });
+ void openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join: () => new Promise(() => {}) });
+ await vi.advanceTimersByTimeAsync(0);
+ vi.resetModules();
+ const reloaded = await import("./computer-takeover");
+ owns = false;
+ await reloaded.openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join: async () => ({ joinUrl: "https://desktop.invalid/scout" }) });
+ expect(reloaded.viewerClosedRelease("scout")).toEqual({ action: "release", controlLeaseId: requests[0]!.lease });
+ });
+
+ it("leaves nothing for a close to give back after an open whose join failed gave its hold back", async () => {
+ vi.stubGlobal("ogb", { desktopViewer: { open: vi.fn(async () => true) } });
+ await expect(openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join: async () => { throw new Error("join failed"); } })).rejects.toThrow("join failed");
+ expect(requests).toEqual([{ action: "take", lease: requests[0]!.lease }, { action: "release", lease: requests[0]!.lease }]);
+ expect(viewerClosedRelease("scout")).toBeNull();
+ });
+
+ it("opens and closes as if nothing were recorded when the page's storage refuses", async () => {
+ const refuses = () => { throw new Error("storage refused"); };
+ vi.stubGlobal("sessionStorage", { getItem: refuses, setItem: refuses, removeItem: refuses });
+ vi.stubGlobal("ogb", { desktopViewer: { open: vi.fn(async () => true) } });
+ await openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join: async () => ({ joinUrl: "https://desktop.invalid/scout" }) });
+ expect(requests.map((entry) => entry.action), "the open went through").toEqual(["take"]);
+ expect(viewerClosedRelease("scout")).toBeNull();
});
});
diff --git a/src/components/computer-takeover.ts b/src/components/computer-takeover.ts
index 61e451bf52..5f6e5636ba 100644
--- a/src/components/computer-takeover.ts
+++ b/src/components/computer-takeover.ts
@@ -17,6 +17,28 @@ const newLeaseId = () => Array.from(crypto.getRandomValues(new Uint8Array(18)),
type Request = (action: "take" | "release", controlLeaseId?: string) => Promise<TakeoverSnapshot>;
+/** Kept in sessionStorage, which a reload of the page keeps, so a viewer still gives back its own hold when a reload came
+ * after its open or cut that open off. */
+const viewerLeaseKey = (botId: string) => `openmausbot.viewer-lease.${botId}`;
+function recordViewerLease(botId: string, lease: string): void {
+ try { sessionStorage.setItem(viewerLeaseKey(botId), lease); } catch { /* no storage: no record */ }
+}
+function forgetViewerLease(botId: string, lease: string): void {
+ try {
+ if (sessionStorage.getItem(viewerLeaseKey(botId)) === lease) sessionStorage.removeItem(viewerLeaseKey(botId));
+ } catch { /* no storage: no record */ }
+}
+/** What the app's viewer window gives back when it closes: only a hold its open's take owned, by that take's lease, else nothing,
+ * so no one else's hold goes. */
+export function viewerClosedRelease(botId: string): { action: "release"; controlLeaseId: string } | null {
+ let lease: string | null = null;
+ try {
+ lease = sessionStorage.getItem(viewerLeaseKey(botId));
+ sessionStorage.removeItem(viewerLeaseKey(botId));
+ } catch { /* no storage: no record */ }
+ return lease ? { action: "release", controlLeaseId: lease } : null;
+}
+
function releaseWhenClosed(tab: Window, release: () => void): void {
const watch = window.setInterval(() => {
if (!tab.closed) return;
@@ -25,18 +47,18 @@ function releaseWhenClosed(tab: Window, release: () => void): void {
}, 1_000);
}
-/** A provider-hosted desktop (a Boat) ships its own viewer, so it opens in the app's viewer window or its own tab. A
- * stuck join gives the computer back instead of leaving the bot waiting. */
-export async function openProviderDesktop({ botId, title, held, request, join, current }: {
+/** A provider-hosted desktop (a Boat) ships its own viewer, so it opens in the app's viewer window or its own tab. It
+ * always takes the conversation's computer first, as a hold shown on the bot may sit on another computer. A stuck join
+ * gives the computer back instead of leaving the bot waiting. */
+export async function openProviderDesktop({ botId, title, request, join, current }: {
botId: string;
title: string;
- held: boolean;
request: Request;
join: (signal: AbortSignal) => Promise<{ joinUrl?: unknown }>;
/** Still the conversation and computer the person asked for. */
current: () => boolean;
}): Promise<void> {
- let lease: string | null = null;
+ const lease = newLeaseId();
// Plain web opens its blank tab synchronously, inside the user gesture; the packaged app uses the Electron viewer window.
let fallbackTab: Window | null = null;
if (!window.ogb?.desktopViewer && !window.ogb?.openExternal) {
@@ -45,10 +67,10 @@ export async function openProviderDesktop({ botId, title, held, request, join, c
}
const changed = () => new DOMException("The selected conversation changed", "AbortError");
try {
- if (!held) {
- lease = newLeaseId();
- if (!(await request("take", lease)).held) throw new LocalizedPanelError("computer.err.confirmControl");
- }
+ const take = await request("take", lease);
+ if (!take.held) throw new LocalizedPanelError("computer.err.confirmControl");
+ const mine = take.owned ? lease : null;
+ if (mine && window.ogb?.desktopViewer) recordViewerLease(botId, mine);
if (!current()) throw changed();
const { joinUrl } = await join(AbortSignal.timeout(JOIN_TIMEOUT_MS));
const viewerUrl = typeof joinUrl === "string" && joinUrl ? joinUrl : null;
@@ -58,8 +80,7 @@ export async function openProviderDesktop({ botId, title, held, request, join, c
if (!(await window.ogb.desktopViewer.open(viewerUrl, title, botId))) throw new LocalizedPanelError("computer.err.openDesktop");
} else if (fallbackTab) {
fallbackTab.location.replace(viewerUrl);
- const taken = lease;
- if (taken) releaseWhenClosed(fallbackTab, () => void request("release", taken).catch(() => {}));
+ if (mine) releaseWhenClosed(fallbackTab, () => void request("release", mine).catch(() => {}));
} else if (window.ogb?.openExternal) {
if (!(await window.ogb.openExternal(viewerUrl))) throw new LocalizedPanelError("computer.err.openDesktopLink");
} else if (!window.open(viewerUrl, "_blank", "noopener")) {
@@ -67,7 +88,8 @@ export async function openProviderDesktop({ botId, title, held, request, join, c
}
} catch (error) {
fallbackTab?.close();
- if (lease) await request("release", lease).catch(() => {});
+ forgetViewerLease(botId, lease);
+ await request("release", lease).catch(() => {});
throw error;
}
}
@@ -121,13 +143,15 @@ export function useComputerTakeover({ botId, session, held, request, viewerClose
setExpanded(expand);
}, [request]);
+ /** A hold this view took is found by its lease wherever it sits; without one, this hands back another viewer's hold. */
const handBack = useCallback(async () => {
- const close = lease.current?.viewerClose ?? closeRef.current;
+ const mine = lease.current;
+ const close = mine?.viewerClose ?? closeRef.current;
lease.current = null;
end();
setHandingBack(true);
try {
- await request("release");
+ await request("release", mine?.id);
} finally {
setHandingBack(false);
if (close) post(close, {});
diff --git a/src/components/remote-desktop-panel.open.test.ts b/src/components/remote-desktop-panel.open.test.ts
new file mode 100644
index 0000000000..334be3d1fb
--- /dev/null
+++ b/src/components/remote-desktop-panel.open.test.ts
@@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+// The remote client's Take control: the real panel and its control requests, a stand-in for the app's viewer window.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import type { AppState, Bot, InstanceInfo } from "@/state/store";
+
+const fixture = vi.hoisted(() => ({ owned: true, controls: [] as Array<{ action: string; controlLeaseId?: string }> }));
+vi.mock("./DesktopCapabilities", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),
+ useCaptionChrome: () => ({ padClass: undefined }),
+}));
+vi.mock("@/lib/page-visible", () => ({ usePageVisible: () => false }));
+vi.mock("./BrowserPanel", () => ({ BrowserPanel: () => null }));
+vi.mock("./RoutinesPage", () => ({ RoutineEditor: () => null }));
+vi.mock("@/state/store", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@/state/store")>(),
+ api: async (path: string, init?: RequestInit) => {
+ if (path === "/api/bots/scout/computer/control") {
+ const body = JSON.parse(String(init?.body));
+ fixture.controls.push(body);
+ return body.action === "take" ? { held: true, helpReason: null, owned: fixture.owned } : { held: false, helpReason: null };
+ }
+ if (path === "/api/bots/scout/computer/join") return { joinUrl: "https://desktop.invalid/scout" };
+ return {};
+ },
+}));
+
+const { RemoteDesktopPanel } = await import("./remote-desktop-panel");
+const { viewerClosedRelease } = await import("./computer-takeover");
+const { BotEditorStore, initialState } = await import("@/state/store");
+
+const engine = {
+ instanceId: "claude", driverKind: "claudeAgent", displayName: "claude", access: "subscription",
+ snapshot: { state: "available", version: "1", authenticated: true },
+ models: { default: "m", options: [{ id: "m", label: "M" }] },
+ capabilities: { computerMcp: true, browserMcp: true },
+} as InstanceInfo;
+const bot = {
+ id: "scout", threadId: "thread", name: "Scout", title: "", description: "", color: "green",
+ notifications: true, unread: false, busy: false, computer: "cloud", messages: [],
+ modelSelection: { instanceId: "claude", model: "m" },
+ tasks: [{ threadId: "thread", title: "Thread", createdAt: 1, approvalMode: "ask" }],
+} as unknown as Bot;
+let root: Root | null = null;
+
+beforeEach(() => {
+ fixture.controls = [];
+ viewerClosedRelease("scout");
+});
+afterEach(() => {
+ root?.unmount();
+ root = null;
+ vi.unstubAllGlobals();
+ document.body.innerHTML = "";
+});
+
+it.each([
+ { row: "its open fails", owned: true, opened: false, releases: true, closes: false },
+ { row: "its take found another device's hold", owned: false, opened: true, releases: false, closes: false },
+ { row: "its take owned the hold", owned: true, opened: true, releases: false, closes: true },
+ { row: "its take names the VPS its bot works on", owned: true, opened: true, releases: false, closes: true, vps: true },
+])("the remote panel's Take control gives back only a hold its own take owned, by that take's lease: $row", async ({ owned, opened, releases, closes, vps }) => {
+ fixture.owned = owned;
+ vi.stubGlobal("ogb", { desktopViewer: { open: vi.fn(async () => opened), close: vi.fn(async () => true), onState: () => () => {}, currentState: async () => ({ open: false, contextId: null }) } });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root!.render(createElement(BotEditorStore, { value: {
+ state: { ...initialState, instances: [engine], config: { box: { configured: true } } as AppState["config"] } as AppState,
+ dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {},
+ }, children: createElement(RemoteDesktopPanel, { bot: vps ? { ...bot, cloudBackend: "vps" } : bot }) })));
+ const take = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Take control");
+ expect(take, document.body.textContent ?? "").toBeDefined();
+ flushSync(() => take!.click());
+ await vi.waitFor(() => expect(fixture.controls.length).toBeGreaterThan(0));
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ const lease = fixture.controls[0]!.controlLeaseId;
+ expect(fixture.controls).toEqual([
+ { action: "take", controlLeaseId: expect.stringMatching(/^[0-9a-f]{36}$/), ...(vps ? { target: "vps/scout" } : {}) },
+ ...(releases ? [{ action: "release", controlLeaseId: lease }] : []),
+ ]);
+ expect(viewerClosedRelease("scout")).toEqual(closes ? { action: "release", controlLeaseId: lease } : null);
+});
diff --git a/src/components/remote-desktop-panel.tsx b/src/components/remote-desktop-panel.tsx
index fa84e9a229..28b815164f 100644
--- a/src/components/remote-desktop-panel.tsx
+++ b/src/components/remote-desktop-panel.tsx
@@ -14,7 +14,8 @@ import { releaseComputerPanelFocus, takeComputerPanelBrowserView, useComputerPan
import { RoutineEditor } from "./RoutinesPage";
import { BrowserPanel, type BrowserSignIn } from "./BrowserPanel";
import { SignInBanner } from "./SignInRequestCard";
-import { productName } from "@/lib/brand";
+import { openProviderDesktop } from "./computer-takeover";
+import { panelErrorText } from "@/lib/computer-messages";
function viewerAddress(raw: unknown): string {
if (typeof raw !== "string" || !raw) throw new Error(t("remoteDesktop.noLink"));
@@ -175,36 +176,21 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {
const open = async () => {
setPending(true);
setError(null);
- let tookControl = false;
try {
if (!window.ogb?.desktopViewer) throw new Error(t("remoteDesktop.viewerUnavailable"));
- await api(`/api/bots/${bot.id}/computer/control`, {
- method: "POST",
- body: JSON.stringify({ action: "take" }),
- });
- tookControl = true;
- const joined = await api(`/api/bots/${bot.id}/computer/join`, {
- method: "POST",
- body: "{}",
+ await openProviderDesktop({
+ botId: bot.id, title: t("computer.viewerTitle", { name: bot.name }), current: () => true,
+ request: (action, controlLeaseId) => api(`/api/bots/${bot.id}/computer/control`, {
+ method: "POST", body: JSON.stringify({ action, controlLeaseId, ...(bot.cloudBackend === "vps" ? { target: `vps/${bot.id}` } : {}) }),
+ }),
+ join: async (signal) => ({ joinUrl: viewerAddress((await api(`/api/bots/${bot.id}/computer/join`, { method: "POST", body: "{}", signal })).joinUrl) }),
});
- const opened = await window.ogb.desktopViewer.open(
- viewerAddress(joined.joinUrl),
- t("computer.viewerTitle", { name: bot.name }),
- bot.id,
- );
- if (!opened) throw new Error(t("computer.err.openDesktop", { app: productName() }));
} catch (cause) {
- if (tookControl) {
- await api(`/api/bots/${bot.id}/computer/control`, {
- method: "POST",
- body: JSON.stringify({ action: "release" }),
- }).catch(() => {});
- }
await api(`/api/bots/${bot.id}/computer/viewer-close`, {
method: "POST",
body: "{}",
}).catch(() => {});
- setError(cause instanceof Error ? cause.message : String(cause));
+ setError(panelErrorText(cause instanceof Error ? cause : String(cause)));
} finally {
setPending(false);
}