diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index be5864f1..944b499d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4866,8 +4866,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.2.2" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.2.2#6cc189f1b9b5ed7bc471f23798f68a147ac6598d" +version = "0.3.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.3.0#ccb032409062787b3277ea62ac94992dad2776c5" dependencies = [ "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c6eda087..a2839751 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -27,7 +27,7 @@ tauri-plugin-shell = "2" # 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制 # 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从 # 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。 -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.2.2" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.3.0" } anyhow = "1" libc = "0.2" diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index 5ac255aa..3877fa64 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -540,12 +540,11 @@ impl ControlClient { } /// 按接口地址自动识别会得到什么。不联网 - pub async fn preview_provider(&self, base_url: String) -> Result { - self.post_json( - "/providers/preview", - &tw_api::ProviderPreviewRequest { base_url }, - ) - .await + pub async fn preview_provider( + &self, + req: &tw_api::ProviderPreviewRequest, + ) -> Result { + self.post_json("/providers/preview", req).await } pub async fn provider_models(&self, name: &str) -> Result { diff --git a/src-tauri/src/upstreams.rs b/src-tauri/src/upstreams.rs index 893601a6..5f8811aa 100644 --- a/src-tauri/src/upstreams.rs +++ b/src-tauri/src/upstreams.rs @@ -60,9 +60,9 @@ pub async fn test_provider( #[tauri::command] pub async fn preview_provider( state: tauri::State<'_, AppState>, - base_url: String, + preview: tw_api::ProviderPreviewRequest, ) -> Out { - state.control.preview_provider(base_url).await.map_err(text) + state.control.preview_provider(&preview).await.map_err(text) } #[tauri::command] diff --git a/src/source.test.ts b/src/source.test.ts new file mode 100644 index 00000000..3d0bc805 --- /dev/null +++ b/src/source.test.ts @@ -0,0 +1,34 @@ +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +function sources(dir: string): string[] { + const out: string[] = []; + for (const e of readdirSync(dir, { withFileTypes: true })) { + const p = join(dir, e.name); + if (e.isDirectory()) out.push(...sources(p)); + else if (/[.](ts|tsx|css)$/.test(e.name)) out.push(p); + } + return out; +} + +/** 制表、换行、回车以外的 C0 控制字符 */ +function hasControlChar(text: string): boolean { + for (let i = 0; i < text.length; i++) { + const c = text.charCodeAt(i); + if (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d) return true; + } + return false; +} + +describe("源码文件", () => { + /** + * **下拉框里的占位值曾经是一个字面的 NUL 字节。**编译和运行都没问题, + * 但 git 从此把整个文件当二进制:PR 里看不到这个文件的 diff,评审时等于 + * 没审。 + */ + it("不含 NUL 等控制字符", () => { + const bad = sources("src").filter((f) => hasControlChar(readFileSync(f, "utf8"))); + expect(bad).toEqual([]); + }); +}); diff --git a/src/types.ts b/src/types.ts index ddf140eb..bdc89e85 100644 --- a/src/types.ts +++ b/src/types.ts @@ -733,14 +733,14 @@ export interface ProviderView { base_url: string; /** 地址里有被打码的部分 */ base_url_masked: boolean; - /** 密钥的来源,不是值 */ - key_source: string; - /** `key` / `env` / `oauth` */ - key_kind: "key" | "env" | "oauth"; - /** `env` 时的变量名 */ - key_env?: string | null; - oauth_endpoint?: string | null; - oauth_client_id?: string | null; + /** API 密钥:打过码的值或环境变量名。没有密钥是 null */ + key?: SecretView | null; + /** 密钥放在哪个请求头里发:`x-api-key` / `authorization` / `x-goog-api-key` */ + auth_header: string; + /** 其余请求头,按配置里的顺序 */ + headers?: HeaderView[]; + /** OAuth 的 token 端点和 client id。refresh token 和 client secret 不出 core */ + oauth?: OAuthView | null; /** 实际生效的协议。推断不出时为 null */ protocol: string | null; /** 协议是配置里写明的,还是按地址推断的 */ @@ -775,6 +775,28 @@ export interface ProviderView { pricing?: string | null; } +/** 一个可能是密钥的值给界面看的样子 */ +export interface SecretView { + /** 打过码的值,或者 `环境变量 ${NAME}` */ + display: string; + /** 整个值恰好是一个 `${NAME}` 时的变量名 */ + env?: string | null; +} + +/** 一行请求头 */ +export interface HeaderView { + name: string; + /** 可能是密钥的值是打过码的 */ + value: string; + /** 值打过码。编辑时这一行不回填,留空表示保持原值 */ + masked: boolean; +} + +export interface OAuthView { + endpoint: string; + client_id?: string | null; +} + /** 配置里引用了某个上游的一处 */ export type ReferenceView = | { kind: "rule_target"; route: string; rule: string } @@ -1172,12 +1194,24 @@ export interface ConfigWritten { version: string; } -/** 凭据的三种写法 */ -export type CredentialInput = - | { kind: "key"; value: string } - | { kind: "env"; var: string } +/** 一个密钥类的值怎么改。视图里拿不到原值,所以有「保持原样」 */ +export type SecretChange = + | { mode: "keep" } + | { mode: "none" } + /** 可以写 `${ENV}` 从环境变量读 */ + | { mode: "set"; value: string }; + +export interface HeaderInput { + name: string; + /** 不给表示沿用同名那一行的原值 */ + value?: string; +} + +export type OAuthChange = + | { mode: "keep" } + | { mode: "none" } | { - kind: "oauth"; + mode: "set"; refresh: string; endpoint: string; client_id?: string; @@ -1191,8 +1225,11 @@ export interface ProviderInput { name: string; /** 修改时不给就是保持原样 */ base_url?: string; - /** 修改时不给就是保持原样 —— 界面拿不到原值 */ - key?: CredentialInput; + /** 修改时默认保持原样 —— 界面拿不到原值 */ + key: SecretChange; + /** 整张表就是保存之后的样子:没列出来的行被删掉 */ + headers: HeaderInput[]; + oauth: OAuthChange; /** 不给就按地址推断 */ protocol?: string; proxy: string; @@ -1227,6 +1264,8 @@ export interface ProviderPreview { protocol?: string | null; official: boolean; redact: string[]; + /** 按推断出的协议,API 密钥放在哪个请求头里 */ + auth_header: string; } /** 一个上游的模型清单 */ diff --git a/src/upstreams/BillingSection.tsx b/src/upstreams/BillingSection.tsx index 7a4dceb3..ed7a47b5 100644 Binary files a/src/upstreams/BillingSection.tsx and b/src/upstreams/BillingSection.tsx differ diff --git a/src/upstreams/ConnectionSection.tsx b/src/upstreams/ConnectionSection.tsx index aa1127d0..a576312d 100644 Binary files a/src/upstreams/ConnectionSection.tsx and b/src/upstreams/ConnectionSection.tsx differ diff --git a/src/upstreams/HeaderEditor.tsx b/src/upstreams/HeaderEditor.tsx new file mode 100644 index 00000000..92aa1c92 --- /dev/null +++ b/src/upstreams/HeaderEditor.tsx @@ -0,0 +1,73 @@ +import { useState } from "react"; +import { PlusIcon, XIcon } from "lucide-react"; +import { Button } from "@/ui/button"; +import { Input } from "@/ui/input"; +import { headerRow, keepsSavedValue, type HeaderRow, type UpstreamForm } from "./upstreamForm"; + +/** + * 发给上游的请求头,一行一个。 + * + * **已保存的敏感值不回填**:那一行的值留空表示沿用,和 API 密钥同一个约定。 + * 名称和值写得对不对(保留头、重名、占位符)由 core 在检测和保存时说。 + */ +export function HeaderEditor({ + form, + set, +}: { + form: UpstreamForm; + set: (patch: Partial) => void; +}) { + // 新加的那一行自动聚焦到名称 + const [focus, setFocus] = useState(null); + const rows = form.headers; + + function update(id: number, patch: Partial) { + set({ headers: rows.map((r) => (r.id === id ? { ...r, ...patch } : r)) }); + } + + function add() { + const row = headerRow(); + setFocus(row.id); + set({ headers: [...rows, row] }); + } + + return ( +
+ {rows.map((r) => ( +
+ update(r.id, { name: e.target.value })} + /> + update(r.id, { value: e.target.value })} + /> + +
+ ))} + +
+ ); +} diff --git a/src/upstreams/UpstreamDialog.tsx b/src/upstreams/UpstreamDialog.tsx index f3f9c5f2..1c4ec04a 100644 --- a/src/upstreams/UpstreamDialog.tsx +++ b/src/upstreams/UpstreamDialog.tsx @@ -29,6 +29,7 @@ import { ProxyDialog } from "./ProxyDialog"; import { SecuritySection } from "./SecuritySection"; import { blankForm, + connectionChanged, connectionMissing, describeModelList, formFromView, @@ -106,7 +107,7 @@ export function UpstreamDialog({ | { kind: "sheet"; name: string | null; add?: string[] } >(null); - // 「自动识别」此刻会判成什么。只看地址,不联网 + // 「自动识别」此刻会判成什么、密钥放在哪个请求头。只看地址和选定的协议,不联网 useEffect(() => { const url = form.baseUrl.trim(); if (!url) { @@ -115,25 +116,25 @@ export function UpstreamDialog({ } const t = setTimeout(() => { api - .previewProvider(url) + .previewProvider(url, form.protocol || undefined) .then(setPreview) .catch(() => setPreview(null)); }, 250); return () => clearTimeout(t); - }, [form.baseUrl]); + }, [form.baseUrl, form.protocol]); // 新建:连接信息一改,之前检测到的结果和模型列表就不再对应这一家 - const connectionKey = [ + const connectionKey = JSON.stringify([ form.baseUrl, form.protocol, - form.credKind, + form.authMode, form.key, - form.envVar, + form.headers.map((h) => [h.name, h.value]), form.oauthRefresh, form.oauthEndpoint, form.oauthAccess, form.proxy, - ].join("\n"); + ]); useEffect(() => { if (editing) return; setTest(null); @@ -223,7 +224,7 @@ export function UpstreamDialog({ async function refreshModels() { // 连接信息改过:按表单里的新值去问;没改过:让 core 刷新已保存的那一家 - if (!editing || form.baseUrlTouched || form.credTouched) { + if (!editing || connectionChanged(form, editing)) { await runTest(); return; } diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index 8057d2d0..f33c3d19 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -83,7 +83,7 @@ export function UpstreamTable({ title={`${protocolLabel(p.protocol)} · ${p.base_url}`} > {protocolLabel(p.protocol)} · {shortUrl(p.base_url)} - {p.key_kind === "oauth" && " · OAuth"} + {p.oauth && " · OAuth"} diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 8fd4e17b..55de8ffe 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -45,7 +45,9 @@ export const api = { deleteProvider: (name: string, baseVersion: Base) => invoke("delete_provider", { name, baseVersion }), testProvider: (test: ProviderTest) => invoke("test_provider", { test }), - previewProvider: (baseUrl: string) => invoke("preview_provider", { baseUrl }), + /** `protocol`:表单里选定的协议,不给就是自动识别 */ + previewProvider: (baseUrl: string, protocol?: string) => + invoke("preview_provider", { preview: { base_url: baseUrl, protocol } }), providerModels: (name: string) => invoke("provider_models", { name }), refreshProviderModels: (name: string) => invoke("refresh_provider_models", { name }), diff --git a/src/upstreams/labels.ts b/src/upstreams/labels.ts index 0a0db500..ca779529 100644 --- a/src/upstreams/labels.ts +++ b/src/upstreams/labels.ts @@ -63,12 +63,16 @@ export function redactLabel(id: string): string { return REDACT_KINDS.find((k) => k.id === id)?.label ?? id; } -export const CREDENTIAL_KINDS: { id: "key" | "env" | "oauth"; label: string }[] = [ +export const AUTH_MODES: { id: "key" | "oauth"; label: string }[] = [ { id: "key", label: "API 密钥" }, - { id: "env", label: "环境变量" }, { id: "oauth", label: "OAuth" }, ]; +/** 密钥所在的请求头,按 HTTP 报文里的写法 */ +export function authHeaderLabel(header: string): string { + return header === "authorization" ? "Authorization: Bearer" : header; +} + export function modelSourceLabel(source: string): string { switch (source) { case "discovered": diff --git a/src/upstreams/presets.ts b/src/upstreams/presets.ts index 641d704a..ed76a0b4 100644 --- a/src/upstreams/presets.ts +++ b/src/upstreams/presets.ts @@ -13,8 +13,6 @@ export interface Preset { /** 空字符串 = 自动识别 */ protocol: string; billing?: string; - /** 这类服务不需要密钥时的占位值 */ - keyPlaceholder?: string; } export const CUSTOM: Preset = { @@ -61,7 +59,6 @@ export const PRESETS: Preset[] = [ baseUrl: "http://127.0.0.1:11434", protocol: "openai-chat", billing: "free", - keyPlaceholder: "ollama", }, ]; diff --git a/src/upstreams/upstreamForm.test.ts b/src/upstreams/upstreamForm.test.ts new file mode 100644 index 00000000..e2c7dbe1 --- /dev/null +++ b/src/upstreams/upstreamForm.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it } from "vitest"; +import type { ProviderView } from "@/types"; +import { + blankForm, + connectionChanged, + connectionMissing, + formFromView, + headerRow, + toInput, + type UpstreamForm, +} from "./upstreamForm"; + +function view(patch: Partial = {}): ProviderView { + return { + name: "relay", + base_url: "https://relay.example", + base_url_masked: false, + key: { display: "sk-…Q3xA" }, + auth_header: "x-api-key", + headers: [ + { name: "anthropic-version", value: "2023-06-01", masked: false }, + { name: "X-Relay-Token", value: "rt-…9f2c", masked: true }, + ], + oauth: null, + protocol: "anthropic", + protocol_explicit: true, + proxy: "direct", + on_proxy_fail: "fail", + models: [], + models_only: null, + model_source: "discovered", + model_count: 3, + disabled: false, + health: "ok", + billing: null, + billing_effective: "per-token", + trust: "untrusted", + trust_explicit: false, + redact: [], + redact_explicit: false, + references: [], + pricing: null, + ...patch, + }; +} + +function fresh(patch: Partial): UpstreamForm { + return { ...blankForm(), name: "relay", baseUrl: "https://relay.example", ...patch }; +} + +describe("编辑时的凭据", () => { + it("没动过:密钥和打过码的请求头沿用,公开的请求头原样发回", () => { + const input = toInput(formFromView(view()), true); + expect(input.key).toEqual({ mode: "keep" }); + expect(input.oauth).toEqual({ mode: "none" }); + expect(input.headers).toEqual([ + { name: "anthropic-version", value: "2023-06-01" }, + // 不给值 = 沿用。发回打过码的值会把码写进配置 + { name: "X-Relay-Token" }, + ]); + }); + + it("打过码的请求头:名称不分大小写,改了名就不再沿用", () => { + const f = formFromView(view()); + const token = f.headers[1]!; + const renamed = { ...f, headers: [{ ...token, name: "x-relay-token" }] }; + expect(toInput(renamed, true).headers).toEqual([{ name: "x-relay-token" }]); + + const other = { ...f, headers: [{ ...token, name: "X-Relay-Key" }] }; + expect(connectionMissing(other, "relay", ["relay"])).toBe("填写请求头「X-Relay-Key」的值"); + }); + + it("填了新密钥就换;点了移除就删", () => { + const f = formFromView(view()); + expect(toInput({ ...f, key: " sk-new " }, true).key).toEqual({ mode: "set", value: "sk-new" }); + expect(toInput({ ...f, keySaved: false }, true).key).toEqual({ mode: "none" }); + }); + + it("环境变量引用回填,原样保存等于沿用", () => { + const p = view({ key: { display: "环境变量 ${RELAY_KEY}", env: "RELAY_KEY" } }); + const f = formFromView(p); + expect(f.key).toBe("${RELAY_KEY}"); + expect(connectionChanged(f, p)).toBe(false); + }); + + it("OAuth 没点更换就整份沿用;改成 API 密钥时删掉 OAuth", () => { + const p = view({ key: null, oauth: { endpoint: "https://auth.example/token" } }); + const f = formFromView(p); + expect(f.authMode).toBe("oauth"); + expect(toInput(f, true).oauth).toEqual({ mode: "keep" }); + expect(toInput(f, true).key).toEqual({ mode: "none" }); + expect(connectionMissing(f, "relay", ["relay"])).toBeNull(); + + const switched = { ...f, authMode: "key" as const, key: "sk-new" }; + expect(toInput(switched, true).oauth).toEqual({ mode: "none" }); + expect(toInput(switched, true).key).toEqual({ mode: "set", value: "sk-new" }); + }); + + it("从 API 密钥改成 OAuth:必须填新的 OAuth 凭据,原密钥删掉", () => { + const f = { ...formFromView(view()), authMode: "oauth" as const }; + expect(connectionMissing(f, "relay", ["relay"])).toBe("填写 Refresh Token 与 Token 端点"); + const filled = { ...f, oauthRefresh: "rt", oauthEndpoint: "https://auth.example/token" }; + expect(toInput(filled, true).key).toEqual({ mode: "none" }); + expect(toInput(filled, true).oauth).toMatchObject({ mode: "set", refresh: "rt" }); + }); + + it("改了请求头、协议或代理都算连接改过", () => { + const p = view(); + const f = formFromView(p); + expect(connectionChanged(f, p)).toBe(false); + expect(connectionChanged({ ...f, headers: [...f.headers, headerRow("X-Org", "o-1")] }, p)).toBe(true); + expect(connectionChanged({ ...f, protocol: "openai-chat" }, p)).toBe(true); + expect(connectionChanged({ ...f, proxy: "system" }, p)).toBe(true); + }); +}); + +describe("新建时的凭据", () => { + it("密钥可以不填:本地服务和用请求头鉴权的中转站都不需要", () => { + const f = fresh({}); + expect(connectionMissing(f, null, [])).toBeNull(); + expect(toInput(f, false).key).toEqual({ mode: "none" }); + }); + + it("空行忽略;只有名称或只有值的行要补全", () => { + expect(toInput(fresh({ headers: [headerRow()] }), false).headers).toEqual([]); + expect(connectionMissing(fresh({ headers: [headerRow("", "v")] }), null, [])).toBe( + "填写请求头名称", + ); + expect(connectionMissing(fresh({ headers: [headerRow("X-Org", " ")] }), null, [])).toBe( + "填写请求头「X-Org」的值", + ); + }); +}); diff --git a/src/upstreams/upstreamForm.ts b/src/upstreams/upstreamForm.ts index 8814acf1..1e29e2fc 100644 --- a/src/upstreams/upstreamForm.ts +++ b/src/upstreams/upstreamForm.ts @@ -1,13 +1,28 @@ /** * 上游对话框的表单:从视图回填、转成交给 core 的输入、判断能不能往下走。 * - * **编辑时凭据和地址默认「保持原样」。**视图里的密钥只有来源、地址可能打了 - * 码,原样写回去会把码写进配置 —— 所以没点「更换」、没改地址时,这两样不发。 + * **编辑时地址和凭据默认「保持原样」。**视图里的密钥和敏感请求头是打过码的、 + * 地址也可能打了码,原样写回去会把码写进配置 —— 所以没改地址时地址不发, + * 密钥和请求头的值留空表示沿用已保存的,OAuth 没点「更换」时沿用。 */ -import type { CredentialInput, ModelList, ProviderInput, ProviderView } from "@/types"; +import type { HeaderInput, ModelList, OAuthChange, ProviderInput, ProviderView, SecretChange } from "@/types"; import { CUSTOM } from "./presets"; -export type CredKind = "key" | "env" | "oauth"; +export type AuthMode = "key" | "oauth"; + +/** 请求头表里的一行 */ +export interface HeaderRow { + /** 只给列表渲染用,不发给 core */ + id: number; + name: string; + value: string; +} + +let nextRow = 0; + +export function headerRow(name = "", value = ""): HeaderRow { + return { id: nextRow++, name, value }; +} export interface UpstreamForm { preset: string; @@ -17,11 +32,16 @@ export interface UpstreamForm { baseUrlTouched: boolean; /** 空 = 自动识别 */ protocol: string; - credKind: CredKind; - /** 编辑时点过「更换」没有。没点就保持原来的凭据 */ - credTouched: boolean; + authMode: AuthMode; + /** 新填的 API 密钥 */ key: string; - envVar: string; + /** 有已保存的密钥:`key` 留空时沿用 */ + keySaved: boolean; + headers: HeaderRow[]; + /** 已保存的、值打过码的请求头名(小写)。这些行的值留空时沿用 */ + savedHeaders: string[]; + /** 有已保存的 OAuth 凭据、没点「更换」:整份沿用 */ + oauthSaved: boolean; oauthRefresh: string; oauthEndpoint: string; oauthClientId: string; @@ -65,10 +85,12 @@ export function blankForm(): UpstreamForm { baseUrl: "", baseUrlTouched: true, protocol: "", - credKind: "key", - credTouched: true, + authMode: "key", key: "", - envVar: "", + keySaved: false, + headers: [], + savedHeaders: [], + oauthSaved: false, oauthRefresh: "", oauthEndpoint: "", oauthClientId: "", @@ -95,13 +117,16 @@ export function formFromView(p: ProviderView): UpstreamForm { baseUrl: p.base_url, baseUrlTouched: false, protocol: p.protocol_explicit ? (p.protocol ?? "") : "", - credKind: p.key_kind, - credTouched: false, - key: "", - envVar: p.key_env ?? "", + authMode: p.oauth ? "oauth" : "key", + // 环境变量名不是秘密,回填;打过码的密钥不回填 + key: p.key?.env ? `\${${p.key.env}}` : "", + keySaved: p.key != null, + headers: (p.headers ?? []).map((h) => headerRow(h.name, h.masked ? "" : h.value)), + savedHeaders: (p.headers ?? []).filter((h) => h.masked).map((h) => h.name.toLowerCase()), + oauthSaved: p.oauth != null, oauthRefresh: "", - oauthEndpoint: p.oauth_endpoint ?? "", - oauthClientId: p.oauth_client_id ?? "", + oauthEndpoint: p.oauth?.endpoint ?? "", + oauthClientId: p.oauth?.client_id ?? "", oauthClientSecret: "", oauthAccess: "", proxy: p.proxy, @@ -118,30 +143,48 @@ export function formFromView(p: ProviderView): UpstreamForm { }; } -function credential(f: UpstreamForm): CredentialInput { - switch (f.credKind) { - case "key": - return { kind: "key", value: f.key }; - case "env": - return { kind: "env", var: f.envVar }; - case "oauth": - return { - kind: "oauth", - refresh: f.oauthRefresh, - endpoint: f.oauthEndpoint, - client_id: f.oauthClientId || undefined, - client_secret: f.oauthClientSecret || undefined, - access: f.oauthAccess || undefined, - }; - } +/** 这一行的值留空时沿用已保存的 */ +export function keepsSavedValue(f: UpstreamForm, row: HeaderRow): boolean { + return row.value.trim() === "" && f.savedHeaders.includes(row.name.trim().toLowerCase()); +} + +function keyChange(f: UpstreamForm): SecretChange { + if (f.authMode === "oauth") return { mode: "none" }; + const key = f.key.trim(); + if (key !== "") return { mode: "set", value: key }; + return f.keySaved ? { mode: "keep" } : { mode: "none" }; } -/** `editing`:改的是已经保存的一家。没动过的地址和凭据不发 */ +function headerInputs(f: UpstreamForm): HeaderInput[] { + return f.headers + .filter((r) => r.name.trim() !== "" || r.value.trim() !== "") + .map((r) => ({ + name: r.name.trim(), + value: keepsSavedValue(f, r) ? undefined : r.value.trim(), + })); +} + +function oauthChange(f: UpstreamForm): OAuthChange { + if (f.authMode === "key") return { mode: "none" }; + if (f.oauthSaved) return { mode: "keep" }; + return { + mode: "set", + refresh: f.oauthRefresh.trim(), + endpoint: f.oauthEndpoint.trim(), + client_id: f.oauthClientId.trim() || undefined, + client_secret: f.oauthClientSecret.trim() || undefined, + access: f.oauthAccess.trim() || undefined, + }; +} + +/** `editing`:改的是已经保存的一家。没动过的地址不发 */ export function toInput(f: UpstreamForm, editing: boolean): ProviderInput { return { name: f.name, base_url: !editing || f.baseUrlTouched ? f.baseUrl.trim() : undefined, - key: !editing || f.credTouched ? credential(f) : undefined, + key: keyChange(f), + headers: headerInputs(f), + oauth: oauthChange(f), protocol: f.protocol || undefined, proxy: f.proxy, on_proxy_fail: f.onProxyFail, @@ -155,6 +198,16 @@ export function toInput(f: UpstreamForm, editing: boolean): ProviderInput { }; } +/** + * 连接信息和已保存的那一家比改过没有:地址、协议、凭据、请求头、出站代理。 + * 改过的话,模型列表要按表单里的新值去问。 + */ +export function connectionChanged(f: UpstreamForm, p: ProviderView): boolean { + const pick = (i: ProviderInput) => + JSON.stringify([i.base_url, i.protocol, i.key, i.headers, i.oauth, i.proxy]); + return pick(toInput(f, true)) !== pick(toInput(formFromView(p), true)); +} + /** * 连接这一节缺什么。**只查必填与重名** —— 写法对不对由 core 说。 * @@ -170,11 +223,17 @@ export function connectionMissing( if (name === "") return "填写名称"; if (name !== original && taken.includes(name)) return `名称「${name}」已被其他上游使用`; if ((!editing || f.baseUrlTouched) && f.baseUrl.trim() === "") return "填写接口地址"; - if (!editing || f.credTouched) { - if (f.credKind === "key" && f.key.trim() === "") return "填写 API 密钥"; - if (f.credKind === "env" && f.envVar.trim() === "") return "填写环境变量名"; - if (f.credKind === "oauth" && (f.oauthRefresh.trim() === "" || f.oauthEndpoint.trim() === "")) - return "填写 Refresh Token 与 Token 端点"; + if ( + f.authMode === "oauth" && + !f.oauthSaved && + (f.oauthRefresh.trim() === "" || f.oauthEndpoint.trim() === "") + ) + return "填写 Refresh Token 与 Token 端点"; + for (const r of f.headers) { + const header = r.name.trim(); + if (header === "" && r.value.trim() === "") continue; + if (header === "") return "填写请求头名称"; + if (r.value.trim() === "" && !keepsSavedValue(f, r)) return `填写请求头「${header}」的值`; } return null; }