Skip to content

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

VPS desktops: log idle-stop failures, retry unreachable boot recovery, and allow stopping outdated managed containers

Liamcc323f76dd6a
diff --git a/server/host/vps-idle.test.ts b/server/host/vps-idle.test.ts
index c14c4fe5ce..54901a2f67 100644
--- a/server/host/vps-idle.test.ts
+++ b/server/host/vps-idle.test.ts
@@ -19,9 +19,9 @@ import { createVpsIdleHost } from "./vps-idle.ts";
const DEFAULT_WINDOW_MS = 480 * 60_000;
/** The Cloud browser sandbox's 3-minute rule lives in cloud-computer-power and never reaches this timer. */
-function host() {
+function host(extra: Partial<AppConfig> = {}, opts: { isShuttingDown?: () => boolean } = {}) {
const bot = { id: "bot-1", name: "Bot", cloudBackend: "vps" } as BotRecord;
- const cfg = { vps: { sshAlias: "my-vps" } } as AppConfig;
+ const cfg = { vps: { sshAlias: "my-vps" }, ...extra } as AppConfig;
const idle = createVpsIdleHost({
cfg,
store: { bots: [bot], bot: (id) => (id === bot.id ? bot : null) },
@@ -32,7 +32,7 @@ function host() {
isVpsConfigTransitioning: () => false,
isLifecycleBusy: () => false,
claimBotComputerLifecycle: () => () => {},
- isShuttingDown: () => false,
+ isShuttingDown: opts.isShuttingDown ?? (() => false),
});
return { bot, idle };
}
@@ -44,8 +44,15 @@ describe("idle SSH server desktops", () => {
vi.useFakeTimers();
viewer.open = false;
vi.mocked(vps.vpsComputerAction).mockClear();
+ vi.mocked(vps.listManagedVpsComputers).mockReset();
+ vi.mocked(vps.listManagedVpsComputers).mockResolvedValue({
+ configured: true, available: true, vpsAliases: ["my-vps"], problem: null, instances: [],
+ });
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
});
- afterEach(() => vi.useRealTimers());
it("stops a quiet desktop after the fixed 480-minute window, not before", async () => {
const { bot, idle } = host();
@@ -72,4 +79,135 @@ describe("idle SSH server desktops", () => {
expect(stops()).toHaveLength(1);
idle.cancelAll();
});
+
+ it("logs idle-stop failures with the retry delay and retries until the stop succeeds", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const windowMs = 5 * 60_000;
+ const { bot, idle } = host({ vpsIdle: { timeoutMinutes: 5 } });
+ vi.mocked(vps.vpsComputerAction).mockRejectedValueOnce(new Error("Docker over SSH timed out"));
+
+ idle.touchVpsIdle(bot);
+ idle.vpsThreadStarted(bot.id, "t-1");
+ await vi.advanceTimersByTimeAsync(1_000);
+ idle.vpsThreadEnded(bot.id, "t-1");
+
+ await vi.advanceTimersByTimeAsync(windowMs - 1);
+ expect(stops()).toHaveLength(0);
+ expect(warn).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(stops()).toHaveLength(1);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("Bot"));
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("my-vps"));
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("300s"));
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("Docker over SSH timed out"));
+ expect(idle.vpsIdles.has(bot.id)).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(windowMs - 1);
+ expect(stops()).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(stops()).toHaveLength(2);
+ expect(idle.vpsIdles.has(bot.id)).toBe(false);
+ idle.cancelAll();
+ });
+
+ it("logs an unreachable VPS during boot recovery and retries with backoff until running desktops are recovered", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const windowMs = 5 * 60_000;
+ const { bot, idle } = host({ vpsIdle: { timeoutMinutes: 5 } });
+ vi.mocked(vps.listManagedVpsComputers)
+ .mockResolvedValueOnce({
+ configured: true, available: false, vpsAliases: ["my-vps"],
+ problem: "Docker over SSH could not list managed computers on my-vps: No route to host",
+ unreachable: true, instances: [],
+ })
+ .mockResolvedValueOnce({
+ configured: true, available: false, vpsAliases: ["my-vps"],
+ problem: "Docker over SSH could not list managed computers on my-vps: Connection timed out",
+ unreachable: true, instances: [],
+ })
+ .mockResolvedValueOnce({
+ configured: true, available: true, vpsAliases: ["my-vps"], problem: null,
+ instances: [{
+ name: "openmausbot-vps-bot1-000000000000", state: "running", vpsAlias: "my-vps",
+ ownerBotId: bot.id, ownerName: bot.name, orphaned: false, inUse: false,
+ }],
+ });
+
+ idle.recover();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("No route to host"));
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("30s"));
+ expect(idle.vpsIdles.has(bot.id)).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(29_999);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(2);
+ expect(warn).toHaveBeenCalledTimes(2);
+ expect(String(warn.mock.calls[1]?.[0])).toEqual(expect.stringContaining("60s"));
+
+ await vi.advanceTimersByTimeAsync(59_999);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(3);
+ expect(idle.vpsIdles.has(bot.id)).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(windowMs);
+ expect(stops()).toHaveLength(1);
+ idle.cancelAll();
+ });
+
+ it("logs a non-unreachable recovery problem once without retrying, and cancels pending retries on cancelAll or shutdown", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ let bootFinished = false;
+ let shuttingDown = false;
+ const { idle } = host({}, {
+ isShuttingDown: () => {
+ if (!bootFinished) throw new ReferenceError("Cannot access 'companyShutdown' before initialization");
+ return shuttingDown;
+ },
+ });
+
+ vi.mocked(vps.listManagedVpsComputers).mockResolvedValueOnce({
+ configured: false, available: false, vpsAliases: [], problem: null, instances: [],
+ });
+ idle.recover();
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ bootFinished = true;
+ expect(warn).not.toHaveBeenCalled();
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(1);
+
+ vi.mocked(vps.listManagedVpsComputers).mockResolvedValueOnce({
+ configured: true, available: false, vpsAliases: ["my-vps"],
+ problem: "The Docker CLI is not on PATH", instances: [],
+ });
+ idle.recover();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(String(warn.mock.calls[0]?.[0])).toEqual(expect.stringContaining("The Docker CLI is not on PATH"));
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(2);
+
+ vi.mocked(vps.listManagedVpsComputers).mockResolvedValue({
+ configured: true, available: false, vpsAliases: ["my-vps"],
+ problem: "SSH timed out", unreachable: true, instances: [],
+ });
+ idle.recover();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(3);
+ idle.cancelAll();
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(3);
+
+ idle.recover();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(4);
+ shuttingDown = true;
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ expect(vps.listManagedVpsComputers).toHaveBeenCalledTimes(4);
+ });
});
diff --git a/server/host/vps-idle.ts b/server/host/vps-idle.ts
index f5a27910a6..e452544219 100644
--- a/server/host/vps-idle.ts
+++ b/server/host/vps-idle.ts
@@ -17,11 +17,26 @@ export interface VpsIdleHostDeps {
isShuttingDown: () => boolean;
}
+const RECOVER_RETRY_BASE_MS = 30_000;
+const MAX_RECOVER_RETRIES = 5;
+
export function createVpsIdleHost(deps: VpsIdleHostDeps) {
const activeVpsThreads = new Map<string, Set<string>>();
const vpsIdles = new Map<string, ComputerIdleTimer>();
const vpsIdleGenerations = new Map<string, number>();
const vpsIdleMs = () => vpsIdleTimeoutMinutes(deps.cfg) * 60_000;
+ let recoverTimer: ReturnType<typeof setTimeout> | null = null;
+ let recoverGeneration = 0;
+ const shuttingDown = () => {
+ try { return deps.isShuttingDown(); }
+ catch (error) { if (error instanceof ReferenceError) return false; throw error; }
+ };
+
+ function clearRecoverRetry(): void {
+ recoverGeneration += 1;
+ if (recoverTimer) clearTimeout(recoverTimer);
+ recoverTimer = null;
+ }
function vpsThreadStarted(botId: string, threadId: string): void {
const threads = activeVpsThreads.get(botId) ?? new Set<string>();
@@ -56,17 +71,25 @@ export function createVpsIdleHost(deps: VpsIdleHostDeps) {
const inUse = () => activeVpsThreads.has(id) || deps.botHasActiveTurn(id) || deps.hasActiveRoutine(id)
|| deps.isSharedVmHeld(id) || Boolean(vps.vpsDesktopConnection(id)) || deps.hasComputerPreview(id)
|| deps.isVpsConfigTransitioning();
- const timer: ComputerIdleTimer = new ComputerIdleTimer(vpsIdleMs(), () => inUse() || deps.isLifecycleBusy(id), async () => {
- if (!current()) return;
- const release = deps.claimBotComputerLifecycle(id);
- try {
- const status = await vps.vpsComputerAction("stop", { vps: { sshAlias: alias } }, id, undefined, () => Boolean(current()) && !inUse());
- if (status.container === "running") return "busy";
- if (vpsIdles.get(id) === timer) vpsIdles.delete(id);
- } finally {
- release();
- }
- });
+ const timer: ComputerIdleTimer = new ComputerIdleTimer(
+ vpsIdleMs(),
+ () => inUse() || deps.isLifecycleBusy(id),
+ async () => {
+ if (!current()) return;
+ const release = deps.claimBotComputerLifecycle(id);
+ try {
+ const status = await vps.vpsComputerAction("stop", { vps: { sshAlias: alias } }, id, undefined, () => Boolean(current()) && !inUse());
+ if (status.container === "running") return "busy";
+ if (vpsIdles.get(id) === timer) vpsIdles.delete(id);
+ } finally {
+ release();
+ }
+ },
+ (error, retryInMs) => {
+ const detail = error instanceof Error ? error.message : String(error);
+ console.warn(`Could not stop idle VPS desktop for ${bot.name} (${id}) on ${alias}; retrying in ${Math.round(retryInMs / 1000)}s: ${detail}`);
+ },
+ );
vpsIdles.set(id, timer);
timer.touch();
}
@@ -79,7 +102,7 @@ export function createVpsIdleHost(deps: VpsIdleHostDeps) {
const alias = vpsSshAliasForBot(deps.cfg, bot);
if (!alias) return;
void vps.vpsComputerRunning({ vps: { sshAlias: alias } }, id).then((running) => {
- if (!running || deps.isShuttingDown() || vpsIdleGenerations.get(id) !== generation) return;
+ if (!running || shuttingDown() || vpsIdleGenerations.get(id) !== generation) return;
const current = deps.store.bot(id);
if (current && current.cloudBackend === "vps" && vpsSshAliasForBot(deps.cfg, current) === alias && !vpsIdles.has(id)) {
touchVpsIdle(current);
@@ -87,16 +110,49 @@ export function createVpsIdleHost(deps: VpsIdleHostDeps) {
});
}
- function recover(): void {
- void vps.listManagedVpsComputers(deps.cfg, deps.store.bots.map(bot => ({ botId: bot.id, name: bot.name, inUse: false })), undefined, vpsAliasesInPlay(deps.cfg, deps.store.bots)).then(inventory => {
+ function runRecover(attempt: number, generation: number): void {
+ if (shuttingDown() || generation !== recoverGeneration) return;
+ void vps.listManagedVpsComputers(
+ deps.cfg,
+ deps.store.bots.map((bot) => ({ botId: bot.id, name: bot.name, inUse: false })),
+ undefined,
+ vpsAliasesInPlay(deps.cfg, deps.store.bots),
+ ).then((inventory) => {
+ if (shuttingDown() || generation !== recoverGeneration) return;
for (const instance of inventory.instances) {
const bot = instance.ownerBotId && deps.store.bot(instance.ownerBotId);
- if (bot && instance.state === "running" && instance.vpsAlias === vpsSshAliasForBot(deps.cfg, bot) && !vpsIdles.has(bot.id)) touchVpsIdle(bot);
+ if (bot && instance.state === "running" && instance.vpsAlias === vpsSshAliasForBot(deps.cfg, bot) && !vpsIdles.has(bot.id)) {
+ touchVpsIdle(bot);
+ }
}
- }).catch(error => console.warn("Could not recover VPS idle timers", error));
+ if (inventory.configured && !inventory.available) {
+ const reason = inventory.problem ?? "VPS inventory unavailable";
+ if (inventory.unreachable && attempt < MAX_RECOVER_RETRIES) {
+ const delayMs = RECOVER_RETRY_BASE_MS * 2 ** attempt;
+ console.warn(`Could not recover VPS idle timers (${reason}); retrying in ${Math.round(delayMs / 1000)}s`);
+ recoverTimer = setTimeout(() => {
+ recoverTimer = null;
+ runRecover(attempt + 1, generation);
+ }, delayMs);
+ recoverTimer.unref?.();
+ } else {
+ console.warn(`Could not recover VPS idle timers: ${reason}`);
+ }
+ }
+ }).catch((error) => {
+ if (!shuttingDown() && generation === recoverGeneration) {
+ console.warn("Could not recover VPS idle timers", error);
+ }
+ });
+ }
+
+ function recover(): void {
+ clearRecoverRetry();
+ runRecover(0, recoverGeneration);
}
function cancelAll(): void {
+ clearRecoverRetry();
for (const botId of new Set([...vpsIdles.keys(), ...vpsIdleGenerations.keys()])) cancelVpsIdle(botId);
}
diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.ts
index f9b8c302ab..e71d7fd9f2 100644
--- a/server/vps-computer.test.ts
+++ b/server/vps-computer.test.ts
@@ -1108,6 +1108,26 @@ describe("VPS computer", () => {
expect(absent.calls.some(({ args }) => args[2] === "rm")).toBe(false);
});
+ it("stops a managed container even when its image is outdated or missing, while refusing unowned containers", async () => {
+ const missingNewImage = fixture({ image: false, environmentId: vpsEnvironmentId() });
+ const idleStopped = await vpsComputerAction("stop", CONFIG, BOT_ID, missingNewImage.runner, () => true);
+ expect(idleStopped.container).toBe("stopped");
+ expect(missingNewImage.calls.some(({ args }) => args[2] === "stop" && args[3] === CONTAINER_ID)).toBe(true);
+
+ const stale = fixture({ containerImageId: `sha256:${"c".repeat(64)}` });
+ const manualStopped = await vpsComputerAction("stop", CONFIG, BOT_ID, stale.runner);
+ expect(manualStopped.container).toBe("stopped");
+ expect(stale.calls.some(({ args }) => args[2] === "stop" && args[3] === CONTAINER_ID)).toBe(true);
+
+ const unowned = fixture({ managed: false });
+ await expect(vpsComputerAction("stop", CONFIG, BOT_ID, unowned.runner)).rejects.toThrow(/did not create/);
+ expect(unowned.calls.some(({ args }) => args[2] === "stop")).toBe(false);
+
+ const foreign = fixture({ environmentId: "11111111-2222-4333-8444-555555555555" });
+ await expect(vpsComputerAction("stop", CONFIG, BOT_ID, foreign.runner)).rejects.toThrow(/did not create/);
+ expect(foreign.calls.some(({ args }) => args[2] === "stop")).toBe(false);
+ });
+
it("surfaces the supervisor error log when the desktop probe fails", async () => {
const fake = fixture({ desktopProbeFails: true });
const status = await vpsComputerStatus(CONFIG, BOT_ID, fake.runner);
diff --git a/server/vps-computer.ts b/server/vps-computer.ts
index a4124f80ea..c55e8463b0 100644
--- a/server/vps-computer.ts
+++ b/server/vps-computer.ts
@@ -989,23 +989,20 @@ export async function vpsComputerAction(
assertUsableContainer(before);
await applyResourcesBeforeStart(containerRef, vpsResources(cfg), run);
await run(["start", containerRef]);
- } else if (action === "remove") {
- // Skips the usability check (remove escapes a broken container); the ownership labels are the only gate.
- if (before.container === "missing") return before;
+ } else {
+ // Skips the usability check (stop and remove shut down a broken or outdated container); ownership labels are the only gate.
+ if (action === "remove" && before.container === "missing") return before;
+ if (action === "stop" && before.container !== "running") throw Object.assign(new Error("The VPS container is not running"), { status: 409 });
if (!before.managed) {
throw Object.assign(
new Error("The VPS container name is occupied by a container OpenMausBot did not create — remove it on the VPS yourself"),
{ status: 409 },
);
}
- await run(["rm", "-f", containerRef]);
+ await run(action === "remove" ? ["rm", "-f", containerRef] : ["stop", containerRef]);
return await computeVpsComputerStatus(cfg, botId, runner);
- } else {
- if (before.container !== "running") throw Object.assign(new Error("The VPS container is not running"), { status: 409 });
- assertUsableContainer(before);
- await run(["stop", containerRef]);
}
- return await (action === "stop" ? computeVpsComputerStatus(cfg, botId, runner) : waitForVpsReady(cfg, botId, runner));
+ return await waitForVpsReady(cfg, botId, runner);
} finally {
invalidateVpsStatus(key);
}