Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(vps): only skip the alias-change check when SSH itself fails
AdityaUmale6b811ef341d0
diff --git a/server/cloud-backend.ts b/server/cloud-backend.tsindex b74507f4f2..4b5e4b52d4 100644--- a/server/cloud-backend.ts+++ b/server/cloud-backend.ts@@ -21,7 +21,8 @@ export function vpsAliasLeftBehindNotice(done: "Saved" | "Removed", alias: strin`When ${alias} is back, list them with: docker -H ssh://${alias} ps -a --filter ${environmentFilter} ` +`and remove any you no longer need with: docker -H ssh://${alias} rm -f <name>. ` +`Computers made by older versions have no installation label: docker -H ssh://${alias} ps -a --filter ${managedFilter} lists every managed one, ` +- `so remove one of those only once you know it is this installation's (named openmausbot-vps-<bot>-… for one of its bots).`;+ `so remove one of those only when you have its exact name from this installation, such as the one in a bot's move or delete notice. ` ++ `A name that only starts with openmausbot-vps- does not prove it is this installation's: if you have nothing more, leave it.`;}/** Why a bot that gets its cloud computer from Boat can't have one while a self-hosted VPS is saved but not chosen for it. */diff --git a/server/index.test.ts b/server/index.test.tsindex 50c0809efc..d0b86e19bb 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -11157,6 +11157,7 @@ describe("harness HTTP API", () => {expect(cleared.body.notice).toContain(`docker -H ssh://fixture-vps ps -a --filter label=com.openmausbot.environment=${environmentId} `);expect(cleared.body.notice).toContain("docker -H ssh://fixture-vps rm -f <name>");expect(cleared.body.notice).toContain("docker -H ssh://fixture-vps ps -a --filter label=com.openmausbot.vps=1 lists every managed one");+ expect(cleared.body.notice).toContain("does not prove it is this installation's: if you have nothing more, leave it");expect((await api("GET", "/api/config")).body.vps.sshAlias).toBe("");expect(existsSync(fakeVpsFixture)).toBe(true);} finally {diff --git a/server/routes/config.ts b/server/routes/config.tsindex 7caa3aa9b9..6a20c6d53f 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -270,6 +270,8 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {providerConfigBusy.set(true);const changingLocalVmMode = patch.localVm?.mode !== undefined && patch.localVm.mode !== localVmMode(cfg);if (changingLocalVmMode) localVmModeChangeBusy.set(true);+ // Set once the alias change is saved: every reply after that, a failed one too, must carry it.+ let savedVpsNotice: string | null = null;try {for (const provider of transitioningProviders) {const conflict = providerOperationConflict(provider);@@ -652,6 +654,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const changedEngines = new Set(changedInstanceIds(enginesBefore, engineLaunches(providerConfigs())));// Revoked before any await: a changed engine's old children are invalid at once.revokeEngineCapabilities(changedEngines);+ if (vpsLeftOn) savedVpsNotice = vpsAliasLeftBehindNotice(nextVpsAlias ? "Saved" : "Removed", vpsLeftOn, `label=${vps.VPS_ENVIRONMENT_LABEL}=${vps.vpsEnvironmentId()}`, `label=${vps.VPS_MANAGED_LABEL}=1`);// Commit failures wait until every mandatory effect has run: no journal failure may leave a bearer or stale engines active.const finalized = await finalizeBrowserCleanupMutation({requests: browserCleanupRequests,@@ -687,10 +690,12 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {finalized.acknowledgements.every(Boolean),removedBrowserProfileIds.length === 1 ? "The browser profile" : "The browser profiles",);- return json(res, 200, {- ...(configForAccess(finalized.value, auth) as object),- ...(vpsLeftOn ? { notice: vpsAliasLeftBehindNotice(nextVpsAlias ? "Saved" : "Removed", vpsLeftOn, `label=${vps.VPS_ENVIRONMENT_LABEL}=${vps.vpsEnvironmentId()}`, `label=${vps.VPS_MANAGED_LABEL}=1`) } : {}),- });+ return json(res, 200, { ...(configForAccess(finalized.value, auth) as object), ...(savedVpsNotice ? { notice: savedVpsNotice } : {}) });+ } catch (error) {+ if (!savedVpsNotice) throw error;+ // The alias change is already saved, so this reply is the only place left to say what the old server may still hold.+ const status = typeof (error as { status?: unknown }).status === "number" ? (error as { status: number }).status : 500;+ return json(res, status, { error: error instanceof Error ? error.message : String(error), notice: savedVpsNotice });} finally {for (const provider of transitioningProviders) computerProviderConfigTransitions.delete(provider);if (changingLocalVmMode) localVmModeChangeBusy.set(false);diff --git a/server/vps-command.ts b/server/vps-command.tsindex 04c3cdbc03..d0c8278b23 100644--- a/server/vps-command.ts+++ b/server/vps-command.ts@@ -21,6 +21,12 @@ export type VpsCommandRunner = (const STREAM_CAP_CHARS = 16 * 1024 * 1024;+/** SSH never got through (or the command ran out of time): unlike a Docker refusal, nothing on the host answered. */+export class VpsHostUnreachableError extends Error {}++// OpenSSH exits 255 for its own failures; Docker's SSH transport quotes that status when the connection drops.+const SSH_EXIT_255 = /exit(?:ed with exit)? status 255\b/i;+function tailCollector() {const chunks: string[] = [];let total = 0;@@ -46,8 +52,11 @@ export async function defaultRunner(args: string[], options: VpsCommandOptions =let deadline = Date.now() + (options.timeoutMs ?? 120_000);const destination = args[0] === "-H" && args[1]?.startsWith("ssh://") ? args[1].slice(6) : null;// Time spent waking a paused host does not count against the command's own timeout.- if (destination) deadline += await ensureVpsSshMaster(ssh, destination, Math.min(30_000, deadline - Date.now()));- if (Date.now() >= deadline) throw new Error("Docker-over-SSH command timed out");+ if (destination) {+ try { deadline += await ensureVpsSshMaster(ssh, destination, Math.min(30_000, deadline - Date.now())); }+ catch (error) { throw new VpsHostUnreachableError(error instanceof Error ? error.message : String(error)); }+ }+ if (Date.now() >= deadline) throw new VpsHostUnreachableError("Docker-over-SSH command timed out");return new Promise((resolve, reject) => {// Docker's SSH transport runs the first `ssh` on PATH: the app's shim, which shares one connection.const child = spawnCli("docker", args, {@@ -79,7 +88,7 @@ export async function defaultRunner(args: string[], options: VpsCommandOptions =};void killCliTree(child, COMMAND_TIMEOUT_TERM_GRACE_MS).then(cleaned, cleaned);};- timeout = setTimeout(() => fail(new Error("Docker-over-SSH command timed out")), Math.max(1, deadline - Date.now()));+ timeout = setTimeout(() => fail(new VpsHostUnreachableError("Docker-over-SSH command timed out")), Math.max(1, deadline - Date.now()));timeout.unref?.();child.stdout.setEncoding("utf8");@@ -101,7 +110,8 @@ export async function defaultRunner(args: string[], options: VpsCommandOptions =settle(() => {if (code === 0) return resolve({ stdout: stdout.text(), stderr: stderr.text() });const detail = stderr.text().trim().slice(-1000);- reject(new Error(detail || `Docker-over-SSH exited ${code ?? signal ?? "without a status"}`));+ const message = detail || `Docker-over-SSH exited ${code ?? signal ?? "without a status"}`;+ reject(SSH_EXIT_255.test(message) ? new VpsHostUnreachableError(message) : new Error(message));});});try {diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.tsindex 39824a8835..81ef79fecf 100644--- a/server/vps-computer.test.ts+++ b/server/vps-computer.test.ts@@ -30,6 +30,7 @@ import {MANAGED_LABEL,} from "./container-computer.ts";import { PIDS_LIMIT } from "./container-limits.ts";+import { ensureVpsSshMaster } from "./vps-ssh.ts";import type { AppConfig } from "./config.ts";import {VPS_CONTAINER_LABEL,@@ -57,6 +58,7 @@ import {reuseVps,dockerCliInstallCommand,listManagedVpsComputers,+ VpsHostUnreachableError,type VpsCommandRunner,} from "./vps-computer.ts";@@ -1376,10 +1378,18 @@ describe("a missing Docker CLI", () => {describe("a VPS inventory that fails", () => {it("is unreachable only when the host gave no list at all", async () => {const silent: VpsCommandRunner = async () => {- throw new Error("ssh: connect to host fixture port 22: Connection timed out");+ throw new VpsHostUnreachableError("ssh: connect to host fixture port 22: Connection timed out");};expect(await listManagedVpsComputers(CONFIG, [], silent)).toMatchObject({ available: false, unreachable: true });+ // SSH got through and the daemon said no: the host is there, so its computers may be too.+ const refused: VpsCommandRunner = async () => {+ throw new Error("permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock");+ };+ const refusal = await listManagedVpsComputers(CONFIG, [], refused);+ expect(refusal.available).toBe(false);+ expect(refusal.unreachable).toBeUndefined();+const garbled: VpsCommandRunner = async () => ({ stdout: "not-a-container-id\n", stderr: "" });const unverified = await listManagedVpsComputers(CONFIG, [], garbled);expect(unverified.available).toBe(false);@@ -1392,4 +1402,26 @@ describe("a VPS inventory that fails", () => {expect(both.unreachable).toBeUndefined();expect((await listManagedVpsComputers(CONFIG, [], answers)).unreachable).toBeUndefined();});++ it("tells an SSH failure from a Docker refusal on the real command path", async () => {+ try {+ mockTransport(async () => {+ throw new Error("error during connect: command [ssh -- production-vps docker system dial-stdio] has exited with exit status 255, stderr=ssh: Could not resolve hostname production-vps");+ });+ expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);++ mockTransport(async () => {+ throw new Error("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?");+ });+ const refused = await listManagedVpsComputers(CONFIG, []);+ expect(refused.available).toBe(false);+ expect(refused.unreachable).toBeUndefined();++ // Windows has no shared SSH master to check first.+ if (process.platform !== "win32") {+ vi.mocked(ensureVpsSshMaster).mockRejectedValueOnce(new Error("ssh: Could not resolve hostname production-vps"));+ expect((await listManagedVpsComputers(CONFIG, [])).unreachable).toBe(true);+ }+ } finally { spawnMock.mockReset(); }+ });});diff --git a/server/vps-computer.ts b/server/vps-computer.tsindex 2ec765e7c2..31c9d4c036 100644--- a/server/vps-computer.ts+++ b/server/vps-computer.ts@@ -23,8 +23,8 @@ import { desktopCapArgs, dockerSecurityIsHardened, type DockerHardeningConfig }import { PIDS_LIMIT, raisePidsLimit } from "./container-limits.ts";import { DATA_DIR, isValidSshAlias, vpsSshAlias, type AppConfig } from "./config.ts";import { augmentedPath } from "./env-path.ts";-import { COMMAND_TIMEOUT_KILL_GRACE_MS, defaultRunner, type VpsCommandRunner } from "./vps-command.ts";-export { defaultRunner, type VpsCommandOptions, type VpsCommandRunner } from "./vps-command.ts";+import { COMMAND_TIMEOUT_KILL_GRACE_MS, defaultRunner, VpsHostUnreachableError, type VpsCommandRunner } from "./vps-command.ts";+export { defaultRunner, VpsHostUnreachableError, type VpsCommandOptions, type VpsCommandRunner } from "./vps-command.ts";import { prepareVpsSsh } from "./vps-ssh.ts";import { loadEnvironmentId } from "./environment.ts";import { SPAWNED_PROXIES } from "./proxy-paths.ts";@@ -144,7 +144,7 @@ export interface ManagedVpsInventory {vpsAliases: string[];problem: string | null;instances: ManagedVpsInventoryInstance[];- /** Set when every host that failed gave no list at all (SSH or Docker did not answer), rather than one that could not be verified. */+ /** Set when every host that failed could not be reached over SSH or timed out, rather than one that answered with a refusal or a list that can't be verified. */unreachable?: true;}@@ -616,7 +616,7 @@ async function scanManagedVpsAlias(try {listed = await runner(vpsDockerArgs(alias, ["container", "ls", "--all", "--filter", `label=${VPS_MANAGED_LABEL}=1`, "--format", "{{.ID}}"]), { timeoutMs: 20_000 });} catch (error) {- return { ...inventoryFailure(alias, error), ...(dockerCliMissing(error) ? {} : { unreachable: true as const }) };+ return { ...inventoryFailure(alias, error), ...(error instanceof VpsHostUnreachableError ? { unreachable: true as const } : {}) };}try {const ids = [...new Set(listed.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))];diff --git a/src/components/keys/KeyPanels.tsx b/src/components/keys/KeyPanels.tsxindex bb31e5888c..0db35648ed 100644--- a/src/components/keys/KeyPanels.tsx+++ b/src/components/keys/KeyPanels.tsx@@ -157,14 +157,18 @@ export function VpsConnection() {if (saving || (!alias.trim() && !configured) || unchanged) return;setSaving(true);setError(null);- setNotice(null);api("/api/config", { method: "PUT", body: JSON.stringify({ vps: { sshAlias: alias.trim() } }) }).then(({ notice: savedNotice, ...status }: ConfigStatus & { notice?: string }) => {dispatch({ type: "configStatus", config: status });setAlias(status.vps?.sshAlias ?? "");setNotice(savedNotice ?? null);})- .catch((e) => setError(e.message))+ .catch((e) => {+ setError(e.message);+ // A save that failed after the alias changed still says what the old server may hold.+ const failedNotice = (e as { body?: { notice?: unknown } }).body?.notice;+ if (typeof failedNotice === "string") setNotice(failedNotice);+ }).finally(() => setSaving(false));};