Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Computer tools on Windows: shorter waits and plainer words

milind-soniefb96dcdc1f2
diff --git a/server/chat-notices.ts b/server/chat-notices.ts
index 9a70f5b7b7..8f30f35bcf 100644
--- a/server/chat-notices.ts
+++ b/server/chat-notices.ts
@@ -25,6 +25,9 @@ export const CHAT_NOTICE = {
"chat.notice.part.weeklyOpusLimit": "weekly Opus limit",
"chat.notice.part.weeklySonnetLimit": "weekly Sonnet limit",
"chat.notice.part.usageLimit": "usage limit",
+ "chat.notice.part.computerToolsTookTooLong": "they took too long to start",
+ "chat.notice.part.computerToolsHelperStopped": "their helper stopped",
+ "chat.notice.part.computerToolsHelperFailed": "their helper did not answer properly",
"chat.notice.part.chooseModel": "choose another model for this bot",
"chat.notice.part.switchAccount": "switch this bot to another AI or Claude account",
"chat.notice.webhookHome":
@@ -137,7 +140,8 @@ export const CHAT_NOTICE = {
"chat.notice.computerDesktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.",
"chat.notice.computerPermissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it",
"chat.notice.computerNotReadyDetail": "OpenMausBot can't use this computer yet — {reason}",
- "chat.notice.computerToolsDidNotStart": "The tools for this computer did not start this time ({reason}). It is still linked to this bot; send your message again in a moment.",
+ "chat.notice.computerToolsDidNotStart": "The tools for this computer did not start this time ({why}). Send your message again in a moment.",
+ "chat.notice.computerToolsStillNotStarting": "The tools for this computer are still not starting.",
"chat.notice.computerNotReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.",
"chat.notice.computerSystemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work",
"chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",
diff --git a/server/drivers/chat-host-computer.test.ts b/server/drivers/chat-host-computer.test.ts
index 8e1e6d1dfc..0872d85068 100644
--- a/server/drivers/chat-host-computer.test.ts
+++ b/server/drivers/chat-host-computer.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
-import { chatToolNoticeLines, mountChatTools, type ChatToolSession } from "./chat-mcp-tools.ts";
+import { mountChatTools, type ChatToolSession } from "./chat-mcp-tools.ts";
import { HOST_COMPUTER_READY, HOST_COMPUTER_STAND_IN, hostComputerKey, hostComputerStartupMs } from "./chat-host-computer.ts";
const FAKE = `
@@ -21,6 +21,7 @@ const FAKE = `
const message = JSON.parse(buffer.slice(0, newline));
buffer = buffer.slice(newline + 1);
if (MODE === "silent") continue;
+ if (MODE === "exit") process.exit(3);
if (message.method === "initialize") setTimeout(() => {
writeFileSync(ANSWERED, "1");
reply(message, { protocolVersion: "2024-11-05", capabilities: { tools: {} } });
@@ -62,8 +63,11 @@ function computer(driver: string, env: Record<string, string> = {}) {
};
}
-async function mount(server: ReturnType<typeof computer>["server"], startup: { ms: number; hostComputerMs: number }) {
- const session = await mountChatTools({ localComputer: server }, controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined, startup);
+type Line = { message: string; text: { key: string; params?: Record<string, string | number> } };
+
+async function mount(server: ReturnType<typeof computer>["server"], startupMs: number, hostComputerMs: number, conversation?: string, lines: Line[] = []) {
+ const session = await mountChatTools({ localComputer: server }, controller.signal, true, undefined, undefined, undefined, undefined, undefined, undefined,
+ { startupMs, hostComputerMs, ...(conversation ? { conversation } : {}), notice: (line) => lines.push(line as Line) });
sessions.push(session);
return session;
}
@@ -81,58 +85,71 @@ describe("this desktop's own computer in a chat turn", () => {
expect(hostComputerKey(one)).not.toBe(hostComputerKey({ ...one, env: { ...one.env, OMB_CUA_ARGS: '["mcp","--embedded"]' } }));
});
- it("is not skipped when it starts slower than the turn's budget, and the next turn lists it at once and waits at its first call", async () => {
+ it("is not skipped when slow, and the next turn lists its last tools after a short wait and its first call waits for the start", async () => {
const driver = `slow-${randomUUID()}`;
- const first = computer(driver, { DELAY_MS: "1500" });
- const cold = await mount(first.server, { ms: 150, hostComputerMs: 20_000 });
+ const cold = await mount(computer(driver, { DELAY_MS: "1500" }).server, 10_000, 20_000);
expect(cold.skipped).toEqual([]);
expect(names(cold)).toEqual(["computer_write"]);
- const second = computer(driver, { DELAY_MS: "1500" });
- const warm = await mount(second.server, { ms: 150, hostComputerMs: 20_000 });
+ const second = computer(driver, { DELAY_MS: "6000" });
+ const warm = await mount(second.server, 10_000, 20_000);
expect(existsSync(second.answered)).toBe(false);
expect(warm.skipped).toEqual([]);
expect(names(warm)).toEqual(["computer_write"]);
await expect(warm.execute("computer_write", { value: "x" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:x" });
expect(existsSync(second.answered)).toBe(true);
- });
-
- it("says through a tool, never by leaving it out, that it did not start, and tells the person", async () => {
- const session = await mount(computer(`dead-${randomUUID()}`, { MODE: "silent" }).server, { ms: 150, hostComputerMs: 400 });
- expect(session.skipped).toEqual([]);
- expect(names(session)).toEqual([HOST_COMPUTER_STAND_IN]);
- expect(session.definitions[0]!.function.description).toContain("did not start this time (MCP startup timed out)");
- expect(session.view(HOST_COMPUTER_STAND_IN, {})).toMatchObject({ ask: false });
- const result = await session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal);
- expect(result.ok).toBe(false);
- expect(result.text).toContain("nothing needs linking or connecting");
- expect(chatToolNoticeLines(session)).toEqual([expect.objectContaining({ text: { key: "chat.notice.computerToolsDidNotStart", params: { reason: "MCP startup timed out" } } })]);
- });
+ }, 30_000);
- it("after a failed start, waits for the next one through the stand-in and then lists the real tools beside the runtime's own", async () => {
- const driver = `flaky-${randomUUID()}`;
- await mount(computer(driver, { MODE: "silent" }).server, { ms: 150, hostComputerMs: 400 });
- const starting = computer(driver, { DELAY_MS: "1200" });
- const session = await mount(starting.server, { ms: 150, hostComputerMs: 20_000 });
+ it("on a first start slower than the turn's wait, goes on with a stand-in that waits for it and then lists the real tools beside the runtime's own", async () => {
+ const starting = computer(`first-${randomUUID()}`, { DELAY_MS: "1200" });
+ const lines: Line[] = [];
+ const session = await mount(starting.server, 150, 20_000, "c-first", lines);
expect(existsSync(starting.answered)).toBe(false);
expect(names(session)).toEqual([HOST_COMPUTER_STAND_IN]);
- expect(session.definitions[0]!.function.description).toContain("still starting");
- expect(session.hostComputerFailure).toBeUndefined();
- const runtime = { type: "function" as const, function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } };
- session.definitions.push(runtime);
+ const described = session.definitions[0]!.function.description;
+ expect(described).toContain("still starting");
+ expect(described).toContain("If the person's request needs this computer");
+ expect(described).not.toContain("already linked");
+ expect(session.view(HOST_COMPUTER_STAND_IN, {})).toMatchObject({ ask: false });
+ session.definitions.push({ type: "function", function: { name: "ask_user", description: "Ask", parameters: { type: "object" } } });
await expect(session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal)).resolves.toEqual({ ok: true, text: HOST_COMPUTER_READY });
expect(names(session)).toEqual(["computer_write", "ask_user"]);
await expect(session.execute("computer_write", { value: "y" }, controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:y" });
+ expect(lines).toEqual([]);
+ });
+
+ it("says through a tool, never by leaving it out, that it did not start, and tells the person once per conversation", async () => {
+ const lines: Line[] = [];
+ const driver = `dead-${randomUUID()}`;
+ const session = await mount(computer(driver, { MODE: "exit" }).server, 2_000, 4_000, "c-dead", lines);
+ expect(session.skipped).toEqual([]);
+ expect(names(session)).toEqual([HOST_COMPUTER_STAND_IN]);
+ const described = session.definitions[0]!.function.description;
+ expect(described).toContain("unavailable this time (MCP server exited before the session closed");
+ expect(described).toContain("Only mention it if the person's request needs this computer");
+ expect(described).toContain("never ask the person to link or connect this computer");
+ const result = await session.execute(HOST_COMPUTER_STAND_IN, {}, controller.signal);
+ expect(result.ok).toBe(false);
+ expect(result.text).toContain("not a missing link");
+ expect(lines).toEqual([{ message: expect.stringContaining("(their helper stopped). Send your message again in a moment."),
+ text: { key: "chat.notice.computerToolsDidNotStart", params: { why: "chat.notice.part.computerToolsHelperStopped" } } }]);
+
+ await mount(computer(driver, { MODE: "exit" }).server, 2_000, 4_000, "c-dead", lines);
+ expect(lines[1]).toEqual({ message: "The tools for this computer are still not starting.", text: { key: "chat.notice.computerToolsStillNotStarting" } });
+ await mount(computer(driver, { MODE: "exit" }).server, 2_000, 4_000, "c-other", lines);
+ expect(lines[2]!.text.key).toBe("chat.notice.computerToolsDidNotStart");
});
- it("answers a call on the last start's tools with why this start failed, and the turn goes on", async () => {
+ it("answers a call on the last start's tools with why this start failed, tells the person, and the turn goes on", async () => {
const driver = `lost-${randomUUID()}`;
- await mount(computer(driver).server, { ms: 5_000, hostComputerMs: 20_000 });
- const session = await mount(computer(driver, { MODE: "silent" }).server, { ms: 150, hostComputerMs: 600 });
+ await mount(computer(driver).server, 10_000, 20_000);
+ const lines: Line[] = [];
+ const session = await mount(computer(driver, { MODE: "silent" }).server, 150, 600, "c-lost", lines);
expect(names(session)).toEqual(["computer_write"]);
const result = await session.execute("computer_write", { value: "z" }, controller.signal);
expect(result).toMatchObject({ ok: false, text: expect.stringContaining("did not start this time (MCP startup timed out)") });
expect(() => session.validate("computer_write", { value: "z" })).not.toThrow();
+ await vi.waitFor(() => expect(lines).toEqual([expect.objectContaining({ text: { key: "chat.notice.computerToolsDidNotStart", params: { why: "chat.notice.part.computerToolsTookTooLong" } } })]));
});
});
diff --git a/server/drivers/chat-host-computer.ts b/server/drivers/chat-host-computer.ts
index 90bf074ef6..2087cece1f 100644
--- a/server/drivers/chat-host-computer.ts
+++ b/server/drivers/chat-host-computer.ts
@@ -1,13 +1,16 @@
// This desktop's own computer for the Chat Completions runtime: its tools are listed even when its helper is slow to
// start, and a turn whose helper did not start says so through a tool instead of having no computer tools.
-import { noticeFailure } from "../chat-notices.ts";
+import { noticeFailure, type ChatNoticeKey } from "../chat-notices.ts";
+import type { ServerText } from "../../shared/server-text.ts";
const HOST_COMPUTER_STARTUP_MS = 20_000;
/** Windows: each turn starts the gate proxy as Electron and cua-driver.exe behind it, beside every other built-in;
* a cold start there (Defender scanning both executables on a busy disk) runs well past the general budget. */
const WINDOWS_HOST_COMPUTER_STARTUP_MS = 45_000;
+/** How long a turn waits before going on with an earlier list, or with the stand-in after a failed start. */
+export const HOST_COMPUTER_QUICK_MS = 1_500;
-/** How long this computer's helper gets to start; past the turn's own budget it starts in the background. */
+/** How long this computer's helper gets to start; past the turn's own wait it starts in the background. */
export function hostComputerStartupMs(platform: NodeJS.Platform = process.platform): number {
return platform === "win32" ? WINDOWS_HOST_COMPUTER_STARTUP_MS : HOST_COMPUTER_STARTUP_MS;
}
@@ -38,10 +41,10 @@ function reasonOf(error: unknown): string {
return error instanceof Error && error.message ? error.message : "its helper did not start";
}
-/** Waits for the listing up to `turnMs` once this driver has listed or failed before; on its first start, for the
- * whole listing, which `list` bounds by hostComputerStartupMs. */
+/** The turn waits `quickMs` once this driver has listed or failed before, `firstMs` on its first start; `list` bounds
+ * the start itself by hostComputerStartupMs, and past the wait it goes on in the background. */
export async function startHostComputer(key: string, list: (include: (tool: unknown) => boolean) => Promise<unknown[]>,
- include: (tool: unknown) => boolean, turnMs: number, signal: AbortSignal): Promise<HostComputerStart> {
+ include: (tool: unknown) => boolean, wait: { quickMs: number; firstMs: number }, signal: AbortSignal): Promise<HostComputerStart> {
const seen: unknown[] = [];
const listing = list((tool) => { seen.push(tool); return include(tool); }).then((tools) => {
lastListed.set(key, seen);
@@ -54,7 +57,7 @@ export async function startHostComputer(key: string, list: (include: (tool: unkn
listing.catch(() => {});
const cached = lastListed.get(key);
let timer: ReturnType<typeof setTimeout> | undefined;
- const late = cached || lastFailed.has(key) ? new Promise<undefined>((resolve) => { timer = setTimeout(resolve, turnMs, undefined); }) : new Promise<undefined>(() => {});
+ const late = new Promise<undefined>((resolve) => { timer = setTimeout(resolve, cached || lastFailed.has(key) ? wait.quickMs : wait.firstMs, undefined); });
const outcome = await Promise.race([listing.then((tools) => ({ tools }), (error: unknown) => ({ error })), late]);
clearTimeout(timer);
if (outcome && "tools" in outcome) return { state: "listed", tools: outcome.tools };
@@ -74,22 +77,52 @@ export function hostComputerFailure(ready: Promise<unknown>, signal: AbortSignal
});
}
-const NEVER_LINK = "This computer is already linked to you; nothing needs linking or connecting, so never ask the person to link it.";
+/** Whether or not this bot was given this computer, a slow helper is never a missing link. */
+const NOT_A_LINK = "This is a start-up problem of the computer's tools, not a missing link: never ask the person to link or connect this computer.";
export function hostComputerDidNotStart(reason: string): string {
- return `The tools for this computer did not start this time (${reason}). ${NEVER_LINK} Tell the person they did not start and to send the message again in a moment.`;
+ return `The tools for this computer did not start this time (${reason}). ${NOT_A_LINK} Tell the person they did not start and to try again in a moment.`;
}
export const HOST_COMPUTER_READY = "The tools for this computer are ready and listed for your next step.";
export function hostComputerStandIn(reason?: string) {
const description = reason === undefined
- ? `The tools for this computer (the person's own computer) are still starting. Call this before any step on this computer: it waits for them, then lists them for your next step. ${NEVER_LINK}`
- : `${hostComputerDidNotStart(reason)} Call this for the same answer.`;
+ ? `The tools for this computer are still starting. If the person's request needs this computer, call this first: it waits for them, then lists them for your next step. ${NOT_A_LINK}`
+ : `The tools for this computer are unavailable this time (${reason}). Only mention it if the person's request needs this computer; then tell them its tools did not start and to try again in a moment. ${NOT_A_LINK}`;
return { type: "function" as const, function: { name: HOST_COMPUTER_STAND_IN, description, parameters: { type: "object", properties: {}, additionalProperties: false } } };
}
-/** For the person: their computer's tools did not start at the start of this turn. */
-export function hostComputerNotice(reason: string | undefined) {
- return reason === undefined ? undefined : noticeFailure("chat.notice.computerToolsDidNotStart", { reason });
+/** A catalog piece for the cause, so the person's line is worded in their language rather than carrying the English. */
+function why(reason: string): string {
+ if (/timed out/i.test(reason)) return "chat.notice.part.computerToolsTookTooLong";
+ if (/exited|could not start|input closed|stopped/i.test(reason)) return "chat.notice.part.computerToolsHelperStopped";
+ return "chat.notice.part.computerToolsHelperFailed";
+}
+
+const NOTICED_KEPT = 500;
+const noticed = new Set<string>();
+
+/** The person's line for a start that failed: in full once per conversation, then a short one while it keeps failing. */
+export function hostComputerNotice(conversation: string | undefined, reason: string): { message: string; text: ServerText } {
+ const repeat = conversation !== undefined && noticed.has(conversation);
+ if (conversation !== undefined && !repeat) {
+ noticed.add(conversation);
+ if (noticed.size > NOTICED_KEPT) noticed.delete(noticed.values().next().value!);
+ }
+ const key: ChatNoticeKey = repeat ? "chat.notice.computerToolsStillNotStarting" : "chat.notice.computerToolsDidNotStart";
+ return noticeFailure(key, repeat ? undefined : { why: why(reason) });
+}
+
+/** The computer started in this conversation, so its next failure is told in full again. */
+export function hostComputerStarted(conversation: string | undefined): void {
+ if (conversation !== undefined) noticed.delete(conversation);
+}
+
+/** Tells the person when a start the turn went on without fails, unless the turn ended first. */
+export function watchHostComputerStart(ready: Promise<unknown>, conversation: string | undefined, notice: ((line: { message: string; text: ServerText }) => void) | undefined,
+ open: () => boolean): void {
+ ready.then(() => hostComputerStarted(conversation), (error: unknown) => {
+ if (open()) notice?.(hostComputerNotice(conversation, reasonOf(error)));
+ });
}
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.ts
index ed0cbaea4f..16d9e83852 100644
--- a/server/drivers/chat-mcp-tools.test.ts
+++ b/server/drivers/chat-mcp-tools.test.ts
@@ -448,10 +448,11 @@ describe("Chat MCP session", () => {
});
describe("how long a server gets to start", () => {
- it("is about half a minute on a Cloud home, twenty seconds on Windows and eight seconds elsewhere", () => {
+ it("is about half a minute on a Cloud home, twenty seconds for the app's own servers on Windows and eight seconds elsewhere", () => {
expect(mcpStartupMs({ OMB_CLOUD_ROLE: "home" }, "win32")).toBe(30_000);
- expect(mcpStartupMs({ OMB_CLOUD_ROLE: "team" }, "linux")).toBe(30_000);
+ expect(mcpStartupMs({ OMB_CLOUD_ROLE: "team" }, "linux", false)).toBe(30_000);
expect(mcpStartupMs({}, "win32")).toBe(20_000);
+ expect(mcpStartupMs({}, "win32", false)).toBe(8_000);
expect(mcpStartupMs({}, "darwin")).toBe(8_000);
expect(mcpStartupMs({}, "linux")).toBe(8_000);
});
@@ -1141,7 +1142,7 @@ describe("Chat MCP startup budgets", () => {
}
});
- it("still gives a command server its own budget: 8 seconds, or 20 on Windows", async () => {
+ it("still gives a configured command server 8 seconds, on Windows too", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
const f = fixture(`if (message.method === "tools/list") return;`);
@@ -1149,10 +1150,10 @@ describe("Chat MCP startup budgets", () => {
const listed = () => { try { return f.read().calls.some((call) => call.method === "tools/list"); } catch { return false; } };
await untilReal(listed);
// The deadline runs on the real clock from the spawn, so a loaded runner has already spent some of it.
- await vi.advanceTimersByTimeAsync(mcpStartupMs() - 3_000);
+ await vi.advanceTimersByTimeAsync(mcpStartupMs(process.env, process.platform, false) - 3_000);
expect(mounting.done).toBe(false);
await vi.advanceTimersByTimeAsync(3_100);
- // stopped at its budget: short of the 30 seconds a URL server gets
+ // stopped at 8 seconds: well short of the 30 a URL server gets
await settleWithin(1_000, () => mounting.done);
expect(mounting.error).toBeUndefined();
expect(mounting.value?.skipped).toEqual([{ server: "audit", reason: expect.stringMatching(/timed out/) }]);
diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts
index 585c2b2dcc..ba61552394 100644
--- a/server/drivers/chat-mcp-tools.ts
+++ b/server/drivers/chat-mcp-tools.ts
@@ -22,8 +22,8 @@ import { REMOTE_MCP_STARTUP_MS, remoteMcpSpec } from "../mcp-http.ts";
import { compileToolSchema, schemaProblems, serverToolValidator, type ServerToolCheck } from "../mcp-schema-validator.ts";
import { fitToolList, withoutDanglingReferences } from "../mcp-tool-schema.ts";
import { listsComputerTool } from "../computer-tool-list.ts";
-import { HOST_COMPUTER_READY, hostComputerDidNotStart, hostComputerFailure, hostComputerKey, hostComputerNotice, hostComputerStandIn, hostComputerStartupMs, startHostComputer,
- type HostComputerStart } from "./chat-host-computer.ts";
+import { HOST_COMPUTER_QUICK_MS, HOST_COMPUTER_READY, hostComputerDidNotStart, hostComputerFailure, hostComputerKey, hostComputerNotice, hostComputerStandIn, hostComputerStarted,
+ hostComputerStartupMs, startHostComputer, watchHostComputerStart, type HostComputerStart } from "./chat-host-computer.ts";
import { READ_OPEN_PAGE_ONLY, readsAroundBrowser } from "../browser-tool-shape.ts";
import { capToolList, learnToolCountLimit, shareToolBudget, toolCountLimitFromError } from "../tool-count-limit.ts";
import type { ToolSchemaProfile } from "../tool-schema-profile.ts";
@@ -53,8 +53,6 @@ export interface ChatToolSession {
trimmed: TrimmedChatMcpServer[];
merged: MergedChatMcpServers[];
budget: ToolBudget;
- /** Why this desktop's own computer did not start for this turn; its tools are then reached through a stand-in. */
- hostComputerFailure?: string;
/** Lists the turn's tools again within `limit`, after a provider refused that many; started servers keep running. */
refit(limit: number): Promise<void>;
validate(name: string, args: unknown): void;
@@ -74,8 +72,8 @@ function chatToolName(server: string, tool: string): string {
const STARTUP_MS = 8_000;
/** A small Cloud home that is busy can take this long to load Node and a server's own imports. */
const CLOUD_STARTUP_MS = 30_000;
-/** Windows starts each built-in as its own Electron process, all at once, and scans each new executable first. */
-const WINDOWS_STARTUP_MS = 20_000;
+/** Windows starts each of the app's built-ins as its own Electron process, all at once, and scans each new executable first. */
+const WINDOWS_BUILT_IN_STARTUP_MS = 20_000;
const STARTUP_TIMED_OUT = "MCP startup timed out";
const REQUEST_TIMED_OUT = "MCP request timed out; execution outcome may be uncertain";
/** How much of a server's stderr is kept, and how much of its last line is ever shown. */
@@ -84,9 +82,18 @@ const STDERR_TAIL_CHARS = 4_000, STDERR_LINE_CHARS = 300;
* was given (mountChatTools `mustHave`). */
const OPTIONAL_BUILT_INS: ReadonlySet<string> = new Set(["computer", "browser", "composio", OWN_APPS_SERVER, "data", "email", "device"]);
-/** How long a server that runs a command gets to start here. */
-export function mcpStartupMs(env: Record<string, string | undefined> = process.env, platform: NodeJS.Platform = process.platform): number {
- return cloudRole(env) ? CLOUD_STARTUP_MS : platform === "win32" ? WINDOWS_STARTUP_MS : STARTUP_MS;
+/** How long a server that runs a command gets to start here: one of the app's own (`builtIn`) or one the person configured. */
+export function mcpStartupMs(env: Record<string, string | undefined> = process.env, platform: NodeJS.Platform = process.platform, builtIn = true): number {
+ return cloudRole(env) ? CLOUD_STARTUP_MS : builtIn && platform === "win32" ? WINDOWS_BUILT_IN_STARTUP_MS : STARTUP_MS;
+}
+
+/** `startupMs` replaces both mcpStartupMs budgets, `hostComputerMs` hostComputerStartupMs. `notice` hears, for the person,
+ * that this computer's tools did not start, worded once per `conversation`. */
+export interface ChatToolMountOptions {
+ startupMs?: number;
+ hostComputerMs?: number;
+ conversation?: string;
+ notice?: (line: { message: string; text: ServerText }) => void;
}
const DEFAULT_CALL_MS = 10 * 60_000;
const FRAME_BYTES = 2 * 1024 * 1024;
@@ -355,12 +362,6 @@ export function chatToolNotices(session: Pick<ChatToolSession, "skipped" | "trim
];
}
-/** chatToolNotices, then this computer's own line, worded for the person's language. */
-export function chatToolNoticeLines(session: ChatToolSession): Array<{ message: string; text?: ServerText }> {
- const computer = hostComputerNotice(session.hostComputerFailure);
- return [...chatToolNotices(session).map((message) => ({ message })), ...(computer ? [computer] : [])];
-}
-
function preview(bytes: Buffer): string {
let end = OUTPUT_BYTES;
while ((bytes[end] & 0xc0) === 0x80) end -= 1;
@@ -506,11 +507,10 @@ export function directServers(servers: ReadonlyArray<{ name: string; tools: numb
/** Under `schemaProfile` the model reads each tool's schema fitted to its provider; calls are still checked against the full one.
* A tool result over 50KB is saved whole in `resultFolder`, the bot's working folder, after `scrub` masks secrets (see savedOrBounded).
- * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number.
- * `startup` replaces the start budgets of mcpStartupMs and hostComputerStartupMs. */
+ * `toolLimit` is the most tools the provider takes in one request, ask_user included; null when it takes any number. */
export async function mountChatTools(integrations: SendTurnInput["integrations"], signal: AbortSignal, computerUse = false, toolScope?: ToolScope, callTimeoutMs: number = DEFAULT_CALL_MS,
schemaProfile?: ToolSchemaProfile, resultFolder?: string, scrub: (text: string) => string = redactSecretsInText, toolLimit: number | null = CHAT_TOOL_LIMIT,
- startup: { ms?: number; hostComputerMs?: number } = {}): Promise<ChatToolSession> {
+ options: ChatToolMountOptions = {}): Promise<ChatToolSession> {
const parsed = parseToolScope(toolScope);
if (!parsed.ok) throw new Error(parsed.error);
const scope = parsed.scope;
@@ -534,10 +534,10 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
// desktop's own): without the VM's tools the model would do the work some other way, outside the VM. Such a server that
// can't start, lists no tools, or fails during the turn ends the turn, as every server did before.
const mustHave = (descriptor: Server) => descriptor === agentsServer || (descriptor === integrations?.localComputer && integrations?.localComputer?.scope !== "local-computer");
- const startupMs = startup.ms ?? mcpStartupMs();
- const hostComputerMs = Math.max(startupMs, startup.hostComputerMs ?? hostComputerStartupMs());
+ const startupMs = options.startupMs ?? mcpStartupMs();
+ const configuredStartupMs = options.startupMs ?? mcpStartupMs(process.env, process.platform, false);
+ const hostComputerMs = Math.max(startupMs, options.hostComputerMs ?? hostComputerStartupMs());
let standIn: { definition: ChatToolDefinition; origin: ToolOrigin; ready?: Promise<unknown[]>; reason?: string } | undefined;
- let hostComputerFailed: string | undefined;
const builtIns = servers.length;
const besideBrowser = servers.some(([, descriptor]) => descriptor === integrations?.browser);
const merged: MergedChatMcpServers[] = [];
@@ -697,8 +697,10 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
&& ((searchable.has(name) && isDirectoryTool(tool.name)) || allowsTool(scope, { kind: "mcp", server: name, name: tool.name }))));
const hostComputer = descriptor === integrations?.localComputer && integrations?.localComputer?.scope === "local-computer";
const host: HostComputerStart | undefined = hostComputer
- ? await startHostComputer(hostComputerKey(descriptor), (record) => client.tools(signal, record, hostComputerMs), include, startupMs, signal) : undefined;
- const tools = host ? (host.state === "listed" || host.state === "pending" ? host.tools : []) : await client.tools(signal, include, searchable.has(name) ? REMOTE_MCP_STARTUP_MS : startupMs, observers.get(name));
+ ? await startHostComputer(hostComputerKey(descriptor), (record) => client.tools(signal, record, hostComputerMs), include, { quickMs: Math.min(startupMs, HOST_COMPUTER_QUICK_MS), firstMs: startupMs }, signal)
+ : undefined;
+ const budgetMs = searchable.has(name) ? REMOTE_MCP_STARTUP_MS : index < builtIns ? startupMs : configuredStartupMs;
+ const tools = host ? (host.state === "listed" || host.state === "pending" ? host.tools : []) : await client.tools(signal, include, budgetMs, observers.get(name));
if (!tools.length && scope === undefined && descriptor === integrations?.localComputer && (!host || host.state === "listed")) throw new Error("The Local VM listed no tools");
// Harness mounts are known by descriptor, never by a name a configured server could claim. A grant
// hashes the descriptor (no credential kept); machine bridges mint a bearer per turn, so theirs last a turn.
@@ -715,9 +717,15 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
throw new Error(`MCP server "${name}" didn't start: ${mount.reason instanceof Error ? mount.reason.message : "no reason given"}`);
}
const host = mount.value.host;
+ if (host?.state === "listed") hostComputerStarted(options.conversation);
+ if (host?.state === "pending" || host?.state === "starting") watchHostComputerStart(host.ready, options.conversation, options.notice, () => !closed && !signal.aborted);
if (host?.state === "starting" || host?.state === "failed") {
const reason = host.state === "failed" ? host.reason : undefined;
- if (reason !== undefined) { hostComputerFailed = reason; console.warn(`chat-mcp: this computer's tools did not start for this turn: ${reason}`); await mount.value.origin.client.close().catch(() => {}); }
+ if (reason !== undefined) {
+ console.warn(`chat-mcp: this computer's tools did not start for this turn: ${reason}`);
+ options.notice?.(hostComputerNotice(options.conversation, reason));
+ await mount.value.origin.client.close().catch(() => {});
+ }
standIn = { definition: hostComputerStandIn(reason), origin: mount.value.origin, ...(host.state === "starting" ? { ready: host.ready } : { reason }) };
continue;
}
@@ -844,7 +852,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
return { ok: true, text: HOST_COMPUTER_READY };
};
return {
- definitions, skipped, trimmed, merged, budget, validate, view, close, ...(hostComputerFailed !== undefined ? { hostComputerFailure: hostComputerFailed } : {}),
+ definitions, skipped, trimmed, merged, budget, validate, view, close,
async refit(limit) {
if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");
await layout(limit);
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index 48187a7cf2..b3814f2aff 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -14,7 +14,7 @@ import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQu
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { redactSecretsInText } from "../redact.ts";
import { toolDetailPreview } from "../tool-summary.ts";
-import { ChatToolSessionError, chatToolNoticeLines, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
+import { ChatToolSessionError, chatToolNotices, mountChatTools, refitChatTools, type ChatToolDefinition, type ChatToolSession, type ChatToolResult } from "./chat-mcp-tools.ts";
import { noteToolBudget } from "../tool-budgets.ts";
import { chatToolLimitFor, chatToolLimitKey } from "../tool-count-limit.ts";
import { assertImageTransport, chatImageBudget, chatToolImages, chatUserContent, type ChatContentPart } from "./chat-images.ts";
@@ -609,9 +609,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const scope = parsed.scope;
const toolsOff = options.tools === false || options.toolUse?.(model) === false;
tools = await mountChatTools(toolsOff ? undefined : turn.integrations, abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
- toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model));
+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), { conversation: turn.threadId, notice: ({ message, text }) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), text }) });
noteToolBudget(turn.botId, tools.budget);
- for (const { message, text } of chatToolNoticeLines(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), ...(text ? { text } : {}) });
+ for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
const questionAllowed = !toolsOff && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });
let optionalQuestionOnly = questionAllowed && tools.definitions.length === 0;
// An MCP server squatting ask_user cannot shadow it (dispatch intercepts the name); skip its definition.
diff --git a/src/locales/en.json b/src/locales/en.json
index d6b6cc2354..abd1ebde1e 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -8462,6 +8462,9 @@
"chat.notice.part.weeklyOpusLimit": "weekly Opus limit",
"chat.notice.part.weeklySonnetLimit": "weekly Sonnet limit",
"chat.notice.part.usageLimit": "usage limit",
+ "chat.notice.part.computerToolsTookTooLong": "they took too long to start",
+ "chat.notice.part.computerToolsHelperStopped": "their helper stopped",
+ "chat.notice.part.computerToolsHelperFailed": "their helper did not answer properly",
"chat.notice.part.chooseModel": "choose another model for this bot",
"chat.notice.part.switchAccount": "switch this bot to another AI or Claude account",
"chat.notice.webhookHome": "I'm back on this computer, so my webhook \"{name}\" has an address here again. Open Automations, choose Copy address on \"{name}\", and paste it into the app that sends to it.",
@@ -10158,7 +10161,8 @@
"chat.notice.computerDesktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.",
"chat.notice.computerPermissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it",
"chat.notice.computerNotReadyDetail": "OpenMausBot can't use this computer yet — {reason}",
- "chat.notice.computerToolsDidNotStart": "The tools for this computer did not start this time ({reason}). It is still linked to this bot; send your message again in a moment.",
+ "chat.notice.computerToolsDidNotStart": "The tools for this computer did not start this time ({why}). Send your message again in a moment.",
+ "chat.notice.computerToolsStillNotStarting": "The tools for this computer are still not starting.",
"chat.notice.computerNotReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.",
"chat.notice.computerSystemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work",
"chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index f079c59620..707637024b 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -8401,6 +8401,9 @@
"chat.notice.part.weeklyOpusLimit": "limite semanal do Opus",
"chat.notice.part.weeklySonnetLimit": "limite semanal do Sonnet",
"chat.notice.part.usageLimit": "limite de uso",
+ "chat.notice.part.computerToolsTookTooLong": "demoraram demais para iniciar",
+ "chat.notice.part.computerToolsHelperStopped": "o auxiliar delas parou",
+ "chat.notice.part.computerToolsHelperFailed": "o auxiliar delas não respondeu corretamente",
"chat.notice.part.chooseModel": "escolha outro modelo para este bot",
"chat.notice.part.switchAccount": "use outra IA ou outra conta do Claude para este bot",
"chat.notice.webhookHome": "Voltei para este computador, então meu webhook “{name}” tem um endereço aqui novamente. Abra “Automações”, escolha “Copiar endereço” em “{name}” e cole no app que envia para ele.",
@@ -10080,7 +10083,8 @@
"chat.notice.computerDesktopOnly": "Só o app OpenMausBot neste computador pode permitir que um bot o use. Abra o app aqui ou deixe o bot trabalhar no próprio navegador ou em um desktop na nuvem.",
"chat.notice.computerPermissionsThenRestart": "O OpenMausBot ainda não consegue usar este computador. Confira se o OpenMausBot tem as permissões que pede e reinicie o app.",
"chat.notice.computerNotReadyDetail": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}",
- "chat.notice.computerToolsDidNotStart": "As ferramentas deste computador não iniciaram desta vez ({reason}). Ele continua vinculado a este bot; envie sua mensagem de novo daqui a pouco.",
+ "chat.notice.computerToolsDidNotStart": "As ferramentas deste computador não iniciaram desta vez ({why}). Envie sua mensagem de novo daqui a pouco.",
+ "chat.notice.computerToolsStillNotStarting": "As ferramentas deste computador ainda não estão iniciando.",
"chat.notice.computerNotReadyMacPermission": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}. Abra o OpenMausBot novamente depois de conceder a permissão do macOS que falta.",
"chat.notice.computerSystemUnsupported": "Os bots não podem usar este computador neste sistema. Escolha outro lugar para este bot trabalhar",
"chat.notice.computerAiUnsupported": "A IA deste bot não pode usar este computador. Escolha outra IA ou outro lugar para o bot trabalhar",