Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(handoff): run handed-off work on the receiving bot's own cloud computer (#4214)
Aditya Umale436eefcd311e
diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex a479ff456a..65455e14b2 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -364,6 +364,51 @@ describe("a cloud computer starts only when the bot uses it", () => {await apiOk("DELETE", `/api/bots/${bot.id}`);}, 30_000);+ it("work handed to a bot on Auto runs on that bot's own cloud computer; a consult, and a bot with none, get no computer", async () => {+ const auto = async (name: string) => {+ const bot = await cloudBot(name);+ const own = await startTurn(bot.id, "Open the cloud desktop");+ expect((await computerCall(own, "tools/call", { name: "screenshot", arguments: {} })).body.result.isError).toBeFalsy();+ await finish(bot.id);+ await apiOk("PATCH", `/api/bots/${bot.id}`, { computer: null });+ return bot;+ };+ const writer = await auto("Writer");+ const asked = await auto("Asked");+ const fresh = await cloudBot("Fresh", { computer: null });+ const sender = await cloudBot("Sender", { computer: null });+ const before = { creates: creates(), resumes: resumes() };+ const agents = (await startTurn(sender.id, "Hand the desktop check over")).mcpConfig.mcpServers.agents;+ const token = (agents.env.OMB_GATE_UPSTREAM ? JSON.parse(agents.env.OMB_GATE_UPSTREAM).env : agents.env).OMB_COMMS_TOKEN;+ const handed = async (botId: string, call: Record<string, unknown>) => {+ rmSync(dumpFile, { force: true });+ const response = await fetch(`${base}/api/internal/coordinate-bots`, {+ method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },+ body: JSON.stringify({ botIds: [botId], ...call }),+ });+ expect(response.status, await response.clone().text()).toBe(200);+ const sent = await dump();+ expect(sent.cwd).toContain(botId);+ return sent;+ };+ const work = await handed(writer.id, { message: "Check the weather site on your desktop" });+ expect(work.mcpConfig.mcpServers.computer?.args).toEqual([expect.stringMatching(/harness-mcp-proxy\.(?:ts|js)$/), "computer"]);+ expect(work.systemPrompt).toContain("assigned cloud computer");+ const consult = await handed(asked.id, { message: "Which weather site do you use?", consult: true });+ expect(consult.mcpConfig.mcpServers.computer).toBeUndefined();+ const none = await handed(fresh.id, { message: "Check the weather site on your desktop" });+ expect(none.mcpConfig.mcpServers.computer).toBeUndefined();+ writeFileSync(finishFile, "finish");+ for (const bot of [writer, asked, fresh, sender]) await idle(bot.id);+ // Mounting is lazy: nothing was created or woken without a computer call.+ expect({ creates: creates(), resumes: resumes() }).toEqual(before);+ // A finished hand-off can still be settling its dispatch for a moment after the bot reads idle; the delete waits for it.+ for (const bot of [writer, asked, fresh, sender]) {+ const deleted = await until(() => api("DELETE", `/api/bots/${bot.id}`), (response) => response.status !== 409);+ expect(deleted.status).toBeLessThan(400);+ }+ }, 90_000);+it("a room member whose cloud computer can't start says why in the room, once, under its own name", async () => {refuse.creates = true;try {diff --git a/server/host/cloud-computer-power.test.ts b/server/host/cloud-computer-power.test.tsindex ec9fdd8baa..57b4ae69c3 100644--- a/server/host/cloud-computer-power.test.ts+++ b/server/host/cloud-computer-power.test.ts@@ -292,6 +292,16 @@ describe("cloud computer power", () => {expect(sleeps().sort()).toEqual(["new", "slow"]);});+ it("an existing-only start wakes the bot's computer but never creates one", async () => {+ expect(await power.start(bot("gone"), turn("t1"), { existingOnly: true })).toBeNull();+ expect(fake.provisionBoat).not.toHaveBeenCalled();+ expect(broadcasts).toEqual([]);++ fake.states.set("asleep", "archived");+ expect(await power.start(bot("asleep"), turn("t2"), { existingOnly: true })).toMatchObject({ state: "ready" });+ expect(fake.provisionBoat).not.toHaveBeenCalled();+ });+it("a start that outlives its turn keeps the computer on until the start is done", async () => {let created!: () => void;fake.provisionBoat = vi.fn(() => new Promise<void>(resolve => { created = () => { fake.states.set("new", "ready"); resolve(); }; }));diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.tsindex cafa75b9a1..2ef969546a 100644--- a/server/host/cloud-computer-power.ts+++ b/server/host/cloud-computer-power.ts@@ -16,6 +16,10 @@ export const CLOUD_COMPUTER_IDLE_MS = Math.max(1_000, Number(process.env.OMB_CLO* minutes or more often never waits on a wake: each wake spends one start from the Boat account's pool, shared by every customer. */export const ROUTINE_DUE_SOON_MS = 30 * 60_000;const MAX_LISTING_RETRY_MS = 60 * 60_000;+/** Above a slow first start; Boat's own ready wait is 90 seconds. */+export const CLOUD_COMPUTER_START_BUDGET_MS = Math.max(1_000, Number(process.env.OMB_CLOUD_COMPUTER_START_BUDGET_MS) || 150_000);+export const CLOUD_COMPUTER_STARTING = "The cloud computer is still starting. This call was not performed. Take a fresh screenshot in a moment.";+export const CLOUD_COMPUTER_DID_NOT_START = "the cloud computer didn't start in time";type ScheduledRoutine = Pick<Routine, "botId" | "runOn" | "enabled" | "nextRunAt">;@@ -104,11 +108,12 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {used(held.owner);}- async function start(bot: BotRecord, turn: TurnOwner) {+ /** `existingOnly`: wake or attach the bot's computer, but never create one (null when it has none). */+ async function start(bot: BotRecord, turn: TurnOwner, opts: { existingOnly?: boolean } = {}) {attached(turn, bot.id);starting.set(bot.id, (starting.get(bot.id) ?? 0) + 1);try {- return await startBotBoat(bot);+ return await startBotBoat(bot, opts.existingOnly === true);} finally {const left = (starting.get(bot.id) ?? 1) - 1;if (left > 0) starting.set(bot.id, left);@@ -116,10 +121,11 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {}}- async function startBotBoat(bot: BotRecord) {+ async function startBotBoat(bot: BotRecord, existingOnly: boolean) {let b = await boat.findBoat(cfg, bot.id);const lifecycleOf = () => boat.boatTurnLifecycleAction(typeof b?.state === "string" ? b.state : null);let lifecycle = lifecycleOf();+ if (lifecycle === "provision" && existingOnly) return null;if (lifecycle === "provision") {broadcast({ kind: "computer", botId: bot.id, state: "provisioning", place: "cloud" });await boat.provisionBoat(cfg, bot.id, bot.name);diff --git a/server/index.ts b/server/index.tsindex 600a0becaa..868bcd8ecf 100644--- a/server/index.ts+++ b/server/index.ts@@ -416,7 +416,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 { 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 { 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";@@ -500,7 +500,7 @@ import { keepTransient, lazyClaimRetryText, settledWithin, startAutoVmClaim, witimport { CONTROL_ACT_WITHIN_MS, CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_WAIT_MS, CONTROL_WAITED, controlRefusal, type ControlState } from "./control-client.ts";import { computerFreeAfterText, computerParkedText, computerPersonAwayText, computerStoppedWaitingText, computerWaitingText, type ComputerHolder } from "./computer-wait.ts";import { modelContextWindow } from "./model-context-window.ts";-import { browserIsThePlace, chosenPin, cloudPlaceRefusal, computerSkippedNote, computerToolsRefusal, parseSurface, pinSource, PlaceUnavailableError, placeUnavailable, resolveSurface, surfaceLabel, surfaceOfComputerKind, surfacePrompt, type ComputerWant, type PlaceSource, type Surface } from "./surface.ts";+import { browserIsThePlace, chosenPin, cloudPlaceRefusal, computerSkippedNote, computerToolsRefusal, handoffUsesOwnCloud, isHandedWork, ownCloudStateWithin, parseSurface, pinSource, PlaceUnavailableError, placeUnavailable, resolveSurface, surfaceLabel, surfaceOfComputerKind, surfacePrompt, type ComputerWant, type PlaceSource, type Surface } from "./surface.ts";import { cloudRefusal, type PlaceRow } from "../shared/place-view.ts";import {PendingTurnCancellations,@@ -5939,11 +5939,6 @@ async function mountBotVps(};}-/** Above a slow first start; Boat's own ready wait is 90 seconds. */-const CLOUD_COMPUTER_START_BUDGET_MS = Math.max(1_000, Number(process.env.OMB_CLOUD_COMPUTER_START_BUDGET_MS) || 150_000);-const CLOUD_COMPUTER_STARTING = "The cloud computer is still starting. This call was not performed. Take a fresh screenshot in a moment.";-const CLOUD_COMPUTER_DID_NOT_START = "the cloud computer didn't start in time";-function mountBotBoat(bot: BotRecord,owner: TurnOwner,@@ -5951,6 +5946,7 @@ function mountBotBoat(source?: PlaceSource;onClaimed: (capture: () => Promise<{ png: string; format: string }>) => void;onRejected?: (failure: string, error?: unknown) => void;+ /** Wake or attach the bot's own computer, never create one. */ existingOnly?: boolean;},): NonNullable<SendTurnInput["integrations"]>["localComputer"] {const slot: AutoVmClaimSlot = {@@ -5964,9 +5960,9 @@ function mountBotBoat(try {attached = await attachBotBoat(bot, owner, {budgetMs: CLOUD_COMPUTER_START_BUDGET_MS,- onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; },+ onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, existingOnly: opts.existingOnly,});- if (!attached) throw new Error("the cloud computer could not be created or reached");+ if (!attached) throw new Error(opts.existingOnly ? "this bot no longer has a cloud computer of its own" : "the cloud computer could not be created or reached");} catch (error) {throw keepTransient(error, opts.source ? await asPlaceFailure(error, "cloud", opts.source, bot, "box") : error);}@@ -5984,11 +5980,11 @@ function claimedBoatId(capability: InternalCapability): string | undefined {}/** The Cloud place is the consent boundary to create or wake a Boat (which un-pauses billing); Auto never reaches here. */-async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs: number; onSeated: () => void }) {+async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs: number; onSeated: () => void; existingOnly?: boolean }) {// Claim before any network await so setup itself cannot race another turn.await bindTurnComputer(owner, `computer:box-bot:${bot.id}`, true);start.onSeated();- const machine = await withinBudget(cloudComputerPower.start(bot, owner), start.budgetMs, CLOUD_COMPUTER_DID_NOT_START);+ const machine = await withinBudget(cloudComputerPower.start(bot, owner, { existingOnly: start.existingOnly }), start.budgetMs, CLOUD_COMPUTER_DID_NOT_START);if (!machine) return null;await bindTurnComputer(owner, `computer:box:${machine.id}`);return {@@ -8071,7 +8067,10 @@ async function beginTurn(const mountsComputerMcp = instance.adapter.capabilities.computerMcp === true;const mountsLocalComputer = instance.adapter.capabilities.localComputerMcp === true;const dispatchTask = store.taskByThread(bot.id, threadId);- let wants: ComputerWant = computerSkipped ? "off" : plan.computer;+ const handoffMayUseCloud = !computerSkipped && plan.computer === undefined && isHandedWork(opts?.coordination ? coordinator.node(opts.coordination.id) : undefined) && !teamComputer && cloudBackend === "box" && boat.boatConfigured(cfg)+ && canWorkOnCloud(cloudEngine(instance)) && !computerPlaceRefusal("box") && !cloudPlaceRefusal(cloudEngine(instance, bot.modelSelection.model), "works-on", bot.name) && !computerToolsRefusal(toolScope, "works-on", bot.name);+ const ownCloud = handoffMayUseCloud ? await ownCloudStateWithin(boat.boatStatus(cfg, bot.id)) : undefined, handoffOwnCloud = handoffUsesOwnCloud({ plan, handoffWork: Boolean(ownCloud), ownCloudState: ownCloud?.state });+ let wants: ComputerWant = computerSkipped ? "off" : handoffOwnCloud ? "cloud" : plan.computer;const skipComputer = (error: unknown) => {if (!answer.incident || error instanceof DirectTurnSetupCancelled || error instanceof ComputerWaitParked) throw error;computerSkipped ??= error instanceof Error ? error.message : String(error);@@ -8110,7 +8109,7 @@ async function beginTurn(const autoPinAllowed = () => {const liveBot = store.bot(bot.id);const liveTask = store.taskByThread(bot.id, threadId);- return liveBot?.computer === undefined && !teamComputer && opts?.runOn !== "cloud" && !plan.pinned && !computerSkipped &&+ return liveBot?.computer === undefined && !teamComputer && opts?.runOn !== "cloud" && !plan.pinned && !computerSkipped && !ownCloud?.unavailable &&Boolean(liveTask && liveTask.surfaceSource !== "user");};const pinAutoSurface = (surface: Surface) => {@@ -8326,6 +8325,7 @@ async function beginTurn(source: placeSource,onClaimed: adoptClaimedCapture,onRejected: surfaceLazyClaimRejection("the cloud computer"),+ existingOnly: handoffOwnCloud,});computerKind = "box";}diff --git a/server/surface.test.ts b/server/surface.test.tsindex 864523f965..0bca613c39 100644--- a/server/surface.test.ts+++ b/server/surface.test.ts@@ -6,6 +6,9 @@ import {cloudPlaceRefusal,computerSkippedNote,computerToolsRefusal,+ handoffUsesOwnCloud,+ isHandedWork,+ ownCloudStateWithin,parseSurface,pinSource,placeUnavailable,@@ -25,6 +28,48 @@ describe("browserIsThePlace", () => {});});+describe("isHandedWork", () => {+ it("counts only work another bot handed over: not a person's own resumed root, not a consult", () => {+ expect(isHandedWork({ parentId: "root-1", mode: "work" })).toBe(true);+ expect(isHandedWork({ mode: "work" })).toBe(false);+ expect(isHandedWork({ parentId: "root-1", mode: "consult" })).toBe(false);+ expect(isHandedWork(undefined)).toBe(false);+ });+});++describe("ownCloudStateWithin", () => {+ it("answers with the cloud computer's state, and marks a failed or slow lookup as unavailable", async () => {+ await expect(ownCloudStateWithin(Promise.resolve({ box: { state: "stopped" } }))).resolves.toEqual({ state: "stopped", unavailable: false });+ await expect(ownCloudStateWithin(Promise.resolve({ box: null }))).resolves.toEqual({ state: undefined, unavailable: false });+ await expect(ownCloudStateWithin(Promise.reject(new Error("Boat is down")))).resolves.toEqual({ state: undefined, unavailable: true });+ const started = Date.now();+ await expect(ownCloudStateWithin(new Promise(() => {}), 20)).resolves.toEqual({ state: undefined, unavailable: true });+ expect(Date.now() - started).toBeLessThan(1_000);+ });+});++describe("handoffUsesOwnCloud", () => {+ const auto = resolveSurface({ destination: undefined, browserOn: true });+ it("runs handed-off work on Auto on the receiving bot's own cloud computer, awake or asleep", () => {+ expect(handoffUsesOwnCloud({ plan: auto, handoffWork: true, ownCloudState: "running" })).toBe(true);+ expect(handoffUsesOwnCloud({ plan: auto, handoffWork: true, ownCloudState: "archived" })).toBe(true);+ });+ it("never creates one, and leaves a person's own turns and consults alone", () => {+ expect(handoffUsesOwnCloud({ plan: auto, handoffWork: true, ownCloudState: null })).toBe(false);+ expect(handoffUsesOwnCloud({ plan: auto, handoffWork: true, ownCloudState: undefined })).toBe(false);+ expect(handoffUsesOwnCloud({ plan: auto, handoffWork: false, ownCloudState: "running" })).toBe(false);+ });+ it("keeps Works on and a pin as they are", () => {+ for (const plan of [+ resolveSurface({ destination: "browser", browserOn: true }),+ resolveSurface({ destination: "local", browserOn: true }),+ resolveSurface({ destination: "off", browserOn: true }),+ resolveSurface({ destination: undefined, pinnedSurface: "browser", browserOn: true }),+ resolveSurface({ destination: undefined, pinnedSurface: "vm", browserOn: true }),+ ]) expect(handoffUsesOwnCloud({ plan, handoffWork: true, ownCloudState: "running" })).toBe(false);+ });+});+describe("pinSource", () => {it("counts a turn's own pin to the place Works on names as Works on, so This computer is not asked for again", () => {expect(pinSource("local", { surfaceSource: "auto" }, "local")).toBe("works-on");diff --git a/server/surface.ts b/server/surface.tsindex f1fee0fcf7..aed1047f47 100644--- a/server/surface.ts+++ b/server/surface.ts@@ -83,6 +83,27 @@ function placeOf(input: { destination: Destination; pinnedSurface?: Surface | nureturn { computer: undefined, browser: browserOn, pinned: null, note: "" };}+/** On Auto, work handed over by another bot runs on the receiving bot's own cloud computer when it has one (asleep or awake): the handoff cannot pick a place itself. Auto still never creates one; Works on, a pin, a person's turn and a consult keep their usual place. */+/** Work another bot handed over: a child node (a person's own root also runs as "work" when it resumes), never a consult. */+export function isHandedWork(node: { parentId?: string; mode: string } | undefined): boolean {+ return Boolean(node?.parentId && node.mode !== "consult");+}++export function handoffUsesOwnCloud(input: { plan: Pick<SurfacePlan, "computer">; handoffWork: boolean; ownCloudState: string | null | undefined }): boolean {+ return input.handoffWork && input.plan.computer === undefined && Boolean(input.ownCloudState);+}++/** Best effort: an unreachable Boat service counts as no cloud computer after `ms`, so a handoff still starts promptly.+ * `unavailable` marks a failed or slow lookup, which is not a confirmed "no cloud computer". */+export function ownCloudStateWithin(status: Promise<{ box?: { state?: string | null } | null }>, ms = 3_000): Promise<{ state: string | null | undefined; unavailable: boolean }> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const unavailable = { state: undefined, unavailable: true };+ return Promise.race([+ status.then((result) => ({ state: result.box?.state, unavailable: false }), () => unavailable),+ new Promise<typeof unavailable>((resolve) => { timer = setTimeout(() => resolve(unavailable), ms); }),+ ]).finally(() => clearTimeout(timer));+}+export function browserIsThePlace(plan: SurfacePlan): boolean {return plan.computer === "off" && plan.browser;}