Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Switch VPS viewer tunnel and idle timer when a bot changes SSH server
Linf4bb2a7f1b23
diff --git a/server/index.ts b/server/index.tsindex d52010b08a..eb82d04b78 100644--- a/server/index.ts+++ b/server/index.ts@@ -5607,12 +5607,21 @@ const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000;const LOCAL_VM_DESKTOP_WAIT_MS = 90_000;const localVmIdles = new Map<string, ComputerIdleTimer>();const vpsIdles = new Map<string, ComputerIdleTimer>();+const vpsIdleGenerations = new Map<string, number>();++function cancelVpsIdle(botId: string): number {+ const generation = (vpsIdleGenerations.get(botId) ?? 0) + 1;+ vpsIdleGenerations.set(botId, generation);+ vpsIdles.get(botId)?.cancel();+ vpsIdles.delete(botId);+ return generation;+}function touchVpsIdle(bot: BotRecord): void {const alias = vpsSshAliasForBot(cfg, bot);if (!alias) return;const id = bot.id;- vpsIdles.get(id)?.cancel();+ cancelVpsIdle(id);const current = () => {const owner = store.bot(id);return owner && vpsSshAliasForBot(cfg, owner) === alias && vpsIdles.get(id) === timer;@@ -5626,6 +5635,7 @@ function touchVpsIdle(bot: BotRecord): void {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();}@@ -5634,6 +5644,22 @@ function touchVpsIdle(bot: BotRecord): void {timer.touch();}+function vpsServerSwitched(bot: BotRecord): void {+ const id = bot.id;+ vps.stopVpsDesktopTunnel(id);+ const generation = cancelVpsIdle(id);+ if (bot.cloudBackend !== "vps") return;+ const alias = vpsSshAliasForBot(cfg, bot);+ if (!alias) return;+ void vps.vpsComputerRunning({ vps: { sshAlias: alias } }, id).then((running) => {+ if (!running || companyShutdown || vpsIdleGenerations.get(id) !== generation) return;+ const current = store.bot(id);+ if (current && current.cloudBackend === "vps" && vpsSshAliasForBot(cfg, current) === alias && !vpsIdles.has(id)) {+ touchVpsIdle(current);+ }+ });+}+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, ctx) => boatRecovery.wakeTimedOut(owner, boxId, ctx),routineComputer: routine => { const bot = store.bot(routine.botId); return bot && turnProvider(bot, routine.runOn) === "box" ? botComputerControlKey(bot) : null; },@@ -9048,6 +9074,8 @@ async function deleteBotWithLifecycle(botId: string, revalidate: () => void = ()}stopScreenPoller(bot.id);activeVpsThreads.delete(bot.id);+ vps.stopVpsDesktopTunnel(bot.id);+ cancelVpsIdle(bot.id);lastReply.delete(bot.threadId);const target = perBotLocalVmTarget(bot.id);localVmIdles.get(target.key)?.cancel();@@ -12026,7 +12054,7 @@ ROUTES.push(createBotSettingsRoutes({canManageCommandAllowlist, commandAllowlistResponse, cardAnswerRefusal, threadRead: teamMessages.seen, levelOf, personMarkThread: personRooms.personMarkThread, personHeldUnread: personRooms.personHeldUnread,}));const botOrderRoutes = createBotOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(botOrders ? { own: { person: botOrders.personOf, order: botOrders, told: (person, botIds) => broadcast({ kind: "bots.order", botIds }, { person }) } } : {}) }); ROUTES.push(createGroupOrderRoutes({ store, visibleFor: (auth) => visibleTo(viewerFor(auth)) }), botOrderRoutes, createBotAccessRoutes({ team: CLOUD_TEAM, people: teamOwners.people, store, levelOf, wireBot, publicGroupState, broadcast, audienceChanged, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }), shared: createShareNotice({ people: () => teamOwners.people?.list() ?? [], profileName: (email) => teamHost.people.profile(personKey({ id: "", email })).name, store: () => store, inbox: () => teamMessages.inbox }) }), accessRequests.routes);-const botPatchRoutes = createBotPatchRoutes({ turnBots: directTurnBots, modelSwitched: noTerminal.modelSwitched,+const botPatchRoutes = createBotPatchRoutes({ turnBots: directTurnBots, modelSwitched: noTerminal.modelSwitched, vpsServerSwitched,store, cfg, registry, sessions, browserRuntime, browserLive, memoryUpkeep, cacheKeepWarm, hostedModels, supportsApprovalMode,routines: () => routines, activeVpsThreads,hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED,@@ -12249,7 +12277,7 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persisharedComputers, sharedComputerControl, closeBrowser, browserEngineSwitched,hostedModels: Boolean(hostedModels),cloudHome: Boolean(CLOUD_HOME), cloudTeam: CLOUD_TEAM !== null, sharedMembership,- lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles, vpsIdleMs, vpsIdles, localVmActiveThreads, localVmLifecycleBusy,+ lendingEnabled: () => lendingEnabled() || ownerLends(), providerConfigs, localVmIdleMs, localVmIdles, vpsIdleMs, vpsIdles, vpsServerSwitched, localVmActiveThreads, localVmLifecycleBusy,localVmImageBusy: { get: () => localVmImageBusy },localVmModeChangeBusy: { set: (busy) => { localVmModeChangeBusy = busy; } },localVmModeChanging: sharedVm.modeChanging,@@ -15019,12 +15047,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {? desktopViewerUrl(`vps/${botId}`, bot.threadId) : result.joinUrl });}const action = m[2] === "provision" ? "provision" : m[2] === "remove" ? "remove" : "stop";+ cancelVpsIdle(botId);const status = await vps.vpsComputerAction(action, vpsConfigForBot(cfg, bot), botId);if (status.container === "running") touchVpsIdle(bot);- else {- vpsIdles.get(botId)?.cancel();- vpsIdles.delete(botId);- }+ else cancelVpsIdle(botId);return json(res, 200, status);} finally {releaseComputerLifecycle();@@ -15244,7 +15270,7 @@ const gracefulShutdown = createGracefulShutdown({desktopViewer.closeAll();upgrades.close();for (const idle of localVmIdles.values()) idle.cancel();- for (const idle of vpsIdles.values()) idle.cancel();+ for (const botId of new Set([...vpsIdles.keys(), ...vpsIdleGenerations.keys()])) cancelVpsIdle(botId);cloudComputerPower.close(); boatRecovery.close();vps.closeAllVpsDesktopTunnels();watchdog.stop();diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.tsindex 5183396976..fd2b0ac4cc 100644--- a/server/routes/bot-patch.test.ts+++ b/server/routes/bot-patch.test.ts@@ -265,6 +265,42 @@ describe("PATCH /api/bots/:id vpsAlias relocation guard", () => {expect(refused.body.error).toBe(VPS_BOT_ALIAS_CHANGE_ERROR);expect(scan).toHaveBeenCalledTimes(3);});++ it("notifies vpsServerSwitched only when a committed patch changes the resolved SSH alias", async () => {+ const switched: Array<string | undefined> = [];+ const { store, bot, patch } = fixture({+ vpsServerSwitched: (updated) => { switched.push(updated.vpsAlias); },+ });++ expect((await patch(bot.id, { vpsAlias: "production-vps" })).status).toBe(200);+ expect((await patch(bot.id, { vpsAlias: null })).status).toBe(200);+ expect(switched).toEqual([]);++ expect((await patch(bot.id, { vpsAlias: "gamma-vps" })).status).toBe(200);+ expect(switched).toEqual(["gamma-vps"]);++ scan.mockResolvedValueOnce({+ ...emptyInventory(),+ instances: [{+ name: vps.vpsContainerName(bot.id),+ state: "running",+ vpsAlias: "gamma-vps",+ ownerBotId: bot.id,+ ownerName: bot.name,+ orphaned: false,+ inUse: false,+ }],+ });+ expect((await patch(bot.id, { vpsAlias: "delta-vps" })).status).toBe(409);+ expect((await patch(bot.id, { vpsAlias: "delta-vps", toolsOff: ["browser"] })).status).toBe(400);+ store.patchBot(bot.id, { busy: true });+ expect((await patch(bot.id, { vpsAlias: "delta-vps" })).status).toBe(409);+ expect(switched).toEqual(["gamma-vps"]);++ store.patchBot(bot.id, { busy: false });+ expect((await patch(bot.id, { vpsAlias: null })).status).toBe(200);+ expect(switched).toEqual(["gamma-vps", undefined]);+ });});describe("PATCH /api/bots/:id defaultBot: null", () => {diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.tsindex 86c33ad33a..0735e07e1b 100644--- a/server/routes/bot-patch.ts+++ b/server/routes/bot-patch.ts@@ -95,6 +95,7 @@ export interface BotPatchRouteDeps {turnBots?: { values(): Iterable<BotRecord> };/** A bot's model changed, from `before` to `after`, seen in `threadId` (host/no-terminal.ts says there what it takes away). */modelSwitched?(botId: string, threadId: string, before: ModelSelection, after: ModelSelection, routinesFollow: boolean): void;+ vpsServerSwitched?(bot: BotRecord): void;}export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {@@ -727,6 +728,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {(freshBrowserBot.busy || browserRuntime.heldBy(currentBrowserSession(freshBrowserBot.id, freshBrowserBot.browserProfile)))) {return json(res, 409, { error: "Stop the bot and release browser control before changing its profile." });}+ const beforeVpsAlias = freshBrowserBot ? vpsSshAliasForBot(cfg, freshBrowserBot) : null;// A mark goes out with its hold in one frame, below.delete patch.unread;if (Array.isArray(patch.alwaysAllow)) dropRemovedGrants(store, deps.turnBots?.values() ?? [], m[1], patch.alwaysAllow);@@ -757,6 +759,7 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {if (normalizedSelection && existingBot) deps.modelSwitched?.(bot.id, movedTask?.threadId ?? existingBot.threadId, movedTask?.modelSelection ?? existingBot.modelSelection, normalizedSelection, true);if (existingBot) {settleBrowserChange(bot, { browserProfile: beforeBrowserProfile, browser: beforeBrowserEnabled }, { closeForBot: (id) => browserLive.closeForBot(id), forgetTemporaryBrowser });+ if (vpsSshAliasForBot(cfg, bot) !== beforeVpsAlias) deps.vpsServerSwitched?.(bot);}const chiefChanges =body.chiefOfStaff === true || chiefMovedSectionsdiff --git a/server/routes/config-engine-effect.test.ts b/server/routes/config-engine-effect.test.tsindex f8b8c7afb2..385f084682 100644--- a/server/routes/config-engine-effect.test.ts+++ b/server/routes/config-engine-effect.test.ts@@ -59,11 +59,11 @@ describe("saving config and the engines' status", () => {const auth = { kind: "owner", via: "loopback", scopes: ["admin", "client"] } as unknown as RequestAuth;function routes() {- const localDeadlines: number[] = [], vpsDeadlines: number[] = [];+ const localDeadlines: number[] = [], vpsDeadlines: number[] = [], switchedBots: string[] = [];let forgotten = 0, broadcasts = 0;const busy = () => ({ get: () => false, set: () => {} });const deps = {- store: { bots: [], patchBot: () => null, clearVoiceSelections: () => {} },+ store: { bots: [{ id: "uses-default" }, { id: "pinned", vpsAlias: "alpha-vps" }], patchBot: () => null, clearVoiceSelections: () => {} },cfg: {},registry: { get: () => undefined, forgetSnapshots: () => { forgotten += 1; } },sessions: { revalidateEmailSessions: () => {} },@@ -85,6 +85,7 @@ describe("saving config and the engines' status", () => {localVmIdles: new Map([["private", { setIdleMs: (ms: number) => localDeadlines.push(ms) }]]),vpsIdleMs: () => (deps.cfg.vpsIdle?.timeoutMinutes ?? 480) * 60_000,vpsIdles: new Map([["server", { setIdleMs: (ms: number) => vpsDeadlines.push(ms) }]]),+ vpsServerSwitched: (bot: { id: string }) => { switchedBots.push(bot.id); },localVmActiveThreads: new Set(),localVmLifecycleBusy: new Set(),localVmImageBusy: busy(),@@ -116,7 +117,7 @@ describe("saving config and the engines' status", () => {} as unknown as Parameters<typeof route>[0]);return replies;};- return { save, localDeadlines, vpsDeadlines, forgotten: () => forgotten, broadcasts: () => broadcasts, cfg: deps.cfg };+ return { save, localDeadlines, vpsDeadlines, switchedBots, forgotten: () => forgotten, broadcasts: () => broadcasts, cfg: deps.cfg };}it("re-arms only timers belonging to the changed idle setting", async () => {@@ -129,6 +130,14 @@ describe("saving config and the engines' status", () => {expect(vpsDeadlines).toEqual([1440 * 60_000]);});+ it("switches only bots that use the default VPS server when the default SSH alias changes", async () => {+ const { save, switchedBots } = routes();+ expect(await save({ vps: { sshAlias: "alpha-vps" } })).toEqual([200]);+ expect(switchedBots).toEqual(["uses-default"]);+ expect(await save({ vps: { sshAlias: "alpha-vps" } })).toEqual([200]);+ expect(switchedBots).toEqual(["uses-default"]);+ });+it("keeps every engine's status through a save of what the app shows", async () => {const { save, forgotten, broadcasts, cfg } = routes();expect(await save({ onboarding: { hintsSeen: ["welcome"] } })).toEqual([200]);diff --git a/server/routes/config.ts b/server/routes/config.tsindex f99c0a869f..ad7287406c 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -17,6 +17,7 @@ import {builtInBrowserEnabled,changedInstanceIds,engineLaunches,+ isValidSshAlias,loadConfig,localVmMode,mergeOpenCodeProviderKeys,@@ -39,7 +40,7 @@ import type { SessionRegistry } from "../sessions.ts";import type { SharedComputerControl } from "../shared-computer-control.ts";import type { SharedComputers } from "../shared-computers.ts";import { parseSkillMd } from "../skills.ts";-import type { Store } from "../store.ts";+import type { BotRecord, Store } from "../store.ts";import * as tts from "../tts/index.ts";import { DEFAULT_DEEPSEEK_VOICE } from "../../shared/deepseek-voice.ts";import * as vps from "../vps-computer.ts";@@ -86,6 +87,7 @@ export interface ConfigRouteDeps {providerConfigs(): InstanceConfigMap;vpsIdleMs(): number;vpsIdles: ConfigRouteDeps["localVmIdles"];+ vpsServerSwitched?(bot: BotRecord): void;localVmIdleMs(): number;localVmIdles: { values(): Iterable<Pick<ComputerIdleTimer, "setIdleMs">> };localVmActiveThreads: { readonly size: number };@@ -639,6 +641,11 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {postiz?.configSaved(patch);// A saved key reaches an engine through the environment its status read uses, often with no reload.if (patchMayChangeEngineStatus(patch)) registry.forgetSnapshots();+ if (changingVpsAlias) {+ for (const bot of store.bots) {+ if (!isValidSshAlias(bot.vpsAlias)) deps.vpsServerSwitched?.(bot);+ }+ }if (patch.vpsIdle?.timeoutMinutes !== undefined) {for (const idle of vpsIdles.values()) idle.setIdleMs(vpsIdleMs());}diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.tsindex 8b556b4043..beb1d92706 100644--- a/server/vps-computer.test.ts+++ b/server/vps-computer.test.ts@@ -44,7 +44,9 @@ import {vpsComputerJoin,vpsDesktopConnection,closeVpsDesktopTunnel,+ stopVpsDesktopTunnel,closeAllVpsDesktopTunnels,+ vpsComputerRunning,vpsComputerScreenshot,vpsComputerStatus,vpsComputerMcp,@@ -1410,6 +1412,33 @@ describe("remote desktop tunnel ownership", () => {expect(child.kill).toHaveBeenCalledTimes(1);} finally { closeAllVpsDesktopTunnels(); vi.useRealTimers(); }});++ it("stops an open viewer tunnel on a server switch without firing onViewerClosed, so the next join opens a fresh tunnel", async () => {+ const closed = vi.fn();+ const { child, runner } = await openFixture(closed);+ try {+ const release = vpsDesktopConnection(BOT_ID)!.retain();+ expect(stopVpsDesktopTunnel(BOT_ID)).toBe(true);+ expect(child.killed).toBe(true);+ release();+ child.emit("close", 0);+ expect(closed).not.toHaveBeenCalled();+ expect(vpsDesktopConnection(BOT_ID)).toBeUndefined();+ const next = await vpsComputerJoin({ vps: { sshAlias: "alpha-vps" } }, BOT_ID, runner, true);+ expect(next.state).toBe("running");+ expect(vpsDesktopConnection(BOT_ID)?.live()).toBe(true);+ } finally { closeAllVpsDesktopTunnels(); }+ });++ it("checks whether a managed VPS desktop container is running without throwing on unreachable or missing hosts", async () => {+ expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ running: true }).runner)).toBe(true);+ expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ running: false }).runner)).toBe(false);+ expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ container: false }).runner)).toBe(false);+ expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ managed: false }).runner)).toBe(false);+ expect(await vpsComputerRunning(CONFIG, BOT_ID, fixture({ environmentId: "another-installation" }).runner)).toBe(false);+ expect(await vpsComputerRunning({}, BOT_ID, fixture().runner)).toBe(false);+ expect(await vpsComputerRunning(CONFIG, BOT_ID, async () => { throw new Error("ssh: connect timeout"); })).toBe(false);+ });});describe("a missing Docker CLI", () => {diff --git a/server/vps-computer.ts b/server/vps-computer.tsindex 2becf7160d..97be939d85 100644--- a/server/vps-computer.ts+++ b/server/vps-computer.ts@@ -256,6 +256,10 @@ export function closeVpsDesktopTunnel(botId: string) {return { closed: tunnel ? endViewerTunnel(botId, tunnel) : stopDesktopTunnel(botId) };}+export function stopVpsDesktopTunnel(botId: string): boolean {+ return stopDesktopTunnel(botId);+}+export function closeAllVpsDesktopTunnels(): void {for (const botId of new Set([...desktopTunnels.keys(), ...pendingDesktopTunnels.keys()])) stopDesktopTunnel(botId);}@@ -548,6 +552,33 @@ async function computeVpsComputerStatus(return status;}+export async function vpsComputerRunning(+ cfg: AppConfig,+ botId: string,+ runner: VpsCommandRunner = defaultRunner,+): Promise<boolean> {+ const alias = vpsSshAlias(snapshotVpsConfig(cfg));+ if (!alias) return false;+ const name = vpsContainerName(botId);+ try {+ const inspected = JSON.parse((await runner(vpsDockerArgs(alias, ["inspect", name]), { timeoutMs: 10_000 })).stdout) as Array<{+ Config?: { Labels?: Record<string, string> };+ State?: { Running?: boolean };+ }>;+ const detail = inspected[0];+ const labels = detail?.Config?.Labels;+ const environmentLabel = labels?.[VPS_ENVIRONMENT_LABEL];+ return Boolean(+ detail?.State?.Running &&+ labels?.[VPS_MANAGED_LABEL] === "1" &&+ labels?.[VPS_CONTAINER_LABEL] === name &&+ (environmentLabel === undefined || environmentLabel === vpsEnvironmentId()),+ );+ } catch {+ return false;+ }+}+export async function vpsComputerStatus(cfg: AppConfig,botId: string,diff --git a/server/vps-routing.test.ts b/server/vps-routing.test.tsindex f178aa322c..ab5001d255 100644--- a/server/vps-routing.test.ts+++ b/server/vps-routing.test.ts@@ -108,7 +108,7 @@ function containerInspectTemplate(): string {const FAKE_DOCKER = `#!/bin/shprintf '%s\\n' "$*" >> "$FAKE_DOCKER_LOG"server=$(printf '%s' "$2" | sed 's|ssh://||')-if [ -f "$FAKE_DOCKER_DIR/unreachable.$server" ]; then echo "ssh: Could not resolve hostname $server: nodename nor servname provided, or not known" >&2; exit 255; fi+if [ -f "$FAKE_DOCKER_DIR/unreachable.$server" ]; then echo "error during connect: stderr=ssh: Could not resolve hostname $server: nodename nor servname provided, or not known" >&2; exit 255; fiif [ -f "$FAKE_DOCKER_DIR/hold" ]; then: > "$FAKE_DOCKER_DIR/started"while [ -f "$FAKE_DOCKER_DIR/hold" ]; do sleep 0.05; done@@ -281,7 +281,7 @@ global.setTimeout = (fn, ms, ...args) => schedule(fn, ms === ${TEST_IDLE_MINUTESawait removeTempDir(home);});- it("renews the current server's idle window when the previous server's viewer drops", async () => {+ it("closes the old viewer on a server switch, opens a fresh tunnel, and renews the idle window when the viewer drops", async () => {const dir = dirname(dockerLog);const template = join(dir, "container.json.tpl");const original = readFileSync(template, "utf8");@@ -295,12 +295,19 @@ global.setTimeout = (fn, ms, ...args) => schedule(fn, ms === ${TEST_IDLE_MINUTESconst { bot } = (await api("POST", "/api/bots")).body;const path = `/api/bots/${bot.id}`;expect((await api("PATCH", path, { computer: "cloud", cloudBackend: "vps" })).status).toBe(200);- expect((await api("POST", `${path}/computer/join?threadId=${bot.threadId}`, {})).status).toBe(200);+ const oldJoin = await api("POST", `${path}/computer/join?threadId=${bot.threadId}`, {});+ expect(oldJoin.status).toBe(200);writeFileSync(unreachable, "");expect((await api("PATCH", path, { vpsAlias: "alpha-vps" })).status).toBe(200);- expect((await api("POST", `${path}/computer/provision`, {})).status).toBe(200);- const stopped = () => readFileSync(dockerLog, "utf8").includes(`ssh://alpha-vps stop ${CONTAINER_ID}`);- await new Promise(resolve => setTimeout(resolve, 1500));+ const newJoin = await api("POST", `${path}/computer/join?threadId=${bot.threadId}`, {});+ expect(newJoin.status).toBe(200);+ expect(newJoin.body.joinUrl).not.toBe(oldJoin.body.joinUrl);+ const stopped = () => {+ const log = readFileSync(dockerLog, "utf8");+ const stopAt = log.lastIndexOf(`ssh://alpha-vps stop ${CONTAINER_ID}`);+ return stopAt >= 0 && log.slice(stopAt).includes(`ssh://alpha-vps inspect ${vpsContainerName(bot.id)}`);+ };+ await new Promise(resolve => setTimeout(resolve, 3000));const droppedAt = performance.now();process.kill(Number(readFileSync(join(dir, "viewer.pid"), "utf8")));await until(async () => stopped(), "idle stop on the new server", 8000);@@ -310,7 +317,74 @@ global.setTimeout = (fn, ms, ...args) => schedule(fn, ms === ${TEST_IDLE_MINUTESwriteFileSync(template, original);await api("PATCH", "/api/config", { vpsIdle: { timeoutMinutes: 480 } });}- }, 20_000);+ }, 25_000);++ it("idle-stops an already-running desktop on the new server after a per-bot or default-server switch", async () => {+ const dir = dirname(dockerLog);+ const template = join(dir, "container.json.tpl");+ const original = readFileSync(template, "utf8");+ const container = JSON.parse(original);+ container[0].Config.Labels[VPS_ENVIRONMENT_LABEL] = loadEnvironmentId(join(home, ".openmausbot"));+ const running = () => writeFileSync(template, JSON.stringify(container));+ const downA = join(dir, "unreachable.production-vps");+ const downB = join(dir, "unreachable.alpha-vps");+ try {+ expect((await api("PUT", "/api/config", { vps: { sshAlias: "production-vps" } })).status).toBe(200);+ expect((await api("PATCH", "/api/config", { vpsIdle: { timeoutMinutes: TEST_IDLE_MINUTES } })).status).toBe(200);+ const { bot } = (await api("POST", "/api/bots")).body;+ const path = `/api/bots/${bot.id}`;+ expect((await api("PATCH", path, { computer: "cloud", cloudBackend: "vps" })).status).toBe(200);+ const waitStoppedOnB = async (since: number, label: string) => {+ await until(async () => {+ const log = readFileSync(dockerLog, "utf8").slice(since);+ const stopAt = log.indexOf(`ssh://alpha-vps stop ${CONTAINER_ID}`);+ return stopAt >= 0 && log.slice(stopAt).includes(`ssh://alpha-vps inspect ${vpsContainerName(bot.id)}`)+ && (await api("GET", `${path}/computer`)).body.container === "stopped";+ }, label, 10_000);+ };++ running();+ let since = readFileSync(dockerLog, "utf8").length;+ expect((await api("POST", `${path}/computer/join?threadId=${bot.threadId}`, {})).status).toBe(200);+ writeFileSync(downA, "");+ expect((await api("PATCH", path, { vpsAlias: "alpha-vps" })).status).toBe(200);+ expect((await api("POST", `${path}/computer/viewer-close?threadId=${bot.threadId}`, {})).status).toBe(200);+ await waitStoppedOnB(since, "idle stop on B without starting B after the move");+ rmSync(downA, { force: true });++ running();+ expect((await api("POST", `${path}/computer/provision`, {})).status).toBe(200);+ writeFileSync(downB, "");+ expect((await api("PATCH", path, { vpsAlias: null })).status).toBe(200);+ rmSync(downB, { force: true });+ expect((await api("POST", `${path}/computer/join?threadId=${bot.threadId}`, {})).status).toBe(200);+ since = readFileSync(dockerLog, "utf8").length;+ writeFileSync(downA, "");+ expect((await api("PATCH", path, { vpsAlias: "alpha-vps" })).status).toBe(200);+ expect((await api("POST", `${path}/computer/viewer-close?threadId=${bot.threadId}`, {})).status).toBe(200);+ await waitStoppedOnB(since, "idle stop on B after visiting A and returning");+ rmSync(downA, { force: true });++ writeFileSync(downB, "");+ expect((await api("PATCH", path, { vpsAlias: null })).status).toBe(200);+ rmSync(downB, { force: true });+ running();+ expect((await api("POST", `${path}/computer/join?threadId=${bot.threadId}`, {})).status).toBe(200);+ since = readFileSync(dockerLog, "utf8").length;+ writeFileSync(downA, "");+ expect((await api("PUT", "/api/config", { vps: { sshAlias: "alpha-vps" } })).status).toBe(200);+ expect((await api("POST", `${path}/computer/viewer-close?threadId=${bot.threadId}`, {})).status).toBe(200);+ await waitStoppedOnB(since, "idle stop on B after default-server switch");+ } finally {+ rmSync(downA, { force: true });+ rmSync(downB, { force: true });+ writeFileSync(template, original);+ await api("PATCH", "/api/config", { vpsIdle: { timeoutMinutes: 480 } });+ writeFileSync(downB, "");+ await api("PUT", "/api/config", { vps: { sshAlias: "production-vps" } });+ rmSync(downB, { force: true });+ }+ }, 45_000);it("recovers a transient VPS inspection failure through the real status route without provisioning", async () => {expect((await api("PUT", "/api/config", { vps: { sshAlias: "production-vps" } })).status).toBe(200);