A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
feat(agy): edit gateway models as a list with the fetched model picker
Jasone45576b88293
diff --git a/src/components/providers/ProviderCard.tsx b/src/components/providers/ProviderCard.tsxindex 4da1e8754..80872a7fe 100644--- a/src/components/providers/ProviderCard.tsx+++ b/src/components/providers/ProviderCard.tsx@@ -69,7 +69,7 @@ import {terminalNeedsRoute,} from "./OpenTerminalDialog";import type { CardChip, CardPresentation, CardTone } from "./presentation";-import { agyGatewayFromSettings } from "./forms/AgyGatewayFields";+import { agyGatewayFromSettings, agyModelIds } from "./forms/AgyGatewayFields";import { appHas } from "@/config/appSpecs";const copilotPlan = (data: unknown) => (data as CopilotQuota).plan;@@ -213,10 +213,7 @@ function extractAgyModel(provider: Provider): string | null {typeof apiKey === "string" &&apiKey.trim()) {- const ids = agyGatewayFromSettings(config)- .models.split(",")- .map((id) => id.trim())- .filter(Boolean);+ const ids = agyModelIds(agyGatewayFromSettings(config));if (ids.length === 0) return null;return ids.length > 1 ? `${ids[0]} +${ids.length - 1}` : ids[0];}diff --git a/src/components/providers/forms/AgyGatewayFields.tsx b/src/components/providers/forms/AgyGatewayFields.tsxindex 60acd635d..ac3e33f96 100644--- a/src/components/providers/forms/AgyGatewayFields.tsx+++ b/src/components/providers/forms/AgyGatewayFields.tsx@@ -1,7 +1,10 @@import { useCallback, useState } from "react";import { useTranslation } from "react-i18next";-import { Download, Loader2 } from "lucide-react";+import { ArrowUp, Plus, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";+import { FormLabel } from "@/components/ui/form";+import { HelpTip } from "@/components/ui/help-tip";+import { HoverTip } from "@/components/ui/hover-tip";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import {@@ -17,6 +20,10 @@ import {showFetchModelsError,type FetchedModel,} from "@/lib/api/model-fetch";+import {+ FetchedModelPicker,+ type FetchedModelSelection,+} from "./FetchedModelPicker";import { ModelDropdown } from "./shared";/** 没填地址的 Key 卡走 Google 自己的 Gemini API(同后端 `GOOGLE_GEMINI_API_URL`) */@@ -24,14 +31,27 @@ const GOOGLE_GEMINI_API_URL = "https://generativelanguage.googleapis.com";export type AgyWireProtocol = "genai" | "openai";+/** 模型列表的一行:多一个只在前端用的行 id,删行时输入框不串位。 */+export interface AgyModelRow {+ rowId: string;+ id: string;+}++let nextRowId = 0;++function modelRow(id = ""): AgyModelRow {+ nextRowId += 1;+ return { rowId: `agy-model-${nextRowId}`, id };+}+/*** 供应商行 `gateway` 对象的表单草稿。表单不管的键(`customHeaders` 等)原样放在 `rest`,* 保存时写回,不因为编辑一次就丢掉。*/export interface AgyGatewayDraft {wireProtocol: AgyWireProtocol;- /** 逗号分隔的模型 ID,第一个是默认模型 */- models: string;+ /** 模型 ID,第一行是默认模型 */+ models: AgyModelRow[];caCertPath: string;rest: Record<string, unknown>;}@@ -56,16 +76,17 @@ export function agyGatewayFromSettings(settings: unknown): AgyGatewayDraft {}return {wireProtocol: wireProtocol === "openai" ? "openai" : "genai",- models: ids.join(", "),+ models: ids.map((id) => modelRow(id)),caCertPath: typeof caCertPath === "string" ? caCertPath : "",rest,};}-function modelIds(text: string): string[] {+/** 草稿里的模型 ID:去空、去重,保持顺序(第一个是默认)。 */+export function agyModelIds(draft: AgyGatewayDraft): string[] {const ids: string[] = [];- for (const part of text.split(",")) {- const id = part.trim();+ for (const row of draft.models) {+ const id = row.id.trim();if (id && !ids.includes(id)) ids.push(id);}return ids;@@ -77,7 +98,7 @@ export function agyGatewayToSettings(): Record<string, unknown> | undefined {const gateway: Record<string, unknown> = { ...draft.rest };if (draft.wireProtocol === "openai") gateway.wireProtocol = "openai";- const ids = modelIds(draft.models);+ const ids = agyModelIds(draft);if (ids.length > 0) {gateway.models = ids;gateway.defaultModel = ids[0];@@ -142,11 +163,20 @@ export function AgyGatewayFields({.finally(() => setIsFetching(false));}, [apiKey, baseUrl, value.wireProtocol, t]);- // 下拉里选一个就追加到列表末尾,已有的不重复加- const addModel = (id: string) => {- const ids = modelIds(value.models);- if (!ids.includes(id)) ids.push(id);- onChange({ ...value, models: ids.join(", ") });+ const setRows = (models: AgyModelRow[]) => onChange({ ...value, models });+ const updateRow = (rowId: string, id: string) =>+ setRows(+ value.models.map((row) => (row.rowId === rowId ? { ...row, id } : row)),+ );++ // 弹窗里勾选的增删:新勾的追加到末尾,取消勾选的移除+ const applyFetchedModels = ({ add, remove }: FetchedModelSelection) => {+ const kept = value.models.filter((row) => !remove.includes(row.id.trim()));+ const existing = new Set(kept.map((row) => row.id.trim()));+ setRows([+ ...kept,+ ...add.filter((id) => !existing.has(id)).map((id) => modelRow(id)),+ ]);};return (@@ -180,42 +210,106 @@ export function AgyGatewayFields({</p></div>- <div className="space-y-2">- <div className="flex items-center justify-between">- <Label htmlFor="agy-models">{t("provider.form.agy.models")}</Label>- <Button- type="button"- variant="outline"- size="sm"- onClick={handleFetch}- disabled={isFetching}- className="h-7 gap-1"- >- {isFetching ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Download className="h-3.5 w-3.5" />- )}- {t("providerForm.fetchModels")}- </Button>- </div>- <div className="flex gap-1">- <Input- id="agy-models"- type="text"- value={value.models}- onChange={(e) => onChange({ ...value, models: e.target.value })}- placeholder="gemini-3.6-pro, gemini-3.6-flash"- autoComplete="off"- className="flex-1"- />- {fetchedModels.length > 0 && (- <ModelDropdown models={fetchedModels} onSelect={addModel} />- )}+ <div className="space-y-3">+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-0.5">+ <FormLabel>{t("provider.form.agy.models")}</FormLabel>+ <HelpTip title={t("provider.form.agy.models")}>+ {t("provider.form.agy.modelsHelp")}+ </HelpTip>+ </div>+ <div className="flex gap-2">+ <FetchedModelPicker+ models={fetchedModels}+ configuredModelIds={agyModelIds(value)}+ onApply={applyFetchedModels}+ onFetch={handleFetch}+ isFetching={isFetching}+ metadataSource={{+ baseUrl: baseUrl.trim() || GOOGLE_GEMINI_API_URL,+ }}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => setRows([...value.models, modelRow()])}+ className="h-7 gap-1"+ >+ <Plus className="h-3.5 w-3.5" />+ {t("providerForm.addStackModel", { defaultValue: "手动添加" })}+ </Button>+ </div></div>- <p className="text-caption text-fg-2">- {t("provider.form.agy.modelsHelp")}- </p>++ {value.models.length === 0 ? (+ <p className="text-xs leading-relaxed text-fg-2">+ {t("provider.form.agy.modelsEmpty")}+ </p>+ ) : (+ <div className="space-y-2">+ {value.models.map((row, index) => (+ <div key={row.rowId} className="flex items-center gap-1">+ <Input+ value={row.id}+ onChange={(event) => updateRow(row.rowId, event.target.value)}+ placeholder="gemini-3.8-flash"+ aria-label={t("provider.form.agy.models")}+ autoComplete="off"+ className="flex-1"+ />+ {fetchedModels.length > 0 && (+ <ModelDropdown+ models={fetchedModels}+ onSelect={(id) => updateRow(row.rowId, id)}+ />+ )}+ {index === 0 ? (+ <span className="w-16 shrink-0 text-center text-xs font-medium text-fg-2">+ {t("provider.form.agy.defaultModel")}+ </span>+ ) : (+ <HoverTip content={t("provider.form.agy.setDefaultModel")}>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="w-16 shrink-0"+ aria-label={t("provider.form.agy.setDefaultModel")}+ onClick={() =>+ setRows([+ row,+ ...value.models.filter(+ (other) => other.rowId !== row.rowId,+ ),+ ])+ }+ >+ <ArrowUp className="h-4 w-4" />+ </Button>+ </HoverTip>+ )}+ <HoverTip content={t("common.delete")}>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={t("common.delete")}+ onClick={() =>+ setRows(+ value.models.filter(+ (other) => other.rowId !== row.rowId,+ ),+ )+ }+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </HoverTip>+ </div>+ ))}+ </div>+ )}</div><div className="space-y-2">diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.jsonindex 8a98dc815..df1f49532 100644--- a/src/i18n/locales/de.json+++ b/src/i18n/locales/de.json@@ -238,7 +238,10 @@"protocolOpenai": "OpenAI-kompatibel (Chat Completions)","protocolHelp": "Das Format, mit dem agy diesen Endpunkt aufruft. Wählen Sie genai für die Google-API und Gemini-Relays, OpenAI-kompatibel für Relays, die nur /v1/chat/completions unterstützen.","models": "Modell-IDs",- "modelsHelp": "Mehrere IDs durch Kommas trennen; die erste ist das Standardmodell. Leer lassen, damit agy die Modellliste von diesem Endpunkt abruft.",+ "modelsHelp": "Die Modellauswahl von agy zeigt nur diese Modelle; die erste Zeile ist das Standardmodell. Bleibt die Liste leer, holt agy die Modellliste von diesem Endpunkt.",+ "modelsEmpty": "Keine Modelle: agy holt die Modellliste von diesem Endpunkt.",+ "defaultModel": "Standard",+ "setDefaultModel": "Als Standard festlegen","caCertPath": "CA-Zertifikat (optional)","caCertPathHelp": "Wenn der Endpunkt ein selbstsigniertes oder internes Zertifikat verwendet, geben Sie den Pfad zur PEM-Datei an."},diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.jsonindex d65354453..e20d568b9 100644--- a/src/i18n/locales/en.json+++ b/src/i18n/locales/en.json@@ -238,7 +238,10 @@"protocolOpenai": "OpenAI-compatible (Chat Completions)","protocolHelp": "The format agy uses to call this endpoint. Choose genai for Google's API and Gemini relays; choose OpenAI-compatible for relays that only support /v1/chat/completions.","models": "Model IDs",- "modelsHelp": "Separate multiple IDs with commas; the first one is the default. Leave empty to let agy fetch the model list from this endpoint.",+ "modelsHelp": "agy's model picker shows only these models; the first row is the default. Leave it empty and agy fetches the model list from this endpoint.",+ "modelsEmpty": "No models: agy fetches the model list from this endpoint.",+ "defaultModel": "Default",+ "setDefaultModel": "Make default","caCertPath": "CA certificate (optional)","caCertPathHelp": "If the endpoint uses a self-signed or internal certificate, enter the path to its PEM file."},diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.jsonindex 00eb11b33..9660fd567 100644--- a/src/i18n/locales/ja.json+++ b/src/i18n/locales/ja.json@@ -238,7 +238,10 @@"protocolOpenai": "OpenAI 互換(Chat Completions)","protocolHelp": "agy がこのエンドポイントを呼び出す形式です。Google の API や Gemini 中継は genai、/v1/chat/completions だけに対応する中継は OpenAI 互換を選びます。","models": "モデル ID",- "modelsHelp": "複数ある場合はカンマで区切り、先頭がデフォルトモデルになります。空欄にすると agy がこのエンドポイントからモデル一覧を取得します。",+ "modelsHelp": "agy のモデル選択にはこれらのモデルだけが表示され、先頭の行がデフォルトモデルです。空のままにすると、agy はこのエンドポイントからモデル一覧を取得します。",+ "modelsEmpty": "モデル未設定:agy はこのエンドポイントからモデル一覧を取得します。",+ "defaultModel": "デフォルト",+ "setDefaultModel": "デフォルトにする","caCertPath": "CA 証明書(任意)","caCertPathHelp": "エンドポイントが自己署名証明書や社内証明書を使う場合は、PEM ファイルのパスを入力します。"},diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.jsonindex 3af568999..7edf327e7 100644--- a/src/i18n/locales/ko.json+++ b/src/i18n/locales/ko.json@@ -236,7 +236,10 @@"protocolOpenai": "OpenAI 호환(Chat Completions)","protocolHelp": "agy가 이 엔드포인트를 호출하는 형식입니다. Google API와 Gemini 릴레이는 genai를, /v1/chat/completions만 지원하는 릴레이는 OpenAI 호환을 선택하세요.","models": "모델 ID",- "modelsHelp": "여러 개는 쉼표로 구분하며, 첫 번째가 기본 모델입니다. 비워 두면 agy가 이 엔드포인트에서 모델 목록을 가져옵니다.",+ "modelsHelp": "agy의 모델 선택기에는 이 모델들만 표시되며, 첫 번째 행이 기본 모델입니다. 비워 두면 agy가 이 엔드포인트에서 모델 목록을 가져옵니다.",+ "modelsEmpty": "모델 없음: agy가 이 엔드포인트에서 모델 목록을 가져옵니다.",+ "defaultModel": "기본",+ "setDefaultModel": "기본으로 설정","caCertPath": "CA 인증서(선택)","caCertPathHelp": "엔드포인트가 자체 서명 인증서나 사내 인증서를 사용하면 PEM 파일 경로를 입력하세요."},diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.jsonindex 1dcabd561..922a49073 100644--- a/src/i18n/locales/ru.json+++ b/src/i18n/locales/ru.json@@ -238,7 +238,10 @@"protocolOpenai": "Совместимый с OpenAI (Chat Completions)","protocolHelp": "Формат, в котором agy обращается к этому эндпоинту. Для API Google и ретрансляторов Gemini выберите genai, для ретрансляторов, поддерживающих только /v1/chat/completions, — совместимый с OpenAI.","models": "ID моделей",- "modelsHelp": "Несколько ID разделяйте запятыми; первый — модель по умолчанию. Оставьте пустым, чтобы agy получил список моделей с этого эндпоинта.",+ "modelsHelp": "В выборе моделей agy показываются только эти модели; первая строка — модель по умолчанию. Если оставить список пустым, agy получит список моделей с этого адреса.",+ "modelsEmpty": "Модели не указаны: agy получит список моделей с этого адреса.",+ "defaultModel": "По умолчанию",+ "setDefaultModel": "Сделать по умолчанию","caCertPath": "Сертификат ЦС (необязательно)","caCertPathHelp": "Если эндпоинт использует самоподписанный или внутренний сертификат, укажите путь к PEM-файлу."},diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.jsonindex cab3bc7cb..175c90ee3 100644--- a/src/i18n/locales/tr.json+++ b/src/i18n/locales/tr.json@@ -238,7 +238,10 @@"protocolOpenai": "OpenAI uyumlu (Chat Completions)","protocolHelp": "agy'nin bu uç noktayı çağırırken kullandığı biçim. Google API'si ve Gemini aktarıcıları için genai'yi, yalnızca /v1/chat/completions destekleyen aktarıcılar için OpenAI uyumlu seçeneğini seçin.","models": "Model kimlikleri",- "modelsHelp": "Birden çok kimliği virgülle ayırın; ilki varsayılan modeldir. agy'nin model listesini bu uç noktadan alması için boş bırakın.",+ "modelsHelp": "agy'nin model seçicisi yalnızca bu modelleri gösterir; ilk satır varsayılan modeldir. Boş bırakırsanız agy model listesini bu uç noktadan alır.",+ "modelsEmpty": "Model yok: agy model listesini bu uç noktadan alır.",+ "defaultModel": "Varsayılan",+ "setDefaultModel": "Varsayılan yap","caCertPath": "CA sertifikası (isteğe bağlı)","caCertPathHelp": "Uç nokta kendinden imzalı veya kurum içi bir sertifika kullanıyorsa PEM dosyasının yolunu girin."},diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.jsonindex 049f172c8..35efbc720 100644--- a/src/i18n/locales/zh-TW.json+++ b/src/i18n/locales/zh-TW.json@@ -238,7 +238,10 @@"protocolOpenai": "OpenAI 相容(Chat Completions)","protocolHelp": "agy 用哪種格式請求這個位址。Google 的 API 和 Gemini 中轉選 genai;只支援 /v1/chat/completions 的中轉選 OpenAI 相容。","models": "模型 ID",- "modelsHelp": "可填多個,用逗號分隔,第一個是預設模型。留空時 agy 向這個位址取得模型清單。",+ "modelsHelp": "agy 的模型選擇器裡只顯示這些模型,第一列是預設模型。留空時 agy 會向這個位址取得模型列表。",+ "modelsEmpty": "未填模型:agy 會向這個位址取得模型列表。",+ "defaultModel": "預設",+ "setDefaultModel": "設為預設","caCertPath": "CA 憑證(選填)","caCertPathHelp": "這個位址使用自簽或企業內部憑證時,填 PEM 檔案的路徑。"},diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.jsonindex af2fa70ae..7530d573a 100644--- a/src/i18n/locales/zh.json+++ b/src/i18n/locales/zh.json@@ -238,7 +238,10 @@"protocolOpenai": "OpenAI 兼容(Chat Completions)","protocolHelp": "agy 用哪种格式请求这个地址。Google 的 API 和 Gemini 中转选 genai;只支持 /v1/chat/completions 的中转选 OpenAI 兼容。","models": "模型 ID",- "modelsHelp": "可填多个,用逗号分隔,第一个是默认模型。留空时 agy 向这个地址获取模型列表。",+ "modelsHelp": "agy 的模型选择器里只显示这些模型,第一行是默认模型。留空时 agy 向这个地址获取模型列表。",+ "modelsEmpty": "未填模型:agy 会向这个地址获取模型列表。",+ "defaultModel": "默认",+ "setDefaultModel": "设为默认","caCertPath": "CA 证书(可选)","caCertPathHelp": "这个地址用自签名或企业内部证书时,填 PEM 文件的路径。"},diff --git a/tests/components/AgyGatewayFields.rows.test.tsx b/tests/components/AgyGatewayFields.rows.test.tsxnew file mode 100644index 000000000..840a55bb6--- /dev/null+++ b/tests/components/AgyGatewayFields.rows.test.tsx@@ -0,0 +1,70 @@+import { useState } from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { Form } from "@/components/ui/form";+import { useForm } from "react-hook-form";+import {+ AgyGatewayFields,+ agyGatewayFromSettings,+ agyModelIds,+ type AgyGatewayDraft,+} from "@/components/providers/forms/AgyGatewayFields";++let latest: AgyGatewayDraft | null = null;++function Harness({ models }: { models: string[] }) {+ const form = useForm();+ const [value, setValue] = useState(() =>+ agyGatewayFromSettings({ gateway: { models } }),+ );+ latest = value;+ return (+ <Form {...form}>+ <AgyGatewayFields+ value={value}+ onChange={setValue}+ apiKey="k"+ baseUrl="https://relay.example"+ />+ </Form>+ );+}++const ids = () => (latest ? agyModelIds(latest) : []);++describe("Antigravity gateway model rows", () => {+ it("shows the empty hint when no model is set", () => {+ render(<Harness models={[]} />);+ expect(+ screen.getByText("provider.form.agy.modelsEmpty"),+ ).toBeInTheDocument();+ });++ it("adds, edits, promotes and deletes rows", () => {+ render(<Harness models={["a", "b"]} />);+ expect(+ screen.getByText("provider.form.agy.defaultModel"),+ ).toBeInTheDocument();++ fireEvent.click(+ screen.getByRole("button", { name: "provider.form.agy.setDefaultModel" }),+ );+ expect(ids()).toEqual(["b", "a"]);++ fireEvent.click(+ screen.getByRole("button", {+ name: /providerForm.addStackModel|手动添加/,+ }),+ );+ const inputs = screen.getAllByRole("textbox", {+ name: "provider.form.agy.models",+ });+ fireEvent.change(inputs[2], { target: { value: "c" } });+ expect(ids()).toEqual(["b", "a", "c"]);++ fireEvent.click(+ screen.getAllByRole("button", { name: "common.delete" })[0],+ );+ expect(ids()).toEqual(["a", "c"]);+ });+});diff --git a/tests/components/AgyGatewayFields.test.ts b/tests/components/AgyGatewayFields.test.tsindex 7cb85226d..d14b2309d 100644--- a/tests/components/AgyGatewayFields.test.ts+++ b/tests/components/AgyGatewayFields.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import {agyGatewayFromSettings,agyGatewayToSettings,+ agyModelIds,} from "@/components/providers/forms/AgyGatewayFields";describe("Antigravity gateway draft", () => {@@ -16,9 +17,9 @@ describe("Antigravity gateway draft", () => {customHeaders: { "x-team": "1" },},});- expect(draft).toEqual({+ expect({ ...draft, models: agyModelIds(draft) }).toEqual({wireProtocol: "openai",- models: "b, a",+ models: ["b", "a"],caCertPath: "/ca.pem",rest: { customHeaders: { "x-team": "1" } },});@@ -28,7 +29,10 @@ describe("Antigravity gateway draft", () => {expect(agyGatewayToSettings({wireProtocol: "openai",- models: " b, a ,b,, ",+ models: [" b", "a ", "b", "", " "].map((id, index) => ({+ rowId: `r${index}`,+ id,+ })),caCertPath: " /ca.pem ",rest: { customHeaders: { "x-team": "1" } },}),