Skip to content

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

fix(engines): let Settings remove an added local server, and stop adding the same one twice

AdityaUmale8e66180682c4
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.ts
index 442ecd1d8e..2ad7f3aab1 100644
--- a/server/app-settings/host.test.ts
+++ b/server/app-settings/host.test.ts
@@ -255,6 +255,18 @@ describe("AI engines", () => {
expect(fx.engines.map((engine) => engine.instanceId)).toEqual(["claude", "openai-compat-gw"]);
});
+ it("refuses a local server already added at the same address, so Settings never lists it twice", async () => {
+ const fx = fixture();
+ await fx.set("engines", JSON.stringify({ kind: "lmstudio", url: "http://127.0.0.1:1234/v1" }));
+ const again = await fx.set("engines", JSON.stringify({ kind: "lmstudio", url: "http://127.0.0.1:1234/v1/" }));
+ expect(again).toMatchObject({ status: 409, body: { error: "\"LM Studio\" at http://127.0.0.1:1234/v1 is already an engine (openai-compat-2). Use that one; do not add it again." } });
+ expect(fx.engineCalls).toHaveLength(1);
+ expect(fx.cards()).toHaveLength(1);
+ // Another address is another server.
+ await fx.set("engines", JSON.stringify({ kind: "lmstudio", url: "http://127.0.0.1:1235/v1" }));
+ expect(fx.engineCalls).toHaveLength(2);
+ });
+
it("an engine that needs a key takes only a saved key's id, which the server reads as it adds it; the key is shown nowhere", async () => {
const fx = fixture();
const missing = await fx.set("engines", JSON.stringify({ kind: "openai-compat", name: "Proxy", url: "https://proxy.example/v1", keyFrom: "mistralApiKey" }));
diff --git a/server/app-settings/registry.ts b/server/app-settings/registry.ts
index 510e9bf04a..0c1bd2584d 100644
--- a/server/app-settings/registry.ts
+++ b/server/app-settings/registry.ts
@@ -10,7 +10,7 @@ import { MAX_MCP_CALL_TIMEOUT_MINUTES, MAX_ROOM_TURN_TIMEOUT_MINUTES, mcpCallTim
import type { InstanceConfig } from "../contracts.ts";
import { BUILT_IN_DRIVERS } from "../drivers/builtIn.ts";
import type { ProviderRegistry } from "../harness/registry.ts";
-import { endpointDisplayUrl, isAddedEndpoint } from "../openai-compat-endpoints.ts";
+import { endpointBaseUrl, endpointDisplayUrl, isAddedEndpoint } from "../openai-compat-endpoints.ts";
import type { RequestAuth } from "../request-auth.ts";
import { callRoute, type RouteReply } from "../routes/call-route.ts";
import type { RouteHandler } from "../routes/table.ts";
@@ -278,6 +278,12 @@ export function createSettingsRegistry(deps: RegistryDeps): SettingEntry[] {
current: (): EngineKeep => ({ kind: "keep", instanceIds: deps.engines().map((engine) => engine.instanceId) }), read: listEngines,
describe: (change: EngineChange) => {
if (change.kind === "remove") return { refusal: personOnly("Removing an AI engine", "Settings → AI") };
+ if (change.kind === "ollama" || change.kind === "lmstudio") {
+ // Settings adds a local server once per address; a second one only shows the same engine twice.
+ const url = endpointBaseUrl(change.url);
+ const existing = url ? Object.entries(instances()).find(([instanceId, entry]) => isAddedEndpoint(instanceId, entry) && endpointDisplayUrl(entry.config) === url) : undefined;
+ if (existing) return { refusal: `"${existing[1].displayName ?? existing[0]}" at ${url} is already an engine (${existing[0]}). Use that one; do not add it again.` };
+ }
if (change.kind === "openai-compat") {
if (!savedKey(change.keyFrom)) return { refusal: keyMissing(change.keyFrom) };
return { change: `Add the engine "${change.name}" (OpenAI-compatible) at ${change.url}, sending it your saved ${CREDENTIAL_TARGETS[change.keyFrom].label}` };
diff --git a/src/components/EnginesSettings.added-server.dom.test.ts b/src/components/EnginesSettings.added-server.dom.test.ts
new file mode 100644
index 0000000000..fb5046c4b6
--- /dev/null
+++ b/src/components/EnginesSettings.added-server.dom.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Bot, InstanceInfo } from "@/state/store";
+import { setLocale } from "@/lib/i18n";
+
+const fixture = vi.hoisted(() => ({ state: { instances: [] as InstanceInfo[], bots: [] as Bot[], config: {} as Record<string, unknown> }, calls: [] as Array<{ path: string; method?: string }> }));
+vi.mock("@/state/store", async (original) => ({
+ ...await original<typeof import("@/state/store")>(),
+ useStore: () => ({
+ state: fixture.state,
+ dispatch: (action: { type: string; instances?: InstanceInfo[] }) => { if (action.type === "instances" && action.instances) fixture.state = { ...fixture.state, instances: action.instances }; },
+ refreshInstances: async () => {}, refreshModels: async () => {},
+ }),
+ api: async (path: string, init?: { method?: string }) => {
+ fixture.calls.push({ path, method: init?.method });
+ if (init?.method !== "DELETE") return {};
+ const instanceId = decodeURIComponent(path.split("/").pop()!);
+ return { instances: fixture.state.instances.filter((instance) => instance.instanceId !== instanceId) };
+ },
+}));
+import { EnginesSettings } from "./EnginesSettings";
+
+function lmStudio(instanceId: string): InstanceInfo {
+ return {
+ instanceId, driverKind: "openai-compat", displayName: "LM Studio", access: "api", url: "http://127.0.0.1:1234/v1",
+ snapshot: { state: "available", authenticated: true }, models: { default: "gemma", options: [] },
+ } as unknown as InstanceInfo;
+}
+
+let container: HTMLDivElement, root: Root;
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ setLocale("en");
+ fixture.state = { instances: [lmStudio("openai-compat-a"), lmStudio("openai-compat-b")], bots: [], config: {} };
+ fixture.calls = [];
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });
+
+const render = async () => {
+ await act(async () => { root.render(createElement(EnginesSettings, { simple: true, more: { id: "more", open: true, onToggle: () => {} } })); });
+};
+const buttons = (within: ParentNode, label: string) => [...within.querySelectorAll("button")].filter((item) => item.textContent === label);
+const click = async (target: Element | undefined) => { expect(target).toBeTruthy(); await act(async () => { (target as HTMLElement).click(); }); };
+const row = (instanceId: string) => container.querySelector(`[data-simple-engine="${instanceId}"]`)!;
+const fold = (instanceId: string) => container.querySelector(`[data-provider-fold="${instanceId}"]`)!;
+
+describe("Settings → AI → an added server's Manage", () => {
+ it("removes a duplicate LM Studio after asking, and keeps the other one", async () => {
+ await render();
+ await click(row("openai-compat-b").querySelector("button")!);
+ await click(buttons(fold("openai-compat-b"), "Remove")[0]);
+ expect(fixture.calls.filter((call) => call.method === "DELETE")).toEqual([]);
+ const dialog = document.querySelector("[role=alertdialog]")!;
+ expect(dialog.textContent).toContain("Remove LM Studio?");
+ await click(buttons(dialog, "Remove")[0]);
+ expect(fixture.calls.filter((call) => call.method === "DELETE")).toEqual([{ path: "/api/instances/openai-compat-b", method: "DELETE" }]);
+ expect(fixture.state.instances.map((instance) => instance.instanceId)).toEqual(["openai-compat-a"]);
+ });
+
+ it("waits until no bot uses the server", async () => {
+ fixture.state = { ...fixture.state, bots: [{ id: "kiwi", modelSelection: { instanceId: "openai-compat-b", model: "gemma" } } as unknown as Bot] };
+ await render();
+ await click(row("openai-compat-b").querySelector("button")!);
+ expect(buttons(fold("openai-compat-b"), "Remove")[0]!.disabled).toBe(true);
+ expect(fold("openai-compat-b").textContent).toContain("1 bot(s) use this account");
+ });
+});
diff --git a/src/components/EnginesSettings.tsx b/src/components/EnginesSettings.tsx
index 06e4b1a18d..37f5a00498 100644
--- a/src/components/EnginesSettings.tsx
+++ b/src/components/EnginesSettings.tsx
@@ -6,6 +6,7 @@ import { EngineCard, EngineSections, RefreshEngines, engineReady } from "./Engin
import { cn } from "@/lib/cn";
import { useMenuMotion } from "./MenuMotion";
import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
import { ApiKeyEngineManage, EngineSetup, EngineUpdateNotice, EngineWarningNotice, isApiKeyEngine } from "./EngineSetup";
import { AppCopyNotice } from "./EngineAppCopy";
import { forgetAppCopySwitches } from "@/state/engine-install";
@@ -19,6 +20,7 @@ import { ConfirmDialog } from "./ConfirmDialog";
import { Select } from "./Select";
import { SettingsFoldRow, SettingsGroup, SettingsMark, SettingsRows, StatusDot } from "./SettingsPrimitives";
import { OllamaModels, ollamaShortStatus } from "./OllamaStatusLine";
+import { isAddedServer } from "@/lib/openai-compat-endpoints";
import { InstanceProviderMark } from "./ProviderIcons";
interface ProbeResult {
@@ -324,8 +326,8 @@ function EngineAdvanced({ instance }: { instance: InstanceInfo }) {
);
}
-/** Remove drops an added account; Sign out forgets a signed-in account's Google sign-in, the first one too. */
-function AntigravityAccountAction({ instance, action }: { instance: InstanceInfo; action: "remove" | "signOut" }) {
+/** Remove drops an added account or server; Sign out forgets a signed-in account's Google sign-in, the first one too. */
+function EngineRemoveAction({ instance, action, removeBody = "accounts.removeBodyAntigravity" }: { instance: InstanceInfo; action: "remove" | "signOut"; removeBody?: LocaleKey }) {
const { state, dispatch, refreshInstances } = useStore();
const [confirming, setConfirming] = useState(false);
const [running, setRunning] = useState(false);
@@ -357,7 +359,7 @@ function AntigravityAccountAction({ instance, action }: { instance: InstanceInfo
</div>
{error && <p role="alert" className="text-[12px] text-danger">{error}</p>}
<ConfirmDialog open={confirming} title={t(remove ? "accounts.removeTitle" : "accounts.signOutTitle", { name: instance.displayName })}
- body={t(remove ? "accounts.removeBodyAntigravity" : "accounts.signOutBody")}
+ body={t(remove ? removeBody : "accounts.signOutBody")}
confirmLabel={label} tone="neutral" pending={running} onCancel={() => { if (!running) setConfirming(false); }} onConfirm={() => void run()} />
</>;
}
@@ -392,6 +394,8 @@ function EngineRow({ instance, bare = false }: { instance: InstanceInfo; bare?:
{!engineReady(instance) && <EngineSetup instance={instance} intent={instance.access === "custom" ? "inject" : "cloud"} description={instance.codexEndpoint ? t("agentEndpoints.codexHint") : undefined} unframed />}
{engineReady(instance) && <ApiKeyEngineManage instance={instance} className="mt-3" />}
{engineReady(instance) && instance.serverKind === "ollama" && <OllamaModels instance={instance} className="mt-3" />}
+ {/* A server added by address (LM Studio, Ollama, a gateway) is removed here too, not only from API keys. */}
+ {isAddedServer(instance) && <div className="mt-3"><EngineRemoveAction instance={instance} action="remove" removeBody="claudeEndpoints.removeBody" /></div>}
{/* The setup panel that first said so is gone once the engine is Ready. */}
{engineReady(instance) && <AppCopyNotice instance={instance} className="mt-3" />}
{instance.snapshot.update && <EngineUpdateNotice update={instance.snapshot.update} instance={instance} className="mt-3" quiet />}
@@ -408,8 +412,8 @@ function EngineRow({ instance, bare = false }: { instance: InstanceInfo; bare?:
<div className="mt-3 space-y-3">
{instance.snapshot.authenticated && <p className="break-words text-[12px] text-ink-secondary">{instance.snapshot.account?.email ?? t("engineSetup.antigravity.emailUnavailable")}</p>}
<AntigravityAddAccount source={instance} />
- {instance.snapshot.authenticated === true && instance.authentication?.signOut === true && <AntigravityAccountAction instance={instance} action="signOut" />}
- {instance.instanceId.startsWith("antigravity-") && <AntigravityAccountAction instance={instance} action="remove" />}
+ {instance.snapshot.authenticated === true && instance.authentication?.signOut === true && <EngineRemoveAction instance={instance} action="signOut" />}
+ {instance.instanceId.startsWith("antigravity-") && <EngineRemoveAction instance={instance} action="remove" />}
</div>
)}
<EngineAdvanced instance={instance} />
diff --git a/src/lib/openai-compat-endpoints.ts b/src/lib/openai-compat-endpoints.ts
index de2d0935ea..20c6cd3499 100644
--- a/src/lib/openai-compat-endpoints.ts
+++ b/src/lib/openai-compat-endpoints.ts
@@ -1,6 +1,10 @@
import type { InstanceInfo } from "@/state/store";
-/** Servers added from Settings → API keys → Other; matches the server's ADDED_ENDPOINT_PREFIX. */
+/** A server added from Settings → API keys → Other; matches the server's ADDED_ENDPOINT_PREFIX. */
+export function isAddedServer(instance: InstanceInfo): boolean {
+ return instance.driverKind === "openai-compat" && instance.instanceId.startsWith("openai-compat-");
+}
+
export function addedServers(instances: readonly InstanceInfo[]): Array<InstanceInfo & { url?: string; managedModels?: string[] }> {
- return instances.filter((instance) => instance.driverKind === "openai-compat" && instance.instanceId.startsWith("openai-compat-"));
+ return instances.filter(isAddedServer);
}