Skip to content

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

fix(vps): share tunnel starts and initialize SSH before command bursts

Sebastian B3851f800eb82
diff --git a/docs/verification/vps-recovery.md b/docs/verification/vps-recovery.md
index edb170071c..ec31736a45 100644
--- a/docs/verification/vps-recovery.md
+++ b/docs/verification/vps-recovery.md
@@ -3,7 +3,7 @@
Run the isolated regression fixtures:
```sh
-pnpm exec vitest run server/vps-routing.test.ts server/vps-computer.test.ts server/vps-computer.runner.test.ts server/vps-ssh.test.ts server/vps-container-mcp.test.ts server/mcp-bridge.test.ts server/vps-inventory.test.ts server/kill-tree.test.ts
+pnpm exec vitest run server/vps-routing.test.ts server/vps-computer.test.ts server/vps-computer.runner.test.ts server/vps-ssh.test.ts server/vps-ssh-init.test.ts server/vps-container-mcp.test.ts server/mcp-bridge.test.ts server/vps-inventory.test.ts server/kill-tree.test.ts
```
`server/vps-routing.test.ts` launches the real server and a fake engine in a temporary home.
@@ -27,6 +27,10 @@ The other fixtures cover:
- Real disposable processes simulate Docker with a stubborn SSH child. Timeout and
stdin failure must reap the owned child, leave an unrelated detached process alone,
and allow the next command to succeed.
+- Concurrent desktop joins share one pending tunnel. Expiry and close callbacks cannot stop a replacement.
+- Close-all cancels pending desktop joins before they can publish a tunnel.
+- A synthetic SSH executable holds cold authentication while sixteen Docker commands wait.
+ Initialization failure starts no Docker work. Failed mutations are never replayed.
- OpenSSH parses paths with spaces and long data directories without contacting a VPS.
- The bot's MCP transport and watchdog use the same SSH settings as the preview.
diff --git a/server/vps-command.ts b/server/vps-command.ts
new file mode 100644
index 0000000000..5e3cd1afa5
--- /dev/null
+++ b/server/vps-command.ts
@@ -0,0 +1,111 @@
+import { DATA_DIR } from "./config.ts";
+import { augmentedPath } from "./env-path.ts";
+import { killCliTree, spawnCli } from "./procs.ts";
+import { ensureVpsSshMaster, prepareVpsSsh } from "./vps-ssh.ts";
+
+// ssh + docker need this long to tear down a remote exec over a WAN; an orphaned exec keeps the driver socket busy.
+const COMMAND_TIMEOUT_TERM_GRACE_MS = 5_000;
+// killCliTree also waits up to one second for the forced group exit.
+export const COMMAND_TIMEOUT_KILL_GRACE_MS = COMMAND_TIMEOUT_TERM_GRACE_MS + 1_000;
+
+export interface VpsCommandOptions {
+ input?: string;
+ timeoutMs?: number;
+}
+
+export type VpsCommandRunner = (
+ args: string[],
+ options?: VpsCommandOptions,
+) => Promise<{ stdout: string; stderr: string }>;
+
+const STREAM_CAP_CHARS = 16 * 1024 * 1024;
+
+function tailCollector() {
+ const chunks: string[] = [];
+ let total = 0;
+ return {
+ push(chunk: string) {
+ chunks.push(chunk);
+ total += chunk.length;
+ for (;;) {
+ const first = chunks[0];
+ if (chunks.length < 2 || first === undefined || total - first.length < STREAM_CAP_CHARS) break;
+ chunks.shift();
+ total -= first.length;
+ }
+ },
+ text(): string {
+ return chunks.join("").slice(-STREAM_CAP_CHARS);
+ },
+ };
+}
+
+export async function defaultRunner(args: string[], options: VpsCommandOptions = {}): Promise<{ stdout: string; stderr: string }> {
+ const ssh = prepareVpsSsh(DATA_DIR, augmentedPath());
+ const deadline = Date.now() + (options.timeoutMs ?? 120_000);
+ const destination = args[0] === "-H" && args[1]?.startsWith("ssh://") ? args[1].slice(6) : null;
+ if (destination) await ensureVpsSshMaster(ssh, destination, Math.min(30_000, deadline - Date.now()));
+ if (Date.now() >= deadline) throw new Error("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, {
+ shell: false,
+ env: { ...process.env, PATH: ssh.path },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ const stdout = tailCollector();
+ const stderr = tailCollector();
+ let settled = false;
+ let failure: Error | null = null;
+ let timeout: ReturnType<typeof setTimeout>;
+ const settle = (finish: () => void) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ finish();
+ };
+ const fail = (error: Error) => {
+ if (settled || failure) return;
+ failure = error;
+ clearTimeout(timeout);
+ // ssh can hold these pipes after Docker exits; stop only this command's process group (SSH masters detach from it).
+ const cleaned = () => {
+ child.stdin.destroy();
+ child.stdout.destroy();
+ child.stderr.destroy();
+ settle(() => reject(error));
+ };
+ 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.unref?.();
+
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout.push(chunk);
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr.push(chunk);
+ });
+ child.stdin.on("error", (error) => {
+ fail(new Error(`Docker-over-SSH stdin failed: ${error.message}`));
+ });
+ child.on("error", (error) => {
+ fail(new Error(`Docker-over-SSH could not start: ${error.message}`));
+ });
+ child.on("close", (code, signal) => {
+ if (failure) return;
+ 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"}`));
+ });
+ });
+ try {
+ child.stdin.end(options.input);
+ } catch (error) {
+ fail(new Error(`Docker-over-SSH stdin failed: ${error instanceof Error ? error.message : String(error)}`));
+ }
+ });
+}
diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.ts
index 4c821a85f4..e2846d1bad 100644
--- a/server/vps-computer.test.ts
+++ b/server/vps-computer.test.ts
@@ -13,6 +13,11 @@ vi.mock("node:child_process", async () => ({
spawn: spawnMock,
}));
+vi.mock("./vps-ssh.ts", async () => ({
+ ...(await vi.importActual<typeof import("./vps-ssh.ts")>("./vps-ssh.ts")),
+ ensureVpsSshMaster: vi.fn().mockResolvedValue(undefined),
+}));
+
import {
BASE_IMAGE,
BASE_IMAGE_DIGEST,
@@ -1184,24 +1189,104 @@ describe("VPS computer", () => {
// A real loopback listener stands in for SSH; no host or remote daemon is used.
describe("remote desktop tunnel ownership", () => {
- async function openFixture() {
- let server: Server | undefined;
- const child = Object.assign(new EventEmitter(), {
- exitCode: null as number | null, killed: false, stderr: new PassThrough(),
- kill: vi.fn(() => { child.killed = true; server?.close(); child.emit("close", 0); return true; }),
- });
- spawnMock.mockImplementation((_binary, args: string[]) => {
+ function tunnelFixture() {
+ const children: ReturnType<typeof fakeTunnel>[] = [];
+ function fakeTunnel(args: string[]) {
const port = Number(args[args.indexOf("-L") + 1].split(":")[1]);
- server = createServer(socket => socket.end()).listen(port, "127.0.0.1");
+ const server: Server = createServer(socket => socket.end()).listen(port, "127.0.0.1");
+ const child = Object.assign(new EventEmitter(), {
+ exitCode: null as number | null, killed: false, stderr: new PassThrough(),
+ kill: vi.fn(() => { child.killed = true; server.close(); child.emit("close", 0); return true; }),
+ });
+ return child;
+ }
+ spawnMock.mockImplementation((_binary, args: string[]) => {
+ const child = fakeTunnel(args);
+ children.push(child);
return child;
});
- const runner = fixture().runner;
+ return { children, runner: fixture().runner, cleanup: () => {
+ closeAllVpsDesktopTunnels();
+ for (const child of children) if (!child.killed) child.kill();
+ } };
+ }
+
+ async function openFixture() {
+ const { children, runner, cleanup } = tunnelFixture();
try {
await vpsComputerJoin(CONFIG, BOT_ID, runner, true);
- return { child, runner };
- } catch (error) { child.kill(); throw error; }
+ return { child: children[0]!, runner };
+ } catch (error) { cleanup(); throw error; }
}
+ it("shares one pending tunnel between concurrent remote and native joins", async () => {
+ const { children, runner, cleanup } = tunnelFixture();
+ let release!: () => void;
+ let entered!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const inspecting = new Promise<void>(resolve => { entered = resolve; });
+ let inspections = 0;
+ const blocked: VpsCommandRunner = async (args, options) => {
+ if (args[2] === "image") { inspections++; entered(); await gate; }
+ return runner(args, options);
+ };
+ try {
+ const first = vpsComputerJoin(CONFIG, BOT_ID, blocked, true);
+ await inspecting;
+ const second = vpsComputerJoin(CONFIG, BOT_ID, blocked);
+ release();
+ const joined = await Promise.all([first, second]);
+ expect(joined[0].joinUrl).toBe(joined[1].joinUrl);
+ expect(inspections).toBe(1);
+ expect(children).toHaveLength(1);
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const leave = vpsDesktopConnection(BOT_ID)!.retain();
+ leave();
+ await vi.advanceTimersByTimeAsync(30_001);
+ expect(children[0]!.killed).toBe(false);
+ closeAllVpsDesktopTunnels();
+ expect(children.every(child => child.killed)).toBe(true);
+ } finally { release(); cleanup(); vi.useRealTimers(); }
+ });
+
+ it("ignores an old tunnel's queued expiry and close after replacement", async () => {
+ const { children, runner, cleanup } = tunnelFixture();
+ const timers = vi.spyOn(globalThis, "setTimeout");
+ try {
+ await vpsComputerJoin(CONFIG, BOT_ID, runner, true);
+ const expired = timers.mock.calls.find(([, delay]) => delay === 30_000)![0] as () => void;
+ closeAllVpsDesktopTunnels();
+ await vpsComputerJoin(CONFIG, BOT_ID, runner, true);
+ expired();
+ children[0]!.emit("close", 0);
+ expect(vpsDesktopConnection(BOT_ID)?.live()).toBe(true);
+ expect(children[1]!.killed).toBe(false);
+ } finally { timers.mockRestore(); cleanup(); }
+ });
+
+ it("cancels pending joins when all tunnels close and allows a fresh join", async () => {
+ const { children, runner, cleanup } = tunnelFixture();
+ let release!: () => void;
+ let entered!: () => void;
+ const gate = new Promise<void>(resolve => { release = resolve; });
+ const inspecting = new Promise<void>(resolve => { entered = resolve; });
+ const blocked: VpsCommandRunner = async (args, options) => {
+ if (args[2] === "image") { entered(); await gate; }
+ return runner(args, options);
+ };
+ const first = vpsComputerJoin(CONFIG, BOT_ID, blocked, true);
+ const rejected = expect(first).rejects.toThrow(/closed|cancel/i);
+ try {
+ await inspecting;
+ closeAllVpsDesktopTunnels();
+ release();
+ await rejected;
+ expect(children).toHaveLength(0);
+ await expect(vpsComputerJoin(CONFIG, BOT_ID, runner, true)).resolves.toMatchObject({ state: "running" });
+ expect(children).toHaveLength(1);
+ } finally { release(); cleanup(); }
+ });
+
it("retains multiple tabs, survives reconnect, then reclaims the idle tunnel", async () => {
const { child } = await openFixture();
try {
diff --git a/server/vps-computer.ts b/server/vps-computer.ts
index e141fd08dd..dd36fa4f6b 100644
--- a/server/vps-computer.ts
+++ b/server/vps-computer.ts
@@ -24,7 +24,8 @@ import {
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 { killCliTree, spawnCli } from "./procs.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 { prepareVpsSsh } from "./vps-ssh.ts";
import { loadEnvironmentId } from "./environment.ts";
import { SPAWNED_PROXIES } from "./proxy-paths.ts";
@@ -41,10 +42,6 @@ function vpsEnvironmentId(): string {
if (!vpsEnvironmentIdCache) vpsEnvironmentIdCache = loadEnvironmentId(DATA_DIR);
return vpsEnvironmentIdCache;
}
-// ssh + docker need this long to tear down a remote exec over a WAN; an orphaned exec keeps the driver socket busy.
-const COMMAND_TIMEOUT_TERM_GRACE_MS = 5_000;
-// killCliTree also waits up to one second for the forced group exit.
-const COMMAND_TIMEOUT_KILL_GRACE_MS = COMMAND_TIMEOUT_TERM_GRACE_MS + 1_000;
const CONTAINER_NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/;
const CONTAINER_ID = /^[a-f0-9]{12,64}$/i;
@@ -86,10 +83,10 @@ const pendingScreenshots = new Map<string, Promise<VpsScreenshot>>();
const viewerConnections = new Map<string, { privateIp: string; password: string }>();
const REMOTE_VIEWER_GRACE_MS = 30_000;
const NATIVE_VIEWER_LIFETIME_MS = 8 * 60 * 60_000;
-const desktopTunnels = new Map<
- string,
- { child: ReturnType<typeof spawn>; joinUrl: string; expiry: ReturnType<typeof setTimeout>; viewers: number; localViewer: boolean }
->();
+type DesktopTunnel = { child: ReturnType<typeof spawn>; joinUrl: string; expiry: ReturnType<typeof setTimeout>; viewers: number; localViewer: boolean };
+type TunnelStart = { cancelled: boolean; child?: ReturnType<typeof spawn> };
+const desktopTunnels = new Map<string, DesktopTunnel>();
+const pendingDesktopTunnels = new Map<string, { promise: Promise<DesktopTunnel>; start: TunnelStart }>();
function invalidateVpsStatus(key: string): void {
statusCache.delete(key);
@@ -97,16 +94,6 @@ function invalidateVpsStatus(key: string): void {
pendingStatuses.delete(key);
}
-export interface VpsCommandOptions {
- input?: string;
- timeoutMs?: number;
-}
-
-export type VpsCommandRunner = (
- args: string[],
- options?: VpsCommandOptions,
-) => Promise<{ stdout: string; stderr: string }>;
-
export type VpsLifecycleAction = "provision" | "start" | "stop" | "remove";
export function vpsStartsForTurn(input: { wants: "cloud" | "vm" | "local" | "off" | undefined; autoStartVps?: boolean; automationSource?: string }): boolean {
@@ -244,9 +231,18 @@ function loopbackAnswers(port: number): Promise<boolean> {
});
}
-function stopDesktopTunnel(botId: string): boolean {
- const tunnel = desktopTunnels.get(botId);
- if (!tunnel) return false;
+function stopDesktopTunnel(botId: string, expected?: DesktopTunnel): boolean {
+ if (!expected) {
+ const pending = pendingDesktopTunnels.get(botId);
+ if (pending) {
+ pending.start.cancelled = true;
+ const child = pending.start.child;
+ if (child?.exitCode === null && !child.killed) child.kill("SIGTERM");
+ pendingDesktopTunnels.delete(botId);
+ }
+ }
+ const tunnel = expected ?? desktopTunnels.get(botId);
+ if (!tunnel || desktopTunnels.get(botId) !== tunnel) return false;
desktopTunnels.delete(botId);
clearTimeout(tunnel.expiry);
if (tunnel.child.exitCode === null && !tunnel.child.killed) tunnel.child.kill("SIGTERM");
@@ -264,7 +260,7 @@ export function closeVpsDesktopTunnel(botId: string) {
}
export function closeAllVpsDesktopTunnels(): void {
- for (const botId of desktopTunnels.keys()) stopDesktopTunnel(botId);
+ for (const botId of new Set([...desktopTunnels.keys(), ...pendingDesktopTunnels.keys()])) stopDesktopTunnel(botId);
}
export function vpsDesktopConnection(botId: string) {
@@ -285,7 +281,7 @@ export function vpsDesktopConnection(botId: string) {
tunnel.viewers--;
if (!tunnel.viewers && !tunnel.localViewer && desktopTunnels.get(botId) === tunnel) {
tunnel.expiry = setTimeout(() => {
- if (desktopTunnels.get(botId) === tunnel) stopDesktopTunnel(botId);
+ stopDesktopTunnel(botId, tunnel);
}, REMOTE_VIEWER_GRACE_MS);
tunnel.expiry.unref();
}
@@ -294,94 +290,6 @@ export function vpsDesktopConnection(botId: string) {
};
}
-const STREAM_CAP_CHARS = 16 * 1024 * 1024;
-
-function tailCollector() {
- const chunks: string[] = [];
- let total = 0;
- return {
- push(chunk: string) {
- chunks.push(chunk);
- total += chunk.length;
- for (;;) {
- const first = chunks[0];
- if (chunks.length < 2 || first === undefined || total - first.length < STREAM_CAP_CHARS) break;
- chunks.shift();
- total -= first.length;
- }
- },
- text(): string {
- return chunks.join("").slice(-STREAM_CAP_CHARS);
- },
- };
-}
-
-export function defaultRunner(args: string[], options: VpsCommandOptions = {}): Promise<{ stdout: string; stderr: string }> {
- return new Promise((resolve, reject) => {
- // Docker's SSH transport runs the first `ssh` on PATH: the app's shim, which shares one connection.
- const ssh = prepareVpsSsh(DATA_DIR, augmentedPath());
- const child = spawnCli("docker", args, {
- shell: false,
- env: { ...process.env, PATH: ssh.path },
- stdio: ["pipe", "pipe", "pipe"],
- });
- const stdout = tailCollector();
- const stderr = tailCollector();
- let settled = false;
- let failure: Error | null = null;
- let timeout: ReturnType<typeof setTimeout>;
- const settle = (finish: () => void) => {
- if (settled) return;
- settled = true;
- clearTimeout(timeout);
- finish();
- };
- const fail = (error: Error) => {
- if (settled || failure) return;
- failure = error;
- clearTimeout(timeout);
- // ssh can hold these pipes after Docker exits; stop only this command's process group (SSH masters detach from it).
- const cleaned = () => {
- child.stdin.destroy();
- child.stdout.destroy();
- child.stderr.destroy();
- settle(() => reject(error));
- };
- void killCliTree(child, COMMAND_TIMEOUT_TERM_GRACE_MS).then(cleaned, cleaned);
- };
- timeout = setTimeout(() => fail(new Error("Docker-over-SSH command timed out")), options.timeoutMs ?? 120_000);
- timeout.unref?.();
-
- child.stdout.setEncoding("utf8");
- child.stderr.setEncoding("utf8");
- child.stdout.on("data", (chunk: string) => {
- stdout.push(chunk);
- });
- child.stderr.on("data", (chunk: string) => {
- stderr.push(chunk);
- });
- child.stdin.on("error", (error) => {
- fail(new Error(`Docker-over-SSH stdin failed: ${error.message}`));
- });
- child.on("error", (error) => {
- fail(new Error(`Docker-over-SSH could not start: ${error.message}`));
- });
- child.on("close", (code, signal) => {
- if (failure) return;
- 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"}`));
- });
- });
- try {
- child.stdin.end(options.input);
- } catch (error) {
- fail(new Error(`Docker-over-SSH stdin failed: ${error instanceof Error ? error.message : String(error)}`));
- }
- });
-}
-
function emptyStatus(botId: string, alias: string | null): VpsComputerStatus {
return {
configured: Boolean(alias),
@@ -1169,20 +1077,36 @@ export async function vpsComputerJoin(
const alias = vpsSshAlias(cfg);
if (!alias) throw Object.assign(new Error("VPS is not configured"), { status: 409 });
- const existing = desktopTunnels.get(botId);
- if (existing && existing.child.exitCode === null && !existing.child.killed) {
- if (!remoteViewer) existing.localViewer = true;
- if (!existing.viewers || existing.localViewer) {
- clearTimeout(existing.expiry);
- existing.expiry = setTimeout(() => stopDesktopTunnel(botId), existing.localViewer ? NATIVE_VIEWER_LIFETIME_MS : REMOTE_VIEWER_GRACE_MS);
- existing.expiry.unref();
+ let tunnel = desktopTunnels.get(botId);
+ if (tunnel && (tunnel.child.exitCode !== null || tunnel.child.killed)) {
+ stopDesktopTunnel(botId, tunnel);
+ tunnel = undefined;
+ }
+ if (!tunnel) {
+ let pending = pendingDesktopTunnels.get(botId);
+ if (!pending) {
+ const start: TunnelStart = { cancelled: false };
+ pending = { start, promise: startDesktopTunnel(cfg, botId, alias, runner, start) };
+ pendingDesktopTunnels.set(botId, pending);
}
- return { joinUrl: existing.joinUrl, state: "running" };
+ try { tunnel = await pending.promise; }
+ finally { if (pendingDesktopTunnels.get(botId) === pending) pendingDesktopTunnels.delete(botId); }
+ }
+ if (!remoteViewer) tunnel.localViewer = true;
+ if (!tunnel.viewers || tunnel.localViewer) {
+ clearTimeout(tunnel.expiry);
+ const current = tunnel;
+ tunnel.expiry = setTimeout(() => stopDesktopTunnel(botId, current), tunnel.localViewer ? NATIVE_VIEWER_LIFETIME_MS : REMOTE_VIEWER_GRACE_MS);
+ tunnel.expiry.unref();
}
- stopDesktopTunnel(botId);
+ return { joinUrl: tunnel.joinUrl, state: "running" };
+}
+async function startDesktopTunnel(cfg: AppConfig, botId: string, alias: string, runner: VpsCommandRunner, start: TunnelStart): Promise<DesktopTunnel> {
+ const assertOpen = () => { if (start.cancelled) throw new Error("VPS desktop tunnel start was cancelled"); };
// Always re-inspect: a cached IP or password may predate a container replacement.
const status = await computeVpsComputerStatus(cfg, botId, runner);
+ assertOpen();
if (!status.ready) {
throw Object.assign(new Error(status.problem ?? "The VPS computer is not ready"), { status: 409 });
}
@@ -1195,6 +1119,7 @@ export async function vpsComputerJoin(
}
const localPort = await unusedLoopbackPort();
+ assertOpen();
const ssh = prepareVpsSsh(DATA_DIR, augmentedPath());
const child = spawn("ssh", vpsSshTunnelArgs(alias, localPort, connection.privateIp, ssh.configPath), {
shell: false,
@@ -1202,6 +1127,7 @@ export async function vpsComputerJoin(
stdio: ["ignore", "ignore", "pipe"],
windowsHide: true,
});
+ start.child = child;
let failure: string | null = null;
let stderr = "";
child.stderr?.setEncoding("utf8");
@@ -1225,17 +1151,22 @@ export async function vpsComputerJoin(
if (await loopbackAnswers(localPort)) break;
await new Promise((resolve) => setTimeout(resolve, 100));
}
- if (failure || !(await loopbackAnswers(localPort))) {
+ const ready = !failure && await loopbackAnswers(localPort);
+ if (start.cancelled || failure || !ready) {
if (child.exitCode === null && !child.killed) child.kill("SIGTERM");
+ assertOpen();
const detail = failure || stderr.trim() || "the SSH port forward did not become ready";
throw Object.assign(new Error(`Could not open the VPS live desktop: ${detail}`), { status: 502 });
}
const joinUrl = `http://127.0.0.1:${localPort}/vnc.html#autoconnect=true&resize=scale&password=${encodeURIComponent(connection.password)}`;
- const expiry = setTimeout(() => stopDesktopTunnel(botId), remoteViewer ? REMOTE_VIEWER_GRACE_MS : NATIVE_VIEWER_LIFETIME_MS);
- expiry.unref?.();
- desktopTunnels.set(botId, { child, joinUrl, expiry, viewers: 0, localViewer: !remoteViewer });
- return { joinUrl, state: "running" };
+ const tunnel: DesktopTunnel = {
+ child, joinUrl, viewers: 0, localViewer: false,
+ expiry: setTimeout(() => stopDesktopTunnel(botId, tunnel), REMOTE_VIEWER_GRACE_MS),
+ };
+ tunnel.expiry.unref();
+ desktopTunnels.set(botId, tunnel);
+ return tunnel;
}
export function vpsContainerMcpArgs(alias: string, containerName: string): string[] {
diff --git a/server/vps-container-mcp.test.ts b/server/vps-container-mcp.test.ts
index 4192fd8438..3f74064f35 100644
--- a/server/vps-container-mcp.test.ts
+++ b/server/vps-container-mcp.test.ts
@@ -54,6 +54,7 @@ describe.skipIf(process.platform === "win32")("VPS Cua MCP bridge", () => {
it("passes MCP bytes unchanged to docker exec over the validated SSH target", async () => {
const bin = await mkdtemp(join(tmpdir(), "openmausbot-vps-mcp-"));
temporary.push(bin);
+ await writeFile(join(bin, "ssh"), "#!/bin/sh\nexit 0\n", { mode: 0o700 });
const fakeDocker = join(bin, "docker");
await writeFile(fakeDocker, "#!/bin/sh\nprintf 'ARGS:%s\\n' \"$*\" >&2\ncat\n", { mode: 0o700 });
await chmod(fakeDocker, 0o700);
@@ -73,6 +74,7 @@ describe.skipIf(process.platform === "win32")("VPS Cua MCP bridge", () => {
it("survives docker closing stdin before consuming the request", async () => {
const bin = await mkdtemp(join(tmpdir(), "openmausbot-vps-mcp-"));
temporary.push(bin);
+ await writeFile(join(bin, "ssh"), "#!/bin/sh\nexit 0\n", { mode: 0o700 });
const fakeDocker = join(bin, "docker");
await writeFile(fakeDocker, "#!/bin/sh\nexit 0\n", { mode: 0o700 });
await chmod(fakeDocker, 0o700);
diff --git a/server/vps-container-mcp.ts b/server/vps-container-mcp.ts
index 74bc1d3870..f3512bbf75 100644
--- a/server/vps-container-mcp.ts
+++ b/server/vps-container-mcp.ts
@@ -3,7 +3,7 @@ import { runMcpBridge } from "./mcp-bridge.ts";
import { vpsContainerMcpArgs, vpsDockerArgs } from "./vps-computer.ts";
import { DATA_DIR } from "./config.ts";
import { augmentedPath } from "./env-path.ts";
-import { prepareVpsSsh } from "./vps-ssh.ts";
+import { ensureVpsSshMaster, prepareVpsSsh } from "./vps-ssh.ts";
const [alias, containerName] = process.argv.slice(2);
const sshAlias = alias ?? "";
@@ -20,6 +20,12 @@ const controlUrl = process.env.OMB_CONTROL_URL ?? "";
const controlToken = process.env.OMB_CONTROL_TOKEN ?? "";
const ssh = prepareVpsSsh(DATA_DIR, augmentedPath());
+try { await ensureVpsSshMaster(ssh, sshAlias); }
+catch (error) {
+ process.stderr.write(`VPS SSH initialization failed: ${error instanceof Error ? error.message : String(error)}\n`);
+ process.exit(1);
+}
+
runMcpBridge({
command: "docker",
args,
diff --git a/server/vps-routing.test.ts b/server/vps-routing.test.ts
index 7808661544..b1e111dd98 100644
--- a/server/vps-routing.test.ts
+++ b/server/vps-routing.test.ts
@@ -203,6 +203,7 @@ posixOnly("VPS turn routing e2e (fake ACP fleet + fake docker over SSH)", () =>
writeFileSync(join(fakeBin, "ssh"), `#!${process.execPath}
import { createServer } from 'node:net';
const args = process.argv.slice(2);
+if (!args.includes('-L')) process.exit(0);
const forward = args[args.indexOf('-L') + 1];
const port = Number(forward.split(':')[1]);
createServer(socket => socket.end()).listen(port, '127.0.0.1');
diff --git a/server/vps-ssh-init.test.ts b/server/vps-ssh-init.test.ts
new file mode 100644
index 0000000000..e2521a4a10
--- /dev/null
+++ b/server/vps-ssh-init.test.ts
@@ -0,0 +1,141 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createServer, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { defaultRunner } from "./vps-computer.ts";
+import { resetPathCache } from "./env-path.ts";
+
+const cleanups: (() => Promise<void>)[] = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0)) await cleanup();
+ vi.unstubAllEnvs();
+ resetPathCache();
+});
+
+async function sshFixture() {
+ const bin = mkdtempSync(join(tmpdir(), "omb-ssh-burst-"));
+ const sockets = new Set<Socket>();
+ const calls: string[][] = [];
+ const held: Socket[] = [];
+ let warm = false;
+ let failInit = false;
+ let autoInitialize = false;
+ let failCommand = false;
+ let entered!: () => void;
+ const authenticating = new Promise<void>(resolve => { entered = resolve; });
+ const respond = (socket: Socket, code: number) => socket.end(JSON.stringify({ code }));
+ const server = createServer(socket => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ let input = "";
+ socket.on("data", chunk => {
+ input += String(chunk);
+ if (!input.endsWith("\n")) return;
+ const args = JSON.parse(input) as string[];
+ calls.push(args);
+ if (args.includes("check")) { respond(socket, warm ? 0 : 255); return; }
+ if (args.at(-1) === "true") {
+ if (failInit) respond(socket, 255);
+ else if (autoInitialize) { warm = true; respond(socket, 0); }
+ else held.push(socket);
+ } else respond(socket, !warm || failCommand ? 255 : 0);
+ entered();
+ });
+ });
+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("missing fixture port");
+ const sshScript = `#!${process.execPath}
+const socket = require('node:net').createConnection(${address.port}, '127.0.0.1');
+socket.on('connect', () => socket.write(JSON.stringify(process.argv.slice(2)) + '\\n'));
+let reply = '';
+socket.on('data', chunk => reply += chunk);
+socket.on('end', () => { const { code } = JSON.parse(reply); if (code) console.error('synthetic SSH failure'); else console.log('synthetic daemon'); process.exitCode = code; });
+`;
+ writeFileSync(join(bin, "ssh"), sshScript, { mode: 0o700 });
+ writeFileSync(join(bin, "docker"), `#!${process.execPath}
+const args = process.argv.slice(2);
+const child = require('node:child_process').spawn('ssh', ['-o', 'ConnectTimeout=30', '-T', '--', args[1].slice(6), 'docker system dial-stdio', ...args.slice(2)], { stdio: 'inherit' });
+child.on('exit', code => { process.exitCode = code; });
+`, { mode: 0o700 });
+ const home = join(bin, "home");
+ mkdirSync(home);
+ vi.stubEnv("HOME", home);
+ vi.stubEnv("USERPROFILE", home);
+ vi.stubEnv("OMB_EXTRA_PATH", bin);
+ resetPathCache();
+ cleanups.push(async () => {
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ rmSync(bin, { recursive: true, force: true });
+ });
+ return {
+ calls, authenticating,
+ release: () => { warm = true; for (const socket of held.splice(0)) respond(socket, 0); },
+ failInitialization: () => { failInit = true; },
+ failCommands: () => { failCommand = true; },
+ expire: () => { warm = false; failInit = false; autoInitialize = true; },
+ };
+}
+
+const target = (alias: string, command = "info") => ["-H", `ssh://${alias}`, command];
+const commands = (calls: string[][]) => calls.filter(args => args.includes("docker system dial-stdio"));
+
+describe.skipIf(process.platform === "win32")("cold VPS SSH startup", () => {
+ it("holds a cold burst behind one authentication before releasing Docker commands", async () => {
+ const fixture = await sshFixture();
+ const burst = Promise.allSettled(Array.from({ length: 16 }, () => defaultRunner(target("cold-vps"))));
+ try {
+ await fixture.authenticating;
+ expect(commands(fixture.calls)).toHaveLength(0);
+ } finally { fixture.release(); await burst; }
+ const results = await burst;
+ expect(results.filter(result => result.status === "fulfilled")).toHaveLength(16);
+ expect(fixture.calls.filter(args => args.at(-1) === "true")).toHaveLength(1);
+ expect(commands(fixture.calls)).toHaveLength(16);
+ });
+
+ it("shares initialization failure, releases the slot, and never replays a mutation", async () => {
+ const fixture = await sshFixture();
+ fixture.failInitialization();
+ const results = await Promise.allSettled(Array.from({ length: 4 }, () => defaultRunner(target("failed-vps", "run"))));
+ expect(results.every(result => result.status === "rejected")).toBe(true);
+ expect(commands(fixture.calls)).toHaveLength(0);
+ expect(fixture.calls.filter(args => args.at(-1) === "true")).toHaveLength(1);
+ fixture.release();
+ fixture.failCommands();
+ await expect(defaultRunner(target("failed-vps", "run"))).rejects.toThrow("synthetic SSH failure");
+ expect(commands(fixture.calls)).toHaveLength(1);
+ });
+
+ it("reinitializes after a master expires without keeping a stale success", async () => {
+ const fixture = await sshFixture();
+ const first = defaultRunner(target("expiring-vps"));
+ await fixture.authenticating;
+ fixture.release();
+ await first;
+ fixture.expire();
+ await expect(defaultRunner(target("expiring-vps"))).resolves.toMatchObject({ stdout: "synthetic daemon\n" });
+ expect(fixture.calls.filter(args => args.at(-1) === "true")).toHaveLength(2);
+ expect(commands(fixture.calls)).toHaveLength(2);
+ });
+
+ it("does not let a short waiter cancel the shared initialization", async () => {
+ const fixture = await sshFixture();
+ const first = defaultRunner(target("shared-budget-vps"));
+ await fixture.authenticating;
+ try {
+ await expect(defaultRunner(target("shared-budget-vps"), { timeoutMs: 100 })).rejects.toThrow(/timed out/i);
+ expect(commands(fixture.calls)).toHaveLength(0);
+ } finally { fixture.release(); await first; }
+ expect(fixture.calls.filter(args => args.at(-1) === "true")).toHaveLength(1);
+ expect(commands(fixture.calls)).toHaveLength(1);
+ });
+
+ it("bounds a stuck initialization without launching Docker", async () => {
+ const fixture = await sshFixture();
+ await expect(defaultRunner(target("stuck-vps", "run"), { timeoutMs: 1_000 })).rejects.toThrow(/SSH|timed out/i);
+ expect(commands(fixture.calls)).toHaveLength(0);
+ });
+});
diff --git a/server/vps-ssh.test.ts b/server/vps-ssh.test.ts
index 086dc751b9..26034a9501 100644
--- a/server/vps-ssh.test.ts
+++ b/server/vps-ssh.test.ts
@@ -4,7 +4,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, st
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { prepareVpsSsh as prepare, vpsSshConfigText } from "./vps-ssh.ts";
+import { ensureVpsSshMaster, prepareVpsSsh as prepare, vpsSshConfigText } from "./vps-ssh.ts";
const dirs: string[] = [];
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
@@ -19,9 +19,10 @@ function prepareVpsSsh(...args: Parameters<typeof prepare>) {
}
describe("VPS SSH connection sharing supplied by the app", () => {
- it("does nothing on Windows, where OpenSSH has no connection sharing", () => {
+ it("does nothing on Windows, where OpenSSH has no connection sharing", async () => {
const data = scratch();
expect(prepareVpsSsh(data, "C:\\Windows\\System32", "win32")).toEqual({ configPath: null, path: "C:\\Windows\\System32" });
+ await expect(ensureVpsSshMaster({ configPath: null, path: "missing-ssh" }, "fixture-vps")).resolves.toBeUndefined();
expect(existsSync(join(data, "ssh"))).toBe(false);
});
});
@@ -70,7 +71,7 @@ describe.skipIf(process.platform === "win32")("VPS SSH connection sharing on POS
it.skipIf(!existsSync("/usr/bin/ssh"))("quotes spaces in user config and socket paths for OpenSSH", () => {
const home = scratch();
const userConfig = join(home, "my config");
- writeFileSync(userConfig, "Host fixture-vps\n HostName 192.0.2.1\n");
+ writeFileSync(userConfig, "Host fixture-vps\n HostName 192.0.2.1\n StrictHostKeyChecking yes\n BatchMode yes\n PasswordAuthentication no\n");
const config = vpsSshConfigText("/isolated/space path/100%", userConfig, join(home, "absent"));
// A real file, not /dev/stdin: spawnSync feeds stdin through a socketpair, which Linux refuses to reopen (ENXIO).
const generatedConfig = join(home, "generated config");
@@ -78,6 +79,9 @@ describe.skipIf(process.platform === "win32")("VPS SSH connection sharing on POS
const parsed = spawnSync("/usr/bin/ssh", ["-G", "-F", generatedConfig, "fixture-vps"], { encoding: "utf8" });
expect(parsed.status, parsed.stderr).toBe(0);
expect(parsed.stdout).toContain("hostname 192.0.2.1\n");
+ expect(parsed.stdout).toContain("stricthostkeychecking true\n");
+ expect(parsed.stdout).toContain("batchmode yes\n");
+ expect(parsed.stdout).toContain("passwordauthentication no\n");
expect(parsed.stdout).toContain("controlpath /isolated/space path/100%/cm-");
});
diff --git a/server/vps-ssh.ts b/server/vps-ssh.ts
index a699fa29c1..81b8a9fc72 100644
--- a/server/vps-ssh.ts
+++ b/server/vps-ssh.ts
@@ -1,4 +1,5 @@
// An ssh_config and an `ssh` shim that add connection sharing and fail-fast timeouts to every VPS command, whatever the user's alias sets.
+import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
@@ -88,3 +89,44 @@ export function prepareVpsSsh(dataDir: string, pathValue: string, platform: Node
writeIfChanged(join(binDir, "ssh"), shim, 0o700);
return { configPath, path: `${binDir}${delimiter}${pathValue}` };
}
+
+const pendingMasters = new Map<string, Promise<void>>();
+
+export async function ensureVpsSshMaster(ssh: VpsSshSetup, alias: string, timeoutMs = 30_000): Promise<void> {
+ if (!ssh.configPath) return;
+ const key = `${ssh.configPath}:${alias}`;
+ const pending = pendingMasters.get(key);
+ if (pending) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([pending, new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error("VPS SSH initialization timed out")), timeoutMs);
+ timer.unref();
+ })]);
+ } finally { clearTimeout(timer); }
+ return;
+ }
+ const deadline = Date.now() + timeoutMs;
+ const command = (args: string[]) => new Promise<void>((resolve, reject) => {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) { reject(new Error("VPS SSH initialization timed out")); return; }
+ const child = execFile("ssh", args, {
+ env: { ...process.env, PATH: ssh.path },
+ timeout: remaining,
+ killSignal: "SIGKILL",
+ maxBuffer: 64 * 1024,
+ }, error => error ? reject(error) : resolve());
+ child.stdin?.end();
+ });
+ const initialization = (async () => {
+ try { await command(["-O", "check", "--", alias]); }
+ catch (error) {
+ if ((error as { killed?: boolean }).killed) throw error;
+ // ControlMaster auto only shares after authentication. A harmless first command starts the persistent master without replaying Docker work.
+ await command(["-o", "BatchMode=yes", "-o", "PermitLocalCommand=no", "-T", "--", alias, "true"]);
+ }
+ })();
+ pendingMasters.set(key, initialization);
+ try { await initialization; }
+ finally { if (pendingMasters.get(key) === initialization) pendingMasters.delete(key); }
+}