diff --git a/scripts/shots/core/config.en.yaml b/scripts/shots/core/config.en.yaml index d677ace6..8e9208d9 100644 --- a/scripts/shots/core/config.en.yaml +++ b/scripts/shots/core/config.en.yaml @@ -38,7 +38,7 @@ providers: refresh: rt_7HEXAMPLEMnB2 endpoint: https://auth.openai.com/oauth/token client_id: app_EMoamEEZ73f0CkXaXp7hrann - access: eyJhbEXAMPLEc2ln + access: eyJhbGciOiJub25lIn0.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJwbHVzIn0sImh0dHBzOi8vYXBpLm9wZW5haS5jb20vcHJvZmlsZSI6eyJlbWFpbCI6ImFsZXhAZXhhbXBsZS5jb20ifX0.EXAMPLE expires_at: "2026-10-04T08:12:40Z" - name: openrouter base_url: https://openrouter.ai/api/v1 diff --git a/scripts/shots/core/config.zh.yaml b/scripts/shots/core/config.zh.yaml index 99ff746e..b89b2cf3 100644 --- a/scripts/shots/core/config.zh.yaml +++ b/scripts/shots/core/config.zh.yaml @@ -38,7 +38,7 @@ providers: refresh: rt_7HEXAMPLEMnB2 endpoint: https://auth.openai.com/oauth/token client_id: app_EMoamEEZ73f0CkXaXp7hrann - access: eyJhbEXAMPLEc2ln + access: eyJhbGciOiJub25lIn0.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJwbHVzIn0sImh0dHBzOi8vYXBpLm9wZW5haS5jb20vcHJvZmlsZSI6eyJlbWFpbCI6ImFsZXhAZXhhbXBsZS5jb20ifX0.EXAMPLE expires_at: "2026-10-04T08:12:40Z" - name: openrouter base_url: https://openrouter.ai/api/v1 diff --git a/scripts/shots/core/en/overview.json b/scripts/shots/core/en/overview.json index 46fb35c3..41a4d744 100644 --- a/scripts/shots/core/en/overview.json +++ b/scripts/shots/core/en/overview.json @@ -58,7 +58,7 @@ "route": "cursor" } ], - "config_version": "blake3:8cda33aea2d3", + "config_version": "blake3:99aaf5e60d80", "default_route": "default", "groups": [ { @@ -211,6 +211,10 @@ "models": [], "name": "chatgpt", "oauth": { + "account": { + "email": "alex@example.com", + "plan": "plus" + }, "client_id": "app_EMoamEEZ73f0CkXaXp7hrann", "endpoint": "https://auth.openai.com/oauth/token", "expires_at": "2026-10-04T08:12:40Z" diff --git a/scripts/shots/core/en/status.json b/scripts/shots/core/en/status.json index 458fbbb3..5f02399f 100644 --- a/scripts/shots/core/en/status.json +++ b/scripts/shots/core/en/status.json @@ -1,5 +1,5 @@ { - "api_version": 20, + "api_version": 21, "clients": 4, "config_path": "", "gateway_addr": null, @@ -14,5 +14,5 @@ "reachable": [] }, "uptime_secs": 0, - "version": "0.47.0" + "version": "0.48.0" } diff --git a/scripts/shots/core/zh/overview.json b/scripts/shots/core/zh/overview.json index 0d0b3790..409b3cfc 100644 --- a/scripts/shots/core/zh/overview.json +++ b/scripts/shots/core/zh/overview.json @@ -58,7 +58,7 @@ "route": "cursor" } ], - "config_version": "blake3:4daf5fdd341b", + "config_version": "blake3:b3ea6e73d991", "default_route": "default", "groups": [ { @@ -211,6 +211,10 @@ "models": [], "name": "chatgpt", "oauth": { + "account": { + "email": "alex@example.com", + "plan": "plus" + }, "client_id": "app_EMoamEEZ73f0CkXaXp7hrann", "endpoint": "https://auth.openai.com/oauth/token", "expires_at": "2026-10-04T08:12:40Z" diff --git a/scripts/shots/core/zh/status.json b/scripts/shots/core/zh/status.json index 458fbbb3..5f02399f 100644 --- a/scripts/shots/core/zh/status.json +++ b/scripts/shots/core/zh/status.json @@ -1,5 +1,5 @@ { - "api_version": 20, + "api_version": 21, "clients": 4, "config_path": "", "gateway_addr": null, @@ -14,5 +14,5 @@ "reachable": [] }, "uptime_secs": 0, - "version": "0.47.0" + "version": "0.48.0" } diff --git a/scripts/shots/mock/app.ts b/scripts/shots/mock/app.ts index 2cd4d943..c93e9aee 100644 --- a/scripts/shots/mock/app.ts +++ b/scripts/shots/mock/app.ts @@ -58,7 +58,7 @@ export const updateView = (): UpdateView => ({ version: APP_VERSION, install: "s // ───────────────────────────────────────── 连接 /** 这一版应用配的 core */ -export const CORE_VERSION = "0.47.0"; +export const CORE_VERSION = "0.48.0"; const PROFILES: Profile[] = [ { id: "local", name: "", local: true, host: null, port: null, addr: null, last_connected_at: NOW - 2 * HOUR }, diff --git a/scripts/shots/mock/core.ts b/scripts/shots/mock/core.ts index 8077aae5..c27b348e 100644 --- a/scripts/shots/mock/core.ts +++ b/scripts/shots/mock/core.ts @@ -18,7 +18,7 @@ import { security, keys, } from "./config"; -import { HISTORY, IN_FLIGHT, SEC_EVENTS, bodies, lastSeen, sessionView, sessions, turns, unpricedModels } from "./traffic"; +import { HISTORY, IN_FLIGHT, SEC_EVENTS, bodies, lastSeen, routeStats, sessionView, sessions, turns, unpricedModels } from "./traffic"; import { DAY, HOUR, NOW, clone, msg } from "./util"; type Handler = (req: Endpoints[N]["req"], params: string[]) => Endpoints[N]["res"]; @@ -61,7 +61,7 @@ export const CORE: { [N in WebviewEndpoint]: Handler } = { overview(lastSeen()) .providers.filter((p) => !req.provider || p.name === req.provider) .map((p) => l1(p.name, p.proxy === "direct" || p.proxy === "system" ? null : p.proxy)), - InFlight: () => clone(IN_FLIGHT), + InFlight: () => ({ now_ms: Date.now(), requests: clone(IN_FLIGHT) }), GetConfig: () => ({ path: "~/.thinkwatch/config.yaml", text: CONFIG_TEXT, version: configVersion() }), PatchConfig: refuse, @@ -119,6 +119,8 @@ export const CORE: { [N in WebviewEndpoint]: Handler } = { UpdateGroup: refuse, DeleteGroup: refuse, KnownModels: () => knownModels(), + // 没给时间窗就是今天:本地零点到现在(`Window` 的默认) + RouteStats: (req) => routeStats(req.from_ms ?? new Date(NOW).setHours(0, 0, 0, 0), req.to_ms ?? Date.now()), Pricing: () => pricing(unpricedModels()), RefreshPricing: refuse, @@ -138,15 +140,18 @@ export const CORE: { [N in WebviewEndpoint]: Handler } = { Security: () => security(), SecurityEvents: (req) => { - const xs = SEC_EVENTS.filter( + // 总数和各做法的条数是整段时间的,翻到第几页都一样(`before` 只是翻页的位置) + const window = SEC_EVENTS.filter( (e) => (!req.guard || e.guard === req.guard) && (req.from_ms == null || e.at_ms >= req.from_ms) && - (req.to_ms == null || e.at_ms < req.to_ms) && - (req.before == null || e.id < req.before), + (req.to_ms == null || e.at_ms < req.to_ms), ); + const xs = window.filter((e) => req.before == null || e.id < req.before); const limit = req.limit ?? 100; - return { events: clone(xs.slice(0, limit)), more: xs.length > limit }; + const by_outcome = { recorded: 0, replaced: 0, cut: 0, blocked: 0 }; + for (const e of window) by_outcome[e.action] += 1; + return { events: clone(xs.slice(0, limit)), more: xs.length > limit, total: window.length, by_outcome }; }, SetSecurityMode: refuse, ToggleBuiltinRule: refuse, @@ -158,9 +163,8 @@ export const CORE: { [N in WebviewEndpoint]: Handler } = { TestSecurity: () => ({ hits: [] }), ChatgptLoginStatus: refuse, + // 登的是谁不在这里:core 从凭据的令牌里读,在上游视图的 `oauth.account`(overview.json) ChatgptUsage: () => ({ - email: "alex@example.com", - plan: "plus", windows: CHATGPT_WINDOWS(), reset_credits: 1, }), diff --git a/scripts/shots/mock/traffic.ts b/scripts/shots/mock/traffic.ts index df3a0eb4..1e406746 100644 --- a/scripts/shots/mock/traffic.ts +++ b/scripts/shots/mock/traffic.ts @@ -14,11 +14,12 @@ import type { CostBucketGroup, CostGroup, Dialect, - Event, HistoryRow, + InFlightRequest, LatencyView, Msg, PriceFields, + RouteHits, RoutingView, SecurityEventView, SessionView, @@ -60,22 +61,26 @@ const PROTOCOL: Record = { ollama: "openai-chat", }; -/** 按 config.*.yaml 的路由规则走:哪条规则、哪个策略组、先试哪家 */ -function route(who: Who, model: string): { rule: string; group: string | null; order: string[] } { +/** + * 按 config.*.yaml 的路由规则走:哪条路由(密钥指定的那条,没指定的走默认路由)、 + * 哪条规则、哪个策略组、先试哪家 + */ +function route(who: Who, model: string): { route: string; rule: string; group: string | null; order: string[] } { if (who === "codex") { - if (model.startsWith("qwen/")) return { rule: N.qwen, group: null, order: ["openrouter"] }; - return { rule: N.catchAll, group: null, order: ["chatgpt"] }; + if (model.startsWith("qwen/")) return { route: "codex", rule: N.qwen, group: null, order: ["openrouter"] }; + return { route: "codex", rule: N.catchAll, group: null, order: ["chatgpt"] }; } if (who === "cursor") { - if (model.startsWith("gemini-")) return { rule: N.gemini, group: null, order: ["gemini"] }; + if (model.startsWith("gemini-")) return { route: "cursor", rule: N.gemini, group: null, order: ["gemini"] }; // `cheapest` 按输入单价排:中转打八折,排在官方前面(tw-engine 的 `order_by`) - return { rule: N.catchAll, group: N.budget, order: ["relay", "anthropic"] }; + return { route: "cursor", rule: N.catchAll, group: N.budget, order: ["relay", "anthropic"] }; } - if (model.startsWith("claude-opus-")) return { rule: N.opus, group: null, order: ["anthropic"] }; - if (model.startsWith("deepseek-")) return { rule: N.deepseek, group: null, order: ["deepseek"] }; - if (model.startsWith("gemini-")) return { rule: N.gemini, group: null, order: ["gemini"] }; - if (model.startsWith("qwen3-coder:")) return { rule: N.local, group: null, order: ["ollama"] }; - return { rule: N.catchAll, group: N.main, order: ["anthropic", "relay"] }; + const via = (rule: string, to: string) => ({ route: "default", rule, group: null, order: [to] }); + if (model.startsWith("claude-opus-")) return via(N.opus, "anthropic"); + if (model.startsWith("deepseek-")) return via(N.deepseek, "deepseek"); + if (model.startsWith("gemini-")) return via(N.gemini, "gemini"); + if (model.startsWith("qwen3-coder:")) return via(N.local, "ollama"); + return { route: "default", rule: N.catchAll, group: N.main, order: ["anthropic", "relay"] }; } // ───────────────────────────────────────── core 会说的几句话 @@ -176,8 +181,8 @@ interface Spec { export const HISTORY: HistoryRow[] = []; export const SEC_EVENTS: SecurityEventView[] = []; -/** 打开页面时还在跑的请求(`InFlight` 快照) */ -export const IN_FLIGHT: Event[] = []; +/** 打开页面时还在跑的请求(`InFlight` 快照):每个请求到目前为止的事件 */ +export const IN_FLIGHT: InFlightRequest[] = []; function makeRow(s: Spec, r: () => number): HistoryRow { const outcome = s.outcome ?? { kind: "ok" }; @@ -199,7 +204,7 @@ function makeRow(s: Spec, r: () => number): HistoryRow { : outcome.kind === "failed" ? [{ provider, outcome: "status", status: outcome.status, error: null, ms: ttfb }] : [{ provider, outcome: "served", status: 200, error: null, ms: duration }]; - const routing: RoutingView = { rule: plan.rule, group: plan.group, attempts }; + const routing: RoutingView = { route: plan.route, rule: plan.rule, group: plan.group, rewritten_by: [], denied_by: null, attempts }; const to = PROTOCOL[provider]!; const row: HistoryRow = { id: 0, @@ -430,21 +435,42 @@ function generate() { for (const row of rows) row.id = id++; HISTORY.push(...rows); - // 正在跑的那一条:Claude Code 的下一轮,6 秒前开始 + // 正在跑的那一条:Claude Code 的下一轮,6 秒前开始,已经在收 anthropic 的回答 + const plan = route("claude-code", "claude-sonnet-5"); IN_FLIGHT.push({ - kind: "request_started", id, - client: "claude-code", - client_hint: "claude-code", - session_fp: cc, - peer: null, - key_masked: MASKED["claude-code"], - provider: "anthropic", - billing: "per-token", - model: "claude-sonnet-5", - method: "POST", - path: "/v1/messages", - at_ms: NOW - 6 * SEC, + events: [ + { + kind: "request_started", + id, + client: "claude-code", + client_hint: "claude-code", + session: cc, + peer: null, + key_masked: MASKED["claude-code"], + route: plan.route, + rule: plan.rule, + group: plan.group, + rewritten_by: [], + provider: plan.order[0]!, + billing: "per-token", + model: "claude-sonnet-5", + method: "POST", + path: "/v1/messages", + at_ms: NOW - 6 * SEC, + }, + { + kind: "request_routed", + id, + route: plan.route, + rule: plan.rule, + group: plan.group, + rewritten_by: [], + attempts: [{ provider: plan.order[0]!, outcome: "served", status: 200, error: null, ms: 1_320 }], + billing: "per-token", + }, + { kind: "request_headers", id, status: 200, ttfb_ms: 1_320 }, + ], }); securityLog(); @@ -524,6 +550,9 @@ export function rowsBetween(from: number, to = Infinity) { } const unpriced = (h: HistoryRow) => !h.error && !h.local && h.cost_micros == null && h.billing !== "free"; +/** 没拿到用量的(tw-store 的 `NO_USAGE`):没失败、没用量、按量计费,取消的或者答了 2xx */ +const noUsage = (h: HistoryRow) => + !h.error && !h.local && h.cost_micros == null && h.input_tokens == null && h.billing === "per-token" && (h.cancelled || (h.status != null && h.status < 300)); export function summary(from: number, to = Infinity): Summary { const rows = rowsBetween(from, to); @@ -541,7 +570,7 @@ export function summary(from: number, to = Infinity): Summary { cost_micros_exact: sum(real, (h) => (h.cost_estimated ? 0 : (h.cost_micros ?? 0))), cost_micros_estimated: sum(real, (h) => (h.cost_estimated ? (h.cost_micros ?? 0) : 0)), unpriced_requests: real.filter(unpriced).length, - no_usage_requests: 0, + no_usage_requests: real.filter(noUsage).length, cache_saved_micros: sum(real, (h) => h.cache_saved_micros ?? 0), security: { secrets: count("redact"), @@ -592,6 +621,7 @@ export function dashboard(sinceMs: number, bucketMs: number): Dashboard { if (h.cost_estimated) b.cost_micros_estimated += h.cost_micros ?? 0; else b.cost_micros_exact += h.cost_micros ?? 0; if (unpriced(h)) b.unpriced_requests += 1; + if (noUsage(h)) b.no_usage_requests += 1; buckets.set(at, b); const k = `${at}|${h.model}`; const g = byModel.get(k) ?? { @@ -601,6 +631,8 @@ export function dashboard(sinceMs: number, bucketMs: number): Dashboard { failed: 0, cost_micros_exact: 0, cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, @@ -610,6 +642,8 @@ export function dashboard(sinceMs: number, bucketMs: number): Dashboard { if (h.error) g.failed += 1; if (h.cost_estimated) g.cost_micros_estimated += h.cost_micros ?? 0; else g.cost_micros_exact += h.cost_micros ?? 0; + if (unpriced(h)) g.unpriced_requests += 1; + if (noUsage(h)) g.no_usage_requests += 1; g.input_tokens += h.input_tokens ?? 0; g.output_tokens += h.output_tokens ?? 0; g.cache_read_tokens += h.cache_read_tokens ?? 0; @@ -645,6 +679,7 @@ export function costBy(from: number, key: (h: HistoryRow) => string | null): Cos g.requests += 1; g.cost_micros += h.cost_micros ?? 0; if (unpriced(h)) g.unpriced_requests += 1; + if (noUsage(h)) g.no_usage_requests += 1; g.input_tokens += h.input_tokens ?? 0; g.output_tokens += h.output_tokens ?? 0; by.set(k, g); @@ -670,6 +705,8 @@ export function costBucketsBy(from: number, bucketMs: number, key: (h: HistoryRo failed: 0, cost_micros_exact: 0, cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, @@ -679,6 +716,8 @@ export function costBucketsBy(from: number, bucketMs: number, key: (h: HistoryRo if (h.error) g.failed += 1; if (h.cost_estimated) g.cost_micros_estimated += h.cost_micros ?? 0; else g.cost_micros_exact += h.cost_micros ?? 0; + if (unpriced(h)) g.unpriced_requests += 1; + if (noUsage(h)) g.no_usage_requests += 1; g.input_tokens += h.input_tokens ?? 0; g.output_tokens += h.output_tokens ?? 0; g.cache_read_tokens += h.cache_read_tokens ?? 0; @@ -690,6 +729,37 @@ export function costBucketsBy(from: number, bucketMs: number, key: (h: HistoryRo export const upstreamLatency = (from: number) => latency(rowsBetween(from), (h) => h.provider); +/** + * 各条路由、各条规则命中了多少(`GET /summary/routes`),照 tw-store 的 `route_hits`:按每一行 + * 记下的路由数;一个请求算在决定去向的规则、每条改写了它的规则、第二阶段拒绝了它的规则上, + * 每条只算一次;本地应答的不算;多的在前,一样多按名字 + */ +export function routeStats(from: number, to: number): RouteHits[] { + const byName = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); + const routes = new Map(); + for (const h of rowsBetween(from, to)) { + const r = h.routing; + if (h.local || !r) continue; + const failed = h.error != null; + let x = routes.get(r.route); + if (!x) routes.set(r.route, (x = { route: r.route, requests: 0, failed: 0, last_ms: 0, rules: [] })); + x.requests += 1; + if (failed) x.failed += 1; + x.last_ms = Math.max(x.last_ms, h.at_ms); + for (const name of new Set([r.rule, ...r.rewritten_by, ...(r.denied_by ? [r.denied_by] : [])])) { + let rule = x.rules.find((y) => y.rule === name); + if (!rule) x.rules.push((rule = { rule: name, decided: 0, requests: 0, failed: 0, last_ms: 0 })); + if (name === r.rule) rule.decided += 1; + rule.requests += 1; + if (failed) rule.failed += 1; + rule.last_ms = Math.max(rule.last_ms, h.at_ms); + } + } + const out = [...routes.values()].sort((a, b) => b.requests - a.requests || byName(a.route, b.route)); + for (const x of out) x.rules.sort((a, b) => b.requests - a.requests || byName(a.rule, b.rule)); + return out; +} + /** 最近一段时间里按名字查不到价格的模型(价格状态里那一栏) */ export function unpricedModels(from = NOW - 7 * DAY) { const by = new Map(); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 6b917ec1..f01e1582 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -82,7 +82,7 @@ dependencies = [ "objc2-foundation", "parking_lot", "percent-encoding", - "windows-sys 0.60.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -974,7 +974,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.3", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1175,7 +1175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2651,7 +2651,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2986,7 +2986,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.45.0", ] [[package]] @@ -3591,7 +3591,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3647,7 +3647,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4733,7 +4733,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5277,8 +5277,8 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "serde", "serde_json", @@ -5288,8 +5288,8 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "serde", "serde_json", @@ -5297,8 +5297,8 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "base64 0.22.1", "regex", @@ -5311,8 +5311,8 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "serde", "serde_json", @@ -5338,8 +5338,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "serde", "ts-rs", @@ -5347,8 +5347,8 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "notify", "thiserror 2.0.21", @@ -5357,8 +5357,8 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.47.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.47.0#8095405672d6271bc495d8b8336b3e1b17b84524" +version = "0.48.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.48.0#44e4a6f1e5e8dd298f566c363219c2829d22819c" dependencies = [ "saphyr-parser", "thiserror 2.0.21", @@ -5855,7 +5855,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index dad95ad8..ca2f1e33 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -26,12 +26,12 @@ license = "MIT" # twcore 二进制必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是 # 从 tw-api 锁到的 tag 去取二进制的(见 scripts/fetch-core.sh)。 [workspace.dependencies] -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.47.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.47.0" } -tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.47.0" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.47.0" } -tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.47.0" } -tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.47.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.48.0" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.48.0" } +tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.48.0" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.48.0" } +tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.48.0" } +tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.48.0" } [lib] name = "thinkwatch_lite_lib" diff --git a/src-tauri/src/call.rs b/src-tauri/src/call.rs index c88d1c03..6548da1c 100644 --- a/src-tauri/src/call.rs +++ b/src-tauri/src/call.rs @@ -5,11 +5,11 @@ //! 拼错是运行时才知道的事。现在界面按端点名调(类型来自生成的 `tw-api.ts`), //! 这里按名字找到 `tw_api::ep` 里那一个端点,把请求按它的类型读一遍再发出去。 //! -//! **界面够得着的端点只有 [`ALLOWED`] 里这些**,和改成这样之前各个转发命令 -//! 覆盖的那一组一模一样。不在里面的有意不给:密钥明文(`KeyValue`,复制走 -//! Rust 这边直接写剪贴板)、让 core 退出、诊断包的正文、事件流,以及只在 -//! 概览、上游页的汇总里用到的统计端点。路径参数由 `tw_api::fill` 做百分号 -//! 编码,所以界面给的名字只能是一段,拼不出别的路径。 +//! **界面够得着的端点只有 [`ALLOWED`] 里这些。**不在里面的有意不给:密钥明文 +//! (`KeyValue`,复制走 Rust 这边直接写剪贴板)、让 core 退出、诊断包的正文、 +//! 事件流,以及只在概览、上游页的汇总里用到的统计端点(那几样由 Rust 这边的 +//! 命令拼好再给)。路径参数由 `tw_api::fill` 做百分号编码,所以界面给的名字 +//! 只能是一段,拼不出别的路径。 //! //! 做的事不止转发的命令(打开浏览器、写剪贴板、拼概览)仍然各是一个命令。 //! 其中有三个端点**只能经过那些命令**,因为这台机器上的客户端要一起照顾到:删密钥 @@ -101,6 +101,8 @@ webview_endpoints![ UpdateGroup, DeleteGroup, KnownModels, + // 各条路由、各条规则命中了多少:路由图按它给线加权、标出从没命中过的规则 + RouteStats, // 价目表 Pricing, RefreshPricing, diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index b81621be..befac9d0 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -686,7 +686,7 @@ mod tests { let mut got = Vec::new(); for chunk in [ "data: {\"kind\":\"request_", - "started\",\"id\":1,\"client\":\"c\",\"provider\":\"p\",\"billing\":\"per-token\",\"model\":\"m\",\"method\":\"POST\",\"path\":\"/x\",\"at_ms\":0}\n\n", + "started\",\"id\":1,\"client\":\"c\",\"route\":\"default\",\"rule\":\"catch-all\",\"rewritten_by\":[],\"provider\":\"p\",\"billing\":\"per-token\",\"model\":\"m\",\"method\":\"POST\",\"path\":\"/x\",\"at_ms\":0}\n\n", ] { buf.push_str(chunk); while let Some(idx) = buf.find("\n\n") { diff --git a/src-tauri/src/menubar/mod.rs b/src-tauri/src/menubar/mod.rs index 2d8f874b..e6236a66 100644 --- a/src-tauri/src/menubar/mod.rs +++ b/src-tauri/src/menubar/mod.rs @@ -214,7 +214,11 @@ async fn refresh_live(state: &AppState, snap: &mut Snapshot) { } } +/// **开始的时刻按 core 报的「已经跑了多久」往回推**,推到这台机器的时钟上(`snap.now_ms` +/// 是刚取的)。不拿 `at_ms`:那是 core 的时钟,连的是另一台机器上的 core 时,两边差着 +/// 几秒,「已跑」就跟着差几秒,差成负数时一直是 0 fn apply_live(snap: &mut Snapshot, live: tw_api::LiveView) { + let now = snap.now_ms; snap.live = live .running .into_iter() @@ -223,7 +227,7 @@ fn apply_live(snap: &mut Snapshot, live: tw_api::LiveView) { app: r.client_hint, key: r.client, model: r.model, - started_ms: r.at_ms, + started_ms: now.saturating_sub(r.elapsed_ms), }) .collect(); snap.rate = live.tokens_per_sec; @@ -725,10 +729,15 @@ mod tests { assert_eq!(start.elapsed(), std::time::Duration::ZERO); } - /// core 给的在跑的请求照原样进菜单:谁、哪个模型、什么时候开始的,还有速率 + /// core 给的在跑的请求照原样进菜单:谁、哪个模型、跑了多久,还有速率。**跑了多久 + /// 以 core 算的为准**:它的时钟比这台机器快了一分钟(`at_ms` 在「将来」),菜单上 + /// 照样是 12 秒 #[test] fn the_live_numbers_come_from_core_as_they_are() { - let mut snap = Snapshot::default(); + let mut snap = Snapshot { + now_ms: 100_000, + ..Default::default() + }; apply_live( &mut snap, tw_api::LiveView { @@ -738,7 +747,13 @@ mod tests { client_hint: Some("codex".into()), model: "gpt-5".into(), provider: "openai".into(), - at_ms: 1_000, + at_ms: 148_000, + elapsed_ms: 12_000, + session: None, + route: "default".into(), + rule: "catch-all".into(), + group: Some("__all__".into()), + upstream: None, }], tokens_per_sec: Some(52), }, @@ -750,7 +765,7 @@ mod tests { app: Some("codex".into()), key: "default".into(), model: "gpt-5".into(), - started_ms: 1_000, + started_ms: 88_000, }] ); assert_eq!(snap.rate, Some(52)); diff --git a/src-tauri/src/menubar/model.rs b/src-tauri/src/menubar/model.rs index 9804798f..122f830a 100644 --- a/src-tauri/src/menubar/model.rs +++ b/src-tauri/src/menubar/model.rs @@ -113,6 +113,8 @@ pub struct Live { /// 网关密钥的名字 pub key: String, pub model: String, + /// 开始的时刻,**这台机器的时钟**:由 core 报的「已经跑了多久」推回来的, + /// 和 `Snapshot::now_ms` 相减就是已跑时长 pub started_ms: u64, } diff --git a/src-tauri/src/notices/tests.rs b/src-tauri/src/notices/tests.rs index 96dd5c8b..b34740a9 100644 --- a/src-tauri/src/notices/tests.rs +++ b/src-tauri/src/notices/tests.rs @@ -397,8 +397,11 @@ async fn an_unreachable_upstream_is_only_listed_and_needs_real_evidence_to_clear // 这家真的又接下了一个请求 b.bus.on_event(&tw_api::Event::RequestRouted { id: 2, + route: "default".into(), rule: "兜底".into(), group: None, + rewritten_by: vec![], + denied_by: None, attempts: vec![tw_api::AttemptView { provider: "relay".into(), outcome: tw_api::AttemptOutcome::Served, diff --git a/src/RequestDrawer.i18n.tsx b/src/RequestDrawer.i18n.tsx index e26980f8..63c34bab 100644 --- a/src/RequestDrawer.i18n.tsx +++ b/src/RequestDrawer.i18n.tsx @@ -67,10 +67,9 @@ export const requestDrawerText = messages( attempts: "尝试链", failover: (failed: number) => `已发生故障转移:前 ${failed} 个上游失败,已自动切换至下一个上游。`, - noRouting: "此请求没有路由信息", + noRouting: "此请求由网关本地应答,未经过路由。", routingPending: "路由尚未完成", - noRoutingTip: "网关本地应答的请求、被路由规则拒绝的请求,以及上游应答之前客户端就断开的请求,不记录路由信息。", - possibleCauses: "可能原因", + noAttempts: "此请求没有上游尝试记录。", // 内容 request: "请求", @@ -174,11 +173,9 @@ export const requestDrawerText = messages( 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.`, - noRouting: "No routing information for this request", + noRouting: "The gateway answered this request locally; it did not go through routing.", routingPending: "Routing has not finished yet", - noRoutingTip: - "Requests answered locally by the gateway, requests refused by a routing rule, and requests whose client disconnected before any upstream answered carry no routing information.", - possibleCauses: "Possible causes", + noAttempts: "No upstream attempts were recorded for this request.", request: "Request", response: "Response", diff --git a/src/RequestDrawer.tsx b/src/RequestDrawer.tsx index 7a2619f8..3c9c2c0e 100644 --- a/src/RequestDrawer.tsx +++ b/src/RequestDrawer.tsx @@ -194,10 +194,13 @@ function Detail({ id, onClose }: { id: number; onClose: () => void }) { } > - - {!r.local && } - {r.local ? t.answeredLocally : r.provider} - + {/* 没有发往任何上游的(被规则拒绝、选中的上游一个都接不了)上游是空的,不写 */} + {(r.local || r.provider) && ( + + {!r.local && } + {r.local ? t.answeredLocally : r.provider} + + )} @@ -358,7 +361,7 @@ function Timeline({ d, state }: { d: RequestDetail; state: ReturnType - + {/* 密钥是身份;应用是按请求头推测的,能伪造;来源是这条连接对面的 地址,只有非本机来的才有 */} } /> @@ -522,19 +525,8 @@ function CostText({ r, running, short }: { r: HistoryRow; running: boolean; shor /** 路由:命中的规则、经过的策略组、尝试链 */ function Routing({ r, running }: { r: HistoryRow; running: boolean }) { const t = useText(requestDrawerText); - if (!r.routing) { - return running ? ( - // 还没走完:尝试链在那一跳有了结果之后才有 -

{t.routingPending}

- ) : ( -

- {t.noRouting} - - {t.possibleCauses} - -

- ); - } + // 只有本地应答的没有:它没到规则那一层 + if (!r.routing) return

{t.noRouting}

; const attempts = r.routing.attempts; return (
@@ -545,29 +537,37 @@ function Routing({ r, running }: { r: HistoryRow; running: boolean }) {

{t.attempts}

-
    - {attempts.map((a, i) => { - const outcome = attemptText(a); - return ( -
  1. - {i + 1} - - - {a.provider} - - {/* **失败的原因要留着** —— 一条说「试过 A → B → C」的链和一条还说清 - 每一跳为什么失败的链,排查价值差得远 */} - - {outcome.text} - - {ms(a.ms)} -
  2. - ); - })} -
+ {/* + 尝试链是空的:还在等第一跳的结果;或者请求没有发给任何上游(被规则拒绝、 + 选中的上游一个都接不了),或者上游应答之前客户端就走了 + */} + {attempts.length === 0 ? ( +

{running ? t.routingPending : t.noAttempts}

+ ) : ( +
    + {attempts.map((a, i) => { + const outcome = attemptText(a); + return ( +
  1. + {i + 1} + + + {a.provider} + + {/* **失败的原因要留着** —— 一条说「试过 A → B → C」的链和一条还说清 + 每一跳为什么失败的链,排查价值差得远 */} + + {outcome.text} + + {ms(a.ms)} +
  2. + ); + })} +
+ )} {attempts.length > 1 && ( // **用户能看见故障转移在替他工作,这是信任的来源**。一个静默切换过的请求和 // 一次就成的请求,在他眼里应该是不同的 diff --git a/src/control.ts b/src/control.ts index 2f43f32f..3f5ab86d 100644 --- a/src/control.ts +++ b/src/control.ts @@ -64,6 +64,7 @@ export const WEBVIEW_ENDPOINTS = [ "UpdateGroup", "DeleteGroup", "KnownModels", + "RouteStats", "Pricing", "RefreshPricing", "SetPricingAutoUpdate", diff --git a/src/events.test.ts b/src/events.test.ts index 5f88319f..9db7641d 100644 --- a/src/events.test.ts +++ b/src/events.test.ts @@ -5,6 +5,7 @@ import { interruptInFlight, type CoreEvent, type HistoryRow, + type InFlightRequest, type RequestRow, } from "./types"; import { mergeHistory } from "./useRequests"; @@ -23,6 +24,10 @@ function started(over: Partial> kind: "request_started", id: 1, client: "claude-code", + route: "default", + rule: "catch-all", + group: "__all__", + rewritten_by: [], provider: "relay", billing: "per-token", model: "claude-sonnet-4-5", @@ -33,6 +38,11 @@ function started(over: Partial> } satisfies CoreEvent; } +/** `GET /in-flight` 里的一个请求:到目前为止的事件,第一条是开始事件 */ +function open(...events: CoreEvent[]): InFlightRequest { + return { id: events[0]!.id, events }; +} + describe("从事件缝出一行", () => { it("开始就带着模型", () => { const rows = new Map(); @@ -40,6 +50,16 @@ describe("从事件缝出一行", () => { expect(rows.get(1)?.model).toBe("claude-sonnet-4-5"); }); + /** 会话是网关在开始的那一刻定的:正在跑的那一条已经在它的会话里,不用等落库 */ + it("开始就带着会话", () => { + const rows = new Map(); + applyEvent(rows, started({ session: "fp-1-1000000" })); + expect(rows.get(1)?.session).toBe("fp-1-1000000"); + // 认不出会话的没有,不拿一个假的凑数 + applyEvent(rows, started({ id: 2 })); + expect(rows.get(2)?.session).toBeUndefined(); + }); + /** WebSocket 这类认不出模型的请求,core 发的是空串 —— 空串不是一个模型名 */ it("模型是空串时当作不知道", () => { const rows = new Map(); @@ -221,14 +241,51 @@ describe("用快照补上进行中的行", () => { it("没见过开始事件的请求补成进行中", () => { const rows = new Map(); - expect(applyInFlight(rows, [started({ id: 7 })], seen())).toBe(true); + expect(applyInFlight(rows, [open(started({ id: 7 }))], seen())).toBe(true); expect(rows.get(7)?.state).toBe("in_flight"); expect(rows.get(7)?.model).toBe("claude-sonnet-4-5"); }); + /** + * 快照里是这个请求到目前为止的全部事件。**照原样重放**:响应头、服务它的上游 + * 都在,和从头听起的那一行一样。 + */ + it("快照里的事件照原样重放", () => { + const rows = new Map(); + applyInFlight( + rows, + [ + open( + started({ id: 7, provider: "relay", session: "fp-7-1000000" }), + { + kind: "request_routed", + id: 7, + route: "default", + rule: "catch-all", + group: "__all__", + rewritten_by: [], + attempts: [ + { provider: "relay", outcome: "status", status: 503, ms: 40 }, + { provider: "official", outcome: "served", status: 200, ms: 900 }, + ], + billing: "per-token", + }, + { kind: "request_headers", id: 7, status: 200, ttfb_ms: 940 }, + ), + ], + seen(), + ); + const r = rows.get(7); + expect(r?.state).toBe("in_flight"); + expect(r?.provider).toBe("official"); + expect(r?.status).toBe(200); + expect(r?.ttfbMs).toBe(940); + expect(r?.session).toBe("fp-7-1000000"); + }); + it("快照在路上时结束了的不补", () => { const rows = new Map(); - expect(applyInFlight(rows, [started({ id: 7 })], seen([], [7]))).toBe(false); + expect(applyInFlight(rows, [open(started({ id: 7 }))], seen([], [7]))).toBe(false); expect(rows.has(7)).toBe(false); }); @@ -237,10 +294,10 @@ describe("用快照补上进行中的行", () => { const rows = new Map(); applyEvent(rows, started({ id: 7 })); applyEvent(rows, { kind: "request_headers", id: 7, status: 200, ttfb_ms: 812 }); - expect(applyInFlight(rows, [started({ id: 7 })], seen([7]))).toBe(false); + expect(applyInFlight(rows, [open(started({ id: 7 }))], seen([7]))).toBe(false); expect(rows.get(7)?.status).toBe(200); // 开始事件还在缓冲里、这一行还没建出来的,同样不补 —— 缓冲落地时会建 - expect(applyInFlight(new Map(), [started({ id: 8 })], seen([8]))).toBe(false); + expect(applyInFlight(new Map(), [open(started({ id: 8 }))], seen([8]))).toBe(false); }); /** @@ -251,7 +308,7 @@ describe("用快照补上进行中的行", () => { const rows = new Map(); applyEvent(rows, started({ id: 7, model: "gpt-5.5" })); interruptInFlight(rows); - expect(applyInFlight(rows, [started({ id: 7 })], seen())).toBe(true); + expect(applyInFlight(rows, [open(started({ id: 7 }))], seen())).toBe(true); expect(rows.get(7)?.state).toBe("in_flight"); expect(rows.get(7)?.model).toBe("claude-sonnet-4-5"); expect(rows.get(7)?.error).toBeUndefined(); @@ -307,8 +364,10 @@ describe("故障转移之后的上游", () => { applyEvent(rows, { kind: "request_routed", id: 1, + route: "default", rule: "catch-all", group: "__all__", + rewritten_by: [], attempts: [ { provider: "relay", outcome: "status", status: 503, ms: 40 }, { provider: "official", outcome: "served", status: 200, ms: 900 }, @@ -317,6 +376,22 @@ describe("故障转移之后的上游", () => { }); expect(rows.get(1)?.provider).toBe("official"); }); + + /** 被规则拒绝的请求没有发往任何上游:开始时上游就是空的,尝试链也是空的 */ + it("没有发往任何上游的,上游一直是空的", () => { + const rows = new Map(); + applyEvent(rows, started({ provider: "", group: null, rule: "no-opus" })); + applyEvent(rows, { + kind: "request_routed", + id: 1, + route: "default", + rule: "no-opus", + rewritten_by: [], + attempts: [], + billing: "per-token", + }); + expect(rows.get(1)?.provider).toBe(""); + }); }); /** 库里读回来的一行。默认是一次正常结束的请求 */ diff --git a/src/generated/tw-api.ts b/src/generated/tw-api.ts index a551abdb..c092da0c 100644 --- a/src/generated/tw-api.ts +++ b/src/generated/tw-api.ts @@ -1,6 +1,27 @@ // Generated by tw-api (`tw_api::ts::export_all`). Do not edit by hand. -export const CONTROL_API_VERSION = 20; +export const CONTROL_API_VERSION = 21; + +/** + * 一个账号上游登的是哪个账号。 + * + * **从这份凭据自己的 access token 里读,不联网**:ChatGPT 的 access token 是 JWT,套餐 + * 在 `https://api.openai.com/auth` 里,邮箱在 `https://api.openai.com/profile` 里。登录 + * 和每一次刷新都换来一个新的、并且写回配置,所以它跟着凭据走:套餐变了,下一次换 + * token 之后这里就是新的;凭据失效之后,这里仍是最后登着的那个账号。 + * + * 账户 ID、用户 ID 同在令牌里,**不往外带**:界面认账号靠邮箱,那两个读不出是谁, + * 而它们一旦出去就会进日志 + */ +export type AccountView = { +/** + * 令牌里没写就没有 + */ +email?: string | null, +/** + * 令牌里没写就没有 + */ +plan?: ChatgptPlan | null, }; /** * 改一条内置规则在拦截档下做什么。只有工具调用审查和内容过滤的规则有这一项 —— @@ -154,23 +175,30 @@ status: LoginStatus, */ provider?: string | null, /** - * 套餐:`plus` / `pro` / `team` …。`done` 时有,令牌里没写就没有 + * 套餐。`done` 时有,令牌里没写就没有 */ -plan?: string | null, +plan?: ChatgptPlan | null, /** * `failed` 时的原因 */ error?: Msg | null, }; /** - * ChatGPT 账号的用量(`GET /providers/{name}/chatgpt/usage`)。 + * ChatGPT 账号的套餐。 + * + * **线上就是后端给的那个词**:认得的是 [`KnownChatgptPlan`],认不出来的原样给。 + * 集合是 OpenAI 的,它随时会多出一个新名字 —— 把新名字说成「未知」,比照原词 + * 写出来更差。前端的类型是 `KnownChatgptPlan | string`。 */ -export type ChatgptUsage = { +export type ChatgptPlan = KnownChatgptPlan | string; + /** - * 登的是哪个账号。**只有邮箱** —— 同一份回答里的用户 ID - * 和账户 ID 不往外带:界面认账号靠邮箱,那两个读不出是谁 + * ChatGPT 账号的用量(`GET /providers/{name}/chatgpt/usage`)。 + * + * **登的是谁不在这里**,在上游视图的 [`OAuthView::account`]:那一份从本机的凭据里读, + * 不用为了给一行上游标上账号去问一次后端 */ -email?: string | null, plan?: string | null, +export type ChatgptUsage = { /** * 额度窗口,词表同 [`QuotaWindow`] */ @@ -397,9 +425,21 @@ no_usage_requests: number, }; */ export type CostBucketGroup = { at_ms: number, /** - * 模型名或上游名,看查的是哪一维 + * 模型名、上游名或密钥名,看查的是哪一维 */ name: string, requests: number, failed: number, cost_micros_exact: number, cost_micros_estimated: number, +/** + * 这一格里这一项有几条请求的模型不在价目表里(用量是有的),见 + * `Summary::unpriced_requests`。 + * + * **每一项自己带着。**这一项的金额是 0 时,要分得清「没有价格」和「确实 + * 没花钱」—— 只有整格的数的话,说不出缺着钱的是哪一项。 + */ +unpriced_requests: number, +/** + * 这一格里这一项有几条请求没有拿到用量,见 `Summary::no_usage_requests` + */ +no_usage_requests: number, /** * 这一格里这一项用掉的 token。 * @@ -568,12 +608,16 @@ client: string, */ client_hint?: string | null, /** - * 这次请求属于哪一段对话的指纹。 + * 这次请求归到哪一次会话(任务)。**落库时 `requests.session` 就是这个值**, + * 和 `SessionView.id` 是同一个。 * - * **只是指纹,不是会话 id** —— 会话是「同一个指纹 + 没隔太久」, - * 而「隔了多久」要看上一条是什么时候,那是 recorder 的活。 + * 由网关在开始的那一刻定,只定一次:同一段对话(system prompt 和第一句话 + * 的指纹)、离这段对话的上一个请求不超过半小时,就还是那一次;隔久了算 + * 新的一次。**开始时就给出来**,界面才能把一个还在跑的请求放进它的会话、 + * 把那次会话标成进行中。认不出会话的没有:正文里没有任何能认人的东西, + * 或者是 WebSocket 升级(升级请求没有正文) */ -session_fp?: string | null, +session?: string | null, /** * 请求从哪台机器来:**这条连接对面的地址**,不可伪造。本机(回环) * 来的不记 —— 那是绝大多数请求,写上只是噪音;局域网来的才值得 @@ -584,14 +628,36 @@ peer?: string | null, * 请求带的那把网关密钥打码后的样子(`tw-re…wb4e`)。**记的是请求那一刻 * 用的那把** —— 密钥更换过之后,老记录上的尾巴照样对得上 */ -key_masked?: string | null, provider: string, +key_masked?: string | null, +/** + * 走的哪条路由:这把密钥指定的那条,没指定的是默认路由。 + * + * **路由的第一阶段在开始之前就走完了**,所以这几项(路由、规则、策略组、 + * 改写)开始时就有:界面不必按密钥现在的配置去猜这个请求走的是哪条, + * 那份配置在请求开始之后可能已经改过了。`RequestRouted` 带着同样的几项, + * 外加第二阶段和尝试链的结果 + */ +route: string, +/** + * 决定去向的那条规则:路由里第一条命中的转发或拒绝 + */ +rule: string, +/** + * 规则把请求交给的策略组。规则直接指上游、或者拒绝了它时没有 + */ +group?: string | null, +/** + * 附加了参数改写的规则,按求值的顺序(`rule` 自己带着改写时也在里面)。 + * 选定上游之后才判断的那些要等 `RequestRouted` + */ +rewritten_by: Array, provider: string, /** * `provider` 那一家怎么收钱,和 `RequestRouted::billing` 同一套词。 * * **算数的是 `RequestRouted` 报的那个**(最终服务的那家)。这里先报 * 一个,是因为不是每个请求都等得到那一条:上游应答之前客户端就走了 - * 的、WebSocket 升级没完成就断开的、被第二阶段规则拒绝的,手上只有 - * 这一个 —— 少了它,那一行说不出该按什么记账。 + * 的、WebSocket 升级没完成就断开的,手上只有这一个 —— 少了它,那一行 + * 说不出该按什么记账。 */ billing: Billing, /** @@ -652,11 +718,25 @@ bytes: number, duration_ms: number, * **没嗅到就是 None,不是零** —— 客户端可能在第一帧之前就走了 */ usage?: UsageView | null, } | { "kind": "request_routed", id: number, +/** + * 走的哪条路由,同 `RequestStarted::route` + */ +route: string, /** * 命中了哪条规则。**日志和界面都要显示它** —— 「命中第 4 条」 * 远不如「命中『带缓存的必须走官方』」有用 */ rule: string, group?: string | null, +/** + * 附加了参数改写的规则:开始事件里的那几条,加上选定上游之后才判断、 + * 又改写了它的(故障转移时每一跳各判断一次,合在一起,不重复) + */ +rewritten_by: Array, +/** + * 选定上游之后才判断的规则拒绝了这次请求:是哪一条。**这时尝试链的最后 + * 一跳就是被拒的那一家**(没有发出去) + */ +denied_by?: string | null, /** * 试过哪几家、各自什么结果。**一次就成的也有一条** —— * 「只试了一家」和「试了三家」在用户眼里应该是不同的 @@ -1034,8 +1114,9 @@ billing: Billing, */ cache_saved_micros?: number | null, /** - * 路由决策与尝试链。本地应答的没有它;路由还没报出结论请求就结束了的 - * 也没有:上游应答之前客户端就走了、被第二阶段规则拒绝 + * 路由决策与尝试链。本地应答的没有它:它没到规则那一层。路由还没报出 + * 结论请求就结束了的(上游应答之前客户端就走了)有开始时就知道的那几项, + * 尝试链是空的 */ routing?: RoutingView | null, /** @@ -1078,6 +1159,42 @@ key_masked?: string | null, */ security?: Array, }; +/** + * 此刻还在跑的请求(`GET /in-flight`):每一个到目前为止的事件,和 core 此刻的 + * 时钟。 + * + * **给半路才来听事件流的一方重建现状用。**事件流只送订阅之后发生的事;一个在那 + * 之前就开始、此刻还没结束的请求,它的开始、响应头、路由都早就发过了。把每个 + * 请求的 `events` 按顺序喂给自己处理事件的那段代码,就和从头听起一样。 + * + * **和 `Status::in_flight` 不是一个数。**那个从连接进到数据面就算,排队等名额的、 + * 鉴权没过的都在里面 —— 它回答的是「现在重启会掐断几个连接」。这里只有发过开始 + * 事件的请求,和事件流里说的是同一批,也和 `LiveView::running` 是同一批。 + */ +export type InFlight = { +/** + * core 此刻的时钟,Unix 毫秒。**算「跑了多久」用它减开始事件的 `at_ms`**, + * 两个都是 core 的时钟;界面自己的时钟和远程 core 的不一定对得上 + */ +now_ms: number, +/** + * 开始了、还没有结局的请求,开始得早的在前 + */ +requests: Array, }; + +/** + * 一个还在跑的请求到目前为止的事件。 + */ +export type InFlightRequest = { id: number, +/** + * 关于它的事件,**照事件流上的样子、按发生的先后**:第一条是 `RequestStarted`, + * 之后是到目前为止发生了的 —— 响应头、路由、格式转换、防护的记录 + * (`RequestHeaders`、`RequestRouted`、`Translated`、`SecretsFound`、 + * `HiddenTextFound`、`ContentMatched`、`OutputLimited`、`ToolCallFlagged`)。 + * 说的是上游现状的(`QuotaSeen`)不在里面:那是 `/quota` 的事 + */ +events: Array, }; + /** * 一把密钥上用户能改的东西。**密钥的值不在里面** —— 它由 core 生成, * 要换就走更换(新值写进已接管的客户端,由桌面端做)。 @@ -1117,6 +1234,14 @@ export type KeySave = { key: KeyInput, base_version?: string | null, }; */ export type KeyValue = { name: string, key: string, }; +/** + * ChatGPT 套餐里认得的那些词,和 Codex 客户端认的是同一份。 + * + * **这个集合不归我们定**:OpenAI 一直在加(`go`、`prolite` 都是后来才有的), + * 认不出来的词见 [`ChatgptPlan::Other`]。 + */ +export type KnownChatgptPlan = "free" | "go" | "plus" | "pro" | "prolite" | "promax" | "team" | "business" | "self_serve_business_prolite" | "self_serve_business_usage_based" | "enterprise" | "ent26" | "enterprise_cbp_automation" | "enterprise_cbp_usage_based" | "edu" | "edu_plus" | "edu_pro"; + /** * 网关知道的一个模型,以及能提供它的上游(已按启用范围与停用过滤)。 */ @@ -1407,7 +1532,15 @@ failure?: Msg | null, /** * 凭据已经失效,只有重新登录能恢复 */ -needs_login?: boolean, }; +needs_login?: boolean, +/** + * 登的是哪个账号。**ChatGPT 账号上游才有**,令牌里一项都读不出来时没有。 + * + * Z.ai / BigModel 的账号上游没有 `oauth` 这一节,也就没有它:那类登录的终点是一把 + * 普通 API key,key 里读不出是谁,登录时读到的账号名只在那一次登录的结果里 + * ([`ZaiLoginStatus::account`]),不随 key 保存 + */ +account?: AccountView | null, }; /** * 代理用不了时怎么办。 @@ -2177,6 +2310,39 @@ export type RouteDelete = { base_version?: string | null, */ reassign_to?: string | null, }; +/** + * 一条路由在一段时间里走了多少请求,各条规则命中了多少(`GET /summary/routes`)。 + * + * **按请求落库时记下的路由算**,不按现在的配置推:一个请求走的是它那一刻的 + * 路由和规则,之后改名、删掉、换了绑定都不改它。所以这里可能有配置里已经没有的 + * 路由和规则,而配置里有、这段时间一次都没命中的不在这里 —— 「从来没命中过」 + * 就是在配置里有、在这里找不到。 + * + * 数的是经过路由的请求:本地应答的不算(它们没到规则那一层);规则还没做出决定 + * 就失败了的也不算 —— 鉴权没过、模型不让用、没有一条规则命中。 + */ +export type RouteHits = { route: string, +/** + * 走这条路由的请求数 + */ +requests: number, +/** + * 其中失败的。**被规则拒绝的也算**;客户端取消的不算(同 `Summary::failed`) + */ +failed: number, +/** + * 最后一个请求是什么时候开始的,Unix 毫秒 + */ +last_ms: number, +/** + * 这条路由里各条规则命中了多少,多的在前。 + * + * **一个请求可以算在几条规则上**:决定去向的那一条(转发或拒绝)、附加了参数 + * 改写的每一条、选定上游之后拒绝了它的那一条。所以各条加起来可以比 + * `requests` 多;决定去向的规则每个请求恰好一条 + */ +rules: Array, }; + /** * 新建或修改一条路由时交过来的定义。**规则的顺序就是数组的顺序。** */ @@ -2222,8 +2388,28 @@ clients: Array, rules: Array, }; /** * 一次请求的路由决策。**详情抽屉的 Routing 那一页吃它。** + * + * 字段就是 [`Event::RequestRouted`] 里的那些(计费方式记在那一行上)。路由还没 + * 报出结论请求就结束了的(上游应答之前客户端就走了)也有:开始时就知道的那几项, + * 尝试链是空的。 + */ +export type RoutingView = { +/** + * 走的哪条路由:密钥指定的那条,没指定的是默认路由 + */ +route: string, +/** + * 决定去向的那条规则:第一条命中的转发或拒绝 + */ +rule: string, group?: string | null, +/** + * 附加了参数改写的规则,按求值的顺序(见 `RequestRouted::rewritten_by`) + */ +rewritten_by: Array, +/** + * 选定上游之后才判断的规则拒绝了它:是哪一条 */ -export type RoutingView = { rule: string, group?: string | null, attempts: Array, }; +denied_by?: string | null, attempts: Array, }; /** * 一条规则在拦截档下做什么。工具调用审查是 `cut` / `record`,内容过滤是 @@ -2236,6 +2422,28 @@ export type RuleAction = "cut" | "block" | "record"; */ export type RuleEffect = "decide" | "apply" | "none"; +/** + * 一条规则命中了多少请求。 + */ +export type RuleHits = { rule: string, +/** + * 它决定了去向(转发或拒绝)的请求数 + */ +decided: number, +/** + * 它命中的请求数:决定了去向的、附加了改写的、选定上游之后拒绝了的,一个 + * 请求只算一次 + */ +requests: number, +/** + * 其中失败的(同 `RouteHits::failed`) + */ +failed: number, +/** + * 最后一次命中的请求是什么时候开始的,Unix 毫秒 + */ +last_ms: number, }; + /** * 一条规则的定义。 * @@ -2351,7 +2559,30 @@ client_hint: string | null, model: string, /** * 开始时的首选上游 */ -provider: string, at_ms: number, }; +provider: string, +/** + * 开始的时刻,**core 的时钟** + */ +at_ms: number, +/** + * 已经跑了多久,毫秒,**core 算的**(按它自己的单调时钟)。界面拿自己的时钟 + * 去减 `at_ms` 的话,连的是另一台机器上的 core 时两边的时钟不一定对得上; + * 问完之后往上走的那一截由界面自己数 + */ +elapsed_ms: number, +/** + * 归到哪一次会话,同 `RequestStarted::session` + */ +session: string | null, +/** + * 走的哪条路由、哪条规则决定的去向、经过哪个策略组 —— 开始时就知道 + */ +route: string, rule: string, group: string | null, +/** + * 实际接下它的上游:尝试链里接下了的那一跳。**路由报出结论之前没有** + * (还在等上游的响应头,或者正在故障转移) + */ +upstream: string | null, }; /** * 一个密钥类的值怎么改。**三态**,因为视图里拿不到原值:不动就得有「保持原样」。 @@ -2508,7 +2739,18 @@ key_masked?: string | null, }; /** * 安全日志的一页。**按时间倒序**,`more` 说后面还有没有。 */ -export type SecurityEventsPage = { events: Array, more: boolean, }; +export type SecurityEventsPage = { events: Array, more: boolean, +/** + * 这一段时间里、按这一项筛出来的一共几条 —— **整段的,不只是这一页**。 + * + * `before` 是翻页的位置,不是筛选:翻到第几页,这个数都一样。页头的 + * 「N 次命中」是它;拿读到的条数去数,读满一页就只能写「100+」 + */ +total: number, +/** + * `total` 里各做了什么。四项加起来就是 `total` + */ +by_outcome: SecurityOutcomeCounts, }; /** * 安全日志一页要的:哪一项、哪一段、从哪条往前、几条(`GET /security/events`)。 @@ -2529,6 +2771,28 @@ before?: number | null, limit?: number | null, }; */ export type SecurityOutcome = "recorded" | "replaced" | "cut" | "blocked"; +/** + * 一段安全日志里,每一种做法各几条(见 [`SecurityOutcome`])。没有的是 0, + * 四项都在。 + */ +export type SecurityOutcomeCounts = { +/** + * 只记录 + */ +recorded: number, +/** + * 已替换成占位符 + */ +replaced: number, +/** + * 已切断 + */ +cut: number, +/** + * 请求被拒,没有发出去 + */ +blocked: number, }; + /** * 一条规则。 */ @@ -3007,6 +3271,7 @@ export const ENDPOINTS = { CostBuckets: { method: "GET", path: "/summary/buckets", params: [], format: "json" }, CostBucketsBy: { method: "GET", path: "/summary/buckets/by", params: [], format: "json" }, CostBy: { method: "GET", path: "/summary/by", params: [], format: "json" }, + RouteStats: { method: "GET", path: "/summary/routes", params: [], format: "json" }, History: { method: "GET", path: "/history", params: [], format: "json" }, Latency: { method: "GET", path: "/latency", params: [], format: "json" }, LatencyByProvider: { method: "GET", path: "/latency/provider", params: [], format: "json" }, @@ -3083,7 +3348,7 @@ export type Endpoints = { Shutdown: { req: null; res: Msg }; Interfaces: { req: null; res: Array }; Events: { req: null; res: Event }; - InFlight: { req: null; res: Array }; + InFlight: { req: null; res: InFlight }; Live: { req: null; res: LiveView }; Overview: { req: null; res: Overview }; L1: { req: L1Request; res: Array }; @@ -3101,6 +3366,7 @@ export type Endpoints = { CostBuckets: { req: BucketQuery; res: Array }; CostBucketsBy: { req: BucketGroupQuery; res: Array }; CostBy: { req: GroupQuery; res: Array }; + RouteStats: { req: Window; res: Array }; History: { req: ListQuery; res: Array }; Latency: { req: Window; res: Array }; LatencyByProvider: { req: Window; res: Array }; diff --git a/src/keys/usage.test.ts b/src/keys/usage.test.ts index a2373b0f..2a23b45b 100644 --- a/src/keys/usage.test.ts +++ b/src/keys/usage.test.ts @@ -16,6 +16,8 @@ function bucket(name: string, hoursAfterSince: number, requests: number, since: failed: 0, cost_micros_exact: 0, cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, diff --git a/src/overview/series.test.ts b/src/overview/series.test.ts index 99b2b1c7..4fa3010a 100644 --- a/src/overview/series.test.ts +++ b/src/overview/series.test.ts @@ -59,6 +59,8 @@ function group(at_ms: number, name: string, tokens: number, cost = 0, requests = failed: 0, cost_micros_exact: cost, cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, input_tokens: tokens, output_tokens: 0, cache_read_tokens: 0, diff --git a/src/overview/useLive.ts b/src/overview/useLive.ts index adda1fe1..3e844ef3 100644 --- a/src/overview/useLive.ts +++ b/src/overview/useLive.ts @@ -169,7 +169,7 @@ export function useInFlight(): number { // 等的这会儿 core 停了、或者又开始了一次对账:这份作废 if (!alive || since !== mark) return; const next = new Set(mark.started); - for (const ev of open) if (ev.kind === "request_started") next.add(ev.id); + for (const r of open.requests) next.add(r.id); for (const id of mark.ended) next.delete(id); flying.current = next; soon(); diff --git a/src/routing/flights.ts b/src/routing/flights.ts index c3b815d9..dbd270b8 100644 --- a/src/routing/flights.ts +++ b/src/routing/flights.ts @@ -9,8 +9,8 @@ * 才画到上游 —— 之前只知道首选,故障转移之后服务它的可能是另一个。 * · 三种结局:这条路随之熄灭。 * - * 半路才打开这一页时,已经在跑的请求从 `/in-flight` 补上。那里只有开始事件,所以这些 - * 请求只画到路由为止。 + * 半路才打开这一页时,已经在跑的请求从 `/in-flight` 补上:每个请求到目前为止的事件照原样 + * 重放一遍,已经路由了的一打开就画到上游。 */ import type { CoreEvent, Overview } from "@/types"; import { chainId, edgeId, type Chain } from "./chain"; diff --git a/src/routing/useFlights.ts b/src/routing/useFlights.ts index a49594c4..30cafc1f 100644 --- a/src/routing/useFlights.ts +++ b/src/routing/useFlights.ts @@ -65,8 +65,10 @@ export function useFlights(): ReadonlyMap { await un; const open = await call("InFlight", null); if (!alive || seen !== mark) return; - for (const ev of open) { - if (ev.kind === "request_started" && !mark.has(ev.id) && !live.has(ev.id)) applyFlightEvent(live, ev); + // 每个请求到目前为止的事件按原来的顺序重放:已经路由了的,一打开就画到上游 + for (const { id, events } of open.requests) { + if (mark.has(id) || live.has(id)) continue; + for (const ev of events) applyFlightEvent(live, ev); } publish(); } catch { diff --git a/src/security/useSecurityLog.ts b/src/security/useSecurityLog.ts index 423df0bb..2275af8b 100644 --- a/src/security/useSecurityLog.ts +++ b/src/security/useSecurityLog.ts @@ -54,10 +54,11 @@ export function useSecurityLog(range: Range, tick: number): SecurityLog { if (!last) return; const p = await api.events({ from_ms: windowStart(range), before: last.id, limit: PAGE }); // 读的这一会儿列表被重读过(来了新记录):尾巴已经不是这一页接得上的那一条, - // 这一页不接,免得中间缺一段。再点一次就从新的尾巴往下读 + // 这一页不接,免得中间缺一段。再点一次就从新的尾巴往下读。 + // 总数和各做法的条数说的是整段时间,哪一页带来的都一样:取新的这一页的 r.mutate((prev) => prev && prev.events[prev.events.length - 1]?.id === last.id - ? { events: [...prev.events, ...p.events], more: p.more } + ? { ...p, events: [...prev.events, ...p.events] } : (prev ?? p), ); }); diff --git a/src/traffic/RequestTable.tsx b/src/traffic/RequestTable.tsx index 4385a460..20b57fb1 100644 --- a/src/traffic/RequestTable.tsx +++ b/src/traffic/RequestTable.tsx @@ -406,7 +406,12 @@ const Row = memo(function Row({ { kind: "sep" }, // **按这一行的值筛,不是打开一个筛选器。**排查时的动作是「这一个上游的」 // 「这一把密钥的」,而手打名字会打错,打错的表现是「筛出来空的」 - { kind: "item", label: t.onlyUpstream(r.provider), onSelect: () => onFilter((f) => ({ ...f, provider: r.provider })) }, + // 没有发往任何上游的那几行上游是空的,没有可筛的 + ...(r.provider + ? ([ + { kind: "item", label: t.onlyUpstream(r.provider), onSelect: () => onFilter((f) => ({ ...f, provider: r.provider })) }, + ] as const) + : []), ...(showClient ? ([ { kind: "item", label: t.onlyClient(r.client), onSelect: () => onFilter((f) => ({ ...f, client: r.client })) }, @@ -560,12 +565,13 @@ function UpstreamCell({ r }: { r: RequestRow }) {
{/* 本地应答的那一句(英文两个词)可以在词间折行:它不是一个名字,别让它定这一列的最小宽度 */} - {r.local ? ( + {r.local || !r.provider ? ( ) : ( )} - {r.provider} + {/* 被规则拒绝、选中的上游一个都接不了的请求没有发往任何上游:上游是空的 */} + {r.provider ? {r.provider} : —} {/* **看不见的安全功能会被用户关掉**,因为他们会怀疑是脱敏搞坏了功能。 所以脱敏发生了就要在列表这一层看得见,而不是藏在详情里 */} diff --git a/src/traffic/SessionPanel.tsx b/src/traffic/SessionPanel.tsx index 786fbc67..86ed6028 100644 --- a/src/traffic/SessionPanel.tsx +++ b/src/traffic/SessionPanel.tsx @@ -97,8 +97,9 @@ export function SessionPanel({ }) { const t = useText(sessionsText); const { session: s, turns } = d; - // 走过哪几个上游,按第一次出现的先后。一次任务中途换过上游,这里能看出来 - const providers = [...new Set(turns.map((x) => x.provider))]; + // 走过哪几个上游,按第一次出现的先后。一次任务中途换过上游,这里能看出来。 + // 没有发往任何上游的那几轮(被规则拒绝)上游是空的,不算 + const providers = [...new Set(turns.map((x) => x.provider).filter(Boolean))]; return ( <> {/* 第二行和请求详情同一个顺序:上游、密钥,然后是这次用过的模型 */} diff --git a/src/traffic/SessionRow.tsx b/src/traffic/SessionRow.tsx index 00ffe015..06d3e07c 100644 --- a/src/traffic/SessionRow.tsx +++ b/src/traffic/SessionRow.tsx @@ -66,8 +66,8 @@ export const SessionRow = memo(function SessionRow({ const started = s?.started_ms ?? Math.min(...rows.map((r) => r.atMs)); const ended = s?.ended_ms ?? Math.max(...rows.map((r) => r.atMs)); // **上游从行里数,不从汇总里拿** —— `SessionView` 没有这一项, - // 而组里的每一条都知道自己走了哪个上游 - const providers = [...new Set(rows.map((r) => r.provider))]; + // 而组里的每一条都知道自己走了哪个上游(没有发往任何上游的那几条是空的,不算) + const providers = [...new Set(rows.map((r) => r.provider).filter(Boolean))]; const failed = s?.errors ?? failedIn(g); const turns = s?.turns ?? rows.length; const openIt = () => { diff --git a/src/types.ts b/src/types.ts index 08da3f17..5a0d83d3 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,6 +14,7 @@ import type { CostBucketGroup, Event, Guard, + InFlightRequest, LatencyView, Msg, SecretItem, @@ -97,9 +98,9 @@ export interface RequestRow { /** * 这次花了多少微分。 * - * **事件流里没有它。**价钱是存储层落库时按价目表算出来的,算在 - * 事件之后 —— 所以刚跑完的那一行先是空的,几秒后由历史补上 - * (见 useRequests 的对账)。空着显示「—」,不显示 0。 + * **结局事件里没有它。**价钱是存储层落库时按价目表算出来的,算完 core + * 补一条 `request_priced` —— 所以刚跑完的那一行先是空的,紧跟着补上。 + * 空着显示「—」,不显示 0。 */ costMicros?: number; /** 上游没给用量、只能按输入长度估的。显示时要带 `~` */ @@ -121,12 +122,11 @@ export interface RequestRow { /** * 它属于哪次会话,和 `SessionView.id` 同一个值。 * - * **只有落库之后才有。**会话 id 是存储层给的,事件里那个 `session_fp` - * 只是指纹,差着起始时刻那一截。所以正在跑的那一条是没有会话的 —— - * 它确实还没被记下来,归组时独立成行,落库之后自然归位。 + * **开始时就有**(`request_started.session`):网关在请求开始的那一刻定下它, + * 落库时记的就是这一个。所以正在跑的那一条已经在它的会话里,不用等落库。 * - * 认不出会话的(拼不出指纹的,比如 WebSocket)也没有 —— **不能拿一个假的 - * 把它们凑成一组**,它们之间唯一的共同点是我们不知道它属于谁。 + * 认不出会话的(正文里没有能认人的东西,或者是 WebSocket)没有 —— **不能拿一个 + * 假的把它们凑成一组**,它们之间唯一的共同点是我们不知道它属于谁。 */ session?: string; } @@ -146,6 +146,7 @@ export function applyEvent(rows: Map, ev: CoreEvent): void { path: ev.path, atMs: ev.at_ms, state: "in_flight", + session: ev.session ?? undefined, }); break; case "request_headers": { @@ -284,12 +285,16 @@ export interface SeenSince { } /** - * 把 core 的「此刻还在跑的」快照(`in_flight_requests`)补成「进行中」的行。 + * 把 core 的「此刻还在跑的」快照(`GET /in-flight` 的 `requests`)补成「进行中」的行。 * 返回有没有改动。 * + * 快照里每个请求带着它到目前为止的事件,第一条是开始事件,之后是响应头、路由、格式 + * 转换、防护的记录。**按原来的顺序重放一遍**,和从头听起一样:半路才补上的那一行也有 + * 状态码、服务它的上游和徽标。 + * * **只补事件流没给的。**中途结束的不补 —— 补进去就是一行永远等不到结局的 - * 「进行中」;中途开始的、已经在跑的也不补 —— 那一行事件流已经建了,开始 - * 事件再套一遍会把已经到了的响应头冲掉。 + * 「进行中」;中途开始的、已经在跑的也不补 —— 那一行事件流已经建了,从开始 + * 事件再重放一遍会把快照之后才到的那几条冲掉。 * * 同一个 id 已经有一行、但它不在跑:那是上一次 core 留下的(见 * `interruptInFlight`)。core 重启后接着库里最大的号往下发,而没落库的 @@ -297,15 +302,14 @@ export interface SeenSince { */ export function applyInFlight( rows: Map, - open: CoreEvent[], + open: InFlightRequest[], seen: SeenSince, ): boolean { let changed = false; - for (const ev of open) { - if (ev.kind !== "request_started") continue; - if (seen.ended.has(ev.id) || seen.started.has(ev.id)) continue; - if (rows.get(ev.id)?.state === "in_flight") continue; - applyEvent(rows, ev); + for (const { id, events } of open) { + if (seen.ended.has(id) || seen.started.has(id)) continue; + if (rows.get(id)?.state === "in_flight") continue; + for (const ev of events) applyEvent(rows, ev); changed = true; } return changed; diff --git a/src/upstreams/ChatgptAccountSection.tsx b/src/upstreams/ChatgptAccountSection.tsx index 6e5a68c5..cb7cbaef 100644 --- a/src/upstreams/ChatgptAccountSection.tsx +++ b/src/upstreams/ChatgptAccountSection.tsx @@ -141,12 +141,7 @@ export function ChatgptAccountSection({
- +
@@ -268,19 +263,12 @@ export function ChatgptAccountSection({ * 先说**登的是哪个账号** —— 上游的名字是用户自己取的,说明不了这一条。 * **凭据失效时这里是唯一的出路**,所以它自己就带着重新登录。 */ -function LoginBox({ - editing, - email, - plan, - onRelogin, -}: { - editing: ProviderView; - email: string | null; - plan: string | null; - onRelogin: () => void; -}) { +function LoginBox({ editing, onRelogin }: { editing: ProviderView; onRelogin: () => void }) { const t = useText(chatgptAccountText); const oauth = editing.oauth; + // 账号和套餐是 core 从凭据的令牌里读的:凭据失效之后仍是最后登着的那个 + const email = oauth?.account?.email ?? null; + const plan = oauth?.account?.plan; const broken = oauth?.needs_login === true; const expires = oauth?.expires_at ? Date.parse(oauth.expires_at) : NaN; const left = Number.isNaN(expires) ? null : resetIn((expires - Date.now()) / 1000); diff --git a/src/upstreams/ChatgptLoginDialog.tsx b/src/upstreams/ChatgptLoginDialog.tsx index 46a14f7e..12a507c1 100644 --- a/src/upstreams/ChatgptLoginDialog.tsx +++ b/src/upstreams/ChatgptLoginDialog.tsx @@ -16,12 +16,12 @@ import { Field, FieldLabel } from "@/ui/field"; import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { StatusLabel } from "@/ui/status-dot"; -import type { ChatgptLoginMode, ChatgptLoginStatus, CoreEvent, Overview } from "@/types"; +import type { ChatgptLoginMode, ChatgptLoginStatus, ChatgptPlan, CoreEvent, Overview } from "@/types"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; import { chatgptLoginText } from "./ChatgptLoginDialog.i18n"; -import { coreText, errorText, proxyKindLabel, shortUrl } from "./labels"; +import { coreText, errorText, planLabel, proxyKindLabel, shortUrl } from "./labels"; import { DialogError, FormItem } from "./parts"; import { freeName } from "./upstreamForm"; import { useSystemProxyLabel } from "@/connection/Remote"; @@ -37,7 +37,7 @@ type Phase = | { at: "browser"; id: string } /** 码已经拿到,等用户在另一台设备上输 */ | { at: "device"; id: string; code: string; url: string } - | { at: "done"; provider: string; plan: string | null }; + | { at: "done"; provider: string; plan: ChatgptPlan | null }; /** * 用 ChatGPT 账号新建上游,或给已有的账号换一次凭据。 @@ -169,6 +169,7 @@ export function ChatgptLoginDialog({ const nameTaken = !relogin && taken.includes(name.trim()) && phase.at === "form"; const canStart = name.trim().length > 0 && !nameTaken && understood && !busy; + const planName = phase.at === "done" ? planLabel(phase.plan) : null; return ( !o && void cancel()}> @@ -296,7 +297,7 @@ export function ChatgptLoginDialog({

{t.done({phase.provider})} - {phase.plan && ` ${t.plan(phase.plan)}`} + {planName && ` ${t.plan(planName)}`}

{t.doneHint}

diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index c5b2dea1..d316eb52 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -14,7 +14,7 @@ import { resetAt } from "@/format"; import { useNow } from "@/useNow"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; -import { usd, type ChatgptUsage, type ProviderView, type QuotaWindow } from "@/types"; +import { usd, type ProviderView, type QuotaWindow } from "@/types"; import type { UpstreamStats } from "./api"; import { slotsByUpstream, type Slot } from "./data"; import { @@ -63,7 +63,6 @@ export function UpstreamTable({ providers, stats, since, - accounts, inFlight, refreshing, focus, @@ -73,8 +72,6 @@ export function UpstreamTable({ stats: Resource; /** 走势第一格的起点(对齐到整点) */ since: number; - /** 账号类上游问来的账号信息,按上游名。还没问到的就没有 */ - accounts: Record; /** 此刻每个上游在途的请求数 */ inFlight: ReadonlyMap; /** 正在手动刷新模型清单的上游 */ @@ -127,7 +124,6 @@ export function UpstreamTable({ > 0 && !p.disabled} liveCount={inFlight.get(p.name) ?? 0} /> @@ -193,21 +189,11 @@ export function problemsOf(p: ProviderView): { tone: StatusTone; label: string; * 名称一格:标志、名字、套餐与状态,下面一行是协议、地址、出站方式 —— 这一家 * 在哪、怎么连。地址可能很长(带路径的中转):截断,悬停看全。 */ -function NameCell({ - p, - account, - live, - liveCount, -}: { - p: ProviderView; - account?: ChatgptUsage; - live: boolean; - liveCount: number; -}) { +function NameCell({ p, live, liveCount }: { p: ProviderView; live: boolean; liveCount: number }) { const t = useText(upstreamTableText); const problems = problemsOf(p); const problem = problems[0]; - const plan = planLabel(account?.plan); + const plan = planLabel(p.oauth?.account?.plan); const tile = ; return ( @@ -255,7 +241,7 @@ function NameCell({ )}
- +
@@ -266,15 +252,17 @@ function NameCell({ * 这一家在哪、怎么连。 * * 账号类上游的地址永远是同一个,**写出来一行废话** —— 那一格留给邮箱:登了两个 - * 账号时,它是唯一能分辨哪行是哪个的东西。 + * 账号时,它是唯一能分辨哪行是哪个的东西。邮箱是 core 从这份凭据的令牌里读的, + * 不用为了它去问上游。 */ -function Where({ p, account }: { p: ProviderView; account?: ChatgptUsage }) { +function Where({ p }: { p: ProviderView }) { const t = useText(upstreamTableText); const isAccount = p.protocol === "chatgpt"; - const where = isAccount ? (account?.email ?? null) : shortUrl(p.base_url); + const email = p.oauth?.account?.email ?? null; + const where = isAccount ? email : shortUrl(p.base_url); // 直连是默认,不用说 const egress = p.proxy === "direct" ? "" : ` · ${t.via(egressLabel(p.proxy))}`; - const full = [protocolLabel(p.protocol), isAccount ? account?.email : p.base_url].filter(Boolean).join(" · "); + const full = [protocolLabel(p.protocol), isAccount ? email : p.base_url].filter(Boolean).join(" · "); return (
{protocolLabel(p.protocol)} diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index 8b558935..04b8238e 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -19,7 +19,7 @@ import { commonText } from "@/i18n/common.i18n"; import { usd, type Overview, type PricingStatus, type ProviderView } from "@/types"; import { api, type UpstreamStats } from "./api"; import { ChatgptLoginDialog } from "./ChatgptLoginDialog"; -import { patch, useAccounts, useInFlight, usePricingStatus, useUpstreamStats } from "./data"; +import { patch, useAccountQuotas, useInFlight, usePricingStatus, useUpstreamStats } from "./data"; import { DeleteDialog, type Referrer } from "./DeleteDialog"; import { coreText, errorText, plain } from "./labels"; import { PriceSheetDialog, type PriceSheetDialogMode } from "./PriceSheetDialog"; @@ -88,7 +88,7 @@ export default function UpstreamsPage({ const [dialog, setDialog] = useState(null); const { stats, since } = useUpstreamStats(); const pricing = usePricingStatus(configVersion); - const accounts = useAccounts(ov.providers, () => void stats.reload()); + useAccountQuotas(ov.providers, () => void stats.reload()); const inFlight = useInFlight(); const proxies = ov.proxies; @@ -381,7 +381,6 @@ export default function UpstreamsPage({ providers={providers} stats={stats} since={since} - accounts={accounts} inFlight={inFlight} refreshing={refreshing} focus={focus} diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 1806183a..8c3118a0 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -52,7 +52,7 @@ export const api = { /** 起点和格宽都由界面给:格子对齐到本地整点(见 `bucketStart`) */ upstreamStats: (sinceMs: number, bucketMs: number) => invoke("upstream_stats", { sinceMs, bucketMs }), - /** 此刻在途的请求(开始事件的快照)。页面半路挂上时用它补齐 */ + /** 此刻在途的请求,各带到目前为止的事件。页面半路挂上时用它补齐 */ inFlight: () => call("InFlight", null), createProxy: (save: ProxySave) => call("CreateProxy", save), diff --git a/src/upstreams/data.test.ts b/src/upstreams/data.test.ts index f5193026..c014f0bf 100644 --- a/src/upstreams/data.test.ts +++ b/src/upstreams/data.test.ts @@ -10,6 +10,8 @@ function bucket(name: string, at: number, requests: number, failed = 0): CostBuc failed, cost_micros_exact: 0, cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, diff --git a/src/upstreams/data.ts b/src/upstreams/data.ts index 31affe09..3d155966 100644 --- a/src/upstreams/data.ts +++ b/src/upstreams/data.ts @@ -1,5 +1,5 @@ /** - * 上游页的几份数据:24 小时统计、默认价目表的状态、账号类上游的账号信息、在途请求。 + * 上游页的几份数据:24 小时统计、默认价目表的状态、账号类上游的额度、在途请求。 * * 前三份走 `useResource`:切走再回来先画上一次的数,后台再取,不闪。在途请求是 * 跟着事件流走的一份现状,不缓存。 @@ -8,7 +8,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { listen } from "@tauri-apps/api/event"; import { bucketStart } from "@/format"; import { useResource, type Resource } from "@/lib/resource"; -import type { ChatgptUsage, CoreEvent, CostBucketGroup, ProviderView } from "@/types"; +import type { CoreEvent, CostBucketGroup, ProviderView } from "@/types"; import { useNow } from "@/useNow"; import { api, type UpstreamStats } from "./api"; @@ -107,15 +107,15 @@ export function usePricingStatus(configVersion: string) { } /** - * 账号类上游:**打开这一页时问一次它自己。** + * 账号类上游的额度:**打开这一页时问一次它自己。** * - * 一次问答同时回答三件事:登的是哪个账号、什么套餐、额度还剩多少。这三件都不在 - * 配置里 —— 额度平时是跟着真实流量白捡的,刚启动、或者这个账号今天还没被用过时, - * 不问就什么都没有。问一次是一次真实调用:**失败了也不重试**,连不上时反复问只会 - * 把错误刷满日志;单个账号问不到不影响别的。问完 core 也记下了额度,`onAnswered` - * 让统计从 core 再读一遍,免得这里和它各存一份。 + * 登的是哪个账号、什么套餐不用问 —— core 从这份凭据自己的令牌里读,就在上游视图里 + * (`oauth.account`)。额度不一样:平时是跟着真实流量白捡的,刚启动、或者这个账号 + * 今天还没被用过时,不问就什么都没有。问一次是一次真实调用:**失败了也不重试**, + * 连不上时反复问只会把错误刷满日志;单个账号问不到不影响别的。问完 core 记下了 + * 额度,`onAnswered` 让统计从 core 再读一遍,免得这里和它各存一份。 */ -export function useAccounts(providers: ProviderView[], onAnswered: () => void): Record { +export function useAccountQuotas(providers: ProviderView[], onAnswered: () => void): void { const names = providers .filter((p) => p.protocol === "chatgpt" && !p.disabled) .map((p) => p.name) @@ -123,28 +123,18 @@ export function useAccounts(providers: ProviderView[], onAnswered: () => void): const key = names.join("\n"); const answered = useRef(onAnswered); answered.current = onAnswered; - const r = useResource( - names.length > 0 ? "upstream-accounts" : null, + useResource( + names.length > 0 ? "upstream-account-quotas" : null, async () => { - const got = await Promise.all( - names.map((n) => - api - .chatgptUsage(n) - .then((u) => [n, u] as const) - .catch(() => null), - ), - ); - const found = got.filter((g) => g !== null); - if (found.length > 0) answered.current(); - return Object.fromEntries(found) as Record; + const got = await Promise.all(names.map((n) => api.chatgptUsage(n).then(() => true, () => false))); + const n = got.filter(Boolean).length; + if (n > 0) answered.current(); + return n; }, { deps: [key] }, ); - return r.data ?? NO_ACCOUNTS; } -const NO_ACCOUNTS: Record = {}; - /** 在途请求记住多少条已经结束的 id(结束事件比快照先到时用来排除)。只是防御性的上限 */ const ENDED_CAP = 512; @@ -153,8 +143,9 @@ const ENDED_CAP = 512; * * 开始事件里就有上游;换了上游(转移)以 `request_routed` 的最后一跳为准;三种结局 * 都算结束。**页面半路挂上**时,已经在飞的那几个没有开始事件可听 —— 挂上时读一次 - * `/in-flight` 的快照补上(比快照先到的结束事件记下来,免得补回一个已经结束的)。 - * core 停了、重启了,在途的全部作废:它们不会再有结局。 + * `/in-flight` 的快照,把每个请求到目前为止的事件照原样重放(比快照先到的结束事件 + * 记下来,免得补回一个已经结束的)。core 停了、重启了,在途的全部作废:它们不会再有 + * 结局。 */ export function useInFlight(): ReadonlyMap { const live = useRef(new Map()); @@ -164,14 +155,22 @@ export function useInFlight(): ReadonlyMap { useEffect(() => { let alive = true; const bump = () => alive && setTick((n) => n + 1); + /** 开始、路由落到「哪个请求在哪个上游」上。事件流和快照重放用的是同一段 */ + const track = (ev: CoreEvent) => { + if (ev.kind === "request_started") live.current.set(ev.id, ev.provider); + else if (ev.kind === "request_routed") { + const last = ev.attempts[ev.attempts.length - 1]; + if (last && live.current.has(ev.id)) live.current.set(ev.id, last.provider); + } + }; const seed = () => { api .inFlight() - .then((evs) => { + .then((open) => { if (!alive) return; - for (const ev of evs) { - if (ev.kind !== "request_started" || ended.current.has(ev.id) || live.current.has(ev.id)) continue; - live.current.set(ev.id, ev.provider); + for (const { id, events } of open.requests) { + if (ended.current.has(id) || live.current.has(id)) continue; + for (const ev of events) track(ev); } bump(); }) @@ -191,13 +190,11 @@ export function useInFlight(): ReadonlyMap { const ev = e.payload; switch (ev.kind) { case "request_started": - if (!ended.current.has(ev.id)) live.current.set(ev.id, ev.provider); + if (!ended.current.has(ev.id)) track(ev); break; - case "request_routed": { - const last = ev.attempts[ev.attempts.length - 1]; - if (last && live.current.has(ev.id)) live.current.set(ev.id, last.provider); + case "request_routed": + track(ev); break; - } case "request_finished": case "request_failed": case "request_cancelled": diff --git a/src/upstreams/labels.test.ts b/src/upstreams/labels.test.ts index a5c22f65..b26b9f9f 100644 --- a/src/upstreams/labels.test.ts +++ b/src/upstreams/labels.test.ts @@ -1,7 +1,7 @@ import { beforeAll, describe, expect, it } from "vitest"; import { setLang } from "@/i18n"; import type { ProviderView } from "@/types"; -import { l1ErrorText, modelFace } from "./labels"; +import { l1ErrorText, modelFace, planLabel } from "./labels"; // 断言按中文写:不随跑测试那台机器的系统语言变 beforeAll(() => setLang("zh")); @@ -85,3 +85,21 @@ describe("链路测速失败的那句话", () => { expect(l1ErrorText(base)).not.toBe(""); }); }); + +describe("planLabel", () => { + it("names a known plan the way Codex does, renamed plans included", () => { + expect(planLabel("plus")).toBe("Plus"); + expect(planLabel("prolite")).toBe("Pro"); + expect(planLabel("team")).toBe("Business"); + expect(planLabel("business")).toBe("Enterprise"); + expect(planLabel("self_serve_business_prolite")).toBe("Business Premium"); + }); + + it("shows a word it does not know as it came, never as 'unknown'", () => { + expect(planLabel("pro_ultra")).toBe("pro_ultra"); + // 对象原型上的名字不算认得 + expect(planLabel("constructor")).toBe("constructor"); + expect(planLabel(null)).toBeNull(); + expect(planLabel("")).toBeNull(); + }); +}); diff --git a/src/upstreams/labels.ts b/src/upstreams/labels.ts index b9bd062d..b0ea1ada 100644 --- a/src/upstreams/labels.ts +++ b/src/upstreams/labels.ts @@ -8,6 +8,8 @@ import { textOf } from "@/i18n"; import { coreText } from "@/i18n/core.i18n"; import type { Billing, + ChatgptPlan, + KnownChatgptPlan, L1Result, L1Skip, L1Stage, @@ -160,22 +162,38 @@ export function modelFace(p: ProviderView): { }; } +/** + * ChatGPT 套餐的叫法,和 Codex 客户端显示的一样。**词和叫法不是一回事**:套餐改过名, + * `team` 现在叫 Business,`business` 叫 Enterprise,`prolite` 才是 Pro。产品名,中英 + * 界面一样。 + */ +const PLANS: Record = { + free: "Free", + go: "Go", + plus: "Plus", + pro: "Pro (More)", + prolite: "Pro", + promax: "Pro (Max)", + team: "Business", + business: "Enterprise", + self_serve_business_prolite: "Business Premium", + self_serve_business_usage_based: "Business", + enterprise: "Enterprise", + ent26: "Enterprise", + enterprise_cbp_automation: "Enterprise (Automation)", + enterprise_cbp_usage_based: "Enterprise", + edu: "Edu", + edu_plus: "Edu Plus", + edu_pro: "Edu Pro", +}; + /** * 订阅类型。**认不出来的原样显示** —— OpenAI 随时会多出一个 * 新名字,把它显示成「未知」比直接写出那个词更差。 */ -export function planLabel(plan: string | null | undefined): string | null { +export function planLabel(plan: ChatgptPlan | null | undefined): string | null { if (!plan) return null; - const known: Record = { - free: "Free", - plus: "Plus", - pro: "Pro", - team: "Team", - business: "Business", - enterprise: "Enterprise", - edu: "Edu", - }; - return known[plan.toLowerCase()] ?? plan; + return Object.hasOwn(PLANS, plan) ? PLANS[plan as KnownChatgptPlan] : plan; } export function quotaWindowLabel(window: string): string { diff --git a/src/useRequests.ts b/src/useRequests.ts index 1985fe66..59db546c 100644 --- a/src/useRequests.ts +++ b/src/useRequests.ts @@ -62,8 +62,7 @@ export function mergeHistory( next.costEstimated = h.cost_estimated; } next.translated ??= h.translated ?? undefined; - // **会话 id 只有库里有。**事件里那个是指纹,差着起始时刻 - next.session = h.session ?? next.session; + next.session ??= h.session ?? undefined; if (!next.secrets || !next.flagged) { const marks = marksFromEvents(h.security); next.secrets ??= marks.secrets; @@ -269,7 +268,7 @@ export function useRequests(ready: boolean) { /** * 从库里读一遍最近的记录,并进当前列表。 * - * 开窗时读一次;之后每批请求落地再读一次(`settled`),给新落地的行补上会话。 + * 开窗时读一次;之后每批请求落地再读一次(`settled`),补上事件流没见全的行。 * 怎么并见 `mergeHistory`:历史只添信息,结局没送到的行按库里补上。 */ const pull = useCallback(async () => { @@ -316,12 +315,11 @@ export function useRequests(ready: boolean) { }, [seed, ready]); /* - **落库之后再对一次账。**会话 id 是存储层给的,而事件里只有指纹 —— - 所以一条请求要等它写进库、再被读回来,才知道自己属于哪次任务。 + **落库之后再对一次账。**事件流没说全的,库里有:页面挂上之前就开始、又在 + 快照路上结束了的请求,事件流上只见过它的结局,列表里还没有这一行;事件流 + 丢过事件时,丢掉的那些结局也要从库里补。 - `settled` 正是「刚落地的那几行已经在库里了」这个信号,本来就有, - 只是一直只用来重算概览的聚合。不挂上它的话,这一程里跑出来的请求 - 永远归不了组,得等重开窗口。 + `settled` 正是「刚落地的那几行已经在库里了」这个信号。 */ useEffect(() => { if (settled === 0) return; @@ -443,7 +441,7 @@ export function useRequests(ready: boolean) { const open = await call("InFlight", null); // 等的这会儿 core 停了、或者又开始了一次对账:这份作废 if (!alive || since !== mark) return; - if (applyInFlight(store.current, open, mark)) publish(); + if (applyInFlight(store.current, open.requests, mark)) publish(); } catch { // 问不到就和以前一样:等它们结束、落库之后对账时出现 } finally {