From 3737f4821de6e8d6cdd05674530f3c1818397c04 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:33:39 +0800 Subject: [PATCH 1/2] Request drawer: the whole routing decision; name requests that reached no upstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Core 0.48 records the full routing decision on every non-local row (route, deciding rule, group, rewritten_by, denied_by, attempts) and keeps a row for requests that went to no upstream. The drawer showed only the rule and the group, and rows with an empty upstream showed a "?" tile in the command palette. - Routing tab: route, the deciding rule (marked when it denied the request before an upstream was chosen), group, the rules that rewrote the request in evaluation order, the phase-two rule that denied it, and the reason (the rule's own text, or core's sentence when no selected upstream could serve it). A hop denied by a phase-two rule reads "Not sent · denied by rule X" instead of looking like an upstream failure, and the note under the chain says only what happened: failed over and then denied, denied before or after the upstream was chosen, or no selected upstream can serve it. - src/requestRouting.ts: `notSent` (denied vs no upstream, from the empty upstream and core's `gw.route.denied`) and `routingFacts` (RoutingView and the row's error into what the tab shows), with tests. - Requests that reached no upstream: the traffic table, the drawer header and timeline, and the command palette show the routing map's deny glyph or a crossed-out upstream with "Denied" / "No upstream". Local answers in the palette get the gateway icon and the probe name as their title (core records them with no model and the probe kind as the path). - IconDenied and IconNoUpstream join the icon vocabulary; the routing map, the dry run and the route dialog use IconDenied. Co-Authored-By: Claude Opus 5.5 --- src/RequestDrawer.i18n.tsx | 33 ++++++++ src/RequestDrawer.tsx | 160 +++++++++++++++++++++++++++-------- src/labels.i18n.ts | 13 +++ src/labels.ts | 11 +++ src/palette/items.test.ts | 44 ++++++++++ src/palette/items.tsx | 26 ++++-- src/requestRouting.test.ts | 128 ++++++++++++++++++++++++++++ src/requestRouting.ts | 138 ++++++++++++++++++++++++++++++ src/routing/ChainMap.tsx | 5 +- src/routing/DryRunDialog.tsx | 6 +- src/routing/RouteDialog.tsx | 5 +- src/traffic/RequestTable.tsx | 29 +++++-- src/traffic/cells.tsx | 22 ++++- src/ui/icons.tsx | 2 + 14 files changed, 566 insertions(+), 56 deletions(-) create mode 100644 src/requestRouting.test.ts create mode 100644 src/requestRouting.ts diff --git a/src/RequestDrawer.i18n.tsx b/src/RequestDrawer.i18n.tsx index 63c34bab..22387e25 100644 --- a/src/RequestDrawer.i18n.tsx +++ b/src/RequestDrawer.i18n.tsx @@ -61,12 +61,29 @@ export const requestDrawerText = messages( generating: "生成", timingLabel: (ttfb: string, gen: string) => `等待首字节 ${ttfb},生成 ${gen}`, + /** 选定上游之后被规则拒绝的请求,「上游」那一行名字后面的标记 */ + notSentSuffix: "(未发送)", + // 路由 + route: "路由", matchedRule: "命中规则", + /** 命中规则后面的标记:决定去向的这一条就是拒绝 */ + denied: "拒绝", viaGroup: "经过策略组", + /** 改写了参数的规则,按求值的顺序 */ + rewrittenBy: "参数改写", + /** 选定上游之后才判断、拒绝了此请求的规则 */ + deniedBy: "拒绝规则", + /** 规则写的拒绝理由,或者选中的上游为何都无法服务 */ + reason: "原因", attempts: "尝试链", failover: (failed: number) => `已发生故障转移:前 ${failed} 个上游失败,已自动切换至下一个上游。`, + failoverDenied: (failed: number, rule: string) => + `已发生故障转移:前 ${failed} 个上游失败,切换至下一个上游后,规则「${rule}」拒绝了此请求,未向该上游发送。`, + deniedAfterPick: (rule: string) => `选定上游后,规则「${rule}」拒绝了此请求,未发往任何上游。`, + deniedBeforePick: (rule: string) => `选定上游之前,规则「${rule}」已拒绝此请求,未发往任何上游。`, + unavailable: "规则选中的上游均无法服务此请求,未发往任何上游。", noRouting: "此请求由网关本地应答,未经过路由。", routingPending: "路由尚未完成", noAttempts: "此请求没有上游尝试记录。", @@ -166,13 +183,29 @@ export const requestDrawerText = messages( generating: "Generating", timingLabel: (ttfb: string, gen: string) => `Waiting for first byte ${ttfb}, generating ${gen}`, + notSentSuffix: " (not sent)", + + route: "Route", matchedRule: "Matched rule", + denied: "Denied", viaGroup: "Via group", + rewrittenBy: "Rewritten by", + deniedBy: "Denied by", + reason: "Reason", attempts: "Attempts", failover: (failed: number) => failed === 1 ? "Failover occurred: the first upstream failed, and the request was switched to the next upstream automatically." : `Failover occurred: the first ${failed} upstreams failed, and the request was switched to the next upstream automatically.`, + failoverDenied: (failed: number, rule: string) => + failed === 1 + ? `Failover occurred: the first upstream failed, and after the switch to the next upstream, rule “${rule}” denied the request before it was sent there.` + : `Failover occurred: the first ${failed} upstreams failed, and after the switch to the next upstream, rule “${rule}” denied the request before it was sent there.`, + deniedAfterPick: (rule: string) => + `Rule “${rule}” denied this request after the upstream was chosen; it was not sent to any upstream.`, + deniedBeforePick: (rule: string) => + `Rule “${rule}” denied this request before an upstream was chosen; it was not sent to any upstream.`, + unavailable: "No upstream the rule selected can serve this request; it was not sent to any upstream.", noRouting: "The gateway answered this request locally; it did not go through routing.", routingPending: "Routing has not finished yet", noAttempts: "No upstream attempts were recorded for this request.", diff --git a/src/RequestDrawer.tsx b/src/RequestDrawer.tsx index 01aaff2e..30c349bf 100644 --- a/src/RequestDrawer.tsx +++ b/src/RequestDrawer.tsx @@ -8,6 +8,7 @@ import { cn } from "@/lib/utils"; import { statusTone, tokens as tokenPair, when } from "@/format"; import { Button } from "@/ui/button"; import { Collapsible, CollapsibleTrigger } from "@/ui/collapsible"; +import { IconDenied } from "@/ui/icons"; import { UpstreamLogo } from "@/ui/logos"; import { AnimatedNumber } from "@/ui/motion"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; @@ -19,12 +20,22 @@ import { StatusLabel, type StatusTone } from "@/ui/status-dot"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/ui/table"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; import { Tip } from "@/ui/tip"; -import { Elapsed } from "@/traffic/cells"; +import { Elapsed, NotSentIcon } from "@/traffic/cells"; import { PanelHeader, PanelHeaderSkeleton, PanelSkeleton } from "@/traffic/PanelHeader"; import { KeyLabel } from "./KeyLabel"; -import { appLabel, attemptText, formatLabel, quoteText, targetLabel } from "./labels"; +import { + appLabel, + attemptText, + deniedHopText, + formatLabel, + notSentText, + probeLabel, + quoteText, + targetLabel, +} from "./labels"; import { prettyJson } from "./prettyJson"; import { requestDrawerText } from "./RequestDrawer.i18n"; +import { notSent, routingFacts, type RoutingNote } from "./requestRouting"; import { ActionBadge, EventDetail, ruleName, whereOf } from "./security/labels"; import { usd, @@ -177,10 +188,12 @@ function Detail({ id, onClose }: { id: number; onClose: () => void }) { const r = d.row; const state = stateOf(d); + const sent = notSent(r); return ( setTab(v as Tab)} className="flex min-h-0 flex-1 flex-col gap-0"> void }) { } > - {/* 没有发往任何上游的(被规则拒绝、选中的上游一个都接不了)上游是空的,不写 */} - {(r.local || r.provider) && ( + {/* 没有发往任何上游的(被规则拒绝、选中的上游一个都接不了)上游是空的:写是哪一种, + 图形和流量表那一格一样 */} + {sent ? ( - {!r.local && } - {r.local ? t.answeredLocally : r.provider} + + {notSentText(sent)} + ) : ( + (r.local || r.provider) && ( + + {!r.local && } + {r.local ? t.answeredLocally : r.provider} + + ) )} @@ -341,6 +362,7 @@ function Timeline({ d, state }: { d: RequestDetail; state: ReturnType - + + {r.provider} + {t.notSentSuffix} + + ) : ( + r.provider || "—" + ) + } + /> {/* 密钥是身份;应用是按请求头推测的,能伪造;来源是这条连接对面的 地址,只有非本机来的才有 */} } /> @@ -532,30 +571,45 @@ function CostText({ r, running, short }: { r: HistoryRow; running: boolean; shor ); } -/** 路由:命中的规则、经过的策略组、尝试链 */ +/** + * 路由:走的哪条路由、哪条规则决定了去向、经过的策略组、改写了参数的规则、拒绝了它的 + * 规则和理由,然后是尝试链。全是 core 记下的(`RoutingView` 和失败的那一句),排法在 + * `routingFacts`。 + */ function Routing({ r, running }: { r: HistoryRow; running: boolean }) { const t = useText(requestDrawerText); + const f = routingFacts(r, running); // 只有本地应答的没有:它没到规则那一层 - if (!r.routing) return

{t.noRouting}

; - const attempts = r.routing.attempts; + if (!f) return

{t.noRouting}

; + const note = f.note && noteText(f.note, t); return (
{/* **「命中第 4 条」远不如「命中『带缓存的必须走官方』」有用** */} - - {r.routing.group && } + + + {f.rule} + {/* 决定去向的这一条就是拒绝:选定上游之前就被拒绝了 */} + {f.ruleDenied && {t.denied}} + + } + /> + {f.group && } + {/* 按求值的顺序:先是选定上游之前的,再是每一跳之后的 */} + {f.rewrittenBy.length > 0 && } + {f.deniedBy && {f.deniedBy}} />} + {f.reason && ( + + )}

{t.attempts}

- {/* - 尝试链是空的:还在等第一跳的结果;或者请求没有发给任何上游(被规则拒绝、 - 选中的上游一个都接不了),或者上游应答之前客户端就走了 - */} - {attempts.length === 0 ? ( -

{running ? t.routingPending : t.noAttempts}

- ) : ( + {f.hops.length > 0 && (
    - {attempts.map((a, i) => { + {f.hops.map(({ attempt: a, denied }, i) => { const outcome = attemptText(a); return (
  1. {i + 1} - + {a.provider} - {/* **失败的原因要留着** —— 一条说「试过 A → B → C」的链和一条还说清 - 每一跳为什么失败的链,排查价值差得远 */} - - {outcome.text} - - {ms(a.ms)} + {denied ? ( + // 选定上游之后的规则在这一跳拒绝了它:没有发给这个上游,不是上游的失败 + + {deniedHopText(f.deniedBy ?? "")} + + ) : ( + /* **失败的原因要留着** —— 一条说「试过 A → B → C」的链和一条还说清 + 每一跳为什么失败的链,排查价值差得远 */ + + {outcome.text} + + )} + {/* 没有发出的那一跳没有耗时可言 */} + {denied ? "—" : ms(a.ms)}
  2. ); })}
)} - {attempts.length > 1 && ( - // **用户能看见故障转移在替他工作,这是信任的来源**。一个静默切换过的请求和 - // 一次就成的请求,在他眼里应该是不同的 -

{t.failover(attempts.length - 1)}

- )} + {/* + **用户能看见故障转移在替他工作,这是信任的来源**。一个静默切换过的请求和一次就成 + 的请求,在他眼里应该是不同的。尝试链是空的时候,这一句说为什么是空的 + */} + {note &&

0 && "mt-2")}>{note}

}
); } +/** 拒绝:禁止符号加字,红色。和路由图上「拒绝」那个节点同一个图形 */ +function Denied({ children, className }: { children: ReactNode; className?: string }) { + return ( + + + {children} + + ); +} + +/** 尝试链下面那一句(见 `RoutingNote`)。只说字面上成立的事:被拒绝的那一跳不算切换成功 */ +function noteText(n: RoutingNote, t: (typeof requestDrawerText)["zh"]): string { + switch (n.kind) { + case "failover": + return t.failover(n.failed); + case "failover_denied": + return t.failoverDenied(n.failed, n.rule); + case "denied_after_pick": + return t.deniedAfterPick(n.rule); + case "denied_before_pick": + return t.deniedBeforePick(n.rule); + case "unavailable": + return t.unavailable; + case "pending": + return t.routingPending; + case "none": + return t.noAttempts; + } +} + /** * 用量:几种 token、费用、价格来源。**没有用量、没有价格、估算,各说各的。** * diff --git a/src/labels.i18n.ts b/src/labels.i18n.ts index 3fdf453d..10a616ec 100644 --- a/src/labels.i18n.ts +++ b/src/labels.i18n.ts @@ -64,6 +64,13 @@ export const labelsText = messages( rateLimited: "429 · 限流", upstreamError: (status: number | string) => `${status} · 上游错误`, noResponse: "未收到响应", + /** 选定上游之后被规则拒绝的那一跳:没有发给这个上游 */ + deniedHop: (rule: string) => `未发送 · 被规则「${rule}」拒绝`, + // 没有发往任何上游的请求,在「上游」的位置上写的那一句 + notSent: { + denied: "规则拒绝", + unavailable: "无可用上游", + }, // ------------------------------------------------------------ 请求与费用 quote: { @@ -186,6 +193,12 @@ export const labelsText = messages( rateLimited: "429 · Rate limited", upstreamError: (status: number | string) => `${status} · Upstream error`, noResponse: "No response received", + deniedHop: (rule: string) => `Not sent · denied by rule “${rule}”`, + // 流量表「上游」那一列放得下的长度:再长就折成两行 + notSent: { + denied: "Denied", + unavailable: "No upstream", + }, quote: { free: "Free.", diff --git a/src/labels.ts b/src/labels.ts index 650b75b3..a97605e3 100644 --- a/src/labels.ts +++ b/src/labels.ts @@ -23,6 +23,7 @@ import { } from "./types"; import { PROTOCOLS } from "./upstreams/labels"; import { labelsText } from "./labels.i18n"; +import type { NotSent } from "./requestRouting"; /* * 显示文字都在 `labels.i18n.ts`,每次调用都按当时的语言取(`textOf`)。 @@ -163,6 +164,16 @@ export function attemptText(a: AttemptView): { text: string; ok: boolean } { } } +/** 尝试链里被规则拒绝的那一跳(选定上游之后判断的规则):没有发给这个上游 */ +export function deniedHopText(rule: string): string { + return textOf(labelsText).deniedHop(rule); +} + +/** 没有发往任何上游的请求,在「上游」的位置上写什么:被规则拒绝,或者没有可用的上游 */ +export function notSentText(kind: NotSent): string { + return textOf(labelsText).notSent[kind]; +} + /** 做过的格式转换:`OpenAI Chat Completions → Anthropic Messages` */ export function translatedText(t: Pick): string { return `${formatLabel(t.from)} → ${formatLabel(t.to)}`; diff --git a/src/palette/items.test.ts b/src/palette/items.test.ts index 521e8c31..295a41a3 100644 --- a/src/palette/items.test.ts +++ b/src/palette/items.test.ts @@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest"; import type { Nav } from "@/nav"; import type { ConnView } from "@/connection/api"; import type { Overview, RequestRow } from "@/types"; +import { NotSentIcon } from "@/traffic/cells"; +import { UpstreamLogo } from "@/ui/logos"; import { score } from "./match"; import { buildItems, requestItems, type Sources } from "./items"; @@ -215,4 +217,46 @@ describe("命令面板里的请求", () => { expect(got).toHaveLength(1); expect(got[0]!.item.title).toBe("打开请求 #48123"); }); + + /** 条目的图形是哪一种:没有发往上游的是 `NotSentIcon`(带 `kind`),其余看组件本身 */ + const iconOf = (icon: unknown) => { + const el = icon as ReactElement<{ kind?: string; name?: string }>; + return el.type === NotSentIcon ? `not-sent:${el.props.kind}` : el.type === UpstreamLogo ? `upstream:${el.props.name}` : "other"; + }; + + it("没有发往任何上游的:图形和那一行说是被规则拒绝还是无可用上游,不画「?」方块", () => { + const denied = row(203, "claude-opus-5", { + provider: "", + client: "codex", + state: "failed", + error: { code: "gw.route.denied", args: { rule: "no-opus", reason: "Opus is not offered" }, text: "" }, + }); + const nowhere = row(202, "moonshotai/kimi-k2", { + provider: "", + client: "codex", + state: "failed", + error: { code: "gw.model.no_upstream_available", args: { model: "moonshotai/kimi-k2", detail: "" }, text: "" }, + }); + // 选定上游之后被拒绝的记在要去的那个上游上:照常画那个上游 + const afterPick = row(201, "claude-sonnet-5", { + provider: "openrouter", + client: "claude-code", + state: "failed", + error: { code: "gw.route.denied", args: { rule: "no-images-via-relay", reason: "" }, text: "" }, + }); + const got = requestItems([denied, nowhere, afterPick], ov, nav, () => 0, "20", 5).map((x) => x.item); + expect(got.map((i) => [i.id, iconOf(i.icon), i.detail])).toEqual([ + ["request:203", "not-sent:denied", "#203 · 规则拒绝 · codex"], + ["request:202", "not-sent:unavailable", "#202 · 无可用上游 · codex"], + ["request:201", "upstream:openrouter", "#201 · openrouter · claude-code"], + ["request:20", "other", undefined], + ]); + }); + + it("本地应答的:标题是辅助请求的类别,图形是网关,按原词也搜得到", () => { + // 流量表给本地应答那几行的「上游」是那一句说明,不是上游的名字 + const local = row(301, "", { model: undefined, provider: "本地应答", local: true, path: "titling", client: "claude-code" }); + const got = requestItems([local], ov, nav, (t, kw) => score("titling", t, kw), null, 5).map((x) => x.item); + expect(got.map((i) => [i.title, iconOf(i.icon), i.detail])).toEqual([["生成标题", "other", "#301 · 本地应答 · claude-code"]]); + }); }); diff --git a/src/palette/items.tsx b/src/palette/items.tsx index e2363d56..23872ce2 100644 --- a/src/palette/items.tsx +++ b/src/palette/items.tsx @@ -21,6 +21,7 @@ import { IconClient, IconDashboard, IconFlow, + IconGateway, IconGuard, IconKey, IconLocal, @@ -33,8 +34,10 @@ import { } from "@/ui/icons"; import { ClientLogo, UpstreamLogo } from "@/ui/logos"; import { StatusDot, type StatusTone } from "@/ui/status-dot"; -import { groupKindLabel, targetLabel, ALL_UPSTREAMS } from "@/labels"; +import { groupKindLabel, notSentText, probeLabel, targetLabel, ALL_UPSTREAMS } from "@/labels"; import { when } from "@/format"; +import { notSent } from "@/requestRouting"; +import { NotSentIcon } from "@/traffic/cells"; import type { ConnView } from "@/connection/api"; import { connText } from "@/connection/connection.i18n"; import { profileName } from "@/connection/describe"; @@ -446,29 +449,40 @@ export function requestItems( /** 按模型搜时已经列过的模型(`rows` 新的在前,先碰到的就是最近的那一条) */ const seen = new Set(); for (const r of rows) { + // 本地应答的没有模型,路径是辅助请求的类别(`titling`):标题写类别的名字,原词留着搜 + const title = r.model || (r.local ? probeLabel(r.path) : r.path); + const keywords = r.local && !r.model ? [r.path] : []; let sc: number; if (idQuery !== null) { const id = String(r.id); sc = id === idQuery ? 1 : id.startsWith(idQuery) ? 0.85 : 0; } else { - const title = r.model || r.path; if (seen.has(title)) continue; - sc = scoreOf(title, []); + sc = scoreOf(title, keywords); if (sc >= 0.5) seen.add(title); } if (sc < 0.5) continue; const p = baseOf.get(r.provider); const tone: StatusTone | null = r.state === "in_flight" ? "pending" : r.state === "failed" ? "error" : null; + // 没有发往任何上游的(被规则拒绝、选中的上游一个都接不了)上游是空的:图形和那一行说是 + // 哪一种,不画一个「?」方块。本地应答的「上游」一格是那一句说明,不是上游的名字 + const sent = notSent(r); out.push({ row: r, score: sc, item: { id: `request:${r.id}`, group: "requests", - title: r.model || r.path, - detail: [t.requestNo(r.id), r.provider, r.client].filter(Boolean).join(" · "), - icon: , + title, + detail: [t.requestNo(r.id), sent ? notSentText(sent) : r.provider, r.client].filter(Boolean).join(" · "), + icon: sent ? ( + + ) : r.local ? ( + + ) : ( + + ), meta: ( <> {tone && } diff --git a/src/requestRouting.test.ts b/src/requestRouting.test.ts new file mode 100644 index 00000000..0d72d12f --- /dev/null +++ b/src/requestRouting.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import { notSent, routingFacts } from "./requestRouting"; +import type { AttemptView, HistoryRow, Msg, RoutingView } from "./types"; + +/** core 规则拒绝时的那一句(`gw.route.denied`) */ +const denied = (rule: string, reason: string): Msg => ({ + code: "gw.route.denied", + args: { rule, reason }, + text: `Rule \`${rule}\` denied this request: ${reason}`, +}); +const unavailable: Msg = { + code: "gw.model.no_upstream_available", + args: { model: "moonshotai/kimi-k2", detail: "chatgpt does not offer this model" }, + text: "No upstream is available to serve model moonshotai/kimi-k2: chatgpt does not offer this model", +}; +const served = (provider: string, ms = 900): AttemptView => ({ provider, outcome: "served", status: 200, ms }); +const overloaded = (provider: string): AttemptView => ({ provider, outcome: "status", status: 529, ms: 1_870 }); + +function row(routing: Partial, over: Partial> = {}) { + return { + provider: "anthropic", + local: false, + error: null, + ...over, + routing: { route: "default", rule: "catch-all", group: "main", rewritten_by: [], denied_by: null, attempts: [], ...routing }, + }; +} + +describe("没有发往任何上游的请求", () => { + it("上游是空的:规则拒绝的看失败的那一句,其余是选中的上游接不了", () => { + expect(notSent({ provider: "", error: denied("no-opus", "Opus is not offered") })).toBe("denied"); + expect(notSent({ provider: "", error: unavailable })).toBe("unavailable"); + expect(notSent({ provider: "", error: { code: "gw.route.all_selected_disabled", args: {}, text: "" } })).toBe("unavailable"); + }); + + it("发往了上游的、本地应答的、还没有结局的都不算", () => { + // 选定上游之后才被拒绝:记在要去的那个上游上 + expect(notSent({ provider: "openrouter", error: denied("no-images", "no images") })).toBeNull(); + expect(notSent({ provider: "", local: true, error: null })).toBeNull(); + expect(notSent({ provider: "", error: undefined })).toBeNull(); + expect(notSent({ provider: "anthropic", error: null })).toBeNull(); + }); +}); + +describe("路由那一页", () => { + it("本地应答的没有路由", () => { + expect(routingFacts({ routing: null, error: null, provider: "", local: true }, false)).toBeNull(); + }); + + it("一次就成:路由、规则、策略组,尝试链一跳,不加说明", () => { + const f = routingFacts(row({ attempts: [served("anthropic")] }), false)!; + expect(f).toMatchObject({ route: "default", rule: "catch-all", ruleDenied: false, group: "main", deniedBy: null, reason: null, note: null }); + expect(f.hops).toEqual([{ attempt: served("anthropic"), denied: false }]); + }); + + it("改写了参数的规则按求值的顺序列出", () => { + const f = routingFacts(row({ rewritten_by: ["long-context", "relay-no-thinking"], attempts: [served("anthropic")] }), false)!; + expect(f.rewrittenBy).toEqual(["long-context", "relay-no-thinking"]); + }); + + it("故障转移:前几个上游失败、换到下一个", () => { + const f = routingFacts(row({ attempts: [overloaded("anthropic"), served("openrouter")] }, { provider: "openrouter" }), false)!; + expect(f.note).toEqual({ kind: "failover", failed: 1 }); + expect(f.hops.map((h) => h.denied)).toEqual([false, false]); + }); + + it("选定上游之前被拒绝:没有尝试,原因是规则里写的那句", () => { + const f = routingFacts( + row({ route: "codex", rule: "no-opus", group: null, attempts: [] }, { provider: "", error: denied("no-opus", "Opus is not offered") }), + false, + )!; + expect(f).toMatchObject({ rule: "no-opus", ruleDenied: true, deniedBy: null, group: null, hops: [] }); + expect(f.reason).toEqual({ text: "Opus is not offered" }); + expect(f.note).toEqual({ kind: "denied_before_pick", rule: "no-opus" }); + }); + + it("在第二跳被拒绝:那一跳标成没有发出,说明不把拒绝说成故障转移成功", () => { + const why = denied("no-images-via-relay", "Requests with images are not sent through the relay"); + const f = routingFacts( + row( + { + denied_by: "no-images-via-relay", + attempts: [overloaded("anthropic"), { provider: "openrouter", outcome: "error", error: why, ms: 1 }], + }, + { provider: "openrouter", error: why }, + ), + false, + )!; + // 决定去向的规则没有拒绝它:拒绝它的是选定上游之后的那一条 + expect(f.ruleDenied).toBe(false); + expect(f.deniedBy).toBe("no-images-via-relay"); + expect(f.hops.map((h) => [h.attempt.provider, h.denied])).toEqual([ + ["anthropic", false], + ["openrouter", true], + ]); + expect(f.note).toEqual({ kind: "failover_denied", failed: 1, rule: "no-images-via-relay" }); + expect(f.reason).toEqual({ text: "Requests with images are not sent through the relay" }); + }); + + it("唯一的一跳就被拒绝:没有故障转移", () => { + const why = denied("no-images-via-relay", "no images"); + const f = routingFacts( + row({ denied_by: "no-images-via-relay", attempts: [{ provider: "openrouter", outcome: "error", error: why, ms: 1 }] }, { provider: "openrouter", error: why }), + false, + )!; + expect(f.hops[0]!.denied).toBe(true); + expect(f.note).toEqual({ kind: "denied_after_pick", rule: "no-images-via-relay" }); + }); + + it("规则没写理由:不出「原因」那一行", () => { + const f = routingFacts(row({ rule: "no-opus", attempts: [] }, { provider: "", error: denied("no-opus", "") }), false)!; + expect(f.ruleDenied).toBe(true); + expect(f.reason).toBeNull(); + }); + + it("选中的上游都接不了:原因是 core 说的那一句", () => { + const f = routingFacts(row({ route: "codex", group: null, attempts: [] }, { provider: "", error: unavailable }), false)!; + expect(f.ruleDenied).toBe(false); + expect(f.reason).toEqual({ msg: unavailable }); + expect(f.note).toEqual({ kind: "unavailable" }); + }); + + it("尝试链是空的:在跑的是还没走完,结束了的是没有尝试记录", () => { + expect(routingFacts(row({ attempts: [] }), true)!.note).toEqual({ kind: "pending" }); + // 上游应答之前客户端就走了:上游是开始时要发往的那一个 + expect(routingFacts(row({ attempts: [] }), false)!.note).toEqual({ kind: "none" }); + }); +}); diff --git a/src/requestRouting.ts b/src/requestRouting.ts new file mode 100644 index 00000000..7a26f457 --- /dev/null +++ b/src/requestRouting.ts @@ -0,0 +1,138 @@ +import type { AttemptView, HistoryRow, Msg } from "./types"; + +/** + * 一条请求的路由结论,给详情抽屉的「路由」那一页和几处列表用。全是 core 记下的事实 + * (`RoutingView`、失败的那一句),这里只把它们排成要显示的几行,不猜。 + */ + +/** 规则拒绝时 core 说的那一句:`gw.route.denied {rule, reason}`。码和参数名是契约 */ +const DENIED = "gw.route.denied"; + +/** + * 一条请求为什么没有发往任何上游: + * + * · `denied`:规则拒绝了它(选定上游之前) + * · `unavailable`:规则选中的上游一个都接不了(停用、不在范围内、不提供这个模型) + * + * 发往了上游的、本地应答的、还没有结局的是 `null`。 + * + * **上游是空的就是没有发往任何上游**:core 只在规则做了决定、请求却一个上游都不会去时 + * 把上游记成空的(本地应答另有 `local`)。是哪一种看失败的那一句:规则拒绝的是 + * `gw.route.denied`,其余是选中的上游接不了。 + */ +export type NotSent = "denied" | "unavailable"; + +export function notSent(r: { local?: boolean; provider: string; error?: Msg | null }): NotSent | null { + if (r.local || r.provider !== "" || !r.error) return null; + return r.error.code === DENIED ? "denied" : "unavailable"; +} + +/** 尝试链里的一跳。`denied`:选定上游之后的规则在这一跳拒绝了它,**没有发给这个上游** */ +export interface Hop { + attempt: AttemptView; + denied: boolean; +} + +/** + * 尝试链下面那一句。只说字面上成立的事: + * + * · `failover`:前 `failed` 个上游失败,换到了下一个(最后一跳的结果在它自己那一行) + * · `failover_denied`:前 `failed` 个上游失败,换到下一个之后被规则 `rule` 拒绝,没有发给它 + * · `denied_after_pick`:唯一的那一跳被规则 `rule` 拒绝:没有发往任何上游 + * · `denied_before_pick`:选定上游之前规则 `rule` 就拒绝了它:没有发往任何上游 + * · `unavailable`:规则选中的上游都接不了:没有发往任何上游 + * · `pending`:还在跑,路由还没有结论 + * · `none`:没有尝试记录(上游应答之前客户端就走了、被请求防护挡下……) + * + * 一次就成的是 `null`:没有要说的。 + */ +export type RoutingNote = + | { kind: "failover"; failed: number } + | { kind: "failover_denied"; failed: number; rule: string } + | { kind: "denied_after_pick"; rule: string } + | { kind: "denied_before_pick"; rule: string } + | { kind: "unavailable" } + | { kind: "pending" } + | { kind: "none" }; + +/** 「原因」那一行:规则里写的拒绝理由(用户自己写的字),或者 core 说的那一句 */ +export type RoutingReason = { text: string } | { msg: Msg }; + +export interface RoutingFacts { + /** 走的哪条路由 */ + route: string; + /** 决定去向的那条规则 */ + rule: string; + /** 这条规则就是拒绝:选定上游之前就被拒绝了 */ + ruleDenied: boolean; + group: string | null; + /** 改写了参数的规则,**按求值的顺序**(先选上游之前的,再每一跳之后的) */ + rewrittenBy: string[]; + /** 选定上游之后才判断、拒绝了它的那条规则 */ + deniedBy: string | null; + reason: RoutingReason | null; + hops: Hop[]; + note: RoutingNote | null; +} + +/** `gw.route.denied` 里规则写的那句理由。规则没写理由时是空的,当作没有 */ +function denyReason(m: Msg | null | undefined): string | null { + if (m?.code !== DENIED) return null; + return m.args?.reason || null; +} + +/** + * 把一条请求的路由记录排成「路由」那一页要显示的样子。本地应答的没有路由,是 `null`。 + * + * `running`:请求还在跑。那时尝试链是空的只是还没走完,不是没有尝试。 + */ +export function routingFacts( + r: Pick, + running: boolean, +): RoutingFacts | null { + const routing = r.routing; + if (!routing) return null; + const attempts = routing.attempts; + const n = attempts.length; + const why = notSent(r); + // 选定上游之前就被拒绝:一跳都没有,失败的那一句是规则拒绝 + const ruleDenied = n === 0 && why === "denied"; + const deniedBy = routing.denied_by ?? null; + // 被拒的那一跳(链的最后一跳)自己带着那一句;它和请求失败的那一句是同一句 + const deniedHop = deniedBy && n > 0 ? attempts[n - 1] : undefined; + + let reason: RoutingReason | null = null; + if (ruleDenied || deniedBy) { + const text = denyReason(deniedHop?.error) ?? denyReason(r.error); + reason = text ? { text } : null; + } else if (why === "unavailable" && r.error) { + reason = { msg: r.error }; + } + + let note: RoutingNote | null = null; + if (n === 0) { + if (ruleDenied) note = { kind: "denied_before_pick", rule: routing.rule }; + else if (why === "unavailable") note = { kind: "unavailable" }; + else note = { kind: running ? "pending" : "none" }; + } else if (deniedBy) { + // 被拒的那一跳不算切换成功:前面几跳失败、换过来,才被拒绝 + note = + n > 1 + ? { kind: "failover_denied", failed: n - 1, rule: deniedBy } + : { kind: "denied_after_pick", rule: deniedBy }; + } else if (n > 1) { + note = { kind: "failover", failed: n - 1 }; + } + + return { + route: routing.route, + rule: routing.rule, + ruleDenied, + group: routing.group ?? null, + rewrittenBy: routing.rewritten_by, + deniedBy, + reason, + hops: attempts.map((attempt, i) => ({ attempt, denied: deniedBy !== null && i === n - 1 })), + note, + }; +} diff --git a/src/routing/ChainMap.tsx b/src/routing/ChainMap.tsx index 45d27abd..ebdc295b 100644 --- a/src/routing/ChainMap.tsx +++ b/src/routing/ChainMap.tsx @@ -1,6 +1,5 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; -import { BanIcon } from "lucide-react"; -import { IconRoute } from "@/ui/icons"; +import { IconDenied, IconRoute } from "@/ui/icons"; import { prefersReducedMotion } from "@/ui/motion"; import { StatusDot } from "@/ui/status-dot"; import { Tip } from "@/ui/tip"; @@ -440,7 +439,7 @@ function describe( return { body: ( <> - + {rt.deny} ), diff --git a/src/routing/DryRunDialog.tsx b/src/routing/DryRunDialog.tsx index 60136750..311b0b74 100644 --- a/src/routing/DryRunDialog.tsx +++ b/src/routing/DryRunDialog.tsx @@ -1,5 +1,5 @@ import { Fragment, useEffect, useId, useMemo, useState, type ReactNode } from "react"; -import { BanIcon, ChevronRightIcon, CircleCheckIcon, CircleDotIcon, CircleMinusIcon } from "lucide-react"; +import { ChevronRightIcon, CircleCheckIcon, CircleDotIcon, CircleMinusIcon } from "lucide-react"; import { Badge } from "@/ui/badge"; import { Banner } from "@/ui/banner"; import { Button } from "@/ui/button"; @@ -13,7 +13,7 @@ import { DialogTitle, } from "@/ui/dialog"; import { Field, FieldLabel } from "@/ui/field"; -import { IconRoute } from "@/ui/icons"; +import { IconDenied, IconRoute } from "@/ui/icons"; import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { Skeleton } from "@/ui/skeleton"; @@ -397,7 +397,7 @@ function Result({ } else if (r.outcome === "deny") { steps.push( - + {rt.deny} , ); diff --git a/src/routing/RouteDialog.tsx b/src/routing/RouteDialog.tsx index 6eecefa6..1573b5ad 100644 --- a/src/routing/RouteDialog.tsx +++ b/src/routing/RouteDialog.tsx @@ -1,5 +1,5 @@ import { useMemo, useState, type KeyboardEvent, type MouseEvent } from "react"; -import { BanIcon, FlaskConicalIcon, GripVerticalIcon, PlusIcon } from "lucide-react"; +import { FlaskConicalIcon, GripVerticalIcon, PlusIcon } from "lucide-react"; import { Badge } from "@/ui/badge"; import { Banner } from "@/ui/banner"; import { Button } from "@/ui/button"; @@ -12,6 +12,7 @@ import { DialogHeader, DialogTitle, } from "@/ui/dialog"; +import { IconDenied } from "@/ui/icons"; import { Input } from "@/ui/input"; import { rowMotion, usePresentList } from "@/ui/motion"; import { RowMenu, RowMenuButton, type MenuItems } from "@/ui/row-menu"; @@ -477,7 +478,7 @@ function Action({ r, ov }: { r: RuleDraft; ov: Overview }) { return (
- + {rt.deny}
{r.deny}
diff --git a/src/traffic/RequestTable.tsx b/src/traffic/RequestTable.tsx index ebcbaadb..ce095d52 100644 --- a/src/traffic/RequestTable.tsx +++ b/src/traffic/RequestTable.tsx @@ -3,8 +3,9 @@ import { useText } from "@/i18n"; import { coreText } from "@/i18n/core.i18n"; import { cn } from "@/lib/utils"; import { latency, money, statusTone, tokens, when } from "@/format"; -import { translatedText } from "@/labels"; +import { notSentText, translatedText } from "@/labels"; import { ruleName } from "@/security/labels"; +import { notSent } from "@/requestRouting"; import { promptTokens, type Filter, type SortDir, type SortKey } from "@/requestTable"; import type { RequestRow } from "@/types"; import { Badge } from "@/ui/badge"; @@ -15,7 +16,7 @@ import { Skeleton } from "@/ui/skeleton"; import { StatusDot, type StatusTone } from "@/ui/status-dot"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/ui/table"; import { Tip } from "@/ui/tip"; -import { copyText, DIM, Elapsed, Lines, MENU_REVEAL, ROW, RowKeyCell } from "./cells"; +import { copyText, DIM, Elapsed, Lines, MENU_REVEAL, NotSentIcon, ROW, RowKeyCell } from "./cells"; import { sortWithin, type Cursor, type Group } from "./grouping"; import { SessionRow } from "./SessionRow"; import { trafficText } from "./Traffic.i18n"; @@ -573,17 +574,29 @@ function StatusCell({ r }: { r: RequestRow }) { */ function UpstreamCell({ r }: { r: RequestRow }) { const t = useText(trafficText); + const sent = notSent(r); return (
{/* 本地应答的那一句(英文两个词)可以在词间折行:它不是一个名字,别让它定这一列的最小宽度 */} - - {r.local || !r.provider ? ( - + + {/* 被规则拒绝、选中的上游一个都接不了的请求没有发往任何上游:上游是空的, + 这一格说是哪一种,图形和路由图上的拒绝一致。和本地应答一样是一句话、不是 + 名字,可以在词间折行 */} + {sent ? ( + <> + + {notSentText(sent)} + ) : ( - + <> + {r.local || !r.provider ? ( + + ) : ( + + )} + {r.provider ? {r.provider} : —} + )} - {/* 被规则拒绝、选中的上游一个都接不了的请求没有发往任何上游:上游是空的 */} - {r.provider ? {r.provider} : —} {/* **看不见的安全功能会被用户关掉**,因为他们会怀疑是脱敏搞坏了功能。 所以脱敏发生了就要在列表这一层看得见,而不是藏在详情里 */} diff --git a/src/traffic/cells.tsx b/src/traffic/cells.tsx index ee70556a..b72681ba 100644 --- a/src/traffic/cells.tsx +++ b/src/traffic/cells.tsx @@ -3,8 +3,10 @@ import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { appLabel } from "@/labels"; import { keyText } from "@/KeyLabel"; +import { cn } from "@/lib/utils"; +import type { NotSent } from "@/requestRouting"; import type { RequestRow } from "@/types"; -import { IconRemote } from "@/ui/icons"; +import { IconDenied, IconNoUpstream, IconRemote } from "@/ui/icons"; import { ClientLogo } from "@/ui/logos"; import { notify } from "@/ui/notify"; import { Tip } from "@/ui/tip"; @@ -101,6 +103,24 @@ export function RowKeyCell({ r, hints }: { r: RequestRow; hints: boolean }) { return ; } +/** + * 没有发往任何上游的请求在上游标志的位置上画什么:被规则拒绝是禁止符号(和路由图上 + * 「拒绝」那个节点同一个),没有可用的上游是划掉的上游。和上游标志一样大,名字对得齐。 + * + * 拒绝带红色,和路由图一致;`plain` 时跟着周围的字色(命令面板里的图标都是单色)。 + */ +export function NotSentIcon({ kind, plain }: { kind: NotSent; plain?: boolean }) { + const Icon = kind === "denied" ? IconDenied : IconNoUpstream; + return ( + + ); +} + /** * 一个在跑的请求已经跑了多久(`0:42`),每秒走一格。`at` 是开始事件的 `at_ms`,core * 的钟;减的也是 core 的钟(见 `clock.ts`)。还没对过钟时写「…」。 diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index e09a7a36..13e2cbde 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -25,6 +25,8 @@ export { Router as IconGateway } from "lucide-react"; // 网关 —— 一台路 export { Laptop as IconClient } from "lucide-react"; // 客户端 —— 一台笔电 export { Plug as IconMcp } from "lucide-react"; // MCP —— 给客户端接上的插头 export { Server as IconServer } from "lucide-react"; // 上游 —— 一摞机器 +export { ServerOff as IconNoUpstream } from "lucide-react"; // 没有可用的上游 —— 那一摞机器划掉 +export { Ban as IconDenied } from "lucide-react"; // 被规则拒绝 —— 禁止符号 export { KeyRound as IconKey } from "lucide-react"; // 密钥 —— 钥匙,不是锁 export { SlidersHorizontal as IconSettings } from "lucide-react"; // 设置 —— 推子,齿轮留给系统设置 export { PanelLeft as IconSidebar } from "lucide-react"; // 收起/展开源列表 From 040a099662ec734b11cab5d3bf821988c51c1619 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:37:07 +0800 Subject: [PATCH 2/2] Palette: a request with no upstream yet is drawn as a request, not a letter tile A request that core started with no upstream is in flight only until its failure arrives. Draw it with the request icon in that moment too. Co-Authored-By: Claude Opus 5.5 --- src/palette/items.test.ts | 5 ++++- src/palette/items.tsx | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/palette/items.test.ts b/src/palette/items.test.ts index 295a41a3..54533110 100644 --- a/src/palette/items.test.ts +++ b/src/palette/items.test.ts @@ -244,8 +244,11 @@ describe("命令面板里的请求", () => { state: "failed", error: { code: "gw.route.denied", args: { rule: "no-images-via-relay", reason: "" }, text: "" }, }); - const got = requestItems([denied, nowhere, afterPick], ov, nav, () => 0, "20", 5).map((x) => x.item); + // 开始时就没有上游、失败还没到的那一瞬:也不画「?」 + const starting = row(204, "claude-opus-5", { provider: "", client: "codex", state: "in_flight" }); + const got = requestItems([starting, denied, nowhere, afterPick], ov, nav, () => 0, "20", 5).map((x) => x.item); expect(got.map((i) => [i.id, iconOf(i.icon), i.detail])).toEqual([ + ["request:204", "other", "#204 · codex"], ["request:203", "not-sent:denied", "#203 · 规则拒绝 · codex"], ["request:202", "not-sent:unavailable", "#202 · 无可用上游 · codex"], ["request:201", "upstream:openrouter", "#201 · openrouter · claude-code"], diff --git a/src/palette/items.tsx b/src/palette/items.tsx index 23872ce2..72970834 100644 --- a/src/palette/items.tsx +++ b/src/palette/items.tsx @@ -480,8 +480,11 @@ export function requestItems( ) : r.local ? ( - ) : ( + ) : r.provider ? ( + ) : ( + // 开始时就没有上游、结局还没到的那一瞬:画成一条请求 + ), meta: ( <>