Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(local-vm): preserve user-installed apps across updates (#3812)
Ahmar Hussain8119d0865067
diff --git a/server/config.ts b/server/config.tsindex 660aba6e5d..b7a8bfb0fc 100644--- a/server/config.ts+++ b/server/config.ts@@ -105,6 +105,7 @@ const localVmConfigSchema = z.object({.min(MIN_LOCAL_VM_IDLE_TIMEOUT_MINUTES).max(MAX_LOCAL_VM_IDLE_TIMEOUT_MINUTES).optional(),+ preserveInstalledApps: z.boolean().optional(),});/** A named browser session; its id names a durable Electron partition. */const browserProfileSchema = z.object({@@ -519,7 +520,7 @@ export interface AppConfig extends HelperConfig {threads?: { maxConcurrentPerBot: number; eventLogMaxBytes?: number; eventLogRetentionDays?: number };context?: { rebuildBytes?: number; compactAt?: number; autoCompact?: boolean; roomCompactAt?: number; roomSessions?: boolean; replayToolHistory?: boolean };memory?: { captureQuietMs?: number; tidyHour?: number };- localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number };+ localVm?: { mode?: "shared" | "per-bot" | "pool"; maxInstances?: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean };features?: { skillAuthoring?: boolean; skillReview?: boolean; skillReviewSteps?: number; showToolCalls?: boolean; browser?: boolean; sharedComputers?: boolean; claudeUserMcp?: boolean; claudeUserSkills?: boolean; llmThreadTitles?: boolean; smartSetupChoices?: boolean; autoRecall?: boolean; skillsLibrary?: boolean; shareLearnedSkills?: "off" | "ask" | "auto"; roomMemoryCapture?: boolean; parallelRoomJobs?: boolean; chiefEscalations?: boolean; acpPlanLines?: boolean; agentsToolBridge?: boolean };onboarding?: { completedAt?: string; version?: number; reelSeen?: boolean; hintsSeen?: string[]; firstTurnAt?: string };browserProfiles?: BrowserProfile[];@@ -665,6 +666,11 @@ export function localVmIdleTimeoutMinutes(cfg: AppConfig): number {return cfg.localVm?.idleTimeoutMinutes ?? DEFAULT_LOCAL_VM_IDLE_TIMEOUT_MINUTES;}+/** App preservation is deliberately opt-in: a normal image replacement keeps its existing small, predictable footprint. */+export function localVmPreservesInstalledApps(cfg: AppConfig): boolean {+ return cfg.localVm?.preserveInstalledApps === true;+}+export function skillAuthoringEnabled(cfg: AppConfig): boolean {return cfg.features?.skillAuthoring !== false;}diff --git a/server/container-workspace.ts b/server/container-workspace.tsindex d31999b7c3..ecada14d18 100644--- a/server/container-workspace.ts+++ b/server/container-workspace.ts@@ -4,7 +4,8 @@ export function workspacePreparationDockerfile(workspace: string): string {'set -eu' \\'workspace=${workspace}' \\'profiles="$workspace/.browser-profiles"' \\- 'mkdir -p "$profiles/google-chrome" "$profiles/chromium" "$profiles/mozilla" "$HOME/.config" "$HOME/.cache"' \\+ 'apps="$workspace/.desktop-apps"' \\+ 'mkdir -p "$profiles/google-chrome" "$profiles/chromium" "$profiles/mozilla" "$apps/local" "$HOME/.config" "$HOME/.cache"' \\'if ! chmod 0700 "$workspace" "$profiles" "$profiles/google-chrome" "$profiles/chromium" "$profiles/mozilla" 2>/dev/null; then' \\' for directory in "$workspace" "$profiles" "$profiles/google-chrome" "$profiles/chromium" "$profiles/mozilla"; do' \\' test -r "$directory" && test -w "$directory" && test -x "$directory"' \\@@ -22,6 +23,11 @@ export function workspacePreparationDockerfile(workspace: string): string {'migrate_profile "$HOME/.config/google-chrome" google-chrome' \\'migrate_profile "$HOME/.config/chromium" chromium' \\'migrate_profile "$HOME/.mozilla" mozilla' \\+ 'if [ -d "$HOME/.local" ] && [ ! -L "$HOME/.local" ] && [ -z "$(find "$apps/local" -mindepth 1 -print -quit)" ]; then' \\+ ' cp -a "$HOME/.local"/. "$apps/local"/' \\+ 'fi' \\+ 'rm -rf "$HOME/.local"' \\+ 'ln -s "$apps/local" "$HOME/.local"' \\'container_start="$(cat /proc/sys/kernel/random/boot_id):$(sed "s/.*) //" /proc/1/stat | cut -d " " -f20)"' \\'prepared="$HOME/.cache/openmausbot-browser-locks"' \\'if [ "$(cat "$prepared" 2>/dev/null || true)" != "$container_start" ]; then' \\diff --git a/server/desktop-updates.test.ts b/server/desktop-updates.test.tsindex 74efb60447..9ebadcac85 100644--- a/server/desktop-updates.test.ts+++ b/server/desktop-updates.test.ts@@ -52,6 +52,7 @@ describe("createLocalVmUpdater", () => {return current;},keepSignIns: async () => { calls.push(`keep (lifecycle busy: ${lifecycleBusy.has(target.key)}, provision busy: ${provisionBusy})`); return "rescued"; },+ keepApps: async () => "none",imageBusy: { get: () => imageBusy, set: (busy) => { imageBusy = busy; } },provisionBusy: { get: () => provisionBusy, set: (busy) => { provisionBusy = busy; } },lifecycleBusy,diff --git a/server/desktop-updates.ts b/server/desktop-updates.tsindex bfb045a6cc..8e50dd2cfe 100644--- a/server/desktop-updates.ts+++ b/server/desktop-updates.ts@@ -11,7 +11,7 @@ import {type LocalVmTarget,} from "./container-computer.ts";import { discoverExistingPerBotLocalVms, discoverExistingPoolLocalVms, shouldArmLocalVmIdle, type LocalVmInventoryBot } from "./local-vm-inventory.ts";-import { keepFirefoxProfileBeforeRemove } from "./local-vm-profiles.ts";+import { keepFirefoxProfileBeforeRemove, keepInstalledAppsBeforeRemove } from "./local-vm-profiles.ts";export type LocalVmUpdateNeed = "image" | "recreate";@@ -64,6 +64,7 @@ export interface LocalVmUpdaterDeps {inUse(target: LocalVmTarget): boolean;updated(target: LocalVmTarget, status: ContainerComputerStatus): void;keepSignIns?: typeof keepFirefoxProfileBeforeRemove;+ keepApps?: typeof keepInstalledAppsBeforeRemove;workspaceExists?(target: LocalVmTarget): boolean;pollMs?: number;/** How long a turn that needs the desktop waits for its update. */@@ -93,6 +94,7 @@ export function createLocalVmUpdater(deps: LocalVmUpdaterDeps) {const pollMs = deps.pollMs ?? 1_000;const waitMs = deps.waitMs ?? Math.max(1_000, Number(process.env.OMB_LOCAL_VM_UPDATE_WAIT_MS) || 20 * 60_000);const keepSignIns = deps.keepSignIns ?? keepFirefoxProfileBeforeRemove;+ const keepApps = deps.keepApps ?? keepInstalledAppsBeforeRemove;const workspaceExists = deps.workspaceExists ?? localVmWorkspaceExists;let image: Promise<void> | null = null;const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));@@ -148,6 +150,7 @@ export function createLocalVmUpdater(deps: LocalVmUpdaterDeps) {status = await deps.status(target);if (status.container === "missing" || !status.managed || status.imageMatches) return;await keepSignIns(target, status, () => deps.act("stop", target));+ await keepApps(target, { ...status, container: "stopped" }, () => deps.act("stop", target));await deps.act("remove", target);status = await deps.act("run", target);} finally {diff --git a/server/index.ts b/server/index.tsindex 3010234912..4737732052 100644--- a/server/index.ts+++ b/server/index.ts@@ -153,6 +153,7 @@ import {localVmIdleTimeoutMinutes,localVmMaxInstances,localVmMode,+ localVmPreservesInstalledApps,roomTurnTimeoutMinutes,mcpCallTimeoutMinutes,cacheKeepWarmSettings,@@ -416,6 +417,7 @@ import { desktopComputer, thisComputerNotReady } from "./desktop-computer.ts";import { askToUseYourComputer, cancelYourComputerAsks, dismissStaleYourComputerCards, yourComputerCallFrom, yourComputerWaiting } from "./your-computer-consent.ts";import { discoverExistingPerBotLocalVms, localVmInventoryEntry } from "./local-vm-inventory.ts";import { createLocalVmUpdater, LOCAL_VM_UPDATING_PROBLEM, recoverLocalVms, VPS_OUTDATED_HINT, vpsDesktopOutdated, withoutHostWhileUpdating } from "./desktop-updates.ts";+import { keepInstalledAppsBeforeRemove } from "./local-vm-profiles.ts";import { localVmStopReason, recordLocalVmIdleStop } from "./local-vm-stop-reason.ts";import { ComputerIdleTimer } from "./computer-idle.ts";import { createCloudComputerPower } from "./host/cloud-computer-power.ts";@@ -5704,6 +5706,9 @@ const localVmUpdates = createLocalVmUpdater({lifecycleBusy: localVmLifecycleBusy,inUse: (target) => localVmModeChangeBusy || localVmActiveThreads.has(target.key) || Boolean(localVmLeaseFor(target).current(localVmOwnerBusy)),updated: (target, status) => { noteLocalVmSeen(target, status); localVmIdleFor(target).touch(); },+ keepApps: async (target, status, stop) => localVmPreservesInstalledApps(cfg)+ ? keepInstalledAppsBeforeRemove(target, status, stop)+ : "none",log: (message) => console.warn(message),});/** A turn that needs its desktop waits out the one-time update with one plain line, rather than fail or move elsewhere. */@@ -11945,6 +11950,7 @@ function configStatus() {mode: localVmMode(cfg),maxInstances: localVmMaxInstances(cfg),idleTimeoutMinutes: localVmIdleTimeoutMinutes(cfg),+ preserveInstalledApps: localVmPreservesInstalledApps(cfg),},features: {skillAuthoring: skillAuthoringEnabled(cfg),diff --git a/server/local-vm-browser-profiles.test.ts b/server/local-vm-browser-profiles.test.tsindex a7a5049fed..3208310574 100644--- a/server/local-vm-browser-profiles.test.ts+++ b/server/local-vm-browser-profiles.test.ts@@ -7,7 +7,7 @@ import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { VM_WORKSPACE_GUEST, managedImageDockerfile, type LocalVmTarget } from "./container-computer.ts";-import { rescueFirefoxProfile } from "./local-vm-profiles.ts";+import { rescueFirefoxProfile, rescueInstalledApps } from "./local-vm-profiles.ts";const temporary: string[] = [];afterEach(() => {@@ -56,6 +56,17 @@ describe.skipIf(process.platform === "win32")("the image's start-up script keeps// Chrome and Chromium keep working as before.expect(readlinkSync(join(home, ".config", "google-chrome"))).toBe(join(workspace, ".browser-profiles", "google-chrome"));expect(readlinkSync(join(home, ".config", "chromium"))).toBe(join(workspace, ".browser-profiles", "chromium"));+ expect(readlinkSync(join(home, ".local"))).toBe(join(workspace, ".desktop-apps", "local"));+ });++ it("keeps a user-installed desktop app across a new VM image", () => {+ const dir = scratch();+ const home = join(dir, "home");+ const workspace = join(dir, "workspace");+ mkdirSync(join(workspace, ".desktop-apps", "local", "share", "applications"), { recursive: true });+ writeFileSync(join(workspace, ".desktop-apps", "local", "share", "applications", "example.desktop"), "[Desktop Entry]");+ runPrepare(prepareScript(dir, workspace), home);+ expect(readFileSync(join(home, ".local", "share", "applications", "example.desktop"), "utf8")).toBe("[Desktop Entry]");});it("keeps a durable profile over the image's empty one and clears the old desktop's Firefox locks", () => {@@ -135,6 +146,31 @@ cp -RP "${container}$src" "$3"const target = (workspaceDir: string): LocalVmTarget => ({ key: "bot:x", containerName: "openmausbot-computer-x", workspaceDir, viewerPort: null, label: "x" });describe.skipIf(process.platform === "win32")("rescueFirefoxProfile", () => {+ it("copies user-installed desktop apps into the durable area before replacement", async () => {+ const dir = scratch();+ const container = join(dir, "container");+ mkdirSync(join(container, "home", "cua", ".local", "share", "applications"), { recursive: true });+ writeFileSync(join(container, "home", "cua", ".local", "share", "applications", "example.desktop"), "[Desktop Entry]");+ const workspace = join(dir, "workspace");+ mkdirSync(workspace);+ expect(await rescueInstalledApps(fakeRuntime(dir, container).runtime, target(workspace))).toBe("rescued");+ expect(readFileSync(join(workspace, ".desktop-apps", "local", "share", "applications", "example.desktop"), "utf8")).toBe("[Desktop Entry]");+ });++ it("refuses to replace a different durable app area", async () => {+ const dir = scratch();+ const container = join(dir, "container");+ mkdirSync(join(container, "home", "cua", ".local", "share", "applications"), { recursive: true });+ writeFileSync(join(container, "home", "cua", ".local", "share", "applications", "example.desktop"), "old desktop");+ const workspace = join(dir, "workspace");+ mkdirSync(join(workspace, ".desktop-apps", "local", "share", "applications"), { recursive: true });+ const durable = join(workspace, ".desktop-apps", "local", "share", "applications", "example.desktop");+ writeFileSync(durable, "durable desktop");++ await expect(rescueInstalledApps(fakeRuntime(dir, container).runtime, target(workspace)))+ .rejects.toThrow(/durable app area differs/);+ expect(readFileSync(durable, "utf8")).toBe("durable desktop");+ });it("copies an old desktop's Firefox profile into the workspace before the desktop is removed", async () => {const dir = scratch();const container = join(dir, "container");diff --git a/server/local-vm-profiles.ts b/server/local-vm-profiles.tsindex f56c6efb67..9a0594c607 100644--- a/server/local-vm-profiles.ts+++ b/server/local-vm-profiles.ts@@ -12,6 +12,7 @@ import { augmentedPath, resolveCliSpawn } from "./env-path.ts";const run = promisify(execFile);const PROFILE_IN_CONTAINER = "/home/cua/.mozilla";+const APPS_IN_CONTAINER = "/home/cua/.local";// docker: "Could not find the file … in container"; podman: "… could not be found on container …: no such file or directory".const NOT_IN_CONTAINER = /could not (?:be )?f(?:ou|i)nd|no such file/iu;@@ -63,3 +64,48 @@ export async function keepFirefoxProfileBeforeRemove(if (status.container === "running") await stop();return rescueFirefoxProfile(status.runtime, target);}++/** User-installed desktop applications conventionally live in ~/.local. Rescue that directory before replacing a legacy+ * Local VM, but never overwrite an application area the durable folder already owns. */+export async function rescueInstalledApps(runtime: string, target: LocalVmTarget): Promise<"rescued" | "kept" | "none"> {+ const apps = join(target.workspaceDir, ".desktop-apps");+ const durable = join(apps, "local");+ await mkdir(apps, { recursive: true, mode: 0o700 });+ const existing = await lstat(durable).catch(() => null);+ const staging = join(apps, `.local-rescue-${randomBytes(6).toString("hex")}`);+ try {+ const { command, args } = resolveCliSpawn(runtime, ["cp", `${target.containerName}:${APPS_IN_CONTAINER}`, staging]);+ try {+ await run(command, args, { timeout: 5 * 60_000, maxBuffer: 1024 * 1024, env: { ...process.env, PATH: augmentedPath() } });+ } catch (error) {+ const failure = error as { stderr?: string; message?: string };+ if (NOT_IN_CONTAINER.test(`${failure.stderr ?? ""} ${failure.message ?? ""}`)) return "none";+ throw new Error(`could not copy installed desktop apps: ${(failure.stderr || failure.message || String(error)).trim().slice(0, 300)}`);+ }+ const copied = await lstat(staging);+ if (!copied.isDirectory()) return "none";+ if (existing && !(existing.isDirectory() && await isEmptyDirectory(durable))) {+ try {+ await run("/usr/bin/diff", ["-qr", staging, durable], { timeout: 5 * 60_000, maxBuffer: 1024 * 1024 });+ } catch {+ throw new Error("could not preserve installed desktop apps because the durable app area differs from the old desktop");+ }+ return "kept";+ }+ if (existing) await rmdir(durable);+ await rename(staging, durable);+ return "rescued";+ } finally {+ await rm(staging, { recursive: true, force: true });+ }+}++export async function keepInstalledAppsBeforeRemove(+ target: LocalVmTarget,+ status: Pick<ContainerComputerStatus, "runtime" | "container" | "managed" | "imageMatches">,+ stop: () => Promise<unknown>,+): Promise<"rescued" | "kept" | "none"> {+ if (!status.runtime || status.container === "missing" || !status.managed || status.imageMatches) return "none";+ if (status.container === "running") await stop();+ return rescueInstalledApps(status.runtime, target);+}diff --git a/server/testing/group-local-vm-hooks.mjs b/server/testing/group-local-vm-hooks.mjsindex 542633cdf7..4a2d5da519 100644--- a/server/testing/group-local-vm-hooks.mjs+++ b/server/testing/group-local-vm-hooks.mjs@@ -31,6 +31,14 @@ registerHooks({if (status.container === 'running') await stop();return rescueFirefoxProfile(status.runtime, target);}+ export async function keepInstalledAppsBeforeRemove(target, status, _stop) {+ if (!status.runtime || status.container === 'missing' || !status.managed || status.imageMatches) return 'none';+ const state = JSON.parse(readFileSync(file, 'utf8'));+ if (state.failAppRescue) throw new Error("could not copy installed desktop apps: fixture refused");+ state.appRescues = [...(state.appRescues ?? []), target.key];+ writeFileAtomic(file, JSON.stringify(state), { durable: false });+ return 'rescued';+ }` };if (url === mock) return { format: 'module', shortCircuit: true, source: `export * from ${JSON.stringify(actual)};diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex b89c59bee7..292f71a02b 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -56,7 +56,7 @@ export interface ConfigStatus {automaticRecovery?: { enabled: boolean; backup?: ModelSelection };/** Prompt-cache keep-warm for idle Claude threads. Absent from older servers. */cacheKeepWarm?: { enabled: boolean; windowMinutes: number };- localVm: { mode: "shared" | "per-bot" | "pool"; maxInstances: number; idleTimeoutMinutes?: number };+ localVm: { mode: "shared" | "per-bot" | "pool"; maxInstances: number; idleTimeoutMinutes?: number; preserveInstalledApps?: boolean };/** `providerKeys`: names of the keys saved for OpenCode's other* providers, never the keys. */opencodeGo?: SavedKey & { providerKeys?: string[] };