Skip to content

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

VPS settings: one server editor on the existing rows

milind-soni1e655615a628
diff --git a/src/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.ts
index ca866e576f..1c7f50fc6e 100644
--- a/src/components/keys/KeysPage.dom.test.ts
+++ b/src/components/keys/KeysPage.dom.test.ts
@@ -12,17 +12,7 @@ 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");
@@ -84,7 +74,6 @@ function paste(input: HTMLInputElement, text: string) {
beforeEach(() => {
setLocale("en");
- fx.sshHosts = [];
fx.api.mockReset();
fx.dispatch.mockReset();
fx.refreshModels.mockReset();
@@ -556,11 +545,16 @@ describe("Boat's credit offer on the Boat card", () => {
});
describe("Self-hosted VPS servers", () => {
- const status = (vps: Record<string, unknown>) => ({ ...fx.config, vps: { memoryGb: 4, cpus: 2, ...vps } });
+ const status = (vps: Record<string, unknown>) => ({ ...fx.config, vps: { configured: true, memoryGb: 4, cpus: 2, servers: [], ...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 field = (label: string) => host.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`)!;
+ const button = (scope: ParentNode, text: string) => [...scope.querySelectorAll<HTMLButtonElement>("button")].find((candidate) => candidate.textContent === text)!;
const lastBody = () => JSON.parse((fx.api.mock.lastCall![1] as RequestInit).body as string);
+ const echo = (base: Record<string, unknown>) => async (_path: string, init: RequestInit) => {
+ const body = JSON.parse(init.body as string);
+ return status({ ...base, ...(body.vps ? { ...body.vps, configured: Boolean(body.vps.sshAlias) } : {}), ...(body.vpsServers ? { servers: body.vpsServers } : {}) });
+ };
it("says any Linux machine with Docker over SSH works, including one on a Tailscale network", async () => {
const { VpsConnection } = await import("./VpsServersPanel");
@@ -570,145 +564,115 @@ describe("Self-hosted VPS servers", () => {
expect(text).toContain("Tailscale name as the alias's HostName");
});
- 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 () => {
+ it("saves the first alias as the default server, then shows it with its limits", 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 }));
+ fx.api.mockImplementation(echo({}));
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" }] });
+ expect(aliases()).toEqual([]);
+ type(field("Self-hosted VPS SSH config alias"), "production-vps");
+ await answered(() => button(host, "Save").click());
+ expect(lastBody()).toEqual({ vps: { sshAlias: "production-vps" } });
+ expect(aliases()).toEqual(["production-vps"]);
+ expect(field("production-vps memory (GB)").value).toBe("4");
+ expect(field("production-vps CPU cores").value).toBe("2");
});
- it("refuses a pinning that names more CPUs than the cores field", async () => {
+ it("adds and removes named servers as one list, leaving the default alias alone", async () => {
const { VpsConnection } = await import("./VpsServersPanel");
- setConfig(status({ configured: true, sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps", cpus: 4 }] }));
+ setConfig(status({ sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps" }] }));
+ fx.api.mockImplementation(echo({ sshAlias: "production-vps" }));
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);
+ expect(aliases()).toEqual(["production-vps", "office-vps"]);
+ type(field("Server name"), " Home lab ");
+ type(field("Server SSH config alias"), "home-lab");
+ await answered(() => button(host, "Add").click());
+ expect(lastBody()).toEqual({ vpsServers: [{ name: "Office", sshAlias: "office-vps" }, { name: "Home lab", sshAlias: "home-lab" }] });
+ expect(aliases()).toEqual(["production-vps", "office-vps", "home-lab"]);
+ expect(field("Server name").value).toBe("");
+ await answered(() => host.querySelector<HTMLButtonElement>('button[aria-label="Remove Office"]')!.click());
+ expect(lastBody()).toEqual({ vpsServers: [{ name: "Home lab", sshAlias: "home-lab" }] });
+ expect(aliases()).toEqual(["production-vps", "home-lab"]);
+ expect(field("Self-hosted VPS SSH config alias").value).toBe("production-vps");
});
- it("saves the default server's limits and clears its pinning with an empty string", async () => {
+ it("renames a named server and saves its own limits, an empty one using the default's", 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: [] }));
+ setConfig(status({ sshAlias: "production-vps", memoryGb: 6, cpus: 3, servers: [{ name: "Office", sshAlias: "office-vps", cpus: 4 }] }));
+ fx.api.mockImplementation(echo({ sshAlias: "production-vps", memoryGb: 6, cpus: 3 }));
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 office = rowFor("office-vps");
+ expect(office.textContent).toContain("office-vps");
+ expect(field("Office memory (GB)").value).toBe("");
+ expect(field("Office memory (GB)").placeholder).toBe("6");
+ expect(field("Office CPU cores").value).toBe("4");
+ expect(button(office, "Save").disabled).toBe(true);
+ type(field("office-vps server name"), "HQ");
+ type(field("Office memory (GB)"), "8");
+ type(field("Office CPU cores"), "");
+ await answered(() => button(office, "Save").click());
+ expect(lastBody()).toEqual({ vpsServers: [{ name: "HQ", sshAlias: "office-vps", memoryGb: 8 }] });
+ expect(field("HQ memory (GB)").value).toBe("8");
+ expect(button(rowFor("office-vps"), "Save").disabled).toBe(true);
+ });
+
+ it("saves the default server's limits with its alias, an empty field meaning 4 GB and 2 cores", 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 }));
+ setConfig(status({ sshAlias: "production-vps", memoryGb: 8, cpus: 4 }));
+ fx.api.mockImplementation(echo({ sshAlias: "production-vps" }));
render(() => createElement(VpsConnection, { key: "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(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("");
+ type(field("production-vps memory (GB)"), "16");
+ type(field("production-vps CPU cores"), "");
+ await answered(() => button(rowFor("production-vps"), "Save").click());
+ expect(lastBody()).toEqual({ vps: { sshAlias: "production-vps", memoryGb: 16, cpus: 2 } });
});
- it("deletes servers in any order: a named one, then the default hands over to the next", async () => {
+ it("keeps Save off for a limit out of range or not a whole number", 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 }] });
- });
+ setConfig(status({ sshAlias: "production-vps" }));
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: [] });
+ const save = () => button(rowFor("production-vps"), "Save");
+ for (const bad of ["1", "129", "2.5"]) {
+ type(field("production-vps memory (GB)"), bad);
+ expect(save().disabled).toBe(true);
+ expect(field("production-vps memory (GB)").getAttribute("aria-invalid")).toBe("true");
+ }
+ type(field("production-vps memory (GB)"), "12");
+ expect(save().disabled).toBe(false);
+ type(field("production-vps CPU cores"), "65");
+ expect(save().disabled).toBe(true);
});
- it("clears the default alias when the default is the only server", async () => {
+ it("removes the default server, says what the server answered, and offers the alias field again", async () => {
const { VpsConnection } = await import("./VpsServersPanel");
- setConfig(status({ configured: true, sshAlias: "production-vps", servers: [] }));
- fx.api.mockImplementation(async () => status({ configured: false, sshAlias: "", servers: [] }));
+ setConfig(status({ sshAlias: "production-vps", servers: [{ name: "Office", sshAlias: "office-vps" }] }));
+ fx.api.mockImplementation(async () => ({ ...status({ configured: false, sshAlias: "", servers: [{ name: "Office", sshAlias: "office-vps" }] }), notice: "Removed. production-vps could not be reached" }));
render(() => createElement(VpsConnection, { key: "vps" }));
- await answered(() => click('button[aria-label="Delete production-vps"]'));
+ await answered(() => host.querySelector<HTMLButtonElement>('button[aria-label="Remove production-vps"]')!.click());
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");
+ expect(aliases()).toEqual(["office-vps"]);
+ expect(host.querySelector("[data-vps-connection] [role=status]")!.textContent).toContain("could not be reached");
+ expect(field("Self-hosted VPS SSH config alias").value).toBe("");
});
- it("offers the hosts from the SSH config as a dropdown, leaving out servers already listed", async () => {
+ it("shows why a limit was refused on its own row and keeps what was typed", 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 }));
+ setConfig(status({ sshAlias: "production-vps" }));
+ fx.api.mockRejectedValue(new Error("production-vps has 2 CPU cores in all. Choose 2 or fewer."));
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 }] });
+ type(field("production-vps CPU cores"), "8");
+ await answered(() => button(rowFor("production-vps"), "Save").click());
+ expect(rowFor("production-vps").querySelector("[role=alert]")!.textContent).toContain("2 CPU cores in all");
+ expect(field("production-vps CPU cores").value).toBe("8");
});
- it("shows why a server was refused and keeps what was typed", async () => {
+ it("shows why a named 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-connection] [role=alert]")!.textContent).toContain("own SSH alias");
- expect(host.querySelector<HTMLInputElement>('input[aria-label="Server name"]')!.value).toBe("Lab");
+ type(field("Server name"), "Lab");
+ type(field("Server SSH config alias"), "lab");
+ await answered(() => button(host, "Add").click());
+ expect(host.querySelector("[data-vps-servers] [role=alert]")!.textContent).toContain("own SSH alias");
+ expect(field("Server name").value).toBe("Lab");
});
});
diff --git a/src/components/keys/VpsServerEditor.tsx b/src/components/keys/VpsServerEditor.tsx
new file mode 100644
index 0000000000..de819e9fe9
--- /dev/null
+++ b/src/components/keys/VpsServerEditor.tsx
@@ -0,0 +1,174 @@
+import { useEffect, useState, useSyncExternalStore } from "react";
+import { Loader2 } from "lucide-react";
+import { api, type ConfigStatus } from "@/state/store";
+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import { SETTINGS_INLINE_INPUT } from "../SettingsPrimitives";
+import { KEY_FIELD } from "./KeyRow";
+
+type VpsStatus = ConfigStatus["vps"];
+export type VpsNamedServer = NonNullable<VpsStatus["servers"]>[number];
+type Range = { min: number; max: number; fallback: number };
+
+/** The server's limits for one desktop (server/container-limits.ts); empty is "not set". */
+const MEMORY_GB: Range = { min: 2, max: 128, fallback: 4 };
+const CPUS: Range = { min: 1, max: 64, fallback: 2 };
+const NO_SERVERS: VpsNamedServer[] = [];
+
+/** One VPS save at a time across every editor: each one sends a whole list, so two at once would undo each other. */
+let savingKey: string | null = null;
+const listeners = new Set<() => void>();
+const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
+const setSavingKey = (next: string | null) => { savingKey = next; for (const listener of listeners) listener(); };
+
+/** Which VPS save is under way: "" for an add, an alias for that server, null for none. */
+export function useVpsSaving(): string | null {
+ return useSyncExternalStore(subscribe, () => savingKey, () => savingKey);
+}
+
+/** Saves a VPS patch and takes the new status; resolves with the server's notice, if any. A refusal rejects with its words. */
+export function useVpsSave() {
+ const dispatch = useStoreDispatch();
+ return (body: { vps?: { sshAlias: string; memoryGb?: number; cpus?: number }; vpsServers?: VpsNamedServer[] }, key: string): Promise<string | null> => {
+ // The buttons are off while one runs; a stray second call is dropped without words.
+ if (savingKey !== null) return Promise.reject(new Error(""));
+ setSavingKey(key);
+ return api("/api/config", { method: "PUT", body: JSON.stringify(body) })
+ .then(({ notice, ...status }: ConfigStatus & { notice?: string }) => {
+ dispatch({ type: "configStatus", config: status });
+ return notice ?? null;
+ })
+ .finally(() => setSavingKey(null));
+ };
+}
+
+/** Empty is "not set"; anything else must be a whole number in range (null when it is not). */
+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;
+}
+const asText = (n: number | undefined) => (n === undefined ? "" : String(n));
+
+function LimitInput({ label, unit, value, onChange, range, placeholder, disabled, onEnter }: {
+ label: string; unit: string; value: string; onChange: (value: string) => void; range: Range; placeholder: number; disabled: boolean; onEnter: () => void;
+}) {
+ return (
+ <label className="flex shrink-0 items-center gap-1.5 text-[13px] leading-[18px] text-ink-secondary">
+ <input
+ type="number"
+ inputMode="numeric"
+ min={range.min}
+ max={range.max}
+ step={1}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && onEnter()}
+ disabled={disabled}
+ placeholder={String(placeholder)}
+ aria-label={label}
+ aria-invalid={limitValue(value, range) === null}
+ className={cn(SETTINGS_INLINE_INPUT, "w-14 placeholder:text-ink-tertiary")}
+ />
+ {unit}
+ </label>
+ );
+}
+
+/**
+ * One self-hosted server's editor: its name (the alias, for the default server), the memory and cores each bot's
+ * desktop on it may use, and Remove. It reads the server from the store by `alias` and saves on its own, so any place
+ * that shows a server can open it. Empty limits on a named server use the default server's; the default's use 4 GB
+ * and 2 cores. `onRemoved` hears the server's notice after a remove, since the editor is gone by then.
+ */
+export function VpsServerEditor({ alias, onRemoved }: { alias: string; onRemoved?: (notice: string | null) => void }) {
+ const vps = useStoreSelector((s) => s.config?.vps);
+ const named = vps?.servers ?? NO_SERVERS;
+ const isDefault = Boolean(vps?.sshAlias) && vps?.sshAlias === alias;
+ const own = isDefault ? undefined : named.find((server) => server.sshAlias === alias);
+ const saving = useVpsSaving();
+ const save = useVpsSave();
+ const savedName = isDefault ? alias : own?.name ?? "";
+ const savedMemory = isDefault ? vps?.memoryGb : own?.memoryGb;
+ const savedCpus = isDefault ? vps?.cpus : own?.cpus;
+ /** What an empty field means here. */
+ const inherited = isDefault
+ ? { memoryGb: MEMORY_GB.fallback, cpus: CPUS.fallback }
+ : { memoryGb: vps?.memoryGb ?? MEMORY_GB.fallback, cpus: vps?.cpus ?? CPUS.fallback };
+
+ const [name, setName] = useState(savedName);
+ const [memory, setMemory] = useState(asText(savedMemory));
+ const [cpus, setCpus] = useState(asText(savedCpus));
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ useEffect(() => setName(savedName), [savedName]);
+ useEffect(() => setMemory(asText(savedMemory)), [savedMemory]);
+ useEffect(() => setCpus(asText(savedCpus)), [savedCpus]);
+
+ if (!isDefault && !own) return null;
+ const memoryGb = limitValue(memory, MEMORY_GB);
+ const cpuCount = limitValue(cpus, CPUS);
+ const label = savedName || alias;
+ const valid = Boolean(name.trim()) && memoryGb !== null && cpuCount !== null;
+ const dirty = name.trim() !== savedName || memoryGb !== savedMemory || cpuCount !== savedCpus;
+ const busy = saving !== null;
+
+ const run = (body: Parameters<typeof save>[0]) => {
+ setError(null);
+ setNotice(null);
+ return save(body, alias).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);
+ throw e;
+ });
+ };
+ const submit = () => {
+ if (busy || !valid || !dirty || memoryGb === null || cpuCount === null) return;
+ const work = isDefault
+ // The default's alias is its name; an empty limit there means 4 GB and 2 cores.
+ ? run({ vps: { sshAlias: name.trim(), memoryGb: memoryGb ?? MEMORY_GB.fallback, cpus: cpuCount ?? CPUS.fallback } })
+ : run({ vpsServers: named.map((server) => (server.sshAlias === alias ? {
+ name: name.trim(), sshAlias: alias, ...(memoryGb === undefined ? {} : { memoryGb }), ...(cpuCount === undefined ? {} : { cpus: cpuCount }),
+ } : server)) });
+ work.then(setNotice, () => undefined);
+ };
+ const remove = () => {
+ if (busy) return;
+ const work = isDefault ? run({ vps: { sshAlias: "" } }) : run({ vpsServers: named.filter((server) => server.sshAlias !== alias) });
+ work.then((removedNotice) => onRemoved?.(removedNotice), () => undefined);
+ };
+
+ return (
+ <div data-vps-server={alias} className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="flex min-w-[min(100%,12rem)] flex-1 items-center gap-2">
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => { setError(null); setName(e.target.value); }}
+ onKeyDown={(e) => e.key === "Enter" && submit()}
+ disabled={busy}
+ aria-label={isDefault ? t("keys.vps.aria") : t("keys.vps.servers.nameOf", { alias })}
+ autoComplete="off"
+ spellCheck={false}
+ className={cn(KEY_FIELD, "flex-1", isDefault && "font-mono")}
+ />
+ {!isDefault && <span className="max-w-[40%] shrink-0 truncate font-mono text-[12px] leading-4 text-ink-secondary">{alias}</span>}
+ </div>
+ <LimitInput label={t("keys.vps.serverMemoryAria", { name: label })} unit={t("keys.vps.unitGb")} value={memory} onChange={setMemory} range={MEMORY_GB} placeholder={inherited.memoryGb} disabled={busy} onEnter={submit} />
+ <LimitInput label={t("keys.vps.serverCpusAria", { name: label })} unit={t("keys.vps.unitCores")} value={cpus} onChange={setCpus} range={CPUS} placeholder={inherited.cpus} disabled={busy} onEnter={submit} />
+ <button type="button" onClick={submit} disabled={busy || !valid || !dirty} className="ui-button ui-button-primary shrink-0">
+ {saving === alias && dirty ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("common.save")}
+ </button>
+ <button type="button" onClick={remove} disabled={busy} aria-label={t("keys.vps.servers.removeAria", { name: label })} className="ui-button shrink-0">
+ {saving === alias && !dirty ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.row.remove")}
+ </button>
+ </div>
+ {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/VpsServersPanel.tsx b/src/components/keys/VpsServersPanel.tsx
index 7a47d3bcff..86c52daa1f 100644
--- a/src/components/keys/VpsServersPanel.tsx
+++ b/src/components/keys/VpsServersPanel.tsx
@@ -1,394 +1,121 @@
-import { useEffect, useState } from "react";
-import { ChevronRight, Loader2, Minus, Pencil, Plus, Trash2 } from "lucide-react";
-import { api, type ConfigStatus } from "@/state/store";
-import { serverFetch } from "@/lib/relay-server";
-import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
+import { useState } from "react";
+import { Loader2 } from "lucide-react";
+import { useStoreSelector } from "@/state/store-select";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
-import { Select } from "../Select";
import { KEY_FIELD } from "./KeyRow";
+import { useVpsSave, useVpsSaving, VpsServerEditor, type VpsNamedServer } from "./VpsServerEditor";
-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}`;
+const NO_SERVERS: VpsNamedServer[] = [];
+/** Not an alias (an alias starts with a letter or digit), so it never matches a server row. */
+const ADDING_DEFAULT = "+default";
+/** Non-secret Docker-over-SSH targets: the default server, then the named ones. Keys and passwords stay with SSH. */
+export function VpsConnection() {
+ const defaultAlias = useStoreSelector((s) => s.config?.vps?.sshAlias ?? "");
+ const [notice, setNotice] = useState<string | null>(null);
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 data-vps-connection 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>
+ {defaultAlias ? <VpsServerEditor key={defaultAlias} alias={defaultAlias} onRemoved={setNotice} /> : <AddDefault onNotice={setNotice} />}
+ {notice && <div role="status" className="text-[12px] leading-4 text-ink-secondary">{notice}</div>}
+ <VpsServers />
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("keys.vps.limitsHint")}</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("");
+/** No default server yet: its SSH alias, as before limits came in. */
+function AddDefault({ onNotice }: { onNotice: (notice: string | null) => void }) {
+ const save = useVpsSave();
+ const saving = useVpsSaving();
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 [error, setError] = useState<string | null>(null);
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);
+ if (saving !== null || !alias.trim()) return;
+ setError(null);
+ save({ vps: { sshAlias: alias.trim() } }, ADDING_DEFAULT).then(onNotice, (e) => setError(e.message));
};
- 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.displayNamePlaceholder")} 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="w-full font-mono" size="sm">
- <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")}
+ <>
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ type="text"
+ data-key-input
+ value={alias}
+ onChange={(e) => { setError(null); setAlias(e.target.value); }}
+ onKeyDown={(e) => e.key === "Enter" && add()}
+ 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={add} disabled={saving !== null || !alias.trim()} className="ui-button ui-button-primary shrink-0">
+ {saving === ADDING_DEFAULT ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("common.save")}
</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>
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</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 dispatch = useStoreDispatch();
- const named = useStoreSelector((s) => s.config?.vps?.servers ?? NO_SERVERS);
- const defaultAlias = useStoreSelector((s) => s.config?.vps?.sshAlias ?? "");
- const defaultMemory = useStoreSelector((s) => s.config?.vps?.memoryGb ?? MEMORY_GB.fallback);
- const defaultCpus = useStoreSelector((s) => s.config?.vps?.cpus ?? CPUS.fallback);
- const defaultCpuset = useStoreSelector((s) => s.config?.vps?.cpuset);
- const defaults = { memoryGb: defaultMemory, cpus: defaultCpus };
- const [busy, setBusy] = useState<string | null>(null);
+/** 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 save = useVpsSave();
+ const saving = useVpsSaving();
+ const [name, setName] = useState("");
+ const [alias, setAlias] = useState("");
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);
+ const add = () => {
+ if (saving !== null || !name.trim() || !alias.trim()) return;
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), cpuset: next.cpuset ?? "" } }, "");
- return put({ vpsServers: [...named, { name: next.name, sshAlias: next.alias, ...limits(next) }] }, "");
+ save({ vpsServers: [...servers, { name: name.trim(), sshAlias: alias.trim() }] }, "")
+ .then(() => { setName(""); setAlias(""); }, (e) => setError(e.message));
};
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.listHint")}</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 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>
+ {servers.map((server) => <VpsServerEditor key={server.sshAlias} alias={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")}
+ />
+ <button type="button" onClick={add} disabled={saving !== null || !name.trim() || !alias.trim()} className="ui-button shrink-0">
+ {saving === "" ? <Loader2 size={13} className="animate-spin" aria-hidden="true" /> : t("keys.vps.servers.add")}
+ </button>
</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/state/config-status.ts b/src/state/config-status.ts
index e0da631647..997bf566ec 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; cpuset?: string }[]; memoryGb?: number; cpus?: number; cpuset?: string };
+ vps: { configured: boolean; sshAlias: string; servers?: { name: string; sshAlias: string; memoryGb?: number; cpus?: number }[]; memoryGb?: number; cpus?: number };
rooms: { turnTimeoutMinutes: number };
/** Per-call ceiling (minutes) for a bot's MCP tools. Absent from servers
* older than the setting; read it with mcpCallTimeoutMinutes(). */