Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(remote-desktop): show a client's Local VM bot on the host's Local VM
AdityaUmaleb5b2091c1c9a
diff --git a/src/components/computer-takeover.test.ts b/src/components/computer-takeover.test.tsindex 6f3104ac10..65ea29b22b 100644--- a/src/components/computer-takeover.test.ts+++ b/src/components/computer-takeover.test.ts@@ -149,3 +149,9 @@ describe("the app's viewer window", () => {expect(viewerClosedRelease("scout")).toBeNull();});});++it("the join is told the lease its take holds, so a Local VM join can name it", async () => {+ const join = vi.fn(async (_signal: AbortSignal, _lease: string) => ({ joinUrl: "https://desktop.invalid/scout" }));+ await openProviderDesktop({ botId: "scout", title: "Scout's live desktop", request, current: () => true, join });+ expect(join).toHaveBeenCalledWith(expect.any(AbortSignal), requests[0]!.lease);+});diff --git a/src/components/computer-takeover.ts b/src/components/computer-takeover.tsindex 5f6e5636ba..978ed25610 100644--- a/src/components/computer-takeover.ts+++ b/src/components/computer-takeover.ts@@ -54,7 +54,8 @@ export async function openProviderDesktop({ botId, title, request, join, currentbotId: string;title: string;request: Request;- join: (signal: AbortSignal) => Promise<{ joinUrl?: unknown }>;+ /** Gets the viewer link; a Local VM's join names the lease its take holds. */+ join: (signal: AbortSignal, controlLeaseId: string) => Promise<{ joinUrl?: unknown }>;/** Still the conversation and computer the person asked for. */current: () => boolean;}): Promise<void> {@@ -72,7 +73,7 @@ export async function openProviderDesktop({ botId, title, request, join, currentconst 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 { joinUrl } = await join(AbortSignal.timeout(JOIN_TIMEOUT_MS), lease);const viewerUrl = typeof joinUrl === "string" && joinUrl ? joinUrl : null;if (!current()) throw changed();if (!viewerUrl) throw new LocalizedPanelError("computer.err.noDesktopLink");diff --git a/src/components/remote-desktop-panel.open.test.ts b/src/components/remote-desktop-panel.open.test.tsindex 334be3d1fb..475f74426d 100644--- a/src/components/remote-desktop-panel.open.test.ts+++ b/src/components/remote-desktop-panel.open.test.ts@@ -6,7 +6,7 @@ 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 }> }));+const fixture = vi.hoisted(() => ({ owned: true, controls: [] as Array<{ action: string; controlLeaseId?: string }>, joins: [] as string[] }));vi.mock("./DesktopCapabilities", async (importOriginal) => ({...await importOriginal<typeof import("./DesktopCapabilities")>(),useCaptionChrome: () => ({ padClass: undefined }),@@ -23,6 +23,10 @@ vi.mock("@/state/store", async (importOriginal) => ({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" };+ if (path.startsWith("/api/bots/scout/local-computer/join?")) {+ fixture.joins.push(path);+ return { joinUrl: "/vps-viewer/relay-1" };+ }return {};},}));@@ -47,6 +51,7 @@ let root: Root | null = null;beforeEach(() => {fixture.controls = [];+ fixture.joins = [];viewerClosedRelease("scout");});afterEach(() => {@@ -83,3 +88,25 @@ it.each([]);expect(viewerClosedRelease("scout")).toEqual(closes ? { action: "release", controlLeaseId: lease } : null);});++it("a client whose host runs the bot on its Local VM takes and opens that desktop, not the cloud computer", async () => {+ fixture.owned = true;+ const open = vi.fn(async () => true);+ vi.stubGlobal("ogb", { desktopViewer: { open, 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: { ...bot, computer: "vm" } }) })));+ expect(document.body.textContent).toContain("Private desktop");+ expect(document.body.textContent).not.toContain("Cloud desktop");+ const take = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Take control");+ flushSync(() => take!.click());+ await vi.waitFor(() => expect(open).toHaveBeenCalled());+ const lease = fixture.controls[0]!.controlLeaseId!;+ expect(fixture.controls).toEqual([{ action: "take", controlLeaseId: expect.stringMatching(/^[0-9a-f]{36}$/) }]);+ expect(fixture.joins).toEqual([`/api/bots/scout/local-computer/join?controlLeaseId=${lease}`]);+ expect(open).toHaveBeenCalledWith(new URL("/vps-viewer/relay-1", window.location.origin).toString(), expect.any(String), "scout");+});diff --git a/src/components/remote-desktop-panel.test.ts b/src/components/remote-desktop-panel.test.tsindex e50761aae8..c6a320fb5d 100644--- a/src/components/remote-desktop-panel.test.ts+++ b/src/components/remote-desktop-panel.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { boatCapableEngine, isActiveTurnRefusal, isRemoteScreenshotContention, remoteScreenshotSource } from "@/lib/remote-desktop";+import { boatCapableEngine, isActiveTurnRefusal, isRemoteScreenshotContention, localVmScreenshotSource, remoteScreenshotSource } from "@/lib/remote-desktop";import type { InstanceInfo } from "@/state/store";import { CLOUD_COMPUTER_BUSY_ERROR } from "../../shared/computer-contention";@@ -45,3 +45,14 @@ describe("remote VPS preview", () => {expect(remoteScreenshotSource(null)).toBeNull();});});++describe("remote Local VM preview", () => {+ it("shows only a PNG or JPEG data URL from the host's Local VM", () => {+ expect(localVmScreenshotSource({ image: "data:image/png;base64,iVBORw0KGgo=" })).toBe("data:image/png;base64,iVBORw0KGgo=");+ expect(localVmScreenshotSource({ image: "data:image/jpeg;base64,/9j/4AAQ" })).toBe("data:image/jpeg;base64,/9j/4AAQ");+ for (const raw of [null, "x", {}, { image: "" }, { image: "data:image/svg+xml;base64,PHN2Zz4=" }, { image: "javascript:alert(1)" },+ { image: "data:image/png;base64,abc\"><" }, { png: "iVBORw0KGgo=", format: "png" }]) {+ expect(localVmScreenshotSource(raw)).toBeNull();+ }+ });+});diff --git a/src/components/remote-desktop-panel.tsx b/src/components/remote-desktop-panel.tsxindex 28b815164f..428d5082b0 100644--- a/src/components/remote-desktop-panel.tsx+++ b/src/components/remote-desktop-panel.tsx@@ -5,7 +5,7 @@ import { CalendarClock, CalendarDays, Globe, ImageOff, Loader2, Monitor, Plus, Ximport { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";import { usePageVisible } from "@/lib/page-visible";-import { isRemoteScreenshotContention, remoteScreenshotSource } from "@/lib/remote-desktop";+import { isRemoteScreenshotContention, localVmScreenshotSource, remoteScreenshotSource } from "@/lib/remote-desktop";import type { Routine } from "@/lib/routines";import { dayName, scheduleLabel } from "@/lib/schedule-label";import { intlLocale, t } from "@/lib/i18n";@@ -77,6 +77,8 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {const previewBusy = useRef(bot.busy);useEffect(() => { previewBusy.current = bot.busy; }, [bot.busy]);const [creatingRoutine, setCreatingRoutine] = useState(false);+ // The host runs this bot on its Local VM: preview, control and viewer all go to that desktop, not the cloud computer.+ const localVm = bot.computer === "vm";const [view, setView] = useState<"desktop" | "browser">(() => takeComputerPanelBrowserView(bot.id) ? "browser" : "desktop");const [signIn, setSignIn] = useState<BrowserSignIn>();const help = state.computerControl[bot.id]?.help ?? null;@@ -103,7 +105,7 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {setFrame(null);setPreviewPending(true);setPreviewUnavailable(false);- }, [bot.id]);+ }, [bot.id, localVm]);useEffect(() => {const viewer = window.ogb?.desktopViewer;@@ -134,11 +136,12 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {requestRunning = true;retryDelay = null;try {- const source = remoteScreenshotSource(await api(`/api/bots/${bot.id}/computer/screenshot`, {+ const shot = await api(`/api/bots/${bot.id}/${localVm ? "local-computer" : "computer"}/screenshot`, {method: "POST",body: "{}",signal: AbortSignal.any([controller.signal, AbortSignal.timeout(90_000)]),- }));+ });+ const source = localVm ? localVmScreenshotSource(shot) : remoteScreenshotSource(shot);if (!controller.signal.aborted && source) {setFrame(source);setPreviewUnavailable(false);@@ -171,19 +174,24 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {controller.abort();window.clearInterval(timer);};- }, [bot.id, pageVisible, viewerOpen, pending, view]);+ }, [bot.id, localVm, pageVisible, viewerOpen, pending, view]);const open = async () => {setPending(true);setError(null);try {if (!window.ogb?.desktopViewer) throw new Error(t("remoteDesktop.viewerUnavailable"));+ // A take with no target holds the desktop the host runs this bot on, its Local VM included, as a phone's does.+ const target = !localVm && bot.cloudBackend === "vps" ? `vps/${bot.id}` : undefined;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}` } : {}) }),+ method: "POST", body: JSON.stringify({ action, controlLeaseId, ...(target ? { target } : {}) }),}),- join: async (signal) => ({ joinUrl: viewerAddress((await api(`/api/bots/${bot.id}/computer/join`, { method: "POST", body: "{}", signal })).joinUrl) }),+ join: async (signal, controlLeaseId) => {+ const path = localVm ? `local-computer/join?${new URLSearchParams({ controlLeaseId })}` : "computer/join";+ return { joinUrl: viewerAddress((await api(`/api/bots/${bot.id}/${path}`, { method: "POST", body: "{}", signal })).joinUrl) };+ },});} catch (cause) {await api(`/api/bots/${bot.id}/computer/viewer-close`, {@@ -202,7 +210,7 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {<div><div className="text-[14px] font-medium text-ink">{t("remoteDesktop.title", { name: bot.name })}</div><div className="mt-0.5 text-[11px] text-ink-secondary">- {t(bot.cloudBackend === "vps" ? "botAccess.cloud.selfHostedVps" : "remoteDesktop.cloudDesktop")}+ {t(localVm ? "vm.dest.vm" : bot.cloudBackend === "vps" ? "botAccess.cloud.selfHostedVps" : "remoteDesktop.cloudDesktop")}</div></div><div className="flex items-center gap-1">diff --git a/src/lib/remote-desktop.ts b/src/lib/remote-desktop.tsindex f62d9f3abd..3e213f20a9 100644--- a/src/lib/remote-desktop.ts+++ b/src/lib/remote-desktop.ts@@ -26,6 +26,13 @@ export function remoteScreenshotSource(raw: unknown): string | null {return `data:${frame.format === "jpeg" ? "image/jpeg" : "image/png"};base64,${frame.png}`;}+/** The host's Local VM preview answers `{ image }` as a PNG or JPEG data URL; anything else shows no frame. */+export function localVmScreenshotSource(raw: unknown): string | null {+ if (!raw || typeof raw !== "object") return null;+ const { image } = raw as { image?: unknown };+ return typeof image === "string" && /^data:image\/(?:png|jpeg);base64,[A-Za-z0-9+/=]+$/.test(image) ? image : null;+}+export function cloudEngineOf(instance: InstanceInfo | undefined): CloudEngine {return { computerMcp: instance?.capabilities?.computerMcp };}