Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Servers section: one list with edit and delete, CPU pinning, SSH host dropdown, limits checked against the host
Liam6aec70726b0b
diff --git a/docs/byo-vps.md b/docs/byo-vps.mdindex 042a21c733..f14e5983d2 100644--- a/docs/byo-vps.md+++ b/docs/byo-vps.md@@ -201,11 +201,17 @@ 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.+Memory (2–128 GiB), CPU cores (1–64) and an optional CPU pinning are set in Settings under **Self-hosted VPS**, for+the default server and, separately, for each named server; a named server that leaves memory or cores empty uses the+default server's. Pinning is a list of logical CPU ids such as `0,2` or `4-7` (Docker's `--cpuset-cpus`); it may not+name more CPUs than the cores field, and a named server never inherits the default server's pinning. The dropdown for+a new server's SSH alias lists the plain `Host` names in `~/.ssh/config`, including files it `Include`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, and Docker cannot remove a pin from an existing container, so a removed pin applies+to desktops made afterwards. When you save a limit, OpenMausBot asks the VPS's Docker engine for its CPU count and+memory over SSH and refuses cores, memory or a pinning the machine does not have. A host that does not answer does+not hold the save up.- **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.diff --git a/server/config.ts b/server/config.tsindex d23b8a6d18..da87ae0c35 100644--- a/server/config.ts+++ b/server/config.ts@@ -571,6 +571,7 @@ export function vpsResources(cfg: AppConfig): DesktopResources {return {memoryGb: cfg.vps?.memoryGb ?? DEFAULT_DESKTOP_RESOURCES.memoryGb,cpus: cfg.vps?.cpus ?? DEFAULT_DESKTOP_RESOURCES.cpus,+ ...(cfg.vps?.cpuset ? { cpuset: cfg.vps.cpuset } : {}),};}diff --git a/server/container-limits.test.ts b/server/container-limits.test.tsnew file mode 100644index 0000000000..0b363304c0--- /dev/null+++ b/server/container-limits.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";++import { cpusetSize, isValidCpuset, resourceArgs } from "./container-limits.ts";+import { normalizeVpsConfig, vpsServersSchema } from "./vps-config.ts";+import { vpsLimits } from "./vps-hosts.ts";++describe("CPU pinning", () => {+ it("accepts CPU ids and ranges and refuses anything else", () => {+ for (const ok of ["0", "0,2", "4-7", "0-1,4,6-7"]) expect(isValidCpuset(ok)).toBe(true);+ for (const bad of ["", "a", "7-4", "0,", "1 2", "0-", "--1", "0;rm"]) expect(isValidCpuset(bad)).toBe(false);+ });++ it("passes --cpuset-cpus to the container only when pinned", () => {+ expect(resourceArgs({ memoryGb: 4, cpus: 2 }, { swap: true })).not.toContain("--cpuset-cpus");+ expect(resourceArgs({ memoryGb: 4, cpus: 2, cpuset: "4-7" }, { swap: true }).slice(-2)).toEqual(["--cpuset-cpus", "4-7"]);+ });++ it("stores the default server's pinning, keeps it when a patch leaves it out, and clears it with an empty string", () => {+ expect(normalizeVpsConfig({ sshAlias: "a", cpuset: "0,2" })).toEqual({ sshAlias: "a", cpuset: "0,2" });+ expect(normalizeVpsConfig({ sshAlias: "a" }, { cpuset: "0,2" })).toEqual({ sshAlias: "a", cpuset: "0,2" });+ expect(normalizeVpsConfig({ sshAlias: "a", cpuset: "" }, { cpuset: "0,2" })).toEqual({ sshAlias: "a" });+ expect(() => normalizeVpsConfig({ sshAlias: "a", cpuset: "9-1" })).toThrow(/cpuset/);+ });++ it("counts the CPUs a pinning names and refuses one above the cores", () => {+ expect([cpusetSize("0"), cpusetSize("0,2"), cpusetSize("4-7"), cpusetSize("0-1,4,6-7")]).toEqual([1, 2, 4, 5]);+ expect(normalizeVpsConfig({ sshAlias: "a", cpus: 4, cpuset: "0-3" })).toEqual({ sshAlias: "a", cpus: 4, cpuset: "0-3" });+ expect(() => normalizeVpsConfig({ sshAlias: "a", cpus: 4, cpuset: "0-4" })).toThrow(/5 CPUs but vps.cpus is 4/);+ expect(() => normalizeVpsConfig({ sshAlias: "a", cpuset: "0-2" })).toThrow(/3 CPUs but vps.cpus is 2/);+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", cpus: 4, cpuset: "0-4" }]).success).toBe(false);+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", cpus: 4, cpuset: "0-3" }]).success).toBe(true);+ });++ it("refuses a bad pinning on a named server", () => {+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", cpuset: "4-7" }]).success).toBe(true);+ expect(vpsServersSchema.safeParse([{ name: "Lab", sshAlias: "lab", cpuset: "x" }]).success).toBe(false);+ });++ it("never lends the default server's pinning to a named server", () => {+ const cfg = { vps: { sshAlias: "main", memoryGb: 6, cpus: 3, cpuset: "0-1" }, vpsServers: [{ name: "Lab", sshAlias: "lab" }, { name: "Pinned", sshAlias: "pin", cpuset: "2" }] };+ expect(vpsLimits(cfg, "main")).toEqual({ memoryGb: 6, cpus: 3, cpuset: "0-1" });+ expect(vpsLimits(cfg, "lab")).toEqual({ memoryGb: 6, cpus: 3 });+ expect(vpsLimits(cfg, "pin")).toEqual({ memoryGb: 6, cpus: 3, cpuset: "2" });+ });+});diff --git a/server/container-limits.ts b/server/container-limits.tsindex 580af22157..2174c9392f 100644--- a/server/container-limits.ts+++ b/server/container-limits.ts@@ -7,6 +7,26 @@ const PREVIOUS_PIDS_LIMIT = 512;export interface DesktopResources {memoryGb: number;cpus: number;+ /** Logical CPU ids the desktop may run on, in `docker --cpuset-cpus` form ("0,2", "4-7"); unset lets the host choose. */+ cpuset?: string;+}++const CPUSET = /^\d{1,4}(-\d{1,4})?(,\d{1,4}(-\d{1,4})?)*$/;++/** How many CPUs a valid `cpuset` names: "0,2" is 2, "4-7" is 4. */+export function cpusetSize(value: string): number {+ return value.split(",").reduce((total, part) => {+ const [from, to = from] = part.split("-").map(Number);+ return total + (to! - from! + 1);+ }, 0);+}++export function isValidCpuset(value: unknown): value is string {+ if (typeof value !== "string" || !CPUSET.test(value)) return false;+ return value.split(",").every((part) => {+ const [from, to = from] = part.split("-").map(Number);+ return from! <= to!;+ });}export const DEFAULT_DESKTOP_RESOURCES: DesktopResources = { memoryGb: 4, cpus: 2 };@@ -19,7 +39,7 @@ export const MAX_DESKTOP_CPUS = 64;* letting it thrash the host. */export function resourceArgs(resources: DesktopResources, options: { swap: boolean }): string[] {const memory = `${resources.memoryGb}g`;- return ["--memory", memory, ...(options.swap ? ["--memory-swap", memory] : []), "--cpus", String(resources.cpus)];+ return ["--memory", memory, ...(options.swap ? ["--memory-swap", memory] : []), "--cpus", String(resources.cpus), ...(resources.cpuset ? ["--cpuset-cpus", resources.cpuset] : [])];}const raised = new Set<string>();diff --git a/server/index.test.ts b/server/index.test.tsindex 4b9b8b8524..876c399a8c 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -11212,13 +11212,13 @@ describe("harness HTTP API", () => {expect(saved.status, JSON.stringify(saved.body)).toBe(200);expect((await api("GET", "/api/config")).body.vps.sshAlias).toBe("rockpi4");- const replaced = await api("PUT", "/api/config", { vps: { sshAlias: "dietpi" } });+ const replaced = await api("PUT", "/api/config", { vps: { sshAlias: "example-host" } });expect(replaced.status, JSON.stringify(replaced.body)).toBe(200);- expect((await api("GET", "/api/config")).body.vps.sshAlias).toBe("dietpi");+ expect((await api("GET", "/api/config")).body.vps.sshAlias).toBe("example-host");const cleared = await api("PUT", "/api/config", { vps: { sshAlias: "" } });expect(cleared.status, JSON.stringify(cleared.body)).toBe(200);- expect(cleared.body.notice).toContain("Removed. dietpi could not be reached");+ expect(cleared.body.notice).toContain("Removed. example-host could not be reached");expect((await api("GET", "/api/config")).body.vps.sshAlias).toBe("");} finally {rmSync(fakeSshUnavailable, { force: true });@@ -12435,13 +12435,13 @@ describe("harness HTTP API", () => {const saved = await api("PUT", "/api/config", { vps: { sshAlias: "production-vps" } });expect(saved.status).toBe(200);- expect(saved.body.vps).toEqual({ configured: true, sshAlias: "production-vps", servers: [] });+ expect(saved.body.vps).toEqual({ configured: true, sshAlias: "production-vps", servers: [], memoryGb: 4, cpus: 2 });expect(JSON.stringify(saved.body)).not.toContain("privateKey");// Named servers are their own list: saving it leaves the default server alone.const named = await api("PUT", "/api/config", { vpsServers: [{ name: "Home lab", sshAlias: "home-lab" }] });expect(named.status, JSON.stringify(named.body)).toBe(200);- expect(named.body.vps).toEqual({ configured: true, sshAlias: "production-vps", servers: [{ name: "Home lab", sshAlias: "home-lab" }] });+ expect(named.body.vps).toEqual({ configured: true, sshAlias: "production-vps", servers: [{ name: "Home lab", sshAlias: "home-lab" }], memoryGb: 4, cpus: 2 });expect((await api("PUT", "/api/config", { vpsServers: [{ name: "Bad", sshAlias: "prod; reboot" }] })).status).toBe(400);const patched = await api("PATCH", `/api/bots/${bot.id}`, { cloudBackend: "vps" });@@ -12477,7 +12477,7 @@ describe("harness HTTP API", () => {const memberStream = await openSse(`${BASE}/api/events`, { authorization: `Bearer ${memberToken}` });const ownerStream = await openSse(`${BASE}/api/events`);try {- expect((await asMember("GET", "/api/config")).body.vps).toEqual({ configured: true, sshAlias: "", servers: [] });+ expect((await asMember("GET", "/api/config")).body.vps).toEqual({ configured: true, sshAlias: "", servers: [], memoryGb: 4, cpus: 2 });const listed = (await asMember("GET", "/api/bots?messages=0")).body.bots.find((candidate: any) => candidate.id === bot.id);expect(listed).toMatchObject({ id: bot.id, cloudBackend: "vps" });expect(listed).not.toHaveProperty("vpsAlias");diff --git a/server/routes/computers.ts b/server/routes/computers.tsindex caf242504b..6d1f9c8099 100644--- a/server/routes/computers.ts+++ b/server/routes/computers.ts@@ -25,6 +25,7 @@ import type { SessionRegistry } from "../sessions.ts";import { sectionKey, type BotRecord, type Store } from "../store.ts";import { teamComputerAssignment, teamComputerCreate, teamComputerOwner, type TeamComputerRecord, type TeamComputers } from "../team-computers.ts";import * as vps from "../vps-computer.ts";+import { sshConfigHosts } from "../ssh-config-hosts.ts";import { vpsAliasesInPlay } from "../vps-hosts.ts";import type { BusyFlag, RemoteComputerProvider } from "./config.ts";import { createCloudComputerRecoveryRoutes, type CloudComputerRecoveryRouteDeps } from "./cloud-computer-recovery.ts";@@ -255,6 +256,12 @@ export function createComputerRoutes(deps: ComputerRouteDeps): RouteHandler {vpsAliasesInPlay(cfg, store.bots),));}+ if (method === "GET" && path === "/api/computers/vps/ssh-hosts") {+ res.setHeader("cache-control", "private, no-store");+ // Aliases are the server's SSH setup: only an admin sees them, as with the saved alias.+ if (!auth.scopes.includes("admin")) return json(res, 403, { error: "admin only" });+ return json(res, 200, { hosts: sshConfigHosts() });+ }m = path.match(/^\/api\/computers\/vps\/([\w-]+)\/remove$/);if (m && method === "POST") {if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {diff --git a/server/routes/config.ts b/server/routes/config.tsindex 9a2f626b95..b7b8fab6cf 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -43,6 +43,7 @@ import type { Store } from "../store.ts";import * as tts from "../tts/index.ts";import { DEFAULT_DEEPSEEK_VOICE } from "../../shared/deepseek-voice.ts";import * as vps from "../vps-computer.ts";+import { vpsHostLimitProblem } from "../vps-host-limits.ts";import { refusalBody, userError, userErrorFields } from "../user-errors.ts";import type { ServerErrorBody } from "../../shared/server-text.ts";import type { Postiz } from "../postiz/service.ts";@@ -205,6 +206,10 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {}if (changingVoiceProvider && patch.tts?.model === undefined) patch.tts = { ...patch.tts, model: "" };if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });+ if (patch.vps !== undefined || patch.vpsServers !== undefined) {+ const overHost = await vpsHostLimitProblem(cfg, patch);+ if (overHost) return json(res, 400, { error: overHost });+ }if (patch.browserProfiles !== undefined && body.expectedBrowserProfiles !== undefined) {const current = (cfg.browserProfiles ?? []).map(({ id, name, browser }) => ({ id, name, ...(browser ? { browser } : {}) }));if (JSON.stringify(body.expectedBrowserProfiles) !== JSON.stringify(current)) {diff --git a/server/ssh-config-hosts.test.ts b/server/ssh-config-hosts.test.tsnew file mode 100644index 0000000000..a68daa6b51--- /dev/null+++ b/server/ssh-config-hosts.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";++import { sshConfigHosts, type SshConfigFiles } from "./ssh-config-hosts.ts";++function files(map: Record<string, string>): SshConfigFiles {+ return {+ read: (path) => map[path] ?? null,+ list: (directory) => Object.keys(map).filter((path) => path.startsWith(`${directory}/`) && !path.slice(directory.length + 1).includes("/")).map((path) => path.slice(directory.length + 1)).sort(),+ };+}++describe("sshConfigHosts", () => {+ it("lists concrete Host names once, in order, and skips patterns and negations", () => {+ const hosts = sshConfigHosts("/h/.ssh", files({+ "/h/.ssh/config": "Host *\n User me\nHost example-host home-lab # comment\n HostName 10.0.0.2\nhost = Prod\nHost *.corp !skip web?\nHost example-host\n",+ }));+ expect(hosts).toEqual(["example-host", "home-lab", "Prod"]);+ });++ it("follows Include, relative to ~/.ssh and with a wildcard, and survives a loop", () => {+ const hosts = sshConfigHosts("/h/.ssh", files({+ "/h/.ssh/config": "Include config.d/*\nInclude config\nHost first\n",+ "/h/.ssh/config.d/a": "Host from-a\n",+ "/h/.ssh/config.d/b": "Host from-b\n",+ }));+ expect(hosts).toEqual(["from-a", "from-b", "first"]);+ });++ it("is empty with no config file, and drops names that are not simple aliases", () => {+ expect(sshConfigHosts("/h/.ssh", files({}))).toEqual([]);+ expect(sshConfigHosts("/h/.ssh", files({ "/h/.ssh/config": "Host bad;name ok-name user@host\n" }))).toEqual(["ok-name"]);+ });+});diff --git a/server/ssh-config-hosts.ts b/server/ssh-config-hosts.tsnew file mode 100644index 0000000000..62ee754f1d--- /dev/null+++ b/server/ssh-config-hosts.ts@@ -0,0 +1,70 @@+import { readdirSync, readFileSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, isAbsolute, join } from "node:path";++import { isValidSshAlias } from "./vps-config.ts";++const MAX_HOSTS = 200;+const MAX_FILE_BYTES = 256 * 1024;+const MAX_INCLUDE_DEPTH = 4;++export interface SshConfigFiles {+ read(path: string): string | null;+ list(directory: string): string[];+}++const nodeFiles: SshConfigFiles = {+ read(path) {+ try {+ if (statSync(path).size > MAX_FILE_BYTES) return null;+ return readFileSync(path, "utf8");+ } catch {+ return null;+ }+ },+ list(directory) {+ try {+ return readdirSync(directory).sort();+ } catch {+ return [];+ }+ },+};++const wildcard = (pattern: string) => /[*?]/.test(pattern);++function includeTargets(pattern: string, sshDir: string, files: SshConfigFiles): string[] {+ const expanded = pattern.startsWith("~/") ? join(homedir(), pattern.slice(2)) : pattern;+ const path = isAbsolute(expanded) ? expanded : join(sshDir, expanded);+ if (!wildcard(path)) return [path];+ const directory = dirname(path);+ if (wildcard(directory)) return [];+ const base = path.slice(directory.length + 1);+ const matcher = new RegExp(`^${base.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);+ return files.list(directory).filter((name) => matcher.test(name)).map((name) => join(directory, name));+}++function collect(path: string, sshDir: string, files: SshConfigFiles, depth: number, seen: Set<string>, out: string[]): void {+ if (depth > MAX_INCLUDE_DEPTH || seen.has(path)) return;+ seen.add(path);+ const text = files.read(path);+ if (text === null) return;+ for (const raw of text.split(/\r?\n/)) {+ const line = raw.replace(/#.*$/, "").trim();+ const [keyword = "", ...rest] = line.split(/[\s=]+/).filter(Boolean);+ const key = keyword.toLowerCase();+ if (key === "host") {+ for (const name of rest) if (!name.startsWith("!") && !wildcard(name) && isValidSshAlias(name) && !out.includes(name)) out.push(name);+ } else if (key === "include") {+ for (const pattern of rest) for (const target of includeTargets(pattern.replace(/^"|"$/g, ""), sshDir, files)) collect(target, sshDir, files, depth + 1, seen, out);+ }+ if (out.length >= MAX_HOSTS) return;+ }+}++/** The concrete `Host` names in the user's SSH config, in file order, including files it `Include`s. Patterns, negations and names that are no valid alias are left out. */+export function sshConfigHosts(sshDir = join(homedir(), ".ssh"), files: SshConfigFiles = nodeFiles): string[] {+ const out: string[] = [];+ collect(join(sshDir, "config"), sshDir, files, 0, new Set(), out);+ return out.slice(0, MAX_HOSTS);+}diff --git a/server/vps-config.ts b/server/vps-config.tsindex ff18fd17ca..a1f304efb7 100644--- a/server/vps-config.ts+++ b/server/vps-config.ts@@ -1,7 +1,7 @@/** 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";+import { cpusetSize, DEFAULT_DESKTOP_RESOURCES, isValidCpuset, 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}$/;@@ -10,7 +10,7 @@ export function isValidSshAlias(value: unknown): value is 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 };+export type VpsConfig = { sshAlias?: string; memoryGb?: number; cpus?: number; cpuset?: string };/** 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 {@@ -36,24 +36,38 @@ export function normalizeVpsConfig(raw: unknown, stored?: unknown): VpsConfig {}out[key] = value;}+ const cpuset = "cpuset" in patch ? patch.cpuset : kept.cpuset;+ if (cpuset !== undefined && cpuset !== "") {+ if (!isValidCpuset(cpuset)) throw new Error("vps.cpuset must be CPU ids like 0,2 or 4-7");+ const cores = out.cpus ?? DEFAULT_DESKTOP_RESOURCES.cpus;+ if (cpusetSize(cpuset) > cores) throw new Error(`vps.cpuset names ${cpusetSize(cpuset)} CPUs but vps.cpus is ${cores}`);+ out.cpuset = cpuset;+ }return out;}const memoryGbSchema = z.number().int().min(MIN_DESKTOP_MEMORY_GB).max(MAX_DESKTOP_MEMORY_GB);+/** Empty clears the pinning on the default server; a named server just leaves it out. */+const cpusetSchema = z.string().refine((value) => value === "" || isValidCpuset(value), { message: "must be CPU ids like 0,2 or 4-7" });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(),+ cpuset: cpusetSchema.optional(),});export const MAX_VPS_SERVERS = 20;/** `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 interface VpsServer { name: string; sshAlias: string; memoryGb?: number; cpus?: number; cpuset?: string }export const vpsServerSchema = z.object({memoryGb: memoryGbSchema.optional(),cpus: cpusSchema.optional(),+ cpuset: z.string().refine(isValidCpuset, { message: "must be CPU ids like 0,2 or 4-7" }).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" }),+}).refine((server) => !server.cpuset || !server.cpus || cpusetSize(server.cpuset) <= server.cpus, {+ message: "cpuset names more CPUs than cpus allows",+ path: ["cpuset"],});/** Named servers a bot can be put on; the default server stays in `vps`, so saving this list never moves a bot. */export const vpsServersSchema = z.array(vpsServerSchema).max(MAX_VPS_SERVERS)diff --git a/server/vps-host-limits.test.ts b/server/vps-host-limits.test.tsnew file mode 100644index 0000000000..ed001a4b55--- /dev/null+++ b/server/vps-host-limits.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from "vitest";++import { hostLimitProblem, vpsHostCapacity, vpsHostLimitProblem } from "./vps-host-limits.ts";++const GIB = 1024 ** 3;++describe("VPS host limits", () => {+ it("asks the host's Docker engine for its CPUs and memory, and says null when it cannot", async () => {+ const run = vi.fn(async () => ({ stdout: "6 8000000000\n", stderr: "" }));+ expect(await vpsHostCapacity("example-host", run)).toEqual({ cpus: 6, memoryBytes: 8_000_000_000 });+ expect(run).toHaveBeenCalledWith(["-H", "ssh://example-host", "info", "--format", "{{.NCPU}} {{.MemTotal}}"], { timeoutMs: 20_000 });+ expect(await vpsHostCapacity("example-host", async () => { throw new Error("down"); })).toBeNull();+ expect(await vpsHostCapacity("example-host", async () => ({ stdout: "x", stderr: "" }))).toBeNull();+ });++ it("refuses more cores or memory than the machine has, and pins to CPUs it does not have", () => {+ const host = { cpus: 6, memoryBytes: 3.7 * GIB };+ expect(hostLimitProblem("example-host", host, { cpus: 6, cpuset: "0-5", memoryGb: 4 })).toBeNull();+ expect(hostLimitProblem("example-host", host, { cpus: 8 })).toBe("example-host has 6 CPU cores, so 8 cores can't be set");+ expect(hostLimitProblem("example-host", host, { cpuset: "4-7" })).toBe("example-host has CPUs 0-5, so CPU pinning 4-7 can't be set");+ expect(hostLimitProblem("example-host", host, { memoryGb: 6 })).toBe("example-host has 3.7 GB of memory, so 6 GB can't be set");+ expect(hostLimitProblem("example-host", { cpus: 1, memoryBytes: 4 * GIB }, { cpus: 2 })).toBe("example-host has 1 CPU core, so 2 cores can't be set");+ });++ it("checks only the limits a save adds or changes, once per host, and lets an unreachable host through", async () => {+ const host = vi.fn(async (alias: string) => (alias === "off" ? null : { cpus: 4, memoryBytes: 8 * GIB }));+ const cfg = { vps: { sshAlias: "main", cpus: 2, memoryGb: 4 }, vpsServers: [{ name: "Lab", sshAlias: "lab", cpus: 8, memoryGb: 64 }] };+ expect(await vpsHostLimitProblem(cfg, { vpsServers: cfg.vpsServers }, host)).toBeNull();+ expect(host).not.toHaveBeenCalled();+ expect(await vpsHostLimitProblem(cfg, { vps: { cpus: 5 } }, host)).toBe("main has 4 CPU cores, so 5 cores can't be set");+ expect(await vpsHostLimitProblem(cfg, { vps: { memoryGb: 16 } }, host)).toBe("main has 8.0 GB of memory, so 16 GB can't be set");+ expect(await vpsHostLimitProblem(cfg, { vpsServers: [{ name: "Lab", sshAlias: "lab", cpus: 8, memoryGb: 64, cpuset: "0-1" }] }, host)).toBe("lab has 4 CPU cores, so 8 cores can't be set");+ expect(await vpsHostLimitProblem(cfg, { vpsServers: [{ name: "Off", sshAlias: "off", cpus: 64, memoryGb: 128 }] }, host)).toBeNull();+ expect(await vpsHostLimitProblem(cfg, { vps: { cpus: 4, memoryGb: 8, cpuset: "0-3" } }, host)).toBeNull();+ expect(host).toHaveBeenCalledTimes(5);+ });+});diff --git a/server/vps-host-limits.ts b/server/vps-host-limits.tsnew file mode 100644index 0000000000..573a0ec369--- /dev/null+++ b/server/vps-host-limits.ts@@ -0,0 +1,70 @@+import type { AppConfig, VpsServer } from "./config.ts";+import { defaultRunner, vpsDockerArgs, type VpsCommandRunner } from "./vps-computer.ts";++export interface HostCapacity { cpus: number; memoryBytes: number }++const GIB = 1024 ** 3;++/** What the host's Docker engine can use, or null when the host did not answer: a save is then not held up by an offline machine. */+export async function vpsHostCapacity(alias: string, runner: VpsCommandRunner = defaultRunner): Promise<HostCapacity | null> {+ try {+ const { stdout } = await runner(vpsDockerArgs(alias, ["info", "--format", "{{.NCPU}} {{.MemTotal}}"]), { timeoutMs: 20_000 });+ const [cpus, memoryBytes] = stdout.trim().split(/\s+/).map(Number);+ return Number.isInteger(cpus) && cpus! > 0 && Number.isFinite(memoryBytes) && memoryBytes! > 0 ? { cpus: cpus!, memoryBytes: memoryBytes! } : null;+ } catch {+ return null;+ }+}++function highestCpu(cpuset: string): number {+ return Math.max(...cpuset.split(",").map((part) => Number(part.split("-").pop())));+}++/** Words for a limit the machine cannot honour, or null. */+export function hostLimitProblem(alias: string, host: HostCapacity, limits: { cpus?: number; cpuset?: string; memoryGb?: number }): string | null {+ if (limits.cpus !== undefined && limits.cpus > host.cpus) {+ return `${alias} has ${host.cpus} CPU core${host.cpus === 1 ? "" : "s"}, so ${limits.cpus} cores can't be set`;+ }+ if (limits.cpuset && highestCpu(limits.cpuset) >= host.cpus) {+ return `${alias} has CPUs 0-${host.cpus - 1}, so CPU pinning ${limits.cpuset} can't be set`;+ }+ // A machine sold as 4 GB reports a little less; round before comparing.+ if (limits.memoryGb !== undefined && limits.memoryGb > Math.round(host.memoryBytes / GIB)) {+ return `${alias} has ${(host.memoryBytes / GIB).toFixed(1)} GB of memory, so ${limits.memoryGb} GB can't be set`;+ }+ return null;+}++type Patch = { vps?: { sshAlias?: string; cpus?: number; cpuset?: string; memoryGb?: number }; vpsServers?: VpsServer[] };+type Limits = { cpus?: number; cpuset?: string; memoryGb?: number };++/** Checks each CPU and memory limit this save adds or changes against what the machine has. */+export async function vpsHostLimitProblem(cfg: AppConfig, patch: Patch, capacity: (alias: string) => Promise<HostCapacity | null> = vpsHostCapacity): Promise<string | null> {+ const targets: ({ alias: string } & Limits)[] = [];+ if (patch.vps !== undefined) {+ const alias = patch.vps.sshAlias || cfg.vps?.sshAlias;+ const cpus = patch.vps.cpus ?? cfg.vps?.cpus;+ const memoryGb = patch.vps.memoryGb ?? cfg.vps?.memoryGb;+ const cpuset = "cpuset" in patch.vps ? patch.vps.cpuset || undefined : cfg.vps?.cpuset;+ const changed = patch.vps.sshAlias !== undefined && patch.vps.sshAlias !== cfg.vps?.sshAlias+ || (patch.vps.cpus !== undefined && patch.vps.cpus !== cfg.vps?.cpus)+ || (patch.vps.memoryGb !== undefined && patch.vps.memoryGb !== cfg.vps?.memoryGb)+ || ("cpuset" in patch.vps && cpuset !== cfg.vps?.cpuset);+ if (alias && changed && (cpus !== undefined || memoryGb !== undefined || cpuset)) targets.push({ alias, ...(cpus === undefined ? {} : { cpus }), ...(memoryGb === undefined ? {} : { memoryGb }), ...(cpuset ? { cpuset } : {}) });+ }+ for (const server of patch.vpsServers ?? []) {+ const before = cfg.vpsServers?.find((entry) => entry.sshAlias === server.sshAlias);+ const limited = server.cpus !== undefined || server.memoryGb !== undefined || Boolean(server.cpuset);+ if (limited && (server.cpus !== before?.cpus || server.cpuset !== before?.cpuset || server.memoryGb !== before?.memoryGb)) {+ targets.push({ alias: server.sshAlias, ...(server.cpus === undefined ? {} : { cpus: server.cpus }), ...(server.memoryGb === undefined ? {} : { memoryGb: server.memoryGb }), ...(server.cpuset ? { cpuset: server.cpuset } : {}) });+ }+ }+ const hosts = new Map<string, Promise<HostCapacity | null>>();+ for (const target of targets) {+ if (!hosts.has(target.alias)) hosts.set(target.alias, capacity(target.alias));+ const host = await hosts.get(target.alias)!;+ const problem = host === null ? null : hostLimitProblem(target.alias, host, target);+ if (problem) return problem;+ }+ return null;+}diff --git a/server/vps-hosts.ts b/server/vps-hosts.tsindex 56c0e5f4e6..c8d9f5912e 100644--- a/server/vps-hosts.ts+++ b/server/vps-hosts.ts@@ -1,12 +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, 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"> {+/** A named server's own limits, each falling back to the default server's. CPU pinning is per machine, so a named server never inherits the default's. */+export function vpsLimits(cfg: AppConfig, alias?: string | null): Pick<VpsConfig, "memoryGb" | "cpus" | "cpuset"> {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 } : {}) };+ const cpuset = own ? own.cpuset : cfg.vps?.cpuset;+ return { ...(memoryGb ? { memoryGb } : {}), ...(cpus ? { cpus } : {}), ...(cpuset ? { cpuset } : {}) };}/** A bot's own SSH alias wins over the default; both are validated the same way. */diff --git a/src/components/keys/KeyPanels.tsx b/src/components/keys/KeyPanels.tsxindex eff0b55871..da19c1fc99 100644--- a/src/components/keys/KeyPanels.tsx+++ b/src/components/keys/KeyPanels.tsx@@ -1,7 +1,6 @@import { useEffect, useRef, useState } from "react";import { Loader2, TriangleAlert } from "lucide-react";import { api, useStore, type ConfigStatus } from "@/state/store";-import { useStoreDispatch, useStoreSelector } from "@/state/store-select";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { Switch } from "../SettingsPrimitives";@@ -139,301 +138,6 @@ export function AnthropicEveryClaudeBot() {);}-/** Non-secret Docker-over-SSH target. Keys and passwords stay with SSH. */-export function VpsConnection() {- const { state, dispatch } = useStore();- const [alias, setAlias] = useState("");- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string | null>(null);- const [notice, setNotice] = useState<string | null>(null);- const configured = Boolean(state.config?.vps?.configured);- const clearing = !alias.trim() && configured;- const unchanged = alias.trim() === (state.config?.vps?.sshAlias ?? "");-- useEffect(() => {- setAlias(state.config?.vps?.sshAlias ?? "");- }, [state.config?.vps?.sshAlias]);-- const save = () => {- if (saving || (!alias.trim() && !configured) || unchanged) return;- setSaving(true);- setError(null);- api("/api/config", { method: "PUT", body: JSON.stringify({ vps: { sshAlias: alias.trim() } }) })- .then(({ notice: savedNotice, ...status }: ConfigStatus & { notice?: string }) => {- dispatch({ type: "configStatus", config: status });- setAlias(status.vps?.sshAlias ?? "");- setNotice(savedNotice ?? null);- })- .catch((e) => {- setError(e.message);- // A save that failed after the alias changed still says what the old server may hold.- const failedNotice = (e as { body?: { notice?: unknown } }).body?.notice;- if (typeof failedNotice === "string") setNotice(failedNotice);- })- .finally(() => setSaving(false));- };-- return (- <div className="flex flex-col gap-2">- <p className="text-[12px] leading-4 text-ink-secondary">- {t("keys.vps.descBefore")}- <a href="https://github.com/milind-soni/OpenMausBot/blob/main/docs/byo-vps.md" target="_blank" rel="noopener noreferrer" className="text-accent-text hover:underline">- {t("keys.vps.descLink")}- </a>- {t("keys.vps.descAfter")}- </p>- <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.anyMachine")}</p>- <div className="flex flex-wrap items-center gap-2">- <input- type="text"- data-key-input- value={alias}- onChange={(e) => setAlias(e.target.value)}- onKeyDown={(e) => e.key === "Enter" && save()}- placeholder="my-vps"- aria-label={t("keys.vps.aria")}- autoComplete="off"- spellCheck={false}- className={cn(KEY_FIELD, "w-auto min-w-[min(100%,12rem)] flex-1")}- />- <button- type="button"- onClick={save}- disabled={saving || (!alias.trim() && !configured) || unchanged}- className={cn("ui-button shrink-0", !clearing && "ui-button-primary")}- title={clearing ? t("keys.vps.removeAlias") : undefined}- >- {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 />- </div>- );-}--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: NamedServer[], busy: string) => {- setSaving(busy);- setError(null);- return api("/api/config", { method: "PUT", body: JSON.stringify({ vpsServers: next }) })- .then((status: ConfigStatus) => dispatch({ type: "configStatus", config: status }))- .finally(() => setSaving(null));- };- const add = () => {- 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));- };-- return (- <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) => (- <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- type="text"- value={name}- onChange={(e) => { setError(null); setName(e.target.value); }}- onKeyDown={(e) => e.key === "Enter" && add()}- disabled={saving !== null}- placeholder={t("keys.vps.servers.namePlaceholder")}- aria-label={t("keys.vps.servers.name")}- autoComplete="off"- className={cn(KEY_FIELD, "w-auto min-w-[min(100%,10rem)] flex-1")}- />- <input- type="text"- value={alias}- onChange={(e) => { setError(null); setAlias(e.target.value); }}- onKeyDown={(e) => e.key === "Enter" && add()}- disabled={saving !== null}- placeholder="home-lab"- aria-label={t("keys.vps.servers.alias")}- autoComplete="off"- spellCheck={false}- className={cn(KEY_FIELD, "w-auto min-w-[min(100%,10rem)] flex-1 font-mono")}- />- <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>- {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}- </div>- );-}--/** 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/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.tsindex 61a890fb21..ca866e576f 100644--- a/src/components/keys/KeysPage.dom.test.ts+++ b/src/components/keys/KeysPage.dom.test.ts@@ -12,7 +12,17 @@ const fx = vi.hoisted(() => ({api: vi.fn(),dispatch: vi.fn(),refreshModels: vi.fn(),+ sshHosts: [] as string[],}));+vi.mock("@/lib/relay-server", async (original) => {+ const actual = await original<typeof import("@/lib/relay-server")>();+ return {+ ...actual,+ serverFetch: (path: string, init?: RequestInit) => path === "/api/computers/vps/ssh-hosts"+ ? Promise.resolve(new Response(JSON.stringify({ hosts: fx.sshHosts })))+ : actual.serverFetch(path, init),+ };+});vi.mock("@/state/store", async (original) => {const actual = await original<typeof import("@/state/store")>();const { useSyncExternalStore } = await import("react");@@ -74,6 +84,7 @@ function paste(input: HTMLInputElement, text: string) {beforeEach(() => {setLocale("en");+ fx.sshHosts = [];fx.api.mockReset();fx.dispatch.mockReset();fx.refreshModels.mockReset();@@ -544,46 +555,160 @@ describe("Boat's credit offer on the Boat card", () => {});});-describe("Self-hosted VPS alias", () => {+describe("Self-hosted VPS servers", () => {+ const status = (vps: Record<string, unknown>) => ({ ...fx.config, vps: { memoryGb: 4, cpus: 2, ...vps } });+ const rowFor = (alias: string) => host.querySelector<HTMLElement>(`[data-vps-server="${alias}"]`)!;+ const aliases = () => [...host.querySelectorAll<HTMLElement>("[data-vps-server]")].map((element) => element.dataset.vpsServer);+ const click = (selector: string) => flushSync(() => host.querySelector<HTMLButtonElement>(selector)!.click());+ const lastBody = () => JSON.parse((fx.api.mock.lastCall![1] as RequestInit).body as string);+it("says any Linux machine with Docker over SSH works, including one on a Tailscale network", async () => {- const { VpsConnection } = await import("./KeyPanels");+ const { VpsConnection } = await import("./VpsServersPanel");render(() => createElement(VpsConnection, { key: "vps" }));- const field = host.querySelector<HTMLInputElement>('input[aria-label="Self-hosted VPS SSH config alias"]')!;- const text = field.closest("div.flex-col")!.textContent!;+ const text = host.querySelector("[data-vps-connection]")!.textContent!;expect(text).toContain("Any Linux machine with Docker that you reach over SSH works");expect(text).toContain("Tailscale name as the alias's HostName");});- it("adds and removes named servers as one list, leaving the default alias alone", async () => {- const { VpsConnection } = await import("./KeyPanels");- setConfig({ ...fx.config, vps: { configured: true, sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps" }] } });- fx.api.mockImplementation(async (_path: string, init: RequestInit) => {- const { vpsServers } = JSON.parse(init.body as string);- return { ...fx.config, vps: { configured: true, sshAlias: "production-vps", servers: vpsServers } };- });+ it("lists the default first, shows names read-only, and renames only after the pencil is pressed", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps", memoryGb: 8, cpuset: "4-7" }] }));+ fx.api.mockImplementation(async (_path: string, init: RequestInit) => status({ configured: true, sshAlias: "production-vps", servers: JSON.parse(init.body as string).vpsServers }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ expect(aliases()).toEqual(["production-vps", "office-vps"]);+ expect(rowFor("office-vps").textContent).toContain("SSH alias: office-vps");+ expect(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office memory (GB)"]')!.value).toBe("8");+ expect(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office CPU pinning"]')!.value).toBe("4-7");+ expect(rowFor("office-vps").querySelector('input[aria-label="Server name"]')).toBeNull();+ click('button[aria-label="Edit Office name and alias"]');+ type(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Server name"]')!, "HQ");+ await answered(() => [...rowFor("office-vps").querySelectorAll("button")].find((button) => button.textContent === "Done")!.click());+ expect(lastBody()).toEqual({ vpsServers: [{ name: "HQ", sshAlias: "office-vps", memoryGb: 8, cpuset: "4-7" }] });+ });++ it("saves a named server's limits and CPU pinning", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps" }] }));+ fx.api.mockImplementation(async (_path: string, init: RequestInit) => status({ configured: true, sshAlias: "production-vps", servers: JSON.parse(init.body as string).vpsServers }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ const save = () => [...rowFor("office-vps").querySelectorAll("button")].find((button) => button.textContent === "Save")!;+ expect(save().disabled).toBe(true);+ type(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office memory (GB)"]')!, "8");+ type(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office CPU pinning"]')!, "nope");+ expect(save().disabled).toBe(true);+ type(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office CPU pinning"]')!, "0,2");+ await answered(() => save().click());+ expect(lastBody()).toEqual({ vpsServers: [{ name: "Office", sshAlias: "office-vps", memoryGb: 8, cpuset: "0,2" }] });+ });++ it("refuses a pinning that names more CPUs than the cores field", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps", cpus: 4 }] }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ const pin = () => rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office CPU pinning"]')!;+ const save = () => [...rowFor("office-vps").querySelectorAll("button")].find((button) => button.textContent === "Save")!;+ type(pin(), "0-4");+ expect(pin().getAttribute("aria-invalid")).toBe("true");+ expect(save().disabled).toBe(true);+ expect(rowFor("office-vps").querySelector("[role=alert]")!.textContent).toContain("5 CPUs, more than the 4 cores");+ type(pin(), "0-3");+ expect(pin().getAttribute("aria-invalid")).toBe("false");+ expect(save().disabled).toBe(false);+ type(rowFor("office-vps").querySelector<HTMLInputElement>('input[aria-label="Office CPU cores"]')!, "2");+ expect(save().disabled).toBe(true);+ });++ it("saves the default server's limits and clears its pinning with an empty string", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", cpuset: "0-1", servers: [] }));+ fx.api.mockImplementation(async () => status({ configured: true, sshAlias: "production-vps", memoryGb: 6, servers: [] }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ type(rowFor("production-vps").querySelector<HTMLInputElement>('input[aria-label="production-vps memory (GB)"]')!, "6");+ type(rowFor("production-vps").querySelector<HTMLInputElement>('input[aria-label="production-vps CPU pinning"]')!, "");+ await answered(() => [...rowFor("production-vps").querySelectorAll("button")].find((button) => button.textContent === "Save")!.click());+ expect(lastBody()).toEqual({ vps: { sshAlias: "production-vps", memoryGb: 6, cpus: 2, cpuset: "" } });+ });++ it("adds a named server below the default and clears the form", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [] }));+ fx.api.mockImplementation(async (_path: string, init: RequestInit) => status({ configured: true, sshAlias: "production-vps", servers: JSON.parse(init.body as string).vpsServers }));render(() => createElement(VpsConnection, { key: "vps" }));- const list = () => [...host.querySelectorAll<HTMLElement>("[data-vps-server]")].map((element) => element.dataset.vpsServer);- expect(list()).toEqual(["office-vps"]);type(host.querySelector<HTMLInputElement>('input[aria-label="Server name"]')!, " Home lab ");type(host.querySelector<HTMLInputElement>('input[aria-label="Server SSH config alias"]')!, "home-lab");await answered(() => [...host.querySelectorAll("button")].find((button) => button.textContent === "Add")!.click());- expect(fx.api).toHaveBeenLastCalledWith("/api/config", { method: "PUT", body: JSON.stringify({ vpsServers: [{ name: "Office", sshAlias: "office-vps" }, { name: "Home lab", sshAlias: "home-lab" }] }) });- expect(list()).toEqual(["office-vps", "home-lab"]);+ expect(lastBody()).toEqual({ vpsServers: [{ name: "Home lab", sshAlias: "home-lab", memoryGb: 4, cpus: 2 }] });+ expect(host.querySelector<HTMLInputElement>('input[aria-label="Memory (GB)"]')!.value).toBe("4");+ expect(host.querySelector<HTMLInputElement>('input[aria-label="CPU cores"]')!.value).toBe("2");+ expect(aliases()).toEqual(["production-vps", "home-lab"]);expect(host.querySelector<HTMLInputElement>('input[aria-label="Server name"]')!.value).toBe("");- await answered(() => host.querySelector<HTMLButtonElement>('button[aria-label="Remove Office"]')!.click());- expect(fx.api).toHaveBeenLastCalledWith("/api/config", { method: "PUT", body: JSON.stringify({ vpsServers: [{ name: "Home lab", sshAlias: "home-lab" }] }) });- expect(list()).toEqual(["home-lab"]);- expect(host.querySelector<HTMLInputElement>('input[aria-label="Self-hosted VPS SSH config alias"]')!.value).toBe("production-vps");});- it("shows why a named server was refused and keeps what was typed", async () => {- const { VpsConnection } = await import("./KeyPanels");+ it("deletes servers in any order: a named one, then the default hands over to the next", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", memoryGb: 6, servers: [{ name: "Office", sshAlias: "office-vps" }, { name: "Lab", sshAlias: "lab-vps", cpus: 4 }] }));+ fx.api.mockImplementation(async (_path: string, init: RequestInit) => {+ const body = JSON.parse(init.body as string);+ return status({ configured: Boolean(body.vps?.sshAlias ?? "production-vps"), sshAlias: body.vps?.sshAlias ?? "production-vps", memoryGb: body.vps?.memoryGb ?? 6, cpus: body.vps?.cpus ?? 2, servers: body.vpsServers ?? [{ name: "Office", sshAlias: "office-vps" }, { name: "Lab", sshAlias: "lab-vps", cpus: 4 }] });+ });+ render(() => createElement(VpsConnection, { key: "vps" }));+ await answered(() => click('button[aria-label="Delete production-vps"]'));+ expect(lastBody()).toEqual({+ vps: { sshAlias: "office-vps", memoryGb: 6, cpus: 2, cpuset: "" },+ vpsServers: [{ name: "Lab", sshAlias: "lab-vps", cpus: 4, memoryGb: 6 }],+ });+ expect(aliases()).toEqual(["office-vps", "lab-vps"]);+ await answered(() => click('button[aria-label="Delete Lab"]'));+ expect(lastBody()).toEqual({ vpsServers: [] });+ });++ it("clears the default alias when the default is the only server", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [] }));+ fx.api.mockImplementation(async () => status({ configured: false, sshAlias: "", servers: [] }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ await answered(() => click('button[aria-label="Delete production-vps"]'));+ expect(lastBody()).toEqual({ vps: { sshAlias: "" } });+ expect(aliases()).toEqual([]);+ });++ it("keeps the limits and pinning notes behind a details button", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [] }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ const toggle = () => [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent === "Limits and pinning details")!;+ expect(host.textContent).not.toContain("CPU pinning is optional");+ expect(toggle().getAttribute("aria-expanded")).toBe("false");+ flushSync(() => toggle().click());+ expect(host.textContent).toContain("CPU pinning is optional");+ expect(host.textContent).toContain("Keep these within what the VPS has");+ expect(toggle().getAttribute("aria-expanded")).toBe("true");+ });++ it("offers the hosts from the SSH config as a dropdown, leaving out servers already listed", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [] }));+ fx.sshHosts = ["production-vps", "example-host", "home-lab"];+ fx.api.mockImplementation(async (_path: string, init: RequestInit) => status({ configured: true, sshAlias: "production-vps", servers: JSON.parse(init.body as string).vpsServers }));+ render(() => createElement(VpsConnection, { key: "vps" }));+ await vi.waitFor(() => expect(host.querySelector("select")).not.toBeNull());+ const select = host.querySelector<HTMLSelectElement>('select[aria-label="Server SSH config alias"]')!;+ expect([...select.options].map((option) => option.value)).toEqual(["", "example-host", "home-lab"]);+ type(host.querySelector<HTMLInputElement>('input[aria-label="Server name"]')!, "Spare");+ flushSync(() => { select.value = "example-host"; select.dispatchEvent(new Event("change", { bubbles: true })); });+ await answered(() => [...host.querySelectorAll("button")].find((button) => button.textContent === "Add")!.click());+ expect(lastBody()).toEqual({ vpsServers: [{ name: "Spare", sshAlias: "example-host", memoryGb: 4, cpus: 2 }] });+ });++ it("shows why a server was refused and keeps what was typed", async () => {+ const { VpsConnection } = await import("./VpsServersPanel");+ setConfig(status({ configured: true, sshAlias: "production-vps", servers: [] }));fx.api.mockRejectedValue(new Error("vpsServers: each server needs its own SSH alias"));render(() => createElement(VpsConnection, { key: "vps" }));type(host.querySelector<HTMLInputElement>('input[aria-label="Server name"]')!, "Lab");type(host.querySelector<HTMLInputElement>('input[aria-label="Server SSH config alias"]')!, "lab");await answered(() => [...host.querySelectorAll("button")].find((button) => button.textContent === "Add")!.click());- expect(host.querySelector("[data-vps-servers] [role=alert]")!.textContent).toContain("own SSH alias");+ expect(host.querySelector("[data-vps-connection] [role=alert]")!.textContent).toContain("own SSH alias");expect(host.querySelector<HTMLInputElement>('input[aria-label="Server name"]')!.value).toBe("Lab");});});diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsxindex 23e2c27f2d..3779b51ebf 100644--- a/src/components/keys/KeysPage.tsx+++ b/src/components/keys/KeysPage.tsx@@ -13,7 +13,8 @@ import { BuiltInReplyWait, LmStudioServer, OtherOpenAiCompatServers } from "../Oimport { OllamaServer } from "../OllamaServer";import { KEY_CATALOG, KEY_SECTIONS, keyHidden, keyMatches, savedState, type KeyEntry, type KeyId, type KeySectionId } from "./key-catalog";import { finishKeyFocus, useKeyFocus, type KeyFocusRequest } from "./key-focus";-import { AnthropicEveryClaudeBot, OpenAiCompatUrl, OpenCodeProviderKeys, VpsConnection } from "./KeyPanels";+import { AnthropicEveryClaudeBot, OpenAiCompatUrl, OpenCodeProviderKeys } from "./KeyPanels";+import { VpsConnection } from "./VpsServersPanel";import { KEY_CONTENT, KEY_ROW, KeyRow, MaskedKey, RowHeading, type KeyStatus } from "./KeyRow";import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";diff --git a/src/components/keys/VpsServersPanel.tsx b/src/components/keys/VpsServersPanel.tsxnew file mode 100644index 0000000000..def8bb40af--- /dev/null+++ b/src/components/keys/VpsServersPanel.tsx@@ -0,0 +1,396 @@+import { useEffect, useState } from "react";+import { ChevronRight, Loader2, Minus, Pencil, Plus, Trash2 } from "lucide-react";+import { api, useStore, type ConfigStatus } from "@/state/store";+import { serverFetch } from "@/lib/relay-server";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { KEY_FIELD } from "./KeyRow";++type NamedServer = NonNullable<ConfigStatus["vps"]["servers"]>[number];+type Limits = { memoryGb?: number; cpus?: number; cpuset?: string };+type ServerEntry = { alias: string; name: string; isDefault: boolean } & Limits;+type Range = { min: number; max: number };++const MEMORY_GB: Range & { fallback: number } = { min: 2, max: 128, fallback: 4 };+const CPUS: Range & { fallback: number } = { min: 1, max: 64, fallback: 2 };+const NO_SERVERS: NamedServer[] = [];+const FIELD_EDGE_BOX = "bg-app shadow-[inset_0_0_0_0.5px_var(--settings-edge,var(--color-hairline))]";+const CPUSET = /^\d{1,4}(-\d{1,4})?(,\d{1,4}(-\d{1,4})?)*$/;++/** Empty is "not set"; anything else must be a whole number in range. */+function limitValue(text: string, range: Range): number | undefined | null {+ if (text.trim() === "") return undefined;+ const n = Number(text);+ return Number.isInteger(n) && n >= range.min && n <= range.max ? n : null;+}++/** Empty is "let the host choose"; anything else is CPU ids like 0,2 or 4-7. */+function pinValue(text: string): string | undefined | null {+ const value = text.replace(/\s+/g, "");+ if (value === "") return undefined;+ return CPUSET.test(value) && value.split(",").every((part) => { const [from, to = from] = part.split("-").map(Number); return from! <= to!; }) ? value : null;+}++/** How many CPUs a valid pin names: "0,2" is 2, "4-7" is 4. */+const pinSize = (pin: string) => pin.split(",").reduce((total, part) => { const [from, to = from] = part.split("-").map(Number); return total + (to! - from! + 1); }, 0);+const tooManyPinned = (cpuset: string | undefined | null, cores: number) => typeof cpuset === "string" && pinSize(cpuset) > cores;++const asText = (n: number | undefined) => (n === undefined ? "" : String(n));++function Caption({ children }: { children: string }) {+ return <span className="whitespace-nowrap text-[11px] uppercase tracking-wide text-ink-tertiary">{children}</span>;+}++function Stepper({ label, unit, value, onChange, range, placeholder, disabled, onEnter, stepLabels }: {+ label: string; unit?: string; value: string; onChange: (value: string) => void; range: Range; placeholder: string; disabled?: boolean; onEnter?: () => void; stepLabels?: boolean;+}) {+ const current = limitValue(value, range);+ const step = (by: number) => onChange(String(Math.min(range.max, Math.max(range.min, (current ?? Number(placeholder)) + by))));+ const arrow = "grid h-full w-[22px] shrink-0 place-items-center text-ink-secondary hover:text-ink disabled:opacity-40";+ return (+ <div className={cn("flex h-8 min-w-0 items-center rounded-lg", FIELD_EDGE_BOX)}>+ <button type="button" onClick={() => step(-1)} disabled={disabled} aria-label={stepLabels === false ? undefined : t("keys.vps.lessAria", { what: label })} className={arrow}>+ <Minus size={13} aria-hidden="true" />+ </button>+ <input+ type="number"+ inputMode="numeric"+ min={range.min}+ max={range.max}+ step={1}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={onEnter ? (e) => e.key === "Enter" && onEnter() : undefined}+ disabled={disabled}+ placeholder={placeholder}+ aria-label={label}+ aria-invalid={current === null}+ className="h-full min-w-0 flex-1 bg-transparent text-center text-[13px] text-ink placeholder:text-ink-tertiary focus:outline-none focus-visible:outline-2 focus-visible:outline-focus disabled:opacity-40 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none"+ />+ {unit && <em className="shrink-0 text-[11px] not-italic text-ink-tertiary">{unit}</em>}+ <button type="button" onClick={() => step(1)} disabled={disabled} aria-label={t("keys.vps.moreAria", { what: label })} className={arrow}>+ <Plus size={13} aria-hidden="true" />+ </button>+ </div>+ );+}++function PinInput({ value, onChange, label, disabled, onEnter, tooMany }: { value: string; onChange: (value: string) => void; label: string; disabled?: boolean; onEnter?: () => void; tooMany?: boolean }) {+ return (+ <input+ type="text"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={onEnter ? (e) => e.key === "Enter" && onEnter() : undefined}+ disabled={disabled}+ placeholder={t("keys.vps.pinAuto")}+ aria-label={label}+ aria-invalid={pinValue(value) === null || tooMany === true}+ autoComplete="off"+ spellCheck={false}+ className={cn(KEY_FIELD, "font-mono")}+ />+ );+}++const FIELDS = "flex flex-wrap items-end gap-2";+const WIDTH = { memory: "w-[104px]", cpu: "w-[84px]", pin: "w-[104px]" };++function ServerCard({ server, defaults, busy, disabled, onSave, onRename, onRemove }: {+ server: ServerEntry; defaults: Required<Pick<Limits, "memoryGb" | "cpus">>; busy: string | null; disabled: boolean;+ onSave: (next: Limits) => void; onRename: (next: string) => void; onRemove: () => void;+}) {+ const [editing, setEditing] = useState(false);+ const [rename, setRename] = useState(server.isDefault ? server.alias : server.name);+ const [memory, setMemory] = useState(asText(server.memoryGb));+ const [cpus, setCpus] = useState(asText(server.cpus));+ const [pin, setPin] = useState(server.cpuset ?? "");+ const reset = () => { setMemory(asText(server.memoryGb)); setCpus(asText(server.cpus)); setPin(server.cpuset ?? ""); };+ useEffect(reset, [server.memoryGb, server.cpus, server.cpuset]);+ const renamed = server.isDefault ? server.alias : server.name;+ useEffect(() => setRename(renamed), [renamed]);++ const memoryGb = limitValue(memory, MEMORY_GB);+ const cpuCount = limitValue(cpus, CPUS);+ const cpuset = pinValue(pin);+ const needsValues = server.isDefault && (memoryGb === undefined || cpuCount === undefined);+ const cores = cpuCount ?? defaults.cpus;+ const pinTooMany = tooManyPinned(cpuset, cores);+ const valid = memoryGb !== null && cpuCount !== null && cpuset !== null && !needsValues && !pinTooMany;+ const dirty = memoryGb !== server.memoryGb || cpuCount !== server.cpus || cpuset !== server.cpuset;+ const save = () => {+ if (!valid || !dirty || memoryGb === null || cpuCount === null || cpuset === null) return;+ onSave({ memoryGb, cpus: cpuCount, cpuset });+ };+ const done = () => {+ const next = rename.trim();+ if (!next) return;+ setEditing(false);+ if (next !== renamed) onRename(next);+ };+ const cancel = () => { setRename(renamed); setEditing(false); };+ const saving = busy === `save:${server.alias}`;++ return (+ <div data-vps-server={server.alias} className="flex flex-col gap-2.5">+ <div className="flex min-h-[30px] min-w-0 items-center gap-2">+ {editing ? (+ <>+ <input+ type="text"+ data-key-input+ value={rename}+ onChange={(e) => setRename(e.target.value)}+ onKeyDown={(e) => { if (e.key === "Enter") done(); if (e.key === "Escape") cancel(); }}+ aria-label={server.isDefault ? t("keys.vps.aria") : t("keys.vps.servers.name")}+ autoComplete="off"+ spellCheck={false}+ autoFocus+ className={cn(KEY_FIELD, "h-[30px] min-w-0 flex-1", server.isDefault && "font-mono")}+ />+ <button type="button" onClick={done} disabled={disabled || !rename.trim()} className="ui-button ui-button-primary ui-button-md">{t("common.done")}</button>+ <button type="button" onClick={cancel} disabled={disabled} className="ui-button ui-button-md">{t("common.cancel")}</button>+ </>+ ) : (+ <>+ <b className="min-w-0 truncate text-[14px] font-semibold text-ink">{server.name}</b>+ <code className="min-w-0 truncate font-mono text-[12px] text-ink-secondary">{t("keys.vps.aliasLine", { alias: server.alias })}</code>+ <span className="flex-1" />+ <button+ type="button"+ onClick={() => setEditing(true)}+ disabled={disabled}+ aria-label={t("keys.vps.editAria", { name: server.name })}+ title={t("keys.vps.edit")}+ className="grid size-7 shrink-0 place-items-center rounded-[7px] text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40"+ >+ <Pencil size={15} aria-hidden="true" />+ </button>+ </>+ )}+ </div>+ <div className={FIELDS}>+ <div className={cn("flex min-w-0 flex-col gap-1 max-[480px]:flex-1", WIDTH.memory)}>+ <Caption>{t("keys.vps.col.memory")}</Caption>+ <Stepper label={t("keys.vps.serverMemoryAria", { name: server.name })} unit={t("keys.vps.unitGb")} value={memory} onChange={setMemory} range={MEMORY_GB} placeholder={String(defaults.memoryGb)} disabled={disabled} onEnter={save} />+ </div>+ <div className={cn("flex min-w-0 flex-col gap-1 max-[480px]:flex-1", WIDTH.cpu)}>+ <Caption>{t("keys.vps.col.cpu")}</Caption>+ <Stepper label={t("keys.vps.serverCpusAria", { name: server.name })} value={cpus} onChange={setCpus} range={CPUS} placeholder={String(defaults.cpus)} disabled={disabled} onEnter={save} />+ </div>+ <div className={cn("flex min-w-0 flex-col gap-1 max-[480px]:flex-1", WIDTH.pin)}>+ <Caption>{t("keys.vps.col.pin")}</Caption>+ <PinInput value={pin} onChange={setPin} label={t("keys.vps.serverPinAria", { name: server.name })} disabled={disabled} onEnter={save} tooMany={pinTooMany} />+ </div>+ <span className="flex-1" />+ <button type="button" onClick={save} disabled={disabled || !valid || !dirty} className="ui-button ui-button-primary">+ {saving ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("common.save")}+ </button>+ <button+ type="button"+ onClick={onRemove}+ disabled={disabled}+ aria-label={t("keys.vps.deleteAria", { name: server.name })}+ title={t("keys.row.remove")}+ className="grid size-8 shrink-0 place-items-center rounded-lg border border-danger/30 bg-danger/10 text-danger hover:bg-danger/20 disabled:opacity-40"+ >+ {busy === server.alias ? <Loader2 size={15} className="animate-spin" aria-hidden="true" /> : <Trash2 size={15} aria-hidden="true" />}+ </button>+ </div>+ {pinTooMany && <p role="alert" className="text-[12px] leading-4 text-danger">{t("keys.vps.pinTooMany", { pinned: pinSize(cpuset ?? ""), cores: cores })}</p>}+ </div>+ );+}++function AddServer({ hasDefault, hosts, defaults, disabled, adding, onAdd }: {+ hasDefault: boolean; hosts: string[]; defaults: Required<Pick<Limits, "memoryGb" | "cpus">>; disabled: boolean; adding: boolean;+ onAdd: (server: { name: string; alias: string } & Limits) => Promise<void>;+}) {+ const [name, setName] = useState("");+ const [alias, setAlias] = useState("");+ const [memory, setMemory] = useState(String(MEMORY_GB.fallback));+ const [cpus, setCpus] = useState(String(CPUS.fallback));+ const [pin, setPin] = useState("");+ const memoryGb = limitValue(memory, MEMORY_GB);+ const cpuCount = limitValue(cpus, CPUS);+ const cpuset = pinValue(pin);+ const pinTooMany = tooManyPinned(cpuset, cpuCount ?? defaults.cpus);+ const canAdd = !disabled && Boolean(alias.trim()) && (!hasDefault || Boolean(name.trim())) && memoryGb !== null && cpuCount !== null && cpuset !== null && !pinTooMany;+ const add = () => {+ if (!canAdd || memoryGb === null || cpuCount === null || cpuset === null) return;+ onAdd({ name: name.trim(), alias: alias.trim(), memoryGb, cpus: cpuCount, cpuset })+ .then(() => { setName(""); setAlias(""); setMemory(String(MEMORY_GB.fallback)); setCpus(String(CPUS.fallback)); setPin(""); }, () => undefined);+ };+ const enter = (e: React.KeyboardEvent) => e.key === "Enter" && add();+ return (+ <div className="flex flex-col gap-2.5 rounded-lg border border-hairline/40 bg-inset p-3.5">+ <div className="text-[13px] text-ink">{t("keys.vps.servers.addTitle")}</div>+ <div className={cn("grid gap-2.5", hasDefault ? "grid-cols-2" : "grid-cols-1")}>+ {hasDefault && (+ <input type="text" value={name} onChange={(e) => setName(e.target.value)} onKeyDown={enter} disabled={disabled} placeholder={t("keys.vps.servers.namePlaceholder")} aria-label={t("keys.vps.servers.name")} autoComplete="off" className={KEY_FIELD} />+ )}+ {hosts.length > 0 ? (+ <select data-key-input value={alias} onChange={(e) => setAlias(e.target.value)} disabled={disabled} aria-label={t("keys.vps.servers.alias")} className={cn(KEY_FIELD, "font-mono", alias === "" && "text-ink-tertiary")}>+ <option value="">{t("keys.vps.servers.aliasPlaceholder")}</option>+ {hosts.map((host) => <option key={host} value={host}>{host}</option>)}+ </select>+ ) : (+ <input type="text" data-key-input value={alias} onChange={(e) => setAlias(e.target.value)} onKeyDown={enter} disabled={disabled} placeholder={t("keys.vps.servers.aliasPlaceholder")} aria-label={t("keys.vps.servers.alias")} autoComplete="off" spellCheck={false} className={cn(KEY_FIELD, "font-mono")} />+ )}+ </div>+ <div className={FIELDS}>+ <div className={cn("min-w-0 max-[480px]:flex-1", WIDTH.memory)}>+ <Stepper label={t("keys.vps.memory")} unit={t("keys.vps.unitGb")} value={memory} onChange={setMemory} range={MEMORY_GB} placeholder={String(defaults.memoryGb)} disabled={disabled} onEnter={add} />+ </div>+ <div className={cn("min-w-0 max-[480px]:flex-1", WIDTH.cpu)}>+ <Stepper label={t("keys.vps.cpus")} unit={t("keys.vps.unitCores")} value={cpus} onChange={setCpus} range={CPUS} placeholder={String(defaults.cpus)} disabled={disabled} onEnter={add} />+ </div>+ <div className={cn("min-w-0 max-[480px]:flex-1", WIDTH.pin)}>+ <PinInput value={pin} onChange={setPin} label={t("keys.vps.col.pin")} disabled={disabled} onEnter={add} tooMany={pinTooMany} />+ </div>+ <span className="flex-1" />+ <button type="button" onClick={add} disabled={!canAdd} className="ui-button ui-button-primary">+ {adding ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.vps.servers.add")}+ </button>+ </div>+ {pinTooMany && <p role="alert" className="text-[12px] leading-4 text-danger">{t("keys.vps.pinTooMany", { pinned: pinSize(cpuset ?? ""), cores: cpuCount ?? defaults.cpus })}</p>}+ </div>+ );+}++/** The default server and the named ones as one list. Saving or deleting never moves a bot, except that bots following the default follow its replacement. */+export function VpsConnection() {+ const { state } = useStore();+ const dispatch = useStoreDispatch();+ const named = useStoreSelector((s) => s.config?.vps?.servers ?? NO_SERVERS);+ const defaultAlias = state.config?.vps?.sshAlias ?? "";+ const defaults = {+ memoryGb: state.config?.vps?.memoryGb ?? MEMORY_GB.fallback,+ cpus: state.config?.vps?.cpus ?? CPUS.fallback,+ };+ const defaultCpuset = state.config?.vps?.cpuset;+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const [details, setDetails] = useState(false);+ const [configHosts, setConfigHosts] = useState<string[]>([]);+ useEffect(() => {+ let alive = true;+ serverFetch("/api/computers/vps/ssh-hosts", { cache: "no-store" })+ .then((response) => (response.ok ? response.json() : null))+ .then((found: { hosts?: unknown } | null) => { if (alive && Array.isArray(found?.hosts)) setConfigHosts(found.hosts.filter((host): host is string => typeof host === "string")); })+ .catch(() => undefined);+ return () => { alive = false; };+ }, []);++ const servers: ServerEntry[] = [+ ...(defaultAlias ? [{ alias: defaultAlias, name: defaultAlias, isDefault: true, ...defaults, ...(defaultCpuset ? { cpuset: defaultCpuset } : {}) }] : []),+ ...named.map((server) => ({ alias: server.sshAlias, name: server.name, isDefault: false, memoryGb: server.memoryGb, cpus: server.cpus, cpuset: server.cpuset })),+ ];++ const put = (body: Record<string, unknown>, key: string): Promise<void> => {+ setBusy(key);+ setError(null);+ setNotice(null);+ return api("/api/config", { method: "PUT", body: JSON.stringify(body) })+ .then(({ notice: savedNotice, ...status }: ConfigStatus & { notice?: string }) => {+ dispatch({ type: "configStatus", config: status });+ setNotice(savedNotice ?? null);+ })+ .catch((e) => {+ setError(e.message);+ const failedNotice = (e as { body?: { notice?: unknown } }).body?.notice;+ if (typeof failedNotice === "string") setNotice(failedNotice);+ throw e;+ })+ .finally(() => setBusy(null));+ };+ const quiet = (work: Promise<void>) => work.catch(() => undefined);+ const limits = ({ memoryGb, cpus, cpuset }: Limits): Limits => ({+ ...(memoryGb === undefined ? {} : { memoryGb }),+ ...(cpus === undefined ? {} : { cpus }),+ ...(cpuset === undefined ? {} : { cpuset }),+ });++ const save = (server: ServerEntry, next: Limits) => {+ if (busy) return;+ if (server.isDefault) {+ return quiet(put({ vps: { sshAlias: server.alias, memoryGb: next.memoryGb, cpus: next.cpus, cpuset: next.cpuset ?? "" } }, `save:${server.alias}`));+ }+ const updated: NamedServer = { name: server.name, sshAlias: server.alias, ...limits(next) };+ return quiet(put({ vpsServers: named.map((entry) => (entry.sshAlias === server.alias ? updated : entry)) }, `save:${server.alias}`));+ };++ /** The default's name is its alias; a named server keeps its alias, which bots are tied to. */+ const rename = (server: ServerEntry, next: string) => {+ if (busy) return;+ if (server.isDefault) return quiet(put({ vps: { sshAlias: next } }, `save:${server.alias}`));+ return quiet(put({ vpsServers: named.map((entry) => (entry.sshAlias === server.alias ? { ...entry, name: next } : entry)) }, `save:${server.alias}`));+ };++ /** Deleting the default makes the next server the default; every server keeps the limits it had in effect. */+ const remove = (server: ServerEntry) => {+ if (busy) return;+ if (!server.isDefault) {+ return quiet(put({ vpsServers: named.filter((entry) => entry.sshAlias !== server.alias) }, server.alias));+ }+ const [next, ...rest] = named;+ if (!next) return quiet(put({ vps: { sshAlias: "" } }, server.alias));+ return quiet(put({+ vps: { sshAlias: next.sshAlias, memoryGb: next.memoryGb ?? defaults.memoryGb, cpus: next.cpus ?? defaults.cpus, cpuset: next.cpuset ?? "" },+ vpsServers: rest.map((entry) => ({ ...entry, memoryGb: entry.memoryGb ?? defaults.memoryGb, cpus: entry.cpus ?? defaults.cpus })),+ }, server.alias));+ };++ const add = (next: { name: string; alias: string } & Limits) => {+ if (!defaultAlias) return put({ vps: { sshAlias: next.alias, ...limits(next) } }, "");+ return put({ vpsServers: [...named, { name: next.name, sshAlias: next.alias, ...limits(next) }] }, "");+ };++ return (+ <div data-vps-connection className="flex max-w-[570px] flex-col gap-2">+ <p className="text-[12px] leading-4 text-ink-secondary">+ {t("keys.vps.descBefore")}+ <a href="https://github.com/milind-soni/OpenMausBot/blob/main/docs/byo-vps.md" target="_blank" rel="noopener noreferrer" className="text-accent-text hover:underline">+ {t("keys.vps.descLink")}+ </a>+ {t("keys.vps.descAfter")}+ </p>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.anyMachine")}</p>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.servers.hint")}</p>+ <div data-vps-servers className="flex flex-col gap-3.5 rounded-lg border border-hairline/40 bg-inset p-3.5">+ {servers.map((server, index) => (+ <div key={server.alias} className={cn(index > 0 && "border-t border-hairline/40 pt-3.5")}>+ <ServerCard+ server={server}+ defaults={defaults}+ busy={busy}+ disabled={busy !== null}+ onSave={(next) => save(server, next)}+ onRename={(next) => rename(server, next)}+ onRemove={() => remove(server)}+ />+ </div>+ ))}+ {servers.length > 0 && (+ <div className="flex flex-col gap-2">+ <button type="button" onClick={() => setDetails(!details)} aria-expanded={details} className="flex w-fit items-center gap-1 text-[12px] leading-4 text-ink-secondary hover:text-ink">+ <ChevronRight size={13} aria-hidden="true" className={cn("transition-transform motion-reduce:transition-none", details && "rotate-90")} />+ {t("keys.vps.details")}+ </button>+ {details && (+ <>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.servers.greyHint")}</p>+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.resourcesHelp")}</p>+ </>+ )}+ </div>+ )}+ </div>+ <AddServer hasDefault={Boolean(defaultAlias)} hosts={configHosts.filter((host) => !servers.some((server) => server.alias === host))} defaults={defaults} disabled={busy !== null} adding={busy === ""} onAdd={add} />+ {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>}+ </div>+ );+}diff --git a/src/components/keys/key-focus.ts b/src/components/keys/key-focus.tsindex c2d424033c..fe19805f2d 100644--- a/src/components/keys/key-focus.ts+++ b/src/components/keys/key-focus.ts@@ -21,11 +21,19 @@ function publish(next: KeyFocusRequest | null) {* uses the key): its section opens, the row scrolls into view, its field takes focus and the row lights up briefly.* With no key it opens the page at its first section. */export function openKeySettings(id?: KeyId, purpose?: KeyId): typeof OPEN_KEYS {+ requestKeyFocus(id, purpose);+ return OPEN_KEYS;+}++/** Asks the keys page for a row without opening Settings: for a caller that navigates to AI itself, with {@link KEYS_ANCHOR_FOR_FOCUS}. */+export function requestKeyFocus(id?: KeyId, purpose?: KeyId): void {nonce += 1;publish(id ? { id, row: purpose ?? id, nonce } : { nonce });- return OPEN_KEYS;}+/** The AI page anchor that opens Other services for a requested row without scrolling to its top block or listing AI providers first. */+export const KEYS_ANCHOR_FOR_FOCUS = "keys-focus";+export function finishKeyFocus(request: KeyFocusRequest) {if (latest?.nonce === request.nonce) publish(null);}diff --git a/src/components/settings/DesktopKinds.tsx b/src/components/settings/DesktopKinds.tsxindex f6b456a237..65becf0e95 100644--- a/src/components/settings/DesktopKinds.tsx+++ b/src/components/settings/DesktopKinds.tsx@@ -4,6 +4,7 @@ import { t } from "@/lib/i18n";import { productName } from "@/lib/brand";import { computerInventoryRequest } from "@/lib/computer-requests";import { useStoreSelector } from "@/state/store-select";+import { KEYS_ANCHOR_FOR_FOCUS, requestKeyFocus } from "../keys/key-focus";import { LocalComputerSection } from "../LocalComputerSection";import { SettingRow, SettingsGroup, SettingsLinkRow, SettingsMark, SettingsRows, StatusDot } from "../SettingsPrimitives";import { useAccountSummary } from "./account-summary";@@ -72,6 +73,7 @@ export function DesktopKinds() {void read<{ configured: boolean; available: boolean }>("vps").then(setVps);}, [cloudHome]);useEffect(load, [load]);+ const openKey = (id: "box" | "vps") => { requestKeyFocus(id); go("ai", KEYS_ANCHOR_FOR_FOCUS); };const summary = useAccountSummary();const others = useOtherPlaces("desktops");const myCloud = others.find((other) => other.kind === "cloud");@@ -102,9 +104,9 @@ export function DesktopKinds() {return (<SettingsGroup label={t("settings.desktops.kinds")} block="desktops"><SettingsRows icons>- {row(cloudKind, t("settings.desktops.cloud"), t("settings.desktops.cloudLine"), <Cloud />, () => go(ctx.plan && !cloud?.configured ? "plan" : "ai", ctx.plan && !cloud?.configured ? undefined : "ai-keys"), "cloud")}+ {row(cloudKind, t("settings.desktops.cloud"), t("settings.desktops.cloudLine"), <Cloud />, () => (ctx.plan && !cloud?.configured ? go("plan") : openKey("box")), "cloud")}{!cloudHome && row(privateKind, t("settings.desktops.private"), t("settings.desktops.privateLine"), <Laptop />, () => setSetup(true), "private")}- {(ctx.advanced || vps?.configured) && row(serversKind, t("settings.desktops.servers"), t("settings.desktops.serversLine"), <Server />, () => go("ai", "ai-keys"), "servers")}+ {(ctx.advanced || vps?.configured) && row(serversKind, t("settings.desktops.servers"), t("settings.desktops.serversLine"), <Server />, () => openKey("vps"), "servers")}</SettingsRows>{setup && <PrivateSetup status={local} onCheck={load} onClose={() => setSetup(false)} />}</SettingsGroup>diff --git a/src/components/settings/pages/PlacePages.tsx b/src/components/settings/pages/PlacePages.tsxindex 924fea4742..b4b05c90f5 100644--- a/src/components/settings/pages/PlacePages.tsx+++ b/src/components/settings/pages/PlacePages.tsx@@ -34,6 +34,7 @@ import { SkillsSection } from "../../SkillsSection";import { ThreadConcurrencySettings } from "../../ThreadConcurrencySettings";import { usePhonePlaceState } from "../phone-status";import { KeysPage } from "../../keys/KeysPage";+import { KEYS_ANCHOR_FOR_FOCUS } from "../../keys/key-focus";import { BrowserProfilesRow, ExperimentalFeaturesRow, NewBotEffortRow } from "../../AppSettingsRows";import { ServerUpdateRow } from "../../ServerUpdateRow";import { versionLine } from "../settings-context";@@ -120,9 +121,10 @@ export function AiPage() {const { ctx, anchor } = useSettingsShell();const [more, setMore] = useState(false);// Simple ends after Providers: Other services is one closed fold row, so the page fits one window.- const [services, setServices] = useState(ctx.advanced || anchor === "ai-keys");+ const asksForKeys = anchor === "ai-keys" || anchor === KEYS_ANCHOR_FOR_FOCUS;+ const [services, setServices] = useState(ctx.advanced || asksForKeys);// A key asked for by search or a link opens Other services whatever the fold says.- const shown = ctx.advanced || services || anchor === "ai-keys";+ const shown = ctx.advanced || services || asksForKeys;const count = KEY_SECTIONS.filter((section) => section.id !== "ai").length;return <><AdminOnly>diff --git a/src/locales/de.json b/src/locales/de.jsonindex a47f3f0bc2..b184a19ea1 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -1469,7 +1469,6 @@"keys.vps.descAfter": " für die benötigte Alias-Form an.","keys.vps.anyMachine": "Jeder Linux-Rechner mit Docker, den du per SSH erreichst, funktioniert, auch ein Computer in deinem Tailscale-Netzwerk: Trag seinen Tailscale-Namen als HostName des Alias ein.","keys.vps.aria": "SSH-Config-Alias des selbst gehosteten VPS",- "keys.vps.removeAlias": "Gespeicherten Alias entfernen","usage.title": "Nutzung","usage.bot.empty": "Für diesen Bot wurde noch keine Nutzung erfasst.","usage.bot.unpriced": "Dieser Anbieter meldet keinen Preis; Tokens werden gezählt.",@@ -4112,13 +4111,9 @@"chat.handoffExchange.loading": "Unterhaltung wird geladen…","chat.handoffExchange.failed": "Die Unterhaltung konnte nicht geladen werden.","chat.handoffExchange.empty": "Noch keine Nachrichten.",- "keys.vps.servers.title": "Benannte Server",- "keys.vps.servers.hint": "Füge weitere Server mit Namen hinzu. Jeder Bot kann dann in seinen eigenen Computer-Einstellungen einen davon wählen; der Alias oben bleibt der Standard.","keys.vps.servers.name": "Servername",- "keys.vps.servers.namePlaceholder": "Heimlabor","keys.vps.servers.alias": "SSH-Config-Alias des Servers","keys.vps.servers.add": "Hinzufügen",- "keys.vps.servers.removeAria": "{name} entfernen","botAccess.cloud.serverPick": "Server für diesen Bot wählen","botAccess.cloud.serverPickHint": "Wähle einen benannten Server oder gib einen anderen SSH-Alias ein.","botAccess.cloud.serverPickDefault": "Standardserver ({alias})",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 8362d24090..c8cc730340 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4301,15 +4301,24 @@"keys.vps.descAfter": " for the required SSH alias shape.","keys.vps.anyMachine": "Any Linux machine with Docker that you reach over SSH works, including a computer on your Tailscale network: use its Tailscale name as the alias's HostName.","keys.vps.aria": "Self-hosted VPS SSH config alias",- "keys.vps.removeAlias": "Remove the saved alias",- "keys.vps.servers.title": "Named servers",- "keys.vps.servers.hint": "Add more servers by name. Each bot can then pick one in its own computer settings; the alias above stays the default.",+ "keys.vps.col.memory": "Memory",+ "keys.vps.col.cpu": "CPU cores",+ "keys.vps.aliasLine": "SSH alias: {alias}",+ "keys.vps.unitGb": "GB",+ "keys.vps.unitCores": "cores",+ "keys.vps.edit": "Edit",+ "keys.vps.editAria": "Edit {name} name and alias",+ "keys.vps.lessAria": "Less: {what}",+ "keys.vps.moreAria": "More: {what}",+ "keys.vps.serverMemoryAria": "{name} memory (GB)",+ "keys.vps.serverCpusAria": "{name} CPU cores",+ "keys.vps.servers.addTitle": "Add server",+ "keys.vps.servers.greyHint": "Grey values are inherited. CPU pinning is optional: logical CPU IDs like 0,2 or 4-7; blank lets the host choose. A desktop that already exists keeps a removed pin until it is recreated.",+ "keys.vps.servers.hint": "Each bot picks one of these servers in its computer settings. Blank limits inherit the first server's.","keys.vps.servers.name": "Server name",- "keys.vps.servers.namePlaceholder": "Home lab",+ "keys.vps.servers.namePlaceholder": "Display name","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.",@@ -11516,5 +11525,12 @@"chat.handoffExchange.back": "Back","chat.handoffExchange.loading": "Loading the conversation…","chat.handoffExchange.failed": "Couldn't load the conversation.",- "chat.handoffExchange.empty": "No messages yet."+ "chat.handoffExchange.empty": "No messages yet.",+ "keys.vps.col.pin": "CPU pinning",+ "keys.vps.pinAuto": "Auto",+ "keys.vps.deleteAria": "Delete {name}",+ "keys.vps.serverPinAria": "{name} CPU pinning",+ "keys.vps.servers.aliasPlaceholder": "SSH alias",+ "keys.vps.details": "Limits and pinning details",+ "keys.vps.pinTooMany": "Pinning names {pinned} CPUs, more than the {cores} cores set. Lower the pinning or raise the cores."}diff --git a/src/locales/es.json b/src/locales/es.jsonindex fb9913dfe3..d4fd5dbc22 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -2970,7 +2970,6 @@"keys.vps.descAfter": " para ver la forma de alias requerida.","keys.vps.anyMachine": "Funciona cualquier equipo Linux con Docker al que llegues por SSH, también un ordenador de tu red de Tailscale: usa su nombre de Tailscale como HostName del alias.","keys.vps.aria": "Alias del SSH config del VPS propio",- "keys.vps.removeAlias": "Quitar el alias guardado","usage.title": "Uso","planUsage.title": "Uso del plan","planUsage.subtitle": "Margen restante en cada proveedor con sesión iniciada. Ventanas de 5 horas y semanales, cuando el plan las tiene.",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 6dab18f064..f9abefc871 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -1349,7 +1349,6 @@"keys.vps.descAfter": " pour la forme d’alias requise.","keys.vps.anyMachine": "Toute machine Linux avec Docker joignable en SSH convient, y compris un ordinateur de votre réseau Tailscale : utilisez son nom Tailscale comme HostName de l'alias.","keys.vps.aria": "Alias de la config SSH du VPS auto-hébergé",- "keys.vps.removeAlias": "Supprimer l’alias enregistré","usage.title": "Utilisation","usage.bot.empty": "Aucune utilisation enregistrée pour ce bot pour l’instant.","usage.bot.unpriced": "Ce fournisseur n’indique pas de prix ; les jetons sont comptés.",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 29c9cc340e..353133f1e3 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -1347,7 +1347,6 @@"keys.vps.descAfter": " देखें।","keys.vps.anyMachine": "SSH से पहुँचने वाली Docker वाली कोई भी Linux मशीन चलेगी, आपके Tailscale नेटवर्क का कंप्यूटर भी: alias के HostName में उसका Tailscale नाम डालें।","keys.vps.aria": "स्वयं-होस्टेड VPS का SSH config उपनाम",- "keys.vps.removeAlias": "सहेजा गया उपनाम हटाएँ","usage.title": "उपयोग","usage.bot.empty": "इस बॉट के लिए अभी तक कोई उपयोग दर्ज नहीं हुआ।","usage.bot.unpriced": "यह प्रदाता कीमत नहीं बताता; टोकन गिने जाते हैं।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 6c8a6d7376..4bb88562a7 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -4283,7 +4283,6 @@"keys.vps.descAfter": " per la forma richiesta dell'alias SSH.","keys.vps.anyMachine": "Funziona qualsiasi macchina Linux con Docker raggiungibile via SSH, anche un computer della tua rete Tailscale: usa il suo nome Tailscale come HostName dell'alias.","keys.vps.aria": "Alias della config SSH del VPS in proprio",- "keys.vps.removeAlias": "Rimuovi l'alias salvato","usage.title": "Utilizzo","planUsage.title": "Utilizzo del piano","planUsage.subtitle": "Quota restante su ogni fornitore a cui hai effettuato l'accesso. Finestre di 5 ore e settimanali, quando il piano le prevede.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 31ff6ed551..99a1ce5d15 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -3647,7 +3647,6 @@"keys.vps.descAfter": "をご覧ください。","keys.vps.anyMachine": "SSH で接続できる Docker 入りの Linux マシンならどれでも使えます。Tailscale ネットワーク上のコンピューターも可能です。エイリアスの HostName にその Tailscale 名を指定してください。","keys.vps.aria": "自分の VPS の SSH config エイリアス",- "keys.vps.removeAlias": "保存したエイリアスを削除","usage.title": "使用状況","planUsage.title": "プランの使用状況","planUsage.subtitle": "サインイン済みプロバイダーごとの残り利用枠です。プランに応じて、5 時間枠と週間枠を表示します。",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex fb1a3056fa..656b39fae0 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -3466,7 +3466,6 @@"keys.vps.descAfter": "를 참고하세요.","keys.vps.anyMachine": "SSH로 접속할 수 있고 Docker가 있는 Linux 컴퓨터라면 무엇이든 됩니다. Tailscale 네트워크의 컴퓨터도 가능합니다. 별칭의 HostName에 그 Tailscale 이름을 넣으세요.","keys.vps.aria": "직접 호스팅하는 VPS의 SSH 설정 별칭",- "keys.vps.removeAlias": "저장된 별칭 제거","usage.title": "사용량","planUsage.title": "요금제 사용량","planUsage.subtitle": "로그인한 각 제공자의 남은 허용량이에요. 요금제에 있으면 5시간 단위와 주간 단위로 보여 줘요.",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 451b7c3723..ce64f17051 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -3191,7 +3191,6 @@"keys.vps.descAfter": " aby poznać wymagany format aliasu SSH.","keys.vps.anyMachine": "Działa każdy komputer z Linuksem i Dockerem dostępny przez SSH, także komputer w Twojej sieci Tailscale: jako HostName aliasu podaj jego nazwę w Tailscale.","keys.vps.aria": "Alias konfiguracji SSH samodzielnie hostowanego VPS",- "keys.vps.removeAlias": "Usuń zapisany alias","usage.title": "Wykorzystanie","planUsage.title": "Wykorzystanie planu","planUsage.subtitle": "Pozostały limit u każdego zalogowanego dostawcy. Okna 5-godzinne i tygodniowe, jeśli plan je ma.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 039e2bfbfd..290d401032 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -4094,14 +4094,9 @@"keys.vps.descAfter": " para ver o formato de apelido SSH exigido.","keys.vps.anyMachine": "Funciona qualquer máquina Linux com Docker que você acesse por SSH, inclusive um computador da sua rede Tailscale: use o nome dele no Tailscale como HostName do alias.","keys.vps.aria": "Apelido na configuração SSH do VPS próprio",- "keys.vps.removeAlias": "Remover o apelido salvo",- "keys.vps.servers.title": "Servidores com nome",- "keys.vps.servers.hint": "Adicione mais servidores com um nome. Cada bot pode escolher um deles nas próprias configurações de computador; o apelido acima continua sendo o padrão.","keys.vps.servers.name": "Nome do servidor",- "keys.vps.servers.namePlaceholder": "Laboratório em casa","keys.vps.servers.alias": "Apelido do servidor na configuração SSH","keys.vps.servers.add": "Adicionar",- "keys.vps.servers.removeAria": "Remover {name}","usage.title": "Uso","planUsage.title": "Uso do plano","planUsage.subtitle": "Saldo restante em cada provedor em que você fez login. Períodos de 5 horas e semanais, quando disponíveis no plano.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex f8c982c37f..efac120b44 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -3233,7 +3233,6 @@"keys.vps.descAfter": " для требуемого формата SSH-алиаса.","keys.vps.anyMachine": "Подойдёт любой компьютер на Linux с Docker, доступный по SSH, в том числе компьютер в вашей сети Tailscale: укажите его имя в Tailscale как HostName псевдонима.","keys.vps.aria": "Алиас SSH-конфига для собственного VPS",- "keys.vps.removeAlias": "Удалить сохранённый алиас","usage.title": "Использование","planUsage.title": "Израсходовано по плану","planUsage.subtitle": "Оставшийся лимит на каждом подключённом провайдере: 5-часовые и недельные окна, если они есть у этого плана.",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 10d65bd745..860bf79c80 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -2624,7 +2624,6 @@"keys.vps.descAfter": " bakın.","keys.vps.anyMachine": "SSH ile ulaştığınız ve Docker çalıştıran her Linux makinesi olur, Tailscale ağınızdaki bir bilgisayar da: takma adın HostName değerine onun Tailscale adını yazın.","keys.vps.aria": "Kendi barındırdığınız VPS SSH yapılandırma takma adı",- "keys.vps.removeAlias": "Kaydedilen takma adı kaldır","usage.title": "Kullanım","planUsage.title": "Plan kullanımı","planUsage.subtitle": "Oturum açılmış her sağlayıcıdaki kalan hak. Planda mevcut olduğunda 5 saatlik ve haftalık pencereler.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 6534585587..f1afa9516e 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -1589,7 +1589,6 @@"keys.vps.descAfter": " для потрібної форми SSH-аліаса.","keys.vps.anyMachine": "Підійде будь-який комп'ютер на Linux із Docker, доступний через SSH, зокрема комп'ютер у вашій мережі Tailscale: вкажіть його ім'я в Tailscale як HostName псевдоніма.","keys.vps.aria": "Аліас SSH-конфігу власного VPS",- "keys.vps.removeAlias": "Прибрати збережений аліас","usage.title": "Використання","usage.bot.empty": "Для цього бота ще не записано використання.","usage.bot.unpriced": "Цей провайдер не повідомляє ціну; токени підраховуються.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 192388c530..3b91335f7f 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -2624,7 +2624,6 @@"keys.vps.descAfter": " để biết định dạng bí danh SSH bắt buộc.","keys.vps.anyMachine": "Mọi máy Linux có Docker mà bạn truy cập được qua SSH đều dùng được, kể cả máy trong mạng Tailscale của bạn: dùng tên Tailscale của máy làm HostName cho alias.","keys.vps.aria": "Bí danh cấu hình SSH của VPS tự quản trị",- "keys.vps.removeAlias": "Xóa bí danh đã lưu","usage.title": "Mức sử dụng","planUsage.title": "Mức sử dụng gói","planUsage.subtitle": "Hạn mức còn lại trên mỗi nhà cung cấp đã đăng nhập. Khung thời gian 5 giờ và hàng tuần, nếu gói đó có áp dụng.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 7e45ff466d..eb1ae2bdcb 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -3802,7 +3802,6 @@"keys.vps.descAfter": ",以了解所需的 SSH 別名格式。","keys.vps.anyMachine": "任何可透過 SSH 連線、裝有 Docker 的 Linux 電腦都可以,包括你 Tailscale 網路中的電腦:把它的 Tailscale 名稱填為別名的 HostName。","keys.vps.aria": "自架 VPS 的 SSH 設定別名",- "keys.vps.removeAlias": "移除已儲存的別名","usage.title": "用量","planUsage.title": "方案用量","planUsage.subtitle": "每個已登入供應商的剩餘額度。若方案有 5 小時與每週時段限制,也會一併顯示。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex fa1aa21aa7..7a9e7e1191 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -3836,7 +3836,6 @@"keys.vps.descAfter": "。","keys.vps.anyMachine": "任何可通过 SSH 访问、装有 Docker 的 Linux 机器都可以,包括你 Tailscale 网络中的电脑:把它的 Tailscale 名称填为别名的 HostName。","keys.vps.aria": "自建 VPS 的 SSH config 别名",- "keys.vps.removeAlias": "移除已保存的别名","usage.title": "用量","planUsage.title": "方案用量","planUsage.subtitle": "每个已登录提供方的剩余额度;若该方案有 5 小时和每周时间窗,也会显示。",diff --git a/src/state/config-status.ts b/src/state/config-status.tsindex 997bf566ec..e0da631647 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; memoryGb?: number; cpus?: number }[]; memoryGb?: number; cpus?: number };+ vps: { configured: boolean; sshAlias: string; servers?: { name: string; sshAlias: string; memoryGb?: number; cpus?: number; cpuset?: string }[]; memoryGb?: number; cpus?: number; cpuset?: string };rooms: { turnTimeoutMinutes: number };/** Per-call ceiling (minutes) for a bot's MCP tools. Absent from servers* older than the setting; read it with mcpCallTimeoutMinutes(). */