Skip to content

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

Providers: Hide and Unhide answer at once (#6668)

laisg3306c520cbb9
diff --git a/server/engine-entry.test.ts b/server/engine-entry.test.ts
new file mode 100644
index 0000000000..7db90257d7
--- /dev/null
+++ b/server/engine-entry.test.ts
@@ -0,0 +1,35 @@
+import { expect, it } from "vitest";
+import type { InstanceConfigMap } from "./contracts.ts";
+import { keepsLoadedEngine, sameEngineEntry } from "./engine-entry.ts";
+
+const entry = (over: Partial<InstanceConfigMap[string]> = {}): InstanceConfigMap[string] =>
+ ({ driver: "claudeAgent", displayName: "Claude", enabled: true, config: { cli: "/bin/claude" }, ...over });
+
+it("treats entries that differ only in hidden as the same engine", () => {
+ expect(sameEngineEntry(entry(), entry({ hidden: true }))).toBe(true);
+ expect(sameEngineEntry(entry({ hidden: true }), entry())).toBe(true);
+});
+
+it.each([
+ ["displayName", { displayName: "Other" }],
+ ["config.cli", { config: { cli: "/bin/other" } }],
+ ["enabled", { enabled: false }],
+])("tells entries apart when %s differs", (_name, over) => {
+ expect(sameEngineEntry(entry(), entry(over))).toBe(false);
+});
+
+it("is false when either side is missing", () => {
+ expect(sameEngineEntry(undefined, entry())).toBe(false);
+ expect(sameEngineEntry(entry(), undefined)).toBe(false);
+ expect(sameEngineEntry(undefined, undefined)).toBe(false);
+});
+
+it("keeps the loaded engine only while the instance is still saved", () => {
+ const saved = { claude: entry({ hidden: true }) };
+ expect(keepsLoadedEngine("claude", saved, entry(), entry({ hidden: true }))).toBe(true);
+ expect(keepsLoadedEngine("claude", saved, entry(), entry({ displayName: "Other" }))).toBe(false);
+});
+
+it("reloads a removed instance whose built-in entry reads back unchanged", () => {
+ expect(keepsLoadedEngine("claudeApi", { claude: entry() }, entry(), entry())).toBe(false);
+});
diff --git a/server/engine-entry.ts b/server/engine-entry.ts
new file mode 100644
index 0000000000..a6a38842d0
--- /dev/null
+++ b/server/engine-entry.ts
@@ -0,0 +1,15 @@
+import { isDeepStrictEqual } from "node:util";
+
+import type { InstanceConfigMap } from "./contracts.ts";
+
+type Entry = InstanceConfigMap[string];
+
+const withoutHidden = ({ hidden: _hidden, ...rest }: Entry) => rest;
+
+export function sameEngineEntry(a: Entry | undefined, b: Entry | undefined): boolean {
+ return a !== undefined && b !== undefined && isDeepStrictEqual(withoutHidden(a), withoutHidden(b));
+}
+
+export function keepsLoadedEngine(instanceId: string, saved: InstanceConfigMap, before: Entry | undefined, after: Entry | undefined): boolean {
+ return Object.hasOwn(saved, instanceId) && sameEngineEntry(before, after);
+}
diff --git a/server/engine-status-reads.e2e.test.ts b/server/engine-status-reads.e2e.test.ts
index 8d5cec5ba5..6a526fb15a 100644
--- a/server/engine-status-reads.e2e.test.ts
+++ b/server/engine-status-reads.e2e.test.ts
@@ -20,12 +20,12 @@ afterEach(async () => {
for (const home of homes.splice(0)) await removeTempDir(home);
});
-function freshHome(): string {
+function freshHome(extra: Record<string, unknown> = {}): string {
const home = mkdtempSync(join(tmpdir(), "omb-engine-status-"));
homes.push(home);
mkdirSync(join(home, "tmp"), { recursive: true });
writeFileSync(join(home, "config.json"), JSON.stringify({
- instances: { claude: { driver: "claudeAgent", displayName: "Verification fixture", config: { cli: FAKE_CLI } } },
+ instances: { claude: { driver: "claudeAgent", displayName: "Verification fixture", config: { cli: FAKE_CLI } }, ...extra },
}));
return home;
}
@@ -155,3 +155,34 @@ it("probes again after a sign-out, a model refresh, a saved key and a Claude upd
await engines();
expect(probeCount(probes, "auth")).toBe(step.before + 1);
}, 60_000);
+
+it("hides and shows a provider without reloading its engine, and a read after a global invalidation still probes each engine once", async () => {
+ const home = freshHome({ claude2: { driver: "claudeAgent", displayName: "Second fixture", config: { cli: FAKE_CLI } } });
+ const probes = join(home, "probes.log");
+ const server = await boot(home, { FAKE_CLAUDE_PROBE_LOG: probes });
+ const ids = (body: { instances: Array<{ instanceId: string }> }) => body.instances.map((instance) => instance.instanceId);
+ const counts = () => ({ version: probeCount(probes, "version"), auth: probeCount(probes, "auth") });
+ const patch = (hidden: boolean) => server.call("PATCH", "/api/instances/claude2", { hidden });
+
+ expect(ids(await server.call("GET", "/api/instances"))).toEqual(expect.arrayContaining(["claude", "claude2"]));
+ const warm = counts();
+
+ expect(ids(await patch(true))).not.toContain("claude2");
+ expect(counts()).toEqual(warm);
+ expect(ids(await patch(false))).toContain("claude2");
+ expect(counts()).toEqual(warm);
+
+ expect(await server.call("POST", "/api/instances/claude/claude-update", {})).toMatchObject({ ok: true });
+ const invalidated = counts();
+ expect(ids(await patch(true))).not.toContain("claude2");
+ expect(counts().auth).toBe(invalidated.auth + 2);
+ await server.call("GET", "/api/instances");
+ expect(counts().auth).toBe(invalidated.auth + 2);
+}, 60_000);
+
+it("removing a built-in API-key instance disposes its engine though the saved fleet adds it back", async () => {
+ const server = await boot(freshHome());
+ const ids = (body: { instances: Array<{ instanceId: string }> }) => body.instances.map((instance) => instance.instanceId);
+ expect(ids(await server.call("GET", "/api/instances"))).toContain("claudeApi");
+ expect(ids(await server.call("DELETE", "/api/instances/claudeApi"))).not.toContain("claudeApi");
+}, 60_000);
diff --git a/server/index.ts b/server/index.ts
index b4ca8d9958..15319c1048 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -185,7 +185,7 @@ import { serveStatic } from "./static-files.ts";
import { startUpkeep } from "./host/start-upkeep.ts";
import { ComputerControl, type ControlSnapshot } from "./computer-control.ts"; import { createSharedVmControl } from "./host/shared-vm-control.ts";
import { resetPathCache } from "./env-path.ts";
-import { registerEnginesBinDir } from "./engine-install.ts"; import { engineUpdatesFor } from "./engine-updates-host.ts";
+import { registerEnginesBinDir } from "./engine-install.ts"; import { keepsLoadedEngine } from "./engine-entry.ts"; import { engineUpdatesFor } from "./engine-updates-host.ts";
import { appendUsage, flushUsageLedger, queuedTurnTrigger, usageTriggerFor, type UsageRow, type UsageTrigger } from "./usage-ledger.ts"; import { createUsageAttribution } from "./usage-attribution.ts";
import { createTraceRecorder } from "./usage-trace/recorder.ts";
import { GroupUsageReader } from "./group-thread-usage.ts";
@@ -11875,17 +11875,17 @@ async function stopCompanyInstances(ids: string[]) {
}
async function persistProviderInstance(instanceId: string, instances: NonNullable<AppConfig["instances"]>) {
+ const before = instanceConfigs(cfg)[instanceId];
saveConfig({ instances }, { replaceInstances: true });
cfg.instances = instances;
+ if (registry.get(instanceId) && keepsLoadedEngine(instanceId, instances, before, instanceConfigs(cfg)[instanceId])) return;
providerAuthSessions.clearInstance(instanceId);
bus.detach(instanceId);
if (Object.hasOwn(instances, instanceId)) {
await registry.load({ [instanceId]: instanceConfigs(cfg)[instanceId] });
const live = registry.get(instanceId);
if (live) bus.attach([live]);
- } else {
- await registry.dispose(instanceId);
- }
+ } else await registry.dispose(instanceId);
resetPathCache();
}
diff --git a/src/components/EngineAccounts.tsx b/src/components/EngineAccounts.tsx
index e28b14d354..aa438dedc8 100644
--- a/src/components/EngineAccounts.tsx
+++ b/src/components/EngineAccounts.tsx
@@ -1,6 +1,7 @@
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { Check, Loader2, MoreHorizontal, Plus } from "lucide-react";
import { api, useStore, type InstanceInfo } from "@/state/store";
+import { useShowInstances } from "@/state/use-show-instances";
import { t } from "@/lib/i18n";
import { engineDisplayName } from "@/lib/engine-name";
import { cn } from "@/lib/cn";
@@ -69,7 +70,8 @@ function summaryFor(group: AccountGroup, accounts: InstanceInfo[]): EngineCardSu
}
function AccountMenu({ group, instance, onRename }: { group: AccountGroup; instance: InstanceInfo; onRename: () => void }) {
- const { state, dispatch, refreshInstances } = useStore();
+ const { state } = useStore();
+ const showInstances = useShowInstances();
const [open, setOpen] = useState(false);
const [confirm, setConfirm] = useState<"signOut" | "remove" | null>(null);
const [busy, setBusy] = useState(false);
@@ -100,10 +102,7 @@ function AccountMenu({ group, instance, onRename }: { group: AccountGroup; insta
const path = `/api/instances/${encodeURIComponent(instance.instanceId)}${action === "signOut" ? "/auth/sign-out" : ""}`;
// Hide leaves the account out of every model list until Unhide (Settings → AI → More providers).
const init = action === "signOut" ? { method: "POST" } : action === "remove" ? { method: "DELETE" } : { method: "PATCH", body: JSON.stringify({ hidden: true }) };
- const { instances } = await api(path, init);
- // The response is the confirmed state: a second request could fail and leave a stale row.
- if (Array.isArray(instances)) dispatch({ type: "instances", instances });
- else await refreshInstances().catch(() => {});
+ await showInstances(await api(path, init)).catch(() => {});
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
} finally {
diff --git a/src/components/EnginesSettings.hidden-providers.dom.test.ts b/src/components/EnginesSettings.hidden-providers.dom.test.ts
index cbd28a6d5b..f90abb026f 100644
--- a/src/components/EnginesSettings.hidden-providers.dom.test.ts
+++ b/src/components/EnginesSettings.hidden-providers.dom.test.ts
@@ -9,12 +9,13 @@ import { setLocale, t } from "@/lib/i18n";
import { BUILT_IN_INSTANCE_DRIVERS } from "@/lib/built-in-instances";
const server = vi.hoisted(() => ({
- all: [] as InstanceInfo[], hidden: new Set<string>(), calls: [] as Array<{ method: string; path: string; body?: unknown }>, refuseUnhide: false,
+ all: [] as InstanceInfo[], hidden: new Set<string>(), calls: [] as Array<{ method: string; path: string; body?: unknown }>, refuseUnhide: false, refreshes: 0,
+ holdHidden: null as Promise<void> | null,
}));
const fixture = vi.hoisted(() => ({ state: { instances: [] as InstanceInfo[], bots: [] as Bot[], config: {} as Record<string, unknown> } }));
vi.mock("@/state/store", async (original) => {
const visible = () => server.all.filter((instance) => !server.hidden.has(instance.instanceId));
- const refresh = async () => { fixture.state = { ...fixture.state, instances: visible() }; };
+ const refresh = async () => { server.refreshes++; fixture.state = { ...fixture.state, instances: visible() }; };
return {
...await original<typeof import("@/state/store")>(),
useStore: () => ({
@@ -26,6 +27,7 @@ vi.mock("@/state/store", async (original) => {
const method = init?.method ?? "GET";
server.calls.push({ method, path, ...(init?.body ? { body: JSON.parse(init.body) } : {}) });
if (path === "/api/instances/hidden") {
+ await server.holdHidden;
return { instances: server.all.filter((instance) => server.hidden.has(instance.instanceId)).map(({ instanceId, driverKind, displayName }) => ({ instanceId, driverKind, displayName })) };
}
const signOut = /^\/api\/instances\/([\w.-]+)\/auth\/sign-out$/.exec(path);
@@ -66,6 +68,8 @@ beforeEach(() => {
server.hidden = new Set();
server.calls = [];
server.refuseUnhide = false;
+ server.refreshes = 0;
+ server.holdHidden = null;
fixture.state = { instances: [...server.all], bots: [], config: {} };
container = document.createElement("div"); document.body.append(container); root = createRoot(container);
});
@@ -97,6 +101,7 @@ describe("Settings → AI: a provider hidden from its own card", () => {
expect(rows()).not.toContain("kimi");
expect(hiddenRows()).toEqual(["kimi"]);
+ expect(server.refreshes).toBe(0);
expect(moreCount()).toContain("More providers");
// Hidden Kimi and the Google AI Studio row.
expect(moreCount()).toContain("2");
@@ -110,6 +115,7 @@ describe("Settings → AI: a provider hidden from its own card", () => {
expect(server.calls).toContainEqual({ method: "PATCH", path: "/api/instances/kimi", body: { hidden: false } });
expect(rows()).toContain("kimi");
expect(hiddenRows()).toEqual([]);
+ expect(server.refreshes).toBe(0);
});
it("keeps the More providers row while every provider left in it is hidden", async () => {
@@ -133,6 +139,25 @@ describe("Settings → AI: a provider hidden from its own card", () => {
expect(rows()).not.toContain("kimi");
});
+ it.each([
+ ["is still pending", (release: { done: () => void; fail: () => void }) => release.done()],
+ ["fails", (release: { done: () => void; fail: () => void }) => release.fail()],
+ ])("drops an unhidden provider from the hidden rows before the hidden list is read again, and when that read %s", async (_name, settle) => {
+ server.hidden.add("kimi");
+ fixture.state = { ...fixture.state, instances: [codex] };
+ await render();
+ expect(hiddenRows()).toEqual(["kimi"]);
+ const release = { done: () => {}, fail: () => {} };
+ server.holdHidden = new Promise<void>((resolve, reject) => { release.done = resolve; release.fail = () => reject(new Error("offline")); });
+ server.holdHidden.catch(() => {});
+ await click(container.querySelector('[data-unhide-engine="kimi"]'));
+ expect(rows().filter((id) => id === "kimi")).toEqual(["kimi"]);
+ expect(hiddenRows()).toEqual([]);
+ await act(async () => { settle(release); await server.holdHidden!.catch(() => {}); });
+ expect(rows().filter((id) => id === "kimi")).toEqual(["kimi"]);
+ expect(hiddenRows()).toEqual([]);
+ });
+
it("signs a connected CLI out from its card without hiding it", async () => {
await render();
await click(rowButton("kimi"));
@@ -261,6 +286,7 @@ describe("Settings → AI → ChatGPT: the built-in account rows can be hidden",
expect(server.calls).toContainEqual({ method: "PATCH", path: "/api/instances/chatgpt", body: { hidden: false } });
expect(accounts()).toEqual(["codex", "chatgpt", "chatgpt-work"]);
expect(hiddenRows()).toEqual([]);
+ expect(server.refreshes).toBe(0);
});
it("offers Hide on the Codex row too", async () => {
diff --git a/src/components/EnginesSettings.hidden.test.ts b/src/components/EnginesSettings.hidden.test.ts
index 7776d9f32b..97fbdb4851 100644
--- a/src/components/EnginesSettings.hidden.test.ts
+++ b/src/components/EnginesSettings.hidden.test.ts
@@ -4,15 +4,15 @@ import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const fixture = vi.hoisted(() => ({ hidden: [] as Array<{ instanceId: string; displayName: string }>, calls: [] as Array<{ path: string; body?: unknown }>, refresh: vi.fn() }));
+const fixture = vi.hoisted(() => ({ hidden: [] as Array<{ instanceId: string; displayName: string }>, calls: [] as Array<{ path: string; body?: unknown }>, refresh: vi.fn(), dispatch: vi.fn(), answer: [{ instanceId: "codex" }] as unknown[] }));
vi.mock("@/state/store", async (original) => ({
...await original<typeof import("@/state/store")>(),
- useStore: () => ({ state: { instances: [] }, refreshInstances: fixture.refresh }),
+ useStore: () => ({ state: { instances: [] }, dispatch: fixture.dispatch, refreshInstances: fixture.refresh }),
api: async (path: string, init?: RequestInit) => {
fixture.calls.push({ path, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
if (path === "/api/instances/hidden") return { instances: fixture.hidden };
fixture.hidden = [];
- return { instances: [] };
+ return { instances: fixture.answer };
},
}));
@@ -24,6 +24,7 @@ const settle = () => new Promise((done) => setTimeout(done, 0));
beforeEach(() => {
fixture.calls = [];
fixture.refresh.mockReset();
+ fixture.dispatch.mockReset();
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -48,6 +49,7 @@ describe("hidden providers in Settings", () => {
flushSync(() => host.querySelector<HTMLButtonElement>('[data-unhide-engine="hermes"]')!.click());
await settle();
expect(fixture.calls).toContainEqual({ path: "/api/instances/hermes", body: { hidden: false } });
- expect(fixture.refresh).toHaveBeenCalled();
+ expect(fixture.refresh).not.toHaveBeenCalled();
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "instances", instances: fixture.answer });
});
});
diff --git a/src/components/EnginesSettings.tsx b/src/components/EnginesSettings.tsx
index 736a5cc827..d9e02162ce 100644
--- a/src/components/EnginesSettings.tsx
+++ b/src/components/EnginesSettings.tsx
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState, type ReactNode } from "react";
import { Check, Loader2, RefreshCw, TriangleAlert } from "lucide-react";
import { api, useStore, type InstanceInfo } from "@/state/store";
+import { useShowInstances } from "@/state/use-show-instances";
import { EngineCard, EngineSections, RefreshEngines, engineReady } from "./EngineLibrary";
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
@@ -195,6 +196,7 @@ function CustomPicker({ instance, cliDefault, onClose, onSaved }: {
/** The executable behind an engine: its path, Claude's self-update, and a reset to the default. */
function EngineAdvanced({ instance }: { instance: InstanceInfo }) {
const { refreshInstances } = useStore();
+ const showInstances = useShowInstances();
const [open, setOpen] = useState(false);
const cliMotion = useMenuMotion(open);
const [switching, setSwitching] = useState(false);
@@ -229,7 +231,7 @@ function EngineAdvanced({ instance }: { instance: InstanceInfo }) {
setSwitching(true);
setError(null);
api(`/api/instances/${encodeURIComponent(instance.instanceId)}`, { method: "PATCH", body: JSON.stringify({ hidden: true }) })
- .then(() => Promise.resolve(refreshInstances()).catch(() => {}))
+ .then((answer) => showInstances(answer).catch(() => {}))
.catch((e) => setError(e.message))
.finally(() => setSwitching(false));
};
@@ -334,7 +336,8 @@ function EngineAdvanced({ instance }: { instance: InstanceInfo }) {
/** Remove drops an added Antigravity account or an added server; Sign out forgets a signed-in account's sign-in (Antigravity's
* Google one, or a CLI's own login such as Kimi's) and never hides the provider, which stays listed with Set up. */
function EngineAccountAction({ instance, action, cli = false, removeBody = "accounts.removeBodyAntigravity" }: { instance: InstanceInfo; action: "remove" | "signOut"; cli?: boolean; removeBody?: LocaleKey }) {
- const { state, dispatch, refreshInstances } = useStore();
+ const { state } = useStore();
+ const showInstances = useShowInstances();
const [confirming, setConfirming] = useState(false);
const [running, setRunning] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -347,9 +350,7 @@ function EngineAccountAction({ instance, action, cli = false, removeBody = "acco
setError(null);
try {
const path = `/api/instances/${encodeURIComponent(instance.instanceId)}${remove ? "" : "/auth/sign-out"}`;
- const { instances } = await api(path, { method: remove ? "DELETE" : "POST" });
- if (Array.isArray(instances)) dispatch({ type: "instances", instances });
- else await refreshInstances();
+ await showInstances(await api(path, { method: remove ? "DELETE" : "POST" }));
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
} finally {
diff --git a/src/components/HiddenProviders.tsx b/src/components/HiddenProviders.tsx
index 87bbbfaac1..5d5d14fad1 100644
--- a/src/components/HiddenProviders.tsx
+++ b/src/components/HiddenProviders.tsx
@@ -1,6 +1,7 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { api, useStore } from "@/state/store";
+import { useShowInstances } from "@/state/use-show-instances";
import { t } from "@/lib/i18n";
import { InstanceProviderMark } from "./ProviderIcons";
import { SettingsMark } from "./SettingsPrimitives";
@@ -21,18 +22,18 @@ export function useHiddenProviders(): HiddenProvider[] {
.catch(() => {});
return () => { alive = false; };
}, [state.instances]);
- return hidden;
+ return useMemo(() => hidden.filter((entry) => !state.instances.some((instance) => instance.instanceId === entry.instanceId)), [hidden, state.instances]);
}
function useUnhide() {
- const { refreshInstances } = useStore();
+ const showInstances = useShowInstances();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const unhide = (instanceId: string) => {
setBusy(instanceId);
setError(null);
api(`/api/instances/${encodeURIComponent(instanceId)}`, { method: "PATCH", body: JSON.stringify({ hidden: false }) })
- .then(() => Promise.resolve(refreshInstances()).catch(() => {}))
+ .then((answer) => showInstances(answer).catch(() => {}))
.catch((e) => setError(e instanceof Error ? e.message : String(e)))
.finally(() => setBusy(null));
};
diff --git a/src/state/use-show-instances.ts b/src/state/use-show-instances.ts
new file mode 100644
index 0000000000..650e2f63f0
--- /dev/null
+++ b/src/state/use-show-instances.ts
@@ -0,0 +1,12 @@
+import { useCallback } from "react";
+
+import { useStore, type InstanceInfo } from "./store";
+
+export function useShowInstances() {
+ const { dispatch, refreshInstances } = useStore();
+ return useCallback(async (answer: unknown) => {
+ const instances = (answer as { instances?: unknown } | undefined)?.instances;
+ if (Array.isArray(instances)) dispatch({ type: "instances", instances: instances as InstanceInfo[] });
+ else await refreshInstances();
+ }, [dispatch, refreshInstances]);
+}