Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
First-class GLM provider setup in the model picker
vincent1f9de187b8f0
diff --git a/NOTICE b/NOTICEindex c84dc5df62..53162611a5 100644--- a/NOTICE+++ b/NOTICE@@ -69,7 +69,7 @@ includes third-party components under their own licenses, listed with thelibrary.Selected provider icon paths are from Simple Icons, used under CC0 1.0.-The Cohere provider icon path is from Lobe Icons, Copyright 2023 LobeHub,+The Cohere and Z.ai provider icon paths are from Lobe Icons, Copyright 2023 LobeHub,used under the MIT License.The Cursor provider mark (src/components/CursorMark.tsx) adapts the Cursordiff --git a/docs/custom-engines.md b/docs/custom-engines.mdindex 1daab47701..2e268b31b5 100644--- a/docs/custom-engines.md+++ b/docs/custom-engines.md@@ -199,8 +199,13 @@ for current addresses, model availability and region requirements.### Example: GLM through Z.ai or Zhipu BigModel-Use the `openai-compat` instance above with a general API key from your-chosen service. Set `config.url` to its OpenAI-compatible base URL:+In the model picker, choose **Set up GLM**. In Advanced mode, find its mark+under **API keys**. Select the region where you obtained your API key and add the key. Models listed by+that service appear under the new provider. If the list is unavailable, you can+enter exact model IDs in **API Keys → Other (OpenAI-compatible)**.++For configuration files, use the `openai-compat` instance above with a general+API key from your chosen service. Set `config.url` to its OpenAI-compatible base URL:| Service | Base URL ||---|---|diff --git a/screenshots/issue-5366/after-1440-daylight.png b/screenshots/issue-5366/after-1440-daylight.pngnew file mode 100644index 0000000000..65154abe57Binary files /dev/null and b/screenshots/issue-5366/after-1440-daylight.png differdiff --git a/screenshots/issue-5366/after-1440-midnight.png b/screenshots/issue-5366/after-1440-midnight.pngnew file mode 100644index 0000000000..ce834c5606Binary files /dev/null and b/screenshots/issue-5366/after-1440-midnight.png differdiff --git a/screenshots/issue-5366/after-390-daylight.png b/screenshots/issue-5366/after-390-daylight.pngnew file mode 100644index 0000000000..66875a8103Binary files /dev/null and b/screenshots/issue-5366/after-390-daylight.png differdiff --git a/screenshots/issue-5366/after-390-midnight.png b/screenshots/issue-5366/after-390-midnight.pngnew file mode 100644index 0000000000..a193fdb518Binary files /dev/null and b/screenshots/issue-5366/after-390-midnight.png differdiff --git a/screenshots/issue-5366/before-1440-daylight.png b/screenshots/issue-5366/before-1440-daylight.pngnew file mode 100644index 0000000000..704c0ca39aBinary files /dev/null and b/screenshots/issue-5366/before-1440-daylight.png differdiff --git a/screenshots/issue-5366/before-1440-midnight.png b/screenshots/issue-5366/before-1440-midnight.pngnew file mode 100644index 0000000000..6d7d892591Binary files /dev/null and b/screenshots/issue-5366/before-1440-midnight.png differdiff --git a/screenshots/issue-5366/before-390-daylight.png b/screenshots/issue-5366/before-390-daylight.pngnew file mode 100644index 0000000000..92e71988e7Binary files /dev/null and b/screenshots/issue-5366/before-390-daylight.png differdiff --git a/screenshots/issue-5366/before-390-midnight.png b/screenshots/issue-5366/before-390-midnight.pngnew file mode 100644index 0000000000..6e4f088ba2Binary files /dev/null and b/screenshots/issue-5366/before-390-midnight.png differdiff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex b32087796d..dace69443d 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -160,6 +160,28 @@ describe("OpenAICompatDriver", () => {await inst.dispose();});+ it.each(["https://api.z.ai/api/paas/v4", "https://open.bigmodel.cn/api/paas/v4"])("discovers GLM models when the %s setup joins the first catalog read", async (url) => {+ let respond!: (response: Response) => void;+ const response = new Promise<Response>((resolve) => { respond = resolve; });+ const fetchMock = vi.fn(() => response);+ vi.stubGlobal("fetch", fetchMock);+ const instance = await OpenAICompatDriver.create({+ instanceId: "openai-compat-glm", displayName: "GLM", enabled: true,+ config: OpenAICompatDriver.decodeConfig({ url, key: "glm-test-key" }), environment: {},+ });+ try {+ expect(instance.models.options).toEqual([]);+ const firstList = instance.refreshModels?.();+ respond(Response.json({ data: [{ id: "glm-5.3" }, { id: "glm-4.6" }] }));+ await firstList;+ expect(fetchMock).toHaveBeenCalledExactlyOnceWith(`${url}/models`, expect.objectContaining({ headers: { authorization: "Bearer glm-test-key" } }));+ expect(instance.models).toMatchObject({ default: "glm-5.3", options: [{ id: "glm-5.3" }, { id: "glm-4.6" }] });+ expect(instance.models.options.every((option) => !option.custom)).toBe(true);+ } finally {+ await instance.dispose();+ }+ });+it("lists Gemini's chat models by their plain IDs", async () => {const fetchMock = vi.fn(async () => Response.json({ object: "list", data: [{ id: "models/gemini-2.5-pro", object: "model", owned_by: "google" },diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex 6ac94a5fff..1a389192a4 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -3,6 +3,7 @@import { titleCaseModelId, type ModelCatalog, type ProviderDriver } from "../contracts.ts";import { onWorkspaceServer, operatorEnvKey } from "../credential-env.ts";import { isLoopback } from "../provider-key-check.ts";+import { isGlmOrigin } from "../../shared/glm-provider.ts";import { lmStudioV1Catalog } from "./local-inject.ts";import { isContextName, isOllama, pickedName, serveWithWindow } from "./ollama-context.ts";import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, thinkingEffort, type OllamaModel, type OllamaStatus } from "./ollama.ts";@@ -223,7 +224,8 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {const missingKey = !ownKeyVariable || OWN_KEY_ENVS.has(config.apiKeyEnv)? "No API key — open Settings → AI → Providers.": `no API key — set ${config.apiKeyEnv} or add it to the instance config`;- const seeded = config.catalog === "openai" ? OPENAI_MODELS : isOllamaServer(config) ? NO_MODELS : DEFAULT_MODELS;+ const glm = isGlmOrigin(config.url);+ const seeded = config.catalog === "openai" ? OPENAI_MODELS : isOllamaServer(config) || glm ? NO_MODELS : DEFAULT_MODELS;let catalog: ModelCatalog = config.managedModels? { default: config.managedModels[0], options: config.managedModels.map(id => ({ id, label: id })) }: config.model@@ -346,7 +348,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {label: openRouter ? freeLabel(label, row) : label,...(contextWindow ? { contextWindow } : {}),...(takesEffort(id, row) ? { variants: EFFORT_CHOICES } : {}),- ...(config.catalog === "openai" ? {} : { custom: true }),+ ...(config.catalog === "openai" || glm ? {} : { custom: true }),});}if (!options.length) return;@@ -391,6 +393,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {// The first list says which models can call tools, and is what the engine list shows right after adding Ollama.if (loading && isOllamaServer(config)) await Promise.race([loading, new Promise((done) => { setTimeout(done, OLLAMA_FIRST_LIST_MS).unref(); })]);+ let firstGlmList: Promise<unknown> | null = glm && loading ? loading.finally(() => { firstGlmList = null; }) : null;const runtime = createOpenAIChatRuntime({input,@@ -404,7 +407,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {models: () => reasoningCatalog(catalog, reasoningFor),prepareTurn: (turn, signal) => loading && (turn.variant || isOllamaServer(config)) ? waitForCatalog(loading, signal) : undefined,selectedReasoning: (model, variant) => Boolean(variant && fact(model)?.thinking?.choices.includes(variant)),- refreshModels: fetchModels,+ refreshModels: async () => { await (firstGlmList ?? fetchModels()); },imageInput: (model) => fact(model)?.vision ?? true,...(gemini ? { videoBytes: GEMINI_VIDEO_BYTES } : {}),toolUse: (model) => fact(model)?.tools ?? true,diff --git a/server/provider-icon.test.ts b/server/provider-icon.test.tsindex abb19d048f..7c8ec7b447 100644--- a/server/provider-icon.test.ts+++ b/server/provider-icon.test.ts@@ -25,6 +25,8 @@ describe("a server's mark comes from its host", () => {["https://api.cohere.com/compatibility/v1", "cohere"],["https://api.cohere.ai/compatibility/v1", "cohere"],["https://openrouter.ai/api/v1", "openrouter"],+ ["https://api.z.ai/api/paas/v4", "zai"],+ ["https://open.bigmodel.cn/api/paas/v4", "zai"],["https://api.anthropic.com/v1", "anthropic"],["https://api.llama.com/compat/v1", "meta"],])("%s shows %s", (url, preset) => {diff --git a/server/provider-icon.ts b/server/provider-icon.tsindex 73d1a63f70..3558bc188d 100644--- a/server/provider-icon.ts+++ b/server/provider-icon.ts@@ -30,6 +30,7 @@ const SERVER_HOSTS: Record<string, ProviderIconPreset> = {"generativelanguage.googleapis.com": "google", "aiplatform.googleapis.com": "google", "*-aiplatform.googleapis.com": "google","api.x.ai": "xai","api.deepseek.com": "deepseek",+ "api.z.ai": "zai", "open.bigmodel.cn": "zai","dashscope.aliyuncs.com": "qwen", "dashscope-*.aliyuncs.com": "qwen","*.*.maas.aliyuncs.com": "qwen","api.moonshot.ai": "moonshot", "api.moonshot.cn": "moonshot",diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex ecf8691892..e4c682de3d 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -5,6 +5,7 @@ import { signInReasonOf } from "../../shared/sign-in-outcome.ts";import { modelManifest } from "../model-manifest/manifest.ts";import { randomUUID } from "node:crypto";import { providerIconError } from "../../shared/provider-icon.ts";+import { isGlmOrigin } from "../../shared/glm-provider.ts";import {assertSeparateClaudeAccount,configuredAccountDirectory,@@ -215,6 +216,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {const added = addEndpoint(instances, parsed.data);if ("error" in added) return json(res, 400, { error: added.error });await persistProviderInstance(added.instanceId, instances);+ if (isGlmOrigin(parsed.data.url)) await registry.refreshModels(added.instanceId).catch(() => false);return json(res, 201, { instanceId: added.instanceId, instances: await describeInstances() });} finally { providerConfigBusy.set(false); }}diff --git a/server/routes/openai-compat-endpoints.test.ts b/server/routes/openai-compat-endpoints.test.tsindex 9f0ab631e0..5dc99daaf5 100644--- a/server/routes/openai-compat-endpoints.test.ts+++ b/server/routes/openai-compat-endpoints.test.ts@@ -1,6 +1,7 @@import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";+import { OpenAICompatDriver } from "../drivers/openai-compat.ts";import type { AppConfig } from "../config.ts";import type { InstanceConfigMap } from "../contracts.ts";@@ -20,6 +21,7 @@ const SECRET = "sk-test-0123456789";async function serve(options: {hosted?: boolean; botInstance?: string; botBusy?: boolean; auth?: RequestAuth;readable?: (config: { url: string; key: string }) => Promise<boolean>;+ models?: (instanceId: string, config: unknown, refresh: boolean) => Promise<unknown>;} = {}) {const cfg = { instances: { openaiCompat: { driver: "openai-compat" }, claude: { driver: "claudeAgent" } } } as unknown as AppConfig;const persisted: InstanceConfigMap[] = [];@@ -36,9 +38,10 @@ async function serve(options: {hostedModels: Boolean(options.hosted),providerConfigBusy: { get: () => busy, set: (value: boolean) => { busy = value; } },providerInstancesChanging: new Set<string>(),- describeInstances: async () => Object.entries(cfg.instances ?? {}).map(([instanceId, entry]) => ({+ describeInstances: async () => Promise.all(Object.entries(cfg.instances ?? {}).map(async ([instanceId, entry]) => ({instanceId, driverKind: entry.driver, displayName: entry.displayName ?? entry.driver,- })),+ ...(options.models && entry.config ? { models: await options.models(instanceId, entry.config, refreshed.includes(instanceId)) } : {}),+ }))),persistProviderInstance: async (_id: string, instances: InstanceConfigMap) => {cfg.instances = instances;persisted.push(structuredClone(instances));@@ -95,6 +98,36 @@ describe("added OpenAI-compatible servers", () => {expect(listed.body.instances.find((row: any) => row.instanceId === "openaiCompat")).not.toHaveProperty("url");});+ it("returns discovered GLM models from the add route without echoing the key", async () => {+ const url = "https://api.z.ai/api/paas/v4";+ const nativeFetch = globalThis.fetch;+ const discover = vi.fn(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ if (String(input) === `${url}/models`) return Response.json({ data: [{ id: "glm-5.3" }, { id: "glm-4.6" }] });+ return nativeFetch(input, init);+ });+ vi.stubGlobal("fetch", discover);+ try {+ const { call, refreshed } = await serve({ models: async (instanceId, config, refresh) => {+ const instance = await OpenAICompatDriver.create({ instanceId, displayName: "GLM (Z.ai)", enabled: true,+ config: OpenAICompatDriver.decodeConfig(config), environment: {} });+ try {+ if (refresh) await instance.refreshModels?.();+ return instance.models;+ } finally { await instance.dispose(); }+ } });+ const created = await call("POST", "/api/instances/openai-compat", { displayName: "GLM (Z.ai)", url, key: SECRET });+ expect(created.status, created.text).toBe(201);+ expect(refreshed).toEqual([created.body.instanceId]);+ expect(created.body.instances.find((instance: { instanceId: string }) => instance.instanceId === created.body.instanceId)).toMatchObject({+ url, models: { default: "glm-5.3", options: [{ id: "glm-5.3" }, { id: "glm-4.6" }] },+ });+ expect(discover).toHaveBeenCalledWith(`${url}/models`, expect.objectContaining({ headers: { authorization: `Bearer ${SECRET}` } }));+ expect(created.text).not.toContain(SECRET);+ } finally {+ vi.unstubAllGlobals();+ }+ });+it("refuses base URLs carrying credentials or query strings, and keys that are URLs", async () => {const { cfg, call } = await serve();for (const url of ["https://user:[email protected]/v1", "https://example.com/v1?api-key=secret", "ftp://example.com/v1", "example.com/v1"]) {diff --git a/shared/glm-provider.ts b/shared/glm-provider.tsnew file mode 100644index 0000000000..7f2e9451f3--- /dev/null+++ b/shared/glm-provider.ts@@ -0,0 +1,13 @@+export const GLM_ENDPOINTS = {+ international: { name: "GLM (Z.ai)", url: "https://api.z.ai/api/paas/v4" },+ china: { name: "GLM (Zhipu BigModel)", url: "https://open.bigmodel.cn/api/paas/v4" },+} as const;++export function isGlmOrigin(url: string): boolean {+ try {+ const origin = new URL(url).origin;+ return origin === "https://api.z.ai" || origin === "https://open.bigmodel.cn";+ } catch {+ return false;+ }+}diff --git a/shared/provider-icon.ts b/shared/provider-icon.tsindex ef6e9170a7..aac9adaddb 100644--- a/shared/provider-icon.ts+++ b/shared/provider-icon.ts@@ -1,6 +1,6 @@export const PROVIDER_ICON_PRESETS = ["openai", "anthropic", "google", "azure", "aws", "xai", "deepseek",- "meta", "mistral", "qwen", "moonshot", "cohere", "openrouter", "ollama",+ "meta", "mistral", "qwen", "moonshot", "cohere", "openrouter", "ollama", "zai",] as const;export type ProviderIconPreset = typeof PROVIDER_ICON_PRESETS[number];@@ -28,6 +28,7 @@ export const PROVIDER_ICON_LABELS: Record<ProviderIconPreset, string> = {cohere: "Cohere",openrouter: "OpenRouter",ollama: "Ollama",+ zai: "GLM (Z.ai)",};function decodedBase64Bytes(value: string): number {diff --git a/src/components/ModelPicker.glm.dom.test.ts b/src/components/ModelPicker.glm.dom.test.tsnew file mode 100644index 0000000000..983786b43f--- /dev/null+++ b/src/components/ModelPicker.glm.dom.test.ts@@ -0,0 +1,104 @@+// @vitest-environment happy-dom+import { act, createElement, useState } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import { BotEditorStore, initialState, reducer, type AppState, type Bot, type InstanceInfo } from "@/state/store";+import { ModelPicker } from "./ModelPicker";++const fixture = vi.hoisted(() => ({ owner: true, advanced: true, api: vi.fn() }));+vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), api: fixture.api }));+vi.mock("@/lib/interface-mode", async (original) => ({ ...await original<typeof import("@/lib/interface-mode")>(), useAdvancedMode: () => fixture.advanced }));+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.owner }));+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));++const local: InstanceInfo = {+ instanceId: "claude", driverKind: "claudeAgent", displayName: "Claude", access: "subscription",+ snapshot: { state: "available", authenticated: true }, models: { default: "sonnet", options: [{ id: "sonnet", label: "Sonnet" }] },+};+const glm: InstanceInfo = {+ instanceId: "openai-compat-glm", driverKind: "openai-compat", displayName: "GLM (Z.ai)", access: "api",+ snapshot: { state: "available", authenticated: true },+ icon: { kind: "preset", preset: "zai" }, url: "https://api.z.ai/api/paas/v4",+ models: { default: "glm-5.3", options: [{ id: "glm-5.3", label: "GLM-5.3" }, { id: "glm-4.6", label: "GLM-4.6" }] },+};+const bot: Bot = {+ id: "scout", threadId: "scout-main", name: "Scout", title: "", description: "", color: "green", notifications: true,+ unread: false, messages: [], modelSelection: { instanceId: "claude", model: "sonnet" },+};+const saveAction = vi.fn();+let host: HTMLDivElement;+let root: ReturnType<typeof createRoot>;+const refreshModels = vi.fn();++function Fixture({ readOnly = false }: { readOnly?: boolean }) {+ const [state, setState] = useState<AppState>({ ...initialState, bots: [bot], instances: [{ ...local, readOnly }], selectedId: bot.id });+ const dispatch = (action: Parameters<typeof reducer>[1]) => {+ saveAction(action);+ setState((previous) => reducer(previous, action));+ };+ refreshModels.mockResolvedValue(undefined);+ return createElement(BotEditorStore, {+ value: { state, dispatch, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels },+ children: createElement(ModelPicker, { bot: state.bots[0]! }),+ });+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ fixture.owner = true;+ fixture.advanced = true;+ fixture.api.mockReset().mockResolvedValue({ instanceId: glm.instanceId, instances: [local, glm] });+ refreshModels.mockClear();+ saveAction.mockClear();+ setLocale("en");+ document.documentElement.dataset.reducedMotion = "true";+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(async () => {+ await act(async () => root.unmount());+ host.remove();+ delete document.documentElement.dataset.reducedMotion;+ vi.unstubAllGlobals();+});++async function open(readOnly = false) {+ await act(async () => root.render(createElement(Fixture, { readOnly })));+ await act(async () => host.querySelector<HTMLButtonElement>('[data-tour="model"]')!.click());+ return document.querySelector<HTMLElement>("[data-model-picker-content]")!;+}+const connect = '[data-model-glm-setup]';++it.each([+ ["international", "GLM (Z.ai)", "https://api.z.ai/api/paas/v4", true],+ ["china", "GLM (Zhipu BigModel)", "https://open.bigmodel.cn/api/paas/v4", false],+])("adds GLM in the %s region and selects a discovered model", async (region, displayName, url, advanced) => {+ fixture.api.mockResolvedValue({ instanceId: glm.instanceId, instances: [local, { ...glm, url, displayName }] });+ fixture.advanced = advanced;+ const menu = await open();+ const setup = menu.querySelector<HTMLButtonElement>(advanced ? connect : "[data-simple-glm-setup]");+ expect(setup).not.toBeNull();+ await act(async () => setup!.click());+ const form = menu.querySelector<HTMLFormElement>("form[data-glm-server]")!;+ const select = form.querySelector("select")!;+ await act(async () => { select.value = region; select.dispatchEvent(new Event("change", { bubbles: true })); });+ const key = form.querySelector<HTMLInputElement>('input[type="password"]')!;+ expect(form.querySelector<HTMLButtonElement>('button[type="submit"]')!.disabled).toBe(true);+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(key, " glm-test-key ");+ key.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => form.querySelector<HTMLButtonElement>('button[type="submit"]')!.click());+ expect(fixture.api).toHaveBeenCalledWith("/api/instances/openai-compat", { method: "POST", body: JSON.stringify({ displayName, url, key: "glm-test-key" }) });+ const model = [...menu.querySelectorAll<HTMLButtonElement>("[data-menu-row]")].find((row) => row.textContent?.includes("GLM-4.6"));+ expect(model).toBeDefined();+ await act(async () => model!.click());+ expect(saveAction).toHaveBeenCalledWith(expect.objectContaining({ type: "setModel", selection: { instanceId: glm.instanceId, model: "glm-4.6" } }));+});++it.each([true, false])("does not offer GLM setup without provider management access (readOnly=%s)", async (readOnly) => {+ fixture.owner = readOnly;+ expect((await open(readOnly)).querySelector(connect)).toBeNull();+});diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex 6bc7f512a9..e82e89b9ed 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -1,4 +1,4 @@-import { engineDisplayName } from "@/lib/engine-rail";+import { GlmServer, GLM_SETUP_ID } from "./OpenAiCompatServers";import { modelLabel, modelProvider } from "@/lib/model-label";import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";import { createPortal } from "react-dom";@@ -6,7 +6,7 @@ import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, KeyRound, Loader2, Rimport { currentTaskBot, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store"; import { sameFields, useStoreActions, useStoreDispatch, useStoreSelector } from "@/state/store-select";import { offeredEffortLevels, type EffortLevel } from "../../shared/wire";import { filterCustomModels, partitionCustomModels, suggestedModels } from "@/lib/custom-models";-import { configuredModelInstances, isClaudeAccount, isCustomOnly, modelsAwaitEngine, SIGN_IN_FAMILY_LABEL, signInFamily } from "@/lib/engine-rail";+import { configuredModelInstances, engineDisplayName, isClaudeAccount, isCustomOnly, isGlmInstance, modelsAwaitEngine, SIGN_IN_FAMILY_LABEL, signInFamily } from "@/lib/engine-rail";import { modelName, simpleModelMenu, variantSuffix } from "@/lib/simple-model-menu";import { choiceIsSelected, modelChoices, modelSelectionForPick, takesTypedModels, withTypedModels, type ModelChoice } from "@/lib/model-choices";export { modelSelectionForPick } from "@/lib/model-choices";@@ -30,7 +30,6 @@ import { lockedWhileBusy, offersReasoning, useRefocusAfterPick, variantChoices,import { BusyModelMenu } from "./ModelPickerBusyMenu";import { useAdvancedMode } from "@/lib/interface-mode";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";-import { t } from "@/lib/i18n";import { COMPACT_SQUARE } from "@/lib/compact-chip";import { useAiSwitch } from "@/lib/ai-switch";@@ -42,7 +41,6 @@ import { Select } from "./Select";const COMPACT_MODEL_COUNT = 5;-export function effortLabel(level: EffortLevel): string {return t(`model.effort.${level}` as Parameters<typeof t>[0]);}@@ -306,12 +304,12 @@ export function ModelPicker({const showActiveAccount = (multipleClaudeAccounts && isClaudeAccount(active)) || Boolean(active?.snapshot.chatgptPlan) || (active?.driverKind === "codex" && /^chatgpt(?:-|$)/.test(active.instanceId));const claudeRailInstance = claudeAccounts.find((instance) => instance.instanceId === lastClaudeIdRef.current)?? claudeAccounts.find((instance) => instance.instanceId === selection.instanceId) ?? claudeAccounts[0];- const railInstance =- pickerInstances.find((instance) => instance.instanceId === (railId ?? selection.instanceId)) ?? pickerInstances[0];+ const glmSetup = railId === GLM_SETUP_ID;+ const railInstance = glmSetup ? undefined : pickerInstances.find((instance) => instance.instanceId === (railId ?? selection.instanceId)) ?? pickerInstances[0];const displayedInstanceId = railInstance?.instanceId;// A plan account discovers its allowed models only after sign-in: an empty catalog must still lead to cloud sign-in,// never local models.- const hasOfficialModels = Boolean(railInstance?.snapshot.chatgptPlan || railInstance?.models.options.some((option) => !option.custom));+ const hasOfficialModels = Boolean(isGlmInstance(railInstance) || railInstance?.snapshot.chatgptPlan || railInstance?.models.options.some((option) => !option.custom));const customOnly = isCustomOnly(railInstance);const { pane, setPane, loading: loadingList } = usePickerPane({ instanceId: displayedInstanceId, railId, hasOfficialModels, customOnly: customOnly && !hasOfficialModels,reading: open && (loadingInstances || refreshingId !== null),@@ -368,7 +366,7 @@ export function ModelPicker({const selectedIsCustom = instance?.models.options.some((option) => option.id === selection.model && option.custom,);- setPane(selectedIsCustom || (official.length === 0 && !instance?.snapshot.chatgptPlan) ? "custom" : "main");+ setPane(selectedIsCustom || (official.length === 0 && !instance?.snapshot.chatgptPlan && !isGlmInstance(instance)) ? "custom" : "main");resetList();};@@ -405,7 +403,7 @@ export function ModelPicker({if (signInFamily(instance) === "openai") lastOpenaiIdRef.current = instance.instanceId;setRailId(instance.instanceId);const official = instance.models.options.filter((option) => !option.custom);- setPane(official.length === 0 && !instance.snapshot.chatgptPlan ? "custom" : "main");+ setPane(official.length === 0 && !instance.snapshot.chatgptPlan && !isGlmInstance(instance) ? "custom" : "main");resetList();};@@ -522,7 +520,8 @@ export function ModelPicker({</div>);const remote = window.ogb?.remoteClient?.active === true;-+ const canSetUpGlm = !remote && ownerOrAdmin === true && (state.instances.length === 0 || state.instances.some((instance) => !instance.readOnly));+ const setUpGlm = () => { setRailId(GLM_SETUP_ID); setFullView(true); if (simpleView) setScope("bot"); };const levels = offeredEffortLevels(active, selection.model);const writeEffort = (effort: EffortLevel | undefined) => {const { effort: _effort, ...model } = selection;@@ -675,8 +674,8 @@ export function ModelPicker({<FollowBotModelRow name={profile.name} model={botModelName} follows={follows} onPick={pickBotModel} />)}<div className="flex min-h-0 min-w-0 flex-1">- {pickerInstances.length > 0 && <ModelEngineRail instances={pickerInstances} selectedInstance={railInstance} claudeInstance={claudeRailInstance} openaiInstance={openaiRailInstance} onSelect={selectRail}- onAddApiKeys={remote ? undefined : openApiKeys} />}+ {(pickerInstances.length > 0 || canSetUpGlm) && <ModelEngineRail instances={pickerInstances} selectedInstance={railInstance} claudeInstance={claudeRailInstance} openaiInstance={openaiRailInstance} onSelect={selectRail}+ onAddApiKeys={remote ? undefined : openApiKeys} glmSetup={glmSetup} onSetUpGlm={canSetUpGlm ? setUpGlm : undefined} />}<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto">{threadId && simpleUpdatesBotDefault && (@@ -695,7 +694,7 @@ export function ModelPicker({</p></div>)}- {railInstance ? (+ {glmSetup && canSetUpGlm ? <GlmServer onAdded={(id) => { setRailId(id); setPane("main"); resetList(); }} /> : railInstance ? (<><div className="shrink-0 px-3.5 pb-2 pt-3"><div className="flex items-center justify-between gap-3">@@ -819,7 +818,7 @@ export function ModelPicker({{shownOfficial.map(renderRow)}{shownOfficial.length === 0 && (<div className="px-2 py-5 text-center text-[13px] leading-[18px] text-ink-secondary">- {t("model.noMatch", { query: query.trim() })}+ {isGlmInstance(railInstance) && !official.length ? t("apiInstances.glmNoModels") : t("model.noMatch", { query: query.trim() })}</div>)}{!query && !showAll && official.length > compactOfficial.length && (@@ -964,7 +963,7 @@ export function ModelPicker({}}onSetUp={openFull}onCheckAgain={(instance) => refreshModels(instance.instanceId)}- onManage={remote ? undefined : openEngines}+ onManage={remote ? undefined : openEngines} onSetUpGlm={canSetUpGlm ? setUpGlm : undefined}onResetVariant={resetVariant}/>) : fullPane}diff --git a/src/components/ModelPickerFull.tsx b/src/components/ModelPickerFull.tsxindex bcfddbef60..9e8c2adfa7 100644--- a/src/components/ModelPickerFull.tsx+++ b/src/components/ModelPickerFull.tsx@@ -4,7 +4,7 @@ import { engineDisplayName, isClaudeAccount, SIGN_IN_FAMILY_LABEL, signInFamily,import { modelOptionLabel } from "@/lib/model-label";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import { InstanceProviderMark } from "./ProviderIcons";+import { InstanceProviderMark, PresetProviderMark } from "./ProviderIcons";import { hasSavedApiKey, needsCli, needsSignIn } from "./EngineSetup";import { MENU_META, MENU_ROW } from "./menu-recipe";import { Select } from "./Select";@@ -128,13 +128,15 @@ export function railProviders(instances: InstanceInfo[], selectedInstance: Instaconst RAIL_LABEL = "pb-0.5 text-center text-[11px] leading-[14px] text-ink-tertiary";-export function ModelEngineRail({ instances, selectedInstance, claudeInstance, openaiInstance, onSelect, onAddApiKeys }: {+export function ModelEngineRail({ instances, selectedInstance, claudeInstance, openaiInstance, onSelect, onAddApiKeys, onSetUpGlm, glmSetup }: {instances: InstanceInfo[];selectedInstance?: InstanceInfo;claudeInstance?: InstanceInfo;openaiInstance?: InstanceInfo;onSelect: (instance: InstanceInfo) => void;onAddApiKeys?: () => void;+ onSetUpGlm?: () => void;+ glmSetup?: boolean;}) {const { subscription, api, custom: local } = railProviders(instances, selectedInstance, claudeInstance, openaiInstance);const railButton = ({ instance, target, selected, label }: RailProvider) => {@@ -168,8 +170,15 @@ export function ModelEngineRail({ instances, selectedInstance, claudeInstance, o<div className="flex w-14 shrink-0 flex-col gap-1 overflow-y-auto border-r-[0.5px] border-ink/10 p-2">{subscription.length > 0 && <div className={cn(RAIL_LABEL, "pt-0.5")}>{t("model.rail.cloud")}</div>}{subscription.map(railButton)}- {(api.length > 0 || onAddApiKeys) && <div className={cn(RAIL_LABEL, subscription.length > 0 ? "pt-2" : "pt-0.5")}>{t("model.rail.apiKeys")}</div>}+ {(api.length > 0 || onAddApiKeys || onSetUpGlm) && <div className={cn(RAIL_LABEL, subscription.length > 0 ? "pt-2" : "pt-0.5")}>{t("model.rail.apiKeys")}</div>}{api.map(railButton)}+ {onSetUpGlm && (+ <button type="button" data-model-glm-setup onClick={onSetUpGlm} aria-pressed={glmSetup}+ aria-label={t("apiInstances.glmSetup")} title={t("apiInstances.glmSetup")}+ className={cn("flex size-9 shrink-0 items-center justify-center rounded-[8px] text-ink", glmSetup ? "bg-ink/[0.08]" : "hover:bg-ink/[0.06]")}>+ <PresetProviderMark preset="zai" size={18} />+ </button>+ )}{onAddApiKeys && (<buttontype="button"diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsxindex fcc203afa9..c3ae29f681 100644--- a/src/components/OpenAiCompatServers.tsx+++ b/src/components/OpenAiCompatServers.tsx@@ -4,6 +4,7 @@ import { api, useStore, type InstanceInfo } from "@/state/store";import { t } from "@/lib/i18n";import { keySaved } from "@/lib/product-events";import { addedServers } from "@/lib/openai-compat-endpoints";+import { GLM_ENDPOINTS } from "../../shared/glm-provider";import { cn } from "@/lib/cn";import { KEY_FIELD } from "./keys/KeyRow";import { Select } from "./Select";@@ -277,7 +278,7 @@ function useAddServer() {const { dispatch, refreshInstances } = useStore();const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);- const add = (body: { displayName: string; url: string; key: string; catalog?: string }): Promise<boolean> => {+ const add = (body: { displayName: string; url: string; key: string; catalog?: string }, onAdded?: (id: string) => void): Promise<boolean> => {setBusy(true);setError(null);return api("/api/instances/openai-compat", { method: "POST", body: JSON.stringify(body) }).then(@@ -285,6 +286,7 @@ function useAddServer() {keySaved("custom_endpoint", "settings", "unverified");if (Array.isArray(created.instances)) dispatch({ type: "instances", instances: created.instances as InstanceInfo[] });else await refreshInstances({ reportErrors: true });+ if (typeof created.instanceId === "string") onAdded?.(created.instanceId);return true;},(cause: unknown) => {@@ -378,6 +380,36 @@ export function hasGeminiServer(instances: readonly InstanceInfo[]): boolean {});}+export const GLM_SETUP_ID = "glm-setup";++export function GlmServer({ onAdded }: { onAdded: (id: string) => void }) {+ const [region, setRegion] = useState<keyof typeof GLM_ENDPOINTS>("international");+ const [key, setKey] = useState("");+ const { busy, error, add } = useAddServer();+ const endpoint = GLM_ENDPOINTS[region];++ return <form data-glm-server="" className="flex flex-col gap-2 px-3.5 py-3" onSubmit={(event) => {+ event.preventDefault();+ if (busy || !key.trim()) return;+ void add({ displayName: endpoint.name, url: endpoint.url, key: key.trim() }, onAdded).then((added) => { if (added) setKey(""); });+ }}>+ <h2 className="text-[14px] font-semibold text-ink">{t("apiInstances.glmSetup")}</h2>+ <label className="flex flex-col gap-1 text-[13px] text-ink-secondary">+ {t("apiInstances.glmRegion")}+ <Select value={region} onChange={(event) => setRegion(event.target.value === "china" ? "china" : "international")} disabled={busy}>+ <option value="international">{t("apiInstances.glmInternational")}</option>+ <option value="china">{t("apiInstances.glmChina")}</option>+ </Select>+ </label>+ <label className="flex flex-col gap-1 text-[13px] text-ink-secondary">+ {t("apiInstances.key")}+ <input type="password" value={key} onChange={(event) => setKey(event.target.value)} autoComplete="off" disabled={busy} className={INPUT} />+ </label>+ <button type="submit" disabled={busy || !key.trim()} className="ui-button self-end">{t(busy ? "apiInstances.adding" : "apiInstances.add")}</button>+ {error && <p role="alert" className="text-[12px] text-danger">{error}</p>}+ </form>;+}+/** Google AI Studio in the Providers list: a Gemini API key, added as an OpenAI-compatible server at Google's address. */export function GeminiServer() {const [key, setKey] = useState("");diff --git a/src/components/ProviderIcons.tsx b/src/components/ProviderIcons.tsxindex c12aae3433..672d4f96a9 100644--- a/src/components/ProviderIcons.tsx+++ b/src/components/ProviderIcons.tsx@@ -240,6 +240,9 @@ export function PresetProviderMark({ preset, size = 16, className }: IconProps &case "xai": return <GrokMark size={size} className={className} />;case "qwen": return <QwenMark size={size} className={className} />;case "moonshot": return <KimiMark size={size} className={className} />;+ case "zai":+ // Z.ai mark from Lobe Icons (MIT).+ return <svg width={size} height={size} viewBox="0 0 24 24" className={className} aria-hidden="true"><path fill="var(--color-ink)" d="M12.105 2L9.927 4.953H.653L2.83 2h9.276zM23.254 19.048L21.078 22h-9.242l2.174-2.952h9.244zM24 2L9.264 22H0L14.736 2H24z" /></svg>;case "google":return <svg width={size} height={size} viewBox="0 0 24 24" className={className} aria-hidden="true"><path fill="#8E75B2" d="M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81" />diff --git a/src/components/SimpleModelMenu.tsx b/src/components/SimpleModelMenu.tsxindex 333bc8f674..f8e28a6896 100644--- a/src/components/SimpleModelMenu.tsx+++ b/src/components/SimpleModelMenu.tsx@@ -8,7 +8,7 @@ import { modelOptionLabel } from "@/lib/model-label";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { BotAvatar } from "./Avatar";-import { InstanceProviderMark } from "./ProviderIcons";+import { InstanceProviderMark, PresetProviderMark } from "./ProviderIcons";import { MENU_GUTTER, MENU_ICON, MENU_LABEL, MENU_LINE, MENU_NOTE, MENU_ROW, MENU_SEPARATOR, MENU_TRAILING, SIMPLE_MENU_META, SIMPLE_MENU_ROW } from "./menu-recipe";import { effortLabel } from "./ModelPicker";@@ -26,6 +26,7 @@ export interface SimpleMenuActions {onCheckAgain: (instance: InstanceInfo) => void;/** Opens the provider settings; left out where they live on another computer. */onManage?: () => void;+ onSetUpGlm?: () => void;onResetVariant?: () => void;}@@ -325,13 +326,13 @@ export function SimpleModelMenu(props: SimpleModelMenuProps) {</div></div>- {(props.thinking || props.onResetVariant || props.onManage) && (+ {(props.thinking || props.onResetVariant || props.onManage || props.onSetUpGlm) && (<div data-simple-effort-band className="flex shrink-0 flex-col gap-0.5 p-1.5 pt-0"><div role="separator" className={MENU_SEPARATOR} />{props.thinking && (<><Thinking thinking={props.thinking} labelId={`${idPrefix}-thinking`} />- {(props.onResetVariant || props.onManage) && <div role="separator" className={MENU_SEPARATOR} />}+ {(props.onResetVariant || props.onManage || props.onSetUpGlm) && <div role="separator" className={MENU_SEPARATOR} />}</>)}{props.onResetVariant && (@@ -340,6 +341,13 @@ export function SimpleModelMenu(props: SimpleModelMenuProps) {<span className="min-w-0 flex-1 truncate">{t("model.variant.session")}</span></button>)}+ {props.onSetUpGlm && (+ <button type="button" data-menu-row data-simple-glm-setup onClick={props.onSetUpGlm} className={MENU_ROW}>+ <Gutter><PresetProviderMark preset="zai" size={16} /></Gutter>+ <span className="min-w-0 flex-1 truncate">{t("apiInstances.glmSetup")}</span>+ <Forward />+ </button>+ )}{props.onManage && (<button type="button" data-menu-row data-simple-manage onClick={props.onManage} className={MENU_ROW}><Gutter><Settings size={16} className={MENU_ICON} aria-hidden="true" /></Gutter>diff --git a/src/components/provider-mark-fade.ts b/src/components/provider-mark-fade.tsindex 6bfc7d0a25..0672e4afc3 100644--- a/src/components/provider-mark-fade.ts+++ b/src/components/provider-mark-fade.ts@@ -3,7 +3,7 @@ import type { InstanceInfo } from "@/state/store";export type ProviderMarkTone = "brand" | "mono";const BRAND_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "mistral", "mistralVibeAgent", "meta", "museCode", "kimiAgent", "qwenAgent", "deepseekAgent", "greenference", "modelgo", "kiroAgent"]);-const MONO_PRESETS: ReadonlySet<string> = new Set(["openai", "xai", "ollama"]);+const MONO_PRESETS: ReadonlySet<string> = new Set(["openai", "xai", "ollama", "zai"]);export function providerMarkTone(instance: Pick<InstanceInfo, "driverKind" | "icon">): ProviderMarkTone {if (instance.icon?.kind === "custom") return "brand";diff --git a/src/lib/engine-rail.ts b/src/lib/engine-rail.tsindex f22381b78f..276ac5fa52 100644--- a/src/lib/engine-rail.ts+++ b/src/lib/engine-rail.ts@@ -1,13 +1,19 @@import type { InstanceInfo } from "@/state/store";import { otherSignInOfSameSubscription } from "../../shared/limit-backup";+import { isGlmOrigin } from "../../shared/glm-provider";import { t } from "@/lib/i18n";export { engineDisplayName } from "@/lib/engine-name";+export function isGlmInstance(instance?: InstanceInfo): boolean {+ return instance?.driverKind === "openai-compat" && isGlmOrigin(instance.url ?? "");+}+export function configuredModelInstances(instances: readonly InstanceInfo[], selectedInstanceId?: string): InstanceInfo[] {return instances.filter((instance) =>instance.instanceId === selectedInstanceId- || (instance.snapshot.state === "available" && (instance.models.options.length > 0 || instance.snapshot.chatgptPlan === true)));+ || (instance.snapshot.state === "available" && (instance.models.options.length > 0 || instance.snapshot.chatgptPlan === true+ || (isGlmInstance(instance) && instance.snapshot.authenticated === true))));}export function isCustomOnly(instance: { access?: InstanceInfo["access"] } | undefined): boolean {diff --git a/src/locales/en.json b/src/locales/en.jsonindex cf38252006..540f062df9 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7701,6 +7701,11 @@"apiInstances.models": "Model IDs, separated by commas (optional)","apiInstances.modelsHint": "Leave the model IDs empty to detect them. If the model picker then shows only sample models, this server does not list its models: enter them here.","apiInstances.geminiPreset": "Fill in Google Gemini",+ "apiInstances.glmSetup": "Set up GLM",+ "apiInstances.glmRegion": "API key region",+ "apiInstances.glmInternational": "Z.ai (international)",+ "apiInstances.glmChina": "Zhipu BigModel (mainland China)",+ "apiInstances.glmNoModels": "No models found. Check your API key or enter a model ID in API keys.","apiInstances.geminiKeyHint": "Paste a Gemini API key from Google AI Studio (aistudio.google.com/apikey). Models are detected after you add it.","apiInstances.add": "Add server","apiInstances.adding": "Adding…",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 0dd3959498..bd4f773599 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7312,6 +7312,11 @@"apiInstances.models": "IDs de modelos, separados por vírgulas (opcional)","apiInstances.modelsHint": "Deixe os IDs em branco para detectar os modelos automaticamente. Se o seletor mostrar só modelos de exemplo, este servidor não lista os modelos disponíveis. Nesse caso, digite os IDs aqui.","apiInstances.geminiPreset": "Preencher com Google Gemini",+ "apiInstances.glmSetup": "Configurar GLM",+ "apiInstances.glmRegion": "Região da chave de API",+ "apiInstances.glmInternational": "Z.ai (internacional)",+ "apiInstances.glmChina": "Zhipu BigModel (China continental)",+ "apiInstances.glmNoModels": "Nenhum modelo encontrado. Confira a chave de API ou informe um ID de modelo nas chaves de API.","apiInstances.geminiKeyHint": "Cole uma chave de API do Gemini gerada no Google AI Studio (aistudio.google.com/apikey). O app detecta os modelos depois que você adiciona a chave.","apiInstances.add": "Adicionar servidor","apiInstances.adding": "Adicionando…",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 2e355b71dd..8f0d74af3c 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -7636,6 +7636,11 @@"apiInstances.models": "模型 ID,用逗号分隔(可选)","apiInstances.modelsHint": "留空即可自动检测模型。如果模型选择器只显示示例模型,说明该服务器不提供模型列表,请在这里填写。","apiInstances.geminiPreset": "填写 Google Gemini",+ "apiInstances.glmSetup": "设置 GLM",+ "apiInstances.glmRegion": "API 密钥地区",+ "apiInstances.glmInternational": "Z.ai(国际)",+ "apiInstances.glmChina": "智谱 BigModel(中国大陆)",+ "apiInstances.glmNoModels": "未找到模型。请检查 API 密钥,或在 API 密钥设置中输入模型 ID。","apiInstances.geminiKeyHint": "请粘贴来自 Google AI Studio 的 Gemini API 密钥(aistudio.google.com/apikey)。添加后会自动检测模型。","apiInstances.add": "添加服务器","apiInstances.adding": "正在添加…",