Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
#5596: reset a stuck cloud computer automatically, with no Allow/Deny card
milind-sonib06c253967f1
diff --git a/server/drivers/agents-call.test.ts b/server/drivers/agents-call.test.tsindex 9f8c298bc5..b5d9239385 100644--- a/server/drivers/agents-call.test.ts+++ b/server/drivers/agents-call.test.ts@@ -626,11 +626,11 @@ describe("reset_cloud_computer", () => {api: async () => ({}),apiResponse: async (path, init) => {calls.push({ path, method: init?.method, body: JSON.parse(String(init?.body)) });- return ok ? { ok: true, status: 200, body: { text: "A card is now in this conversation." } } : { ok: false, status: 403, body: { error: "not yours" } };+ return ok ? { ok: true, status: 200, body: { text: "Your cloud computer is being reset." } } : { ok: false, status: 403, body: { error: "not yours" } };},},});- expect(await callTool("reset_cloud_computer", { why: "Stuck starting." }, reply(true))).toEqual({ text: "A card is now in this conversation." });+ expect(await callTool("reset_cloud_computer", { why: "Stuck starting." }, reply(true))).toEqual({ text: "Your cloud computer is being reset." });expect(await callTool("reset_cloud_computer", { why: "Stuck.", for_bot_id: " bot-b " }, reply(false))).toEqual({ text: "not yours", isError: true });expect(calls).toEqual([{ path: "/api/internal/cloud-computer/reset", method: "POST", body: { why: "Stuck starting." } },diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex 8921ac94ca..aa6ecc0b4c 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -277,12 +277,12 @@ const TOOL_DEFINITIONS = [{name: "reset_cloud_computer",description:- "Ask the person to reset your cloud computer when it is stuck (starting for a long time, or not responding): a card asks them to Allow, and on Allow it is deleted, with everything saved on it, once you are not working; your next turn makes a fresh one. Use it only for a stuck computer, never to tidy up. After calling it, end your turn: you are not resumed, and the card shows how it went." + CHIEF_PROFILE_TARGET,+ "Reset your cloud computer when it is stuck: it is deleted with everything on it once your turn ends, and your next turn makes a fresh one. Only for a stuck computer. End your turn after calling it." + CHIEF_PROFILE_TARGET,inputSchema: {type: "object",additionalProperties: false,properties: {- why: { type: "string", description: "One sentence for the card: what is wrong with the computer." },+ why: { type: "string", description: "One sentence shown in the chat: what is wrong with the computer." },for_bot_id: { type: "string", description: "Chief of Staff only: the bot whose cloud computer to reset, from list_bots." },},required: ["why"],diff --git a/server/host/cloud-computer-reset-asks.test.ts b/server/host/cloud-computer-reset-asks.test.tsindex 3dc30f29d0..6f799f875c 100644--- a/server/host/cloud-computer-reset-asks.test.ts+++ b/server/host/cloud-computer-reset-asks.test.ts@@ -1,12 +1,13 @@import { describe, expect, it, vi } from "vitest";-import { createCloudComputerResetAsks, noOwnCloudComputer, RESET_CLOUD_COMPUTER_TOOL, RESET_RETRIES, RESET_RETRY_MS } from "./cloud-computer-reset-asks.ts";+import { createCloudComputerResetAsks, noOwnCloudComputer, RESET_RETRIES, RESET_RETRY_MS } from "./cloud-computer-reset-asks.ts";import type { BotRecord } from "../store.ts";-type Line = { id: string; role: string; kind: string; card?: Record<string, any>; from?: unknown };+type Line = { id: string; role: string; kind: string; text?: string; from?: unknown };const bot = (id: string, name: string) => ({ id, name, color: "blue" }) as unknown as BotRecord;const ada = bot("bot-a", "Ada"), chief = bot("chief", "Chief"), bea = bot("bot-b", "Bea");+const IN_USE = () => Object.assign(new Error("this cloud computer is in use — stop its bot's work first"), { status: 409 });function setup(options: { refusal?: (from: BotRecord, target: BotRecord) => string | null; reset?: () => Promise<any>; computer?: () => Promise<string | null> } = {}) {const lines = new Map<string, Line[]>();@@ -14,7 +15,6 @@ function setup(options: { refusal?: (from: BotRecord, target: BotRecord) => striconst store = {bot: (id: string) => roster.find((candidate) => candidate.id === id),groupByThread: () => undefined,- messagesFor: (threadId: string) => lines.get(threadId) ?? [],appendMessage: (threadId: string, message: Omit<Line, "id">) => {const line = { ...message, id: `m${(lines.get(threadId)?.length ?? 0) + 1}` };lines.set(threadId, [...(lines.get(threadId) ?? []), line]);@@ -23,156 +23,130 @@ function setup(options: { refusal?: (from: BotRecord, target: BotRecord) => stripatchMessage: (threadId: string, id: string, patch: Partial<Line>) => {const line = lines.get(threadId)?.find((candidate) => candidate.id === id);if (line) Object.assign(line, patch);- return Boolean(line);+ return line ?? null;},};const timers: Array<() => void> = [];const reset = vi.fn(options.reset ?? (async () => ({ ok: true })));const computer = vi.fn(options.computer ?? (async () => "bx_1"));- const asks = createCloudComputerResetAsks({+ const resets = createCloudComputerResetAsks({store: store as never,refusal: options.refusal ?? (() => null),computer,reset,setTimer: (run, ms) => { expect(ms).toBe(RESET_RETRY_MS); timers.push(run); },- openCards: () => [...lines.entries()].flatMap(([threadId, list]) => list.filter((line) => line.card?.tool === RESET_CLOUD_COMPUTER_TOOL).map((line) => ({ threadId, messageId: line.id }))),});const call = async (sender: BotRecord, body: Record<string, unknown>) => {const res = { status: 0, body: {} as Record<string, any> };- await asks.internal({+ await resets.internal({method: "POST", path: "/api/internal/cloud-computer/reset", res: {} as never, sender, threadId: "t1", readBody: async () => ({ why: "Stuck starting.", ...body }),json: ((_res: unknown, status: number, sent: Record<string, unknown>) => { res.status = status; res.body = sent; }) as never,});return res;};- const card = () => lines.get("t1")?.at(-1)?.card;+ const line = () => lines.get("t1")?.at(-1);const flush = () => new Promise((resolve) => setTimeout(resolve, 0));- return { asks, call, card, reset, computer, timers, flush, lines, roster };+ return { call, line, reset, computer, timers, flush, lines, roster };}-describe("a bot asking for its cloud computer to be reset", () => {- it("shows the person a card and tells the bot to end its turn, resetting nothing yet", async () => {- const { call, card, reset } = setup();+describe("a bot resetting its stuck cloud computer", () => {+ it("says so in one plain line, starts the reset at once with no card, and tells the bot to end its turn", async () => {+ const { call, line, reset, flush } = setup();const res = await call(ada, { why: "It has been starting for 20 minutes." });expect(res.status).toBe(200);expect(res.body.text).toContain("End this turn");- expect(card()).toMatchObject({ title: "Reset Ada's cloud desktop?", options: ["Allow", "Deny"], requestType: "permission", tool: RESET_CLOUD_COMPUTER_TOOL });- expect(card()?.subtitle).toContain("It has been starting for 20 minutes.");- expect(card()?.subtitle).toContain("files and browser sign-ins");- expect(reset).not.toHaveBeenCalled();- });-- it("does nothing on Deny", async () => {- const { asks, call, card, reset, flush } = setup();- await call(ada, {});- expect(asks.answer(card()!.requestId, "deny")).toBe(true);+ expect(line()).toMatchObject({ role: "bot", kind: "text" });+ expect(line()).not.toHaveProperty("card");+ expect(line()?.text).toMatch(/^Resetting Ada's cloud desktop: It has been starting for 20 minutes\./);await flush();- expect(reset).not.toHaveBeenCalled();- expect(card()?.answered).toBe("deny");+ expect(reset).toHaveBeenCalledWith("bot-a", "bx_1");+ expect(line()?.text).toContain("Reset: a fresh cloud desktop starts with Ada's next message.");});- it("resets on Allow and says so on the card", async () => {- const { asks, call, card, reset, flush } = setup();- await call(ada, {});- expect(asks.answer(card()!.requestId, "allow")).toBe(true);- await flush();- expect(reset).toHaveBeenCalledWith("bot-a", "bx_1");- expect(card()).toMatchObject({ answered: "allow" });- expect(card()?.subtitle).toContain("Reset: a fresh cloud desktop starts with Ada's next message.");+ it("says when the old cloud desktop is still being deleted, or there was none", async () => {+ const pending = setup({ reset: async () => ({ ok: true, pending: true }) });+ await pending.call(ada, {});+ await pending.flush();+ expect(pending.line()?.text).toContain("still being deleted");+ const missing = setup({ reset: async () => ({ ok: true, missing: true }) });+ await missing.call(ada, {});+ await missing.flush();+ expect(missing.line()?.text).toContain("Nothing to reset");});- it("waits for the asking turn to end: a computer in use is retried, then reset", async () => {+ it("waits for the calling turn to end: a computer in use is retried, then reset", async () => {let busy = true;- const { asks, call, card, reset, timers, flush } = setup({- reset: async () => {- if (busy) throw Object.assign(new Error("this cloud computer is in use — stop its bot's work first"), { status: 409 });- return { ok: true };- },- });+ const { call, line, reset, timers, flush } = setup({ reset: async () => { if (busy) throw IN_USE(); return { ok: true }; } });await call(ada, {});- asks.answer(card()!.requestId, "allow");await flush();- expect(card()?.subtitle).toContain("Waiting for Ada to finish its work");+ expect(line()?.text).toContain("Waiting for Ada to finish its work");expect(timers).toHaveLength(1);busy = false;timers.shift()!();await flush();expect(reset).toHaveBeenCalledTimes(2);- expect(card()?.subtitle).toContain("Reset: a fresh cloud desktop");+ expect(line()?.text).toContain("Reset: a fresh cloud desktop");+ expect(line()?.text).toMatch(/^Resetting Ada's cloud desktop: Stuck starting\.\n/);});it("gives up on a computer that stays in use, and resets nothing", async () => {- const { asks, call, card, timers, flush } = setup({- reset: async () => { throw Object.assign(new Error("this cloud computer is in use — stop its bot's work first"), { status: 409 }); },- });+ const { call, line, timers, flush } = setup({ reset: async () => { throw IN_USE(); } });await call(ada, {});- asks.answer(card()!.requestId, "allow");await flush();for (let i = 0; i < RESET_RETRIES; i += 1) { timers.shift()!(); await flush(); }expect(timers).toHaveLength(0);- expect(card()?.subtitle).toContain("Not reset: this cloud computer is in use");+ expect(line()?.text).toContain("Not reset: this cloud computer is in use");});it("reports any other failure without retrying", async () => {- const { asks, call, card, timers, flush } = setup({ reset: async () => { throw Object.assign(new Error("Could not reach boat.dev"), { status: 503 }); } });+ const { call, line, timers, flush } = setup({ reset: async () => { throw Object.assign(new Error("Could not reach boat.dev"), { status: 503 }); } });await call(ada, {});- asks.answer(card()!.requestId, "allow");await flush();expect(timers).toHaveLength(0);- expect(card()?.subtitle).toContain("Not reset: Could not reach boat.dev");+ expect(line()?.text).toContain("Not reset: Could not reach boat.dev");});- it("lets a Chief ask for a bot it manages and refuses what the rule refuses", async () => {+ it("lets a Chief reset a bot it manages and refuses what the rule refuses", async () => {const refusal = (from: BotRecord, target: BotRecord) => from.id === target.id || (from.id === "chief" && target.id === "bot-a") ? null : "not yours";- const { asks, call, card, reset, flush } = setup({ refusal });+ const { call, line, reset, flush } = setup({ refusal });expect(await call(ada, { targetBotId: "bot-b" })).toMatchObject({ status: 403, body: { error: "not yours" } });- expect(card()).toBeUndefined();+ expect(line()).toBeUndefined();+ expect(reset).not.toHaveBeenCalled();const asked = await call(chief, { targetBotId: "bot-a" });expect(asked.status).toBe(200);- expect(asked.body.text).toContain("reset Ada's cloud computer");- asks.answer(card()!.requestId, "allow");+ expect(asked.body.text).toContain("Ada's cloud computer is being reset");await flush();expect(reset).toHaveBeenCalledWith("bot-a", "bx_1");expect((await call(chief, { targetBotId: "nobody" })).status).toBe(404);});- it("checks again on Allow and on every retry whether the bot may still ask, and resets nothing once it may not", async () => {- let allowed = true;- const { asks, call, card, reset, flush } = setup({ refusal: () => allowed ? null : "Ada has no cloud computer of its own to reset here." });- await call(ada, {});- allowed = false;- asks.answer(card()!.requestId, "allow");- await flush();- expect(reset).not.toHaveBeenCalled();- expect(card()?.subtitle).toContain("Not reset: Ada has no cloud computer of its own to reset here.");-- let busy = true;- allowed = true;- const retry = setup({+ it("checks again on every retry whether the bot may still reset, and resets nothing once it may not", async () => {+ let allowed = true, busy = true;+ const { call, line, reset, timers, flush } = setup({refusal: () => allowed ? null : "not yours",- reset: async () => { if (busy) throw Object.assign(new Error("this cloud computer is in use — stop its bot's work first"), { status: 409 }); return { ok: true }; },+ reset: async () => { if (busy) throw IN_USE(); return { ok: true }; },});- await retry.call(chief, { targetBotId: "bot-a" });- retry.asks.answer(retry.card()!.requestId, "allow");- await retry.flush();- expect(retry.reset).toHaveBeenCalledTimes(1);+ await call(chief, { targetBotId: "bot-a" });+ await flush();+ expect(reset).toHaveBeenCalledTimes(1);allowed = false;busy = false;- retry.timers.shift()!();- await retry.flush();- expect(retry.reset).toHaveBeenCalledTimes(1);- expect(retry.timers).toHaveLength(0);- expect(retry.card()?.subtitle).toContain("Not reset: not yours");+ timers.shift()!();+ await flush();+ expect(reset).toHaveBeenCalledTimes(1);+ expect(timers).toHaveLength(0);+ expect(line()?.text).toContain("Not reset: not yours");});- it("says in the card's language that nothing was reset when a bot was deleted before Allow", async () => {- const { asks, call, card, reset, flush, roster } = setup();+ it("says nothing was reset when a bot is deleted while the reset waits", async () => {+ const { call, line, reset, timers, flush, roster } = setup({ reset: async () => { throw IN_USE(); } });await call(ada, {});+ await flush();roster.splice(roster.indexOf(ada), 1);- asks.answer(card()!.requestId, "allow");+ timers.shift()!();await flush();- expect(reset).not.toHaveBeenCalled();- expect(card()?.subtitle).toContain("Not reset: Ada or the bot that asked no longer exists.");+ expect(reset).toHaveBeenCalledTimes(1);+ expect(line()?.text).toContain("Not reset: Ada or the bot that asked no longer exists.");});it("counts a bot on Auto as having a cloud computer of its own, unless it uses its department's", () => {@@ -186,60 +160,48 @@ describe("a bot asking for its cloud computer to be reset", () => {expect(noOwnCloudComputer(named("local"), true, false)).toBe(none);});- it("needs a reason, and shows no card without one", async () => {- const { call, card, computer } = setup();+ it("needs a reason, and posts nothing without one", async () => {+ const { call, line, computer, reset } = setup();for (const why of [undefined, "", " "]) {expect(await call(ada, { why })).toMatchObject({ status: 400 });}- expect(card()).toBeUndefined();+ expect(line()).toBeUndefined();expect(computer).not.toHaveBeenCalled();+ expect(reset).not.toHaveBeenCalled();});- it("binds Allow to the computer there was when asked, or to none", async () => {- const { asks, call, card, reset, flush } = setup({ computer: async () => null });+ it("resets the computer there was when called, or none", async () => {+ const { call, reset, flush } = setup({ computer: async () => null });await call(ada, {});- asks.answer(card()!.requestId, "allow");await flush();expect(reset).toHaveBeenCalledWith("bot-a", null);});- it("shows no card when it cannot tell which computer runs now", async () => {- const { call, card } = setup({ computer: async () => { throw new Error("Could not reach boat.dev"); } });+ it("posts nothing and resets nothing when it cannot tell which computer runs now", async () => {+ const { call, line, reset } = setup({ computer: async () => { throw new Error("Could not reach boat.dev"); } });expect(await call(ada, {})).toMatchObject({ status: 503 });- expect(card()).toBeUndefined();+ expect(line()).toBeUndefined();+ expect(reset).not.toHaveBeenCalled();});- it("does not retry when a different computer runs at Allow", async () => {- const { asks, call, card, timers, flush } = setup({+ it("does not retry when a different computer runs by the time it resets", async () => {+ const { call, line, timers, flush } = setup({reset: async () => { throw Object.assign(new Error("a different cloud desktop runs now than when this was asked, so nothing was reset"), { status: 409 }); },});await call(ada, {});- asks.answer(card()!.requestId, "allow");await flush();expect(timers).toHaveLength(0);- expect(card()?.subtitle).toContain("nothing was reset");+ expect(line()?.text).toContain("nothing was reset");});- it("keeps one open card per computer", async () => {- const { call } = setup();+ it("keeps one reset in flight per computer, and takes another once it is done", async () => {+ const { call, timers, flush, lines } = setup({ reset: async () => { throw IN_USE(); } });await call(ada, {});+ await flush();expect((await call(ada, {})).status).toBe(409);- });-- it("is not one of its cards for an unknown request", () => {- expect(setup().asks.answer("other", "allow")).toBe(false);- });-- it("closes a card left open by a previous run", async () => {- const first = setup();- await first.call(ada, {});- const fresh = createCloudComputerResetAsks({- store: { messagesFor: (id: string) => first.lines.get(id) ?? [], patchMessage: (threadId: string, id: string, patch: Partial<Line>) => Object.assign(first.lines.get(threadId)!.find((line) => line.id === id)!, patch) } as never,- refusal: () => null, computer: vi.fn(), reset: vi.fn(),- openCards: () => [{ threadId: "t1", messageId: "m1" }],- });- expect(fresh.dismissStale()).toBe(1);- expect(first.card()).toMatchObject({ expired: true, options: [] });- expect(fresh.answer(first.card()!.requestId, "allow")).toBe(false);+ expect((await call(bea, {})).status).toBe(200);+ expect(lines.get("t1")).toHaveLength(2);+ for (let i = 0; i < RESET_RETRIES; i += 1) { for (const run of timers.splice(0)) run(); await flush(); }+ expect((await call(ada, {})).status).toBe(200);});});diff --git a/server/host/cloud-computer-reset-asks.ts b/server/host/cloud-computer-reset-asks.tsindex e7f0f704a2..60002640e1 100644--- a/server/host/cloud-computer-reset-asks.ts+++ b/server/host/cloud-computer-reset-asks.ts@@ -1,35 +1,30 @@-// A bot asks the person to reset a stuck cloud computer (its own, or as a Chief one of a bot it manages): a card-// in the chat, and on Allow the computer is deleted the way Settings does, once its bot is not working.+// A bot resets a stuck cloud computer (its own, or as a Chief one of a bot it manages): a line in the chat says so,+// and the computer is deleted the way Settings does, once its bot is not working; the line then says how it went.import type { ServerResponse } from "node:http";-import { newId } from "../contracts.ts";import type { json as sendJson } from "../harness/http.ts";-import { optionCardsForTools } from "../message-db.ts";import { PASS } from "../routes/table.ts";import { serverLine, type ServerLineKey } from "../server-lines.ts";import type { BotRecord, Store } from "../store.ts";-export const RESET_CLOUD_COMPUTER_TOOL = "reset_cloud_computer";const PATH = "/api/internal/cloud-computer/reset";-/** The turn that asked holds its own computer until it ends: Allow waits up to this long for it. */+/** The turn that called holds its own computer until it ends: the reset waits up to this long for it. */export const RESET_RETRY_MS = 5_000;export const RESET_RETRIES = 36;const WHY_LIMIT = 300;type Reset = { ok: boolean; pending?: true; missing?: true };-type Ask = { threadId: string; messageId: string; fromId: string; targetId: string; targetName: string; subtitle: string; boxId: string | null };+type Run = { threadId: string; messageId: string; fromId: string; targetId: string; targetName: string; text: string; boxId: string | null };type Reply = { status: number; body: Record<string, unknown> };export interface CloudComputerResetAsksDeps {- store: Pick<Store, "appendMessage" | "patchMessage" | "messagesFor" | "bot" | "groupByThread">;- /** Why `from` may not ask to reset `target`'s cloud computer, in words for the bot; null when it may. */+ store: Pick<Store, "appendMessage" | "patchMessage" | "bot" | "groupByThread">;+ /** Why `from` may not reset `target`'s cloud computer, in words for the bot; null when it may. */refusal(from: BotRecord, target: BotRecord): string | null;/** The id of the bot's own cloud computer now, null when it has none; throws when that cannot be read. */computer(botId: string): Promise<string | null>;/** Deletes the bot's own cloud computer, only while it is still `boxId`; throws with status 409 while it is in use. */reset(botId: string, boxId: string | null): Promise<Reset>;- /** Cards a previous run left open; defaults to the message database. */- openCards?(): Array<{ threadId: string; messageId: string }>;setTimer?(run: () => void, ms: number): void;/** The language of the person the conversation is for. */language?(threadId: string): string | undefined;@@ -47,39 +42,43 @@ const inUse = (error: unknown) =>export function createCloudComputerResetAsks(deps: CloudComputerResetAsksDeps) {const { store } = deps;- const asks = new Map<string, Ask>();+ /** One reset in flight per bot's computer, by target bot id. */+ const running = new Map<string, Run>();const later = deps.setTimer ?? ((run: () => void, ms: number) => { setTimeout(run, ms).unref?.(); });const words = (threadId: string, key: ServerLineKey, params: Record<string, string>) => serverLine(deps.language?.(threadId), key, params);- function show(ask: Ask, line: string, answered?: "allow" | "deny"): void {- const card = store.messagesFor(ask.threadId).find((message) => message.id === ask.messageId)?.card;- if (!card) return;- store.patchMessage(ask.threadId, ask.messageId, { card: { ...card, ...(answered ? { answered } : {}), subtitle: line ? `${ask.subtitle}\n${line}` : ask.subtitle } });+ function show(run: Run, line: string): void {+ store.patchMessage(run.threadId, run.messageId, { text: `${run.text}\n${line}` });}- async function run(ask: Ask, tries: number): Promise<void> {+ function finish(run: Run, line: string): void {+ running.delete(run.targetId);+ show(run, line);+ }++ async function attempt(run: Run, tries: number): Promise<void> {try {- // Who may ask can change while the card waits (a moved bot, another computer setting): checked again on every try.- const from = store.bot(ask.fromId), target = store.bot(ask.targetId);- if (!from || !target) { show(ask, words(ask.threadId, "server.cloudReset.gone", { name: ask.targetName })); return; }+ // Who may reset can change while it waits (a moved bot, another computer setting): checked again on every try.+ const from = store.bot(run.fromId), target = store.bot(run.targetId);+ if (!from || !target) { finish(run, words(run.threadId, "server.cloudReset.gone", { name: run.targetName })); return; }const refused = deps.refusal(from, target);- if (refused) { show(ask, words(ask.threadId, "server.cloudReset.failed", { reason: refused })); return; }- const result = await deps.reset(ask.targetId, ask.boxId);+ if (refused) { finish(run, words(run.threadId, "server.cloudReset.failed", { reason: refused })); return; }+ const result = await deps.reset(run.targetId, run.boxId);const key = result.missing ? "server.cloudReset.missing" : result.pending ? "server.cloudReset.pending" : "server.cloudReset.done";- show(ask, words(ask.threadId, key, { name: ask.targetName }));+ finish(run, words(run.threadId, key, { name: run.targetName }));} catch (error) {if (inUse(error) && tries < RESET_RETRIES) {- if (tries === 0) show(ask, words(ask.threadId, "server.cloudReset.waiting", { name: ask.targetName }));- later(() => void run(ask, tries + 1), RESET_RETRY_MS);+ if (tries === 0) show(run, words(run.threadId, "server.cloudReset.waiting", { name: run.targetName }));+ later(() => void attempt(run, tries + 1), RESET_RETRY_MS);return;}- show(ask, words(ask.threadId, "server.cloudReset.failed", { reason: error instanceof Error ? error.message : String(error) }));+ finish(run, words(run.threadId, "server.cloudReset.failed", { reason: error instanceof Error ? error.message : String(error) }));}}- /** A bot's call: shows the card. `targetBotId` names another bot, for a Chief. */- async function propose(from: BotRecord, threadId: string, body: Record<string, unknown>): Promise<Reply> {+ /** A bot's call: says so in the chat and starts the reset. `targetBotId` names another bot, for a Chief. */+ async function start(from: BotRecord, threadId: string, body: Record<string, unknown>): Promise<Reply> {const targetId = typeof body.targetBotId === "string" && body.targetBotId.trim() ? body.targetBotId.trim() : from.id;const target = store.bot(targetId);if (!target) return { status: 404, body: { error: "No bot has that id. Use list_bots for teammate ids." } };@@ -87,58 +86,36 @@ export function createCloudComputerResetAsks(deps: CloudComputerResetAsksDeps) {if (refused) return { status: 403, body: { error: refused } };const why = typeof body.why === "string" ? body.why.trim().slice(0, WHY_LIMIT) : "";if (!why) return { status: 400, body: { error: "why is required: one sentence on what is wrong with the computer." } };- const already: Reply = { status: 409, body: { error: `A card asking to reset ${target.name}'s cloud computer is already waiting for the person. End this turn.` } };- const waiting = () => [...asks.values()].some((ask) => ask.targetId === target.id);- if (waiting()) return already;- // Allow resets the computer there is now, never a newer one made after the card was shown.+ const already: Reply = { status: 409, body: { error: `${target.name}'s cloud computer is already being reset. End this turn.` } };+ if (running.has(target.id)) return already;+ // The reset deletes the computer there is now, never a newer one made after this call.let boxId: string | null;try { boxId = await deps.computer(target.id); } catch (error) {return { status: 503, body: { error: `Could not check ${target.name}'s cloud computer: ${error instanceof Error ? error.message : String(error)}` } };}- if (waiting()) return already;- const subtitle = [why, words(threadId, "server.cloudReset.what", { name: target.name })].filter(Boolean).join("\n");+ if (running.has(target.id)) return already;+ const text = words(threadId, "server.cloudReset.resetting", { name: target.name, why });const room = store.groupByThread(threadId);- const requestId = newId();const message = store.appendMessage(threadId, {role: "bot",- kind: "options",+ kind: "text",+ text,...(room ? { from: { botId: from.id, name: from.name, color: from.color } } : {}),- card: { title: words(threadId, "server.cloudReset.title", { name: target.name }), subtitle, options: ["Allow", "Deny"], requestId, requestType: "permission", tool: RESET_CLOUD_COMPUTER_TOOL },});- asks.set(requestId, { threadId, messageId: message.id, fromId: from.id, targetId: target.id, targetName: target.name, subtitle, boxId });- const whose = target.id === from.id ? "your" : `${target.name}'s`;- return { status: 200, body: { text: `A card asking the person to reset ${whose} cloud computer is now in this conversation. End this turn now and say in one line that it waits for them. On Allow the computer is deleted once ${target.name} is not working, and ${target.name}'s next turn makes a fresh one. You are not resumed: the card shows how it went.` } };+ const run: Run = { threadId, messageId: message.id, fromId: from.id, targetId: target.id, targetName: target.name, text, boxId };+ running.set(target.id, run);+ void attempt(run, 0);+ const whose = target.id === from.id ? "Your" : `${target.name}'s`;+ return { status: 200, body: { text: `${whose} cloud computer is being reset: it is deleted, with everything on it, once ${target.name} is not working, and ${target.name}'s next turn makes a fresh one. End this turn now. You are not resumed: a line in this conversation shows how it went.` } };}return {- /** A tap on the card; false when the card is not one of these. */- answer(requestId: string, behavior: string | undefined): boolean {- const ask = asks.get(requestId);- if (!ask) return false;- asks.delete(requestId);- if (behavior !== "allow") { show(ask, "", "deny"); return true; }- show(ask, words(ask.threadId, "server.cloudReset.resetting", { name: ask.targetName }), "allow");- void run(ask, 0);- return true;- },-- /** A card a previous run left open has nothing behind it now: closed at startup. */- dismissStale(): number {- let closed = 0;- for (const { threadId, messageId } of (deps.openCards ?? (() => optionCardsForTools([RESET_CLOUD_COMPUTER_TOOL])))()) {- const card = store.messagesFor(threadId).find((message) => message.id === messageId)?.card;- if (!card || card.answered || card.dismissed || card.expired || asks.has(card.requestId ?? "")) continue;- if (store.patchMessage(threadId, messageId, { card: { ...card, expired: true, options: [] } })) closed += 1;- }- return closed;- },-/** POST /api/internal/cloud-computer/reset: { targetBotId?, why? } from a bot's turn. */async internal(args: { method: string; path: string; res: ServerResponse; json: typeof sendJson; sender: BotRecord; threadId: string; readBody(): Promise<unknown> }): Promise<typeof PASS | void> {if (args.path !== PATH) return PASS;if (args.method !== "POST") return void args.json(args.res, 405, { error: "POST only" });const body = await args.readBody();- const reply = await propose(args.sender, args.threadId, body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {});+ const reply = await start(args.sender, args.threadId, body && typeof body === "object" && !Array.isArray(body) ? body as Record<string, unknown> : {});return void args.json(args.res, reply.status, reply.body);},};diff --git a/server/index.ts b/server/index.tsindex 41cf96a3eb..37daa4d7a4 100644--- a/server/index.ts+++ b/server/index.ts@@ -4891,7 +4891,7 @@ async function respondToCard(input: {if (refused) return { ok: false, status: 409, error: refused };let result: CardRespondResult = { ok: true };await answeringCardAs(auth, threadId, requestId, async () => {- if (await harnessCardOutcome(threadId, requestId, behavior, message)) return; const outcome = await answerRequest(+ const outcome = await answerRequest(threadId, botForThread(bot.id, threadId)?.modelSelection.instanceId ?? "", requestId, behavior, message,{ id: bot.id, name: bot.name },);@@ -9599,13 +9599,13 @@ const ROOM_POST_MAX_CHARS = 4_000;const approvalBus: YourComputerBus = { store, notify };-// A bot's ask to reset a stuck cloud computer: its own, or as a Chief one of a bot it manages; Settings' reset on Allow.+// A bot resets a stuck cloud computer: its own, or as a Chief one of a bot it manages; Settings' reset, at once.const cloudComputerResets = createCloudComputerResetAsks({ language: threadLanguage, store, refusal: (from, target) => target.id !== from.id && !(chiefLevel(from) && canManage(from, target)) ? "You can ask to reset only your own cloud computer; a Chief of Staff can also ask for a bot in a department it manages." : noOwnCloudComputer(target, boat.boatConfigured(cfg), Boolean(inheritedTeamComputer(target))), computer: async (botId) => (await ownCloudComputer(cfg, botId, managedBoatOwners()))?.boxId ?? null, reset: async (botId, boxId) => { if (boatLifecycleBusyBots.has(botId)) throw Object.assign(new Error("this bot's cloud computer is being changed — wait for it to finish"), { status: 409 }); return resetBotCloudComputer(cfg, botId, managedBoatOwners(), (instance) => { if (computerProviderConfigTransitions.has("box")) throw Object.assign(new Error(providerTransitionMessage("box")), { status: 409 }); workspaceMaintenance.assertAvailable(); return claimManagedBoatMutation(instance); }, boxId); } });-const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover, ownCards: (requestId, behavior) => (computerAsks?.asks.answer(requestId, behavior) ?? false) || cloudComputerResets.answer(requestId, behavior) });+const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover, ownCards: (requestId, behavior) => computerAsks?.asks.answer(requestId, behavior) ?? false });// Consent cards live only in memory: settle every card still open on disk, or it locks the composer forever.{- const stale = dismissLeftoverPeerCards(store) + dismissStaleYourComputerCards(store) + (computerAsks?.asks.dismissStale() ?? 0) + cloudComputerResets.dismissStale();+ const stale = dismissLeftoverPeerCards(store) + dismissStaleYourComputerCards(store) + (computerAsks?.asks.dismissStale() ?? 0);if (stale) console.log(`approvals: dismissed ${stale} card(s) left by a previous run`);}diff --git a/src/components/ApprovalCard.tsx b/src/components/ApprovalCard.tsxindex 84aa782ab7..914b460b4a 100644--- a/src/components/ApprovalCard.tsx+++ b/src/components/ApprovalCard.tsx@@ -126,7 +126,6 @@ export function toolLabel(tool?: string): string {stage_skill: "approval.tool.enableSkill",update_skill: "approval.tool.updateSkill",update_profile: "approval.tool.updateProfile",- reset_cloud_computer: "approval.tool.resetCloudComputer",// ACP drivers may send the protocol's toolCall kind as the tool, so every kind maps to a phrase ("shell" is// execute; "tool" is no kind at all).shell: "approval.tool.runCommand",diff --git a/src/locales/de.json b/src/locales/de.jsonindex 1ae04ea71e..cda1c26a80 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -158,9 +158,7 @@"server.mcp.card.cleared": "Gespeicherte Werte werden gelöscht: {items}.","server.mcp.card.usedBy": "Wird von {names} genutzt.","server.mcp.card.usedByNone": "Kein anderer Bot nutzt ihn.",- "server.cloudReset.title": "Cloud-Desktop von {name} zurücksetzen?",- "server.cloudReset.what": "Er wird mit seinen Dateien und Browser-Anmeldungen gelöscht, und mit der nächsten Nachricht von {name} startet ein neuer. Das lässt sich nicht rückgängig machen.",- "server.cloudReset.resetting": "Cloud-Desktop von {name} wird zurückgesetzt.",+ "server.cloudReset.resetting": "Cloud-Desktop von {name} wird zurückgesetzt: {why}","server.cloudReset.waiting": "Warte, bis {name} seine Arbeit beendet hat, dann wird zurückgesetzt.","server.cloudReset.done": "Zurückgesetzt: Mit der nächsten Nachricht von {name} startet ein neuer Cloud-Desktop.","server.cloudReset.pending": "Zurücksetzen gestartet. Der alte Cloud-Desktop wird noch gelöscht; sobald er weg ist, startet mit der nächsten Nachricht von {name} ein neuer.",@@ -456,7 +454,6 @@"approval.tool.enableSkill": "eine erlernte Fähigkeit aktivieren","approval.tool.updateSkill": "eine erlernte Fähigkeit aktualisieren","approval.tool.updateProfile": "sein Profil aktualisieren",- "approval.tool.resetCloudComputer": "einen Cloud-Desktop zurücksetzen","approval.tool.deleteFile": "eine Datei löschen","approval.tool.think": "nachdenken","approval.tool.takeAction": "eine Aktion ausführen",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 989c2c0974..8ea264aa94 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -290,9 +290,7 @@"server.mcp.card.cleared": "Clears the saved {items}.","server.mcp.card.usedBy": "Used by {names}.","server.mcp.card.usedByNone": "No other bot uses it.",- "server.cloudReset.title": "Reset {name}'s cloud desktop?",- "server.cloudReset.what": "It is deleted with its files and browser sign-ins, and a fresh one starts with {name}'s next message. This cannot be undone.",- "server.cloudReset.resetting": "Resetting {name}'s cloud desktop.",+ "server.cloudReset.resetting": "Resetting {name}'s cloud desktop: {why}","server.cloudReset.waiting": "Waiting for {name} to finish its work before resetting.","server.cloudReset.done": "Reset: a fresh cloud desktop starts with {name}'s next message.","server.cloudReset.pending": "Reset started. The old cloud desktop is still being deleted; a fresh one starts with {name}'s next message once it is gone.",@@ -1003,7 +1001,6 @@"approval.tool.enableSkill": "enable a learned skill","approval.tool.updateSkill": "update a learned skill","approval.tool.updateProfile": "update its profile",- "approval.tool.resetCloudComputer": "reset a cloud desktop","approval.tool.deleteFile": "delete a file","approval.tool.think": "think","approval.tool.takeAction": "take an action",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 953a97834c..dc09ec7ffc 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -273,9 +273,7 @@"server.mcp.card.cleared": "Limpa estes dados salvos: {items}.","server.mcp.card.usedBy": "Usado por {names}.","server.mcp.card.usedByNone": "Nenhum outro bot usa este servidor.",- "server.cloudReset.title": "Redefinir o desktop na nuvem de {name}?",- "server.cloudReset.what": "Ele é excluído com os arquivos e logins do navegador, e um novo começa com a próxima mensagem de {name}. Não dá para desfazer.",- "server.cloudReset.resetting": "Redefinindo o desktop na nuvem de {name}.",+ "server.cloudReset.resetting": "Redefinindo o desktop na nuvem de {name}: {why}","server.cloudReset.waiting": "Esperando {name} terminar o trabalho antes de redefinir.","server.cloudReset.done": "Redefinido: um novo desktop na nuvem começa com a próxima mensagem de {name}.","server.cloudReset.pending": "Redefinição iniciada. O desktop na nuvem antigo ainda está sendo excluído; um novo começa com a próxima mensagem de {name} quando ele sumir.",@@ -978,7 +976,6 @@"approval.tool.enableSkill": "ativar uma habilidade aprendida","approval.tool.updateSkill": "atualizar uma habilidade aprendida","approval.tool.updateProfile": "atualizar o próprio perfil",- "approval.tool.resetCloudComputer": "redefinir um desktop na nuvem","approval.tool.deleteFile": "excluir um arquivo","approval.tool.think": "pensar","approval.tool.takeAction": "executar uma ação",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 5446b5a9eb..59adae71a0 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -2662,9 +2662,7 @@"server.mcp.card.cleared": "d161202e56397fcf8c80df6a1b6020801a3d1a2e8eda2e8e593e96c88230b43f","server.mcp.card.usedBy": "cd9bc7ed73f73d4299ac83758c2c11c9c94d7a3bb263d9cf19f11303a89fe809","server.mcp.card.usedByNone": "e92c1c2ed4fcbb0ce6cbae06883d6a9a65bbc78eef599ee8419da6be826f502c",- "server.cloudReset.title": "14ae704c302b4d1f0cf94b614c6a7b6c892357dd877aa182e2474934f92b8252",- "server.cloudReset.what": "2f901af1e4d8be98a234e5392bf9384ed53d65d24a27015d87178c5e5be23b26",- "server.cloudReset.resetting": "597df4ff607d90ba995ba3a6406f224813211de4805d085989273e04dd533538",+ "server.cloudReset.resetting": "d5fe13cf48183df5189b02ae39d5c6e0284f869dd0bf87e965462dded78251af","server.cloudReset.waiting": "9c9d4b3784d64dd5ae8106c9587561ad928a7fc1d2c46830a2b80db5a95d4611","server.cloudReset.done": "27e4089cf08c6d6097f59d79515c7da826cf3e1cff34e03d76cb8f0cbfa161fd","server.cloudReset.pending": "cae5248026f571c7a73a8b7319a8ae7b276ebd6b2ed3615572086f0e9b2ca36d",@@ -3956,8 +3954,7 @@"backup.importAction": "ea94509e38cf6d6427db3a1b5a3b5816cba1e8f89b08f9739f6077ade188163c","computer.reset.button": "196d09c7f7dc0290cc84c7a01347ae3f9a50067925490e7a0b9e262fa2add7f7","computer.reset.confirm": "49ee8910d29a1da38e3b3dd2518685d77c45bd5fbb248f44566c2d7b721765f9",- "computer.reset.pending": "cae5248026f571c7a73a8b7319a8ae7b276ebd6b2ed3615572086f0e9b2ca36d",- "approval.tool.resetCloudComputer": "c977d1d3b7504d9176231a7d8a521f553f5347292f3ccaa13857d1b1d5214f7f"+ "computer.reset.pending": "cae5248026f571c7a73a8b7319a8ae7b276ebd6b2ed3615572086f0e9b2ca36d"},"es": {"whop.description": "1a07cf04ef17029448d3781415cbac16d54e66b821907a40d94e0e6349710e70",@@ -36528,10 +36525,7 @@"settings.logins.onePassword.useVaultChoice": "a14647f6e4b5a8dbbb97d8fbd70814f8d93c2debf7c85fade4e8988fb4bf31ee","botPanel.advanced.title": "d823803689ad1713989d7cd80dde661392f93c2a6a5690e748ab88ed10c98237","botPanel.advanced.hint": "434ef07a7c8eafd2789a2fc936f8d050b62d7658d6777b0494db07e3c7d6294f",- "approval.tool.resetCloudComputer": "c977d1d3b7504d9176231a7d8a521f553f5347292f3ccaa13857d1b1d5214f7f",- "server.cloudReset.title": "14ae704c302b4d1f0cf94b614c6a7b6c892357dd877aa182e2474934f92b8252",- "server.cloudReset.what": "2f901af1e4d8be98a234e5392bf9384ed53d65d24a27015d87178c5e5be23b26",- "server.cloudReset.resetting": "597df4ff607d90ba995ba3a6406f224813211de4805d085989273e04dd533538",+ "server.cloudReset.resetting": "d5fe13cf48183df5189b02ae39d5c6e0284f869dd0bf87e965462dded78251af","server.cloudReset.waiting": "9c9d4b3784d64dd5ae8106c9587561ad928a7fc1d2c46830a2b80db5a95d4611","server.cloudReset.done": "27e4089cf08c6d6097f59d79515c7da826cf3e1cff34e03d76cb8f0cbfa161fd","server.cloudReset.pending": "cae5248026f571c7a73a8b7319a8ae7b276ebd6b2ed3615572086f0e9b2ca36d",