Skip to content

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

Keep the default model and show model-ID limits when editing a server's list

AdityaUmaleca765049eaf6
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index c40d5ea4d2..1b97ce1a5b 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -211,6 +211,28 @@ describe("an added server's model IDs", () => {
expect(persisted).toHaveLength(2);
});
+ it("refuses to drop the default model from the list, and allows going back to detecting models", async () => {
+ const persisted: unknown[] = [];
+ const cfg = {
+ defaultModelSelection: { instanceId: "openai-compat-1", model: "glm-4.6" },
+ instances: { "openai-compat-1": { driver: "openai-compat", config: { url: "https://api.example.com/v1", key: "k", managedModels: ["glm-4.6"] } } },
+ };
+ const { base } = await serve({
+ cfg: cfg as unknown as AppConfig,
+ persistProviderInstance: async (_id: string, instances: unknown) => { persisted.push(structuredClone(instances)); },
+ });
+ const patch = (models: string[]) => fetch(`${base}/api/instances/openai-compat-1`, {
+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ models }),
+ });
+ const refused = await patch(["glm-5"]);
+ expect(refused.status).toBe(409);
+ expect(await refused.json()).toMatchObject({ errorKey: "serverError.instance.defaultModelRemoved", errorParams: { model: "glm-4.6" } });
+ expect(persisted).toHaveLength(0);
+ expect((await patch(["glm-5", "glm-4.6"])).status).toBe(200);
+ expect((await patch([])).status).toBe(200);
+ 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({
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index a19dfd8f86..5783520289 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -411,6 +411,10 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
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)];
+ const defaultModel = cfg.defaultModelSelection?.instanceId === instanceId ? cfg.defaultModelSelection.model : undefined;
+ if (models.length && defaultModel && !models.includes(defaultModel)) {
+ return json(res, 409, { ...userError("serverError.instance.defaultModelRemoved", { model: defaultModel }) });
+ }
entry.config = models.length ? { ...rest, managedModels: models } : rest;
}
if (body.displayName !== undefined) entry.displayName = body.displayName;
diff --git a/server/user-errors.ts b/server/user-errors.ts
index 0736b42502..b059fc6b88 100644
--- a/server/user-errors.ts
+++ b/server/user-errors.ts
@@ -174,6 +174,7 @@ export const USER_ERROR = {
"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.instance.defaultModelRemoved": "{model} is the default model. Choose another default model before removing it from this server.",
"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 6186700621..eedab9fefc 100644
--- a/src/components/OpenAiCompatServers.test.ts
+++ b/src/components/OpenAiCompatServers.test.ts
@@ -297,11 +297,11 @@ describe("changing an added server's model IDs", () => {
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[]) {
+ function row(managedModels?: string[], dispatch = vi.fn()) {
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(),
+ state: { ...store.initialState, instances: servers }, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),
});
const added = nodes(OtherOpenAiCompatServers()).find((node) => node.props.servers !== undefined)!;
fixture.counting = true;
@@ -318,15 +318,18 @@ describe("changing an added server's model IDs", () => {
it("opens the saved IDs for editing and saves the new list", async () => {
fixture.values = [];
fixture.api.mockReset();
- fixture.api.mockResolvedValue({ instances: [] });
+ const dispatch = vi.fn();
+ const updated = [instance("openai-compat-1", "Zhipu", { managedModels: ["glm-5", "qwen3"] })];
+ fixture.api.mockResolvedValue({ instances: updated });
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!();
+ save(row(["glm-4.6", "glm-5"], dispatch)).props.onClick!();
await flush();
expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ models: ["glm-5", "qwen3"] }) });
+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({ type: "instances", instances: updated });
expect(labelled(row(["glm-5", "qwen3"]), "Model IDs for Zhipu")).toBeUndefined();
});
@@ -340,4 +343,16 @@ describe("changing an added server's model IDs", () => {
await flush();
expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ models: [] }) });
});
+
+ it("shows the model-ID limits next to the editor instead of sending a list the server refuses", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ labelled(row(["glm-4.6"]), "Change model IDs for Zhipu")!.props.onClick!();
+ labelled(row(["glm-4.6"]), "Model IDs for Zhipu")!.props.onChange!({ target: { value: Array.from({ length: 65 }, (_, i) => `m${i}`).join(" ") } });
+ save(row(["glm-4.6"])).props.onClick!();
+ await flush();
+ expect(fixture.api).not.toHaveBeenCalled();
+ const alert = row(["glm-4.6"]).find((node) => (node.props as { role?: string }).role === "alert");
+ expect(alert?.props.children).toBe("Use at most 64 model IDs, each up to 200 characters.");
+ });
});
diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsx
index e865cca4b0..d7f9f6b3fc 100644
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@ -19,6 +19,10 @@ 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;
+/** The server accepts at most this many model IDs per server, each up to this many characters. */
+const MODEL_ID_LIMITS = { count: 64, length: 200 } as const;
+const withinModelIdLimits = (ids: string[]) => ids.length <= MODEL_ID_LIMITS.count && ids.every((id) => id.length <= MODEL_ID_LIMITS.length);
+
const saveSettings = (instanceId: string, settings: { replyWaitMinutes?: number | null; models?: string[] }): Promise<{ instances?: unknown }> =>
api(`/api/instances/${encodeURIComponent(instanceId)}`, { method: "PATCH", body: JSON.stringify(settings) });
@@ -81,13 +85,14 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
const [key, setKey] = useState("");
const [models, setModels] = useState("");
const [busy, setBusy] = useState<"add" | "other" | null>(null);
- const [error, setError] = useState<string | null>(null);
+ /** The last failure, and the server whose model-ID editor it belongs to (shown there instead of below the add form). */
+ const [error, setError] = useState<{ text: string; at?: 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) => {
+ const run = (kind: "add" | "other", request: () => Promise<{ instances?: unknown }>, onDone?: () => void, at?: string) => {
if (busy) return;
setBusy(kind);
setError(null);
@@ -97,7 +102,7 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
else await refreshInstances({ reportErrors: true });
onDone?.();
})
- .catch((e: Error) => setError(e.message || t("apiInstances.failed")))
+ .catch((e: Error) => setError({ text: e.message || t("apiInstances.failed"), at }))
.finally(() => setBusy(null));
};
@@ -135,6 +140,7 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
onClick={() => {
setEditText((server.managedModels ?? []).join(", "));
setEditing(editing === server.instanceId ? null : server.instanceId);
+ setError(null);
}}
disabled={busy !== null}
aria-label={t("apiInstances.editModels", { name: server.displayName })}
@@ -173,11 +179,14 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
<div className="flex gap-1.5">
<button
type="button"
- onClick={() => run(
- "other",
- () => saveSettings(server.instanceId, { models: modelIds(editText) }),
- () => setEditing(null),
- )}
+ onClick={() => {
+ const ids = modelIds(editText);
+ if (!withinModelIdLimits(ids)) {
+ setError({ text: t("apiInstances.modelsLimit", MODEL_ID_LIMITS), at: server.instanceId });
+ return;
+ }
+ run("other", () => saveSettings(server.instanceId, { models: ids }), () => setEditing(null), server.instanceId);
+ }}
disabled={busy !== null}
className="ui-button"
>
@@ -185,6 +194,7 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
</button>
<button type="button" onClick={() => setEditing(null)} disabled={busy !== null} className="ui-button">{t("common.cancel")}</button>
</div>
+ {error?.at === server.instanceId && <div role="alert" className="text-[12px] leading-4 text-danger">{error.text}</div>}
</div>
)}
</div>
@@ -218,7 +228,7 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
{busy === "add" ? t("apiInstances.adding") : t("apiInstances.add")}
</button>
</div>
- {error && <div className="mt-1 text-[12px] text-danger">{error}</div>}
+ {error && !error.at && <div className="mt-1 text-[12px] text-danger">{error.text}</div>}
</div>
);
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 7e6343f7ce..c1c6d4a568 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -6879,6 +6879,7 @@
"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.modelsLimit": "Use at most {count} model IDs, each up to {length} characters.",
"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",
@@ -9387,6 +9388,7 @@
"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.instance.defaultModelRemoved": "{model} is the default model. Choose another default model before removing it from this server.",
"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 ffecf4cc9b..9fb7311621 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -6600,6 +6600,7 @@
"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.modelsLimit": "Use no máximo {count} IDs de modelo, cada um com até {length} caracteres.",
"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}",
@@ -9358,6 +9359,7 @@
"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.instance.defaultModelRemoved": "{model} é o modelo padrão. Escolha outro modelo padrão antes de removê-lo deste servidor.",
"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.",