Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep work on the private desktop: Auto prefers it over a sleeping cloud computer, and the bot panel offers it (#4797)
Milind Soni5e3b992220cb
diff --git a/server/computer-selection.test.ts b/server/computer-selection.test.tsindex cf86ada329..c20c44f8f9 100644--- a/server/computer-selection.test.ts+++ b/server/computer-selection.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { pickComputer, type ComputerOption } from "./computer-selection.ts";+import { chosenPlace, pickComputer, type ComputerOption } from "./computer-selection.ts";const option = (surface: ComputerOption["surface"], state: "ready" | "asleep" | "missing" | "off"): ComputerOption => ({surface,@@ -48,4 +48,31 @@ describe("which computer select_computer picks", () => {expect(pickComputer([option("cloud", "missing"), option("vm", "missing")], "auto", "off", false).option?.surface).toBe("vm");expect(pickComputer([option("cloud", "off")], "auto", "off", false).option).toBeUndefined();});++ it("on Auto starts a stopped private desktop before waking or creating a cloud computer", () => {+ // A stopped or recreatable private desktop reads as canCreate; a sleeping cloud computer as canStart.+ expect(pickComputer([option("cloud", "asleep"), option("vm", "missing")], "auto", "off", false).option?.surface).toBe("vm");+ expect(pickComputer([option("cloud", "asleep"), option("vm", "off")], "auto", "off", false).option?.surface).toBe("cloud");+ });++ it("on Auto keeps the place the person chose while it can be had, even when another computer is up, and moves only when asked", () => {+ const options = [option("cloud", "ready"), option("vm", "missing"), option("browser", "ready")];+ expect(pickComputer(options, "auto", "off", false, "vm")).toMatchObject({ option: { surface: "vm" }, current: false });+ expect(pickComputer([option("cloud", "asleep"), option("vm", "ready")], "auto", "off", false, "cloud").option?.surface).toBe("cloud");+ expect(pickComputer(options, "cloud", "off", false, "vm").option?.surface).toBe("cloud");+ // A chosen place that cannot be had at all leaves Auto its usual pick.+ expect(pickComputer([option("cloud", "missing"), option("browser", "off")], "auto", "off", false, "browser").option?.surface).toBe("cloud");+ expect(pickComputer(options, "auto", "vm", true, "vm")).toMatchObject({ option: { surface: "vm" }, current: true });+ });+});++describe("the place a person chose", () => {+ it("is their pin in the conversation, else the bot's Works on, and never a pin a turn made or Auto/Off", () => {+ expect(chosenPlace({ surface: "vm", surfaceSource: "user" }, "cloud")).toBe("vm");+ expect(chosenPlace({ surface: "vm" }, undefined)).toBe("vm");+ expect(chosenPlace({ surface: "cloud", surfaceSource: "auto" }, "vm")).toBe("vm");+ expect(chosenPlace({ surface: "cloud", surfaceSource: "auto" }, undefined)).toBeUndefined();+ expect(chosenPlace(undefined, "off")).toBeUndefined();+ expect(chosenPlace(undefined, "browser")).toBe("browser");+ });});diff --git a/server/computer-selection.ts b/server/computer-selection.tsindex 1a5093f6c2..7f823d9898 100644--- a/server/computer-selection.ts+++ b/server/computer-selection.ts@@ -8,22 +8,33 @@ export interface ComputerOption {canCreate: boolean;}+/** The place a person chose for this conversation: their own pin in it, else the bot's Works on. A pin a turn made on+ * its own is not a choice, and Auto or Off chooses no place. */+export function chosenPlace(task: { surface?: Surface; surfaceSource?: "user" | "auto" } | undefined, worksOn: string | undefined): Surface | undefined {+ if (task?.surface && task.surfaceSource !== "auto") return task.surface;+ return worksOn === "cloud" || worksOn === "vm" || worksOn === "local" || worksOn === "browser" ? worksOn : undefined;+}+/** `startsOnFirstCall`: the turn's first computer call creates or wakes it, so it is this turn's before it is up, and- * asking for it (or for Auto) keeps it rather than restarting the request elsewhere. */+ * asking for it (or for Auto) keeps it rather than restarting the request elsewhere.+ * `chosen`: the place the person chose. Auto keeps it whenever it can be had, up or not, so a bot never moves their work+ * to another computer on its own; only a request naming another place moves it. Otherwise a private desktop that is set+ * up (up, stopped, or recreatable on this device) comes before waking or creating a cloud computer. */export function pickComputer<T extends ComputerOption>(options: readonly T[],requested: Surface | "auto",current: string | undefined,startsOnFirstCall: boolean,+ chosen?: Surface,): { option: T | undefined; current: boolean } {const isCurrent = (option: T) => option.surface === current && (option.ready || (startsOnFirstCall && option.available));- const option = requested === "auto"- ? options.find(isCurrent)+ const kept = chosen === undefined ? undefined : options.find((candidate) => candidate.surface === chosen && candidate.available);+ const option = requested !== "auto" ? options.find((candidate) => candidate.surface === requested)+ : kept ?? options.find(isCurrent)?? options.find((candidate) => candidate.ready && candidate.surface === "vm")?? options.find((candidate) => candidate.ready)+ ?? options.find((candidate) => candidate.available && candidate.surface === "vm")?? options.find((candidate) => candidate.canStart)- ?? options.find((candidate) => candidate.canCreate && candidate.surface === "vm")- ?? options.find((candidate) => candidate.canCreate)- : options.find((candidate) => candidate.surface === requested);+ ?? options.find((candidate) => candidate.canCreate);return { option, current: option !== undefined && isCurrent(option) };}diff --git a/server/group-local-vm.e2e.test.ts b/server/group-local-vm.e2e.test.tsindex 1ddcef5969..e2fb6bcec7 100644--- a/server/group-local-vm.e2e.test.ts+++ b/server/group-local-vm.e2e.test.ts@@ -609,6 +609,36 @@ describe("Group Local VM ownership on the real isolated server", () => {}});+ it("lets a chat tool's Auto start a stopped private desktop before waking a sleeping cloud computer", async () => {+ vmState({ containers: ["shared"], stopped: ["shared"] }); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });+ const { bot } = await api("POST", "/api/bots", { name: "Chat prefers its desktop" });+ try {+ await api("PUT", "/api/config", { box: { token: "box_fixture" } });+ await api("PATCH", `/api/bots/${bot.id}`, { computer: "browser", browser: false });+ const environmentId = readFileSync(join(fixtureHome, "data", "environment-id"), "utf8").trim();+ const scope = createHash("sha256").update(environmentId).digest("hex").slice(0, 12);+ const prefix = bot.id.slice(0, 8).replace(/[^a-z0-9]/g, "");+ const suffix = createHash("sha256").update(bot.id).digest("hex").slice(0, 6);+ boatRow = { id: "bx_23456789", name: `ogb-${scope}-${prefix}-${suffix}`, state: "archived" };+ await api("POST", `/api/bots/${bot.id}/messages`, { text: "Open Chrome on an available computer" });+ const token = ((await dump()) as any).mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN;+ const call = (method: string, body?: unknown) => fetch(base + "/api/internal/computer/select", { method,+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(body ? { body: JSON.stringify(body) } : {}) });+ const listed = await (await call("GET")).json() as any, offered = listed.options;+ // Works on Browser with the browser off: chosen, but not to be had, so Auto picks.+ expect(listed.chosen).toBe("browser");+ expect(offered).toContainEqual(expect.objectContaining({ surface: "cloud", ready: false, canStart: true }));+ expect(offered).toContainEqual(expect.objectContaining({ surface: "vm", ready: false, available: true }));+ expect(await (await call("POST", { surface: "auto" })).json()).toMatchObject({ status: "pending", surface: "vm" });+ } finally {+ writeFileSync(finishFile, "finish");+ await api("POST", `/api/bots/${bot.id}/interrupt`, {}); await idle(bot.id);+ boatRow = null;+ await api("DELETE", `/api/bots/${bot.id}`);+ await api("PUT", "/api/config", { box: { token: "" } });+ }+ });+it.each(["stop", "failure", "off", "manual-selection", "new-request"])("does not continue a computer selection after %s", async failure => {vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });const { bot } = await api("POST", "/api/bots", { name: `Computer selection ${failure}` });diff --git a/server/index.ts b/server/index.tsindex e8d4107bfc..99cbbe08ee 100644--- a/server/index.ts+++ b/server/index.ts@@ -92,7 +92,7 @@ import { createReplyVoiceNotes } from "./host/reply-voice-notes.ts";import { runtimeRequestCardFields } from "./request-card.ts";import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";-import { pickComputer } from "./computer-selection.ts";+import { chosenPlace, pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";import { cloudComputerRpc } from "./cloud-computer-tools.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";@@ -13031,15 +13031,15 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {return json(res, 400, { error: "surface must be auto, cloud, vm, local, or browser" });}const unoffered = CLOUD_HOME && method === "POST" && requested !== "auto" ? cloudHomePlaceRefusal(parseSurface(requested)!) : undefined;- const options = await selectableComputers(bot);+ const options = await selectableComputers(bot), chosen = chosenPlace(store.taskByThread(bot.id, internalCapability.threadId), bot.computer);const current = source ? source.mounted ?? "off" : await computerPreviewSurface(bot, bot.threadId);requireActiveInternalCapability();- if (method === "GET") return json(res, 200, { current, canSelect, ...(refusal ? { why: refusal } : {}), options });+ if (method === "GET") return json(res, 200, { current, canSelect, ...(refusal ? { why: refusal } : {}), ...(chosen ? { chosen, chosenNote: `The person chose ${surfaceLabel(chosen)} for this conversation, and auto keeps it while it is available. Select another place only when they ask for one or it is unavailable.` } : {}), options });if (computerSelectionTurns.get(internalCapability.threadId) !== source) return json(res, 409, { error: "The user request ended before its computer was selected." });if (unoffered) return json(res, 409, { error: unoffered, options });const claim = autoVmClaims.get(internalCapability.threadId);const startsOnFirstCall = claim?.owner.generation === internalCapability.generation && claim.startsComputer === true && !claim.failed;- const picked = pickComputer(options, requested, current, startsOnFirstCall);+ const picked = pickComputer(options, requested, current, startsOnFirstCall, chosen);const option = picked.option;if (!option?.available) return json(res, 409, { error: option?.reason ?? "No configured computer or browser is available. Open the Screen panel to set one up.", options });if (!source!.selected && picked.current) {diff --git a/src/components/BotSettingsDialog.simple.test.ts b/src/components/BotSettingsDialog.simple.test.tsindex b4e429c937..eef31b7c81 100644--- a/src/components/BotSettingsDialog.simple.test.ts+++ b/src/components/BotSettingsDialog.simple.test.ts@@ -891,10 +891,11 @@ describe("the Where it works page", () => {.map((node) => [node.props["data-panel-choice"], node.props.title, Boolean(node.props.disabled), node.props.checked]);const choose = (rendered: Rendered, value: string) => click(find(rendered, "data-panel-choice", value));- it("offers Let it choose, this computer, the bot's browser and the Cloud desktop, with the chosen one checked", () => {+ it("offers Let it choose, this computer, the bot's browser, the Cloud desktop and the private desktop, with the chosen one checked", () => {// The tests run on no platform in particular, so this computer is a PC; a Mac says This Mac.expect(choices(where(makeBot()))).toEqual([["auto", "Let it choose", false, true], ["local", "This PC", false, false], ["browser", "Browser", false, false], ["cloud", "Cloud desktop", false, false],+ ["vm", "Private desktop", false, false],]);expect(where(makeBot()).html).toContain('role="radiogroup"');});@@ -907,6 +908,8 @@ describe("the Where it works page", () => {expect(patch).toHaveBeenLastCalledWith({ computer: "local" });choose(rendered, "browser");expect(patch).toHaveBeenLastCalledWith({ computer: "browser", browser: true });+ choose(rendered, "vm");+ expect(patch).toHaveBeenLastCalledWith({ computer: "vm" });choose(where(makeBot({ computer: "cloud" })), "auto");expect(patch).toHaveBeenLastCalledWith({ computer: null });patch.mockReset();@@ -914,10 +917,10 @@ describe("the Where it works page", () => {expect(patch).not.toHaveBeenCalled();});- it.each([["vm", "Private desktop"], ["off", "Off"]] as const)("shows a bot kept on %s as a last, checked choice it cannot pick again", (place, label) => {- const rendered = where(makeBot({ computer: place }));- expect(choices(rendered).at(-1)).toEqual([place, label, true, true]);- choose(rendered, place);+ it("shows a bot kept Off as a last, checked choice it cannot pick again", () => {+ const rendered = where(makeBot({ computer: "off" }));+ expect(choices(rendered).at(-1)).toEqual(["off", "Off", true, true]);+ choose(rendered, "off");expect(patch).not.toHaveBeenCalled();choose(rendered, "auto");expect(patch).toHaveBeenLastCalledWith({ computer: null });@@ -927,7 +930,10 @@ describe("the Where it works page", () => {fixture.places.cloud = [true, false, "Not ready"];expect(find(where(makeBot()), "data-panel-choice", "cloud").props).toMatchObject({ disabled: true, hint: "Not ready." });fixture.places.cloud = [false, false, "Not offered"];+ fixture.places.vm = [false, false, "Not offered"];expect(choices(where(makeBot())).map(([value]) => value)).toEqual(["auto", "local", "browser"]);+ // A bot already kept on the private desktop still shows it, checked.+ expect(choices(where(makeBot({ computer: "vm" }))).at(-1)).toEqual(["vm", "Private desktop", true, true]);fixture.places.local = [false, false, "Not offered"];fixture.places.browser = [false, false, "Not offered"];expect(choices(where(makeBot())).map(([value]) => value)).toEqual(["auto"]);diff --git a/src/components/bot-panel/ComputerTab.tsx b/src/components/bot-panel/ComputerTab.tsxindex b769cace40..a3fe19942b 100644--- a/src/components/bot-panel/ComputerTab.tsx+++ b/src/components/bot-panel/ComputerTab.tsx@@ -26,10 +26,7 @@ interface PlaceOption {disabled?: boolean;}-const EXTRA_PLACE_LABEL: Record<Exclude<PlaceChoice, "auto" | "local" | "cloud" | "browser">, () => string> = {- vm: () => t("place.vm"),- off: () => t("place.off"),-};+const OFF_LABEL = () => t("place.off");export function useOpenComputer(bot: Pick<Bot, "id">) {const { dispatch } = useStore();@@ -72,12 +69,14 @@ function usePlaceChoices(bot: Bot) {...(placeViews.local.policy ? [choice("local")] : []),...(placeViews.browser.policy || current === "browser" ? [choice("browser")] : []),...(placeViews.cloud.policy ? [choice("cloud")] : []),- ...(current === "vm" || current === "off" ? [{ value: current, label: EXTRA_PLACE_LABEL[current](), disabled: true }] : []),+ // Offered as in the Screen panel and the composer, so a bot can be kept on the private desktop from here too.+ ...(placeViews.vm.policy || current === "vm" ? [choice("vm")] : []),+ ...(current === "off" ? [{ value: current, label: OFF_LABEL(), disabled: true }] : []),];const liveSurface = bot.tasks?.find((task) => task.threadId === bot.threadId)?.surface;const usingNow = liveSurface && liveSurface !== current ? placeLabel(liveSurface) : null;const currentLabel = options.find((option) => option.value === current)?.label- ?? (current === "auto" || current === "vm" || current === "off" ? undefined : placeLabel(current));+ ?? (current === "auto" || current === "off" ? undefined : placeLabel(current));return { options, current, currentLabel, usingNow };}@@ -87,7 +86,7 @@ export function WherePage({ bot, derived }: { bot: Bot; derived: Derived }) {const [localAutoWarning, setLocalAutoWarning] = useState<{ botId: string; patch: BotPatch } | null>(null);const { patch, approvalMode } = derived;const choosePlace = (value: PlaceChoice) => {- if (value === current || value === "vm" || value === "off") return;+ if (value === current || value === "off") return;if (value === "local" && approvalMode === "auto") {setLocalAutoWarning({ botId: bot.id, patch: { computer: "local", acknowledgeLocalAuto: true } });return;