Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Computer busy: a take and hand-back between two looks is still seen
laijsg14cdb7e4f28fa
diff --git a/docs/verification/computer-wait.md b/docs/verification/computer-wait.mdindex 35d83d7894..dc4c1d215c 100644--- a/docs/verification/computer-wait.md+++ b/docs/verification/computer-wait.md@@ -9,8 +9,8 @@ pnpm exec vitest run server/index.test.ts -t 'parks the turn at the wait ceilingpnpm exec vitest run server/runtime-roots.e2e.test.ts server/room-roots.e2e.test.tspnpm exec vitest run server/turn-resources.test.ts server/group-local-vm.e2e.test.ts server/shared-computers.e2e.test.tspnpm exec vitest run server/managed-desktop-cleanup.test.ts-pnpm exec vitest run server/group-local-vm.e2e.test.ts -t 'queue place without naming|not that another thread has it|once the turn holds the seat|person.s hold, not another thread|handed it back while it waited'-pnpm exec vitest run server/computer-wait.test.ts server/turn-resources.test.ts server/host/computer-gate-answers.test.ts server/mcp-bridge.test.ts server/saved-steps/computer-client.test.ts+pnpm exec vitest run server/group-local-vm.e2e.test.ts -t 'queue place without naming|not that another thread has it|once the turn holds the seat|person.s hold, not another thread|handed it back at once while it waited'+pnpm exec vitest run server/computer-wait.test.ts server/computer-control.test.ts server/turn-resources.test.ts server/host/computer-gate-answers.test.ts server/mcp-bridge.test.ts server/saved-steps/computer-client.test.ts```The shared-team-computer case proves:@@ -68,10 +68,9 @@ screen call is not performed, from what holds at that moment:has the seat and waits for readiness): the answer says the computer is notready yet, never that another thread has it.- A person takes the shared desktop during a queued call: the answer is the- person's hold, read on the seat the turn queues for. When the call's 250 ms- look sees the person take it and they hand it back before the turn gets the- seat, the call is still not performed: the turn takes a fresh screenshot- first.+ person's hold, read on the seat the turn queues for. When the person takes it+ and hands it back before the turn gets the seat, however quickly, the call is+ still not performed: the turn takes a fresh screenshot first.- At the wait ceiling the parked turn hears that it waited without getting thecomputer and should stop calling the computer tools; not a start failure, noholder, and no promise to resume (a goal step that parks is reassigned).diff --git a/server/computer-control.test.ts b/server/computer-control.test.tsindex 282dc005db..3b58e620c6 100644--- a/server/computer-control.test.ts+++ b/server/computer-control.test.ts@@ -31,6 +31,21 @@ describe("computer control", () => {expect(control.take("b1").heldSinceMs).toBe(1000);});+ it("numbers each hold that starts, by take or lease, and not a repeated take of a held key", () => {+ const { control } = tracked();+ expect([control.takeSequence(), control.lastTake("b1")]).toEqual([0, 0]);+ control.take("b1");+ control.take("b1");+ control.release("b1");+ control.take("b2");+ control.acquireLease("b1", "lease-a");+ control.acquireLease("b1", "lease-b");+ expect([control.takeSequence(), control.lastTake("b1"), control.lastTake("b2")]).toEqual([3, 3, 2]);+ control.release("b2");+ control.forgetBot("b2");+ expect([control.takeSequence(), control.lastTake("b2")]).toEqual([3, 0]);+ });+it("atomically acquires a workspace lease without exposing its id", () => {const { control, changes } = tracked();const leaseId = "5b6bbbd2-b88b-4c50-a748-ec87f332662f";diff --git a/server/computer-control.ts b/server/computer-control.tsindex 5596ab7908..5b659070e4 100644--- a/server/computer-control.ts+++ b/server/computer-control.ts@@ -40,6 +40,8 @@ interface Entry {export class ComputerControl {private entries = new Map<string, Entry>();+ private holdsStarted = 0;+ private lastHoldStarted = new Map<string, number>();private onChange: (botId: string, snapshot: ControlSnapshot) => void;private now: () => number;private waits: (ref: ComputerHelpRef) => boolean;@@ -72,11 +74,26 @@ export class ComputerControl {};}+ /** Increases each time a hold on any key starts: a call notes it, then asks `lastTake` of whatever keys turn out to matter. */+ takeSequence(): number {+ return this.holdsStarted;+ }++ /** The `takeSequence` at which the latest hold on this key started, 0 for none, so a take and hand-back between two snapshots still shows. */+ lastTake(botId: string): number {+ return this.lastHoldStarted.get(botId) ?? 0;+ }++ private hold(botId: string, entry: Entry | undefined, controlLeaseId: string | null): void {+ this.entries.set(botId, { heldSinceMs: this.now(), pleas: entry?.pleas ?? [], controlLeaseId });+ this.lastHoldStarted.set(botId, ++this.holdsStarted);+ }+/** Idempotent: a second click must not reset `heldSinceMs`. */take(botId: string): ControlSnapshot {const entry = this.entries.get(botId);if (entry?.heldSinceMs != null) return this.snapshot(botId);- this.entries.set(botId, { heldSinceMs: this.now(), pleas: entry?.pleas ?? [], controlLeaseId: null });+ this.hold(botId, entry, null);return this.changed(botId);}@@ -91,7 +108,7 @@ export class ComputerControl {if (owned && options.armed) this.beat(botId, controlLeaseId);return { snapshot: this.snapshot(botId), owned, acquired: false };}- this.entries.set(botId, { heldSinceMs: this.now(), pleas: entry?.pleas ?? [], controlLeaseId });+ this.hold(botId, entry, controlLeaseId);if (options.armed) this.beat(botId, controlLeaseId);return { snapshot: this.changed(botId), owned: true, acquired: true };}@@ -169,6 +186,7 @@ export class ComputerControl {/** Removes the deleted bot's pleas from every key; holds stay. */forgetBot(botId: string): void {this.forgetPleas((ref) => ref.botId === botId);+ this.lastHoldStarted.delete(botId);}/** Removes the pleas of a deleted conversation's sign-in cards from every key, and returns the bots that asked; holds stay. */diff --git a/server/group-local-vm.e2e.test.ts b/server/group-local-vm.e2e.test.tsindex adb80eba26..985976b094 100644--- a/server/group-local-vm.e2e.test.ts+++ b/server/group-local-vm.e2e.test.ts@@ -1247,7 +1247,7 @@ describe("Group Local VM ownership on the real isolated server", () => {}});- it("does not perform a queued call after a person took the shared VM and handed it back while it waited", async () => {+ it("does not perform a queued call after a person took the shared VM and handed it back at once while it waited", async () => {vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });const { bot: auto } = await api("POST", "/api/bots", { name: "Handed-back Auto", browser: false });const { bot: holder } = await api("POST", "/api/bots", { name: "VM holder", computer: "vm", browser: false });@@ -1260,8 +1260,6 @@ describe("Group Local VM ownership on the real isolated server", () => {const waiting = check(autoComputer);await until(() => activityRows(auto.threadId, "Waiting for its turn on this computer"), count => count > 0);await api("POST", `/api/bots/${holder.id}/computer/control`, { action: "take" });- // The gate reads the person's hold on its 250 ms poll; nothing outside it signals that it has looked.- await new Promise(resolve => setTimeout(resolve, 600));await api("POST", `/api/bots/${holder.id}/computer/control`, { action: "release" });await api("POST", `/api/bots/${holder.id}/interrupt`, {});expect(await waiting).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_HANDED_BACK });diff --git a/server/host/computer-gate-answers.test.ts b/server/host/computer-gate-answers.test.tsindex c105edbc23..d0f5e3f1cf 100644--- a/server/host/computer-gate-answers.test.ts+++ b/server/host/computer-gate-answers.test.ts@@ -8,10 +8,13 @@ const waiter = { threadId: "waiter", generation: "2" };const third = { threadId: "third", generation: "3" };const SHARED = "computer:vm:shared";-function setup(personOn: string[] = []) {+const nobody = { held: () => false, lastTake: () => 0 };++function setup(personOn: string[] = [], seatTakes = new Map<string, number>(), sequence = { now: 0 }) {const resources = new TurnResources();const bound = new Map<string, { owner: TurnOwner; resource: string }>();- const answers = createComputerGateAnswers({ resources, bound: (threadId) => bound.get(threadId), personHolds: (resource) => personOn.includes(resource), pollMs: 10 });+ const answers = createComputerGateAnswers({ resources, bound: (threadId) => bound.get(threadId), personHolds: (resource) => personOn.includes(resource),+ personLastTake: (resource) => seatTakes.get(resource) ?? 0, takeSequence: () => sequence.now, pollMs: 10 });return { resources, bound, answers };}@@ -57,7 +60,7 @@ describe("what a screen call that was not performed tells the model", () => {resources.startWaiting(SHARED, waiter);let grant!: () => void;const begin = new Promise<void>((resolve) => { grant = resolve; });- const waited = answers.waitForClaim(begin, Date.now() + 5_000, waiter, () => false);+ const waited = answers.waitForClaim(begin, Date.now() + 5_000, waiter, nobody);await vi.advanceTimersByTimeAsync(10);personOn.push(SHARED);await vi.advanceTimersByTimeAsync(10);@@ -69,6 +72,34 @@ describe("what a screen call that was not performed tells the model", () => {}});+ it("remembers a take and hand-back of a seat the turn queues for only after its first look", async () => {+ const seatTakes = new Map([[SHARED, 3]]);+ const sequence = { now: 3 };+ const { resources, answers } = setup([], seatTakes, sequence);+ resources.claim(SHARED, holder);+ let grant!: () => void;+ const begin = new Promise<void>((resolve) => { grant = resolve; });+ const waited = answers.waitForClaim(begin, Date.now() + 5_000, waiter, nobody);+ resources.startWaiting(SHARED, waiter);+ sequence.now = 4;+ seatTakes.set(SHARED, 4);+ grant();+ expect(await waited).toBe(true);+ });++ it("does not count a hold that started before the call, on a key the turn reads only later", async () => {+ const sequence = { now: 7 };+ const { resources, answers } = setup([], new Map(), sequence);+ resources.startWaiting(SHARED, waiter);+ let lastTake = 0;+ let grant!: () => void;+ const begin = new Promise<void>((resolve) => { grant = resolve; });+ const waited = answers.waitForClaim(begin, Date.now() + 5_000, waiter, { held: () => false, lastTake: () => lastTake });+ lastTake = 7;+ grant();+ expect(await waited).toBe(false);+ });+it("sees no person when nobody took the seat, stops at its deadline, and listens to the claim once", async () => {vi.useFakeTimers();try {@@ -76,7 +107,7 @@ describe("what a screen call that was not performed tells the model", () => {resources.startWaiting(SHARED, waiter);const begin = new Promise<void>(() => {});const then = vi.spyOn(begin, "then");- const waited = answers.waitForClaim(begin, Date.now() + 1_000, waiter, () => false);+ const waited = answers.waitForClaim(begin, Date.now() + 1_000, waiter, nobody);await vi.advanceTimersByTimeAsync(1_000);expect(await waited).toBe(false);expect(then).toHaveBeenCalledTimes(1);diff --git a/server/host/computer-gate-answers.ts b/server/host/computer-gate-answers.tsindex de7b787ebf..68501f16e7 100644--- a/server/host/computer-gate-answers.ts+++ b/server/host/computer-gate-answers.ts@@ -4,11 +4,20 @@ import type { TurnOwner, TurnResources } from "../turn-resources.ts";export const PERSON_HOLDS = "person";+/** A person's hold on the keys a conversation's own computer reads, and the latest hold started on any of them. */+export interface PersonOnBot {+ held: () => boolean;+ lastTake: () => number;+}+export interface ComputerGateAnswersDeps {resources: TurnResources;/** The computer seat this thread's turn is bound to, if any. */bound: (threadId: string) => { owner: TurnOwner; resource: string } | undefined;personHolds: (resource: string) => boolean;+ /** The latest hold a person started on this seat, as a `takeSequence`, so a take and hand-back between two looks still shows. */+ personLastTake: (resource: string) => number;+ takeSequence: () => number;pollMs: number;}@@ -36,10 +45,10 @@ export function createComputerGateAnswers(deps: ComputerGateAnswersDeps) {}/**- * Waits for a pending claim while watching for a person's hold, and says whether one was seen: a click composed before- * a person took the screen and handed it back must not land on whatever is there now.+ * Waits for a pending claim and says whether a person took the computer meanwhile, even one who already handed it back:+ * a click composed before a person took the screen must not land on whatever is there now.*/- async function waitForClaim(begin: Promise<unknown>, until: number, owner: TurnOwner, personHere: () => boolean, signal?: AbortSignal): Promise<boolean> {+ async function waitForClaim(begin: Promise<unknown>, until: number, owner: TurnOwner, person: PersonOnBot, signal?: AbortSignal): Promise<boolean> {let settled = false;let wake: (() => void) | undefined;const settle = () => { settled = true; wake?.(); };@@ -50,11 +59,16 @@ export function createComputerGateAnswers(deps: ComputerGateAnswersDeps) {signal?.addEventListener("abort", done, { once: true });wake = done;});- let personSeen = false;- while (!settled && Date.now() < until && !signal?.aborted) {+ const since = deps.takeSequence();+ const personCame = (): boolean => {+ if (person.held() || person.lastTake() > since) return true;const seat = deps.resources.computerWaitOf(owner)?.resource ?? boundSeat(owner)?.resource;- if (personHere() || (seat !== undefined && deps.personHolds(seat))) personSeen = true;+ return seat !== undefined && (deps.personHolds(seat) || deps.personLastTake(seat) > since);+ };+ let personSeen = personCame();+ while (!settled && Date.now() < until && !signal?.aborted) {await tick(Math.min(deps.pollMs, until - Date.now()));+ personSeen = personCame() || personSeen;}return personSeen;}diff --git a/server/host/shared-vm-control.ts b/server/host/shared-vm-control.tsindex 1c05e1aec3..f9fe0a20d4 100644--- a/server/host/shared-vm-control.ts+++ b/server/host/shared-vm-control.ts@@ -12,7 +12,7 @@ const SHARED_VM_RESOURCE = `computer:vm:${SHARED_LOCAL_VM_TARGET.key}`;const SHARED_VM_VIEWER = viewerTargetId(SHARED_LOCAL_VM_TARGET);export interface SharedVmControlDeps {- control: Pick<ComputerControl, "snapshot" | "release" | "releaseLease" | "ownsLease" | "heldBy" | "beat" | "forgetBot">;+ control: Pick<ComputerControl, "snapshot" | "takeSequence" | "lastTake" | "release" | "releaseLease" | "ownsLease" | "heldBy" | "beat" | "forgetBot">;store: { readonly bots: BotRecord[]; bot(id: string): BotRecord | null; tasks(botId: string): ReadonlyArray<{ threadId: string; surface?: string }> };/** The Local VM mode; null in a Cloud home, which has no Local VM. */mode(): "shared" | "per-bot" | "pool" | null;@@ -79,11 +79,12 @@ export function createSharedVmControl(deps: SharedVmControlDeps) {/** A hold taken without a conversation pauses every conversation of the bot, as a hold on its own key does; a turn still* on the shared VM waits for its hold whatever its bot is set to now. */- const snapshot = (botId: string, threadId?: string): ControlSnapshot => {+ const threadKeys = (botId: string, threadId?: string): string[] => {const bot = threadId ? deps.botForThread(botId, threadId) : store.bot(botId);const mounted = threadId && sharedDesk() && deps.turnVmTargets.get(threadId)?.key === SHARED_LOCAL_VM_TARGET.key ? [SHARED_VM_CONTROL_KEY] : [];- return merged([...new Set([botId, ...(bot ? [keyFor(bot, threadId), keyFor(bot)] : []), ...mounted])]);+ return [...new Set([botId, ...(bot ? [keyFor(bot, threadId), keyFor(bot)] : []), ...mounted])];};+ const snapshot = (botId: string, threadId?: string): ControlSnapshot => merged(threadKeys(botId, threadId));/** What a bot's panels and the bot list are told: the first of its keys held, else the first pleading, else its own. */const botSnapshot = (botId: string): ControlSnapshot => {@@ -99,6 +100,7 @@ export function createSharedVmControl(deps: SharedVmControlDeps) {: sharedKey(key) ? store.bots.filter(bot => botKeys(bot).includes(key)).map(bot => bot.id) : [key];const personHolds = (resource: string): boolean => resource === SHARED_VM_RESOURCE && control.snapshot(SHARED_VM_CONTROL_KEY).held;+ const personLastTake = (resource: string): number => resource === SHARED_VM_RESOURCE ? control.lastTake(SHARED_VM_CONTROL_KEY) : 0;/** The hold this lease owns: the key a take resolved may differ now, as places, pins and team turns change. */const leaseHolder = (bot: BotRecord, threadId: string | undefined, lease: string): string => {@@ -118,6 +120,9 @@ export function createSharedVmControl(deps: SharedVmControlDeps) {return sharedDesk() && !teamKey(bot, threadId) && (place === undefined || place === "vm") ? SHARED_VM_CONTROL_KEY : null;},snapshot,+ takeSequence: (): number => control.takeSequence(),+ /** The latest hold started on any key `snapshot` reads for this conversation, as a `takeSequence`. */+ lastTake: (botId: string, threadId?: string): number => Math.max(0, ...threadKeys(botId, threadId).map(key => control.lastTake(key))),membersOf,botSnapshot,/** A snapshot carrying the bot's sign-in plea as this viewer may see it: an answer never hides a plea the bot's frames@@ -138,6 +143,8 @@ export function createSharedVmControl(deps: SharedVmControlDeps) {},/** True while a person holds the shared VM this turn resource names. */personHolds,+ /** The latest hold a person started on the shared VM this turn resource names, as a `takeSequence`. */+ personLastTake,sharedKey,signInKey: (bot: BotRecord, threadId: string, place: Surface): string => place === "browser" ? bot.id : keyFor(bot, threadId),keyMovesWhileHeld: (before: BotRecord, after: BotRecord): boolean =>diff --git a/server/index.ts b/server/index.tsindex cf055e089c..2e043d8f1c 100644--- a/server/index.ts+++ b/server/index.ts@@ -5559,7 +5559,7 @@ const localVmActiveThreads = new Map<string, string>();const autoVmClaims: AutoVmClaimTable = new Map();const COMPUTER_CALL_WAIT_MS = Math.min(CONTROL_WAIT_MS, Math.max(500, Number(process.env.OMB_COMPUTER_CALL_WAIT_MS) || CONTROL_WAIT_MS));const COMPUTER_CALL_ACT_WITHIN_MS = Math.min(CONTROL_ACT_WITHIN_MS, Math.max(100, Number(process.env.OMB_COMPUTER_CALL_ACT_WITHIN_MS) || CONTROL_ACT_WITHIN_MS));-const COMPUTER_CALL_POLL_MS = 250; const computerGateAnswers = createComputerGateAnswers({ resources: turnResources, bound: (threadId) => turnComputerResources.get(threadId), personHolds: (resource) => sharedVm.personHolds(resource), pollMs: COMPUTER_CALL_POLL_MS });+const COMPUTER_CALL_POLL_MS = 250; const computerGateAnswers = createComputerGateAnswers({ resources: turnResources, bound: (threadId) => turnComputerResources.get(threadId), personHolds: (resource) => sharedVm.personHolds(resource), personLastTake: (resource) => sharedVm.personLastTake(resource), takeSequence: () => sharedVm.takeSequence(), pollMs: COMPUTER_CALL_POLL_MS });const browserSeats = createBrowserSeats({ resources: turnResources, claim: claimTurnResource, active: (owner) => activeInternalGenerationByThread.get(owner.threadId) === owner.generation, working: (session) => browserRuntime.working(session), holderOf: holderOfTurn, language: threadLanguage, callWaitMs: COMPUTER_CALL_WAIT_MS, actWithinMs: COMPUTER_CALL_ACT_WITHIN_MS, ...(Number(process.env.OMB_BROWSER_IDLE_HANDOVER_MS) > 0 ? { idleHandoverMs: Number(process.env.OMB_BROWSER_IDLE_HANDOVER_MS) } : {}),row: (threadId, name, threadRef) => { store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name, ok: true }, ...(threadRef ? { threadRef } : {}) }); },waitStarted: (threadId, resource, position, holder) => bus.publish({ ...waitEventBase(threadId), type: "turn.wait_started", resource, position, ...(holder ? { holder } : {}) }),@@ -5655,7 +5655,7 @@ async function computerCallGate(internalCapability: InternalCapability, signal?:} else if (lazyClaim?.lazy && !lazyClaim.claimed) {startAutoVmClaim(autoVmClaims, threadId, generation, call);if (lazyClaim.begin && Date.now() < deadline && !signal?.aborted) {- if (await computerGateAnswers.waitForClaim(lazyClaim.begin, deadline, { threadId, generation }, () => sharedVm.snapshot(botId, threadId).held, signal)) personHeld = true;+ if (await computerGateAnswers.waitForClaim(lazyClaim.begin, deadline, { threadId, generation }, { held: () => sharedVm.snapshot(botId, threadId).held, lastTake: () => sharedVm.lastTake(botId, threadId) }, signal)) personHeld = true;if (lazyClaim.claimed || lazyClaim.failed || sharedVm.snapshot(botId, threadId).held) continue;if (lazyClaim.retryReason) return { held: true, helpOpen: false, blockedReason: lazyClaimRetryText(lazyClaim) };}