Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Replace a cloud computer that is dead at the provider or stops answering (#5640)
Milind Soniee89b889c97f
diff --git a/server/boat-health.test.ts b/server/boat-health.test.tsnew file mode 100644index 0000000000..9b871ebadb--- /dev/null+++ b/server/boat-health.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it } from "vitest";+import { createBoatHealth, DEAD_COMPUTER, unansweredStatus } from "./boat-health.ts";++const clock = () => {+ let at = 1_000_000;+ return { now: () => at, advance: (ms: number) => { at += ms; } };+};+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++describe("cloud computer health", () => {+ it("counts only gateway failures as no answer, never the relay's account-wide 503", () => {+ expect([502, 504, 522, 524].map(unansweredStatus)).toEqual([true, true, true, true]);+ expect([200, 400, 404, 409, 429, 500, 503].map(unansweredStatus)).toEqual([false, false, false, false, false, false, false]);+ });++ it("one failed command only starts a probe, and a probe that answers clears it", async () => {+ const time = clock(), health = createBoatHealth(time.now);+ const heard: string[] = [];+ health.onNotResponding((boxId) => heard.push(boxId));+ let probes = 0;+ health.suspect("bx_a", async () => { probes += 1; return true; });+ await settle();+ expect(probes).toBe(1);+ expect(health.notRespondingSince("bx_a")).toBeNull();+ expect(health.answeredWithin("bx_a", 1_000)).toBe(true);+ expect(heard).toEqual([]);+ });++ it("a probe the provider refused counts neither way", async () => {+ const time = clock(), health = createBoatHealth(time.now);+ health.unanswered("bx_a");+ health.suspect("bx_a", async () => null);+ await settle();+ expect(health.answeredWithin("bx_a", 60_000)).toBe(false);+ time.advance(30_000);+ health.unanswered("bx_a");+ time.advance(31_000);+ health.unanswered("bx_a");+ expect(health.notRespondingSince("bx_a")).not.toBeNull();+ });++ it("remembers when a person last opened a computer's desktop", () => {+ const time = clock(), health = createBoatHealth(time.now);+ health.personUsed("bx_a");+ time.advance(DEAD_COMPUTER.personGraceMs);+ expect(health.personUsedWithin("bx_a", DEAD_COMPUTER.personGraceMs)).toBe(true);+ time.advance(1);+ expect(health.personUsedWithin("bx_a", DEAD_COMPUTER.personGraceMs)).toBe(false);+ });++ it("probes at most once per gap however many commands fail", async () => {+ const time = clock(), health = createBoatHealth(time.now);+ let probes = 0;+ const probe = async () => { probes += 1; return false; };+ for (let i = 0; i < 10; i++) health.suspect("bx_a", probe);+ await settle();+ expect(probes).toBe(1);+ time.advance(DEAD_COMPUTER.probeGapMs - 1);+ health.suspect("bx_a", probe);+ await settle();+ expect(probes).toBe(1);+ time.advance(1);+ health.suspect("bx_a", probe);+ await settle();+ expect(probes).toBe(2);+ });++ it("three probes with no answer inside a minute are not yet a dead computer", () => {+ const time = clock(), health = createBoatHealth(time.now);+ const heard: string[] = [];+ health.onNotResponding((boxId) => heard.push(boxId));+ for (let i = 0; i < 5; i++) { health.unanswered("bx_a"); time.advance(10_000); }+ expect(health.notRespondingSince("bx_a")).toBeNull();+ expect(heard).toEqual([]);+ });++ it("three probes with no answer over a minute or more mark it not responding, reported once per gap", () => {+ const time = clock(), health = createBoatHealth(time.now);+ const heard: Array<[string, number]> = [];+ health.onNotResponding((boxId, since) => heard.push([boxId, since]));+ const first = time.now();+ health.unanswered("bx_a");+ time.advance(30_000);+ health.unanswered("bx_a");+ time.advance(30_000);+ health.unanswered("bx_a");+ expect(health.notRespondingSince("bx_a")).toBe(first);+ expect(heard).toEqual([["bx_a", first]]);+ time.advance(30_000);+ health.unanswered("bx_a");+ expect(heard).toHaveLength(1);+ time.advance(DEAD_COMPUTER.reportGapMs);+ health.unanswered("bx_a");+ expect(heard).toHaveLength(2);+ });++ it("an answer in between starts the count again", () => {+ const time = clock(), health = createBoatHealth(time.now);+ health.unanswered("bx_a");+ time.advance(40_000);+ health.unanswered("bx_a");+ health.answered("bx_a");+ time.advance(40_000);+ health.unanswered("bx_a");+ expect(health.notRespondingSince("bx_a")).toBeNull();+ });++ it("knows whether another computer answered recently", () => {+ const time = clock(), health = createBoatHealth(time.now);+ health.answered("bx_a");+ expect(health.otherAnsweredWithin("bx_a", DEAD_COMPUTER.witnessMs)).toBe(false);+ health.answered("bx_b");+ expect(health.otherAnsweredWithin("bx_a", DEAD_COMPUTER.witnessMs)).toBe(true);+ time.advance(DEAD_COMPUTER.witnessMs + 1);+ expect(health.otherAnsweredWithin("bx_a", DEAD_COMPUTER.witnessMs)).toBe(false);+ });+});diff --git a/server/boat-health.ts b/server/boat-health.tsnew file mode 100644index 0000000000..7ee7a3a09e--- /dev/null+++ b/server/boat-health.ts@@ -0,0 +1,124 @@+/** Whether each cloud computer still answers its commands. A failed command is only a suspicion: it starts one short probe,+ * and only probes count, so a command that itself runs long, or one slow answer, never marks a computer dead. */+export const DEAD_COMPUTER = {+ /** Probes in a row that got no answer (a gateway error or no reply at all). */+ failures: 3,+ /** From the first such probe to the last: a burst of failures inside one minute is a blip, not a dead machine. */+ spanMs: 60_000,+ /** Probes are at least this far apart, however many commands fail. */+ probeGapMs: 20_000,+ /** A probe runs `true`; a live machine answers it in well under a second. */+ probeTimeoutMs: 45_000,+ /** Not responding for this long, with a restart already tried, before the computer is replaced. */+ replaceAfterMs: 10 * 60_000,+ /** A computer that answered any command this recently is never deleted. */+ answeredGraceMs: 5 * 60_000,+ /** Another computer of this installation answered this recently: the provider itself is up. */+ witnessMs: 10 * 60_000,+ /** At most this many automatic replacements per computer owner in an hour; after that it stops and says so. */+ replacementsPerHour: 1,+ /** And at most this many automatic deletes per installation in an hour, whoever's computers they are. */+ installationDeletesPerHour: 1,+ /** The provider's `error` must be seen on two reads at least this far apart before a computer is deleted for it. */+ deadConfirmMs: process.env.OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS?.trim() ? Math.max(0, Number(process.env.OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS) || 0) : 30 * 60_000,+ /** At most one automatic restart per installation in this long. */+ restartGapMs: 10 * 60_000,+ /** No automatic restart or replacement while a person opened or drove the desktop this recently. */+ personGraceMs: 10 * 60_000,+ /** A computer still not answering is reported again at most this often. */+ reportGapMs: 5 * 60_000,+} as const;++/** 502 and 504 are a gateway that could not reach the machine, 520–524 the same behind a CDN. 503 is left out: the Cloud's+ * relay answers it for an account-wide refusal, which says nothing about one machine. */+export const unansweredStatus = (status: number): boolean => status === 502 || status === 504 || (status >= 520 && status <= 524);++interface BoxHealth {+ /** Probes in a row that got no answer, the first and last of them. */+ failures: number;+ firstFailureAt: number | null;+ lastFailureAt: number | null;+ lastAnsweredAt: number | null;+ probing: boolean;+ lastProbeAt: number;+ reportedAt: number | null;+ personAt: number | null;+}++export type NotRespondingListener = (boxId: string, since: number) => void;++export function createBoatHealth(now: () => number = Date.now) {+ const boxes = new Map<string, BoxHealth>();+ const listeners = new Set<NotRespondingListener>();+ const entry = (boxId: string): BoxHealth => {+ let found = boxes.get(boxId);+ if (!found) boxes.set(boxId, found = { failures: 0, firstFailureAt: null, lastFailureAt: null, lastAnsweredAt: null, probing: false, lastProbeAt: -Infinity, reportedAt: null, personAt: null });+ return found;+ };+ const notResponding = (health: BoxHealth | undefined): health is BoxHealth & { firstFailureAt: number; lastFailureAt: number } =>+ Boolean(health && health.failures >= DEAD_COMPUTER.failures && health.firstFailureAt !== null && health.lastFailureAt !== null+ && health.lastFailureAt - health.firstFailureAt >= DEAD_COMPUTER.spanMs);++ function answered(boxId: string): void {+ const health = entry(boxId);+ Object.assign(health, { failures: 0, firstFailureAt: null, lastFailureAt: null, lastAnsweredAt: now(), reportedAt: null });+ }++ function unanswered(boxId: string): void {+ const health = entry(boxId), at = now();+ health.failures += 1;+ health.firstFailureAt ??= at;+ health.lastFailureAt = at;+ if (!notResponding(health) || (health.reportedAt !== null && at - health.reportedAt < DEAD_COMPUTER.reportGapMs)) return;+ health.reportedAt = at;+ for (const listener of listeners) listener(boxId, health.firstFailureAt!);+ }++ /** A command to this computer got no answer: probe it once, unless a probe is under way or ran moments ago. A probe's+ * null (refused, say, by a rate limit) counts neither way. */+ function suspect(boxId: string, probe: () => Promise<boolean | null>): void {+ const health = entry(boxId);+ if (health.probing || now() - health.lastProbeAt < DEAD_COMPUTER.probeGapMs) return;+ health.probing = true;+ health.lastProbeAt = now();+ void probe().catch(() => false).then((ok) => {+ health.probing = false;+ if (boxes.get(boxId) !== health || ok === null) return;+ if (ok) answered(boxId); else unanswered(boxId);+ });+ }++ return {+ answered,+ unanswered,+ suspect,+ /** Since when this computer has not answered, once it counts as not responding; null while it answers. */+ notRespondingSince: (boxId: string): number | null => {+ const health = boxes.get(boxId);+ return notResponding(health) ? health.firstFailureAt : null;+ },+ answeredWithin: (boxId: string, ms: number): boolean => {+ const at = boxes.get(boxId)?.lastAnsweredAt;+ return at !== null && at !== undefined && now() - at <= ms;+ },+ /** Some other computer answered recently, so the provider and the path to it work. */+ otherAnsweredWithin: (boxId: string, ms: number): boolean =>+ [...boxes].some(([id, health]) => id !== boxId && health.lastAnsweredAt !== null && now() - health.lastAnsweredAt <= ms),+ /** A person opened this computer's desktop. */+ personUsed: (boxId: string) => { entry(boxId).personAt = now(); },+ personUsedWithin: (boxId: string, ms: number): boolean => {+ const at = boxes.get(boxId)?.personAt;+ return at !== null && at !== undefined && now() - at <= ms;+ },+ onNotResponding(listener: NotRespondingListener): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ forget: (boxId: string) => { boxes.delete(boxId); },+ clear: () => boxes.clear(),+ };+}++export type BoatHealth = ReturnType<typeof createBoatHealth>;++export const boatHealth = createBoatHealth(() => Date.now());diff --git a/server/boat-recovery.test.ts b/server/boat-recovery.test.tsnew file mode 100644index 0000000000..2cac587c07--- /dev/null+++ b/server/boat-recovery.test.ts@@ -0,0 +1,647 @@+// A loopback stand-in for the Cloud's relay (the box dialect, as included cloud computers reach Boat) plays a computer+// whose machine is gone. No network, no real computer; the data folder is the test's own.+import { mkdtempSync, writeFileSync } from "node:fs";+import { createServer, type IncomingMessage, type Server } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { AppConfig } from "./config.ts";++type Box = { id: string; name: string; state: string; error?: string };+type Seen = { method: string; path: string; headers: IncomingMessage["headers"] };++const ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz";+let made = 0;+const newId = () => `bx_${String(made++).padStart(8, "0").split("").map((digit) => ALPHABET[Number(digit)]).join("")}`;+const opId = (boxId: string) => `bdop_${Buffer.from(boxId.padEnd(16, "x")).toString("hex").slice(0, 32)}`;++let server: Server;+let boxes: Box[] = [];+let requests: Seen[] = [];+let commandStatus = new Map<string, number>();+let boxReadStatus = new Map<string, number>();+let listStatus = 200;+let deleteCompletes = true;+let resumeAnswers = new Set<string>();+let deleteDelayMs = 0;+let autoOn = true;+const teamOwners = new Set<string>();+const watched = new Set<string>();+const deleteSpans: Array<{ boxId: string; start: number; end: number }> = [];+const pendingDeletes = new Set<string>();++const send = (res: import("node:http").ServerResponse, status: number, body: unknown) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+};++beforeAll(async () => {+ server = createServer((req, res) => {+ let raw = "";+ req.on("data", (chunk) => { raw += chunk; });+ req.on("end", () => {+ const url = new URL(req.url ?? "/", "http://relay.test");+ const path = url.pathname.replace(/^\/relay\/api\/box\/v1/, "");+ requests.push({ method: req.method ?? "GET", path, headers: req.headers });+ const body = raw ? JSON.parse(raw) : {};+ const method = req.method;+ if (path === "/boxes" && method === "GET") {+ if (listStatus !== 200) return send(res, listStatus, { ok: false, code: "upstream_unavailable", message: "Cloud computers could not be reached." });+ return send(res, 200, { ok: true, boxes, pageInfo: { nextCursor: null } });+ }+ if (path === "/boxes" && method === "POST") {+ const box = { id: newId(), name: "", state: "ready" };+ boxes.push(box);+ return send(res, 200, { ok: true, box });+ }+ const operation = /^\/deletion-operations\/([^/]+)$/.exec(path);+ if (operation && method === "GET") {+ const target = [...pendingDeletes].find((id) => opId(id) === operation[1]);+ const status = target && !deleteCompletes ? "pending" : "completed";+ if (target && status === "completed") { pendingDeletes.delete(target); boxes = boxes.filter((box) => box.id !== target); }+ return send(res, 200, { ok: true, operation: { id: operation[1], kind: "box", targetId: target ?? "", status } });+ }+ const match = /^\/boxes\/([^/]+)(?:\/(stop|resume|commands|desktop))?$/.exec(path);+ const box = match ? boxes.find((candidate) => candidate.id === match[1]) : undefined;+ if (!match || !box) return send(res, 404, { ok: false, code: "not_found", message: "That cloud computer does not exist." });+ const action = match[2];+ if (!action && method === "GET") {+ const status = boxReadStatus.get(box.id) ?? 200;+ return status === 200 ? send(res, 200, { ok: true, box }) : send(res, status, { ok: false, code: "upstream_unavailable" });+ }+ if (!action && method === "PATCH") { box.name = body.name; return send(res, 200, { ok: true, box }); }+ if (!action && method === "DELETE") {+ if (req.headers["x-ascii-confirm-delete"] !== box.id) return send(res, 409, { ok: false, code: "confirmation_required" });+ const start = Date.now();+ setTimeout(() => {+ if (deleteCompletes) boxes = boxes.filter((candidate) => candidate.id !== box.id);+ else pendingDeletes.add(box.id);+ deleteSpans.push({ boxId: box.id, start, end: Date.now() });+ send(res, 202, { ok: true, operation: { id: opId(box.id), kind: "box", targetId: box.id, status: deleteCompletes ? "completed" : "pending" } });+ }, deleteDelayMs);+ return;+ }+ if (action === "stop") { box.state = "archived"; return send(res, 200, { ok: true, box }); }+ if (action === "resume") {+ box.state = "ready";+ if (resumeAnswers.has(box.id)) commandStatus.delete(box.id);+ return send(res, 200, { ok: true, box });+ }+ if (action === "commands") {+ const status = commandStatus.get(box.id) ?? 200;+ // The relay's answer when Boat's gateway cannot reach the machine.+ return status === 200 ? send(res, 200, { exitCode: 0, stdout: "captured", stderr: "" })+ : send(res, status, { ok: false, code: "upstream_unavailable", message: "Cloud computers could not be reached. Try again in a minute." });+ }+ if (action === "desktop") return send(res, 200, { desktopUrl: "https://desktop.test/view" });+ return send(res, 404, { ok: false });+ });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const { port } = server.address() as { port: number };+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `http://127.0.0.1:${port}/relay/api/box/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", "box_omb_synthetic");+});+afterAll(async () => {+ vi.unstubAllEnvs();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+});++const cfg = {} as AppConfig;+let boat: typeof import("./boat.ts");+let recoveryModule: typeof import("./boat-recovery.ts");+let healthModule: typeof import("./boat-health.ts");+let words: typeof import("../shared/cloud-computer-recovery.ts");+let journal: typeof import("./boat-delete-journal.ts");+let at = 10_000_000;+const now = () => at;+let told: Array<[string, string]>;+let recovery: import("./boat-recovery.ts").BoatRecovery;+let health: import("./boat-health.ts").BoatHealth;+let file: string;++async function load() {+ vi.resetModules();+ boat = await import("./boat.ts");+ recoveryModule = await import("./boat-recovery.ts");+ healthModule = await import("./boat-health.ts");+ words = await import("../shared/cloud-computer-recovery.ts");+ journal = await import("./boat-delete-journal.ts");+}+function start() {+ told = [];+ health = healthModule.createBoatHealth(now);+ recovery = recoveryModule.createBoatRecovery({ cfg: () => cfg, tell: (owner, line) => told.push([owner, line]), log: () => {}, file, now, health, pollMs: 5,+ autoReplace: () => autoOn, eligible: (owner) => !teamOwners.has(owner), personActive: (owner) => watched.has(owner) });+}++beforeEach(async () => {+ boxes = []; requests = []; commandStatus = new Map(); boxReadStatus = new Map(); listStatus = 200; deleteCompletes = true; resumeAnswers = new Set();+ pendingDeletes.clear();+ deleteDelayMs = 0; autoOn = true; deleteSpans.length = 0; teamOwners.clear(); watched.clear();+ at += 24 * 60 * 60_000;+ file = join(mkdtempSync(join(tmpdir(), "omb-repl-")), "boat-replacements.json");+ await load();+ start();+});+afterEach(() => recovery.close());++let bots = 0;+async function botWith(state: string, extra: Partial<Box> = {}) {+ const botId = `bot-dead-${bots++}`;+ const box = { id: newId(), name: await boat.boatNameFor(botId), state, ...extra };+ boxes.push(box);+ return { botId, box };+}+/** As a turn's start does: provision, then look the computer up. */+const provisioned = async (botId: string) => {+ const created = await boat.provisionBoat(cfg, botId, "Bot");+ await boat.findBoat(cfg, botId);+ return created;+};+const deletes = () => requests.filter((request) => request.method === "DELETE");+const until = async (check: () => boolean, ms = 20_000) => {+ for (const end = Date.now() + ms; Date.now() < end; await new Promise((resolve) => setTimeout(resolve, 20))) if (check()) return;+ throw new Error("timed out");+};+/** Three probes with no answer over more than ten minutes, as the health check records them. */+const stopsAnswering = (boxId: string) => {+ health.unanswered(boxId);+ at += 30_000;+ health.unanswered(boxId);+ at += 11 * 60_000;+ health.unanswered(boxId);+};++const stops = () => requests.filter((request) => request.method === "POST" && request.path.endsWith("/stop"));+const DEAD_CONFIRM = 31 * 60_000;+/** The provider's `error` must be read twice, half an hour apart, before the computer is deleted by itself. */+async function deadTwice(botId: string) {+ const before = deletes().length;+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_DEAD_WAITING);+ expect(deletes()).toHaveLength(before);+ at += DEAD_CONFIRM;+}++describe("a cloud computer the provider reports in error", () => {+ it("is never shown or used as ready, is replaced once it stays in error, and the bot and the person are told once", async () => {+ const { botId, box } = await botWith("error", { error: "machine unreachable: 278 consecutive /health failures" });+ expect(await boat.findBoat(cfg, botId)).toBeNull();+ expect(boat.deadBoatOf(botId)).toEqual({ boxId: box.id, name: box.name });+ expect(boat.boatTurnLifecycleAction("error")).toBe("provision");+ expect((await boat.boatStatus(cfg, botId)).box).toBeNull();+ await expect(boat.joinBoat(cfg, botId)).rejects.toThrow(/no computer yet/);++ await deadTwice(botId);+ expect(told).toEqual([[botId, "needsPerson"]]);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(deletes()).toHaveLength(1);+ expect(deletes()[0]!.headers["x-ascii-confirm-delete"]).toBe(box.id);+ expect(told).toEqual([[botId, "needsPerson"], [botId, "replaced"]]);+ expect(recovery.status(botId)?.state).toBe("replaced");++ const created = await provisioned(botId);+ expect(created.boxId).not.toBe(box.id);+ expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED);+ expect(recovery.notice(created.boxId)).toBeNull();+ expect(told).toHaveLength(2);+ expect(deletes()).toHaveLength(1);+ });++ it("is not deleted while the provider's list fails", async () => {+ const { botId } = await botWith("error");+ await boat.findBoat(cfg, botId);+ await deadTwice(botId);+ listStatus = 502;+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow();+ expect(deletes()).toHaveLength(0);+ });++ it("is kept when it answered a command moments ago", async () => {+ const { botId, box } = await botWith("error");+ await boat.findBoat(cfg, botId);+ health.answered(box.id);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NOT_RESPONDING);+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([]);+ });++ it("is replaced at most once an hour per bot, then left and said so", async () => {+ const { botId } = await botWith("error");+ await boat.findBoat(cfg, botId);+ await deadTwice(botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ const second = await provisioned(botId);+ boxes.find((box) => box.id === second.boxId)!.state = "error";+ at += 60_000;+ expect(await boat.findBoat(cfg, botId)).toBeNull();+ await deadTwice(botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(/at most once an hour/);+ expect(deletes()).toHaveLength(1);+ expect(told.filter(([, line]) => line === "capped")).toHaveLength(1);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(/at most once an hour/);+ expect(told.filter(([, line]) => line === "capped")).toHaveLength(1);++ at += 30 * 60_000;+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(deletes()).toHaveLength(2);+ });++ it("is deleted by itself at most once an hour for the whole installation, whoever's computer it is", async () => {+ const first = await botWith("error");+ const second = await botWith("error");+ await boat.findBoat(cfg, first.botId);+ await boat.findBoat(cfg, second.botId);+ await expect(boat.provisionBoat(cfg, first.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_DEAD_WAITING);+ await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_DEAD_WAITING);+ at += DEAD_CONFIRM;+ await expect(boat.provisionBoat(cfg, first.botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON);+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([first.box.id]);+ at += 61 * 60_000;+ await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(deletes()).toHaveLength(2);+ });++ it("finishes after a crash between the delete and the new computer, telling each side once", async () => {+ deleteCompletes = false;+ const { botId, box } = await botWith("error");+ await boat.findBoat(cfg, botId);+ await deadTwice(botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETING });+ expect(told).toEqual([[botId, "needsPerson"], [botId, "replaced"]]);++ recovery.close();+ await load();+ start();+ deleteCompletes = true;+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ const created = await provisioned(botId);+ expect(created.boxId).not.toBe(box.id);+ expect(deletes()).toHaveLength(1);+ expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED);+ expect(told).toEqual([]);+ });++ it("keeps every guard for a replacement recorded before its delete was sent, without counting it twice", async () => {+ const { botId, box } = await botWith("error");+ writeFileSync(file, JSON.stringify([{ owner: botId, boxId: box.id, at: now() - 60_000 }]));+ recovery.close();+ start();+ await boat.findBoat(cfg, botId);+ await deadTwice(botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(deletes()).toHaveLength(1);+ const created = await provisioned(botId);+ expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED);+ });+});++describe("a cloud computer that says it is ready but does not answer", () => {+ it("is restarted first, then replaced while another computer answers, and calls to it are refused meanwhile", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ expect(recovery.refusal(box.id, "before")).toBe(words.CLOUD_COMPUTER_NOT_RESPONDING);+ await until(() => recovery.status(botId)?.state === "replaced");+ const order = requests.filter((request) => request.path.startsWith(`/boxes/${box.id}`)).map((request) => `${request.method} ${request.path.replace(`/boxes/${box.id}`, "") || "/"}`);+ expect(order.indexOf("POST /commands")).toBeLessThan(order.indexOf("POST /stop"));+ expect(order.indexOf("POST /resume")).toBeGreaterThan(order.indexOf("POST /stop"));+ expect(order.indexOf("DELETE /")).toBeGreaterThan(order.indexOf("POST /resume"));+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);+ expect(told).toEqual([[botId, "replaced"]]);+ expect(recovery.refusal(box.id, "before")).toBe(words.CLOUD_COMPUTER_NOT_RESPONDING);+ expect(boxes.some((candidate) => candidate.id === witness.box.id)).toBe(true);+ });++ it("is kept when the restart brings it back, and the bot hears that once", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ resumeAnswers.add(box.id);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "restarted");+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([[botId, "restarted"]]);+ expect(recovery.notice(box.id)).toBe(words.CLOUD_COMPUTER_RESTARTED);+ expect(recovery.notice(box.id)).toBeNull();+ expect(recovery.refusal(box.id, "before")).toBeNull();+ expect(recovery.stuck(botId)).toBe(false);+ });++ it("is not stopped when a fresh probe answers: three failed probes may have been this home's own outage", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId) === null && requests.some((request) => request.path === `/boxes/${box.id}/commands`));+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ });++ it("is neither restarted nor deleted when no other computer answers: it waits for the person", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([[botId, "needsPerson"]]);+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NEEDS_PERSON);+ expect(recovery.refusal(box.id, "before")).toBeNull();+ expect(recovery.stuck(botId)).toBe(true);+ });++ it("is neither restarted nor deleted while the provider's list fails", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ listStatus = 502;+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "unreachable");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_UNREACHABLE);+ });++ it("is left alone, not even restarted, while the provider cannot say what it is", async () => {+ const { botId, box } = await botWith("ready");+ await boat.findBoat(cfg, botId);+ boxReadStatus.set(box.id, 502);+ stopsAnswering(box.id);+ await until(() => recovery.status(botId)?.state === "unreachable");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ });++ it("is not restarted or deleted while a person has its desktop open or used it in the last ten minutes", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ watched.add(botId);+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);++ const other = await botWith("ready");+ commandStatus.set(other.box.id, 502);+ await boat.findBoat(cfg, other.botId);+ stopsAnswering(other.box.id);+ health.personUsed(other.box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(other.botId)?.state === "needs-person");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ });++ it("restarts at most one computer of the installation by itself in ten minutes", async () => {+ const first = await botWith("ready");+ const second = await botWith("ready");+ const witness = await botWith("ready");+ for (const { botId, box } of [first, second]) { commandStatus.set(box.id, 502); await boat.findBoat(cfg, botId); }+ for (const box of [first.box, second.box]) health.unanswered(box.id);+ at += 30_000;+ for (const box of [first.box, second.box]) health.unanswered(box.id);+ at += 11 * 60_000;+ health.answered(witness.box.id);+ for (const box of [first.box, second.box]) health.unanswered(box.id);+ const settled = (botId: string) => ["needs-person", "replaced", "capped"].includes(recovery.status(botId)?.state ?? "");+ await until(() => settled(first.botId) && settled(second.botId));+ expect(stops()).toHaveLength(1);+ });++ it("is replaced only once the provider's error is seen twice half an hour apart, and without a restart", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ await boat.findBoat(cfg, botId);+ box.state = "error";+ stopsAnswering(box.id);+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(deletes()).toHaveLength(0);+ at += DEAD_CONFIRM;+ health.answered(witness.box.id);+ health.unanswered(box.id);+ await until(() => recovery.status(botId)?.state === "replaced");+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(1);+ });+});++describe("a team's shared cloud computer", () => {+ for (const on of [false, true]) {+ it(`is never stopped or deleted by itself, with automatic replacement ${on ? "on" : "off"}`, async () => {+ autoOn = on;+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ teamOwners.add(botId);+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(recovery.status(botId)?.state).toBe("needs-person");+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_TEAM_NOT_RESPONDING);++ box.state = "error";+ expect(await boat.findBoat(cfg, botId)).toBeNull();+ at += DEAD_CONFIRM;+ for (let i = 0; i < 2; i++) await expect(boat.provisionBoat(cfg, botId, "Team")).rejects.toThrow(words.CLOUD_COMPUTER_TEAM_NOT_RESPONDING);+ expect(stops()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([[botId, "teamNotResponding"]]);+ });+ }+});++describe("what counts as an answer", () => {+ it("is only the computer's own: a refusal neither answers nor fails, so it never stands witness", async () => {+ const { box } = await botWith("ready");+ const other = await botWith("ready");+ commandStatus.set(other.box.id, 409);+ const refused = await boat.runCommand(cfg, other.box.id, "true");+ expect(refused.unanswered).toBeUndefined();+ expect(healthModule.boatHealth.answeredWithin(other.box.id, 60_000)).toBe(false);+ expect(healthModule.boatHealth.otherAnsweredWithin(box.id, 60_000)).toBe(false);+ expect(await boat.probeBoat(cfg, other.box.id)).toBeNull();+ commandStatus.delete(other.box.id);+ await boat.runCommand(cfg, other.box.id, "true");+ expect(healthModule.boatHealth.otherAnsweredWithin(box.id, 60_000)).toBe(true);+ });+});++describe("the desktop link", () => {+ it("still opens while a computer is marked not responding, so the person can save files first", async () => {+ const { botId, box } = await botWith("ready");+ await boat.findBoat(cfg, botId);+ const realNow = Date.now();+ const clock = vi.spyOn(Date, "now");+ try {+ for (const offset of [0, 30_000, 70_000]) { clock.mockReturnValue(realNow + offset); healthModule.boatHealth.unanswered(box.id); }+ } finally { clock.mockRestore(); }+ expect(healthModule.boatHealth.notRespondingSince(box.id)).not.toBeNull();+ expect((await boat.joinReadyBoat(cfg, botId)).joinUrl).toBe("https://desktop.test/view");+ });+});++describe("one failed command", () => {+ it("changes nothing: the next call goes through and nothing is restarted or deleted", async () => {+ const { botId, box } = await botWith("ready");+ await boat.findBoat(cfg, botId);+ commandStatus.set(box.id, 502);+ const out = await boat.runCommand(cfg, box.id, "xdotool getdisplaygeometry");+ expect(out).toMatchObject({ ok: false, unanswered: true });+ commandStatus.delete(box.id);+ await until(() => requests.filter((request) => request.path.endsWith("/commands")).length >= 2);+ expect(recovery.status(botId)).toBeNull();+ expect(recovery.refusal(box.id, "before")).toBeNull();+ expect(requests.some((request) => request.path.endsWith("/stop") || request.method === "DELETE")).toBe(false);+ expect(healthModule.boatHealth.notRespondingSince(box.id)).toBeNull();+ });+});++describe("the computer panel's Restart computer and Replace computer", () => {+ it("restart stops and starts the computer and reports that it answers", async () => {+ const { botId, box } = await botWith("ready");+ expect(await recovery.restart(botId)).toEqual({ answers: true });+ expect(requests.map((request) => `${request.method} ${request.path}`)).toEqual(expect.arrayContaining([`POST /boxes/${box.id}/stop`, `POST /boxes/${box.id}/resume`]));+ expect(recovery.status(botId)).toMatchObject({ state: "restarted", manual: true });+ expect(told).toEqual([]);+ });++ it("restart says when the computer still does not answer, and deletes nothing", async () => {+ const { botId, box } = await botWith("ready");+ commandStatus.set(box.id, 502);+ expect(await recovery.restart(botId)).toEqual({ answers: false });+ expect(deletes()).toHaveLength(0);+ });++ it("refuses to restart a computer the provider reports in error", async () => {+ const { botId } = await botWith("error");+ await expect(recovery.restart(botId)).rejects.toThrow(/replace it instead/);+ });++ it("replace deletes through the same path, needs no hourly allowance, and the bot hears it was the person's", async () => {+ const { botId, box } = await botWith("ready");+ expect(await recovery.replace(botId)).toEqual({ replaced: true });+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);+ expect(recovery.status(botId)).toMatchObject({ state: "replaced", manual: true });+ expect(told).toEqual([]);+ const created = await provisioned(botId);+ expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED_BY_PERSON);+ expect(await recovery.replace(botId)).toEqual({ replaced: true });+ expect(deletes()).toHaveLength(2);+ });++ it("replace also takes a computer the provider reports in error", async () => {+ const { botId, box } = await botWith("error");+ expect(await recovery.replace(botId)).toEqual({ replaced: true });+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);+ });+});++describe("a start the Admin refuses right after a replacement", () => {+ it("tells the bot the computer is being replaced, not that the plan is full", async () => {+ const { botId } = await botWith("ready");+ await recovery.replace(botId);+ const refusal = boat.boatRefusal(429, "boat create", { ok: false, code: "limit_reached", reason: "at_once", limit: 1, used: 1 }, true);+ expect(recovery.claimSentence(botId, refusal)).toBe(words.CLOUD_COMPUTER_NOT_RESPONDING);+ expect(recovery.claimSentence("another-bot", refusal)).toBeUndefined();+ });+});++describe("with automatic replacement off, the default", () => {+ beforeEach(() => { autoOn = false; });++ it("is off unless the environment or config.json turns it on, and the environment wins", () => {+ const on = recoveryModule.cloudComputerAutoReplace;+ expect(on({}, {})).toBe(false);+ expect(on({ features: { cloudComputerAutoReplace: true } }, {})).toBe(true);+ expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "1" })).toBe(true);+ expect(on({ features: { cloudComputerAutoReplace: true } }, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "0" })).toBe(false);+ expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "yes" })).toBe(false);+ });++ it("never deletes a computer the provider reports in error: the bot and the person hear it once", async () => {+ const { botId } = await botWith("error");+ await boat.findBoat(cfg, botId);+ for (let i = 0; i < 3; i++) { await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON); at += DEAD_CONFIRM; }+ expect(deletes()).toHaveLength(0);+ expect(requests.some((request) => request.method === "POST" && request.path === "/boxes")).toBe(false);+ expect(told).toEqual([[botId, "needsPerson"]]);+ expect(recovery.status(botId)?.state).toBe("needs-person");+ });++ it("still restarts a computer that stopped answering, but never deletes it after ten minutes", async () => {+ const { botId, box } = await botWith("ready");+ const witness = await botWith("ready");+ commandStatus.set(box.id, 502);+ await boat.findBoat(cfg, botId);+ stopsAnswering(box.id);+ health.answered(witness.box.id);+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(stops().map((request) => request.path)).toEqual([`/boxes/${box.id}/stop`]);+ expect(requests.some((request) => request.path === `/boxes/${box.id}/resume`)).toBe(true);+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([[botId, "needsPerson"]]);+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NEEDS_PERSON);+ expect(recovery.refusal(box.id, "before")).toBeNull();+ at += 6 * 60_000;+ health.answered(witness.box.id);+ health.unanswered(box.id);+ expect(recovery.status(botId)?.state).toBe("not-responding");+ await until(() => recovery.status(botId)?.state === "needs-person");+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([[botId, "needsPerson"]]);+ });++ it("does not reach the hourly limit either: nothing is deleted, so nothing is counted", async () => {+ const { botId } = await botWith("error");+ await boat.findBoat(cfg, botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON);+ at += 2 * 60 * 60_000;+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON);+ expect(deletes()).toHaveLength(0);+ expect(told.filter(([, line]) => line === "capped")).toEqual([]);+ });++ it("Replace computer still deletes it and the next start makes a new one", async () => {+ const { botId, box } = await botWith("error");+ await boat.findBoat(cfg, botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON);+ expect(await recovery.replace(botId)).toEqual({ replaced: true });+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);+ const created = await provisioned(botId);+ expect(created.boxId).not.toBe(box.id);+ expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED_BY_PERSON);+ });+});++describe("deletes from this installation", () => {+ it("are sent one at a time, whoever asks for them, with each one fenced on disk before it waits", async () => {+ deleteDelayMs = 300;+ const first = await botWith("ready");+ const second = await botWith("ready");+ await boat.findBoat(cfg, first.botId);+ await boat.findBoat(cfg, second.botId);+ const both = Promise.all([recovery.replace(first.botId), recovery.replace(second.botId)]);+ await until(() => deletes().length === 1);+ expect(journal.getBoatDeletion(second.box.id)).toBeTruthy();+ await both;+ expect(deleteSpans).toHaveLength(2);+ const [a, b] = deleteSpans;+ expect(b!.start).toBeGreaterThanOrEqual(a!.end);+ });+});diff --git a/server/boat-recovery.ts b/server/boat-recovery.tsnew file mode 100644index 0000000000..93e6a4cd5c--- /dev/null+++ b/server/boat-recovery.ts@@ -0,0 +1,418 @@+// A cloud computer that stopped answering: restarted once, then replaced (its deletion frees the plan's place, and the next+// use creates a new one), and the bot and the person are told once. Nothing here asks the person anything.+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { writeFileAtomic } from "./atomic.ts";+import * as boat from "./boat.ts";+import { BOAT_DELETING, BOAT_DELETION_FINISHED, getBoatDeletion } from "./boat-delete-journal.ts";+import { boatHealth, DEAD_COMPUTER, type BoatHealth } from "./boat-health.ts";+import { cloudFailureOf } from "./boat-limit.ts";+import { DATA_DIR, type AppConfig } from "./config.ts";+import {+ CLOUD_COMPUTER_CAPPED, CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_NOT_RESPONDING, CLOUD_COMPUTER_REPLACED,+ CLOUD_COMPUTER_REPLACED_BY_PERSON, CLOUD_COMPUTER_RESTARTED, CLOUD_COMPUTER_TEAM_NOT_RESPONDING, CLOUD_COMPUTER_UNREACHABLE, recoveryUnderWay,+ type CloudComputerPersonLine, type CloudComputerRecovery, type CloudComputerRecoveryState,+} from "../shared/cloud-computer-recovery.ts";++const HOUR_MS = 60 * 60_000;+const DAY_MS = 24 * HOUR_MS;+const KEPT_MS = DAY_MS;+const STOP_WAIT_MS = 90_000;+const WAKE_BUDGET_MS = 120_000;+const POLL_MS = 2_500;+/** A restart or replacement no longer running after this long has ended where the next start picks it up. */+const STALE_MS = 15 * 60_000;+const READY = new Set(["idle", "ready", "running"]);++/** One replacement, written before its delete is sent: a crash after it still counts against the hourly limit and still+ * owes the bot and the person their line. */+interface Replacement {+ owner: string;+ boxId: string;+ at: number;+ manual?: true;+ toldBot?: true;+ toldPerson?: true;+}++/** Whether a dead computer is deleted and replaced without the person. Off unless OMB_CLOUD_COMPUTER_AUTO_REPLACE is "1" or+ * config.json has `"features": {"cloudComputerAutoReplace": true}`; the environment, "1" or "0", wins. Off by default until+ * the provider confirms that deleting a computer whose host is unreachable is safe for the rest of the account. */+export function cloudComputerAutoReplace(cfg: Pick<AppConfig, "features">, env: NodeJS.ProcessEnv = process.env): boolean {+ const override = env.OMB_CLOUD_COMPUTER_AUTO_REPLACE?.trim();+ if (override === "1") return true;+ if (override === "0") return false;+ return cfg.features?.cloudComputerAutoReplace === true;+}++export interface BoatRecoveryDeps {+ cfg(): AppConfig;+ /** Posts the person's line: in a bot's chat and Inbox, or for a team's computer where its admins see it (the Team map). */+ tell(owner: string, line: CloudComputerPersonLine): void;+ changed?(owner: string): void;+ log(line: string): void;+ /** Only a bot's own computer is ever restarted or deleted by itself; a team's shared one is only reported. */+ eligible?(owner: string): boolean;+ /** A person is driving or viewing this owner's desktop now. */+ personActive?(owner: string): boolean;+ file?: string;+ now?: () => number;+ health?: BoatHealth;+ pollMs?: number;+ autoReplace?: () => boolean;+}++type Dead = { boxId: string; name: string };+type ReplaceOutcome = "confirmed" | "pending" | "kept" | "held" | "waiting" | "capped" | "failed";++export function createBoatRecovery(deps: BoatRecoveryDeps) {+ const health = deps.health ?? boatHealth;+ const now = deps.now ?? Date.now;+ const file = deps.file ?? join(DATA_DIR, "boat-replacements.json");+ const pollMs = deps.pollMs ?? POLL_MS;+ const autoReplace = deps.autoReplace ?? (() => cloudComputerAutoReplace(deps.cfg()));+ const eligible = (owner: string) => deps.eligible?.(owner) ?? true;+ const states = new Map<string, CloudComputerRecovery & { boxId: string }>();+ const lanes = new Map<string, Promise<unknown>>();+ const restarts = new Map<string, number>();+ const timers = new Map<string, ReturnType<typeof setTimeout>>();+ const retired = new Set<string>();+ /** Lines already told about a computer still not answering, so a long outage is reported once. */+ const told = new Map<string, Set<CloudComputerPersonLine>>();+ const restartedOwners = new Set<string>();+ const restartToldAt = new Map<string, number>();+ /** When the provider's `error` was first seen for each computer. */+ const errorSeen = new Map<string, number>();+ let lastAutoRestartAt = -Infinity;+ let closed = false;++ const load = (): Replacement[] => {+ try {+ const parsed = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : [];+ return Array.isArray(parsed) ? parsed.filter((entry): entry is Replacement => typeof entry?.owner === "string"+ && typeof entry.boxId === "string" && typeof entry.at === "number") : [];+ } catch {+ return [];+ }+ };+ let entries = load();+ const write = (next: Replacement[]) => {+ entries = next.filter((entry) => now() - entry.at < KEPT_MS);+ writeFileAtomic(file, JSON.stringify(entries));+ };+ const update = (boxId: string, patch: Partial<Replacement>) => write(entries.map((entry) => entry.boxId === boxId ? { ...entry, ...patch } : entry));++ const set = (owner: string, boxId: string, state: CloudComputerRecoveryState, manual = false) => {+ states.set(owner, { state, at: now(), boxId, ...(manual ? { manual: true as const } : {}) });+ deps.changed?.(owner);+ };+ const clear = (owner: string, boxId: string) => {+ told.delete(boxId);+ errorSeen.delete(boxId);+ if (states.get(owner)?.boxId !== boxId) return;+ states.delete(owner);+ deps.changed?.(owner);+ };+ const tellOnce = (owner: string, boxId: string, state: CloudComputerRecoveryState, line: CloudComputerPersonLine) => {+ set(owner, boxId, state);+ const lines = told.get(boxId) ?? new Set<CloudComputerPersonLine>();+ told.set(boxId, lines);+ if (lines.has(line)) return;+ lines.add(line);+ deps.tell(owner, line);+ };+ const needsPerson = (owner: string, boxId: string) =>+ tellOnce(owner, boxId, "needs-person", eligible(owner) ? "needsPerson" : "teamNotResponding");+ const personBusy = (owner: string, boxId: string) =>+ deps.personActive?.(owner) === true || health.personUsedWithin(boxId, DEAD_COMPUTER.personGraceMs);+ /** The provider's `error`, seen now: true once it was also seen at least DEAD_COMPUTER.deadConfirmMs earlier. */+ const deadConfirmed = (boxId: string) => {+ const first = errorSeen.get(boxId);+ if (first === undefined) errorSeen.set(boxId, now());+ return first !== undefined && now() - first >= DEAD_COMPUTER.deadConfirmMs;+ };++ /** One recovery at a time per owner, in the order asked. */+ function lane<T>(owner: string, work: () => Promise<T>): Promise<T> {+ const started = (lanes.get(owner) ?? Promise.resolve()).catch(() => undefined).then(work);+ const settled = started.finally(() => { if (lanes.get(owner) === settled) lanes.delete(owner); });+ lanes.set(owner, settled);+ return started;+ }++ const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++ async function restart(owner: string, boxId: string, manual = false): Promise<"answers" | "no-answer" | "refused"> {+ const cfg = deps.cfg();+ set(owner, boxId, "restarting", manual);+ restarts.set(boxId, now());+ try {+ const stopped = await boat.boatFetch(cfg, `/sandboxes/${boxId}/stop`, { method: "POST", signal: AbortSignal.timeout(30_000) });+ await stopped.body?.cancel().catch(() => undefined);+ if (!stopped.ok && stopped.status !== 409) return "refused";+ } catch {+ return "refused";+ }+ for (const deadline = Date.now() + STOP_WAIT_MS; Date.now() < deadline && !closed;) {+ const seen = await boat.inspectBoatIdentity(cfg, boxId);+ const state = seen.identity?.state;+ if (seen.available && (!seen.identity || state === "error" || (state && boat.SLEEPING_BOAT_STATES.has(state) && state !== "archiving"))) break;+ await wait(pollMs);+ }+ const woken = await boat.readyBoat(cfg, owner, WAKE_BUDGET_MS).catch(() => null);+ if (!woken || woken.id !== boxId) return "no-answer";+ if ((await boat.probeBoat(cfg, boxId)) !== true) return "no-answer";+ health.answered(boxId);+ return "answers";+ }++ const listWorks = async (cfg: AppConfig) => {+ try {+ const listed = await boat.boatFetch(cfg, "/sandboxes?limit=1", { signal: AbortSignal.timeout(20_000) });+ await listed.body?.cancel().catch(() => undefined);+ return listed.ok;+ } catch {+ return false;+ }+ };++ function unreachable(owner: string, boxId: string): void {+ tellOnce(owner, boxId, "unreachable", "unreachable");+ deps.log(`cloud computer ${owner}: ${boxId} is not responding, and the provider can't be shown to be up; nothing was deleted`);+ }++ /** `dead` is the provider's word that the machine is gone; otherwise this computer only stopped answering. */+ async function replace(owner: string, target: Dead, opts: { manual?: boolean; dead?: boolean } = {}): Promise<ReplaceOutcome> {+ const cfg = deps.cfg();+ const recorded = entries.find((entry) => entry.boxId === target.boxId);+ // Only a delete already fenced on disk is finished without asking again.+ const fenced = Boolean(recorded && getBoatDeletion(target.boxId));+ if (!opts.manual) {+ if (!eligible(owner)) { needsPerson(owner, target.boxId); return "held"; }+ if (!fenced && health.answeredWithin(target.boxId, DEAD_COMPUTER.answeredGraceMs)) { clear(owner, target.boxId); return "kept"; }+ if (!autoReplace()) {+ needsPerson(owner, target.boxId);+ deps.log(`cloud computer ${owner}: ${target.boxId} is ${opts.dead ? "dead" : "not responding"}; automatic replacement is off, so it waits for the person`);+ return "held";+ }+ if (!fenced) {+ if (personBusy(owner, target.boxId)) { needsPerson(owner, target.boxId); return "held"; }+ if (opts.dead && !deadConfirmed(target.boxId)) { needsPerson(owner, target.boxId); return "waiting"; }+ if (!(await listWorks(cfg))) { unreachable(owner, target.boxId); return "held"; }+ const automatic = entries.filter((entry) => !entry.manual && entry.boxId !== target.boxId && now() - entry.at < HOUR_MS);+ if (automatic.filter((entry) => entry.owner === owner).length >= DEAD_COMPUTER.replacementsPerHour) {+ tellOnce(owner, target.boxId, "capped", "capped");+ deps.log(`cloud computer ${owner}: ${target.boxId} was already replaced in the last hour; left as it is`);+ return "capped";+ }+ if (automatic.length >= DEAD_COMPUTER.installationDeletesPerHour) {+ needsPerson(owner, target.boxId);+ deps.log(`cloud computer ${owner}: ${target.boxId} left for the person: this installation already deleted a computer by itself in the last hour`);+ return "held";+ }+ }+ }+ set(owner, target.boxId, "replacing", opts.manual);+ if (!recorded) write([...entries, { owner, boxId: target.boxId, at: now(), ...(opts.manual ? { manual: true as const } : {}) }]);+ retired.add(target.boxId);+ let outcome: ReplaceOutcome;+ try {+ const deleted = await boat.requestRecordedBoatDeletion(cfg, { boxId: target.boxId, name: target.name, ownerBotId: owner });+ outcome = deleted === "confirmed" ? "confirmed" : "pending";+ } catch (error) {+ deps.log(`cloud computer ${owner}: deleting ${target.boxId} was not confirmed; its next start finishes it: ${error instanceof Error ? error.message : String(error)}`);+ outcome = "failed";+ }+ boat.forgetBoatId(target.boxId);+ health.forget(target.boxId);+ if (outcome === "failed") {+ if (!getBoatDeletion(target.boxId)) retired.delete(target.boxId);+ return outcome;+ }+ set(owner, target.boxId, "replaced", opts.manual);+ if (!opts.manual) {+ deps.tell(owner, "replaced");+ update(target.boxId, { toldPerson: true });+ }+ deps.log(`cloud computer ${owner}: replaced ${target.boxId} (${opts.manual ? "asked for" : opts.dead ? "the provider reports it in error" : "not responding"})`);+ return outcome;+ }++ /** A fresh probe that got no answer, with the provider's list working; null when that is not so (the outcome is reported). */+ async function stillDown(owner: string, boxId: string, cfg: AppConfig): Promise<boolean> {+ const probe = await boat.probeBoat(cfg, boxId);+ if (probe !== false) {+ if (probe) health.answered(boxId);+ clear(owner, boxId);+ return false;+ }+ if (!(await listWorks(cfg))) { unreachable(owner, boxId); return false; }+ // An installation whose other computers do not answer either cannot tell a dead machine from its own outage.+ if (!health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs)) { needsPerson(owner, boxId); return false; }+ return true;+ }++ /** After the restart: replaced once the provider says the machine is gone, or after DEAD_COMPUTER.replaceAfterMs of no+ * answers while another computer of this installation answers (else the provider itself may be down). */+ async function decide(owner: string, boxId: string): Promise<void> {+ timers.delete(owner);+ const cfg = deps.cfg();+ const since = health.notRespondingSince(boxId);+ const seen = await boat.inspectBoatIdentity(cfg, boxId);+ if (!seen.available) return unreachable(owner, boxId);+ if (!seen.identity || !(await boat.boatNameMatchesBot(owner, seen.identity.name))) return clear(owner, boxId);+ if (seen.identity.state === "error") return void await replace(owner, seen.identity, { dead: true });+ if (since === null || !READY.has(seen.identity.state)) return clear(owner, boxId);+ const left = since + DEAD_COMPUTER.replaceAfterMs - now();+ if (left > 0) {+ set(owner, boxId, "not-responding");+ const timer = setTimeout(() => void lane(owner, () => decide(owner, boxId)).catch((error) => deps.log(`cloud computer ${owner}: ${String(error)}`)), left);+ timer.unref?.();+ timers.set(owner, timer);+ return;+ }+ if (!(await stillDown(owner, boxId, cfg))) return;+ await replace(owner, seen.identity);+ }++ async function notResponding(owner: string, boxId: string): Promise<void> {+ const cfg = deps.cfg();+ set(owner, boxId, "not-responding");+ const seen = await boat.inspectBoatIdentity(cfg, boxId);+ if (!seen.available) return unreachable(owner, boxId);+ if (!seen.identity || !(await boat.boatNameMatchesBot(owner, seen.identity.name))) return clear(owner, boxId);+ if (seen.identity.state === "error") return void await replace(owner, seen.identity, { dead: true });+ if (!READY.has(seen.identity.state)) {+ health.forget(boxId);+ return clear(owner, boxId);+ }+ // Every guard before a stop: it closes the person's programs, and three failed probes can be this home's own outage.+ if (!(await stillDown(owner, boxId, cfg))) return;+ const lastRestart = restarts.get(boxId);+ if ((lastRestart === undefined || now() - lastRestart >= HOUR_MS) && now() - lastAutoRestartAt >= DEAD_COMPUTER.restartGapMs && !personBusy(owner, boxId)) {+ lastAutoRestartAt = now();+ const restarted = await restart(owner, boxId);+ if (restarted === "answers") {+ set(owner, boxId, "restarted");+ told.delete(boxId);+ if (now() - (restartToldAt.get(boxId) ?? -Infinity) >= DAY_MS) {+ restartToldAt.set(boxId, now());+ deps.tell(owner, "restarted");+ }+ restartedOwners.add(owner);+ return;+ }+ }+ return decide(owner, boxId);+ }++ const unsubscribe = health.onNotResponding((boxId) => {+ const owner = boat.boatOwnerOf(boxId);+ if (!owner || closed) return;+ if (!eligible(owner)) return needsPerson(owner, boxId);+ if (lanes.has(owner) || timers.has(owner)) return;+ set(owner, boxId, "not-responding");+ void lane(owner, () => notResponding(owner, boxId)).catch((error) => deps.log(`cloud computer ${owner}: recovery failed: ${String(error)}`));+ });++ boat.onDeadBoat(async (_cfg, owner, dead): Promise<never> => {+ if (!eligible(owner)) {+ needsPerson(owner, dead.boxId);+ throw Object.assign(new Error(CLOUD_COMPUTER_TEAM_NOT_RESPONDING), { status: 409 });+ }+ const outcome = await lane(owner, () => replace(owner, dead, { dead: true }));+ if (outcome === "capped") {+ throw Object.assign(new Error("it stopped working within an hour of being replaced, and MausBot replaces it at most once an hour; Replace computer in the computer panel tries once more"), { status: 409 });+ }+ if (outcome === "kept") throw Object.assign(new Error(CLOUD_COMPUTER_NOT_RESPONDING), { status: 409 });+ if (outcome === "waiting") throw Object.assign(new Error(CLOUD_COMPUTER_DEAD_WAITING), { status: 409 });+ if (outcome === "held") throw Object.assign(new Error(CLOUD_COMPUTER_NEEDS_PERSON), { status: 409 });+ throw Object.assign(new Error("the previous cloud computer deletion finished — retry to create a new computer"),+ { status: 409, code: outcome === "confirmed" ? BOAT_DELETION_FINISHED : BOAT_DELETING });+ });++ return {+ /** What the computer panel shows; ended states for an hour. */+ status(owner: string): CloudComputerRecovery | null {+ const found = states.get(owner);+ if (!found) return null;+ const age = now() - found.at;+ const over = recoveryUnderWay(found.state)+ ? !lanes.has(owner) && !timers.has(owner) && age >= STALE_MS+ : age >= HOUR_MS || (["unreachable", "capped", "needs-person"].includes(found.state) && health.answeredWithin(found.boxId, age));+ if (over) {+ clear(owner, found.boxId);+ return null;+ }+ return { state: found.state, at: found.at, ...(found.manual ? { manual: true as const } : {}) };+ },+ /** In place of a computer call: `before` it runs, while the computer is being restarted or replaced; `after` it got no+ * answer, what is known about why. */+ refusal(boxId: string, phase: "before" | "after"): string | null {+ if (retired.has(boxId)) return CLOUD_COMPUTER_NOT_RESPONDING;+ const owner = boat.boatOwnerOf(boxId);+ const found = owner ? states.get(owner) : undefined;+ if (found?.boxId === boxId && recoveryUnderWay(found.state)) return CLOUD_COMPUTER_NOT_RESPONDING;+ if (phase === "before") return null;+ if (found?.boxId === boxId && found.state === "unreachable") return CLOUD_COMPUTER_UNREACHABLE;+ if (found?.boxId === boxId && found.state === "capped") return CLOUD_COMPUTER_CAPPED;+ if (found?.boxId === boxId && found.state === "needs-person") return eligible(owner!) ? CLOUD_COMPUTER_NEEDS_PERSON : CLOUD_COMPUTER_TEAM_NOT_RESPONDING;+ return health.notRespondingSince(boxId) === null ? null : CLOUD_COMPUTER_NOT_RESPONDING;+ },+ /** Told once, with the first call on the owner's computer after a replacement or a restart. */+ notice(boxId: string): string | null {+ const owner = boat.boatOwnerOf(boxId);+ if (!owner) return null;+ if (restartedOwners.delete(owner)) return CLOUD_COMPUTER_RESTARTED;+ const owed = entries.filter((entry) => entry.owner === owner && entry.boxId !== boxId && !entry.toldBot);+ if (!owed.length) return null;+ write(entries.map((entry) => owed.includes(entry) ? { ...entry, toldBot: true as const, toldPerson: true as const } : entry));+ if (owed.some((entry) => !entry.toldPerson && !entry.manual)) deps.tell(owner, "replaced");+ return owed.every((entry) => entry.manual) ? CLOUD_COMPUTER_REPLACED_BY_PERSON : CLOUD_COMPUTER_REPLACED;+ },+ /** A start the Admin turned away for computers at once, right after this owner's computer was replaced: the old one's+ * place is still being given back. */+ claimSentence(owner: string, error: unknown): string | undefined {+ const recent = entries.some((entry) => entry.owner === owner && now() - entry.at < 15 * 60_000);+ return recent && cloudFailureOf(error).limit?.reason === "at_once" ? CLOUD_COMPUTER_NOT_RESPONDING : undefined;+ },+ /** Its computer is dead at the provider, has stopped answering, or is being handled here: what lets the person act+ * during a turn. A computer that came back (restarted, or already replaced) is not stuck. */+ stuck(owner: string): boolean {+ const box = boat.boatIdOf(owner), state = states.get(owner)?.state;+ return (state !== undefined && state !== "restarted" && state !== "replaced") || boat.deadBoatOf(owner) !== null+ || (box !== null && health.notRespondingSince(box) !== null);+ },+ /** The panel's Restart computer: the same restart the automatic path tries first. */+ async restart(owner: string): Promise<{ answers: boolean }> {+ const found = await boat.findBoat(deps.cfg(), owner);+ if (!found) throw Object.assign(new Error(boat.deadBoatOf(owner) ? "This computer can't be restarted; replace it instead." : "This bot has no cloud computer to restart."), { status: 409 });+ const outcome = await lane(owner, () => restart(owner, found.id, true));+ if (outcome === "answers") {+ set(owner, found.id, "restarted", true);+ return { answers: true };+ }+ clear(owner, found.id);+ return { answers: false };+ },+ /** The panel's Replace computer, confirmed by the person: the same deletion the automatic path makes, with no hourly limit. */+ async replace(owner: string): Promise<{ replaced: boolean }> {+ const found = (await boat.findBoat(deps.cfg(), owner)) ?? boat.deadBoatOf(owner);+ if (!found) throw Object.assign(new Error("This bot has no cloud computer to replace."), { status: 409 });+ const target = "boxId" in found ? found as Dead : { boxId: String(found.id), name: String(found.name) };+ const outcome = await lane(owner, () => replace(owner, target, { manual: true }));+ if (outcome === "failed") throw Object.assign(new Error("The old computer's deletion was not confirmed. Try again in a minute."), { status: 503 });+ return { replaced: true };+ },+ close(): void {+ closed = true;+ unsubscribe();+ boat.onDeadBoat(null);+ for (const timer of timers.values()) clearTimeout(timer);+ timers.clear();+ },+ };+}++export type BoatRecovery = ReturnType<typeof createBoatRecovery>;diff --git a/server/boat.ts b/server/boat.tsindex e38e5d8e18..160c4b568c 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -8,6 +8,8 @@ import { DATA_DIR, type AppConfig } from "./config.ts";import { loadEnvironmentId } from "./environment.ts";import { boatCredential, boatProviderApi, type ServiceCredential } from "./included-services.ts";import { relayBody, relayPath } from "./boat-relay.ts";+import { boatHealth, DEAD_COMPUTER, unansweredStatus } from "./boat-health.ts";+import { CLOUD_COMPUTER_NO_ANSWER } from "../shared/cloud-computer-recovery.ts";import { cloudLimitFromBody, type CloudLimit } from "../shared/place-view.ts";import {blockedUntilBoatFinishes,@@ -124,7 +126,7 @@ export type BoatTurnLifecycleAction = "attach" | "provision" | "wake";export function boatTurnLifecycleAction(state: string | null): BoatTurnLifecycleAction {if (state && READY.has(state)) return "attach";- return state ? "wake" : "provision";+ return state && !TERMINAL.has(state) ? "wake" : "provision";}export type ManagedBoatMutationClaim = (@@ -298,8 +300,12 @@ async function confirmAcceptedBoatDeletion(return reconcileRecordedBoatDeletion(cfg, next, pollDelaysMs, true);}+/** One DELETE in flight per installation, whoever asked: a burst of deletes never reaches the provider at once. */+let deletionInFlight: Promise<unknown> = Promise.resolve();+const oneDeleteAtATime = <T>(send: () => Promise<T>): Promise<T> => { const run = deletionInFlight.then(send); deletionInFlight = run.catch(() => undefined); return run; };+/** Send DELETE only after the immutable target is on disk. */-async function requestRecordedBoatDeletion(+export async function requestRecordedBoatDeletion(cfg: AppConfig,identity: { boxId: string; name: string; ownerBotId: string | null },pollDelaysMs: readonly number[] = BOAT_DELETE_OPERATION_POLL_DELAYS_MS,@@ -307,10 +313,7 @@ async function requestRecordedBoatDeletion(const deletion = prepareBoatDeletion(identity);let removed: Awaited<ReturnType<typeof boatJson>>;try {- removed = await boatJson(cfg, `/sandboxes/${identity.boxId}`, {- method: "DELETE",- headers: { "X-Ascii-Confirm-Delete": identity.boxId },- });+ removed = await oneDeleteAtATime(() => boatJson(cfg, `/sandboxes/${identity.boxId}`, { method: "DELETE", headers: { "X-Ascii-Confirm-Delete": identity.boxId }, signal: AbortSignal.timeout(60_000) }));} catch (error) {throw Object.assign(new Error("Could not confirm whether boat.dev accepted the delete. The computer was kept fenced; retry Delete to reconcile it"),@@ -336,10 +339,7 @@ function boatBotNameParts(botId: string): { prefix: string; hash: string } {return { prefix, hash };}-function legacyBoatNameFor(botId: string): string {- const { prefix, hash } = boatBotNameParts(botId);- return `ogb-${prefix}-${hash}`;-}+function legacyBoatNameFor(botId: string): string { const { prefix, hash } = boatBotNameParts(botId); return `ogb-${prefix}-${hash}`; }export async function boatNameFor(botId: string) {const { prefix, hash } = boatBotNameParts(botId);@@ -350,22 +350,24 @@ export async function boatNameMatchesBot(botId: string, name: string): Promise<breturn name === await boatNameFor(botId) || name === legacyBoatNameFor(botId);}-export async function runCommand(cfg: AppConfig, boxId: string, command: string, { timeoutMs = 120_000, signal }: { timeoutMs?: number; signal?: AbortSignal } = {}) {+/** `probe`: the health check itself, which records nothing; any other command that gets no answer starts one. */+export async function runCommand(cfg: AppConfig, boxId: string, command: string, { timeoutMs = 120_000, signal, probe = false }: { timeoutMs?: number; signal?: AbortSignal; probe?: boolean } = {}) {assertBoatNotDeleting(boxId);- const res = await boatFetch(cfg, `/sandboxes/${boxId}/commands`, {- method: "POST",- body: JSON.stringify({ command }),- signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs),- });- const body: any = await res.json().catch(() => null);+ const suspect = () => { if (!probe && !signal?.aborted) boatHealth.suspect(boxId, () => probeBoat(cfg, boxId)); };+ const res = await boatFetch(cfg, `/sandboxes/${boxId}/commands`, { method: "POST", body: JSON.stringify({ command }),+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) }).catch((error: unknown) => { suspect(); throw error; });+ const body: any = await res.json().catch(() => null), unanswered = unansweredStatus(res.status);+ // Only the computer's own answer counts: a refusal (404, 409, 429, 401, 402) says nothing about the machine.+ if (unanswered) suspect(); else if (!probe && res.ok && typeof body?.exitCode === "number") boatHealth.answered(boxId);return {- ok: res.ok && body?.exitCode === 0,- exitCode: body?.exitCode ?? null,- stdout: body?.stdout ?? "",- stderr: body?.stderr ?? "", ...(body?.timedOut === true ? { timedOut: true as const } : {}),+ ok: res.ok && body?.exitCode === 0, exitCode: body?.exitCode ?? null, stdout: body?.stdout ?? "",+ stderr: body?.stderr ?? "", ...(body?.timedOut === true ? { timedOut: true as const } : {}), ...(unanswered ? { unanswered: true as const } : {}),};}+export const probeBoat = (cfg: AppConfig, boxId: string): Promise<boolean | null> =>+ runCommand(cfg, boxId, "true", { timeoutMs: DEAD_COMPUTER.probeTimeoutMs, probe: true }).then((out) => out.ok ? true : out.unanswered ? false : null, () => false);+// Boat desktop access: VNC (POST /desktop?vnc=1) first, a plain WebSocket that survives P2P-blocking networks and answers// {provisioning:true} until ready; WebRTC (POST /desktop) is a STUN-only fallback that can hang. The sandbox's desktopUrl is not usable alone.async function mintDesktopUrl(cfg: AppConfig, boxId: string, { vncBudgetMs = 60_000, requestMs = 30_000 } = {}) {@@ -415,6 +417,14 @@ async function waitReady(cfg: AppConfig, boxId: string, budgetMs = 90_000) {}const boatIdCache = new Map<string, string>();+/** The bot's computer the provider reports in `error`: its machine is gone and it never runs again, but until it is+ * deleted it still has the bot's name and may hold one of the plan's computers. */+const deadBoats = new Map<string, { boxId: string; name: string }>();+export type DeadBoatHandler = (cfg: AppConfig, owner: string, dead: { boxId: string; name: string }) => Promise<never>;+let deadBoatHandler: DeadBoatHandler | null = null;+export const onDeadBoat = (handler: DeadBoatHandler | null) => { deadBoatHandler = handler; };+export const deadBoatOf = (owner: string) => deadBoats.get(owner) ?? null, boatIdOf = (owner: string) => boatIdCache.get(owner) ?? null,+ boatOwnerOf = (boxId: string) => [...boatIdCache].find(([, id]) => id === boxId)?.[0] ?? null;function boatInventoryProblem(status: number, body: any, included = false): string {if (status === 401 || status === 403) {@@ -716,20 +726,12 @@ export function inventoryFailure(inventory: ManagedBoatInventory): Error & { stareturn error;}-function deletionFenceError(): Error & { status: number } {- return Object.assign(- new Error("this cloud computer is being deleted — wait for it to finish, or retry Delete if it needs attention"),- { status: 409, code: BOAT_DELETING },- );-}+const deletionFenceError = (): Error & { status: number } => Object.assign(+ new Error("this cloud computer is being deleted — wait for it to finish, or retry Delete if it needs attention"), { status: 409, code: BOAT_DELETING });-export function assertBoatNotDeleting(boxId: string): void {- if (getBoatDeletion(boxId)) throw deletionFenceError();-}+export function assertBoatNotDeleting(boxId: string): void { if (getBoatDeletion(boxId)) throw deletionFenceError(); }-function assertBotBoatNotDeleting(botId: string): void {- if (hasPendingBoatDeletionForBot(botId)) throw deletionFenceError();-}+function assertBotBoatNotDeleting(botId: string): void { if (hasPendingBoatDeletionForBot(botId)) throw deletionFenceError(); }async function revalidateManagedBoat(cfg: AppConfig,@@ -760,7 +762,7 @@ async function stopBoat(cfg: AppConfig, boxId: string): Promise<void> {}}-function forgetBoatId(boxId: string): void {+export function forgetBoatId(boxId: string): void {for (const [botId, cachedId] of boatIdCache) {if (cachedId === boxId) boatIdCache.delete(botId);}@@ -865,6 +867,7 @@ export async function findBoat(cfg: AppConfig, botId: string) {const found = expected.find((candidate: any) => candidate.name === name && !TERMINAL.has(candidate.state))?? expected.find((candidate: any) => candidate.name === legacyName && !TERMINAL.has(candidate.state))?? null;+ const dead = found ? undefined : expected.find((candidate: any) => candidate.state === "error"); if (dead) deadBoats.set(botId, { boxId: dead.id, name: dead.name }); else deadBoats.delete(botId);if (found) {const duplicateId = listed.boats.filter((candidate: any) => candidate?.id === found.id).length !== 1;if (duplicateId) {@@ -884,23 +887,15 @@ export async function readyBoat(cfg: AppConfig, botId: string, budgetMs = 60_000return waitReady(cfg, boat.id, budgetMs);}-export function boatAccount(cfg: AppConfig): ServiceCredential | null {- return boatCredential(cfg.box?.token);-}+export const boatAccount = (cfg: AppConfig): ServiceCredential | null => boatCredential(cfg.box?.token);-export function boatConfigured(cfg: AppConfig) {- return Boolean(boatAccount(cfg));-}+export const boatConfigured = (cfg: AppConfig) => Boolean(boatAccount(cfg));-function usesIncludedBoat(cfg: AppConfig): boolean {- return boatAccount(cfg)?.included === true;-}+const usesIncludedBoat = (cfg: AppConfig): boolean => boatAccount(cfg)?.included === true;/** Configured-or-not for Settings, never the token. */-export function describeBoatAccount(cfg: AppConfig): { configured: boolean; included?: true } {- const account = boatAccount(cfg);- return { configured: Boolean(account), ...(account?.included ? { included: true as const } : {}) };-}+export const describeBoatAccount = (cfg: AppConfig): { configured: boolean; included?: true } => {+ const account = boatAccount(cfg); return { configured: Boolean(account), ...(account?.included ? { included: true as const } : {}) }; };export async function verifyToken(token: string): Promise<{ ok: true } | { ok: false; message: string; rejected?: true }> {try {@@ -1080,6 +1075,7 @@ export async function provisionBoat(cfg: AppConfig, botId: string, _botName: strlet createRequest: BoatCreateRequest | null = null;try {if (!boat) {+ const dead = deadBoats.get(botId); if (dead && deadBoatHandler) await deadBoatHandler(cfg, botId, dead);// Another process may have prepared a deletion since the lookup; never create a replacement before the fence is reconciled.assertBotBoatNotDeleting(botId);// Boat's TTL archives the computer if every stop path dies.@@ -1145,7 +1141,7 @@ export async function joinBoat(cfg: AppConfig, botId: string) {const ready = await waitReady(cfg, boat.id);if (!ready) throw new Error("the cloud computer did not wake in time — try again");// Archive/resume keeps disk but not processes; the sandbox restarts its own driver daemon.- return { joinUrl: await mintDesktopUrl(cfg, boat.id), state: ready.state ?? null };+ boatHealth.personUsed(boat.id); return { joinUrl: await mintDesktopUrl(cfg, boat.id), state: ready.state ?? null };}/** The only join path allowed while a bot turn is active: no lifecycle or guest-process change. */@@ -1159,7 +1155,7 @@ export async function joinReadyBoat(cfg: AppConfig, botId: string) {{ status: 409 },);}- return { joinUrl: await mintDesktopUrl(cfg, boat.id), state: boat.state ?? null };+ boatHealth.personUsed(boat.id); return { joinUrl: await mintDesktopUrl(cfg, boat.id), state: boat.state ?? null };}export async function sleepBoat(cfg: AppConfig, botId: string) {@@ -1249,7 +1245,7 @@ export async function screenshotBoat(cfg: AppConfig, botId: string, knownBoatId?const out = await runCommand(cfg, boxId, options?.nativeSize ? panelShotCommand({ framePath, nativeSize: true }) : SHOT_CMD,{ timeoutMs: 60_000, signal: options?.signal });if (!/captured/.test(out.stdout)) {- throw new Error(out.stderr.slice(0, 200) || "screen capture failed on the cloud computer");+ throw new Error(out.unanswered ? CLOUD_COMPUTER_NO_ANSWER : out.stderr.slice(0, 200) || "screen capture failed on the cloud computer");}const data = await readFileBase64(cfg, boxId, framePath, options?.signal);if (!data) throw new Error("could not read the frame back from the cloud computer");diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex d973f303e1..6baf27718c 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -18,7 +18,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_CLAUDE_INHERIT_USER_CONFIG", "OMB_CLAUDE_SESSION_IDLE_", "OMB_CLI_OWNER_STDIN", "OMB_CLI_PREFIX","OMB_CLOUDFLARED_PATH", "OMB_CLOUD_", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_AI_TOKEN", "OMB_CLOUD_AI_URL","OMB_CLOUD_BOAT_TOKEN", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_CLOUD_CAPS_DROPPED",- "OMB_CLOUD_CLIENT_IP_HEADER", "OMB_CLOUD_COMPUTER_IDLE_MS", "OMB_CLOUD_COMPUTER_START_BUDGET_MS",+ "OMB_CLOUD_CLIENT_IP_HEADER", "OMB_CLOUD_COMPUTER_AUTO_REPLACE", "OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS", "OMB_CLOUD_COMPUTER_IDLE_MS", "OMB_CLOUD_COMPUTER_START_BUDGET_MS","OMB_CLOUD_CONNECTED_APPS_GRANT", "OMB_CLOUD_DECIDER_TOKEN", "OMB_CLOUD_DECIDER_URL", "OMB_CLOUD_EDGE_ACME_EMAIL","OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_EDGE_CERT_ISSUERS","OMB_CLOUD_EDGE_CLIENT_IP_HEADER", "OMB_CLOUD_EDGE_CONFIG", "OMB_CLOUD_EDGE_HOLD", "OMB_CLOUD_EDGE_STORAGE",diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex 800da52783..fdd354b914 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -8,6 +8,7 @@ import { join } from "node:path";import { fileURLToPath } from "node:url";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { CONTROL_WAITED } from "./control-client.ts";+import { CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_REPLACED, CLOUD_COMPUTER_REPLACED_BY_PERSON } from "../shared/cloud-computer-recovery.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { freePortBlock } from "./testing/ports.ts";import { openSse, type SseRecorder } from "./testing/sse.ts";@@ -39,6 +40,8 @@ describe("a cloud computer starts only when the bot uses it", () => {* hours are used up. */const refuse = { creates: false };const requests: Request[] = [];+ /** Computers deleted at the relay: no longer listed, and a 404 to a direct read. */+ const gone = new Set<string>();/** Files the bots wrote on their computers, by path. */const written = new Map<string, string>();/** Boat ids in Boat's own alphabet, one per computer created. */@@ -149,7 +152,7 @@ describe("a cloud computer starts only when the bot uses it", () => {return send(401, { ok: false, code: "unauthorized", message: "Unauthorized" });}const body = raw ? JSON.parse(raw) : {};- if (path === "/boxes" && req.method === "GET") return send(200, { ok: true, boxes: rows, pageInfo: { nextCursor: null } });+ if (path === "/boxes" && req.method === "GET") return send(200, { ok: true, boxes: rows.filter(row => !gone.has(row.id)), pageInfo: { nextCursor: null } });if (path === "/boxes" && req.method === "POST") {if (refuse.creates) return send(402, { ok: false, code: "hours_used", message: "This month's 50 cloud computer hours are used up." });const row = { id: boxId(rows.length), state: "provisioning" };@@ -157,8 +160,13 @@ describe("a cloud computer starts only when the bot uses it", () => {return send(201, { ok: true, box: row });}const [, id = "", verb = ""] = /^\/boxes\/([^/]+)(?:\/(.+))?$/.exec(path) ?? [];- const row = rows.find(candidate => candidate.id === id);+ const row = rows.find(candidate => candidate.id === id && !gone.has(candidate.id));if (!row) return send(404, { ok: false, code: "not_found", message: "Not found" });+ if (!verb && req.method === "DELETE") {+ if (req.headers["x-ascii-confirm-delete"] !== row.id) return send(409, { ok: false, code: "confirmation_required" });+ gone.add(row.id);+ return send(202, { ok: true, operation: { id: `bdop_${"0".repeat(24)}${row.id.slice(3)}`, kind: "box", targetId: row.id, status: "completed" } });+ }if (!verb && req.method === "PATCH") {row.name = body.name;return send(200, { ok: true, box: row });@@ -226,6 +234,8 @@ describe("a cloud computer starts only when the bot uses it", () => {OMB_BOAT_API: `${relayBase}/own-key-must-not-be-used`,OMB_CLOUD_BOAT_URL: `${relayBase}/relay/api/box/v1`,OMB_CLOUD_BOAT_TOKEN: INCLUDED,+ // The provider's error is still read twice before a computer is deleted; here the reads need not be half an hour apart.+ OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS: "0",},stdio: ["ignore", "pipe", "pipe"],});@@ -325,6 +335,88 @@ describe("a cloud computer starts only when the bot uses it", () => {await apiOk("DELETE", `/api/bots/${bot.id}`);}, 60_000);+ const callThroughWait = async (sent: any) => {+ let result = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });+ for (let tries = 0; result.body.result.content?.[0]?.text === CONTROL_WAITED && tries < 3; tries++) {+ result = await computerCall(sent, "tools/call", { name: "screenshot", arguments: {} });+ }+ return result;+ };+ const recoveryLines = async (botId: string) => (await task(botId)).messages+ .filter((message: any) => message.tool?.name?.startsWith("recovery:")).map((message: any) => message.tool.name);+ const inboxNotices = (botId: string) => events.frames+ .filter((frame: any) => frame.kind === "notify" && frame.notification?.botId === botId && frame.notification.kind === "notice")+ .map((frame: any) => frame.notification.body);++ it("by default a computer whose machine is gone is never deleted by itself: the bot and the person are told once, and Replace computer replaces it", async () => {+ const bot = await cloudBot("Waiting");+ await apiOk("POST", `/api/bots/${bot.id}/computer/provision`);+ const dead = rows.at(-1)!;+ dead.state = "error";+ const before = requests.length, made = creates();+ const next = await startTurn(bot.id, "Look again");+ const held = await callThroughWait(next);+ expect(held.body.result.isError).toBe(true);+ expect(held.body.result.content[0].text).toContain(CLOUD_COMPUTER_NEEDS_PERSON);+ await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });+ expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([]);+ expect(creates()).toBe(made);+ const line = "Waiting's cloud computer stopped responding. Replace computer in the computer panel gives it a new one; files only on the old computer are lost.";+ expect(await recoveryLines(bot.id)).toEqual([`recovery: ${line}`]);+ expect(inboxNotices(bot.id)).toEqual([line]);++ // The person replaces it while the turn still waits on it.+ expect(await apiOk("POST", `/api/bots/${bot.id}/computer/recovery`, { action: "replace" })).toEqual({ replaced: true });+ expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([{ method: "DELETE", path: `/boxes/${dead.id}` }]);+ await finish(bot.id);+ const after = await startTurn(bot.id, "Try again");+ const fresh = await callThroughWait(after);+ expect(fresh.body.result.isError, JSON.stringify(fresh.body)).toBeFalsy();+ expect(fresh.body.result.content[0]).toEqual({ type: "text", text: CLOUD_COMPUTER_REPLACED_BY_PERSON });+ expect(creates()).toBe(made + 1);+ await finish(bot.id);+ expect(await recoveryLines(bot.id)).toHaveLength(1);+ await apiOk("DELETE", `/api/bots/${bot.id}`);+ }, 60_000);++ it("with automatic replacement on, a computer whose machine is gone is replaced on its next use, and the bot and the person are told once", async () => {+ await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: true } });+ const bot = await cloudBot("Stranded");+ // Made from the panel, so no command has answered on it lately: one that has is kept for a few minutes.+ await apiOk("POST", `/api/bots/${bot.id}/computer/provision`);+ const dead = rows.at(-1)!;+ expect(dead.name).toBeTruthy();+ // What Boat reports once the host under a computer is lost.+ dead.state = "error";+ const before = requests.length, made = creates();+ const status = await apiOk("GET", `/api/bots/${bot.id}/computer?threadId=${bot.threadId}`);+ expect(status.box).toBeNull();++ // The first read of the provider's error only notes it; the next start, after a second read, replaces the computer.+ const first = await startTurn(bot.id, "Look");+ const noted = await callThroughWait(first);+ expect(noted.body.result.content[0].text).toContain(CLOUD_COMPUTER_DEAD_WAITING);+ expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([]);+ await finish(bot.id);+ const next = await startTurn(bot.id, "Look again");+ const replaced = await callThroughWait(next);+ expect(replaced.body.result.isError, JSON.stringify(replaced.body)).toBeFalsy();+ expect(replaced.body.result.content[0]).toEqual({ type: "text", text: CLOUD_COMPUTER_REPLACED });+ expect(replaced.body.result.content[1]).toMatchObject({ type: "image", mimeType: "image/jpeg" });+ const again = await computerCall(next, "tools/call", { name: "screenshot", arguments: {} });+ expect(again.body.result.content).toHaveLength(1);+ expect(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([{ method: "DELETE", path: `/boxes/${dead.id}` }]);+ expect(creates()).toBe(made + 1);+ await finish(bot.id);++ const waiting = "Stranded's cloud computer stopped responding. Replace computer in the computer panel gives it a new one; files only on the old computer are lost.";+ const line = "Stranded's cloud computer stopped responding, so MausBot replaced it with a new one. Files that were only on the old computer are gone.";+ expect(await recoveryLines(bot.id)).toEqual([`recovery: ${waiting}`, `recovery: ${line}`]);+ expect(inboxNotices(bot.id)).toEqual([waiting, line]);+ await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: false } });+ await apiOk("DELETE", `/api/bots/${bot.id}`);+ }, 60_000);+it("a signed-out engine fails with the existing sign-in row and no relay call", async () => {const bot = await cloudBot("Signed out", { modelSelection: { instanceId: "claude-out", model: "claude-sonnet-5" } });const before = requests.length;diff --git a/server/cloud-computer-tools.test.ts b/server/cloud-computer-tools.test.tsindex 66297b6f40..4a8cd3782e 100644--- a/server/cloud-computer-tools.test.ts+++ b/server/cloud-computer-tools.test.ts@@ -7,19 +7,25 @@ const jpeg = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwlet server: Server;let tools: typeof import("./cloud-computer-tools.ts");let holdCommand = false;+let commandStatus = 200;+let commandExit = 0;let commandStarted: (() => void) | undefined;const calls: Array<{ path: string; body: any; authorization?: string }> = [];const cfg: AppConfig = { box: { token: "synthetic-box-key" } } as AppConfig;beforeAll(async () => {server = createServer(async (req, res) => {+ // Every answer closes its connection: the tests that leave a command hanging close the server's sockets, and a pooled+ // keep-alive socket reused after that fails the next test's request with "other side closed".+ res.setHeader("connection", "close");let body = "";for await (const part of req) body += part;const path = req.url ?? "";calls.push({ path, body: body ? JSON.parse(body) : null, authorization: req.headers.authorization });if (path.endsWith("/commands")) {commandStarted?.();- if (!holdCommand) res.end(JSON.stringify({ exitCode: 0, stdout: "captured", stderr: "" }));+ if (commandStatus !== 200) { res.writeHead(commandStatus); res.end(JSON.stringify({ ok: false, code: "upstream_unavailable" })); return; }+ if (!holdCommand) res.end(JSON.stringify({ exitCode: commandExit, stdout: "captured", stderr: "" }));return;}if (path.includes("/artifacts?")) { res.end(Buffer.from(jpeg, "base64")); return; }@@ -32,16 +38,17 @@ beforeAll(async () => {vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", undefined);tools = await import("./cloud-computer-tools.ts");});-beforeEach(() => { calls.length = 0; holdCommand = false; commandStarted = undefined; });+beforeEach(() => { calls.length = 0; holdCommand = false; commandStarted = undefined; commandStatus = 200; commandExit = 0; });afterAll(async () => { vi.unstubAllEnvs(); server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });-const rpc = (request: unknown, gate: { held: boolean; reason?: "person"; blockedReason?: string } = { held: false }, signal = new AbortController().signal) => {+type Recovery = NonNullable<Parameters<typeof import("./cloud-computer-tools.ts").cloudComputerRpc>[1]["recovery"]>;+const rpc = (request: unknown, gate: { held: boolean; reason?: "person"; blockedReason?: string } = { held: false }, signal = new AbortController().signal, recovery?: Recovery) => {let gated = 0;let checks = 0;const done = tools.cloudComputerRpc(request as never, {cfg, boxId: () => "bx_23456789", signal,gate: async () => { gated++; return gate; },- assertActive: () => { checks++; },+ assertActive: () => { checks++; }, recovery,});return { done, gated: () => gated, checks: () => checks };};@@ -209,4 +216,46 @@ describe("cloud computer tools", () => {expect(calls.filter(entry => entry.path.endsWith("/commands"))).toHaveLength(1);server.closeAllConnections();});++ describe("a computer that stopped answering", () => {+ const words = () => import("../shared/cloud-computer-recovery.ts");+ const call = (name: string, args: Record<string, unknown>, recovery?: Recovery) =>+ rpc({ method: "tools/call", params: { name, arguments: args } }, { held: false }, new AbortController().signal, recovery).done as Promise<{ isError?: boolean; content: Array<{ type: string; text?: string }> }>;++ it("says a call got no answer, instead of an empty failed result", async () => {+ commandStatus = 502;+ const result = await call("click", { x: 1, y: 2 });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: (await words()).CLOUD_COMPUTER_NO_ANSWER }] });+ });++ it("refuses calls without touching the computer while it is being restarted or replaced", async () => {+ const { CLOUD_COMPUTER_NOT_RESPONDING } = await words();+ const result = await call("click", { x: 1, y: 2 }, { refusal: (_box, phase) => phase === "before" ? CLOUD_COMPUTER_NOT_RESPONDING : null, notice: () => null });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_NOT_RESPONDING }] });+ expect(calls).toEqual([]);+ });++ it("tells what is known about a computer that did not answer, and leaves a command's own failure as it is", async () => {+ const { CLOUD_COMPUTER_UNREACHABLE } = await words();+ const recovery: Recovery = { refusal: (_box, phase) => phase === "after" ? CLOUD_COMPUTER_UNREACHABLE : null, notice: () => null };+ commandStatus = 502;+ expect((await call("click", { x: 1, y: 2 }, recovery)).content).toEqual([{ type: "text", text: CLOUD_COMPUTER_UNREACHABLE }]);+ commandStatus = 200;+ commandExit = 1;+ const failed = await call("exec", { command: "false" }, recovery);+ expect(failed.isError).toBe(true);+ expect(JSON.parse(failed.content[0]!.text!)).toMatchObject({ ok: false, exitCode: 1 });+ });++ it("puts the replacement notice once before the first result on the new computer", async () => {+ const { CLOUD_COMPUTER_REPLACED } = await words();+ let owed = true;+ const recovery: Recovery = { refusal: () => null, notice: () => (owed ? ((owed = false), CLOUD_COMPUTER_REPLACED) : null) };+ const first = await call("get_screen_size", {}, recovery);+ expect(first.content[0]).toEqual({ type: "text", text: CLOUD_COMPUTER_REPLACED });+ expect(first.content).toHaveLength(2);+ const second = await call("get_screen_size", {}, recovery);+ expect(second.content).toHaveLength(1);+ });+ });});diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex 545c162dc2..dfb961aba0 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -10,6 +10,7 @@ import type { AppConfig } from "./config.ts";import { controlRefusal, type ControlState } from "./control-client.ts";import { COMPUTER_COPY_BUDGET_MS, HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";import { compileToolSchema } from "./mcp-schema-validator.ts";+import { CLOUD_COMPUTER_NO_ANSWER } from "../shared/cloud-computer-recovery.ts";const coordinate = { type: "integer", minimum: 0, maximum: 32767 };const tool = (name: string, description: string, properties: Record<string, unknown> = {}, required: string[] = []) =>@@ -116,6 +117,7 @@ export async function runCloudComputerTool(signal.throwIfAborted();if (name === "open_url" && result.ok) return { content: [{ type: "text", text: "Browser launch requested. Page loading is not confirmed; inspect the screen before continuing." }] };if (name === "exec" && result.timedOut) return { isError: true, content: [{ type: "text", text: EXEC_LATE }] };+ if (result.unanswered) return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_NO_ANSWER }] };return { isError: !result.ok, content: [{ type: "text", text: JSON.stringify(result) }] };}@@ -134,6 +136,8 @@ export async function cloudComputerRpc(signal: AbortSignal;/** The whole call, the gate's wait included, answers within this. */budgetMs?: number;+ /** A computer that stopped answering (server/boat-recovery.ts): what the bot is told instead, and once after it was replaced. */+ recovery?: { refusal(boxId: string, phase: "before" | "after"): string | null; notice(boxId: string): string | null };},): Promise<{ tools: typeof CLOUD_COMPUTER_TOOLS } | CloudComputerResult> {const started = Date.now();@@ -154,14 +158,26 @@ export async function cloudComputerRpc(deps.assertActive();const boxId = deps.boxId();if (!boxId) return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_NOT_READY }] };+ const refused = (phase: "before" | "after"): CloudComputerResult | null => {+ const text = deps.recovery?.refusal(boxId, phase);+ return text ? { isError: true, content: [{ type: "text", text }] } : null;+ };+ const before = refused("before");+ if (before) return before;const late = AbortSignal.timeout(Math.max(1, deadline - Date.now()));let result: CloudComputerResult;try {result = await runCloudComputerTool(deps.cfg, boxId, params.name as string, args as Record<string, unknown>, AbortSignal.any([deps.signal, late]), deps.folder?.());} catch (error) {- if (!late.aborted || deps.signal.aborted) throw error;+ if (deps.signal.aborted) throw error;+ const after = refused("after");+ if (after) return after;+ if (!late.aborted) throw error;return { isError: true, content: [{ type: "text", text: commandLateText(params.name, args) ?? (copy ? CLOUD_COMPUTER_COPY_LATE : CLOUD_COMPUTER_LATE) }] };}deps.assertActive();- return result;+ const unanswered = result.isError && result.content.some((part) => part.type === "text" && part.text === CLOUD_COMPUTER_NO_ANSWER);+ if (unanswered) result = refused("after") ?? result;+ const notice = deps.recovery?.notice(boxId);+ return notice ? { ...result, content: [{ type: "text", text: notice }, ...result.content] } : result;}diff --git a/server/config.ts b/server/config.tsindex e9009e2323..b1f8a002ac 100644--- a/server/config.ts+++ b/server/config.ts@@ -244,7 +244,7 @@ const featureConfigSchema = z.object({/** Room jobs to several members run side by side, each in a thread of its own. Off unless true. */parallelRoomJobs: z.boolean().optional(),acpPlanLines: z.boolean().optional(), // An ACP agent's plan as activity lines. Off unless true.-}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional() }); // agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional() }); // cloudComputerAutoReplace: delete and replace a dead cloud computer by itself, off unless true (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless trueconst onboardingConfigSchema = z.object({completedAt: z.string().trim().max(40).optional(),version: z.number().int().min(0).max(1000).optional(),@@ -483,7 +483,7 @@ export interface AppConfig extends HelperConfig {context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };memory?: { captureQuietMs?: number; tidyHour?: number };localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean; memoryGb?: number; cpus?: number };- features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean };+ features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean; savedSteps?: boolean; usbPhoneTakeover?: boolean; cloudComputerAutoReplace?: boolean };onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };browserProfiles?: BrowserProfile[];browserEngine?: BrowserEngineConfig;diff --git a/server/index.ts b/server/index.tsindex f7a5319609..33b763af73 100644--- a/server/index.ts+++ b/server/index.ts@@ -94,7 +94,7 @@ import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";import { chosenPlace, pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";-import { cloudComputerRpc } from "./cloud-computer-tools.ts";+import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES } from "../shared/cloud-computer-recovery.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";import { BUILT_IN_DATA_SYSTEM_PROMPT } from "./data/instructions.ts";import { DATA_INTERNAL_MCP_PATH, dataRpc } from "./data/rpc.ts";@@ -5659,7 +5659,7 @@ const meetingsHost = createMeetingsHost({ cfg, dataDir: DATA_DIR, store, startTuroutineComputer: routine => { const bot = store.bot(routine.botId); return bot && turnProvider(bot, routine.runOn) === "box" ? botComputerControlKey(bot) : null; },busy: owner => computerProviderConfigTransitions.has("box") || boatLifecycleBusyBots.has(owner) || managedBoatOwners().some(entry => entry.botId === owner && entry.inUse) || meetingsHost.keepsAwake(owner),claim: owner => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); return team ? claimTeamComputerLifecycle(team) : claimBotComputerLifecycle(owner); },-});+}); const boatRecovery = createBoatRecovery({ cfg: () => cfg, log: line => console.warn(line), eligible: owner => { const bot = store.bot(owner); return Boolean(bot) && botComputerControlKey(bot!) === owner; }, personActive: owner => computerControl.snapshot(owner).held || desktopViewer.viewing(owner) > 0, tell: (owner, key) => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); if (team) { teamComputers.setProblem(team.id, serverLine(appLanguage(), CLOUD_COMPUTER_PERSON_LINES.teamNotResponding, { name: team.name })); return; } const bot = store.bot(owner); if (!bot) return; const text = serverLine(conversationLanguage(bot.threadId), CLOUD_COMPUTER_PERSON_LINES[key], { name: bot.name }); store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${text}`, ok: true } }); notify(buildNoticeNotification(bot, bot.threadId, text)); } });function inheritedTeamComputer(bot: Pick<BotRecord, "section" | "computer" | "cloudBackend">): TeamComputerRecord | undefined {return teamComputers.forBot(bot);@@ -5791,7 +5791,7 @@ function mountTeamBoat(computer: TeamComputerRecord, botId: string, owner: TurnOif (!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; }).catch((error: unknown) => { slot.limit = cloudLimitText(error); throw error; });+ const attached = await attachTeamBoat(computer, owner, () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }).catch((error: unknown) => { slot.limit = boatRecovery.claimSentence(teamComputerOwner(computer.id), error) ?? cloudLimitText(error); throw error; });slot.boxId = attached.boxId;opts.onClaimed(attached.capture);} };@@ -5891,7 +5891,7 @@ function mountBotBoat(if (!attached) throw new Error(opts.existingOnly ? "this bot no longer has a cloud computer of its own" : "the cloud computer could not be created or reached");} catch (error) {slot.cause = error instanceof Error ? error.message : String(error);- slot.limit = cloudLimitText(error);+ slot.limit = boatRecovery.claimSentence(bot.id, error) ?? cloudLimitText(error);throw keepTransient(error, opts.source ? await asPlaceFailure(error, "cloud", opts.source, bot, "box") : error);}slot.boxId = attached.boxId;@@ -12408,7 +12408,7 @@ ROUTES.push(createComputerRoutes({localVmPayload, localVmInventoryPayload, existingPerBotLocalVmCount, teamComputersPayload, teamComputerInUse,managedBoatOwners, providerTransitionMessage, botHasActiveTurn, localVmLeaseKey: sharedVm.leaseKey, botComputerControlSnapshot: sharedVm.snapshot,computerPreviewBot, computerPreviewSurface, claimTeamComputerLifecycle, claimBotComputerLifecycle,- claimBoatInventoryRequest, claimManagedBoatMutation, claimManagedVpsMutation, cloudComputerUsed: owner => cloudComputerPower.used(owner),+ claimBoatInventoryRequest, claimManagedBoatMutation, claimManagedVpsMutation, cloudComputerUsed: owner => cloudComputerPower.used(owner), boatRecovery, cloudComputerOwner: botComputerControlKey,}));ROUTES.push(createStatusRoutes({store, cfg,@@ -13142,7 +13142,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {cfg, signal: abort.signal, folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],boxId: () => internalCapability.boxId ?? claimedBoatId(internalCapability),gate: () => computerCallGate(internalCapability, abort.signal),- assertActive: requireActiveInternalCapability,+ assertActive: requireActiveInternalCapability, recovery: boatRecovery,}) });}// DuckDB runs here on the bot's own database; the agent process holds only the turn's capability.@@ -15454,7 +15454,7 @@ const gracefulShutdown = createGracefulShutdown({desktopViewer.closeAll();upgrades.close();for (const idle of localVmIdles.values()) idle.cancel();- cloudComputerPower.close();+ cloudComputerPower.close(); boatRecovery.close();vps.closeAllVpsDesktopTunnels();watchdog.stop();routines?.close(); void appTriggers.stop();diff --git a/server/routes/cloud-computer-recovery.test.ts b/server/routes/cloud-computer-recovery.test.tsnew file mode 100644index 0000000000..1fdbf3f6b8--- /dev/null+++ b/server/routes/cloud-computer-recovery.test.ts@@ -0,0 +1,95 @@+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";++import { json, readBody } from "../harness/http.ts";+import { requiredScope } from "../request-auth.ts";+import type { BotRecord } from "../store.ts";+import { createCloudComputerRecoveryRoutes, type CloudComputerRecoveryRouteDeps } from "./cloud-computer-recovery.ts";+import { dispatchRoutes } from "./table.ts";++const servers: Server[] = [];+afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++const bot = (patch: Partial<BotRecord> = {}) => ({ id: "bot-1", name: "Ada", ...patch }) as BotRecord;++async function serve(deps: Partial<CloudComputerRecoveryRouteDeps> = {}, actions: string[] = []) {+ const claimed: string[] = [];+ const routes = [createCloudComputerRecoveryRoutes({+ store: { bot: (id) => (id === "bot-1" ? bot() : null) },+ boatRecovery: {+ status: () => ({ state: "replaced", at: 1 }),+ restart: async (owner) => { actions.push(`restart ${owner}`); return { answers: true }; },+ replace: async (owner) => { actions.push(`replace ${owner}`); return { replaced: true }; },+ stuck: () => false,+ },+ computerProviderConfigTransitions: new Set(),+ providerTransitionMessage: () => "changing",+ botHasActiveTurn: () => false,+ botComputerControlKey: (record) => record.id,+ claimBotComputerLifecycle: (botId) => { claimed.push(botId); return () => claimed.push(`released ${botId}`); },+ cloudComputerUsed: () => {},+ ...deps,+ })];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: { kind: "loopback", scopes: ["admin"] }, json, readBody });+ if (!handled) json(res, 404, { from: "inline routes" });+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ return { base: `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/bots`, claimed };+}+const post = (url: string, body: unknown, contentType = "application/json") =>+ fetch(url, { method: "POST", headers: { "content-type": contentType }, body: JSON.stringify(body) });++describe("the computer panel's recovery routes", () => {+ it("are for admins only", () => {+ expect(requiredScope("GET", "/api/bots/bot-1/computer/recovery")).toBe("admin");+ expect(requiredScope("POST", "/api/bots/bot-1/computer/recovery")).toBe("admin");+ });++ it("report what MausBot is doing about the bot's computer", async () => {+ const { base } = await serve();+ const response = await fetch(`${base}/bot-1/computer/recovery`);+ expect(response.headers.get("cache-control")).toContain("no-store");+ expect(await response.json()).toEqual({ recovery: { state: "replaced", at: 1 } });+ expect((await fetch(`${base}/nobody/computer/recovery`)).status).toBe(404);+ });++ it("restart and replace run the shared recovery under the bot's lifecycle lane", async () => {+ const actions: string[] = [];+ const { base, claimed } = await serve({}, actions);+ expect(await (await post(`${base}/bot-1/computer/recovery`, { action: "restart" })).json()).toEqual({ answers: true });+ expect(await (await post(`${base}/bot-1/computer/recovery`, { action: "replace" })).json()).toEqual({ replaced: true });+ expect(actions).toEqual(["restart bot-1", "replace bot-1"]);+ expect(claimed).toEqual(["bot-1", "released bot-1", "bot-1", "released bot-1"]);+ });++ it("refuse a form post, an unknown action, a VPS bot and a team's shared computer", async () => {+ const actions: string[] = [];+ const { base } = await serve({ store: { bot: (id) => (id === "vps" ? bot({ id, cloudBackend: "vps" }) : id === "team" ? bot({ id }) : null) },+ botComputerControlKey: (record) => (record.id === "team" ? "team:computer" : record.id) }, actions);+ expect((await post(`${base}/vps/computer/recovery`, { action: "restart" }, "text/plain")).status).toBe(415);+ expect((await post(`${base}/vps/computer/recovery`, { action: "reboot" })).status).toBe(400);+ expect((await post(`${base}/vps/computer/recovery`, { action: "restart" })).status).toBe(409);+ expect((await post(`${base}/team/computer/recovery`, { action: "replace" })).status).toBe(409);+ expect(actions).toEqual([]);+ });++ it("leave a working computer alone while the bot uses it, but not one that stopped answering", async () => {+ const actions: string[] = [];+ let stuck = false;+ const { base } = await serve({+ botHasActiveTurn: () => true,+ boatRecovery: { status: () => null, stuck: () => stuck,+ restart: async () => ({ answers: true }), replace: async (owner) => { actions.push(owner); return { replaced: true }; } },+ }, actions);+ expect((await post(`${base}/bot-1/computer/recovery`, { action: "replace" })).status).toBe(409);+ stuck = true;+ expect((await post(`${base}/bot-1/computer/recovery`, { action: "replace" })).status).toBe(200);+ expect(actions).toEqual(["bot-1"]);+ });+});diff --git a/server/routes/cloud-computer-recovery.ts b/server/routes/cloud-computer-recovery.tsnew file mode 100644index 0000000000..5136deb316--- /dev/null+++ b/server/routes/cloud-computer-recovery.ts@@ -0,0 +1,50 @@+import type { BoatRecovery } from "../boat-recovery.ts";+import type { BotRecord, Store } from "../store.ts";+import type { RemoteComputerProvider } from "./config.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface CloudComputerRecoveryRouteDeps {+ store: Pick<Store, "bot">;+ boatRecovery: Pick<BoatRecovery, "status" | "restart" | "replace" | "stuck">;+ computerProviderConfigTransitions: Pick<Set<RemoteComputerProvider>, "has">;+ providerTransitionMessage(provider: RemoteComputerProvider): string;+ botHasActiveTurn(botId: string): boolean;+ botComputerControlKey(bot: BotRecord): string;+ claimBotComputerLifecycle(botId: string, allowPreview?: boolean): () => void;+ cloudComputerUsed(owner: string): void;+}++/** GET and POST /api/bots/:id/computer/recovery: what MausBot is doing about a bot's cloud computer that stopped answering,+ * and the computer panel's Restart computer and Replace computer. Admin-only like every computer route. */+export function createCloudComputerRecoveryRoutes(deps: CloudComputerRecoveryRouteDeps): RouteHandler {+ return async ({ req, res, path, method, json, readBody }) => {+ const m = path.match(/^\/api\/bots\/([\w-]+)\/computer\/recovery$/);+ if (!m || (method !== "GET" && method !== "POST")) return PASS;+ const bot = deps.store.bot(m[1]!);+ if (!bot) return json(res, 404, { error: "no such bot" });+ const owner = deps.botComputerControlKey(bot);+ if (method === "GET") {+ res.setHeader("cache-control", "private, no-store");+ return json(res, 200, { recovery: owner === bot.id ? deps.boatRecovery.status(owner) : null });+ }+ if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {+ return json(res, 415, { error: "content-type must be application/json" });+ }+ const action = (await readBody(req))?.action;+ if (action !== "restart" && action !== "replace") return json(res, 400, { error: "action must be restart or replace" });+ if (bot.cloudBackend === "vps") return json(res, 409, { error: "This bot uses a VPS, not a cloud computer." });+ if (owner !== bot.id) return json(res, 409, { error: "Manage this shared computer from the Team map" });+ if (deps.computerProviderConfigTransitions.has("box")) return json(res, 409, { error: deps.providerTransitionMessage("box") });+ // A turn may be waiting on the computer that stopped answering; a working computer is left alone while it is used.+ if (deps.botHasActiveTurn(bot.id) && !deps.boatRecovery.stuck(owner)) {+ return json(res, 409, { error: "this bot is using its cloud computer — interrupt it first" });+ }+ const release = deps.claimBotComputerLifecycle(bot.id, true);+ try {+ return json(res, 200, action === "restart" ? await deps.boatRecovery.restart(owner) : await deps.boatRecovery.replace(owner));+ } finally {+ release();+ deps.cloudComputerUsed(owner);+ }+ };+}diff --git a/server/routes/computer-frames.ts b/server/routes/computer-frames.tsindex 37fa483b85..1ac75176a0 100644--- a/server/routes/computer-frames.ts+++ b/server/routes/computer-frames.ts@@ -1,4 +1,5 @@import * as boat from "../boat.ts";+import { boatHealth } from "../boat-health.ts";import type { ComputerControl } from "../computer-control.ts";import type { MapComputer, MapComputersPayload } from "../../shared/map-computer.ts";import { createComputerFrames, mapComputerState, type ComputerFrames, type FrameMachine } from "../computer-frames.ts";@@ -92,7 +93,7 @@ export function createComputerFramesRoutes(deps: ComputerFramesRouteDeps, framesconst inventory = await boat.listManagedBoats(cfg, deps.managedBoatOwners(), { adoptLegacy: false });if (!inventory.available) return null;return inventory.instances.flatMap((instance) => instance.ownerBotId && instance.state !== "removing"- ? [{ owner: instance.ownerBotId, boxId: instance.boxId, state: instance.state }] : []);+ ? [{ owner: instance.ownerBotId, boxId: instance.boxId, state: boatHealth.notRespondingSince(instance.boxId) === null ? instance.state : "error" }] : []);},capture: (boxId, signal) => captureThumbnail(cfg, boxId, signal),turnFrame: (boxId) => {diff --git a/server/routes/computers.ts b/server/routes/computers.tsindex 9afec2a57c..3b9c242a87 100644--- a/server/routes/computers.ts+++ b/server/routes/computers.ts@@ -1,5 +1,6 @@import { z, type ZodString } from "zod";import * as boat from "../boat.ts";+import { boatHealth } from "../boat-health.ts";import type { ComputerControl } from "../computer-control.ts";import { isValidSshAlias, localVmMaxInstances, localVmMode, localVmResources, type AppConfig } from "../config.ts";import {@@ -26,6 +27,7 @@ import { teamComputerAssignment, teamComputerCreate, teamComputerOwner, type Teaimport * as vps from "../vps-computer.ts";import { vpsAliasesInPlay } from "../vps-hosts.ts";import type { BusyFlag, RemoteComputerProvider } from "./config.ts";+import { createCloudComputerRecoveryRoutes, type CloudComputerRecoveryRouteDeps } from "./cloud-computer-recovery.ts";import { createComputerFramesRoutes } from "./computer-frames.ts";import { createComputerUsageRoutes } from "./computer-usage.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -79,6 +81,9 @@ export interface ComputerRouteDeps {claimManagedVpsMutation(containerName: string): () => void;/** A cloud computer was just woken, created or opened: its idle window starts again. */cloudComputerUsed(owner: string): void;+ boatRecovery: CloudComputerRecoveryRouteDeps["boatRecovery"];+ /** Whose cloud computer a bot uses: its own id, or its team computer's key. */+ cloudComputerOwner(bot: BotRecord): string;}export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {@@ -95,9 +100,11 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {const usage = createComputerUsageRoutes(deps);// A map owner is a bot id or a team computer's key; a bot's hold may sit on the shared desktop's key.const frames = createComputerFramesRoutes({ ...deps, computerControl: { snapshot: botComputerControlSnapshot } });+ const recovery = createCloudComputerRecoveryRoutes({ ...deps, botComputerControlKey: deps.cloudComputerOwner });return async (context) => {if (await usage(context) !== PASS) return;if (await frames(context) !== PASS) return;+ if (await recovery(context) !== PASS) return;const { req, res, url, path, method, auth, json, readBody } = context;const routines = deps.routines();let m: RegExpMatchArray | null = null;@@ -204,7 +211,10 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {// Read-only; lifecycle changes are revalidated against a fresh provider listing. The path keeps its historical /boxes segment.if (method === "GET" && path === "/api/computers/boxes") {res.setHeader("cache-control", "private, no-store");- return json(res, 200, await boat.listManagedBoats(cfg, managedBoatOwners()));+ const inventory = await boat.listManagedBoats(cfg, managedBoatOwners());+ // A computer that stopped answering is not shown running, whatever the provider still says.+ return json(res, 200, { ...inventory, instances: inventory.instances.map((instance) =>+ boatHealth.notRespondingSince(instance.boxId) === null ? instance : { ...instance, state: "error" }) });}m = path.match(/^\/api\/computers\/boxes\/([\w-]+)\/(sleep|delete)$/);if (m && method === "POST") {diff --git a/server/routes/desktop-viewer.ts b/server/routes/desktop-viewer.tsindex 0f444cd154..926c4200c5 100644--- a/server/routes/desktop-viewer.ts+++ b/server/routes/desktop-viewer.ts@@ -185,6 +185,8 @@ export function createDesktopViewer(deps: {}return closed;},+ /** Desktop viewers open on this bot's computer now. */+ viewing: (botId: string) => [...viewers.values()].filter((viewer) => viewer.botId === botId && !viewer.socket.destroyed).length,closeAll: () => {stopped = true;if (ownGate) upgrades.close();diff --git a/shared/cloud-computer-recovery.test.ts b/shared/cloud-computer-recovery.test.tsnew file mode 100644index 0000000000..25c85feb80--- /dev/null+++ b/shared/cloud-computer-recovery.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from "vitest";+import en from "../src/locales/en.json";+import { CLOUD_COMPUTER_PERSON_LINES } from "./cloud-computer-recovery.ts";++describe("the person's line about a cloud computer that stopped answering", () => {+ it("has words in the language packs, naming the bot", () => {+ for (const key of Object.values(CLOUD_COMPUTER_PERSON_LINES)) {+ expect((en as Record<string, string>)[key], key).toContain("{name}");+ }+ });+});diff --git a/shared/cloud-computer-recovery.ts b/shared/cloud-computer-recovery.tsnew file mode 100644index 0000000000..b740c55145--- /dev/null+++ b/shared/cloud-computer-recovery.ts@@ -0,0 +1,54 @@+/** What MausBot is doing about a cloud computer that stopped answering, as `GET /api/bots/:id/computer/recovery` reports it.+ * `not-responding`, `restarting` and `replacing` are under way; the others are how it ended. */+export const CLOUD_COMPUTER_RECOVERY_STATES = [+ "not-responding", "restarting", "replacing", "restarted", "replaced", "unreachable", "capped", "needs-person",+] as const;+export type CloudComputerRecoveryState = (typeof CLOUD_COMPUTER_RECOVERY_STATES)[number];++export interface CloudComputerRecovery {+ state: CloudComputerRecoveryState;+ at: number;+ /** The person asked for it from the computer panel. */+ manual?: true;+}++export const recoveryUnderWay = (state: CloudComputerRecoveryState): boolean =>+ state === "not-responding" || state === "restarting" || state === "replacing";++/** What the bot is told, in place of a computer call, while its computer is being restarted or replaced. */+export const CLOUD_COMPUTER_NOT_RESPONDING =+ "This bot's cloud computer isn't responding; MausBot is replacing it. Try again in a minute. Do not retry now.";+/** Told once, on the bot's first computer call after the replacement. */+export const CLOUD_COMPUTER_REPLACED =+ "This bot's cloud computer stopped responding and was replaced with a new one. Files that were only on the old computer are gone.";+export const CLOUD_COMPUTER_REPLACED_BY_PERSON =+ "This bot's cloud computer was replaced with a new one. Files that were only on the old computer are gone.";+export const CLOUD_COMPUTER_RESTARTED =+ "This bot's cloud computer stopped responding and was restarted. Programs that were open on it were closed; its files are still there.";+export const CLOUD_COMPUTER_UNREACHABLE =+ "Cloud computers can't be reached right now. This call may not have run. Try again in a few minutes.";+export const CLOUD_COMPUTER_CAPPED =+ "This bot's cloud computer isn't responding, and it was already replaced once in the last hour, so MausBot stopped replacing it. Do not retry computer work in this turn; tell the person.";+/** Automatic replacement is off: the person decides, from the computer panel. */+export const CLOUD_COMPUTER_NEEDS_PERSON =+ "This bot's cloud computer isn't responding. The person can replace it from the computer panel. Do not retry computer work in this turn; tell the person.";+/** A team's shared computer is never restarted or deleted by itself: every teammate's work is on it. */+export const CLOUD_COMPUTER_TEAM_NOT_RESPONDING =+ "This team's shared cloud computer isn't responding. A team admin can delete it in Settings → Computers and create it again from the Team map. Do not retry computer work in this turn; tell the person.";+/** The provider says the machine is gone, but not yet for long enough to delete it by itself. */+export const CLOUD_COMPUTER_DEAD_WAITING =+ "This bot's cloud computer isn't responding. MausBot replaces it if it is still down in half an hour; the person can replace it now from the computer panel. Do not retry computer work in this turn; tell the person.";+/** One command got no answer; the computer is not judged on one. */+export const CLOUD_COMPUTER_NO_ANSWER =+ "The cloud computer did not answer this call, so it may not have run. Take a fresh screenshot in a moment before repeating it.";++/** The person's one line in the chat and the Inbox, by its language pack key; each takes the bot's `{name}`. */+export const CLOUD_COMPUTER_PERSON_LINES = {+ replaced: "server.cloudComputer.replaced",+ restarted: "server.cloudComputer.restarted",+ capped: "server.cloudComputer.capped",+ unreachable: "server.cloudComputer.unreachable",+ needsPerson: "server.cloudComputer.needsPerson",+ teamNotResponding: "server.cloudComputer.teamNotResponding",+} as const;+export type CloudComputerPersonLine = keyof typeof CLOUD_COMPUTER_PERSON_LINES;diff --git a/src/components/CloudComputerRecovery.dom.test.ts b/src/components/CloudComputerRecovery.dom.test.tsnew file mode 100644index 0000000000..c15a6730a7--- /dev/null+++ b/src/components/CloudComputerRecovery.dom.test.ts@@ -0,0 +1,85 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const calls: Array<{ path: string; init?: { method?: string; body?: string } }> = [];+let status: unknown = null;+let answer: unknown = { answers: true };+vi.mock("@/state/store", async (original) => ({+ ...await original<typeof import("@/state/store")>(),+ api: vi.fn(async (path: string, init?: { method?: string; body?: string }) => {+ calls.push({ path, init });+ return init?.method === "POST" ? answer : { recovery: status };+ }),+}));++import { CloudComputerRecoveryRow } from "./CloudComputerRecovery";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let host: HTMLDivElement;+let root: Root;+beforeEach(() => {+ calls.length = 0;+ status = null;+ answer = { answers: true };+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+});++const render = async (always = true) => {+ await act(async () => { root.render(createElement(CloudComputerRecoveryRow, { botId: "bot-1", name: "Ada", always })); });+};+const button = (label: string) => [...host.querySelectorAll("button")].find((candidate) => candidate.textContent?.includes(label))!;++describe("the computer panel's recovery row", () => {+ it("shows nothing in Simple mode while the computer is fine", async () => {+ await render(false);+ expect(host.querySelector("[data-testid=cloud-computer-recovery]")).toBeNull();+ });++ it("shows what MausBot did, in Simple mode too, with the buttons", async () => {+ status = { state: "replaced", at: 1 };+ await render(false);+ expect(host.textContent).toContain("Ada's cloud computer stopped responding, so MausBot replaced it with a new one. Files that were only on the old computer are gone.");+ expect(button("Restart computer")).toBeTruthy();+ expect(button("Replace computer")).toBeTruthy();+ });++ it("holds the buttons while a restart or replacement is under way", async () => {+ status = { state: "replacing", at: 1 };+ await render();+ expect(host.textContent).toContain("This cloud computer isn't responding. MausBot is replacing it.");+ expect(button("Restart computer").disabled).toBe(true);+ expect(button("Replace computer").disabled).toBe(true);+ });++ it("restarts on one click and says when the computer still does not answer", async () => {+ answer = { answers: false };+ await render();+ await act(async () => { button("Restart computer").click(); });+ expect(calls.find((call) => call.init?.method === "POST")).toEqual({ path: "/api/bots/bot-1/computer/recovery", init: { method: "POST", body: JSON.stringify({ action: "restart" }) } });+ expect(host.textContent).toContain("The cloud computer still isn't answering after a restart. Replace computer gives Ada a new one.");+ });++ it("replaces only after the person confirms that files only on it are lost", async () => {+ const confirm = vi.fn(() => false);+ vi.stubGlobal("confirm", confirm);+ window.confirm = confirm;+ await render();+ await act(async () => { button("Replace computer").click(); });+ expect(confirm).toHaveBeenCalledWith("Replace Ada's cloud computer with a new one? Files that are only on this computer are lost.");+ expect(calls.some((call) => call.init?.method === "POST")).toBe(false);+ confirm.mockReturnValue(true);+ answer = { replaced: true };+ await act(async () => { button("Replace computer").click(); });+ expect(calls.filter((call) => call.init?.method === "POST").map((call) => call.init?.body)).toEqual([JSON.stringify({ action: "replace" })]);+ });+});diff --git a/src/components/CloudComputerRecovery.tsx b/src/components/CloudComputerRecovery.tsxnew file mode 100644index 0000000000..2f4dc4a2a6--- /dev/null+++ b/src/components/CloudComputerRecovery.tsx@@ -0,0 +1,93 @@+import { useCallback, useEffect, useState } from "react";+import { Loader2, RefreshCw, RotateCcw } from "lucide-react";+import { api } from "@/state/store";+import { t } from "@/lib/i18n";+import type { LocaleKey } from "@/locales";+import { recoveryUnderWay, type CloudComputerRecovery, type CloudComputerRecoveryState } from "../../shared/cloud-computer-recovery";++const POLL_MS = 15_000;++const LINES: Record<CloudComputerRecoveryState, LocaleKey> = {+ "not-responding": "computer.recovery.notResponding",+ restarting: "computer.recovery.restarting",+ replacing: "computer.recovery.replacing",+ restarted: "server.cloudComputer.restarted",+ replaced: "server.cloudComputer.replaced",+ unreachable: "server.cloudComputer.unreachable",+ capped: "server.cloudComputer.capped",+ "needs-person": "server.cloudComputer.needsPerson",+};++/** The line the computer panel shows; an action the person took is worded as theirs. */+export function recoveryLine(recovery: CloudComputerRecovery, name: string): string {+ if (recovery.manual && recovery.state === "replaced") return t("computer.recovery.replacedManual", { name });+ if (recovery.manual && recovery.state === "restarted") return t("computer.recovery.restartedManual");+ return t(LINES[recovery.state], { name });+}++/** What MausBot is doing about a cloud computer that stopped answering, and the person's Restart computer and Replace computer. */+/** `always`: the buttons show even while nothing is wrong (Advanced); otherwise only once MausBot is dealing with the computer. */+export function CloudComputerRecoveryRow({ botId, name, always }: { botId: string; name: string; always?: boolean }) {+ const [recovery, setRecovery] = useState<CloudComputerRecovery | null>(null);+ const [pending, setPending] = useState<"restart" | "replace" | null>(null);+ const [result, setResult] = useState<string | null>(null);+ const path = `/api/bots/${botId}/computer/recovery`;++ const refresh = useCallback(() => {+ api<{ recovery: CloudComputerRecovery | null }>(path, { background: true })+ .then((body) => setRecovery(body.recovery ?? null))+ .catch(() => {});+ }, [path]);++ useEffect(() => {+ refresh();+ const timer = window.setInterval(refresh, POLL_MS);+ return () => window.clearInterval(timer);+ }, [refresh]);++ const act = async (action: "restart" | "replace") => {+ if (action === "replace" && !window.confirm(t("computer.recovery.confirmReplace", { name }))) return;+ setPending(action);+ setResult(null);+ try {+ const out = await api<{ answers?: boolean }>(path, { method: "POST", body: JSON.stringify({ action }) });+ if (action === "restart" && !out.answers) setResult(t("computer.recovery.stillNotAnswering", { name }));+ } catch (error) {+ setResult(error instanceof Error ? error.message : String(error));+ } finally {+ setPending(null);+ refresh();+ }+ };++ const busy = pending !== null || Boolean(recovery && recoveryUnderWay(recovery.state));+ if (!always && !recovery && !result) return null;+ return (+ <div className="mt-3" data-testid="cloud-computer-recovery">+ {recovery && <p className="text-[12px] leading-5 text-ink-secondary" role="status">{recoveryLine(recovery, name)}</p>}+ {result && <p className="text-[12px] leading-5 text-danger" role="alert">{result}</p>}+ <div className="mt-2 flex flex-wrap gap-2">+ <button+ type="button"+ onClick={() => void act("restart")}+ disabled={busy}+ className="flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50"+ title={t("computer.recovery.restartTitle")}+ >+ {pending === "restart" ? <Loader2 size={14} className="animate-spin" /> : <RotateCcw size={14} />}+ {t("computer.recovery.restart")}+ </button>+ <button+ type="button"+ onClick={() => void act("replace")}+ disabled={busy}+ className="flex flex-auto items-center justify-center gap-2 whitespace-nowrap rounded-lg border border-danger/30 px-3 py-2 text-[13px] text-danger hover:bg-danger/10 disabled:opacity-50"+ title={t("computer.recovery.replaceTitle")}+ >+ {pending === "replace" ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}+ {t("computer.recovery.replace")}+ </button>+ </div>+ </div>+ );+}diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsxindex 8a372cafa2..a10cc697b6 100644--- a/src/components/ComputerPanel.tsx+++ b/src/components/ComputerPanel.tsx@@ -17,7 +17,7 @@ import { cn } from "@/lib/cn";import { useCaptionChrome } from "@/components/DesktopCapabilities";import { usePageVisible } from "@/lib/page-visible";import { listenLiveFrames } from "@/lib/live-events";-import { CloudScreenPreview } from "./CloudScreenPreview"; import { ResetCloudComputerButton } from "./ResetCloudComputerButton";+import { CloudScreenPreview } from "./CloudScreenPreview"; import { ResetCloudComputerButton } from "./ResetCloudComputerButton"; import { CloudComputerRecoveryRow } from "./CloudComputerRecovery";import { isActiveTurnRefusal, isRemoteScreenshotContention } from "@/lib/remote-desktop";import { CloudBackendPicker } from "./CloudBackendPicker";import { SimpleVpsChoices } from "./SimpleVpsChoices";@@ -1660,7 +1660,7 @@ export function ComputerPanel({)}</div>)}-+ {canManageCloud && cloudBackend !== "vps" && phase !== "unconfigured" && phase !== "team-boat" && teamComputer?.botId !== bot.id && <CloudComputerRecoveryRow botId={bot.id} name={bot.name} always={advanced} />}{phase !== "team-boat" && (bot.computer !== undefined || computerStatusCurrent) && <><LocalScreenPreview /><LinuxLocalControl />diff --git a/src/locales/de.json b/src/locales/de.jsonindex cb25b920ce..51974ea0b7 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -3955,5 +3955,22 @@"settings.simple.billing.included": "Inklusive Nutzung in diesem Monat","settings.simple.billing.summary": "{percent} % der inklusiven Nutzung in diesem Monat","settings.simple.billing.used": "genutzt",- "settings.skin.dressUp.title": "Meine Bots verkleiden"+ "settings.skin.dressUp.title": "Meine Bots verkleiden",+ "server.cloudComputer.replaced": "Der Cloud-Computer von {name} hat nicht mehr reagiert, deshalb hat MausBot ihn durch einen neuen ersetzt. Dateien, die nur auf dem alten Computer lagen, sind weg.",+ "server.cloudComputer.restarted": "Der Cloud-Computer von {name} hat nicht mehr reagiert, deshalb hat MausBot ihn neu gestartet. Er antwortet wieder; Programme, die darauf geöffnet waren, wurden geschlossen.",+ "server.cloudComputer.capped": "Der Cloud-Computer von {name} hat innerhalb einer Stunde nach dem Ersetzen wieder nicht reagiert, deshalb hat MausBot ihn so gelassen. „Computer ersetzen“ im Computer-Bereich versucht es noch einmal.",+ "server.cloudComputer.unreachable": "Cloud-Computer sind gerade nicht erreichbar. MausBot hat den Cloud-Computer von {name} behalten und prüft ihn erneut.",+ "server.cloudComputer.needsPerson": "Der Cloud-Computer von {name} reagiert nicht mehr. „Computer ersetzen“ im Computer-Bereich gibt einen neuen; Dateien, die nur auf dem alten Computer liegen, gehen verloren.",+ "server.cloudComputer.teamNotResponding": "{name} reagiert nicht. Löschen Sie ihn unter Einstellungen → Computer und erstellen Sie ihn dann in der Team-Übersicht neu; Dateien, die nur darauf liegen, gehen verloren.",+ "computer.recovery.notResponding": "Dieser Cloud-Computer reagiert nicht. MausBot prüft ihn und startet ihn neu oder ersetzt ihn.",+ "computer.recovery.restarting": "Dieser Cloud-Computer reagiert nicht. MausBot startet ihn neu.",+ "computer.recovery.replacing": "Dieser Cloud-Computer reagiert nicht. MausBot ersetzt ihn.",+ "computer.recovery.replacedManual": "Ersetzt. {name} bekommt einen neuen Cloud-Computer, sobald einer gebraucht wird.",+ "computer.recovery.restartedManual": "Neu gestartet. Der Cloud-Computer antwortet wieder.",+ "computer.recovery.stillNotAnswering": "Der Cloud-Computer antwortet auch nach dem Neustart nicht. „Computer ersetzen“ gibt {name} einen neuen.",+ "computer.recovery.confirmReplace": "Den Cloud-Computer von {name} durch einen neuen ersetzen? Dateien, die nur auf diesem Computer liegen, gehen verloren.",+ "computer.recovery.restart": "Computer neu starten",+ "computer.recovery.restartTitle": "Diesen Cloud-Computer stoppen und wieder starten. Geöffnete Programme werden geschlossen; die Dateien bleiben.",+ "computer.recovery.replace": "Computer ersetzen",+ "computer.recovery.replaceTitle": "Diesen Cloud-Computer löschen und dem Bot einen neuen geben. Dateien, die nur darauf liegen, gehen verloren."}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 00e6f7e9a7..dc44eed658 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -8215,6 +8215,23 @@"chat.notice.stalledCommand": "the command `{command}` ran for {minutes} minutes without finishing and looks stuck — the turn was stopped","chat.notice.followupInterrupted": "Queued follow-up interrupted by restart or restore — it may have already run. Review the result before sending it again.","chat.notice.usageLimit": "This {provider} account has reached its usage limit{detail}. Wait for it to reset, or switch this bot to another AI.",+ "server.cloudComputer.replaced": "{name}'s cloud computer stopped responding, so MausBot replaced it with a new one. Files that were only on the old computer are gone.",+ "server.cloudComputer.restarted": "{name}'s cloud computer stopped responding, so MausBot restarted it. It answers again; programs that were open on it were closed.",+ "server.cloudComputer.capped": "{name}'s cloud computer stopped responding again within an hour of being replaced, so MausBot left it as it is. Replace computer in the computer panel tries once more.",+ "server.cloudComputer.unreachable": "Cloud computers can't be reached right now. MausBot kept {name}'s cloud computer and will check it again.",+ "server.cloudComputer.needsPerson": "{name}'s cloud computer stopped responding. Replace computer in the computer panel gives it a new one; files only on the old computer are lost.",+ "server.cloudComputer.teamNotResponding": "{name} isn't responding. Delete it in Settings → Computers, then create it again from the Team map; files only on it are lost.",+ "computer.recovery.notResponding": "This cloud computer isn't responding. MausBot is checking it and will restart or replace it.",+ "computer.recovery.restarting": "This cloud computer isn't responding. MausBot is restarting it.",+ "computer.recovery.replacing": "This cloud computer isn't responding. MausBot is replacing it.",+ "computer.recovery.replacedManual": "Replaced. {name} gets a new cloud computer the next time it needs one.",+ "computer.recovery.restartedManual": "Restarted. The cloud computer answers again.",+ "computer.recovery.stillNotAnswering": "The cloud computer still isn't answering after a restart. Replace computer gives {name} a new one.",+ "computer.recovery.confirmReplace": "Replace {name}'s cloud computer with a new one? Files that are only on this computer are lost.",+ "computer.recovery.restart": "Restart computer",+ "computer.recovery.restartTitle": "Stop and start this cloud computer. Programs open on it are closed; its files stay.",+ "computer.recovery.replace": "Replace computer",+ "computer.recovery.replaceTitle": "Delete this cloud computer and give the bot a new one. Files only on it are lost.","chat.notice.claudeExtraUsage": "Claude refused this turn because this model runs on extra usage for your account, and those credits are used up. Your plan's own usage is not affected: switch this bot to a model your plan includes, or add extra usage in your Claude account.","chat.notice.claudeLimitResets": "This Claude account has reached its {limit}, which resets {resets}. Until then, {meanwhile}.","chat.notice.claudeLimitSaid": "This Claude account has reached its {limit} (Claude says: \"{said}\"). For now, {meanwhile}.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex b17d4c3e80..7b5e222f7c 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6480,5 +6480,22 @@"settings.simple.billing.included": "Uso incluido de este mes","settings.simple.billing.summary": "{percent} % del uso incluido de este mes","settings.simple.billing.used": "usado",- "settings.skin.dressUp.title": "Disfrazar a mis bots"+ "settings.skin.dressUp.title": "Disfrazar a mis bots",+ "server.cloudComputer.replaced": "La computadora en la nube de {name} dejó de responder, así que MausBot la reemplazó por una nueva. Los archivos que solo estaban en la computadora anterior se perdieron.",+ "server.cloudComputer.restarted": "La computadora en la nube de {name} dejó de responder, así que MausBot la reinició. Ya responde de nuevo; los programas que tenía abiertos se cerraron.",+ "server.cloudComputer.capped": "La computadora en la nube de {name} volvió a dejar de responder menos de una hora después de ser reemplazada, así que MausBot la dejó como está. Reemplazar computadora, en el panel de la computadora, lo intenta una vez más.",+ "server.cloudComputer.unreachable": "Ahora mismo no se puede acceder a las computadoras en la nube. MausBot conservó la computadora en la nube de {name} y la volverá a revisar.",+ "server.cloudComputer.needsPerson": "La computadora en la nube de {name} dejó de responder. Reemplazar computadora, en el panel de la computadora, le da una nueva; los archivos que solo están en la computadora anterior se pierden.",+ "server.cloudComputer.teamNotResponding": "{name} no responde. Elimínala en Ajustes → Computadoras y vuelve a crearla desde el mapa del equipo; los archivos que solo están en ella se pierden.",+ "computer.recovery.notResponding": "Esta computadora en la nube no responde. MausBot la está revisando y la reiniciará o la reemplazará.",+ "computer.recovery.restarting": "Esta computadora en la nube no responde. MausBot la está reiniciando.",+ "computer.recovery.replacing": "Esta computadora en la nube no responde. MausBot la está reemplazando.",+ "computer.recovery.replacedManual": "Reemplazada. {name} recibirá una computadora en la nube nueva la próxima vez que la necesite.",+ "computer.recovery.restartedManual": "Reiniciada. La computadora en la nube vuelve a responder.",+ "computer.recovery.stillNotAnswering": "La computadora en la nube sigue sin responder después de reiniciarla. Reemplazar computadora le da a {name} una nueva.",+ "computer.recovery.confirmReplace": "¿Reemplazar la computadora en la nube de {name} por una nueva? Los archivos que solo están en esta computadora se perderán.",+ "computer.recovery.restart": "Reiniciar computadora",+ "computer.recovery.restartTitle": "Detiene y vuelve a iniciar esta computadora en la nube. Los programas abiertos se cierran; sus archivos se conservan.",+ "computer.recovery.replace": "Reemplazar computadora",+ "computer.recovery.replaceTitle": "Elimina esta computadora en la nube y le da una nueva al bot. Los archivos que solo están en ella se pierden."}diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 602cd8ca46..7c86b7dd67 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3782,5 +3782,22 @@"settings.simple.billing.included": "Utilisation incluse ce mois-ci","settings.simple.billing.summary": "{percent} % de l'utilisation incluse ce mois-ci","settings.simple.billing.used": "utilisé",- "settings.skin.dressUp.title": "Déguiser mes bots"+ "settings.skin.dressUp.title": "Déguiser mes bots",+ "server.cloudComputer.replaced": "L'ordinateur cloud de {name} ne répondait plus, alors MausBot l'a remplacé par un nouveau. Les fichiers qui n'étaient que sur l'ancien ordinateur sont perdus.",+ "server.cloudComputer.restarted": "L'ordinateur cloud de {name} ne répondait plus, alors MausBot l'a redémarré. Il répond de nouveau ; les programmes qui y étaient ouverts ont été fermés.",+ "server.cloudComputer.capped": "L'ordinateur cloud de {name} a de nouveau cessé de répondre moins d'une heure après avoir été remplacé, alors MausBot l'a laissé tel quel. Remplacer l'ordinateur, dans le panneau de l'ordinateur, réessaie une fois.",+ "server.cloudComputer.unreachable": "Les ordinateurs cloud sont injoignables pour le moment. MausBot a gardé l'ordinateur cloud de {name} et le vérifiera de nouveau.",+ "server.cloudComputer.needsPerson": "L'ordinateur cloud de {name} ne répond plus. Remplacer l'ordinateur, dans le panneau de l'ordinateur, lui en donne un nouveau ; les fichiers qui ne sont que sur l'ancien ordinateur sont perdus.",+ "server.cloudComputer.teamNotResponding": "{name} ne répond pas. Supprimez-le dans Réglages → Ordinateurs, puis recréez-le depuis la carte de l'équipe ; les fichiers qui ne sont que dessus sont perdus.",+ "computer.recovery.notResponding": "Cet ordinateur cloud ne répond pas. MausBot le vérifie et va le redémarrer ou le remplacer.",+ "computer.recovery.restarting": "Cet ordinateur cloud ne répond pas. MausBot le redémarre.",+ "computer.recovery.replacing": "Cet ordinateur cloud ne répond pas. MausBot le remplace.",+ "computer.recovery.replacedManual": "Remplacé. {name} aura un nouvel ordinateur cloud la prochaine fois qu'il en aura besoin.",+ "computer.recovery.restartedManual": "Redémarré. L'ordinateur cloud répond de nouveau.",+ "computer.recovery.stillNotAnswering": "L'ordinateur cloud ne répond toujours pas après un redémarrage. Remplacer l'ordinateur donne un nouvel ordinateur à {name}.",+ "computer.recovery.confirmReplace": "Remplacer l'ordinateur cloud de {name} par un nouveau ? Les fichiers qui ne sont que sur cet ordinateur seront perdus.",+ "computer.recovery.restart": "Redémarrer l'ordinateur",+ "computer.recovery.restartTitle": "Arrête puis relance cet ordinateur cloud. Les programmes ouverts sont fermés ; ses fichiers restent.",+ "computer.recovery.replace": "Remplacer l'ordinateur",+ "computer.recovery.replaceTitle": "Supprime cet ordinateur cloud et en donne un nouveau au bot. Les fichiers qui ne sont que dessus sont perdus."}diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 743e555521..b3d5693a48 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3636,5 +3636,22 @@"settings.simple.billing.included": "इस महीने का शामिल इस्तेमाल","settings.simple.billing.summary": "इस महीने के शामिल इस्तेमाल का {percent}%","settings.simple.billing.used": "इस्तेमाल हुआ",- "settings.skin.dressUp.title": "मेरे बॉट्स को सजाएँ"+ "settings.skin.dressUp.title": "मेरे बॉट्स को सजाएँ",+ "server.cloudComputer.replaced": "{name} का क्लाउड कंप्यूटर जवाब नहीं दे रहा था, इसलिए MausBot ने उसे नए कंप्यूटर से बदल दिया। जो फ़ाइलें सिर्फ़ पुराने कंप्यूटर पर थीं, वे अब नहीं रहीं।",+ "server.cloudComputer.restarted": "{name} का क्लाउड कंप्यूटर जवाब नहीं दे रहा था, इसलिए MausBot ने उसे फिर से चालू किया। अब वह फिर जवाब दे रहा है; उस पर खुले प्रोग्राम बंद हो गए।",+ "server.cloudComputer.capped": "{name} का क्लाउड कंप्यूटर बदले जाने के एक घंटे के अंदर फिर से जवाब देना बंद कर गया, इसलिए MausBot ने उसे वैसे ही छोड़ दिया। कंप्यूटर पैनल में कंप्यूटर बदलें एक बार और कोशिश करता है।",+ "server.cloudComputer.unreachable": "अभी क्लाउड कंप्यूटर तक पहुँचा नहीं जा सकता। MausBot ने {name} का क्लाउड कंप्यूटर रखा है और उसे फिर से जाँचेगा।",+ "server.cloudComputer.needsPerson": "{name} का क्लाउड कंप्यूटर जवाब नहीं दे रहा। कंप्यूटर पैनल में कंप्यूटर बदलें से नया कंप्यूटर मिलता है; जो फ़ाइलें सिर्फ़ पुराने कंप्यूटर पर हैं, वे खो जाती हैं।",+ "server.cloudComputer.teamNotResponding": "{name} जवाब नहीं दे रहा। इसे सेटिंग्स → कंप्यूटर में हटाएँ, फिर टीम मैप से दोबारा बनाएँ; जो फ़ाइलें सिर्फ़ इस पर हैं, वे खो जाएँगी।",+ "computer.recovery.notResponding": "यह क्लाउड कंप्यूटर जवाब नहीं दे रहा। MausBot इसे जाँच रहा है और इसे फिर से चालू करेगा या बदल देगा।",+ "computer.recovery.restarting": "यह क्लाउड कंप्यूटर जवाब नहीं दे रहा। MausBot इसे फिर से चालू कर रहा है।",+ "computer.recovery.replacing": "यह क्लाउड कंप्यूटर जवाब नहीं दे रहा। MausBot इसे बदल रहा है।",+ "computer.recovery.replacedManual": "बदल दिया गया। अगली बार ज़रूरत होने पर {name} को नया क्लाउड कंप्यूटर मिलेगा।",+ "computer.recovery.restartedManual": "फिर से चालू किया गया। क्लाउड कंप्यूटर फिर जवाब दे रहा है।",+ "computer.recovery.stillNotAnswering": "फिर से चालू करने के बाद भी क्लाउड कंप्यूटर जवाब नहीं दे रहा। कंप्यूटर बदलें से {name} को नया कंप्यूटर मिलेगा।",+ "computer.recovery.confirmReplace": "{name} के क्लाउड कंप्यूटर को नए से बदलें? जो फ़ाइलें सिर्फ़ इसी कंप्यूटर पर हैं, वे खो जाएँगी।",+ "computer.recovery.restart": "कंप्यूटर फिर से चालू करें",+ "computer.recovery.restartTitle": "इस क्लाउड कंप्यूटर को बंद करके फिर से चालू करें। खुले प्रोग्राम बंद हो जाते हैं; फ़ाइलें बनी रहती हैं।",+ "computer.recovery.replace": "कंप्यूटर बदलें",+ "computer.recovery.replaceTitle": "यह क्लाउड कंप्यूटर हटाकर बॉट को नया दें। जो फ़ाइलें सिर्फ़ इस पर हैं, वे खो जाती हैं।"}diff --git a/src/locales/it.json b/src/locales/it.jsonindex e428195e54..2b850ca62f 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -7103,5 +7103,22 @@"backup.excluded": "Le credenziali degli account salvate e le connessioni non sono incluse. Ricollega i tuoi account sul nuovo computer; le credenziali già presenti lì non cambiano. Non sono inclusi nemmeno gli accessi ad altre app AI e i dischi dei desktop remoti.","settings.simple.billing.included": "Uso incluso di questo mese","settings.simple.billing.summary": "{percent}% dell'uso incluso di questo mese",- "settings.simple.billing.used": "usato"+ "settings.simple.billing.used": "usato",+ "server.cloudComputer.replaced": "Il computer cloud di {name} non rispondeva più, quindi MausBot l'ha sostituito con uno nuovo. I file che erano solo sul vecchio computer sono andati persi.",+ "server.cloudComputer.restarted": "Il computer cloud di {name} non rispondeva più, quindi MausBot l'ha riavviato. Ora risponde di nuovo; i programmi aperti sono stati chiusi.",+ "server.cloudComputer.capped": "Il computer cloud di {name} ha smesso di nuovo di rispondere entro un'ora dalla sostituzione, quindi MausBot l'ha lasciato com'è. Sostituisci computer, nel pannello del computer, riprova una volta.",+ "server.cloudComputer.unreachable": "Al momento i computer cloud non sono raggiungibili. MausBot ha tenuto il computer cloud di {name} e lo ricontrollerà.",+ "server.cloudComputer.needsPerson": "Il computer cloud di {name} non risponde più. Sostituisci computer, nel pannello del computer, gliene dà uno nuovo; i file che sono solo sul vecchio computer vanno persi.",+ "server.cloudComputer.teamNotResponding": "{name} non risponde. Eliminalo in Impostazioni → Computer, poi ricrealo dalla mappa del team; i file che sono solo lì vanno persi.",+ "computer.recovery.notResponding": "Questo computer cloud non risponde. MausBot lo sta controllando e lo riavvierà o lo sostituirà.",+ "computer.recovery.restarting": "Questo computer cloud non risponde. MausBot lo sta riavviando.",+ "computer.recovery.replacing": "Questo computer cloud non risponde. MausBot lo sta sostituendo.",+ "computer.recovery.replacedManual": "Sostituito. {name} avrà un nuovo computer cloud la prossima volta che ne avrà bisogno.",+ "computer.recovery.restartedManual": "Riavviato. Il computer cloud risponde di nuovo.",+ "computer.recovery.stillNotAnswering": "Il computer cloud non risponde ancora dopo il riavvio. Sostituisci computer dà a {name} un computer nuovo.",+ "computer.recovery.confirmReplace": "Sostituire il computer cloud di {name} con uno nuovo? I file che sono solo su questo computer andranno persi.",+ "computer.recovery.restart": "Riavvia computer",+ "computer.recovery.restartTitle": "Ferma e riavvia questo computer cloud. I programmi aperti vengono chiusi; i suoi file restano.",+ "computer.recovery.replace": "Sostituisci computer",+ "computer.recovery.replaceTitle": "Elimina questo computer cloud e ne dà uno nuovo al bot. I file che sono solo lì vanno persi."}diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 6b4db993cb..d235dce651 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -8074,5 +8074,22 @@"settings.domain.change": "変更","settings.domain.httpsFirst": "まずこのアドレスで HTTPS を有効にしてから、ここで接続します。","settings.backTo": "設定に戻る",- "devices.route.httpsAccount": "{app} アカウントを使います。"+ "devices.route.httpsAccount": "{app} アカウントを使います。",+ "server.cloudComputer.replaced": "{name} のクラウドコンピューターが応答しなくなったため、MausBot が新しいものに置き換えました。古いコンピューターにしかなかったファイルは失われました。",+ "server.cloudComputer.restarted": "{name} のクラウドコンピューターが応答しなくなったため、MausBot が再起動しました。再び応答しています。開いていたプログラムは閉じられました。",+ "server.cloudComputer.capped": "{name} のクラウドコンピューターが置き換えから 1 時間以内に再び応答しなくなったため、MausBot はそのままにしました。コンピューターパネルの「コンピューターを置き換え」でもう一度試せます。",+ "server.cloudComputer.unreachable": "現在クラウドコンピューターに接続できません。MausBot は {name} のクラウドコンピューターを残し、あとで再確認します。",+ "server.cloudComputer.needsPerson": "{name} のクラウドコンピューターが応答しなくなりました。コンピューターパネルの「コンピューターを置き換え」で新しいものにできます。古いコンピューターにしかないファイルは失われます。",+ "server.cloudComputer.teamNotResponding": "{name} が応答していません。設定 → コンピューターで削除し、チームマップから作り直してください。そこにしかないファイルは失われます。",+ "computer.recovery.notResponding": "このクラウドコンピューターは応答していません。MausBot が確認し、再起動または置き換えを行います。",+ "computer.recovery.restarting": "このクラウドコンピューターは応答していません。MausBot が再起動しています。",+ "computer.recovery.replacing": "このクラウドコンピューターは応答していません。MausBot が置き換えています。",+ "computer.recovery.replacedManual": "置き換えました。{name} は次に必要になったときに新しいクラウドコンピューターを使います。",+ "computer.recovery.restartedManual": "再起動しました。クラウドコンピューターは再び応答しています。",+ "computer.recovery.stillNotAnswering": "再起動してもクラウドコンピューターが応答しません。「コンピューターを置き換え」で {name} に新しいものを用意できます。",+ "computer.recovery.confirmReplace": "{name} のクラウドコンピューターを新しいものに置き換えますか?このコンピューターにしかないファイルは失われます。",+ "computer.recovery.restart": "コンピューターを再起動",+ "computer.recovery.restartTitle": "このクラウドコンピューターを停止して起動し直します。開いているプログラムは閉じられますが、ファイルは残ります。",+ "computer.recovery.replace": "コンピューターを置き換え",+ "computer.recovery.replaceTitle": "このクラウドコンピューターを削除し、ボットに新しいものを用意します。ここにしかないファイルは失われます。"}diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex 121642dcd3..ac4934f39f 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7758,5 +7758,22 @@"settings.domain.change": "변경","settings.domain.httpsFirst": "먼저 이 주소에 HTTPS를 켠 다음 여기에서 연결하세요.","settings.backTo": "설정으로 돌아가기",- "devices.route.httpsAccount": "{app} 계정을 사용합니다."+ "devices.route.httpsAccount": "{app} 계정을 사용합니다.",+ "server.cloudComputer.replaced": "{name}의 클라우드 컴퓨터가 응답하지 않아 MausBot이 새 컴퓨터로 교체했어요. 이전 컴퓨터에만 있던 파일은 사라졌어요.",+ "server.cloudComputer.restarted": "{name}의 클라우드 컴퓨터가 응답하지 않아 MausBot이 다시 시작했어요. 다시 응답하고 있으며, 열려 있던 프로그램은 닫혔어요.",+ "server.cloudComputer.capped": "{name}의 클라우드 컴퓨터가 교체된 지 한 시간 안에 다시 응답하지 않아 MausBot이 그대로 두었어요. 컴퓨터 패널의 컴퓨터 교체로 한 번 더 시도할 수 있어요.",+ "server.cloudComputer.unreachable": "지금은 클라우드 컴퓨터에 연결할 수 없어요. MausBot이 {name}의 클라우드 컴퓨터를 그대로 두고 다시 확인할게요.",+ "server.cloudComputer.needsPerson": "{name}의 클라우드 컴퓨터가 응답하지 않아요. 컴퓨터 패널의 컴퓨터 교체로 새 컴퓨터를 받을 수 있어요. 이전 컴퓨터에만 있는 파일은 사라져요.",+ "server.cloudComputer.teamNotResponding": "{name}이(가) 응답하지 않아요. 설정 → 컴퓨터에서 삭제한 뒤 팀 지도에서 다시 만드세요. 그 컴퓨터에만 있는 파일은 사라져요.",+ "computer.recovery.notResponding": "이 클라우드 컴퓨터가 응답하지 않아요. MausBot이 확인한 뒤 다시 시작하거나 교체할게요.",+ "computer.recovery.restarting": "이 클라우드 컴퓨터가 응답하지 않아요. MausBot이 다시 시작하는 중이에요.",+ "computer.recovery.replacing": "이 클라우드 컴퓨터가 응답하지 않아요. MausBot이 교체하는 중이에요.",+ "computer.recovery.replacedManual": "교체했어요. {name}은(는) 다음에 필요할 때 새 클라우드 컴퓨터를 받아요.",+ "computer.recovery.restartedManual": "다시 시작했어요. 클라우드 컴퓨터가 다시 응답해요.",+ "computer.recovery.stillNotAnswering": "다시 시작한 뒤에도 클라우드 컴퓨터가 응답하지 않아요. 컴퓨터 교체를 누르면 {name}에게 새 컴퓨터가 생겨요.",+ "computer.recovery.confirmReplace": "{name}의 클라우드 컴퓨터를 새 컴퓨터로 교체할까요? 이 컴퓨터에만 있는 파일은 사라져요.",+ "computer.recovery.restart": "컴퓨터 다시 시작",+ "computer.recovery.restartTitle": "이 클라우드 컴퓨터를 멈췄다가 다시 시작해요. 열린 프로그램은 닫히고 파일은 그대로 남아요.",+ "computer.recovery.replace": "컴퓨터 교체",+ "computer.recovery.replaceTitle": "이 클라우드 컴퓨터를 삭제하고 봇에게 새 컴퓨터를 줘요. 이 컴퓨터에만 있는 파일은 사라져요."}diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 9f9e85dc5e..40a44d83aa 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -7244,5 +7244,22 @@"backup.excluded": "Zapisane dane logowania do kont i połączenia nie są uwzględnione. Połącz konta ponownie na nowym komputerze; istniejące dane logowania w miejscu docelowym się nie zmienią. Nie są też uwzględnione logowania do innych aplikacji AI ani dyski zdalnych pulpitów.","settings.simple.billing.included": "Uwzględnione użycie w tym miesiącu","settings.simple.billing.summary": "{percent}% uwzględnionego użycia w tym miesiącu",- "settings.simple.billing.used": "użyto"+ "settings.simple.billing.used": "użyto",+ "server.cloudComputer.replaced": "Komputer w chmurze bota {name} przestał odpowiadać, więc MausBot zastąpił go nowym. Pliki, które były tylko na starym komputerze, przepadły.",+ "server.cloudComputer.restarted": "Komputer w chmurze bota {name} przestał odpowiadać, więc MausBot go uruchomił ponownie. Znów odpowiada; otwarte na nim programy zostały zamknięte.",+ "server.cloudComputer.capped": "Komputer w chmurze bota {name} znów przestał odpowiadać w ciągu godziny od wymiany, więc MausBot zostawił go bez zmian. Zastąp komputer w panelu komputera spróbuje jeszcze raz.",+ "server.cloudComputer.unreachable": "Komputery w chmurze są teraz nieosiągalne. MausBot zachował komputer w chmurze bota {name} i sprawdzi go ponownie.",+ "server.cloudComputer.needsPerson": "Komputer w chmurze bota {name} przestał odpowiadać. Zastąp komputer w panelu komputera daje nowy; pliki, które są tylko na starym komputerze, zostaną utracone.",+ "server.cloudComputer.teamNotResponding": "{name} nie odpowiada. Usuń go w Ustawienia → Komputery, a potem utwórz ponownie z mapy zespołu; pliki, które są tylko na nim, zostaną utracone.",+ "computer.recovery.notResponding": "Ten komputer w chmurze nie odpowiada. MausBot go sprawdza i uruchomi go ponownie albo zastąpi.",+ "computer.recovery.restarting": "Ten komputer w chmurze nie odpowiada. MausBot uruchamia go ponownie.",+ "computer.recovery.replacing": "Ten komputer w chmurze nie odpowiada. MausBot go zastępuje.",+ "computer.recovery.replacedManual": "Zastąpiono. {name} dostanie nowy komputer w chmurze, gdy następnym razem będzie go potrzebować.",+ "computer.recovery.restartedManual": "Uruchomiono ponownie. Komputer w chmurze znów odpowiada.",+ "computer.recovery.stillNotAnswering": "Komputer w chmurze nadal nie odpowiada po ponownym uruchomieniu. Zastąp komputer da botowi {name} nowy.",+ "computer.recovery.confirmReplace": "Zastąpić komputer w chmurze bota {name} nowym? Pliki, które są tylko na tym komputerze, zostaną utracone.",+ "computer.recovery.restart": "Uruchom komputer ponownie",+ "computer.recovery.restartTitle": "Zatrzymuje i ponownie uruchamia ten komputer w chmurze. Otwarte programy zostaną zamknięte; pliki zostają.",+ "computer.recovery.replace": "Zastąp komputer",+ "computer.recovery.replaceTitle": "Usuwa ten komputer w chmurze i daje botowi nowy. Pliki, które są tylko na nim, zostaną utracone."}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex fedb2e4dad..7d19d75f79 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10633,5 +10633,22 @@"settings.domain.change": "Alterar","settings.domain.httpsFirst": "Ative o HTTPS neste endereço primeiro e depois conecte-o aqui.","settings.backTo": "Voltar às Configurações",- "devices.route.httpsAccount": "Usa sua conta do {app}."+ "devices.route.httpsAccount": "Usa sua conta do {app}.",+ "server.cloudComputer.replaced": "O computador na nuvem de {name} parou de responder, então o MausBot o substituiu por um novo. Os arquivos que estavam só no computador antigo foram perdidos.",+ "server.cloudComputer.restarted": "O computador na nuvem de {name} parou de responder, então o MausBot o reiniciou. Ele voltou a responder; os programas que estavam abertos nele foram fechados.",+ "server.cloudComputer.capped": "O computador na nuvem de {name} parou de responder de novo menos de uma hora depois de ser substituído, então o MausBot o deixou como está. Substituir computador, no painel do computador, tenta mais uma vez.",+ "server.cloudComputer.unreachable": "Os computadores na nuvem não podem ser acessados agora. O MausBot manteve o computador na nuvem de {name} e vai verificá-lo de novo.",+ "server.cloudComputer.needsPerson": "O computador na nuvem de {name} parou de responder. Substituir computador, no painel do computador, dá um novo; os arquivos que estão só no computador antigo são perdidos.",+ "server.cloudComputer.teamNotResponding": "{name} não está respondendo. Exclua em Configurações → Computadores e crie de novo pelo mapa da equipe; os arquivos que estão só nele são perdidos.",+ "computer.recovery.notResponding": "Este computador na nuvem não está respondendo. O MausBot está verificando e vai reiniciá-lo ou substituí-lo.",+ "computer.recovery.restarting": "Este computador na nuvem não está respondendo. O MausBot está reiniciando ele.",+ "computer.recovery.replacing": "Este computador na nuvem não está respondendo. O MausBot está substituindo ele.",+ "computer.recovery.replacedManual": "Substituído. {name} vai ganhar um computador na nuvem novo na próxima vez que precisar.",+ "computer.recovery.restartedManual": "Reiniciado. O computador na nuvem voltou a responder.",+ "computer.recovery.stillNotAnswering": "O computador na nuvem ainda não responde depois de reiniciar. Substituir computador dá um novo para {name}.",+ "computer.recovery.confirmReplace": "Substituir o computador na nuvem de {name} por um novo? Os arquivos que estão só neste computador serão perdidos.",+ "computer.recovery.restart": "Reiniciar computador",+ "computer.recovery.restartTitle": "Para e inicia de novo este computador na nuvem. Os programas abertos são fechados; os arquivos continuam lá.",+ "computer.recovery.replace": "Substituir computador",+ "computer.recovery.replaceTitle": "Exclui este computador na nuvem e dá um novo ao bot. Os arquivos que estão só nele são perdidos."}diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex f9b3abe358..8805eb6cc5 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -7297,5 +7297,22 @@"backup.excluded": "Сохранённые учётные данные и подключения не входят в копию. Подключите аккаунты заново на новом компьютере; уже имеющиеся там данные не изменятся. Входы в другие AI-приложения и диски удалённых рабочих столов тоже не входят.","settings.simple.billing.included": "Включённое использование в этом месяце","settings.simple.billing.summary": "{percent}% включённого использования в этом месяце",- "settings.simple.billing.used": "использовано"+ "settings.simple.billing.used": "использовано",+ "server.cloudComputer.replaced": "Облачный компьютер бота {name} перестал отвечать, поэтому MausBot заменил его новым. Файлы, которые были только на старом компьютере, потеряны.",+ "server.cloudComputer.restarted": "Облачный компьютер бота {name} перестал отвечать, поэтому MausBot перезапустил его. Он снова отвечает; открытые на нём программы были закрыты.",+ "server.cloudComputer.capped": "Облачный компьютер бота {name} снова перестал отвечать в течение часа после замены, поэтому MausBot оставил его как есть. Кнопка «Заменить компьютер» в панели компьютера попробует ещё раз.",+ "server.cloudComputer.unreachable": "Облачные компьютеры сейчас недоступны. MausBot сохранил облачный компьютер бота {name} и проверит его снова.",+ "server.cloudComputer.needsPerson": "Облачный компьютер бота {name} перестал отвечать. Кнопка «Заменить компьютер» в панели компьютера даст новый; файлы, которые есть только на старом компьютере, будут потеряны.",+ "server.cloudComputer.teamNotResponding": "{name} не отвечает. Удалите его в разделе «Настройки → Компьютеры», затем создайте заново на карте команды; файлы, которые есть только на нём, будут потеряны.",+ "computer.recovery.notResponding": "Этот облачный компьютер не отвечает. MausBot проверяет его и перезапустит или заменит.",+ "computer.recovery.restarting": "Этот облачный компьютер не отвечает. MausBot перезапускает его.",+ "computer.recovery.replacing": "Этот облачный компьютер не отвечает. MausBot заменяет его.",+ "computer.recovery.replacedManual": "Заменён. {name} получит новый облачный компьютер, когда он понадобится в следующий раз.",+ "computer.recovery.restartedManual": "Перезапущен. Облачный компьютер снова отвечает.",+ "computer.recovery.stillNotAnswering": "Облачный компьютер не отвечает и после перезапуска. «Заменить компьютер» даст боту {name} новый.",+ "computer.recovery.confirmReplace": "Заменить облачный компьютер бота {name} новым? Файлы, которые есть только на этом компьютере, будут потеряны.",+ "computer.recovery.restart": "Перезапустить компьютер",+ "computer.recovery.restartTitle": "Остановить и снова запустить этот облачный компьютер. Открытые программы закроются; файлы останутся.",+ "computer.recovery.replace": "Заменить компьютер",+ "computer.recovery.replaceTitle": "Удалить этот облачный компьютер и дать боту новый. Файлы, которые есть только на нём, будут потеряны."}diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex a6f5363275..c9df937235 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -5984,5 +5984,22 @@"settings.simple.billing.included": "Bu ayın dahil kullanımı","settings.simple.billing.summary": "Bu ayın dahil kullanımının %{percent} kadarı","settings.simple.billing.used": "kullanıldı",- "settings.skin.dressUp.title": "Botlarımı giydir"+ "settings.skin.dressUp.title": "Botlarımı giydir",+ "server.cloudComputer.replaced": "{name} botunun bulut bilgisayarı yanıt vermeyi bıraktı, bu yüzden MausBot onu yenisiyle değiştirdi. Yalnızca eski bilgisayarda olan dosyalar artık yok.",+ "server.cloudComputer.restarted": "{name} botunun bulut bilgisayarı yanıt vermeyi bıraktı, bu yüzden MausBot onu yeniden başlattı. Yeniden yanıt veriyor; üzerinde açık olan programlar kapatıldı.",+ "server.cloudComputer.capped": "{name} botunun bulut bilgisayarı değiştirildikten sonraki bir saat içinde yine yanıt vermeyi bıraktı, bu yüzden MausBot onu olduğu gibi bıraktı. Bilgisayar panelindeki Bilgisayarı değiştir bir kez daha dener.",+ "server.cloudComputer.unreachable": "Bulut bilgisayarlara şu anda ulaşılamıyor. MausBot, {name} botunun bulut bilgisayarını tuttu ve yeniden kontrol edecek.",+ "server.cloudComputer.needsPerson": "{name} botunun bulut bilgisayarı yanıt vermeyi bıraktı. Bilgisayar panelindeki Bilgisayarı değiştir yenisini verir; yalnızca eski bilgisayarda olan dosyalar kaybolur.",+ "server.cloudComputer.teamNotResponding": "{name} yanıt vermiyor. Ayarlar → Bilgisayarlar'dan silin, ardından Ekip haritasından yeniden oluşturun; yalnızca üzerinde olan dosyalar kaybolur.",+ "computer.recovery.notResponding": "Bu bulut bilgisayar yanıt vermiyor. MausBot onu kontrol ediyor; yeniden başlatacak ya da değiştirecek.",+ "computer.recovery.restarting": "Bu bulut bilgisayar yanıt vermiyor. MausBot onu yeniden başlatıyor.",+ "computer.recovery.replacing": "Bu bulut bilgisayar yanıt vermiyor. MausBot onu değiştiriyor.",+ "computer.recovery.replacedManual": "Değiştirildi. {name} bir dahaki sefere ihtiyaç duyduğunda yeni bir bulut bilgisayar alacak.",+ "computer.recovery.restartedManual": "Yeniden başlatıldı. Bulut bilgisayar yeniden yanıt veriyor.",+ "computer.recovery.stillNotAnswering": "Bulut bilgisayar yeniden başlatıldıktan sonra da yanıt vermiyor. Bilgisayarı değiştir, {name} için yeni bir tane verir.",+ "computer.recovery.confirmReplace": "{name} botunun bulut bilgisayarı yenisiyle değiştirilsin mi? Yalnızca bu bilgisayarda olan dosyalar kaybolur.",+ "computer.recovery.restart": "Bilgisayarı yeniden başlat",+ "computer.recovery.restartTitle": "Bu bulut bilgisayarı durdurup yeniden başlatır. Açık programlar kapanır; dosyaları kalır.",+ "computer.recovery.replace": "Bilgisayarı değiştir",+ "computer.recovery.replaceTitle": "Bu bulut bilgisayarı siler ve bota yenisini verir. Yalnızca üzerinde olan dosyalar kaybolur."}diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 736a8746c8..c8ed8b8d51 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -4057,5 +4057,22 @@"settings.simple.billing.included": "Включене використання цього місяця","settings.simple.billing.summary": "{percent}% включеного використання цього місяця","settings.simple.billing.used": "використано",- "settings.skin.dressUp.title": "Перевдягнути моїх ботів"+ "settings.skin.dressUp.title": "Перевдягнути моїх ботів",+ "server.cloudComputer.replaced": "Хмарний комп'ютер бота {name} перестав відповідати, тому MausBot замінив його новим. Файли, які були лише на старому комп'ютері, втрачено.",+ "server.cloudComputer.restarted": "Хмарний комп'ютер бота {name} перестав відповідати, тому MausBot перезапустив його. Він знову відповідає; відкриті на ньому програми було закрито.",+ "server.cloudComputer.capped": "Хмарний комп'ютер бота {name} знову перестав відповідати протягом години після заміни, тому MausBot залишив його як є. Кнопка «Замінити комп'ютер» на панелі комп'ютера спробує ще раз.",+ "server.cloudComputer.unreachable": "Хмарні комп'ютери зараз недоступні. MausBot зберіг хмарний комп'ютер бота {name} і перевірить його знову.",+ "server.cloudComputer.needsPerson": "Хмарний комп'ютер бота {name} перестав відповідати. Кнопка «Замінити комп'ютер» на панелі комп'ютера дасть новий; файли, які є лише на старому комп'ютері, буде втрачено.",+ "server.cloudComputer.teamNotResponding": "{name} не відповідає. Видаліть його в розділі «Налаштування → Комп'ютери», потім створіть знову на карті команди; файли, які є лише на ньому, буде втрачено.",+ "computer.recovery.notResponding": "Цей хмарний комп'ютер не відповідає. MausBot перевіряє його й перезапустить або замінить.",+ "computer.recovery.restarting": "Цей хмарний комп'ютер не відповідає. MausBot перезапускає його.",+ "computer.recovery.replacing": "Цей хмарний комп'ютер не відповідає. MausBot замінює його.",+ "computer.recovery.replacedManual": "Замінено. {name} отримає новий хмарний комп'ютер, коли він знадобиться наступного разу.",+ "computer.recovery.restartedManual": "Перезапущено. Хмарний комп'ютер знову відповідає.",+ "computer.recovery.stillNotAnswering": "Хмарний комп'ютер не відповідає й після перезапуску. «Замінити комп'ютер» дасть боту {name} новий.",+ "computer.recovery.confirmReplace": "Замінити хмарний комп'ютер бота {name} новим? Файли, які є лише на цьому комп'ютері, буде втрачено.",+ "computer.recovery.restart": "Перезапустити комп'ютер",+ "computer.recovery.restartTitle": "Зупинити й знову запустити цей хмарний комп'ютер. Відкриті програми закриються; файли залишаться.",+ "computer.recovery.replace": "Замінити комп'ютер",+ "computer.recovery.replaceTitle": "Видалити цей хмарний комп'ютер і дати боту новий. Файли, які є лише на ньому, буде втрачено."}diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 336b8650d2..9da58584d1 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -5984,5 +5984,22 @@"settings.simple.billing.included": "Mức dùng kèm theo trong tháng này","settings.simple.billing.summary": "{percent}% mức dùng kèm theo trong tháng này","settings.simple.billing.used": "đã dùng",- "settings.skin.dressUp.title": "Hóa trang cho bot của tôi"+ "settings.skin.dressUp.title": "Hóa trang cho bot của tôi",+ "server.cloudComputer.replaced": "Máy tính đám mây của {name} đã ngừng phản hồi, nên MausBot đã thay nó bằng máy mới. Các tệp chỉ có trên máy cũ đã mất.",+ "server.cloudComputer.restarted": "Máy tính đám mây của {name} đã ngừng phản hồi, nên MausBot đã khởi động lại nó. Máy đã phản hồi trở lại; các chương trình đang mở trên đó đã bị đóng.",+ "server.cloudComputer.capped": "Máy tính đám mây của {name} lại ngừng phản hồi trong vòng một giờ sau khi được thay, nên MausBot để nguyên nó. Thay máy tính trong bảng máy tính sẽ thử thêm một lần.",+ "server.cloudComputer.unreachable": "Hiện không thể kết nối tới máy tính đám mây. MausBot vẫn giữ máy tính đám mây của {name} và sẽ kiểm tra lại.",+ "server.cloudComputer.needsPerson": "Máy tính đám mây của {name} đã ngừng phản hồi. Thay máy tính trong bảng máy tính sẽ cho một máy mới; các tệp chỉ có trên máy cũ sẽ bị mất.",+ "server.cloudComputer.teamNotResponding": "{name} không phản hồi. Hãy xóa nó trong Cài đặt → Máy tính, rồi tạo lại từ bản đồ nhóm; các tệp chỉ có trên đó sẽ bị mất.",+ "computer.recovery.notResponding": "Máy tính đám mây này không phản hồi. MausBot đang kiểm tra và sẽ khởi động lại hoặc thay nó.",+ "computer.recovery.restarting": "Máy tính đám mây này không phản hồi. MausBot đang khởi động lại nó.",+ "computer.recovery.replacing": "Máy tính đám mây này không phản hồi. MausBot đang thay nó.",+ "computer.recovery.replacedManual": "Đã thay. {name} sẽ có máy tính đám mây mới vào lần tới cần dùng.",+ "computer.recovery.restartedManual": "Đã khởi động lại. Máy tính đám mây đã phản hồi trở lại.",+ "computer.recovery.stillNotAnswering": "Máy tính đám mây vẫn không phản hồi sau khi khởi động lại. Thay máy tính sẽ cho {name} một máy mới.",+ "computer.recovery.confirmReplace": "Thay máy tính đám mây của {name} bằng máy mới? Các tệp chỉ có trên máy này sẽ bị mất.",+ "computer.recovery.restart": "Khởi động lại máy tính",+ "computer.recovery.restartTitle": "Dừng rồi khởi động lại máy tính đám mây này. Các chương trình đang mở sẽ bị đóng; tệp vẫn còn.",+ "computer.recovery.replace": "Thay máy tính",+ "computer.recovery.replaceTitle": "Xóa máy tính đám mây này và cho bot một máy mới. Các tệp chỉ có trên máy này sẽ bị mất."}diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex abca5c4c0a..ba3285a00b 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -10273,5 +10273,22 @@"settings.domain.change": "變更","settings.domain.httpsFirst": "請先為這個網址開啟 HTTPS,再到這裡連接。","settings.backTo": "返回設定",- "devices.route.httpsAccount": "使用你的 {app} 帳號。"+ "devices.route.httpsAccount": "使用你的 {app} 帳號。",+ "server.cloudComputer.replaced": "{name} 的雲端電腦停止回應,所以 MausBot 用一台新的取代了它。只存在舊電腦上的檔案已經不見了。",+ "server.cloudComputer.restarted": "{name} 的雲端電腦停止回應,所以 MausBot 重新啟動了它。它已恢復回應;上面開著的程式已被關閉。",+ "server.cloudComputer.capped": "{name} 的雲端電腦在被取代後一小時內又停止回應,所以 MausBot 沒有再動它。在電腦面板中按「取代電腦」可以再試一次。",+ "server.cloudComputer.unreachable": "目前無法連線到雲端電腦。MausBot 保留了 {name} 的雲端電腦,稍後會再檢查。",+ "server.cloudComputer.needsPerson": "{name} 的雲端電腦停止回應了。在電腦面板中按「取代電腦」可換一台新的;只存在舊電腦上的檔案會遺失。",+ "server.cloudComputer.teamNotResponding": "{name} 沒有回應。請在「設定 → 電腦」中刪除它,然後在團隊地圖中重新建立;只存在它上面的檔案會遺失。",+ "computer.recovery.notResponding": "這台雲端電腦沒有回應。MausBot 正在檢查,並會重新啟動或取代它。",+ "computer.recovery.restarting": "這台雲端電腦沒有回應。MausBot 正在重新啟動它。",+ "computer.recovery.replacing": "這台雲端電腦沒有回應。MausBot 正在取代它。",+ "computer.recovery.replacedManual": "已取代。{name} 下次需要時會取得一台新的雲端電腦。",+ "computer.recovery.restartedManual": "已重新啟動。雲端電腦已恢復回應。",+ "computer.recovery.stillNotAnswering": "重新啟動後雲端電腦仍然沒有回應。「取代電腦」會給 {name} 一台新的。",+ "computer.recovery.confirmReplace": "要把 {name} 的雲端電腦取代成一台新的嗎?只存在這台電腦上的檔案會遺失。",+ "computer.recovery.restart": "重新啟動電腦",+ "computer.recovery.restartTitle": "停止並重新啟動這台雲端電腦。開著的程式會被關閉;檔案會保留。",+ "computer.recovery.replace": "取代電腦",+ "computer.recovery.replaceTitle": "刪除這台雲端電腦並給機器人一台新的。只存在上面的檔案會遺失。"}diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 02d9758118..f89054071f 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7967,5 +7967,22 @@"settings.domain.change": "更改","settings.domain.httpsFirst": "请先为此地址开启 HTTPS,再在这里连接。","settings.backTo": "返回设置",- "devices.route.httpsAccount": "使用你的 {app} 账号。"+ "devices.route.httpsAccount": "使用你的 {app} 账号。",+ "server.cloudComputer.replaced": "{name} 的云电脑停止响应,所以 MausBot 用一台新的替换了它。只在旧电脑上的文件已经没有了。",+ "server.cloudComputer.restarted": "{name} 的云电脑停止响应,所以 MausBot 重启了它。它已恢复响应;上面打开的程序已被关闭。",+ "server.cloudComputer.capped": "{name} 的云电脑在被替换后一小时内再次停止响应,所以 MausBot 没有再动它。在电脑面板中点“替换电脑”可以再试一次。",+ "server.cloudComputer.unreachable": "现在无法连接云电脑。MausBot 保留了 {name} 的云电脑,稍后会再检查。",+ "server.cloudComputer.needsPerson": "{name} 的云电脑停止响应了。在电脑面板中点“替换电脑”可换一台新的;只在旧电脑上的文件会丢失。",+ "server.cloudComputer.teamNotResponding": "{name} 没有响应。请在“设置 → 电脑”中删除它,然后在团队地图中重新创建;只在它上面的文件会丢失。",+ "computer.recovery.notResponding": "这台云电脑没有响应。MausBot 正在检查,并会重启或替换它。",+ "computer.recovery.restarting": "这台云电脑没有响应。MausBot 正在重启它。",+ "computer.recovery.replacing": "这台云电脑没有响应。MausBot 正在替换它。",+ "computer.recovery.replacedManual": "已替换。{name} 下次需要时会获得一台新的云电脑。",+ "computer.recovery.restartedManual": "已重启。云电脑已恢复响应。",+ "computer.recovery.stillNotAnswering": "重启后云电脑仍然没有响应。“替换电脑”会给 {name} 一台新的。",+ "computer.recovery.confirmReplace": "要把 {name} 的云电脑替换成一台新的吗?只在这台电脑上的文件会丢失。",+ "computer.recovery.restart": "重启电脑",+ "computer.recovery.restartTitle": "停止并重新启动这台云电脑。打开的程序会被关闭;文件会保留。",+ "computer.recovery.replace": "替换电脑",+ "computer.recovery.replaceTitle": "删除这台云电脑并给机器人一台新的。只在上面的文件会丢失。"}