Skip to content

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

Settings: change an OpenAI-compatible provider's base URL in place (#6185)

Milind Sonib3a619daca47
diff --git a/server/claude-accounts.ts b/server/claude-accounts.ts
index 3a752ce768..f9ae5fcb0a 100644
--- a/server/claude-accounts.ts
+++ b/server/claude-accounts.ts
@@ -23,6 +23,10 @@ export const instanceSettingsSchema = z.object({
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,
+ /** An added OpenAI-compatible server's base URL, changed in place. */
+ url: addEndpointSchema.shape.url.optional(),
+ /** Its new API key; omitted keeps the saved one, unless the URL's host changes. */
+ apiKey: addEndpointSchema.shape.key.optional(),
}).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 19a363b2e4..13ce4602af 100644
--- a/server/openai-compat-endpoints.ts
+++ b/server/openai-compat-endpoints.ts
@@ -1,6 +1,7 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";
+import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, probeOllama } from "./drivers/ollama.ts";
export const ADDED_ENDPOINT_PREFIX = "openai-compat-";
@@ -59,6 +60,47 @@ export function addEndpoint(instances: InstanceConfigMap, body: AddEndpoint): {
return { instanceId };
}
+/** A new base URL and, optionally, a new key for an added server, in place: its id, models and bots stay. A saved key is
+ * only sent on to the origin (scheme, host and port) it was entered for, so a move to another origin, or from https to
+ * http, needs the key again. Ollama's placeholder key is no secret and moves with it. */
+export function changeEndpointAddress(
+ instances: InstanceConfigMap, instanceId: string, change: { url?: string; apiKey?: string },
+): { addressChanged: boolean } | { error: string; status: 400 | 409 } {
+ const entry = instances[instanceId];
+ const config = (entry.config ?? {}) as Record<string, unknown>;
+ const saved = typeof config.url === "string" ? endpointBaseUrl(config.url) : null;
+ const url = change.url === undefined ? saved : endpointBaseUrl(change.url);
+ if (!url) return { status: 400, error: "Enter an http or https base URL without a user name, password or query string." };
+ if (change.apiKey !== undefined && /^https?:\/\//i.test(change.apiKey)) {
+ return { status: 400, error: "That API key looks like a URL. Paste the secret key itself, not a web address." };
+ }
+ if (change.apiKey === undefined && config.key !== OLLAMA_PLACEHOLDER_KEY && (!saved || new URL(url).origin !== new URL(saved).origin)) {
+ return { status: 400, error: "Enter the API key again: a saved key is only sent to the server it was entered for." };
+ }
+ if (config.catalog && url !== saved) {
+ const others = Object.fromEntries(Object.entries(instances).filter(([id]) => id !== instanceId));
+ const duplicate = localServerAlreadyAdded(others, url);
+ if (duplicate) return { status: 409, error: duplicate };
+ }
+ entry.config = { ...config, url, ...(change.apiKey !== undefined ? { key: change.apiKey } : {}) };
+ return { addressChanged: url !== saved };
+}
+
+/** Whether the server at `url` lists its models with `key`: Ollama's own list for an Ollama server, else /models. */
+export async function endpointModelsReadable(config: { url: string; key: string; catalog?: unknown }, timeoutMs = 8_000): Promise<boolean> {
+ if (isOllamaServer(config)) return ["ready", "no-models"].includes((await probeOllama(config.url, { key: config.key, timeoutMs })).state);
+ try {
+ const response = await fetch(`${config.url}/models`, {
+ headers: { authorization: `Bearer ${config.key}` }, redirect: "error", signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!response.ok) return false;
+ const body = await response.json() as { data?: unknown } | unknown[];
+ return Array.isArray(body) || Array.isArray((body as { data?: unknown }).data);
+ } catch {
+ return false;
+ }
+}
+
export function withEndpointUrls(described: unknown, configs: InstanceConfigMap): unknown {
if (!Array.isArray(described)) return described;
return described.map((instance: { instanceId?: string }) => {
@@ -66,6 +108,7 @@ export function withEndpointUrls(described: unknown, configs: InstanceConfigMap)
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 } : {}) };
+ const placeholderKey = (entry.config as { key?: unknown } | undefined)?.key === OLLAMA_PLACEHOLDER_KEY;
+ return { ...instance, ...(url ? { url } : {}), ...(Array.isArray(managedModels) ? { managedModels } : {}), ...(placeholderKey ? { placeholderKey } : {}) };
});
}
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index 274ff1362e..39e50f8bcc 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -28,7 +28,7 @@ import {
} from "../claude-bedrock.ts";
import { updateClaudeCli } from "../claude-update.ts";
import { persistableInstanceConfigs, saveConfig, withInstanceCli, type AppConfig } from "../config.ts";
-import { addEndpoint, addEndpointSchema, endpointBaseUrl, isAddedEndpoint, localServerAlreadyAdded, withEndpointUrls } from "../openai-compat-endpoints.ts";
+import { addEndpoint, addEndpointSchema, changeEndpointAddress, endpointBaseUrl, endpointModelsReadable, isAddedEndpoint, localServerAlreadyAdded, withEndpointUrls } from "../openai-compat-endpoints.ts";
import { findOllama, probeOllama } from "../drivers/ollama.ts";
import type { InstanceConfigMap, ModelSelection, ProviderInstance } from "../contracts.ts";
import { removeAntigravityProfile } from "../drivers/antigravity-acp.ts";
@@ -66,6 +66,8 @@ export interface InstanceRouteDeps {
activeGroupTurnForBot(botId: string): { threadId: string } | null;
/** The server's tested-AI record (server/tested-ai.ts): a check there also settles the new-bot default. */
checkInstance?(instance: ProviderInstance): Promise<EngineCheck>;
+ /** Whether an added server lists its models (server/openai-compat-endpoints.ts); replaced in tests. */
+ endpointModelsReadable?(config: { url: string; key: string; catalog?: unknown }): Promise<boolean>;
}
export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
@@ -74,6 +76,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
persistProviderInstance, configStatus, broadcast, testCliBinary, cliProbeEnvironment, threadBusy,
botForThread, activeGroupTurnForBot,
} = deps;
+ const detectModels = deps.endpointModelsReadable ?? endpointModelsReadable;
const describeInstances = async () => hostedModels ? deps.describeInstances()
: withEndpointUrls(withCodexEndpointInfo(withClaudeBedrockInfo(withClaudeEndpointInfo(await deps.describeInstances(), cfg.instances ?? {}), cfg.instances ?? {}), cfg.instances ?? {}), cfg.instances ?? {});
/** Bots, their backups and threads, the new-bot default, or a turn running on it: a provider in use can't go away. */
@@ -461,7 +464,8 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
}
}
- // PATCH /api/instances/:id {cli: "/path/to/cli" | ""}: "" reverts to the driver default.
+ // PATCH /api/instances/:id {cli: "/path/to/cli" | ""}: "" reverts to the driver default. An added OpenAI-compatible
+ // server also takes {url, apiKey}: its address changes in place, and its key stays unless the host changes.
const instancePatch = /^\/api\/instances\/([\w.-]+)$/.exec(path);
if (method === "PATCH" && instancePatch) {
// JSON-only, so a hostile page cannot send it as a simple request.
@@ -476,6 +480,9 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
if (busyProviderSelections().some((selection) => selection.instanceId === instanceId)) {
return json(res, 409, { error: "Wait for bots using this account to finish before changing its settings." });
}
+ /** Set when the model list is read again from a new address or with a new key: after the busy guard, so bots on
+ * this server are not refused while a slow server answers. */
+ let detect: { url: string; key: string; catalog?: unknown } | null = null;
providerConfigBusy.set(true);
providerInstancesChanging.add(instanceId);
try {
@@ -514,6 +521,15 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
}
entry.config = models.length ? { ...rest, managedModels: models } : rest;
}
+ if (body.url !== undefined || body.apiKey !== undefined) {
+ if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can change a server's address or key." });
+ if (!isAddedEndpoint(instanceId, entry)) return json(res, 400, { error: "The base URL and key can be changed here for added OpenAI-compatible servers only." });
+ const changed = changeEndpointAddress(instances, instanceId, { url: body.url, apiKey: body.apiKey });
+ if ("error" in changed) return json(res, changed.status, { error: changed.error });
+ // A model list read from the server's /models is read again from the new address or with the new key.
+ const config = entry.config as { url: string; key: string; catalog?: unknown; managedModels?: unknown };
+ if ((changed.addressChanged || body.apiKey !== undefined) && !Array.isArray(config.managedModels)) detect = { url: config.url, key: config.key, catalog: config.catalog };
+ }
if (body.displayName !== undefined) entry.displayName = body.displayName;
if (body.configDir !== undefined) {
let previousDir: string | undefined;
@@ -527,11 +543,17 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
}
}
await persistProviderInstance(instanceId, instances);
- return json(res, 200, { instances: await describeInstances() });
+ if (!detect) return json(res, 200, { instances: await describeInstances() });
} finally {
providerInstancesChanging.delete(instanceId);
providerConfigBusy.set(false);
}
+ // Saved either way; a list that can't be read leaves sample models in the picker, so the answer says so.
+ const [, readable] = await Promise.all([registry?.refreshModels(instanceId).catch(() => {}), detectModels(detect)]);
+ return json(res, 200, {
+ instances: await describeInstances(),
+ ...(readable ? {} : { warning: "Saved. The model list could not be read at this address with this key, so the model picker may show sample models. Check the address and key, or enter the model IDs." }),
+ });
}
if (method === "DELETE" && instancePatch) {
diff --git a/server/routes/openai-compat-endpoints.test.ts b/server/routes/openai-compat-endpoints.test.ts
index 2f89bebe71..9f0ab631e0 100644
--- a/server/routes/openai-compat-endpoints.test.ts
+++ b/server/routes/openai-compat-endpoints.test.ts
@@ -5,8 +5,8 @@ import { afterEach, describe, expect, it } from "vitest";
import type { AppConfig } from "../config.ts";
import type { InstanceConfigMap } from "../contracts.ts";
import { json, readBody } from "../harness/http.ts";
-import { endpointBaseUrl, endpointDisplayUrl } from "../openai-compat-endpoints.ts";
-import { requiredScope } from "../request-auth.ts";
+import { endpointBaseUrl, endpointDisplayUrl, endpointModelsReadable } from "../openai-compat-endpoints.ts";
+import { requiredScope, type RequestAuth } from "../request-auth.ts";
import { createInstanceRoutes, type InstanceRouteDeps } from "./instances.ts";
import { dispatchRoutes } from "./table.ts";
@@ -17,16 +17,22 @@ afterEach(async () => {
const SECRET = "sk-test-0123456789";
-async function serve(options: { hosted?: boolean; botInstance?: string } = {}) {
+async function serve(options: {
+ hosted?: boolean; botInstance?: string; botBusy?: boolean; auth?: RequestAuth;
+ readable?: (config: { url: string; key: string }) => Promise<boolean>;
+} = {}) {
const cfg = { instances: { openaiCompat: { driver: "openai-compat" }, claude: { driver: "claudeAgent" } } } as unknown as AppConfig;
const persisted: InstanceConfigMap[] = [];
+ const refreshed: string[] = [];
let busy = false;
const bots = options.botInstance
- ? [{ id: "b1", busy: false, modelSelection: { instanceId: options.botInstance, model: "m" } }]
+ ? [{ id: "b1", busy: Boolean(options.botBusy), modelSelection: { instanceId: options.botInstance, model: "m" } }]
: [];
const deps = {
store: { bots, tasks: () => [] },
cfg,
+ registry: { refreshModels: async (instanceId: string) => { refreshed.push(instanceId); return true; } },
+ endpointModelsReadable: options.readable ?? (async () => true),
hostedModels: Boolean(options.hosted),
providerConfigBusy: { get: () => busy, set: (value: boolean) => { busy = value; } },
providerInstancesChanging: new Set<string>(),
@@ -46,7 +52,7 @@ async function serve(options: { hosted?: boolean; botInstance?: string } = {}) {
const url = new URL(req.url ?? "/", "http://localhost");
const handled = await dispatchRoutes(routes, {
req, res, url, path: url.pathname, method: req.method ?? "GET",
- auth: { kind: "loopback", scopes: ["admin"] }, json, readBody,
+ auth: options.auth ?? { kind: "loopback", scopes: ["admin"] }, json, readBody,
});
if (!handled) json(res, 404, { from: "inline routes" });
});
@@ -60,7 +66,7 @@ async function serve(options: { hosted?: boolean; botInstance?: string } = {}) {
const text = await response.text();
return { status: response.status, text, body: JSON.parse(text) as any };
};
- return { cfg, persisted, call };
+ return { cfg, persisted, refreshed, call, busy: () => busy };
}
const add = { displayName: "Zhipu", url: "https://open.bigmodel.cn/api/paas/v4/", key: SECRET, models: ["glm-4.6", "glm-4.6", "glm-5"] };
@@ -133,6 +139,141 @@ describe("added OpenAI-compatible servers", () => {
});
});
+describe("changing an added server's base URL", () => {
+ const ID = "openai-compat-edit";
+ const seed = (cfg: AppConfig, config: Record<string, unknown> = { key: SECRET, url: "https://old.example.com/v1", managedModels: ["glm-5"] }) => {
+ cfg.instances = { ...cfg.instances, [ID]: { driver: "openai-compat", displayName: "Zhipu", access: "api", config } };
+ };
+
+ it("is admin-only", () => {
+ expect(requiredScope("PATCH", `/api/instances/${ID}`)).toBe("admin");
+ });
+
+ it("changes the address in place, keeping the id, models, the bot using it and the saved key", async () => {
+ const { cfg, refreshed, call } = await serve({ botInstance: ID });
+ seed(cfg);
+ const changed = await call("PATCH", `/api/instances/${ID}`, { url: " https://old.example.com/api/v2/ " });
+ expect(changed.status, changed.text).toBe(200);
+ expect(changed.text).not.toContain(SECRET);
+ expect(cfg.instances?.[ID]).toEqual({
+ driver: "openai-compat", displayName: "Zhipu", access: "api",
+ config: { key: SECRET, url: "https://old.example.com/api/v2", managedModels: ["glm-5"] },
+ });
+ // Models were entered by hand, so nothing is detected again.
+ expect(refreshed).toEqual([]);
+ });
+
+ it("detects the models again when they came from the server's own list", async () => {
+ const { cfg, refreshed, call } = await serve();
+ seed(cfg, { key: SECRET, url: "https://old.example.com/v1" });
+ expect((await call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" })).status).toBe(200);
+ expect(refreshed).toEqual([ID]);
+ });
+
+ it("refuses a bad address and changes nothing", async () => {
+ const { cfg, persisted, call } = await serve();
+ seed(cfg);
+ for (const url of ["ftp://old.example.com/v1", "old.example.com/v1", "https://u:[email protected]/v1", "https://old.example.com/v1?key=x", ""]) {
+ expect((await call("PATCH", `/api/instances/${ID}`, { url })).status, url).toBe(400);
+ }
+ expect((await call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2", apiKey: "https://x.example" })).status).toBe(400);
+ expect(persisted).toEqual([]);
+ expect((cfg.instances?.[ID]?.config as { url?: string } | undefined)?.url).toBe("https://old.example.com/v1");
+ });
+
+ it("needs the key again when the host changes, and takes a new key with the address", async () => {
+ const { cfg, call } = await serve();
+ seed(cfg);
+ for (const url of ["https://new.example.com/v1", "https://old.example.com:8443/v1"]) {
+ const refused = await call("PATCH", `/api/instances/${ID}`, { url });
+ expect(refused.status, url).toBe(400);
+ expect(refused.body.error).toMatch(/API key again/);
+ }
+ expect((cfg.instances?.[ID]?.config as { url?: string } | undefined)?.url).toBe("https://old.example.com/v1");
+ const moved = await call("PATCH", `/api/instances/${ID}`, { url: "https://new.example.com/v1", apiKey: "sk-new" });
+ expect(moved.status, moved.text).toBe(200);
+ expect(moved.text).not.toContain("sk-new");
+ expect(cfg.instances?.[ID]?.config).toEqual({ key: "sk-new", url: "https://new.example.com/v1", managedModels: ["glm-5"] });
+ const rekeyed = await call("PATCH", `/api/instances/${ID}`, { apiKey: "sk-third" });
+ expect(rekeyed.status, rekeyed.text).toBe(200);
+ expect(cfg.instances?.[ID]?.config).toMatchObject({ key: "sk-third", url: "https://new.example.com/v1" });
+ });
+
+ it("needs the key again when https becomes http on the same host", async () => {
+ const { cfg, call } = await serve();
+ seed(cfg);
+ const refused = await call("PATCH", `/api/instances/${ID}`, { url: "http://old.example.com/v1" });
+ expect(refused.status, refused.text).toBe(400);
+ expect(refused.body.error).toMatch(/API key again/);
+ expect(cfg.instances?.[ID]?.config).toMatchObject({ key: SECRET, url: "https://old.example.com/v1" });
+ });
+
+ it("moves an Ollama server's placeholder key to another host without asking", async () => {
+ const { cfg, call } = await serve();
+ seed(cfg, { key: "ollama", url: "http://127.0.0.1:11434", catalog: "ollama" });
+ const listed = await call("GET", "/api/instances");
+ expect(listed.body.instances.find((row: any) => row.instanceId === ID)).toMatchObject({ placeholderKey: true });
+ const moved = await call("PATCH", `/api/instances/${ID}`, { url: "http://192.168.1.20:11434" });
+ expect(moved.status, moved.text).toBe(200);
+ expect(cfg.instances?.[ID]?.config).toEqual({ key: "ollama", url: "http://192.168.1.20:11434", catalog: "ollama" });
+ });
+
+ it("saves an address whose model list can't be read, says so, and reads it after the busy guard", async () => {
+ let busyWhileReading: boolean | undefined;
+ const asked: Array<{ url: string; key: string }> = [];
+ const server = await serve({ readable: async (config) => { asked.push(config); busyWhileReading = server.busy(); return false; } });
+ seed(server.cfg, { key: SECRET, url: "https://old.example.com/v1" });
+ const saved = await server.call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" });
+ expect(saved.status, saved.text).toBe(200);
+ expect(saved.body.warning).toMatch(/model list could not be read/);
+ expect(saved.text).not.toContain(SECRET);
+ expect(asked).toEqual([{ url: "https://old.example.com/v2", key: SECRET }]);
+ expect(busyWhileReading).toBe(false);
+ expect((server.cfg.instances?.[ID]?.config as { url?: string } | undefined)?.url).toBe("https://old.example.com/v2");
+
+ const fine = await serve();
+ seed(fine.cfg, { key: SECRET, url: "https://old.example.com/v1" });
+ const clean = await fine.call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" });
+ expect(clean.status).toBe(200);
+ expect(clean.body).not.toHaveProperty("warning");
+ });
+
+ it("waits while a bot using it is mid-turn, or while provider settings are changing", async () => {
+ const { cfg, persisted, call } = await serve({ botInstance: ID, botBusy: true });
+ seed(cfg);
+ expect((await call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" })).status).toBe(409);
+ expect(persisted).toEqual([]);
+ });
+
+ it("is refused for the built-in slot, other engines, a client without admin and a hosted server", async () => {
+ const { cfg, call } = await serve();
+ seed(cfg);
+ expect((await call("PATCH", "/api/instances/openaiCompat", { url: "https://x.example/v1", apiKey: "k" })).status).toBe(400);
+ expect((await call("PATCH", "/api/instances/claude", { url: "https://x.example/v1", apiKey: "k" })).status).toBe(400);
+ const service = await serve({ auth: { kind: "loopback", scopes: ["client"], trust: "service" } });
+ seed(service.cfg);
+ expect((await service.call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" })).status).toBe(403);
+ const hosted = await serve({ hosted: true });
+ seed(hosted.cfg);
+ expect((await hosted.call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" })).status).toBe(403);
+ });
+});
+
+describe("reading an added server's model list", () => {
+ it("is true only when /models answers a list with the key", async () => {
+ const server = createServer((req, res) => {
+ const ok = req.url === "/v1/models" && req.headers.authorization === `Bearer ${SECRET}`;
+ res.writeHead(ok ? 200 : 401, { "content-type": "application/json" }).end(JSON.stringify(ok ? { data: [{ id: "m" }] } : { error: "no" }));
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`;
+ expect(await endpointModelsReadable({ url, key: SECRET })).toBe(true);
+ expect(await endpointModelsReadable({ url, key: "wrong" })).toBe(false);
+ expect(await endpointModelsReadable({ url: `${url}/nope`, key: SECRET })).toBe(false);
+ });
+});
+
describe("base URL handling", () => {
it("keeps origin and path only", () => {
expect(endpointBaseUrl(" http://localhost:11434/v1/ ")).toBe("http://localhost:11434/v1");
diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.ts
index eedab9fefc..846528b6e5 100644
--- a/src/components/OpenAiCompatServers.test.ts
+++ b/src/components/OpenAiCompatServers.test.ts
@@ -2,7 +2,7 @@ import { Children, createElement, isValidElement, type ReactElement, type ReactN
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as store from "@/state/store";
-import { BuiltInReplyWait, modelIds, OtherOpenAiCompatServers, LmStudioServer, lmStudioBaseUrl } from "./OpenAiCompatServers";
+import { BuiltInReplyWait, modelIds, originChanged, OtherOpenAiCompatServers, LmStudioServer, lmStudioBaseUrl } from "./OpenAiCompatServers";
const fixture = vi.hoisted(() => ({ counting: false, values: [] as unknown[], index: 0, api: vi.fn(), track: vi.fn() }));
vi.mock("react", async (original) => {
@@ -297,9 +297,9 @@ 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[], dispatch = vi.fn()) {
+ function row(managedModels?: string[], dispatch = vi.fn(), extra: Record<string, unknown> = {}) {
vi.stubGlobal("window", {});
- const servers = [instance("openai-compat-1", "Zhipu", { url: "https://open.bigmodel.cn/api/paas/v4", ...(managedModels ? { managedModels } : {}) })];
+ const servers = [instance("openai-compat-1", "Zhipu", { url: "https://open.bigmodel.cn/api/paas/v4", ...(managedModels ? { managedModels } : {}), ...extra })];
vi.spyOn(store, "useStore").mockReturnValue({
state: { ...store.initialState, instances: servers }, dispatch, flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),
});
@@ -322,7 +322,7 @@ describe("changing an added server's model IDs", () => {
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!();
+ labelled(row(["glm-4.6", "glm-5"]), "Edit 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" } });
@@ -337,7 +337,7 @@ describe("changing an added server's model IDs", () => {
fixture.values = [];
fixture.api.mockReset();
fixture.api.mockResolvedValue({ instances: [] });
- labelled(row(), "Change model IDs for Zhipu")!.props.onClick!();
+ labelled(row(), "Edit Zhipu")!.props.onClick!();
expect(labelled(row(), "Model IDs for Zhipu")!.props.value).toBe("");
save(row()).props.onClick!();
await flush();
@@ -347,7 +347,7 @@ describe("changing an added server's model IDs", () => {
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"]), "Edit 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();
@@ -355,4 +355,85 @@ describe("changing an added server's model IDs", () => {
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.");
});
+
+ it("opens with the saved base URL and an empty key, and sends a new path on the same host without a key", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [] });
+ labelled(row(["glm-5"]), "Edit Zhipu")!.props.onClick!();
+ const address = labelled(row(["glm-5"]), "Base URL for Zhipu")!;
+ expect(address.props.value).toBe("https://open.bigmodel.cn/api/paas/v4");
+ expect(labelled(row(["glm-5"]), "New API key for Zhipu")!.props.value).toBe("");
+ address.props.onChange!({ target: { value: "https://open.bigmodel.cn/api/coding/paas/v4/" } });
+ save(row(["glm-5"])).props.onClick!();
+ await flush();
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", {
+ method: "PATCH", body: JSON.stringify({ models: ["glm-5"], url: "https://open.bigmodel.cn/api/coding/paas/v4" }),
+ });
+ });
+
+ it("asks for the key again before saving an address on another host", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [] });
+ labelled(row(["glm-5"]), "Edit Zhipu")!.props.onClick!();
+ labelled(row(["glm-5"]), "Base URL for Zhipu")!.props.onChange!({ target: { value: "https://api.z.ai/api/paas/v4" } });
+ expect((save(row(["glm-5"])).props as { disabled?: boolean }).disabled).toBe(true);
+ expect(JSON.stringify(row(["glm-5"]).map((node) => node.props.children))).toContain("This address is on another server or protocol.");
+ labelled(row(["glm-5"]), "New API key for Zhipu")!.props.onChange!({ target: { value: " sk-new " } });
+ expect((save(row(["glm-5"])).props as { disabled?: boolean }).disabled).toBe(false);
+ save(row(["glm-5"])).props.onClick!();
+ await flush();
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", {
+ method: "PATCH", body: JSON.stringify({ models: ["glm-5"], url: "https://api.z.ai/api/paas/v4", apiKey: "sk-new" }),
+ });
+ });
+
+ it("asks for the key again when https becomes http on the same host", () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ labelled(row(["glm-5"]), "Edit Zhipu")!.props.onClick!();
+ labelled(row(["glm-5"]), "Base URL for Zhipu")!.props.onChange!({ target: { value: "http://open.bigmodel.cn/api/paas/v4" } });
+ expect((save(row(["glm-5"])).props as { disabled?: boolean }).disabled).toBe(true);
+ expect(JSON.stringify(row(["glm-5"]).map((node) => node.props.children))).toContain("This address is on another server or protocol.");
+ });
+
+ it("moves a server with Ollama's placeholder key to another host without asking for a key", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [] });
+ const ollama = { url: "http://127.0.0.1:11434", placeholderKey: true };
+ labelled(row(undefined, vi.fn(), ollama), "Edit Zhipu")!.props.onClick!();
+ labelled(row(undefined, vi.fn(), ollama), "Base URL for Zhipu")!.props.onChange!({ target: { value: "http://192.168.1.20:11434" } });
+ expect((save(row(undefined, vi.fn(), ollama)).props as { disabled?: boolean }).disabled).toBe(false);
+ save(row(undefined, vi.fn(), ollama)).props.onClick!();
+ await flush();
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat-1", {
+ method: "PATCH", body: JSON.stringify({ models: [], url: "http://192.168.1.20:11434" }),
+ });
+ });
+
+ it("keeps the editor open with one line when the new address's model list could not be read", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [], warning: "Saved. The model list could not be read" });
+ labelled(row(), "Edit Zhipu")!.props.onClick!();
+ labelled(row(), "Base URL for Zhipu")!.props.onChange!({ target: { value: "https://open.bigmodel.cn/api/v5" } });
+ save(row()).props.onClick!();
+ await flush();
+ const status = row().find((node) => (node.props as { role?: string }).role === "status");
+ expect(status?.props.children).toMatch(/^Saved\. The model list could not be read at this address/);
+ expect(labelled(row(), "Base URL for Zhipu")).toBeDefined();
+ });
+});
+
+describe("originChanged", () => {
+ it("compares scheme, host and port", () => {
+ expect(originChanged("https://a.example/v1", "https://a.example/v2")).toBe(false);
+ expect(originChanged("https://a.example/v1", "https://b.example/v1")).toBe(true);
+ expect(originChanged("https://a.example/v1", "https://a.example:8443/v1")).toBe(true);
+ expect(originChanged("https://a.example/v1", "http://a.example/v1")).toBe(true);
+ expect(originChanged(undefined, "https://a.example/v1")).toBe(true);
+ expect(originChanged("https://a.example/v1", "not a url")).toBe(false);
+ });
});
diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsx
index 97abd1dea1..86a93ed236 100644
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@ -15,6 +15,7 @@ export function modelIds(text: string): string[] {
const INPUT = cn(KEY_FIELD, "font-sans");
/** A slow computer can take minutes before a local model's first words, so the wait is the person's call. */
export const REPLY_WAIT_CHOICES = [5, 10, 20, 30, 60] as const;
+const EDIT_LABEL = "flex flex-col gap-1 text-[12px] leading-4 text-ink-secondary";
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;
@@ -23,9 +24,15 @@ export const GEMINI_PRESET = { name: "Google Gemini", url: "https://generativela
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 }> =>
+const saveSettings = (instanceId: string, settings: { replyWaitMinutes?: number | null; models?: string[]; url?: string; apiKey?: string }): Promise<{ instances?: unknown; warning?: unknown }> =>
api(`/api/instances/${encodeURIComponent(instanceId)}`, { method: "PATCH", body: JSON.stringify(settings) });
+/** The server keeps a saved key only for the origin (scheme, host and port) it was entered for
+ * (server/openai-compat-endpoints.ts), so https to http counts as a change. */
+export function originChanged(saved: string | undefined, next: string): boolean {
+ try { return !saved || new URL(next.trim()).origin !== new URL(saved).origin; } catch { return false; }
+}
+
function ReplyWaitSelect({ server, disabled, onPick }: { server: InstanceInfo; disabled: boolean; onPick: (minutes: number | null) => void }) {
return (
<Select
@@ -90,17 +97,23 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
/** 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("");
+ /** The open server's base URL and a new key; an empty key keeps the saved one. */
+ const [editUrl, setEditUrl] = useState("");
+ const [editKey, setEditKey] = useState("");
+ /** The server saved at an address whose model list could not be read: the open editor says so in one line. */
+ const [unreadable, setUnreadable] = useState<string | null>(null);
const ready = Boolean(name.trim() && url.trim() && key.trim());
- const run = (kind: "add" | "other", request: () => Promise<{ instances?: unknown }>, onDone?: () => void, at?: string) => {
+ const run = (kind: "add" | "other", request: () => Promise<{ instances?: unknown; warning?: unknown }>, onDone?: (warned: boolean) => void, at?: string) => {
if (busy) return;
setBusy(kind);
setError(null);
+ setUnreadable(null);
void request()
- .then(async ({ instances }) => {
+ .then(async ({ instances, warning }) => {
if (Array.isArray(instances)) dispatch({ type: "instances", instances: instances as InstanceInfo[] });
else await refreshInstances({ reportErrors: true });
- onDone?.();
+ onDone?.(Boolean(warning));
})
.catch((e: Error) => setError({ text: e.message || t("apiInstances.failed"), at }))
.finally(() => setBusy(null));
@@ -123,7 +136,11 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
<div className="mb-0.5 text-[13px] font-medium leading-[18px] text-ink">{t("apiInstances.title")}</div>
<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) => (
+ {servers.map((server) => {
+ const newUrl = editUrl.trim().replace(/\/+$/, "");
+ const urlChanged = newUrl !== (server.url ?? "");
+ const needsKey = urlChanged && !editKey.trim() && !server.placeholderKey && originChanged(server.url, newUrl);
+ return (
<div key={server.instanceId} className="py-1.5">
<div className="flex items-center justify-between gap-2">
<div className="min-w-0 flex-1">
@@ -139,13 +156,16 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
type="button"
onClick={() => {
setEditText((server.managedModels ?? []).join(", "));
+ setEditUrl(server.url ?? "");
+ setEditKey("");
setEditing(editing === server.instanceId ? null : server.instanceId);
setError(null);
+ setUnreadable(null);
}}
disabled={busy !== null}
- aria-label={t("apiInstances.editModels", { name: server.displayName })}
+ aria-label={t("apiInstances.editServer", { name: server.displayName })}
aria-expanded={editing === server.instanceId}
- title={t("apiInstances.editModels", { name: server.displayName })}
+ title={t("apiInstances.editServer", { name: server.displayName })}
className={ICON_BUTTON}
>
<Pencil size={13} aria-hidden="true" />
@@ -173,6 +193,17 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
</div>
{editing === server.instanceId && (
<div className="mt-1.5 flex flex-col gap-1.5">
+ <label className={EDIT_LABEL}>
+ {t("apiInstances.url")}
+ <input type="url" value={editUrl} onChange={(e) => setEditUrl(e.target.value)} placeholder="https://api.example.com/v1"
+ aria-label={t("apiInstances.urlFor", { name: server.displayName })} spellCheck={false} disabled={busy !== null} className={INPUT} />
+ </label>
+ <label className={EDIT_LABEL}>
+ {t("apiInstances.key")}
+ <input type="password" value={editKey} onChange={(e) => setEditKey(e.target.value)} placeholder={t("apiInstances.keepKey")}
+ aria-label={t("apiInstances.keyFor", { name: server.displayName })} autoComplete="off" disabled={busy !== null} className={INPUT} />
+ </label>
+ {needsKey && <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.newHostKey")}</p>}
<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={INPUT} />
<p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.editModelsHint")}</p>
@@ -185,20 +216,28 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })
setError({ text: t("apiInstances.modelsLimit", MODEL_ID_LIMITS), at: server.instanceId });
return;
}
- run("other", () => saveSettings(server.instanceId, { models: ids }), () => setEditing(null), server.instanceId);
+ const settings = { models: ids, ...(urlChanged ? { url: newUrl } : {}), ...(editKey.trim() ? { apiKey: editKey.trim() } : {}) };
+ run("other", () => saveSettings(server.instanceId, settings), (warned) => {
+ setEditKey("");
+ // Saved, but the new address did not list its models: the editor stays open to say so.
+ if (warned) setUnreadable(server.instanceId);
+ else setEditing(null);
+ }, server.instanceId);
}}
- disabled={busy !== null}
+ disabled={busy !== null || needsKey}
className="ui-button"
>
{t("common.save")}
</button>
- <button type="button" onClick={() => setEditing(null)} disabled={busy !== null} className="ui-button">{t("common.cancel")}</button>
+ <button type="button" onClick={() => { setEditing(null); setEditKey(""); }} 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>}
+ {unreadable === server.instanceId && <p role="status" className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.modelsUnreadable")}</p>}
</div>
)}
</div>
- ))}
+ );
+ })}
<div className="mt-2 flex flex-col gap-1.5">
<button
type="button"
diff --git a/src/lib/openai-compat-endpoints.ts b/src/lib/openai-compat-endpoints.ts
index 20c6cd3499..a3d94647c4 100644
--- a/src/lib/openai-compat-endpoints.ts
+++ b/src/lib/openai-compat-endpoints.ts
@@ -5,6 +5,10 @@ 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[] }> {
+export function addedServers(instances: readonly InstanceInfo[]): Array<InstanceInfo & {
+ url?: string; managedModels?: string[];
+ /** Its saved key is Ollama's placeholder, which the server keeps on any address. */
+ placeholderKey?: boolean;
+}> {
return instances.filter(isAddedServer);
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 7b065c8164..ba57e75465 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7396,8 +7396,13 @@
"apiInstances.adding": "Adding…",
"apiInstances.remove": "Remove {name}",
"apiInstances.refreshModels": "Detect models for {name} again",
- "apiInstances.editModels": "Change model IDs for {name}",
+ "apiInstances.editServer": "Edit {name}",
"apiInstances.modelsFor": "Model IDs for {name}",
+ "apiInstances.urlFor": "Base URL for {name}",
+ "apiInstances.keyFor": "New API key for {name}",
+ "apiInstances.keepKey": "Leave empty to keep the current key",
+ "apiInstances.newHostKey": "This address is on another server or protocol. Enter its API key: a saved key is only sent to the server and protocol (http or https) it was entered for.",
+ "apiInstances.modelsUnreadable": "Saved. The model list could not be read at this address with this key, so the model picker may show sample models. Check the address and key, or enter the model IDs.",
"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.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index e146c859d9..a4e94fc4b4 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -7055,8 +7055,13 @@
"apiInstances.adding": "Adicionando…",
"apiInstances.remove": "Remover {name}",
"apiInstances.refreshModels": "Detectar modelos de {name} novamente",
- "apiInstances.editModels": "Alterar IDs de modelo de {name}",
+ "apiInstances.editServer": "Editar {name}",
"apiInstances.modelsFor": "IDs de modelo de {name}",
+ "apiInstances.urlFor": "URL base de {name}",
+ "apiInstances.keyFor": "Nova chave de API de {name}",
+ "apiInstances.keepKey": "Deixe vazio para manter a chave atual",
+ "apiInstances.newHostKey": "Este endereço está em outro servidor ou protocolo. Digite a chave de API dele: uma chave salva só é enviada ao servidor e ao protocolo (http ou https) para os quais foi informada.",
+ "apiInstances.modelsUnreadable": "Salvo. Não foi possível ler a lista de modelos neste endereço com esta chave, então o seletor de modelos pode mostrar modelos de exemplo. Confira o endereço e a chave ou digite os IDs de modelo.",
"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.",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 4acace4ab5..b690d53ed2 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -35887,8 +35887,13 @@
"chat.error.pastUsageLimit": "7c63a440471f4d20b5ce89b6e9c83547db02d840c79cbe7a4913b06e5a57c381",
"computer.watchFullScreenTitle": "9f3f625c39cd1e74ba76474fda7f8cd15b2fabe6e6ee337201a72551f47986d2",
"computer.watchingBotWorks": "b441025e38fe828e8ec4d56a2c9c685f88d9b41d993242c2af8eeaeb8ae3878b",
- "apiInstances.editModels": "6289535b3751b28360962c140a14f124af1368871e0ebaa7968d2676a99948d6",
+ "apiInstances.editServer": "2313fe21ea84567f451e913cae39bd4ef9775a83458b23f3f440c2108e5363a1",
"apiInstances.modelsFor": "928aa8803b92765b315905a8bec2d9c8d1712c506ab62e1a39e9fa2d12f2c8a1",
+ "apiInstances.urlFor": "f09780278e5bc216fec5ab79f6d43ce1571aeae22d57847a8720d86ec72ab4d4",
+ "apiInstances.keyFor": "601be4dea953727aaca3d12697c589b33c92fe436f2f1df2a1daa518f8cccfd3",
+ "apiInstances.keepKey": "a13496c5084b926dd47a6660b2011c073e8a9e0897031c48a913fe0e48e3675b",
+ "apiInstances.newHostKey": "c3aa57a9fc1826dbf7280584a1c53888b8528e851f64feaa5a3018c9bee765ce",
+ "apiInstances.modelsUnreadable": "66dcae6ca8bacb6614f324a61e6543a0a0b46c1b004db3ec170640a78dc8891c",
"apiInstances.editModelsHint": "417c86a79ae13950d99588cb9c63e6981978aa80263e24458e1fde3097ea9e49",
"apiInstances.modelsLimit": "872a834885967b40ebcc35d2ff89adbc1ae4e8585bf0673f4a3ed1d718ba23fc",
"shortcuts.new-thread": "3fb707417e2f33bda62583185a5f38f34990d0327583a776f29666f092624735",
@@ -57171,8 +57176,13 @@
"settings.simple.themes.hint": "b4a933bbef7eebd1ba5305d6bbc14395b9c23eb149178c14c1b1436510c88a9b",
"settings.simple.themes.followHint": "d42ba551158199061ebfda7029c05ad07f84ebad29cfc8c24ffe4a7323ed5629",
"settings.simple.themes.fixedHint": "9debc6ac74d17e0dee92665cd9c4c39963b0a25c3de4830d59175e94e2ad5625",
- "apiInstances.editModels": "6289535b3751b28360962c140a14f124af1368871e0ebaa7968d2676a99948d6",
+ "apiInstances.editServer": "2313fe21ea84567f451e913cae39bd4ef9775a83458b23f3f440c2108e5363a1",
"apiInstances.modelsFor": "928aa8803b92765b315905a8bec2d9c8d1712c506ab62e1a39e9fa2d12f2c8a1",
+ "apiInstances.urlFor": "f09780278e5bc216fec5ab79f6d43ce1571aeae22d57847a8720d86ec72ab4d4",
+ "apiInstances.keyFor": "601be4dea953727aaca3d12697c589b33c92fe436f2f1df2a1daa518f8cccfd3",
+ "apiInstances.keepKey": "a13496c5084b926dd47a6660b2011c073e8a9e0897031c48a913fe0e48e3675b",
+ "apiInstances.newHostKey": "c3aa57a9fc1826dbf7280584a1c53888b8528e851f64feaa5a3018c9bee765ce",
+ "apiInstances.modelsUnreadable": "66dcae6ca8bacb6614f324a61e6543a0a0b46c1b004db3ec170640a78dc8891c",
"apiInstances.editModelsHint": "417c86a79ae13950d99588cb9c63e6981978aa80263e24458e1fde3097ea9e49",
"apiInstances.modelsLimit": "872a834885967b40ebcc35d2ff89adbc1ae4e8585bf0673f4a3ed1d718ba23fc",
"chat.page.uncertain": "9daa06969cfe8f33de35e4cdce7b829eeafd5ed4b041ea6372784f1f22c6ec73",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index c0df5766a9..314aa45c60 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -9863,8 +9863,13 @@
"settings.simple.themes.hint": "「跟隨系統」會在 Daylight 與 Midnight 之間切換。其他主題則會保持固定,直到你手動更改。",
"settings.simple.themes.followHint": "跟隨你的電腦設定:淺色時使用 Daylight,深色時使用 Midnight。",
"settings.simple.themes.fixedHint": "保持目前的選擇。選取「跟隨系統」即可在 Daylight 與 Midnight 之間自動切換。",
- "apiInstances.editModels": "變更 {name} 的模型 ID",
+ "apiInstances.editServer": "編輯 {name}",
"apiInstances.modelsFor": "{name} 的模型 ID",
+ "apiInstances.urlFor": "{name} 的基礎 URL",
+ "apiInstances.keyFor": "{name} 的新 API 金鑰",
+ "apiInstances.keepKey": "留空即保留目前的金鑰",
+ "apiInstances.newHostKey": "此位址位於另一個伺服器或使用另一種協定。請輸入它的 API 金鑰:已儲存的金鑰只會傳送給當初輸入時的伺服器與協定(http 或 https)。",
+ "apiInstances.modelsUnreadable": "已儲存。無法用此金鑰在此位址讀取模型清單,因此模型選擇器可能會顯示範例模型。請檢查位址和金鑰,或輸入模型 ID。",
"apiInstances.editModelsHint": "模型 ID 請以逗號或空格分隔。留空即可重新從伺服器偵測。",
"apiInstances.modelsLimit": "最多使用 {count} 個模型 ID,每個最長 {length} 個字元。",
"chat.page.uncertain": "這個頁面可能仍在線上。取消發布即可將其移除。",