Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Computer panel: reset a cloud computer stuck starting
AdityaUmaleae03c10abd2b
diff --git a/server/boat.ts b/server/boat.tsindex 40e18b5c7b..e38e5d8e18 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -706,7 +706,7 @@ export async function inspectBoatIdentity(cfg: AppConfig, boxId: string): Promisreturn { available: true, identity: { boxId, name, state: safeBoatState(candidate.state) }, problem: null };}-function inventoryFailure(inventory: ManagedBoatInventory): Error & { status: number } {+export function inventoryFailure(inventory: ManagedBoatInventory): Error & { status: number } {const error = new Error(inventory.configured? (inventory.problem ?? "Cloud computer inventory is unavailable")diff --git a/server/host/cloud-computer-reset.test.ts b/server/host/cloud-computer-reset.test.tsnew file mode 100644index 0000000000..4fb45936bf--- /dev/null+++ b/server/host/cloud-computer-reset.test.ts@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const listManagedBoats = vi.fn();+const deleteManagedBoat = vi.fn();+vi.mock("../boat.ts", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../boat.ts")>()),+ listManagedBoats: (...args: unknown[]) => listManagedBoats(...args),+ deleteManagedBoat: (...args: unknown[]) => deleteManagedBoat(...args),+}));++const { resetBotCloudComputer } = await import("./cloud-computer-reset.ts");++const cfg = { box: { token: "box_test" } } as any;+const owners = [{ botId: "bot-a", name: "Ada", inUse: false }, { botId: "bot-b", name: "Bea", inUse: false }];+const instance = (boxId: string, ownerBotId: string | null) => ({+ boxId, name: `omb-${boxId}`, state: "starting", ownerBotId, ownerName: null, orphaned: ownerBotId === null, inUse: false,+});++describe("resetting a bot's cloud computer", () => {+ beforeEach(() => {+ listManagedBoats.mockReset();+ deleteManagedBoat.mockReset().mockResolvedValue({ ok: true });+ });++ it("deletes only the bot's own computer, by its listed id and name, through the lifecycle claim", async () => {+ listManagedBoats.mockResolvedValue({+ configured: true, available: true, problem: null,+ instances: [instance("bx_other", "bot-b"), instance("bx_orphan", null), instance("bx_mine", "bot-a")],+ });+ const claim = vi.fn();+ await expect(resetBotCloudComputer(cfg, "bot-a", owners, claim)).resolves.toEqual({ ok: true });+ expect(deleteManagedBoat).toHaveBeenCalledTimes(1);+ expect(deleteManagedBoat).toHaveBeenCalledWith(cfg, owners, "bx_mine", "omb-bx_mine", claim);+ });++ it("has nothing to delete when the bot has no computer yet", async () => {+ listManagedBoats.mockResolvedValue({ configured: true, available: true, problem: null, instances: [instance("bx_other", "bot-b")] });+ await expect(resetBotCloudComputer(cfg, "bot-a", owners, vi.fn())).resolves.toEqual({ ok: true, missing: true });+ expect(deleteManagedBoat).not.toHaveBeenCalled();+ });++ it("deletes nothing when the computer list cannot be read", async () => {+ listManagedBoats.mockResolvedValue({ configured: true, available: false, problem: "Could not reach boat.dev", instances: [] });+ await expect(resetBotCloudComputer(cfg, "bot-a", owners, vi.fn())).rejects.toMatchObject({ message: "Could not reach boat.dev", status: 503 });+ expect(deleteManagedBoat).not.toHaveBeenCalled();+ });++ it("passes on the refusal while the bot is working", async () => {+ listManagedBoats.mockResolvedValue({ configured: true, available: true, problem: null, instances: [instance("bx_mine", "bot-a")] });+ deleteManagedBoat.mockRejectedValue(Object.assign(new Error("this cloud computer is in use — stop its bot's work first"), { status: 409 }));+ await expect(resetBotCloudComputer(cfg, "bot-a", owners, vi.fn())).rejects.toMatchObject({ status: 409 });+ });+});diff --git a/server/host/cloud-computer-reset.ts b/server/host/cloud-computer-reset.tsnew file mode 100644index 0000000000..c1cfcf707e--- /dev/null+++ b/server/host/cloud-computer-reset.ts@@ -0,0 +1,21 @@+import * as boat from "../boat.ts";+import type { AppConfig } from "../config.ts";++/**+ * Deletes a bot's own cloud computer the way Settings → Cloud computers does, so one stuck+ * starting can be replaced: the bot's next turn makes a fresh one. A missing computer is+ * already reset. deleteManagedBoat refuses while the bot works, and `claim` holds the+ * bot's lifecycle lane, so a turn cannot start on the computer being deleted.+ */+export async function resetBotCloudComputer(+ cfg: AppConfig,+ botId: string,+ owners: boat.ManagedBoatOwner[],+ claim: boat.ManagedBoatMutationClaim,+): Promise<{ ok: boolean; pending?: true; missing?: true }> {+ const inventory = await boat.listManagedBoats(cfg, owners);+ if (!inventory.available) throw boat.inventoryFailure(inventory);+ const own = inventory.instances.find((instance) => instance.ownerBotId === botId);+ if (!own) return { ok: true, missing: true };+ return boat.deleteManagedBoat(cfg, owners, own.boxId, own.name, claim);+}diff --git a/server/index.test.ts b/server/index.test.tsindex 3ca95bf97a..231fe9fb30 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -4375,6 +4375,41 @@ describe("harness HTTP API", () => {}});+ it("resets only the bot's own stuck cloud computer from its Computer panel, never while it is in use", async () => {+ let botId = "";+ try {+ expect((await api("PUT", "/api/config", { box: { token: "box_route" } })).status).toBe(200);+ const bot = (await api("POST", "/api/bots")).body.bot;+ botId = bot.id;+ expect((await api("PATCH", `/api/bots/${bot.id}`, { computer: "cloud", cloudBackend: "box" })).status).toBe(200);+ const managedName = managedBoatNameForFixture(bot.id);+ const orphanName = managedBoatNameForFixture("deleted-orphan-bot");+ managedBoatRows = [+ { id: "bx_23456789", name: managedName, state: "starting" },+ { id: "bx_abcdefgh", name: orphanName, state: "starting" },+ ];++ expect((await api("POST", `/api/bots/${bot.id}/computer/control`, { action: "take" })).status).toBe(200);+ const inUse = await api("POST", `/api/bots/${bot.id}/computer/remove`, {});+ expect(inUse.status).toBe(409);+ expect(inUse.body.error).toMatch(/in use/i);+ expect(managedBoatDeleteConfirmations).toEqual([]);+ expect((await api("POST", `/api/bots/${bot.id}/computer/control`, { action: "release" })).status).toBe(200);++ const reset = await api("POST", `/api/bots/${bot.id}/computer/remove`, {});+ expect(reset).toMatchObject({ status: 202, body: { ok: true } });+ expect(managedBoatDeleteConfirmations).toEqual([{ boxId: "bx_23456789", confirmation: "bx_23456789" }]);+ expect(managedBoatRows.map((row) => row.id)).toEqual(["bx_abcdefgh"]);+ expect(await api("POST", `/api/bots/${bot.id}/computer/remove`, {})).toMatchObject({ status: 202, body: { ok: true, missing: true } });+ } finally {+ managedBoatRows = [];+ managedBoatDeleteConfirmations.length = 0;+ if (botId) await api("DELETE", `/api/bots/${botId}`).catch(() => undefined);+ await api("PUT", "/api/config", { box: { token: "" } });+ boatRouteCalls.length = 0;+ }+ });+it("deletes a bot-owned Boat automatically even after the bot changes destination", async () => {let botId = "";try {diff --git a/server/index.ts b/server/index.tsindex f8906fd387..02ba7f2c8a 100644--- a/server/index.ts+++ b/server/index.ts@@ -424,7 +424,7 @@ import { createLocalVmUpdater, LOCAL_VM_UPDATING_PROBLEM, recoverLocalVms, VPS_Oimport { keepInstalledAppsBeforeRemove } from "./local-vm-profiles.ts";import { localVmStopReason, recordLocalVmIdleStop } from "./local-vm-stop-reason.ts";import { ComputerIdleTimer } from "./computer-idle.ts";-import { CLOUD_COMPUTER_DID_NOT_START, CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_STARTING, createCloudComputerPower } from "./host/cloud-computer-power.ts";+import { CLOUD_COMPUTER_DID_NOT_START, CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_STARTING, createCloudComputerPower } from "./host/cloud-computer-power.ts"; import { resetBotCloudComputer } from "./host/cloud-computer-reset.ts";import { LocalVmLease, LocalVmLeasePool } from "./local-vm-lease.ts";import { LocalVmSeatPool, type LocalVmSeatHolder } from "./local-vm-seat-pool.ts";import { createLoopGuard, loopGuardSettings } from "./host/loop-guard.ts"; import { createPersonFirst } from "./host/person-first.ts"; import { createRunOwners, runActorOf } from "./host/run-owner.ts";@@ -15265,9 +15265,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {error: "Choose Cloud computer before changing or opening this cloud computer. Auto only checks existing computer state.",});}- if (m[2] === "remove") {- return json(res, 409, { error: "a cloud computer has no container to remove — put it to sleep instead" });- }+ if (m[2] === "remove") return json(res, 202, await resetBotCloudComputer(cfg, botId, managedBoatOwners(), claimManagedBoatMutation));if (m[2] === "screenshot") {res.setHeader("cache-control", "private, no-store");try { return json(res, 200, await computerPreviews.capture(botId, () => boat.screenshotBoat(cfg, botId))); }diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsxindex 708f50dae9..12b78fd7e8 100644--- a/src/components/ComputerPanel.tsx+++ b/src/components/ComputerPanel.tsx@@ -17,7 +17,7 @@ import { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";import { usePageVisible } from "@/lib/page-visible";import { listenLiveFrames } from "@/lib/live-events";-import { CloudScreenPreview } from "./CloudScreenPreview";+import { CloudScreenPreview } from "./CloudScreenPreview"; import { ResetCloudComputerButton } from "./ResetCloudComputerButton";import { isActiveTurnRefusal, isRemoteScreenshotContention } from "@/lib/remote-desktop";import { CloudBackendPicker } from "./CloudBackendPicker";import { SimpleVpsChoices } from "./SimpleVpsChoices";@@ -35,8 +35,7 @@ import { browserAvailable, browserUnavailableReason, builtInBrowserEnabled } froimport { parseComputerHelp, transitionComputerControlLease, type ComputerControlAction } from "@/lib/computer-control";import { openProviderDesktop, useComputerTakeover } from "./computer-takeover";import { SignInBanner } from "./SignInRequestCard";-import { FullScreenButton } from "./FullScreenButton";-import { LocalScreenPreview } from "./LocalScreenPreview";+import { FullScreenButton } from "./FullScreenButton"; import { LocalScreenPreview } from "./LocalScreenPreview";import { LinuxLocalControl } from "./LinuxLocalControl";import { MacLocalControl } from "./MacLocalControl"; import { WindowsLocalControl } from "./WindowsLocalControl";import { LocalComputerAutoWarning } from "./LocalComputerAutoWarning";@@ -1399,6 +1398,7 @@ export function ComputerPanel({</span>{currentTeamComputer && placeActionButton(autoView)}{bot.computer === "cloud" && (phase === "unconfigured" || phase === "error") && cloudView.action?.id !== "add-boat-key" && placeActionButton(cloudView)}+ <ResetCloudComputerButton botId={bot.id} botName={bot.name} onReset={() => { setError(null); setRetry((n) => n + 1); }} view={{ computer: bot.computer, cloudBackend, canManage: canManageCloud, busy: profileBot.busy === true, pending: pending !== null, phase, boatState, refusal: cloudRefused?.state }} />{phase === "local" && !isLinux && localMisses >= 3 && (<buttononClick={() => window.ogb?.permOpenSettings?.("screen")}diff --git a/src/components/ResetCloudComputerButton.test.ts b/src/components/ResetCloudComputerButton.test.tsnew file mode 100644index 0000000000..d664e9442a--- /dev/null+++ b/src/components/ResetCloudComputerButton.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from "vitest";+import { cloudComputerResettable, type CloudResetView } from "./ResetCloudComputerButton";++const stuck: CloudResetView = {+ computer: "cloud", cloudBackend: "box", canManage: true, busy: false, pending: false,+ phase: "busy-boat", boatState: "starting", refusal: undefined,+};++describe("Reset cloud desktop in the Computer panel", () => {+ it("shows while the cloud computer is stuck starting with no turn running, and when it did not start", () => {+ expect(cloudComputerResettable(stuck)).toBe(true);+ expect(cloudComputerResettable({ ...stuck, boatState: "provisioning" })).toBe(true);+ expect(cloudComputerResettable({ ...stuck, phase: "error", boatState: null, refusal: "cc-no-start" })).toBe(true);+ });++ it("stays hidden while the bot works on it, while the panel is busy, or for a computer that is fine", () => {+ expect(cloudComputerResettable({ ...stuck, busy: true })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, pending: true })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, phase: "ready", boatState: "running" })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, phase: "starting" })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, phase: "cloud-asleep", boatState: "archived" })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, boatState: "archived" })).toBe(false);+ });++ it("is not offered for a refusal a reset cannot fix, or outside the bot's own Cloud computer", () => {+ expect(cloudComputerResettable({ ...stuck, phase: "error", refusal: "cc-no-hours" })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, cloudBackend: "vps" })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, computer: undefined })).toBe(false);+ expect(cloudComputerResettable({ ...stuck, canManage: false })).toBe(false);+ });+});diff --git a/src/components/ResetCloudComputerButton.tsx b/src/components/ResetCloudComputerButton.tsxnew file mode 100644index 0000000000..f3f7c209e7--- /dev/null+++ b/src/components/ResetCloudComputerButton.tsx@@ -0,0 +1,59 @@+import { useState } from "react";+import { Loader2, RotateCcw } from "lucide-react";+import { api } from "@/state/store";+import { busyBoatView } from "@/lib/local-computer";+import { t } from "@/lib/i18n";++export interface CloudResetView {+ computer: string | null | undefined;+ cloudBackend: string;+ canManage: boolean;+ busy: boolean;+ pending: boolean;+ phase: string;+ boatState: string | null;+ refusal: string | undefined;+}++/** Offered only on the person's explicit Cloud computer, with no work on it: start failed, or it shows starting while no turn runs. */+export function cloudComputerResettable(view: CloudResetView): boolean {+ if (view.computer !== "cloud" || view.cloudBackend !== "box" || !view.canManage || view.busy || view.pending) return false;+ if (view.phase === "error") return view.refusal === "cc-no-start";+ return view.phase === "busy-boat" && busyBoatView(view.boatState, false).spinner;+}++/** Deletes the bot's cloud computer after the person confirms; its next message makes a fresh one. */+export function ResetCloudComputerButton({ botId, botName, view, onReset }: {+ botId: string;+ botName: string;+ view: CloudResetView;+ onReset: () => void;+}) {+ const [resetting, setResetting] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ if (!cloudComputerResettable(view)) return null;+ const reset = () => {+ if (resetting || !window.confirm(t("computer.reset.confirm", { name: botName }))) return;+ setResetting(true);+ setProblem(null);+ api(`/api/bots/${botId}/computer/remove`, { method: "POST", body: "{}" })+ .then(onReset)+ .catch((error) => setProblem(error instanceof Error ? error.message : String(error)))+ .finally(() => setResetting(false));+ };+ return (+ <>+ <button+ type="button"+ onClick={reset}+ disabled={resetting}+ aria-busy={resetting}+ className="mt-1 inline-flex items-center gap-1.5 rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-60"+ >+ {resetting ? <Loader2 size={12} className="animate-spin" /> : <RotateCcw size={12} />}+ {t("computer.reset.button")}+ </button>+ {problem && <p role="alert" className="text-[12px] text-danger">{problem}</p>}+ </>+ );+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex bf963b7654..f55247c9ad 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6622,6 +6622,8 @@"computer.phase.showPendingBoat": "Auto found an existing cloud desktop that is not ready. It was not changed.","computer.cloud.new": "{name} gets its own cloud desktop the first time a task needs one. The first start takes about a minute.","computer.cloud.asleep": "{name}'s cloud desktop is asleep. It wakes in a few seconds when {name} needs it.",+ "computer.reset.button": "Reset cloud desktop",+ "computer.reset.confirm": "Reset {name}'s cloud desktop? It is deleted with its files and browser sign-ins, and a fresh one starts with {name}'s next message. This cannot be undone.","computer.badge.autoBoat": "cloud desktop · Auto · read-only","desktopViewer.title": "Desktop viewer","desktopViewer.reconnect": "Reconnect",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex c0b918a2a6..eb64c6c1b9 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6308,6 +6308,8 @@"computer.phase.showPendingBoat": "O modo Auto encontrou um desktop na nuvem que não está pronto. Ele não foi alterado.","computer.cloud.new": "{name} ganha o próprio desktop na nuvem na primeira vez que uma tarefa precisar. A primeira inicialização leva cerca de um minuto.","computer.cloud.asleep": "O desktop na nuvem de {name} está dormindo. Ele acorda em alguns segundos quando {name} precisar.",+ "computer.reset.button": "Redefinir desktop na nuvem",+ "computer.reset.confirm": "Redefinir o desktop na nuvem de {name}? Ele é excluído com os arquivos e logins do navegador, e um novo começa com a próxima mensagem de {name}. Não dá para desfazer.","computer.badge.autoBoat": "desktop na nuvem · Auto · somente leitura","desktopViewer.title": "Visualizador do desktop","desktopViewer.reconnect": "Reconectar",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex aefdc23670..8604710fb2 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -36470,7 +36470,9 @@"settings.domain.httpsFirst": "41486ac1d5f39e25ccf3835d520137ecac15a0f49a9dcb5b73f7523fe6df330f","settings.backTo": "ea37ec29c3865c359d3efb005bd252c35457976140bb718824f39d157ea32567","devices.route.httpsAccount": "518ed79b3110cf735bc507bd796cf5c9cd701c3b2dc72bd764e599d411e3baf5",- "backup.importAction": "ea94509e38cf6d6427db3a1b5a3b5816cba1e8f89b08f9739f6077ade188163c"+ "backup.importAction": "ea94509e38cf6d6427db3a1b5a3b5816cba1e8f89b08f9739f6077ade188163c",+ "computer.reset.button": "196d09c7f7dc0290cc84c7a01347ae3f9a50067925490e7a0b9e262fa2add7f7",+ "computer.reset.confirm": "49ee8910d29a1da38e3b3dd2518685d77c45bd5fbb248f44566c2d7b721765f9"},"zh": {"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",