Skip to content

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

Let added OpenAI-compatible servers' model IDs be changed after adding

AdityaUmalee000bf6fd99d
diff --git a/server/claude-accounts.ts b/server/claude-accounts.ts
index f07e888a2d..3a752ce768 100644
--- a/server/claude-accounts.ts
+++ b/server/claude-accounts.ts
@@ -6,6 +6,7 @@ import { join } from "node:path";
import { z } from "zod";
import { DATA_DIR, persistableInstanceConfigs, type AppConfig } from "./config.ts";
import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";
+import { addEndpointSchema } from "./openai-compat-endpoints.ts";
import { CLAUDE_ACCOUNT_ENV_KEYS, resolveClaudeConfigDir } from "./drivers/claude.ts";
import { resolveCli } from "./procs.ts";
@@ -20,6 +21,8 @@ export const instanceSettingsSchema = z.object({
hidden: z.boolean().optional(),
/** null goes back to the server's default wait. */
replyWaitMinutes: z.number().int().min(1).max(60).nullable().optional(),
+ /** An added OpenAI-compatible server's model IDs; [] goes back to its /models list. */
+ models: addEndpointSchema.shape.models,
}).strict().refine((value) => Object.keys(value).length > 0, "No settings supplied");
function rawConfig(entry: InstanceConfig): Record<string, unknown> {
diff --git a/server/openai-compat-endpoints.ts b/server/openai-compat-endpoints.ts
index f1bbfbe8cf..ba42c3a7a2 100644
--- a/server/openai-compat-endpoints.ts
+++ b/server/openai-compat-endpoints.ts
@@ -56,7 +56,9 @@ export function withEndpointUrls(described: unknown, configs: InstanceConfigMap)
if (!Array.isArray(described)) return described;
return described.map((instance: { instanceId?: string }) => {
const entry = instance.instanceId ? configs[instance.instanceId] : undefined;
- const url = entry && isAddedEndpoint(instance.instanceId!, entry) ? endpointDisplayUrl(entry.config) : undefined;
- return url ? { ...instance, url } : instance;
+ if (!entry || !isAddedEndpoint(instance.instanceId!, entry)) return instance;
+ const url = endpointDisplayUrl(entry.config);
+ const managedModels = (entry.config as { managedModels?: unknown } | undefined)?.managedModels;
+ return { ...instance, ...(url ? { url } : {}), ...(Array.isArray(managedModels) ? { managedModels } : {}) };
});
}
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index ce8707fb07..c40d5ea4d2 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -181,6 +181,50 @@ describe("installing an engine's own build from Settings", () => {
});
});
+describe("an added server's model IDs", () => {
+ it("replaces the list, goes back to detecting models with an empty list, and refuses other servers", async () => {
+ const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
+ const cfg = { instances: {
+ a: { driver: "fake" },
+ openaiCompat: { driver: "openai-compat", config: { url: "http://127.0.0.1:11434/v1" } },
+ "openai-compat-1": { driver: "openai-compat", config: { url: "https://api.example.com/v1", key: "k", managedModels: ["glm-4.6"] } },
+ } };
+ const { call, base } = await serve({
+ cfg: cfg as unknown as AppConfig,
+ persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
+ persisted.push(structuredClone(instances));
+ (cfg as { instances: unknown }).instances = instances;
+ },
+ });
+ await call("PATCH", "/api/instances/openai-compat-1", { models: ["glm-5", " qwen3 ", "glm-5"] });
+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://api.example.com/v1", key: "k", managedModels: ["glm-5", "qwen3"] });
+ await call("PATCH", "/api/instances/openai-compat-1", { models: [] });
+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://api.example.com/v1", key: "k" });
+ const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {
+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
+ })).status;
+ expect(await status("openaiCompat", { models: ["m"] })).toBe(400);
+ expect(await status("a", { models: ["m"] })).toBe(400);
+ for (const bad of [[""], ["x".repeat(201)], "glm-5", Array.from({ length: 65 }, (_, i) => `m${i}`)]) {
+ expect(await status("openai-compat-1", { models: bad })).toBe(400);
+ }
+ expect(persisted).toHaveLength(2);
+ });
+
+ it("lists the IDs entered for an added server so they can be edited", async () => {
+ const cfg = { instances: { "openai-compat-1": { driver: "openai-compat", config: { url: "https://api.example.com/v1", key: "k", managedModels: ["glm-4.6", "glm-5"] } } } };
+ const { base } = await serve({
+ cfg: cfg as unknown as AppConfig,
+ describeInstances: async () => [{ instanceId: "openai-compat-1", driverKind: "openai-compat" }, { instanceId: "a", driverKind: "fake" }],
+ });
+ const body = await (await fetch(`${base}/api/instances`)).json() as { instances: Array<Record<string, unknown>> };
+ expect(body.instances).toEqual([
+ { instanceId: "openai-compat-1", driverKind: "openai-compat", url: "https://api.example.com/v1", managedModels: ["glm-4.6", "glm-5"] },
+ { instanceId: "a", driverKind: "fake" },
+ ]);
+ });
+});
+
describe("a server's reply wait", () => {
it("saves minutes for an OpenAI-compatible server, clears them with null, and refuses other engines or bad values", async () => {
const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index 03e67b029b..a19dfd8f86 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -407,6 +407,12 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
const { replyWaitMinutes: _previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
entry.config = body.replyWaitMinutes === null ? rest : { ...rest, replyWaitMinutes: body.replyWaitMinutes };
}
+ if (body.models !== undefined) {
+ if (!isAddedEndpoint(instanceId, entry)) return json(res, 400, { ...userError("serverError.instance.modelsUnsupported") });
+ const { managedModels: _previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
+ const models = [...new Set(body.models)];
+ entry.config = models.length ? { ...rest, managedModels: models } : rest;
+ }
if (body.displayName !== undefined) entry.displayName = body.displayName;
if (body.configDir !== undefined) {
let previousDir: string | undefined;
diff --git a/server/user-errors.ts b/server/user-errors.ts
index 9512ac862c..0736b42502 100644
--- a/server/user-errors.ts
+++ b/server/user-errors.ts
@@ -173,6 +173,7 @@ export const USER_ERROR = {
"serverError.inbox.answerRequired": "This waits on your answer: answer it, or close it, where it asks.",
"serverError.instance.settingsInvalid": "Supply a valid CLI path, account name, configuration directory, boolean tools setting or a reply wait of 1 to 60 minutes.",
"serverError.instance.replyWaitUnsupported": "The reply wait is available for OpenAI-compatible servers only.",
+ "serverError.instance.modelsUnsupported": "Model IDs can be changed for added OpenAI-compatible servers only.",
"serverError.mcp.personalHeadersShared": "Personal MCP header values cannot be saved in shared configuration. Save your key in your personal connection.",
"serverError.mcp.testSignInFirst": "Sign in to the team to test your own connection.",
"serverError.postiz.adminOnly": "Only the owner or an admin can manage the Postiz connection.",
diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.ts
index 7a1ea89820..6186700621 100644
--- a/src/components/OpenAiCompatServers.test.ts
+++ b/src/components/OpenAiCompatServers.test.ts
@@ -291,3 +291,53 @@ describe("LM Studio and Bionic setup", () => {
expect(html).toContain("disabled");
});
});
+
+describe("changing an added server's model IDs", () => {
+ type Props = { children?: ReactNode; servers?: unknown; value?: unknown; onChange?: (event: { target: { value: string } }) => void; onClick?: () => void; "aria-label"?: string };
+ const nodes = (tree: ReactNode): Array<ReactElement<Props>> =>
+ Children.toArray(tree).flatMap((child) => isValidElement<Props>(child) ? [child, ...nodes(child.props.children)] : []);
+ const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };
+ function row(managedModels?: string[]) {
+ vi.stubGlobal("window", {});
+ const servers = [instance("openai-compat-1", "Zhipu", { url: "https://open.bigmodel.cn/api/paas/v4", ...(managedModels ? { managedModels } : {}) })];
+ vi.spyOn(store, "useStore").mockReturnValue({
+ state: { ...store.initialState, instances: servers }, dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),
+ });
+ const added = nodes(OtherOpenAiCompatServers()).find((node) => node.props.servers !== undefined)!;
+ fixture.counting = true;
+ fixture.index = 0;
+ try {
+ return nodes((added.type as (props: Props) => ReactNode)(added.props));
+ } finally {
+ fixture.counting = false;
+ }
+ }
+ const labelled = (tree: Array<ReactElement<Props>>, label: string) => tree.find((node) => node.props["aria-label"] === label);
+ const save = (tree: Array<ReactElement<Props>>) => tree.find((node) => node.type === "button" && JSON.stringify(node.props.children ?? "") === JSON.stringify("Save"))!;
+
+ it("opens the saved IDs for editing and saves the new list", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [] });
+ expect(labelled(row(["glm-4.6", "glm-5"]), "Model IDs for Zhipu")).toBeUndefined();
+ labelled(row(["glm-4.6", "glm-5"]), "Change model IDs for Zhipu")!.props.onClick!();
+ const field = labelled(row(["glm-4.6", "glm-5"]), "Model IDs for Zhipu")!;
+ expect(field.props.value).toBe("glm-4.6, glm-5");
+ field.props.onChange!({ target: { value: "glm-5,qwen3 glm-5" } });
+ save(row(["glm-4.6", "glm-5"])).props.onClick!();
+ await flush();
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ models: ["glm-5", "qwen3"] }) });
+ expect(labelled(row(["glm-5", "qwen3"]), "Model IDs for Zhipu")).toBeUndefined();
+ });
+
+ it("starts empty when the server's models are detected, and an empty list goes back to detecting them", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [] });
+ labelled(row(), "Change model IDs for Zhipu")!.props.onClick!();
+ expect(labelled(row(), "Model IDs for Zhipu")!.props.value).toBe("");
+ save(row()).props.onClick!();
+ await flush();
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ models: [] }) });
+ });
+});
diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsx
index 1c48225146..e865cca4b0 100644
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@ -1,5 +1,5 @@
import { useState } from "react";
-import { Loader2, Plus, RotateCw, Trash2 } from "lucide-react";
+import { Loader2, Pencil, Plus, RotateCw, Trash2 } from "lucide-react";
import { api, useStore, type InstanceInfo } from "@/state/store";
import { t } from "@/lib/i18n";
import { keySaved } from "@/lib/product-events";
@@ -19,8 +19,8 @@ const ICON_BUTTON = "ui-icon-button shrink-0 hover:text-ink";
/** Google's Gemini API speaks the OpenAI protocol here; the key comes from Google AI Studio. */
export const GEMINI_PRESET = { name: "Google Gemini", url: "https://generativelanguage.googleapis.com/v1beta/openai" } as const;
-const saveReplyWait = (instanceId: string, minutes: number | null): Promise<{ instances?: unknown }> =>
- api(`/api/instances/${encodeURIComponent(instanceId)}`, { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: minutes }) });
+const saveSettings = (instanceId: string, settings: { replyWaitMinutes?: number | null; models?: string[] }): Promise<{ instances?: unknown }> =>
+ api(`/api/instances/${encodeURIComponent(instanceId)}`, { method: "PATCH", body: JSON.stringify(settings) });
function ReplyWaitSelect({ server, disabled, onPick }: { server: InstanceInfo; disabled: boolean; onPick: (minutes: number | null) => void }) {
return (
@@ -52,7 +52,7 @@ export function BuiltInReplyWait() {
if (busy) return;
setBusy(true);
setError(null);
- void saveReplyWait(server.instanceId, minutes)
+ void saveSettings(server.instanceId, { replyWaitMinutes: minutes })
.then(async ({ instances }) => {
if (Array.isArray(instances)) dispatch({ type: "instances", instances: instances as InstanceInfo[] });
else await refreshInstances({ reportErrors: true });
@@ -74,7 +74,7 @@ export function OtherOpenAiCompatServers() {
return <AddedServers servers={addedServers(state.instances)} />;
}
-function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: string }> }) {
+function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> }) {
const { dispatch, refreshInstances } = useStore();
const [name, setName] = useState("");
const [url, setUrl] = useState("");
@@ -82,6 +82,9 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin
const [models, setModels] = useState("");
const [busy, setBusy] = useState<"add" | "other" | null>(null);
const [error, setError] = useState<string | null>(null);
+ /** The server whose model IDs are open for editing, and the text being edited. */
+ const [editing, setEditing] = useState<string | null>(null);
+ const [editText, setEditText] = useState("");
const ready = Boolean(name.trim() && url.trim() && key.trim());
const run = (kind: "add" | "other", request: () => Promise<{ instances?: unknown }>, onDone?: () => void) => {
@@ -116,36 +119,74 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin
<p className="mb-2 text-[12px] leading-4 text-ink-secondary">{t("apiInstances.subtitle")}</p>
{servers.length === 0 && <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.empty")}</p>}
{servers.map((server) => (
- <div key={server.instanceId} className="mb-1.5 flex items-center justify-between gap-2 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5">
- <div className="min-w-0 flex-1">
- <div className="truncate text-[12px] text-ink">{server.displayName}</div>
- {server.url && <div className="truncate font-mono text-[11px] text-ink-secondary">{server.url}</div>}
+ <div key={server.instanceId} className="mb-1.5 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12px] text-ink">{server.displayName}</div>
+ {server.url && <div className="truncate font-mono text-[11px] text-ink-secondary">{server.url}</div>}
+ </div>
+ <ReplyWaitSelect
+ server={server}
+ disabled={busy !== null}
+ onPick={(minutes) => run("other", () => saveSettings(server.instanceId, { replyWaitMinutes: minutes }))}
+ />
+ <button
+ type="button"
+ onClick={() => {
+ setEditText((server.managedModels ?? []).join(", "));
+ setEditing(editing === server.instanceId ? null : server.instanceId);
+ }}
+ disabled={busy !== null}
+ aria-label={t("apiInstances.editModels", { name: server.displayName })}
+ aria-expanded={editing === server.instanceId}
+ title={t("apiInstances.editModels", { name: server.displayName })}
+ className={ICON_BUTTON}
+ >
+ <Pencil size={13} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ onClick={() => run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}/refresh-models`, { method: "POST" }))}
+ disabled={busy !== null}
+ aria-label={t("apiInstances.refreshModels", { name: server.displayName })}
+ title={t("apiInstances.refreshModels", { name: server.displayName })}
+ className={ICON_BUTTON}
+ >
+ <RotateCw size={13} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ onClick={() => run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}`, { method: "DELETE" }))}
+ disabled={busy !== null}
+ aria-label={t("apiInstances.remove", { name: server.displayName })}
+ title={t("apiInstances.remove", { name: server.displayName })}
+ className={`${ICON_BUTTON} hover:bg-danger/10 hover:text-danger`}
+ >
+ <Trash2 size={13} aria-hidden="true" />
+ </button>
</div>
- <ReplyWaitSelect
- server={server}
- disabled={busy !== null}
- onPick={(minutes) => run("other", () => saveReplyWait(server.instanceId, minutes))}
- />
- <button
- type="button"
- onClick={() => run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}/refresh-models`, { method: "POST" }))}
- disabled={busy !== null}
- aria-label={t("apiInstances.refreshModels", { name: server.displayName })}
- title={t("apiInstances.refreshModels", { name: server.displayName })}
- className={ICON_BUTTON}
- >
- <RotateCw size={13} aria-hidden="true" />
- </button>
- <button
- type="button"
- onClick={() => run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}`, { method: "DELETE" }))}
- disabled={busy !== null}
- aria-label={t("apiInstances.remove", { name: server.displayName })}
- title={t("apiInstances.remove", { name: server.displayName })}
- className={`${ICON_BUTTON} hover:bg-danger/10 hover:text-danger`}
- >
- <Trash2 size={13} aria-hidden="true" />
- </button>
+ {editing === server.instanceId && (
+ <div className="mt-1.5 flex flex-col gap-1.5">
+ <input value={editText} onChange={(e) => setEditText(e.target.value)} placeholder={t("apiInstances.models")}
+ aria-label={t("apiInstances.modelsFor", { name: server.displayName })} spellCheck={false} disabled={busy !== null} className={cn(INPUT, "font-mono")} />
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.editModelsHint")}</p>
+ <div className="flex gap-1.5">
+ <button
+ type="button"
+ onClick={() => run(
+ "other",
+ () => saveSettings(server.instanceId, { models: modelIds(editText) }),
+ () => setEditing(null),
+ )}
+ disabled={busy !== null}
+ className="ui-button"
+ >
+ {t("common.save")}
+ </button>
+ <button type="button" onClick={() => setEditing(null)} disabled={busy !== null} className="ui-button">{t("common.cancel")}</button>
+ </div>
+ </div>
+ )}
</div>
))}
<div className="mt-2 flex flex-col gap-1.5">
diff --git a/src/lib/openai-compat-endpoints.ts b/src/lib/openai-compat-endpoints.ts
index a7ff21551a..de2d0935ea 100644
--- a/src/lib/openai-compat-endpoints.ts
+++ b/src/lib/openai-compat-endpoints.ts
@@ -1,6 +1,6 @@
import type { InstanceInfo } from "@/state/store";
/** Servers added from Settings → API keys → Other; matches the server's ADDED_ENDPOINT_PREFIX. */
-export function addedServers(instances: readonly InstanceInfo[]): Array<InstanceInfo & { url?: string }> {
+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-"));
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 7f7e5fd9c6..7e6343f7ce 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -6876,6 +6876,9 @@
"apiInstances.adding": "Adding…",
"apiInstances.remove": "Remove {name}",
"apiInstances.refreshModels": "Detect models for {name} again",
+ "apiInstances.editModels": "Change model IDs for {name}",
+ "apiInstances.modelsFor": "Model IDs for {name}",
+ "apiInstances.editModelsHint": "Separate model IDs with commas or spaces. Leave empty to detect them from the server again.",
"apiInstances.empty": "No other servers yet.",
"apiInstances.failed": "Couldn't save the server. Check the fields and try again.",
"apiInstances.replyWaitFor": "How long to wait for {name} to reply",
@@ -9383,6 +9386,7 @@
"serverError.inbox.answerRequired": "This waits on your answer: answer it, or close it, where it asks.",
"serverError.instance.settingsInvalid": "Supply a valid CLI path, account name, configuration directory, boolean tools setting or a reply wait of 1 to 60 minutes.",
"serverError.instance.replyWaitUnsupported": "The reply wait is available for OpenAI-compatible servers only.",
+ "serverError.instance.modelsUnsupported": "Model IDs can be changed for added OpenAI-compatible servers only.",
"serverError.postiz.adminOnly": "Only the owner or an admin can manage the Postiz connection.",
"serverError.postiz.keyAlone": "Paste the Postiz API key alone.",
"serverError.postiz.addressAsText": "Send the Postiz address as text.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index f9d5671d9b..ffecf4cc9b 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -6597,6 +6597,9 @@
"apiInstances.adding": "Adicionando…",
"apiInstances.remove": "Remover {name}",
"apiInstances.refreshModels": "Detectar modelos de {name} novamente",
+ "apiInstances.editModels": "Alterar IDs de modelo de {name}",
+ "apiInstances.modelsFor": "IDs de modelo de {name}",
+ "apiInstances.editModelsHint": "Separe os IDs de modelo com vírgulas ou espaços. Deixe vazio para detectá-los no servidor novamente.",
"apiInstances.empty": "Nenhum outro servidor ainda.",
"apiInstances.failed": "Não foi possível salvar o servidor. Verifique os campos e tente novamente.",
"apiInstances.replyWaitFor": "Quanto tempo esperar pela resposta de {name}",
@@ -9354,6 +9357,7 @@
"serverError.inbox.answerRequired": "Este pedido aguarda sua resposta. Responda ou feche o pedido onde ele aparece.",
"serverError.instance.settingsInvalid": "Informe um caminho válido para a CLI, um nome de conta, uma pasta de configuração, uma opção booleana de ferramentas ou um tempo de espera pela resposta de 1 a 60 minutos.",
"serverError.instance.replyWaitUnsupported": "O tempo de espera pela resposta só está disponível para servidores compatíveis com OpenAI.",
+ "serverError.instance.modelsUnsupported": "Os IDs de modelo só podem ser alterados em servidores compatíveis com OpenAI adicionados.",
"serverError.postiz.adminOnly": "Só o proprietário ou um administrador pode gerenciar a conexão com o Postiz.",
"serverError.postiz.keyAlone": "Cole só a chave de API do Postiz.",
"serverError.postiz.addressAsText": "Envie o endereço do Postiz como texto.",