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 waiting turn's model is told its place in line, not who holds the computer
laijsg15cedb24debcc
diff --git a/docs/verification/computer-wait.md b/docs/verification/computer-wait.mdindex ed33c9c907..35d83d7894 100644--- a/docs/verification/computer-wait.md+++ b/docs/verification/computer-wait.md@@ -9,6 +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```The shared-team-computer case proves:@@ -56,6 +58,30 @@ The park-and-resume cases prove:re-run queue are gone. A parked root waits through the runtime's admission(the host's busy hook holds it until the seat frees).+The model-facing answer cases prove what a waiting turn's model reads when a+screen call is not performed, from what holds at that moment:++- Another turn holds the computer: the answer says so, gives this turn's place+ in line, how long the other thread has had it and recent waits, and never+ names the holding bot, task or room. The person's waiting chip still does.+- Nobody holds it (its own desktop is still getting ready, or this turn already+ has the seat and waits for readiness): the answer says the computer is not+ ready 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.+- At the wait ceiling the parked turn hears that it waited without getting the+ computer and should stop calling the computer tools; not a start failure, no+ holder, and no promise to resume (a goal step that parks is reassigned).+- A call answered late after waiting says the turn now has the computer only+ when the server sees it holding the seat. The bridge's own late answer, for a+ call that only sat behind the previous one, says the call waited too long to+ run and nothing about the computer. Saved steps still read+ every one of these as the gate's refusal, and each fits the 300 characters a+ fallback hands the model.+Waiting is bounded by the computer wait ceiling (`OMB_COMPUTER_WAIT_MAX_MS`,30 minutes by default). At the ceiling the turn parks instead of failing, andits root continues on its own when the computer is free. Cancellation checksdiff --git a/server/auto-vm-claims.test.ts b/server/auto-vm-claims.test.tsindex f39796f8f2..b81b20111b 100644--- a/server/auto-vm-claims.test.ts+++ b/server/auto-vm-claims.test.ts@@ -198,6 +198,20 @@ describe("startAutoVmClaim", () => {describe("lazyClaimFailedText", () => {const boat = { label: "the cloud computer", startsComputer: true as const, failure: "Miso's cloud desktop didn't start. This conversation is back on Auto. Send your message again." };+ it("gives a parked claim's own words instead of a start failure, for a team computer parked before its machine was looked up", async () => {+ const table: AutoVmClaimTable = new Map();+ const parkedRefusal = "This turn waited 30 minutes for this computer without getting it, so this call was NOT performed. Stop calling the computer tools now; nothing is broken.";+ const onRejected = vi.fn();+ table.set("t", { ...boat, owner: { threadId: "t", generation: "g" }, lazy: true, onRejected,+ claim: async () => { throw Object.assign(new Error("Computer still busy after 30 minutes. Parked — it continues automatically when the computer is free."), { parkedRefusal }); } });+ startAutoVmClaim(table, "t", "g");+ await table.get("t")!.begin;+ const slot = table.get("t")!;+ expect(slot.failed).toBe(true);+ expect(lazyClaimFailedText(slot)).toBe(parkedRefusal);+ expect(onRejected).toHaveBeenCalledTimes(1);+ });+it("gives the bot the computer's own reason, and says the conversation is back on Auto only when it is", () => {expect(lazyClaimFailedText({ ...boat, cause: "the cloud computer could not be created or reached", backOnAuto: true })).toBe("The cloud computer could not be started: the cloud computer could not be created or reached. This call was not performed. " +diff --git a/server/auto-vm-claims.ts b/server/auto-vm-claims.tsindex adcf5e9619..01a3d453f0 100644--- a/server/auto-vm-claims.ts+++ b/server/auto-vm-claims.ts@@ -18,6 +18,8 @@ export interface AutoVmClaimSlot {cause?: string;/** The plan's limit that turned the computer away, as one sentence for the bot: said in place of `cause`. */limit?: string;+ /** The claim waited out the computer wait ceiling: what the screen calls hear instead of a start failure. */+ parked?: string;/** The failure took the conversation's automatic pick off this computer. */backOnAuto?: boolean;/** The last claim failed on the network; the next screen call claims again. */@@ -76,6 +78,8 @@ export function startAutoVmClaim(table: AutoVmClaimTable, threadId: string, gene}slot.failed = true;slot.failure = failure;+ const parked = (error as { parkedRefusal?: unknown } | null)?.parkedRefusal;+ if (typeof parked === "string") slot.parked = parked;// A person's No is an answer, not a failure: the screen calls say so, and nothing reports a broken turn.if ((error as { declined?: unknown } | null)?.declined !== true) slot.onRejected?.(slot.failure, error);},@@ -99,7 +103,8 @@ export async function reclaimAutoVm(table: AutoVmClaimTable, owner: AutoVmClaimO}/** What every screen call hears for the rest of a turn whose computer could not be claimed. */-export function lazyClaimFailedText(slot: Pick<AutoVmClaimSlot, "label" | "failure" | "cause" | "limit" | "startsComputer" | "backOnAuto">): string {+export function lazyClaimFailedText(slot: Pick<AutoVmClaimSlot, "label" | "failure" | "cause" | "limit" | "startsComputer" | "backOnAuto" | "parked">): string {+ if (slot.parked) return slot.parked;const label = slot.label ?? "this computer";const why = (slot.cause ?? slot.failure)?.trim().replace(/[\s.]+$/, "");if (!slot.startsComputer) {diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex 313d7fca50..651ee1ac8b 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -7,7 +7,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";import { afterAll, beforeAll, describe, expect, it } from "vitest";-import { CONTROL_WAITED } from "./control-client.ts";+import { CONTROL_WAITED, CONTROL_WAITED_HELD } from "./control-client.ts";import { CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_REPLACED_BY_PERSON, cloudComputerSetAsideNotice } from "../shared/cloud-computer-recovery.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { freePortBlock } from "./testing/ports.ts";@@ -358,7 +358,7 @@ describe("a cloud computer starts only when the bot uses it", () => {const next = await startTurn(bot.id, "Look again");expect(resumes()).toBe(0);const waited = await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });- expect(waited.body.result).toEqual({ isError: true, content: [{ type: "text", text: CONTROL_WAITED }] });+ expect(waited.body.result).toEqual({ isError: true, content: [{ type: "text", text: CONTROL_WAITED_HELD }] });expect(resumes()).toBe(1);const woken = await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });expect(woken.body.result.isError, JSON.stringify(woken.body)).toBeFalsy();@@ -372,7 +372,7 @@ describe("a cloud computer starts only when the bot uses it", () => {const callThroughWait = async (sent: any) => {let result = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });- for (let tries = 0; result.body.result.content?.[0]?.text === CONTROL_WAITED && tries < 3; tries++) {+ for (let tries = 0; [CONTROL_WAITED, CONTROL_WAITED_HELD].includes(result.body.result.content?.[0]?.text) && tries < 3; tries++) {result = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });}return result;diff --git a/server/computer-wait.test.ts b/server/computer-wait.test.tsindex 1c47adbb25..1a8f91f9ee 100644--- a/server/computer-wait.test.ts+++ b/server/computer-wait.test.ts@@ -1,11 +1,16 @@import { describe, expect, it } from "vitest";+import { CONTROL_BUSY, CONTROL_BUSY_OPENING, CONTROL_CALL_LATE, CONTROL_NOT_READY, CONTROL_NOT_READY_OPENING, CONTROL_WAITED, CONTROL_WAITED_HELD } from "./control-client.ts";import {+ computerBusyText,computerFreeAfterText,+ computerParkedRefusal,+ computerQueuedText,computerParkedText,computerStoppedWaitingText,computerWaitDuration,computerWaitingText,+ isComputerParkedRefusal,} from "./computer-wait.ts";describe("computer wait wording", () => {@@ -83,3 +88,48 @@ describe("computer wait wording", () => {);});});++describe("what a waiting turn's model reads", () => {+ const longest = "under a second";+ it("says another thread holds it, with its queue place and timings, and never who", () => {+ expect(computerBusyText({ position: 1, heldForMs: 120_000, estimateMs: 180_000 })).toBe(+ "Another thread is using this computer. This call was not performed. No screen or app state was checked. " ++ "This turn is 1st in line (the other thread has had it 2 minutes; recent waits 3 minutes) and gets it automatically. To keep waiting, take a screenshot.",+ );+ });++ it("promises no automatic seat when the turn is not in the queue", () => {+ const text = computerBusyText({ heldForMs: 5_000 });+ expect(text.startsWith(CONTROL_BUSY_OPENING)).toBe(true);+ expect(text).toContain("The other thread has had it 5 seconds. To check again");+ expect(text).not.toContain("automatically");+ expect(computerBusyText({ heldForMs: 120_000, estimateMs: 180_000 })).toContain("The other thread has had it 2 minutes; recent waits 3 minutes.");+ expect(computerBusyText({})).not.toContain("(");+ });++ it("reports a queue place without claiming anyone holds the computer", () => {+ const text = computerQueuedText({ position: 2, estimateMs: 3_000 });+ expect(text).toBe(+ "This computer is not ready for this turn yet, so this call was NOT performed. This turn is 2nd in line (recent waits 3 seconds) and gets it automatically. " ++ "No screen or app state was checked. To keep waiting, take a screenshot.",+ );+ expect(text.startsWith(CONTROL_NOT_READY_OPENING)).toBe(true);+ expect(text).not.toContain("Another thread");+ });++ it("parks without a holder, a failure, or a promise to continue", () => {+ const text = computerParkedRefusal(30 * 60_000);+ expect(text).toBe("This turn waited 30 minutes for this computer without getting it, so this call was NOT performed. Stop calling the computer tools now; nothing is broken.");+ expect(isComputerParkedRefusal(text)).toBe(true);+ expect(isComputerParkedRefusal(computerParkedRefusal(1_000))).toBe(true);+ expect(isComputerParkedRefusal("This turn waited 5 seconds for the application window to appear.")).toBe(false);+ });++ it("fits the 300 characters a saved-steps fallback hands the model, at its longest", () => {+ const facts = { position: 12, heldForMs: 500, estimateMs: 500 };+ expect(computerWaitDuration(500)).toBe(longest);+ for (const text of [computerBusyText(facts), computerBusyText({ heldForMs: 500, estimateMs: 500 }), computerQueuedText(facts), computerParkedRefusal(59 * 60_000), CONTROL_BUSY, CONTROL_NOT_READY, CONTROL_WAITED, CONTROL_WAITED_HELD, CONTROL_CALL_LATE]) {+ expect(text.length).toBeLessThanOrEqual(300);+ }+ });+});diff --git a/server/computer-wait.ts b/server/computer-wait.tsindex c2f0874fd7..e7ed3de3e8 100644--- a/server/computer-wait.ts+++ b/server/computer-wait.ts@@ -1,3 +1,5 @@+import { CONTROL_BUSY_OPENING, CONTROL_NOT_READY_OPENING } from "./control-client.ts";+export interface ComputerHolder {name: string;task?: string;@@ -61,3 +63,40 @@ export function computerPersonAwayText(ceilingMs: number): string {return `A person has had control of this computer for over ${minutes(ceilingMs)}, so this call was NOT performed and this turn stops waiting for them. ` +"Pause this task: tell the person you are waiting for them to hand control back, and take a fresh screenshot before your next action once they have.";}++/** No holder (the seat may be between turns), and no promise to resume: a goal step that parks is reassigned, not continued. */+export function computerParkedRefusal(ceilingMs: number): string {+ return `This turn waited ${minutes(ceilingMs)} for this computer without getting it, so this call was NOT performed. ` ++ "Stop calling the computer tools now; nothing is broken.";+}++export const isComputerParkedRefusal = (text: string): boolean =>+ /^This turn waited \d+ (?:second|minute)s? for this computer without getting it, so this call was NOT performed\./u.test(text);++export interface ComputerContention {+ position?: number;+ heldForMs?: number;+ estimateMs?: number;+}++const timings = (facts: ComputerContention, held: boolean): string[] => [+ held && facts.heldForMs !== undefined ? `the other thread has had it ${computerWaitDuration(facts.heldForMs)}` : "",+ facts.estimateMs !== undefined ? `recent waits ${computerWaitDuration(facts.estimateMs)}` : "",+].filter(Boolean);+const inBrackets = (parts: string[]): string => (parts.length ? ` (${parts.join("; ")})` : "");++export function computerBusyText(facts: ComputerContention): string {+ const head = `${CONTROL_BUSY_OPENING} This call was not performed. No screen or app state was checked.`;+ const parts = timings(facts, true);+ if (!facts.position) {+ const said = parts.length ? ` ${parts.join("; ").replace(/^t/u, "T")}.` : "";+ return `${head}${said} To check again, take a screenshot instead of ending your turn.`;+ }+ return `${head} This turn is ${ordinal(facts.position)} in line${inBrackets(parts)} and gets it automatically. To keep waiting, take a screenshot.`;+}++/** Queued, but nobody holds the seat at this instant (the turn ahead has not taken it yet). */+export function computerQueuedText(facts: ComputerContention & { position: number }): string {+ return `${CONTROL_NOT_READY_OPENING}, so this call was NOT performed. This turn is ${ordinal(facts.position)} in line${inBrackets(timings(facts, false))} and gets it automatically. ` ++ "No screen or app state was checked. To keep waiting, take a screenshot.";+}diff --git a/server/control-client.ts b/server/control-client.tsindex 0d5f475271..aba69837ed 100644--- a/server/control-client.ts+++ b/server/control-client.ts@@ -21,10 +21,25 @@ export const CONTROL_HANDED_BACK ="Take a fresh screenshot, then continue the task.";export const CONTROL_WAITED ="This computer is free now, but this call had to wait for it, so it was NOT performed. " +- "Call again: the next call goes through at once. If you meant to click or type from an earlier screenshot, take a fresh one first — the screen may have changed while you waited.";+ "Call again. If you meant to click or type from an earlier screenshot, take a fresh one first — the screen may have changed while you waited.";+/** Only when the server knows this turn now holds the computer's seat: a late bridge answer or a wake-up wait proves no hand-over. */+export const CONTROL_WAITED_HELD =+ "This computer is free now, but this call had to wait for it, so it was NOT performed. This turn now has this computer. " ++ "Call again. If you meant to click or type from an earlier screenshot, take a fresh one first — the screen may have changed while you waited.";+/** The bridge's own answer for a call that sat behind the previous one: nothing says the computer was busy. */+export const CONTROL_CALL_LATE =+ "This call waited too long before it could run, so it was NOT performed. " ++ "Call again. If you meant to click or type from an earlier screenshot, take a fresh one first — the screen may have changed while you waited.";+export const CONTROL_BUSY_OPENING = "Another thread is using this computer.";+const NOT_CHECKED = "No screen or app state was checked.";+/** Another turn holds the seat right now; never says who, since the waiting model may not be allowed to see that thread. */export const CONTROL_BUSY =- "Another thread is using this computer. This call was not performed. This turn gets the computer as soon as it is free: " +- `to keep waiting, take a screenshot (each computer call waits up to ${WAIT_WORDS}) instead of ending your turn.`;+ `${CONTROL_BUSY_OPENING} This call was not performed. ${NOT_CHECKED} ` ++ `To check again, take a screenshot (each computer call waits up to ${WAIT_WORDS}) instead of ending your turn.`;+export const CONTROL_NOT_READY_OPENING = "This computer is not ready for this turn yet";+export const CONTROL_NOT_READY =+ `${CONTROL_NOT_READY_OPENING}, so this call was NOT performed. It may still be starting or being prepared; no screen or app state was checked. ` ++ `To keep waiting, take a screenshot (each computer call waits up to ${WAIT_WORDS}).`;export const CONTROL_UNCONFIRMED ="OpenMausBot could not confirm that this computer is free, so this call was NOT performed and nothing happened on the screen. " +"Retry in a few seconds.";diff --git a/server/group-local-vm.e2e.test.ts b/server/group-local-vm.e2e.test.tsindex f6e6a30f69..adb80eba26 100644--- a/server/group-local-vm.e2e.test.ts+++ b/server/group-local-vm.e2e.test.ts@@ -10,7 +10,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";import { writeFileAtomic } from "./atomic.ts";import { cloudHomePrompt } from "./system-prompt.ts";import { availableTools, catalogProfileFromEnv } from "./drivers/agents-catalog.ts";-import { CONTROL_BUSY, CONTROL_REFUSAL_PLAIN, controlRefusal, createControlClient } from "./control-client.ts";+import { CONTROL_HANDED_BACK, CONTROL_REFUSAL_PLAIN, controlRefusal, createControlClient } from "./control-client.ts";import { freePortBlock } from "./testing/ports.ts";import { readHandoffs } from "./testing/handoff-rows.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";@@ -1126,7 +1126,9 @@ describe("Group Local VM ownership on the real isolated server", () => {expect((await gate(holderComputer)).status).toBe(200);const started = Date.now();const first = await check(autoComputer);- expect(first).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_BUSY });+ expect(first.held).toBe(true);+ expect(first.blockedReason).toMatch(/^Another thread is using this computer\. This call was not performed\. No screen or app state was checked\. This turn is 1st in line/);+ expect(first.blockedReason).not.toContain("VM holder");expect(controlRefusal(first)).not.toBe(CONTROL_REFUSAL_PLAIN);expect(Date.now() - started).toBeGreaterThanOrEqual(CALL_WAIT_MS - 200);await until(async () => {@@ -1149,6 +1151,127 @@ describe("Group Local VM ownership on the real isolated server", () => {}});+ it("tells a waiting turn its queue place without naming the private task that holds the computer, then parks it without a failure", async () => {+ await waitForExit(child, { signal: "SIGTERM" });+ await startServer(5_000);+ vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });+ const { bot: holder } = await api("POST", "/api/bots", { name: "Payroll Holder", computer: "vm", browser: false });+ const { bot: auto } = await api("POST", "/api/bots", { name: "Queued Auto", browser: false });+ const secret = "Private payroll review";+ try {+ await api("POST", `/api/bots/${auto.id}/messages`, { text: "Take a screenshot when free" });+ const autoComputer = computer(await dump());+ rmSync(dumpFile, { force: true });+ const { task } = await api("POST", `/api/bots/${holder.id}/tasks`, { title: secret });+ await api("POST", `/api/bots/${holder.id}/messages`, { text: "Hold the VM", threadId: task.threadId });+ expect((await gate(computer(await dump()))).status).toBe(200);++ const busy = await check(autoComputer);+ expect(busy.blockedReason).toMatch(/^Another thread is using this computer\. This call was not performed\. No screen or app state was checked\. This turn is 1st in line/);+ const parked = await check(autoComputer);+ expect(parked.blockedReason).toBe("This turn waited 5 seconds for this computer without getting it, so this call was NOT performed. Stop calling the computer tools now; nothing is broken.");+ for (const said of [busy.blockedReason, parked.blockedReason]) {+ expect(said).not.toContain(secret);+ expect(said).not.toContain("Payroll Holder");+ expect(said).not.toMatch(/could not be started|could not claim/);+ }+ // The person still sees who held it.+ expect(await activityRows(auto.threadId, "Payroll Holder")).toBeGreaterThan(0);+ } finally {+ writeFileSync(finishFile, "finish");+ for (const bot of [auto, holder]) { await api("POST", `/api/bots/${bot.id}/interrupt`, {}); await idle(bot.id); await api("DELETE", `/api/bots/${bot.id}`); }+ vmState();+ await waitForExit(child, { signal: "SIGTERM" });+ await startServer();+ }+ }, 60_000);++ it("says its own desktop is not ready, not that another thread has it, while nobody holds it", async () => {+ vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });+ const { bot: auto } = await api("POST", "/api/bots", { name: "Slow desktop Auto", browser: false });+ try {+ await api("POST", `/api/bots/${auto.id}/messages`, { text: "Take a screenshot" });+ const autoComputer = computer(await dump());+ vmState({ blockedTarget: "shared" });+ const first = await check(autoComputer);+ expect(first.blockedReason).toMatch(/^This computer is not ready for this turn yet, so this call was NOT performed\./);+ expect(first.blockedReason).not.toContain("Another thread");+ } finally {+ vmState();+ writeFileSync(finishFile, "finish");+ await api("POST", `/api/bots/${auto.id}/interrupt`, {}); await idle(auto.id);+ await api("DELETE", `/api/bots/${auto.id}`);+ }+ });++ it("stops saying another thread has it once the turn holds the seat and only its desktop is still getting ready", async () => {+ vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });+ const { bot: auto } = await api("POST", "/api/bots", { name: "Seated slow Auto", browser: false });+ const { bot: holder } = await api("POST", "/api/bots", { name: "VM holder", computer: "vm", browser: false });+ try {+ await api("POST", `/api/bots/${auto.id}/messages`, { text: "Take a screenshot when free" });+ const autoComputer = computer(await dump());+ rmSync(dumpFile, { force: true });+ await api("POST", `/api/bots/${holder.id}/messages`, { text: "Hold the VM" });+ expect((await gate(computer(await dump()))).status).toBe(200);+ expect((await check(autoComputer)).blockedReason).toMatch(/^Another thread is using this computer\./);+ vmState({ blockedTarget: "shared" });+ await api("POST", `/api/bots/${holder.id}/interrupt`, {}); await idle(holder.id);+ const seated = await check(autoComputer);+ expect(seated.blockedReason).toMatch(/^This computer is not ready for this turn yet, so this call was NOT performed\. It may still be starting/);+ } finally {+ vmState();+ writeFileSync(finishFile, "finish");+ for (const bot of [auto, holder]) { await api("POST", `/api/bots/${bot.id}/interrupt`, {}); await idle(bot.id); await api("DELETE", `/api/bots/${bot.id}`); }+ }+ });++ it("answers with the person's hold, not another thread, when a person takes the shared VM during a queued call", async () => {+ vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });+ const { bot: auto } = await api("POST", "/api/bots", { name: "Person-blocked Auto", browser: false });+ const { bot: holder } = await api("POST", "/api/bots", { name: "VM holder", computer: "vm", browser: false });+ try {+ await api("POST", `/api/bots/${auto.id}/messages`, { text: "Take a screenshot when free" });+ const autoComputer = computer(await dump());+ rmSync(dumpFile, { force: true });+ await api("POST", `/api/bots/${holder.id}/messages`, { text: "Hold the VM" });+ expect((await gate(computer(await dump()))).status).toBe(200);+ 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" });+ expect(await waiting).toMatchObject({ held: true, reason: "person" });+ } finally {+ await api("POST", `/api/bots/${holder.id}/computer/control`, { action: "release" });+ writeFileSync(finishFile, "finish");+ for (const bot of [auto, holder]) { await api("POST", `/api/bots/${bot.id}/interrupt`, {}); await idle(bot.id); await api("DELETE", `/api/bots/${bot.id}`); }+ }+ });++ it("does not perform a queued call after a person took the shared VM and handed it back 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 });+ try {+ await api("POST", `/api/bots/${auto.id}/messages`, { text: "Click when free" });+ const autoComputer = computer(await dump());+ rmSync(dumpFile, { force: true });+ await api("POST", `/api/bots/${holder.id}/messages`, { text: "Hold the VM" });+ expect((await gate(computer(await dump()))).status).toBe(200);+ 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 });+ } finally {+ await api("POST", `/api/bots/${holder.id}/computer/control`, { action: "release" });+ writeFileSync(finishFile, "finish");+ for (const bot of [auto, holder]) { await api("POST", `/api/bots/${bot.id}/interrupt`, {}); await idle(bot.id); await api("DELETE", `/api/bots/${bot.id}`); }+ }+ });+it("ends the turn with a terminal error after a rejected lazy claim (issues #1361 F1, #1369)", async () => {vmState(); rmSync(dumpFile, { force: true }); rmSync(finishFile, { force: true });const { bot: chief } = await api("POST", "/api/bots", { name: "Rejected claim chief" });diff --git a/server/host-lazy-claim.e2e.test.ts b/server/host-lazy-claim.e2e.test.tsindex d8814decaf..1b83044d33 100644--- a/server/host-lazy-claim.e2e.test.ts+++ b/server/host-lazy-claim.e2e.test.ts@@ -5,7 +5,7 @@ import { dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";import { writeFileAtomic } from "./atomic.ts";-import { CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_REFUSAL_PLAIN, CONTROL_WAITED, controlRefusal, createControlClient } from "./control-client.ts";+import { CONTROL_HANDED_BACK, CONTROL_REFUSAL_PLAIN, CONTROL_WAITED_HELD, controlRefusal, createControlClient } from "./control-client.ts";import { computerPersonAwayText } from "./computer-wait.ts";import { hostTimeout } from "./testing/host-timeout.ts";import { freePortBlock } from "./testing/ports.ts";@@ -215,7 +215,8 @@ describe("lazy host claim and pin on use (issue #1650)", () => {await apiOk("POST", `/api/bots/${second.id}/messages`, { text: "Also work slowly.", threadId: secondTask.threadId });await busy(second.id, secondTask.threadId);const contested = await timed(withAnswer(base, secondTask.threadId, gate(mountedComputer(await dumpFor(second.id)))));- expect(contested.value).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_BUSY });+ expect(contested.value).toMatchObject({ held: true, helpOpen: false, blockedReason: expect.stringMatching(/^Another thread is using this computer\. This call was not performed\. No screen or app state was checked\. This turn is 1st in line/) });+ expect(contested.value.blockedReason).not.toContain("Host Screen Bot");expect(controlRefusal(contested.value)).not.toBe(CONTROL_REFUSAL_PLAIN);expect(contested.ms).toBeGreaterThanOrEqual(CALL_WAIT_MS - 200);writeFileSync(finishFile, "finish");@@ -243,7 +244,7 @@ describe("lazy host claim and pin on use (issue #1650)", () => {await new Promise(resolve => setTimeout(resolve, ACT_WITHIN_MS + 200));await apiOk("POST", `/api/bots/${holder.bot.id}/interrupt`, { threadId: holder.threadId });const freed = await waiting;- expect(freed.value).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_WAITED });+ expect(freed.value).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_WAITED_HELD });expect(freed.ms).toBeLessThan(CALL_WAIT_MS);const next = await timed(gate(waiter.computer));expect(next.value).toEqual({ held: false, helpOpen: false });diff --git a/server/host/computer-gate-answers.test.ts b/server/host/computer-gate-answers.test.tsnew file mode 100644index 0000000000..c105edbc23--- /dev/null+++ b/server/host/computer-gate-answers.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it, vi } from "vitest";+import { CONTROL_WAITED, CONTROL_WAITED_HELD } from "../control-client.ts";+import { TurnResources, type TurnOwner } from "../turn-resources.ts";+import { createComputerGateAnswers, PERSON_HOLDS } from "./computer-gate-answers.ts";++const holder = { threadId: "holder", generation: "1" };+const waiter = { threadId: "waiter", generation: "2" };+const third = { threadId: "third", generation: "3" };+const SHARED = "computer:vm:shared";++function setup(personOn: string[] = []) {+ 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 });+ return { resources, bound, answers };+}++describe("what a screen call that was not performed tells the model", () => {+ it("says another thread has it, with the queue place, while one holds the seat", () => {+ const { resources, answers } = setup();+ resources.claim(SHARED, holder);+ resources.startWaiting(SHARED, waiter);+ expect(answers.contention(waiter)).toMatch(/^Another thread is using this computer\. .* This turn is 1st in line \(the other thread has had it /);+ });++ it("gives a queue place without claiming a holder between turns", () => {+ const { resources, answers } = setup();+ resources.claim(SHARED, holder);+ resources.startWaiting(SHARED, waiter);+ resources.release(holder);+ resources.startWaiting(SHARED, third);+ expect(answers.contention(third)).toMatch(/^This computer is not ready for this turn yet, .* This turn is 2nd in line/);+ });++ it("answers with the person's hold on the seat the turn queues for, though its own computer key names another", () => {+ const { resources, answers } = setup([SHARED]);+ resources.claim(SHARED, holder);+ resources.startWaiting(SHARED, waiter);+ expect(answers.contention(waiter)).toBe(PERSON_HOLDS);+ expect(answers.held(PERSON_HOLDS, true)).toEqual({ held: true, helpOpen: true, reason: "person" });+ });++ it("has nothing to say once the turn holds its seat and only waits for readiness", () => {+ const { resources, bound, answers } = setup();+ resources.claim(SHARED, waiter);+ bound.set(waiter.threadId, { owner: waiter, resource: SHARED });+ expect(answers.contention(waiter)).toBeUndefined();+ expect(answers.contention(third)).toBeUndefined();+ });++ it("remembers a person who took the queued seat and handed it back while the claim was pending", async () => {+ vi.useFakeTimers();+ try {+ const personOn: string[] = [];+ const { resources, answers } = setup(personOn);+ resources.claim(SHARED, holder);+ 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);+ await vi.advanceTimersByTimeAsync(10);+ personOn.push(SHARED);+ await vi.advanceTimersByTimeAsync(10);+ personOn.length = 0;+ grant();+ expect(await waited).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ it("sees no person when nobody took the seat, stops at its deadline, and listens to the claim once", async () => {+ vi.useFakeTimers();+ try {+ const { resources, answers } = setup();+ 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);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(await waited).toBe(false);+ expect(then).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it("says the turn now has the computer only for a seat it holds in this generation", () => {+ const { resources, bound, answers } = setup();+ expect(answers.waited(waiter)).toBe(CONTROL_WAITED);+ bound.set(waiter.threadId, { owner: waiter, resource: SHARED });+ expect(answers.waited(waiter)).toBe(CONTROL_WAITED);+ resources.claim(SHARED, waiter);+ expect(answers.waited(waiter)).toBe(CONTROL_WAITED_HELD);+ expect(answers.waited({ ...waiter, generation: "older" })).toBe(CONTROL_WAITED);+ });+});diff --git a/server/host/computer-gate-answers.ts b/server/host/computer-gate-answers.tsnew file mode 100644index 0000000000..de7b787ebf--- /dev/null+++ b/server/host/computer-gate-answers.ts@@ -0,0 +1,74 @@+import { CONTROL_WAITED, CONTROL_WAITED_HELD, type ControlState } from "../control-client.ts";+import { computerBusyText, computerQueuedText } from "../computer-wait.ts";+import type { TurnOwner, TurnResources } from "../turn-resources.ts";++export const PERSON_HOLDS = "person";++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;+ pollMs: number;+}++/** What a screen call that was not performed tells the model, from what holds at that moment. */+export function createComputerGateAnswers(deps: ComputerGateAnswersDeps) {+ const boundSeat = (owner: TurnOwner) => {+ const bound = deps.bound(owner.threadId);+ return bound && bound.owner.generation === owner.generation ? bound : undefined;+ };++ /**+ * Checked on the seat the turn actually queues for: a bot falling back to the shared desktop waits on a resource its+ * own control key does not name. A queue place alone never claims that another thread is using the computer.+ */+ function contention(owner: TurnOwner): string | undefined {+ const waiting = deps.resources.computerWaitOf(owner);+ const resource = waiting?.resource ?? boundSeat(owner)?.resource;+ if (!resource) return undefined;+ if (deps.personHolds(resource)) return PERSON_HOLDS;+ const blocker = deps.resources.blocker(resource, owner);+ const since = deps.resources.holderSince(resource);+ const facts = { estimateMs: deps.resources.waitEstimateMs(resource), ...(blocker && since !== undefined ? { heldForMs: Date.now() - since } : {}) };+ if (blocker) return computerBusyText({ ...facts, ...(waiting ? { position: waiting.position } : {}) });+ return waiting ? computerQueuedText({ ...facts, position: waiting.position }) : undefined;+ }++ /**+ * 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.+ */+ async function waitForClaim(begin: Promise<unknown>, until: number, owner: TurnOwner, personHere: () => boolean, signal?: AbortSignal): Promise<boolean> {+ let settled = false;+ let wake: (() => void) | undefined;+ const settle = () => { settled = true; wake?.(); };+ begin.then(settle, settle);+ const tick = (ms: number) => new Promise<void>((resolve) => {+ const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); wake = undefined; resolve(); };+ const timer = setTimeout(done, Math.max(0, ms));+ signal?.addEventListener("abort", done, { once: true });+ wake = done;+ });+ let personSeen = false;+ while (!settled && Date.now() < until && !signal?.aborted) {+ const seat = deps.resources.computerWaitOf(owner)?.resource ?? boundSeat(owner)?.resource;+ if (personHere() || (seat !== undefined && deps.personHolds(seat))) personSeen = true;+ await tick(Math.min(deps.pollMs, until - Date.now()));+ }+ return personSeen;+ }++ return {+ contention,+ waitForClaim,+ held(reason: string, helpOpen: boolean): ControlState {+ return reason === PERSON_HOLDS ? { held: true, helpOpen, reason: "person" } : { held: true, helpOpen: false, blockedReason: reason };+ },+ /** "Now has this computer" only for a seat the server sees this turn holding. */+ waited(owner: TurnOwner): string {+ const bound = boundSeat(owner);+ return bound && deps.resources.owns(bound.resource, bound.owner) ? CONTROL_WAITED_HELD : CONTROL_WAITED;+ },+ };+}diff --git a/server/index.ts b/server/index.tsindex 74309df0c0..cf055e089c 100644--- a/server/index.ts+++ b/server/index.ts@@ -498,8 +498,8 @@ import { newBotWorksOn, shouldMountLocalComputer } from "./local-routing.ts";import { autoLocalVmAttachable, type ContainerComputerStatus } from "./container-computer.ts";import { startStoppedPodmanMachine } from "./podman-machine.ts";import { keepTransient, lazyClaimFailedText, lazyClaimRetryText, reclaimAutoVm, settledWithin, startAutoVmClaim, withinBudget, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";-import { 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 { CONTROL_ACT_WITHIN_MS, CONTROL_HANDED_BACK, CONTROL_NOT_READY, CONTROL_WAIT_MS, controlRefusal, type ControlState } from "./control-client.ts";+import { computerFreeAfterText, computerParkedRefusal, computerParkedText, computerPersonAwayText, computerStoppedWaitingText, computerWaitingText, type ComputerHolder } from "./computer-wait.ts"; import { createComputerGateAnswers } from "./host/computer-gate-answers.ts";import { modelContextWindow } from "./model-context-window.ts";import { browserIsThePlace, chosenPin, cloudPlaceRefusal, computerSelectionPrompt, computerSkippedNote, computerToolsRefusal, handoffUsesOwnCloud, isHandedWork, failedOnHostPath, openBrowserBeside, ownCloudStateWithin, parseSurface, pinSource, PlaceUnavailableError, placeUnavailable, resolveSurface, surfaceLabel, surfaceOfComputerKind, surfacePrompt, thisComputerSwitch, whereWorksControl, type ComputerWant, type PlaceSource, type Surface } from "./surface.ts";import { cloudRefusal, type PlaceRow } from "../shared/place-view.ts";@@ -2159,7 +2159,7 @@ async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive =endWait("parked");owner.computerParkedOn = resource;computerParks.set(owner.generation, resource);- throw new ComputerWaitParked(computerParkedText(holder, COMPUTER_WAIT_MAX_MS), resource, owner.generation);+ throw Object.assign(new ComputerWaitParked(computerParkedText(undefined, COMPUTER_WAIT_MAX_MS), resource, owner.generation), { parkedRefusal: computerParkedRefusal(COMPUTER_WAIT_MAX_MS) });}await new Promise<void>(resolve => setTimeout(resolve, 100));}@@ -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 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 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,22 +5655,23 @@ 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) {- await settledWithin(lazyClaim.begin, deadline - Date.now(), signal);- if (lazyClaim.claimed || lazyClaim.failed) continue;+ if (await computerGateAnswers.waitForClaim(lazyClaim.begin, deadline, { threadId, generation }, () => sharedVm.snapshot(botId, threadId).held, 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) };}- held = { held: true, helpOpen: false, blockedReason: yourComputerWaiting(threadId, generation) ?? lazyClaim.pendingReason ?? CONTROL_BUSY };+ // A queue place outranks a startup note: a team computer says "starting" once seated, then may queue again for its machine.+ held = computerGateAnswers.held(yourComputerWaiting(threadId, generation) ?? computerGateAnswers.contention({ threadId, generation }) ?? lazyClaim.pendingReason ?? CONTROL_NOT_READY, helpOpen); personHeld ||= held.reason === "person";} else {const computer = turnComputerResources.get(threadId);if (computer && computer.owner.generation === generation && !claimTurnResource(computer.owner, computer.resource)) {- held = { held: true, helpOpen: false, blockedReason: CONTROL_BUSY };+ held = computerGateAnswers.held(computerGateAnswers.contention(computer.owner) ?? CONTROL_NOT_READY, helpOpen); personHeld ||= held.reason === "person";} else if (!internalCapabilityIsActive(internalCapability)) {// A call from a turn that is over never reaches the screen.return { held: true, helpOpen, blockedReason: "This turn no longer has this computer, so this call was not performed." };} else if (personHeld) {return { held: true, helpOpen, blockedReason: CONTROL_HANDED_BACK };} else {- return Date.now() - askedAt > COMPUTER_CALL_ACT_WITHIN_MS ? { held: true, helpOpen, blockedReason: CONTROL_WAITED } : { held: false, helpOpen };+ return Date.now() - askedAt > COMPUTER_CALL_ACT_WITHIN_MS ? { held: true, helpOpen, blockedReason: computerGateAnswers.waited({ threadId, generation }) } : { held: false, helpOpen };}}if (Date.now() >= deadline || signal?.aborted || !internalCapabilityIsActive(internalCapability)) return held;diff --git a/server/long-running-chief.e2e.test.ts b/server/long-running-chief.e2e.test.tsindex 3805dc495d..c440794bbf 100644--- a/server/long-running-chief.e2e.test.ts+++ b/server/long-running-chief.e2e.test.ts@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";import { expect, it } from "vitest";import { launchVerificationServer, runControlOmb, verificationServerArgs, verificationServerEnvironment } from "../scripts/control-omb.ts";-import { CONTROL_WAITED } from "./control-client.ts";+import { CONTROL_WAITED_HELD } from "./control-client.ts";import { CONSENT_RULE } from "./peer-provenance.ts";import { waitForExit } from "./testing/cleanup.ts";import { readHandoffs } from "./testing/handoff-rows.ts";@@ -550,7 +550,7 @@ it("tells a teammate the person's job is its task, and a routine's handoff is noawait f.final(april, "APRIL-FINAL");const [waited, acted] = f.turn("KS").screen;- expect(waited.state).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_WAITED });+ expect(waited.state).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_WAITED_HELD });expect(waited.ms).toBeGreaterThanOrEqual(1_000);expect(acted.state).toEqual({ held: false, helpOpen: false });expect(f.turn("MS").screen.map((call: any) => call.state)).toEqual([{ held: false, helpOpen: false }]);diff --git a/server/mcp-bridge.test.ts b/server/mcp-bridge.test.tsindex 3355807f6d..eb90739c3d 100644--- a/server/mcp-bridge.test.ts+++ b/server/mcp-bridge.test.ts@@ -1,7 +1,7 @@// Unit level: the 45 s e2e wait is too slow for the suite, and what matters is the decision table, not the constant.import { describe, expect, it, vi } from "vitest";-import { CONTROL_REFUSAL_PLAIN, CONTROL_UNCONFIRMED, CONTROL_WAITED, type ControlState } from "./control-client.ts";+import { CONTROL_CALL_LATE, CONTROL_REFUSAL_PLAIN, CONTROL_UNCONFIRMED, type ControlState } from "./control-client.ts";import {completeFor,createChildCalls,@@ -296,7 +296,9 @@ describe("createGateInterceptor", () => {checks.shift()!(free);await Promise.all([held, queued]);expect(forwarded).toEqual([frame("tools/call", 1)]);- expect(refused.map((line) => [JSON.parse(line).id, refusalText(line)])).toEqual([[2, CONTROL_WAITED], [3, CONTROL_WAITED]]);+ expect(refused.map((line) => [JSON.parse(line).id, refusalText(line)])).toEqual([[2, CONTROL_CALL_LATE], [3, CONTROL_CALL_LATE]]);+ // Queued behind the previous call says nothing about the computer: no wait for it, no held seat, no instant next call.+ expect(CONTROL_CALL_LATE).not.toMatch(/computer is free|had to wait for it|now has this computer|goes through at once/);} finally {vi.useRealTimers();}diff --git a/server/mcp-bridge.ts b/server/mcp-bridge.tsindex 9ad355f9a1..d3deee91ea 100644--- a/server/mcp-bridge.ts+++ b/server/mcp-bridge.ts@@ -1,7 +1,7 @@import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";import { StringDecoder } from "node:string_decoder";-import { CONTROL_ACT_WITHIN_MS, CONTROL_UNCONFIRMED, CONTROL_WAITED, controlRefusal, createControlClient, type ControlState } from "./control-client.ts";+import { CONTROL_ACT_WITHIN_MS, CONTROL_CALL_LATE, CONTROL_UNCONFIRMED, controlRefusal, createControlClient, type ControlState } from "./control-client.ts";import { augmentedPath, resolveCliSpawn } from "./env-path.ts";import { textOnlyErrorResultLine } from "./mcp-error-result.ts";import { createToolListNormalizer } from "./mcp-tool-schema.ts";@@ -184,7 +184,7 @@ export function createGateInterceptor(options: {JSON.stringify({jsonrpc: "2.0",id: frame.id ?? null,- result: completeFor(frame.params?._meta, { content: [{ type: "text", text: state.held ? controlRefusal(state) : CONTROL_WAITED }], isError: true }),+ result: completeFor(frame.params?._meta, { content: [{ type: "text", text: state.held ? controlRefusal(state) : CONTROL_CALL_LATE }], isError: true }),}),);});diff --git a/server/parallel-threads.e2e.test.ts b/server/parallel-threads.e2e.test.tsindex 2f9340fc0d..9c1492536a 100644--- a/server/parallel-threads.e2e.test.ts+++ b/server/parallel-threads.e2e.test.ts@@ -9,7 +9,6 @@ import { basename, dirname, join } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { cloudPairingSignature, cloudRequestSignature } from "./cloud-home.ts";-import { CONTROL_BUSY } from "./control-client.ts";import { BROWSER_HANDED_OVER, browserBusyText } from "./host/browser-seats.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { freePortBlock } from "./testing/ports.ts";@@ -354,7 +353,7 @@ describe.each(["desktop", "team"] as const)("two threads of a bot on the team'sfor (let attempt = 0; attempt < 40 && first.body.result?.isError; attempt++) first = await screenshot(threads[0]!);expect(first.body.result.isError, JSON.stringify(first.body)).toBeFalsy();const second = await screenshot(threads[1]!);- expect(second.body.result).toEqual({ isError: true, content: [{ type: "text", text: CONTROL_BUSY }] });+ expect(second.body.result).toEqual({ isError: true, content: [{ type: "text", text: expect.stringMatching(/^Another thread is using this computer\. This call was not performed\. No screen or app state was checked\. This turn is 1st in line/) }] });expect((await rows(f, threads[1]!)).find((name) => name.startsWith("Waiting for its turn on this computer")), "the person sees why").toContain("Scout is running");expect((await busyThreads(f, botId)).sort()).toEqual([...threads].sort());diff --git a/server/saved-steps/computer-client.test.ts b/server/saved-steps/computer-client.test.tsindex 8ddb6b13df..34e6d149c4 100644--- a/server/saved-steps/computer-client.test.ts+++ b/server/saved-steps/computer-client.test.ts@@ -3,8 +3,8 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it, vi } from "vitest";-import { CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_TURN_ENDED, CONTROL_WAIT_MS, CONTROL_WAITED, controlRefusal, type ControlState } from "../control-client.ts";-import { computerPersonAwayText } from "../computer-wait.ts";+import { CONTROL_BUSY, CONTROL_CALL_LATE, CONTROL_HANDED_BACK, CONTROL_NOT_READY, CONTROL_TURN_ENDED, CONTROL_WAIT_MS, CONTROL_WAITED_HELD, controlRefusal, type ControlState } from "../control-client.ts";+import { computerBusyText, computerParkedRefusal, computerPersonAwayText, computerQueuedText } from "../computer-wait.ts";import { ChatMcpClient } from "../drivers/chat-mcp-tools.ts";import { createGateInterceptor } from "../mcp-bridge.ts";import { callOutcome, openComputerCaller, STEP_TIMEOUT_MS } from "./computer-client.ts";@@ -114,17 +114,23 @@ describe("callOutcome", () => {["the person handed it back mid-call", { held: true, helpOpen: false, blockedReason: CONTROL_HANDED_BACK }, {}],["the person has had it too long", { held: true, helpOpen: false, blockedReason: computerPersonAwayText(30 * 60_000) }, {}],["the turn that had it has ended", { held: true, helpOpen: false, blockedReason: CONTROL_TURN_ENDED }, {}],+ ["another thread holds it, with its queue place", { held: true, helpOpen: false, blockedReason: computerBusyText({ position: 2, heldForMs: 60_000, estimateMs: 90_000 }) }, {}],+ ["it is queued between turns", { held: true, helpOpen: false, blockedReason: computerQueuedText({ position: 2 }) }, {}],+ ["it is not ready yet", { held: true, helpOpen: false, blockedReason: CONTROL_NOT_READY }, {}],+ ["this turn now has it after waiting", { held: true, helpOpen: false, blockedReason: CONTROL_WAITED_HELD }, {}],+ ["the turn parked waiting for it", { held: true, helpOpen: false, blockedReason: computerParkedRefusal(30 * 60_000) }, {}],])("fails a call the control gate refuses because %s, marked as the gate's", async (_case, state, timing) => {let refused = "";const gate = createGateInterceptor({ check: async () => state, forward: () => { throw new Error("forwarded"); }, refuse: (line) => { refused = line; }, ...timing });await gate(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "click", arguments: {} } }));- const text = state.held ? controlRefusal(state) : CONTROL_WAITED;+ const text = state.held ? controlRefusal(state) : CONTROL_CALL_LATE;expect(callOutcome(JSON.parse(refused).result)).toEqual({ ok: false, error: text.slice(0, 300), gate: true });});it.each([["the driver's own error", { content: [{ type: "text", text: "AXPress was not performed" }], isError: true }],["a driver error that quotes part of a gate text", { content: [{ type: "text", text: "A person has taken control" }], isError: true }],+ ["a driver error that opens like the parked answer", { content: [{ type: "text", text: "This turn waited 5 seconds for the application window to appear." }], isError: true }],["the driver's refusal", { content: [], structuredContent: { refusal: { code: "x", message: CONTROL_BUSY } } }],])("never marks %s as the gate's", (_case, result) => {const outcome = callOutcome(result);diff --git a/server/saved-steps/computer-client.ts b/server/saved-steps/computer-client.tsindex 6f3f76db64..2d3eb24083 100644--- a/server/saved-steps/computer-client.ts+++ b/server/saved-steps/computer-client.ts@@ -1,5 +1,5 @@-import { computerPersonAwayText } from "../computer-wait.ts";-import { CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_REFUSAL_PLAIN, CONTROL_TURN_ENDED, CONTROL_UNCONFIRMED, CONTROL_WAITED } from "../control-client.ts";+import { computerPersonAwayText, isComputerParkedRefusal } from "../computer-wait.ts";+import { CONTROL_BUSY, CONTROL_BUSY_OPENING, CONTROL_CALL_LATE, CONTROL_HANDED_BACK, CONTROL_NOT_READY_OPENING, CONTROL_REFUSAL_PLAIN, CONTROL_TURN_ENDED, CONTROL_UNCONFIRMED, CONTROL_WAITED, CONTROL_WAITED_HELD } from "../control-client.ts";import { ChatMcpClient } from "../drivers/chat-mcp-tools.ts";import type { CallOutcome, ComputerCaller } from "./resolve.ts";@@ -11,9 +11,10 @@ export type LocalComputerSpec = { command: string; args: string[]; env: Record<sconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);-const GATE_REFUSALS: ReadonlySet<string> = new Set([CONTROL_REFUSAL_PLAIN, CONTROL_HANDED_BACK, CONTROL_WAITED, CONTROL_BUSY, CONTROL_UNCONFIRMED, CONTROL_TURN_ENDED]);+const GATE_REFUSALS: ReadonlySet<string> = new Set([CONTROL_REFUSAL_PLAIN, CONTROL_HANDED_BACK, CONTROL_WAITED, CONTROL_WAITED_HELD, CONTROL_CALL_LATE, CONTROL_BUSY, CONTROL_UNCONFIRMED, CONTROL_TURN_ENDED]);const PERSON_AWAY = computerPersonAwayText(60_000).replace(/ for over [\s\S]*$/u, " for over ");-const gateRefusal = (text: string) => GATE_REFUSALS.has(text) || text.startsWith(PERSON_AWAY);+const GATE_OPENINGS = [PERSON_AWAY, CONTROL_BUSY_OPENING, CONTROL_NOT_READY_OPENING];+const gateRefusal = (text: string) => GATE_REFUSALS.has(text) || GATE_OPENINGS.some((opening) => text.startsWith(opening)) || isComputerParkedRefusal(text);function errorOutcome(content: unknown[]): CallOutcome {const text = content.flatMap((item) => (isRecord(item) && item.type === "text" && typeof item.text === "string" ? [item.text] : [])).join(" ").trim();diff --git a/server/turn-resources.test.ts b/server/turn-resources.test.tsindex b1f32151d8..ad2b525a75 100644--- a/server/turn-resources.test.ts+++ b/server/turn-resources.test.ts@@ -142,3 +142,44 @@ describe("wait estimate history", () => {expect(leases.waitEstimateMs("computer:vm:other")).toBeUndefined();});});++describe("what a waiting computer turn can be told", () => {+ const c = { threadId: "c", generation: "3" };++ it("dates the current holder's claim and forgets it on release", () => {+ const leases = new TurnResources();+ expect(leases.holderSince("computer:host")).toBeUndefined();+ const before = Date.now();+ leases.claim("computer:host", a);+ expect(leases.holderSince("computer:host")).toBeGreaterThanOrEqual(before);+ leases.releaseOne("computer:host", a);+ expect(leases.holderSince("computer:host")).toBeUndefined();+ leases.claim("computer:host", b);+ leases.release(b);+ expect(leases.holderSince("computer:host")).toBeUndefined();+ });++ it("finds a turn's computer queue place, never a browser seat's", () => {+ const leases = new TurnResources();+ leases.claim("browser:one", a);+ leases.startWaiting("browser:one", b);+ expect(leases.computerWaitOf(b)).toBeUndefined();+ leases.claim("computer:host", a);+ leases.startWaiting("computer:host", c);+ leases.startWaiting("computer:host", b);+ expect(leases.computerWaitOf(b)).toEqual({ resource: "computer:host", position: 2 });+ leases.stopWaiting("computer:host", b);+ expect(leases.computerWaitOf(b)).toBeUndefined();+ });++ it("leaves the second waiter with a place but no holder between turns", () => {+ const leases = new TurnResources();+ leases.claim("computer:host", a);+ leases.startWaiting("computer:host", b);+ leases.release(a);+ expect(leases.claim("computer:host", c)).toBe(false);+ leases.startWaiting("computer:host", c);+ expect(leases.blocker("computer:host", c)).toBeUndefined();+ expect(leases.computerWaitOf(c)).toEqual({ resource: "computer:host", position: 2 });+ });+});diff --git a/server/turn-resources.ts b/server/turn-resources.tsindex 0781a9bd85..6be24bbbe5 100644--- a/server/turn-resources.ts+++ b/server/turn-resources.ts@@ -9,6 +9,7 @@ export type TurnOwner = {/** Whole-turn claims on app-managed resources (a desktop, a browser session, a phone), so a screenshot and its click see the same desktop. Not a shell sandbox. */export class TurnResources {private readonly owners = new Map<string, TurnOwner>();+ private readonly heldSince = new Map<string, number>();/** Only turns actually waiting: a lazy claim that failed once and moved on must not block the front. */private readonly waiters = new Map<string, TurnOwner[]>();private readonly waitStats = new Map<string, { ewmaMs: number; samples: number }>();@@ -77,6 +78,7 @@ export class TurnResources {if (!queue.length) this.waiters.delete(resource);}this.owners.set(resource, owner);+ this.heldSince.set(resource, Date.now());for (const listener of this.claimListeners) listener(resource, owner);return true;}@@ -85,6 +87,19 @@ export class TurnResources {return this.owners.get(resource);}+ holderSince(resource: string): number | undefined {+ return this.owners.has(resource) ? this.heldSince.get(resource) : undefined;+ }++ /** Browser seats share this waitlist, so only `computer:` resources count; a turn waits on one computer at a time. */+ computerWaitOf(owner: TurnOwner): { resource: string; position: number } | undefined {+ for (const resource of this.waiters.keys()) {+ const position = resource.startsWith("computer:") ? this.waitPosition(resource, owner) : undefined;+ if (position) return { resource, position };+ }+ return undefined;+ }+owns(resource: string, owner: TurnOwner): boolean {const current = this.owners.get(resource);return Boolean(current && sameOwner(current, owner));@@ -97,15 +112,20 @@ export class TurnResources {else this.waiters.delete(key);}for (const [key, current] of this.owners) {- if (sameOwner(current, owner)) this.owners.delete(key);+ if (sameOwner(current, owner)) this.drop(key);}}releaseOne(resource: string, owner: TurnOwner): void {- if (this.owns(resource, owner)) this.owners.delete(resource);+ if (this.owns(resource, owner)) this.drop(resource);this.stopWaiting(resource, owner);}+ private drop(resource: string): void {+ this.owners.delete(resource);+ this.heldSince.delete(resource);+ }+free(resource: string): boolean {return !this.owners.has(resource);}diff --git a/server/vps-routing.test.ts b/server/vps-routing.test.tsindex 8d1ce5c27d..df6761c283 100644--- a/server/vps-routing.test.ts+++ b/server/vps-routing.test.ts@@ -16,7 +16,7 @@ import {MANAGED_LABEL,} from "./container-computer.ts";import { VPS_CONTAINER_LABEL, VPS_IMAGE, VPS_MANAGED_LABEL, VPS_VIEWER_LABEL, vpsContainerName } from "./vps-computer.ts";-import { CONTROL_BUSY, CONTROL_REFUSAL_PLAIN, controlRefusal, createControlClient } from "./control-client.ts";+import { CONTROL_REFUSAL_PLAIN, controlRefusal, createControlClient } from "./control-client.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import type { RoutineSchedule } from "../shared/routines.ts";import { workerPort } from "./testing/worker-port.ts";@@ -703,7 +703,7 @@ createServer(socket => socket.end()).listen(port, '127.0.0.1');expect(await gate(checkMount)).toEqual({ held: false, helpOpen: false });const started = Date.now();const contended = await gate(refillMount);- expect(contended).toEqual({ held: true, helpOpen: false, blockedReason: CONTROL_BUSY });+ expect(contended).toMatchObject({ held: true, helpOpen: false, blockedReason: expect.stringMatching(/^Another thread is using this computer\. This call was not performed\. No screen or app state was checked\. This turn is 1st in line/) });expect(controlRefusal(contended)).not.toBe(CONTROL_REFUSAL_PLAIN);expect(Date.now() - started).toBeGreaterThanOrEqual(CALL_WAIT_MS - 200);// The chip may add a queue position and an estimate; the holder it names is what is under test.