Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
VPS computers: memory and CPU limits for the default server and each named server
Liam8eb26d79c358
diff --git a/docs/byo-vps.md b/docs/byo-vps.mdindex ce1396d9c2..042a21c733 100644--- a/docs/byo-vps.md+++ b/docs/byo-vps.md@@ -201,6 +201,12 @@ policies, including the legacy `no` policy. OpenMausBot does not reset those setcontainer to enforce its defaults. Restart behavior follows the chosen Docker policy; for example,`always` can wake a slept container after a Docker daemon restart.+Memory (2–128 GiB) and CPU cores (1–64) are set in Settings under **Self-hosted VPS**, for the default server and,+separately, for each named server; a named server that leaves a limit empty uses the default server's. A new+container takes the limits at once. A stopped one takes them when it next starts. A running container keeps+its limits until it is recreated. OpenMausBot does not check them against what the VPS has, so keep them within+the machine's memory and core count.+- **Provision** (choosing **Cloud** for the bot, or the panel's button): builds the pinned Cua image on theVPS if needed, creates the container if missing, starts it if stopped, and waits until the desktop answers.- **Start** only wakes an existing stopped container; it never creates one.diff --git a/server/config.ts b/server/config.tsindex dcbec96351..d23b8a6d18 100644--- a/server/config.ts+++ b/server/config.ts@@ -10,10 +10,11 @@ import type { ImageGenerationConfig } from "../shared/image-generation.ts";import { imageGenConfigSchema, imageGenPatchSchema, keepKeysOutOfImageModels, type ImageGenCredentialPatch } from "./image-generation-config.ts";import { botAvatarUrlSchema } from "../shared/bot-avatar.ts";import { writeFileAtomic } from "./atomic.ts";-import { isValidSshAlias, normalizeVpsConfig, storedVpsServersSchema, vpsConfigSchema, vpsServersSchema, type VpsServer } from "./vps-config.ts";+import { isValidSshAlias, normalizeVpsConfig, storedVpsServersSchema, vpsConfigSchema, vpsServersSchema, type VpsConfig, type VpsServer } from "./vps-config.ts";import { configBackupRefusal, configSaveRefusal, readConfigFile, writeConfigBackup } from "./config-backup.ts";import { defaultBotThreads, MAX_CONCURRENT_BOT_THREADS } from "./bot-thread-limits.ts";import { anthropicKeyEnv } from "./anthropic-key-env.ts";+import { DEFAULT_DESKTOP_RESOURCES, type DesktopResources } from "./container-limits.ts";import { withoutComputerEngine } from "./computer-engine-removal.ts";import { newBotDefaultsSchema, type NewBotDefaults } from "./new-bot-defaults.ts";import { replaySettings } from "./replay-settings.ts";@@ -453,8 +454,7 @@ export interface AppConfig extends HelperConfig {composio?: { apiKey?: string; userId?: string; sessionId?: string };/** Boat token (ascii.dev renamed Box to Boat); config key "box", env BOX_TOKEN. */box?: { token?: string };- /** A named host from the user's SSH config. Authentication stays with SSH. */- vps?: { sshAlias?: string };+ vps?: VpsConfig;vpsServers?: VpsServer[];opencodeGo?: { apiKey?: string; providerKeys?: Record<string, string> };tts?: { key?: string; fishKey?: string; geminiKey?: string; voice?: string; provider?: "elevenlabs" | "fish" | "system" | "chatterbox" | "xai" | "gemini" | "openai" | "deepseek"; baseUrl?: string; model?: string; fishModel?: FishTtsModel; everyReply?: boolean; hearWith?: "device" | "elevenlabs"; hearLanguage?: string };@@ -567,6 +567,13 @@ export function parseConfigPatch(value: JsonValue): ConfigPatch {return parsed.data;}+export function vpsResources(cfg: AppConfig): DesktopResources {+ return {+ memoryGb: cfg.vps?.memoryGb ?? DEFAULT_DESKTOP_RESOURCES.memoryGb,+ cpus: cfg.vps?.cpus ?? DEFAULT_DESKTOP_RESOURCES.cpus,+ };+}+export function vpsSshAlias(cfg: AppConfig): string | null {return isValidSshAlias(cfg.vps?.sshAlias) ? cfg.vps.sshAlias : null;}@@ -903,7 +910,7 @@ export function saveConfig(disk[key] = merged;}keepImageModels();- if (checkedPatch.vps !== undefined) disk.vps = normalizeVpsConfig(checkedPatch.vps);+ if (checkedPatch.vps !== undefined) disk.vps = normalizeVpsConfig(checkedPatch.vps, disk.vps);// vpsServers is kept even when empty: the running config is updated by Object.assign, which cannot drop a key.for (const key of ["language", "computerName", "everyBotRules", "vpsServers"] as const) if (checkedPatch[key] !== undefined) disk[key] = checkedPatch[key];if (checkedPatch.customDomain !== undefined) disk.customDomain = checkedPatch.customDomain;diff --git a/server/index.ts b/server/index.tsindex 8eefb28de1..e7fa27e0bb 100644--- a/server/index.ts+++ b/server/index.ts@@ -175,6 +175,7 @@ import {builtInBrowserEnabled,persistableInstanceConfigs,type AppConfig,+ vpsResources,vpsSshAlias,DATA_DIR, EVENTS_DIR,onConfigSaved,@@ -11633,7 +11634,7 @@ function configStatus() {configured: composio.configured(cfg), mode: composio.connectionMode(cfg),},box: { ...boat.describeBoatAccount(cfg), ...(boat.boatAccount(cfg)?.included ? {} : keyHint(cfg.box?.token)) },- vps: { configured: Boolean(vpsSshAlias(cfg)), sshAlias: vpsSshAlias(cfg) ?? "", servers: cfg.vpsServers ?? [] },+ vps: { configured: Boolean(vpsSshAlias(cfg)), sshAlias: vpsSshAlias(cfg) ?? "", servers: cfg.vpsServers ?? [], ...vpsResources(cfg) },opencodeGo: { ...keyStatus(cfg.opencodeGo?.apiKey), providerKeys: Object.keys(openCodeProviderKeys(cfg)) },tts: tts.describeVoice(cfg),decider: describeDecider(cfg), helpers: describeHelpers(cfg),@@ -11701,7 +11702,7 @@ function configForAccess(status: ReturnType<typeof configStatus>, admin: boolean...withoutKeyHints(status),edition: { edition: status.edition.edition, features: status.edition.features },signIn: { admins: [], members: [] }, live: liveSettingsForClient(status.live), everyBotRules: undefined,- vps: { configured: status.vps.configured, sshAlias: "", servers: [] },+ vps: { configured: status.vps.configured, sshAlias: "", servers: [], memoryGb: status.vps.memoryGb, cpus: status.vps.cpus },opencodeGo: { configured: status.opencodeGo.configured, providerKeys: [] },...(CLOUD_TEAM ? { onboarding } : {}), profile: CLOUD_TEAM ? profile : { name: profile.name, email: "", ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}) },browserProfiles: status.browserProfiles.map((profile) => Object.fromEntries(Object.entries(profile).filter(([key]) => key !== "partitionId"))),diff --git a/server/vps-computer.ts b/server/vps-computer.tsindex 31c9d4c036..032545774c 100644--- a/server/vps-computer.ts+++ b/server/vps-computer.ts@@ -20,8 +20,8 @@ import {MANAGED_LABEL,} from "./container-computer.ts";import { desktopCapArgs, dockerSecurityIsHardened, type DockerHardeningConfig } from "./container-isolation.ts";-import { PIDS_LIMIT, raisePidsLimit } from "./container-limits.ts";-import { DATA_DIR, isValidSshAlias, vpsSshAlias, type AppConfig } from "./config.ts";+import { applyResourcesBeforeStart, DEFAULT_DESKTOP_RESOURCES, PIDS_LIMIT, raisePidsLimit, resourceArgs, type DesktopResources } from "./container-limits.ts";+import { DATA_DIR, isValidSshAlias, vpsResources, vpsSshAlias, type AppConfig } from "./config.ts";import { augmentedPath } from "./env-path.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";@@ -65,7 +65,7 @@ const lifecycleLocks = new Map<string, Promise<void>>();/** The app config reloads in place: across awaits it could inspect one host and mutate another. */function snapshotVpsConfig(cfg: AppConfig): AppConfig {const sshAlias = vpsSshAlias(cfg);- return sshAlias ? { vps: { sshAlias } } : {};+ return sshAlias ? { vps: { ...cfg.vps, sshAlias } } : {};}export function vpsLifecycleBusy(): boolean {@@ -722,6 +722,7 @@ export function vpsContainerRunArgs(containerName: string,imageRef = VPS_IMAGE,viewerSecret = randomBytes(18).toString("base64url"),+ resources: DesktopResources = DEFAULT_DESKTOP_RESOURCES,): string[] {if (!CONTAINER_NAME.test(containerName) || (imageRef !== VPS_IMAGE && !IMAGE_ID.test(imageRef))) {throw new Error("invalid managed VPS container or image reference");@@ -748,12 +749,7 @@ export function vpsContainerRunArgs(`${BASE_IMAGE_LABEL}=${BASE_IMAGE_DIGEST}`,"--label",`${IMAGE_LAYER_LABEL}=${IMAGE_LAYER_VERSION}`,- "--memory",- "4g",- "--memory-swap",- "4g",- "--cpus",- "2",+ ...resourceArgs(resources, { swap: true }),"--pids-limit", String(PIDS_LIMIT),"--network","bridge",@@ -986,15 +982,19 @@ export async function vpsComputerAction(imageRef = (await computeVpsComputerStatus(cfg, botId, runner)).image_id;}if (!imageRef) throw Object.assign(new Error("The prepared VPS image could not be identified"), { status: 409 });- await run(vpsContainerRunArgs(before.container_name, imageRef));+ await run(vpsContainerRunArgs(before.container_name, imageRef, undefined, vpsResources(cfg)));} else {assertUsableContainer(before);- if (before.container === "stopped") await run(["start", containerRef]);+ if (before.container === "stopped") {+ await applyResourcesBeforeStart(containerRef, vpsResources(cfg), run);+ await run(["start", containerRef]);+ }}} else if (action === "start") {if (before.container === "missing") throw Object.assign(new Error("No VPS container exists for this bot"), { status: 409 });if (before.container === "running") throw Object.assign(new Error("The VPS container is already running"), { status: 409 });assertUsableContainer(before);+ await applyResourcesBeforeStart(containerRef, vpsResources(cfg), run);await run(["start", containerRef]);} else if (action === "remove") {// Skips the usability check (remove escapes a broken container); the ownership labels are the only gate.diff --git a/server/vps-config.ts b/server/vps-config.tsindex ad24b91715..ff18fd17ca 100644--- a/server/vps-config.ts+++ b/server/vps-config.ts@@ -1,31 +1,57 @@/** The self-hosted VPS settings: the default SSH alias (`vps`) and the named servers (`vpsServers`). */import { z } from "zod";+import { MAX_DESKTOP_CPUS, MAX_DESKTOP_MEMORY_GB, MIN_DESKTOP_CPUS, MIN_DESKTOP_MEMORY_GB } from "./container-limits.ts";+const SSH_ALIAS = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;export function isValidSshAlias(value: unknown): value is string {return typeof value === "string" && SSH_ALIAS.test(value);}-export function normalizeVpsConfig(raw: unknown): { sshAlias?: string } {+/** A named host from the user's SSH config, authentication stays with SSH. `memoryGb` (no swap beyond it, 4 when unset) and `cpus` (2 when unset) cap each bot's VPS desktop; a running desktop takes a change when it is next provisioned or started. */+export type VpsConfig = { sshAlias?: string; memoryGb?: number; cpus?: number };++/** The alias is replaced by every save; a limit the patch leaves out keeps its stored value. */+export function normalizeVpsConfig(raw: unknown, stored?: unknown): VpsConfig {if (raw === undefined || raw === null) return {};if (!raw || typeof raw !== "object" || Array.isArray(raw)) {throw new Error("vps must be an object containing an SSH config alias");}- const alias = (raw as Record<string, unknown>).sshAlias;- if (alias === undefined || alias === "") return {};- if (!isValidSshAlias(alias)) {- throw new Error("vps.sshAlias must be a simple SSH config alias (letters, numbers, dot, dash, or underscore)");+ const patch = raw as Record<string, unknown>;+ const kept = stored && typeof stored === "object" && !Array.isArray(stored) ? (stored as Record<string, unknown>) : {};+ const out: VpsConfig = {};+ const alias = patch.sshAlias;+ if (alias !== undefined && alias !== "") {+ if (!isValidSshAlias(alias)) {+ throw new Error("vps.sshAlias must be a simple SSH config alias (letters, numbers, dot, dash, or underscore)");+ }+ out.sshAlias = alias;+ }+ for (const [key, min, max] of [["memoryGb", MIN_DESKTOP_MEMORY_GB, MAX_DESKTOP_MEMORY_GB], ["cpus", MIN_DESKTOP_CPUS, MAX_DESKTOP_CPUS]] as const) {+ const value = key in patch ? patch[key] : kept[key];+ if (value === undefined) continue;+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {+ throw new Error(`vps.${key} must be a whole number from ${min} to ${max}`);+ }+ out[key] = value;}- return { sshAlias: alias };+ return out;}+const memoryGbSchema = z.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB);+const cpusSchema = z.number().int().min(MIN_DESKTOP_CPUS).max(MAX_DESKTOP_CPUS);export const vpsConfigSchema = z.object({sshAlias: z.string().refine((value) => value === "" || isValidSshAlias(value), { message: "must be a simple SSH config alias" }).optional(),+ memoryGb: memoryGbSchema.optional(),+ cpus: cpusSchema.optional(),});export const MAX_VPS_SERVERS = 20;-export interface VpsServer { name: string; sshAlias: string }+/** `memoryGb` and `cpus` cap this server's desktops; a limit left out is the default server's (`vps`). */+export interface VpsServer { name: string; sshAlias: string; memoryGb?: number; cpus?: number }export const vpsServerSchema = z.object({+ memoryGb: memoryGbSchema.optional(),+ cpus: cpusSchema.optional(),name: z.string().trim().min(1).max(60).refine((value) => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value), { message: "must be plain text" }),sshAlias: z.string().refine(isValidSshAlias, { message: "must be a simple SSH config alias" }),});diff --git a/server/vps-hosts.ts b/server/vps-hosts.tsindex 7f58a73599..56c0e5f4e6 100644--- a/server/vps-hosts.ts+++ b/server/vps-hosts.ts@@ -1,5 +1,13 @@// Which VPS host a bot's computer lives on: the app-wide SSH alias, or the bot's own.-import { isValidSshAlias, vpsSshAlias, type AppConfig } from "./config.ts";+import { isValidSshAlias, vpsSshAlias, type AppConfig, type VpsConfig } from "./config.ts";++/** A named server's own limits, each falling back to the default server's. */+export function vpsLimits(cfg: AppConfig, alias?: string | null): Pick<VpsConfig, "memoryGb" | "cpus"> {+ const own = alias ? cfg.vpsServers?.find((server) => server.sshAlias === alias) : undefined;+ const memoryGb = own?.memoryGb ?? cfg.vps?.memoryGb;+ const cpus = own?.cpus ?? cfg.vps?.cpus;+ return { ...(memoryGb ? { memoryGb } : {}), ...(cpus ? { cpus } : {}) };+}/** A bot's own SSH alias wins over the default; both are validated the same way. */export function vpsSshAliasForBot(cfg: AppConfig, bot: { vpsAlias?: string } | null | undefined): string | null {@@ -9,7 +17,7 @@ export function vpsSshAliasForBot(cfg: AppConfig, bot: { vpsAlias?: string } | n/** A config scoped to one bot's VPS alias, shaped for the vps-computer calls. */export function vpsConfigForBot(cfg: AppConfig, bot: { vpsAlias?: string } | null | undefined): AppConfig {const sshAlias = vpsSshAliasForBot(cfg, bot);- return sshAlias ? { vps: { sshAlias } } : {};+ return sshAlias ? { vps: { sshAlias, ...vpsLimits(cfg, sshAlias) } } : {};}/** Every alias this installation can hold VPS computers on: the default first, then each bot's own. */diff --git a/server/vps-resources.test.ts b/server/vps-resources.test.tsnew file mode 100644index 0000000000..08976c6705--- /dev/null+++ b/server/vps-resources.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";++import { normalizeVpsConfig, vpsResources } from "./config.ts";+import { vpsContainerRunArgs } from "./vps-computer.ts";+import { vpsConfigForBot, vpsLimits } from "./vps-hosts.ts";+import { vpsServersSchema } from "./vps-config.ts";++const NAME = "openmausbot-vps-bot-abc123";++describe("VPS desktop resources", () => {+ it("defaults to 4 GB and 2 cores", () => {+ const args = vpsContainerRunArgs(NAME);+ expect(args.slice(args.indexOf("--memory"), args.indexOf("--memory") + 5)).toEqual(["--memory", "4g", "--memory-swap", "4g", "--cpus"]);+ expect(args[args.indexOf("--cpus") + 1]).toBe("2");+ });++ it("applies the configured limits", () => {+ const args = vpsContainerRunArgs(NAME, undefined, undefined, vpsResources({ vps: { sshAlias: "v", memoryGb: 16, cpus: 6 } }));+ expect(args[args.indexOf("--memory") + 1]).toBe("16g");+ expect(args[args.indexOf("--memory-swap") + 1]).toBe("16g");+ expect(args[args.indexOf("--cpus") + 1]).toBe("6");+ });++ it("keeps stored limits when a patch carries only the alias", () => {+ expect(normalizeVpsConfig({ sshAlias: "b" }, { sshAlias: "a", memoryGb: 8, cpus: 3 })).toEqual({ sshAlias: "b", memoryGb: 8, cpus: 3 });+ });++ it("rejects out-of-range or fractional limits", () => {+ expect(() => normalizeVpsConfig({ memoryGb: 1 })).toThrow(/memoryGb/);+ expect(() => normalizeVpsConfig({ cpus: 2.5 })).toThrow(/cpus/);+ expect(() => normalizeVpsConfig({ cpus: 65 })).toThrow(/cpus/);+ });++ describe("named servers", () => {+ const cfg = {+ vps: { sshAlias: "main", memoryGb: 8, cpus: 4 },+ vpsServers: [+ { name: "Lab", sshAlias: "lab", memoryGb: 3, cpus: 2 },+ { name: "Half", sshAlias: "half", cpus: 6 },+ { name: "Plain", sshAlias: "plain" },+ ],+ };++ it("gives a named server its own limits", () => {+ expect(vpsLimits(cfg, "lab")).toEqual({ memoryGb: 3, cpus: 2 });+ });++ it("falls back to the default server's limit for each one a named server leaves out", () => {+ expect(vpsLimits(cfg, "half")).toEqual({ memoryGb: 8, cpus: 6 });+ expect(vpsLimits(cfg, "plain")).toEqual({ memoryGb: 8, cpus: 4 });+ });++ it("uses the default server's limits for the default alias and for an alias that is not listed", () => {+ expect(vpsLimits(cfg, "main")).toEqual({ memoryGb: 8, cpus: 4 });+ expect(vpsLimits(cfg, "elsewhere")).toEqual({ memoryGb: 8, cpus: 4 });+ });++ it("scopes a bot's config to its own server's limits", () => {+ expect(vpsConfigForBot(cfg, { vpsAlias: "lab" })).toEqual({ vps: { sshAlias: "lab", memoryGb: 3, cpus: 2 } });+ expect(vpsConfigForBot(cfg, undefined)).toEqual({ vps: { sshAlias: "main", memoryGb: 8, cpus: 4 } });+ });++ it("accepts whole-number limits in range and refuses the rest", () => {+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", memoryGb: 3, cpus: 2 }]).success).toBe(true);+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", memoryGb: 1 }]).success).toBe(false);+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", cpus: 2.5 }]).success).toBe(false);+ });+ });+});diff --git a/src/components/keys/KeyPanels.tsx b/src/components/keys/KeyPanels.tsxindex a2c87e4eaa..eff0b55871 100644--- a/src/components/keys/KeyPanels.tsx+++ b/src/components/keys/KeyPanels.tsx@@ -206,6 +206,7 @@ export function VpsConnection() {{saving ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : clearing ? t("keys.row.remove") : t("common.save")}</button></div>+ {configured && <VpsResources />}{notice && <div role="status" className="text-[12px] leading-4 text-ink-secondary">{notice}</div>}{error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}<VpsServers />@@ -215,16 +216,93 @@ export function VpsConnection() {const NO_SERVERS: { name: string; sshAlias: string }[] = [];+type NamedServer = NonNullable<ConfigStatus["vps"]["servers"]>[number];++const VPS_MEMORY_GB = { min: 2, max: 128, fallback: 4 };+const VPS_CPUS = { min: 1, max: 64, fallback: 2 };++/** Empty is "not set"; anything else must be a whole number in range. */+function limitValue(text: string, range: { min: number; max: number }): number | undefined | null {+ if (text.trim() === "") return undefined;+ const n = Number(text);+ return Number.isInteger(n) && n >= range.min && n <= range.max ? n : null;+}++function LimitInput({ label, value, onChange, range, placeholder, disabled }: {+ label: string; value: string; onChange: (value: string) => void; range: { min: number; max: number }; placeholder: string; disabled: boolean;+}) {+ return (+ <input+ type="number"+ inputMode="numeric"+ min={range.min}+ max={range.max}+ step={1}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ disabled={disabled}+ placeholder={placeholder}+ aria-label={label}+ aria-invalid={limitValue(value, range) === null}+ className={cn(KEY_FIELD, "w-20")}+ />+ );+}++/** One saved server with its own limits; empty fields use the default server's. */+function VpsServerRow({ server, busy, disabled, onSave, onRemove, defaults }: {+ server: NamedServer; busy: boolean; disabled: boolean; onSave: (next: NamedServer) => void; onRemove: () => void; defaults: { memoryGb: number; cpus: number };+}) {+ const [memory, setMemory] = useState(server.memoryGb === undefined ? "" : String(server.memoryGb));+ const [cpus, setCpus] = useState(server.cpus === undefined ? "" : String(server.cpus));+ useEffect(() => {+ setMemory(server.memoryGb === undefined ? "" : String(server.memoryGb));+ setCpus(server.cpus === undefined ? "" : String(server.cpus));+ }, [server.memoryGb, server.cpus]);+ const memoryGb = limitValue(memory, VPS_MEMORY_GB);+ const cpuCount = limitValue(cpus, VPS_CPUS);+ const valid = memoryGb !== null && cpuCount !== null;+ const dirty = memoryGb !== server.memoryGb || cpuCount !== server.cpus;+ const save = () => {+ if (!valid || !dirty) return;+ const { memoryGb: _memory, cpus: _cpus, ...rest } = server;+ onSave({ ...rest, ...(memoryGb === undefined ? {} : { memoryGb }), ...(cpuCount === undefined ? {} : { cpus: cpuCount }) });+ };+ return (+ <div data-vps-server={server.sshAlias} className="flex flex-wrap items-center gap-2">+ <span className={cn(KEY_FIELD, "block flex-1 truncate text-ink")}>+ {server.name} <span className="font-mono text-ink-secondary">{server.sshAlias}</span>+ </span>+ <LimitInput label={t("keys.vps.memory")} value={memory} onChange={setMemory} range={VPS_MEMORY_GB} placeholder={String(defaults.memoryGb)} disabled={disabled} />+ <LimitInput label={t("keys.vps.cpus")} value={cpus} onChange={setCpus} range={VPS_CPUS} placeholder={String(defaults.cpus)} disabled={disabled} />+ <button type="button" onClick={save} disabled={disabled || !valid || !dirty} className="ui-button ui-button-primary shrink-0">+ {t("common.save")}+ </button>+ <button type="button" onClick={onRemove} disabled={disabled} aria-label={t("keys.vps.servers.removeAria", { name: server.name })} className="ui-button shrink-0">+ {busy ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.row.remove")}+ </button>+ </div>+ );+}+/** Named servers a bot can be put on from its own settings. Saving the list never moves a bot. */function VpsServers() {const servers = useStoreSelector((s) => s.config?.vps?.servers ?? NO_SERVERS);+ const defaultMemory = useStoreSelector((s) => s.config?.vps?.memoryGb ?? VPS_MEMORY_GB.fallback);+ const defaultCpus = useStoreSelector((s) => s.config?.vps?.cpus ?? VPS_CPUS.fallback);const dispatch = useStoreDispatch();const [name, setName] = useState("");const [alias, setAlias] = useState("");+ const [memory, setMemory] = useState("");+ const [cpus, setCpus] = useState("");const [saving, setSaving] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);+ const defaults = { memoryGb: defaultMemory, cpus: defaultCpus };+ const newMemory = limitValue(memory, VPS_MEMORY_GB);+ const newCpus = limitValue(cpus, VPS_CPUS);+ const canAdd = saving === null && Boolean(name.trim()) && Boolean(alias.trim()) && newMemory !== null && newCpus !== null;- const put = (next: { name: string; sshAlias: string }[], busy: string) => {+ const put = (next: NamedServer[], busy: string) => {setSaving(busy);setError(null);return api("/api/config", { method: "PUT", body: JSON.stringify({ vpsServers: next }) })@@ -232,11 +310,16 @@ function VpsServers() {.finally(() => setSaving(null));};const add = () => {- if (saving || !name.trim() || !alias.trim()) return;- put([...servers, { name: name.trim(), sshAlias: alias.trim() }], "")- .then(() => { setName(""); setAlias(""); })+ if (!canAdd) return;+ const added: NamedServer = { name: name.trim(), sshAlias: alias.trim(), ...(newMemory === undefined || newMemory === null ? {} : { memoryGb: newMemory }), ...(newCpus === undefined || newCpus === null ? {} : { cpus: newCpus }) };+ put([...servers, added], "")+ .then(() => { setName(""); setAlias(""); setMemory(""); setCpus(""); }).catch((e) => setError(e.message));};+ const replace = (target: string, next: NamedServer) => {+ if (saving) return;+ put(servers.map((server) => (server.sshAlias === target ? next : server)), `save:${target}`).catch((e) => setError(e.message));+ };const remove = (target: string) => {if (saving) return;put(servers.filter((server) => server.sshAlias !== target), target).catch((e) => setError(e.message));@@ -246,21 +329,17 @@ function VpsServers() {<div data-vps-servers className="mt-2 flex flex-col gap-2"><div className="text-[13px] text-ink">{t("keys.vps.servers.title")}</div><p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.servers.hint")}</p>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.servers.limitsHint")}</p>{servers.map((server) => (- <div key={server.sshAlias} data-vps-server={server.sshAlias} className="flex flex-wrap items-center gap-2">- <span className={cn(KEY_FIELD, "block flex-1 truncate text-ink")}>- {server.name} <span className="font-mono text-ink-secondary">{server.sshAlias}</span>- </span>- <button- type="button"- onClick={() => remove(server.sshAlias)}- disabled={saving !== null}- aria-label={t("keys.vps.servers.removeAria", { name: server.name })}- className="ui-button shrink-0"- >- {saving === server.sshAlias ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.row.remove")}- </button>- </div>+ <VpsServerRow+ key={server.sshAlias}+ server={server}+ busy={saving === server.sshAlias}+ disabled={saving !== null}+ defaults={defaults}+ onSave={(next) => replace(server.sshAlias, next)}+ onRemove={() => remove(server.sshAlias)}+ />))}<div className="flex flex-wrap items-center gap-2"><input@@ -286,7 +365,9 @@ function VpsServers() {spellCheck={false}className={cn(KEY_FIELD, "w-auto min-w-[min(100%,10rem)] flex-1 font-mono")}/>- <button type="button" onClick={add} disabled={saving !== null || !name.trim() || !alias.trim()} className="ui-button shrink-0">+ <LimitInput label={t("keys.vps.memory")} value={memory} onChange={setMemory} range={VPS_MEMORY_GB} placeholder={String(defaultMemory)} disabled={saving !== null} />+ <LimitInput label={t("keys.vps.cpus")} value={cpus} onChange={setCpus} range={VPS_CPUS} placeholder={String(defaultCpus)} disabled={saving !== null} />+ <button type="button" onClick={add} disabled={!canAdd} className="ui-button shrink-0">{saving === "" ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.vps.servers.add")}</button></div>@@ -295,6 +376,64 @@ function VpsServers() {);}+/** What each bot's VPS desktop may use; the host's own capacity is the real ceiling. */+function VpsResources() {+ const { state, dispatch } = useStore();+ const savedMemory = state.config?.vps?.memoryGb ?? VPS_MEMORY_GB.fallback;+ const savedCpus = state.config?.vps?.cpus ?? VPS_CPUS.fallback;+ const [memory, setMemory] = useState(String(savedMemory));+ const [cpus, setCpus] = useState(String(savedCpus));+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => { setMemory(String(savedMemory)); setCpus(String(savedCpus)); }, [savedMemory, savedCpus]);+ const whole = (value: string, range: { min: number; max: number }) => {+ const n = Number(value);+ return value.trim() !== "" && Number.isInteger(n) && n >= range.min && n <= range.max ? n : null;+ };+ const memoryGb = whole(memory, VPS_MEMORY_GB);+ const cpuCount = whole(cpus, VPS_CPUS);+ const dirty = memoryGb !== savedMemory || cpuCount !== savedCpus;+ const save = () => {+ if (saving || memoryGb === null || cpuCount === null || !dirty) return;+ setSaving(true);+ setError(null);+ api("/api/config", { method: "PUT", body: JSON.stringify({ vps: { sshAlias: state.config?.vps?.sshAlias ?? "", memoryGb, cpus: cpuCount } }) })+ .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))+ .catch((e) => setError(e.message))+ .finally(() => setSaving(false));+ };+ const field = (label: string, value: string, set: (v: string) => void, range: { min: number; max: number }) => (+ <label className="flex items-center gap-2 text-[12px] leading-4 text-ink-secondary">+ {label}+ <input+ type="number"+ inputMode="numeric"+ min={range.min}+ max={range.max}+ step={1}+ value={value}+ onChange={(e) => set(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && save()}+ aria-invalid={whole(value, range) === null}+ className={cn(KEY_FIELD, "w-20")}+ />+ </label>+ );+ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex flex-wrap items-center gap-3">+ {field(t("keys.vps.memory"), memory, setMemory, VPS_MEMORY_GB)}+ {field(t("keys.vps.cpus"), cpus, setCpus, VPS_CPUS)}+ <button type="button" onClick={save} disabled={saving || memoryGb === null || cpuCount === null || !dirty} className="ui-button ui-button-primary shrink-0">+ {saving ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("common.save")}+ </button>+ </div>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.resourcesHelp")}</p>+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}+ </div>+ );+}+export function OpenAiCompatUrl() {const { state, dispatch } = useStore();const saved = state.config?.openaiCompat?.url ?? "";diff --git a/src/locales/en.json b/src/locales/en.jsonindex 37b8e5e378..bf22029b47 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4304,7 +4304,11 @@"keys.vps.servers.namePlaceholder": "Home lab","keys.vps.servers.alias": "Server SSH config alias","keys.vps.servers.add": "Add",+ "keys.vps.servers.limitsHint": "Memory (GB) and CPU cores are per server. Leave them empty to use the default server's limits (shown in grey).","keys.vps.servers.removeAria": "Remove {name}",+ "keys.vps.memory": "Memory (GB)",+ "keys.vps.cpus": "CPU cores",+ "keys.vps.resourcesHelp": "The most each bot's VPS desktop on the default server may use; named servers below can set their own. A new desktop takes a change at once; a stopped one takes it when it next starts. A running one keeps its limits until it is stopped and started again. Keep these within what the VPS has.","usage.title": "Usage","planUsage.title": "Plan usage","planUsage.subtitle": "Remaining allowance on each signed-in provider. 5-hour and weekly windows, when that plan has them.",diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex e245fc0937..6ee8e483ec 100644--- a/src/state/config-status.ts+++ b/src/state/config-status.ts@@ -54,7 +54,7 @@ export interface ConfigStatus {/** `included`: cloud computers come with Cloud Pro, no key is saved. */box: SavedKey & { included?: boolean };/** `servers`: named servers for the per-bot picker; empty for client sessions, missing from an older server. */- vps: { configured: boolean; sshAlias: string; servers?: { name: string; sshAlias: string }[] };+ vps: { configured: boolean; sshAlias: string; servers?: { name: string; sshAlias: string; memoryGb?: number; cpus?: number }[]; memoryGb?: number; cpus?: number };rooms: { turnTimeoutMinutes: number };/** Per-call ceiling (minutes) for a bot's MCP tools. Absent from servers* older than the setting; read it with mcpCallTimeoutMinutes(). */