diff --git a/package.json b/package.json index 7bfb72dd..ff5c7ce3 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "thinkwatch-lite", "private": true, "description": "Desktop app for a local AI API gateway on macOS, Windows and Linux", - "version": "2026.11.24", + "version": "2026.11.25", "type": "module", "packageManager": "pnpm@11.13.1", "scripts": { diff --git a/release-notes/2026.11.25.md b/release-notes/2026.11.25.md new file mode 100644 index 00000000..1f2ecbc9 --- /dev/null +++ b/release-notes/2026.11.25.md @@ -0,0 +1,2 @@ +- From an upstream model's menu, choose **Add alias…** to create an alias or add the model to an existing one. The model is appended to the list. Preview which model each upstream will receive before saving. +- When configuring a route with **Specific upstream models**, select an upstream and search by alias to find its model ID. Selecting a result pins that ID. You can also enter an ID manually. To have the route follow future alias changes, choose **Upstream or group** and enter the alias under **Change model to**. diff --git a/scripts/ui/model-aliases.pw.ts b/scripts/ui/model-aliases.pw.ts new file mode 100644 index 00000000..69f3c8f5 --- /dev/null +++ b/scripts/ui/model-aliases.pw.ts @@ -0,0 +1,133 @@ +import { expect, test, type Page } from "@playwright/test"; +import type { AliasPreviewRequest, AliasView, RouteSave } from "@/types"; +import type {} from "../shots/drive"; + +async function open(page: Page, scene: "upstreams" | "routing") { + await page.goto(`/scripts/shots/index.html?scene=${scene}&lang=zh`); + await page.waitForFunction(() => window.__shot?.state === "ready"); + await page.evaluate(() => { + const ctx = window as unknown as { + __TAURI_INTERNALS__: { invoke(cmd: string, args?: Record): Promise }; + aliasWrites: unknown[]; + savedRoute?: RouteSave; + }; + ctx.aliasWrites = []; + const invoke = ctx.__TAURI_INTERNALS__.invoke; + const alias: AliasView = { + name: "coding", hide_originals: true, requests_24h: 0, cost_micros_24h: null, shadows: [], + models: [{ model: "claude-opus-5", providers: ["anthropic"] }, { model: "claude-sonnet-5", providers: ["relay"] }], + served_by: [{ provider: "anthropic", model: "claude-opus-5" }, { provider: "relay", model: "claude-sonnet-5" }], + }; + ctx.__TAURI_INTERNALS__.invoke = async (cmd, args) => { + if (cmd === "alias_hints") return []; + if (cmd === "call" && args) { + switch (args.endpoint) { + case "Aliases": + return { aliases: [alias], hide_originals_supported: true, suggestions: [] }; + case "PreviewAlias": { + const draft = args.req as AliasPreviewRequest; + const targets = [...alias.served_by]; + if (draft.original === alias.name && draft.alias.models.includes("deepseek-chat")) { + targets.push({ provider: "deepseek", model: "deepseek-chat" }); + } + return { served_by: targets, problems: [], shadows: [], unserved: [], same_model: [], hidden_originals: [] }; + } + case "CreateAlias": + case "UpdateAlias": + ctx.aliasWrites.push(args); + return { version: "v2", renamed_in: { keys: [], rules: [], requests_24h: 0 } }; + case "UpdateRoute": + ctx.savedRoute = args.req as RouteSave; + return { version: "v2" }; + } + } + return invoke(cmd, args); + }; + }); +} + +async function startAlias(page: Page) { + await page.getByRole("button", { name: "deepseek 的模型", exact: true }).click(); + await page.getByRole("button", { name: "deepseek-chat 的操作", exact: true }).click(); + await page.getByRole("menuitem", { name: "设置别名…" }).click(); +} + +test("an upstream model joins an existing alias only after preview and save", async ({ page }) => { + await open(page, "upstreams"); + for (const action of ["取消", "保存"]) { + await startAlias(page); + await page.getByRole("combobox", { name: "添加到现有别名…" }).click(); + await page.getByRole("option", { name: "coding", exact: true }).click(); + const editor = page.getByRole("dialog", { name: "编辑别名 coding" }); + await expect(editor.getByRole("checkbox", { name: "客户端仅展示别名" })).toBeChecked(); + const preview = editor.getByText("客户端请求 coding 时", { exact: true }).locator(".."); + await expect(preview.getByText("deepseek-chat", { exact: true })).toBeVisible(); + await expect(editor.getByRole("button", { name: "保存" })).toBeEnabled(); + expect(await page.evaluate(() => (window as unknown as { aliasWrites: unknown[] }).aliasWrites)).toEqual([]); + await editor.getByRole("button", { name: action, exact: true }).click(); + await expect(editor).toBeHidden(); + } + expect(await page.evaluate(() => (window as unknown as { aliasWrites: unknown[] }).aliasWrites)).toEqual([{ + endpoint: "UpdateAlias", params: ["coding"], req: { base_version: expect.any(String), + alias: { name: "coding", models: ["claude-opus-5", "claude-sonnet-5", "deepseek-chat"], hide_originals: true } }, + }]); +}); + +test("the upstream editor can create another alias for an already included ID", async ({ page }) => { + await open(page, "upstreams"); + await page.getByRole("row", { name: /^选择 anthropic / }).click(); + const upstream = page.getByRole("dialog", { name: "编辑上游" }); + await upstream.getByRole("button", { name: "模型", exact: true }).click(); + await upstream.getByRole("button", { name: "claude-opus-5 的操作", exact: true }).click(); + await page.getByRole("menuitem", { name: "设置别名…" }).click(); + const dialog = page.getByRole("dialog", { name: "新建别名" }); + await dialog.getByRole("combobox", { name: "添加到现有别名…" }).click(); + await expect(page.getByRole("option", { name: "coding(已包含)" })).toBeDisabled(); + await page.keyboard.press("Escape"); + await dialog.getByLabel("名称", { exact: true }).fill("new-name"); + await dialog.getByRole("button", { name: "创建", exact: true }).click(); + await expect(dialog).toBeHidden(); + await expect(upstream).toBeVisible(); + expect(await page.evaluate(() => (window as unknown as { aliasWrites: unknown[] }).aliasWrites)).toMatchObject([{ + endpoint: "CreateAlias", req: { alias: { name: "new-name", models: ["claude-opus-5"] } }, + }]); +}); + +test("pinned alias searches keep only the chosen upstream ID and permit literal unlisted IDs", async ({ page }) => { + await open(page, "routing"); + await page.getByRole("row", { name: /^default / }).click(); + const route = page.getByRole("dialog", { name: "编辑路由「default」" }); + await route.getByRole("button", { name: "添加规则" }).click(); + const rule = page.getByRole("dialog", { name: "添加规则" }); + await rule.getByLabel("名称", { exact: true }).fill("pin"); + await rule.getByRole("radio", { name: "指定上游模型" }).click(); + + for (const [n, provider, model] of [[1, "anthropic", "claude-opus-5"], [2, "relay", "claude-sonnet-5"]] as const) { + if (n === 2) await rule.getByRole("button", { name: "添加备用" }).click(); + await rule.getByRole("combobox", { name: `第 ${n} 个指定模型的上游` }).click(); + await page.getByRole("option", { name: provider, exact: true }).click(); + const raw = rule.getByRole("textbox", { name: "上游模型 ID" }).nth(n - 1); + await raw.fill("manual-id"); + await raw.press("ArrowDown"); + const search = rule.getByPlaceholder("搜索模型 ID 或别名"); + await search.fill("CoDiNg"); + await expect(page.getByRole("option")).toHaveCount(1); + await expect(page.getByRole("option")).toContainText(model); + await search.press("Escape"); + await expect(raw).toHaveValue("manual-id"); + await raw.press("ArrowDown"); + await search.fill("coding"); + await page.getByRole("option", { name: new RegExp(model) }).click(); + await expect(raw).toHaveValue(model); + } + await rule.getByRole("button", { name: "添加备用" }).click(); + await rule.getByRole("combobox", { name: "第 3 个指定模型的上游" }).click(); + await page.getByRole("option", { name: "deepseek", exact: true }).click(); + await rule.getByRole("textbox", { name: "上游模型 ID" }).nth(2).fill("manual-only"); + await rule.getByRole("button", { name: "添加", exact: true }).click(); + await route.getByRole("button", { name: "保存", exact: true }).click(); + await expect.poll(() => page.evaluate(() => (window as unknown as { savedRoute?: RouteSave }).savedRoute?.route.rules.find((r) => r.name === "pin")?.to)).toEqual([ + { provider: "anthropic", model: "claude-opus-5" }, { provider: "relay", model: "claude-sonnet-5" }, + { provider: "deepseek", model: "manual-only" }, + ]); +}); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index cbd916c6..15dbf62f 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4950,7 +4950,7 @@ dependencies = [ [[package]] name = "thinkwatch-lite" -version = "2026.11.24" +version = "2026.11.25" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 67560c66..4fc33ec1 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "thinkwatch-lite" -version = "2026.11.24" +version = "2026.11.25" edition = "2024" # **这个数决定依赖能升到哪一版。**edition 2024 的解析器只挑声明的 Rust # 版本编得动的依赖:写 1.85 的时候,`cargo update` 一直停在旧的 time 和 diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 25fdb75b..d4ab81e2 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "ThinkWatch Lite", - "version": "2026.11.24", + "version": "2026.11.25", "identifier": "app.thinkwatch.lite", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/aliases/AliasDialog.i18n.ts b/src/aliases/AliasDialog.i18n.ts index a5d50618..3c9bd619 100644 --- a/src/aliases/AliasDialog.i18n.ts +++ b/src/aliases/AliasDialog.i18n.ts @@ -10,12 +10,15 @@ export const aliasDialogText = messages( name: "名称", nameHint: "客户端用这个名称请求。", + joinExisting: "添加到现有别名…", + alreadyIncludes: (name: string) => `${name}(已包含)`, + editExistingAliasHint: "要添加更多上游模型,请在「上游 → 别名」里编辑已有别名。", namePlaceholder: "例如 claude-sonnet-5", /** 名称恰好是某个上游的模型名,自动列成了第一个上游模型 */ prefilled: (providers: string, name: string) => `${providers} 也有名为 ${name} 的模型,已列为第一个上游模型。`, /** 名称恰好是没列进来的那些上游的真模型:别名优先,它们不再收到这个名称 */ shadows: (providers: string, name: string, models: string, creating: boolean) => - `${providers} 有名为 ${name} 的模型。${creating ? "建这个别名后" : "保存后"},所有客户端用 ${name} 请求都会改发给 ${models},不再发给 ${providers}。只想让某个客户端这样用,请在路由里给它的密钥写一条规则,转发至选「指定模型」。`, + `${providers} 有名为 ${name} 的模型。${creating ? "建这个别名后" : "保存后"},所有客户端用 ${name} 请求都会改发给 ${models},不再发给 ${providers}。只想让某个客户端这样用,请在路由里给它的密钥写一条规则,转发至选「指定上游模型」。`, writeRule: "改为写路由规则…", claudeCodeReserved: (name: string) => `Claude Code 把 ${name} 当作自己的档位名,请求前换成完整的模型名,它的请求用不到这个别名。`, @@ -78,11 +81,14 @@ export const aliasDialogText = messages( name: "Name", nameHint: "Clients request this name.", + joinExisting: "Add to existing alias…", + alreadyIncludes: (name: string) => `${name} (already included)`, + editExistingAliasHint: "To add more upstream models, edit the existing alias under Upstreams → Aliases.", namePlaceholder: "e.g. claude-sonnet-5", prefilled: (providers: string, name: string) => `${providers} also has a model named ${name}; it is listed as the first upstream model.`, shadows: (providers: string, name: string, models: string, creating: boolean) => - `${providers} has a model named ${name}. ${creating ? "Once this alias exists" : "Once saved"}, every client requesting ${name} goes to ${models} instead, and ${providers} no longer receives it. To do this for one client only, write a rule for its key in Routing and forward to “Specific models”.`, + `${providers} has a model named ${name}. ${creating ? "Once this alias exists" : "Once saved"}, every client requesting ${name} goes to ${models} instead, and ${providers} no longer receives it. To do this for one client only, write a rule for its key in Routing and forward to “Specific upstream models”.`, writeRule: "Write a routing rule instead…", claudeCodeReserved: (name: string) => `Claude Code treats ${name} as its own tier name and swaps in the full model name before requesting, so its requests never use this alias.`, @@ -147,8 +153,11 @@ export const aliasDialogText = messages( notFound: (name: string) => `別名 ${name} 已不在配置裡。`, name: "名稱", nameHint: "用戶端用這個名稱請求。", + joinExisting: "新增至現有別名…", + alreadyIncludes: (name: string) => `${name}(已包含)`, + editExistingAliasHint: "若要新增更多上游模型,請在「上游 → 別名」中編輯現有別名。", prefilled: (providers: string, name: string) => `${providers} 也有名為 ${name} 的模型,已列為第一個上游模型。`, - shadows: (providers: string, name: string, models: string, creating: boolean) => `${providers} 有名為 ${name} 的模型。${creating ? "建這個別名後" : "儲存後"},所有用戶端用 ${name} 請求都會改發給 ${models},不再發給 ${providers}。只想讓某個用戶端這樣用,請在路由裡給它的金鑰寫一條規則,轉發至選「指定模型」。`, + shadows: (providers: string, name: string, models: string, creating: boolean) => `${providers} 有名為 ${name} 的模型。${creating ? "建這個別名後" : "儲存後"},所有用戶端用 ${name} 請求都會改發給 ${models},不再發給 ${providers}。只想讓某個用戶端這樣用,請在路由裡給它的金鑰寫一條規則,轉發至選「指定上游模型」。`, writeRule: "改為寫路由規則…", claudeCodeReserved: (name: string) => `Claude Code 把 ${name} 當作自己的檔位名,請求前換成完整的模型名,它的請求用不到這個別名。`, familyMismatch: (family: string, model: string, clients: string) => `名稱像 ${family} 模型,上游模型卻是 ${model}:${clients} 會按 ${family} 模型的格式發出這個名稱的請求,由閘道器轉換後發給上游。`, @@ -187,8 +196,15 @@ export const aliasDialogText = messages( renamed: (old: string, name: string) => `已將別名 ${old} 改名為 ${name}`, renamedIn: (refs: string) => `${refs}裡的名稱已一起更新。`, }, + ja: { + joinExisting: "既存のエイリアスに追加…", + alreadyIncludes: (name: string) => `${name}(追加済み)`, + }, ko: { name: "이름", + joinExisting: "기존 별칭에 추가…", + alreadyIncludes: (name: string) => `${name} (이미 포함됨)`, + editExistingAliasHint: "업스트림 모델을 더 추가하려면 업스트림 → Aliases에서 기존 별칭을 편집하세요.", removeShort: "제거", needName: "이름을 입력하세요.", }, @@ -200,9 +216,12 @@ export const aliasDialogText = messages( notFound: (name: string) => `Alias ${name} ya no está en la configuración.`, name: "Nombre", nameHint: "Los clientes solicitan este nombre.", + joinExisting: "Añadir a un alias existente…", + alreadyIncludes: (name: string) => `${name} (ya incluido)`, + editExistingAliasHint: "Para añadir más modelos de proveedores, edita el alias actual en Proveedores → Alias.", namePlaceholder: "Por ejemplo, claude-sonnet-5", prefilled: (providers: string, name: string) => `${providers} también tiene un modelo denominado ${name}; está listado como el primer modelo de del proveedor.`, - shadows: (providers: string, name: string, models: string, creating: boolean) => `${providers} tiene un modelo llamado ${name}. ${creating ? "Una vez que este alias existe" : "Una vez guardado"}, cada cliente que solicita ${name} va a ${models} en su lugar, y ${providers} ya no lo recibe. Para hacer esto sólo para un cliente, escriba una regla para su clave en Enrutamiento y reenvíe a "modelos específicos".`, + shadows: (providers: string, name: string, models: string, creating: boolean) => `${providers} tiene un modelo llamado ${name}. ${creating ? "Una vez que este alias existe" : "Una vez guardado"}, cada cliente que solicita ${name} va a ${models} en su lugar, y ${providers} ya no lo recibe. Para hacer esto sólo para un cliente, escriba una regla para su clave en Enrutamiento y reenvíe a «Modelos específicos del proveedor».`, writeRule: "Escribe una regla de enrutamiento en su lugar…", claudeCodeReserved: (name: string) => `Claude Code trata ${name} como su propio nombre de nivel y swaps en el nombre completo del modelo antes de solicitar, por lo que sus solicitudes nunca utilizan este alias.`, familyMismatch: (family: string, model: string, clients: string) => `El nombre se parece a un modelo ${family}, pero el modelo ascendente es ${model}: ${clients} enviará solicitudes para él en el formato ${family}, y la puerta de enlace las convierte para el ascendente.`, diff --git a/src/aliases/AliasDialog.tsx b/src/aliases/AliasDialog.tsx index 366f83d1..55ad2d38 100644 --- a/src/aliases/AliasDialog.tsx +++ b/src/aliases/AliasDialog.tsx @@ -7,6 +7,7 @@ import { latestOnly } from "@/lib/latestOnly"; import { cn } from "@/lib/utils"; import { useNav } from "@/nav"; import { Button } from "@/ui/button"; +import { SelectField, SelectOption } from "@/ui/select-field"; import { Checkbox } from "@/ui/checkbox"; import { Autocomplete, ComboboxBareInput, ComboboxContent, ComboboxItem, ComboboxList } from "@/ui/combobox"; import { @@ -24,7 +25,7 @@ import { Skeleton } from "@/ui/skeleton"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { coreText, errorText } from "@/i18n/core.i18n"; -import type { AliasHint, AliasInput, AliasPreview, AliasSave, AliasUsage, KnownModel, PinnedModel } from "@/types"; +import type { AliasesView, AliasHint, AliasInput, AliasPreview, AliasSave, AliasUsage, KnownModel, PinnedModel } from "@/types"; import { Boxed, DialogError, FormItem } from "@/upstreams/parts"; import { aliasDialogText } from "./AliasDialog.i18n"; import { api } from "./api"; @@ -37,6 +38,14 @@ const PREVIEW_DELAY_MS = 250; /** 建议列表最多列几条 */ const MAX_SUGGESTIONS = 50; +type AliasFormProps = { + editing?: string; + initial?: Partial; + sourceModel?: string; + onSaved?(version: string): void; + onClose(): void; +}; + /** * 新建、编辑一个模型别名。 * @@ -50,18 +59,12 @@ const MAX_SUGGESTIONS = 50; * * 红字是 core 说的问题,不能保存;黄字是要留意的,可以保存。 * - * 挂载方:别名标签(新建、编辑),上游模型弹窗和编辑上游对话框的「模型」一节(「起别名…」, - * `initial.models` 是那个模型)。 + * 挂载方:别名标签(新建、编辑),上游模型弹窗和编辑上游对话框的「模型」一节(「设置别名…」, + * `sourceModel` 是当前选中的上游模型 ID)。 */ -export function AliasDialog(props: { +export function AliasDialog(props: Omit & { open: boolean; onOpenChange(open: boolean): void; - /** 编辑哪个别名(原名)。不给就是新建 */ - editing?: string; - /** 新建时预填。编辑时不用给:模型按原名从 core 读 */ - initial?: Partial; - /** 写完了。`version`:写完之后的配置版本(编辑上游对话框里打开的,那边接着用它) */ - onSaved?(version: string): void; }) { const { open, onOpenChange, editing } = props; return ( @@ -78,23 +81,30 @@ export function AliasDialog(props: { }} > {/* 内容只在开着时挂上:每次打开都从头填 */} - onOpenChange(false)} /> + onOpenChange(false)} /> ); } +type JoinAlias = { name: string; models: string[] }; + +function AliasForm(props: AliasFormProps) { + const [join, setJoin] = useState(); + return ( + + ); +} + function Body({ - editing, - initial, - onSaved, - onClose, -}: { - editing?: string; - initial?: Partial; - onSaved?(version: string): void; - onClose: () => void; -}) { + editing, initial, sourceModel, modelsToAdd, onSaved, onClose, onJoin, +}: AliasFormProps & { modelsToAdd?: string[]; onJoin(join: JoinAlias): void }) { const t = useText(aliasDialogText); const c = useText(commonText); const nav = useNav(); @@ -112,10 +122,11 @@ function Body({ }, [catalog]); const [draft, setDraft] = useState(() => - draftOf(initial?.name ?? editing ?? "", initial?.models ?? [], initial?.hide_originals ?? false), + draftOf(initial?.name ?? editing ?? "", initial?.models ?? (sourceModel ? [sourceModel] : []), initial?.hide_originals ?? false), ); const { name, models, auto, hideOriginals } = draft; - const [discoverySupport, setDiscoverySupport] = useState(null); + const [aliasView, setAliasView] = useState(null); + const discoverySupport = aliasView && aliasView.hide_originals_supported === true; const input = aliasInput(draft, discoverySupport === true); /** 编辑时从 core 读到的模型和各自的上游。读到之前是 `null` */ const [loaded, setLoaded] = useState | null>(() => @@ -131,39 +142,36 @@ function Body({ const [saving, setSaving] = useState(false); const [error, setError] = useState(null); - useEffect(() => { - api - .configVersion() - .then(setBase) - .catch(() => {}); - }, []); - - // 编辑:按原名读出列着的模型 useEffect(() => { let live = true; - api - .aliases() - .then((v) => { - if (!live) return; - setDiscoverySupport(v.hide_originals_supported === true); - if (editing == null) return; - const a = v.aliases.find((x) => x.name === editing); - if (!a) { - setLoadError(t.notFound(editing)); - return; - } - setDraft((d) => ({ - ...d, - models: initial?.models ?? a.models.map((m) => m.model), - hideOriginals: a.hide_originals ?? false, - })); - setLoaded(new Map(a.models.map((m) => [m.model, m.providers]))); - }) - .catch((e) => live && setLoadError(errorText(e))); + async function load() { + // Read the version before the alias definition so a concurrent edit cannot be overwritten. + const version = await api.configVersion().catch((e) => { + if (modelsToAdd) throw e; + return undefined; + }); + const v = await api.aliases(); + if (!live) return; + setBase(version); + setAliasView(v); + if (editing == null) return; + const a = v.aliases.find((x) => x.name === editing); + if (!a) { + setLoadError(t.notFound(editing)); + return; + } + const existingModels = a.models.map((m) => m.model); + setDraft((d) => { + const existing = { ...d, models: initial?.models ?? existingModels, hideOriginals: a.hide_originals ?? false }; + return modelsToAdd ? modelsToAdd.reduce(withModel, existing) : existing; + }); + setLoaded(new Map(a.models.map((m) => [m.model, m.providers]))); + } + void load().catch((e) => live && setLoadError(errorText(e))); return () => { live = false; }; - }, [editing, initial?.models]); + }, [editing, initial?.models, modelsToAdd]); const trimmed = name.trim(); const renaming = editing != null && trimmed !== "" && trimmed !== editing; @@ -226,8 +234,8 @@ function Body({ const add = (m: string) => setDraft((d) => withModel(d, m)); const remove = (m: string) => setDraft((d) => withoutModel(d, m)); - const p = preview?.p ?? null; const fresh = preview?.key === draftKey; + const p = modelsToAdd && !fresh ? null : preview?.p ?? null; const problems = shownProblems(p?.problems ?? [], draft); const onlyItself = onlyAuto(draft) && fresh && (p?.problems ?? []).some((m) => m.code === ONLY_ITSELF); const shadows = trimmed && p ? p.shadows : []; @@ -248,7 +256,9 @@ function Body({ : onlyItself ? t.needOtherName : null; - const blocked = missing !== null || loadError !== null || (hideOriginals && discoverySupport !== true) || (fresh && problems.length > 0); + const blocked = + missing !== null || loadError !== null || (hideOriginals && discoverySupport !== true) || + (fresh && problems.length > 0) || (modelsToAdd !== undefined && (!base || !fresh)); /** 建这个别名之后,名称改发给哪些模型(各上游实际收到的,没有就是列出的) */ const sentModels = unique((p?.served_by ?? []).map((s) => s.model)); @@ -290,23 +300,39 @@ function Body({
- 0 || undefined} - onChange={(e) => changeName(e.target.value)} - /> +
+ 0 || undefined} + onChange={(e) => changeName(e.target.value)} + /> + {sourceModel && creating && !!aliasView?.aliases.length && ( + onJoin({ name, models })} className="shrink-0"> + {t.joinExisting} + {aliasView.aliases.map((a) => { + const included = models.every((id) => a.models.some((m) => m.model === id)); + return ( + + {included ? t.alreadyIncludes(a.name) : a.name} + + ); + })} + + )} +
{(problems.length > 0 || shadows.length > 0 || hints.length > 0 || auto || renameRefs) && (
{problems.map((m) => ( {coreText(m)} + {creating && !sourceModel && fresh && m.code === "config.alias_duplicate" && ` ${t.editExistingAliasHint}`} ))} {auto && models.includes(auto) && ( diff --git a/src/aliases/AliasesTab.tsx b/src/aliases/AliasesTab.tsx index 8e2e3a6d..ccecb8a2 100644 --- a/src/aliases/AliasesTab.tsx +++ b/src/aliases/AliasesTab.tsx @@ -27,7 +27,7 @@ type Providers = Pick[]; * 上游页的「别名」标签:别名表、顶上的建议、尚无别名时直接列出建议。 * * 新建与编辑的对话框不在这里,交给上游页(`onCreate` / `onEdit`):上游模型弹窗里的 - * 「起别名…」打开的是同一个。同一模型不同名称的对话框和删除对话框在这里。 + * 「设置别名…」打开的是同一个。同一模型不同名称的对话框和删除对话框在这里。 */ export function AliasesTab({ providers, diff --git a/src/aliases/draft.test.ts b/src/aliases/draft.test.ts index cc793652..7ce00973 100644 --- a/src/aliases/draft.test.ts +++ b/src/aliases/draft.test.ts @@ -40,7 +40,7 @@ describe("别名草稿:名称是上游的真模型时自动列为第一个上 expect(d.models).toEqual(["claude-opus-5", "anthropic/claude-opus-5"]); }); - it("列表里已经有模型(从上游模型弹窗起别名)、编辑时、名称不是真模型:不自动列", () => { + it("列表里已经有模型(从上游模型弹窗设置别名)、编辑时、名称不是真模型:不自动列", () => { expect(withName(draftOf("", ["deepseek-chat"]), "claude-opus-5", offered, true).models).toEqual(["deepseek-chat"]); expect(withName(draftOf("x", []), "claude-opus-5", offered, false).models).toEqual([]); expect(withName(draftOf("", []), "my-model", offered, true).models).toEqual([]); diff --git a/src/routing/PinnedModels.i18n.ts b/src/routing/PinnedModels.i18n.ts index a26bfcc8..637de7b2 100644 --- a/src/routing/PinnedModels.i18n.ts +++ b/src/routing/PinnedModels.i18n.ts @@ -9,7 +9,10 @@ export const pinnedModelsText = messages( chooseProvider: "选择上游", missing: (name: string) => `${name}(不存在)`, disabled: (name: string) => `${name}(已停用)`, - model: "模型名", + model: "上游模型 ID", + search: "搜索模型 ID 或别名", + noMatch: "无匹配模型", + aliases: (names: string[]) => `别名 · ${names.join("、")}`, remove: (n: number) => `删除第 ${n} 个指定模型`, }, { @@ -20,7 +23,10 @@ export const pinnedModelsText = messages( chooseProvider: "Select an upstream", missing: (name: string) => `${name} (not found)`, disabled: (name: string) => `${name} (disabled)`, - model: "Model name", + model: "Upstream model ID", + search: "Search model IDs or aliases", + noMatch: "No matching models", + aliases: (names: string[]) => `Aliases · ${names.join(", ")}`, remove: (n: number) => `Remove specified model ${n}`, }, { @@ -30,8 +36,23 @@ export const pinnedModelsText = messages( note: "按順序傳送,前一個失敗換下一個。模型名原樣發出,不經過別名表。", provider: (n: number) => `第 ${n} 個指定模型的上游`, chooseProvider: "選擇上游", + model: "上游模型 ID", + search: "搜尋模型 ID 或別名", + noMatch: "沒有相符的模型", + aliases: (names: string[]) => `別名 · ${names.join("、")}`, remove: (n: number) => `刪除第 ${n} 個指定模型`, }, + ja: { + search: "モデル ID またはエイリアスで検索", + noMatch: "一致するモデルがありません", + aliases: (names: string[]) => `エイリアス · ${names.join("、")}`, + }, + ko: { + model: "업스트림 모델 ID", + search: "모델 ID 또는 별칭 검색", + noMatch: "일치하는 모델 없음", + aliases: (names: string[]) => `별칭 · ${names.join(", ")}`, + }, es: { addModel: "Añadir modelo", addBackup: "Añadir copia de seguridad", @@ -40,7 +61,10 @@ export const pinnedModelsText = messages( chooseProvider: "Seleccione un cursor", missing: (name: string) => `${name} (no encontrado)`, disabled: (name: string) => `${name} (inhabilitado)`, - model: "Nombre del modelo", + model: "ID del modelo del proveedor", + search: "Buscar por ID o alias", + noMatch: "Ningún modelo coincide", + aliases: (names: string[]) => `Alias · ${names.join(", ")}`, remove: (n: number) => `Eliminar el modelo especificado ${n}`, }, }, diff --git a/src/routing/PinnedModels.tsx b/src/routing/PinnedModels.tsx index 413a2661..010ae775 100644 --- a/src/routing/PinnedModels.tsx +++ b/src/routing/PinnedModels.tsx @@ -1,14 +1,18 @@ +import { useMemo, useRef } from "react"; import { PlusIcon } from "lucide-react"; import { Button } from "@/ui/button"; +import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/ui/input-group"; +import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList, ComboboxTrigger } from "@/ui/combobox"; import { SelectField, SelectOption } from "@/ui/select-field"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { useResource } from "@/lib/resource"; -import type { KnownModel, ProviderView } from "@/types"; +import type { AliasView, KnownModel, ProviderView } from "@/types"; import { compact } from "@/format"; import { modelsKey } from "@/upstreams/data"; import { api } from "./api"; -import { ModelInput } from "./fields"; +import { api as aliasApi } from "@/aliases/api"; +import { pinnedChoices } from "./pinnedChoices"; import { blankPinned, type PinnedDraft } from "./model"; import { pinnedModelsText } from "./PinnedModels.i18n"; @@ -17,7 +21,7 @@ import { pinnedModelsText } from "./PinnedModels.i18n"; * * **模型从这个上游自己的清单里选**(`/providers/{name}/models`,和上游页的模型弹窗是同一份), * 右边是它的上下文窗口;清单里没有的照样能写(中转刚上的新模型)。模型名原样发出,不经过 - * 别名表,所以候选里**不列别名**。 + * 别名表。搜索可按别名找到这家上游对应的 ID,选择后仍只保存 ID。 */ export function PinnedModels({ value, @@ -31,6 +35,9 @@ export function PinnedModels({ known: readonly KnownModel[]; }) { const t = useText(pinnedModelsText); + const aliases = useResource("aliases", aliasApi.aliases, { + events: ["config_reloaded", "models_changed"], + }).data?.aliases; const patch = (i: number, p: Partial) => onChange(value.map((x, j) => (j === i ? { ...x, ...p } : x))); return ( @@ -43,6 +50,7 @@ export function PinnedModels({ p={p} providers={providers} known={known} + aliases={aliases} onProvider={(provider) => // 换了上游:新上游也有这个模型就留着,否则清空重选 patch(i, { @@ -76,6 +84,7 @@ function PinnedRow({ p, providers, known, + aliases, onProvider, onModel, onRemove, @@ -84,6 +93,7 @@ function PinnedRow({ p: PinnedDraft; providers: readonly ProviderView[]; known: readonly KnownModel[]; + aliases: readonly AliasView[] | undefined; onProvider: (provider: string) => void; onModel: (model: string) => void; onRemove: () => void; @@ -92,16 +102,18 @@ function PinnedRow({ const ct = useText(commonText); const pv = providers.find((x) => x.name === p.provider); // 和上游页的模型弹窗共用一份缓存;那边刷新了清单,这里跟着换 - const rows = useResource( + const inventory = useResource( pv ? modelsKey(pv.name) : null, () => api.providerModels(p.provider), - { deps: [pv?.model_checked_at_ms, pv?.model_fetching, pv?.model_count] }, - ).data?.models; - // 清单还没取到时先用网关的模型目录里这家的那些 - const ids = rows - ? rows.filter((r) => r.enabled).map((r) => r.id) - : known.filter((m) => !m.alias && m.providers.includes(p.provider)).map((m) => m.id); - const ctx = rows?.find((r) => r.id === p.model.trim())?.context_window; + { + deps: [pv?.model_checked_at_ms, pv?.model_fetching, pv?.model_count], + events: ["config_reloaded", "models_changed"], + }, + ).data; + const choices = useMemo(() => pinnedChoices(p.provider, inventory, known, aliases ?? []), [p.provider, inventory, known, aliases]); + const anchor = useRef(null); + const trigger = useRef(null); + const ctx = inventory?.models.find((r) => r.id === p.model.trim())?.context_window; return (
{n} @@ -120,13 +132,55 @@ function PinnedRow({ ))} - + + key={p.provider} + items={Array.from(choices.keys())} + value={p.model || null} + onValueChange={(id) => { + if (id !== null) onModel(id); + }} + filter={(id, query) => { + const needle = query.trim().toLowerCase(); + return id.toLowerCase().includes(needle) || !!choices.get(id)?.some((name) => name.toLowerCase().includes(needle)); + }} + > + + onModel(e.target.value)} + onKeyDown={(e) => { + if (e.key === "ArrowDown") { + e.preventDefault(); + trigger.current?.click(); + } + }} + /> + + } /> + + + + + {t.noMatch} + + {(id: string) => { + const names = choices.get(id); + return ( + + {id} + {names && names.length > 0 && ( + {t.aliases(names)} + )} + + ); + }} + + + {ctx ? compact(ctx) : ""} diff --git a/src/routing/RuleDialog.i18n.ts b/src/routing/RuleDialog.i18n.ts index be30052e..d7dada0d 100644 --- a/src/routing/RuleDialog.i18n.ts +++ b/src/routing/RuleDialog.i18n.ts @@ -14,7 +14,7 @@ export const ruleDialogText = messages( forward: "转发", forwardTo: "转发至", toTarget: "上游或策略组", - toPinned: "指定模型", + toPinned: "指定上游模型", chooseTarget: "选择去向", groups: "策略组", newGroupMenu: "新建策略组…", @@ -62,7 +62,7 @@ export const ruleDialogText = messages( forward: "Forward", forwardTo: "Forward to", toTarget: "Upstream or group", - toPinned: "Specified models", + toPinned: "Specific upstream models", chooseTarget: "Select a destination", groups: "Groups", newGroupMenu: "New group…", @@ -115,6 +115,7 @@ export const ruleDialogText = messages( forward: "轉發", forwardTo: "轉發至", toTarget: "上游或策略組", + toPinned: "指定上游模型", chooseTarget: "選擇去向", groups: "策略組", newGroupMenu: "新建策略組…", @@ -143,6 +144,7 @@ export const ruleDialogText = messages( removeCondition: (name: string) => `刪除條件 ${name}`, }, ko: { + toPinned: "지정 업스트림 모델", upstreams: "업스트림", notSet: "설정되지 않음", off: "끄기", @@ -159,7 +161,7 @@ export const ruleDialogText = messages( forward: "Adelante", forwardTo: "Adelante a", toTarget: "Upstream o grupo", - toPinned: "Modelos especificados", + toPinned: "Modelos específicos del proveedor", chooseTarget: "Seleccionar un destino", groups: "Grupos", newGroupMenu: "Nuevo grupo…", diff --git a/src/routing/pinnedChoices.test.ts b/src/routing/pinnedChoices.test.ts new file mode 100644 index 00000000..739965d2 --- /dev/null +++ b/src/routing/pinnedChoices.test.ts @@ -0,0 +1,23 @@ +import { expect, it } from "vitest"; +import type { AliasView, ProviderModelsView } from "@/types"; +import { pinnedChoices } from "./pinnedChoices"; + +const coding: AliasView = { + name: "coding", models: [], shadows: [], requests_24h: 0, + served_by: [{ provider: "relay", model: "raw" }, { provider: "other", model: "other-raw" }], +}; + +it("offers the ID Core resolves on a provider without a model list, including its other aliases", () => { + const inventory: ProviderModelsView = { provider: "relay", source: "none", status: "no_list", fetching: false, models: [] }; + const options = pinnedChoices("relay", inventory, [], [coding, { ...coding, name: "daily" }]); + expect([...options]).toEqual([["raw", ["coding", "daily"]]]); +}); + +it("a refreshed provider inventory excludes disabled or removed IDs even if the alias view is older", () => { + const inventory: ProviderModelsView = { + provider: "relay", source: "discovered", status: "listed", fetching: false, + models: [{ id: "raw", enabled: false, manual: false, listed: true, estimated: false, aliases: ["coding"] }], + }; + const removed = { ...coding, name: "old", served_by: [{ provider: "relay", model: "removed" }] }; + expect([...pinnedChoices("relay", inventory, [], [coding, removed])]).toEqual([]); +}); diff --git a/src/routing/pinnedChoices.ts b/src/routing/pinnedChoices.ts new file mode 100644 index 00000000..19674f67 --- /dev/null +++ b/src/routing/pinnedChoices.ts @@ -0,0 +1,28 @@ +import type { AliasView, KnownModel, ProviderModelsView } from "@/types"; + +/** Each option value is a literal upstream ID. Core supplies the effective target for each alias. */ +export function pinnedChoices( + provider: string, + inventory: ProviderModelsView | undefined, + known: readonly KnownModel[], + aliases: readonly AliasView[], +): Map { + const choices = new Map(); + if (inventory) { + for (const row of inventory.models) if (row.enabled) choices.set(row.id, []); + } else { + for (const row of known) if (!row.alias && row.providers.includes(provider)) choices.set(row.id, []); + } + for (const alias of aliases) { + const target = alias.served_by.find((p) => p.provider === provider); + if (!target) continue; + const names = choices.get(target.model); + if (names) { + names.push(alias.name); + } else if (!inventory || inventory.source === "none") { + // Core can resolve an alias on an upstream without a published model list. + choices.set(target.model, [alias.name]); + } + } + return choices; +} diff --git a/src/upstreams/ModelsPanel.i18n.ts b/src/upstreams/ModelsPanel.i18n.ts index 141936b4..ea8a19dc 100644 --- a/src/upstreams/ModelsPanel.i18n.ts +++ b/src/upstreams/ModelsPanel.i18n.ts @@ -30,7 +30,7 @@ export const modelsPanelText = messages( context: "上下文窗口", aliasMark: (alias: string) => `别名 ${alias}`, aliasTitle: (alias: string) => `别名 ${alias} 列着这个模型:客户端用 ${alias} 请求时可以发往这个模型`, - makeAlias: "起别名…", + makeAlias: "设置别名…", specs: "规格…", setPrice: "设置价格…", unpriced: "未定价", @@ -120,7 +120,7 @@ export const modelsPanelText = messages( context: "上下文視窗", aliasMark: (alias: string) => `別名 ${alias}`, aliasTitle: (alias: string) => `別名 ${alias} 列著這個模型:用戶端用 ${alias} 請求時可以發往這個模型`, - makeAlias: "起別名…", + makeAlias: "設定別名…", specs: "規格…", setPrice: "設定價格…", unpriced: "未定價", diff --git a/src/upstreams/ModelsPanel.tsx b/src/upstreams/ModelsPanel.tsx index a8af097c..49984427 100644 --- a/src/upstreams/ModelsPanel.tsx +++ b/src/upstreams/ModelsPanel.tsx @@ -42,8 +42,7 @@ const FILTER_FROM = 10; * 窗口(不知道写「未知」);在这一家手写过规格的,名字后面标「手动规格」,悬停说是哪几项。 * * 每行行尾「…」常显,和右键是同一份菜单:「规格…」(`onSpec`,手写规格的对话框)、「设置 - * 价格…」(`onPrice`,价目表对话框)、「起别名…」(`onAlias`,新建别名的对话框,这个模型已经 - * 列为上游模型),手动添加的另有「移除」。和编辑对话框「模型」一节的菜单一样。 + * 价格…」(`onPrice`,价目表对话框)、「设置别名…」(`onAlias`,为这个模型新建别名或将其添加到现有别名),手动添加的另有「移除」。和编辑对话框「模型」一节的菜单一样。 */ export function ModelsPanel({ p, @@ -65,7 +64,7 @@ export function ModelsPanel({ onEdit: () => void; /** 打开添加模型的对话框。`listed` 是上游自己列出的那些 */ onAdd: (listed: string[]) => void; - /** 给这个模型起别名。不给就不出「起别名…」 */ + /** 给这个模型设置别名。不给就不出「设置别名…」 */ onAlias?: (model: string) => void; /** 手写这个模型的规格。不给就不出「规格…」 */ onSpec?: (model: ModelRow) => void; diff --git a/src/upstreams/ModelsSection.i18n.ts b/src/upstreams/ModelsSection.i18n.ts index 5c6e9fb9..64b76dc0 100644 --- a/src/upstreams/ModelsSection.i18n.ts +++ b/src/upstreams/ModelsSection.i18n.ts @@ -35,7 +35,7 @@ export const modelsSectionText = messages( setPrice: "设置价格…", setPriceShort: "设置价格", priceOf: (id: string) => `设置 ${id} 的价格`, - makeAlias: "起别名…", + makeAlias: "设置别名…", aliasMark: (alias: string) => `别名 ${alias}`, aliasTitle: (alias: string) => `别名 ${alias} 列着这个模型:客户端用 ${alias} 请求时可以发往这个模型`, unknown: "未知", @@ -127,7 +127,7 @@ export const modelsSectionText = messages( setPrice: "設定價格…", setPriceShort: "設定價格", priceOf: (id: string) => `設定 ${id} 的價格`, - makeAlias: "起別名…", + makeAlias: "設定別名…", aliasMark: (alias: string) => `別名 ${alias}`, aliasTitle: (alias: string) => `別名 ${alias} 列著這個模型:用戶端用 ${alias} 請求時可以發往這個模型`, fill: "填寫", diff --git a/src/upstreams/ModelsSection.tsx b/src/upstreams/ModelsSection.tsx index a05a47ae..d2f45dd3 100644 --- a/src/upstreams/ModelsSection.tsx +++ b/src/upstreams/ModelsSection.tsx @@ -126,7 +126,7 @@ export function modelCount(hasList: boolean, listed: number, added: number): str * * 编辑已有的上游时(`actions`),上下文窗口、定价两格就是按钮:不知道的写「未知 · 填写」, * 未定价的写「未定价 · 设置价格」。行尾「…」和右键是同一份菜单:规格…、设置价格…、 - * 起别名…。**这些都只是入口**,打开的是现有的对话框,在那边保存、立即生效,和这个对话框的 + * 设置别名…。**这些都只是入口**,打开的是现有的对话框,在那边保存、立即生效,和这个对话框的 * 「保存」无关。模型名后面标出列着它的别名。 * * 输入框的状态(`entry`)放在对话框里:切到别的分节再保存,输入框里没按回车的也要先加上、 diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index 4e7178a8..474cb702 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -272,7 +272,7 @@ export function UpstreamDialog({ | { kind: "draft-sheet"; add?: string[] } /** 「模型」一节里那一行的规格 */ | { kind: "spec"; row: ModelRow } - /** 「模型」一节里给这个模型起别名 */ + /** 「模型」一节里给这个模型设置别名 */ | { kind: "alias"; model: string } >(null); @@ -1068,7 +1068,7 @@ export function UpstreamDialog({ !o && setNested(null)} - initial={{ models: [nested.model] }} + sourceModel={nested.model} onSaved={(version) => { setBase(version); reloadCatalog(); diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index 86d81f5b..05d6f012 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -475,7 +475,7 @@ function ModelsCell({ const t = useText(upstreamTableText); const l = useText(labelsText); const [open, setOpen] = useState(false); - /** 「起别名…」点的那个模型。对话框挂在弹窗外面:弹窗一收起,里面的东西就卸掉了 */ + /** 「设置别名…」点的那个模型。对话框挂在弹窗外面:弹窗一收起,里面的东西就卸掉了 */ const [aliasFor, setAliasFor] = useState(null); /** 「规格…」点的那一行,同上 */ const [specFor, setSpecFor] = useState(null); @@ -571,7 +571,7 @@ function ModelsCell({ !o && setAliasFor(null)} - initial={{ models: aliasFor !== null ? [aliasFor] : [] }} + sourceModel={aliasFor ?? undefined} /> );