diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index 21d95da4..95005e3e 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -712,6 +712,79 @@ impl ControlClient { self.send_json(hyper::Method::DELETE, &path, &()).await } + // ───────────────────────────────────────── 路由与策略组 + + pub async fn create_route(&self, req: &tw_api::RouteSave) -> Result { + self.post_json("/routes", req).await + } + + pub async fn update_route( + &self, + name: &str, + req: &tw_api::RouteSave, + ) -> Result { + self.send_json( + hyper::Method::PUT, + &format!("/routes/{}", segment(name)), + req, + ) + .await + } + + /// 删除一条路由。使用它的密钥改用 `reassign_to`;不给就改用默认路由 + pub async fn delete_route( + &self, + name: &str, + base_version: Option<&str>, + reassign_to: Option<&str>, + ) -> Result { + let mut path = with_base(format!("/routes/{}", segment(name)), base_version); + if let Some(t) = reassign_to { + path.push(if path.contains('?') { '&' } else { '?' }); + path.push_str(&format!("reassign_to={}", urlencode(t))); + } + self.send_json(hyper::Method::DELETE, &path, &()).await + } + + pub async fn set_default_route( + &self, + req: &tw_api::DefaultRouteSave, + ) -> Result { + self.send_json(hyper::Method::PUT, "/default_route", req) + .await + } + + pub async fn create_group(&self, req: &tw_api::GroupSave) -> Result { + self.post_json("/groups", req).await + } + + pub async fn update_group( + &self, + name: &str, + req: &tw_api::GroupSave, + ) -> Result { + self.send_json( + hyper::Method::PUT, + &format!("/groups/{}", segment(name)), + req, + ) + .await + } + + pub async fn delete_group( + &self, + name: &str, + base_version: Option<&str>, + ) -> Result { + let path = with_base(format!("/groups/{}", segment(name)), base_version); + self.send_json(hyper::Method::DELETE, &path, &()).await + } + + /// 网关知道的全部模型,以及能提供它们的上游 + pub async fn known_models(&self) -> Result> { + Ok(serde_json::from_slice(&self.get("/models").await?)?) + } + pub async fn config_at(&self, offset: usize) -> Result { let body = self.get(&format!("/config/at?offset={offset}")).await?; Ok(serde_json::from_slice(&body)?) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 31fa88b1..f489c388 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -17,6 +17,7 @@ pub mod control; pub mod memcheck; pub mod menubar; pub mod notices; +pub mod routing; pub mod supervisor; pub mod update; pub mod upstreams; @@ -1242,6 +1243,14 @@ pub fn run() { config_history, config_at, rollback_config, + routing::create_route, + routing::update_route, + routing::delete_route, + routing::set_default_route, + routing::create_group, + routing::update_group, + routing::delete_group, + routing::known_models, upstreams::create_provider, upstreams::update_provider, upstreams::delete_provider, diff --git a/src-tauri/src/routing.rs b/src-tauri/src/routing.rs new file mode 100644 index 00000000..b46232e7 --- /dev/null +++ b/src-tauri/src/routing.rs @@ -0,0 +1,87 @@ +//! 路由页的命令:路由、策略组的增删改,更换默认路由,以及模型建议。 +//! +//! **这一层只转发。**规则怎么校验、改名时密钥和规则怎么跟着改、删除时密钥 +//! 改用哪条路由,全在 core。 + +use crate::AppState; + +type Out = Result; + +fn text(e: anyhow::Error) -> String { + format!("{e:#}") +} + +#[tauri::command] +pub async fn create_route( + state: tauri::State<'_, AppState>, + save: tw_api::RouteSave, +) -> Out { + state.control.create_route(&save).await.map_err(text) +} + +#[tauri::command] +pub async fn update_route( + state: tauri::State<'_, AppState>, + name: String, + save: tw_api::RouteSave, +) -> Out { + state.control.update_route(&name, &save).await.map_err(text) +} + +#[tauri::command] +pub async fn delete_route( + state: tauri::State<'_, AppState>, + name: String, + base_version: Option, + reassign_to: Option, +) -> Out { + state + .control + .delete_route(&name, base_version.as_deref(), reassign_to.as_deref()) + .await + .map_err(text) +} + +#[tauri::command] +pub async fn set_default_route( + state: tauri::State<'_, AppState>, + save: tw_api::DefaultRouteSave, +) -> Out { + state.control.set_default_route(&save).await.map_err(text) +} + +#[tauri::command] +pub async fn create_group( + state: tauri::State<'_, AppState>, + save: tw_api::GroupSave, +) -> Out { + state.control.create_group(&save).await.map_err(text) +} + +#[tauri::command] +pub async fn update_group( + state: tauri::State<'_, AppState>, + name: String, + save: tw_api::GroupSave, +) -> Out { + state.control.update_group(&name, &save).await.map_err(text) +} + +#[tauri::command] +pub async fn delete_group( + state: tauri::State<'_, AppState>, + name: String, + base_version: Option, +) -> Out { + state + .control + .delete_group(&name, base_version.as_deref()) + .await + .map_err(text) +} + +/// 规则条件和试算里的模型建议 +#[tauri::command] +pub async fn known_models(state: tauri::State<'_, AppState>) -> Out> { + state.control.known_models().await.map_err(text) +} diff --git a/src/App.tsx b/src/App.tsx index cc18b014..70e93e67 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -18,7 +18,7 @@ import { ConfigFileDialog, VersionHistoryDialog } from "./ConfigDialogs"; import UpstreamsPage from "./upstreams/UpstreamsPage"; import Clients from "./Clients"; import Keys from "./Keys"; -import Routes from "./Routes"; +import RoutingPage from "./routing/RoutingPage"; import Security from "./Security"; import Guard from "./Guard"; import { Notices } from "./Notices"; @@ -1113,20 +1113,13 @@ export default function App() { ) ) : tab === "routing" ? ( ov ? ( - <> - setNudge((n) => n + 1)} - /> - {/* 试算和策略组还在 Config 里 —— 它俩和文本模式那条路缠着 */} - setConfigFile({ focus })} - /> - + setNudge((n) => n + 1)} + onOpenConfigFile={(focus) => setConfigFile({ focus })} + onNavigate={(to) => setTab(to as Surface)} + /> ) : (

读取配置中…

) @@ -1149,7 +1142,6 @@ export default function App() { section={tab === "settings" ? "settings" : "gateway"} ov={ov} configVersion={configVersion} - onOpenConfigFile={(focus) => setConfigFile({ focus })} /> ) : (

读取配置中…

diff --git a/src/Config.tsx b/src/Config.tsx index 5338defb..270e9a2d 100644 --- a/src/Config.tsx +++ b/src/Config.tsx @@ -4,10 +4,9 @@ import { Checkbox } from "@/ui/checkbox"; import { Field, FieldContent, FieldDescription, FieldLabel } from "@/ui/field"; import { invoke } from "@tauri-apps/api/core"; import { useEffect } from "react"; -import DryRun from "./DryRun"; import Update from "./Update"; import NoticeSettings from "./NoticeSettings"; -import type { ConfigText, NicView, Overview, PatchOp } from "./types"; +import type { NicView, Overview, PatchOp } from "./types"; import { Button } from "@/ui/button"; import { Input } from "@/ui/input"; import { cn } from "@/lib/utils"; @@ -17,7 +16,7 @@ import { Spinner } from "@/ui/spinner"; import { Switch } from "@/ui/switch"; import { toast } from "sonner"; import { patchConfig } from "./patch"; -import { GROUP_KINDS, PROBES } from "./labels"; +import { PROBES } from "./labels"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { ButtonGroup } from "@/ui/button-group"; @@ -118,64 +117,6 @@ function EditableCell({ ); } -/** - * 一个下拉改一个标量字段。 - * - * **和 `EditableCell` 走同一条路**(`patch_config` + 乐观并发),只是 - * 输入形状不同 —— 枚举字段让用户手打,打错一个字母就是一次静默的 - * 「配了没生效」。 - */ -function SelectCell({ - value, - options, - path, - version, - onDone, -}: { - value: string; - /** `[写进 YAML 的值, 显示给人看的字]` */ - options: [string, string][]; - path: string; - version: string | null; - onDone?: () => void; -}) { - const [busy, setBusy] = useState(false); - return ( - { - if (!version) { - toast.error("配置版本尚未读取,请稍后重试"); - return; - } - const v = ev.target.value; - setBusy(true); - try { - await patchConfig( - // 空串写成 null —— 「没写这个字段」和「写了个空值」是两回事, - // 而前者才是「按默认/自动判」的意思 - [{ op: "replace", path, value: v === "" ? null : v }], - version, - ); - onDone?.(); - } catch (err) { - toast.error(typeof err === "string" ? err : String(err)); - } finally { - setBusy(false); - } - }} - > - {options.map(([v, label]) => ( - - {label} - - ))} - - ); -} - /** * 监听方式 —— 网关绑在哪张网卡上。 * @@ -594,182 +535,25 @@ export default function Config({ section = "gateway", ov, configVersion, - onOpenConfigFile, }: { /** - * 这一次渲染哪一域。 - * - * `routing` 这一域现在只剩「试算」和「策略组」—— 路由本身在 - * `Routes.tsx`,上游、代理与价目表在 `upstreams/`。路由页把两个组件叠起来 - * 渲染,对用户是一页。 + * 这一次渲染哪一域。路由与策略组在 `routing/`,上游、代理与价目表在 + * `upstreams/`。 */ - section?: "gateway" | "routing" | "settings"; + section?: "gateway" | "settings"; ov: Overview; configVersion: string | null; - /** 打开配置文件并定位到这个名字 */ - onOpenConfigFile: (focus: string | null) => void; }) { useEffect(() => { void invoke("autostart_enabled") .then(setAutostart) .catch(() => setAutostart(false)); }, []); - const [cfg, setCfg] = useState(null); // 开机自启。**出厂是关的** —— null 表示还没读到,别在读到之前先画一个 // 勾或不勾出来:那一瞬间画错的话,用户会以为是自己之前设的。 const [autostart, setAutostart] = useState(null); - const [reloadKey, setReloadKey] = useState(0); - - // 每次配置换了版本就重新拉一遍 —— 手里那份的 version 过期之后, - // 下一次编辑会撞 409,而用户看不出为什么 - useEffect(() => { - let alive = true; - (async () => { - try { - const c = await invoke("get_config"); - if (alive) setCfg(c); - } catch (e) { - if (alive) toast.error(typeof e === "string" ? e : String(e)); - } - })(); - return () => { - alive = false; - }; - }, [configVersion, reloadKey]); return (
- {section === "routing" && } - - {/* 分组这个概念只在真的有组的时候出现 */} - {section === "routing" && ov.groups.length > 0 && ( -
-

策略组

-
    - {ov.groups.map((g) => ( -
  • -
    - {g.name} - - - - [k.id, k.label])} - path={`/groups/${g.name}/type`} - version={cfg?.version ?? null} - onDone={() => setReloadKey((k) => k + 1)} - /> - - {g.providers.join(" → ")} - -
    - {/* - **`select` 组要能在这儿切。**这个策略本身就是 - 「UI 上点选」,而切不了的话它等于一个只能改 YAML - 才能用的功能。 - - 选中之后其余的仍然留着做故障转移 —— 手动选择一个上游不等于 - 放弃容错,所以这里说的是「优先」而不是「只用」。 - */} - {g.kind === "select" && ( -
    - 优先使用 - { - const v = ev.target.value; - if (!cfg?.version) { - toast.error("配置版本尚未读取,请稍后重试"); - return; - } - try { - await patchConfig([ - { - op: "replace", - path: `/groups/${g.name}/selected`, - value: v, - }, - ], cfg.version); - setReloadKey((k) => k + 1); - } catch (err) { - toast.error(typeof err === "string" ? err : String(err)); - } - }} - > - {g.providers.map((p) => ( - - {p} - - ))} - - - 其余上游作为故障转移备选 - -
    - )} - {/* - **会话粘滞要摆在明面上,因为它直接决定账单。** - 关掉它,一次长会话每轮跳一家,prompt cache 全部失效, - 而缓存命中与否成本差 5 到 10 倍。 - */} - {g.kind === "load-balance" && ( - - { - if (!cfg?.version) { - toast.error("配置版本尚未读取,请稍后重试"); - return; - } - try { - await patchConfig([ - { - op: "replace", - path: `/groups/${g.name}/session_affinity`, - value: checked === true, - }, - ], cfg.version); - setReloadKey((k) => k + 1); - } catch (err) { - toast.error(typeof err === "string" ? err : String(err)); - } - }} - /> - - 会话粘滞(同一会话固定使用同一上游) - - - )} - {g.hurts_cache && ( - // 这句必须在界面上直说:它决定了用户的账单。 - // 缓存命中与否成本差 5 到 10 倍,而为了省 20% 的单价 - // 丢掉 90% 的缓存折扣,是一笔怎么算都不划算的账。 -

    - ⚠ 此策略会使 prompt cache 失效,长会话的费用将明显上升。 - {g.kind === "load-balance" ? "开启会话粘滞可避免此问题。" : ""} -

    - )} -
  • - ))} -
-
- )} - {section === "settings" && (

开机启动

diff --git a/src/DryRun.tsx b/src/DryRun.tsx deleted file mode 100644 index 5bf70e9c..00000000 --- a/src/DryRun.tsx +++ /dev/null @@ -1,284 +0,0 @@ -import { useId, useState } from "react"; -import { invoke } from "@tauri-apps/api/core"; -import { Checkbox } from "@/ui/checkbox"; -import { Field, FieldLabel } from "@/ui/field"; -import type { DryRunResult, RuleTrace } from "./types"; -import { Button } from "@/ui/button"; -import { Input } from "@/ui/input"; -import { Spinner } from "@/ui/spinner"; -import { toast } from "sonner"; -import { skipLabel } from "./upstreams/labels"; -import { groupKindLabel, mismatchText, setText, translatedText } from "./labels"; -import { - Combobox, - ComboboxContent, - ComboboxEmpty, - ComboboxInput, - ComboboxItem, - ComboboxList, - ComboboxTrigger, -} from "@/ui/combobox"; - -/** - * 路由试算。 - * - * 它回答的不是「会走到哪儿」,而是**「为什么没走我以为的那条」** —— - * 后者才是用户真正在问的问题,所以每条没命中的规则也要列出来,并说清 - * 它卡在哪个条件上。 - * - * **只算,不发任何请求**,也不改任何东西。 - */ -export default function DryRun({ models }: { models: string[] }) { - const [model, setModel] = useState(models[0] ?? "claude-sonnet-4-5"); - const [cache, setCache] = useState(false); - const [tools, setTools] = useState(false); - const [image, setImage] = useState(false); - const [thinking, setThinking] = useState(false); - const [kTokens, setKTokens] = useState(8); - const [r, setR] = useState(null); - const [busy, setBusy] = useState(false); - const uid = useId(); - - async function run() { - setBusy(true); - try { - setR( - await invoke("dry_run", { - req: { - model, - cache, - tools, - image, - thinking, - input_tokens: kTokens * 1000, - dialect: "anthropic", - stream: true, - client: "", - intent: "", - tool_count: tools ? 5 : 0, - max_tokens: null, - }, - }), - ); - } catch (e) { - // Tauri 的 invoke 用字符串 reject,不是 Error - toast.error(typeof e === "string" ? e : String(e)); - } finally { - setBusy(false); - } - } - - return ( -
-

路由试算

-

- 按给定条件计算该请求将匹配的路由及其原因。仅计算,不发起请求。 -

- -
- {/* - **自由输入 + 建议**,不是受限选择:模型名可能是刚发布的、也可能 - 是中转自己起的,列表里没有的照样得能敲进去。原来用的是原生 - `` —— 它能做到这件事,但样式完全不受控(系统画的), - 而且不支持模糊匹配。`Combobox` 的 `inputValue` 就是自由输入。 - */} - - - - - - 无匹配项,可直接输入完整模型名 - - {(m: string) => ( - - {m} - - )} - - - - - {( - [ - ["带缓存", cache, setCache], - ["带工具", tools, setTools], - ["带图片", image, setImage], - ["扩展思考", thinking, setThinking], - ] as const - ).map(([label, v, set]) => ( - /* - **`w-auto` 是布局,不是配色。**`Field` 默认 `w-full` —— 那是 - 给表单一行一个字段用的,而这四个是挤在一条工具条里的开关, - 撑满会把后面的按钮挤下去。 - */ - - set(c === true)} - /> - {label} - - ))} - -
- - {r && } -
- ); -} - -/** 规则选中了、但服务不了这个请求的上游。**要列出来** —— 「规则明明写的是 A」正是来试算的原因 */ -function Skipped({ r }: { r: DryRunResult }) { - if (r.skipped.length === 0) return null; - return ( -
- 已跳过: - {r.skipped.map((s, i) => ( - - {i > 0 && "、"} - {s.provider}({skipLabel(s.reason)}) - - ))} -
- ); -} - -/** 候选里要转换格式的上游。转换可能丢字段,试算时就要看得见 */ -function Converted({ r }: { r: DryRunResult }) { - if (r.converted.length === 0) return null; - return ( -
- 需转换格式: - {r.converted.map((c, i) => ( - - {i > 0 && "、"} - {c.provider}({translatedText(c)}) - - ))} -
- ); -} - -/** 规则匹配明细里的一行说明 */ -function traceText(t: RuleTrace): string { - if (t.verdict === "matched") return "命中"; - if (t.verdict === "phase_two") return "条件需在选定上游后求值,试算不作判断"; - if (t.error) return t.error; - return t.mismatch ? mismatchText(t.mismatch) : "未命中"; -} - -function Result({ r }: { r: DryRunResult }) { - const matched = ( - <> - 命中规则「{r.rule}」 - {r.via_group && ( - <> - {" "} - · 策略组「{r.via_group}」{r.strategy && `(${groupKindLabel(r.strategy)})`} - - )} - - ); - return ( -
- {r.outcome === "deny" ? ( -
- 拒绝 · 规则「{r.rule}」:{r.reason} -
- ) : r.outcome === "no_match" ? ( -
没有规则命中,且没有兜底规则,请求将返回错误。
- ) : r.outcome === "unavailable" ? ( -
- {matched} -
选中的上游均无法服务此请求,请求将返回错误。
- -
- ) : ( -
- {matched} -
- 尝试顺序: - {r.candidates.map((c, i) => ( - - {i > 0 && " → "} - - {c} - - - ))} - {r.circuit_open.length > 0 && ( - (划线的上游当前处于熔断状态,将被跳过) - )} -
- - - {r.hurts_cache && ( - // 要直说 —— 它决定账单 -
- 该策略组在上游之间分配请求,prompt cache 命中率会下降。 -
- )} - {r.set.length > 0 && ( -
- 参数改写: - {r.set.map((s) => ( -
- {setText(s)} -
- ))} -
- )} -
- )} - - {/* **「为什么没走我以为的那条」才是用户在问的问题。** */} -
- 规则匹配明细 -
    - {r.trace.map((t) => ( -
  • - - {t.verdict === "matched" ? "✓" : t.verdict === "phase_two" ? "…" : "·"} - - {t.name} - {traceText(t)} -
  • - ))} -
-
-
- ); -} diff --git a/src/RequestDrawer.tsx b/src/RequestDrawer.tsx index 21c623bf..8261b654 100644 --- a/src/RequestDrawer.tsx +++ b/src/RequestDrawer.tsx @@ -18,7 +18,7 @@ import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { Collapsible, CollapsibleTrigger } from "@/ui/collapsible"; import { XIcon } from "lucide-react"; import { priceSourceDetail } from "./upstreams/labels"; -import { attemptText, formatLabel, quoteText } from "./labels"; +import { attemptText, formatLabel, quoteText, targetLabel } from "./labels"; import { Table, TableBody, @@ -282,7 +282,7 @@ export default function RequestDrawer({ 有用** */}
- {r.routing.group && } + {r.routing.group && }
尝试链
diff --git a/src/Routes.tsx b/src/Routes.tsx deleted file mode 100644 index 28951922..00000000 --- a/src/Routes.tsx +++ /dev/null @@ -1,465 +0,0 @@ -import { useId, useState } from "react"; -import { Tip } from "@/ui/tip"; -import { Checkbox } from "@/ui/checkbox"; -import { Field, FieldLabel } from "@/ui/field"; -import type { Overview, PatchOp, RouteView } from "./types"; -import { Button } from "@/ui/button"; -import { Input } from "@/ui/input"; -import { toast } from "sonner"; -import { patchConfig } from "./patch"; -import { conditionText } from "./labels"; -import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; -import { - Card, - CardAction, - CardDescription, - CardHeader, - CardTitle, -} from "@/ui/card"; -import { - AlertDialog, - AlertDialogCancel, - AlertDialogAction, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/ui/alert-dialog"; - -/** - * 路由。 - * - * **一条路由是一组按顺序求值的规则,一把密钥绑一条。**默认路由是 - * 「没绑定时走的那条」,不是「所有人都要过的那条」—— 这个区别是整个 - * 模型的支点:前者意味着求值永远只看一张规则表。 - * - * 在此之前这一页只能看不能建:`to` 能通过策略组的下拉改,而 `when` 的 - * 十三个条件、`set`、`deny`、`guard` 全部只读,新建一条规则更无从谈起。 - * **一个只能查看的路由页,等于没有路由这个功能。** - */ -export default function Routes({ - ov, - configVersion, - onChanged, -}: { - ov: Overview; - configVersion: string | null; - onChanged: () => void; -}) { - const [busy, setBusy] = useState(null); - const [adding, setAdding] = useState(false); - const [newName, setNewName] = useState(""); - const [confirmDelete, setConfirmDelete] = useState(null); - const [addRuleTo, setAddRuleTo] = useState(null); - - const routes = ov.routes ?? []; - const defaultRoute = ov.default_route ?? "默认"; - const targets = [ - ...ov.groups.map((g) => [g.name, `${g.name}(策略组)`] as const), - ...ov.providers.map((p) => [p.name, p.name] as const), - ]; - - async function patch(ops: PatchOp[], tag: string) { - if (!configVersion) { - toast.error("配置版本尚未读取,请稍后重试"); - return false; - } - setBusy(tag); - try { - await patchConfig(ops, configVersion); - onChanged(); - return true; - } catch (e) { - toast.error(typeof e === "string" ? e : String(e)); - return false; - } finally { - setBusy(null); - } - } - - return ( -
- {/* - 默认路由单独一块,因为它在模型里就是单独的一个字段 - (顶层的 `default_route`)—— 不是某条路由身上的标志。 - */} - {/* 标题 + 一个操作 + 一句说明 —— Card 的形状 */} - - - 默认路由 - - - void patch( - [{ op: "replace", path: "/default_route", value: e.target.value }], - "default", - ) - } - > - {routes.map((r) => ( - - {r.name} - - ))} - - - - 未绑定路由的密钥使用此路由;已绑定路由的密钥不经过此路由。 - - - - -
-
-

- 路由内的规则自上而下依次匹配,由第一条命中的规则决定转发目标。 -

- -
- - {adding && ( -
- setNewName(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Escape") setAdding(false); - }} - /> - - -
- )} - -
- {routes.map((r) => ( -
-
- {r.name} - {r.default && ( - - 默认 - - )} - - {/* - 绑了这条的密钥。默认路由这里通常是空的 —— 走它的人是 - 「没绑」,不是「绑了它」。把这件事说出来,否则空白读起来 - 像是「未被引用」。 - */} - {r.clients.length > 0 - ? `已绑定:${r.clients.join("、")}` - : r.default - ? "未绑定路由的密钥使用此路由" - : "尚无密钥绑定"} - - - 0 - ? `${r.clients.length} 个密钥绑定了此路由,删除后这些密钥将改用默认路由。` - : "删除此路由。" - } - > - - -
- - {addRuleTo === r.name && ( - setAddRuleTo(null)} - onCreate={async (item) => { - const ok = await patch( - [{ op: "append", path: `/routes/${r.name}/rules`, item }], - `rule-${r.name}`, - ); - if (ok) setAddRuleTo(null); - }} - /> - )} - -
    - {r.rules.map((rule, i) => ( -
  1. - {i + 1} - {rule.name} - - {rule.conditions.length === 0 ? ( - // 兜底规则要标出来。少了它,用户会以为「没有兜底」 - // 而反复调试一条其实一直在生效的规则。 - - 兜底 - - ) : ( - rule.conditions.map(conditionText).join(" 且 ") - )} - - - {rule.deny ? ( - 拒绝 - ) : rule.to ? ( - `→ ${rule.to}` - ) : ( - 仅改写参数 - )} - - -
  2. - ))} - {r.rules.length === 0 && ( -
  3. - 此路由尚无规则。绑定此路由的密钥发出的请求将全部失败。 -
  4. - )} -
-
- ))} -
- -
- - !o && setConfirmDelete(null)} - > - - - 删除路由「{confirmDelete?.name}」 - - {confirmDelete && confirmDelete.clients.length > 0 - ? `${confirmDelete.clients.join("、")} 绑定了此路由,删除后将改用默认路由。` - : "此路由未被任何密钥绑定,删除后不影响现有请求。"} - - - - 取消 - { - const r = confirmDelete; - setConfirmDelete(null); - if (!r) return; - // 先解绑,再删路由 —— **一次写入**。反过来的话,中间那一刻 - // 配置里有一把绑着不存在路由的密钥,而那是加载不了的。 - const ops: PatchOp[] = [ - ...r.clients.map( - (c): PatchOp => ({ - op: "replace", - path: `/clients/${c}/route`, - value: null, - }), - ), - { op: "remove", path: `/routes/${r.name}` }, - ]; - void patch(ops, r.name); - }} - > - 删除 - - - - -
- ); -} - -/** - * 加一条规则。 - * - * **只放最常用的三个条件**(模型、是否带工具、输入长度)。`when` 一共 - * 十三个维度,全铺开是一张没人读得完的表 —— 而剩下那些在文本模式里写 - * 一行就完事。这里要解决的是「新建一条规则」这件事本身不可能,不是 - * 「每个条件都得有个控件」。 - */ -function NewRule({ - route, - targets, - busy, - onCancel, - onCreate, -}: { - route: string; - targets: readonly (readonly [string, string])[]; - busy: boolean; - onCancel: () => void; - onCreate: (item: string) => void; -}) { - const uid = useId(); - const [name, setName] = useState(""); - const [model, setModel] = useState(""); - const [tools, setTools] = useState(false); - const [tokens, setTokens] = useState(""); - const [to, setTo] = useState(targets[0]?.[0] ?? ""); - - function build(): string { - const when: string[] = []; - if (model.trim()) when.push(`model: "${model.trim()}"`); - if (tools) when.push("tools: true"); - if (tokens.trim()) when.push(`input_tokens: "${tokens.trim()}"`); - const lines = [`name: ${name.trim()}`]; - if (when.length > 0) lines.push(`when: { ${when.join(", ")} }`); - lines.push(`to: ${to}`); - return lines.join("\n"); - } - - return ( -
-
- setName(e.target.value)} - /> - 转发至 - setTo(e.target.value)}> - {targets.map(([v, label]) => ( - - {label} - - ))} - -
- -
- 条件 - setModel(e.target.value)} - /> - setTokens(e.target.value)} - className="w-40 font-mono" - /> - - setTools(c === true)} - /> - 带工具调用 - - - - 留空即为兜底规则 - - -
- -
- - {route} / {build().replace(/\n/g, " ")} - - - -
-
- ); -} diff --git a/src/labels.ts b/src/labels.ts index 1456cec4..ac8590e7 100644 --- a/src/labels.ts +++ b/src/labels.ts @@ -38,6 +38,14 @@ export function groupKindLabel(kind: string): string { return GROUP_KINDS.find((k) => k.id === kind)?.label ?? kind; } +/** 内置策略组在配置里的名字。**界面上不出现它**,显示为「全部上游」 */ +export const ALL_UPSTREAMS = "__all__"; + +/** 规则去向、策略组、流量详情里的一个策略组或上游名 */ +export function targetLabel(name: string): string { + return name === ALL_UPSTREAMS ? "全部上游" : name; +} + /** 客户端和上游的格式。和上游协议同一个词表,认不出时原样显示 */ export function formatLabel(id: string): string { return PROTOCOLS.find((p) => p.id === id)?.label ?? id; @@ -81,15 +89,20 @@ const CONDITION_NAMES: Record = { max_tokens: "max_tokens", tool_count: "工具数", intent: "辅助请求", - provider_would_be: "预定上游", + provider_would_be: "选定上游", }; +/** 条件的名称。是否类条件用「满足」时的说法 */ +export function conditionName(field: string): string { + return FLAGS[field]?.[0] ?? CONDITION_NAMES[field] ?? field; +} + /** 值是比较式的条件 */ const COUNTS = new Set(["input_tokens", "max_tokens", "tool_count"]); /** 条件里写的值怎么念:辅助请求和格式换成名称,其余原样 */ function conditionValue(field: string, value: string): string { - if (field === "intent") return probeLabel(value); + if (field === "intent") return value === "assistant_internal" ? "任一辅助请求" : probeLabel(value); if (field === "dialect") return formatLabel(value); return value; } @@ -112,8 +125,13 @@ export function mismatchText(m: MismatchView): string { } const name = CONDITION_NAMES[m.field] ?? m.field; const want = m.want.map((v) => conditionValue(m.field, v)).join(" 或 "); - // 辅助请求为空说的是「这是用户自己发的请求」 - const got = m.field === "intent" && m.got === "" ? "用户请求" : conditionValue(m.field, m.got); + // 辅助请求为空说的是「这是用户自己发的请求」;max_tokens 为空是请求里没写 + const got = + m.field === "intent" && m.got === "" + ? "用户请求" + : m.field === "max_tokens" && m.got === "" + ? "未设置" + : conditionValue(m.field, m.got); // 数量条件写的是比较式(`>200k`),前面不加「为」 return COUNTS.has(m.field) ? `要求${name} ${want},实际为 ${got}` diff --git a/src/routing/DryRunDialog.tsx b/src/routing/DryRunDialog.tsx new file mode 100644 index 00000000..92b19d6b --- /dev/null +++ b/src/routing/DryRunDialog.tsx @@ -0,0 +1,424 @@ +import { useEffect, useId, useMemo, useState } from "react"; +import { CircleCheckIcon, CircleDotIcon, CircleMinusIcon } from "lucide-react"; +import { Alert, AlertDescription } from "@/ui/alert"; +import { Badge } from "@/ui/badge"; +import { Button } from "@/ui/button"; +import { Checkbox } from "@/ui/checkbox"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +import { Field, FieldLabel } from "@/ui/field"; +import { Input } from "@/ui/input"; +import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; +import { Spinner } from "@/ui/spinner"; +import { cn } from "@/lib/utils"; +import { + PROBES, + formatLabel, + groupKindLabel, + mismatchText, + setText, + targetLabel, + translatedText, +} from "@/labels"; +import type { DryRunResult, KnownModel, Overview, RouteInput, RuleTrace } from "@/types"; +import { errorText, skipLabel } from "@/upstreams/labels"; +import { FormItem } from "@/upstreams/parts"; +import { api } from "./api"; +import { ModelInput } from "./fields"; +import { DIALECTS, usersOf } from "./model"; + +/** 按什么求值:密钥使用的路由、指定的路由、路由对话框里还没保存的草稿 */ +export type DryRunTarget = + | { kind: "key" } + | { kind: "route"; name: string } + | { kind: "draft"; route: RouteInput; keys: string[] }; + +/** + * 试算。回答的不只是「会走到哪儿」,还有**「为什么没走我以为的那条」**: + * 每条规则的匹配情况都列出来。**只计算,不发出请求。** + */ +export function DryRunDialog({ + target, + ov, + models, + onClose, +}: { + target: DryRunTarget; + ov: Overview; + models: KnownModel[]; + onClose: () => void; +}) { + const uid = useId(); + const firstKey = + target.kind === "key" + ? (ov.clients[0]?.name ?? "") + : target.kind === "route" + ? (() => { + const r = ov.routes.find((x) => x.name === target.name); + return r ? (usersOf(r, ov.clients)[0] ?? "") : ""; + })() + : (target.keys[0] ?? ""); + const [client, setClient] = useState(firstKey); + const [model, setModel] = useState(models[0]?.id ?? "claude-sonnet-4-5"); + const [dialect, setDialect] = useState("anthropic"); + const [kTokens, setKTokens] = useState("8"); + const [maxTokens, setMaxTokens] = useState(""); + const [flags, setFlags] = useState({ cache: false, tools: false, image: false, thinking: false, stream: true }); + const [toolCount, setToolCount] = useState("5"); + const [intent, setIntent] = useState(""); + const [r, setR] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const keyRoute = (name: string) => + ov.clients.find((c) => c.name === name)?.route ?? ov.routes.find((x) => x.default)?.name ?? ""; + + const req = useMemo( + () => ({ + model: model.trim(), + client, + route: target.kind === "route" ? target.name : null, + draft: target.kind === "draft" ? target.route : null, + dialect, + input_tokens: Math.round((Number.parseFloat(kTokens) || 0) * 1000), + max_tokens: /^\d+$/.test(maxTokens.trim()) ? Number(maxTokens.trim()) : null, + cache: flags.cache, + tools: flags.tools, + tool_count: flags.tools ? Number.parseInt(toolCount, 10) || 0 : 0, + image: flags.image, + thinking: flags.thinking, + stream: flags.stream, + intent, + }), + [model, client, target, dialect, kTokens, maxTokens, flags, toolCount, intent], + ); + + // 输入一变就重算:只计算,不发请求,没有必要等一个按钮 + useEffect(() => { + if (!req.model) return; + let alive = true; + setBusy(true); + const t = setTimeout(() => { + api + .dryRun(req) + .then((res) => { + if (!alive) return; + setR(res); + setError(null); + }) + .catch((e) => alive && setError(errorText(e))) + .finally(() => alive && setBusy(false)); + }, 250); + return () => { + alive = false; + clearTimeout(t); + }; + }, [req]); + + const routeName = target.kind === "key" ? keyRoute(client) : target.kind === "route" ? target.name : target.route.name; + + return ( + !open && onClose()}> + + + 试算 + 按给定请求计算匹配结果。不发出请求,不产生费用。 + + +
+
+ {target.kind !== "key" && ( + +
+ {routeName} + {target.kind === "draft" && 未保存} +
+
+ )} + + setClient(e.target.value)} + > + {target.kind !== "key" && 不指定} + {ov.clients.map((c) => ( + + {c.name} + + ))} + + + + m.id)} /> + + + setDialect(e.target.value)} + > + {DIALECTS.map((d) => ( + + {formatLabel(d)} + + ))} + + +
+ +
+ setKTokens(e.target.value)} + /> + k +
+
+ + setMaxTokens(e.target.value)} + /> + +
+
+ {( + [ + ["cache", "带缓存"], + ["tools", "带工具"], + ["image", "带图片"], + ["thinking", "扩展思考"], + ["stream", "流式"], + ] as const + ).map(([k, label]) => ( + + setFlags((f) => ({ ...f, [k]: v === true }))} + /> + {label} + + ))} +
+ {flags.tools && ( + + setToolCount(e.target.value)} + /> + + )} + + setIntent(e.target.value)} + > + 无(用户请求) + {PROBES.map((p) => ( + + {p.label} + + ))} + + +
+ +
+ {error ? ( + + {error} + + ) : r ? ( + + ) : ( +

+ + 正在计算 +

+ )} +
+
+ + + {busy && r && } + + +
+
+ ); +} + +function Result({ r, ov, draft }: { r: DryRunResult; ov: Overview; draft: boolean }) { + const decided = r.trace.findIndex((t) => t.effect === "decide"); + const route = ov.routes.find((x) => x.name === r.route); + return ( + <> +
+ {headline(r)} + {r.outcome === "route" && r.strategy && {groupKindLabel(r.strategy)}} +
+ {r.outcome === "deny" && r.reason &&

原因:{r.reason}

} + +
+
路由
+
+ {r.route} + {!draft && route?.default && · 默认路由} + {draft && · 未保存的修改} +
+ {r.rule && ( + <> +
命中规则
+
+ {r.rule} + {decided >= 0 && · 第 {decided + 1} 条} +
+ + )} + {r.outcome === "route" && ( + <> +
尝试顺序
+
+ {r.candidates.map((c, i) => { + const open = r.circuit_open.includes(c); + const conv = r.converted.find((x) => x.provider === c); + return ( +
+ {i + 1} + {c} + {open && 熔断中,将跳过} + {conv && 需转换格式:{translatedText(conv)}} +
+ ); + })} +
+ + )} + {r.skipped.length > 0 && ( + <> +
已跳过
+
+ {r.skipped.map((s, i) => ( + + {i > 0 && "、"} + {s.provider} + ({skipLabel(s.reason)}) + + ))} +
+ + )} + {r.outcome === "route" && ( + <> +
参数改写
+
+ {r.set.length === 0 ? ( + 无 + ) : ( + r.set.map((s) => {setText(s)}) + )} +
+ + )} +
+ {r.hurts_cache && ( +

该策略组在上游之间分配请求,prompt cache 命中率会下降。

+ )} + +
+
规则匹配明细
+
    + {r.trace.map((t, i) => { + const v = traceView(t, decided); + return ( +
  • + + {v.icon === "hit" ? ( + + ) : v.icon === "later" ? ( + + ) : ( + + )} + + {i + 1} + + {t.name} + + + {v.text} + +
  • + ); + })} +
+
+ + ); +} + +function headline(r: DryRunResult): string { + switch (r.outcome) { + case "route": + return r.via_group + ? `转发至策略组「${targetLabel(r.via_group)}」` + : `转发至上游「${r.candidates[0] ?? ""}」`; + case "deny": + return "拒绝"; + case "unavailable": + return "选中的上游均无法服务此请求,请求将返回错误"; + default: + return "无规则命中,请求将返回错误"; + } +} + +/** 规则匹配明细里的一行 */ +function traceView( + t: RuleTrace, + decided: number, +): { text: string; tone: "ok" | "muted" | "warn"; icon: "hit" | "later" | "miss" } { + if (t.verdict === "matched") { + if (t.effect === "decide") return { text: "命中 · 决定去向", tone: "ok", icon: "hit" }; + if (t.effect === "apply") return { text: "命中 · 应用改写参数或安全要求", tone: "ok", icon: "hit" }; + return { + text: decided >= 0 ? `命中 · 去向已由第 ${decided + 1} 条决定` : "命中", + tone: "muted", + icon: "hit", + }; + } + if (t.verdict === "phase_two") return { text: "选定上游后判断,试算不计算此条", tone: "muted", icon: "later" }; + if (t.error) return { text: t.error, tone: "warn", icon: "miss" }; + return { text: t.mismatch ? `未命中:${mismatchText(t.mismatch)}` : "未命中", tone: "muted", icon: "miss" }; +} diff --git a/src/routing/GroupDialog.tsx b/src/routing/GroupDialog.tsx new file mode 100644 index 00000000..5a188f93 --- /dev/null +++ b/src/routing/GroupDialog.tsx @@ -0,0 +1,279 @@ +import { useState } from "react"; +import { GripVerticalIcon } from "lucide-react"; +import { Alert, AlertDescription } from "@/ui/alert"; +import { Badge } from "@/ui/badge"; +import { Button } from "@/ui/button"; +import { Checkbox } from "@/ui/checkbox"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +import { Input } from "@/ui/input"; +import { Spinner } from "@/ui/spinner"; +import { Switch } from "@/ui/switch"; +import { cn } from "@/lib/utils"; +import { groupKindLabel } from "@/labels"; +import type { GroupKind, Overview } from "@/types"; +import { billingLabel, errorText, protocolLabel } from "@/upstreams/labels"; +import { Boxed, FormItem, Note, RadioRow } from "@/upstreams/parts"; +import { api } from "./api"; +import { groupRefs } from "./GroupTable"; +import { STRATEGIES, move } from "./model"; +import { useReorder } from "./useReorder"; + +export type GroupDialogMode = + | { kind: "create" } + | { kind: "edit"; name: string } + | { kind: "duplicate"; from: string }; + +/** + * 新建、编辑、复制策略组。 + * + * 左边是策略,右边是成员 —— 成员的先后在「按顺序」「手动选择」里就是优先级, + * 所以可以拖动;手动选择还要在已选成员里定一个优先使用的。 + */ +export function GroupDialog({ + mode, + ov, + configVersion, + onClose, + onSaved, +}: { + mode: GroupDialogMode; + ov: Overview; + configVersion: string | null; + onClose: () => void; + onSaved: (name: string) => void; +}) { + const source = + mode.kind === "edit" + ? ov.groups.find((g) => g.name === mode.name) + : mode.kind === "duplicate" + ? ov.groups.find((g) => g.name === mode.from) + : undefined; + const [name, setName] = useState( + mode.kind === "edit" ? mode.name : mode.kind === "duplicate" ? `${mode.from} 副本` : "", + ); + const [kind, setKind] = useState(source?.kind ?? "fallback"); + const [order, setOrder] = useState(() => { + const members = source?.providers ?? []; + return [...members, ...ov.providers.map((p) => p.name).filter((n) => !members.includes(n))]; + }); + const [members, setMembers] = useState(source?.providers ?? []); + const [selected, setSelected] = useState(source?.selected ?? null); + const [sticky, setSticky] = useState(source?.session_affinity ?? true); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const reorder = useReorder((from, to) => setOrder((o) => move(o, from, to))); + + const chosen = order.filter((n) => members.includes(n)); + const preferred = + kind === "select" ? (selected && chosen.includes(selected) ? selected : (chosen[0] ?? null)) : null; + const refs = mode.kind === "edit" ? groupRefs(ov, mode.name) : []; + const trimmed = name.trim(); + const taken = + ov.groups.some((g) => g.name === trimmed && !(mode.kind === "edit" && g.name === mode.name)) || + ov.providers.some((p) => p.name === trimmed); + const missing = !trimmed + ? "填写名称" + : trimmed.startsWith("__") + ? "名称不能以 __ 开头" + : taken + ? `名称「${trimmed}」已被使用` + : chosen.length === 0 + ? "至少选择一个上游" + : null; + + async function save() { + setSaving(true); + setError(null); + try { + const save = { + group: { + name: trimmed, + kind, + providers: chosen, + selected: preferred, + session_affinity: kind === "load-balance" ? sticky : true, + }, + base_version: configVersion ?? undefined, + }; + if (mode.kind === "edit") await api.updateGroup(mode.name, save); + else await api.createGroup(save); + onSaved(trimmed); + } catch (e) { + setError(errorText(e)); + setSaving(false); + } + } + + const title = + mode.kind === "edit" ? `编辑策略组「${mode.name}」` : mode.kind === "duplicate" ? "复制策略组" : "新建策略组"; + + return ( + !open && onClose()}> + + + {title} + + {refs.length > 0 + ? `被${refs.map((r) => `「${r.route} · ${r.rule}」`).join("、")}引用。` + : "规则可以转发至策略组,由策略决定使用其中哪个上游。"} + + + +
+
+ + setName(e.target.value)} /> + +
+ 策略 +
+ {STRATEGIES.map((s) => ( + + {s.desc} + + 影响 prompt cache + + + ) : ( + s.desc + ) + } + onSelect={() => setKind(s.id)} + /> + ))} +
+
+ {kind === "load-balance" && ( +
+ + + {sticky + ? "同一会话固定使用同一上游,prompt cache 保持命中。" + : "长会话的 prompt cache 将频繁失效,费用上升。"} + +
+ )} +
+ +
+
+ 成员 + 已选 {chosen.length} 个 +
+ {ov.providers.length === 0 ? ( + 尚无上游。 + ) : ( + + + + + + {kind === "select" && } + + + + {order.map((n, i) => { + const p = ov.providers.find((x) => x.name === n); + const on = members.includes(n); + const mark = reorder.marker(i, order.length); + return ( + + + + + {kind === "select" && ( + + )} + + ); + })} + +
+ + 上游优先使用
+ + + + setMembers((m) => (v === true ? [...m, n] : m.filter((x) => x !== n))) + } + /> + +
{n}
+ {p && ( +
+ {protocolLabel(p.protocol)} · {billingLabel(p.billing ?? p.billing_effective)} + {p.disabled && " · 已停用"} +
+ )} +
+ {on && ( + setSelected(n)} + /> + )} +
+
+ )} + + {kind === "select" + ? "拖动调整顺序。选定的上游不可用时,按顺序使用其余成员。" + : kind === "fallback" + ? "拖动调整顺序:依次使用,前一个不可用时使用下一个。" + : "拖动调整顺序。排序依据相同时按此顺序。"} + +
+
+ + {error && ( + + {error} + + )} + + + {missing && {missing}} + + + +
+
+ ); +} diff --git a/src/routing/GroupTable.tsx b/src/routing/GroupTable.tsx new file mode 100644 index 00000000..ba66756a --- /dev/null +++ b/src/routing/GroupTable.tsx @@ -0,0 +1,163 @@ +import { Fragment } from "react"; +import { Badge } from "@/ui/badge"; +import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/ui/table"; +import { cn } from "@/lib/utils"; +import { groupKindLabel } from "@/labels"; +import type { GroupView, Overview } from "@/types"; + +export interface GroupActions { + edit: (name: string) => void; + prefer: (group: GroupView, provider: string) => void; + duplicate: (name: string) => void; + locate: (name: string) => void; + remove: (name: string) => void; + showUpstreams: () => void; +} + +/** 引用了这个策略组的规则:「路由 · 规则」 */ +export function groupRefs(ov: Overview, name: string): { route: string; rule: string }[] { + return ov.routes.flatMap((r) => + r.rules.filter((x) => x.to === name).map((x) => ({ route: r.name, rule: x.name })), + ); +} + +/** + * 策略组列表。「全部上游」是内置的,排第一行:成员随上游列表更新,不能编辑。 + */ +export function GroupTable({ ov, actions }: { ov: Overview; actions: GroupActions }) { + const groups = [...ov.groups].sort((a, b) => Number(b.builtin) - Number(a.builtin)); + return ( + + + + 名称 + 策略 + 成员 + 引用 + + + + + {groups.map((g) => { + const items = menu(g, actions); + const refs = groupRefs(ov, g.name); + return ( + + (g.builtin ? actions.showUpstreams() : actions.edit(g.name))} + className="cursor-default" + > + +
+ {g.builtin ? "全部上游" : g.name} + {g.builtin && 内置} +
+
+ +
{groupKindLabel(g.kind)}
+ {g.hurts_cache &&
影响 prompt cache
} +
+ + + {g.builtin ? ( +
按上游列表顺序
+ ) : g.kind === "select" && g.selected ? ( +
优先使用 {g.selected}
+ ) : null} +
+ + {refs.length === 0 ? ( + 未被引用 + ) : ( +
`${r.route} · ${r.rule}`).join(";")}> + {refs.map((r, i) => ( + + {i > 0 && ";"} + {r.route} · {r.rule} + + ))} +
+ )} +
+ + + +
+
+ ); + })} +
+
+ ); +} + +/** + * 成员。**有先后的用「→」连**(按顺序、手动选择:前一个不可用才用下一个), + * 按运行时数字排的(轮询、延迟最低、费用最低)不连 —— 那几种的次序不是写死的。 + */ +function Members({ g }: { g: GroupView }) { + const ordered = g.kind === "fallback" || g.kind === "select"; + const list = + g.kind === "select" && g.selected + ? [g.selected, ...g.providers.filter((p) => p !== g.selected)] + : g.providers; + return ( +
+ {list.map((p, i) => ( + // 箭头和它后面的成员放在一起换行,续行以「→」开头,读得出是接着上一行 + + {i > 0 && ordered && →} + + {g.kind === "select" && p === g.selected && ( + + )} + {p} + + + ))} +
+ ); +} + +function menu(g: GroupView, a: GroupActions): MenuItems { + if (g.builtin) { + return [{ kind: "item", label: "前往上游页", onSelect: a.showUpstreams }]; + } + return [ + { kind: "item", label: "编辑…", onSelect: () => a.edit(g.name) }, + ...(g.kind === "select" + ? ([ + { + kind: "sub", + label: "优先使用", + choices: g.providers.map((p) => ({ + label: p, + checked: p === g.selected, + onSelect: () => a.prefer(g, p), + })), + }, + ] as MenuItems) + : []), + { kind: "item", label: "复制…", onSelect: () => a.duplicate(g.name) }, + { kind: "sep" }, + { kind: "item", label: "在配置文件中定位", onSelect: () => a.locate(g.name) }, + { kind: "sep" }, + { kind: "item", label: "删除…", onSelect: () => a.remove(g.name), danger: true }, + ]; +} diff --git a/src/routing/RouteConfirmDialogs.tsx b/src/routing/RouteConfirmDialogs.tsx new file mode 100644 index 00000000..7216175a --- /dev/null +++ b/src/routing/RouteConfirmDialogs.tsx @@ -0,0 +1,174 @@ +import { useState } from "react"; +import { KeyRoundIcon } from "lucide-react"; +import { + AlertDialog, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/ui/alert-dialog"; +import { Button } from "@/ui/button"; +import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; +import { Spinner } from "@/ui/spinner"; +import type { Overview } from "@/types"; +import { errorText } from "@/upstreams/labels"; +import { FormItem, Note } from "@/upstreams/parts"; +import { usersOf } from "./model"; + +/** 一列密钥,右边可以附一句说明 */ +function KeyList({ rows }: { rows: { name: string; note?: string }[] }) { + return ( +
+ {rows.map((r) => ( +
+ + {r.name} + + {r.note && {r.note}} +
+ ))} +
+ ); +} + +/** + * 设为默认路由。**没指定路由的密钥全都跟着换**,所以把它们列出来再确认。 + */ +export function SetDefaultDialog({ + ov, + name, + onConfirm, + onClose, +}: { + ov: Overview; + name: string; + onConfirm: () => Promise; + onClose: () => void; +}) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const current = ov.routes.find((r) => r.default); + const moving = ov.clients.filter((c) => !c.route).map((c) => c.name); + + async function run() { + setBusy(true); + setError(null); + try { + await onConfirm(); + } catch (e) { + setError(errorText(e)); + setBusy(false); + } + } + + return ( + !open && onClose()}> + + + 将「{name}」设为默认路由 + + {moving.length > 0 ? "未指定路由的密钥将改用此路由。" : "当前所有密钥均已指定路由,更换默认路由不影响现有密钥。"} + + + {moving.length > 0 && ( + ({ name: k, note: `${current?.name ?? "默认"} → ${name}` }))} /> + )} + {current && 「{current.name}」保留为普通路由,可继续指定给密钥。} + {error && {error}} + + 取消 + + + + + ); +} + +/** + * 删除路由。使用它的密钥**由用户选**改用哪一条,默认选项是默认路由 —— + * 一条限制用途的路由被删掉之后悄悄改走默认路由,限制也就随之没了。 + */ +export function DeleteRouteDialog({ + ov, + name, + onConfirm, + onClose, +}: { + ov: Overview; + name: string; + /** `reassignTo` 为空:改用默认路由 */ + onConfirm: (reassignTo: string | null) => Promise; + onClose: () => void; +}) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [target, setTarget] = useState(""); + const route = ov.routes.find((r) => r.name === name); + const users = route ? usersOf(route, ov.clients) : []; + const fallback = ov.routes.find((r) => r.default); + const others = ov.routes.filter((r) => r.name !== name && !r.default); + + async function run() { + setBusy(true); + setError(null); + try { + await onConfirm(target || null); + } catch (e) { + setError(errorText(e)); + setBusy(false); + } + } + + return ( + !open && onClose()}> + + + 删除路由「{name}」 + + {users.length > 0 + ? "以下密钥使用此路由,删除后改用所选路由。可在版本历史中恢复。" + : "此路由未被密钥使用。删除后可在版本历史中恢复。"} + + + {users.length > 0 && ( + <> + ({ name: k }))} /> + + setTarget(e.target.value)} + > + + {fallback ? `${fallback.name}(默认路由)` : "默认路由"} + + {others.map((r) => ( + + {r.name} + + ))} + + + + )} + {error && {error}} + + 取消 + + + + + ); +} diff --git a/src/routing/RouteDialog.tsx b/src/routing/RouteDialog.tsx new file mode 100644 index 00000000..7bad9471 --- /dev/null +++ b/src/routing/RouteDialog.tsx @@ -0,0 +1,446 @@ +import { useMemo, useState } from "react"; +import { CircleAlertIcon, FlaskConicalIcon, GripVerticalIcon, PlusIcon } from "lucide-react"; +import { Alert, AlertDescription } from "@/ui/alert"; +import { Badge } from "@/ui/badge"; +import { Button } from "@/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +import { Input } from "@/ui/input"; +import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; +import { Spinner } from "@/ui/spinner"; +import { cn } from "@/lib/utils"; +import { ALL_UPSTREAMS, conditionText, targetLabel } from "@/labels"; +import type { KnownModel, Overview, RouteInput } from "@/types"; +import { errorText } from "@/upstreams/labels"; +import { Boxed, FormItem, NameChips } from "@/upstreams/parts"; +import { api } from "./api"; +import { ToggleChips } from "./fields"; +import { + addOnsText, + blankRule, + copyDraft, + describeTarget, + draftFromView, + draftNotes, + draftToInput, + hasCatchAll, + insertIndex, + liftShadowed, + move, + usersOf, + type RuleDraft, +} from "./model"; +import { RuleDialog } from "./RuleDialog"; +import { useReorder } from "./useReorder"; + +export type RouteDialogMode = + | { kind: "create" } + | { kind: "edit"; name: string } + | { kind: "duplicate"; from: string }; + +/** 正在编辑的规则:`index` 为空是新加的,放在 `at` */ +type Editing = null | { index: number | null; at: number; draft: RuleDraft }; + +/** + * 新建、编辑、复制路由。 + * + * **一次保存就是整条路由**:名称、使用它的密钥、规则的顺序,一个配置版本。 + * 取消不写入任何东西。规则在嵌套的规则对话框里编辑,那边的「保存」只改 + * 这里的草稿。 + */ +export function RouteDialog({ + mode, + ov, + models, + configVersion, + onChanged, + onClose, + onSaved, + onDryRun, +}: { + mode: RouteDialogMode; + ov: Overview; + models: KnownModel[]; + configVersion: string | null; + onChanged: () => void; + onClose: () => void; + onSaved: () => void; + /** 按对话框里还没保存的内容试算 */ + onDryRun: (draft: RouteInput, keys: string[]) => void; +}) { + const source = + mode.kind === "edit" + ? ov.routes.find((r) => r.name === mode.name) + : mode.kind === "duplicate" + ? ov.routes.find((r) => r.name === mode.from) + : undefined; + const isDefault = mode.kind === "edit" && !!source?.default; + const original = mode.kind === "edit" && source ? usersOf(source, ov.clients) : []; + + const [name, setName] = useState( + mode.kind === "edit" ? mode.name : mode.kind === "duplicate" ? `${mode.from} 副本` : "", + ); + const [keys, setKeys] = useState( + mode.kind === "edit" && source ? ov.clients.filter((c) => c.route === source.name).map((c) => c.name) : [], + ); + const [rules, setRules] = useState(() => + source ? source.rules.map(draftFromView) : [{ ...blankRule(ALL_UPSTREAMS), name: "兜底" }], + ); + const [probes, setProbes] = useState([]); + const [editing, setEditing] = useState(null); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const reorder = useReorder((from, to) => setRules((r) => move(r, from, to))); + + const notes = useMemo(() => draftNotes(rules), [rules]); + const shadowed = rules.filter((_, i) => notes[i]!.shadowed); + const trimmed = name.trim(); + const takenByOther = ov.routes.some( + (r) => r.name === trimmed && !(mode.kind === "edit" && r.name === mode.name), + ); + const missing = !trimmed + ? "填写名称" + : trimmed.startsWith("__") + ? "名称不能以 __ 开头" + : takenByOther + ? `名称「${trimmed}」已被使用` + : null; + + // 保存之后密钥的去向变化,说在字段下面 + const joining = keys.filter( + (k) => mode.kind !== "edit" || ov.clients.find((c) => c.name === k)?.route !== mode.name, + ); + const leaving = + mode.kind === "edit" && !isDefault ? original.filter((k) => !keys.includes(k)) : []; + + function input(): RouteInput { + return { name: trimmed, rules: rules.map(draftToInput) }; + } + + async function save() { + setSaving(true); + setError(null); + try { + const save = { + route: input(), + base_version: configVersion ?? undefined, + // 默认路由的使用者是「没指定路由的密钥」,这里不改 + keys: isDefault ? undefined : keys, + route_probes: probes, + }; + if (mode.kind === "edit") await api.updateRoute(mode.name, save); + else await api.createRoute(save); + onSaved(); + } catch (e) { + setError(errorText(e)); + setSaving(false); + } + } + + function add(at: number, prefill?: Partial) { + setEditing({ index: null, at, draft: { ...blankRule(), ...prefill } }); + } + + function rowMenu(i: number): MenuItems { + return [ + { kind: "item", label: "编辑…", onSelect: () => setEditing({ index: i, at: i, draft: rules[i]! }) }, + { kind: "item", label: "在上方插入…", onSelect: () => add(i) }, + { + kind: "item", + label: "复制", + onSelect: () => + setRules((r) => { + const c = { ...copyDraft(r[i]!), name: uniqueName(`${r[i]!.name} 副本`, r) }; + return [...r.slice(0, i + 1), c, ...r.slice(i + 1)]; + }), + }, + { kind: "sep" }, + { kind: "item", label: "上移", disabled: i === 0, onSelect: () => setRules((r) => move(r, i, i - 1)) }, + { + kind: "item", + label: "下移", + disabled: i === rules.length - 1, + onSelect: () => setRules((r) => move(r, i, i + 1)), + }, + { kind: "sep" }, + { kind: "item", label: "删除", danger: true, onSelect: () => setRules((r) => r.filter((_, j) => j !== i)) }, + ]; + } + + const title = + mode.kind === "edit" ? `编辑路由「${mode.name}」` : mode.kind === "duplicate" ? "复制路由" : "新建路由"; + + return ( + !open && onClose()}> + + + {title} + 请求自上而下逐条匹配,第一条命中的转发或拒绝规则决定去向。 + + +
+
+ + setName(e.target.value)} + /> + + {isDefault ? ( + +
+ +
+
+ ) : ( + +
+ ({ + id: c.name, + title: + c.route && c.route !== source?.name + ? `当前使用路由「${c.route}」` + : !c.route + ? "当前使用默认路由" + : undefined, + }))} + value={keys} + onChange={setKeys} + /> +
+
+ )} +
+ +
+
+ 规则 + {rules.length} +
+ + +
+ + + + + + + + + + + + + {rules.map((r, i) => { + const n = notes[i]!; + const mark = reorder.marker(i, rules.length); + const items = rowMenu(i); + return ( + + setEditing({ index: i, at: i, draft: r })} + className={cn( + "cursor-default border-b border-border last:border-b-0 hover:bg-muted/40", + reorder.dragging === i && "opacity-50", + mark === "before" && "shadow-[inset_0_2px_0_var(--color-foreground)]", + mark === "after" && "shadow-[inset_0_-2px_0_var(--color-foreground)]", + )} + > + + + + + + + + + ); + })} + {rules.length === 0 && ( + + + + )} + +
+ #规则条件命中后 +
+ + {i + 1} +
+ {r.name} + {n.shadowed && 不会生效} + {n.phaseTwo && 选定上游后} +
+
+ {r.conditions.length === 0 ? ( + 全部请求(兜底) + ) : ( + conditionsText(r) + )} + + + + +
+ 尚无规则。 +
+
+ + {shadowed.length > 0 && ( +
+ + + {shadowed.map((r) => `「${r.name}」`).join("、")}位于兜底规则之后,转发与拒绝不会生效。 + + +
+ )} + {!hasCatchAll(rules) && ( +
+ + 尚无兜底规则。未命中任何规则的请求将返回错误。 + +
+ )} +
+
+ + {error && ( + + {error} + + )} + + + {missing && {missing}} + + + + + {editing && ( + j !== editing.index).map((x) => x.name.trim())} + ov={ov} + models={models} + configVersion={configVersion} + onChanged={onChanged} + onClose={() => setEditing(null)} + onSave={(d, routeProbes) => { + setRules((r) => + editing.index == null + ? [...r.slice(0, editing.at), d, ...r.slice(editing.at)] + : r.map((x, j) => (j === editing.index ? d : x)), + ); + if (routeProbes.length) setProbes((p) => [...new Set([...p, ...routeProbes])]); + setEditing(null); + }} + /> + )} + +
+ ); +} + +function conditionsText(r: RuleDraft): string { + return r.conditions.map(conditionText).join(" 且 "); +} + +/** 「命中后」一栏:去向(或拒绝、继续匹配),次行是去向的说明或附加项 */ +function Action({ r, ov }: { r: RuleDraft; ov: Overview }) { + const addOns = addOnsText(r); + if (r.action === "deny") { + return ( +
+
拒绝
+
+ {r.deny} +
+
+ ); + } + if (r.action === "continue") { + return ( +
+
继续匹配
+
+ {addOns} +
+
+ ); + } + const sub = [describeTarget(r.to, ov.groups, ov.providers), addOns].filter(Boolean).join(" · "); + return ( +
+
+ → + {targetLabel(r.to)} +
+
+ {sub} +
+
+ ); +} + +/** `兜底`、`兜底 2`:同一条路由里规则名不能重复 */ +function uniqueName(base: string, rules: RuleDraft[]): string { + const taken = new Set(rules.map((r) => r.name.trim())); + if (!taken.has(base)) return base; + for (let i = 2; ; i++) if (!taken.has(`${base} ${i}`)) return `${base} ${i}`; +} diff --git a/src/routing/RouteTable.tsx b/src/routing/RouteTable.tsx new file mode 100644 index 00000000..acf6b495 --- /dev/null +++ b/src/routing/RouteTable.tsx @@ -0,0 +1,129 @@ +import { Badge } from "@/ui/badge"; +import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/ui/table"; +import type { Overview, RouteView } from "@/types"; +import { NameChips } from "@/upstreams/parts"; +import { flowOf, routeSummary, usersOf } from "./model"; + +export interface RouteActions { + edit: (name: string) => void; + dryRun: (name: string) => void; + duplicate: (name: string) => void; + setDefault: (name: string) => void; + locate: (name: string) => void; + remove: (name: string) => void; +} + +/** + * 路由列表。**只读**:改任何东西都走对话框。 + * + * 默认路由固定在第一行 —— 没指定路由的密钥都走它,它是读这张表的起点。 + * 「规则」一栏按顺序写出决定去向的规则,不打开对话框也能看出一条路由做什么。 + */ +export function RouteTable({ ov, actions }: { ov: Overview; actions: RouteActions }) { + const routes = [...ov.routes].sort((a, b) => Number(b.default) - Number(a.default)); + return ( + + + + 路由 + 使用密钥 + 规则 + + + + + {routes.map((r) => { + const items = menu(r, actions); + const users = usersOf(r, ov.clients); + const summary = routeSummary(r); + return ( + + actions.edit(r.name)} + className="cursor-default" + > + +
+ {r.name} + {r.default && 默认} +
+
+ + + + + +
+ {summary.text} +
+
+ + + +
+
+ ); + })} +
+
+ ); +} + +/** 「长上下文 → 长上下文池 · 兜底 → 主力」。截断,悬停看全 */ +function Flow({ route }: { route: RouteView }) { + const flow = flowOf(route); + if (flow.length === 0) { + return
无决定去向的规则
; + } + const title = flow.map((f) => `${f.rule} → ${f.target ?? "拒绝"}`).join(" · "); + return ( +
+ {flow.map((f, i) => ( + + {i > 0 && ·} + {f.rule} + → + {f.target ? ( + {f.target} + ) : ( + 拒绝 + )} + + ))} +
+ ); +} + +function menu(r: RouteView, a: RouteActions): MenuItems { + return [ + { kind: "item", label: "编辑…", onSelect: () => a.edit(r.name) }, + { kind: "item", label: "试算…", onSelect: () => a.dryRun(r.name) }, + { kind: "item", label: "复制…", onSelect: () => a.duplicate(r.name) }, + { kind: "sep" }, + ...(r.default + ? [] + : ([{ kind: "item", label: "设为默认路由", onSelect: () => a.setDefault(r.name) }] as MenuItems)), + // 网关补出来的默认路由不在配置文件里,定位不到 + ...(r.builtin + ? [] + : ([{ kind: "item", label: "在配置文件中定位", onSelect: () => a.locate(r.name) }] as MenuItems)), + ...(r.default && r.builtin ? [] : ([{ kind: "sep" }] as MenuItems)), + { + kind: "item", + label: "删除…", + onSelect: () => a.remove(r.name), + danger: true, + // 默认路由不能删:没指定路由的密钥要有地方去 + disabled: r.default, + }, + ]; +} diff --git a/src/routing/RoutingPage.tsx b/src/routing/RoutingPage.tsx new file mode 100644 index 00000000..cf68cd14 --- /dev/null +++ b/src/routing/RoutingPage.tsx @@ -0,0 +1,251 @@ +import { useEffect, useState } from "react"; +import { FlaskConicalIcon, PlusIcon } from "lucide-react"; +import { toast } from "sonner"; +import { Button } from "@/ui/button"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from "@/ui/empty"; +import { IconRoute } from "@/ui/icons"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; +import type { GroupView, KnownModel, Overview, RouteInput } from "@/types"; +import { DeleteDialog } from "@/upstreams/DeleteDialog"; +import { errorText } from "@/upstreams/labels"; +import { api } from "./api"; +import { DryRunDialog, type DryRunTarget } from "./DryRunDialog"; +import { GroupDialog, type GroupDialogMode } from "./GroupDialog"; +import { GroupTable, groupRefs } from "./GroupTable"; +import { DeleteRouteDialog, SetDefaultDialog } from "./RouteConfirmDialogs"; +import { RouteDialog, type RouteDialogMode } from "./RouteDialog"; +import { RouteTable } from "./RouteTable"; + +export type RoutingTab = "routes" | "groups"; + +type DialogState = + | null + | { kind: "route"; mode: RouteDialogMode } + | { kind: "set-default"; name: string } + | { kind: "delete-route"; name: string } + | { kind: "group"; mode: GroupDialogMode } + | { kind: "delete-group"; name: string }; + +/** + * 路由页:路由、策略组两个标签。 + * + * **路由是配给密钥的**:一把密钥使用一条路由,没指定的使用默认路由。策略组 + * 只被路由规则引用,所以和路由放在同一页,引用关系在页内闭合 —— 和上游页里 + * 代理、价目表的做法一样。列表只读,新建与编辑都在对话框里完成,一次保存 + * 一个配置版本。试算是针对路由的工具,放在工具栏和行菜单里。 + */ +export default function RoutingPage({ + ov, + configVersion, + onChanged, + onOpenConfigFile, + onNavigate, +}: { + ov: Overview; + configVersion: string | null; + onChanged: () => void; + onOpenConfigFile: (focus: string | null) => void; + onNavigate: (tab: string) => void; +}) { + const [tab, setTab] = useState("routes"); + const [dialog, setDialog] = useState(null); + // 试算叠在路由对话框上面时,两个要同时开着 —— 单独一份状态 + const [dryRun, setDryRun] = useState(null); + const [models, setModels] = useState([]); + + // 模型建议(规则条件、改写参数、试算)。拿不到不影响任何功能,照常可以手写。 + // **跟着各上游的模型清单重读**,不只是配置版本:后台问完一家,建议里就该有它的模型 + const catalogKey = ov.providers.map((p) => `${p.name}:${p.model_source}:${p.model_count}`).join("|"); + useEffect(() => { + api + .knownModels() + .then(setModels) + .catch(() => {}); + }, [configVersion, catalogKey]); + + const done = () => { + setDialog(null); + onChanged(); + }; + + async function prefer(g: GroupView, provider: string) { + try { + await api.updateGroup(g.name, { + group: { + name: g.name, + kind: g.kind, + providers: g.providers, + selected: provider, + session_affinity: g.session_affinity ?? true, + }, + base_version: configVersion ?? undefined, + }); + onChanged(); + } catch (e) { + toast.error(errorText(e)); + } + } + + if (ov.providers.length === 0) { + return ( +
+ + + + + + 尚无上游 + + 路由规则将请求转发至上游或策略组。新建上游后,默认路由将请求依次转发至全部上游。 + + + + + + +
+ ); + } + + return ( +
+ setTab(v as RoutingTab)}> +
+ + + 路由 + + + 策略组 + + +
+ {tab === "routes" ? ( + <> + + + + ) : ( + + )} +
+ + + setDialog({ kind: "route", mode: { kind: "edit", name } }), + dryRun: (name) => setDryRun({ kind: "route", name }), + duplicate: (name) => setDialog({ kind: "route", mode: { kind: "duplicate", from: name } }), + setDefault: (name) => setDialog({ kind: "set-default", name }), + locate: (name) => onOpenConfigFile(name), + remove: (name) => setDialog({ kind: "delete-route", name }), + }} + /> + + + + setDialog({ kind: "group", mode: { kind: "edit", name } }), + prefer: (g, p) => void prefer(g, p), + duplicate: (name) => setDialog({ kind: "group", mode: { kind: "duplicate", from: name } }), + locate: (name) => onOpenConfigFile(name), + remove: (name) => setDialog({ kind: "delete-group", name }), + showUpstreams: () => onNavigate("upstreams"), + }} + /> + + + + {dialog?.kind === "route" && ( + setDialog(null)} + onSaved={done} + onDryRun={(route: RouteInput, keys: string[]) => setDryRun({ kind: "draft", route, keys })} + /> + )} + {dialog?.kind === "set-default" && ( + setDialog(null)} + onConfirm={async () => { + await api.setDefaultRoute(dialog.name, configVersion); + done(); + }} + /> + )} + {dialog?.kind === "delete-route" && ( + setDialog(null)} + onConfirm={async (reassignTo) => { + await api.deleteRoute(dialog.name, configVersion, reassignTo); + done(); + }} + /> + )} + {dialog?.kind === "group" && ( + setDialog(null)} + onSaved={done} + /> + )} + {dialog?.kind === "delete-group" && ( + ({ + kind: "reference" as const, + ref: { kind: "rule_target" as const, route: r.route, rule: r.rule }, + }))} + consequence="删除后,此策略组将从配置文件中移除,可在版本历史中恢复。" + onDelete={async () => { + await api.deleteGroup(dialog.name, configVersion); + done(); + }} + onClose={() => setDialog(null)} + onShow={(r) => { + if (r.kind !== "reference" || r.ref.kind === "group") return; + setTab("routes"); + setDialog({ kind: "route", mode: { kind: "edit", name: r.ref.route } }); + }} + /> + )} + {dryRun && setDryRun(null)} />} +
+ ); +} + +function Count({ n }: { n: number }) { + return {n}; +} diff --git a/src/routing/RuleDialog.tsx b/src/routing/RuleDialog.tsx new file mode 100644 index 00000000..34dd2832 --- /dev/null +++ b/src/routing/RuleDialog.tsx @@ -0,0 +1,540 @@ +import { useMemo, useState, type ReactNode } from "react"; +import { ChevronDownIcon, ChevronRightIcon, PlusIcon, XIcon } from "lucide-react"; +import { Button } from "@/ui/button"; +import { Checkbox } from "@/ui/checkbox"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/ui/dialog"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/ui/dropdown-menu"; +import { Field, FieldLabel } from "@/ui/field"; +import { Input } from "@/ui/input"; +import { NativeSelect, NativeSelectOptGroup, NativeSelectOption } from "@/ui/native-select"; +import { cn } from "@/lib/utils"; +import { PROBES, conditionName, formatLabel, probeLabel, targetLabel } from "@/labels"; +import type { ConditionView, KnownModel, Overview } from "@/types"; +import { globMatch } from "@/upstreams/glob"; +import { REDACT_KINDS } from "@/upstreams/labels"; +import { FormItem, Note, Segmented } from "@/upstreams/parts"; +import { GroupDialog } from "./GroupDialog"; +import { ModelInput, ToggleChips } from "./fields"; +import { + COMPARE_OPS, + COND_FIELDS, + DIALECTS, + PROBE_IDS, + addOnsText, + blankCondition, + condField, + describeTarget, + isPhaseTwo, + ruleProblem, + splitCompare, + type Action, + type RuleDraft, +} from "./model"; + +/** 目标下拉里「新建策略组…」那一项的值。只活在这个下拉里,不会写进配置 */ +const NEW_GROUP = "::new-group"; + +/** + * 添加与编辑一条规则。 + * + * **按读规则的顺序排**:条件(什么样的请求)→ 命中后(转发、拒绝,或继续 + * 匹配)→ 附加项(改写参数、安全要求)。保存只更新路由对话框里的草稿, + * 路由对话框保存时才写入配置。 + */ +export function RuleDialog({ + initial, + create, + routeName, + position, + takenNames, + ov, + models, + configVersion, + onChanged, + onClose, + onSave, +}: { + initial: RuleDraft; + create: boolean; + routeName: string; + /** 第几条,从 1 开始 */ + position: number; + /** 同一条路由里其余规则的名字 */ + takenNames: string[]; + ov: Overview; + models: KnownModel[]; + configVersion: string | null; + /** 在这里新建了策略组:外面要重读概览 */ + onChanged: () => void; + onClose: () => void; + /** `routeProbes`:保存路由时一并设为「交给路由」的辅助请求类别 */ + onSave: (rule: RuleDraft, routeProbes: string[]) => void; +}) { + const [d, setD] = useState(initial); + const set = (patch: Partial) => setD((x) => ({ ...x, ...patch })); + const [rewriteOpen, setRewriteOpen] = useState( + () => initial.model !== "" || initial.maxTokens !== "" || initial.thinking !== "keep", + ); + const [guardOpen, setGuardOpen] = useState(() => initial.redact.length > 0 || initial.untrusted); + const [routeProbes, setRouteProbes] = useState(null); + const [newGroup, setNewGroup] = useState(false); + + const modelIds = useMemo(() => models.map((m) => m.id), [models]); + const phaseTwo = isPhaseTwo(d); + const problem = ruleProblem(d, takenNames); + + // 辅助请求条件里还没交给路由的类别:不交给路由,这个条件永远不满足 + const intent = d.conditions.find((c) => c.field === "intent"); + const anyProbe = intent?.values.includes("assistant_internal") ?? false; + const unrouted = (anyProbe ? PROBE_IDS : (intent?.values ?? [])).filter( + (id) => (ov.client_probes ?? []).find((p) => p.id === id)?.mode !== "route", + ); + // 「任一辅助请求」时不默认勾选:连通性检查和预热原本由网关本地应答,改为交给路由会产生费用 + const routing = routeProbes ?? !anyProbe; + + const rewriteSummary = addOnsText({ ...d, redact: [], untrusted: false }); + const guardSummary = addOnsText({ ...d, model: "", maxTokens: "", thinking: "keep" }); + + return ( + !open && onClose()}> + + + {create ? "添加规则" : `编辑规则「${initial.name}」`} + + 路由「{routeName}」· 第 {position} 条 + + + +
+ + set({ name: e.target.value })} + /> + + +
+
+ 条件 + {d.conditions.length > 1 && ( + 同时满足以下条件 + )} +
+
+ {d.conditions.length === 0 && ( +

全部请求(兜底)

+ )} + {d.conditions.map((c, i) => ( + set({ conditions: d.conditions.map((x, j) => (j === i ? nc : x)) })} + onRemove={() => set({ conditions: d.conditions.filter((_, j) => j !== i) })} + /> + ))} + {unrouted.length > 0 && ( +
+ + {unrouted.map(probeLabel).join("、")}当前未设为交给路由,此条件不会满足。 + + + setRouteProbes(v === true)} + /> + 保存时将这些类别改为交给路由 + +
+ )} + c.field)} + onAdd={(id) => set({ conditions: [...d.conditions, blankCondition(id)] })} + /> +
+
+ +
+ + + value={d.action} + onChange={(a) => set({ action: a })} + options={[ + { id: "forward", label: "转发", disabled: phaseTwo }, + { id: "deny", label: "拒绝" }, + { id: "continue", label: "继续匹配" }, + ]} + /> + + {d.action === "forward" && ( + + + e.target.value === NEW_GROUP ? setNewGroup(true) : set({ to: e.target.value }) + } + > + {!d.to && 选择去向} + + {ov.groups.map((g) => ( + + {targetLabel(g.name)} + + ))} + 新建策略组… + + + {ov.providers.map((p) => ( + + {p.name} + + ))} + + + + )} + {d.action === "deny" && ( + + set({ deny: e.target.value })} + /> + + )} + {d.action === "continue" && ( +

+ 应用下方的改写参数与安全要求,然后继续匹配后续规则。 +

+ )} +
+ {phaseTwo && ( + 含「选定上游」条件的规则在选定上游之后判断,只能拒绝或继续匹配。 + )} + + {d.action !== "deny" && ( +
+
setRewriteOpen((o) => !o)} + > +
+ + set({ model: v })} + models={modelIds} + placeholder="不改变" + /> + + + set({ maxTokens: e.target.value })} + /> + + + + value={d.thinking} + onChange={(v) => set({ thinking: v })} + options={[ + { id: "keep", label: "不改变" }, + { id: "on", label: "开启" }, + { id: "off", label: "关闭" }, + ]} + /> + +
+ {d.model.trim() && 更换模型后,已缓存的 prompt 不再命中。} +
+
setGuardOpen((o) => !o)} + > + + ({ id: k.id, label: k.label }))} + value={d.redact} + onChange={(u) => setD((x) => ({ ...x, redact: u(x.redact) }))} + /> + + + set({ untrusted: v === true })} + /> + 按非官方端点处理 + +
+
+ )} +
+ + + {problem && {problem}} + + + + + {newGroup && ( + setNewGroup(false)} + onSaved={(name) => { + setNewGroup(false); + set({ to: name }); + onChanged(); + }} + /> + )} +
+
+ ); +} + +/** 附加项的一节:标题一行可以展开,收起时显示已设置的摘要 */ +function Section({ + title, + summary, + open, + onToggle, + children, +}: { + title: string; + summary: string; + open: boolean; + onToggle: () => void; + children: ReactNode; +}) { + return ( +
+ + {open &&
{children}
} +
+ ); +} + +/** 「添加条件」:按请求、特征、来源、上游分组,已有的不再列出 */ +function AddCondition({ used, onAdd }: { used: string[]; onAdd: (field: string) => void }) { + const left = COND_FIELDS.filter((f) => !used.includes(f.id)); + if (left.length === 0) return null; + const groups = [...new Set(left.map((f) => f.group))]; + return ( + + + + + + {groups.map((g, i) => ( +
+ {i > 0 && } +
{g}
+ {left + .filter((f) => f.group === g) + .map((f) => ( + onAdd(f.id)}> + {conditionName(f.id)} + + ))} +
+ ))} +
+
+ ); +} + +/** 一个条件:名称、取值控件、删除。**控件随条件的类型变**,不是一个通用输入框 */ +function ConditionRow({ + c, + ov, + models, + onChange, + onRemove, +}: { + c: ConditionView; + ov: Overview; + models: string[]; + onChange: (c: ConditionView) => void; + onRemove: () => void; +}) { + const f = condField(c.field); + const name = conditionName(c.field); + const v0 = c.values[0] ?? ""; + let control: ReactNode; + let hint: string | null = null; + switch (f.kind) { + case "glob": { + control = ( + onChange({ ...c, values: [v] })} + models={models} + placeholder="例如 claude-opus-*" + /> + ); + if (v0.trim() && models.length > 0) { + const n = models.filter((m) => globMatch(v0.trim(), m)).length; + hint = n > 0 ? `匹配 ${n} 个已知模型` : "不匹配任何已知模型"; + } + break; + } + case "compare": { + const [op, amount] = splitCompare(v0); + control = ( + <> + onChange({ ...c, values: [`${e.target.value}${amount}`] })} + > + {COMPARE_OPS.map((o) => ( + + {o.label} + + ))} + + onChange({ ...c, values: [`${op}${e.target.value}`] })} + /> + + ); + break; + } + case "flag": + control = ( + + value={v0 === "false" ? "false" : "true"} + onChange={(v) => onChange({ ...c, values: [v] })} + options={[ + { id: "true", label: "是" }, + { id: "false", label: "否" }, + ]} + /> + ); + break; + case "one": + control = + c.field === "dialect" ? ( + onChange({ ...c, values: [e.target.value] })}> + {DIALECTS.map((d) => ( + + {formatLabel(d)} + + ))} + + ) : ( + onChange({ ...c, values: [e.target.value] })}> + {!v0 && 选择密钥} + {ov.clients.map((k) => ( + + {k.name} + + ))} + + ); + break; + case "many": + control = + c.field === "intent" ? ( + ({ id: p.id, label: p.label })), + ]} + value={c.values} + onChange={(u) => onChange({ ...c, values: u(c.values) })} + /> + ) : ( + ({ id: p.name }))} + value={c.values} + onChange={(u) => onChange({ ...c, values: u(c.values) })} + /> + ); + break; + } + return ( +
+
+ {name} +
+ {control} +
+ +
+ {hint &&

{hint}

} +
+ ); +} diff --git a/src/routing/api.ts b/src/routing/api.ts new file mode 100644 index 00000000..21b68e48 --- /dev/null +++ b/src/routing/api.ts @@ -0,0 +1,35 @@ +/** + * 路由页用到的控制面调用。**只是类型化的 invoke**:规则怎么校验、改名时 + * 密钥和规则怎么跟着改、删除时密钥改用哪条路由,全在 core。 + */ +import { invoke } from "@tauri-apps/api/core"; +import type { + ConfigWritten, + DryRunRequest, + DryRunResult, + GroupSave, + KnownModel, + RouteSave, +} from "@/types"; + +type Base = string | null; + +export const api = { + createRoute: (save: RouteSave) => invoke("create_route", { save }), + updateRoute: (name: string, save: RouteSave) => + invoke("update_route", { name, save }), + /** `reassignTo` 为空:使用它的密钥改用默认路由 */ + deleteRoute: (name: string, baseVersion: Base, reassignTo: string | null) => + invoke("delete_route", { name, baseVersion, reassignTo }), + setDefaultRoute: (name: string, baseVersion: Base) => + invoke("set_default_route", { + save: { name, base_version: baseVersion ?? undefined }, + }), + createGroup: (save: GroupSave) => invoke("create_group", { save }), + updateGroup: (name: string, save: GroupSave) => + invoke("update_group", { name, save }), + deleteGroup: (name: string, baseVersion: Base) => + invoke("delete_group", { name, baseVersion }), + knownModels: () => invoke("known_models"), + dryRun: (req: DryRunRequest) => invoke("dry_run", { req }), +}; diff --git a/src/routing/fields.tsx b/src/routing/fields.tsx new file mode 100644 index 00000000..86c19e49 --- /dev/null +++ b/src/routing/fields.tsx @@ -0,0 +1,123 @@ +/** + * 路由页几个对话框共用的小件:带建议的模型输入、一排可切换的名称标签。 + */ +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; +import { + Combobox, + ComboboxContent, + ComboboxEmpty, + ComboboxInput, + ComboboxItem, + ComboboxList, +} from "@/ui/combobox"; + +/** + * 模型名:**自由输入 + 建议**。模型可能是刚发布的、也可能是中转自己起的, + * 建议里没有的照样得能写进去。 + */ +export function ModelInput({ + value, + onChange, + models, + placeholder = "模型名", + id, + className, +}: { + value: string; + onChange: (v: string) => void; + models: string[]; + placeholder?: string; + id?: string; + className?: string; +}) { + // **建议列表挂进所在的对话框,不挂在 body 上。**Radix 的模态对话框把 body + // 设成 pointer-events: none,并把对话框外的点击当成「点在外面」,滚轮也 + // 只放行对话框内部 —— 挂在 body 上的列表看得见、点不中也滚不动 + const anchor = useRef(null); + const [container, setContainer] = useState(null); + useLayoutEffect(() => { + setContainer(anchor.current?.closest('[role="dialog"]') ?? null); + }, []); + // **Esc 只收起列表。**对话框的 Esc 监听在 document 的捕获阶段,比输入框先 + // 拿到这一下;不在 window 上先截住,就连对话框带没保存的编辑一起关掉了 + const [open, setOpen] = useState(false); + useEffect(() => { + if (!open) return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Escape" || e.isComposing) return; + e.stopPropagation(); + setOpen(false); + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + }, [open]); + return ( +
+ setOpen(next)} + > + + + 无匹配项,可直接输入完整模型名 + + {(m: string) => ( + + {m} + + )} + + + +
+ ); +} + +/** + * 一排可切换的名称标签。**和价目表的「使用上游」是同一种控件**:选中的 + * 高亮,悬停可以看一句说明(比如它现在用的是哪条路由)。 + */ +export function ToggleChips({ + options, + value, + onChange, + mono = true, +}: { + options: { id: string; label?: string; title?: string }[]; + value: string[]; + /** 交出去的是更新函数:连点两个标签时,第二下基于第一下的结果 */ + onChange: (update: (prev: string[]) => string[]) => void; + mono?: boolean; +}) { + return ( +
+ {options.map((o) => { + const on = value.includes(o.id); + return ( + + ); + })} +
+ ); +} diff --git a/src/routing/model.test.ts b/src/routing/model.test.ts new file mode 100644 index 00000000..e9a2ec2b --- /dev/null +++ b/src/routing/model.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from "vitest"; +import type { RouteView, RuleView } from "@/types"; +import { + blankRule, + draftFromView, + draftNotes, + draftToInput, + flowOf, + insertIndex, + liftShadowed, + move, + routeSummary, + ruleProblem, + splitCompare, + usersOf, + type RuleDraft, +} from "./model"; + +function view(p: Partial & { name: string }): RuleView { + return { conditions: [], catch_all: false, phase_two: false, shadowed: false, ...p }; +} + +function rule(name: string, p: Partial = {}): RuleDraft { + return { ...blankRule("pool"), name, ...p }; +} + +const model = (glob: string) => ({ field: "model", values: [glob] }); + +describe("规则草稿", () => { + it("视图读进来、交回去是同一套写法", () => { + const v = view({ + name: "长上下文", + conditions: [{ field: "input_tokens", values: [">200k"] }, model("claude-*")], + to: "长上下文池", + }); + const input = draftToInput(draftFromView(v)); + expect(input).toEqual({ + name: "长上下文", + conditions: v.conditions, + to: "长上下文池", + deny: null, + set: null, + guard: null, + }); + }); + + it("三种命中后各自只交它用得到的字段", () => { + const deny = draftFromView(view({ name: "禁用 Opus", conditions: [model("claude-opus-*")], deny: "不提供" })); + expect(deny.action).toBe("deny"); + // 拒绝时附加项不起作用,即使草稿里还留着 + expect(draftToInput({ ...deny, model: "x" })).toMatchObject({ to: null, deny: "不提供", set: null }); + + const cont = draftFromView( + view({ name: "标题用小模型", conditions: [{ field: "intent", values: ["titling"] }], set: { model: "claude-haiku-4-5" } }), + ); + expect(cont.action).toBe("continue"); + expect(draftToInput(cont)).toMatchObject({ to: null, deny: null, set: { model: "claude-haiku-4-5" } }); + }); + + it("比较式拆成比较符和数值,写回去时拼上", () => { + expect(splitCompare(">200k")).toEqual([">", "200k"]); + expect(splitCompare(">= 32k")).toEqual([">=", "32k"]); + expect(splitCompare("==0")).toEqual(["=", "0"]); + const d = rule("x", { conditions: [{ field: "input_tokens", values: ["<=32k"] }] }); + expect(draftToInput(d).conditions).toEqual([{ field: "input_tokens", values: ["<=32k"] }]); + }); + + it("保存按钮旁边说出还缺什么", () => { + expect(ruleProblem(rule(""), [])).toBe("填写规则名称"); + expect(ruleProblem(rule("兜底"), ["兜底"])).toBe("规则名称「兜底」已存在"); + expect(ruleProblem(rule("a", { conditions: [{ field: "input_tokens", values: [">"] }] }), [])).toContain("数值"); + expect(ruleProblem(rule("a", { conditions: [{ field: "input_tokens", values: [">200q"] }] }), [])).toContain("有误"); + expect(ruleProblem(rule("a", { action: "deny" }), [])).toBe("填写拒绝原因"); + expect(ruleProblem(rule("a", { action: "continue" }), [])).toContain("改写参数或安全要求"); + expect( + ruleProblem(rule("a", { conditions: [{ field: "provider_would_be", values: ["relay"] }] }), []), + ).toContain("不能转发"); + expect(ruleProblem(rule("a"), [])).toBeNull(); + }); +}); + +describe("规则在路由里的处境", () => { + const catchAll = rule("兜底"); + const gemini = rule("Gemini", { conditions: [model("gemini-*")] }); + const rewrite = rule("限制输出", { action: "continue", maxTokens: "4096" }); + + it("兜底之后的转发不会生效,只附加改写的照常生效", () => { + const notes = draftNotes([catchAll, gemini, rewrite]); + expect(notes.map((n) => n.shadowed)).toEqual([false, true, false]); + expect(notes[0]!.catchAll).toBe(true); + }); + + it("「添加规则」插在第一条兜底之前", () => { + expect(insertIndex([gemini, catchAll, rewrite])).toBe(1); + expect(insertIndex([gemini])).toBe(1); + // 只附加改写的规则不算兜底 + expect(insertIndex([rewrite, gemini])).toBe(2); + }); + + it("「移至兜底规则之前」只挪被挡住的,其余次序不变", () => { + const b = rule("b", { conditions: [model("b-*")] }); + const out = liftShadowed([rewrite, catchAll, gemini, b]); + expect(out.map((r) => r.name)).toEqual(["限制输出", "Gemini", "b", "兜底"]); + }); + + it("移动一项", () => { + expect(move(["a", "b", "c"], 2, 0)).toEqual(["c", "a", "b"]); + expect(move(["a", "b", "c"], 0, 5)).toEqual(["b", "c", "a"]); + }); +}); + +describe("路由列表", () => { + const route = (p: Partial): RouteView => ({ + name: "codex", + default: false, + builtin: false, + has_catch_all: true, + clients: [], + rules: [], + ...p, + }); + + it("默认路由的使用者包括没指定路由的密钥", () => { + const clients = [ + { name: "claude-code", key: "tw-a", max_concurrent: null, route: null }, + { name: "codex", key: "tw-b", max_concurrent: null, route: "codex" }, + ]; + expect(usersOf(route({ name: "默认", default: true }), clients)).toEqual(["claude-code"]); + expect(usersOf(route({}), clients)).toEqual(["codex"]); + }); + + it("规则一栏只列决定去向的规则,内置策略组显示为「全部上游」", () => { + const r = route({ + rules: [ + view({ name: "标题用小模型", set: { model: "m" } }), + view({ name: "禁用 Opus", deny: "不提供" }), + view({ name: "兜底", to: "__all__", catch_all: true }), + view({ name: "Gemini", to: "openrouter", shadowed: true }), + ], + }); + expect(flowOf(r)).toEqual([ + { rule: "禁用 Opus", target: null }, + { rule: "兜底", target: "全部上游" }, + ]); + expect(routeSummary(r)).toEqual({ text: "4 条规则 · 1 条位于兜底规则之后,不会生效", warn: true }); + expect(routeSummary(route({ has_catch_all: false, rules: [] })).text).toBe("0 条规则 · 尚无兜底规则"); + }); +}); diff --git a/src/routing/model.ts b/src/routing/model.ts new file mode 100644 index 00000000..ef0da1f0 --- /dev/null +++ b/src/routing/model.ts @@ -0,0 +1,360 @@ +/** + * 路由页的草稿与换算。**纯函数**,对话框和列表共用,测试盯着这一层。 + * + * 保存时交给 core 的是结构(`RouteInput`),规则的顺序就是数组的顺序。名字 + * 能不能用、条件写得对不对,最后由 core 说;这里只做对话框里需要实时给出 + * 的那几件事:保存按钮旁边缺什么、哪条规则被兜底挡住。 + */ +import type { + ClientView, + ConditionView, + GroupKind, + GroupView, + ProviderView, + RouteView, + RuleInput, + RuleView, +} from "@/types"; +import { ALL_UPSTREAMS, conditionName, groupKindLabel, targetLabel } from "@/labels"; +import { protocolLabel } from "@/upstreams/labels"; + +// ---------------------------------------------------------------- 条件 + +export type CondKind = "glob" | "compare" | "flag" | "one" | "many"; + +export interface CondField { + id: string; + kind: CondKind; + group: "请求" | "特征" | "来源" | "上游"; +} + +/** 能写的条件,按「添加条件」菜单里的分组和顺序 */ +export const COND_FIELDS: CondField[] = [ + { id: "model", kind: "glob", group: "请求" }, + { id: "input_tokens", kind: "compare", group: "请求" }, + { id: "max_tokens", kind: "compare", group: "请求" }, + { id: "tool_count", kind: "compare", group: "请求" }, + { id: "cache", kind: "flag", group: "特征" }, + { id: "tools", kind: "flag", group: "特征" }, + { id: "image", kind: "flag", group: "特征" }, + { id: "thinking", kind: "flag", group: "特征" }, + { id: "stream", kind: "flag", group: "特征" }, + { id: "dialect", kind: "one", group: "来源" }, + { id: "intent", kind: "many", group: "来源" }, + { id: "client", kind: "one", group: "来源" }, + { id: "provider_would_be", kind: "many", group: "上游" }, +]; + +export function condField(id: string): CondField { + return COND_FIELDS.find((f) => f.id === id) ?? { id, kind: "one", group: "请求" }; +} + +/** 比较符。配置里写的是符号,界面上是词 */ +export const COMPARE_OPS: { id: string; label: string }[] = [ + { id: ">", label: "大于" }, + { id: ">=", label: "不小于" }, + { id: "<", label: "小于" }, + { id: "<=", label: "不大于" }, + { id: "=", label: "等于" }, +]; + +/** `>200k` → `[">", "200k"]`。写不出比较符的原样放进数值里,让校验说话 */ +export function splitCompare(v: string): [string, string] { + const m = /^\s*(>=|<=|==|=|>|<)\s*(.*)$/.exec(v); + if (!m) return [">", v.trim()]; + return [m[1] === "==" ? "=" : m[1]!, m[2]!.trim()]; +} + +/** 比较式里的数:`200k`、`1.5m`、`8` */ +export function validAmount(v: string): boolean { + return /^\d+(\.\d+)?[kKmM]?$/.test(v.trim()); +} + +/** 一个新加的条件的初始值 */ +export function blankCondition(id: string): ConditionView { + switch (condField(id).kind) { + case "flag": + return { field: id, values: ["true"] }; + case "compare": + return { field: id, values: [">"] }; + case "one": + return { field: id, values: id === "dialect" ? ["anthropic"] : [] }; + default: + return { field: id, values: [] }; + } +} + +/** 条件缺什么。没问题时为空 */ +export function conditionProblem(c: ConditionView): string | null { + const name = conditionName(c.field); + const values = c.values.map((v) => v.trim()).filter(Boolean); + switch (condField(c.field).kind) { + case "compare": { + const [, amount] = splitCompare(values[0] ?? ""); + if (!amount) return `填写条件「${name}」的数值`; + return validAmount(amount) ? null : `条件「${name}」的数值有误,示例:200k`; + } + case "flag": + return null; + default: + return values.length ? null : `填写条件「${name}」的取值`; + } +} + +// ---------------------------------------------------------------- 规则草稿 + +export type Action = "forward" | "deny" | "continue"; + +export interface RuleDraft { + /** 列表里的稳定标识。规则名在编辑中会变,不能拿来当 key */ + key: string; + name: string; + conditions: ConditionView[]; + action: Action; + to: string; + deny: string; + model: string; + maxTokens: string; + thinking: "keep" | "on" | "off"; + redact: string[]; + untrusted: boolean; +} + +let seq = 0; +function nextKey(): string { + seq += 1; + return `r${seq}`; +} + +export function blankRule(to = ALL_UPSTREAMS): RuleDraft { + return { + key: nextKey(), + name: "", + conditions: [], + action: "forward", + to, + deny: "", + model: "", + maxTokens: "", + thinking: "keep", + redact: [], + untrusted: false, + }; +} + +export function draftFromView(r: RuleView): RuleDraft { + return { + key: nextKey(), + name: r.name, + conditions: r.conditions.map((c) => ({ field: c.field, values: [...c.values] })), + action: r.to ? "forward" : r.deny != null ? "deny" : "continue", + to: r.to ?? "", + deny: r.deny ?? "", + model: r.set?.model ?? "", + maxTokens: r.set?.max_tokens != null ? String(r.set.max_tokens) : "", + thinking: r.set?.thinking == null ? "keep" : r.set.thinking ? "on" : "off", + redact: [...(r.guard?.redact ?? [])], + untrusted: r.guard?.untrusted ?? false, + }; +} + +export function copyDraft(d: RuleDraft): RuleDraft { + return { ...d, key: nextKey(), conditions: d.conditions.map((c) => ({ ...c, values: [...c.values] })) }; +} + +/** 附加了改写或安全要求 */ +export function hasAddOns(d: RuleDraft): boolean { + return ( + d.model.trim() !== "" || + d.maxTokens.trim() !== "" || + d.thinking !== "keep" || + d.redact.length > 0 || + d.untrusted + ); +} + +/** 在选定上游之后才判断:条件里有「选定上游」 */ +export function isPhaseTwo(d: RuleDraft): boolean { + return d.conditions.some((c) => c.field === "provider_would_be"); +} + +/** 草稿 → 交给 core 的规则 */ +export function draftToInput(d: RuleDraft): RuleInput { + const conditions = d.conditions.map((c) => { + const values = c.values.map((v) => v.trim()).filter(Boolean); + if (condField(c.field).kind === "compare") { + const [op, amount] = splitCompare(values[0] ?? ""); + return { field: c.field, values: [`${op}${amount}`] }; + } + return { field: c.field, values }; + }); + const deny = d.action === "deny"; + const maxTokens = Number.parseInt(d.maxTokens.trim(), 10); + const set = { + model: d.model.trim() || null, + max_tokens: Number.isFinite(maxTokens) && maxTokens > 0 ? maxTokens : null, + thinking: d.thinking === "keep" ? null : d.thinking === "on", + }; + const guard = { redact: d.redact, untrusted: d.untrusted }; + return { + name: d.name.trim(), + conditions, + to: d.action === "forward" ? d.to : null, + deny: deny ? d.deny.trim() : null, + // 拒绝时附加项不起作用:不写进去 + set: !deny && (set.model || set.max_tokens || set.thinking != null) ? set : null, + guard: !deny && (guard.redact.length || guard.untrusted) ? guard : null, + }; +} + +/** 规则对话框里保存按钮旁边要说的:还缺什么。没问题时为空 */ +export function ruleProblem(d: RuleDraft, takenNames: string[]): string | null { + const name = d.name.trim(); + if (!name) return "填写规则名称"; + if (takenNames.includes(name)) return `规则名称「${name}」已存在`; + for (const c of d.conditions) { + const p = conditionProblem(c); + if (p) return p; + } + if (d.action === "forward") { + if (isPhaseTwo(d)) return "含「选定上游」条件的规则不能转发"; + if (!d.to) return "选择转发去向"; + } + if (d.action === "deny" && !d.deny.trim()) return "填写拒绝原因"; + if (d.action === "continue" && !hasAddOns(d)) return "继续匹配的规则须设置改写参数或安全要求"; + const mt = d.maxTokens.trim(); + if (mt && !/^\d+$/.test(mt)) return "max_tokens 须为正整数"; + return null; +} + +// ---------------------------------------------------------------- 规则在路由里的处境 + +export interface Notes { + catchAll: boolean; + phaseTwo: boolean; + /** 转发或拒绝不会被采用:前面已有一条匹配全部请求的转发或拒绝 */ + shadowed: boolean; +} + +/** + * 每条草稿规则的处境。 + * + * **和 core 的 `tw_engine::notes` 是同一条规则**:已保存的路由由 core 给出, + * 这里只算对话框里还没保存的那份,好在排序、添加的时候立刻提示。 + */ +export function draftNotes(rules: RuleDraft[]): Notes[] { + let decided = false; + return rules.map((r) => { + const phaseTwo = isPhaseTwo(r); + const catchAll = r.conditions.length === 0; + const decides = r.action !== "continue"; + const shadowed = !phaseTwo && decides && decided; + if (!phaseTwo && catchAll && decides) decided = true; + return { catchAll, phaseTwo, shadowed }; + }); +} + +export function hasCatchAll(rules: RuleDraft[]): boolean { + return rules.some((r) => !isPhaseTwo(r) && r.conditions.length === 0 && r.action !== "continue"); +} + +/** 「添加规则」插在哪儿:第一条兜底规则之前;没有兜底就在末尾 */ +export function insertIndex(rules: RuleDraft[]): number { + const i = rules.findIndex((r) => !isPhaseTwo(r) && r.conditions.length === 0 && r.action !== "continue"); + return i < 0 ? rules.length : i; +} + +/** 把被兜底挡住的规则挪到第一条兜底规则之前,其余次序不变 */ +export function liftShadowed(rules: RuleDraft[]): RuleDraft[] { + const notes = draftNotes(rules); + const lifted = rules.filter((_, i) => notes[i]!.shadowed); + const rest = rules.filter((_, i) => !notes[i]!.shadowed); + const at = insertIndex(rest); + return [...rest.slice(0, at), ...lifted, ...rest.slice(at)]; +} + +export function move(list: T[], from: number, to: number): T[] { + if (from === to || from < 0 || from >= list.length) return list; + const out = [...list]; + const [it] = out.splice(from, 1); + out.splice(Math.max(0, Math.min(to, out.length)), 0, it!); + return out; +} + +// ---------------------------------------------------------------- 列表与说明 + +/** 这条路由被哪些密钥使用:指定了它的,加上默认路由的那些没指定路由的 */ +export function usersOf(route: RouteView, clients: ClientView[]): string[] { + return clients + .filter((c) => c.route === route.name || (route.default && !c.route)) + .map((c) => c.name); +} + +/** 列表「规则」一栏:按顺序列出决定去向的规则。被挡住的、只附加的不列 */ +export function flowOf(route: RouteView): { rule: string; target: string | null }[] { + return route.rules + .filter((r) => !r.shadowed && !r.phase_two && (r.to || r.deny != null)) + .map((r) => ({ rule: r.name, target: r.to ? targetLabel(r.to) : null })); +} + +/** 列表「规则」一栏的次行:规则数,以及需要留意的事 */ +export function routeSummary(route: RouteView): { text: string; warn: boolean } { + const parts = [`${route.rules.length} 条规则`]; + const shadowed = route.rules.filter((r) => r.shadowed).length; + if (shadowed > 0) parts.push(`${shadowed} 条位于兜底规则之后,不会生效`); + if (!route.has_catch_all) parts.push("尚无兜底规则"); + return { text: parts.join(" · "), warn: shadowed > 0 || !route.has_catch_all }; +} + +/** 去向的说明:策略组的策略与成员,或上游的协议 */ +export function describeTarget( + name: string, + groups: GroupView[], + providers: ProviderView[], +): string { + const g = groups.find((x) => x.name === name); + if (g) { + if (g.builtin) return "内置策略组 · 按上游列表顺序"; + const members = membersText(g); + return `策略组 · ${groupKindLabel(g.kind)}${members ? `:${members}` : ""}`; + } + const p = providers.find((x) => x.name === name); + if (p) return `上游 · ${protocolLabel(p.protocol)}${p.disabled ? " · 已停用" : ""}`; + return "不存在的去向"; +} + +/** 成员怎么写:有先后的用「→」连,其余用顿号 */ +export function membersText(g: Pick): string { + const ordered = g.kind === "fallback" || g.kind === "select"; + if (g.kind === "select" && g.selected) { + const rest = g.providers.filter((p) => p !== g.selected); + return [g.selected, ...rest].join(" → "); + } + return g.providers.join(ordered ? " → " : "、"); +} + +/** 规则的附加项写成一句:`模型改为 claude-haiku-4-5 · 额外脱敏 2 类` */ +export function addOnsText(d: RuleDraft): string { + const parts: string[] = []; + if (d.model.trim()) parts.push(`模型改为 ${d.model.trim()}`); + if (d.maxTokens.trim()) parts.push(`max_tokens 改为 ${d.maxTokens.trim()}`); + if (d.thinking !== "keep") parts.push(d.thinking === "on" ? "开启扩展思考" : "关闭扩展思考"); + if (d.redact.length) parts.push(`额外脱敏 ${d.redact.length} 类`); + if (d.untrusted) parts.push("按非官方端点处理"); + return parts.join(" · "); +} + +/** 策略组的策略,附一句会影响用户决定的说明 */ +export const STRATEGIES: { id: GroupKind; desc: string }[] = [ + { id: "fallback", desc: "依次使用成员,前一个不可用时使用下一个。" }, + { id: "select", desc: "使用选定的上游;它不可用时,按顺序使用其余成员。" }, + { id: "load-balance", desc: "在成员之间轮流分配请求。" }, + { id: "url-test", desc: "优先使用首字节时间最短的上游。" }, + { id: "cheapest", desc: "优先使用输入单价最低的上游。" }, +]; + +/** 客户端格式:规则条件和试算里可选的几种 */ +export const DIALECTS = ["anthropic", "openai-chat", "openai-responses", "gemini"]; + +/** 辅助请求的类别(不含总称) */ +export const PROBE_IDS = ["health_check", "warmup", "titling", "topic_detect", "suggestion"]; diff --git a/src/routing/useReorder.ts b/src/routing/useReorder.ts new file mode 100644 index 00000000..666a1f1e --- /dev/null +++ b/src/routing/useReorder.ts @@ -0,0 +1,74 @@ +import { useRef, useState, type PointerEvent } from "react"; + +/** + * 拖动把手调整一张列表的顺序。 + * + * **用指针事件,不用 HTML5 拖放。**Tauri 的窗口默认接管拖放(为了接住从 + * Finder 拖进来的文件),网页里的 `dragstart` / `drop` 因此时有时无;指针 + * 事件不受它影响。行上标 `data-reorder-row={i}`,把手上摊 `handle(i)`。 + */ +export function useReorder(onMove: (from: number, to: number) => void) { + const from = useRef(null); + const [dragging, setDragging] = useState(null); + /** 放下时会落到哪个位置之前(等于长度时是末尾) */ + const [target, setTarget] = useState(null); + + function locate(e: PointerEvent): number | null { + const el = document.elementFromPoint(e.clientX, e.clientY)?.closest("[data-reorder-row]"); + if (!el) return null; + const i = Number(el.dataset.reorderRow); + const r = el.getBoundingClientRect(); + return e.clientY < r.top + r.height / 2 ? i : i + 1; + } + + function handle(i: number) { + return { + onPointerDown: (e: PointerEvent) => { + if (e.button !== 0) return; + e.preventDefault(); + try { + // 把后续的移动都交给把手,指针离开它也不丢 + e.currentTarget.setPointerCapture(e.pointerId); + } catch { + // 指针已经不在了(比如刚按下就被系统取消):照常开始,松开时会结束 + } + from.current = i; + setDragging(i); + setTarget(null); + }, + onPointerMove: (e: PointerEvent) => { + if (from.current == null) return; + setTarget(locate(e)); + }, + onPointerUp: (e: PointerEvent) => { + const start = from.current; + from.current = null; + setDragging(null); + setTarget(null); + if (start == null) return; + const to = locate(e); + if (to == null) return; + // 落在自己前后等于没动;往后挪时,拿走自己之后下标要减一 + const dest = to > start ? to - 1 : to; + if (dest !== start) onMove(start, dest); + }, + onPointerCancel: () => { + from.current = null; + setDragging(null); + setTarget(null); + }, + style: { cursor: dragging === i ? "grabbing" : "grab", touchAction: "none" as const }, + }; + } + + /** 这一行要不要画插入线:`before` 画在它上沿,`after` 画在它下沿(只有最后一行用) */ + function marker(i: number, count: number): "before" | "after" | null { + if (dragging == null || target == null) return null; + if (target === dragging || target === dragging + 1) return null; + if (target === i) return "before"; + if (i === count - 1 && target === count) return "after"; + return null; + } + + return { handle, dragging, marker }; +} diff --git a/src/types.ts b/src/types.ts index a49a09b9..16ebab9e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -728,15 +728,83 @@ export interface LimitsView { queue_timeout_secs: number; } -/** 一条规则 */ +/** 一条规则。**全文**:编辑对话框靠它回填,交回去的 `RuleInput` 是同一套写法 */ export interface RuleView { name: string; - /** 去向:上游名或组名。拒绝的规则和只改参数的规则没有 */ - to?: string | null; - /** 命中就拒绝 */ - deny?: boolean; /** `when` 里写了的条件,按固定顺序。空 = 兜底 */ conditions: ConditionView[]; + /** 去向:上游名或组名。拒绝的规则和只附加改写、安全要求的规则没有 */ + to?: string | null; + /** 命中就拒绝,值是返回给客户端的原因 */ + deny?: string | null; + set?: RuleRewrite | null; + guard?: RuleGuard | null; + /** 没有条件,匹配全部请求 */ + catch_all: boolean; + /** 在选定上游之后才判断 */ + phase_two: boolean; + /** 转发或拒绝不会被采用:前面已有一条匹配全部请求的转发或拒绝。附加项照常生效 */ + shadowed: boolean; +} + +/** 规则里的参数改写。不写就是不改 */ +export interface RuleRewrite { + model?: string | null; + max_tokens?: number | null; + thinking?: boolean | null; +} + +/** 规则里的安全要求。只能收紧 */ +export interface RuleGuard { + /** 额外脱敏的类别,和上游的脱敏类别同一套标识符 */ + redact?: string[]; + /** 按非官方端点处理 */ + untrusted?: boolean; +} + +/** 新建或修改路由时交过去的一条规则 */ +export interface RuleInput { + name: string; + /** 空 = 兜底 */ + conditions: ConditionView[]; + to?: string | null; + deny?: string | null; + set?: RuleRewrite | null; + guard?: RuleGuard | null; +} + +/** 新建或修改路由时交过去的定义。**规则的顺序就是数组的顺序** */ +export interface RouteInput { + name: string; + rules: RuleInput[]; +} + +export interface RouteSave { + route: RouteInput; + base_version?: string; + /** 保存之后恰好使用这条路由的密钥。不给就不动 */ + keys?: string[]; + /** 一并设为「交给路由」的辅助请求类别:规则里的辅助请求条件只对它们生效 */ + route_probes?: string[]; +} + +export interface GroupInput { + name: string; + kind: GroupKind; + providers: string[]; + selected?: string | null; + session_affinity: boolean; +} + +export interface GroupSave { + group: GroupInput; + base_version?: string; +} + +/** 网关知道的一个模型,以及能提供它的上游 */ +export interface KnownModel { + id: string; + providers: string[]; } /** 规则里的一个条件 */ @@ -956,11 +1024,15 @@ export interface PriceSheetView { used_by: string[]; } -/** 一条路由 —— 一组规则,加上绑了它的密钥 */ +/** 一条路由 —— 一组规则,加上指定了它的密钥 */ export interface RouteView { name: string; - /** 没绑路由的密钥走的就是这条 */ + /** 没指定路由的密钥使用的就是这条 */ default: boolean; + /** 网关按配置补出来的默认路由:配置文件里没有它,编辑并保存即写入 */ + builtin: boolean; + /** 有一条匹配全部请求的转发或拒绝 */ + has_catch_all: boolean; /** **显式绑了这条的密钥。**默认路由这里通常是空的 —— 走它的人是「没绑」 */ clients: string[]; rules: RuleView[]; @@ -971,6 +1043,8 @@ export type GroupKind = "fallback" | "select" | "load-balance" | "url-test" | "c export interface GroupView { name: string; + /** 内置的「全部上游」:成员是全部上游,按上游列表的顺序。不能编辑、不能删除 */ + builtin: boolean; kind: GroupKind; /** 同一次会话固定走同一家。**这一项直接决定账单** */ session_affinity?: boolean; @@ -1242,6 +1316,8 @@ export interface RuleTrace { name: string; /** `phase_two`:条件要等选定上游之后才能求值,静态试算给不了结论 */ verdict: "matched" | "skipped" | "phase_two"; + /** 命中时它起了什么作用 */ + effect?: "decide" | "apply" | "none" | null; /** 没命中时,第一个没对上的条件 */ mismatch?: MismatchView | null; /** 条件本身写错了、没法求值时的说明 */ @@ -1265,7 +1341,29 @@ export interface SetView { value: string; } +/** 试算的请求。求值对象三选一:草稿 > 路由 > 密钥使用的路由 */ +export interface DryRunRequest { + model: string; + /** 发出请求的密钥。规则里的密钥条件也按它判断 */ + client: string; + route?: string | null; + draft?: RouteInput | null; + dialect: string; + input_tokens: number; + max_tokens: number | null; + cache: boolean; + tools: boolean; + tool_count: number; + image: boolean; + thinking: boolean; + stream: boolean; + /** 辅助请求的类别。空 = 用户请求 */ + intent: string; +} + export interface DryRunResult { + /** 按哪条路由求的值。草稿是草稿的名字 */ + route: string; /** `unavailable`:规则选中的上游都服务不了这个请求,原因见 `skipped` */ outcome: "route" | "deny" | "no_match" | "unavailable"; /** 经过的策略组按什么排序候选。直指上游时没有 */ diff --git a/src/ui/combobox.tsx b/src/ui/combobox.tsx index b4f0e917..62a9ce58 100644 --- a/src/ui/combobox.tsx +++ b/src/ui/combobox.tsx @@ -91,14 +91,17 @@ function ComboboxContent({ align = "start", alignOffset = 0, anchor, + container, ...props }: ComboboxPrimitive.Popup.Props & Pick< ComboboxPrimitive.Positioner.Props, "side" | "align" | "sideOffset" | "alignOffset" | "anchor" - >) { + > & + Pick) { return ( - + // 挂进别的容器时不占位:容器可能是 flex / grid,多一个子项就多一道 gap + ) { + return +} + +function DropdownMenuSubTrigger({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + {children} + + + ) +} + +function DropdownMenuSubContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +function DropdownMenuCheckboxItem({ + className, + children, + checked, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + export { DropdownMenu, DropdownMenuTrigger, @@ -90,4 +161,8 @@ export { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubTrigger, + DropdownMenuSubContent, + DropdownMenuCheckboxItem, } diff --git a/src/ui/row-menu.tsx b/src/ui/row-menu.tsx index 1187ca9c..c93d1af5 100644 --- a/src/ui/row-menu.tsx +++ b/src/ui/row-menu.tsx @@ -3,25 +3,41 @@ import { MoreHorizontalIcon } from "lucide-react"; import { Button } from "@/ui/button"; import { ContextMenu, + ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuSeparator, + ContextMenuSub, + ContextMenuSubContent, + ContextMenuSubTrigger, ContextMenuTrigger, } from "@/ui/context-menu"; import { DropdownMenu, + DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, DropdownMenuTrigger, } from "@/ui/dropdown-menu"; -/** 一份菜单:条目或分隔线。**右键和行尾按钮共用同一份** */ +/** 子菜单里的一项:单选的那种,当前选中的打勾 */ +export interface MenuChoice { + label: string; + checked: boolean; + onSelect: () => void; +} + +/** 一份菜单:条目、子菜单或分隔线。**右键和行尾按钮共用同一份** */ export type MenuItems = ( | { kind: "sep" } | { kind: "item"; label: string; onSelect: () => void; danger?: boolean; disabled?: boolean } + | { kind: "sub"; label: string; choices: MenuChoice[] } )[]; /** @@ -44,6 +60,17 @@ export function RowMenu({ children, items }: { children: ReactNode; items: MenuI {items.map((it, i) => it.kind === "sep" ? ( + ) : it.kind === "sub" ? ( + + {it.label} + + {it.choices.map((c) => ( + + {c.label} + + ))} + + ) : ( it.kind === "sep" ? ( + ) : it.kind === "sub" ? ( + + {it.label} + + {it.choices.map((c) => ( + + {c.label} + + ))} + + ) : ( ({ disabled, }: { value: T; - options: { id: T; label: ReactNode }[]; + options: { id: T; label: ReactNode; disabled?: boolean }[]; onChange: (v: T) => void; disabled?: boolean; }) { @@ -99,7 +99,7 @@ export function Segmented({ type="button" role="radio" aria-checked={value === o.id} - disabled={disabled} + disabled={disabled || o.disabled} onClick={() => onChange(o.id)} className={cn( "inline-flex h-6 items-center gap-1.5 rounded-md border border-transparent px-2.5 tw-body font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50",