Skip to content

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

Address review comments on the VPS limits

Liame4181accdc7f
diff --git a/docs/byo-vps.md b/docs/byo-vps.md
index f14e5983d2..57d76af43d 100644
--- a/docs/byo-vps.md
+++ b/docs/byo-vps.md
@@ -208,8 +208,8 @@ name more CPUs than the cores field, and a named server never inherits the defau
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
+its limits until it stops; the next start applies the current ones, so recreating it is not needed. 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.
diff --git a/server/container-limits.test.ts b/server/container-limits.test.ts
index 0b363304c0..c454afffc3 100644
--- a/server/container-limits.test.ts
+++ b/server/container-limits.test.ts
@@ -43,3 +43,10 @@ describe("CPU pinning", () => {
expect(vpsLimits(cfg, "pin")).toEqual({ memoryGb: 6, cpus: 3, cpuset: "2" });
});
});
+
+describe("CPU pinning size", () => {
+ it("counts distinct CPUs when ranges overlap", () => {
+ expect(cpusetSize("0-3,2-5")).toBe(6);
+ expect(cpusetSize("0,2,4-7")).toBe(6);
+ });
+});
diff --git a/server/container-limits.ts b/server/container-limits.ts
index 2174c9392f..3c47f9aced 100644
--- a/server/container-limits.ts
+++ b/server/container-limits.ts
@@ -13,12 +13,14 @@ export interface DesktopResources {
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. */
+/** How many distinct CPUs a valid `cpuset` names: "0,2" is 2, "4-7" is 4, "0-3,2-5" is 6. */
export function cpusetSize(value: string): number {
- return value.split(",").reduce((total, part) => {
+ const ids = new Set<number>();
+ for (const part of value.split(",")) {
const [from, to = from] = part.split("-").map(Number);
- return total + (to! - from! + 1);
- }, 0);
+ for (let id = from!; id <= to!; id++) ids.add(id);
+ }
+ return ids.size;
}
export function isValidCpuset(value: unknown): value is string {
@@ -56,11 +58,26 @@ export function raisePidsLimit(
void Promise.resolve().then(() => docker(["update", "--pids-limit", String(PIDS_LIMIT), container], 15_000)).catch(() => {});
}
-/** A stopped desktop takes the configured limits before it starts. An engine without `update --memory` keeps the old ones. */
+/** A stopped desktop takes the configured limits before it starts. An engine without `update --memory` keeps the old ones,
+ * so a failed update is returned for the caller to report, never thrown: the desktop still starts. */
export async function applyResourcesBeforeStart(
container: string,
resources: DesktopResources,
docker: (args: string[], timeoutMs?: number) => Promise<unknown>,
-): Promise<void> {
- await docker(["update", ...resourceArgs(resources, { swap: true }), container], 15_000).catch(() => {});
+): Promise<string | null> {
+ return docker(["update", ...resourceArgs(resources, { swap: true }), container], 15_000).then(
+ () => null,
+ (error: unknown) => `The desktop started with its previous limits: ${error instanceof Error ? error.message : String(error)}`,
+ );
+}
+
+/** Starts a stopped desktop after applying the limits; returns the warning when they could not be applied. */
+export async function startWithResources(
+ container: string,
+ resources: DesktopResources,
+ docker: (args: string[], timeoutMs?: number) => Promise<unknown>,
+): Promise<string | null> {
+ const warning = await applyResourcesBeforeStart(container, resources, docker);
+ await docker(["start", container]);
+ return warning;
}
diff --git a/server/routes/config.ts b/server/routes/config.ts
index b7b8fab6cf..6b36d529ed 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -207,7 +207,8 @@ 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);
+ providerConfigBusy.set(true);
+ const overHost = await vpsHostLimitProblem(cfg, patch).finally(() => providerConfigBusy.set(false));
if (overHost) return json(res, 400, { error: overHost });
}
if (patch.browserProfiles !== undefined && body.expectedBrowserProfiles !== undefined) {
diff --git a/server/ssh-config-hosts.test.ts b/server/ssh-config-hosts.test.ts
index a68daa6b51..2b0c362569 100644
--- a/server/ssh-config-hosts.test.ts
+++ b/server/ssh-config-hosts.test.ts
@@ -31,3 +31,23 @@ describe("sshConfigHosts", () => {
expect(sshConfigHosts("/h/.ssh", files({ "/h/.ssh/config": "Host bad;name ok-name user@host\n" }))).toEqual(["ok-name"]);
});
});
+
+describe("sshConfigHosts quoting and wildcards", () => {
+ it("reads quoted names and quoted Include paths with spaces", () => {
+ const hosts = sshConfigHosts("/h/.ssh", files({
+ "/h/.ssh/config": 'Host "prod" # note\nInclude "work hosts/a.conf"\n',
+ "/h/.ssh/work hosts/a.conf": "Host staging\n",
+ }));
+ expect(hosts).toEqual(["prod", "staging"]);
+ });
+
+ it("expands wildcards in directory components", () => {
+ const map: Record<string, string> = {
+ "/h/.ssh/config": "Include config.d/*/*.conf\n",
+ "/h/.ssh/config.d/a/one.conf": "Host one\n",
+ "/h/.ssh/config.d/b/two.conf": "Host two\n",
+ };
+ const children = (directory: string) => [...new Set(Object.keys(map).filter((path) => path.startsWith(`${directory}/`)).map((path) => path.slice(directory.length + 1).split("/")[0]!))].sort();
+ expect(sshConfigHosts("/h/.ssh", { read: (path) => map[path] ?? null, list: children })).toEqual(["one", "two"]);
+ });
+});
diff --git a/server/ssh-config-hosts.ts b/server/ssh-config-hosts.ts
index 62ee754f1d..c006c2efaa 100644
--- a/server/ssh-config-hosts.ts
+++ b/server/ssh-config-hosts.ts
@@ -1,12 +1,13 @@
import { readdirSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { dirname, isAbsolute, join } from "node:path";
+import { 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;
+const MAX_INCLUDE_TARGETS = 200;
export interface SshConfigFiles {
read(path: string): string | null;
@@ -33,15 +34,51 @@ const nodeFiles: SshConfigFiles = {
const wildcard = (pattern: string) => /[*?]/.test(pattern);
+const segmentMatcher = (segment: string) =>
+ new RegExp(`^${segment.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);
+
+/** Expands `*` and `?` in every path segment, in lexical order, like OpenSSH's Include. */
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));
+ let paths = [path.startsWith("/") ? "/" : ""];
+ for (const segment of path.split("/").filter(Boolean)) {
+ const next: string[] = [];
+ for (const parent of paths) {
+ if (!wildcard(segment)) next.push(join(parent, segment));
+ else for (const name of files.list(parent || ".").filter((entry) => segmentMatcher(segment).test(entry))) next.push(join(parent, name));
+ }
+ paths = next.slice(0, MAX_INCLUDE_TARGETS);
+ }
+ return paths;
+}
+
+/** Splits a config line into arguments the way ssh_config does: double quotes group, `=` may follow the keyword, `#` outside quotes starts a comment. */
+function tokenize(line: string): string[] {
+ const tokens: string[] = [];
+ let current = "";
+ let started = false;
+ let quoted = false;
+ for (const char of line) {
+ if (quoted) {
+ if (char === '"') quoted = false;
+ else current += char;
+ } else if (char === '"') {
+ quoted = true;
+ started = true;
+ } else if (char === "#") {
+ break;
+ } else if (/\s/.test(char) || (char === "=" && tokens.length === 0)) {
+ if (started) tokens.push(current);
+ current = "";
+ started = false;
+ } else {
+ current += char;
+ started = true;
+ }
+ }
+ if (started) tokens.push(current);
+ return tokens;
}
function collect(path: string, sshDir: string, files: SshConfigFiles, depth: number, seen: Set<string>, out: string[]): void {
@@ -50,13 +87,12 @@ function collect(path: string, sshDir: string, files: SshConfigFiles, depth: num
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 [keyword = "", ...rest] = tokenize(raw);
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);
+ for (const pattern of rest) for (const target of includeTargets(pattern, sshDir, files)) collect(target, sshDir, files, depth + 1, seen, out);
}
if (out.length >= MAX_HOSTS) return;
}
diff --git a/server/vps-computer.ts b/server/vps-computer.ts
index 032545774c..826a35526b 100644
--- a/server/vps-computer.ts
+++ b/server/vps-computer.ts
@@ -20,7 +20,7 @@ import {
MANAGED_LABEL,
} from "./container-computer.ts";
import { desktopCapArgs, dockerSecurityIsHardened, type DockerHardeningConfig } from "./container-isolation.ts";
-import { applyResourcesBeforeStart, DEFAULT_DESKTOP_RESOURCES, PIDS_LIMIT, raisePidsLimit, resourceArgs, type DesktopResources } from "./container-limits.ts";
+import { startWithResources, DEFAULT_DESKTOP_RESOURCES, PIDS_LIMIT, raisePidsLimit, resourceArgs, type DesktopResources } from "./container-limits.ts";
import { DATA_DIR, isValidSshAlias, vpsResources, vpsSshAlias, type AppConfig } from "./config.ts";
import { augmentedPath } from "./env-path.ts";
import { COMMAND_TIMEOUT_KILL_GRACE_MS, defaultRunner, VpsHostUnreachableError, type VpsCommandRunner } from "./vps-command.ts";
@@ -118,6 +118,7 @@ export interface VpsComputerStatus {
container_name: string;
container_id: string | null;
image_id: string | null;
+ /** Set when a start could not apply the saved limits: the desktop runs with its previous ones. */ warning?: string;
}
export interface ManagedVpsOwner {
@@ -974,6 +975,7 @@ export async function vpsComputerAction(
const run = (args: string[], timeoutMs = 2 * 60_000) => runner(vpsDockerArgs(alias, args), { timeoutMs });
const containerRef = before.container_id ?? before.container_name;
+ let warning: string | null = null;
if (action === "provision") {
if (before.container === "missing") {
let imageRef = before.image ? before.image_id : null;
@@ -986,16 +988,14 @@ export async function vpsComputerAction(
} else {
assertUsableContainer(before);
if (before.container === "stopped") {
- await applyResourcesBeforeStart(containerRef, vpsResources(cfg), run);
- await run(["start", containerRef]);
+ warning = await startWithResources(containerRef, vpsResources(cfg), run);
}
}
} else if (action === "start") {
if (before.container === "missing") throw Object.assign(new Error("No VPS container exists for this bot"), { status: 409 });
if (before.container === "running") throw Object.assign(new Error("The VPS container is already running"), { status: 409 });
assertUsableContainer(before);
- await applyResourcesBeforeStart(containerRef, vpsResources(cfg), run);
- await run(["start", containerRef]);
+ warning = await startWithResources(containerRef, vpsResources(cfg), run);
} else if (action === "remove") {
// Skips the usability check (remove escapes a broken container); the ownership labels are the only gate.
if (before.container === "missing") return before;
@@ -1012,7 +1012,7 @@ export async function vpsComputerAction(
assertUsableContainer(before);
await run(["stop", containerRef]);
}
- return await (action === "stop" ? computeVpsComputerStatus(cfg, botId, runner) : waitForVpsReady(cfg, botId, runner));
+ return Object.assign(await (action === "stop" ? computeVpsComputerStatus(cfg, botId, runner) : waitForVpsReady(cfg, botId, runner)), warning ? { warning } : {});
} finally {
invalidateVpsStatus(key);
}
diff --git a/server/vps-host-limits.test.ts b/server/vps-host-limits.test.ts
index ed001a4b55..80438e272d 100644
--- a/server/vps-host-limits.test.ts
+++ b/server/vps-host-limits.test.ts
@@ -35,3 +35,21 @@ describe("VPS host limits", () => {
expect(host).toHaveBeenCalledTimes(5);
});
});
+
+describe("VPS host limits across servers", () => {
+ const host = async () => ({ cpus: 4, memoryBytes: 16 * GIB });
+ it("does not check the default server when its alias is cleared", async () => {
+ const small = async () => ({ cpus: 1, memoryBytes: 16 * GIB });
+ expect(await vpsHostLimitProblem({ vps: { sshAlias: "main", cpus: 2 } }, { vps: { sshAlias: "" } }, small)).toBeNull();
+ });
+ it("checks a named server that inherits a raised default", async () => {
+ const cfg = { vps: { sshAlias: "main", cpus: 2 }, vpsServers: [{ name: "Small", sshAlias: "small" }] };
+ const capacity = async (alias: string) => (alias === "small" ? { cpus: 2, memoryBytes: 16 * GIB } : { cpus: 8, memoryBytes: 16 * GIB });
+ expect(await vpsHostLimitProblem(cfg, { vps: { cpus: 4 } }, capacity)).toContain("small has 2 CPU cores");
+ });
+ it("refuses a pin larger than the effective core limit", async () => {
+ const cfg = { vps: { sshAlias: "main", cpus: 2 }, vpsServers: [] };
+ const patch = { vpsServers: [{ name: "Pinned", sshAlias: "pinned", cpuset: "0-3" }] };
+ expect(await vpsHostLimitProblem(cfg, patch, host)).toContain("pins 4 CPUs");
+ });
+});
diff --git a/server/vps-host-limits.ts b/server/vps-host-limits.ts
index 573a0ec369..6380ce7926 100644
--- a/server/vps-host-limits.ts
+++ b/server/vps-host-limits.ts
@@ -1,4 +1,6 @@
import type { AppConfig, VpsServer } from "./config.ts";
+import { cpusetSize } from "./container-limits.ts";
+import { vpsLimits } from "./vps-hosts.ts";
import { defaultRunner, vpsDockerArgs, type VpsCommandRunner } from "./vps-computer.ts";
export interface HostCapacity { cpus: number; memoryBytes: number }
@@ -38,26 +40,33 @@ export function hostLimitProblem(alias: string, host: HostCapacity, limits: { cp
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. */
+/** The config as it will be once `patch` is saved: an omitted default alias is kept, an empty one clears it, and an empty pin removes it. */
+function afterPatch(cfg: AppConfig, patch: Patch): AppConfig {
+ if (patch.vps === undefined && patch.vpsServers === undefined) return cfg;
+ const { sshAlias, cpus, memoryGb, cpuset } = patch.vps ?? {};
+ const vps = { ...cfg.vps, ...(sshAlias === undefined ? {} : { sshAlias }), ...(cpus === undefined ? {} : { cpus }), ...(memoryGb === undefined ? {} : { memoryGb }) };
+ if (patch.vps && "cpuset" in patch.vps) delete vps.cpuset;
+ if (cpuset) vps.cpuset = cpuset;
+ return { ...cfg, vps, vpsServers: patch.vpsServers ?? cfg.vpsServers };
+}
+
+const sameLimits = (a: Limits, b: Limits) => a.cpus === b.cpus && a.cpuset === b.cpuset && a.memoryGb === b.memoryGb;
+
+/** Checks each CPU and memory limit this save adds or changes, as each server will effectively have it, against what the machine has. */
export async function vpsHostLimitProblem(cfg: AppConfig, patch: Patch, capacity: (alias: string) => Promise<HostCapacity | null> = vpsHostCapacity): Promise<string | null> {
+ const after = afterPatch(cfg, patch);
+ const aliases = new Set<string>();
+ if (after.vps?.sshAlias) aliases.add(after.vps.sshAlias);
+ for (const server of after.vpsServers ?? []) aliases.add(server.sshAlias);
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 } : {}) });
+ for (const alias of aliases) {
+ const limits = vpsLimits(after, alias);
+ if (limits.cpuset && limits.cpus !== undefined && cpusetSize(limits.cpuset) > limits.cpus) {
+ return `${alias} pins ${cpusetSize(limits.cpuset)} CPUs (${limits.cpuset}), more than its ${limits.cpus} cores`;
}
+ const known = alias === cfg.vps?.sshAlias || (cfg.vpsServers ?? []).some((server) => server.sshAlias === alias);
+ const hasLimits = limits.cpus !== undefined || limits.memoryGb !== undefined || Boolean(limits.cpuset);
+ if (hasLimits && !(known && sameLimits(limits, vpsLimits(cfg, alias)))) targets.push({ alias, ...limits });
}
const hosts = new Map<string, Promise<HostCapacity | null>>();
for (const target of targets) {
diff --git a/src/components/keys/VpsServersPanel.tsx b/src/components/keys/VpsServersPanel.tsx
index 7b51028385..7a47d3bcff 100644
--- a/src/components/keys/VpsServersPanel.tsx
+++ b/src/components/keys/VpsServersPanel.tsx
@@ -343,7 +343,7 @@ export function VpsConnection() {
};
const add = (next: { name: string; alias: string } & Limits) => {
- if (!defaultAlias) return put({ vps: { sshAlias: next.alias, ...limits(next) } }, "");
+ if (!defaultAlias) return put({ vps: { sshAlias: next.alias, ...limits(next), cpuset: next.cpuset ?? "" } }, "");
return put({ vpsServers: [...named, { name: next.name, sshAlias: next.alias, ...limits(next) }] }, "");
};
diff --git a/src/components/settings/pages/PlacePages.tsx b/src/components/settings/pages/PlacePages.tsx
index b4b05c90f5..4f636167a5 100644
--- a/src/components/settings/pages/PlacePages.tsx
+++ b/src/components/settings/pages/PlacePages.tsx
@@ -123,8 +123,8 @@ export function AiPage() {
// Simple ends after Providers: Other services is one closed fold row, so the page fits one window.
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 || asksForKeys;
+ useEffect(() => { if (asksForKeys) setServices(true); }, [asksForKeys]);
+ const shown = ctx.advanced || services;
const count = KEY_SECTIONS.filter((section) => section.id !== "ai").length;
return <>
<AdminOnly>