Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computer: set a silent one aside with its files instead of deleting it
milind-soni61e123a0b59d
diff --git a/server/auto-vm-claims.ts b/server/auto-vm-claims.tsindex 7958fc2562..3394e46c7f 100644--- a/server/auto-vm-claims.ts+++ b/server/auto-vm-claims.ts@@ -66,7 +66,8 @@ export function startAutoVmClaim(table: AutoVmClaimTable, threadId: string, gene() => { slot.claimed = true; },(error: unknown) => {const failure = error instanceof Error ? error.message : String(error);- if (transientClaimFailure(error) && attempt < MAX_CLAIM_ATTEMPTS) {+ // A computer MausBot keeps bringing back by itself (`keepsTrying`) is never given up on for the turn.+ if (transientClaimFailure(error) && (attempt < MAX_CLAIM_ATTEMPTS || (error as { keepsTrying?: unknown } | null)?.keepsTrying === true)) {slot.retryReason = failure;if (slot.begin === begin) slot.begin = undefined;return;diff --git a/server/boat-create-idempotency.ts b/server/boat-create-idempotency.tsindex 4038e5ff7f..f667a3d1e4 100644--- a/server/boat-create-idempotency.ts+++ b/server/boat-create-idempotency.ts@@ -457,6 +457,12 @@ export function retireDeletedBoatCreate(boxId: string): void {});}+/** A Boat set aside under another name (server/boat-set-aside.ts): it is no longer the bot's, so a create for the bot+ * must make a new one instead of finding this one again. */+export function forgetSetAsideBoatCreate(boxId: string): void {+ retireDeletedBoatCreate(boxId);+}+export function discardBoatCreate(request: BoatCreateRequest): void {withJournalLock((requests) => {const next = requests.filter((candidate) => candidate.idempotencyKey !== request.idempotencyKey);diff --git a/server/boat-health.ts b/server/boat-health.tsindex 0a1d1024d3..2a2651d3e8 100644--- a/server/boat-health.ts+++ b/server/boat-health.ts@@ -15,6 +15,18 @@ export const DEAD_COMPUTER = {answeredGraceMs: 5 * 60_000,/** Another computer of this installation answered this recently: the provider itself is up. */witnessMs: 10 * 60_000,+ /** Before a silent computer is set aside, another one must have answered a command this recently: proof that the+ * provider's command path works now, which its list answering does not give. */+ freshWitnessMs: 2 * 60_000,+ /** Without such a witness, a computer is set aside only after this long without one answer, a restart included. */+ loneSilenceMs: 30 * 60_000,+ /** And never within this long of a resume while the provider does not say whether its disk is back. */+ unknownRestoreMs: 30 * 60_000,+ /** Probes after the patience that got no answer, at least this many, spread over at least this long. */+ setAsideProbes: 3,+ setAsideProbeSpanMs: 2 * 60_000,+ /** A set-aside computer is kept, stopped with its files, this long before it is deleted. */+ setAsideKeepMs: 7 * 24 * 60 * 60_000,/** At most this many automatic replacements per computer owner in an hour; after that it stops and says so. */replacementsPerHour: 1,/** And in a day, so a provider that keeps handing out broken computers cannot use up the plan's computers or hours. */@@ -35,9 +47,18 @@ export const DEAD_COMPUTER = {* 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);+/** A probe that took this much longer than its own timeout was not timed by the computer but by this process (its event+ * loop stalled): it says nothing about the computer, so it counts neither way. */+export const stalledProbe = (sample: ProbeSample): boolean => sample.elapsedMs > sample.timeoutMs * 2 + 5_000;+export interface ProbeSample { elapsedMs: number; timeoutMs: number }+interface BoxHealth {/** Probes in a row that got no answer, the first and last of them. */failures: number;+ /** When each of those probes ended, the latest last (at most 64). */+ silences: number[];+ /** When the computer was last resumed, created or restarted, as seen by this process. */+ wokeAt: number | null;firstFailureAt: number | null;lastFailureAt: number | null;lastAnsweredAt: number | null;@@ -54,7 +75,7 @@ export function createBoatHealth(now: () => number = Date.now) {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 });+ if (!found) boxes.set(boxId, found = { failures: 0, silences: [], wokeAt: null, 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 } =>@@ -63,12 +84,15 @@ export function createBoatHealth(now: () => number = Date.now) {function answered(boxId: string): void {const health = entry(boxId);- Object.assign(health, { failures: 0, firstFailureAt: null, lastFailureAt: null, lastAnsweredAt: now(), reportedAt: null });+ Object.assign(health, { failures: 0, silences: [], firstFailureAt: null, lastFailureAt: null, lastAnsweredAt: now(), reportedAt: null });}- function unanswered(boxId: string): void {+ /** A probe got no answer. With `sample`, one that ran far past its own timeout is dropped (stalledProbe). */+ function unanswered(boxId: string, sample?: ProbeSample): void {+ if (sample && stalledProbe(sample)) return;const health = entry(boxId), at = now();health.failures += 1;+ health.silences = [...health.silences.slice(-63), at];health.firstFailureAt ??= at;health.lastFailureAt = at;if (!notResponding(health) || (health.reportedAt !== null && at - health.reportedAt < DEAD_COMPUTER.reportGapMs)) return;@@ -82,11 +106,11 @@ export function createBoatHealth(now: () => number = Date.now) {const health = entry(boxId);if (health.probing || now() - health.lastProbeAt < DEAD_COMPUTER.probeGapMs) return;health.probing = true;- health.lastProbeAt = now();+ const started = 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);+ if (ok) answered(boxId); else unanswered(boxId, { elapsedMs: now() - started, timeoutMs: DEAD_COMPUTER.probeTimeoutMs });});}@@ -99,6 +123,21 @@ export function createBoatHealth(now: () => number = Date.now) {const health = boxes.get(boxId);return notResponding(health) ? health.firstFailureAt : null;},+ /** When the current run of unanswered probes began, however short it is; null while the computer answers. */+ silentSince: (boxId: string): number | null => boxes.get(boxId)?.firstFailureAt ?? null,+ /** The unanswered probes of the current run that ended at or after `since`: how many, and the first and last. */+ silencesSince(boxId: string, since: number): { count: number; first: number | null; last: number | null } {+ const list = (boxes.get(boxId)?.silences ?? []).filter((at) => at >= since);+ return { count: list.length, first: list[0] ?? null, last: list.at(-1) ?? null };+ },+ /** This computer was resumed, created or restarted now. `fresh`: a wake or create after it slept, so an earlier+ * silence says nothing about it now and its run of unanswered probes starts over. A restart keeps the run. */+ woke: (boxId: string, fresh = false) => {+ const health = entry(boxId);+ health.wokeAt = now();+ if (fresh) Object.assign(health, { failures: 0, silences: [], firstFailureAt: null, lastFailureAt: null, reportedAt: null });+ },+ wokeAt: (boxId: string): number | null => boxes.get(boxId)?.wokeAt ?? null,answeredWithin: (boxId: string, ms: number): boolean => {const at = boxes.get(boxId)?.lastAnsweredAt;return at !== null && at !== undefined && now() - at <= ms;diff --git a/server/boat-ready.ts b/server/boat-ready.tsindex 3dff9c2e42..f0b05a8987 100644--- a/server/boat-ready.ts+++ b/server/boat-ready.ts@@ -133,6 +133,7 @@ export function createBoatReadiness(overrides: Partial<BoatReadinessDeps> = {})return answer;};for (;;) {+ const sent = deps.now();const answered = await deps.probe(cfg, boxId, opts.signal);if (opts.signal?.aborted) return done({ ok: false, phase, waitedMs: deps.now() - started });if (answered !== false) {@@ -140,7 +141,8 @@ export function createBoatReadiness(overrides: Partial<BoatReadinessDeps> = {})return done({ ok: true, waitedMs: deps.now() - started });}failures += 1;- deps.health.unanswered(boxId);+ // Timed: a probe that ran far past its timeout was held up here, not by the computer, and is not counted against it.+ deps.health.unanswered(boxId, { elapsedMs: deps.now() - sent, timeoutMs: READY_WAIT.probeTimeoutMs });enter(boatSignals(await deps.read(cfg, boxId)).restoring === true ? "restoring" : phase);const patience = phase === "restoring" ? READY_WAIT.restorePatienceMs : opts.woke ? READY_WAIT.wakePatienceMs : READY_WAIT.answerPatienceMs;const gap = opts.woke ? READY_WAIT.wakeGapsMs[Math.min(failures, READY_WAIT.wakeGapsMs.length) - 1]! : READY_WAIT.probeGapMs;diff --git a/server/boat-recovery.test.ts b/server/boat-recovery.test.tsindex e5b135957f..c196a122fb 100644--- a/server/boat-recovery.test.ts+++ b/server/boat-recovery.test.ts@@ -1,5 +1,7 @@// 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.+// whose machine is gone, or that stopped answering. No network, no real computer; the data folder is the test's own.+// The automatic path sets a computer aside (stopped and renamed, with its files) and never deletes it, except one the+// provider reports broken that it will not even stop: every DELETE here is checked against that.import { mkdtempSync, writeFileSync } from "node:fs";import { createServer, type IncomingMessage, type Server } from "node:http";import { tmpdir } from "node:os";@@ -25,6 +27,10 @@ let deleteCompletes = true;let resumeAnswers = new Set<string>();let deleteDelayMs = 0;let autoOn = true;+/** Computers the provider refuses to stop. */+let stopRefused = new Set<string>();+/** Only the person's Replace computer, and a broken computer the provider will not stop, may send a DELETE. */+let deletesAllowed = false;const teamOwners = new Set<string>();const watched = new Set<string>();const deleteSpans: Array<{ boxId: string; start: number; end: number }> = [];@@ -81,7 +87,11 @@ beforeAll(async () => {}, deleteDelayMs);return;}- if (action === "stop") { box.state = "archived"; return send(res, 200, { ok: true, box }); }+ if (action === "stop") {+ if (stopRefused.has(box.id)) return send(res, 500, { ok: false, code: "upstream_error", message: "The stop failed." });+ 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);@@ -133,7 +143,7 @@ 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, recheckMs: 20,- autoReplace: () => autoOn, eligible: (owner) => !teamOwners.has(owner), personActive: (owner) => watched.has(owner),+ setAsideRecheckMs: 20, stalled: () => false, autoReplace: () => autoOn, eligible: (owner) => !teamOwners.has(owner), personActive: (owner) => watched.has(owner),// One probe stands for the wait, so a restart that does not help is judged at once.readiness: { awaitAnswer: async (_cfg, boxId) => ((await boat.probeBoat(cfg, boxId)) === true ? { ok: true, waitedMs: 0 } : { ok: false, phase: "waking", waitedMs: 0 }) } });}@@ -141,13 +151,16 @@ function start() {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();+ deleteDelayMs = 0; autoOn = true; deleteSpans.length = 0; teamOwners.clear(); watched.clear(); stopRefused = new Set(); deletesAllowed = false;at += 24 * 60 * 60_000;file = join(mkdtempSync(join(tmpdir(), "omb-repl-")), "boat-replacements.json");await load();start();});-afterEach(() => recovery.close());+afterEach(() => {+ recovery.close();+ if (!deletesAllowed) expect(requests.filter((request) => request.method === "DELETE")).toEqual([]);+});let bots = 0;async function botWith(state: string, extra: Partial<Box> = {}) {@@ -163,6 +176,18 @@ const provisioned = async (botId: string) => {return created;};const deletes = () => requests.filter((request) => request.method === "DELETE");+const creates = () => requests.filter((request) => request.method === "POST" && request.path === "/boxes");+const SET_ASIDE_NAME = /^ogb-[a-f0-9]{12}-[a-z0-9]{1,8}-[a-f0-9]{6}-set-aside-\d{4}-\d{2}-\d{2}$/;+/** Set aside: still there, stopped, under a name that is no bot's. */+const setAside = (boxId: string) => {+ const box = boxes.find((candidate) => candidate.id === boxId);+ return Boolean(box && SET_ASIDE_NAME.test(box.name) && box.state === "archived");+};+/** While `check` is not yet true, moves the test's clock on and keeps `witness` answering, as other bots' work would. */+const ticking = (witness: string | null, stepMs = 30_000, stopAt = Infinity) => {+ const timer = setInterval(() => { if (at + stepMs <= stopAt) at += stepMs; if (witness) health.answered(witness); }, 15);+ return () => clearInterval(timer);+};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");@@ -187,7 +212,7 @@ async function deadTwice(botId: string) {}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 () => {+ it("is never shown or used as ready, is set aside 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 });@@ -198,17 +223,33 @@ describe("a cloud computer the provider reports in error", () => {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(deletes()).toHaveLength(0);+ expect(setAside(box.id)).toBe(true);+ expect(creates()).toHaveLength(1);+ expect(told).toEqual([[botId, "needsPerson"], [botId, "setAside"]]);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(created.reused).toBe(true);+ expect(recovery.notice(created.boxId)).toMatch(/set it aside and gave this bot a new one/);expect(recovery.notice(created.boxId)).toBeNull();expect(told).toHaveLength(2);- expect(deletes()).toHaveLength(1);+ expect(deletes()).toHaveLength(0);+ });++ it("is deleted, as before, only when the provider will not even stop it", async () => {+ deletesAllowed = true;+ const { botId, box } = await botWith("error");+ stopRefused.add(box.id);+ await boat.findBoat(cfg, botId);+ await deadTwice(botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);+ expect(told).toEqual([[botId, "needsPerson"], [botId, "replaced"]]);+ const created = await provisioned(botId);+ expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED);+ expect(words.CLOUD_COMPUTER_REPLACED).toMatch(/sign-ins/);});it("is not deleted while the provider's list fails", async () => {@@ -240,17 +281,19 @@ describe("a cloud computer the provider reports in error", () => {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(creates()).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);+ expect(creates()).toHaveLength(2);+ expect(setAside(second.boxId)).toBe(true);+ expect(deletes()).toHaveLength(0);});- it("is deleted by itself at most once an hour for the whole installation, whoever's computer it is", async () => {+ it("is set aside 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);@@ -260,15 +303,18 @@ describe("a cloud computer the provider reports in error", () => {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]);+ expect([setAside(first.box.id), setAside(second.box.id)]).toEqual([true, false]);at += 61 * 60_000;await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });- expect(deletes()).toHaveLength(2);+ expect(setAside(second.box.id)).toBe(true);+ expect(deletes()).toHaveLength(0);});- it("finishes after a crash between the delete and the new computer, telling each side once", async () => {+ it("finishes after a crash between the delete of one that could not be stopped and the new computer, telling each side once", async () => {+ deletesAllowed = true;deleteCompletes = false;const { botId, box } = await botWith("error");+ stopRefused.add(box.id);await boat.findBoat(cfg, botId);await deadTwice(botId);await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETING });@@ -294,29 +340,37 @@ describe("a cloud computer the provider reports in error", () => {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);+ expect(deletes()).toHaveLength(0);+ expect(setAside(box.id)).toBe(true);const created = await provisioned(botId);- expect(recovery.notice(created.boxId)).toBe(words.CLOUD_COMPUTER_REPLACED);+ expect(recovery.notice(created.boxId)).toMatch(/set it aside/);});});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");+ it("is restarted first, then set aside (stopped and renamed, never deleted) for a new one while another computer answers, and calls to it are refused meanwhile", async () => {+ const { botId, box } = await botWith("ready", { hydrated: true });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");+ await until(() => recovery.verdict(botId) === "restart-failed");+ // Minutes of probes after the restart, with the other computer answering throughout.+ const stop = ticking(witness.box.id, 10_000);+ try { await until(() => recovery.status(botId)?.state === "replaced"); } finally { stop(); }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(order.lastIndexOf("POST /stop")).toBeGreaterThan(order.indexOf("POST /resume"));+ expect(order.indexOf("PATCH /")).toBeGreaterThan(order.lastIndexOf("POST /stop"));+ expect(deletes()).toHaveLength(0);+ expect(setAside(box.id)).toBe(true);+ expect(creates()).toHaveLength(1);+ expect(told).toEqual([[botId, "setAside"]]);expect(recovery.refusal(box.id, "before")).toBe(words.CLOUD_COMPUTER_NOT_RESPONDING);+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NOT_RESPONDING_UNANSWERED);expect(boxes.some((candidate) => candidate.id === witness.box.id)).toBe(true);});@@ -348,17 +402,24 @@ describe("a cloud computer that says it is ready but does not answer", () => {expect(deletes()).toHaveLength(0);});- it("with no other computer to compare against, is restarted, then replaced as soon as the restart's wake gets no answer", async () => {- const { botId, box } = await botWith("ready");+ it("whose command gateway is down while the provider's list works, with no other computer to compare against: restarted, and nothing set aside", async () => {+ const { botId, box } = await botWith("ready", { hydrated: true });commandStatus.set(box.id, 502);await boat.findBoat(cfg, botId);stopsAnswering(box.id);- await until(() => recovery.status(botId)?.state === "replaced");+ await until(() => recovery.verdict(botId) === "restart-failed");+ // Minutes more of silence, probed again and again: still no witness, and the clock stops well short of half an hour.+ const limit = health.silentSince(box.id)! + 25 * 60_000;+ const stop = ticking(null, 20_000, limit);+ try { await until(() => at + 20_000 > limit); } finally { stop(); }+ await new Promise((resolve) => setTimeout(resolve, 100));expect(stops().map((request) => request.path)).toEqual([`/boxes/${box.id}/stop`]);- expect(recovery.verdict(botId)).toBe("restart-failed");- expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);- expect(told).toEqual([[botId, "replaced"]]);- expect(recovery.replaced(box.id)).toBe(true);+ expect(requests.some((request) => request.method === "PATCH")).toBe(false);+ expect(creates()).toHaveLength(0);+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([]);+ expect(recovery.replaced(box.id)).toBe(false);+ expect(boxes.find((candidate) => candidate.id === box.id)?.name).toBe(await boat.boatNameFor(botId));});it("is neither restarted nor deleted while the provider's list fails", async () => {@@ -419,25 +480,27 @@ describe("a cloud computer that says it is ready but does not answer", () => {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));+ await until(() => recovery.verdict(first.botId) !== null && recovery.verdict(second.botId) !== null);expect(stops()).toHaveLength(1);+ expect([recovery.verdict(first.botId), recovery.verdict(second.botId)].sort()).toEqual(["restart-failed", "restart-limited"]);});- it("is replaced only once the provider's error is seen twice half an hour apart, and without a restart", async () => {+ it("is set aside 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);+ expect(stops()).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);+ expect(requests.some((request) => request.path.endsWith("/resume"))).toBe(false);+ expect(stops()).toHaveLength(1);+ expect(setAside(box.id)).toBe(true);+ expect(deletes()).toHaveLength(0);});});@@ -724,6 +787,7 @@ describe("the computer panel's Restart computer and Replace computer", () => {});it("replace deletes through the same path, needs no hourly allowance, and the bot hears it was the person's", async () => {+ deletesAllowed = true;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]);@@ -736,19 +800,24 @@ describe("the computer panel's Restart computer and Replace computer", () => {});it("replace also takes a computer the provider reports in error", async () => {+ deletesAllowed = true;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);+describe("a start the Admin refuses for computers at once", () => {+ it("names the set-aside computer that holds a place, and where the person deletes it", async () => {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);+ const { botId, box } = await botWith("error");+ await boat.findBoat(cfg, botId);expect(recovery.claimSentence("another-bot", refusal)).toBeUndefined();+ await deadTwice(botId);+ await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(setAside(box.id)).toBe(true);+ expect(recovery.claimSentence("another-bot", refusal)).toMatch(/set aside, with their files, until \d{4}-\d{2}-\d{2}.*Settings → Desktops & browser → Desktops/);+ expect(recovery.claimSentence("another-bot", new Error("something else"))).toBeUndefined();});});@@ -759,8 +828,11 @@ describe("automatic replacement", () => {expect(on({ features: { cloudComputerAutoReplace: false } }, {})).toBe(false);expect(on({ features: { cloudComputerAutoReplace: false } }, { 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: "0" })).toBe(false);- expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "yes" })).toBe(true);+ for (const off of ["0", "false", "off", "no", " FALSE ", "Off"]) expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: off })).toBe(false);+ for (const value of ["1", "true", "on", "yes"]) expect(on({ features: { cloudComputerAutoReplace: false } }, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: value })).toBe(true);+ // Anything else leaves it to config.json.+ expect(on({ features: { cloudComputerAutoReplace: false } }, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "maybe" })).toBe(false);+ expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "" })).toBe(true);});});@@ -811,6 +883,7 @@ describe("with automatic replacement switched off", () => {});it("Replace computer still deletes it and the next start makes a new one", async () => {+ deletesAllowed = true;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);@@ -824,6 +897,7 @@ describe("with automatic replacement switched off", () => {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 () => {+ deletesAllowed = true;deleteDelayMs = 300;const first = await botWith("ready");const second = await botWith("ready");diff --git a/server/boat-recovery.ts b/server/boat-recovery.tsindex 5b62000e14..6304f45a45 100644--- a/server/boat-recovery.ts+++ b/server/boat-recovery.ts@@ -1,23 +1,27 @@-// A cloud computer that stopped answering: waited for while the provider is still restoring its disk, restarted once,-// then replaced (its deletion frees the plan's place, and the next use creates a new one) or, with automatic replacement-// switched off, left for the person. A computer woken for a turn that stays silent past the wake's patience is replaced-// at once (wakeTimedOut), so the turn goes on on a new one. The bot and the person are told once. Nothing here asks the-// person anything.+// A cloud computer that stopped answering: waited for while the provider is still restoring its disk, restarted (which+// keeps its files), and only then, if it is still silent and every guard holds, set aside: stopped with its files,+// renamed so it is no longer the bot's, and kept for DEAD_COMPUTER.setAsideKeepMs while the bot gets a new one+// (boat-set-aside.ts). Nothing here deletes a computer by itself, except a set-aside one whose time is up, and one the+// provider reports broken that cannot even be stopped. A computer woken for a turn that stays silent past the wake's+// patience goes the same way, inside the turn (wakeTimedOut). 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 { boatHealth, DEAD_COMPUTER, stalledProbe, type BoatHealth } from "./boat-health.ts";import { boatReadiness, boatSignals, readBoat, READY_WAIT, type BoatReadiness } from "./boat-ready.ts";+import { deleteExpiredSetAside, setAsideBoat, setAsideBoatName, type SetAsideDeps } from "./boat-set-aside.ts";import { cloudComputerCounters } from "./cloud-computer-counters.ts";import { cloudFailureOf } from "./boat-limit.ts";import { DATA_DIR, type AppConfig } from "./config.ts";+import { eventLoopStalls } from "./event-loop-stalls.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_RESTARTING, CLOUD_COMPUTER_RESTARTING_UNANSWERED, CLOUD_COMPUTER_RESTORING,- CLOUD_COMPUTER_STILL_RESTORING, CLOUD_COMPUTER_TEAM_NOT_RESPONDING, CLOUD_COMPUTER_UNREACHABLE, recoveryUnderWay,+ CLOUD_COMPUTER_CAPPED, CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_NOT_RESPONDING, CLOUD_COMPUTER_NOT_RESPONDING_UNANSWERED,+ CLOUD_COMPUTER_REPLACED, CLOUD_COMPUTER_REPLACED_BY_PERSON, CLOUD_COMPUTER_RESTARTED, CLOUD_COMPUTER_RESTARTING, CLOUD_COMPUTER_RESTARTING_UNANSWERED,+ CLOUD_COMPUTER_RESTORING, CLOUD_COMPUTER_STILL_RESTORING, CLOUD_COMPUTER_TEAM_NOT_RESPONDING, CLOUD_COMPUTER_UNREACHABLE, cloudComputerSetAsideNotice, recoveryUnderWay,type CloudComputerPersonLine, type CloudComputerRecovery, type CloudComputerRecoveryState,} from "../shared/cloud-computer-recovery.ts";@@ -31,14 +35,22 @@ const POLL_MS = 2_500;const STALE_MS = 15 * 60_000;/** How often a computer that is waited on before a restart (a disk restore, too short a silence, an unread state) is looked at again. */const RECHECK_MS = 30_000;+/** How often a silent computer that may not be set aside yet is probed and looked at again. */+const SET_ASIDE_RECHECK_MS = 2 * 60_000;+/** After the plan had no room for a new computer, none is tried again for this long. */+const NO_ROOM_BACKOFF_MS = 6 * HOUR_MS;+/** How often set-aside computers whose time is up are looked for. */+const SWEEP_MS = HOUR_MS;/** With no other computer to compare against, a silent one is restarted only after this long without one answer. */const SOLO_SILENCE_MS = 5 * 60_000;/** A restart the person asked for answers the panel within this, however long the disk takes. */const MANUAL_ANSWER_WAIT_MS = 3 * 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. */+/** One replacement, written before it is acted on: a crash after it still counts against the limits and still owes the+ * bot and the person their line. `setAside`: the old computer was set aside under `name`, kept until `until`, and the bot+ * given `newBoxId`; without it the old one was deleted (the person's Replace computer, or a broken one that could not be+ * stopped). `undone`: a set-aside that did not happen or was put back; it still counts against the limits. */interface Replacement {owner: string;boxId: string;@@ -46,62 +58,92 @@ interface Replacement {manual?: true;toldBot?: true;toldPerson?: true;+ setAside?: { name: string; until: number; newBoxId?: string };+ undone?: true;}-/** Whether a dead or silent computer is deleted and replaced without the person. On unless OMB_CLOUD_COMPUTER_AUTO_REPLACE- * is "0" or config.json has `"features": {"cloudComputerAutoReplace": false}`; the environment, "1" or "0", wins. Off, a- * silent computer waits for the person's Replace computer, as before. */+const ON = new Set(["1", "true", "on", "yes"]), OFF = new Set(["0", "false", "off", "no"]);++/** Whether a silent computer is set aside and replaced without the person. On unless OMB_CLOUD_COMPUTER_AUTO_REPLACE is+ * off ("0", "false", "off" or "no") or config.json has `"features": {"cloudComputerAutoReplace": false}`; the+ * environment wins. Off, a silent computer is still restarted, and otherwise waits for the person's Replace computer. */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;+ const override = env.OMB_CLOUD_COMPUTER_AUTO_REPLACE?.trim().toLowerCase();+ if (override && ON.has(override)) return true;+ if (override && OFF.has(override)) return false;return cfg.features?.cloudComputerAutoReplace !== false;}+/** The turn a wait is made for, and what it hears meanwhile. */+export interface WakeTimeoutContext {+ turn?: { threadId: string; generation: string };+ onRestarting?(): void;+ /** Called only once every guard passed and the computer is being set aside. */+ onReplacing?(): void;+}+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;+ tell(owner: string, line: CloudComputerPersonLine, vars?: Record<string, string>): 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. */+ /** Only a bot's own computer is ever restarted or set aside 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;- /** A running turn of another bot holds this computer: it is never replaced by itself then. */- usedByOther?(owner: string, boxId: string): boolean;+ /** A running turn other than this bot's own (or than `asking`) holds this computer: it is never set aside then. */+ usedByOther?(owner: string, boxId: string, asking?: { threadId: string; generation: string }): boolean;+ /** A new computer was made for this owner here: its idle window starts, so it does not stay on unused. */+ created?(owner: string): void;file?: string;now?: () => number;health?: BoatHealth;pollMs?: number;autoReplace?: () => boolean;readiness?: Pick<BoatReadiness, "awaitAnswer">;+ /** A turn is waiting for this computer to answer, and goes on to restart it and set it aside itself (wakeTimedOut):+ * the background recovery leaves it alone meanwhile. A scheduled run's wait is not one: it relies on the background. */+ turnWaiting?(boxId: string): boolean;/** The provider's sandbox object, for its state and what it says about a disk restore; null when it could not be read. */read?(cfg: AppConfig, boxId: string): Promise<unknown>;recheckMs?: number;+ /** How long a restart waits for the provider to report the computer ready again (WAKE_BUDGET_MS). */+ wakeBudgetMs?: number;+ /** How often a silent computer that may not be set aside yet is looked at again (SET_ASIDE_RECHECK_MS). */+ setAsideRecheckMs?: number;+ /** This process's event loop stalled between the two times. */+ stalled?(from: number, to: number): boolean;+ provision?: SetAsideDeps["provision"];}/** Why a computer that is not answering was left as it is, for a run that waited on it. */export type RecoveryVerdict = "restart-failed" | "person-busy" | "restart-limited" | "shared";type Dead = { boxId: string; name: string };-type ReplaceOutcome = "confirmed" | "pending" | "kept" | "held" | "waiting" | "capped" | "failed";--/** What became of a computer that was woken for a turn and stayed silent past the wake's patience. `answers`: a last probe- * got through after all. `gone`: it no longer exists, so the next start makes a new one. `off`: nothing was done, as- * automatic replacement is switched off (or the computer answered moments ago), and the turn's wait fails as a passing- * failure, as before. `kept`: it was left as it is, and `why` says so in a few words for the turn. */-export type WakeTimeoutOutcome = { kind: "answers" | "replaced" | "gone" | "off" } | { kind: "kept"; why: string };--const KEPT_WHY: Partial<Record<ReplaceOutcome | "unreachable", string>> = {- capped: "it was already replaced recently, and MausBot replaces a bot's computer at most once an hour and three times a day",- held: "it could not be replaced by itself right now (a person or another bot is using it, or this installation already replaced computers in the last hour)",- failed: "replacing it failed: the old computer's deletion was not confirmed",- unreachable: "the cloud computer service itself can't be reached right now",- waiting: "the provider reports it broken, and it is replaced if it stays that way",+type DeleteOutcome = "confirmed" | "pending" | "failed";+/** What became of an attempt to set a computer aside. */+type SetAsideResult = "set-aside" | "deleted" | "deleting" | "capped" | "held" | "no-room" | "stop-refused" | "rename-failed" | "create-failed" | "lost" | "failed";++/** What became of a computer that was woken for a turn and stayed silent past the wake's patience. `answers`: it answers+ * (a last probe, or a restart). `replaced`: it was set aside and the bot has a new one. `gone`: it no longer exists, so+ * the next start makes a new one. `kept`: it was left the bot's, and `why` says so for the turn: a passing failure. */+export type WakeTimeoutOutcome = { kind: "answers" | "replaced" | "gone" } | { kind: "kept"; why: string };++const LATER = "MausBot keeps trying in the background; trying again later is fine";+const kept = (why: string): WakeTimeoutOutcome => ({ kind: "kept", why });+const silentWhy = (restarted: boolean) =>+ `the cloud computer is still not answering${restarted ? ", even after a restart" : ""}. ${LATER}`;+const KEPT_WHY: Record<Exclude<SetAsideResult, "set-aside" | "deleted" | "deleting">, string> = {+ capped: `the cloud computer is still not answering after a restart, and this bot already got a new computer recently (at most once an hour and three times a day), so the old one was left as it is. ${LATER}`,+ held: `the cloud computer is still not answering after a restart, and it could not be set aside by itself right now (someone is using it, or this installation already replaced a computer in the last hour), so it was left as it is. ${LATER}`,+ "no-room": `the cloud computer is still not answering after a restart, and the plan has no room for a new computer beside it, so MausBot kept it, stopped and with its files. ${LATER}`,+ "stop-refused": `the cloud computer is still not answering after a restart; MausBot asked to set it aside, but the provider would not stop it, so nothing else was changed. ${LATER}`,+ "rename-failed": `the cloud computer is still not answering after a restart; MausBot stopped it to set it aside but could not, so it stays this bot's computer with its files and wakes again on its next use. ${LATER}`,+ "create-failed": `the cloud computer is still not answering after a restart, and MausBot could not make a new one beside it, so the old one stays this bot's computer, stopped and with its files; it wakes again on its next use. ${LATER}`,+ lost: `the cloud computer is still not answering after a restart; MausBot set it aside, with its files, but could not make a new one or give the old one back, so the person finds it in Settings → Desktops & browser → Desktops. ${LATER}`,+ failed: `the cloud computer is still not answering, and replacing it failed: the old computer's deletion was not confirmed. ${LATER}`,};-const keptWhy = (outcome: keyof typeof KEPT_WHY): WakeTimeoutOutcome =>- ({ kind: "kept", why: `the cloud computer did not answer after waking, and ${KEPT_WHY[outcome] ?? "it was left as it is"}. Nothing else was changed; trying again later is fine` });export function createBoatRecovery(deps: BoatRecoveryDeps) {const health = deps.health ?? boatHealth;@@ -112,14 +154,20 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {const eligible = (owner: string) => deps.eligible?.(owner) ?? true;const readiness = deps.readiness ?? boatReadiness;const read = deps.read ?? readBoat;+ // Watched from now on, so a stall before the first decision is seen too.+ const stalls = deps.stalled ? null : eventLoopStalls();+ const stalled = deps.stalled ?? ((from: number, to: number) => stalls!.stalledBetween(from, to));/** When each computer was first seen not answering with its disk still being restored. */const restoringSince = new Map<string, number>();const recheckMs = deps.recheckMs ?? RECHECK_MS;+ const setAsideRecheckMs = deps.setAsideRecheckMs ?? SET_ASIDE_RECHECK_MS;const verdicts = new Map<string, { boxId: string; why: RecoveryVerdict; at: number }>();const judge = (owner: string, boxId: string, why: RecoveryVerdict) => verdicts.set(owner, { boxId, why, at: now() });const states = new Map<string, CloudComputerRecovery & { boxId: string }>();const lanes = new Map<string, Promise<unknown>>();const restarts = new Map<string, number>();+ /** When a restart's own wait for an answer ran out, per computer: only that is a restart that did not help. */+ const restartFailedAt = 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. */@@ -128,22 +176,32 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {const restartToldAt = new Map<string, number>();/** When the provider's `error` was first seen for each computer. */const errorSeen = new Map<string, number>();+ /** Why each owner's silent computer was last not set aside, so the log says it once. */+ const blockedWhy = new Map<string, string>();let lastAutoRestartAt = -Infinity;+ let noRoomAt = -Infinity;let closed = false;+ /** A file that cannot be read keeps every automatic replacement off (`unreadable`): its limits cannot be told. */+ let unreadable = false;const load = (): Replacement[] => {+ if (!existsSync(file)) return [];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") : [];+ const parsed = JSON.parse(readFileSync(file, "utf8"));+ if (!Array.isArray(parsed)) throw new Error("not a list");+ return parsed.filter((entry): entry is Replacement => typeof entry?.owner === "string" && typeof entry.boxId === "string" && typeof entry.at === "number");} catch {+ unreadable = true;return [];}};let entries = load();+ if (unreadable) deps.log(`cloud computers: ${file} could not be read, so no computer is set aside or replaced by itself until it can be`);+ // A set-aside computer stays listed until its deletion, however old the entry.+ const keep = (entry: Replacement) => now() - entry.at < KEPT_MS || (entry.setAside !== undefined && !entry.undone);const write = (next: Replacement[]) => {- entries = next.filter((entry) => now() - entry.at < KEPT_MS);- writeFileAtomic(file, JSON.stringify(entries));+ entries = next.filter(keep);+ if (!unreadable) writeFileAtomic(file, JSON.stringify(entries));};const update = (boxId: string, patch: Partial<Replacement>) => write(entries.map((entry) => entry.boxId === boxId ? { ...entry, ...patch } : entry));@@ -156,6 +214,7 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {restoringSince.delete(boxId);told.delete(boxId);errorSeen.delete(boxId);+ blockedWhy.delete(owner);if (states.get(owner)?.boxId !== boxId) return;states.delete(owner);deps.changed?.(owner);@@ -180,6 +239,7 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {if (first === undefined) errorSeen.set(boxId, now());return first !== undefined && now() - first >= DEAD_COMPUTER.deadConfirmMs;};+ const dateOf = (at: number) => new Date(at).toISOString().slice(0, 10);/** One recovery at a time per owner, in the order asked. */function lane<T>(owner: string, work: () => Promise<T>): Promise<T> {@@ -191,7 +251,9 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));- async function restart(owner: string, boxId: string, manual = false): Promise<"answers" | "no-answer" | "refused"> {+ /** `no-answer`: it woke, and its wait for an answer ran out, the only restart that did not help. `not-ready`: the+ * provider did not report it ready again in time, which says nothing about the machine. */+ async function restart(owner: string, boxId: string, manual = false): Promise<"answers" | "no-answer" | "not-ready" | "refused"> {const cfg = deps.cfg();set(owner, boxId, "restarting", manual);restarts.set(boxId, now());@@ -209,12 +271,16 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {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";+ const woken = await boat.readyBoat(cfg, owner, deps.wakeBudgetMs ?? WAKE_BUDGET_MS).catch(() => null);+ if (!woken || woken.id !== boxId) return "not-ready";+ health.woke(boxId);// The provider reports a resumed computer ready before it answers, so one probe right after the resume proves nothing.const answer = await readiness.awaitAnswer(cfg, boxId, { woke: true, ...(manual ? { deadline: now() + MANUAL_ANSWER_WAIT_MS } : {}) });cloudComputerCounters.count(boxId, "restarts", now() - started);- if (!answer.ok) return "no-answer";+ if (!answer.ok) {+ restartFailedAt.set(boxId, now());+ return "no-answer";+ }health.answered(boxId);return "answers";}@@ -231,45 +297,75 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {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`);+ deps.log(`cloud computer ${owner}: ${boxId} is not responding, and the provider can't be shown to be up; nothing was changed`);}- /** `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) || deps.usedByOther?.(owner, target.boxId) === true) { 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);- const today = entries.filter((entry) => !entry.manual && entry.boxId !== target.boxId && entry.owner === owner && now() - entry.at < DAY_MS);- if (automatic.filter((entry) => entry.owner === owner).length >= DEAD_COMPUTER.replacementsPerHour || today.length >= DEAD_COMPUTER.replacementsPerDay) {- tellOnce(owner, target.boxId, "capped", "capped");- deps.log(`cloud computer ${owner}: ${target.boxId} was already replaced in the last hour, or three times today; 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";- }- }+ /** A probe whose time is recorded with it: one this process held up past its timeout counts neither way. */+ async function probe(cfg: AppConfig, boxId: string): Promise<boolean | null> {+ const sent = now();+ const answered = await boat.probeBoat(cfg, boxId);+ if (answered === true) health.answered(boxId);+ if (answered !== false) return answered;+ const sample = { elapsedMs: now() - sent, timeoutMs: DEAD_COMPUTER.probeTimeoutMs };+ health.unanswered(boxId, sample);+ return stalledProbe(sample) ? null : false;+ }++ /** Every condition for setting a silent computer aside, the last a fresh probe. `answers` and `unreachable` end the+ * wait; any other reason leaves it for later. */+ async function setAsideBlocked(owner: string, boxId: string, cfg: AppConfig, asking?: WakeTimeoutContext["turn"]): Promise<null | { why: string; answers?: true; unreachable?: true; person?: true }> {+ if (unreadable) return { why: "the record of earlier replacements could not be read" };+ if (now() - noRoomAt < NO_ROOM_BACKOFF_MS) return { why: "the plan had no room for a new computer in the last hours" };+ if (personBusy(owner, boxId) || deps.usedByOther?.(owner, boxId, asking) === true) return { why: "a person or another turn is using it", person: true };+ const silentSince = health.silentSince(boxId), failedAt = restartFailedAt.get(boxId);+ // A restart's own wait that ran out during this silence; a restart the provider never reported ready does not count.+ if (silentSince === null || failedAt === undefined || failedAt < silentSince) return { why: "no restart has been tried and failed during this silence" };+ const box = await read(cfg, boxId);+ const state = box && typeof box === "object" ? (box as { state?: unknown }).state : undefined;+ if (typeof state !== "string" || !READY.has(state)) return { why: `the provider reports it ${typeof state === "string" ? state : "in a state it could not read"}` };+ const restoring = boatSignals(box).restoring, wokeAt = health.wokeAt(boxId);+ if (restoring === true) return { why: "the provider is still restoring its disk" };+ if (restoring === null && (wokeAt === null || now() - wokeAt < DEAD_COMPUTER.unknownRestoreMs)) {+ return { why: "the provider does not say whether its disk is back, and it was resumed less than 30 minutes ago" };+ }+ // Several probes after the patience, spread over minutes: not one sample.+ const probes = health.silencesSince(boxId, wokeAt ?? failedAt);+ if (probes.count < DEAD_COMPUTER.setAsideProbes || probes.last! - probes.first! < DEAD_COMPUTER.setAsideProbeSpanMs) return { why: "too few unanswered probes since its restart" };+ if (stalled(wokeAt ?? failedAt, now())) return { why: "this process stalled while the computer was probed" };+ const witnessed = health.otherAnsweredWithin(boxId, DEAD_COMPUTER.freshWitnessMs);+ if (!witnessed && health.othersSilentWithin(boxId, DEAD_COMPUTER.witnessMs)) return { why: "the installation's other computers are silent too", unreachable: true };+ if (!witnessed && now() - silentSince < DEAD_COMPUTER.loneSilenceMs) {+ return { why: "no other computer answered in the last two minutes, and it has been silent less than 30 minutes" };}- set(owner, target.boxId, "replacing", opts.manual);- if (!recorded) write([...entries, { owner, boxId: target.boxId, at: now(), ...(opts.manual ? { manual: true as const } : {}) }]);+ if (!(await listWorks(cfg))) return { why: "the provider's list does not answer", unreachable: true };+ const last = await probe(cfg, boxId);+ if (last === true) return { why: "it answers", answers: true };+ if (last === null) return { why: "a last probe was turned away or held up here" };+ return null;+ }++ /** The limits, counted before anything is done: null when they allow one more. */+ function limited(owner: string, boxId: string): "capped" | "held" | null {+ const automatic = entries.filter((entry) => !entry.manual && entry.boxId !== boxId && now() - entry.at < HOUR_MS);+ const today = entries.filter((entry) => !entry.manual && entry.boxId !== boxId && entry.owner === owner && now() - entry.at < DAY_MS);+ if (automatic.filter((entry) => entry.owner === owner).length >= DEAD_COMPUTER.replacementsPerHour || today.length >= DEAD_COMPUTER.replacementsPerDay) {+ tellOnce(owner, boxId, "capped", "capped");+ deps.log(`cloud computer ${owner}: ${boxId} was already replaced in the last hour, or three times today; left as it is`);+ return "capped";+ }+ if (automatic.length >= DEAD_COMPUTER.installationDeletesPerHour) {+ needsPerson(owner, boxId);+ deps.log(`cloud computer ${owner}: ${boxId} left for the person: this installation already replaced a computer by itself in the last hour`);+ return "held";+ }+ return null;+ }++ /** The DELETE, for the person's Replace computer and a broken computer that cannot be stopped; its entry is written. */+ async function remove(owner: string, target: Dead, manual: boolean): Promise<DeleteOutcome> {+ const cfg = deps.cfg();retired.add(target.boxId);- let outcome: ReplaceOutcome;+ let outcome: DeleteOutcome;try {const deleted = await boat.requestRecordedBoatDeletion(cfg, { boxId: target.boxId, name: target.name, ownerBotId: owner });outcome = deleted === "confirmed" ? "confirmed" : "pending";@@ -283,56 +379,112 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {if (!getBoatDeletion(target.boxId)) retired.delete(target.boxId);return outcome;}- set(owner, target.boxId, "replaced", opts.manual);- if (!opts.manual) {+ set(owner, target.boxId, "replaced", manual);+ if (!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"})`);+ deps.log(`cloud computer ${owner}: deleted ${target.boxId} (${manual ? "asked for" : "the provider reports it broken, and it could not be stopped"})`);return outcome;}- /** A fresh probe that got no answer, with the provider's list working; false when that is not so (the outcome is- * reported). `witness`: before a delete, the installation's other computers must not all be silent as well: that is- * the provider's own outage, which a new computer would not fix. An installation with no other computer in use has no- * one to compare against; its list answering, a restart that did not help and the hourly and daily limits stand for- * that, or a lone computer would never be replaced. */- async function stillDown(owner: string, boxId: string, cfg: AppConfig, witness = true): Promise<boolean> {- const probe = await boat.probeBoat(cfg, boxId);- if (probe !== false) {- if (probe) health.answered(boxId);- clear(owner, boxId);- return false;+ /** Sets the computer aside and makes the bot a new one, within the limits, which are written first. `dead`: the+ * provider reports it broken; one that cannot even be stopped is deleted instead, as before. The caller checked the+ * other guards. Never sends a DELETE for a computer that could be stopped. */+ async function setAside(owner: string, target: Dead, opts: { dead?: boolean; onReplacing?: () => void } = {}): Promise<SetAsideResult> {+ const cfg = deps.cfg();+ if (unreadable) { needsPerson(owner, target.boxId); return "held"; }+ const limit = limited(owner, target.boxId);+ if (limit) return limit;+ const at = now(), name = await setAsideBoatName(owner, at), until = at + DEAD_COMPUTER.setAsideKeepMs;+ write([...entries.filter((entry) => entry.boxId !== target.boxId), { owner, boxId: target.boxId, at, setAside: { name, until } }]);+ opts.onReplacing?.();+ set(owner, target.boxId, "replacing");+ deps.log(`cloud computer ${owner}: setting ${target.boxId} aside as ${name}${opts.dead ? " (the provider reports it broken)" : ""}`);+ const result = await setAsideBoat(cfg, owner, target, name, { log: deps.log, provision: deps.provision });+ if (result.kind === "set-aside") {+ retired.add(target.boxId);+ health.forget(target.boxId);+ update(target.boxId, { setAside: { name, until, newBoxId: result.newBoxId }, toldPerson: true });+ set(owner, target.boxId, "replaced");+ deps.tell(owner, "setAside", { date: dateOf(until) });+ deps.created?.(owner);+ deps.log(`cloud computer ${owner}: ${target.boxId} set aside as ${name} until ${dateOf(until)}; the bot's new computer is ${result.newBoxId}`);+ return "set-aside";}- if (!(await listWorks(cfg))) { unreachable(owner, boxId); return false; }- if (witness && !health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs) && health.othersSilentWithin(boxId, DEAD_COMPUTER.witnessMs)) {- unreachable(owner, boxId);- return false;+ if (result.kind === "stop-refused" && opts.dead) {+ // A broken computer the provider will not even stop: deleted, as before.+ update(target.boxId, { setAside: undefined });+ const deleted = await remove(owner, target, false);+ return deleted === "failed" ? "failed" : deleted === "confirmed" ? "deleted" : "deleting";}- return true;+ if ((result.kind === "no-room" || result.kind === "create-failed") && !result.restored) {+ // Still set aside, and the bot has no computer: it is never deleted by itself (`undone`), only by the person, who+ // finds it in Settings.+ retired.add(target.boxId);+ update(target.boxId, { undone: true });+ needsPerson(owner, target.boxId);+ return "lost";+ }+ update(target.boxId, { undone: true });+ if (result.kind === "no-room") {+ noRoomAt = now();+ tellOnce(owner, target.boxId, "needs-person", "noRoom");+ deps.log(`cloud computer ${owner}: ${target.boxId} kept: the plan has no room for a new computer beside it (${result.reason})`);+ } else {+ set(owner, target.boxId, "not-responding");+ deps.log(`cloud computer ${owner}: ${target.boxId} was not set aside: ${"reason" in result ? result.reason : result.kind}`);+ }+ return result.kind;}- /** After the restart: replaced once the provider says the machine is gone, at once when the restart's own wake got no- * answer in its patience (`restartFailed`), or else after DEAD_COMPUTER.replaceAfterMs of no answers. */- async function decide(owner: string, boxId: string, restartFailed = false): Promise<void> {+ /** The provider reports this computer broken. It is set aside, or deleted when it cannot be stopped, once that was+ * seen twice DEAD_COMPUTER.deadConfirmMs apart. */+ async function dead(owner: string, target: Dead): Promise<SetAsideResult | "kept" | "waiting"> {+ if (!eligible(owner)) { needsPerson(owner, target.boxId); return "held"; }+ if (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 broken; automatic replacement is off, so it waits for the person`);+ return "held";+ }+ if (personBusy(owner, target.boxId) || deps.usedByOther?.(owner, target.boxId) === true) { needsPerson(owner, target.boxId); return "held"; }+ if (!deadConfirmed(target.boxId)) { needsPerson(owner, target.boxId); return "waiting"; }+ if (!(await listWorks(deps.cfg()))) { unreachable(owner, target.boxId); return "held"; }+ return setAside(owner, target, { dead: true });+ }++ /** After the restart: set aside once every condition holds (setAsideBlocked), looked at again every few minutes while+ * the computer stays silent and some condition does not. */+ 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 = restartFailed ? 0 : 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);+ if (seen.identity.state === "error") return void await dead(owner, seen.identity);+ if (health.notRespondingSince(boxId) === null || !READY.has(seen.identity.state)) return clear(owner, boxId);+ if (!autoReplace()) {+ needsPerson(owner, boxId);+ deps.log(`cloud computer ${owner}: ${boxId} is not responding; automatic replacement is off, so it waits for the person`);+ return;+ }+ const blocked = await setAsideBlocked(owner, boxId, cfg);+ if (blocked?.answers) return clear(owner, boxId);+ if (blocked?.unreachable) return unreachable(owner, boxId);+ if (blocked) {+ if (blockedWhy.get(owner) !== blocked.why) deps.log(`cloud computer ${owner}: ${boxId} is not responding and is not set aside yet: ${blocked.why}`);+ blockedWhy.set(owner, blocked.why);+ if (blocked.person) needsPerson(owner, boxId); else set(owner, boxId, "not-responding");+ const timer = setTimeout(() => {+ timers.delete(owner);+ if (!closed) void lane(owner, () => notResponding(owner, boxId)).catch((error) => deps.log(`cloud computer ${owner}: ${String(error)}`));+ }, setAsideRecheckMs);timer.unref?.();timers.set(owner, timer);return;}- if (!(await stillDown(owner, boxId, cfg))) return;- await replace(owner, seen.identity);+ await setAside(owner, seen.identity);}async function notResponding(owner: string, boxId: string): Promise<void> {@@ -341,15 +493,11 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {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 (seen.identity.state === "error") return void await dead(owner, seen.identity);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, false))) return;- const since = Math.min(health.notRespondingSince(boxId) ?? now(), restoringSince.get(boxId) ?? now());- restoringSince.set(boxId, since);/** Looks again shortly instead of restarting now. */const later = (state: "restoring" | "not-responding") => {set(owner, boxId, state);@@ -360,6 +508,14 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {timer.unref?.();timers.set(owner, timer);};+ // A turn waiting for this computer to answer owns it meanwhile: its own patience, restart and set-aside come first.+ if (deps.turnWaiting?.(boxId) === true) return later("not-responding");+ // Every guard before a stop: it closes the person's programs, and three failed probes can be this home's own outage.+ const fresh = await probe(cfg, boxId);+ if (fresh !== false) return clear(owner, boxId);+ if (!(await listWorks(cfg))) return unreachable(owner, boxId);+ const since = Math.min(health.notRespondingSince(boxId) ?? now(), restoringSince.get(boxId) ?? now());+ restoringSince.set(boxId, since);// The provider's command gateway can fail for every computer while its API still calls each one ready. Then a// restart helps nobody and stops work that is still running, so one is made only when this computer alone is silent.const witnessed = health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs);@@ -374,84 +530,139 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {if (boatSignals(box).restoring === true && now() - since < READY_WAIT.restorePatienceMs) return later("restoring");if (!witnessed && now() - since < SOLO_SILENCE_MS) return later("not-responding");const lastRestart = restarts.get(boxId);- const limited = (lastRestart !== undefined && now() - lastRestart < HOUR_MS) || now() - lastAutoRestartAt < DEAD_COMPUTER.restartGapMs;- if (limited || personBusy(owner, boxId)) {+ const limitedNow = (lastRestart !== undefined && now() - lastRestart < HOUR_MS) || now() - lastAutoRestartAt < DEAD_COMPUTER.restartGapMs;+ if (limitedNow || personBusy(owner, boxId)) {// A restart that just failed stays the reason: it says more than the limit that restart itself set off.const failed = verdicts.get(owner);- if (!(limited && failed?.boxId === boxId && failed.why === "restart-failed")) judge(owner, boxId, limited ? "restart-limited" : "person-busy");- deps.log(`cloud computer ${owner}: ${boxId} is not responding and was not restarted: ${limited ? "a restart was made too recently" : "a person is using it"}`);+ if (!(limitedNow && failed?.boxId === boxId && failed.why === "restart-failed")) judge(owner, boxId, limitedNow ? "restart-limited" : "person-busy");+ if (blockedWhy.get(owner) === undefined) deps.log(`cloud computer ${owner}: ${boxId} is not responding and was not restarted: ${limitedNow ? "a restart was made too recently" : "a person is using it"}`);} else {lastAutoRestartAt = now();deps.log(`cloud computer ${owner}: ${boxId} is not responding though the provider reports it ready; restarting it`);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;- }+ if (restarted === "answers") return restartedNow(owner, boxId);judge(owner, boxId, "restart-failed");- deps.log(`cloud computer ${owner}: ${boxId} still does not answer after a restart`);- return decide(owner, boxId, restarted === "no-answer");+ deps.log(`cloud computer ${owner}: ${boxId} still does not answer after a restart${restarted === "no-answer" ? "" : ` (${restarted}: the restart itself did not finish)`}`);}return decide(owner, boxId);}- /** A computer woken, created or restarted for a turn that did not answer in the wake's patience. Every guard of a- * replacement holds; one that is merely slow but answers a last probe is kept. */- async function wakeTimedOut(owner: string, boxId: string): Promise<WakeTimeoutOutcome> {- if (!autoReplace()) return { kind: "off" };- if (!eligible(owner)) { needsPerson(owner, boxId); return keptWhy("held"); }+ function restartedNow(owner: string, boxId: string): void {+ 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);+ }++ /** After a turn left its silent computer as it is: the background recovery looks at it again shortly, as the turn was+ * told, unless it already does. */+ function followUp(owner: string, boxId: string): void {+ if (closed || timers.has(owner)) return;+ const timer = setTimeout(() => {+ timers.delete(owner);+ if (!closed) void lane(owner, () => notResponding(owner, boxId)).catch((error) => deps.log(`cloud computer ${owner}: ${String(error)}`));+ }, recheckMs);+ timer.unref?.();+ timers.set(owner, timer);+ }++ /** A computer woken, created or restarted for a turn that did not answer in the wake's patience: restarted (its files+ * kept) and waited for again, then set aside only if every condition holds. Otherwise left as it is, and the turn's+ * claim fails as a passing failure that says MausBot keeps trying, which the background recovery then does. */+ async function wakeTimedOut(owner: string, boxId: string, ctx: WakeTimeoutContext = {}): Promise<WakeTimeoutOutcome> {+ const outcome = await wakeTimedOutOnce(owner, boxId, ctx);+ if (outcome.kind === "kept" && eligible(owner) && !retired.has(boxId)) followUp(owner, boxId);+ return outcome;+ }++ async function wakeTimedOutOnce(owner: string, boxId: string, ctx: WakeTimeoutContext): Promise<WakeTimeoutOutcome> {+ if (!eligible(owner)) { needsPerson(owner, boxId); return kept(silentWhy(false)); }const cfg = deps.cfg();const seen = await boat.inspectBoatIdentity(cfg, boxId);- if (!seen.available) { unreachable(owner, boxId); return keptWhy("unreachable"); }+ if (!seen.available) { unreachable(owner, boxId); return kept(`the cloud computer service itself can't be reached right now, so nothing was changed. ${LATER}`); }if (!seen.identity || !(await boat.boatNameMatchesBot(owner, seen.identity.name))) return { kind: "gone" };- if (seen.identity.state !== "error") {- const probe = await boat.probeBoat(cfg, boxId);- if (probe !== false) {- if (probe) health.answered(boxId);- clear(owner, boxId);- return { kind: "answers" };- }- if (!(await listWorks(cfg))) { unreachable(owner, boxId); return keptWhy("unreachable"); }- if (!health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs) && health.othersSilentWithin(boxId, DEAD_COMPUTER.witnessMs)) {- unreachable(owner, boxId);- return keptWhy("unreachable");+ if (seen.identity.state === "error") {+ const outcome = await dead(owner, seen.identity);+ if (outcome === "set-aside" || outcome === "deleted" || outcome === "deleting") return { kind: "replaced" };+ return kept(outcome === "kept" ? silentWhy(false) : `the provider reports the cloud computer broken, and MausBot left it as it is for now${outcome === "waiting" ? ", until the provider has said so for half an hour" : ""}. ${LATER}`);+ }+ if ((await probe(cfg, boxId)) === true) { clear(owner, boxId); return { kind: "answers" }; }+ if (personBusy(owner, boxId) || deps.usedByOther?.(owner, boxId, ctx.turn) === true) {+ deps.log(`cloud computer ${owner}: ${boxId} did not answer its wake, and someone else is using it; left as it is`);+ return kept(`the cloud computer is still not answering, and someone else is using it, so it was left as it is. ${LATER}`);+ }+ const lastRestart = restarts.get(boxId);+ let restarted = false;+ if (!((lastRestart !== undefined && now() - lastRestart < HOUR_MS) || now() - lastAutoRestartAt < DEAD_COMPUTER.restartGapMs)) {+ lastAutoRestartAt = now();+ deps.log(`cloud computer ${owner}: ${boxId} did not answer within ${Math.round(READY_WAIT.wakePatienceMs / 60_000)} minutes of waking; restarting it`);+ ctx.onRestarting?.();+ const outcome = await restart(owner, boxId);+ if (outcome === "answers") { restartedNow(owner, boxId); return { kind: "answers" }; }+ judge(owner, boxId, "restart-failed");+ restarted = outcome === "no-answer";+ if (!restarted) { set(owner, boxId, "not-responding"); return kept(silentWhy(false)); }+ }+ if (!autoReplace()) { set(owner, boxId, "not-responding"); return kept(silentWhy(restarted)); }+ const blocked = await setAsideBlocked(owner, boxId, cfg, ctx.turn);+ if (blocked?.answers) { clear(owner, boxId); return { kind: "answers" }; }+ if (blocked) {+ if (blocked.unreachable) unreachable(owner, boxId); else set(owner, boxId, "not-responding");+ deps.log(`cloud computer ${owner}: ${boxId} is still silent and was left as it is: ${blocked.why}`);+ return kept(silentWhy(restarted));+ }+ const outcome = await setAside(owner, seen.identity, { onReplacing: ctx.onReplacing });+ if (outcome === "set-aside" || outcome === "deleted" || outcome === "deleting") return { kind: "replaced" };+ return kept(KEPT_WHY[outcome]);+ }++ /** Deletes the set-aside computers whose time is up, one at a time. */+ async function sweep(): Promise<void> {+ if (unreadable || closed) return;+ for (const entry of entries.filter((candidate) => candidate.setAside && !candidate.undone && candidate.setAside.until <= now())) {+ let outcome: Awaited<ReturnType<typeof deleteExpiredSetAside>>;+ try {+ outcome = await deleteExpiredSetAside(deps.cfg(), { boxId: entry.boxId, name: entry.setAside!.name });+ } catch (error) {+ deps.log(`cloud computer ${entry.owner}: the set-aside ${entry.boxId} could not be deleted yet: ${error instanceof Error ? error.message : String(error)}`);+ continue;}+ if (outcome === "kept") continue;+ deps.log(`cloud computer ${entry.owner}: the set-aside ${entry.boxId} ${outcome === "deleted" ? "was deleted after its seven days" : outcome === "gone" ? "is gone" : "was renamed by someone, so it is kept"}`);+ write(entries.filter((candidate) => candidate !== entry));}- deps.log(`cloud computer ${owner}: ${boxId} did not answer within ${Math.round(READY_WAIT.wakePatienceMs / 60_000)} minutes of waking; replacing it`);- const outcome = await replace(owner, seen.identity, seen.identity.state === "error" ? { dead: true } : {});- // "kept": it answered a command moments ago by the record, though not this probe; left as it is, as when switched off.- return outcome === "confirmed" || outcome === "pending" ? { kind: "replaced" } : outcome === "kept" ? { kind: "off" } : keptWhy(outcome);}+ const sweeper = setInterval(() => void sweep().catch((error) => deps.log(`cloud computers: ${String(error)}`)), SWEEP_MS);+ sweeper.unref?.();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;+ // A turn waiting for this computer owns it meanwhile: looked at again once that wait is over, as the turn may not.+ if (deps.turnWaiting?.(boxId) === true) return followUp(owner, boxId);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> => {+ boat.onDeadBoat(async (_cfg, owner, broken): Promise<never> => {if (!eligible(owner)) {- needsPerson(owner, dead.boxId);+ needsPerson(owner, broken.boxId);throw Object.assign(new Error(CLOUD_COMPUTER_TEAM_NOT_RESPONDING), { status: 409 });}- const outcome = await lane(owner, () => replace(owner, dead, { dead: true }));+ const outcome = await lane(owner, () => dead(owner, broken));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 });+ if (outcome !== "set-aside" && outcome !== "deleted" && outcome !== "deleting") throw Object.assign(new Error(CLOUD_COMPUTER_NEEDS_PERSON), { status: 409 });+ throw Object.assign(new Error("the previous cloud computer was replaced — retry to use the new one"),+ { status: 409, code: outcome === "deleting" ? BOAT_DELETING : BOAT_DELETION_FINISHED });});return {@@ -472,19 +683,25 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {/** 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 silent = phase === "before" ? CLOUD_COMPUTER_NOT_RESPONDING : CLOUD_COMPUTER_NOT_RESPONDING_UNANSWERED;+ if (retired.has(boxId)) return silent;const owner = boat.boatOwnerOf(boxId);- const found = owner ? states.get(owner) : undefined;+ let found = owner ? states.get(owner) : undefined;+ // It answered a command since it was found silent: nothing is under way any more.+ if (found?.boxId === boxId && found.state === "not-responding" && !lanes.has(owner!) && health.answeredWithin(boxId, now() - found.at)) {+ clear(owner!, boxId);+ found = undefined;+ }if (found?.boxId === boxId && found.state === "restarting") return phase === "before" ? CLOUD_COMPUTER_RESTARTING : CLOUD_COMPUTER_RESTARTING_UNANSWERED;if (found?.boxId === boxId && found.state === "restoring") return phase === "before" ? CLOUD_COMPUTER_RESTORING : CLOUD_COMPUTER_STILL_RESTORING;- if (found?.boxId === boxId && recoveryUnderWay(found.state)) return CLOUD_COMPUTER_NOT_RESPONDING;+ if (found?.boxId === boxId && recoveryUnderWay(found.state)) return silent;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;+ return health.notRespondingSince(boxId) === null ? null : silent;},- wakeTimedOut: (owner: string, boxId: string): Promise<WakeTimeoutOutcome> => lane(owner, () => wakeTimedOut(owner, boxId)),+ wakeTimedOut: (owner: string, boxId: string, ctx?: WakeTimeoutContext): Promise<WakeTimeoutOutcome> => lane(owner, () => wakeTimedOut(owner, boxId, ctx)),/** Resolves once no restart or replacement of this computer is under way, or at `until`: a call waits that out instead* of being refused at once, so a recovery in progress is not taken for one failure after another. */async settle(boxId: string, until: number, signal?: AbortSignal): Promise<void> {@@ -496,30 +713,38 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {};// `until` is the caller's own clock, the wall clock.while (underWay() && Date.now() < until && !signal?.aborted && !closed) {- await Promise.race([lanes.get(owner)?.catch(() => undefined), wait(Math.max(1, Math.min(pollMs, until - Date.now())))]);+ const running = lanes.get(owner), pause = wait(Math.max(1, Math.min(pollMs, until - Date.now())));+ // Only a lane under way is raced: with none (a timer waits), the pause alone, never a promise already settled.+ await (running ? Promise.race([running.catch(() => undefined), pause]) : pause);}},- /** This computer was deleted by a replacement: the turn that used it goes on on the owner's new one. */+ /** This computer is no longer its bot's (set aside, or deleted): the turn that used it goes on on the owner's new one. */replaced: (boxId: string): boolean => retired.has(boxId),/** 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);+ const owed = entries.filter((entry) => entry.owner === owner && entry.boxId !== boxId && !entry.toldBot && !entry.undone);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");+ const setAside = [...owed].reverse().find((entry) => entry.setAside);+ if (setAside?.setAside) return cloudComputerSetAsideNotice(dateOf(setAside.setAside.until));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. *//** This owner's computer was replaced by itself in the last fifteen minutes: its turns may make the new one even* where they would never make a first one. */- replacedRecently: (owner: string): boolean => entries.some((entry) => entry.owner === owner && !entry.manual && now() - entry.at < 15 * 60_000),- 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;+ replacedRecently: (owner: string): boolean => entries.some((entry) => entry.owner === owner && !entry.manual && !entry.undone && now() - entry.at < 15 * 60_000),+ /** A start the Admin turned away for computers at once, while a computer this installation set aside still holds a+ * place: what the bot is told, in place of the plan's own sentence. */+ claimSentence(_owner: string, error: unknown): string | undefined {+ if (cloudFailureOf(error).limit?.reason !== "at_once") return undefined;+ const held = entries.filter((entry) => entry.setAside && !entry.undone && entry.setAside.until > now());+ if (!held.length) return undefined;+ return `The plan's cloud computers are all in use, ${held.length === 1 ? "one of them by an old computer" : "some of them by old computers"} MausBot set aside, with their files, `+ + `until ${dateOf(Math.min(...held.map((entry) => entry.setAside!.until)))}. The person can delete ${held.length === 1 ? "it" : "them"} in Settings → Desktops & browser → Desktops to free the place. `+ + "Do not retry computer work in this turn; tell the person.";},/** 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. */@@ -546,17 +771,24 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {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. */+ /** The panel's Replace computer, confirmed by the person: deleted, with no hourly limit, as the person asked. */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 }));+ const outcome = await lane(owner, async () => {+ set(owner, target.boxId, "replacing", true);+ write([...entries.filter((entry) => entry.boxId !== target.boxId), { owner, boxId: target.boxId, at: now(), manual: true }]);+ return remove(owner, target, 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 };},+ /** Deletes set-aside computers whose time is up; runs by itself every hour. */+ sweep,close(): void {closed = true;+ clearInterval(sweeper);unsubscribe();boat.onDeadBoat(null);for (const timer of timers.values()) clearTimeout(timer);diff --git a/server/boat-set-aside.ts b/server/boat-set-aside.tsnew file mode 100644index 0000000000..08f554c31a--- /dev/null+++ b/server/boat-set-aside.ts@@ -0,0 +1,97 @@+// A bot's cloud computer that stopped answering is never deleted by itself: it is set aside. It is stopped (the provider+// keeps its disk), renamed so it is no longer the bot's, and a new computer is made for the bot. The old one is kept for+// DEAD_COMPUTER.setAsideKeepMs, listed in Settings → Desktops & browser → Desktops, and only then deleted+// (deleteExpiredSetAside). If the new computer cannot be made (the plan has no room for one more, say), the old one gets+// its name back and stays the bot's: nothing is lost either way.+//+// The Admin counts a stopped computer against the plan's computers at once until it is deleted, so on a plan that+// includes one computer the new one is refused (`at_once`) and the old one is put back.+import * as boat from "./boat.ts";+import { forgetSetAsideBoatCreate } from "./boat-create-idempotency.ts";+import { cloudFailureOf } from "./boat-limit.ts";+import type { AppConfig } from "./config.ts";++/** `-set-aside-YYYY-MM-DD` after the bot's own computer name (boat.SET_ASIDE_BOAT_NAME): only characters every computer+ * name already has, and a name Settings lists as this installation's, owned by no bot. */+export async function setAsideBoatName(owner: string, at: number): Promise<string> {+ return `${await boat.boatNameFor(owner)}-set-aside-${new Date(at).toISOString().slice(0, 10)}`;+}++/** `set-aside`: the old computer is stopped and renamed, and the bot has `newBoxId`. `stop-refused`: nothing was changed.+ * `rename-failed`: the old computer was stopped but keeps its name, so it is still the bot's and wakes on its next use.+ * `no-room`: the plan has no room for a new computer; `create-failed`: the new one could not be made. In both, the old one+ * got its name back (`restored`), or, when even that failed, it is still set aside and the bot has no computer. */+export type SetAsideOutcome =+ | { kind: "set-aside"; newBoxId: string; name: string }+ | { kind: "stop-refused" | "rename-failed" }+ | { kind: "no-room" | "create-failed"; restored: boolean; reason: string };++export interface SetAsideDeps {+ log(line: string): void;+ /** Makes the bot's new computer; boat.provisionBoat unless a test plays it. */+ provision?(cfg: AppConfig, owner: string): Promise<{ boxId: string }>;+}++/** How long a stop is waited for before the rename: the provider may refuse a change to a computer still archiving. */+const STOP_WAIT_MS = 60_000;+const POLL_MS = 2_500;+const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++const rename = async (cfg: AppConfig, boxId: string, name: string): Promise<boolean> => {+ try {+ const renamed = await boat.boatFetch(cfg, `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ name }), signal: AbortSignal.timeout(30_000) });+ await renamed.body?.cancel().catch(() => undefined);+ return renamed.ok;+ } catch {+ return false;+ }+};++/** Stop, rename, then make the new computer. Never sends a DELETE for `target`. */+export async function setAsideBoat(cfg: AppConfig, owner: string, target: { boxId: string; name: string }, setAsideName: string, deps: SetAsideDeps): Promise<SetAsideOutcome> {+ const provision = deps.provision ?? (async (config: AppConfig, bot: string) => ({ boxId: String((await boat.provisionBoat(config, bot, "")).boxId) }));+ try {+ const stopped = await boat.boatFetch(cfg, `/sandboxes/${target.boxId}/stop`, { method: "POST", signal: AbortSignal.timeout(30_000) });+ await stopped.body?.cancel().catch(() => undefined);+ // 409: already stopping or stopped.+ if (!stopped.ok && stopped.status !== 409) return { kind: "stop-refused" };+ } catch {+ return { kind: "stop-refused" };+ }+ // The create receipt goes first: were it kept, the next create would find this computer again and name it back. A+ // computer that keeps its name needs no receipt to be found.+ for (const deadline = Date.now() + STOP_WAIT_MS; Date.now() < deadline;) {+ const seen = await boat.inspectBoatIdentity(cfg, target.boxId);+ if (seen.available && seen.identity?.state !== "archiving") break;+ await pause(POLL_MS);+ }+ forgetSetAsideBoatCreate(target.boxId);+ if (!(await rename(cfg, target.boxId, setAsideName))) return { kind: "rename-failed" };+ boat.forgetBoatId(target.boxId);+ try {+ const made = await provision(cfg, owner);+ return { kind: "set-aside", newBoxId: made.boxId, name: setAsideName };+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ // Tried a few times: a set-aside computer whose name cannot be given back leaves the bot with none.+ let restored = false;+ for (let attempt = 0; attempt < 3 && !restored; attempt++) {+ if (attempt) await pause(POLL_MS);+ restored = await rename(cfg, target.boxId, target.name);+ }+ if (!restored) deps.log(`cloud computer ${owner}: ${target.boxId} was set aside as ${setAsideName}, but no new computer could be made and its name could not be given back: ${reason}`);+ return { kind: cloudFailureOf(error).limit?.reason === "at_once" ? "no-room" : "create-failed", restored, reason };+ }+}++/** Deletes a set-aside computer whose time is up: only while it is still there under the name it was set aside with (a+ * person who renamed it took it back). `kept`: it could not be read, so it is tried again later. */+export async function deleteExpiredSetAside(cfg: AppConfig, record: { boxId: string; name: string }): Promise<"deleted" | "gone" | "renamed" | "kept"> {+ const seen = await boat.inspectBoatIdentity(cfg, record.boxId);+ if (!seen.available) return "kept";+ if (!seen.identity) return "gone";+ if (seen.identity.name !== record.name || !boat.SET_ASIDE_BOAT_NAME.test(seen.identity.name)) return "renamed";+ // No owner: the deletion of a set-aside computer never holds up its bot's new one.+ await boat.requestRecordedBoatDeletion(cfg, { boxId: record.boxId, name: record.name, ownerBotId: null });+ return "deleted";+}diff --git a/server/boat.ts b/server/boat.tsindex c244ef66c1..c6805db7fb 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -72,7 +72,7 @@ const BOAT_INVENTORY_PAGE_SIZE = 200;// Bounded: a broken or adversarial cursor must not hold Settings open.const MAX_BOAT_INVENTORY_PAGES = 10;const LEGACY_MANAGED_BOAT_NAME = /^ogb-[a-z0-9]{1,8}-[a-f0-9]{6}$/;-const SCOPED_MANAGED_BOAT_NAME = /^ogb-[a-f0-9]{12}-[a-z0-9]{1,8}-[a-f0-9]{6}$/;+const SCOPED_MANAGED_BOAT_NAME = /^ogb-[a-f0-9]{12}-[a-z0-9]{1,8}-[a-f0-9]{6}$/; /** Set aside (boat-set-aside.ts): this installation's, no bot's. */ export const SET_ASIDE_BOAT_NAME = /^ogb-[a-f0-9]{12}-[a-z0-9]{1,8}-[a-f0-9]{6}-set-aside-\d{4}-\d{2}-\d{2}$/;const BOAT_ID = /^bx_[23456789abcdefghjkmnpqrstuvwxyz]{8}$/;/** Sandbox.state in v1, plus OpenMausBot's own `removing` for a sandbox whose deletion is under way. */const BOAT_STATES = new Set([@@ -642,7 +642,7 @@ export async function listManagedBoats(const name = typeof candidate.name === "string" ? candidate.name : "";let owner: ManagedBoatOwner | null = null;let legacyOwner = false;- if (SCOPED_MANAGED_BOAT_NAME.test(name)) {+ if (SCOPED_MANAGED_BOAT_NAME.test(name) || SET_ASIDE_BOAT_NAME.test(name)) {if (!name.startsWith(scopedPrefix)) continue;owner = ownerByCurrentName.get(name) ?? null;} else if (LEGACY_MANAGED_BOAT_NAME.test(name)) {diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex 200530dfcb..e5473481c7 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -8,7 +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 { CLOUD_COMPUTER_DEAD_WAITING, CLOUD_COMPUTER_NEEDS_PERSON, CLOUD_COMPUTER_REPLACED_BY_PERSON, cloudComputerSetAsideNotice } from "../shared/cloud-computer-recovery.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { freePortBlock } from "./testing/ports.ts";import { openSse, type SseRecorder } from "./testing/sse.ts";@@ -39,6 +39,8 @@ describe("a cloud computer starts only when the bot uses it", () => {/** The relay refuses every create the way the Admin does once a plan's* hours are used up. */const refuse = { creates: false };+ /** The relay stops a computer when asked; off, a stop is unknown here, as a provider that will not stop one. */+ const stops = { on: false };const requests: Request[] = [];/** Computers deleted at the relay: no longer listed, and a 404 to a direct read. */const gone = new Set<string>();@@ -178,6 +180,10 @@ describe("a cloud computer starts only when the bot uses it", () => {if (row.state === "resuming" && --wakeLooks.left <= 0) row.state = "ready";return send(200, { ok: true, box: seen });}+ if (verb === "stop" && req.method === "POST" && stops.on) {+ row.state = "archived";+ return send(200, { ok: true, box: row });+ }if (verb === "resume" && req.method === "POST") {row.state = "resuming";wakeLooks.left = 3;@@ -381,7 +387,8 @@ describe("a cloud computer starts only when the bot uses it", () => {await apiOk("DELETE", `/api/bots/${bot.id}`);}, 60_000);- it("by default, a computer whose machine is gone is replaced on its next use, and the bot and the person are told once", async () => {+ it("by default, a computer whose machine is gone is set aside (never deleted) on its next use for a new one, and the bot and the person are told once", async () => {+ stops.on = 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`);@@ -402,18 +409,21 @@ describe("a cloud computer starts only when the bot uses it", () => {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 });+ const until = /until (\d{4}-\d{2}-\d{2})/.exec(replaced.body.result.content[0].text)?.[1] ?? "";+ expect(replaced.body.result.content[0]).toEqual({ type: "text", text: cloudComputerSetAsideNotice(until) });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(requests.slice(before).filter(request => request.method === "DELETE")).toEqual([]);+ expect(dead).toMatchObject({ state: "archived", name: expect.stringMatching(/-set-aside-\d{4}-\d{2}-\d{2}$/) });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.";+ const line = `Stranded's cloud computer stopped responding, so MausBot gave it a new one. The old one is kept with its files until ${until} in Settings → Desktops & browser → Desktops, then deleted.`;expect(await recoveryLines(bot.id)).toEqual([`recovery: ${waiting}`, `recovery: ${line}`]);expect(inboxNotices(bot.id)).toEqual([waiting, line]);+ stops.on = false;await apiOk("DELETE", `/api/bots/${bot.id}`);}, 60_000);diff --git a/server/cloud-computer-wake.test.ts b/server/cloud-computer-wake.test.tsindex e6030bf2e9..fd06993f19 100644--- a/server/cloud-computer-wake.test.ts+++ b/server/cloud-computer-wake.test.ts@@ -1,8 +1,10 @@-// A cloud computer woken for a turn that is slow to answer, or never answers: the turn waits for it patiently, and one-// that stays silent past the wake's patience is replaced, once, within its limits, and the turn goes on on the new one.+// A cloud computer woken for a turn that is slow to answer, or never answers: the turn waits for it patiently, then+// restarts it (its files kept) and waits again, and only one still silent after that, with every guard holding, is set+// aside (stopped, renamed, kept with its files) for a new one. Nothing here is ever deleted by the automatic path.// A loopback stand-in for the Cloud's relay plays the provider. No network, no real computer; the data folder is the-// test's own, and the clock the waits read is the test's.-import { mkdtempSync, rmSync } from "node:fs";+// test's own, and the clock the waits read is the test's. The turn's wait and the background recovery share one health+// record, as they do in the app.+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";@@ -10,7 +12,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }import type { AppConfig } from "./config.ts";import type { BotRecord } from "./store.ts";-type Box = { id: string; name: string; state: string };+type Box = { id: string; name: string; state: string; hydrated?: boolean };const ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz";let made = 0;@@ -19,13 +21,19 @@ const opId = (boxId: string) => `bdop_${Buffer.from(boxId.padEnd(16, "x")).toStrlet server: Server;let boxes: Box[] = [];-let requests: Array<{ method: string; path: string; command?: string }> = [];+let requests: Array<{ method: string; path: string; command?: string; name?: string }> = [];/** Until when, on the test's clock, each computer leaves every command unanswered (the gateway's 502). */let silentUntil = new Map<string, number>();/** A computer made from now on is silent for this long, on the test's clock. */let newSilentMs = 0;-let deleteStatus = 202;-let deleteDelayMs = 0;+/** What the provider says of a computer's disk, on every computer: unset says nothing. */+let hydrated: boolean | undefined;+/** The Admin turns a new computer away: the plan's computers at once are all held. */+let noRoom = false;+/** A resume the provider accepts but never finishes. */+let resumeHangs = false;+/** A set-aside rename answers this late, in real milliseconds. */+let renameDelayMs = 0;let at = 50_000_000;const now = () => at;@@ -43,9 +51,14 @@ beforeAll(async () => {const path = url.pathname.replace(/^\/relay\/api\/box\/v1/, "");const body = raw ? JSON.parse(raw) : {};const method = req.method ?? "GET";- requests.push({ method, path, ...(typeof body.command === "string" ? { command: body.command } : {}) });- if (path === "/boxes" && method === "GET") return send(res, 200, { ok: true, boxes, pageInfo: { nextCursor: null } });+ requests.push({ method, path, ...(typeof body.command === "string" ? { command: body.command } : {}), ...(typeof body.name === "string" ? { name: body.name } : {}) });+ const shown = (box: Box) => ({ ...box, ...(hydrated === undefined ? {} : { hydrated }) });+ if (path === "/boxes" && method === "GET") return send(res, 200, { ok: true, boxes: boxes.map(shown), pageInfo: { nextCursor: null } });if (path === "/boxes" && method === "POST") {+ if (noRoom) {+ const fields = { reason: "at_once", plan: "Personal", limit: 1, used: 1 };+ return send(res, 429, { ok: false, code: "limit_reached", message: "Your Personal plan includes 1 cloud computer at once. Delete one to start another.", ...fields, error: { code: "limit_reached", ...fields } });+ }const box = { id: newId(), name: "", state: "ready" };boxes.push(box);if (newSilentMs) silentUntil.set(box.id, at + newSilentMs);@@ -57,18 +70,18 @@ beforeAll(async () => {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") return send(res, 200, { ok: true, box });- if (!action && method === "PATCH") { box.name = body.name; return send(res, 200, { ok: true, box }); }+ if (!action && method === "GET") return send(res, 200, { ok: true, box: shown(box) });+ if (!action && method === "PATCH") {+ const renamed = () => { box.name = body.name; send(res, 200, { ok: true, box: shown(box) }); };+ if (renameDelayMs && String(body.name).includes("-set-aside-")) { setTimeout(renamed, renameDelayMs); return; }+ return renamed();+ }if (!action && method === "DELETE") {- setTimeout(() => {- if (deleteStatus >= 400) return send(res, deleteStatus, { ok: false, code: "upstream_error", message: "The delete failed." });- boxes = boxes.filter((candidate) => candidate.id !== box.id);- send(res, 202, { ok: true, operation: { id: opId(box.id), kind: "box", targetId: box.id, status: "completed" } });- }, deleteDelayMs);- return;+ boxes = boxes.filter((candidate) => candidate.id !== box.id);+ return send(res, 202, { ok: true, operation: { id: opId(box.id), kind: "box", targetId: box.id, status: "completed" } });}- if (action === "stop") { box.state = "archived"; return send(res, 200, { ok: true, box }); }- if (action === "resume") { box.state = "ready"; return send(res, 200, { ok: true, box }); }+ if (action === "stop") { box.state = "archived"; return send(res, 200, { ok: true, box: shown(box) }); }+ if (action === "resume") { if (!resumeHangs) box.state = "ready"; return send(res, 200, { ok: true, box: shown(box) }); }if (action === "commands") {if ((silentUntil.get(box.id) ?? -Infinity) > at) return send(res, 502, { ok: false, code: "upstream_unavailable", message: "Cloud computers could not be reached." });return send(res, 200, { exitCode: 0, stdout: "captured", stderr: "" });@@ -96,45 +109,71 @@ let claims: typeof import("./auto-vm-claims.ts");let power: ReturnType<typeof import("./host/cloud-computer-power.ts").createCloudComputerPower>;let recovery: import("./boat-recovery.ts").BoatRecovery;let health: import("./boat-health.ts").BoatHealth;-let told: Array<[string, string]>;+let told: Array<[string, string, Record<string, string>?]>;+let logs: string[];let hooks: string[];let autoOn: boolean;let inUseByOther: Set<string>;+let personViewing: Set<string>;+/** Another computer of this installation keeps answering commands while the test's clock moves. */+let witness: boolean;+/** Each probe of the turn's wait ends this long after it was sent, on the test's clock. */+let probeTakesMs: number;+let stalledLoop: boolean;+/** The 7-day sweep may send its one DELETE in this test; nothing else ever may. */+let sweepDeletes: boolean;let dir: string;+let replacementsFile: string;+/** How long a restart waits for the provider to report the computer ready again, in real milliseconds. */+let wakeBudgetMs: number;-beforeEach(async () => {- boxes = []; requests = []; silentUntil = new Map(); newSilentMs = 0; deleteStatus = 202; deleteDelayMs = 0;- at += 7 * 24 * 60 * 60_000;- told = []; hooks = []; autoOn = true; inUseByOther = new Set();- dir = mkdtempSync(join(tmpdir(), "omb-wake-"));- vi.resetModules();- boat = await import("./boat.ts");- words = await import("../shared/cloud-computer-recovery.ts");- tools = await import("./cloud-computer-tools.ts");- claims = await import("./auto-vm-claims.ts");+async function build() {const { createBoatHealth } = await import("./boat-health.ts");const { createBoatReadiness } = await import("./boat-ready.ts");const { createBoatRecovery } = await import("./boat-recovery.ts");const { createCloudComputerCounters } = await import("./cloud-computer-counters.ts");const { createCloudComputerPower } = await import("./host/cloud-computer-power.ts");health = createBoatHealth(now);- // Each wait moves the test's clock instead of passing real time. The waits keep their own health record, so the- // background recovery (restart, then replace, on three silent probes) stays out of these scenarios: they are about- // the turn's own wait.- const readiness = createBoatReadiness({ health: createBoatHealth(now), counters: createCloudComputerCounters(now), now, sleep: async (ms) => { at += ms; } });+ const readiness = createBoatReadiness({+ health, counters: createCloudComputerCounters(now), now,+ probe: async (config, boxId) => {+ const out = await boat.runCommand(config, boxId, "true", { timeoutMs: 8_000, probe: true });+ at += probeTakesMs;+ return out.ok ? true : out.unanswered ? false : null;+ },+ sleep: async (ms) => { at += ms; if (witness) health.answered("bx_witness"); },+ });recovery = createBoatRecovery({- cfg: () => cfg, tell: (owner, line) => told.push([owner, line]), log: () => {}, file: join(dir, "boat-replacements.json"), now, health,- pollMs: 5, recheckMs: 20, readiness, autoReplace: () => autoOn, usedByOther: (owner) => inUseByOther.has(owner),+ cfg: () => cfg, tell: (owner, line, vars) => told.push(vars ? [owner, line, vars] : [owner, line]), log: (line) => logs.push(line), file: replacementsFile, now, health,+ pollMs: 5, recheckMs: 60_000, setAsideRecheckMs: 60_000, wakeBudgetMs, readiness, autoReplace: () => autoOn,+ usedByOther: (owner) => inUseByOther.has(owner), personActive: (owner) => personViewing.has(owner), stalled: () => stalledLoop, turnWaiting: (boxId) => power.waiting(boxId),});power = createCloudComputerPower({cfg, busy: () => false, claim: () => () => {}, owners: () => [], routines: () => [], routineComputer: () => null,- broadcast: () => {}, log: () => {}, readiness, wakeTimedOut: (owner, boxId) => recovery.wakeTimedOut(owner, boxId),+ broadcast: () => {}, log: () => {}, readiness, health, wakeTimedOut: (owner, boxId, ctx) => recovery.wakeTimedOut(owner, boxId, ctx),});+}++beforeEach(async () => {+ boxes = []; requests = []; silentUntil = new Map(); newSilentMs = 0; hydrated = undefined; noRoom = false; resumeHangs = false; renameDelayMs = 0;+ at += 30 * 24 * 60 * 60_000;+ told = []; logs = []; hooks = []; autoOn = true; inUseByOther = new Set(); personViewing = new Set();+ witness = false; probeTakesMs = 0; stalledLoop = false; sweepDeletes = false; wakeBudgetMs = 10_000;+ dir = mkdtempSync(join(tmpdir(), "omb-wake-"));+ replacementsFile = join(dir, "boat-replacements.json");+ vi.resetModules();+ boat = await import("./boat.ts");+ words = await import("../shared/cloud-computer-recovery.ts");+ tools = await import("./cloud-computer-tools.ts");+ claims = await import("./auto-vm-claims.ts");+ await build();});afterEach(() => {recovery.close();power.close();rmSync(dir, { recursive: true, force: true });+ // The automatic path never deletes a computer: only the sweep of a set-aside one whose seven days are up may.+ if (!sweepDeletes) expect(requests.filter((request) => request.method === "DELETE")).toEqual([]);});let bots = 0;@@ -148,135 +187,316 @@ async function asleep(silentMs: number) {}const turn = (threadId = "thread-1") => ({ threadId, generation: "g1" });const ready = (bot: BotRecord) => power.ready(bot, turn(), {- budgetMs: 30_000, onWaking: () => hooks.push("waking"), onReplacing: () => hooks.push("replacing"), onRestoring: () => hooks.push("restoring"),+ budgetMs: 30_000, onWaking: () => hooks.push("waking"), onRestarting: () => hooks.push("restarting"), onReplacing: () => hooks.push("replacing"), onRestoring: () => hooks.push("restoring"),});-const deletes = () => requests.filter((request) => request.method === "DELETE");+const failure = (bot: BotRecord) => ready(bot).then(() => null, (error: unknown) => error as Error);const creates = () => requests.filter((request) => request.method === "POST" && request.path === "/boxes");+const stops = (boxId: string) => requests.filter((request) => request.method === "POST" && request.path === `/boxes/${boxId}/stop`);+const renames = (boxId: string) => requests.filter((request) => request.method === "PATCH" && request.path === `/boxes/${boxId}`);+const SET_ASIDE_NAME = /^ogb-[a-f0-9]{12}-[a-z0-9]{1,8}-[a-f0-9]{6}-set-aside-\d{4}-\d{2}-\d{2}$/;/** One computer call as the bot makes it, through the same route a turn's calls take: by default an exec of `echo hi`. */const call = (boxId: () => string, extra: Partial<Parameters<typeof tools.cloudComputerRpc>[1]> = {}, name = "exec") =>tools.cloudComputerRpc({ method: "tools/call", params: { name, arguments: name === "exec" ? { command: "echo hi" } : {} } }, {cfg, signal: new AbortController().signal, boxId, gate: async () => ({ held: false }), assertActive: () => {}, recovery, ...extra,});const ranEcho = () => requests.filter((request) => request.command?.includes("echo hi")).length;+/** Left as it is: a passing failure that says MausBot keeps trying, never "do not retry". */+function keptAsItIs(error: Error | null) {+ expect(error).toBeInstanceOf(Error);+ expect(error!.message).toMatch(/MausBot keeps trying in the background; trying again later is fine/);+ expect(error!.message).not.toMatch(/Do not retry|replac/i);+ expect(claims.transientClaimFailure(error)).toBe(true);+}describe("a woken cloud computer that is slow to answer", () => {- it("is waited for inside the wake's patience: the bot's command runs once, nothing is replaced, and no error is shown", async () => {+ it("is waited for inside the wake's patience: the bot's command runs once, nothing is restarted or set aside, and no error is shown", async () => {const { bot, box } = await asleep(150_000);const machine = await ready(bot);expect(machine?.id).toBe(box.id);expect(hooks).toEqual(["waking"]);const result = await call(() => box.id);- expect(result).toMatchObject({ content: [{ type: "text" }] });expect((result as { isError?: boolean }).isError).toBeFalsy();expect(ranEcho()).toBe(1);- expect(deletes()).toHaveLength(0);+ expect(stops(box.id)).toHaveLength(0);expect(told).toEqual([]);});++ it("silent for twenty minutes after its resume, then answering by itself (the incident): restarted once, never set aside, and the bot is never told to give up", async () => {+ witness = true;+ const { bot, box } = await asleep(20 * 60_000);+ const first = await failure(bot);+ keptAsItIs(first);+ expect(first!.message).toMatch(/even after a restart/);+ expect(hooks.slice(0, 2)).toEqual(["waking", "restarting"]);+ expect(hooks).not.toContain("replacing");+ // The reason it was kept: the provider does not say whether the disk is back, and it was resumed minutes ago.+ expect(logs.some((line) => /resumed less than 30 minutes ago/.test(line))).toBe(true);+ // The turn's wait owned it: the background recovery, on the same health record, did not stop it a second time.+ expect(stops(box.id)).toHaveLength(1);+ expect(renames(box.id)).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ expect(told).toEqual([]);++ // The turn's computer calls claim again and again, as a bot repeating its screenshot does, each a few minutes of+ // waiting: the claim is never given up for the turn, and once the computer answers by itself the turn goes on on it.+ const table: import("./auto-vm-claims.ts").AutoVmClaimTable = new Map();+ let machine: Awaited<ReturnType<typeof ready>> = null;+ const slot: import("./auto-vm-claims.ts").AutoVmClaimSlot = {+ owner: { threadId: "thread-1", generation: "g1" }, lazy: true, startsComputer: true,+ claim: async () => { machine = await ready(bot); },+ };+ table.set("thread-1", slot);+ for (let tries = 0; tries < 8 && !slot.claimed; tries++) {+ claims.startAutoVmClaim(table, "thread-1", "g1");+ await slot.begin;+ expect(slot.failed).toBeFalsy();+ if (!slot.claimed) expect(slot.retryReason).toMatch(/MausBot keeps trying in the background/);+ }+ expect(slot.claimed).toBe(true);+ expect(slot.attempts).toBeGreaterThan(3);+ expect(machine!.id).toBe(box.id);+ expect(boxes.map((candidate) => candidate.id)).toEqual([box.id]);+ expect(box.name).toBe(await boat.boatNameFor(bot.id));+ const result = await call(() => box.id);+ expect((result as { isError?: boolean }).isError).toBeFalsy();+ expect(ranEcho()).toBe(1);+ });});describe("a woken cloud computer that never answers", () => {- it("is replaced once, the turn goes on on the new one, and the bot and the person each hear it once", async () => {- const { bot, box } = await asleep(Infinity);+ /** A bot whose computer was made the normal way (so its create is on record), then went to sleep and stays silent. */+ async function madeThenSilent() {+ const botId = `bot-made-${bots++}`;+ const made = await boat.provisionBoat(cfg, botId, "Scout");+ const box = boxes.find((candidate) => candidate.id === made.boxId)!;+ box.state = "archived";+ silentUntil.set(box.id, Infinity);+ boat.forgetBoatId(box.id);+ requests = [];+ return { bot: { id: botId, name: "Scout" } as BotRecord, box, originalName: box.name };+ }++ it("with another computer answering and the disk said to be back, is restarted, then set aside with its files (stopped and renamed, never deleted) for a new one", async () => {+ witness = true; hydrated = true;+ const { bot, box, originalName } = await madeThenSilent();const machine = await ready(bot);expect(machine?.id).not.toBe(box.id);- expect(hooks).toEqual(["waking", "replacing"]);- expect(deletes().map((request) => request.path)).toEqual([`/boxes/${box.id}`]);+ expect(hooks).toEqual(["waking", "restarting", "replacing"]);+ // The old one: stopped for the restart, stopped again to be set aside, renamed, and still there.+ expect(stops(box.id)).toHaveLength(2);+ expect(renames(box.id).map((request) => request.name)).toEqual([expect.stringMatching(SET_ASIDE_NAME)]);+ expect(boxes.find((candidate) => candidate.id === box.id)).toMatchObject({ state: "archived", name: expect.stringMatching(SET_ASIDE_NAME) });+ expect(box.name.startsWith(`${originalName}-set-aside-`)).toBe(true);+ // A real new computer: its create was not answered by the old one's create receipt.expect(creates()).toHaveLength(1);- expect(told).toEqual([[bot.id, "replaced"]]);- expect(recovery.replacedRecently(bot.id)).toBe(true);+ expect(boxes.find((candidate) => candidate.id === machine!.id)?.name).toBe(originalName);+ const until = new Date(at + 7 * 24 * 60 * 60_000).toISOString().slice(0, 10);+ expect(told).toEqual([[bot.id, "setAside", { date: until }]]);+ // Settings lists it as this installation's, owned by no bot, so the person finds it.+ const inventory = await boat.listManagedBoats(cfg, [{ botId: bot.id, name: "Scout", inUse: false }]);+ expect(inventory.available).toBe(true);+ expect(inventory.instances.find((instance) => instance.boxId === box.id)).toMatchObject({ orphaned: true, ownerBotId: null });+ expect(inventory.instances.find((instance) => instance.boxId === machine!.id)).toMatchObject({ ownerBotId: bot.id });++ // The bot hears it once, with the date and that sign-ins are not on the new one.const first = await call(() => machine!.id as string);expect((first as { isError?: boolean }).isError).toBeFalsy();- expect((first as { content: unknown[] }).content[0]).toEqual({ type: "text", text: words.CLOUD_COMPUTER_REPLACED });- expect(words.CLOUD_COMPUTER_REPLACED).toMatch(/install again/);+ const notice = (first as { content: Array<{ text?: string }> }).content[0]!.text!;+ expect(notice).toBe(words.cloudComputerSetAsideNotice(until));+ expect(notice).toMatch(/kept, stopped and with its files, until \d{4}-\d{2}-\d{2}/);+ expect(notice).toMatch(/sign-ins/);expect(ranEcho()).toBe(1);const second = await call(() => machine!.id as string);expect((second as { content: unknown[] }).content).toHaveLength(1);expect(told).toHaveLength(1);});- it("is kept when a last probe gets through: a computer that is only slow is never replaced", async () => {- const { bot, box } = await asleep(0);- box.state = "ready";- await boat.findBoat(cfg, bot.id);- await expect(recovery.wakeTimedOut(bot.id, box.id)).resolves.toEqual({ kind: "answers" });- expect(deletes()).toHaveLength(0);- expect(told).toEqual([]);+ it("is deleted only by the sweep once its seven days are up, and only while it still has the name it was set aside with", async () => {+ witness = true; hydrated = true;+ const { bot, box } = await madeThenSilent();+ const other = await madeThenSilent();+ await ready(bot);+ at += 2 * 60 * 60_000;+ await ready(other.bot);+ await recovery.sweep();+ expect(requests.filter((request) => request.method === "DELETE")).toEqual([]);++ // Someone took the second one back by renaming it: it is never deleted.+ other.box.name = "kept-by-the-person";+ at += 8 * 24 * 60 * 60_000;+ sweepDeletes = true;+ await recovery.sweep();+ expect(requests.filter((request) => request.method === "DELETE").map((request) => request.path)).toEqual([`/boxes/${box.id}`]);+ expect(boxes.some((candidate) => candidate.id === other.box.id)).toBe(true);+ await recovery.sweep();+ expect(requests.filter((request) => request.method === "DELETE")).toHaveLength(1);});- it("is replaced at most once an hour and three times a day per bot", async () => {- newSilentMs = 1e12;- const { bot } = await asleep(Infinity);- await expect(ready(bot)).rejects.toThrow(/new one did not answer in time either/);- expect(deletes()).toHaveLength(1);- expect(told).toEqual([[bot.id, "replaced"]]);+ it("is kept, with its name, when the plan has no room for a new computer beside it, and the person hears that once", async () => {+ witness = true; hydrated = true;+ const { bot, box, originalName } = await madeThenSilent();+ noRoom = true;+ const error = await failure(bot);+ expect(error!.message).toMatch(/plan has no room for a new computer beside it, so MausBot kept it, stopped and with its files/);+ expect(claims.transientClaimFailure(error)).toBe(true);+ expect(box.name).toBe(originalName);+ expect(renames(box.id).map((request) => request.name)).toEqual([expect.stringMatching(SET_ASIDE_NAME), originalName]);+ expect(boxes.map((candidate) => candidate.id)).toEqual([box.id]);+ expect(told).toEqual([[bot.id, "noRoom"]]);+ // It is still the bot's: the next start finds it again, and no other set-aside is tried for hours.+ expect((await boat.findBoat(cfg, bot.id))?.id).toBe(box.id);+ at += 61 * 60_000;+ box.state = "archived";+ keptAsItIs(await failure(bot));+ expect(renames(box.id)).toHaveLength(2);+ });- // Within the hour: left as it is, and the turn says why.- const current = () => boxes.find((box) => box.name)!;- current().state = "archived";- await expect(ready(bot)).rejects.toThrow(/at most once an hour and three times a day/);- expect(deletes()).toHaveLength(1);- expect(told.filter(([, line]) => line === "capped")).toHaveLength(1);+ it("is not set aside on a silence that began before it last slept: a wake starts its silence over", async () => {+ hydrated = true;+ const { bot, box } = await asleep(Infinity);+ health.unanswered(box.id);+ at += 40 * 60_000;+ keptAsItIs(await failure(bot));+ expect(renames(box.id)).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ expect(logs.some((line) => /no other computer answered in the last two minutes/.test(line))).toBe(true);+ });- for (let replaced = 2; replaced <= 3; replaced++) {- at += 61 * 60_000;- current().state = "archived";- await expect(ready(bot)).rejects.toThrow(/new one did not answer/);- expect(deletes()).toHaveLength(replaced);- }- at += 61 * 60_000;- current().state = "archived";- await expect(ready(bot)).rejects.toThrow(/three times a day/);- expect(deletes()).toHaveLength(3);+ it("with no other computer answering, is restarted and then left as it is: a lone computer is not set aside within half an hour", async () => {+ hydrated = true;+ const { bot, box } = await asleep(Infinity);+ keptAsItIs(await failure(bot));+ expect(stops(box.id)).toHaveLength(1);+ expect(renames(box.id)).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ expect(logs.some((line) => /no other computer answered in the last two minutes/.test(line))).toBe(true);});- it("fails the turn with a clear reason when the replacement itself fails, and makes no new computer", async () => {- deleteStatus = 500;- const { bot } = await asleep(Infinity);- const failed = await ready(bot).then(() => null, (error: unknown) => error);- expect(failed).toBeInstanceOf(Error);- expect((failed as Error).message).toMatch(/did not answer after waking, and replacing it failed.*trying again later is fine/);- expect(claims.transientClaimFailure(failed)).toBe(false);+ it("is not set aside while the provider says its disk is still being restored", async () => {+ witness = true; hydrated = false;+ const { bot, box } = await asleep(Infinity);+ keptAsItIs(await failure(bot));+ expect(hooks).toContain("restoring");+ expect(renames(box.id)).toHaveLength(0);expect(creates()).toHaveLength(0);});- it("is not replaced while another bot's running turn uses it", async () => {- const { bot } = await asleep(Infinity);+ it("is not set aside when this process's event loop stalled while it was probed", async () => {+ witness = true; hydrated = true; stalledLoop = true;+ const { bot, box } = await asleep(Infinity);+ keptAsItIs(await failure(bot));+ expect(renames(box.id)).toHaveLength(0);+ expect(logs.some((line) => /stalled while the computer was probed/.test(line))).toBe(true);+ });++ it("does not count probes that ran far past their own timeout: they were held up here, not by the computer", async () => {+ witness = true; hydrated = true; probeTakesMs = 60_000;+ const { bot, box } = await asleep(Infinity);+ await failure(bot);+ expect(logs.some((line) => /too few unanswered probes since its restart/.test(line))).toBe(true);+ expect(renames(box.id)).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ });++ it("is not set aside when the restart never got the computer ready again: that is not a restart that failed", async () => {+ witness = true; hydrated = true;+ recovery.close();+ power.close();+ wakeBudgetMs = 500;+ await build();+ const { bot, box } = await asleep(Infinity);+ box.state = "ready";+ await boat.findBoat(cfg, bot.id);+ for (let probe = 0; probe < 8; probe++) { health.unanswered(box.id); at += 30_000; }+ resumeHangs = true;+ const outcome = await recovery.wakeTimedOut(bot.id, box.id, { turn: turn() });+ expect(outcome.kind).toBe("kept");+ expect((outcome as { why: string }).why).not.toMatch(/after a restart/);+ expect(stops(box.id)).toHaveLength(1);+ expect(renames(box.id)).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ });++ it("is neither restarted nor set aside while a person views its desktop", async () => {+ witness = true; hydrated = true;+ const { bot, box } = await asleep(Infinity);+ personViewing.add(bot.id);+ const error = await failure(bot);+ keptAsItIs(error);+ expect(error!.message).toMatch(/someone else is using it/);+ expect(stops(box.id)).toHaveLength(0);+ expect(renames(box.id)).toHaveLength(0);+ });++ it("is not set aside while another bot's running turn uses it", async () => {+ witness = true; hydrated = true;+ const { bot, box } = await asleep(Infinity);inUseByOther.add(bot.id);- await expect(ready(bot)).rejects.toThrow(/could not be replaced by itself right now/);- expect(deletes()).toHaveLength(0);+ keptAsItIs(await failure(bot));+ expect(stops(box.id)).toHaveLength(0);expect(creates()).toHaveLength(0);- expect(told).toEqual([[bot.id, "needsPerson"]]);});- it("is not replaced while the installation's other computers are silent too: that is the provider's outage", async () => {+ it("is set aside at most once an hour and three times a day per bot", async () => {+ witness = true; hydrated = true; newSilentMs = 1e12;const { bot } = await asleep(Infinity);- health.unanswered("bx_someoneelse");- await expect(ready(bot)).rejects.toThrow(/service itself can't be reached/);- expect(deletes()).toHaveLength(0);+ const first = await failure(bot);+ expect(first!.message).toMatch(/the new one did not answer in time either/);+ expect(creates()).toHaveLength(1);+ const current = () => boxes.find((box) => !SET_ASIDE_NAME.test(box.name))!;+ current().state = "archived";+ at += 2 * 60_000;+ const capped = await failure(bot);+ expect(capped!.message).toMatch(/at most once an hour and three times a day/);+ expect(creates()).toHaveLength(1);+ for (let made = 2; made <= 3; made++) {+ at += 61 * 60_000;+ current().state = "archived";+ await failure(bot);+ expect(creates()).toHaveLength(made);+ }+ at += 61 * 60_000;+ current().state = "archived";+ expect((await failure(bot))!.message).toMatch(/three times a day/);+ expect(creates()).toHaveLength(3);+ }, 90_000);++ it("is not set aside when the record of earlier replacements cannot be read: the limits fail closed", async () => {+ recovery.close();+ power.close();+ writeFileSync(replacementsFile, "{not json");+ await build();+ witness = true; hydrated = true;+ const { bot, box } = await asleep(Infinity);+ keptAsItIs(await failure(bot));+ expect(renames(box.id)).toHaveLength(0);+ expect(creates()).toHaveLength(0);});- it("with automatic replacement switched off, keeps today's behaviour: nothing is replaced and the claim may be tried again", async () => {- autoOn = false;- const { bot } = await asleep(Infinity);- const failed = await ready(bot).then(() => null, (error: unknown) => error);- expect((failed as Error).message).toBe("the cloud computer is awake but is not answering yet");- expect(claims.transientClaimFailure(failed)).toBe(true);- expect(deletes()).toHaveLength(0);+ it("with automatic replacement switched off, is restarted, never set aside, and nothing says it is being replaced", async () => {+ autoOn = false; witness = true; hydrated = true;+ const { bot, box } = await asleep(Infinity);+ keptAsItIs(await failure(bot));+ expect(hooks).not.toContain("replacing");+ expect(stops(box.id)).toHaveLength(1);+ expect(renames(box.id)).toHaveLength(0);expect(creates()).toHaveLength(0);expect(told).toEqual([]);});});-describe("a computer call made while its computer is being replaced", () => {- /** A computer the recovery is replacing, slowly, while the turn still names it. */- async function replacing() {+describe("a computer call made while its computer is being set aside", () => {+ /** A computer the recovery is setting aside, slowly, while the turn still names it. */+ async function settingAside() {+ witness = true; hydrated = true;const { bot, box } = await asleep(Infinity);box.state = "ready";await boat.findBoat(cfg, bot.id);- deleteDelayMs = 300;- const done = recovery.wakeTimedOut(bot.id, box.id);- await vi.waitFor(() => expect(recovery.refusal(box.id, "before")).not.toBeNull(), { timeout: 10_000 });+ for (let probe = 0; probe < 8; probe++) { health.unanswered(box.id); at += 30_000; }+ renameDelayMs = 300;+ const done = recovery.wakeTimedOut(bot.id, box.id, { turn: turn() });+ await vi.waitFor(() => expect(recovery.status(bot.id)?.state).toBe("replacing"), { timeout: 10_000 });let current = box.id;let reclaims = 0;const reclaim = async (replacedBoxId: string) => {@@ -289,52 +509,53 @@ describe("a computer call made while its computer is being replaced", () => {return { box, done, reclaim, current: () => current, reclaims: () => reclaims };}- it("waits for the replacement instead of being refused again and again, and a look at the screen then runs on the new computer", async () => {- const r = await replacing();+ it("waits for it instead of being refused again and again, and a look at the screen then runs on the new computer", async () => {+ const r = await settingAside();let gates = 0;const result = await call(r.current, { reclaim: r.reclaim, gate: async () => { gates++; return { held: false }; } }, "get_screen_size");- await r.done;+ expect(await r.done).toEqual({ kind: "replaced" });expect(r.reclaims()).toBe(1);expect(r.current()).not.toBe(r.box.id);expect(gates).toBe(2);expect((result as { isError?: boolean }).isError).toBeFalsy();- expect((result as { content: unknown[] }).content[0]).toEqual({ type: "text", text: words.CLOUD_COMPUTER_REPLACED });+ expect((result as { content: Array<{ text?: string }> }).content[0]!.text).toMatch(/set it aside and gave this bot a new one/);expect(requests.some((request) => request.command?.includes("getdisplaygeometry") && request.path.includes(r.current()))).toBe(true);});it("hands back a call that would change something, unperformed, once the new computer answers: the bot looks first", async () => {- const r = await replacing();+ const r = await settingAside();const result = await call(r.current, { reclaim: r.reclaim });await r.done;expect(r.reclaims()).toBe(1);- expect(result).toEqual({ isError: true, content: [- { type: "text", text: words.CLOUD_COMPUTER_REPLACED }, { type: "text", text: words.CLOUD_COMPUTER_ANSWERS_AGAIN },- ] });+ const texts = (result as { content: Array<{ text?: string }> }).content.map((part) => part.text);+ expect((result as { isError?: boolean }).isError).toBe(true);+ expect(texts[1]).toBe(words.CLOUD_COMPUTER_ANSWERS_AGAIN);expect(ranEcho()).toBe(0);});- it("is refused after the wait when a person took the computer meanwhile", async () => {- const r = await replacing();- let gates = 0;- const result = await call(r.current, { reclaim: r.reclaim, gate: async () => (++gates === 1 ? { held: false } : { held: true, reason: "person" as const }) }, "get_screen_size");+ it("says the new computer is still starting, and that the call was not performed, when it is not up in time", async () => {+ const r = await settingAside();await r.done;- expect((result as { isError?: boolean }).isError).toBe(true);- expect(requests.some((request) => request.command?.includes("getdisplaygeometry"))).toBe(false);+ const result = await call(() => r.box.id, { reclaim: async () => null });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: words.CLOUD_COMPUTER_REPLACEMENT_STARTING }] });+ expect(ranEcho()).toBe(0);});+});- it("says the new computer is still starting, and that the call was not performed, when it is not up in time", async () => {+describe("what a call that got no answer is told", () => {+ it("says it got no answer and most likely did not run, never that it was not performed", async () => {const { bot, box } = await asleep(Infinity);box.state = "ready";await boat.findBoat(cfg, bot.id);- await recovery.wakeTimedOut(bot.id, box.id);- const result = await call(() => box.id, { reclaim: async () => null });- expect(result).toEqual({ isError: true, content: [{ type: "text", text: words.CLOUD_COMPUTER_REPLACEMENT_STARTING }] });- expect(ranEcho()).toBe(0);+ for (let probe = 0; probe < 3; probe++) { health.unanswered(box.id); at += 30_000; }+ expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NOT_RESPONDING_UNANSWERED);+ expect(words.CLOUD_COMPUTER_NOT_RESPONDING_UNANSWERED).toMatch(/got no answer and most likely did not run/);+ expect(words.CLOUD_COMPUTER_NOT_RESPONDING).not.toMatch(/replac/i);});});-describe("moving a turn's claim onto the replacement", () => {- it("claims again once, however many calls see the replacement, and hands back the new computer", async () => {+describe("moving a turn's claim onto the new computer", () => {+ it("claims again once, however many calls see the set-aside, and hands back the new computer", async () => {const table: import("./auto-vm-claims.ts").AutoVmClaimTable = new Map();let next = 1;const slot: import("./auto-vm-claims.ts").AutoVmClaimSlot = {diff --git a/server/config.ts b/server/config.tsindex fcbed51c48..3e97a55079 100644--- a/server/config.ts+++ b/server/config.ts@@ -245,7 +245,7 @@ const featureConfigSchema = z.object({/** Room jobs to several members run side by side, each in a thread of its own. On unless false. */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(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional() }); // cloudComputerAutoReplace: delete and replace a dead or silent cloud computer by itself, on unless false (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 true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional() }); // cloudComputerAutoReplace: set a dead or silent cloud computer aside (kept seven days with its files) and give its bot a new one by itself, on unless false (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 true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)const onboardingConfigSchema = z.object({completedAt: z.string().trim().max(40).optional(),version: z.number().int().min(0).max(1000).optional(),diff --git a/server/event-loop-stalls.test.ts b/server/event-loop-stalls.test.tsnew file mode 100644index 0000000000..ab257886cc--- /dev/null+++ b/server/event-loop-stalls.test.ts@@ -0,0 +1,20 @@+import { afterEach, describe, expect, it } from "vitest";++import { createEventLoopStalls, type EventLoopStalls } from "./event-loop-stalls.ts";++let watch: EventLoopStalls | null = null;+afterEach(() => { watch?.close(); watch = null; });+const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++describe("this process's event loop stalls", () => {+ it("are seen in the window they fall in, and not in one that ended before them", async () => {+ watch = createEventLoopStalls(Date.now, { sampleMs: 50, stallMs: 1_000 });+ await pause(200);+ const before = Date.now();+ // Held for well over the threshold: a margin of more than a second.+ for (const end = Date.now() + 2_500; Date.now() < end;) { /* the stall */ }+ await pause(200);+ expect(watch.stalledBetween(before, Date.now())).toBe(true);+ expect(watch.stalledBetween(before - 10_000, before - 5_000)).toBe(false);+ });+});diff --git a/server/event-loop-stalls.ts b/server/event-loop-stalls.tsnew file mode 100644index 0000000000..a30323c49a--- /dev/null+++ b/server/event-loop-stalls.ts@@ -0,0 +1,42 @@+// When this process's event loop was held up. A probe timed out by a stalled loop says nothing about the computer it was+// sent to, so no cloud computer is set aside on probes taken while the loop stalled (server/boat-recovery.ts).+import { monitorEventLoopDelay, performance } from "node:perf_hooks";++/** A delay this long, anywhere in a sample, counts as a stall. */+export const STALL_MS = 2_000;+const SAMPLE_MS = 5_000;+const KEEP_MS = 2 * 60 * 60_000;++export interface EventLoopStalls {+ /** The loop stalled at some point between `from` and `to` (by `now`). */+ stalledBetween(from: number, to: number): boolean;+ close(): void;+}++export function createEventLoopStalls(now: () => number = Date.now, { sampleMs = SAMPLE_MS, stallMs = STALL_MS } = {}): EventLoopStalls {+ const histogram = monitorEventLoopDelay({ resolution: 20 });+ histogram.enable();+ /** The end of each sample whose longest delay was a stall, and that delay. */+ const stalls: Array<{ at: number; delayMs: number }> = [];+ let last = performance.now();+ const timer = setInterval(() => {+ // The histogram's longest delay, or this timer's own lateness: the histogram was seen to miss a stall under the test+ // runner, and a late timer cannot.+ const tick = performance.now(), delayMs = Math.max(histogram.max / 1e6, tick - last - sampleMs);+ last = tick;+ histogram.reset();+ const at = now();+ if (delayMs >= stallMs) stalls.push({ at, delayMs });+ while (stalls.length && at - stalls[0]!.at > KEEP_MS) stalls.shift();+ }, sampleMs);+ timer.unref?.();+ return {+ // A sample ending after `from` may hold a stall from up to one sample earlier; that is counted, to be safe.+ stalledBetween: (from, to) => stalls.some((stall) => stall.at >= from && stall.at - stall.delayMs - sampleMs <= to),+ close: () => { clearInterval(timer); histogram.disable(); },+ };+}++let shared: EventLoopStalls | null = null;+/** This process's own, started on first use. */+export const eventLoopStalls = (): EventLoopStalls => (shared ??= createEventLoopStalls());diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.tsindex 5aa3b08b61..bc61d83e38 100644--- a/server/host/cloud-computer-power.ts+++ b/server/host/cloud-computer-power.ts@@ -4,8 +4,9 @@import * as boat from "../boat.ts";import { boatCreateRecoverySnapshot } from "../boat-create-idempotency.ts";import { BOAT_DELETING, BOAT_DELETION_FINISHED, hasPendingBoatDeletionForBot } from "../boat-delete-journal.ts";+import { boatHealth, type BoatHealth } from "../boat-health.ts";import { boatReadiness, type BoatAnswer, type BoatReadiness } from "../boat-ready.ts";-import type { WakeTimeoutOutcome } from "../boat-recovery.ts";+import type { WakeTimeoutContext, WakeTimeoutOutcome } from "../boat-recovery.ts";import { withinBudget } from "../auto-vm-claims.ts";import { backgroundCommandRunning } from "../cloud-computer-background.ts";import { ComputerIdleTimer } from "../computer-idle.ts";@@ -46,9 +47,11 @@ export interface CloudComputerPowerDeps {broadcast(payload: Record<string, unknown>): void;log(line: string): void;readiness?: Pick<BoatReadiness, "awaitAnswer">;- /** A computer woken or created for a turn stayed silent past the wake's patience: replace it, within every guard- * (server/boat-recovery.ts). Absent, such a computer is only reported, as with automatic replacement switched off. */- wakeTimedOut?(owner: string, boxId: string): Promise<WakeTimeoutOutcome>;+ /** Where a wake or a create is noted, so a computer is never set aside within its first half hour unseen. */+ health?: Pick<BoatHealth, "woke">;+ /** A computer woken or created for a turn stayed silent past the wake's patience: restart it, then set it aside+ * within every guard (server/boat-recovery.ts). Absent, such a computer is only reported. */+ wakeTimedOut?(owner: string, boxId: string, ctx: WakeTimeoutContext): Promise<WakeTimeoutOutcome>;}/** How a turn's start went, for the line the bot hears meanwhile. */@@ -56,7 +59,9 @@ export interface CloudComputerReadyHooks {onRestoring?(): void;/** Woken and silent: the wait goes on. */onWaking?(): void;- /** Silent past the wake's patience, and being replaced with a new computer. */+ /** Silent past the wake's patience, and being restarted; its files are kept. */+ onRestarting?(): void;+ /** Still silent after that, every guard passed, and being set aside for a new computer. */onReplacing?(): void;}@@ -67,8 +72,11 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {/** A start can outlive the turn that asked for it; stopping a computer mid-create would make provisionBoat delete it. */const starting = new Map<string, number>();const readiness = deps.readiness ?? boatReadiness;+ const health = deps.health ?? boatHealth;/** Computers this process created or woke and has not yet heard answer. */const unheard = new Set<string>();+ /** Computers a turn's start is waiting on (ready): the background recovery leaves them to it. */+ const waits = new Map<string, number>();let listingRetry: ReturnType<typeof setTimeout> | null = null;let closed = false;@@ -159,14 +167,14 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {await provisionOnceRemoved(bot, deadline);b = await boat.findBoat(cfg, bot.id);lifecycle = lifecycleOf();- if (typeof b?.id === "string") unheard.add(b.id);+ if (typeof b?.id === "string") { unheard.add(b.id); health.woke(b.id, true); }}// An archived Boat answers every action with an error until it resumes: wake it once here.if (lifecycle === "wake") {broadcast({ kind: "computer", botId: bot.id, state: "waking", place: "cloud" });b = (await boat.readyBoat(cfg, bot.id, Math.max(1_000, deadline - Date.now()))) ?? b;lifecycle = lifecycleOf();- if (typeof b?.id === "string") unheard.add(b.id);+ if (typeof b?.id === "string") { unheard.add(b.id); health.woke(b.id, true); }}return b && lifecycle === "attach" ? b : null;}@@ -222,30 +230,41 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {if (!answer.ok) throw notAnswering(answer);}+ /** A passing failure: the turn's next computer call claims again, however often (`keepsTrying`), since MausBot keeps+ * bringing the computer back meanwhile. */+ const passing = (why: string) => Object.assign(new Error(why), { status: 503, transient: true, keepsTrying: true });+/** A bot's own computer for a turn: started (woken, or created) within `budgetMs`, then waited on until it answers. One- * woken or created here that stays silent past the wake's patience is replaced, once, and the turn goes on on the new- * one; the old one's files are gone, which the recovery tells the bot and the person. Null when `existingOnly` and the- * bot has none. */+ * woken or created here that stays silent past the wake's patience is restarted (its files kept) and waited for again;+ * only if it is still silent and every guard holds is it set aside, with its files, for a new one, and the turn goes on+ * on that. Otherwise the turn's claim fails as a passing failure, and the computer is left as it is. Null when+ * `existingOnly` and the bot has none. */async function ready(bot: BotRecord, turn: TurnOwner, opts: { existingOnly?: boolean; budgetMs: number } & CloudComputerReadyHooks) {for (let replaced = false; ; replaced = true) {// The replacement stands in for the computer the bot already had, so it is made even where a first one would not be.const machine = await withinBudget(start(bot, turn, { existingOnly: !replaced && opts.existingOnly, budgetMs: opts.budgetMs }), opts.budgetMs, CLOUD_COMPUTER_DID_NOT_START);if (!machine) {- if (replaced) throw new Error("the cloud computer did not answer after waking, so it was replaced, but its replacement could not be found. Trying again later is fine");+ if (replaced) throw passing("the cloud computer was set aside, with its files, for a new one, but the new one could not be found yet. Trying again later is fine");return null;}const boxId = machine.id as string;- const answer = await awaitAnswer(boxId, opts);- if (answer.ok) return machine;- // A computer this process did not wake keeps today's short wait: the recovery restarts it, then replaces it.- if (!answer.woke || !deps.wakeTimedOut) throw notAnswering(answer);- if (replaced) throw new Error("the cloud computer did not answer after waking, so it was replaced with a new one, but the new one did not answer in time either. Trying again later is fine");- opts.onReplacing?.();- const outcome = await deps.wakeTimedOut(bot.id, boxId);+ if (replaced) { unheard.add(boxId); health.woke(boxId, true); }+ waits.set(boxId, (waits.get(boxId) ?? 0) + 1);+ let outcome: WakeTimeoutOutcome;+ try {+ const answer = await awaitAnswer(boxId, opts);+ if (answer.ok) return machine;+ // A computer this process did not wake keeps today's short wait: the recovery restarts it, then may set it aside.+ if (!answer.woke || !deps.wakeTimedOut) throw notAnswering(answer);+ if (replaced) throw passing("the cloud computer was set aside, with its files, for a new one, but the new one did not answer in time either. Trying again later is fine");+ outcome = await deps.wakeTimedOut(bot.id, boxId, { turn, onRestarting: opts.onRestarting, onReplacing: opts.onReplacing });+ } finally {+ const left = (waits.get(boxId) ?? 1) - 1;+ if (left > 0) waits.set(boxId, left); else waits.delete(boxId);+ }if (outcome.kind === "answers") return machine;- if (outcome.kind === "off") throw notAnswering(answer);- if (outcome.kind === "kept") throw new Error(outcome.why);- deps.log(`cloud computer ${bot.id}: ${boxId} ${outcome.kind === "gone" ? "is gone" : "was replaced"} after it did not answer its wake; starting a new one for the turn`);+ if (outcome.kind === "kept") throw passing(outcome.why);+ deps.log(`cloud computer ${bot.id}: ${boxId} ${outcome.kind === "gone" ? "is gone" : "was set aside"} after it did not answer its wake; starting the new one for the turn`);}}@@ -253,6 +272,8 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {start,answering,ready,+ /** A turn's start is waiting on this computer to answer, or deciding what to do about it. */+ waiting: (boxId: string): boolean => waits.has(boxId),attached,released,used,diff --git a/server/host/cloud-computer-users.test.ts b/server/host/cloud-computer-users.test.tsindex 0ddcf7ecc6..4fa97cba2b 100644--- a/server/host/cloud-computer-users.test.ts+++ b/server/host/cloud-computer-users.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";import { usedByAnotherBot } from "./cloud-computer-users.ts";const deps = (holders: Record<string, string>, bots: Record<string, string>) => ({- holder: (resource: string) => (holders[resource] ? { threadId: holders[resource]! } : undefined),+ holder: (resource: string) => (holders[resource] ? { threadId: holders[resource]!, generation: "g1" } : undefined),botOfThread: (threadId: string) => bots[threadId] ?? null,});@@ -17,8 +17,11 @@ describe("a bot's cloud computer held by a running turn", () => {expect(usedByAnotherBot("bot-a", "bx_1", deps({ "computer:box:bx_1": "task-a" }, { "task-a": "bot-a" }))).toBe(false);});- it("is not counted as someone else's when the holder is a room's turn, which only the bot itself can be", () => {- expect(usedByAnotherBot("bot-a", "bx_1", deps({ "computer:box-bot:bot-a": "room-1" }, {}))).toBe(false);+ it("counts a room's turn as someone else's, since with room jobs side by side it may be any member, unless it is the turn that asks", () => {+ const room = deps({ "computer:box-bot:bot-a": "room-1" }, {});+ expect(usedByAnotherBot("bot-a", "bx_1", room)).toBe(true);+ expect(usedByAnotherBot("bot-a", "bx_1", room, { threadId: "room-1", generation: "g1" })).toBe(false);+ expect(usedByAnotherBot("bot-a", "bx_1", room, { threadId: "room-1", generation: "g0" })).toBe(true);});it("is someone else's when another bot's turn holds the computer or the machine", () => {diff --git a/server/host/cloud-computer-users.ts b/server/host/cloud-computer-users.tsindex 1c31ce953a..a90280a655 100644--- a/server/host/cloud-computer-users.ts+++ b/server/host/cloud-computer-users.ts@@ -1,21 +1,22 @@-// Whether a bot's own cloud computer is held by a running turn of some other bot, so it is never replaced by itself from-// under that turn. A turn takes a bot's computer through two resources, the bot's and the machine's, and only a turn of-// that same bot binds them; a holder whose bot cannot be told (a room's turn, say) is that bot's own turn acting in-// the room, and does not stop a replacement its own silence asked for.+// Whether a bot's own cloud computer is held by a running turn other than its bot's own, so it is never set aside by+// itself from under that turn. A turn takes a bot's computer through two resources, the bot's and the machine's. A+// holder in the bot's own thread is the bot itself; a holder whose bot cannot be told (a room's turn, with room jobs+// running side by side) may be any member, so it counts as another, unless it is the very turn that asks.export interface CloudComputerUsersDeps {/** The running turn that holds this resource, if one does. */- holder(resource: string): { threadId: string } | undefined;+ holder(resource: string): { threadId: string; generation: string } | undefined;/** The bot whose turn runs in this thread; null when the thread is not one bot's (a room's). */botOfThread(threadId: string): string | null;}export const computerResources = (owner: string, boxId: string): string[] => [`computer:box-bot:${owner}`, `computer:box:${boxId}`];-export function usedByAnotherBot(owner: string, boxId: string, deps: CloudComputerUsersDeps): boolean {+/** `asking`: the turn on whose behalf this is asked, which never counts against itself. */+export function usedByAnotherBot(owner: string, boxId: string, deps: CloudComputerUsersDeps, asking?: { threadId: string; generation: string }): boolean {return computerResources(owner, boxId).some((resource) => {const holder = deps.holder(resource);if (!holder) return false;- const bot = deps.botOfThread(holder.threadId);- return bot !== null && bot !== owner;+ if (asking && holder.threadId === asking.threadId && holder.generation === asking.generation) return false;+ return deps.botOfThread(holder.threadId) !== owner;});}diff --git a/server/index.ts b/server/index.tsindex e95b00ea6c..c9e8331b1e 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 { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES, CLOUD_COMPUTER_REPLACING, CLOUD_COMPUTER_RESTORING, CLOUD_COMPUTER_WAKING, RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts"; import { boatReadiness } from "./boat-ready.ts"; import { createRunComputerGate } from "./host/cloud-computer-run-gate.ts"; import { cloudComputerDisk } from "./cloud-computer-disk.ts"; import { runComputerMemory } from "./host/cloud-computer-run-memory.ts";+import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES, CLOUD_COMPUTER_REPLACING, CLOUD_COMPUTER_RESTARTING, CLOUD_COMPUTER_RESTORING, CLOUD_COMPUTER_WAKING, RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts"; import { boatReadiness } from "./boat-ready.ts"; import { createRunComputerGate } from "./host/cloud-computer-run-gate.ts"; import { cloudComputerDisk } from "./cloud-computer-disk.ts"; import { runComputerMemory } from "./host/cloud-computer-run-memory.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";import { DATA_INTERNAL_MCP_PATH, dataRpc } from "./data/rpc.ts";import { removeRetiredAppFiles } from "./retired-apps.ts"; import { createEmailRoutes } from "./routes/email.ts"; import { createEmailHost, EMAIL_INTERNAL_MCP_PATH, emailAccess } from "./email/host.ts"; import { createEmailService } from "./email/service.ts"; import { createPostizRoutes } from "./routes/postiz.ts"; import { createPostiz } from "./postiz/service.ts";@@ -5629,11 +5629,11 @@ const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000;const LOCAL_VM_DESKTOP_WAIT_MS = 90_000;const localVmIdles = new Map<string, ComputerIdleTimer>();const meetingsHost = createMeetingsHost({ cfg, dataDir: DATA_DIR, store, startTurn: (botId, text, opts) => startTurn(botId, text, opts), threadBusy, power: () => cloudComputerPower, computerOwner: (bot) => botComputerControlKey(bot), routines: () => routines, log: (line) => console.warn(line) }, () => ({ personName: personNameIn, sendsFreely: (botId, threadId) => roomTurnLevels.forRequest(threadId, botId, () => sourceApprovalMode(botId, threadId)) === "full", outbound: () => outboundHold, markOutside: (threadId) => outsideLineage.mark(threadId), folder: (botId, threadId) => messageFileRootsForThread(botId, threadId).filter((root) => root !== ATTACHMENTS_DIR)[0] ?? null })); const cloudComputerPower = createCloudComputerPower({- cfg, owners: managedBoatOwners, broadcast, log: line => console.warn(line), routines: () => routines?.listRoutines() ?? [], wakeTimedOut: (owner, boxId) => boatRecovery.wakeTimedOut(owner, boxId),+ cfg, owners: managedBoatOwners, broadcast, log: line => console.warn(line), routines: () => routines?.listRoutines() ?? [], wakeTimedOut: (owner, boxId, ctx) => boatRecovery.wakeTimedOut(owner, boxId, ctx),routineComputer: 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, usedByOther: (owner, boxId) => usedByAnotherBot(owner, boxId, { holder: resource => turnResources.holder(resource), botOfThread: threadId => store.botByThread(threadId)?.id ?? null }), 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)); } }); const runComputers = createRunComputerGate({ computerOf: (run) => { const bot = store.bot(run.botId); return bot && turnProvider(bot, run.runOn as RoutineRunOn | undefined) === "box" ? botComputerControlKey(bot) : null; }, find: (owner) => boat.findBoat(cfg, owner), wake: (owner, budgetMs) => boat.readyBoat(cfg, owner, budgetMs), awaitAnswer: (boxId, opts) => boatReadiness.awaitAnswer(cfg, boxId, opts), verdict: (owner, since) => boatRecovery.verdict(owner, since), recoveryState: (owner) => boatRecovery.status(owner)?.state ?? null, used: (owner) => cloudComputerPower.used(owner), disk: (boxId, signal) => cloudComputerDisk.beforeRun(cfg, boxId, signal), remember: runComputerMemory(join(DATA_DIR, "routine-computers.json")), routineOf: (botId, threadId) => { const run = routines?.activeRunForBot(botId); return run?.threadId === threadId ? run.routineId : null; }, log: (line) => console.warn(line) });+}); 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, usedByOther: (owner, boxId, asking) => usedByAnotherBot(owner, boxId, { holder: resource => turnResources.holder(resource), botOfThread: threadId => store.botByThread(threadId)?.id ?? null }, asking), created: owner => cloudComputerPower.used(owner), turnWaiting: boxId => cloudComputerPower.waiting(boxId), tell: (owner, key, vars) => { 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], { ...vars, name: bot.name }); store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${text}`, ok: true } }); notify(buildNoticeNotification(bot, bot.threadId, text)); } }); const runComputers = createRunComputerGate({ computerOf: (run) => { const bot = store.bot(run.botId); return bot && turnProvider(bot, run.runOn as RoutineRunOn | undefined) === "box" ? botComputerControlKey(bot) : null; }, find: (owner) => boat.findBoat(cfg, owner), wake: (owner, budgetMs) => boat.readyBoat(cfg, owner, budgetMs), awaitAnswer: (boxId, opts) => boatReadiness.awaitAnswer(cfg, boxId, opts), verdict: (owner, since) => boatRecovery.verdict(owner, since), recoveryState: (owner) => boatRecovery.status(owner)?.state ?? null, used: (owner) => cloudComputerPower.used(owner), disk: (boxId, signal) => cloudComputerDisk.beforeRun(cfg, boxId, signal), remember: runComputerMemory(join(DATA_DIR, "routine-computers.json")), routineOf: (botId, threadId) => { const run = routines?.activeRunForBot(botId); return run?.threadId === threadId ? run.routineId : null; }, log: (line) => console.warn(line) });function inheritedTeamComputer(bot: Pick<BotRecord, "section" | "computer" | "cloudBackend">): TeamComputerRecord | undefined {return teamComputers.forBot(bot);@@ -5860,7 +5860,7 @@ function mountBotBoat(try {attached = await attachBotBoat(bot, owner, {budgetMs: CLOUD_COMPUTER_START_BUDGET_MS,- onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, onRestoring: () => { slot.pendingReason = CLOUD_COMPUTER_RESTORING; }, existingOnly: opts.existingOnly && !boatRecovery.replacedRecently(bot.id), onWaking: () => { slot.pendingReason = CLOUD_COMPUTER_WAKING; }, onReplacing: () => { slot.pendingReason = CLOUD_COMPUTER_REPLACING; },+ onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, onRestoring: () => { slot.pendingReason = CLOUD_COMPUTER_RESTORING; }, existingOnly: opts.existingOnly && !boatRecovery.replacedRecently(bot.id), onWaking: () => { slot.pendingReason = CLOUD_COMPUTER_WAKING; }, onRestarting: () => { slot.pendingReason = CLOUD_COMPUTER_RESTARTING; }, onReplacing: () => { slot.pendingReason = CLOUD_COMPUTER_REPLACING; },});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) {diff --git a/shared/cloud-computer-recovery.ts b/shared/cloud-computer-recovery.tsindex 13efa89ffb..b15fc04857 100644--- a/shared/cloud-computer-recovery.ts+++ b/shared/cloud-computer-recovery.ts@@ -36,16 +36,19 @@ export interface CloudComputerDisk {spaceClearedAt?: number;}-/** What the bot is told, in place of a computer call, while its computer is being restarted or replaced and the call- * waited for that as long as it could. */+/** What the bot is told, in place of a computer call, while its computer is not answering and MausBot is bringing it+ * back, and the call waited for that as long as it could. Says nothing of a replacement, which may be switched off. */export const CLOUD_COMPUTER_NOT_RESPONDING =- "This bot's cloud computer isn't responding yet. MausBot is restarting or replacing it by itself, and this turn continues on it once it answers. This call was not performed. Repeat it in a minute.";-/** The computer did not answer after waking, so a new one is being made for this turn. */+ "This bot's cloud computer isn't responding yet. MausBot keeps trying to bring it back by itself, and this turn can go on once it answers. This call was not performed. Repeat it in a minute.";+/** The same, for a call that was sent and got no answer. */+export const CLOUD_COMPUTER_NOT_RESPONDING_UNANSWERED =+ "This bot's cloud computer isn't responding yet, so this call got no answer and most likely did not run. MausBot keeps trying to bring it back by itself. Take a fresh screenshot in a minute before repeating it.";+/** Every guard passed: the silent computer is being set aside and a new one made for this turn. */export const CLOUD_COMPUTER_REPLACING =- "This bot's cloud computer did not answer after waking, so MausBot is replacing it with a new one. This call was not performed. Repeat it in a minute.";-/** The turn's computer was replaced while this call waited, and the new one is not up yet. */+ "This bot's cloud computer still did not answer after a restart, so MausBot is setting it aside, with its files, and giving this bot a new one. This call was not performed. Repeat it in a minute.";+/** The turn's computer was set aside while this call waited, and the new one is not up yet. */export const CLOUD_COMPUTER_REPLACEMENT_STARTING =- "This bot's cloud computer stopped responding and was replaced with a new one, which is still starting. This call was not performed. Repeat it in a minute.";+ "This bot's cloud computer stopped responding and was set aside; its new one is still starting. This call was not performed. Repeat it in a minute.";/** A call that waited out its computer's restart or replacement: only a look at the screen is made after such a wait,* since the bot has not seen what the computer is like now. */export const CLOUD_COMPUTER_ANSWERS_AGAIN =@@ -61,9 +64,15 @@ export const CLOUD_COMPUTER_RESTARTING_UNANSWERED =/** While the provider is still putting its disk back after a wake. */export const CLOUD_COMPUTER_RESTORING ="This bot's cloud computer is awake but still restoring its disk, so it is not answering yet. This call was not performed. Try again in a minute.";-/** Told once, on the bot's first computer call after the replacement. */+/** Told once, on the bot's first computer call after the replacement: one the provider reported broken and that could+ * not even be stopped, so it was deleted. */export const CLOUD_COMPUTER_REPLACED =- "This bot's cloud computer stopped responding and was replaced with a new one. Files and programs that were only on the old computer are gone: clone, download or install again what this task needs.";+ "This bot's cloud computer stopped working and was replaced with a new one. Files, programs and sign-ins that were only on the old computer are gone: clone, download or install again, and sign in again, as this task needs.";+/** Told once, on the bot's first computer call after its silent computer was set aside, kept until `date`. */+export const cloudComputerSetAsideNotice = (date: string): string =>+ `This bot's cloud computer stopped responding, so MausBot set it aside and gave this bot a new one. The old computer is kept, stopped and with its files, until ${date}; `+ + "the person finds it in Settings → Desktops & browser → Desktops. Files, programs and sign-ins that were only on the old computer are not on the new one: "+ + "clone, download or install again, and sign in again, as this task needs.";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 =@@ -113,6 +122,8 @@ export const RUN_COMPUTER_LINES = {/** 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",+ setAside: "server.cloudComputer.setAside",+ noRoom: "server.cloudComputer.noRoom",restarted: "server.cloudComputer.restarted",capped: "server.cloudComputer.capped",unreachable: "server.cloudComputer.unreachable",diff --git a/src/locales/en.json b/src/locales/en.jsonindex bea8bf2a48..b98718ce2d 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -8408,6 +8408,8 @@"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.setAside": "{name}'s cloud computer stopped responding, so MausBot gave it a new one. The old one is kept with its files until {date} in Settings → Desktops & browser → Desktops, then deleted.",+ "server.cloudComputer.noRoom": "{name}'s cloud computer stopped responding, and the plan has no room for a new computer beside it, so MausBot kept it, with its files, and keeps trying to bring it back. Restart computer in the computer panel tries again now.","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.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 487275462f..721a375d21 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10911,6 +10911,8 @@"settings.backTo": "Voltar às Configurações","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.setAside": "O computador na nuvem de {name} parou de responder, então o MausBot deu a ele um novo. O antigo fica guardado com seus arquivos até {date} em Configurações → Desktops e navegador → Desktops e depois é excluído.",+ "server.cloudComputer.noRoom": "O computador na nuvem de {name} parou de responder, e o plano não tem espaço para um computador novo ao lado dele, então o MausBot o manteve, com seus arquivos, e continua tentando trazê-lo de volta. Reiniciar computador, no painel do computador, tenta de novo agora.","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.",