Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Threads of one bot run at once, as many as the machine holds, and one per bot on Starter (#4212)
Milind Sonib6d45fa27de8
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex c4dc90b754..b5e0c20c86 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1103,6 +1103,11 @@ provider outage. So on a Cloud home (`server/engine-memory.ts`):ten minutes (which keeps both stall checks quiet), and the turn starts byitself. Stop ends the wait. A thread whose engine is still running neverwaits, and the only task is never held back.+- **How many threads a bot may run.** No number decides on a Cloud: up to 16 per+ bot unless one is saved, and this gate holds the rest. A Starter Cloud runs one+ thread per bot for what a person or a routine starts; the Admin says so with its+ signed `POST /api/cloud/plan` `{"v":1,"tier":"starter"}` (`server/host/cloud-plan-tier.ts`), and a+ home it never told has no such limit. What a bot's own turn starts always goes through.- **OpenCode threads share a process.** Threads whose OpenCode would startthe same way (same login, approval level and settings) run as sessions of one`opencode acp` process, up to six at a time and twelve over its lifediff --git a/docs/verification/chat-turns.md b/docs/verification/chat-turns.mdindex 64d60ee90e..eca6e34401 100644--- a/docs/verification/chat-turns.md+++ b/docs/verification/chat-turns.md@@ -273,3 +273,19 @@ one sent while the turn waits on the person or a computerwas stopped 1.5 s after the steered question, and the fake engine answered thequestion in the next turn. With the steered message's watch removed, thequestion stayed unanswered for 30 s and the test failed.++## Threads of one bot at the same time++Different threads of one bot run at once. A saved `threads.maxConcurrentPerBot` sets how many. With none saved, a Cloud+runs up to 16 and its memory gate decides; a machine without the gate runs one per 2 GB of memory, 3 to 16. The bot's main+chat always starts, and takes a slot. On a Starter Cloud a person's or routine's work runs one thread per bot whatever is+saved; work a bot's own turn started goes through, so a turn can never wait on a child queued behind itself.+`server/parallel-threads.e2e.test.ts` holds a turn open in each thread with a gate only+the test releases, as a desktop, personal Cloud and Team Cloud server, on the Claude CLI, ACP and OpenAI-compatible+engines. What stays one at a time, and what the person sees:++- One thread's own turns stay in order: a later send queues or steers.+- One bot's browser: a call from another thread waits, the row says who has it, and a holder quiet for a minute gives it+ to the waiter. The holder's next call is refused once, so nothing lands on a page it did not open.+- One computer: a turn takes it at its first screen call, not when it starts, and keeps it until it ends.+- Memory on a Linux Cloud: a turn that would run the machine out says "Waiting for memory" and starts by itself.diff --git a/evals/scenarios/lazy-claim-screenless.json b/evals/scenarios/lazy-claim-screenless.jsonindex 8cbf98d2a8..0e4e4660b2 100644--- a/evals/scenarios/lazy-claim-screenless.json+++ b/evals/scenarios/lazy-claim-screenless.json@@ -26,7 +26,8 @@"steps": [{ "kind": "send", "bot": "holder", "text": "Hold the VM for this fixture." },{ "kind": "waitForBusy", "bot": "holder", "busy": true, "timeoutMs": 20000 },- { "kind": "consumeDump" },+ { "kind": "captureComputer", "bot": "holder" },+ { "kind": "pollComputerGate", "bot": "holder", "saveAs": "holderScreenCall" },{ "kind": "send", "bot": "auto", "text": "No screen work today." },{ "kind": "waitForBusy", "bot": "auto", "busy": true, "timeoutMs": 20000 },{ "kind": "captureComputer", "bot": "auto" },diff --git a/evals/scenarios/lazy-computer-claim.json b/evals/scenarios/lazy-computer-claim.jsonindex 4158de6816..4973a27897 100644--- a/evals/scenarios/lazy-computer-claim.json+++ b/evals/scenarios/lazy-computer-claim.json@@ -60,7 +60,13 @@"timeoutMs": 20000},{- "kind": "consumeDump"+ "kind": "captureComputer",+ "bot": "holder"+ },+ {+ "kind": "pollComputerGate",+ "bot": "holder",+ "saveAs": "holderScreenCall"},{"kind": "pollComputerGate",@@ -106,6 +112,11 @@}],"assertions": [+ {+ "kind": "gateAnswer",+ "of": "holderScreenCall",+ "held": false+ },{"kind": "gateAnswer","of": "firstScreenCall",diff --git a/server/bot-thread-limits.ts b/server/bot-thread-limits.tsnew file mode 100644index 0000000000..9359265cbb--- /dev/null+++ b/server/bot-thread-limits.ts@@ -0,0 +1,36 @@+// How many threads one bot runs at once.+import { totalmem } from "node:os";++import { engineMemory } from "./engine-memory.ts";++export const MAX_CONCURRENT_BOT_THREADS = 16;+const DEFAULT_THREADS_FLOOR = 3, BYTES_PER_DEFAULT_THREAD = 2 * 1024 ** 3;++/** Where the memory gate runs it decides, so only the ceiling applies; elsewhere nothing protects the machine. */+export interface BotThreadsHost { memoryGate: boolean; totalBytes: number; oneThreadPerBot: boolean }+type SavedThreads = { threads?: { maxConcurrentPerBot?: number } };++export const botThreadsHost = (oneThreadPerBot = false): BotThreadsHost => ({ memoryGate: engineMemory.enabled, totalBytes: totalmem(), oneThreadPerBot });++export function defaultBotThreads(host: Pick<BotThreadsHost, "memoryGate" | "totalBytes"> = botThreadsHost()): number {+ if (host.memoryGate) return MAX_CONCURRENT_BOT_THREADS;+ return Math.min(MAX_CONCURRENT_BOT_THREADS, Math.max(DEFAULT_THREADS_FLOOR, Math.round(host.totalBytes / BYTES_PER_DEFAULT_THREAD)));+}++/** Separate work a person or a routine starts. A plan's limit outranks a saved number. */+export function maxConcurrentBotThreads(cfg: SavedThreads, host: BotThreadsHost = botThreadsHost()): number {+ if (host.oneThreadPerBot) return 1;+ return cfg.threads?.maxConcurrentPerBot ?? defaultBotThreads(host);+}++/** Work a bot's own turn started (its own thread, a hand-off). That turn may be waiting on it, so a plan's limit never holds+ * it behind the turn that started it. */+export function maxConcurrentChildThreads(cfg: SavedThreads, host: BotThreadsHost = botThreadsHost()): number {+ return host.oneThreadPerBot ? MAX_CONCURRENT_BOT_THREADS : maxConcurrentBotThreads(cfg, host);+}++export function botThreadLimitText(cfg: SavedThreads, host: BotThreadsHost = botThreadsHost()): string {+ return host.oneThreadPerBot+ ? "Starter runs one thread at a time per bot — wait for it to finish, or move to a bigger plan to run more"+ : `this bot has reached its limit of ${maxConcurrentBotThreads(cfg, host)} parallel threads — wait for one to finish`;+}diff --git a/server/browser/engines.ts b/server/browser/engines.tsindex 70ff25615e..d90a5bb58f 100644--- a/server/browser/engines.ts+++ b/server/browser/engines.ts@@ -248,6 +248,10 @@ export class RuntimeRouter {return this.#chrome.service.heldBy(session) ?? this.#old.heldBy(session);}+ working(session: string): boolean {+ return this.#chrome.service.working(session) || this.#old.working(session);+ }+interrupted(session: string): boolean {return this.#chrome.service.interrupted(session) || this.#old.interrupted(session);}diff --git a/server/browser/service.ts b/server/browser/service.tsindex b4d1b5e53e..0ff30596fd 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -625,6 +625,12 @@ export class BrowserService {return this.#bySession(session)?.control.owner ?? null;}+ /** A bot call or a person's hold is under way in this session's browser. */+ working(session: string): boolean {+ const profile = this.#bySession(session);+ return Boolean(profile && (profile.calls > 0 || profile.control.owner !== null || profile.control.agents > 0 || this.#lanes.held(profile.key)));+ }+/** Whether the page's open picker was offered to `owner`'s view as `chooserId`: an upload for any other is refused unread. */fileChooserOffered(session: string, owner: string, chooserId: string): boolean {return this.#bySession(session)?.hub.fileChooserOffered(owner, chooserId) ?? false;diff --git a/server/comms.test.ts b/server/comms.test.tsindex b828c943bf..ef646e3528 100644--- a/server/comms.test.ts+++ b/server/comms.test.ts@@ -241,6 +241,7 @@ describe("routine comms e2e on the job runtime (fake ACP fleet)", () => {writeFileSync(join(home, ".openmausbot", "config.json"),JSON.stringify({+ threads: { maxConcurrentPerBot: 3 },openaiCompat: { key: "comms-compat-key", url: compatUrl },instances: {// the asker: consults the first visible teammate and answers a resume carrying the result with a fixed linediff --git a/server/config.test.ts b/server/config.test.tsindex 8f4b7121cf..d32be5068c 100644--- a/server/config.test.ts+++ b/server/config.test.ts@@ -2,6 +2,7 @@ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, utimeimport { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { botThreadLimitText, defaultBotThreads, maxConcurrentBotThreads, maxConcurrentChildThreads } from "./bot-thread-limits.ts";import type { JsonValue } from "./schema.ts";import { cacheUntilConfigChanges,@@ -22,7 +23,6 @@ import { cacheUntilConfigChanges,persistableInstanceConfigs,roomTurnTimeoutMinutes,mcpCallTimeoutMinutes,- maxConcurrentBotThreads,threadEventLogMaxBytes,threadEventLogRetentionDays,showToolCallsEnabled,@@ -127,8 +127,21 @@ describe("configuration boundaries", () => {expect(() => parseConfigPatch({ tts: { fishModel: "s1" } })).toThrow("fishModel");});- it("defaults to three parallel threads and validates a configurable maximum of sixteen", () => {- expect(maxConcurrentBotThreads({})).toBe(3);+ it("defaults to what each host holds, and a saved number wins except over a plan's limit", () => {+ const GB = 1024 ** 3;+ const desktop = (gb: number) => ({ memoryGate: false, totalBytes: gb * GB, oneThreadPerBot: false });+ for (const [gb, threads] of [[2, 3], [4, 3], [8, 4], [16, 8], [26, 13], [32, 16], [128, 16]] as const) expect(maxConcurrentBotThreads({}, desktop(gb))).toBe(threads);+ expect(maxConcurrentBotThreads({}, desktop(15.8)), "a 16 GB machine reports a little less").toBe(8);+ for (const gb of [2, 8]) expect(maxConcurrentBotThreads({}, { memoryGate: true, totalBytes: gb * GB, oneThreadPerBot: false }), "the memory gate decides").toBe(16);+ expect(maxConcurrentBotThreads({ threads: { maxConcurrentPerBot: 2 } }, desktop(64))).toBe(2);+ expect(maxConcurrentBotThreads({ threads: { maxConcurrentPerBot: 2 } }, { memoryGate: true, totalBytes: 8 * GB, oneThreadPerBot: false })).toBe(2);+ const starter = { memoryGate: true, totalBytes: 2 * GB, oneThreadPerBot: true };+ expect(maxConcurrentBotThreads({}, starter)).toBe(1);+ expect(maxConcurrentBotThreads({ threads: { maxConcurrentPerBot: 8 } }, starter), "a plan's limit is not a preference").toBe(1);+ expect(maxConcurrentChildThreads({}, starter), "a bot's own turn is never held behind itself").toBe(16);+ expect(maxConcurrentChildThreads({ threads: { maxConcurrentPerBot: 2 } }, desktop(64)), "only a plan's limit lets children through").toBe(2);+ expect(botThreadLimitText({}, starter)).toContain("Starter runs one thread at a time per bot");+ expect(botThreadLimitText({ threads: { maxConcurrentPerBot: 5 } }, desktop(16))).toBe("this bot has reached its limit of 5 parallel threads — wait for one to finish");expect(parseStoredConfig({ threads: { maxConcurrentPerBot: 16 } })).toEqual({ threads: { maxConcurrentPerBot: 16 } });expect(maxConcurrentBotThreads(parseConfigPatch({ threads: { maxConcurrentPerBot: 1 } }))).toBe(1);for (const value of [0, -1, 17, 1.5, "10", null]) {@@ -786,15 +799,15 @@ describe("saving the newer sections", () => {}});- it("seeds the concurrency default when the first threads save is an event-log knob", () => {+ it("seeds what this machine holds when the first threads save is an event-log knob, so an older version can still read the file", () => {const path = join(DATA_DIR, "config.json");mkdirSync(DATA_DIR, { recursive: true });writeFileSync(path, JSON.stringify({}));try {saveConfig({ threads: { eventLogRetentionDays: 30 } });const disk = JSON.parse(readFileSync(path, "utf8"));- expect(disk.threads).toEqual({ maxConcurrentPerBot: 3, eventLogRetentionDays: 30 });- expect(parseStoredConfig(disk).threads).toEqual({ maxConcurrentPerBot: 3, eventLogRetentionDays: 30 });+ expect(disk.threads).toEqual({ maxConcurrentPerBot: defaultBotThreads(), eventLogRetentionDays: 30 });+ expect(parseStoredConfig(disk).threads).toEqual({ maxConcurrentPerBot: defaultBotThreads(), eventLogRetentionDays: 30 });} finally {rmSync(path, { force: true });}diff --git a/server/config.ts b/server/config.tsindex bb91671eab..6aa81832d1 100644--- a/server/config.ts+++ b/server/config.ts@@ -7,6 +7,7 @@ import { z } from "zod";import { normalizeImageGenerationUrl, type ImageGenerationConfig } from "../shared/image-generation.ts";import { botAvatarUrlSchema } from "../shared/bot-avatar.ts";import { writeFileAtomic } from "./atomic.ts";+import { defaultBotThreads, MAX_CONCURRENT_BOT_THREADS } from "./bot-thread-limits.ts";import { anthropicKeyEnv } from "./anthropic-key-env.ts";import { withoutComputerEngine } from "./computer-engine-removal.ts";import { newBotDefaultsSchema, type NewBotDefaults } from "./new-bot-defaults.ts";@@ -44,8 +45,6 @@ export const MAX_ROOM_TURN_TIMEOUT_MINUTES = 1_440;export const DEFAULT_MCP_CALL_TIMEOUT_MINUTES = 10;export const MIN_MCP_CALL_TIMEOUT_MINUTES = 1;export const MAX_MCP_CALL_TIMEOUT_MINUTES = 60;-export const DEFAULT_MAX_CONCURRENT_BOT_THREADS = 3;-export const MAX_CONCURRENT_BOT_THREADS = 16;/** The floor keeps a log tail large enough for the event inspector's recent-line window. */export const MIN_THREAD_EVENT_LOG_BYTES = 256 * 1024;export const MAX_THREAD_EVENT_LOG_BYTES = 4 * 1024 * 1024 * 1024;@@ -639,10 +638,6 @@ export function cacheKeepWarmSettings(cfg: AppConfig): { enabled: boolean; windoreturn { enabled: cfg.cacheKeepWarm?.enabled === true, windowMinutes: cfg.cacheKeepWarm?.windowMinutes ?? DEFAULT_WINDOW_MINUTES };}-export function maxConcurrentBotThreads(cfg: { threads?: { maxConcurrentPerBot?: number } }): number {- return cfg.threads?.maxConcurrentPerBot ?? DEFAULT_MAX_CONCURRENT_BOT_THREADS;-}-export function threadEventLogMaxBytes(cfg: AppConfig): number | null {const cap = cfg.threads?.eventLogMaxBytes;return typeof cap === "number" && Number.isFinite(cap) && cap > 0 ? cap : null;@@ -952,7 +947,7 @@ export function saveConfig(if (!section) continue;const current = jsonObjectSchema.safeParse(disk[key]);const merged: JsonObject = current.success ? { ...current.data } : {};- if (key === "threads" && !current.success) merged.maxConcurrentPerBot = DEFAULT_MAX_CONCURRENT_BOT_THREADS;+ if (key === "threads" && !current.success) merged.maxConcurrentPerBot = defaultBotThreads();// A partial egress patch (the owner's local-sites switch) keeps the rest of the stored egress, such as the allow-list.const egress = key === "browserEngine" && checkedPatch.browserEngine?.egress ? { ...jsonObjectSchema.safeParse(merged.egress).data, ...checkedPatch.browserEngine.egress } : null;Object.assign(merged, section, egress ? { egress } : {});diff --git a/server/engine-memory.test.ts b/server/engine-memory.test.tsindex 7b22e22f45..194eae8861 100644--- a/server/engine-memory.test.ts+++ b/server/engine-memory.test.ts@@ -311,6 +311,60 @@ describe("bots' browsers", () => {expect(await third).toBe(false);});+ it("lets a second thread of one bot run beside the first on a 2 GB Cloud, counting the bot's one browser once", async () => {+ let clock = 1_800_000_000_000;+ const running = new Map<number, number>();+ const memory = new EngineMemory({+ enabled: true, tickMs: 5,+ // 2 GB with no swap, 1.5 GB available beside the server; an engine takes 350 MB once it has run a while.+ read: (): HostMemory => ({ totalBytes: 2 * GB, availableBytes: 1.5 * GB - [...running.values()].reduce((sum, bytes) => sum + bytes, 0), swapFreeBytes: 0, oomKills: 0, fullStall10: 0 }),+ groups: () => new Map(running), now: () => clock, signal: () => {}, log: () => {},+ });+ memory.useBrowsers({ starts: () => true, which: () => "bot-a", running: () => false, stopped: () => {} });+ expect(await memory.admit("first", new AbortController().signal, () => {})).toBe(true);+ memory.turnStarted("first");+ memory.within("first", () => { const child = new FakeChild(1000); running.set(child.pid, 350 * MB); memory.track(child as unknown as ChildProcess); });++ const notices: string[] = [];+ const second = memory.admit("second", new AbortController().signal, (text) => notices.push(text));+ await settle();+ expect(notices, "said why while the first engine has not been measured").toEqual([memoryWaitText(1)]);+ // Measured, with the reservation for its browser still held: no more than 30 s, not the 90 s of a browser counted twice.+ clock += 31_000;+ await expect.poll(async () => Promise.race([second, settle().then(() => "waiting")]), { timeout: 2_000, interval: 10 }).toBe(true);+ });++ it.each([[2, 1.5, 2], [8, 7.2, 10]])("holds sixteen threads on a %d GB Cloud to what fits: the rest wait and say so, none refused or stopped", async (totalGb, availableGb, fits) => {+ let clock = 1_800_000_000_000;+ const running = new Map<number, number>(), signals: string[] = [];+ const memory = new EngineMemory({+ enabled: true, tickMs: 5,+ read: (): HostMemory => ({ totalBytes: totalGb * GB, availableBytes: availableGb * GB - [...running.values()].reduce((sum, bytes) => sum + bytes, 0), swapFreeBytes: 0, oomKills: 0, fullStall10: 0 }),+ groups: () => new Map(running), now: () => clock, signal: (pid, signal) => { signals.push(`${signal} ${pid}`); }, log: () => {},+ });+ const notices: string[] = [], outcomes = new Map<string, boolean>(), children = new Map<string, FakeChild>();+ let pid = 2000;+ const threads = Array.from({ length: 16 }, (_, i) => `thread-${i}`);+ for (const thread of threads) void memory.admit(thread, new AbortController().signal, (text) => notices.push(text)).then((admitted) => {+ outcomes.set(thread, admitted);+ memory.turnStarted(thread);+ memory.within(thread, () => { const child = new FakeChild(pid++); children.set(thread, child); running.set(child.pid, 600 * MB); memory.track(child as unknown as ChildProcess); });+ });+ // Each engine is measured once it has run a while, which is when the next can be let in.+ for (let round = 0; round < 20; round++) { await settle(); clock += 31_000; }+ expect(outcomes.size).toBe(fits);+ expect([...outcomes.values()].every(Boolean)).toBe(true);+ expect(notices.some((text) => text.startsWith("Waiting for memory:"))).toBe(true);+ expect(signals, "nothing stopped to make room").toEqual([]);+ // One ends, and the next starts by itself.+ const first = threads.find((thread) => outcomes.has(thread))!;+ memory.turnEnded(first);+ running.delete(children.get(first)!.pid);+ children.get(first)!.exit();+ await expect.poll(() => outcomes.size, { timeout: 2_000, interval: 10 }).toBe(fits + 1);+ expect(signals).toEqual([]);+ });+it("stops holding a browser's share once it has run a while, where what it takes shows in free memory", async () => {const h = host();const { pending } = browsers(h, ["a", "b", "c"]);diff --git a/server/engine-memory.ts b/server/engine-memory.tsindex e25851c1a7..ff49fcbde9 100644--- a/server/engine-memory.ts+++ b/server/engine-memory.ts@@ -119,6 +119,8 @@ export class PressureLedger {export interface EngineBrowsers {/** Whether this thread's bot may browse and its browser is not running yet. */starts(threadId: string): boolean;+ /** Which browser this thread would use: threads naming the same one start it once between them. */+ which?(threadId: string): string | undefined;/** Whether this thread's bot's browser is running now. */running(threadId: string): boolean;/** This thread's engine was stopped for memory: its browser can close too once no turn holds it. */@@ -350,19 +352,25 @@ export class EngineMemory {const measured = live.filter(([, engine]) => at - engine.startedAt >= SETTLED_MS).map(([pid]) => groups.get(pid)).filter((bytes) => bytes !== undefined);const process = Math.min(ENGINE_MAX_BYTES, Math.max(ENGINE_MIN_BYTES, measured.length ? measured.reduce((sum, bytes) => sum + bytes, 0) / measured.length : ENGINE_DEFAULT_BYTES));let held = 0;+ const heldBrowsers = new Set<string>();for (const [threadId, admitted] of this.reserved) {if (at - admitted.at >= RESERVE_MS) { this.reserved.delete(threadId); continue; }// A browser grows as it starts and loads its first pages: its share is held until it has run SETTLED_MS.if (admitted.browser) {if (!this.browserStarts(threadId)) admitted.browserSince ??= at;- if (admitted.browserSince === undefined || at - admitted.browserSince < SETTLED_MS) held += BROWSER_BYTES;+ const browser = this.browsers?.which?.(threadId) ?? threadId;+ if ((admitted.browserSince === undefined || at - admitted.browserSince < SETTLED_MS) && !heldBrowsers.has(browser)) {+ heldBrowsers.add(browser);+ held += BROWSER_BYTES;+ }}// A session's growth hides inside its shared process's total, so it stays held in full until it settles.if (admitted.start === "session") { held += SESSION_BYTES; continue; }const pid = live.find(([, engine]) => engine.threads.has(threadId))?.[0];held += Math.max(0, process - (pid === undefined ? 0 : groups.get(pid) ?? 0));}- const need = (start === "session" ? SESSION_BYTES : process) + (this.browserStarts(threadId) ? BROWSER_BYTES : 0);+ const newBrowser = this.browserStarts(threadId) && !heldBrowsers.has(this.browsers?.which?.(threadId) ?? threadId);+ const need = (start === "session" ? SESSION_BYTES : process) + (newBrowser ? BROWSER_BYTES : 0);if (this.free(memory) - this.floor(memory) - held >= need) return "admit";return this.idle() ?? (this.othersBusy(threadId) === 0 ? "admit" : "wait");}diff --git a/server/group-local-vm.e2e.test.ts b/server/group-local-vm.e2e.test.tsindex 9f8689fe4f..1ddcef5969 100644--- a/server/group-local-vm.e2e.test.ts+++ b/server/group-local-vm.e2e.test.ts@@ -310,16 +310,17 @@ describe("Group Local VM ownership on the real isolated server", () => {rmSync(dumpFile, { force: true });await api("POST", `/api/bots/${bots[2].id}/messages`, { text: "Wait for an available seat." });+ const waitingComputer = computer(await dump());+ void gate(waitingComputer).catch(() => undefined);await until(async () => {const state = await api("GET", "/api/bots?messages=30");return state.bots.find((bot: any) => bot.id === bots[2].id)?.messages.some((message: any) => String(message.tool?.name ?? "").startsWith("Waiting for its turn on this computer"));}, Boolean);- expect(existsSync(dumpFile)).toBe(false);const waitingStatus = await api("GET", `/api/bots/${bots[2].id}/local-computer`);const holder = waitingStatus.target_key === "pool:0" ? bots[0] : bots[1];await api("POST", `/api/bots/${holder.id}/interrupt`, {}); await idle(holder.id);- expect(JSON.stringify(computer(await dump()))).toContain(waitingStatus.container_name);+ expect(JSON.stringify(waitingComputer)).toContain(waitingStatus.container_name);expect(readState().containers.filter((key: string) => key.startsWith("pool:")).sort()).toEqual(["pool:0", "pool:1"]);} finally {vmState({ ...readState(), blockedTarget: undefined });diff --git a/server/host/browser-seats.test.ts b/server/host/browser-seats.test.tsnew file mode 100644index 0000000000..747647a626--- /dev/null+++ b/server/host/browser-seats.test.ts@@ -0,0 +1,124 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { TurnResources, type TurnOwner } from "../turn-resources.ts";+import { BROWSER_HANDED_OVER, BROWSER_WAITED, browserBusyText, browserResource, createBrowserSeats } from "./browser-seats.ts";++const A: TurnOwner = { threadId: "a", generation: "g-a" }, B: TurnOwner = { threadId: "b", generation: "g-b" }, C: TurnOwner = { threadId: "c", generation: "g-c" };+const SESSION = "bot-1", RESOURCE = browserResource(SESSION);++function seats(options: { working?: boolean; idleHandoverMs?: number; callWaitMs?: number } = {}) {+ const resources = new TurnResources(), rows: Array<{ threadId: string; name: string }> = [], events: string[] = [];+ const ended = new Set<string>();+ const state = { working: options.working ?? false, clock: 1_000 };+ const seat = createBrowserSeats({+ resources, claim: (owner, resource) => resources.claim(resource, owner), active: (owner) => !ended.has(owner.generation), working: () => state.working,+ holderOf: (owner) => ({ holder: { name: "Scout", task: `job ${owner.threadId}` } }), language: () => undefined,+ row: (threadId, name) => { rows.push({ threadId, name }); },+ waitStarted: (threadId, resource, position) => { events.push(`started ${threadId} ${resource} ${position}`); },+ waitEnded: (threadId, _resource, outcome) => { events.push(`${outcome} ${threadId}`); },+ callWaitMs: options.callWaitMs ?? 20, actWithinMs: 1_000_000, idleHandoverMs: options.idleHandoverMs ?? 1_000_000, pollMs: 2, now: () => state.clock,+ });+ const end = (owner: TurnOwner) => { ended.add(owner.generation); resources.release(owner); };+ return { seat, resources, rows, events, state, end };+}+const until = (check: () => boolean) => vi.waitFor(() => expect(check()).toBe(true), { timeout: 2_000, interval: 2 });++describe("one bot's browser between its conversations", () => {+ afterEach(() => { vi.useRealTimers(); });++ it("lets the same turn keep calling, and answers another turn's call with why, naming the wait in its chat", async () => {+ const { seat, resources, rows, events, end } = seats();+ expect(await seat.take(A, SESSION)).toBeNull();+ expect(await seat.take(A, SESSION)).toBeNull();+ expect(await seat.take(B, SESSION)).toBe(browserBusyText(20));+ expect(rows).toEqual([{ threadId: "b", name: "Waiting for the browser: Scout is using it for job a. This continues by itself when it is free." }]);+ expect(events).toEqual([`started b ${RESOURCE} 1`]);+ expect(await seat.take(B, SESSION), "a second call joins the wait already under way").toBe(browserBusyText(20));+ expect(rows).toHaveLength(1);+ end(A);+ await until(() => resources.owns(RESOURCE, B));+ expect(rows.at(-1)).toEqual({ threadId: "b", name: "The browser is free. Continuing." });+ expect(await seat.take(B, SESSION)).toBeNull();+ end(B);+ });++ it("serves waiters in the order they came", async () => {+ const { seat, resources, end } = seats();+ await seat.take(A, SESSION);+ await seat.take(B, SESSION);+ await seat.take(C, SESSION);+ end(A);+ await until(() => resources.owns(RESOURCE, B));+ expect(resources.owns(RESOURCE, C)).toBe(false);+ end(B);+ await until(() => resources.owns(RESOURCE, C));+ end(C);+ });++ it("stops a wait when its turn ends, and says so", async () => {+ const { seat, rows, events, end } = seats();+ await seat.take(A, SESSION);+ await seat.take(B, SESSION);+ end(B);+ await until(() => events.includes("stopped b"));+ expect(rows.at(-1)).toEqual({ threadId: "b", name: "Stopped waiting for the browser." });+ end(A);+ });++ it("does not perform a call that waited longer than the engine may still be waiting for it", async () => {+ const resources = new TurnResources();+ let clock = 0;+ const seat = createBrowserSeats({+ resources, claim: (owner, resource) => resources.claim(resource, owner), active: () => true, working: () => false, holderOf: () => ({}), language: () => undefined, row: () => {},+ waitStarted: () => {}, waitEnded: () => {}, callWaitMs: 200, actWithinMs: 5_000, idleHandoverMs: 1_000_000, pollMs: 1, now: () => clock,+ });+ await seat.take(A, SESSION);+ const late = seat.take(B, SESSION);+ await new Promise((resolve) => setTimeout(resolve, 5));+ clock += 6_000;+ resources.release(A);+ expect(await late).toBe(BROWSER_WAITED);+ expect(await seat.take(B, SESSION)).toBeNull();+ });++ it("hands a browser its holder has stopped using to the conversation waiting, and refuses the holder's next call once", async () => {+ const { seat, resources, state, end } = seats({ idleHandoverMs: 60_000 });+ await seat.take(A, SESSION);+ await seat.take(B, SESSION);+ expect(resources.owns(RESOURCE, A)).toBe(true);+ state.clock += 59_000;+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(resources.owns(RESOURCE, A), "a pause for thought keeps it").toBe(true);+ state.clock += 2_000;+ await until(() => resources.owns(RESOURCE, B));+ expect(await seat.take(B, SESSION)).toBeNull();+ end(B);+ expect(await seat.take(A, SESSION), "nothing lands on a page this turn did not open").toBe(BROWSER_HANDED_OVER);+ expect(await seat.take(A, SESSION)).toBeNull();+ end(A);+ });++ it("never takes it from a holder with a call running or a person's hands in the browser", async () => {+ const { seat, resources, state, end } = seats({ idleHandoverMs: 60_000, working: true });+ await seat.take(A, SESSION);+ await seat.take(B, SESSION);+ state.clock += 3_600_000;+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(resources.owns(RESOURCE, A)).toBe(true);+ state.working = false;+ await until(() => resources.owns(RESOURCE, B));+ end(A); end(B);+ });++ it("gives a holder that is still using it the whole allowance again after each call", async () => {+ const { seat, resources, state, end } = seats({ idleHandoverMs: 60_000 });+ await seat.take(A, SESSION);+ await seat.take(B, SESSION);+ state.clock += 59_000;+ seat.used(A, SESSION);+ state.clock += 59_000;+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(resources.owns(RESOURCE, A)).toBe(true);+ end(A); end(B);+ });+});diff --git a/server/host/browser-seats.ts b/server/host/browser-seats.tsnew file mode 100644index 0000000000..c20e779951--- /dev/null+++ b/server/host/browser-seats.ts@@ -0,0 +1,109 @@+// A bot's browser has one page and one set of refs, so one conversation drives it at a time. Another conversation's call+// waits for it in plain sight instead of being refused, and a holder that has stopped browsing gives it up to a waiter.+import { settledWithin } from "../auto-vm-claims.ts";+import type { ComputerHolder } from "../computer-wait.ts";+import { serverLine } from "../server-lines.ts";+import type { TurnOwner, TurnResources } from "../turn-resources.ts";++/** Longer than a model usually thinks between two browser calls. A holder quiet for this long, while another conversation+ * waits, gives the browser up; its next call is refused once, so nothing lands on a page it did not open. */+export const BROWSER_IDLE_HANDOVER_MS = 60_000;+const POLL_MS = 250;++export const browserResource = (session: string) => `browser:${session}`;++export const browserBusyText = (waitMs: number) =>+ "Another conversation of this bot is using this browser. This call was NOT performed. This turn gets the browser as soon as it is free: "+ + `to keep waiting, make a browser call again (each waits up to ${Math.round(waitMs / 1000)} seconds). Do not end your turn over this, and carry on with anything that does not need the browser.`;+export const BROWSER_WAITED =+ "This browser 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. "+ + "Another conversation had the browser, so look at the page before you act on it.";+export const BROWSER_HANDED_OVER =+ "Another conversation used this browser while this turn was not using it, so this call was NOT performed and the page may have changed. "+ + "Open the page you need again, take a fresh snapshot, then continue.";++export interface BrowserSeatDeps {+ resources: Pick<TurnResources, "blocker" | "owns" | "releaseOne" | "startWaiting" | "stopWaiting">;+ claim(owner: TurnOwner, resource: string): boolean;+ active(owner: TurnOwner): boolean;+ /** A bot call, or a person's hands, in this browser right now. */+ working(session: string): boolean;+ holderOf(owner: TurnOwner): { holder?: ComputerHolder; threadRef?: { botId: string; threadId: string; title: string } };+ row(threadId: string, name: string, threadRef?: { botId: string; threadId: string; title: string }): void;+ language(threadId: string): string | undefined;+ /** Why the watchdog does not read a long wait as a stall. */+ waitStarted(threadId: string, resource: string, position: number, holder?: ComputerHolder): void;+ waitEnded(threadId: string, resource: string, outcome: "acquired" | "stopped", waitedMs: number, holder?: ComputerHolder): void;+ callWaitMs: number;+ actWithinMs: number;+ idleHandoverMs?: number;+ pollMs?: number;+ now?: () => number;+}++export function createBrowserSeats(deps: BrowserSeatDeps) {+ const now = deps.now ?? Date.now, idleMs = deps.idleHandoverMs ?? BROWSER_IDLE_HANDOVER_MS, pollMs = deps.pollMs ?? POLL_MS;+ const waits = new Map<string, Promise<void>>();+ const lastUse = new Map<string, { generation: string; at: number }>();+ const handedOver = new Map<string, TurnOwner>();++ const handOverIfQuiet = (resource: string, session: string, waiter: TurnOwner) => {+ const holder = deps.resources.blocker(resource, waiter);+ if (!holder) return;+ const seen = lastUse.get(resource);+ if (seen?.generation !== holder.generation) { lastUse.set(resource, { generation: holder.generation, at: now() }); return; }+ if (now() - seen.at < idleMs || deps.working(session)) return;+ deps.resources.releaseOne(resource, holder);+ for (const [generation, owner] of handedOver) if (!deps.active(owner)) handedOver.delete(generation);+ handedOver.set(holder.generation, holder);+ };++ const wait = (owner: TurnOwner, resource: string, session: string): Promise<void> => {+ const running = waits.get(owner.generation);+ if (running) return running;+ const work = (async () => {+ const position = deps.resources.startWaiting(resource, owner);+ const blocker = deps.resources.blocker(resource, owner);+ const { holder, threadRef } = blocker ? deps.holderOf(blocker) : { holder: undefined, threadRef: undefined };+ const language = deps.language(owner.threadId);+ deps.row(owner.threadId, holder?.task+ ? serverLine(language, "server.browser.waitingTask", { name: holder.name, task: holder.task })+ : serverLine(language, "server.browser.waiting"), threadRef);+ deps.waitStarted(owner.threadId, resource, position, holder);+ const since = now();+ let acquired = false;+ try {+ while (deps.active(owner)) {+ handOverIfQuiet(resource, session, owner);+ if (deps.claim(owner, resource)) { acquired = true; break; }+ await new Promise<void>((resolve) => { setTimeout(resolve, pollMs).unref?.(); });+ }+ } finally {+ deps.resources.stopWaiting(resource, owner);+ waits.delete(owner.generation);+ deps.row(owner.threadId, serverLine(language, acquired ? "server.browser.free" : "server.browser.stoppedWaiting"));+ deps.waitEnded(owner.threadId, resource, acquired ? "acquired" : "stopped", now() - since, holder);+ }+ })();+ waits.set(owner.generation, work);+ return work;+ };++ return {+ /** Null when this call may go ahead; otherwise what the engine reads instead of the call's result. */+ async take(owner: TurnOwner, session: string, signal?: AbortSignal): Promise<string | null> {+ const resource = browserResource(session), askedAt = now();+ if (!deps.claim(owner, resource)) {+ await settledWithin(wait(owner, resource, session), deps.callWaitMs, signal);+ if (!deps.resources.owns(resource, owner)) return browserBusyText(deps.callWaitMs);+ }+ lastUse.set(resource, { generation: owner.generation, at: now() });+ if (handedOver.delete(owner.generation)) return BROWSER_HANDED_OVER;+ return now() - askedAt > deps.actWithinMs ? BROWSER_WAITED : null;+ },+ /** The call just answered: the quiet time a holder is allowed starts now. */+ used(owner: TurnOwner, session: string): void {+ lastUse.set(browserResource(session), { generation: owner.generation, at: now() });+ },+ };+}diff --git a/server/host/browser.ts b/server/host/browser.tsindex 7bca64f1df..b521781b05 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -439,6 +439,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {const browser = threadBrowser(threadId);return browser !== null && (browser.session === undefined || !browserRunning(browser.session, browser.spec));},+ which: (threadId) => threadBrowser(threadId)?.session,running: (threadId) => {const browser = threadBrowser(threadId);return browser?.session !== undefined && browserRunning(browser.session, browser.spec);diff --git a/server/host/cloud-plan-tier.test.ts b/server/host/cloud-plan-tier.test.tsnew file mode 100644index 0000000000..1dcc4eb955--- /dev/null+++ b/server/host/cloud-plan-tier.test.ts@@ -0,0 +1,46 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { CLOUD_PLAN_TIER_FILE, createCloudPlanTier } from "./cloud-plan-tier.ts";++const dirs: string[] = [];+const dir = () => { const made = mkdtempSync(join(tmpdir(), "omb-plan-tier-")); dirs.push(made); return made; };+afterEach(() => { for (const made of dirs.splice(0)) rmSync(made, { recursive: true, force: true }); });++describe("which plan this Cloud is on", () => {+ it("is not Starter until the Admin says so, and follows what it says at once, across a restart", () => {+ const dataDir = dir();+ let changes = 0;+ const plan = createCloudPlanTier({ dataDir, cloudHome: true, changed: () => { changes += 1; } });+ expect(plan.tier()).toBeUndefined();+ expect(plan.starter()).toBe(false);+ plan.set("starter");+ expect(plan.starter()).toBe(true);+ expect(createCloudPlanTier({ dataDir, cloudHome: true }).starter()).toBe(true);+ plan.set("starter");+ expect(changes).toBe(1);+ plan.set("pro");+ expect(plan.starter()).toBe(false);+ expect(changes).toBe(2);+ expect(JSON.parse(readFileSync(join(dataDir, CLOUD_PLAN_TIER_FILE), "utf8"))).toEqual({ v: 1, tier: "pro" });+ });++ it("treats Personal, a damaged file, a malformed tier and a server that is no Cloud as not Starter", () => {+ const dataDir = dir();+ const plan = createCloudPlanTier({ dataDir, cloudHome: true });+ plan.set("personal");+ expect(plan.starter()).toBe(false);+ plan.set("NOT A TIER");+ expect(plan.tier()).toBe("personal");+ writeFileSync(join(dataDir, CLOUD_PLAN_TIER_FILE), "{broken");+ expect(createCloudPlanTier({ dataDir, cloudHome: true }).starter()).toBe(false);+ const desktop = createCloudPlanTier({ dataDir: dir(), cloudHome: false });+ desktop.set("starter");+ expect(desktop.starter()).toBe(false);+ const leftover = dir();+ writeFileSync(join(leftover, CLOUD_PLAN_TIER_FILE), JSON.stringify({ v: 1, tier: "starter" }));+ expect(createCloudPlanTier({ dataDir: leftover, cloudHome: false }).starter()).toBe(false);+ });+});diff --git a/server/host/cloud-plan-tier.ts b/server/host/cloud-plan-tier.tsnew file mode 100644index 0000000000..e8c4b3fd97--- /dev/null+++ b/server/host/cloud-plan-tier.ts@@ -0,0 +1,45 @@+// Which plan this Cloud is on, as the Admin last said in its signed POST /api/cloud/plan. Kept in a file so a restart keeps+// it. An Admin that never said, a damaged file, and anything that is not a Cloud home all read as not Starter: a limit never+// lands on someone by accident of a missing signal.+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { writeFileAtomic } from "../atomic.ts";++export const CLOUD_PLAN_TIER_FILE = "cloud-plan-tier.json";+export const CLOUD_TIER = /^[a-z][a-z0-9_-]{0,31}$/;+const fileSchema = z.object({ v: z.literal(1), tier: z.string().regex(CLOUD_TIER) });++export interface CloudPlanTier {+ tier(): string | undefined;+ starter(): boolean;+ set(tier: string): void;+}++export function createCloudPlanTier(deps: { dataDir: string; cloudHome: boolean; changed?: () => void }): CloudPlanTier {+ const file = join(deps.dataDir, CLOUD_PLAN_TIER_FILE);+ let tier: string | undefined;+ if (deps.cloudHome) {+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) tier = parsed.data.tier;+ } catch {+ // none yet, or unreadable: not Starter+ }+ }+ return {+ tier: () => tier,+ starter: () => tier === "starter",+ set(next) {+ if (!deps.cloudHome || !CLOUD_TIER.test(next) || next === tier) return;+ tier = next;+ try {+ writeFileAtomic(file, `${JSON.stringify({ v: 1, tier: next })}\n`, { mode: 0o600 });+ } catch (error) {+ console.warn(`cloud plan: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);+ }+ deps.changed?.();+ },+ };+}diff --git a/server/host/cloud-signed-host.ts b/server/host/cloud-signed-host.tsindex 959cf68296..1cb4cb5aaf 100644--- a/server/host/cloud-signed-host.ts+++ b/server/host/cloud-signed-host.ts@@ -24,6 +24,8 @@ export interface CloudSignedHostDeps {policyChanged?: () => void;/** The plan was cancelled, or renews again (the Admin's signed request): routines wait while it is cancelled. */plan?: (cancelled: boolean) => void;+ /** Which plan this Cloud is on now (the Admin's signed request). */+ planTier?: (tier: string) => void;}export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth: CloudHealth | null; cloudSigned: ReturnType<typeof createCloudSignedRoutes> | null } {@@ -31,7 +33,7 @@ export function createCloudSignedHost(deps: CloudSignedHostDeps): { cloudHealth:const cloudSigned = deps.cloudHome && cloudHealth? createCloudSignedRoutes({ secret: deps.cloudHome.bootstrapSecret, sessions: deps.sessions, team: deps.cloudHome.team, health: cloudHealth, power: deps.power, box: deps.box,...(deps.cloudHome.team && deps.teamAdmin ? { teamAdmin: deps.teamAdmin } : {}),- ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}) })+ ...(deps.cloudHome.team && deps.memberLeft ? { memberLeft: deps.memberLeft } : {}), ...(deps.cloudHome.team && deps.policyChanged ? { policyChanged: deps.policyChanged } : {}), ...(deps.plan ? { plan: deps.plan } : {}), ...(deps.planTier ? { planTier: deps.planTier } : {}) }): null;return { cloudHealth, cloudSigned };}diff --git a/server/incidents.e2e.test.ts b/server/incidents.e2e.test.tsindex 7728cd18e4..2ade004afc 100644--- a/server/incidents.e2e.test.ts+++ b/server/incidents.e2e.test.ts@@ -248,7 +248,7 @@ it("reviews the work it handed on from a report without the Chief's computer, ev}}, 150_000);-it("keeps the team computer for a report turn, and answers without it once it is missing", async () => {+it("keeps the team computer for a report turn, and reports a run that reaches for one that has gone missing", async () => {// A loopback Boat: the team computer is created, then disappears; one listing can be held open.const boxes: Array<{ id: string; name: string; state: string }> = [];let gone = false;@@ -324,16 +324,22 @@ it("keeps the team computer for a report turn, and answers without it once it isgone = true;rmSync(file(incidents, "gate"));+ // A turn runs without the computer until it reaches for it, which is when a missing one stops it.+ const reachForComputer = async (threadId: string) => {+ const env = (await dump(threadId)).mcpConfig.mcpServers.computer.env;+ await fetch(`${env.OMB_HARNESS_URL}/api/internal/computer/mcp`, {+ method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${env.OMB_MCP_TOKEN_COMPUTER}` },+ body: JSON.stringify({ method: "tools/call", params: { name: "screenshot", arguments: {} } }),+ });+ };await control(["send", "--bot", team.cara.id, "--text", "File the expense report."]);+ await reachForComputer(team.cara.activeTaskId);await expect.poll(async () => (await messages(incidents)).some((m) =>m.kind === "activity" && /^Cara hit a problem: its run in its thread #File the expense report\. could not start: .*cloud computer is missing/.test(m.tool?.name ?? ""),), { timeout: 20_000 }).toBe(true);await reportRan("Cara's run in its thread #File the expense report. could not start");- const run = await dump(incidents);- expect(Object.keys(run.mcpConfig.mcpServers)).not.toContain("computer");- expect(run.systemPrompt).toContain("your computer could not be prepared for it (The team's cloud computer is missing");- expect(run.systemPrompt).not.toContain("Your team shares the cloud computer");await control(["send", "--bot", team.dan.id, "--text", "Book the venue."]);+ await reachForComputer(team.dan.activeTaskId);await expect.poll(async () => (await messages(team.dan.activeTaskId)).some((m) => /cloud computer is missing/.test(m.tool?.name ?? "")), { timeout: 20_000 }).toBe(true);expect((await messages(team.dan.activeTaskId)).some((m) => /Waiting for its turn/.test(m.tool?.name ?? ""))).toBe(false);writeFileSync(file(incidents, "gate"), "finish");diff --git a/server/index.test.ts b/server/index.test.tsindex 1f6339d6fb..f9094469c5 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -338,6 +338,16 @@ const claudePrompts = (file = fakeClaudePrompts): string[] =>existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean) : [];const COMPUTER_FREE_NOTE = "OpenMausBot computer update: the computer this conversation waited for is free again. Continue the task that parked waiting for it.";+/** The running turn's first screen call, which is what takes a cloud computer; the answer waits while another turn has it. */+const reachForComputer = async () => {+ const dump = await readJsonFileWhenReady<{ mcpConfig: { mcpServers: { computer: { env: Record<string, string> } } } }>(fakeClaudeDump);+ const env = dump.mcpConfig.mcpServers.computer.env;+ return fetch(`${env.OMB_HARNESS_URL}/api/internal/computer/mcp`, {+ method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${env.OMB_MCP_TOKEN_COMPUTER}` },+ body: JSON.stringify({ method: "tools/call", params: { name: "screenshot", arguments: {} } }),+ }).catch(() => undefined);+};+const readJsonFileWhenReady = async <T = unknown>(file: string, timeout = 5_000): Promise<T> => {let parsed: unknown;await expect.poll(() => {@@ -3529,9 +3539,12 @@ describe("harness HTTP API", () => {await promptedOnTeamComputer(1, botIds[0]);expect((await readJsonFileWhenReady<ComputerDump>(fakeClaudeDump)).mcpConfig.mcpServers.computer?.args).toEqual([expect.stringMatching(/harness-mcp-proxy\.(?:ts|js)$/), "computer"]);+ await reachForComputer();const firstThread = (await api("GET", "/api/bots?messages=0")).body.bots.find((b: { id: string }) => b.id === botIds[0]).threadId;const sibling = (await api("POST", `/api/bots/${botIds[0]}/tasks`, { title: "Waiting sibling" })).body.task;+ rmSync(fakeClaudeDump, { force: true });expect((await api("POST", `/api/bots/${botIds[0]}/messages`, { text: "wait then cancel", threadId: sibling.threadId })).status).toBe(202);+ void reachForComputer();await expect.poll(async () => JSON.stringify((await api("GET", `/api/threads/${sibling.threadId}/messages`)).body),{ timeout: 5_000 }).toMatch(/Waiting for its turn on this computer/);expect((await api("POST", `/api/bots/${botIds[0]}/interrupt`, { threadId: sibling.threadId })).status).toBe(200);@@ -3553,7 +3566,7 @@ describe("harness HTTP API", () => {outcome: "stopped",});expect(siblingEvents.find((event) => event.type === "turn.wait_ended").waitedMs).toBeGreaterThanOrEqual(0);- expect(claudePrompts().length - promptBaseline).toBe(1);+ expect(claudePrompts().length - promptBaseline, "the sibling ran from the start").toBe(2);expect((await api("POST", `/api/bots/${botIds[0]}/tasks/${firstThread}`, {})).status).toBe(200);for (const action of ["sleep", "provision"]) {expect((await api("POST", `/api/team-computers/${requestId}/${action}`, { acknowledgeCost: true })).status).toBe(409);@@ -3561,15 +3574,16 @@ describe("harness HTTP API", () => {expect((await api("PATCH", `/api/team-computers/${requestId}`, { section: null, acknowledgeSharedAccess: true })).status).toBe(409);expect((await api("PATCH", `/api/bots/${botIds[0]}`, { computer: "off" })).status).toBe(409);+ rmSync(fakeClaudeDump, { force: true });expect((await api("POST", `/api/groups/${roomId}/messages`, { text: "use the occupied shared desktop" })).status).toBe(202);+ void reachForComputer();await expect.poll(async () => JSON.stringify((await api("GET", "/api/bots?messages=30")).body.groups.find((group: { id: string }) => group.id === roomId,)), { timeout: 5_000 }).toMatch(/Waiting for its turn on this computer/);- expect(claudePrompts().length - promptBaseline).toBe(1);+ expect(claudePrompts().length - promptBaseline, "the room's speaker ran from the start too").toBe(3);expect((await api("POST", `/api/bots/${botIds[0]}/interrupt`, {})).status).toBe(200);await idle(botIds[0]);- await promptedOnTeamComputer(2, botIds[1]);await expect.poll(async () => JSON.stringify((await api("GET", "/api/bots?messages=30")).body.groups.find((group: { id: string }) => group.id === roomId,)), { timeout: 5_000 }).toMatch(/Computer free — continuing after waiting /);@@ -3594,11 +3608,11 @@ describe("harness HTTP API", () => {managedBoatCreatedIds.clear();rmSync(fakeClaudeDump, { force: true });expect((await api("POST", `/api/bots/${botIds[0]}/messages`, { text: "do not create a replacement" })).status).toBe(202);+ void reachForComputer();await expect.poll(async () => JSON.stringify((await api("GET", "/api/bots?messages=30")).body.bots.find((bot: { id: string }) => bot.id === botIds[0],)), { timeout: 5_000 }).toMatch(/team's cloud computer is missing/);await idle(botIds[0]);- expect(existsSync(fakeClaudeDump)).toBe(false);expect(boatRouteCalls.filter(call => call.method === "POST" && call.path === "/sandboxes")).toHaveLength(createCount);} finally {if (roomId) await api("POST", `/api/groups/${roomId}/interrupt`, {}).catch(() => undefined);@@ -3626,7 +3640,7 @@ describe("harness HTTP API", () => {const waiterThreads: string[] = [];try {expect((await api("PUT", "/api/config", { box: { token: "box_route" } })).status).toBe(200);- // Four live threads on one bot: at the default cap of 3 the fourth would park in the send queue instead.+ // Four live threads on one bot: on a small machine's default of 3 the fourth would park in the send queue instead.expect((await api("PUT", "/api/config", { threads: { maxConcurrentPerBot: 6 } })).status).toBe(200);const bot = (await api("POST", "/api/bots", { name: "Queue probe", section,modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot;@@ -3646,13 +3660,17 @@ describe("harness HTTP API", () => {(((await api("GET", `/api/threads/${threadId}/events`)).body.entries as Array<{ kind: string; data: any }>).filter(entry => entry.kind === "runtime").map(entry => entry.data));+ rmSync(fakeClaudeDump, { force: true });expect((await api("POST", `/api/bots/${botId}/messages`, { text: "hold the queue desktop" })).status).toBe(202);await expect.poll(promptsOnBox, { timeout: 5_000 }).toBe(1);+ await reachForComputer();for (const [index, title] of ["First waiter", "Second waiter", "Third waiter"].entries()) {const task = (await api("POST", `/api/bots/${botId}/tasks`, { title })).body.task;waiterThreads.push(task.threadId);+ rmSync(fakeClaudeDump, { force: true });expect((await api("POST", `/api/bots/${botId}/messages`, { text: `arrival ${index + 1} of the queue`, threadId: task.threadId })).status).toBe(202);+ void reachForComputer();await expect.poll(async () => JSON.stringify(await threadMessages(task.threadId)), { timeout: 5_000 }).toMatch(new RegExp(`${index + 1}(st|nd|rd) in queue`));expect((await threadMessages(task.threadId)).some(message => (message.tool?.name ?? "").includes("recent waits here"))).toBe(false);@@ -3660,16 +3678,17 @@ describe("harness HTTP API", () => {.toMatchObject({ position: index + 1 });}+ expect(promptsOnBox(), "every waiter ran from the start").toBe(4);expect((await api("POST", `/api/bots/${botId}/interrupt`, { threadId: holderThread })).status).toBe(200);- await expect.poll(promptsOnBox, { timeout: 10_000 }).toBe(2);- expect(claudePrompts().at(-1)).toContain("arrival 1 of the queue");await expect.poll(async () => JSON.stringify(await threadMessages(waiterThreads[0]!)), { timeout: 5_000 }).toMatch(/Computer free — continuing after waiting /);- expect(promptsOnBox()).toBe(2);+ expect(JSON.stringify(await threadMessages(waiterThreads[1]!))).not.toMatch(/Computer free/);const fourth = (await api("POST", `/api/bots/${botId}/tasks`, { title: "Fourth waiter" })).body.task;waiterThreads.push(fourth.threadId);+ rmSync(fakeClaudeDump, { force: true });expect((await api("POST", `/api/bots/${botId}/messages`, { text: "arrival 4 wants an estimate", threadId: fourth.threadId })).status).toBe(202);+ void reachForComputer();await expect.poll(async () => JSON.stringify(await threadMessages(fourth.threadId)), { timeout: 5_000 }).toMatch(/3rd in queue/);await expect.poll(async () => JSON.stringify(await threadMessages(fourth.threadId)), { timeout: 5_000 }).toMatch(/recent waits here have taken /);for (const threadId of waiterThreads.slice(0, 3)) {@@ -3678,8 +3697,8 @@ describe("harness HTTP API", () => {}expect((await api("POST", `/api/bots/${botId}/interrupt`, { threadId: waiterThreads[0] })).status).toBe(200);- await expect.poll(promptsOnBox, { timeout: 10_000 }).toBe(3);- expect(claudePrompts().at(-1)).toContain("arrival 2 of the queue");+ await expect.poll(async () => JSON.stringify(await threadMessages(waiterThreads[1]!)), { timeout: 10_000 })+ .toMatch(/Computer free — continuing after waiting /);} finally {if (holderThread) await api("POST", `/api/bots/${botId}/interrupt`, { threadId: holderThread }).catch(() => undefined);for (const threadId of waiterThreads) await api("POST", `/api/bots/${botId}/interrupt`, { threadId }).catch(() => undefined);@@ -3729,9 +3748,11 @@ describe("harness HTTP API", () => {OMB_STATIC_DIR: isolatedStatic,OMB_BOAT_API: `http://127.0.0.1:${boatStubPort}`,FAKE_CLAUDE_MODE: "hang",+ FAKE_CLAUDE_USES_CLOUD_COMPUTER: "1",FAKE_CLAUDE_PROMPTS: join(isolatedHome, "desktop-prompts.jsonl"),// seconds, not minutes: the point of this test is the computer cap firingOMB_COMPUTER_WAIT_MAX_MS: "2000",+ OMB_COMPUTER_CALL_WAIT_MS: "500",},stdio: ["ignore", "pipe", "pipe"],});@@ -3801,7 +3822,7 @@ describe("harness HTTP API", () => {expect(settledMessages.filter((message: any) => message.tool?.ok === false && /Computer still busy|Parked/.test(message.tool.name))).toHaveLength(0);expect((await isolatedApi("POST", `/api/bots/${botId}/interrupt`, { threadId: holderThreadId })).status).toBe(200);- await expect.poll(promptsOnParkBox, { timeout: 10_000 }).toBeGreaterThanOrEqual(2);+ await expect.poll(promptsOnParkBox, { timeout: 10_000 }).toBeGreaterThanOrEqual(3);const roomBot = (await isolatedApi("POST", "/api/bots", {name: "Park room speaker", section,@@ -3828,19 +3849,23 @@ describe("harness HTTP API", () => {}, { timeout: 5_000 }).toMatchObject([{ data: { outcome: "parked" } }]);expect((await isolatedApi("POST", `/api/bots/${botId}/interrupt`, { threadId: sibling.threadId })).status).toBe(200);- await expect.poll(promptsOnParkBox, { timeout: 10_000 }).toBeGreaterThanOrEqual(3);+ await expect.poll(promptsOnParkBox, { timeout: 10_000 }).toBeGreaterThanOrEqual(5);await expect.poll(roomRows, { timeout: 5_000 }).toEqual([[roomBot.id, null, "running", 2, null]]);expect(claudePrompts(join(isolatedHome, "desktop-prompts.jsonl")).at(-1)).toContain("Continue the task that parked waiting for it");- // Every turn that reaches the hanging Box prompt counts once, so a stale resume would show as a fifth prompt.+ // Every turn counts once as it starts, and a resume once more: a stale resume would show as one prompt too many.expect((await isolatedApi("POST", `/api/bots/${botId}/messages`, { text: "wait past the ceiling a second time", threadId: siblingThreadId })).status).toBe(202);await expect.poll(async () => JSON.stringify((await isolatedApi("GET", `/api/threads/${siblingThreadId}/messages`)).body),{ timeout: 8_000 }).toMatch(/wait past the ceiling a second time[\s\S]*Parked — it continues automatically when the computer is free/);+ // Parked once its engine has gone: until then a message would go into the turn that is being stopped.+ await expect.poll(async () => (await isolatedApi("GET", "/api/bots?messages=0")).body.bots+ .find((entry: any) => entry.id === botId)?.tasks.find((task: any) => task.threadId === siblingThreadId)?.activity,+ { timeout: 8_000 }).toBe("parked.computer");expect((await isolatedApi("POST", `/api/bots/${botId}/messages`, { text: "newer work replaces the parked wait", threadId: siblingThreadId })).status).toBe(202);expect((await isolatedApi("POST", `/api/groups/${roomId}/interrupt`, {})).status).toBe(200);- await expect.poll(promptsOnParkBox, { timeout: 10_000 }).toBeGreaterThanOrEqual(4);+ await expect.poll(promptsOnParkBox, { timeout: 10_000 }).toBeGreaterThanOrEqual(7);await new Promise((resolve) => setTimeout(resolve, 3_000));- expect(promptsOnParkBox()).toBe(4);+ expect(promptsOnParkBox()).toBe(7);expect(roomRows()).toEqual([[roomBot.id, null, "cancelled", 2, null]]);await expect.poll(async () => {const task = (await isolatedApi("GET", "/api/bots?messages=0")).body.bots@@ -3863,9 +3888,10 @@ describe("harness HTTP API", () => {await expect.poll(roomRows, { timeout: 5_000 }).toEqual([[roomBot.id, null, "cancelled", 2, null], [roomBot.id, null, "queued", 1, COMPUTER_FREE_NOTE]]);expect((await isolatedApi("POST", `/api/groups/${roomId}/interrupt`, {})).status).toBe(200);await expect.poll(roomRows, { timeout: 5_000 }).toEqual([[roomBot.id, null, "cancelled", 2, null], [roomBot.id, null, "cancelled", 1, COMPUTER_FREE_NOTE]]);+ const beforeFreed = promptsOnParkBox();expect((await isolatedApi("POST", `/api/bots/${botId}/interrupt`, { threadId: siblingThreadId })).status).toBe(200);await new Promise((resolve) => setTimeout(resolve, 3_000));- expect(promptsOnParkBox()).toBe(4);+ expect(promptsOnParkBox(), `nothing stopped resumes once the computer frees: ${claudePrompts(join(isolatedHome, "desktop-prompts.jsonl")).slice(beforeFreed).join("\n").slice(-1_500)}`).toBe(beforeFreed);expect((await isolatedApi("GET", "/api/bots?messages=0")).body.bots.find((entry: any) => entry.id === botId)?.tasks.find((task: any) => task.threadId === stoppedThreadId)?.busy).toBe(false);@@ -3916,7 +3942,7 @@ describe("harness HTTP API", () => {holder: {driver: "claudeAgent",displayName: "Fixture holder",- environment: { FAKE_CLAUDE_MODE: "hang", FAKE_CLAUDE_PROMPTS: join(isolatedHome, "desktop-prompts.jsonl") },+ environment: { FAKE_CLAUDE_MODE: "hang", FAKE_CLAUDE_USES_CLOUD_COMPUTER: "1", FAKE_CLAUDE_PROMPTS: join(isolatedHome, "desktop-prompts.jsonl") },config: { cli: FAKE_CLAUDE_CLI },},lead: {@@ -3934,9 +3960,8 @@ describe("harness HTTP API", () => {displayName: "Fixture worker",environment: {FAKE_CLAUDE_PROMPTS: join(isolatedHome, "desktop-prompts.jsonl"),- FAKE_CLAUDE_MODE: "happy",- FAKE_CLAUDE_REPLIES: JSON.stringify(["The parked computer work is complete."]),- FAKE_CLAUDE_REPLY_STATE: join(isolatedHome, "worker-replies.txt"),+ FAKE_CLAUDE_USES_CLOUD_COMPUTER: "1",+ FAKE_CLAUDE_MODE: "hang",},config: { cli: FAKE_CLAUDE_CLI },},@@ -3955,6 +3980,7 @@ describe("harness HTTP API", () => {OMB_STATIC_DIR: isolatedStatic,OMB_BOAT_API: `http://127.0.0.1:${boatStubPort}`,OMB_COMPUTER_WAIT_MAX_MS: "2000",+ OMB_COMPUTER_CALL_WAIT_MS: "500",},stdio: ["ignore", "pipe", "pipe"],});@@ -4047,7 +4073,7 @@ describe("harness HTTP API", () => {expect((await isolatedApi("POST", `/api/bots/${holderBotId}/interrupt`, { threadId: holderThreadId })).status).toBe(200);await new Promise((resolve) => setTimeout(resolve, 3_000));- expect(promptsOnGoalBox()).toBe(1);+ expect(promptsOnGoalBox(), "the holder, and the worker's one start: its parked step never runs again").toBe(2);expect(goalRows()).toHaveLength(3);expect((await goalCard()).working).toBe(false);} finally {diff --git a/server/index.ts b/server/index.tsindex cc977bc83b..ad58a5e009 100644--- a/server/index.ts+++ b/server/index.ts@@ -152,7 +152,6 @@ import {mcpCallTimeoutMinutes,cacheKeepWarmSettings,threadEventLogMaxBytes,- maxConcurrentBotThreads,threadEventLogRetentionDays,saveConfig,showToolCallsEnabled,@@ -441,7 +440,7 @@ import { loginSite } from "../shared/logins.ts";import { browserRestartRefusal } from "./browser-live.ts";import { browserEngineStatus } from "./browser-engine.ts";import { chromeLauncher } from "./browser/chrome/launcher.ts";-import { createBrowserHost } from "./host/browser.ts";+import { botThreadLimitText, botThreadsHost, maxConcurrentBotThreads, maxConcurrentChildThreads } from "./bot-thread-limits.ts"; import { createBrowserSeats } from "./host/browser-seats.ts"; import { createBrowserHost } from "./host/browser.ts"; import { createCloudPlanTier } from "./host/cloud-plan-tier.ts";import { createScreenFrameSource, rememberTurnFrame, type ScreenCapture } from "./screen-frame-source.ts";import { screenFrameHash, screenSurfaceForTool, screenTouchingTool, settledFrameIsNews } from "./screen-frame-gate.ts";import { asSchedule, RoutineRequestService } from "./routine-requests.ts"; import { ownerSpokeOnly } from "./cloud-routine-level.ts"; import { routineRunCard, routineRunFallbackText } from "./routine-run-card.ts";@@ -2149,6 +2148,16 @@ function releaseTurnComputer(owner: TurnOwner): void {if (teamComputerTurns.get(owner.threadId)?.owner.generation === owner.generation) teamComputerTurns.delete(owner.threadId);}+function waitEventBase(threadId: string) {+ const selection = store.botByThread(threadId)?.modelSelection, instance = selection ? registry.get(selection.instanceId) : null;+ return { eventId: newId(), provider: instance?.driverKind ?? "harness", ...(instance && selection ? { providerInstanceId: selection.instanceId } : {}), threadId, createdAt: new Date().toISOString() };+}++function holderOfTurn({ threadId }: TurnOwner): { holder?: ComputerHolder; threadRef?: { botId: string; threadId: string; title: string } } {+ const bot = store.botByThread(threadId), task = bot && store.taskByThread(bot.id, threadId), room = !bot ? store.groupByThread(threadId) : null;+ return { holder: bot ? { name: bot.name, ...(task?.title ? { task: task.title } : {}) } : room ? { name: room.name } : undefined, threadRef: bot && task?.title ? { botId: bot.id, threadId: task.threadId, title: task.title } : undefined };+}+async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive = false): Promise<void> {// Every computer claim passes here, so a disallowed kind is refused whichever path selected it.const kind = computerKindForResource(resource), refusal = kind && computerPlaceRefusal(kind);@@ -2161,17 +2170,6 @@ async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive =const deadline = Date.now() + COMPUTER_WAIT_MAX_MS;let waitedSince: number | undefined;let waitEnded = false;- const waitEventBase = () => {- const selection = store.botByThread(owner.threadId)?.modelSelection;- const instance = selection ? registry.get(selection.instanceId) : null;- return {- eventId: newId(),- provider: instance?.driverKind ?? "harness",- ...(instance && selection ? { providerInstanceId: selection.instanceId } : {}),- threadId: owner.threadId,- createdAt: new Date().toISOString(),- };- };const endWait = (outcome: "acquired" | "parked" | "stopped") => {if (!waitingMessage || waitEnded) return;waitEnded = true;@@ -2188,7 +2186,7 @@ async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive =...(holderThreadRef ? { threadRef: holderThreadRef } : {}),});bus.publish({- ...waitEventBase(),+ ...waitEventBase(owner.threadId),type: "turn.wait_ended",resource,...(holder ? { holder } : {}),@@ -2204,15 +2202,7 @@ async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive =const position = turnResources.startWaiting(resource, owner);const estimateMs = turnResources.waitEstimateMs(resource);const blocker = turnResources.blocker(resource, owner);- const holderBot = blocker && store.botByThread(blocker.threadId);- const holderTask = holderBot && blocker && store.taskByThread(holderBot.id, blocker.threadId);- const holderRoom = !holderBot && blocker ? store.groupByThread(blocker.threadId) : null;- holder = holderBot- ? { name: holderBot.name, ...(holderTask?.title ? { task: holderTask.title } : {}) }- : holderRoom ? { name: holderRoom.name } : undefined;- holderThreadRef = holderBot && holderTask?.title- ? { botId: holderBot.id, threadId: holderTask.threadId, title: holderTask.title }- : undefined;+ ({ holder, threadRef: holderThreadRef } = blocker ? holderOfTurn(blocker) : { holder: undefined, threadRef: undefined });waitingMessage = store.appendMessage(owner.threadId, {role: "bot", kind: "activity",tool: { name: computerWaitingText(holder, { position, estimateMs }) },@@ -2220,7 +2210,7 @@ async function bindTurnComputer(owner: TurnOwner, resource: string, exclusive =});waitedSince = Date.now();bus.publish({- ...waitEventBase(),+ ...waitEventBase(owner.threadId),type: "turn.wait_started",resource,position,@@ -2257,9 +2247,9 @@ function parksBehindCoordination(botId: string, threadId: string): boolean {return (store.projectBotForTask(botId, threadId) ?? store.bot(botId))?.parkDirectMessages === true;}-function botAtThreadCapacity(botId: string, personThreadId?: string): boolean {+function botAtThreadCapacity(botId: string, personThreadId?: string, startedByABot = false): boolean {// The person's main chat is never at capacity. threadBusy, not the stored flag: a reservation holds its slot after an early completion clears the flag.- return (!personThreadId || personThreadId !== botMainThread(botId)) && store.tasks(botId).filter((task) => threadBusy(botId, task.threadId)).length >= maxConcurrentBotThreads(cfg);+ return (!personThreadId || personThreadId !== botMainThread(botId)) && store.tasks(botId).filter((task) => threadBusy(botId, task.threadId)).length >= (startedByABot ? maxConcurrentChildThreads : maxConcurrentBotThreads)(cfg, botThreadsHost(cloudPlanTier.starter()));}function hasDirectDispatch(botId: string): boolean {@@ -2270,7 +2260,7 @@ function hasDirectDispatch(botId: string): boolean {function canAdmitDirectTurn(botId: string, threadId: string): boolean {return admit("peer", {}, {threadBusy: threadBusy(botId, threadId),- atCapacity: botAtThreadCapacity(botId),+ atCapacity: botAtThreadCapacity(botId, undefined, true),groupTurn: Boolean(activeGroupTurnForBot(botId)),}).action === "start";}@@ -2882,8 +2872,8 @@ const phones = createPhones({mint: (botId, turn) => mintInternalCapability({ botId, ...turn, kind: "device", depth: 0, skillAuthoring: false, createdBots: 0, openedThreads: 0 }),active: (turn) => internalCapabilityIsActive(turn as InternalCapability),});-let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.-const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, plan: (cancelled) => routineHolds?.plan(cancelled), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,+const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolean(CLOUD_HOME), changed: () => broadcast({ kind: "config", ...configStatus() }) }); let cloudPower: CloudPower | null = null; // The sleep handshake of a plan that sleeps (server/cloud-power.ts), made just before the server listens.+const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE,engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),connectors: () => highlevelHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.dayPressure() } : {}) } });@@ -3815,7 +3805,7 @@ const threadReadableFrom = (threadId: string) => (other: string): boolean => !prconst teammatePrompts = createTeammatePrompts({ store, outstandingDirect: (threadId) => coordinator.outstandingDirect(threadId), openPersonCard, queuedStatus, isUnattended, fullAccess: fullAccessForSource, startedOutside: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "outside" || coordinator.active().some((node) => node.threadId === threadId && node.origin?.kind === "outside"), guestDriven: cloudGuestDriven, confined: (threadId) => proactive.fence.confines(threadId), readableFrom: threadReadableFrom, waitingForPerson: (chief, teammates, readable) => questionRouting.waitingForPerson(chief, teammates, readable) });function queuedBehindPerson(node: HandoffView): { threadId: string; kind: "approval" | "question" | "review"; title: string } | undefined {- if (node.groupId || node.status !== "queued" || threadBusy(node.botId, node.threadId) || !botAtThreadCapacity(node.botId)) return undefined;+ if (node.groupId || node.status !== "queued" || threadBusy(node.botId, node.threadId) || !botAtThreadCapacity(node.botId, undefined, true)) return undefined;for (const task of store.tasks(node.botId)) {if (task.threadId === node.threadId || task.activity !== "waiting-on-you") continue;const card = openPersonCard(task.threadId);@@ -5674,6 +5664,10 @@ 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 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 } : {}) }),+ waitEnded: (threadId, resource, outcome, waitedMs, holder) => bus.publish({ ...waitEventBase(threadId), type: "turn.wait_ended", resource, outcome, waitedMs, ...(holder ? { holder } : {}) }) });const localVmSeen = new Set<string>();/** An old desktop waiting for its update is still the bot's place, so it counts as seen: Auto never takes it for absent. */function noteLocalVmSeen(target: LocalVmTarget, status: ContainerComputerStatus | null | undefined): void {@@ -5843,29 +5837,37 @@ async function teamComputersPayload(): Promise<TeamComputersPayload> {}/** Assignment authorizes waking, never replacing a missing paid machine. */-async function attachTeamBoat(computer: TeamComputerRecord, botId: string, owner: TurnOwner, canMount: boolean) {- if (!canMount) throw new Error("This model cannot use the team's cloud computer; choose a model provider with computer tools or an explicit bot destination");- if (!boat.boatConfigured(cfg)) throw new Error("The team's Boat account is not configured; reconnect it in Settings");+async function attachTeamBoat(computer: TeamComputerRecord, owner: TurnOwner, onSeated: () => void) {const ownerId = teamComputerOwner(computer.id);if (boatLifecycleBusyBots.has(ownerId)) throw new Error("The team computer is being changed; wait for it to finish");- if (computerControl.snapshot(ownerId).held) throw new Error("Release human control of the team computer before starting another turn");await bindTurnComputer(owner, `computer:box-bot:${ownerId}`, true);- teamComputerTurns.set(owner.threadId, { owner, computerId: computer.id, botId });+ onSeated();let machine = await boat.findBoat(cfg, ownerId);if (!machine) throw new Error("The team's cloud computer is missing; explicitly create or retry it from the Team map");await bindTurnComputer(owner, `computer:box:${machine.id}`, true);cloudComputerPower.attached(owner, ownerId);const action = boat.boatTurnLifecycleAction(typeof machine.state === "string" ? machine.state : null);- if (action === "wake") machine = await boat.readyBoat(cfg, ownerId);+ if (action === "wake") machine = await withinBudget(boat.readyBoat(cfg, ownerId), CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_DID_NOT_START);if (!machine || boat.boatTurnLifecycleAction(typeof machine.state === "string" ? machine.state : null) !== "attach") {throw new Error("The team computer is not ready; check it in the Team map");}if (turnResourceOwners.get(owner.threadId)?.generation !== owner.generation ||!turnResources.owns(`computer:box:${machine.id}`, owner)) throw new Error("This computer turn ended while its machine was starting");- return {- mount: cloudComputerMount(botId, owner, machine.id),- capture: () => boat.screenshotBoat(cfg, ownerId, machine!.id),- };+ return { boxId: machine.id as string, capture: () => boat.screenshotBoat(cfg, ownerId, machine!.id) };+}++/** The turn runs from the start; only its first screen call takes the team's computer. */+function mountTeamBoat(computer: TeamComputerRecord, botId: string, owner: TurnOwner, canMount: boolean, opts: { onClaimed: (capture: () => Promise<{ png: string; format: string }>) => void; onRejected: (failure: string, error?: unknown) => void }): NonNullable<SendTurnInput["integrations"]>["localComputer"] {+ if (!canMount) throw new Error("This model cannot use the team's cloud computer; choose a model provider with computer tools or an explicit bot destination");+ if (!boat.boatConfigured(cfg)) throw new Error("The team's Boat account is not configured; reconnect it in Settings");+ teamComputerTurns.set(owner.threadId, { owner, computerId: computer.id, botId });+ const slot: AutoVmClaimSlot = { owner, lazy: true, startsComputer: true, label: "the team's cloud computer", onRejected: opts.onRejected, claim: async () => {+ const attached = await attachTeamBoat(computer, owner, () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; });+ slot.boxId = attached.boxId;+ opts.onClaimed(attached.capture);+ } };+ autoVmClaims.set(owner.threadId, slot);+ return cloudComputerTools(botId, owner, null);}function cloudEngine(instance: ReturnType<typeof registry.get>, model?: string): CloudEngine & { name: string } {@@ -5876,10 +5878,6 @@ function cloudEngine(instance: ReturnType<typeof registry.get>, model?: string):}/** The agent process holds only a turn-scoped capability naming this Boat, never a Boat credential. */-function cloudComputerMount(botId: string, owner: TurnOwner, boxId: string): Pick<NonNullable<SendTurnInput["integrations"]>, "localComputer"> {- return { localComputer: cloudComputerTools(botId, owner, boxId) };-}-function cloudComputerTools(botId: string, owner: TurnOwner, boxId: string | null): NonNullable<SendTurnInput["integrations"]>["localComputer"] {const control = controlIntegration(botId, owner.threadId, owner.generation, { boxId });return {@@ -7286,7 +7284,7 @@ function drainQueuedSendsNow() {}).catch(reject);}),// Provider completion can precede its dispatch promise: keep the queue until that exact handshake releases its claim.- (botId, threadId, head) => threadBusy(botId, threadId) || botAtThreadCapacity(botId, head.peerAsk ? undefined : threadId) || roomTurnHolds(activeGroupTurnForBot(botId), threadId, !head.peerAsk)+ (botId, threadId, head) => threadBusy(botId, threadId) || botAtThreadCapacity(botId, head.peerAsk ? undefined : threadId, Boolean(head.peerAsk)) || roomTurnHolds(activeGroupTurnForBot(botId), threadId, !head.peerAsk)|| directRootQueued(threadId) || (!head.peerAsk?.incident && parksBehindCoordination(botId, threadId)),);}@@ -7494,7 +7492,7 @@ async function startOrQueueOpenedThread(): Promise<{ state: "running" } | { state: "queued"; position: number } | { state: "failed"; error: string }> {const peerAsk = { botId, name: store.bot(botId)!.name, unattended: unattended || undefined };const decision = admit("opened-thread", {}, {- atCapacity: botAtThreadCapacity(botId),+ atCapacity: botAtThreadCapacity(botId, undefined, true),groupTurn: Boolean(activeGroupTurnForBot(botId)),});if (decision.action === "queue") {@@ -7722,8 +7720,8 @@ async function beginTurn(if (roomTurnHolds(activeGroupTurnForBot(botId), threadId, opts?.allowRoomTurnElsewhere === true)) {throw Object.assign(new Error("the bot is already working in a channel — wait for it to finish"), { status: 409, code: "thread_busy" });}- if (botAtThreadCapacity(botId, threadId)) {- throw Object.assign(new Error(`this bot has reached its limit of ${maxConcurrentBotThreads(cfg)} parallel threads — wait for one to finish`), { status: 409, code: "thread_limit" });+ if (botAtThreadCapacity(botId, threadId, Boolean(opts?.coordination || opts?.peerAsk || opts?.commsDepth || opts?.cardContinuation || opts?.computerSelectionContinuation))) {+ throw Object.assign(new Error(botThreadLimitText(cfg, botThreadsHost(cloudPlanTier.starter()))), { status: 409, code: "thread_limit" });}// Revoke what a previous turn left behind before minting this turn's integrations.revokeEarlierTurnCapabilities(threadId);@@ -8216,7 +8214,10 @@ async function beginTurn(}const localVmTarget = { ...localVmTargetForThread(bot.id, threadId) };let lazyReadyVm: { runtime: Runtime } | null = null;- if (!strict) {+ if (strict) {+ const seen = await containerComputerStatus(undefined, undefined, localVmTarget).catch(() => null);+ if (seen?.ready && seen.runtime && !localVmUpdates.observe(localVmTarget, seen) && !localVmImageBusy && !localVmModeChangeBusy && !localVmLifecycleBusy.has(localVmTarget.key)) lazyReadyVm = { runtime: seen.runtime };+ } else {if (!localVmSeen.has(localVmTarget.key) && !opts?.automationSource) return false;let seen = await containerComputerStatus(undefined, undefined, localVmTarget).catch(() => null);// An old desktop is updated, never swapped for this computer: an unattended run waits for it, a chat is told.@@ -8316,9 +8317,7 @@ async function beginTurn(}if (teamComputer) {- const attached = await attachTeamBoat(teamComputer, bot.id, resourceOwner, canWorkOnCloud(cloudEngine(instance)));- Object.assign(integrations, attached.mount);- previewCapture = attached.capture;+ integrations.localComputer = mountTeamBoat(teamComputer, bot.id, resourceOwner, canWorkOnCloud(cloudEngine(instance)), { onClaimed: adoptClaimedCapture, onRejected: surfaceLazyClaimRejection("the team's cloud computer") });computerKind = "box";}if (!teamComputer && cloudBackend === "box" && boat.boatConfigured(cfg) && wants === "cloud") {@@ -10120,14 +10119,6 @@ async function runClaimedGroupMemberTurn(return false;}- if (roomTeamComputer) {- const attached = await attachTeamBoat(roomTeamComputer, readyBot.id, resourceOwner, canWorkOnCloud(cloudEngine(instance)));- if (isCancelled?.() || groupSpeakers.get(threadId) !== roomSpeaker ||- activeInternalGenerationByThread.get(threadId) !== internalGeneration) return false;- Object.assign(integrations, attached.mount);- startScreenPoller(readyBot.id, threadId, { computer: attached.capture });- }-// A channel has no pin and no Auto fallback: only a destination the person chose reaches a desktop.const roomSetupIsCurrent = () => !isCancelled?.() &&groupSpeakers.get(threadId) === roomSpeaker &&@@ -10159,6 +10150,7 @@ async function runClaimedGroupMemberTurn(void instance.adapter.interruptTurn(threadId).catch(() => {});};try {+ if (roomTeamComputer) integrations.localComputer = mountTeamBoat(roomTeamComputer, readyBot.id, resourceOwner, canWorkOnCloud(cloudEngine(instance)), { onClaimed: showClaimedScreen, onRejected: failRoomClaim });if (!roomTeamComputer && roomPlan.computer === "local") {integrations.localComputer = await mountHostComputer(resourceOwner, readyBot.id, instance.adapter.capabilities.localComputerMcp === true, failRoomClaim);@@ -11868,7 +11860,7 @@ function configStatus() {const eventLogMaxBytes = threadEventLogMaxBytes(cfg);const eventLogRetentionDays = threadEventLogRetentionDays(cfg);return {- xai: keyStatus(cfg.xai?.key),+ cloudStarter: cloudPlanTier.starter(), xai: keyStatus(cfg.xai?.key),mistral: keyStatus(cfg.mistral?.key),cerebras: keyStatus(cfg.cerebras?.key),groq: keyStatus(cfg.groq?.key), greenference: keyStatus(cfg.greenference?.key),@@ -11908,7 +11900,7 @@ function configStatus() {cacheKeepWarm: cacheKeepWarmSettings(cfg),newBots: cfg.newBots?.effort ? { effort: cfg.newBots.effort } : {},threads: {- maxConcurrentPerBot: maxConcurrentBotThreads(cfg),+ maxConcurrentPerBot: maxConcurrentBotThreads(cfg, botThreadsHost(cloudPlanTier.starter())),...(eventLogMaxBytes !== null ? { eventLogMaxBytes } : {}),...(eventLogRetentionDays !== null ? { eventLogRetentionDays } : {}),},@@ -13277,6 +13269,11 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {if (body?.method !== "tools/list" && body?.method !== "tools/call") {return json(res, 400, { error: "unsupported browser method" });}+ if (body.method === "tools/call") {+ const abort = new AbortController(); res.once("close", () => { if (!res.writableEnded) abort.abort(); });+ const refused = await browserSeats.take(internalCapability, browser.session, abort.signal); requireActiveInternalCapability();+ if (refused) return json(res, 200, { result: { isError: true, content: [{ type: "text", text: refused }] } });+ }let params = body.params;if (body.method === "tools/call" && params?.name === BROWSER_UPLOAD_TOOL) {const upload = uploadableFiles(params.arguments?.files, messageFileRootsForThread(bot.id, internalCapability.threadId));@@ -13296,7 +13293,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {throw Object.assign(new Error("another thread is using this browser — pause browser work until that thread finishes"), { status: 409 });}}, stepContext(bot, internalCapability, () => liveTurnByThread.get(internalCapability.threadId) ?? null));- requireActiveInternalCapability();+ requireActiveInternalCapability(); if (body.method === "tools/call") browserSeats.used(internalCapability, browser.session);return json(res, 200, { result });}// The turn's capability names its Boat; the Boat credential stays here.@@ -14326,7 +14323,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {botId: from.id,botName: from.name,self: true,- limit: maxConcurrentBotThreads(cfg),+ limit: maxConcurrentBotThreads(cfg, botThreadsHost(cloudPlanTier.starter())),...outcome,});}diff --git a/server/parallel-threads.e2e.test.ts b/server/parallel-threads.e2e.test.tsnew file mode 100644index 0000000000..08e95da527--- /dev/null+++ b/server/parallel-threads.e2e.test.ts@@ -0,0 +1,525 @@+// Three threads of one bot, each with a turn held open by a gate only the test releases, as a desktop, personal Cloud and Team Cloud server.+import { randomBytes, randomUUID } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+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";++const SERVER_DIR = dirname(fileURLToPath(import.meta.url));+const HOST = "omb-t-0123456789ab.fly.dev";+type Role = "desktop" | "home" | "team";+const TEAM = { id: "team-7f3a", name: "Acme" };++class Fixture {+ home = mkdtempSync(join(tmpdir(), "omb-parallel-"));+ dataDir = join(this.home, ".openmausbot");+ gates = join(this.home, "gates");+ base = "";+ log = "";+ token = "";+ secret = randomBytes(32).toString("base64url");+ child: ChildProcess | null = null;+ chat: Server | null = null;+ chatInFlight: { thread: string; release: () => void }[] = [];+ extraEnv: Record<string, string> = {};+ readonly role: Role;+ constructor(role: Role) {+ this.role = role;+ mkdirSync(this.dataDir, { recursive: true });+ mkdirSync(this.gates, { recursive: true });+ }+ cloud() { return this.role !== "desktop"; }+ headers(extra: Record<string, string> = {}) {+ return {+ ...(this.cloud() ? { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}` } : { origin: this.base }),+ ...(this.token ? { authorization: `Bearer ${this.token}` } : {}),+ ...extra,+ };+ }+ async api(method: string, path: string, body?: unknown) {+ const response = await fetch(`${this.base}${path}`, {+ method,+ headers: this.headers(body === undefined ? {} : { "content-type": "application/json" }),+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ }+ async start() {+ const claude = join(this.home, "held-claude.mjs");+ writeFileSync(claude, `#!/usr/bin/env node+import { join } from "node:path";+if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true, email: "[email protected]" })); process.exit(0); }+process.env.FAKE_CLAUDE_VERSION = "2.1.284";+if (process.argv[2] !== "--version") {+ process.env.FAKE_CLAUDE_MODE = "slow";+ process.env.FAKE_CLAUDE_SLOW_FINISH_GATE = join(${JSON.stringify(this.gates)}, "release-" + process.pid);+ process.env.FAKE_CLAUDE_DUMP = join(${JSON.stringify(this.gates)}, "claude-" + process.pid + ".json");+}+await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});+`, { mode: 0o755 });+ const acp = join(this.home, "held-acp.mjs");+ writeFileSync(acp, `#!/usr/bin/env node+process.env.FAKE_ACP_MODE = "echo-gated";+process.env.FAKE_ACP_GATE_FILE = ${JSON.stringify(join(this.gates, "release"))};+process.env.FAKE_ACP_RPC_APPEND_FILE = ${JSON.stringify(join(this.gates, "acp-rpc.jsonl"))};+process.env.FAKE_ACP_MODELS = "fixture-fast";+await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-acp-cli.ts")).href)});+`, { mode: 0o755 });+ this.chat = createServer((req, res) => {+ if (req.method !== "POST") { res.writeHead(404).end("{}"); return; }+ let raw = "";+ req.on("data", (chunk) => { raw += chunk; });+ req.on("end", () => {+ const body = JSON.parse(raw) as { messages?: { role: string; content: unknown }[]; stream?: boolean };+ const last = JSON.stringify(body.messages?.findLast((m) => m.role === "user")?.content ?? "");+ const entry = { thread: last, release: () => {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ id: "c", object: "chat.completion", choices: [{ index: 0, finish_reason: "stop", message: { role: "assistant", content: "done" } }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }));+ } };+ this.chatInFlight.push(entry);+ });+ });+ await new Promise<void>((resolve) => this.chat!.listen(0, "127.0.0.1", resolve));+ const chatUrl = `http://127.0.0.1:${(this.chat.address() as AddressInfo).port}/v1`;+ writeFileSync(join(this.dataDir, "config.json"), JSON.stringify({+ features: { smartSetupChoices: false },+ instances: {+ ...Object.fromEntries(["codex", "cursor", "githubCopilot", "qwen", "hermes", "pi"].map((id) => [id, { driver: "not-a-real-driver" }])),+ claude: { driver: "claudeAgent", displayName: "Claude", config: { cli: claude } },+ heldAcp: { driver: "customAcp", displayName: "Held ACP", config: { cli: acp } },+ },+ openaiCompat: { key: "synthetic-fixture-key", url: chatUrl, model: "fixture-model" },+ }));+ const port = await freePortBlock([0, 1]);+ this.base = `http://127.0.0.1:${port}`;+ const prelude = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`;+ const roleEnv = this.role === "desktop" ? {} : {+ OMB_CLOUD_ROLE: this.role, OMB_CLOUD_MACHINE_ID: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_CLOUD_BOOTSTRAP_SECRET: this.secret, OMB_PUBLIC_URL: `https://${HOST}`,+ ...(this.role === "team" ? { OMB_CLOUD_TEAM_ID: TEAM.id, OMB_CLOUD_TEAM_NAME: TEAM.name } : {}),+ };+ this.child = spawn(process.execPath, ["--import", prelude, join(SERVER_DIR, "index.ts")], {+ cwd: join(SERVER_DIR, ".."),+ env: { PATH: process.env.PATH, HOME: this.home, USERPROFILE: this.home, OMB_DATA_DIR: this.dataDir, OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), ...roleEnv, ...this.extraEnv },+ stdio: ["ignore", "pipe", "pipe"],+ });+ this.child.stdout?.on("data", (chunk) => { this.log += chunk; });+ this.child.stderr?.on("data", (chunk) => { this.log += chunk; });+ await expect.poll(async () => {+ if (this.child!.exitCode !== null) throw new Error(`the server exited:\n${this.log}`);+ return fetch(`${this.base}/api/health`).then((r) => r.ok).catch(() => false);+ }, { timeout: 30_000, interval: 100 }).toBe(true);+ if (this.cloud()) this.token = await this.pair();+ }+ async pair() {+ const body = JSON.stringify({ label: "OpenMausBot app (Cloud)", ttlSeconds: 300, ...(this.role === "team" ? { team: TEAM, member: { email: "[email protected]", role: "admin" } } : {}) });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${this.base}/api/cloud/pairing`, { method: "POST", headers: {+ host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(this.secret, timestamp, nonce, body)}`,+ }, body });+ const granted = await response.json() as { code: string };+ return (await this.api("POST", "/api/auth/pair", { code: granted.code })).body.token as string;+ }+ release() {+ writeFileSync(join(this.gates, "release"), "finish");+ for (const held of this.chatInFlight.splice(0)) held.release();+ for (const name of this.claudeDumps()) writeFileSync(join(this.gates, `release-${name.slice("claude-".length, -".json".length)}`), "finish");+ }+ private turnDump(threadId: string) {+ const name = this.claudeDumps().find((file) => basename(this.dump(file).cwd) === threadId);+ if (!name) throw new Error(`no turn is running in ${threadId}`);+ return name;+ }+ /** Finishes only this thread's Claude turn. */+ finish(threadId: string) {+ writeFileSync(join(this.gates, `release-${this.turnDump(threadId).slice("claude-".length, -".json".length)}`), "finish");+ }+ /** The MCP servers this thread's Claude turn was launched with. */+ servers(threadId: string) { return this.dump(this.turnDump(threadId)).mcpConfig.mcpServers; }+ dump(file: string) { return JSON.parse(readFileSync(join(this.gates, file), "utf8")); }+ claudeDumps() {+ return readdirSync(this.gates).filter((name) => {+ if (!name.startsWith("claude-") || !name.endsWith(".json")) return false;+ try { this.dump(name); return true; } catch { return false; }+ });+ }+ async stop() {+ if (this.child && this.child.exitCode === null) { this.child.kill("SIGTERM"); await waitForExit(this.child); }+ await new Promise<void>((resolve) => this.chat ? this.chat.close(() => resolve()) : resolve());+ await removeTempDir(this.home);+ }+ claudeTurnsStarted() { return this.claudeDumps().length; }+ acpPrompts() {+ const file = join(this.gates, "acp-rpc.jsonl");+ return existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((row) => row.method === "session/prompt") : [];+ }+}++const roles: Role[] = ["desktop", "home", "team"];+const CLAUDE = { instanceId: "claude", model: "claude-sonnet-5" };+const engines = [+ { name: "the Claude CLI", selection: CLAUDE, running: (f: Fixture) => f.claudeTurnsStarted() },+ { name: "an ACP agent", selection: { instanceId: "heldAcp", model: "fixture-fast" }, running: (f: Fixture) => f.acpPrompts().length },+ { name: "an OpenAI-compatible model", selection: { instanceId: "openaiCompat", model: "fixture-model" }, running: (f: Fixture) => f.chatInFlight.length },+];++async function botWithThreads(f: Fixture, selection: { instanceId: string; model: string }, count: number, name = "Scout") {+ const created = await f.api("POST", "/api/bots", { name, modelSelection: selection });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ const bot = created.body.bot as { id: string; threadId: string };+ const threads = [bot.threadId];+ while (threads.length < count) {+ const made = await f.api("POST", `/api/bots/${bot.id}/tasks`, { title: `Thread ${threads.length + 1}` });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ threads.push(made.body.task.threadId);+ }+ return { botId: bot.id, threads };+}+const botRow = async (f: Fixture, botId: string) => (await f.api("GET", "/api/bots?messages=0")).body.bots.find((row: any) => row.id === botId);+const busyThreads = async (f: Fixture, botId: string) => (await botRow(f, botId)).tasks.filter((task: any) => task.busy).map((task: any) => task.threadId as string);+const send = async (f: Fixture, botId: string, threadId: string, text: string) => {+ const sent = await f.api("POST", `/api/bots/${botId}/messages`, { threadId, text });+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);+ expect(sent.body.queued, JSON.stringify(sent.body)).toBeUndefined();+};+const rows = async (f: Fixture, threadId: string) => ((await f.api("GET", `/api/threads/${threadId}/messages?limit=30`)).body.messages as any[])+ .map((message) => message.tool?.name).filter((name): name is string => typeof name === "string");+const internal = async (f: Fixture, path: string, token: string, body: unknown) => {+ const response = await fetch(`${f.base}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify(body) });+ return { status: response.status, body: await response.json() as any };+};++describe.each(roles)("one bot's threads on a %s server", (role) => {+ let f: Fixture;+ afterEach(async () => { await f?.stop(); });++ it.each(engines)("are all running at once on $name", async ({ selection, running }) => {+ f = new Fixture(role);+ await f.start();+ const { botId, threads } = await botWithThreads(f, selection, 3);+ await Promise.all(threads.map((threadId, i) => send(f, botId, threadId, `Long job ${i}`)));+ await expect.poll(() => running(f), { timeout: 20_000, interval: 50 }).toBe(3);+ expect((await busyThreads(f, botId)).sort()).toEqual([...threads].sort());+ f.release();+ await expect.poll(async () => (await botRow(f, botId)).busy, { timeout: 20_000, interval: 100 }).toBe(false);+ }, 90_000);++ it("still count as busy while one finishes and another runs, so a Cloud does not sleep under the other", async () => {+ f = new Fixture(role);+ await f.start();+ const { botId, threads } = await botWithThreads(f, CLAUDE, 2);+ await send(f, botId, threads[0]!, "Long job 0");+ await send(f, botId, threads[1]!, "Long job 1");+ await expect.poll(() => f.claudeTurnsStarted(), { timeout: 20_000, interval: 50 }).toBe(2);+ f.finish(threads[0]!);+ await expect.poll(() => busyThreads(f, botId), { timeout: 20_000, interval: 100 }).toEqual([threads[1]]);+ expect((await botRow(f, botId)).busy).toBe(true);+ f.release();+ await expect.poll(async () => (await botRow(f, botId)).busy, { timeout: 20_000, interval: 100 }).toBe(false);+ }, 90_000);+});++/** An agent-browser stand-in answering MCP: no Chrome, no page. */+function inertBrowser(dir: string) {+ const browser = join(dir, "agent-browser");+ writeFileSync(browser, [+ "#!/usr/bin/env node",+ 'import { createInterface } from "node:readline";',+ 'if (process.argv[2] === "mcp") {',+ ' createInterface({ input: process.stdin }).on("line", (line) => {',+ ' const message = JSON.parse(line); if (message.id === undefined) return;',+ ' const result = message.method === "initialize" ? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "inert-browser", version: "1" } }',+ ' : message.method === "tools/list" ? { tools: [{ name: "agent_browser_snapshot", inputSchema: { type: "object" } }] }',+ ' : { content: [{ type: "text", text: "inert browser action" }] };',+ ' process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }) + "\\n");',+ ' });',+ '} else { if (process.argv[2] === "session") console.log(JSON.stringify({ success: true, data: { sessions: [] } })); process.exit(0); }',+ ].join("\n"), { mode: 0o755 });+ return browser;+}+const browse = (f: Fixture, threadId: string) => internal(f, "/api/internal/browser/mcp", f.servers(threadId).browser.env.OMB_MCP_TOKEN_BROWSER, {+ method: "tools/call", params: { name: "agent_browser_snapshot", arguments: {} },+});++// The stand-in is a script with a shebang, which Windows cannot run as a program.+describe.skipIf(process.platform === "win32").each(["desktop", "home"] as const)("two threads wanting one bot's browser on a %s server", (role) => {+ let f: Fixture;+ afterEach(async () => { await f?.stop(); });+ const running = async (env: Record<string, string>) => {+ f = new Fixture(role);+ f.extraEnv = { OMB_AGENT_BROWSER_PATH: inertBrowser(f.home), OMB_COMPUTER_CALL_WAIT_MS: "500", ...env };+ await f.start();+ const { botId, threads } = await botWithThreads(f, CLAUDE, 2);+ await send(f, botId, threads[0]!, "First job");+ await send(f, botId, threads[1]!, "Second job");+ await expect.poll(() => f.claudeTurnsStarted(), { timeout: 20_000, interval: 50 }).toBe(2);+ return { botId, threads };+ };++ it("wait in plain sight while both keep working, and the second gets it when the first finishes", async () => {+ const { botId, threads } = await running({});+ expect((await browse(f, threads[0]!)).body.result.isError).toBeFalsy();+ const waiting = await browse(f, threads[1]!);+ expect(waiting.status, "the second thread's call is answered, not refused").toBe(200);+ expect(waiting.body.result).toEqual({ isError: true, content: [{ type: "text", text: browserBusyText(500) }] });+ expect((await rows(f, threads[1]!)).find((name) => name.startsWith("Waiting for the browser")), "the person sees why").toContain("Scout is using it");+ expect((await busyThreads(f, botId)).sort(), "both threads run at once").toEqual([...threads].sort());+ f.finish(threads[0]!);+ await expect.poll(async () => (await browse(f, threads[1]!)).body.result.isError, { timeout: 20_000, interval: 100 }).toBeFalsy();+ await expect.poll(() => rows(f, threads[1]!), { timeout: 10_000, interval: 50 }).toContain("The browser is free. Continuing.");+ f.release();+ await expect.poll(async () => (await botRow(f, botId)).busy, { timeout: 20_000, interval: 100 }).toBe(false);+ }, 90_000);++ it("hand the browser over once its holder has stopped using it, and the holder does not act on a page it did not open", async () => {+ const { botId, threads } = await running({ OMB_BROWSER_IDLE_HANDOVER_MS: "200", OMB_COMPUTER_CALL_WAIT_MS: "5000" });+ expect((await browse(f, threads[0]!)).body.result.isError).toBeFalsy();+ expect((await browse(f, threads[1]!)).body.result.isError, "taken from a holder that went quiet, with both turns still running").toBeFalsy();+ expect((await busyThreads(f, botId)).sort()).toEqual([...threads].sort());+ expect((await browse(f, threads[0]!)).body.result.content[0].text).toBe(BROWSER_HANDED_OVER);+ expect((await browse(f, threads[0]!)).body.result.isError).toBeFalsy();+ f.release();+ await expect.poll(async () => (await botRow(f, botId)).busy, { timeout: 20_000, interval: 100 }).toBe(false);+ }, 90_000);+});++// One relay stands in for the Admin's Boat proxy; a picture stands in for the desktop.+const FRAME = Buffer.from("/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/wAALCAABAAEBAREA/8QAFAABAAAAAAAAAAAAAAAAAAAACf/EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAD8AKp//2Q==", "base64");+describe.each(["desktop", "team"] as const)("two threads of a bot on the team's shared computer on a %s server", (role) => {+ let f: Fixture;+ const servers: Server[] = [];+ afterEach(async () => {+ await f?.stop();+ for (const server of servers.splice(0)) { server.closeAllConnections(); server.close(); }+ });++ it("both run from the start, and only the one that reaches for the screen second waits, saying so", async () => {+ const boxes: Array<{ id: string; state: string; name?: string }> = [];+ const relay = createServer((req, res) => {+ const path = new URL(req.url ?? "/", "http://relay.test").pathname.replace(/^\/relay\/api\/box\/v1/, "");+ let raw = "";+ req.on("data", (chunk) => { raw += chunk; });+ req.on("end", () => {+ const answer = (status: number, payload: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(payload)); };+ if (path === "/boxes" && req.method === "GET") return answer(200, { ok: true, boxes, pageInfo: { nextCursor: null } });+ if (path === "/boxes" && req.method === "POST") { const box = { id: "bx_23456789", state: "ready" }; boxes.push(box); return answer(201, { ok: true, box }); }+ const [, id = "", verb = ""] = /^\/boxes\/([^/]+)(?:\/(.+))?$/.exec(path) ?? [];+ const box = boxes.find((candidate) => candidate.id === id);+ if (!box) return answer(404, { ok: false, code: "not_found", message: "Not found" });+ if (!verb && req.method === "PATCH") { box.name = JSON.parse(raw).name; return answer(200, { ok: true, box }); }+ if (!verb && req.method === "GET") return answer(200, { ok: true, box });+ if (verb === "desktop") return answer(200, { desktopUrl: `https://desktop.invalid/${box.id}` });+ if (verb === "commands") return answer(200, { exitCode: 0, stdout: "captured", stderr: "" });+ if (verb === "artifacts") { res.writeHead(200, { "content-type": "image/jpeg", "content-length": String(FRAME.length) }); return res.end(FRAME); }+ return answer(404, { ok: false, code: "not_found", message: "Not found" });+ });+ });+ servers.push(relay);+ await new Promise<void>((resolve) => relay.listen(0, "127.0.0.1", resolve));+ const relayBase = `http://127.0.0.1:${(relay.address() as AddressInfo).port}`;+ f = new Fixture(role);+ f.extraEnv = { OMB_BOAT_API: `${relayBase}/own-key-must-not-be-used`, OMB_CLOUD_BOAT_URL: `${relayBase}/relay/api/box/v1`, OMB_CLOUD_BOAT_TOKEN: "box_omb_fixture", OMB_COMPUTER_CALL_WAIT_MS: "500" };+ await f.start();+ const requestId = randomUUID();+ const made = await f.api("POST", "/api/team-computers", { requestId, name: "Ops desktop", acknowledgeCost: true });+ expect(made.status, JSON.stringify(made.body)).toBe(201);+ const { botId, threads } = await botWithThreads(f, CLAUDE, 2);+ expect((await f.api("PATCH", `/api/bots/${botId}`, { section: "Ops" })).status).toBe(200);+ const assigned = await f.api("PATCH", `/api/team-computers/${requestId}`, { section: "Ops", acknowledgeSharedAccess: true });+ expect(assigned.status, JSON.stringify(assigned.body)).toBe(200);++ await send(f, botId, threads[0]!, "First job");+ await send(f, botId, threads[1]!, "Second job");+ await expect.poll(() => f.claudeTurnsStarted(), { timeout: 20_000, interval: 50 }).toBe(2);+ expect((await busyThreads(f, botId)).sort(), "neither has touched the computer, so neither waited for it").toEqual([...threads].sort());+ expect((await rows(f, threads[1]!)).filter((name) => name.startsWith("Waiting for its turn"))).toEqual([]);++ const screenshot = (threadId: string) => {+ const env = f.servers(threadId).computer.env;+ return internal(f, "/api/internal/computer/mcp", env.OMB_MCP_TOKEN_COMPUTER, { method: "tools/call", params: { name: "screenshot", arguments: {} } });+ };+ let first = await screenshot(threads[0]!);+ for (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((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());++ f.finish(threads[0]!);+ await expect.poll(async () => (await screenshot(threads[1]!)).body.result.isError, { timeout: 30_000, interval: 200 }).toBeFalsy();+ f.release();+ await expect.poll(async () => (await botRow(f, botId)).busy, { timeout: 20_000, interval: 100 }).toBe(false);+ }, 120_000);+});++describe("a Starter Cloud", () => {+ let f: Fixture;+ const started = (threadId: string) => f.claudeDumps().some((file) => basename(f.dump(file).cwd) === threadId);+ const whenStarted = (threadId: string) => expect.poll(() => started(threadId), { timeout: 20_000, interval: 50 }).toBe(true);+ /** What the bot's own turn calls as start_thread, on the turn's own capability. */+ const startThread = async (fromThread: string, title: string, toBotId?: string) => {+ const agents = f.servers(fromThread).agents;+ const env = agents.env.OMB_GATE_UPSTREAM ? JSON.parse(agents.env.OMB_GATE_UPSTREAM).env : agents.env;+ return internal(f, "/api/internal/threads", env.OMB_COMMS_TOKEN, { title, message: `Work on ${title}`, ...(toBotId ? { toBotId } : {}) });+ };+ const ownThread = async (botId: string, title: string) => {+ await expect.poll(async () => (await botRow(f, botId)).tasks.find((task: any) => task.title === title)?.threadId, { timeout: 20_000, interval: 50 }).toBeTruthy();+ return (await botRow(f, botId)).tasks.find((task: any) => task.title === title).threadId as string;+ };+ /** What the Admin says, signed as it signs: which plan this Cloud is on. */+ const tellPlan = async (tier: string) => {+ const body = JSON.stringify({ v: 1, tier }), timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${f.base}/api/cloud/plan`, { method: "POST", body, headers: { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", "content-type": "application/json",+ "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudRequestSignature(f.secret, timestamp, nonce, "POST", "/api/cloud/plan", body)}` } });+ expect(response.status).toBe(200);+ };+ const starter = async () => {+ f = new Fixture("home");+ await f.start();+ await tellPlan("starter");+ };+ afterEach(async () => { f?.release(); await f?.stop(); });++ it("runs one thread per bot whatever is saved, queues the next in plain words, and starts it by itself when the slot frees", async () => {+ await starter();+ const saved = await f.api("PATCH", "/api/config", { threads: { maxConcurrentPerBot: 8 } });+ expect(saved.status).toBe(200);+ expect(saved.body.threads).toEqual({ maxConcurrentPerBot: 1 });+ expect(saved.body.cloudStarter).toBe(true);+ const { botId, threads } = await botWithThreads(f, CLAUDE, 3);+ await send(f, botId, threads[1]!, "First separate job");+ await whenStarted(threads[1]!);+ const queued = await f.api("POST", `/api/bots/${botId}/messages`, { threadId: threads[2], text: "Second separate job" });+ expect(queued.body).toMatchObject({ queued: true, reason: "capacity" });+ expect(started(threads[2]!)).toBe(false);+ // Per bot, not per machine: another bot's own thread runs beside it.+ const other = await botWithThreads(f, CLAUDE, 1, "Other");+ await send(f, other.botId, other.threads[0]!, "Another bot's job");+ await whenStarted(other.threads[0]!);+ f.finish(threads[1]!);+ await whenStarted(threads[2]!);+ }, 90_000);++ it("always starts the main chat the person last asked in, beside a routine, and the thread behind them starts once both are done", async () => {+ await starter();+ const { botId, threads: [main, other] } = await botWithThreads(f, CLAUDE, 2);+ await send(f, botId, main!, "The chat the person is in");+ await whenStarted(main!);+ f.finish(main!);+ await expect.poll(() => busyThreads(f, botId), { timeout: 20_000, interval: 100 }).toEqual([]);+ const created = await f.api("POST", "/api/routines", { name: "Slot holder", prompt: "Write the digest.", target: "bot", botId, runOn: "maus", enabled: true, schedule: { type: "daily", time: "23:00" } });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ const run = (await f.api("POST", `/api/routines/${created.body.routine.id}/run`)).body.run;+ await expect.poll(async () => (await f.api("GET", "/api/routines")).body.runs.find((candidate: any) => candidate.id === run.id)?.status, { timeout: 20_000, interval: 100 }).toBe("running");+ const routineThread = (await f.api("GET", "/api/routines")).body.runs.find((candidate: any) => candidate.id === run.id).threadId as string;+ await whenStarted(routineThread);+ expect((await f.api("POST", `/api/bots/${botId}/messages`, { threadId: other, text: "Waits for the slot" })).body).toMatchObject({ queued: true, reason: "capacity" });+ await send(f, botId, main!, "Never queued");+ f.release();+ await whenStarted(other!);+ }, 90_000);++ it("lets a running turn's own thread through, so a turn waiting on its child never hangs behind itself", async () => {+ await starter();+ const { botId, threads: [main] } = await botWithThreads(f, CLAUDE, 1);+ await send(f, botId, main!, "Parent job");+ await whenStarted(main!);+ const opened = await startThread(main!, "Own child");+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);+ expect(opened.body.state).toBe("running");+ await whenStarted(opened.body.threadId);+ expect((await busyThreads(f, botId)).sort(), "parent and child run at once").toEqual([main, opened.body.threadId].sort());+ const grandchild = await startThread(opened.body.threadId, "Own grandchild");+ expect(grandchild.body.state).toBe("running");+ await whenStarted(grandchild.body.threadId);+ }, 90_000);++ it("lets a hand-off through to a busy bot, and one from it back to a bot whose turn is still running", async () => {+ await starter();+ const a = await botWithThreads(f, CLAUDE, 1, "Ada");+ const b = await botWithThreads(f, CLAUDE, 1, "Ben");+ await send(f, a.botId, a.threads[0]!, "Ada's job");+ await whenStarted(a.threads[0]!);+ await send(f, b.botId, b.threads[0]!, "Ben's own job");+ await whenStarted(b.threads[0]!);+ const toBen = await startThread(a.threads[0]!, "For Ben", b.botId);+ expect(toBen.status, JSON.stringify(toBen.body)).toBeLessThan(300);+ await whenStarted(await ownThread(b.botId, "For Ben"));+ const toAda = await startThread(b.threads[0]!, "For Ada", a.botId);+ expect(toAda.status, JSON.stringify(toAda.body)).toBeLessThan(300);+ await whenStarted(await ownThread(a.botId, "For Ada"));+ expect(await busyThreads(f, a.botId), "Ada's first turn never had to end for it").toContain(a.threads[0]);+ }, 90_000);++ it("brings a teammate's result back into the thread that asked, while another thread of that bot holds the slot", async () => {+ await starter();+ const a = await botWithThreads(f, CLAUDE, 2, "Ada");+ const b = await botWithThreads(f, CLAUDE, 1, "Ben");+ const [job, busy] = a.threads;+ await send(f, a.botId, job!, "Ask Ben");+ await whenStarted(job!);+ const toBen = await startThread(job!, "For Ben", b.botId);+ expect(toBen.status, JSON.stringify(toBen.body)).toBeLessThan(300);+ const benThread = await ownThread(b.botId, "For Ben");+ await whenStarted(benThread);+ f.finish(job!);+ await expect.poll(() => busyThreads(f, a.botId), { timeout: 20_000, interval: 100 }).toEqual([]);+ await send(f, a.botId, busy!, "Holds the slot");+ await whenStarted(busy!);+ f.finish(benThread);+ const replies = async () => ((await f.api("GET", `/api/threads/${job}/messages?limit=30`)).body.messages as any[]).filter((line) => line.role === "bot" && line.kind === "text").length;+ await expect.poll(replies, { timeout: 30_000, interval: 200 }).toBeGreaterThanOrEqual(2);+ expect(await busyThreads(f, a.botId), "the other thread never had to end for it").toContain(busy);+ }, 90_000);++ it("holds a routine behind the running thread, starts it by itself when the slot frees, and refuses a guarded send at the cap", async () => {+ await starter();+ const { botId, threads } = await botWithThreads(f, CLAUDE, 2);+ await send(f, botId, threads[1]!, "Busy thread");+ await whenStarted(threads[1]!);+ const refused = await f.api("POST", `/api/bots/${botId}/messages/guarded`, { threadId: threads[0], sendId: randomUUID(), text: "From a script", expectedActiveLeafId: null, expectedApprovalMode: "ask" });+ expect(refused.status, JSON.stringify(refused.body)).toBe(409);+ const created = await f.api("POST", "/api/routines", { name: "Digest", prompt: "Write the digest.", target: "bot", botId, runOn: "maus", enabled: true, schedule: { type: "daily", time: "23:00" } });+ expect(created.status, JSON.stringify(created.body)).toBe(201);+ const run = (await f.api("POST", `/api/routines/${created.body.routine.id}/run`)).body.run;+ const state = async () => (await f.api("GET", "/api/routines")).body.runs.find((candidate: any) => candidate.id === run.id);+ expect((await state())?.status).toBe("queued");+ f.finish(threads[1]!);+ await expect.poll(async () => (await state())?.status, { timeout: 30_000, interval: 200 }).toBe("running");+ }, 90_000);++ it.each([[undefined, "an older Admin says nothing"], ["personal", "Personal is not Starter"], ["pro", "a bigger plan"]])("has no such limit on %s: %s", async (tier, _why) => {+ f = new Fixture("home");+ await f.start();+ if (tier) await tellPlan(tier);+ const { botId, threads } = await botWithThreads(f, CLAUDE, 2);+ await send(f, botId, threads[0]!, "One");+ await send(f, botId, threads[1]!, "Two");+ await expect.poll(() => f.claudeTurnsStarted(), { timeout: 20_000, interval: 50 }).toBe(2);+ expect((await f.api("GET", "/api/config")).body.cloudStarter).toBe(false);+ }, 90_000);++ it("runs more as soon as the Admin says the plan is bigger", async () => {+ await starter();+ const { botId, threads } = await botWithThreads(f, CLAUDE, 3);+ await send(f, botId, threads[0]!, "One");+ await whenStarted(threads[0]!);+ expect((await f.api("POST", `/api/bots/${botId}/messages`, { threadId: threads[1], text: "Two" })).body).toMatchObject({ queued: true, reason: "capacity" });+ await tellPlan("pro");+ await send(f, botId, threads[2]!, "Three");+ await whenStarted(threads[2]!);+ f.finish(threads[0]!);+ await whenStarted(threads[1]!);+ }, 90_000);+});diff --git a/server/routes/cloud-signed-plan.test.ts b/server/routes/cloud-signed-plan.test.tsindex 4f7592fdd8..5f96553a42 100644--- a/server/routes/cloud-signed-plan.test.ts+++ b/server/routes/cloud-signed-plan.test.ts@@ -14,14 +14,14 @@ const secret = "S".repeat(43);function routes(withPlan = true) {let counter = 0;const now = () => 1_800_000_000_000;- const told: boolean[] = [];+ const told: boolean[] = [], tiers: string[] = [];const sessions = new SessionRegistry({ file: join(DATA_DIR, "sessions.json"), now });const health = createCloudHealth({store: { onChange: () => () => {}, botByThread: () => null, bots: [] }, bus: { subscribe: () => () => {} },engines: () => [], dataDir: DATA_DIR, eventsDir: DATA_DIR, version: "0.1.0", image: undefined, connectors: () => null,browser: () => ({ available: true, installing: false, interrupted: 0 }), now,});- const handle = createCloudSignedRoutes({ secret, sessions, health, now, ...(withPlan ? { plan: (cancelled: boolean) => { told.push(cancelled); } } : {}) });+ const handle = createCloudSignedRoutes({ secret, sessions, health, now, ...(withPlan ? { plan: (cancelled: boolean) => { told.push(cancelled); }, planTier: (tier: string) => { tiers.push(tier); } } : {}) });const sign = (body: string, key = secret, method = "POST") => {const timestamp = String(Math.floor(now() / 1000)), nonce = `nonce-${String(++counter).padStart(12, "0")}`;return { "content-type": "application/json", "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,@@ -36,10 +36,31 @@ function routes(withPlan = true) {(req as unknown as PassThrough).end(body);return { answered: await answered, status, body: text ? JSON.parse(text) : null };};- return { sign, send, told };+ return { sign, send, told, tiers };}describe("POST /api/cloud/plan", () => {+ it("takes which plan this Cloud is on, alone or with the cancelled word, and leaves it alone when an older Admin says nothing of it", async () => {+ const { sign, send, told, tiers } = routes();+ const post = (value: unknown) => { const body = JSON.stringify(value); return send("POST", sign(body), body); };+ expect((await post({ v: 1, tier: "starter" })).status).toBe(200);+ expect(tiers).toEqual(["starter"]);+ expect(told).toEqual([]);+ expect((await post({ v: 1, cancelled: false })).status).toBe(200);+ expect(tiers).toEqual(["starter"]);+ expect(told).toEqual([false]);+ expect((await post({ v: 1, cancelled: true, tier: "pro" })).status).toBe(200);+ expect(tiers).toEqual(["starter", "pro"]);+ for (const bad of [{ v: 1 }, { v: 1, tier: "NOT A TIER" }, { v: 1, tier: 3 }, { v: 1, cancelled: false, tier: "../x" }, { v: 1, cancelled: "yes", tier: "pro" }]) {+ expect(await post(bad)).toMatchObject({ status: 400, body: { error: "invalid_plan" } });+ }+ expect(tiers).toEqual(["starter", "pro"]);+ expect(told).toEqual([false, true]);+ const forged = JSON.stringify({ v: 1, tier: "max" });+ expect((await send("POST", sign(forged, "F".repeat(43)), forged)).status).toBe(401);+ expect(tiers).toEqual(["starter", "pro"]);+ });+it("takes the Admin's signed word that the plan was cancelled, or renews again", async () => {const { sign, send, told } = routes();const cancelled = JSON.stringify({ v: 1, cancelled: true });diff --git a/server/routes/cloud-signed.ts b/server/routes/cloud-signed.tsindex fb9ca9969d..3c490f6942 100644--- a/server/routes/cloud-signed.ts+++ b/server/routes/cloud-signed.ts@@ -2,6 +2,7 @@// log their headers, bodies or codes. A bad pairing signature counts against the pairing lockout; a health or power read// opens nothing, so each route has its own nonces and never locks the Admin out of pairing. The power routes are the sleep// handshake of a plan that sleeps (server/cloud-power.ts); the Admin calls them for no other plan.+import { CLOUD_TIER } from "../host/cloud-plan-tier.ts";import type { IncomingMessage, ServerResponse } from "node:http";import type { BoxReport } from "../bot-box/box.ts";import { boxSummary } from "../cloud-health.ts";@@ -24,8 +25,8 @@ export const CLOUD_BOX_PATH = "/api/cloud/box";* theirs alone is deleted here (host/team-member-left.ts). */export const CLOUD_TEAM_MEMBER_LEFT_PATH = "/api/cloud/team/member-left";-/** The plan was cancelled, or renews again: `{"v":1,"cancelled":true|false}`, signed with the body like the sleep request.- * While it is cancelled the home's routines wait (host/routine-holds-host.ts). */+/** The Admin's word on the plan, signed with the body like the sleep request: `{"v":1,"cancelled":true|false}`, `{"v":1,"tier":"starter"}`,+ * or both. While it is cancelled the home's routines wait (host/routine-holds-host.ts); the tier is kept by host/cloud-plan-tier.ts. */export const CLOUD_PLAN_PATH = "/api/cloud/plan";export function createCloudSignedRoutes(deps: {@@ -46,6 +47,8 @@ export function createCloudSignedRoutes(deps: {policyChanged?: (() => void) | null;/** The plan was cancelled (true) or renews again (false); absent on a server that is not a Cloud home. */plan?: ((cancelled: boolean) => void) | null;+ /** Which plan this Cloud is on now; absent on a server that is not a Cloud home. */+ planTier?: ((tier: string) => void) | null;now?: () => number;}) {const pairing = createCloudPairing({ secret: deps.secret, sessions: deps.sessions, team: deps.team ?? null, now: deps.now });@@ -62,7 +65,7 @@ export function createCloudSignedRoutes(deps: {const power = path === CLOUD_POWER_PATH || path === CLOUD_POWER_SLEEP_PATH ? deps.power?.() ?? null : null;const teamAdmin = path === CLOUD_TEAM_ADMIN_PATH && deps.team ? deps.teamAdmin ?? null : null;const memberLeft = path === CLOUD_TEAM_MEMBER_LEFT_PATH && deps.team ? deps.memberLeft ?? null : null;- const plan = path === CLOUD_PLAN_PATH ? deps.plan ?? null : null;+ const plan = path === CLOUD_PLAN_PATH && (deps.plan || deps.planTier) ? true : null;const policyChanged = path === CLOUD_TEAM_POLICY_CHANGED_PATH && deps.team ? deps.policyChanged ?? null : null;if (path !== CLOUD_PAIRING_PATH && path !== CLOUD_HEALTH_PATH && path !== CLOUD_BOX_PATH && !power && !teamAdmin && !memberLeft && !plan && !policyChanged) return false;res.setHeader("cache-control", "no-store");@@ -128,9 +131,11 @@ export function createCloudSignedRoutes(deps: {if (!verdict.ok) { console.warn(`cloud plan request refused from ${source}: ${verdict.error}`); json(res, verdict.status, { error: verdict.error }); return true; }let parsed: unknown;try { parsed = JSON.parse(body.toString("utf8")); } catch { json(res, 400, { error: "invalid_body" }); return true; }- const cancelled = (parsed as { cancelled?: unknown } | null)?.cancelled;- if (typeof cancelled !== "boolean") { json(res, 400, { error: "invalid_plan" }); return true; }- plan(cancelled);+ const { cancelled, tier } = (parsed ?? {}) as { cancelled?: unknown; tier?: unknown };+ const saysCancelled = typeof cancelled === "boolean", saysTier = typeof tier === "string" && CLOUD_TIER.test(tier);+ if ((cancelled !== undefined && !saysCancelled) || (tier !== undefined && !saysTier) || (!saysCancelled && !saysTier)) { json(res, 400, { error: "invalid_plan" }); return true; }+ if (saysCancelled) deps.plan?.(cancelled);+ if (saysTier) deps.planTier?.(tier);json(res, 200, { ok: true });return true;}diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.tsindex 55638a430b..e0c66be61d 100755--- a/server/testing/fake-claude-cli.ts+++ b/server/testing/fake-claude-cli.ts@@ -959,6 +959,7 @@ const playTurn = (prompt: JsonValue, late = false) => {return;}+ if (process.env.FAKE_CLAUDE_USES_CLOUD_COMPUTER === "1") useCloudComputer();if (mode === "hang") {const release = process.env.FAKE_CLAUDE_RELEASE;const finishGate = process.env.FAKE_CLAUDE_FINISH_GATE;@@ -1020,7 +1021,6 @@ const playTurn = (prompt: JsonValue, late = false) => {});}- if (process.env.FAKE_CLAUDE_USES_CLOUD_COMPUTER === "1") useCloudComputer();if (process.env.FAKE_CLAUDE_CONNECT_APPS) connectApps(process.env.FAKE_CLAUDE_CONNECT_APPS.split(",").filter(Boolean));let replyParts = replyForPrompt(prompt) ?? nextScriptedReply();diff --git a/server/thread-capacity-api.test.ts b/server/thread-capacity-api.test.tsindex 4dbcf350fc..574e7efcf6 100644--- a/server/thread-capacity-api.test.ts+++ b/server/thread-capacity-api.test.ts@@ -106,6 +106,7 @@ describe("per-bot thread capacity through an isolated HTTP fixture", () => {expect((await api("PATCH", "/api/instances/claude", { cli: wrapper })).status).toBe(200);const instance = (await api("GET", "/api/instances")).body.instances.find((candidate: any) => candidate.instanceId === "claude");model = instance.models.options[0].id;+ await limit(3);}, 30_000);afterEach(async () => {@@ -118,7 +119,7 @@ describe("per-bot thread capacity through an isolated HTTP fixture", () => {for (const project of projectDirs.splice(0)) await removeTempDir(project);});- it("defaults to three, runs ten real turns after raising the limit, and safely queues and cancels overflow", async () => {+ it("keeps a saved limit, runs ten real turns after raising the limit, and safely queues and cancels overflow", async () => {expect((await api("GET", "/api/config")).body.threads).toEqual({ maxConcurrentPerBot: 3 });for (const maxConcurrentPerBot of [0, 17, 1.5, "2", null]) {expect((await api("PATCH", "/api/config", { threads: { maxConcurrentPerBot } })).status).toBe(400);diff --git a/shared/runtime-events.ts b/shared/runtime-events.tsindex 72c6533479..90cfbc5f12 100644--- a/shared/runtime-events.ts+++ b/shared/runtime-events.ts@@ -79,7 +79,7 @@ export type RuntimeEvent = RuntimeEventBase &}| {type: "turn.wait_started";- /** The computer resource this turn queued behind (e.g. "computer:box:bx_…"). */+ /** The computer or browser this turn queued behind (e.g. "computer:box:bx_…", "browser:bot-…"). */resource: string;/** Where this turn sat in the resource's arrival-ordered waitlist when* the wait began. */diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex a412785f8e..a5005074b2 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -766,6 +766,8 @@ export function Composer({/><QueuedComposerMessagesitems={queuedMessages}+ oneThreadPerBot={state.config?.cloudStarter === true}+ onSeePlans={() => dispatch({ type: "toggleAppSettings", open: true, section: "cloudAccount" })}onSteer={canSteerQueued ? steerQueued : undefined}steerInterrupts={!canSteer}steerMode={group ? "next" : "all"}diff --git a/src/components/ComposerQueuedMessages.test.ts b/src/components/ComposerQueuedMessages.test.tsindex 6e014ad494..7fec099cb3 100644--- a/src/components/ComposerQueuedMessages.test.ts+++ b/src/components/ComposerQueuedMessages.test.ts@@ -23,6 +23,18 @@ describe("composerCanSteerQueuedMessages", () => {});});+describe("the queued line", () => {+ const capacity = [{ queueId: "q1", text: "later", reason: "capacity" as const }];+ it("says a free slot elsewhere, and on Starter names the plan and the way to a bigger one", () => {+ const line = (props: object) => renderToStaticMarkup(createElement(QueuedComposerMessages, { items: capacity, onCancel: () => {}, ...props }));+ expect(line({})).toContain("Starts when this bot has a free thread slot.");+ const starter = line({ oneThreadPerBot: true, onSeePlans: () => {} });+ expect(starter).toContain("Starter runs one thread at a time per bot");+ expect(starter).toContain("A bigger plan runs more.");+ expect(starter).toContain("See plans");+ });+});+describe("double-Enter steer gesture", () => {it("opens the window only when a chip arrives on a busy steer-capable thread", () => {const now = 1_000_000;diff --git a/src/components/ComposerQueuedMessages.tsx b/src/components/ComposerQueuedMessages.tsxindex 3d456a78e4..7768c957c9 100644--- a/src/components/ComposerQueuedMessages.tsx+++ b/src/components/ComposerQueuedMessages.tsx@@ -50,8 +50,12 @@ export function QueuedComposerMessages({steerInterrupts = false,onCancel,onEdit,+ oneThreadPerBot = false,+ onSeePlans,}: {items: Array<{ queueId: string; text: string; reason?: SteerQueueReason }>;+ oneThreadPerBot?: boolean;+ onSeePlans?: () => void;onSteer?: () => void;steerMode?: "all" | "next";steering?: boolean;@@ -95,7 +99,10 @@ export function QueuedComposerMessages({<p className="px-3 pt-2 text-[12px] text-ink-secondary">{t("composer.queued.groupTurn")}</p>)}{items.some((item) => item.reason === "capacity") && (- <p className="px-3 pt-2 text-[12px] text-ink-secondary">{t("composer.queued.capacity")}</p>+ <p className="px-3 pt-2 text-[12px] text-ink-secondary">+ {t(oneThreadPerBot ? "composer.queued.capacityStarter" : "composer.queued.capacity")}+ {oneThreadPerBot && onSeePlans && <>{" "}<button type="button" className="underline" onClick={onSeePlans}>{t("composer.queued.seePlans")}</button></>}+ </p>)}<ul className="divide-y divide-hairline/25" aria-label={t("composer.queued.list")}>{items.map((item, index) => {diff --git a/src/components/ThreadConcurrencySettings.test.ts b/src/components/ThreadConcurrencySettings.test.tsindex 2f160cf043..981e5b9dbe 100644--- a/src/components/ThreadConcurrencySettings.test.ts+++ b/src/components/ThreadConcurrencySettings.test.ts@@ -3,14 +3,14 @@ import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it, vi } from "vitest";import { ThreadConcurrencySettings } from "./ThreadConcurrencySettings";-const fixture = vi.hoisted(() => ({ limit: undefined as number | undefined }));+const fixture = vi.hoisted(() => ({ limit: undefined as number | undefined, cloudStarter: undefined as true | undefined }));vi.mock("@/state/store", () => ({api: vi.fn(),- useStore: () => ({ state: { config: { threads: fixture.limit === undefined ? undefined : { maxConcurrentPerBot: fixture.limit } } }, dispatch: vi.fn() }),+ useStore: () => ({ state: { config: { threads: fixture.limit === undefined ? undefined : { maxConcurrentPerBot: fixture.limit }, cloudStarter: fixture.cloudStarter } }, dispatch: vi.fn() }),}));describe("ThreadConcurrencySettings", () => {- it("keeps three as the legacy default and offers one through ten", () => {+ it("shows three until the first answer arrives, and offers one through sixteen", () => {fixture.limit = undefined;const markup = renderToStaticMarkup(createElement(ThreadConcurrencySettings));expect(markup).toContain('value="3" selected=""');@@ -19,6 +19,14 @@ describe("ThreadConcurrencySettings", () => {expect(markup).toContain("Extra messages queue until a slot opens.");expect(markup).toContain("Maximum running threads per bot");});+ it("shows Starter's one thread per bot as a plan limit it cannot raise", () => {+ fixture.limit = 1; fixture.cloudStarter = true;+ const markup = renderToStaticMarkup(createElement(ThreadConcurrencySettings));+ fixture.cloudStarter = undefined;+ expect(markup).toContain('value="1" selected=""');+ expect(markup).toContain("disabled");+ expect(markup).toContain("Starter runs one thread at a time per bot");+ });it("shows the confirmed server value", () => {fixture.limit = 10;expect(renderToStaticMarkup(createElement(ThreadConcurrencySettings))).toContain('value="10" selected=""');diff --git a/src/components/ThreadConcurrencySettings.tsx b/src/components/ThreadConcurrencySettings.tsxindex 9bdff9bb84..2e7392cf6f 100644--- a/src/components/ThreadConcurrencySettings.tsx+++ b/src/components/ThreadConcurrencySettings.tsx@@ -7,6 +7,7 @@ import { Select } from "./Select";export function ThreadConcurrencySettings() {const { state, dispatch } = useStore();const confirmed = state.config?.threads?.maxConcurrentPerBot ?? 3;+ const oneThreadPerBot = state.config?.cloudStarter === true;const [pending, setPending] = useState<number | null>(null);const [error, setError] = useState("");const saving = useRef(false);@@ -31,12 +32,12 @@ export function ThreadConcurrencySettings() {return (<Card title={t("settings.threads.title")} subtitle={t("settings.threads.subtitle")}><label htmlFor="thread-concurrency" className="block text-[13px] font-medium text-ink">{t("settings.threads.label")}</label>- <Select className="mt-2" id="thread-concurrency" value={pending ?? confirmed} disabled={pending !== null}+ <Select className="mt-2" id="thread-concurrency" value={pending ?? confirmed} disabled={pending !== null || oneThreadPerBot}aria-describedby="thread-concurrency-help"onChange={(event) => void save(Number(event.target.value))}>{Array.from({ length: 16 }, (_, i) => i + 1).map((limit) => <option key={limit} value={limit}>{limit}</option>)}</Select>- <p id="thread-concurrency-help" className="mt-2 text-[12px] leading-relaxed text-ink-secondary">{t("settings.threads.helpHanded")}</p>+ <p id="thread-concurrency-help" className="mt-2 text-[12px] leading-relaxed text-ink-secondary">{oneThreadPerBot ? t("settings.threads.starter") : t("settings.threads.helpHanded")}</p>{pending !== null && <p role="status" className="mt-2 text-[12px] text-ink-secondary">{t("settings.threads.saving")}</p>}{error && <p role="alert" className="mt-2 text-[12px] text-danger">{error}</p>}</Card>diff --git a/src/lib/inspector.ts b/src/lib/inspector.tsindex ef67ef59d7..d20719cb07 100644--- a/src/lib/inspector.ts+++ b/src/lib/inspector.ts@@ -70,13 +70,13 @@ export function summarizeRuntime(e: RuntimeEvent): { summary: string; tone: Insp}case "turn.wait_started":return {- summary: `waiting for computer — ${e.holder ? `${e.holder.name}${e.holder.task ? ` (${e.holder.task})` : ""}` : "holder unknown"}`,+ summary: `waiting for ${e.resource.startsWith("browser:") ? "browser" : "computer"} — ${e.holder ? `${e.holder.name}${e.holder.task ? ` (${e.holder.task})` : ""}` : "holder unknown"}`,tone: "plain",};case "turn.wait_ended": {const seconds = Math.round(e.waitedMs / 1000);const waited = e.waitedMs < 1_000 ? "under a second" : `${seconds}s`;- if (e.outcome === "acquired") return { summary: `computer acquired after ${waited}`, tone: "boundary" };+ if (e.outcome === "acquired") return { summary: `${e.resource.startsWith("browser:") ? "browser" : "computer"} acquired after ${waited}`, tone: "boundary" };if (e.outcome === "parked") return { summary: `computer wait parked after ${waited}`, tone: "plain" };if (e.outcome === "gave_up") return { summary: `computer wait gave up after ${waited}`, tone: "error" };return { summary: `computer wait stopped after ${waited}`, tone: "plain" };diff --git a/src/locales/de.json b/src/locales/de.jsonindex b05947c7ad..0ab1e78f02 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -2785,5 +2785,12 @@"botAccess.overview.botCount.other": "{count} Bots","botAccess.overview.noBotsForPerson": "{name} hat noch keine Bots.","botAccess.overview.allPeople": "Alle Personen",- "botAccess.overview.toastRemoved": "{bot}: {name} entfernt"+ "botAccess.overview.toastRemoved": "{bot}: {name} entfernt",+ "server.browser.waiting": "Warte auf den Browser: {name} verwendet ihn gerade. Es geht von selbst weiter, sobald er frei ist.",+ "server.browser.waitingTask": "Warte auf den Browser: {name} verwendet ihn gerade für {task}. Es geht von selbst weiter, sobald er frei ist.",+ "server.browser.free": "Der Browser ist frei. Es geht weiter.",+ "server.browser.stoppedWaiting": "Warten auf den Browser beendet.",+ "composer.queued.capacityStarter": "In der Warteschlange. Starter führt pro Bot einen Thread gleichzeitig aus, das hier startet also, sobald der laufende fertig ist. Ein größerer Plan führt mehr aus.",+ "composer.queued.seePlans": "Pläne ansehen",+ "settings.threads.starter": "Starter führt pro Bot einen Thread gleichzeitig aus, ein größerer Plan führt mehr aus. Arbeit, die ein Bot selbst startet, läuft trotzdem, und jeder Bot hat seinen eigenen Thread."}diff --git a/src/locales/en.json b/src/locales/en.jsonindex b29bddd68b..a65d420857 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7399,5 +7399,12 @@"botAccess.overview.botCount.other": "{count} bots","botAccess.overview.noBotsForPerson": "{name} has no bots yet.","botAccess.overview.allPeople": "All people",- "botAccess.overview.toastRemoved": "{bot}: removed {name}"+ "botAccess.overview.toastRemoved": "{bot}: removed {name}",+ "server.browser.waiting": "Waiting for the browser: {name} is using it. This continues by itself when it is free.",+ "server.browser.waitingTask": "Waiting for the browser: {name} is using it for {task}. This continues by itself when it is free.",+ "server.browser.free": "The browser is free. Continuing.",+ "server.browser.stoppedWaiting": "Stopped waiting for the browser.",+ "composer.queued.capacityStarter": "Queued. Starter runs one thread at a time per bot, so this starts when the one running finishes. A bigger plan runs more.",+ "composer.queued.seePlans": "See plans",+ "settings.threads.starter": "Starter runs one thread at a time per bot, and a bigger plan runs more. Work a bot starts for itself still runs, and each bot has its own one."}diff --git a/src/locales/es.json b/src/locales/es.jsonindex c696459690..c174e9494c 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -5663,5 +5663,12 @@"botAccess.overview.botCount.other": "{count} bots","botAccess.overview.noBotsForPerson": "{name} aún no tiene bots.","botAccess.overview.allPeople": "Todas las personas",- "botAccess.overview.toastRemoved": "{bot}: se quitó a {name}"+ "botAccess.overview.toastRemoved": "{bot}: se quitó a {name}",+ "server.browser.waiting": "Esperando el navegador: {name} lo está usando. Esto continuará solo cuando esté libre.",+ "server.browser.waitingTask": "Esperando el navegador: {name} lo está usando para {task}. Esto continuará solo cuando esté libre.",+ "server.browser.free": "El navegador está libre. Continuando.",+ "server.browser.stoppedWaiting": "Se dejó de esperar el navegador.",+ "composer.queued.capacityStarter": "En cola. Starter ejecuta un hilo a la vez por bot, así que este empieza cuando termine el que está en marcha. Un plan mayor ejecuta más.",+ "composer.queued.seePlans": "Ver planes",+ "settings.threads.starter": "Starter ejecuta un hilo a la vez por bot, y un plan mayor ejecuta más. El trabajo que un bot inicia por su cuenta se ejecuta igualmente, y cada bot tiene el suyo."}diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 94f9fe141d..e4f44b2dc5 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -2720,5 +2720,12 @@"botAccess.overview.botCount.other": "{count} bots","botAccess.overview.noBotsForPerson": "{name} n'a pas encore de bots.","botAccess.overview.allPeople": "Toutes les personnes",- "botAccess.overview.toastRemoved": "{bot} : {name} retiré"+ "botAccess.overview.toastRemoved": "{bot} : {name} retiré",+ "server.browser.waiting": "En attente du navigateur : {name} l'utilise. Cela reprendra tout seul dès qu'il sera libre.",+ "server.browser.waitingTask": "En attente du navigateur : {name} l'utilise pour {task}. Cela reprendra tout seul dès qu'il sera libre.",+ "server.browser.free": "Le navigateur est libre. On continue.",+ "server.browser.stoppedWaiting": "Attente du navigateur arrêtée.",+ "composer.queued.capacityStarter": "En file d'attente. Starter exécute un fil à la fois par bot : celui-ci démarrera quand le fil en cours sera terminé. Un plan supérieur en exécute davantage.",+ "composer.queued.seePlans": "Voir les plans",+ "settings.threads.starter": "Starter exécute un fil à la fois par bot, un plan supérieur en exécute davantage. Le travail qu'un bot lance lui-même s'exécute quand même, et chaque bot a le sien."}diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 748c1c06bb..608e35095c 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -2720,5 +2720,12 @@"botAccess.overview.botCount.other": "{count} बॉट","botAccess.overview.noBotsForPerson": "{name} के पास अभी कोई बॉट नहीं है।","botAccess.overview.allPeople": "सभी लोग",- "botAccess.overview.toastRemoved": "{bot}: {name} को हटाया"+ "botAccess.overview.toastRemoved": "{bot}: {name} को हटाया",+ "server.browser.waiting": "ब्राउज़र का इंतज़ार है: {name} इसका उपयोग कर रहा है। खाली होते ही यह अपने आप आगे बढ़ेगा।",+ "server.browser.waitingTask": "ब्राउज़र का इंतज़ार है: {name} इसे {task} के लिए उपयोग कर रहा है। खाली होते ही यह अपने आप आगे बढ़ेगा।",+ "server.browser.free": "ब्राउज़र खाली है। आगे बढ़ रहे हैं।",+ "server.browser.stoppedWaiting": "ब्राउज़र का इंतज़ार बंद किया।",+ "composer.queued.capacityStarter": "कतार में है। Starter हर बॉट के लिए एक समय में एक थ्रेड चलाता है, इसलिए यह चल रहे थ्रेड के खत्म होने पर शुरू होगा। बड़ा प्लान ज़्यादा चलाता है।",+ "composer.queued.seePlans": "प्लान देखें",+ "settings.threads.starter": "Starter हर बॉट के लिए एक समय में एक थ्रेड चलाता है, और बड़ा प्लान ज़्यादा चलाता है। बॉट का खुद शुरू किया काम फिर भी चलता है, और हर बॉट का अपना एक थ्रेड होता है।"}diff --git a/src/locales/it.json b/src/locales/it.jsonindex d4d260159f..2bc127fb39 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -6359,5 +6359,12 @@"botAccess.overview.botCount.other": "{count} bot","botAccess.overview.noBotsForPerson": "{name} non ha ancora bot.","botAccess.overview.allPeople": "Tutte le persone",- "botAccess.overview.toastRemoved": "{bot}: rimosso {name}"+ "botAccess.overview.toastRemoved": "{bot}: rimosso {name}",+ "server.browser.waiting": "In attesa del browser: {name} lo sta usando. Si riprende da solo appena è libero.",+ "server.browser.waitingTask": "In attesa del browser: {name} lo sta usando per {task}. Si riprende da solo appena è libero.",+ "server.browser.free": "Il browser è libero. Si continua.",+ "server.browser.stoppedWaiting": "Attesa del browser interrotta.",+ "composer.queued.capacityStarter": "In coda. Starter esegue un thread alla volta per bot, quindi questo parte quando finisce quello in corso. Un piano più grande ne esegue di più.",+ "composer.queued.seePlans": "Vedi i piani",+ "settings.threads.starter": "Starter esegue un thread alla volta per bot, un piano più grande ne esegue di più. Il lavoro che un bot avvia da solo viene comunque eseguito, e ogni bot ha il suo."}diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 9b0b499187..3e4b27ab77 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -6584,5 +6584,12 @@"botAccess.overview.botCount.other": "{count} 個のボット","botAccess.overview.noBotsForPerson": "{name} にはまだボットがありません。","botAccess.overview.allPeople": "すべてのメンバー",- "botAccess.overview.toastRemoved": "{bot}: {name} を削除しました"+ "botAccess.overview.toastRemoved": "{bot}: {name} を削除しました",+ "server.browser.waiting": "ブラウザの空きを待っています:{name} が使用中です。空きしだい自動で続行します。",+ "server.browser.waitingTask": "ブラウザの空きを待っています:{name} が「{task}」で使用中です。空きしだい自動で続行します。",+ "server.browser.free": "ブラウザが空きました。続行します。",+ "server.browser.stoppedWaiting": "ブラウザの待機を終了しました。",+ "composer.queued.capacityStarter": "順番待ちです。Starter はボットごとに一度に 1 つのスレッドを実行するので、実行中のものが終わると始まります。より大きなプランではもっと実行できます。",+ "composer.queued.seePlans": "プランを見る",+ "settings.threads.starter": "Starter はボットごとに一度に 1 つのスレッドを実行し、より大きなプランではもっと実行できます。ボットが自分で始めた作業はそのまま実行され、ボットごとに 1 つずつ使えます。"}diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex af5e82cd20..5711cfb256 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7085,5 +7085,12 @@"botAccess.overview.botCount.other": "봇 {count}개","botAccess.overview.noBotsForPerson": "{name} 님에게는 아직 봇이 없어요.","botAccess.overview.allPeople": "모든 사람",- "botAccess.overview.toastRemoved": "{bot}: {name} 님을 삭제했어요"+ "botAccess.overview.toastRemoved": "{bot}: {name} 님을 삭제했어요",+ "server.browser.waiting": "브라우저를 기다리는 중: {name}이(가) 사용 중입니다. 비는 대로 자동으로 계속합니다.",+ "server.browser.waitingTask": "브라우저를 기다리는 중: {name}이(가) {task}에 사용 중입니다. 비는 대로 자동으로 계속합니다.",+ "server.browser.free": "브라우저가 비었습니다. 계속합니다.",+ "server.browser.stoppedWaiting": "브라우저 대기를 멈췄습니다.",+ "composer.queued.capacityStarter": "대기 중입니다. Starter는 봇당 한 번에 스레드 하나를 실행하므로, 실행 중인 스레드가 끝나면 시작됩니다. 더 큰 요금제는 더 많이 실행합니다.",+ "composer.queued.seePlans": "요금제 보기",+ "settings.threads.starter": "Starter는 봇당 한 번에 스레드 하나를 실행하고, 더 큰 요금제는 더 많이 실행합니다. 봇이 스스로 시작한 작업은 그대로 실행되며, 봇마다 하나씩 쓸 수 있습니다."}diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex ecbce41a31..7eeb4f4133 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -6500,5 +6500,12 @@"botAccess.overview.botCount.other": "Boty: {count}","botAccess.overview.noBotsForPerson": "{name}: jeszcze bez botów.","botAccess.overview.allPeople": "Wszystkie osoby",- "botAccess.overview.toastRemoved": "{bot}: usunięto {name}"+ "botAccess.overview.toastRemoved": "{bot}: usunięto {name}",+ "server.browser.waiting": "Czekam na przeglądarkę: {name} jej używa. Praca wznowi się sama, gdy będzie wolna.",+ "server.browser.waitingTask": "Czekam na przeglądarkę: {name} używa jej do: {task}. Praca wznowi się sama, gdy będzie wolna.",+ "server.browser.free": "Przeglądarka jest wolna. Kontynuuję.",+ "server.browser.stoppedWaiting": "Przestano czekać na przeglądarkę.",+ "composer.queued.capacityStarter": "W kolejce. Starter uruchamia jeden wątek naraz na bota, więc ten ruszy, gdy skończy się bieżący. Większy plan uruchamia więcej.",+ "composer.queued.seePlans": "Zobacz plany",+ "settings.threads.starter": "Starter uruchamia jeden wątek naraz na bota, a większy plan więcej. Praca, którą bot zaczyna sam, i tak się wykonuje, a każdy bot ma swój wątek."}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 47a00cc99a..e9285af416 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6342,5 +6342,12 @@"botAccess.overview.botCount.other": "{count} bots","botAccess.overview.noBotsForPerson": "{name} ainda não tem bots.","botAccess.overview.allPeople": "Todas as pessoas",- "botAccess.overview.toastRemoved": "{bot}: {name} removido"+ "botAccess.overview.toastRemoved": "{bot}: {name} removido",+ "server.browser.waiting": "Aguardando o navegador: {name} está usando. Isto continua sozinho quando ele estiver livre.",+ "server.browser.waitingTask": "Aguardando o navegador: {name} está usando para {task}. Isto continua sozinho quando ele estiver livre.",+ "server.browser.free": "O navegador está livre. Continuando.",+ "server.browser.stoppedWaiting": "Parou de aguardar o navegador.",+ "composer.queued.capacityStarter": "Na fila. O Starter executa uma conversa por vez em cada bot, então esta começa quando a atual terminar. Um plano maior executa mais.",+ "composer.queued.seePlans": "Ver planos",+ "settings.threads.starter": "O Starter executa uma conversa por vez em cada bot, e um plano maior executa mais. O trabalho que um bot inicia por conta própria ainda é executado, e cada bot tem a sua."}diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex 2afe7b4987..55bcf6a4f6 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -6562,5 +6562,12 @@"botAccess.overview.botCount.other": "Ботов: {count}","botAccess.overview.noBotsForPerson": "{name}: ботов пока нет.","botAccess.overview.allPeople": "Все люди",- "botAccess.overview.toastRemoved": "{bot}: {name} удалён(а)"+ "botAccess.overview.toastRemoved": "{bot}: {name} удалён(а)",+ "server.browser.waiting": "Ожидание браузера: его использует {name}. Работа продолжится сама, когда он освободится.",+ "server.browser.waitingTask": "Ожидание браузера: {name} использует его для задачи «{task}». Работа продолжится сама, когда он освободится.",+ "server.browser.free": "Браузер свободен. Продолжаем.",+ "server.browser.stoppedWaiting": "Ожидание браузера прекращено.",+ "composer.queued.capacityStarter": "В очереди. Starter запускает по одному потоку за раз на бота, поэтому этот начнётся, когда завершится текущий. Более крупный план запускает больше.",+ "composer.queued.seePlans": "Посмотреть планы",+ "settings.threads.starter": "Starter запускает по одному потоку за раз на бота, а более крупный план запускает больше. Работа, которую бот начинает сам, всё равно выполняется, и у каждого бота свой поток."}diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex a42d010cb6..5a277b2afc 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5154,5 +5154,12 @@"botAccess.overview.botCount.other": "{count} bot","botAccess.overview.noBotsForPerson": "{name} için henüz bot yok.","botAccess.overview.allPeople": "Tüm kişiler",- "botAccess.overview.toastRemoved": "{bot}: {name} kaldırıldı"+ "botAccess.overview.toastRemoved": "{bot}: {name} kaldırıldı",+ "server.browser.waiting": "Tarayıcı bekleniyor: {name} kullanıyor. Boşalınca kendiliğinden devam eder.",+ "server.browser.waitingTask": "Tarayıcı bekleniyor: {name}, {task} için kullanıyor. Boşalınca kendiliğinden devam eder.",+ "server.browser.free": "Tarayıcı boşta. Devam ediliyor.",+ "server.browser.stoppedWaiting": "Tarayıcı beklemesi durduruldu.",+ "composer.queued.capacityStarter": "Sırada. Starter, bot başına aynı anda bir konu çalıştırır; bu, çalışan bitince başlar. Daha büyük bir plan daha fazlasını çalıştırır.",+ "composer.queued.seePlans": "Planları gör",+ "settings.threads.starter": "Starter, bot başına aynı anda bir konu çalıştırır, daha büyük bir plan daha fazlasını çalıştırır. Botun kendi başlattığı iş yine çalışır ve her botun kendi konusu vardır."}diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 2f03ece597..995dec4537 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -3161,5 +3161,12 @@"botAccess.overview.botCount.other": "Ботів: {count}","botAccess.overview.noBotsForPerson": "{name}: ботів ще немає.","botAccess.overview.allPeople": "Усі люди",- "botAccess.overview.toastRemoved": "{bot}: {name} вилучено"+ "botAccess.overview.toastRemoved": "{bot}: {name} вилучено",+ "server.browser.waiting": "Очікування браузера: його використовує {name}. Робота продовжиться сама, щойно він звільниться.",+ "server.browser.waitingTask": "Очікування браузера: {name} використовує його для завдання «{task}». Робота продовжиться сама, щойно він звільниться.",+ "server.browser.free": "Браузер вільний. Продовжуємо.",+ "server.browser.stoppedWaiting": "Очікування браузера припинено.",+ "composer.queued.capacityStarter": "У черзі. Starter запускає по одному потоку за раз на бота, тож цей почнеться, коли завершиться поточний. Більший план запускає більше.",+ "composer.queued.seePlans": "Переглянути плани",+ "settings.threads.starter": "Starter запускає по одному потоку за раз на бота, а більший план запускає більше. Робота, яку бот починає сам, усе одно виконується, і кожен бот має свій потік."}diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 6b40d89e9e..14b74b4304 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5154,5 +5154,12 @@"botAccess.overview.botCount.other": "{count} bot","botAccess.overview.noBotsForPerson": "{name} chưa có bot nào.","botAccess.overview.allPeople": "Tất cả mọi người",- "botAccess.overview.toastRemoved": "{bot}: đã gỡ {name}"+ "botAccess.overview.toastRemoved": "{bot}: đã gỡ {name}",+ "server.browser.waiting": "Đang chờ trình duyệt: {name} đang dùng. Sẽ tự tiếp tục khi trình duyệt rảnh.",+ "server.browser.waitingTask": "Đang chờ trình duyệt: {name} đang dùng cho {task}. Sẽ tự tiếp tục khi trình duyệt rảnh.",+ "server.browser.free": "Trình duyệt đã rảnh. Đang tiếp tục.",+ "server.browser.stoppedWaiting": "Đã dừng chờ trình duyệt.",+ "composer.queued.capacityStarter": "Đang xếp hàng. Starter chạy mỗi bot một luồng một lúc, nên luồng này bắt đầu khi luồng đang chạy xong. Gói lớn hơn chạy được nhiều hơn.",+ "composer.queued.seePlans": "Xem các gói",+ "settings.threads.starter": "Starter chạy mỗi bot một luồng một lúc, gói lớn hơn chạy được nhiều hơn. Việc do bot tự bắt đầu vẫn chạy, và mỗi bot có luồng riêng."}diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 203a8c8d45..5a4acc1d17 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -4546,5 +4546,12 @@"botAccess.overview.botCount.other": "{count} 個機器人","botAccess.overview.noBotsForPerson": "{name} 還沒有機器人。","botAccess.overview.allPeople": "所有人員",- "botAccess.overview.toastRemoved": "{bot}:已移除 {name}"+ "botAccess.overview.toastRemoved": "{bot}:已移除 {name}",+ "server.browser.waiting": "正在等待瀏覽器:{name} 正在使用。空閒後會自動繼續。",+ "server.browser.waitingTask": "正在等待瀏覽器:{name} 正在用它處理「{task}」。空閒後會自動繼續。",+ "server.browser.free": "瀏覽器已空閒,繼續進行。",+ "server.browser.stoppedWaiting": "已停止等待瀏覽器。",+ "composer.queued.capacityStarter": "排隊中。Starter 每個機器人一次執行一個對話,所以這則會在目前對話結束後開始。更大的方案可以執行更多。",+ "composer.queued.seePlans": "查看方案",+ "settings.threads.starter": "Starter 每個機器人一次執行一個對話,更大的方案可以執行更多。機器人自己發起的工作仍會執行,每個機器人各有一個。"}diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex f8d4b6cca3..21f5046659 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7284,5 +7284,12 @@"botAccess.overview.botCount.other": "{count} 个机器人","botAccess.overview.noBotsForPerson": "{name} 还没有机器人。","botAccess.overview.allPeople": "所有人员",- "botAccess.overview.toastRemoved": "{bot}:已移除 {name}"+ "botAccess.overview.toastRemoved": "{bot}:已移除 {name}",+ "server.browser.waiting": "正在等待浏览器:{name} 正在使用。空闲后会自动继续。",+ "server.browser.waitingTask": "正在等待浏览器:{name} 正在用它处理「{task}」。空闲后会自动继续。",+ "server.browser.free": "浏览器已空闲,继续进行。",+ "server.browser.stoppedWaiting": "已停止等待浏览器。",+ "composer.queued.capacityStarter": "排队中。Starter 每个机器人一次运行一个对话,所以这条会在当前对话结束后开始。更大的方案可以运行更多。",+ "composer.queued.seePlans": "查看方案",+ "settings.threads.starter": "Starter 每个机器人一次运行一个对话,更大的方案可以运行更多。机器人自己发起的工作仍会运行,每个机器人各有一个。"}diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex ffa6b4c84b..b3d56628b0 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -53,6 +53,8 @@ export interface ConfigStatus {mcp?: { callTimeoutMinutes: number };/** Workspace defaults for new bots; absent effort = no level is sent. */newBots?: { effort?: EffortLevel };+ /** This Cloud is on the Starter plan, as the Admin last said; absent or false otherwise. */+ cloudStarter?: boolean;threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number };automaticRecovery?: { enabled: boolean; backup?: ModelSelection };/** Prompt-cache keep-warm for idle Claude threads. Absent from older servers. */