Skip to content

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

Restart VPS idle window when a viewer tunnel expires or drops

Lin8673c29108d2
diff --git a/server/index.ts b/server/index.ts
index 3b4020f1d8..60062d1a9a 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -14946,7 +14946,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, 415, { error: "content-type must be application/json" });
}
const closedViewers = auth.kind === "session" ? desktopViewer.closeForOwner(auth.session.id, bot.id) : 0;
- if (bot.cloudBackend === "vps") return json(res, 200, vps.closeVpsDesktopTunnel(bot.id, () => touchVpsIdle(bot)));
+ if (bot.cloudBackend === "vps") return json(res, 200, vps.closeVpsDesktopTunnel(bot.id));
return json(res, 200, { closed: closedViewers > 0 });
}
m = path.match(/^\/api\/bots\/([\w-]+)\/computer\/(provision|join|sleep|exec|screenshot|remove)$/);
@@ -15012,7 +15012,9 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
if (m[2] === "join") {
const remote = auth.kind !== "loopback";
- const result = await vps.vpsComputerJoin(vpsConfigForBot(cfg, bot), botId, undefined, remote);
+ const result = await vps.vpsComputerJoin(vpsConfigForBot(cfg, bot), botId, undefined, remote, () => {
+ if (vpsIdles.has(botId)) touchVpsIdle(bot);
+ });
touchVpsIdle(bot);
return json(res, 200, { ...result, joinUrl: remote
? desktopViewerUrl(`vps/${botId}`, bot.threadId) : result.joinUrl });
diff --git a/server/vps-computer.test.ts b/server/vps-computer.test.ts
index 9cc3cd4b1a..8b556b4043 100644
--- a/server/vps-computer.test.ts
+++ b/server/vps-computer.test.ts
@@ -1245,10 +1245,10 @@ describe("remote desktop tunnel ownership", () => {
} };
}
- async function openFixture() {
+ async function openFixture(onViewerClosed?: () => void) {
const { children, runner, cleanup } = tunnelFixture();
try {
- await vpsComputerJoin(CONFIG, BOT_ID, runner, true);
+ await vpsComputerJoin(CONFIG, BOT_ID, runner, true, onViewerClosed);
return { child: children[0]!, runner };
} catch (error) { cleanup(); throw error; }
}
@@ -1286,13 +1286,15 @@ describe("remote desktop tunnel ownership", () => {
it("ignores an old tunnel's queued expiry and close after replacement", async () => {
const { children, runner, cleanup } = tunnelFixture();
const timers = vi.spyOn(globalThis, "setTimeout");
+ const closed = vi.fn();
try {
- await vpsComputerJoin(CONFIG, BOT_ID, runner, true);
+ await vpsComputerJoin(CONFIG, BOT_ID, runner, true, closed);
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(closed).not.toHaveBeenCalled();
expect(vpsDesktopConnection(BOT_ID)?.live()).toBe(true);
expect(children[1]!.killed).toBe(false);
} finally { timers.mockRestore(); cleanup(); }
@@ -1359,15 +1361,35 @@ describe("remote desktop tunnel ownership", () => {
expect(child.kill).toHaveBeenCalledTimes(1);
} finally { closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
});
- it("waits a full idle window after a short desktop view closes", async () => {
- await openFixture();
+ it.each(["grace expiry", "SSH exit"])("renews the full VPS idle window after %s", async (end) => {
+ const stop = vi.fn(async () => {});
+ const timer = new ComputerIdleTimer(300_000, () => Boolean(vpsDesktopConnection(BOT_ID)), stop);
+ const { child } = await openFixture(() => timer.touch());
vi.useFakeTimers();
+ try {
+ timer.touch();
+ const release = vpsDesktopConnection(BOT_ID)!.retain();
+ await vi.advanceTimersByTimeAsync(240_000);
+ release();
+ if (end === "SSH exit") child.kill();
+ else await vi.advanceTimersByTimeAsync(30_000);
+ expect(vpsDesktopConnection(BOT_ID)).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(299_999);
+ expect(stop).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(stop).toHaveBeenCalledTimes(1);
+ } finally { timer.cancel(); closeAllVpsDesktopTunnels(); vi.useRealTimers(); }
+ });
+
+ it("waits a full idle window after a short desktop view closes", async () => {
const stop = vi.fn(async () => {});
const timer = new ComputerIdleTimer(1000, () => Boolean(vpsDesktopConnection(BOT_ID)), stop);
+ await openFixture(() => timer.touch());
+ vi.useFakeTimers();
try {
timer.touch();
await vi.advanceTimersByTimeAsync(400);
- expect(closeVpsDesktopTunnel(BOT_ID, () => timer.touch())).toEqual({ closed: true });
+ expect(closeVpsDesktopTunnel(BOT_ID)).toEqual({ closed: true });
await vi.advanceTimersByTimeAsync(999);
expect(stop).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
diff --git a/server/vps-computer.ts b/server/vps-computer.ts
index 5deb21e730..2becf7160d 100644
--- a/server/vps-computer.ts
+++ b/server/vps-computer.ts
@@ -84,7 +84,7 @@ 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;
-type DesktopTunnel = { child: ReturnType<typeof spawn>; joinUrl: string; expiry: ReturnType<typeof setTimeout>; viewers: number; localViewer: boolean };
+type DesktopTunnel = { onViewerClosed?: () => void; 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 }>();
@@ -240,16 +240,20 @@ function stopDesktopTunnel(botId: string, expected?: DesktopTunnel): boolean {
return true;
}
-export function closeVpsDesktopTunnel(botId: string, onClosed?: () => void) {
+function endViewerTunnel(botId: string, tunnel: DesktopTunnel): boolean {
+ if (!stopDesktopTunnel(botId, tunnel)) return false;
+ tunnel.onViewerClosed?.();
+ return true;
+}
+
+export function closeVpsDesktopTunnel(botId: string) {
const tunnel = desktopTunnels.get(botId);
if (tunnel?.viewers) {
tunnel.localViewer = false;
clearTimeout(tunnel.expiry);
return { closed: false };
}
- const closed = stopDesktopTunnel(botId);
- if (closed) onClosed?.();
- return { closed };
+ return { closed: tunnel ? endViewerTunnel(botId, tunnel) : stopDesktopTunnel(botId) };
}
export function closeAllVpsDesktopTunnels(): void {
@@ -274,7 +278,7 @@ export function vpsDesktopConnection(botId: string) {
tunnel.viewers--;
if (!tunnel.viewers && !tunnel.localViewer && desktopTunnels.get(botId) === tunnel) {
tunnel.expiry = setTimeout(() => {
- stopDesktopTunnel(botId, tunnel);
+ endViewerTunnel(botId, tunnel);
}, REMOTE_VIEWER_GRACE_MS);
tunnel.expiry.unref();
}
@@ -1064,6 +1068,7 @@ export async function vpsComputerJoin(
botId: string,
runner: VpsCommandRunner = defaultRunner,
remoteViewer = false,
+ onViewerClosed?: () => void,
): Promise<{ joinUrl: string; state: "running" }> {
cfg = snapshotVpsConfig(cfg);
const alias = vpsSshAlias(cfg);
@@ -1071,7 +1076,7 @@ export async function vpsComputerJoin(
let tunnel = desktopTunnels.get(botId);
if (tunnel && (tunnel.child.exitCode !== null || tunnel.child.killed)) {
- stopDesktopTunnel(botId, tunnel);
+ endViewerTunnel(botId, tunnel);
tunnel = undefined;
}
if (!tunnel) {
@@ -1084,11 +1089,12 @@ export async function vpsComputerJoin(
try { tunnel = await pending.promise; }
finally { if (pendingDesktopTunnels.get(botId) === pending) pendingDesktopTunnels.delete(botId); }
}
+ if (onViewerClosed) tunnel.onViewerClosed = onViewerClosed;
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 = setTimeout(() => endViewerTunnel(botId, current), tunnel.localViewer ? NATIVE_VIEWER_LIFETIME_MS : REMOTE_VIEWER_GRACE_MS);
tunnel.expiry.unref();
}
return { joinUrl: tunnel.joinUrl, state: "running" };
@@ -1134,6 +1140,7 @@ async function startDesktopTunnel(cfg: AppConfig, botId: string, alias: string,
if (active?.child === child) {
clearTimeout(active.expiry);
desktopTunnels.delete(botId);
+ active.onViewerClosed?.();
}
if (!failure) failure = stderr.trim() || `SSH viewer tunnel exited ${code ?? "without a status"}`;
});
@@ -1154,7 +1161,7 @@ async function startDesktopTunnel(cfg: AppConfig, botId: string, alias: string,
const joinUrl = `http://127.0.0.1:${localPort}/vnc.html#autoconnect=true&resize=scale&password=${encodeURIComponent(connection.password)}`;
const tunnel: DesktopTunnel = {
child, joinUrl, viewers: 0, localViewer: false,
- expiry: setTimeout(() => stopDesktopTunnel(botId, tunnel), REMOTE_VIEWER_GRACE_MS),
+ expiry: setTimeout(() => endViewerTunnel(botId, tunnel), REMOTE_VIEWER_GRACE_MS),
};
tunnel.expiry.unref();
desktopTunnels.set(botId, tunnel);