From 3a5ec3ba94dd595fe0eae624875e269af19b50b6 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:08:57 -0500 Subject: [PATCH 01/12] feat(routing): record the serving OAuth pool's per-account state on the final request row The final request log of a request served by a multi-account generic OAuth provider now carries accountRoster: each account's hashed o-label and whether it was available, paused, needing re-auth, cooling down, out of quota, or not listing the model. It stays in memory for /api/logs and never reaches usage.jsonl. /api/oauth/accounts returns the same logLabel per account so the dashboard can name the account a roster label belongs to. --- scripts/test-layout/layout-usage.json | 2 + src/oauth/generic-account-failover.ts | 53 ++++++ src/server/management/oauth-account-routes.ts | 3 +- src/server/request-log-route-live.ts | 58 +++++++ src/server/request-log.ts | 4 +- tests/fixtures/test-layout-expected.json | 4 +- tests/oauth/oauth-accounts-log-label.test.ts | 74 +++++++++ .../usage/request-log-account-roster.test.ts | 152 ++++++++++++++++++ 8 files changed, 346 insertions(+), 4 deletions(-) create mode 100644 src/server/request-log-route-live.ts create mode 100644 tests/oauth/oauth-accounts-log-label.test.ts create mode 100644 tests/usage/request-log-account-roster.test.ts diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index f7c547b8f8d..dfebb09aa51 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -3,6 +3,8 @@ "usage-filter-index.test.ts": "usage", "usage-filter-paging.test.ts": "usage", "request-log.test.ts": "usage", + "request-log-account-roster.test.ts": "usage", + "oauth-accounts-log-label.test.ts": "oauth", "request-log-normalization.test.ts": "usage", "request-log-error-detail.test.ts": "usage", "provider-failure-detail.test.ts": "usage", diff --git a/src/oauth/generic-account-failover.ts b/src/oauth/generic-account-failover.ts index 49cca431de1..f62ca631f31 100644 --- a/src/oauth/generic-account-failover.ts +++ b/src/oauth/generic-account-failover.ts @@ -48,6 +48,9 @@ import { ACCOUNT_QUOTA_TTL_MS } from "../providers/quota-wire"; import { sweepExpiredOnWrite } from "../lib/state-store-sweeper"; import { subscribeOAuthAccountPauseChanges } from "../lib/account-selection-events"; import type { OcxConfig, OcxProviderConfig } from "../types"; +import { oauthAccountLogLabel } from "../codex/account-label"; +import { baseProviderLabel } from "../providers/label"; +import { registerAccountRosterProbe, type AccountRosterState, type AccountRosterV1 } from "../server/request-log-route-live"; /** Cap same-request rotations so a short Retry-After cannot spin. Mirrors the Anthropic bound. */ export const GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST = 3; @@ -410,6 +413,56 @@ function eligibleIdsIn( .map(account => account.id); } +const ROSTER_CAP = 16; +const LABEL_MEMO_CAP = 256; +const labelMemo = new Map(); + +/** The `o` label `accountLogLabel` uses for this account; hashed once per provider and account. */ +export function genericAccountLogLabel(providerName: string, accountId: string): string { + const base = baseProviderLabel(providerName); + const key = `${base}${accountId}`; + let label = labelMemo.get(key); + if (label === undefined) { + if (labelMemo.size >= LABEL_MEMO_CAP) labelMemo.clear(); + label = oauthAccountLogLabel(accountId, base); + labelMemo.set(key, label); + } + return label; +} + +/** Same checks the selector applies, in the order that decides which reason a skipped account shows. */ +function rosterState( + providerName: string, account: ProviderAccount, model: string, now: number, family: QuotaModelFamily | undefined, +): AccountRosterState { + if (account.paused === true) return "paused"; + if (account.needsReauth === true) return "needs-reauth"; + if (isAccountQuotaExhausted(providerName, account.id, model, account)) return "quota-exhausted"; + if (isCooled(providerName, account.id, now, providerName === "kiro" ? undefined : family)) return "cooldown"; + if (providerName === "google-antigravity" && accountListsModel(providerName, account.id, model) === false) { + return "model-unlisted"; + } + return "available"; +} + +/** Per-account state for a multi-account generic OAuth pool, or undefined when there is no pool to show. */ +export function genericAccountRoster(providerName: string, model: string, now = Date.now()): AccountRosterV1 | undefined { + const base = baseProviderLabel(providerName); + if (EXCLUDED_PROVIDERS.has(providerName) || base === "openai" || base === "anthropic" || base === "anthropic2") return undefined; + const set = getAccountSet(providerName); + if (!set || set.accounts.length < 2) return undefined; + const family = classifyModelFamilyForQuota(providerName, model); + return { + provider: base, + accounts: set.accounts.slice(0, ROSTER_CAP).map(account => ({ + label: genericAccountLogLabel(providerName, account.id), + state: rosterState(providerName, account, model, now, family), + })), + ...(set.accounts.length > ROSTER_CAP ? { truncated: true as const } : {}), + }; +} + +registerAccountRosterProbe(genericAccountRoster); + /** * Whether reactive rotation has an alternate account it could select right now. * diff --git a/src/server/management/oauth-account-routes.ts b/src/server/management/oauth-account-routes.ts index 8df040da50f..4b9649acf4d 100644 --- a/src/server/management/oauth-account-routes.ts +++ b/src/server/management/oauth-account-routes.ts @@ -517,7 +517,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise< const quotaMode = providerOAuthAccountQuotaMode(provider); const quotaProvider = config.providers[provider]; const { getAccountSet } = await import("../../oauth/store"); - const { isGenericFailoverProvider, kiroAutoSelection } = await import("../../oauth/generic-account-failover"); + const { genericAccountLogLabel, isGenericFailoverProvider, kiroAutoSelection } = await import("../../oauth/generic-account-failover"); const effectiveProvider = genericOAuthProviderConfig(provider, config); const supportsPause = effectiveProvider !== undefined && (isAnthropicOAuthInstance(provider) && effectiveProvider.authMode === "oauth" @@ -546,6 +546,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise< const accountLabel = accountDisplayLabel(full?.credential.email, maskEmails); return { ...summary, ...(maskedLabel ? { maskedLabel } : {}), ...(accountLabel ? { accountLabel } : {}), ...oauthAccountHealthFields(provider, summary.id, health), quotaMode, + ...(effectiveProvider && isGenericFailoverProvider(provider, effectiveProvider) ? { logLabel: genericAccountLogLabel(provider, summary.id) } : {}), ...(supportsPause ? { paused: full?.paused === true, ...(full?.pauseDetails ? { pauseDetails: full.pauseDetails } : {}) } : {}), ...(isAnthropicOAuthInstance(provider) && supportsPause ? { autoSwitchThresholdOverride: full?.autoSwitchThresholdOverride ?? null, effectiveAutoSwitchThreshold: effectiveAnthropicAccountThresholdForInstance(provider as AnthropicInstanceId, config, full), diff --git a/src/server/request-log-route-live.ts b/src/server/request-log-route-live.ts new file mode 100644 index 00000000000..c19cbefe587 --- /dev/null +++ b/src/server/request-log-route-live.ts @@ -0,0 +1,58 @@ +import { OAUTH_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label"; + +/** + * Per-account state of a multi-account OAuth pool, captured once when the final request row is + * written. Labels are the same hashed `o` labels `accountLogLabel` carries; no account id, + * email or credential ever appears here. In-memory only: the usage.jsonl projection in + * request-log.ts rebuilds its row field by field and never copies this. + */ +export type AccountRosterState = + | "available" + | "paused" + | "needs-reauth" + | "cooldown" + | "quota-exhausted" + | "model-unlisted"; + +export interface AccountRosterV1 { + /** Base provider name whose account pool this is. */ + provider: string; + /** At most 16 entries in account-set order. */ + accounts: Array<{ label: string; state: AccountRosterState }>; + truncated?: true; +} + +export interface AccountRosterEntryField { + accountRoster?: AccountRosterV1; +} + +export type AccountRosterProbe = (providerName: string, model: string, now: number) => AccountRosterV1 | undefined; + +/** + * Registered by the OAuth layer at module load. request-log must not import `src/oauth`, and an + * install that never loads it keeps a null probe, so the final log path costs one null check. + */ +let probe: AccountRosterProbe | null = null; + +export function registerAccountRosterProbe(fn: AccountRosterProbe | null): void { + probe = fn; +} + +/** + * The roster for the account that served a request, or `{}`. The `o` label gate is the cheap, + * IO-free test for "a generic multi-account OAuth provider served this": only + * `stampOAuthAccountLabel` mints it, and it skips Codex and Anthropic pools. + */ +export function accountRosterField( + served: { provider?: string; model?: string; accountLogLabel?: string } | undefined, + now = Date.now(), +): AccountRosterEntryField { + if (!probe || !served?.provider || !OAUTH_ACCOUNT_LOG_LABEL_RE.test(served.accountLogLabel ?? "")) return {}; + try { + const accountRoster = probe(served.provider, served.model ?? "", now); + return accountRoster ? { accountRoster } : {}; + } catch { + // A diagnostic must never fail request logging. + return {}; + } +} diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 09bce7a2bd6..9ae0758d5c9 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -4,6 +4,7 @@ import { normalizeRecordedClient, type UsageClient } from "../usage/client"; import { anthropicAccountTagField, stampApiKeyAccountLabel, usesApiKeyAccount } from "../providers/label"; import { finalizeProviderCacheAffinity } from "./request-log-cache-affinity"; import { aggregateAttemptUsage } from "./request-log-attempt-usage"; +import { accountRosterField, type AccountRosterEntryField } from "./request-log-route-live"; export { aggregateAttemptUsage } from "./request-log-attempt-usage"; import { KEY_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label"; @@ -329,7 +330,7 @@ export function rebindCacheDiagnosticBody( cacheDiagnosticHooks()?.rebind(body, draft); } -export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField { +export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField, AccountRosterEntryField { requestId: string; client?: UsageClient; /** The logical request this row belongs to (#4546); absent on rows written without a budget. */ @@ -1684,6 +1685,7 @@ function writeFinalRequestLog( ...(logCtx.transportPhase ? { transportPhase: logCtx.transportPhase } : {}), ...(logCtx.terminalSource ? { terminalSource: logCtx.terminalSource } : {}), ...(logCtx.routeDecision ? { routeDecision: logCtx.routeDecision } : {}), + ...accountRosterField(isCombo ? attempts?.at(-1) : logCtx), ...(jevDecision ? { jevDecision } : {}), ...(claudeCompatibility ? { claudeCompatibility } : {}), ...(protocolTrace ? { protocolTrace } : {}), diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ebfabf37355..c3c6b1b1b95 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1120,7 +1120,7 @@ "nous-oauth.test.ts": "providers", "novita-provider.test.ts": "providers", "nscale-vultr-provider.test.ts": "providers", "nvidia-nim-hardening.test.ts": "providers", "oauth-account-attribution.test.ts": "oauth", "oauth-account-id-collision.test.ts": "oauth", - "oauth-account-quota-rank.test.ts": "oauth", "oauth-accounts-api.test.ts": "oauth", + "oauth-account-quota-rank.test.ts": "oauth", "oauth-accounts-api.test.ts": "oauth", "oauth-accounts-log-label.test.ts": "oauth", "oauth-anthropic-identity.test.ts": "oauth", "oauth-callback-binds.test.ts": "oauth", "oauth-callback-server.test.ts": "oauth", "oauth-device-code-contract.test.ts": "oauth", "oauth-first-add-hint.test.ts": "gui", "oauth-health.test.ts": "oauth", @@ -1283,7 +1283,7 @@ "fixture-windows-runtime-preload.test.ts": "ci-workflows", "repo-hygiene.test.ts": "ci-workflows", "request-decompress.test.ts": "usage", "request-evidence.test.ts": "usage", "request-history-index.test.ts": "usage", "request-history-integrity.test.ts": "usage", - "request-log-attempt-identity.test.ts": "usage", "request-log-conversation.test.ts": "usage", + "request-log-attempt-identity.test.ts": "usage", "request-log-account-roster.test.ts": "usage", "request-log-conversation.test.ts": "usage", "request-log-estimate-cap.test.ts": "usage", "request-log-jev.test.ts": "usage", "request-log-nonstream.test.ts": "usage", "request-log-protocol-trace.test.ts": "usage", "request-log-served-model.test.ts": "usage", "request-log-model-filter.test.ts": "usage", "request-log-generation-window.test.ts": "usage", diff --git a/tests/oauth/oauth-accounts-log-label.test.ts b/tests/oauth/oauth-accounts-log-label.test.ts new file mode 100644 index 00000000000..6c275128740 --- /dev/null +++ b/tests/oauth/oauth-accounts-log-label.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { oauthAccountLogLabel } from "../../src/codex/account-label"; +import { startServer } from "../../src/server"; +import type { OcxConfig } from "../../src/types"; +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { managementFetch as fetch } from "../helpers/management-auth"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +let testDir = ""; +let previousHome: string | undefined; +let isolatedCodexHome: IsolatedCodexHome | null = null; + +function pool(prefix: string, email: string) { + return { + activeAccountId: `${prefix}1`, + accounts: [1, 2].map(n => ({ + id: `${prefix}${n}`, + credential: { access: `t${n}`, refresh: `r${n}`, expires: 9999999999999, email: `${prefix}${n}@${email}`, accountId: `acct-${prefix}${n}`, source: "oauth" }, + })), + }; +} + +beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + isolatedCodexHome = installIsolatedCodexHome("ocx-oauth-log-label-codex-"); + testDir = mkdtempSync(join(tmpdir(), "ocx-oauth-log-label-")); + process.env.OPENCODEX_HOME = testDir; + saveConfig({ + port: 0, hostname: "127.0.0.1", defaultProvider: "xai", + providers: { + xai: { adapter: "openai-chat", baseUrl: "https://api.x.ai/v1", authMode: "oauth" }, + anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "oauth" }, + }, + } as unknown as OcxConfig); + writeFileSync(join(testDir, "auth.json"), JSON.stringify({ xai: pool("xa", "example.test"), anthropic: pool("an", "example.test") }), { mode: 0o600 }); +}); + +afterEach(() => { + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + isolatedCodexHome?.restore(); + isolatedCodexHome = null; + if (testDir) removeTreeWithRetry(testDir); +}); + +describe("GET /api/oauth/accounts logLabel", () => { + test("a generic OAuth provider's accounts carry the label request rows use", async () => { + const server = startServer(0); + try { + const res = await fetch(new URL("/api/oauth/accounts?provider=xai", server.url)); + expect(res.status).toBe(200); + const body = await res.json() as { accounts: Array<{ id: string; logLabel?: string }> }; + expect(body.accounts.map(a => [a.id, a.logLabel])).toEqual([ + ["xa1", oauthAccountLogLabel("xa1", "xai")], + ["xa2", oauthAccountLogLabel("xa2", "xai")], + ]); + expect(body.accounts[0]!.logLabel).toMatch(/^o[a-f0-9]{6}$/); + } finally { await server.stop(true); } + }, 30_000); + + test("the Anthropic pool does not get a generic label", async () => { + const server = startServer(0); + try { + const res = await fetch(new URL("/api/oauth/accounts?provider=anthropic", server.url)); + const body = await res.json() as { accounts: Array<{ logLabel?: string }> }; + expect(body.accounts).toHaveLength(2); + expect(body.accounts.every(a => a.logLabel === undefined)).toBe(true); + } finally { await server.stop(true); } + }, 30_000); +}); diff --git a/tests/usage/request-log-account-roster.test.ts b/tests/usage/request-log-account-roster.test.ts new file mode 100644 index 00000000000..ef995cdcbcf --- /dev/null +++ b/tests/usage/request-log-account-roster.test.ts @@ -0,0 +1,152 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { oauthAccountLogLabel } from "../../src/codex/account-label"; +import { clearGenericFailoverHealth, genericAccountRoster, rotateGenericOAuthAccountOn429 } from "../../src/oauth/generic-account-failover"; +import { clearAccountQuotaCache, setCachedProviderAccountQuotaForTests } from "../../src/providers/quota"; +import { addFinalRequestLog, clearRequestLogsForTests, getRequestLogEntries, type RequestLogEntry } from "../../src/server/request-log"; +import { resetUsageReadCacheForTests, readUsageEntries } from "../../src/usage/log"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const originalHome = process.env.OPENCODEX_HOME; +let home: string; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-account-roster-")); + process.env.OPENCODEX_HOME = home; + clearGenericFailoverHealth(); + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); +}); + +afterEach(() => { + clearGenericFailoverHealth(); + clearAccountQuotaCache("xai"); + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + removeTreeWithRetry(home); +}); + +const config = { + providers: { xai: { adapter: "openai-chat", baseUrl: "https://api.x.ai/v1", authMode: "oauth" } as unknown as OcxProviderConfig }, +} as unknown as OcxConfig; + +interface SeedFlags { paused?: boolean; needsReauth?: boolean } + +/** Writes auth.json directly: the store's own writers harden ACLs per call, which is slow on Windows. */ +function seed(count: number, provider = "xai", flags: Record = {}): string[] { + const accounts = Array.from({ length: count }, (_, i) => ({ + id: `${provider}-acct-${i}`, + credential: { access: `access-${i}`, refresh: `refresh-${i}`, expires: 9999999999999, accountId: `uuid-${i}`, source: "oauth" }, + ...flags[i], + })); + const path = join(home, "auth.json"); + const existing = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {}; + writeFileSync(path, JSON.stringify({ ...existing, [provider]: { activeAccountId: accounts[0]!.id, accounts } }), { mode: 0o600 }); + return accounts.map(account => account.id); +} + +const label = (id: string) => oauthAccountLogLabel(id, "xai"); + +function finalRow(provider: string, accountId: string | undefined, extra: Record = {}): RequestLogEntry { + const rows: RequestLogEntry[] = []; + addFinalRequestLog("roster-row", Date.now(), { + model: "grok-4.7", provider, ...(accountId ? { accountLogLabel: label(accountId) } : {}), ...extra, + }, 200, undefined, row => rows.push(row)); + return rows[0]!; +} + +describe("account roster classification", () => { + test("every account is available when nothing is wrong", () => { + const ids = seed(3); + expect(genericAccountRoster("xai", "grok-4.7")).toEqual({ + provider: "xai", + accounts: ids.map(id => ({ label: label(id), state: "available" })), + }); + }); + + test("paused, needs-reauth, quota-exhausted and cooldown are told apart", () => { + const [paused, reauth, exhausted, cooled, ok] = seed(5, "xai", { 0: { paused: true }, 1: { needsReauth: true } }); + setCachedProviderAccountQuotaForTests("xai", exhausted!, { weeklyPercent: 100, updatedAt: Date.now() }); + rotateGenericOAuthAccountOn429(config, "xai", cooled!, null); + const states = Object.fromEntries(genericAccountRoster("xai", "grok-4.7")!.accounts.map(a => [a.label, a.state])); + expect(states).toEqual({ + [label(paused!)]: "paused", + [label(reauth!)]: "needs-reauth", + [label(exhausted!)]: "quota-exhausted", + [label(cooled!)]: "cooldown", + [label(ok!)]: "available", + }); + }); + + test("precedence is paused, needs-reauth, quota-exhausted, then cooldown", () => { + const [both, exhaustedAndCooled, ok] = seed(3, "xai", { 0: { paused: true, needsReauth: true } }); + setCachedProviderAccountQuotaForTests("xai", exhaustedAndCooled!, { weeklyPercent: 100, updatedAt: Date.now() }); + rotateGenericOAuthAccountOn429(config, "xai", exhaustedAndCooled!, null); + const states = genericAccountRoster("xai", "grok-4.7")!.accounts.map(a => a.state); + expect(states[0]).toBe("paused"); + expect(states[1]).toBe("quota-exhausted"); + expect(states[2]).toBe("available"); + expect(ok).toBeDefined(); + }); + + test("a pool of 17 reports 16 accounts and says it was cut", () => { + seed(17); + const roster = genericAccountRoster("xai", "grok-4.7")!; + expect(roster.accounts).toHaveLength(16); + expect(roster.truncated).toBe(true); + }); + + test("one account, no account, and the Codex or Anthropic pools have no roster", () => { + seed(1); + expect(genericAccountRoster("xai", "grok-4.7")).toBeUndefined(); + expect(genericAccountRoster("cursor", "composer")).toBeUndefined(); + seed(2, "openai"); + seed(2, "anthropic"); + expect(genericAccountRoster("openai", "gpt")).toBeUndefined(); + expect(genericAccountRoster("anthropic", "claude")).toBeUndefined(); + }); +}); + +describe("accountRoster on the final request row", () => { + test("the served row carries the roster and the served label is one of its accounts", () => { + const ids = seed(2, "xai", { 1: { paused: true } }); + const row = finalRow("xai", ids[0]!); + expect(row.accountRoster).toEqual({ + provider: "xai", + accounts: [{ label: label(ids[0]!), state: "available" }, { label: label(ids[1]!), state: "paused" }], + }); + expect(row.accountRoster!.accounts.some(a => a.label === row.accountLogLabel)).toBe(true); + }); + + test("a combo row takes the roster from the last attempt's provider and label", () => { + const ids = seed(2); + const attempt = { + ordinal: 1, provider: "xai", model: "grok-4.7", adapter: "openai-chat", status: 200, durationMs: 5, sendCount: 1, + recoveryKinds: [], usageStatus: "unreported", accountLogLabel: label(ids[0]!), + }; + const row = finalRow("combo-owner", undefined, { comboId: "c", requestedModel: "my-combo", attempts: [attempt] }); + expect(row.provider).toBe("combo"); + expect(row.accountRoster?.accounts.map(a => a.label)).toEqual(ids.map(label)); + }); + + test("single-account and non-OAuth rows have no roster field", () => { + const [only] = seed(1); + expect("accountRoster" in finalRow("xai", only!)).toBe(false); + expect("accountRoster" in finalRow("openrouter", undefined)).toBe(false); + }); + + test("the roster stays in memory and never reaches usage.jsonl", () => { + const ids = seed(2); + expect(finalRow("xai", ids[0]!).accountRoster).toBeDefined(); + addFinalRequestLog("roster-persisted", Date.now(), { model: "grok-4.7", provider: "xai", accountLogLabel: label(ids[0]!) }, 200); + expect(getRequestLogEntries()[0]?.accountRoster).toBeDefined(); + const persisted = readUsageEntries(); + expect(persisted).toHaveLength(1); + expect(JSON.stringify(persisted)).not.toContain("accountRoster"); + }); +}); From c1e12029d49929dac9ef280a239111c364d5247a Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:17:04 -0500 Subject: [PATCH 02/12] feat(routing): record when the final upstream attempt started and how long privacy redaction took Adds upstreamSendMs (request start to the final attempt's start, which includes earlier failed attempts) and an optional privacyRedactionMs to the in-memory request row, so the live routing view can split a request's time into measured phases without inventing DNS or TLS numbers. --- scripts/test-layout/layout-usage.json | 1 + src/server/request-log-route-live.ts | 25 +++++++++++++++ src/server/request-log.ts | 7 +++-- tests/fixtures/test-layout-expected.json | 2 +- .../request-log-route-live-timing.test.ts | 31 +++++++++++++++++++ 5 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 tests/usage/request-log-route-live-timing.test.ts diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index dfebb09aa51..207ba3725f5 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -4,6 +4,7 @@ "usage-filter-paging.test.ts": "usage", "request-log.test.ts": "usage", "request-log-account-roster.test.ts": "usage", + "request-log-route-live-timing.test.ts": "usage", "oauth-accounts-log-label.test.ts": "oauth", "request-log-normalization.test.ts": "usage", "request-log-error-detail.test.ts": "usage", diff --git a/src/server/request-log-route-live.ts b/src/server/request-log-route-live.ts index c19cbefe587..399c9491ead 100644 --- a/src/server/request-log-route-live.ts +++ b/src/server/request-log-route-live.ts @@ -56,3 +56,28 @@ export function accountRosterField( return {}; } } + +/** Request-scoped timing the live routing view reads; both are measured, never derived. */ +export interface RouteLiveTimingContext { + /** Epoch ms the final physical attempt started; set by whoever opens the attempt. */ + activeAttemptStartedAt?: number; + /** ms a privacy redactor spent rewriting the client body, when one ran. */ + privacyRedactionMs?: number; +} + +export interface RouteLiveTimingEntryField { + /** ms from request start until the final attempt started; includes earlier failed attempts. */ + upstreamSendMs?: number; + privacyRedactionMs?: number; +} + +export function routeLiveTimingField(logCtx: RouteLiveTimingContext, start: number): RouteLiveTimingEntryField { + const sendAt = logCtx.activeAttemptStartedAt; + const upstreamSendMs = sendAt !== undefined && Number.isFinite(sendAt) && Number.isFinite(start) && sendAt >= start + ? sendAt - start : undefined; + const redaction = logCtx.privacyRedactionMs; + return { + ...(upstreamSendMs !== undefined ? { upstreamSendMs } : {}), + ...(redaction !== undefined && Number.isFinite(redaction) && redaction >= 0 ? { privacyRedactionMs: redaction } : {}), + }; +} diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 9ae0758d5c9..35b1cdfa55a 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -4,7 +4,7 @@ import { normalizeRecordedClient, type UsageClient } from "../usage/client"; import { anthropicAccountTagField, stampApiKeyAccountLabel, usesApiKeyAccount } from "../providers/label"; import { finalizeProviderCacheAffinity } from "./request-log-cache-affinity"; import { aggregateAttemptUsage } from "./request-log-attempt-usage"; -import { accountRosterField, type AccountRosterEntryField } from "./request-log-route-live"; +import { accountRosterField, routeLiveTimingField, type AccountRosterEntryField, type RouteLiveTimingContext, type RouteLiveTimingEntryField } from "./request-log-route-live"; export { aggregateAttemptUsage } from "./request-log-attempt-usage"; import { KEY_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label"; @@ -126,7 +126,7 @@ export function cacheDiagnosticsObserving(): boolean { return cacheDiagnosticHooks()?.enabled() === true; } -export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyLogContext { +export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyLogContext, RouteLiveTimingContext { model: string; provider: string; client?: UsageClient; @@ -330,7 +330,7 @@ export function rebindCacheDiagnosticBody( cacheDiagnosticHooks()?.rebind(body, draft); } -export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField, AccountRosterEntryField { +export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField, AccountRosterEntryField, RouteLiveTimingEntryField { requestId: string; client?: UsageClient; /** The logical request this row belongs to (#4546); absent on rows written without a budget. */ @@ -1686,6 +1686,7 @@ function writeFinalRequestLog( ...(logCtx.terminalSource ? { terminalSource: logCtx.terminalSource } : {}), ...(logCtx.routeDecision ? { routeDecision: logCtx.routeDecision } : {}), ...accountRosterField(isCombo ? attempts?.at(-1) : logCtx), + ...(isCombo ? {} : routeLiveTimingField(logCtx, start)), ...(jevDecision ? { jevDecision } : {}), ...(claudeCompatibility ? { claudeCompatibility } : {}), ...(protocolTrace ? { protocolTrace } : {}), diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index c3c6b1b1b95..e99fa793a15 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1283,7 +1283,7 @@ "fixture-windows-runtime-preload.test.ts": "ci-workflows", "repo-hygiene.test.ts": "ci-workflows", "request-decompress.test.ts": "usage", "request-evidence.test.ts": "usage", "request-history-index.test.ts": "usage", "request-history-integrity.test.ts": "usage", - "request-log-attempt-identity.test.ts": "usage", "request-log-account-roster.test.ts": "usage", "request-log-conversation.test.ts": "usage", + "request-log-attempt-identity.test.ts": "usage", "request-log-account-roster.test.ts": "usage", "request-log-route-live-timing.test.ts": "usage", "request-log-conversation.test.ts": "usage", "request-log-estimate-cap.test.ts": "usage", "request-log-jev.test.ts": "usage", "request-log-nonstream.test.ts": "usage", "request-log-protocol-trace.test.ts": "usage", "request-log-served-model.test.ts": "usage", "request-log-model-filter.test.ts": "usage", "request-log-generation-window.test.ts": "usage", diff --git a/tests/usage/request-log-route-live-timing.test.ts b/tests/usage/request-log-route-live-timing.test.ts new file mode 100644 index 00000000000..4394d15c5f0 --- /dev/null +++ b/tests/usage/request-log-route-live-timing.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { addFinalRequestLog, clearRequestLogsForTests, type RequestLogEntry } from "../../src/server/request-log"; + +afterEach(() => clearRequestLogsForTests()); + +function finalRow(start: number, extra: Record): RequestLogEntry { + const rows: RequestLogEntry[] = []; + addFinalRequestLog("timing-row", start, { model: "gpt-5", provider: "openai", ...extra }, 200, undefined, row => rows.push(row)); + return rows[0]!; +} + +describe("live routing timing on the final request row", () => { + test("upstreamSendMs is the offset of the final attempt's start from the request start", () => { + const start = Date.now() - 500; + const row = finalRow(start, { activeAttemptStartedAt: start + 120 }); + expect(row.upstreamSendMs).toBe(120); + }); + + test("privacy redaction time passes through when a redactor measured it", () => { + const start = Date.now() - 50; + const row = finalRow(start, { activeAttemptStartedAt: start + 10, privacyRedactionMs: 3.5 }); + expect(row.privacyRedactionMs).toBe(3.5); + }); + + test("nothing is invented when the attempt start is unknown or before the request", () => { + const start = Date.now(); + expect(finalRow(start, {}).upstreamSendMs).toBeUndefined(); + expect(finalRow(start, { activeAttemptStartedAt: start - 5 }).upstreamSendMs).toBeUndefined(); + expect(finalRow(start, { privacyRedactionMs: -1 }).privacyRedactionMs).toBeUndefined(); + }); +}); From 60542011b4771ec14c56ed18dd89448d40fa7e90 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:32:18 -0500 Subject: [PATCH 03/12] feat(gui): live routing tab on the Models page Models gains a Live routing tab (#models/live) that polls /api/logs while visible. For the latest or a pinned request it shows client -> OpenCodex -> candidates, marking the account or target that answered, the ones that failed with their status and reason, and the ones skipped with the reason the route decision or the account pool recorded. An outcome sentence and a step list explain the route. The request list groups by request, session or key and shows account, model, effort, duration, time to first token, tokens, cache-hit rate, tok/s and estimated cost; unknown values show a dash, never zero. Combos and accounts keep their own pages and are linked. --- gui/.eslint/i18n-allowlist.ts | 3 + gui/src/app-routing.ts | 4 +- gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/route-live-copy.ts | 111 ++++++++++++++ gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/Models.tsx | 22 +++ gui/src/pages/logs-client-chip.tsx | 13 +- gui/src/pages/logs-client-label.ts | 21 +++ gui/src/pages/models-tab-strip.tsx | 1 + gui/src/pages/models-tab.ts | 5 +- gui/src/pages/route-live/FlowDiagram.tsx | 79 ++++++++++ gui/src/pages/route-live/ReasonText.tsx | 18 +++ gui/src/pages/route-live/RequestList.tsx | 161 +++++++++++++++++++ gui/src/pages/route-live/RouteLive.tsx | 116 ++++++++++++++ gui/src/pages/route-live/RouteSteps.tsx | 54 +++++++ gui/src/pages/route-live/flow-model.ts | 156 +++++++++++++++++++ gui/src/pages/route-live/request-groups.ts | 71 +++++++++ gui/src/pages/route-live/route-format.ts | 50 ++++++ gui/src/pages/route-live/route-live.css | 88 +++++++++++ gui/src/pages/route-live/route-reasons.ts | 59 +++++++ gui/src/pages/route-live/route-rows.ts | 170 +++++++++++++++++++++ gui/src/pages/route-live/slots.ts | 9 ++ gui/src/pages/route-live/use-route-live.ts | 58 +++++++ gui/tests/compatibility-lab.test.tsx | 4 +- gui/tests/models-workspace-panels.test.tsx | 12 +- gui/tests/route-live-model.test.ts | 92 +++++++++++ gui/tests/route-live-render.test.tsx | 77 ++++++++++ tests/gui/models-workspace-tabs.test.ts | 2 +- 37 files changed, 1453 insertions(+), 25 deletions(-) create mode 100644 gui/src/i18n/route-live-copy.ts create mode 100644 gui/src/pages/logs-client-label.ts create mode 100644 gui/src/pages/route-live/FlowDiagram.tsx create mode 100644 gui/src/pages/route-live/ReasonText.tsx create mode 100644 gui/src/pages/route-live/RequestList.tsx create mode 100644 gui/src/pages/route-live/RouteLive.tsx create mode 100644 gui/src/pages/route-live/RouteSteps.tsx create mode 100644 gui/src/pages/route-live/flow-model.ts create mode 100644 gui/src/pages/route-live/request-groups.ts create mode 100644 gui/src/pages/route-live/route-format.ts create mode 100644 gui/src/pages/route-live/route-live.css create mode 100644 gui/src/pages/route-live/route-reasons.ts create mode 100644 gui/src/pages/route-live/route-rows.ts create mode 100644 gui/src/pages/route-live/slots.ts create mode 100644 gui/src/pages/route-live/use-route-live.ts create mode 100644 gui/tests/route-live-model.test.ts create mode 100644 gui/tests/route-live-render.test.tsx diff --git a/gui/.eslint/i18n-allowlist.ts b/gui/.eslint/i18n-allowlist.ts index 805d7dcfbc2..f831e97983c 100644 --- a/gui/.eslint/i18n-allowlist.ts +++ b/gui/.eslint/i18n-allowlist.ts @@ -62,6 +62,9 @@ export function isTechnicalLiteral(value: string): boolean { // Internal Models session-cache suffix, never rendered as user-facing copy. if (trimmed === ":picker-order") return true; + // Opaque id tags of the Live routing view model (never rendered). + if (/^(session|key|admission|attempt|decision|roster):$/.test(trimmed)) return true; + // Absolute/relative URLs and localhost endpoints if (/^https?:\/\//i.test(trimmed)) return true; if (/^https?:\/\/[^\s]+$/i.test(trimmed)) return true; diff --git a/gui/src/app-routing.ts b/gui/src/app-routing.ts index 1a92cf20bfe..45f5909172b 100644 --- a/gui/src/app-routing.ts +++ b/gui/src/app-routing.ts @@ -92,11 +92,11 @@ export function canonicalHashPath(hash: string): string { export const DASHBOARD_TAB_HASHES = ["dashboard/providers", "dashboard/models"] as const; /** - * Models owns four tabs: the catalog, Combos, Routing, and Compatibility. The catalog + * Models owns five tabs: the catalog, Live routing, Combos, Routing, and Compatibility. The catalog * is the bare `#models`, so it has no suffix entry here - same convention Dashboard * uses for Overview and Logs uses for the log list. */ -export const MODELS_TAB_HASHES = ["models/combos", "models/routing", "models/compatibility"] as const; +export const MODELS_TAB_HASHES = ["models/live", "models/combos", "models/routing", "models/compatibility"] as const; /** Action deep link that opens the editable JEV Auto template in the Combos tab. */ export const JEV_AUTO_CREATE_HASH = "models/combos/jev-auto"; diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 234541ce8ca..0ab5d474324 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -136,6 +137,7 @@ export const de: Record = { ...desktopCompatibilityCopy("de"), ...shellV2Copy("de"), ...codexCliUpdateCopy("de"), + ...routeLiveCopy("de"), ...remoteLinkDiagnosticsCopy("de"), ...modelsV2Copy("de"), ...accountsV2Copy("de"), diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 76381be2404..77448fcfe62 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -137,6 +138,7 @@ export const en = { ...desktopCompatibilityCopy("en"), ...shellV2Copy("en"), ...codexCliUpdateCopy("en"), + ...routeLiveCopy("en"), ...remoteLinkDiagnosticsCopy("en"), ...modelsV2Copy("en"), ...accountsV2Copy("en"), diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index f0314b0c16e..1eb111f9c4c 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -135,6 +136,7 @@ export const fr: Record = { ...desktopCompatibilityCopy("fr"), ...shellV2Copy("fr"), ...codexCliUpdateCopy("fr"), + ...routeLiveCopy("fr"), ...remoteLinkDiagnosticsCopy("fr"), ...modelsV2Copy("fr"), ...accountsV2Copy("fr"), diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index b71b131dd49..3815a8a3c05 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -135,6 +136,7 @@ export const ja: Record = { ...desktopCompatibilityCopy("ja"), ...shellV2Copy("ja"), ...codexCliUpdateCopy("ja"), + ...routeLiveCopy("ja"), ...remoteLinkDiagnosticsCopy("ja"), ...modelsV2Copy("ja"), ...accountsV2Copy("ja"), diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 399a227c363..3edc9e09404 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -135,6 +136,7 @@ export const ko: Record = { ...desktopCompatibilityCopy("ko"), ...shellV2Copy("ko"), ...codexCliUpdateCopy("ko"), + ...routeLiveCopy("ko"), ...remoteLinkDiagnosticsCopy("ko"), ...modelsV2Copy("ko"), ...accountsV2Copy("ko"), diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 1b5c4960b76..1c6c03f8b6f 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -137,6 +138,7 @@ export const pt: Record = { ...desktopCompatibilityCopy("pt"), ...shellV2Copy("pt"), ...codexCliUpdateCopy("pt"), + ...routeLiveCopy("pt"), ...remoteLinkDiagnosticsCopy("pt"), ...modelsV2Copy("pt"), ...accountsV2Copy("pt"), diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts new file mode 100644 index 00000000000..a714dd3c37a --- /dev/null +++ b/gui/src/i18n/route-live-copy.ts @@ -0,0 +1,111 @@ +/* + * Copy for the Live routing tab (Models > Live routing). One row per key, columns in the order of + * `locales`, like codex-cli-update-copy.ts. Reason codes the registry in + * pages/route-live/route-reasons.ts does not name are shown raw, in . + */ +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; + +const rows = { + tab: ["Live routing","실시간 라우팅","Live-Routing","Routage en direct","实时路由","即時路由","Маршрутизация вживую","ライブルーティング","Canlı yönlendirme","Định tuyến trực tiếp","Roteamento ao vivo"], + subtitle: ["See which account answered each request and why the others were skipped. Updates every few seconds while this tab is open.","각 요청에 어느 계정이 답했는지, 다른 계정은 왜 건너뛰었는지 보여줘요. 이 탭이 열려 있는 동안 몇 초마다 갱신돼요.","Zeigt, welches Konto jede Anfrage beantwortet hat und warum die anderen übersprungen wurden. Aktualisiert alle paar Sekunden, solange dieser Tab offen ist.","Montre quel compte a répondu à chaque requête et pourquoi les autres ont été ignorés. Se met à jour toutes les quelques secondes tant que cet onglet est ouvert.","查看每个请求由哪个账号回答,其他账号为什么被跳过。这个标签页打开时每隔几秒自动刷新。","查看每個請求由哪個帳號回答,其他帳號為什麼被跳過。這個分頁開啟時每隔幾秒自動更新。","Показывает, какой аккаунт ответил на каждый запрос и почему остальные пропущены. Обновляется каждые несколько секунд, пока вкладка открыта.","各リクエストにどのアカウントが応答し、他がなぜスキップされたかを表示します。このタブを開いている間、数秒ごとに更新されます。","Her isteği hangi hesabın yanıtladığını ve diğerlerinin neden atlandığını gösterir. Bu sekme açıkken birkaç saniyede bir yenilenir.","Cho biết tài khoản nào đã trả lời từng yêu cầu và vì sao các tài khoản khác bị bỏ qua. Tự làm mới vài giây một lần khi tab này đang mở.","Mostra qual conta respondeu a cada requisição e por que as outras foram ignoradas. Atualiza a cada poucos segundos enquanto esta aba estiver aberta."], + loadFailed: ["Could not load recent requests.","최근 요청을 불러오지 못했어요.","Letzte Anfragen konnten nicht geladen werden.","Impossible de charger les requêtes récentes.","无法加载最近的请求。","無法載入最近的請求。","Не удалось загрузить последние запросы.","最近のリクエストを読み込めませんでした。","Son istekler yüklenemedi.","Không tải được các yêu cầu gần đây.","Não foi possível carregar as requisições recentes."], + empty: ["No requests yet. Send one through OpenCodex and its route shows up here.","아직 요청이 없어요. OpenCodex로 요청을 보내면 경로가 여기에 나타나요.","Noch keine Anfragen. Sende eine über OpenCodex, dann erscheint ihre Route hier.","Aucune requête pour l’instant. Envoyez-en une via OpenCodex et son parcours apparaîtra ici.","还没有请求。通过 OpenCodex 发一个请求,它的路由就会显示在这里。","還沒有請求。透過 OpenCodex 發一個請求,它的路由就會顯示在這裡。","Запросов пока нет. Отправьте запрос через OpenCodex, и его маршрут появится здесь.","まだリクエストがありません。OpenCodex 経由で送ると、ここに経路が表示されます。","Henüz istek yok. OpenCodex üzerinden bir istek gönderin, yolu burada görünür.","Chưa có yêu cầu nào. Gửi một yêu cầu qua OpenCodex và tuyến đường của nó sẽ hiện ở đây.","Ainda não há requisições. Envie uma pelo OpenCodex e o caminho dela aparece aqui."], + latestHead: ["How the latest request was routed","최근 요청은 이렇게 라우팅됐어요","So wurde die letzte Anfrage geroutet","Comment la dernière requête a été routée","最近一个请求是怎么路由的","最近一個請求是怎麼路由的","Как был маршрутизирован последний запрос","直近のリクエストの経路","Son istek nasıl yönlendirildi","Yêu cầu gần nhất được định tuyến thế nào","Como a última requisição foi roteada"], + pinnedHead: ["How the request from {time} was routed","{time} 요청은 이렇게 라우팅됐어요","So wurde die Anfrage von {time} geroutet","Comment la requête de {time} a été routée","{time} 这个请求是怎么路由的","{time} 這個請求是怎麼路由的","Как был маршрутизирован запрос от {time}","{time} のリクエストの経路","{time} tarihli istek nasıl yönlendirildi","Yêu cầu lúc {time} được định tuyến thế nào","Como a requisição de {time} foi roteada"], + backToLatest: ["Back to latest","최근 요청으로","Zurück zur neuesten","Revenir à la dernière","回到最新","回到最新","К последнему","最新に戻る","En yeniye dön","Về yêu cầu mới nhất","Voltar à mais recente"], + outcomeOk: ["{who} · {model} answered in {duration}","{who} · {model} 응답 완료, {duration} 걸렸어요","{who} · {model} hat geantwortet, {duration}","{who} · {model} a répondu en {duration}","{who} · {model} 已回答,用时 {duration}","{who} · {model} 已回答,用時 {duration}","{who} · {model} ответил за {duration}","{who} · {model} が応答しました({duration})","{who} · {model} {duration} içinde yanıtladı","{who} · {model} đã trả lời trong {duration}","{who} · {model} respondeu em {duration}"], + outcomeMoved: ["Tried {count} times; {who} answered last","{count}번 시도했고 마지막에 {who}이(가) 답했어요","{count} Versuche; zuletzt hat {who} geantwortet","{count} essais ; {who} a répondu en dernier","试了 {count} 次,最后由 {who} 回答","試了 {count} 次,最後由 {who} 回答","{count} попыток; в итоге ответил {who}","{count} 回試行し、最後に {who} が応答しました","{count} deneme yapıldı; son olarak {who} yanıtladı","Đã thử {count} lần; {who} trả lời cuối cùng","{count} tentativas; {who} respondeu por último"], + outcomeFailed: ["{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}"], + outcomeFailedTries: ["{status} · {reason} (after {count} tries)","{status} · {reason} ({count}번 시도 후)","{status} · {reason} (nach {count} Versuchen)","{status} · {reason} (après {count} essais)","{status} · {reason}(试了 {count} 次)","{status} · {reason}(試了 {count} 次)","{status} · {reason} (после {count} попыток)","{status} · {reason}({count} 回試行後)","{status} · {reason} ({count} denemeden sonra)","{status} · {reason} (sau {count} lần thử)","{status} · {reason} (após {count} tentativas)"], + outcomeLocal: ["OpenCodex answered this one itself. Nothing was sent to a provider.","OpenCodex가 직접 처리했어요. 제공자로는 아무것도 보내지 않았어요.","OpenCodex hat diese Anfrage selbst beantwortet. Es wurde nichts an einen Anbieter gesendet.","OpenCodex a répondu lui-même. Rien n’a été envoyé à un fournisseur.","这个请求由 OpenCodex 自己处理,没有发给任何服务商。","這個請求由 OpenCodex 自己處理,沒有發給任何服務商。","OpenCodex ответил сам. Провайдеру ничего не отправлялось.","OpenCodex 自身が処理しました。プロバイダーには何も送っていません。","Bu isteği OpenCodex kendisi yanıtladı. Sağlayıcıya hiçbir şey gönderilmedi.","OpenCodex tự xử lý yêu cầu này. Không có gì được gửi tới nhà cung cấp.","O próprio OpenCodex respondeu. Nada foi enviado a um provedor."], + flowLabel: ["Route of the selected request: client, OpenCodex, then the candidates","선택한 요청의 경로: 클라이언트, OpenCodex, 후보","Route der gewählten Anfrage: Client, OpenCodex, dann die Kandidaten","Parcours de la requête : client, OpenCodex, puis les candidats","所选请求的路由:客户端、OpenCodex、候选项","所選請求的路由:用戶端、OpenCodex、候選項","Маршрут выбранного запроса: клиент, OpenCodex, затем кандидаты","選択したリクエストの経路:クライアント、OpenCodex、候補","Seçili isteğin yolu: istemci, OpenCodex, ardından adaylar","Tuyến của yêu cầu đã chọn: máy khách, OpenCodex, rồi các ứng viên","Caminho da requisição: cliente, OpenCodex e depois os candidatos"], + noCandidates: ["No candidates were recorded for this request.","이 요청에는 기록된 후보가 없어요.","Für diese Anfrage wurden keine Kandidaten erfasst.","Aucun candidat n’a été enregistré pour cette requête.","这个请求没有记录到候选项。","這個請求沒有記錄到候選項。","Для этого запроса кандидаты не записаны.","このリクエストには候補が記録されていません。","Bu istek için aday kaydedilmedi.","Yêu cầu này không ghi lại ứng viên nào.","Nenhum candidato foi registrado para esta requisição."], + statusAnswered: ["Answered","응답함","Geantwortet","A répondu","已回答","已回答","Ответил","応答","Yanıtladı","Đã trả lời","Respondeu"], + statusFailed: ["Failed","실패","Fehlgeschlagen","Échec","失败","失敗","Ошибка","失敗","Başarısız","Thất bại","Falhou"], + statusSkipped: ["Skipped","건너뜀","Übersprungen","Ignoré","已跳过","已跳過","Пропущен","スキップ","Atlandı","Bỏ qua","Ignorado"], + statusIdle: ["Not needed","필요 없었음","Nicht nötig","Pas nécessaire","没用上","沒用上","Не понадобился","不要","Gerekmedi","Không cần","Não precisou"], + stepAsked: ["{client} asked for {model}","{client}이(가) {model}을(를) 요청했어요","{client} hat {model} angefragt","{client} a demandé {model}","{client} 请求了 {model}","{client} 請求了 {model}","{client} запросил {model}","{client} が {model} を要求しました","{client} {model} istedi","{client} yêu cầu {model}","{client} pediu {model}"], + stepAskedCombo: ["{client} asked for {model}, a routing group (combo)","{client}이(가) 라우팅 그룹(콤보) {model}을(를) 요청했어요","{client} hat {model} angefragt, eine Routing-Gruppe (Combo)","{client} a demandé {model}, un groupe de routage (combo)","{client} 请求了 {model},这是一个路由组(组合)","{client} 請求了 {model},這是一個路由組(組合)","{client} запросил {model} — группу маршрутизации (комбо)","{client} がルーティンググループ(コンボ){model} を要求しました","{client} bir yönlendirme grubu (kombo) olan {model} istedi","{client} yêu cầu {model}, một nhóm định tuyến (combo)","{client} pediu {model}, um grupo de roteamento (combo)"], + stepWhy: ["Why this one: {reason}","이것을 고른 이유: {reason}","Darum diese: {reason}","Pourquoi celui-ci : {reason}","为什么选它:{reason}","為什麼選它:{reason}","Почему этот: {reason}","選ばれた理由:{reason}","Neden bu: {reason}","Vì sao chọn nó: {reason}","Por que este: {reason}"], + stepSkipped: ["{who} was skipped: {reason}","{who}은(는) 건너뛰었어요: {reason}","{who} wurde übersprungen: {reason}","{who} a été ignoré : {reason}","{who} 被跳过:{reason}","{who} 被跳過:{reason}","{who} пропущен: {reason}","{who} はスキップされました:{reason}","{who} atlandı: {reason}","{who} bị bỏ qua: {reason}","{who} foi ignorado: {reason}"], + stepTryOk: ["{who} answered in {duration}","{who}이(가) {duration} 만에 답했어요","{who} hat in {duration} geantwortet","{who} a répondu en {duration}","{who} 回答了,用时 {duration}","{who} 回答了,用時 {duration}","{who} ответил за {duration}","{who} が {duration} で応答しました","{who} {duration} içinde yanıtladı","{who} đã trả lời trong {duration}","{who} respondeu em {duration}"], + stepTryFailed: ["{who} returned {result}","{who}이(가) {result}을(를) 반환했어요","{who} lieferte {result}","{who} a renvoyé {result}","{who} 返回 {result}","{who} 回傳 {result}","{who} вернул {result}","{who} が {result} を返しました","{who} {result} döndürdü","{who} trả về {result}","{who} retornou {result}"], + stepTryFailedNext: ["{who} returned {result}, so it moved on to the next","{who}이(가) {result}을(를) 반환해서 다음으로 넘어갔어요","{who} lieferte {result}, daher ging es zum nächsten","{who} a renvoyé {result}, passage au suivant","{who} 返回 {result},换下一个","{who} 回傳 {result},換下一個","{who} вернул {result}, перешли к следующему","{who} が {result} を返したため、次へ進みました","{who} {result} döndürdü, sonrakine geçildi","{who} trả về {result}, chuyển sang cái tiếp theo","{who} retornou {result}, então passou ao próximo"], + stepNone: ["No request was sent.","요청을 보내지 않았어요.","Es wurde keine Anfrage gesendet.","Aucune requête n’a été envoyée.","没有发出请求。","沒有發出請求。","Запрос не отправлялся.","リクエストは送信されませんでした。","Hiçbir istek gönderilmedi.","Không có yêu cầu nào được gửi đi.","Nenhuma requisição foi enviada."], + linkCombos: ["Routing groups are managed in Models › Combos","라우팅 그룹은 모델 › 콤보에서 관리해요","Routing-Gruppen verwaltest du unter Modelle › Combos","Les groupes de routage se gèrent dans Modèles › Combos","路由组在 模型 › 组合 里管理","路由組在 模型 › 組合 裡管理","Группы маршрутизации настраиваются в Модели › Комбо","ルーティンググループは モデル › コンボ で管理します","Yönlendirme grupları Modeller › Kombolar altında yönetilir","Nhóm định tuyến được quản lý ở Mô hình › Combo","Grupos de roteamento são gerenciados em Modelos › Combos"], + poolSummary: ["Pool {provider}: {total} accounts · {available} available · {cooldown} cooling · {paused} paused · {reauth} need sign-in","풀 {provider}: 계정 {total}개 · 사용 가능 {available} · 대기 중 {cooldown} · 일시중지 {paused} · 재로그인 필요 {reauth}","Pool {provider}: {total} Konten · {available} verfügbar · {cooldown} Abkühlung · {paused} pausiert · {reauth} brauchen Anmeldung","Pool {provider} : {total} comptes · {available} disponibles · {cooldown} en pause temporaire · {paused} suspendus · {reauth} à reconnecter","号池 {provider}:{total} 个账号 · 可用 {available} · 冷却 {cooldown} · 暂停 {paused} · 需重新登录 {reauth}","號池 {provider}:{total} 個帳號 · 可用 {available} · 冷卻 {cooldown} · 暫停 {paused} · 需重新登入 {reauth}","Пул {provider}: {total} аккаунтов · доступно {available} · на паузе после ошибок {cooldown} · приостановлено {paused} · нужен вход {reauth}","プール {provider}:{total} アカウント · 利用可 {available} · クールダウン {cooldown} · 一時停止 {paused} · 要再ログイン {reauth}","Havuz {provider}: {total} hesap · {available} uygun · {cooldown} bekleme · {paused} duraklatıldı · {reauth} yeniden giriş gerek","Nhóm {provider}: {total} tài khoản · {available} sẵn sàng · {cooldown} đang nghỉ · {paused} tạm dừng · {reauth} cần đăng nhập lại","Pool {provider}: {total} contas · {available} disponíveis · {cooldown} em espera · {paused} pausadas · {reauth} precisam entrar de novo"], + linkAccounts: ["Open accounts","계정 열기","Konten öffnen","Ouvrir les comptes","打开账号页","開啟帳號頁","Открыть аккаунты","アカウントを開く","Hesapları aç","Mở tài khoản","Abrir contas"], + modeLabel: ["Group requests","요청 묶기","Anfragen gruppieren","Grouper les requêtes","分组方式","分組方式","Группировка","グループ化","Gruplama","Nhóm yêu cầu","Agrupar requisições"], + modeRequest: ["By request","요청별","Nach Anfrage","Par requête","按请求","按請求","По запросам","リクエスト別","İsteğe göre","Theo yêu cầu","Por requisição"], + modeSession: ["By session","세션별","Nach Sitzung","Par session","按会话","按工作階段","По сессиям","セッション別","Oturuma göre","Theo phiên","Por sessão"], + modeKey: ["By key","키별","Nach Schlüssel","Par clé","按密钥","按金鑰","По ключам","キー別","Anahtara göre","Theo khóa","Por chave"], + groupNoSession: ["No session ID","세션 ID 없음","Keine Sitzungs-ID","Sans ID de session","无会话 ID","無工作階段 ID","Без ID сессии","セッション ID なし","Oturum kimliği yok","Không có ID phiên","Sem ID de sessão"], + groupSession: ["Session {id}","세션 {id}","Sitzung {id}","Session {id}","会话 {id}","工作階段 {id}","Сессия {id}","セッション {id}","Oturum {id}","Phiên {id}","Sessão {id}"], + groupKey: ["Key {id}","키 {id}","Schlüssel {id}","Clé {id}","密钥 {id}","金鑰 {id}","Ключ {id}","キー {id}","Anahtar {id}","Khóa {id}","Chave {id}"], + admLoopback: ["This computer (loopback)","이 컴퓨터 (loopback)","Dieser Computer (Loopback)","Cet ordinateur (loopback)","本机 (loopback)","本機 (loopback)","Этот компьютер (loopback)","このコンピューター (loopback)","Bu bilgisayar (loopback)","Máy này (loopback)","Este computador (loopback)"], + admEnvironment: ["Environment key","환경 변수 키","Umgebungsschlüssel","Clé d’environnement","环境变量密钥","環境變數金鑰","Ключ из окружения","環境変数のキー","Ortam anahtarı","Khóa môi trường","Chave de ambiente"], + admUnknown: ["Unknown key","알 수 없는 키","Unbekannter Schlüssel","Clé inconnue","未知密钥","未知金鑰","Неизвестный ключ","不明なキー","Bilinmeyen anahtar","Khóa không rõ","Chave desconhecida"], + groupCount: ["{count} requests","요청 {count}개","{count} Anfragen","{count} requêtes","{count} 个请求","{count} 個請求","Запросов: {count}","{count} 件","{count} istek","{count} yêu cầu","{count} requisições"], + groupTokens: ["{value} tokens","토큰 {value}","{value} Tokens","{value} jetons","{value} tokens","{value} tokens","{value} токенов","{value} トークン","{value} token","{value} token","{value} tokens"], + groupCache: ["{value} cache hit","캐시 적중 {value}","{value} Cache-Treffer","{value} de cache","缓存命中 {value}","快取命中 {value}","кэш {value}","キャッシュ {value}","Önbellek {value}","Cache {value}","Cache {value}"], + listLabel: ["Recent requests","최근 요청","Letzte Anfragen","Requêtes récentes","最近的请求","最近的請求","Недавние запросы","最近のリクエスト","Son istekler","Yêu cầu gần đây","Requisições recentes"], + rowHint: ["Select a request to pin it above. Esc goes back to the latest.","요청을 선택하면 위에 고정돼요. Esc를 누르면 최근 요청으로 돌아가요.","Anfrage wählen, um sie oben festzuhalten. Esc springt zur neuesten zurück.","Sélectionnez une requête pour l’épingler en haut. Échap revient à la dernière.","点一个请求就会固定显示在上方。按 Esc 回到最新。","點一個請求就會固定顯示在上方。按 Esc 回到最新。","Выберите запрос, чтобы закрепить его вверху. Esc возвращает к последнему.","リクエストを選ぶと上に固定されます。Esc で最新に戻ります。","Bir isteği seçerek yukarıya sabitleyin. Esc en yeniye döner.","Chọn một yêu cầu để ghim lên trên. Nhấn Esc để về yêu cầu mới nhất.","Selecione uma requisição para fixá-la acima. Esc volta à mais recente."], + colTime: ["Time","시간","Zeit","Heure","时间","時間","Время","時刻","Zaman","Thời gian","Hora"], + colAccount: ["Account","계정","Konto","Compte","账号","帳號","Аккаунт","アカウント","Hesap","Tài khoản","Conta"], + colEffort: ["Effort","추론 강도","Aufwand","Effort","思考强度","思考強度","Усилие","推論強度","Efor","Mức suy luận","Esforço"], + colDuration: ["Duration","소요 시간","Dauer","Durée","用时","用時","Время","所要時間","Süre","Thời lượng","Duração"], + colTtft: ["First token","첫 토큰","Erstes Token","Premier jeton","首字","首字","Первый токен","最初のトークン","İlk token","Token đầu","Primeiro token"], + colCache: ["Cache hit","캐시 적중","Cache-Treffer","Cache","缓存命中","快取命中","Кэш","キャッシュ","Önbellek","Cache","Cache"], + whyComboPick: ["it was the next target in the group","그룹의 다음 대상이었어요","es war das nächste Ziel der Gruppe","c’était la cible suivante du groupe","它是路由组里轮到的下一个目标","它是路由組裡輪到的下一個目標","это была следующая цель в группе","グループの次のターゲットだったため","grubun sıradaki hedefiydi","đó là mục tiêu kế tiếp trong nhóm","era o próximo destino do grupo"], + whyPolicySelected: ["it scored best under the routing policy","라우팅 정책에서 점수가 가장 높았어요","es erzielte die beste Bewertung der Routing-Richtlinie","il a obtenu le meilleur score selon la politique de routage","它在路由策略里得分最高","它在路由策略裡得分最高","он получил лучшую оценку по политике маршрутизации","ルーティングポリシーで最高スコアだったため","yönlendirme politikasında en yüksek puanı aldı","nó đạt điểm cao nhất theo chính sách định tuyến","teve a melhor pontuação na política de roteamento"], + rCooldown: ["cooling down after errors","오류 후 쉬는 중","kühlt nach Fehlern ab","en pause après des erreurs","出错后冷却中","出錯後冷卻中","на паузе после ошибок","エラー後のクールダウン中","hatalardan sonra bekliyor","đang nghỉ sau lỗi","em espera após erros"], + rDisabled: ["turned off","꺼져 있음","ausgeschaltet","désactivé","已关闭","已關閉","отключён","オフ","kapalı","đã tắt","desativado"], + rNotSelected: ["another target came first","다른 대상이 먼저 선택됨","ein anderes Ziel kam zuerst","une autre cible est passée avant","别的目标排在前面","別的目標排在前面","раньше выбрали другую цель","他のターゲットが先に選ばれた","başka bir hedef önce seçildi","mục tiêu khác được chọn trước","outro destino veio primeiro"], + rPaused: ["paused by you","사용자가 일시중지함","von dir pausiert","mis en pause par vous","已被你暂停","已被你暫停","приостановлен вами","一時停止中","duraklatıldı","bạn đã tạm dừng","pausada por você"], + rNeedsReauth: ["needs to sign in again","다시 로그인해야 함","muss sich neu anmelden","doit se reconnecter","需要重新登录","需要重新登入","нужно войти заново","再ログインが必要","yeniden giriş yapmalı","cần đăng nhập lại","precisa entrar de novo"], + rQuotaExhausted: ["quota used up","사용량 한도 소진","Kontingent aufgebraucht","quota épuisé","额度用尽","額度用盡","квота исчерпана","クォータ切れ","kota doldu","hết hạn mức","cota esgotada"], + rModelUnlisted: ["its plan does not include this model","요금제에 이 모델이 없음","ihr Tarif enthält dieses Modell nicht","son offre n’inclut pas ce modèle","它的套餐不包含这个模型","它的方案不包含這個模型","в его тарифе нет этой модели","プランにこのモデルが含まれない","planı bu modeli içermiyor","gói của nó không có mô hình này","o plano dele não inclui este modelo"], + fRate: ["rate limited","요청 한도 초과","ratenbegrenzt","limité en débit","限流","限流","лимит запросов","レート制限","hız sınırı","bị giới hạn tốc độ","limite de taxa"], + fQuota: ["out of quota or credit","한도 또는 크레딧 소진","Kontingent oder Guthaben aufgebraucht","quota ou crédit épuisé","额度或余额用尽","額度或餘額用盡","квота или баланс исчерпаны","クォータまたは残高切れ","kota veya kredi bitti","hết hạn mức hoặc số dư","sem cota ou crédito"], + fAuth: ["needs to sign in again","다시 로그인 필요","Neuanmeldung nötig","reconnexion nécessaire","需要重新登录","需要重新登入","нужен повторный вход","再ログインが必要","yeniden giriş gerekli","cần đăng nhập lại","precisa entrar de novo"], + fContext: ["over the model's context window","모델 컨텍스트 초과","über dem Kontextfenster des Modells","dépasse le contexte du modèle","超出该模型上下文","超出該模型上下文","превышено контекстное окно","モデルのコンテキスト超過","modelin bağlam penceresini aştı","vượt cửa sổ ngữ cảnh","acima do contexto do modelo"], + fServer: ["provider error","제공자 오류","Anbieterfehler","erreur du fournisseur","服务商出错","服務商出錯","ошибка провайдера","プロバイダーのエラー","sağlayıcı hatası","lỗi nhà cung cấp","erro do provedor"], + fOverloaded: ["provider overloaded","제공자 과부하","Anbieter überlastet","fournisseur surchargé","服务商繁忙","服務商繁忙","провайдер перегружен","プロバイダーが混雑","sağlayıcı aşırı yüklü","nhà cung cấp quá tải","provedor sobrecarregado"], + fCancelled: ["cancelled","취소됨","abgebrochen","annulé","已取消","已取消","отменено","キャンセル","iptal edildi","đã hủy","cancelado"], + colClient: ["Client","클라이언트","Client","Client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente"], + colModel: ["Model","모델","Modell","Modèle","模型","模型","Модель","モデル","Model","Mô hình","Modelo"], + colTokens: ["Tokens","토큰","Tokens","Tokens","Tokens","Tokens","Токены","トークン","Token","Token","Tokens"], + colRate: ["Speed","속도","Tempo","Vitesse","速度","速度","Скорость","速度","Hız","Tốc độ","Velocidade"], + colCost: ["Cost","비용","Kosten","Coût","费用","費用","Стоимость","コスト","Maliyet","Chi phí","Custo"], + colStatus: ["Status","상태","Status","Statut","状态","狀態","Статус","状態","Durum","Trạng thái","Status"], + admConfigured: ["Configured API key","설정된 API 키","Konfigurierter API-Schlüssel","Clé API configurée","已配置的密钥","已設定的金鑰","Настроенный ключ API","設定済みの API キー","Yapılandırılmış API anahtarı","Khóa API đã cấu hình","Chave de API configurada"], + whyNoEligible: ["no target passed the checks, so the first one was used","검사를 통과한 대상이 없어 첫 번째를 썼어요","kein Ziel hat die Prüfungen bestanden, daher wurde das erste genommen","aucune cible n'a passé les contrôles, la première a donc été utilisée","没有目标通过检查,只好用第一个","沒有目標通過檢查,只好用第一個","ни одна цель не прошла проверки, поэтому взята первая","条件を満たす対象がなかったため、最初のものを使いました","hiçbir hedef kontrolleri geçemedi, bu yüzden ilki kullanıldı","không đích nào qua được kiểm tra nên dùng đích đầu tiên","nenhum destino passou nas verificações, então o primeiro foi usado"], + whyBlockedRedirect: ["the model you asked for is blocked, so it was redirected","요청한 모델이 차단되어 다른 곳으로 돌렸어요","das angefragte Modell ist gesperrt und wurde umgeleitet","le modèle demandé est bloqué, la requête a donc été redirigée","你请求的模型被屏蔽了,已改道","你請求的模型被封鎖了,已改道","запрошенная модель заблокирована, запрос перенаправлен","指定のモデルはブロックされているため、別の対象に振り替えました","istenen model engellendi, bu yüzden yönlendirildi","mô hình bạn yêu cầu bị chặn nên đã chuyển hướng","o modelo pedido está bloqueado, então foi redirecionado"], + whyComboToolLoopPin: ["this conversation is in the middle of a tool-call loop, so it stayed on the same target","이 대화는 도구 호출을 이어가는 중이라 같은 대상을 유지했어요","dieses Gespräch steckt mitten in einer Tool-Schleife und blieb beim selben Ziel","cette conversation est en pleine boucle d'outils et est restée sur la même cible","这个对话正在连续调用工具,所以沿用上一次的目标","這個對話正在連續呼叫工具,所以沿用上一次的目標","разговор в разгаре цикла вызовов инструментов, поэтому остался на той же цели","このスレッドはツール呼び出しの途中のため、同じ対象のままにしました","bu konuşma bir araç çağrısı döngüsünün ortasında, bu yüzden aynı hedefte kaldı","cuộc trò chuyện đang trong vòng gọi công cụ nên giữ nguyên đích cũ","esta conversa está no meio de um ciclo de ferramentas, então ficou no mesmo destino"], + whyJevSessionPin: ["this session stays on the target it started with","이 세션은 처음 고른 대상을 계속 써요","diese Sitzung bleibt bei dem Ziel, mit dem sie begonnen hat","cette session reste sur la cible choisie au départ","这个会话固定使用最初选中的目标","這個工作階段固定使用最初選中的目標","эта сессия остаётся на цели, выбранной вначале","このセッションは最初に選ばれた対象を使い続けます","bu oturum başladığı hedefte kalıyor","phiên này giữ nguyên đích đã chọn ban đầu","esta sessão continua no destino com que começou"], + whyExplicitProvider: ["the model name named this provider","모델 이름에 이 제공자가 적혀 있었어요","der Modellname nannte diesen Anbieter","le nom du modèle désignait ce fournisseur","模型名里写明了这个服务商","模型名稱裡寫明了這個服務商","в названии модели указан этот провайдер","モデル名でこのプロバイダーが指定されていました","model adı bu sağlayıcıyı belirtiyordu","tên mô hình chỉ rõ nhà cung cấp này","o nome do modelo indicava este provedor"], + whyDefaultProvider: ["no provider was named, so the default one was used","제공자가 지정되지 않아 기본 제공자를 썼어요","kein Anbieter genannt, daher wurde der Standard genommen","aucun fournisseur n'était indiqué, le fournisseur par défaut a donc servi","没指定服务商,用了默认的","沒指定服務商,用了預設的","провайдер не указан, использован провайдер по умолчанию","プロバイダーの指定がなかったため、既定のものを使いました","sağlayıcı belirtilmedi, varsayılan kullanıldı","không chỉ định nhà cung cấp nên dùng mặc định","nenhum provedor foi indicado, então foi usado o padrão"], + rUnconfigured: ["not set up yet","아직 설정되지 않음","noch nicht eingerichtet","pas encore configuré","还没配置","還沒設定","ещё не настроено","まだ設定されていません","henüz kurulmadı","chưa được thiết lập","ainda não configurado"], + rAlreadyAttempted: ["already tried for this request","이 요청에서 이미 시도함","für diese Anfrage schon versucht","déjà essayé pour cette requête","这个请求里已经试过了","這個請求裡已經試過了","уже пробовали для этого запроса","このリクエストでは試行済み","bu istek için zaten denendi","đã thử cho yêu cầu này","já tentado nesta requisição"], + rCapability: ["it cannot do something this request needs, such as tools or images","이 요청에 필요한 기능(도구, 이미지 등)을 지원하지 않음","es kann etwas nicht, das diese Anfrage braucht, etwa Tools oder Bilder","il ne gère pas ce dont la requête a besoin, comme les outils ou les images","它处理不了这个请求需要的功能,比如工具或图片","它處理不了這個請求需要的功能,例如工具或圖片","не поддерживает то, что нужно запросу, например инструменты или изображения","このリクエストに必要な機能(ツールや画像など)に対応していません","bu isteğin ihtiyaç duyduğu bir şeyi (araçlar, görseller) desteklemiyor","không hỗ trợ thứ yêu cầu này cần, như công cụ hoặc hình ảnh","não oferece algo de que a requisição precisa, como ferramentas ou imagens"], + rCostLimit: ["over the cost limit","비용 한도를 넘음","über dem Kostenlimit","au-dessus de la limite de coût","超出费用上限","超出費用上限","превышен лимит стоимости","コスト上限を超過","maliyet sınırını aştı","vượt giới hạn chi phí","acima do limite de custo"], + rRouteUnavailable: ["no route to it right now","지금은 연결할 수 없음","derzeit nicht erreichbar","pas de route vers elle pour l'instant","暂时走不通","暫時走不通","сейчас недоступно","現在は経路がありません","şu an ulaşılamıyor","hiện chưa có đường đến","sem rota para ele no momento"], + fPermission: ["access denied","접근 거부","Zugriff verweigert","accès refusé","没有权限","沒有權限","доступ запрещён","アクセス拒否","erişim reddedildi","bị từ chối truy cập","acesso negado"], + fModelMissing: ["model not found","모델을 찾을 수 없음","Modell nicht gefunden","modèle introuvable","找不到该模型","找不到該模型","модель не найдена","モデルが見つかりません","model bulunamadı","không tìm thấy mô hình","modelo não encontrado"], + fTimeout: ["timed out","시간 초과","Zeitüberschreitung","délai dépassé","超时","逾時","время ожидания истекло","タイムアウト","zaman aşımı","hết thời gian","tempo esgotado"], + detailFailed: ["{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}","{status} · {reason}"], + rowTries: ["{count} tries","{count}회 시도","{count} Versuche","{count} essais","试了 {count} 次","試了 {count} 次","попыток: {count}","{count} 回試行","{count} deneme","{count} lần thử","{count} tentativas"], + poolTruncated: ["Only the first 16 accounts are shown.","앞의 16개 계정만 보여줘요.","Nur die ersten 16 Konten werden angezeigt.","Seuls les 16 premiers comptes sont affichés.","只显示前 16 个账号。","只顯示前 16 個帳號。","Показаны только первые 16 аккаунтов.","最初の 16 アカウントのみ表示しています。","Yalnızca ilk 16 hesap gösteriliyor.","Chỉ hiển thị 16 tài khoản đầu tiên.","Apenas as primeiras 16 contas são exibidas."], + loading: ["Loading…","불러오는 중…","Wird geladen…","Chargement…","加载中…","載入中…","Загрузка…","読み込み中…","Yükleniyor…","Đang tải…","Carregando…"], +} satisfies Record; + +export type RouteLiveCopyKey = `routeLive.${keyof typeof rows}`; + +export function routeLiveCopy(locale: Locale): Record { + const column = locales.indexOf(locale); + return Object.fromEntries( + Object.entries(rows).map(([key, row]) => [`routeLive.${key}`, row[column]!]), + ) as Record; +} diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 2771adadf00..375a8a569eb 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -135,6 +136,7 @@ export const ru: Record = { ...desktopCompatibilityCopy("ru"), ...shellV2Copy("ru"), ...codexCliUpdateCopy("ru"), + ...routeLiveCopy("ru"), ...remoteLinkDiagnosticsCopy("ru"), ...modelsV2Copy("ru"), ...accountsV2Copy("ru"), diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index c27997fc8b4..0214315e3d9 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -136,6 +137,7 @@ export const tr: Record = { ...desktopCompatibilityCopy("tr"), ...shellV2Copy("tr"), ...codexCliUpdateCopy("tr"), + ...routeLiveCopy("tr"), ...remoteLinkDiagnosticsCopy("tr"), ...modelsV2Copy("tr"), ...accountsV2Copy("tr"), diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 930028388dc..40d056ce1c4 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -137,6 +138,7 @@ export const vi: Record = { ...desktopCompatibilityCopy("vi"), ...shellV2Copy("vi"), ...codexCliUpdateCopy("vi"), + ...routeLiveCopy("vi"), ...remoteLinkDiagnosticsCopy("vi"), ...modelsV2Copy("vi"), ...accountsV2Copy("vi"), diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 33da090ccc0..1d72281d2d4 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -133,6 +134,7 @@ export const zhTW: Record = { ...desktopCompatibilityCopy("zh-TW"), ...shellV2Copy("zh-TW"), ...codexCliUpdateCopy("zh-TW"), + ...routeLiveCopy("zh-TW"), ...remoteLinkDiagnosticsCopy("zh-TW"), ...modelsV2Copy("zh-TW"), ...accountsV2Copy("zh-TW"), diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index fe8f2d4c4d9..9772a2defcc 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -1,6 +1,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; import { shellV2Copy } from "./shell-v2-copy"; import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -135,6 +136,7 @@ export const zh: Record = { ...desktopCompatibilityCopy("zh"), ...shellV2Copy("zh"), ...codexCliUpdateCopy("zh"), + ...routeLiveCopy("zh"), ...remoteLinkDiagnosticsCopy("zh"), ...modelsV2Copy("zh"), ...accountsV2Copy("zh"), diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index f7e093760e9..0f49057cfd3 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -32,6 +32,7 @@ import { DataSurfaceSkeleton } from "../components/data-surface"; import ErrorBoundary from "../components/ErrorBoundary"; import Combos from "./Combos"; import RoutingProfiles from "./RoutingProfiles"; +import RouteLive from "./route-live/RouteLive"; import CompatibilityMatrix from "./CompatibilityMatrix"; import { ModelsTabStrip } from "./models-tab-strip"; import { ProviderFastRow } from "./models-fast-row"; @@ -115,6 +116,7 @@ type CachedModelsPage = { /** One plain lead line per tab; a longer description (if any) opens from the "?" beside it. */ const SUBTITLE_TKEY: Record = { catalog: ["modelsV2.ledeCatalog", "models.subtitle"], + live: ["routeLive.subtitle"], combos: ["modelsV2.ledeCombos", "models.subtitle.combos"], routing: ["models.subtitle.routing"], compatibility: ["models.subtitle.compatibility"], @@ -2678,6 +2680,26 @@ export default function Models({ apiBase, restartEpoch = 0, connected = false, c )} + +
; const CLIENT_ICONS: Record = { codex_cli: "openai.svg", codex_desktop: "openai.svg", codex_ide: "openai.svg", diff --git a/gui/src/pages/logs-client-label.ts b/gui/src/pages/logs-client-label.ts new file mode 100644 index 00000000000..ce0760260d7 --- /dev/null +++ b/gui/src/pages/logs-client-label.ts @@ -0,0 +1,21 @@ +import { normalizeRecordedClient, type UsageClient } from "../../../src/usage/client"; +import type { TFn } from "../i18n/shared"; + +export const CLIENT_LABELS = { + codex_cli: "Codex", + codex_desktop: "Codex", + codex_ide: "Codex", + claude_code: "Claude Code", + claude_desktop: "Claude Desktop", + grok: "Grok", + opencode: "OpenCode", + aside: "Aside", + other: "logsV2.clientOther", + unknown: "logsV2.clientUnknown", +} as const satisfies Record; + +/** The plain client name (Codex, Claude Code, ...), for sentences that name the client. */ +export function clientLabel(client: unknown, t: TFn): string { + const classified = normalizeRecordedClient(client) ?? "unknown"; + return classified === "other" || classified === "unknown" ? t(CLIENT_LABELS[classified]) : CLIENT_LABELS[classified]; +} diff --git a/gui/src/pages/models-tab-strip.tsx b/gui/src/pages/models-tab-strip.tsx index 05bd374aece..3bc7410dfb1 100644 --- a/gui/src/pages/models-tab-strip.tsx +++ b/gui/src/pages/models-tab-strip.tsx @@ -18,6 +18,7 @@ import { const TAB_LABEL: Record = { catalog: "models.tab.catalog", + live: "routeLive.tab", combos: "models.tab.combos", routing: "models.tab.routing", compatibility: "models.tab.compatibility", diff --git a/gui/src/pages/models-tab.ts b/gui/src/pages/models-tab.ts index 4afe3f87d26..e3b8d867291 100644 --- a/gui/src/pages/models-tab.ts +++ b/gui/src/pages/models-tab.ts @@ -14,9 +14,9 @@ import { JEV_AUTO_CREATE_HASH } from "../app-routing"; * tab shows the plain model list, so a distinct id keeps "the page" and "the tab" from * ever having to be disambiguated in code. The visible label is still "Models". */ -export type ModelsTab = "catalog" | "combos" | "routing" | "compatibility"; +export type ModelsTab = "catalog" | "live" | "combos" | "routing" | "compatibility"; -export const MODELS_TABS: readonly ModelsTab[] = ["catalog", "combos", "routing", "compatibility"]; +export const MODELS_TABS: readonly ModelsTab[] = ["catalog", "live", "combos", "routing", "compatibility"]; export function modelsTabHash(tab: ModelsTab): string { return tab === "catalog" ? "models" : `models/${tab}`; @@ -34,6 +34,7 @@ export function modelsTabHash(tab: ModelsTab): string { export function readModelsTab(hash = window.location.hash): ModelsTab { // A compatibility prefilter rides in `?query` (protocol-deep-links.ts); the tab is the path. const raw = splitHashQuery(normalizeHashPath(hash)).path; + if (raw === "models/live") return "live"; if (raw === "models/combos" || raw === JEV_AUTO_CREATE_HASH || raw === "combos" || raw.startsWith("combos/")) return "combos"; if (raw === "models/routing" || raw === "routing" || raw.startsWith("routing/")) return "routing"; if (raw === "models/compatibility" || raw === "lab" || raw.startsWith("lab/")) return "compatibility"; diff --git a/gui/src/pages/route-live/FlowDiagram.tsx b/gui/src/pages/route-live/FlowDiagram.tsx new file mode 100644 index 00000000000..0678fd527c4 --- /dev/null +++ b/gui/src/pages/route-live/FlowDiagram.tsx @@ -0,0 +1,79 @@ +/** Client -> OpenCodex -> candidates. The answered row is highlighted, failed rows say why, skipped rows are muted. */ +import type { ReactNode } from "react"; +import { useI18n, LOCALES, type TKey } from "../../i18n/shared"; +import { LogsClientChip } from "../logs-client-chip"; +import { clientLabel } from "../logs-client-label"; +import { candidateWho, type FlowCandidate, type FlowStatus, type RouteFlow } from "./flow-model"; +import { formatDuration } from "./route-format"; +import { FailedDetail, ReasonText } from "./ReasonText"; +import "./route-live.css"; + +const STATUS_TKEY: Record = { + answered: "routeLive.statusAnswered", + failed: "routeLive.statusFailed", + skipped: "routeLive.statusSkipped", + idle: "routeLive.statusIdle", +}; +const STATUS_GLYPH: Record = { answered: "✓", failed: "✕", skipped: "–", idle: "·" }; + +function CandidateDetail({ candidate, localeTag }: { candidate: FlowCandidate; localeTag?: string }) { + const { t } = useI18n(); + const parts: ReactNode[] = []; + if (candidate.status === "failed") { + parts.push(); + } else if (candidate.status === "skipped" && candidate.reasonCode) { + parts.push(); + } else if (candidate.status === "idle") { + parts.push(t(STATUS_TKEY.idle)); + } + if (candidate.status !== "skipped" && candidate.status !== "idle") { + if (candidate.ttftMs !== undefined) parts.push(`${t("routeLive.colTtft")} ${formatDuration(candidate.ttftMs, localeTag)}`); + if (candidate.durationMs !== undefined) parts.push(`${t("routeLive.colDuration")} ${formatDuration(candidate.durationMs, localeTag)}`); + } + if (parts.length === 0) return null; + return {parts.flatMap((part, i) => (i === 0 ? [part] : [" · ", part]))}; +} + +export function FlowDiagram({ flow }: { flow: RouteFlow }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const candidates = flow.candidates; + return ( +
+
+ + + {clientLabel(flow.client.value, t)} + {flow.client.surface && {flow.client.surface}} + +
+
+ ); +} diff --git a/gui/src/pages/route-live/ReasonText.tsx b/gui/src/pages/route-live/ReasonText.tsx new file mode 100644 index 00000000000..f959db9f644 --- /dev/null +++ b/gui/src/pages/route-live/ReasonText.tsx @@ -0,0 +1,18 @@ +import type { ReactNode } from "react"; +import { useT } from "../../i18n/shared"; +import { reasonKey, type ReasonKind } from "./route-reasons"; +import { withSlots } from "./slots"; + +/** Plain-language reason for a routing code; a code the registry lacks shows raw, in ``. */ +export function ReasonText({ kind, code }: { kind: ReasonKind; code: string }): ReactNode { + const t = useT(); + const key = reasonKey(kind, code); + return key ? t(key) : {code}; +} + +/** "{status} · {reason}" for a try that failed; the reason part is dropped when no code was recorded. */ +export function FailedDetail({ status, code }: { status: number; code?: string }): ReactNode { + const t = useT(); + if (!code) return <>{status}; + return <>{withSlots(t("routeLive.detailFailed", { status, reason: "{reason}" }), { reason: })}; +} diff --git a/gui/src/pages/route-live/RequestList.tsx b/gui/src/pages/route-live/RequestList.tsx new file mode 100644 index 00000000000..f74b4fa25e3 --- /dev/null +++ b/gui/src/pages/route-live/RequestList.tsx @@ -0,0 +1,161 @@ +/** + * Recent requests, flat or grouped by session / API key. Rows are real buttons, so Tab, Enter and + * Space work without extra wiring; Esc anywhere in the list unpins. A metric with no value shows + * a dash, never a zero. + */ +import { useState, type KeyboardEvent } from "react"; +import { useI18n, LOCALES, type TFn } from "../../i18n/shared"; +import { formatEstimatedUsdValue } from "../logs-cost-format"; +import { LogsClientChip } from "../logs-client-chip"; +import type { AccountNames } from "./flow-model"; +import { groupRows, type GroupLabel, type GroupMode, type GroupStats } from "./request-groups"; +import { formatClock, formatCount, formatDuration, formatPercent, formatRate, shortId } from "./route-format"; +import { + cacheHitPercent, costUsdOf, rowAccountLabel, rowKey, servedModelOf, tokPerSecondOf, tokenTotal, type RouteRow, +} from "./route-rows"; +import "./route-live.css"; + +const DASH = "—"; +const MODES: ReadonlyArray<{ mode: GroupMode; key: "routeLive.modeRequest" | "routeLive.modeSession" | "routeLive.modeKey" }> = [ + { mode: "request", key: "routeLive.modeRequest" }, + { mode: "session", key: "routeLive.modeSession" }, + { mode: "key", key: "routeLive.modeKey" }, +]; + +function groupLabelText(label: GroupLabel, t: TFn): string { + switch (label.kind) { + case "session": return t("routeLive.groupSession", { id: shortId(label.id) }); + case "no-session": return t("routeLive.groupNoSession"); + case "key": return t("routeLive.groupKey", { id: shortId(label.id) }); + case "admission": + if (label.admission === "loopback") return t("routeLive.admLoopback"); + if (label.admission === "environment") return t("routeLive.admEnvironment"); + if (label.admission === "configured") return t("routeLive.admConfigured"); + return t("routeLive.admUnknown"); + } +} + +function effortText(row: RouteRow): string { + const asked = row.requestedEffort; + const used = row.effectiveEffort; + if (asked && used && asked !== used) return `${asked} → ${used}`; + return used ?? asked ?? DASH; +} + +function whoText(row: RouteRow, names: AccountNames): string { + const label = rowAccountLabel(row); + const provider = row.accountRoster?.provider ?? row.provider; + return (label && (names[provider]?.[label] ?? names[row.provider]?.[label])) ?? label ?? row.provider; +} + +function GroupHead({ label, stats, open, onToggle, localeTag }: { + label: GroupLabel; stats: GroupStats; open: boolean; onToggle: () => void; localeTag?: string; +}) { + const { t } = useI18n(); + const bits = [t("routeLive.groupCount", { count: stats.count })]; + if (stats.tokens !== undefined) bits.push(t("routeLive.groupTokens", { value: formatCount(stats.tokens, localeTag) })); + if (stats.cacheHit !== undefined) bits.push(t("routeLive.groupCache", { value: formatPercent(stats.cacheHit, localeTag) })); + if (stats.tokPerSecond !== undefined) bits.push(`${formatRate(stats.tokPerSecond, false, localeTag)} tok/s`); + if (stats.costUsd !== undefined) bits.push(formatEstimatedUsdValue(stats.costUsd, t, localeTag)); + return ( + + ); +} + +function RequestRow({ row, pinned, names, localeTag, onPin }: { + row: RouteRow; pinned: boolean; names: AccountNames; localeTag?: string; onPin: (key: string) => void; +}) { + const { t } = useI18n(); + const failed = row.status >= 400; + const tokens = tokenTotal(row); + const cache = cacheHitPercent(row); + const rate = tokPerSecondOf(row); + const cost = costUsdOf(row); + const tries = row.attempts?.length ?? 0; + return ( +
  • + +
  • + ); +} + +export function RequestList({ rows, pinnedKey, onPin, mode, onMode, names }: { + rows: RouteRow[]; + pinnedKey: string | null; + onPin: (key: string | null) => void; + mode: GroupMode; + onMode: (mode: GroupMode) => void; + names: AccountNames; +}) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const [collapsed, setCollapsed] = useState>(() => new Set()); + const groups = mode === "request" ? undefined : groupRows(rows, mode); + const toggle = (id: string) => setCollapsed(prev => { + const next = new Set(prev); + if (!next.delete(id)) next.add(id); + return next; + }); + const pin = (key: string) => onPin(key === pinnedKey ? null : key); + const renderRows = (list: RouteRow[]) => list.map(row => ( + + )); + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape" && pinnedKey !== null) onPin(null); + }; + + return ( +
    +
    +

    {t("routeLive.listLabel")}

    +
    + {MODES.map(({ mode: m, key }) => ( + + ))} +
    +
    +

    {t("routeLive.rowHint")}

    + + {groups ? groups.map(group => { + const open = !collapsed.has(group.id); + return ( +
    + toggle(group.id)} localeTag={localeTag} /> + {open &&
      {renderRows(group.rows)}
    } +
    + ); + }) :
      {renderRows(rows)}
    } +
    + ); +} diff --git a/gui/src/pages/route-live/RouteLive.tsx b/gui/src/pages/route-live/RouteLive.tsx new file mode 100644 index 00000000000..69d4fa767f0 --- /dev/null +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -0,0 +1,116 @@ +/** + * Models > Live routing. For the newest request, or the one the operator pinned, shows who was + * asked, who answered, why the rest were skipped, then the list of recent requests. + */ +import { useMemo, useState } from "react"; +import { useI18n, LOCALES } from "../../i18n/shared"; +import { EmptyState, Notice } from "../../ui"; +import { FlowDiagram } from "./FlowDiagram"; +import { buildRouteFlow, candidateWho, summarizePool, type FlowOutcome, type RouteFlow } from "./flow-model"; +import { FailedDetail, ReasonText } from "./ReasonText"; +import { withSlots } from "./slots"; +import { RequestList } from "./RequestList"; +import { RouteSteps } from "./RouteSteps"; +import { formatClock, formatDuration } from "./route-format"; +import { rowKey, type RouteRow } from "./route-rows"; +import type { GroupMode } from "./request-groups"; +import { useAccountNames, useRouteRows } from "./use-route-live"; +import "./route-live.css"; + +function OutcomeLine({ outcome, row }: { outcome: FlowOutcome; row: RouteRow }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + switch (outcome.kind) { + case "ok": + case "moved": { + const who = {candidateWho(outcome.answered)}; + const duration = formatDuration(outcome.answered.durationMs ?? row.durationMs, localeTag); + const sentence = outcome.kind === "ok" + ? withSlots(t("routeLive.outcomeOk", { who: "{who}", model: "{model}", duration: "{duration}" }), { + who, model: {outcome.answered.model}, duration, + }) + : withSlots(t("routeLive.outcomeMoved", { count: outcome.tries, who: "{who}" }), { who }); + return

    {sentence}

    ; + } + case "failed": { + const fallback = ; + const withTries = outcome.tries > 1 && outcome.reasonCode !== undefined; + return ( +

    + {withTries + ? withSlots(t("routeLive.outcomeFailedTries", { status: "{status}", reason: "{reason}", count: outcome.tries }), { + status: outcome.httpStatus, reason: , + }) + : fallback} +

    + ); + } + case "local": + return

    {t("routeLive.outcomeLocal")}

    ; + } +} + +function PoolLine({ row }: { row: RouteRow }) { + const { t } = useI18n(); + const pool = summarizePool(row.accountRoster); + if (!pool) return null; + return ( +

    + {t("routeLive.poolSummary", { + provider: pool.provider, total: pool.total, available: pool.available, + cooldown: pool.cooldown, paused: pool.paused, reauth: pool.needsReauth, + })} + {row.accountRoster?.truncated && ` ${t("routeLive.poolTruncated")}`} + {" "} + {t("routeLive.linkAccounts")} +

    + ); +} + +function Selected({ row, flow, pinned, onBack }: { row: RouteRow; flow: RouteFlow; pinned: boolean; onBack: () => void }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const heading = pinned ? t("routeLive.pinnedHead", { time: formatClock(row.timestamp, localeTag) }) : t("routeLive.latestHead"); + return ( +
    +
    +

    {heading}

    + {pinned && } +
    + + + + + {row.routeDecision?.routeKind === "combo" &&

    {t("routeLive.linkCombos")}

    } +
    + ); +} + +export default function RouteLive({ apiBase, active }: { apiBase: string; active: boolean }) { + const { t } = useI18n(); + const [pinnedKey, setPinnedKey] = useState(null); + const [mode, setMode] = useState("request"); + const resource = useRouteRows(apiBase, active); + const rows = useMemo(() => resource.data ?? [], [resource.data]); + const providers = useMemo(() => [...new Set(rows.flatMap(r => (r.accountRoster ? [r.accountRoster.provider] : [])))], [rows]); + const names = useAccountNames(apiBase, active, providers); + const pinnedRow = pinnedKey === null ? undefined : rows.find(r => rowKey(r) === pinnedKey); + const selected = pinnedRow ?? rows[0]; + const flow = useMemo(() => (selected ? buildRouteFlow(selected, names) : undefined), [selected, names]); + + if (resource.data === undefined) { + return resource.error + ? {t("routeLive.loadFailed")} + :

    {t("routeLive.loading")}

    ; + } + if (rows.length === 0 || !selected || !flow) { + return ; + } + return ( +
    + {resource.error != null && !resource.lastAttemptOk && {t("routeLive.loadFailed")}} + setPinnedKey(null)} /> + +
    + ); +} diff --git a/gui/src/pages/route-live/RouteSteps.tsx b/gui/src/pages/route-live/RouteSteps.tsx new file mode 100644 index 00000000000..921a6bdc322 --- /dev/null +++ b/gui/src/pages/route-live/RouteSteps.tsx @@ -0,0 +1,54 @@ +/** "How the latest request was routed": the same facts as the flow, as a numbered plain-language list. */ +import type { ReactNode } from "react"; +import { useI18n, LOCALES } from "../../i18n/shared"; +import { clientLabel } from "../logs-client-label"; +import { buildRouteSteps, candidateWho, type RouteFlow, type RouteStep } from "./flow-model"; +import { formatDuration } from "./route-format"; +import { FailedDetail, ReasonText } from "./ReasonText"; +import { withSlots } from "./slots"; +import type { RouteRow } from "./route-rows"; + +export function RouteSteps({ row, flow }: { row: RouteRow; flow: RouteFlow }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const steps = buildRouteSteps(row, flow); + + const text = (step: RouteStep): ReactNode => { + switch (step.kind) { + case "asked": + return withSlots(t(step.combo ? "routeLive.stepAskedCombo" : "routeLive.stepAsked", { client: "{client}", model: "{model}" }), { + client: clientLabel(flow.client.value, t), model: {step.requested}, + }); + case "why": + return withSlots(t("routeLive.stepWhy", { reason: "{reason}" }), { reason: }); + case "skipped": + return withSlots(t("routeLive.stepSkipped", { who: "{who}", reason: "{reason}" }), { + who: {candidateWho(step.candidate)}, + reason: step.candidate.reasonCode ? : "", + }); + case "try": { + const who = {candidateWho(step.candidate)}; + if (step.ok) { + return withSlots(t("routeLive.stepTryOk", { who: "{who}", duration: "{duration}" }), { + who, duration: formatDuration(step.candidate.durationMs ?? row.durationMs, localeTag), + }); + } + return withSlots(t(step.moveOn ? "routeLive.stepTryFailedNext" : "routeLive.stepTryFailed", { who: "{who}", result: "{result}" }), { + who, result: , + }); + } + case "none": + return t("routeLive.stepNone"); + } + }; + + return ( +
      + {steps.map((step, index) => ( +
    1. + {text(step)} +
    2. + ))} +
    + ); +} diff --git a/gui/src/pages/route-live/flow-model.ts b/gui/src/pages/route-live/flow-model.ts new file mode 100644 index 00000000000..e85c0373ebc --- /dev/null +++ b/gui/src/pages/route-live/flow-model.ts @@ -0,0 +1,156 @@ +/** + * Pure flow view model for one request row: who was asked, who answered, who was skipped and why. + * No React, no i18n: reasons stay codes and `route-reasons.ts` owns the wording. + */ +import { rowAccountLabel, type RouteRoster, type RouteRow } from "./route-rows"; + +export type FlowStatus = "answered" | "failed" | "skipped" | "idle"; + +export interface FlowCandidate { + key: string; + provider: string; + model: string; + accountLabel?: string; + displayName?: string; + status: FlowStatus; + reasonCode?: string; + httpStatus?: number; + ttftMs?: number; + durationMs?: number; +} + +export type FlowOutcome = + | { kind: "ok"; answered: FlowCandidate } + | { kind: "moved"; answered: FlowCandidate; tries: number } + | { kind: "failed"; httpStatus: number; reasonCode?: string; tries: number } + | { kind: "local" }; + +export interface RouteFlow { + client: { value: unknown; surface?: string }; + requested: { model: string; alias?: string }; + candidates: FlowCandidate[]; + outcome: FlowOutcome; +} + +/** provider -> account log label -> display name (from `/api/oauth/accounts`). */ +export type AccountNames = Readonly>>>; + +const NUL = String.fromCharCode(0); +const pm = (provider: string, model: string) => `${provider}${NUL}${model}`; + +export function candidateWho(c: FlowCandidate): string { + return c.displayName ?? c.accountLabel ?? c.provider; +} + +export function buildRouteFlow(row: RouteRow, names: AccountNames = {}): RouteFlow { + const attempts = row.attempts ?? []; + const candidates: FlowCandidate[] = []; + const coveredModels = new Set(); + const coveredLabels = new Set(); + const nameOf = (provider: string, label?: string) => (label ? names[provider]?.[label] : undefined); + + attempts.forEach((a, i) => { + const label = a.accountLogLabel ?? a.accountTag; + const last = i === attempts.length - 1; + const ok = a.status < 400 && !a.errorCode; + const answered = last && ok && row.status < 400; + const reasonCode = answered ? undefined : a.errorCode ?? (last ? row.errorCode : undefined); + coveredModels.add(pm(a.provider, a.model)); + if (label) coveredLabels.add(label); + candidates.push({ + key: `attempt:${i}`, provider: a.provider, model: a.model, status: answered ? "answered" : "failed", + httpStatus: a.status, + ...(label ? { accountLabel: label } : {}), + ...(nameOf(a.provider, label) ? { displayName: nameOf(a.provider, label) } : {}), + ...(reasonCode ? { reasonCode } : {}), + ...(typeof a.firstOutputMs === "number" ? { ttftMs: a.firstOutputMs } : {}), + ...(typeof a.durationMs === "number" ? { durationMs: a.durationMs } : {}), + }); + }); + + row.routeDecision?.candidates?.forEach((c, i) => { + if (typeof c.provider !== "string" || typeof c.model !== "string" || coveredModels.has(pm(c.provider, c.model))) return; + const code = c.exclusions?.find(e => typeof e.code === "string")?.code; + const skipped = c.eligible === false; + candidates.push({ + key: `decision:${i}`, provider: c.provider, model: c.model, status: skipped ? "skipped" : "idle", + ...(skipped && code ? { reasonCode: code } : {}), + }); + }); + + const roster: RouteRoster | undefined = row.accountRoster; + roster?.accounts.forEach(account => { + if (coveredLabels.has(account.label)) return; + const served = account.label === row.accountLogLabel; + const status: FlowStatus = served ? (row.status < 400 ? "answered" : "failed") + : account.state === "available" ? "idle" : "skipped"; + candidates.push({ + key: `roster:${account.label}`, provider: roster.provider, model: row.model, status, + accountLabel: account.label, + ...(nameOf(roster.provider, account.label) ? { displayName: nameOf(roster.provider, account.label) } : {}), + ...(status === "skipped" ? { reasonCode: account.state } : {}), + ...(served ? { httpStatus: row.status, durationMs: row.durationMs } : {}), + }); + }); + + const answered = candidates.find(c => c.status === "answered"); + const tries = Math.max(attempts.length, 1); + const outcome: FlowOutcome = answered + ? (tries > 1 ? { kind: "moved", answered, tries } : { kind: "ok", answered }) + : row.status >= 400 + ? { kind: "failed", httpStatus: row.status, tries: attempts.length, ...(row.errorCode ? { reasonCode: row.errorCode } : {}) } + : { kind: "local" }; + + return { + client: { value: row.client, ...(row.surface ? { surface: row.surface } : {}) }, + requested: { + model: row.requestedModel ?? row.model, + ...(row.requestedAlias ? { alias: row.requestedAlias } : {}), + }, + candidates, + outcome, + }; +} + +export type RouteStep = + | { kind: "asked"; requested: string; combo: boolean } + | { kind: "why"; reasonCode: string } + | { kind: "skipped"; candidate: FlowCandidate } + | { kind: "try"; candidate: FlowCandidate; ok: boolean; moveOn: boolean } + | { kind: "none" }; + +export function buildRouteSteps(row: RouteRow, flow: RouteFlow): RouteStep[] { + const steps: RouteStep[] = [{ + kind: "asked", requested: flow.requested.alias ?? flow.requested.model, combo: row.routeDecision?.routeKind === "combo", + }]; + const reason = row.routeDecision?.selected?.reason; + if (reason) steps.push({ kind: "why", reasonCode: reason }); + for (const c of flow.candidates) if (c.status === "skipped") steps.push({ kind: "skipped", candidate: c }); + const tried = flow.candidates.filter(c => c.key.startsWith("attempt:") || (c.key.startsWith("roster:") && c.httpStatus !== undefined)); + tried.forEach((c, i) => steps.push({ kind: "try", candidate: c, ok: c.status === "answered", moveOn: c.status === "failed" && i < tried.length - 1 })); + if (tried.length === 0) steps.push({ kind: "none" }); + return steps; +} + +export interface PoolSummary { + provider: string; + total: number; + available: number; + cooldown: number; + paused: number; + needsReauth: number; + quotaExhausted: number; + modelUnlisted: number; +} + +export function summarizePool(roster: RouteRoster | undefined): PoolSummary | undefined { + if (!roster) return undefined; + const count = (state: string) => roster.accounts.filter(a => a.state === state).length; + return { + provider: roster.provider, total: roster.accounts.length, available: count("available"), cooldown: count("cooldown"), + paused: count("paused"), needsReauth: count("needs-reauth"), quotaExhausted: count("quota-exhausted"), + modelUnlisted: count("model-unlisted"), + }; +} + +export { rowAccountLabel }; diff --git a/gui/src/pages/route-live/request-groups.ts b/gui/src/pages/route-live/request-groups.ts new file mode 100644 index 00000000000..ad13dd6987b --- /dev/null +++ b/gui/src/pages/route-live/request-groups.ts @@ -0,0 +1,71 @@ +/** Grouping of request rows by session or API key, with the aggregates a group head shows. */ +import { cacheHitPercent, costUsdOf, tokPerSecondOf, tokenTotal, type RouteRow } from "./route-rows"; + +export type GroupMode = "request" | "session" | "key"; + +export type GroupLabel = + | { kind: "session"; id: string } + | { kind: "no-session" } + | { kind: "key"; id: string } + | { kind: "admission"; admission: string }; + +export interface GroupStats { + count: number; + tokens?: number; + cacheHit?: number; + tokPerSecond?: number; + costUsd?: number; +} + +export interface RouteGroup { + id: string; + label: GroupLabel; + rows: RouteRow[]; + stats: GroupStats; +} + +const NO_SESSION = "session:none"; + +function groupOf(row: RouteRow, mode: Exclude): { id: string; label: GroupLabel } { + if (mode === "session") { + return row.conversationId + ? { id: `session:${row.conversationId}`, label: { kind: "session", id: row.conversationId } } + : { id: NO_SESSION, label: { kind: "no-session" } }; + } + if (row.apiKeyId) return { id: `key:${row.apiKeyId}`, label: { kind: "key", id: row.apiKeyId } }; + const admission = row.admissionKind ?? "unknown"; + return { id: `admission:${admission}`, label: { kind: "admission", admission } }; +} + +function mean(values: number[]): number | undefined { + return values.length === 0 ? undefined : values.reduce((sum, v) => sum + v, 0) / values.length; +} + +function known(rows: RouteRow[], read: (row: RouteRow) => T | undefined): T[] { + return rows.flatMap(row => { const value = read(row); return value === undefined ? [] : [value]; }); +} + +export function groupStats(rows: RouteRow[]): GroupStats { + const tokens = known(rows, tokenTotal); + const costs = known(rows, costUsdOf); + const stats: GroupStats = { count: rows.length }; + if (tokens.length) stats.tokens = tokens.reduce((sum, v) => sum + v, 0); + const cache = mean(known(rows, cacheHitPercent)); + if (cache !== undefined) stats.cacheHit = cache; + const rate = mean(known(rows, row => tokPerSecondOf(row)?.value)); + if (rate !== undefined) stats.tokPerSecond = rate; + if (costs.length) stats.costUsd = costs.reduce((sum, v) => sum + v, 0); + return stats; +} + +/** Groups keep first-seen order, so newest-first rows give newest-first groups. */ +export function groupRows(rows: RouteRow[], mode: Exclude): RouteGroup[] { + const groups = new Map(); + for (const row of rows) { + const { id, label } = groupOf(row, mode); + const group = groups.get(id) ?? { id, label, rows: [], stats: { count: 0 } }; + group.rows.push(row); + groups.set(id, group); + } + return [...groups.values()].map(group => ({ ...group, stats: groupStats(group.rows) })); +} diff --git a/gui/src/pages/route-live/route-format.ts b/gui/src/pages/route-live/route-format.ts new file mode 100644 index 00000000000..49d1fe0b537 --- /dev/null +++ b/gui/src/pages/route-live/route-format.ts @@ -0,0 +1,50 @@ +/** Number and time formatting for the Live routing tab. All locale-aware, all Intl. */ + +const numberFormats = new Map(); + +function numberFormat(locale: string | undefined, options: Intl.NumberFormatOptions): Intl.NumberFormat { + const key = `${locale ?? ""}|${JSON.stringify(options)}`; + let cached = numberFormats.get(key); + if (!cached) { + cached = new Intl.NumberFormat(locale, options); + numberFormats.set(key, cached); + } + return cached; +} + +export function formatDuration(ms: number, locale?: string): string { + if (!Number.isFinite(ms) || ms < 0) return "—"; + if (ms < 1000) { + return numberFormat(locale, { style: "unit", unit: "millisecond", unitDisplay: "narrow", maximumFractionDigits: 0 }).format(ms); + } + return numberFormat(locale, { + style: "unit", unit: "second", unitDisplay: "narrow", maximumFractionDigits: ms < 10_000 ? 2 : 1, + }).format(ms / 1000); +} + +export function formatPercent(percent: number, locale?: string): string { + return numberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(percent / 100); +} + +export function formatRate(value: number, estimated: boolean, locale?: string): string { + const digits = value >= 100 ? 0 : 1; + const text = numberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value); + return estimated ? `~${text}` : text; +} + +export function formatCount(value: number, locale?: string): string { + return numberFormat(locale, { notation: "compact", maximumFractionDigits: 1 }).format(value); +} + +export function formatClock(timestamp: number, locale?: string): string { + try { + return new Date(timestamp).toLocaleTimeString(locale, { hour12: false }); + } catch { + return new Date(timestamp).toLocaleTimeString(); + } +} + +/** First 8 characters of an id: enough to tell sessions apart without printing the whole value. */ +export function shortId(id: string): string { + return id.length > 8 ? id.slice(0, 8) : id; +} diff --git a/gui/src/pages/route-live/route-live.css b/gui/src/pages/route-live/route-live.css new file mode 100644 index 00000000000..e38c325779a --- /dev/null +++ b/gui/src/pages/route-live/route-live.css @@ -0,0 +1,88 @@ +/* Live routing tab. Design tokens only; the shared styles.css is not touched. */ +.rl-page { display: flex; flex-direction: column; gap: var(--space-6); } +.rl-muted { color: var(--muted); } +.rl-bad { color: var(--red); font-weight: var(--weight-semibold); } +.rl-h { margin: 0; font-size: var(--text-body); font-weight: var(--weight-semibold); } +.rl-ellipsis { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rl-num { text-align: right; font-variant-numeric: tabular-nums; } + +.rl-selected { display: flex; flex-direction: column; gap: var(--space-3); } +.rl-selected-bar, .rl-list-bar { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); flex-wrap: wrap; } +.rl-pool, .rl-hint { margin: 0; font-size: var(--text-label); } + +.rl-outcome { + margin: 0; padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm); + border: 1px solid var(--border); background: var(--raised); font-size: var(--text-body); +} +.rl-outcome--ok { border-color: var(--green); background: var(--green-soft); } +.rl-outcome--bad { border-color: var(--red); background: var(--red-soft); } + +/* client -> hub -> candidates */ +.rl-flow { display: grid; grid-template-columns: auto 28px auto 28px minmax(0, 1fr); align-items: center; } +.rl-node { + display: flex; align-items: center; gap: var(--space-2); padding: var(--space-2) var(--space-3); + border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--surface); min-width: 0; +} +.rl-node--hub { border-color: var(--text); } +.rl-node-text { display: flex; flex-direction: column; min-width: 0; } +.rl-node-title { font-weight: var(--weight-semibold); } +.rl-node-sub { font-size: var(--text-caption); color: var(--muted); overflow-wrap: anywhere; } +.rl-arrow { height: 1px; background: var(--border); position: relative; } +.rl-arrow::after { + content: ""; position: absolute; right: 0; top: -3px; width: 6px; height: 6px; + border-top: 1px solid var(--muted); border-right: 1px solid var(--muted); transform: rotate(45deg); +} +.rl-cands { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-1-5); } +.rl-empty-cands { margin: 0; } +.rl-cand { + display: flex; gap: var(--space-2); padding: var(--space-2) var(--space-3); border-radius: var(--radius-sm); + border: 1px solid var(--border); background: var(--surface); +} +.rl-cand-mark { flex: 0 0 auto; width: 18px; text-align: center; font-weight: var(--weight-bold); } +.rl-cand-body { display: flex; flex-direction: column; min-width: 0; gap: 2px; } +.rl-cand-head { display: flex; align-items: baseline; gap: var(--space-2); flex-wrap: wrap; } +.rl-cand-model { font-size: var(--text-caption); color: var(--muted); overflow-wrap: anywhere; } +.rl-cand-status { margin-left: auto; font-size: var(--text-caption); color: var(--muted); } +.rl-cand-detail { font-size: var(--text-label); color: var(--muted); } +.rl-cand--answered { border-color: var(--green); background: var(--green-soft); } +.rl-cand--answered .rl-cand-mark, .rl-cand--answered .rl-cand-status { color: var(--green); font-weight: var(--weight-semibold); } +.rl-cand--failed { border-color: var(--red); background: var(--red-soft); } +.rl-cand--failed .rl-cand-mark, .rl-cand--failed .rl-cand-detail { color: var(--red); } +.rl-cand--skipped, .rl-cand--idle { background: transparent; border-style: dashed; color: var(--muted); } +.rl-cand--skipped .rl-cand-who, .rl-cand--idle .rl-cand-who { font-weight: var(--weight-regular); } + +.rl-steps { margin: 0; padding-left: var(--space-5); display: flex; flex-direction: column; gap: var(--space-1-5); font-size: var(--text-control); } +.rl-step--ok::marker { color: var(--green); } +.rl-step--bad { color: var(--red); } +.rl-step--skipped { color: var(--muted); } + +/* request list */ +.rl-list { display: flex; flex-direction: column; gap: var(--space-2); min-width: 0; overflow-x: auto; } +.rl-rows { list-style: none; margin: 0; padding: 0; min-width: 880px; } +.rl-row { + display: grid; width: 100%; min-width: 880px; align-items: center; gap: var(--space-2); text-align: left; + grid-template-columns: 68px minmax(130px, 1.3fr) minmax(150px, 1.5fr) 80px 64px 64px 64px 64px 56px 72px 44px; + padding: var(--space-1-5) var(--space-2); font: inherit; font-size: var(--text-label); color: var(--text); + background: transparent; border: 0; border-bottom: 1px solid var(--border-soft); +} +button.rl-row { cursor: pointer; } +button.rl-row:hover { background: var(--hover); } +button.rl-row:focus-visible, .rl-group-head:focus-visible { outline: 2px solid var(--text); outline-offset: -2px; } +.rl-row--pinned { background: var(--raised); outline: 1px solid var(--text); outline-offset: -1px; } +.rl-row--head { color: var(--muted); font-size: var(--text-caption); border-bottom-color: var(--border); } +.rl-cell { display: flex; align-items: center; gap: var(--space-1-5); min-width: 0; } +.rl-cell--who { flex-direction: column; align-items: flex-start; gap: 0; } +.rl-cell.rl-num { justify-content: flex-end; } +.rl-row--head > .rl-num { justify-content: flex-end; } +.rl-group-head { + display: flex; align-items: baseline; gap: var(--space-2); width: 100%; padding: var(--space-2); + font: inherit; font-size: var(--text-label); color: var(--text); text-align: left; cursor: pointer; + background: var(--raised); border: 0; border-radius: var(--radius-xs); +} +.rl-group { display: flex; flex-direction: column; gap: var(--space-1); } + +@media (max-width: 760px) { + .rl-flow { grid-template-columns: minmax(0, 1fr); row-gap: var(--space-2); } + .rl-arrow { width: 1px; height: 16px; margin-left: var(--space-4); } + .rl-arrow::after { right: -3px; top: auto; bottom: 0; transform: rotate(135deg); } +} diff --git a/gui/src/pages/route-live/route-reasons.ts b/gui/src/pages/route-live/route-reasons.ts new file mode 100644 index 00000000000..518e499cd91 --- /dev/null +++ b/gui/src/pages/route-live/route-reasons.ts @@ -0,0 +1,59 @@ +/** + * The one registry that turns a routing code into a plain sentence fragment. + * + * Three vocabularies reach this tab and none of them is closed: exclusion codes from the routing + * trace (`skip`), `errorCode` values from provider attempts (`fail`), and `selected.reason` from + * the router (`why`). A code the registry does not list is returned as `undefined` so the caller + * shows the raw text in ``, never a blank and never a guess. + */ +import type { TKey } from "../../i18n/shared"; + +export type ReasonKind = "skip" | "fail" | "why"; + +export const ROUTE_REASONS: Record>> = { + skip: { + cooldown: "routeLive.rCooldown", + disabled: "routeLive.rDisabled", + "not-selected": "routeLive.rNotSelected", + paused: "routeLive.rPaused", + "needs-reauth": "routeLive.rNeedsReauth", + "quota-exhausted": "routeLive.rQuotaExhausted", + "model-unlisted": "routeLive.rModelUnlisted", + unconfigured: "routeLive.rUnconfigured", + "already-attempted": "routeLive.rAlreadyAttempted", + "capability-unsatisfied": "routeLive.rCapability", + "cost-limit": "routeLive.rCostLimit", + "route-unavailable": "routeLive.rRouteUnavailable", + }, + fail: { + rate_limit_exceeded: "routeLive.fRate", + insufficient_quota: "routeLive.fQuota", + usage_limit_reached: "routeLive.fQuota", + invalid_api_key: "routeLive.fAuth", + authentication_error: "routeLive.fAuth", + permission_denied: "routeLive.fPermission", + model_not_found: "routeLive.fModelMissing", + context_length_exceeded: "routeLive.fContext", + upstream_server_error: "routeLive.fServer", + upstream_error: "routeLive.fServer", + upstream_unavailable: "routeLive.fServer", + upstream_timeout: "routeLive.fTimeout", + server_is_overloaded: "routeLive.fOverloaded", + client_cancelled: "routeLive.fCancelled", + client_closed_request: "routeLive.fCancelled", + }, + why: { + "combo-pick": "routeLive.whyComboPick", + "policy-selected": "routeLive.whyPolicySelected", + "no-eligible-candidate": "routeLive.whyNoEligible", + "blocked-model-redirect": "routeLive.whyBlockedRedirect", + "combo-tool-loop-pin": "routeLive.whyComboToolLoopPin", + "jev-session-pin": "routeLive.whyJevSessionPin", + "explicit-provider": "routeLive.whyExplicitProvider", + "default-provider": "routeLive.whyDefaultProvider", + }, +}; + +export function reasonKey(kind: ReasonKind, code: string): TKey | undefined { + return Object.hasOwn(ROUTE_REASONS[kind], code) ? ROUTE_REASONS[kind][code] : undefined; +} diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts new file mode 100644 index 00000000000..41d5a843917 --- /dev/null +++ b/gui/src/pages/route-live/route-rows.ts @@ -0,0 +1,170 @@ +/** + * Row shape and metrics for the Live routing tab. + * + * `/api/logs` rows are arbitrary JSON to this page, so `parseRouteRows` is the one + * boundary: every field the flow model and the request list read is checked here or read + * through a numeric guard below. Nothing past this file trusts a row's types. + */ +import { parseLogPollResponse } from "../log-poll"; +import { + sanitizeLogEntryRouteDecision, + type LogEntryBase, + type LogRouteDecision, +} from "../log-route-decision"; +import { cacheSplit } from "../logs-token-title"; +import type { formatEstimatedUsd } from "../logs-cost-format"; + +export const ROUTE_LIVE_ROW_CAP = 200; + +export type AccountRosterState = + | "available" | "paused" | "needs-reauth" | "cooldown" | "quota-exhausted" | "model-unlisted"; + +const ROSTER_STATES: ReadonlySet = new Set([ + "available", "paused", "needs-reauth", "cooldown", "quota-exhausted", "model-unlisted", +]); + +export interface RouteAttempt { + provider: string; + model: string; + status: number; + durationMs?: number; + firstOutputMs?: number; + accountLogLabel?: string; + accountTag?: string; + errorCode?: string; +} + +export interface RouteRoster { + provider: string; + accounts: Array<{ label: string; state: AccountRosterState }>; + truncated?: true; +} + +type RowCost = Parameters[0]; + +export interface RouteRow extends LogEntryBase { + requestedModel?: string; + requestedAlias?: string; + resolvedModel?: string; + servedModel?: string; + firstOutputMs?: number; + requestedEffort?: string; + effectiveEffort?: string; + usage?: { + inputTokens?: number; + outputTokens?: number; + totalTokens?: number; + cachedInputTokens?: number; + cacheReadInputTokens?: number; + cacheCreationInputTokens?: number; + }; + totalTokens?: number; + attempts?: RouteAttempt[]; + accountRoster?: RouteRoster; + accountLogLabel?: string; + accountTag?: string; + conversationId?: string; + apiKeyId?: string; + admissionKind?: string; + client?: unknown; + surface?: string; + errorCode?: string; + displayMetrics?: { + tokPerSecond?: { kind?: string; value?: number; estimated?: boolean }; + cost?: RowCost; + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value); + +function parseAttempts(value: unknown): RouteAttempt[] | undefined { + if (!Array.isArray(value)) return undefined; + return value.filter((item): item is RouteAttempt => isRecord(item) + && typeof item.provider === "string" && typeof item.model === "string" && finite(item.status)); +} + +function parseRoster(value: unknown): RouteRoster | undefined { + if (!isRecord(value) || typeof value.provider !== "string" || !Array.isArray(value.accounts)) return undefined; + const accounts = value.accounts.filter((item): item is RouteRoster["accounts"][number] => isRecord(item) + && typeof item.label === "string" && typeof item.state === "string" && ROSTER_STATES.has(item.state)); + return accounts.length === 0 ? undefined + : { provider: value.provider, accounts, ...(value.truncated === true ? { truncated: true as const } : {}) }; +} + +function parseRow(raw: unknown): RouteRow | null { + if (!isRecord(raw) || !finite(raw.timestamp) || typeof raw.model !== "string" + || typeof raw.provider !== "string" || !finite(raw.status) || !finite(raw.durationMs)) return null; + const { attempts, accountRoster, ...rest } = raw; + const row = { ...rest } as unknown as RouteRow; + const parsedAttempts = parseAttempts(attempts); + if (parsedAttempts) row.attempts = parsedAttempts; + const roster = parseRoster(accountRoster); + if (roster) row.accountRoster = roster; + return sanitizeLogEntryRouteDecision(row); +} + +/** Newest first, capped. Rows that fail the shape check are dropped, not repaired. */ +export function parseRouteRows(body: unknown): RouteRow[] { + const rows: RouteRow[] = []; + for (const raw of parseLogPollResponse(body).rows) { + const row = parseRow(raw); + if (row) rows.push(row); + } + rows.sort((a, b) => b.timestamp - a.timestamp); + return rows.slice(0, ROUTE_LIVE_ROW_CAP); +} + +export function rowKey(row: RouteRow): string { + return row.requestId ?? `${row.timestamp}:${row.provider}:${row.model}`; +} + +export function routeDecisionOf(row: RouteRow): LogRouteDecision | undefined { + return row.routeDecision; +} + +/** The label that names the account on a row: the row's own, else the last attempt's. */ +export function rowAccountLabel(row: RouteRow): string | undefined { + const last = row.attempts?.at(-1); + return row.accountLogLabel ?? row.accountTag ?? last?.accountLogLabel ?? last?.accountTag; +} + +export function servedModelOf(row: RouteRow): string { + return row.servedModel ?? row.resolvedModel ?? row.model; +} + +/** Same rule as the Logs table: `inputTokens` already includes cache, `max` keeps legacy rows honest. */ +export function tokenTotal(row: RouteRow): number | undefined { + const usage = row.usage; + if (!usage || !finite(usage.inputTokens) || !finite(usage.outputTokens)) { + return finite(row.totalTokens) ? row.totalTokens : undefined; + } + const base = usage.inputTokens + usage.outputTokens; + const explicit = finite(usage.totalTokens) ? usage.totalTokens : row.totalTokens; + return finite(explicit) ? Math.max(explicit, base) : base; +} + +/** Cache read share of the input, 0..100. Unknown cache detail stays undefined, never 0. */ +export function cacheHitPercent(row: RouteRow): number | undefined { + const usage = row.usage; + if (!usage || !finite(usage.inputTokens) || usage.inputTokens <= 0) return undefined; + const { read } = cacheSplit({ provider: row.provider, usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens ?? 0, ...usage } }); + if (!finite(read)) return undefined; + return Math.min(100, Math.max(0, (100 * read) / usage.inputTokens)); +} + +export function tokPerSecondOf(row: RouteRow): { value: number; estimated: boolean } | undefined { + const rate = row.displayMetrics?.tokPerSecond; + if (rate?.kind !== "value" || !finite(rate.value) || rate.value <= 0) return undefined; + return { value: rate.value, estimated: rate.estimated === true }; +} + +export function costUsdOf(row: RouteRow): number | undefined { + const cost = row.displayMetrics?.cost; + if (cost?.kind !== "value") return undefined; + const total = cost.estimate.cost.total; + return finite(total) && total >= 0 ? total : undefined; +} diff --git a/gui/src/pages/route-live/slots.ts b/gui/src/pages/route-live/slots.ts new file mode 100644 index 00000000000..9856092e211 --- /dev/null +++ b/gui/src/pages/route-live/slots.ts @@ -0,0 +1,9 @@ +import { createElement, Fragment, type ReactNode } from "react"; + +/** Splits a sentence on `{slot}` markers so a JSX node can sit inside translated copy. */ +export function withSlots(sentence: string, slots: Record): ReactNode[] { + return sentence.split(/(\{[a-zA-Z]+\})/).map((part, index) => { + const name = /^\{([a-zA-Z]+)\}$/.exec(part)?.[1]; + return name && name in slots ? createElement(Fragment, { key: index }, slots[name]) : part; + }); +} diff --git a/gui/src/pages/route-live/use-route-live.ts b/gui/src/pages/route-live/use-route-live.ts new file mode 100644 index 00000000000..27d99a333a7 --- /dev/null +++ b/gui/src/pages/route-live/use-route-live.ts @@ -0,0 +1,58 @@ +/** Data for the Live routing tab: recent request rows (3 s poll) and account display names (60 s poll). */ +import { useClientResource } from "../../client-resource"; +import { ROUTE_LIVE_ROW_CAP, parseRouteRows, type RouteRow } from "./route-rows"; +import type { AccountNames } from "./flow-model"; + +export const ROUTE_LIVE_POLL_MS = 3000; +const NAMES_POLL_MS = 60_000; + +export function useRouteRows(apiBase: string, active: boolean) { + const resource = useClientResource( + `route-live:rows:${apiBase}`, + async signal => { + const res = await fetch(`${apiBase}/api/logs?limit=${ROUTE_LIVE_ROW_CAP}`, { signal }); + if (!res.ok) throw new Error(String(res.status)); + return parseRouteRows(await res.json()); + }, + { enabled: active, pollMs: ROUTE_LIVE_POLL_MS, deadlineMs: 10_000, staleAfterMs: 0 }, + ); + return resource; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** logLabel -> the name the Accounts page shows. A failed provider is skipped, never an error. */ +async function readProviderNames(apiBase: string, provider: string, signal: AbortSignal): Promise> { + const names: Record = {}; + try { + const res = await fetch(`${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}`, { signal }); + if (!res.ok) return names; + const body: unknown = await res.json(); + const accounts = isRecord(body) && Array.isArray(body.accounts) ? body.accounts : []; + for (const account of accounts) { + if (!isRecord(account) || typeof account.logLabel !== "string") continue; + const name = [account.accountLabel, account.alias].find((v): v is string => typeof v === "string" && v.trim() !== ""); + if (name) names[account.logLabel] = name; + } + } catch { + // Names are decoration: the hashed label still identifies the account. + } + return names; +} + +const NO_NAMES: AccountNames = {}; + +export function useAccountNames(apiBase: string, active: boolean, providers: readonly string[]): AccountNames { + const sorted = [...new Set(providers)].sort(); + const resource = useClientResource( + `route-live:names:${apiBase}:${sorted.join(",")}`, + async signal => { + const entries = await Promise.all(sorted.map(async p => [p, await readProviderNames(apiBase, p, signal)] as const)); + return Object.fromEntries(entries); + }, + { enabled: active && sorted.length > 0, pollMs: NAMES_POLL_MS, deadlineMs: 10_000 }, + ); + return resource.data ?? NO_NAMES; +} diff --git a/gui/tests/compatibility-lab.test.tsx b/gui/tests/compatibility-lab.test.tsx index 5bdd7d9592b..cc9e9bfe2dd 100644 --- a/gui/tests/compatibility-lab.test.tsx +++ b/gui/tests/compatibility-lab.test.tsx @@ -304,12 +304,12 @@ test("3. refresh/bookmark behavior via models-tab roundtrip", () => { expect(readModelsTab("#lab")).toBe("compatibility"); }); -test("4. keyboard traversal covers four tabs in strip", async () => { +test("4. keyboard traversal covers five tabs in strip", async () => { installLabFetch(); const { root, container } = await mountModels(); try { const tabs = [...container.querySelectorAll('[role="tab"]')] as HTMLButtonElement[]; - expect(tabs).toHaveLength(4); + expect(tabs).toHaveLength(5); const routing = container.querySelector("#models-tab-routing") as HTMLButtonElement; await act(async () => { routing.click(); }); routing.focus(); diff --git a/gui/tests/models-workspace-panels.test.tsx b/gui/tests/models-workspace-panels.test.tsx index 5cb9098e488..eea9b7525d6 100644 --- a/gui/tests/models-workspace-panels.test.tsx +++ b/gui/tests/models-workspace-panels.test.tsx @@ -94,12 +94,12 @@ async function mountModels(): Promise<{ container: HTMLElement; root: Root }> { const tabs = (container: HTMLElement) => [...container.querySelectorAll('[role="tab"]')] as HTMLButtonElement[]; const panel = (container: HTMLElement, id: string) => container.querySelector(`#models-panel-${id}`); -test("the strip renders all four tabs with the catalog selected on the bare hash", async () => { +test("the strip renders all five tabs with the catalog selected on the bare hash", async () => { installFetch(); const { container, root } = await mountModels(); try { expect(tabs(container).map(t => t.id)).toEqual([ - "models-tab-catalog", "models-tab-combos", "models-tab-routing", "models-tab-compatibility", + "models-tab-catalog", "models-tab-live", "models-tab-combos", "models-tab-routing", "models-tab-compatibility", ]); const selected = tabs(container).filter(t => t.getAttribute("aria-selected") === "true"); expect(selected).toHaveLength(1); @@ -131,11 +131,11 @@ test("a cold catalog never removes the tab strip", async () => { const { container, root } = await mountModels(); try { // Still cold here: the catalog fetch is parked on the gate. - expect(tabs(container)).toHaveLength(4); + expect(tabs(container)).toHaveLength(5); expect(panel(container, "catalog")).toBeTruthy(); releaseCatalog(); await act(async () => { await Promise.resolve(); }); - expect(tabs(container)).toHaveLength(4); + expect(tabs(container)).toHaveLength(5); } finally { await act(async () => root.unmount()); } @@ -157,7 +157,7 @@ test("a cold catalog failure still lets the user reach another tab", async () => const { container, root } = await mountModels(); try { await act(async () => { await Promise.resolve(); }); - expect(tabs(container)).toHaveLength(4); + expect(tabs(container)).toHaveLength(5); // "Reachable" has to mean the click works and the panel actually appears — asserting // the button merely exists would pass with a dead tab. @@ -276,7 +276,7 @@ test("a panel load failure does not take its siblings with it", async () => { // failed LOAD, not a render throw — the boundary mechanism itself is covered by // error-boundary.test.tsx; what matters here is that one panel's failure is // contained. - expect(tabs(container)).toHaveLength(4); + expect(tabs(container)).toHaveLength(5); await act(async () => { (container.querySelector("#models-tab-routing") as HTMLButtonElement).click(); }); diff --git a/gui/tests/route-live-model.test.ts b/gui/tests/route-live-model.test.ts new file mode 100644 index 00000000000..add57d26172 --- /dev/null +++ b/gui/tests/route-live-model.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, test } from "bun:test"; +import { buildRouteFlow, buildRouteSteps, summarizePool } from "../src/pages/route-live/flow-model"; +import { groupRows } from "../src/pages/route-live/request-groups"; +import { cacheHitPercent, parseRouteRows, type RouteRow } from "../src/pages/route-live/route-rows"; + +const base = { timestamp: 1000, model: "m", provider: "p", status: 200, durationMs: 900 }; +const row = (extra: Partial): RouteRow => ({ ...base, ...extra } as RouteRow); + +describe("route flow model", () => { + test("failover across attempts is a moved outcome with the last try answering", () => { + const flow = buildRouteFlow(row({ attempts: [ + { provider: "p", model: "m", status: 429, errorCode: "rate_limit_exceeded", accountLogLabel: "oaaaaaa" }, + { provider: "p", model: "m", status: 200, accountLogLabel: "obbbbbb" }, + ] }), { p: { obbbbbb: "Work" } }); + expect(flow.outcome.kind).toBe("moved"); + expect(flow.candidates.map(c => c.status)).toEqual(["failed", "answered"]); + expect(flow.candidates[0]!.reasonCode).toBe("rate_limit_exceeded"); + expect(flow.candidates[1]!.displayName).toBe("Work"); + const steps = buildRouteSteps(row({ attempts: [] }), flow); + expect(steps.filter(s => s.kind === "try").map(s => s.kind === "try" && s.moveOn)).toEqual([true, false]); + }); + + test("combo exclusions become skipped candidates with the first code, eligible ones idle", () => { + const flow = buildRouteFlow(row({ + attempts: [{ provider: "p", model: "m", status: 200 }], + routeDecision: { routeKind: "combo", selected: { reason: "combo-pick" }, candidates: [ + { provider: "p", model: "m", eligible: true }, + { provider: "q", model: "n", eligible: false, exclusions: [{ code: "cooldown" }, { code: "x" }] }, + { provider: "r", model: "o", eligible: true, exclusions: [{ code: "not-selected" }] }, + ] }, + })); + expect(flow.candidates.map(c => [c.provider, c.status, c.reasonCode])).toEqual([ + ["p", "answered", undefined], ["q", "skipped", "cooldown"], ["r", "idle", undefined]]); + expect(buildRouteSteps(row({ routeDecision: { routeKind: "combo", selected: { reason: "combo-pick" } } }), flow) + .slice(0, 2)).toEqual([{ kind: "asked", requested: "m", combo: true }, { kind: "why", reasonCode: "combo-pick" }]); + }); + + test("roster states skip paused and cooling accounts, available ones stay idle", () => { + const r = row({ + accountLogLabel: "oserved", + attempts: [{ provider: "p", model: "m", status: 200, accountLogLabel: "oserved" }], + accountRoster: { provider: "p", accounts: [ + { label: "oserved", state: "available" }, { label: "opaused", state: "paused" }, + { label: "ocool", state: "cooldown" }, { label: "ofree", state: "available" }] }, + }); + const flow = buildRouteFlow(r); + expect(flow.candidates.map(c => [c.accountLabel, c.status, c.reasonCode])).toEqual([ + ["oserved", "answered", undefined], ["opaused", "skipped", "paused"], ["ocool", "skipped", "cooldown"], ["ofree", "idle", undefined]]); + expect(summarizePool(r.accountRoster)).toMatchObject({ total: 4, available: 2, cooldown: 1, paused: 1, needsReauth: 0 }); + }); + + test("no attempts is local when it succeeded and failed otherwise", () => { + expect(buildRouteFlow(row({})).outcome.kind).toBe("local"); + expect(buildRouteSteps(row({}), buildRouteFlow(row({}))).at(-1)).toEqual({ kind: "none" }); + expect(buildRouteFlow(row({ status: 503, errorCode: "server_is_overloaded" })).outcome) + .toEqual({ kind: "failed", httpStatus: 503, reasonCode: "server_is_overloaded", tries: 0 }); + }); +}); + +describe("route rows and groups", () => { + test("cache hit is unknown, never 0, when the row carries no cache detail", () => { + expect(cacheHitPercent(row({ usage: { inputTokens: 100, outputTokens: 5 } }))).toBeUndefined(); + expect(cacheHitPercent(row({}))).toBeUndefined(); + expect(cacheHitPercent(row({ usage: { inputTokens: 200, outputTokens: 5, cacheReadInputTokens: 50 } }))).toBe(25); + expect(cacheHitPercent(row({ usage: { inputTokens: 200, outputTokens: 5, cacheReadInputTokens: 0 } }))).toBe(0); + }); + + test("parseRouteRows drops malformed rows, sorts newest first, keeps valid attempts", () => { + const rows = parseRouteRows({ logs: [ + { ...base, timestamp: 1, requestId: "a" }, { nope: true }, null, + { ...base, timestamp: 5, requestId: "b", attempts: [{ provider: "p", model: "m", status: 200 }, "x"] }, + ] }); + expect(rows.map(r => r.requestId)).toEqual(["b", "a"]); + expect(rows[0]!.attempts).toHaveLength(1); + }); + + test("grouping by session and key keeps aggregates and the no-session bucket", () => { + const rows = [ + row({ requestId: "1", conversationId: "c1", apiKeyId: "k1", usage: { inputTokens: 100, outputTokens: 10, cacheReadInputTokens: 50 }, + displayMetrics: { tokPerSecond: { kind: "value", value: 10 }, cost: { kind: "value", estimate: { cost: { total: 0.5 } } } } }), + row({ requestId: "2", conversationId: "c1", apiKeyId: "k1", usage: { inputTokens: 100, outputTokens: 10, cacheReadInputTokens: 0 }, + displayMetrics: { tokPerSecond: { kind: "value", value: 30 }, cost: { kind: "value", estimate: { cost: { total: 0.25 } } } } }), + row({ requestId: "3", admissionKind: "loopback" }), + ]; + const sessions = groupRows(rows, "session"); + expect(sessions.map(g => [g.id, g.stats.count])).toEqual([["session:c1", 2], ["session:none", 1]]); + expect(sessions[0]!.stats).toMatchObject({ tokens: 220, cacheHit: 25, tokPerSecond: 20, costUsd: 0.75 }); + expect(sessions[1]!.stats.cacheHit).toBeUndefined(); + expect(groupRows(rows, "key").map(g => g.label)).toEqual([ + { kind: "key", id: "k1" }, { kind: "admission", admission: "loopback" }]); + }); +}); diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx new file mode 100644 index 00000000000..4c4eb322530 --- /dev/null +++ b/gui/tests/route-live-render.test.tsx @@ -0,0 +1,77 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import type { ReactNode } from "react"; +import { Window } from "happy-dom"; +import { I18nContext, DICTS, interpolate, LOCALES, type Locale, type TFn } from "../src/i18n/shared"; +import { FlowDiagram } from "../src/pages/route-live/FlowDiagram"; +import { RequestList } from "../src/pages/route-live/RequestList"; +import { RouteSteps } from "../src/pages/route-live/RouteSteps"; +import { buildRouteFlow } from "../src/pages/route-live/flow-model"; +import { ROUTE_REASONS } from "../src/pages/route-live/route-reasons"; +import type { RouteRow } from "../src/pages/route-live/route-rows"; + +const translator = (locale: Locale): TFn => (key, vars) => interpolate(DICTS[locale][key], vars); + +function render(node: ReactNode, locale: Locale = "zh") { + const win = new Window(); + win.document.body.innerHTML = renderToStaticMarkup( + {node}, + ); + return win.document; +} + +const failover = { + timestamp: 1_700_000_000_000, requestId: "r1", model: "gemini-3.8-flash", provider: "google-antigravity", status: 200, durationMs: 2400, + firstOutputMs: 900, effectiveEffort: "high", requestedEffort: "medium", accountLogLabel: "obbbbbb", conversationId: "session-12345678", + usage: { inputTokens: 1000, outputTokens: 200, cacheReadInputTokens: 500 }, + attempts: [ + { provider: "google-antigravity", model: "gemini-3.8-flash", status: 429, errorCode: "rate_limit_exceeded", accountLogLabel: "oaaaaaa" }, + { provider: "google-antigravity", model: "gemini-3.8-flash", status: 200, accountLogLabel: "obbbbbb", durationMs: 1800 }, + ], + routeDecision: { routeKind: "combo", selected: { reason: "some-future-reason" }, candidates: [] }, + accountRoster: { provider: "google-antigravity", accounts: [ + { label: "oaaaaaa", state: "cooldown" }, { label: "obbbbbb", state: "available" }, + { label: "occcccc", state: "needs-reauth" }, { label: "oddddd0", state: "weird-state" }, + ] }, +} as unknown as RouteRow; + +test("flow marks the answered account, the failed try with its reason, and a skipped account with its reason", () => { + const flow = buildRouteFlow(failover, { "google-antigravity": { obbbbbb: "工作号" } }); + const doc = render(); + const answered = doc.querySelector(".rl-cand--answered"); + expect(answered?.textContent).toContain("工作号"); + expect(answered?.textContent).toContain("已回答"); + const failed = doc.querySelector(".rl-cand--failed"); + expect(failed?.textContent).toContain("429"); + expect(failed?.textContent).toContain("限流"); + const skipped = doc.querySelector(".rl-cand--skipped"); + expect(skipped?.textContent).toContain("需要重新登录"); +}); + +test("steps show an unknown reason code raw, in , instead of dropping it", () => { + const flow = buildRouteFlow(failover); + const doc = render(); + expect(doc.querySelectorAll("li").length).toBeGreaterThanOrEqual(3); + expect([...doc.querySelectorAll("code")].map(c => c.textContent)).toContain("some-future-reason"); +}); + +test("request list groups by session, shows dashes for unknown metrics, and marks the pinned row", () => { + const sparse = { timestamp: 1_700_000_100_000, model: "m", provider: "p", status: 500, durationMs: 50 } as unknown as RouteRow; + const list = (mode: "request" | "session") => render( + {}} mode={mode} onMode={() => {}} names={{}} />, + ); + const flat = list("request"); + expect(flat.querySelectorAll("button.rl-row").length).toBe(2); + expect(flat.querySelector(".rl-row--pinned")?.getAttribute("aria-pressed")).toBe("true"); + expect(flat.querySelectorAll("button.rl-row")[0]!.textContent).toContain("—"); + expect(flat.querySelector(".rl-bad")?.textContent).toBe("500"); + const grouped = list("session"); + expect(grouped.querySelectorAll(".rl-group-head").length).toBe(2); + expect(grouped.querySelector(".rl-group-head")?.getAttribute("aria-expanded")).toBe("true"); +}); + +test.each(LOCALES)("every reason key the registry points at has copy in $code", ({ code }) => { + for (const group of Object.values(ROUTE_REASONS)) { + for (const key of Object.values(group)) expect(DICTS[code][key]?.length).toBeGreaterThan(0); + } +}); diff --git a/tests/gui/models-workspace-tabs.test.ts b/tests/gui/models-workspace-tabs.test.ts index fed12f40c24..5392d4524e9 100644 --- a/tests/gui/models-workspace-tabs.test.ts +++ b/tests/gui/models-workspace-tabs.test.ts @@ -24,7 +24,7 @@ import { describe("nested Models hashes", () => { test("all tab hashes are registered and belong to the models page", () => { - expect([...MODELS_TAB_HASHES]).toEqual(["models/combos", "models/routing", "models/compatibility"]); + expect([...MODELS_TAB_HASHES]).toEqual(["models/live", "models/combos", "models/routing", "models/compatibility"]); for (const hash of MODELS_TAB_HASHES) { expect(hashBelongsToPage(hash, "models")).toBe(true); expect(readPageFromHash(hash)).toBe("models"); From 4e8d28bec8d547ff6297b84470d60e49540dbdeb Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:36:22 -0500 Subject: [PATCH 04/12] feat(gui): show where a routed request's time went The live routing view gains a time bar for the pinned or latest request: privacy redaction, OpenCodex internal time, earlier failed attempts, the wait for the upstream's first token, and streaming. Every segment comes from a measured field; a request without timing says so instead of drawing a bar, and no DNS or TLS split is shown because Bun's fetch does not expose one. --- gui/src/i18n/route-live-copy.ts | 8 +++ gui/src/pages/route-live/RouteLive.tsx | 2 + gui/src/pages/route-live/TimeBar.tsx | 67 ++++++++++++++++++++++ gui/src/pages/route-live/route-format.ts | 7 +++ gui/src/pages/route-live/route-live.css | 21 +++++++ gui/src/pages/route-live/route-rows.ts | 3 + gui/src/pages/route-live/time-parts.ts | 64 +++++++++++++++++++++ gui/tests/route-live-render.test.tsx | 17 ++++++ gui/tests/route-live-time.test.ts | 72 ++++++++++++++++++++++++ 9 files changed, 261 insertions(+) create mode 100644 gui/src/pages/route-live/TimeBar.tsx create mode 100644 gui/src/pages/route-live/time-parts.ts create mode 100644 gui/tests/route-live-time.test.ts diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index a714dd3c37a..53ffde6b9cb 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -99,6 +99,14 @@ const rows = { rowTries: ["{count} tries","{count}회 시도","{count} Versuche","{count} essais","试了 {count} 次","試了 {count} 次","попыток: {count}","{count} 回試行","{count} deneme","{count} lần thử","{count} tentativas"], poolTruncated: ["Only the first 16 accounts are shown.","앞의 16개 계정만 보여줘요.","Nur die ersten 16 Konten werden angezeigt.","Seuls les 16 premiers comptes sont affichés.","只显示前 16 个账号。","只顯示前 16 個帳號。","Показаны только первые 16 аккаунтов.","最初の 16 アカウントのみ表示しています。","Yalnızca ilk 16 hesap gösteriliyor.","Chỉ hiển thị 16 tài khoản đầu tiên.","Apenas as primeiras 16 contas são exibidas."], loading: ["Loading…","불러오는 중…","Wird geladen…","Chargement…","加载中…","載入中…","Загрузка…","読み込み中…","Yükleniyor…","Đang tải…","Carregando…"], + timeHead: ["Where the time went","시간이 어디에 쓰였나","Wohin die Zeit ging","Où est passé le temps","时间花在哪里","時間花在哪裡","Куда ушло время","時間の内訳","Zaman nereye gitti","Thời gian đã đi đâu","Onde o tempo foi gasto"], + timePrivacy: ["Privacy redaction","개인정보 마스킹","Datenschutz-Schwärzung","Masquage de confidentialité","隐私脱敏","隱私去識別","Скрытие личных данных","プライバシーのマスキング","Gizlilik maskeleme","Che thông tin riêng tư","Ocultação de privacidade"], + timeInternal: ["OpenCodex internal","OpenCodex 내부","OpenCodex intern","Interne OpenCodex","OpenCodex 内部","OpenCodex 內部","Внутри OpenCodex","OpenCodex 内部処理","OpenCodex iç işlem","Nội bộ OpenCodex","Interno do OpenCodex"], + timeEarlier: ["Earlier attempts","이전 시도","Frühere Versuche","Essais précédents","之前的尝试","之前的嘗試","Предыдущие попытки","それ以前の試行","Önceki denemeler","Các lần thử trước","Tentativas anteriores"], + timeUpstreamWait: ["Waiting for the first token","첫 토큰 대기","Warten auf das erste Token","Attente du premier jeton","等上游第一个字","等上游第一個字","Ожидание первого токена","最初のトークン待ち","İlk token bekleniyor","Chờ token đầu tiên","Esperando o primeiro token"], + timeStreaming: ["Streaming","스트리밍 출력","Streaming-Ausgabe","Diffusion de la réponse","流式输出","串流輸出","Потоковая передача","ストリーミング出力","Akış çıktısı","Phát trực tuyến","Transmissão da resposta"], + timeReading: ["Waiting for the upstream reply","업스트림 응답 대기","Warten auf die Antwort des Anbieters","Attente de la réponse du fournisseur","等待上游回复","等待上游回覆","Ожидание ответа провайдера","上流の応答待ち","Sağlayıcının yanıtı bekleniyor","Chờ phản hồi từ nhà cung cấp","Esperando a resposta do provedor"], + timeNone: ["The time split was not recorded for this request.","이 요청은 시간 내역이 기록되지 않았어요.","Für diese Anfrage wurde keine Zeitaufteilung erfasst.","La répartition du temps n’a pas été enregistrée pour cette requête.","这个请求没有记录时间分布。","這個請求沒有記錄時間分布。","Для этого запроса разбивка времени не записана.","このリクエストには時間の内訳が記録されていません。","Bu istek için zaman dökümü kaydedilmedi.","Yêu cầu này không ghi lại phân bổ thời gian.","A divisão de tempo não foi registrada para esta requisição."], } satisfies Record; export type RouteLiveCopyKey = `routeLive.${keyof typeof rows}`; diff --git a/gui/src/pages/route-live/RouteLive.tsx b/gui/src/pages/route-live/RouteLive.tsx index 69d4fa767f0..83de99359d0 100644 --- a/gui/src/pages/route-live/RouteLive.tsx +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -11,6 +11,7 @@ import { FailedDetail, ReasonText } from "./ReasonText"; import { withSlots } from "./slots"; import { RequestList } from "./RequestList"; import { RouteSteps } from "./RouteSteps"; +import { TimeSection } from "./TimeBar"; import { formatClock, formatDuration } from "./route-format"; import { rowKey, type RouteRow } from "./route-rows"; import type { GroupMode } from "./request-groups"; @@ -81,6 +82,7 @@ function Selected({ row, flow, pinned, onBack }: { row: RouteRow; flow: RouteFlo + {flow.outcome.kind !== "local" && } {row.routeDecision?.routeKind === "combo" &&

    {t("routeLive.linkCombos")}

    } ); diff --git a/gui/src/pages/route-live/TimeBar.tsx b/gui/src/pages/route-live/TimeBar.tsx new file mode 100644 index 00000000000..c00605f5f49 --- /dev/null +++ b/gui/src/pages/route-live/TimeBar.tsx @@ -0,0 +1,67 @@ +/** + * "Where the time went": one stacked bar plus a legend, from measured stages only. + * The idea follows Magpie's time bar (MIT, Copyright (c) 2026 yetone); the markup is this page's own. + */ +import { useI18n, LOCALES } from "../../i18n/shared"; +import type { RouteLiveCopyKey } from "../../i18n/route-live-copy"; +import { formatDuration, formatPartDuration } from "./route-format"; +import { timeParts, type TimePart, type TimePartKind, type TimeRow } from "./time-parts"; + +type Side = "ocx" | "earlier" | "upstream"; + +const PART_SIDE: Record = { + privacy: "ocx", internal: "ocx", earlier: "earlier", upstreamWait: "upstream", streaming: "upstream", reading: "upstream", +}; + +const PART_LABEL = { + privacy: "routeLive.timePrivacy", + internal: "routeLive.timeInternal", + earlier: "routeLive.timeEarlier", + upstreamWait: "routeLive.timeUpstreamWait", + streaming: "routeLive.timeStreaming", + reading: "routeLive.timeReading", +} as const satisfies Record; + +function TimeBar({ parts }: { parts: TimePart[] }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const total = parts.reduce((sum, part) => sum + part.ms, 0); + return ( + <> +
    +

    {t("routeLive.timeHead")}

    + {formatDuration(total, localeTag)} +
    + +
      + {parts.map(part => ( +
    • +
    • + ))} +
    + + ); +} + +/** The bar for a request that reached a provider; a one-line note when its timing was not recorded. */ +export function TimeSection({ row }: { row: TimeRow }) { + const { t } = useI18n(); + const parts = timeParts(row); + return ( +
    + {parts ? :

    {t("routeLive.timeNone")}

    } +
    + ); +} diff --git a/gui/src/pages/route-live/route-format.ts b/gui/src/pages/route-live/route-format.ts index 49d1fe0b537..e9920edb354 100644 --- a/gui/src/pages/route-live/route-format.ts +++ b/gui/src/pages/route-live/route-format.ts @@ -22,6 +22,13 @@ export function formatDuration(ms: number, locale?: string): string { }).format(ms / 1000); } +/** Like formatDuration, but a part under 10 ms keeps one decimal so a 2.4 ms stage is not shown as 2 ms. */ +export function formatPartDuration(ms: number, locale?: string): string { + if (!Number.isFinite(ms) || ms < 0) return "—"; + if (ms >= 10) return formatDuration(ms, locale); + return numberFormat(locale, { style: "unit", unit: "millisecond", unitDisplay: "narrow", maximumFractionDigits: 1 }).format(ms); +} + export function formatPercent(percent: number, locale?: string): string { return numberFormat(locale, { style: "percent", maximumFractionDigits: 0 }).format(percent / 100); } diff --git a/gui/src/pages/route-live/route-live.css b/gui/src/pages/route-live/route-live.css index e38c325779a..b46d338ce6f 100644 --- a/gui/src/pages/route-live/route-live.css +++ b/gui/src/pages/route-live/route-live.css @@ -56,6 +56,27 @@ .rl-step--bad { color: var(--red); } .rl-step--skipped { color: var(--muted); } +/* where the time went: OpenCodex side, earlier tries, upstream side */ +.rl-time { display: flex; flex-direction: column; gap: var(--space-2); } +.rl-time-head { display: flex; align-items: baseline; gap: var(--space-3); } +.rl-time-bar { + display: flex; height: 10px; border-radius: var(--radius-xs); overflow: hidden; background: var(--raised); + border: 1px solid var(--border); +} +.rl-time-seg { flex: 1 1 0; min-width: 2px; } +.rl-time-side--ocx { background: var(--muted); } +.rl-time-seg--privacy { opacity: 0.55; } +.rl-time-side--earlier { background: var(--amber); } +.rl-time-side--upstream { background: var(--blue); } +.rl-time-seg--streaming { opacity: 0.55; } +.rl-time-legend { + list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); + font-size: var(--text-label); +} +.rl-time-legend li { display: flex; align-items: center; gap: var(--space-1-5); } +.rl-time-dot { flex: 0 0 auto; width: 8px; height: 8px; border-radius: 50%; } +.rl-time-legend .rl-num { color: var(--muted); } + /* request list */ .rl-list { display: flex; flex-direction: column; gap: var(--space-2); min-width: 0; overflow-x: auto; } .rl-rows { list-style: none; margin: 0; padding: 0; min-width: 880px; } diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts index 41d5a843917..cd03e74a876 100644 --- a/gui/src/pages/route-live/route-rows.ts +++ b/gui/src/pages/route-live/route-rows.ts @@ -48,6 +48,9 @@ export interface RouteRow extends LogEntryBase { resolvedModel?: string; servedModel?: string; firstOutputMs?: number; + /** ms from request start until the final attempt started (src/server/request-log-route-live.ts). */ + upstreamSendMs?: number; + privacyRedactionMs?: number; requestedEffort?: string; effectiveEffort?: string; usage?: { diff --git a/gui/src/pages/route-live/time-parts.ts b/gui/src/pages/route-live/time-parts.ts new file mode 100644 index 00000000000..504b8420b47 --- /dev/null +++ b/gui/src/pages/route-live/time-parts.ts @@ -0,0 +1,64 @@ +/** + * "Where the time went" for one request, from measured fields only. + * + * The stages and the idea of dropping sub-0.1 ms parts follow Magpie's `timeParts` + * (internal/gui/assets/plugins/routing/client.js), MIT, Copyright (c) 2026 yetone. + * Bun's fetch exposes no DNS/connect/TLS timing, so those stages do not exist here. + * + * privacy privacyRedactionMs + * internal time before the final attempt started, minus privacy and earlier attempts + * earlier sum of every attempt's duration except the final one + * upstreamWait final attempt's firstOutputMs (attempt-relative) + * streaming the rest of the request + * reading replaces upstreamWait + streaming when no first output was seen + */ +import type { RouteRow } from "./route-rows"; + +export type TimePartKind = "privacy" | "internal" | "earlier" | "upstreamWait" | "streaming" | "reading"; + +export interface TimePart { + kind: TimePartKind; + ms: number; +} + +export type TimeRow = Pick; + +export const MIN_PART_MS = 0.1; + +/** A measured, non-negative duration, or undefined. */ +function measured(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined; +} + +export function timeParts(row: TimeRow): TimePart[] | null { + const total = measured(row.durationMs); + if (total === undefined) return null; + const attempts = row.attempts ?? []; + const final = attempts.at(-1); + const finalDuration = measured(final?.durationMs); + + const sendMs = measured(row.upstreamSendMs) ?? (finalDuration !== undefined ? Math.max(0, total - finalDuration) : undefined); + if (sendMs === undefined) return null; + + const privacy = measured(row.privacyRedactionMs) ?? 0; + const earlier = attempts.slice(0, -1).reduce((sum, attempt) => sum + (measured(attempt.durationMs) ?? 0), 0); + const internal = Math.max(0, sendMs - earlier - privacy); + + const attemptFirst = measured(final?.firstOutputMs); + const requestFirst = measured(row.firstOutputMs); + const wait = attemptFirst ?? (requestFirst !== undefined ? Math.max(0, requestFirst - sendMs) : undefined); + + const parts: TimePart[] = [ + { kind: "privacy", ms: privacy }, + { kind: "internal", ms: internal }, + { kind: "earlier", ms: earlier }, + ...(wait === undefined + ? [{ kind: "reading", ms: Math.max(0, total - sendMs) } satisfies TimePart] + : [ + { kind: "upstreamWait", ms: wait } satisfies TimePart, + { kind: "streaming", ms: Math.max(0, total - sendMs - wait) } satisfies TimePart, + ]), + ]; + const shown = parts.filter(part => part.ms >= MIN_PART_MS); + return shown.length > 0 ? shown : null; +} diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 4c4eb322530..54a64145f9f 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -6,6 +6,7 @@ import { I18nContext, DICTS, interpolate, LOCALES, type Locale, type TFn } from import { FlowDiagram } from "../src/pages/route-live/FlowDiagram"; import { RequestList } from "../src/pages/route-live/RequestList"; import { RouteSteps } from "../src/pages/route-live/RouteSteps"; +import { TimeSection } from "../src/pages/route-live/TimeBar"; import { buildRouteFlow } from "../src/pages/route-live/flow-model"; import { ROUTE_REASONS } from "../src/pages/route-live/route-reasons"; import type { RouteRow } from "../src/pages/route-live/route-rows"; @@ -70,6 +71,22 @@ test("request list groups by session, shows dashes for unknown metrics, and mark expect(grouped.querySelector(".rl-group-head")?.getAttribute("aria-expanded")).toBe("true"); }); +test("time bar lists each measured stage in order with its label, or a note when nothing was recorded", () => { + const [first, last] = failover.attempts!; + const timed = { + ...failover, upstreamSendMs: 1010, privacyRedactionMs: 5, firstOutputMs: 1710, + attempts: [{ ...first!, durationMs: 1000 }, { ...last!, firstOutputMs: 700 }], + } as unknown as RouteRow; + const doc = render(); + expect(doc.querySelector("h4")?.textContent).toBe("时间花在哪里"); + expect([...doc.querySelectorAll(".rl-time-legend li > span:nth-child(2)")].map(s => s.textContent)).toEqual( + ["隐私脱敏", "OpenCodex 内部", "之前的尝试", "等上游第一个字", "流式输出"]); + expect(doc.querySelectorAll(".rl-time-seg").length).toBe(5); + const bare = render(); + expect(bare.querySelector(".rl-time-bar")).toBeNull(); + expect(bare.querySelector("p")?.textContent).toContain("没有记录时间分布"); +}); + test.each(LOCALES)("every reason key the registry points at has copy in $code", ({ code }) => { for (const group of Object.values(ROUTE_REASONS)) { for (const key of Object.values(group)) expect(DICTS[code][key]?.length).toBeGreaterThan(0); diff --git a/gui/tests/route-live-time.test.ts b/gui/tests/route-live-time.test.ts new file mode 100644 index 00000000000..bc95ddb0f6f --- /dev/null +++ b/gui/tests/route-live-time.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test } from "bun:test"; +import { timeParts, type TimeRow } from "../src/pages/route-live/time-parts"; + +const row = (extra: Partial): TimeRow => ({ durationMs: 2000, ...extra }); +const attempt = (extra: object) => ({ provider: "p", model: "m", status: 200, ...extra }); + +describe("timeParts", () => { + test("a normal stream splits into internal, upstream wait and streaming", () => { + expect(timeParts(row({ + upstreamSendMs: 12, firstOutputMs: 812, attempts: [attempt({ durationMs: 1988, firstOutputMs: 800 })], + }))).toEqual([ + { kind: "internal", ms: 12 }, { kind: "upstreamWait", ms: 800 }, { kind: "streaming", ms: 1188 }, + ]); + }); + + test("privacy redaction is its own part and leaves the internal remainder", () => { + const parts = timeParts(row({ + upstreamSendMs: 40, privacyRedactionMs: 25, attempts: [attempt({ durationMs: 1960, firstOutputMs: 500 })], + })); + expect(parts).toEqual([ + { kind: "privacy", ms: 25 }, { kind: "internal", ms: 15 }, { kind: "upstreamWait", ms: 500 }, { kind: "streaming", ms: 1460 }, + ]); + }); + + test("failover: earlier attempts are subtracted from the time before the final attempt", () => { + const parts = timeParts(row({ + durationMs: 3000, upstreamSendMs: 1010, privacyRedactionMs: 5, + attempts: [attempt({ status: 429, durationMs: 1000 }), attempt({ durationMs: 1990, firstOutputMs: 700 })], + })); + expect(parts).toEqual([ + { kind: "privacy", ms: 5 }, { kind: "internal", ms: 5 }, { kind: "earlier", ms: 1000 }, + { kind: "upstreamWait", ms: 700 }, { kind: "streaming", ms: 1290 }, + ]); + }); + + test("a combo row without upstreamSendMs derives the final attempt's start from the two measured durations", () => { + const parts = timeParts(row({ + durationMs: 2500, attempts: [attempt({ status: 503, durationMs: 600 }), attempt({ durationMs: 1800, firstOutputMs: 400 })], + })); + expect(parts).toEqual([ + { kind: "internal", ms: 100 }, { kind: "earlier", ms: 600 }, { kind: "upstreamWait", ms: 400 }, { kind: "streaming", ms: 1400 }, + ]); + }); + + test("with no attempt first output, the request's own firstOutputMs is taken from the send time", () => { + const parts = timeParts(row({ upstreamSendMs: 100, firstOutputMs: 600, attempts: [attempt({ durationMs: 1900 })] })); + expect(parts).toEqual([ + { kind: "internal", ms: 100 }, { kind: "upstreamWait", ms: 500 }, { kind: "streaming", ms: 1400 }, + ]); + }); + + test("a non-streamed reply has no first output, so the rest of the time is one reading part", () => { + expect(timeParts(row({ upstreamSendMs: 30, attempts: [attempt({ durationMs: 1970 })] }))).toEqual([ + { kind: "internal", ms: 30 }, { kind: "reading", ms: 1970 }, + ]); + }); + + test("parts under 0.1 ms are dropped and negatives clamp to zero", () => { + const parts = timeParts(row({ + durationMs: 1000, upstreamSendMs: 0.05, privacyRedactionMs: 3, attempts: [attempt({ durationMs: 999.95, firstOutputMs: 2000 })], + })); + expect(parts).toEqual([{ kind: "privacy", ms: 3 }, { kind: "upstreamWait", ms: 2000 }]); + }); + + test("no usable timing returns null", () => { + expect(timeParts(row({}))).toBeNull(); + expect(timeParts(row({ attempts: [attempt({})] }))).toBeNull(); + expect(timeParts(row({ upstreamSendMs: Number.NaN, attempts: [] }))).toBeNull(); + expect(timeParts(row({ durationMs: Number.NaN, upstreamSendMs: 5 }))).toBeNull(); + expect(timeParts(row({ durationMs: 0, upstreamSendMs: 0, attempts: [attempt({ durationMs: 0 })] }))).toBeNull(); + }); +}); From ed4e7c7ba70a27a0b31f5f0b4ac7de16b15e2c0f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:54:54 -0500 Subject: [PATCH 05/12] fix(gui): name combos, API-key accounts and common route reasons plainly in the live routing view A combo row showed the target it landed on as what the client asked for; it now shows the combo. An API-key account reads as its provider plus a short fingerprint instead of a 33-character digest, and the explicit-provider, alias, rule and native route reasons have plain sentences. --- gui/src/i18n/route-live-copy.ts | 3 +++ gui/src/pages/route-live/RequestList.tsx | 9 +++++---- gui/src/pages/route-live/flow-model.ts | 7 +++---- gui/src/pages/route-live/route-reasons.ts | 6 ++++++ gui/src/pages/route-live/route-rows.ts | 19 +++++++++++++++++++ gui/tests/route-live-model.test.ts | 17 ++++++++++++++++- 6 files changed, 52 insertions(+), 9 deletions(-) diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index 53ffde6b9cb..7475e833f0c 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -86,6 +86,9 @@ const rows = { whyComboToolLoopPin: ["this conversation is in the middle of a tool-call loop, so it stayed on the same target","이 대화는 도구 호출을 이어가는 중이라 같은 대상을 유지했어요","dieses Gespräch steckt mitten in einer Tool-Schleife und blieb beim selben Ziel","cette conversation est en pleine boucle d'outils et est restée sur la même cible","这个对话正在连续调用工具,所以沿用上一次的目标","這個對話正在連續呼叫工具,所以沿用上一次的目標","разговор в разгаре цикла вызовов инструментов, поэтому остался на той же цели","このスレッドはツール呼び出しの途中のため、同じ対象のままにしました","bu konuşma bir araç çağrısı döngüsünün ortasında, bu yüzden aynı hedefte kaldı","cuộc trò chuyện đang trong vòng gọi công cụ nên giữ nguyên đích cũ","esta conversa está no meio de um ciclo de ferramentas, então ficou no mesmo destino"], whyJevSessionPin: ["this session stays on the target it started with","이 세션은 처음 고른 대상을 계속 써요","diese Sitzung bleibt bei dem Ziel, mit dem sie begonnen hat","cette session reste sur la cible choisie au départ","这个会话固定使用最初选中的目标","這個工作階段固定使用最初選中的目標","эта сессия остаётся на цели, выбранной вначале","このセッションは最初に選ばれた対象を使い続けます","bu oturum başladığı hedefte kalıyor","phiên này giữ nguyên đích đã chọn ban đầu","esta sessão continua no destino com que começou"], whyExplicitProvider: ["the model name named this provider","모델 이름에 이 제공자가 적혀 있었어요","der Modellname nannte diesen Anbieter","le nom du modèle désignait ce fournisseur","模型名里写明了这个服务商","模型名稱裡寫明了這個服務商","в названии модели указан этот провайдер","モデル名でこのプロバイダーが指定されていました","model adı bu sağlayıcıyı belirtiyordu","tên mô hình chỉ rõ nhà cung cấp này","o nome do modelo indicava este provedor"], + whyModelAlias: ["the model name is an alias set up for this target","모델 이름이 이 대상에 설정된 별칭이에요","der Modellname ist ein für dieses Ziel angelegter Alias","le nom du modèle est un alias configuré pour cette cible","模型名是给这个目标设的别名","模型名稱是為這個目標設定的別名","имя модели — псевдоним, заданный для этой цели","モデル名がこの宛先用に設定した別名です","model adı bu hedef için tanımlanmış bir takma ad","tên mô hình là bí danh đặt cho đích này","o nome do modelo é um apelido configurado para este destino"], + whyModelPattern: ["the model name matched a routing rule","모델 이름이 라우팅 규칙과 맞았어요","der Modellname passte zu einer Routing-Regel","le nom du modèle correspond à une règle de routage","模型名匹配了一条路由规则","模型名稱符合一條路由規則","имя модели подошло под правило маршрутизации","モデル名がルーティング規則に一致しました","model adı bir yönlendirme kuralıyla eşleşti","tên mô hình khớp một quy tắc định tuyến","o nome do modelo correspondeu a uma regra de roteamento"], + whyNative: ["it is a native model, so it goes straight to its own service","네이티브 모델이라 자기 서비스로 바로 가요","ein natives Modell geht direkt an seinen eigenen Dienst","c'est un modèle natif, il va directement à son propre service","这是原生模型,直接发给它自己的服务","這是原生模型,直接送往它自己的服務","это родная модель, она идёт прямо в свой сервис","ネイティブモデルなので自分のサービスへ直接送ります","yerel bir model, doğrudan kendi hizmetine gider","đây là mô hình gốc nên đi thẳng tới dịch vụ của nó","é um modelo nativo, então vai direto para o próprio serviço"], whyDefaultProvider: ["no provider was named, so the default one was used","제공자가 지정되지 않아 기본 제공자를 썼어요","kein Anbieter genannt, daher wurde der Standard genommen","aucun fournisseur n'était indiqué, le fournisseur par défaut a donc servi","没指定服务商,用了默认的","沒指定服務商,用了預設的","провайдер не указан, использован провайдер по умолчанию","プロバイダーの指定がなかったため、既定のものを使いました","sağlayıcı belirtilmedi, varsayılan kullanıldı","không chỉ định nhà cung cấp nên dùng mặc định","nenhum provedor foi indicado, então foi usado o padrão"], rUnconfigured: ["not set up yet","아직 설정되지 않음","noch nicht eingerichtet","pas encore configuré","还没配置","還沒設定","ещё не настроено","まだ設定されていません","henüz kurulmadı","chưa được thiết lập","ainda não configurado"], rAlreadyAttempted: ["already tried for this request","이 요청에서 이미 시도함","für diese Anfrage schon versucht","déjà essayé pour cette requête","这个请求里已经试过了","這個請求裡已經試過了","уже пробовали для этого запроса","このリクエストでは試行済み","bu istek için zaten denendi","đã thử cho yêu cầu này","já tentado nesta requisição"], diff --git a/gui/src/pages/route-live/RequestList.tsx b/gui/src/pages/route-live/RequestList.tsx index f74b4fa25e3..316fa4b4e8c 100644 --- a/gui/src/pages/route-live/RequestList.tsx +++ b/gui/src/pages/route-live/RequestList.tsx @@ -11,7 +11,7 @@ import type { AccountNames } from "./flow-model"; import { groupRows, type GroupLabel, type GroupMode, type GroupStats } from "./request-groups"; import { formatClock, formatCount, formatDuration, formatPercent, formatRate, shortId } from "./route-format"; import { - cacheHitPercent, costUsdOf, rowAccountLabel, rowKey, servedModelOf, tokPerSecondOf, tokenTotal, type RouteRow, + cacheHitPercent, costUsdOf, readableAccountLabel, requestedOf, rowAccountLabel, servingProviderOf, rowKey, servedModelOf, tokPerSecondOf, tokenTotal, type RouteRow, } from "./route-rows"; import "./route-live.css"; @@ -44,8 +44,9 @@ function effortText(row: RouteRow): string { function whoText(row: RouteRow, names: AccountNames): string { const label = rowAccountLabel(row); - const provider = row.accountRoster?.provider ?? row.provider; - return (label && (names[provider]?.[label] ?? names[row.provider]?.[label])) ?? label ?? row.provider; + const provider = row.accountRoster?.provider ?? servingProviderOf(row); + const named = label ? names[provider]?.[label] ?? names[row.provider]?.[label] : undefined; + return named ?? (label ? readableAccountLabel(label, servingProviderOf(row)) : servingProviderOf(row)); } function GroupHead({ label, stats, open, onToggle, localeTag }: { @@ -82,7 +83,7 @@ function RequestRow({ row, pinned, names, localeTag, onPin }: { {formatClock(row.timestamp, localeTag)} - {row.requestedAlias ?? row.requestedModel ?? row.model} + {requestedOf(row)} {whoText(row, names)} diff --git a/gui/src/pages/route-live/flow-model.ts b/gui/src/pages/route-live/flow-model.ts index e85c0373ebc..5c8c4fbf841 100644 --- a/gui/src/pages/route-live/flow-model.ts +++ b/gui/src/pages/route-live/flow-model.ts @@ -2,7 +2,7 @@ * Pure flow view model for one request row: who was asked, who answered, who was skipped and why. * No React, no i18n: reasons stay codes and `route-reasons.ts` owns the wording. */ -import { rowAccountLabel, type RouteRoster, type RouteRow } from "./route-rows"; +import { readableAccountLabel, requestedOf, rowAccountLabel, type RouteRoster, type RouteRow } from "./route-rows"; export type FlowStatus = "answered" | "failed" | "skipped" | "idle"; @@ -39,7 +39,7 @@ const NUL = String.fromCharCode(0); const pm = (provider: string, model: string) => `${provider}${NUL}${model}`; export function candidateWho(c: FlowCandidate): string { - return c.displayName ?? c.accountLabel ?? c.provider; + return c.displayName ?? (c.accountLabel ? readableAccountLabel(c.accountLabel, c.provider) : c.provider); } export function buildRouteFlow(row: RouteRow, names: AccountNames = {}): RouteFlow { @@ -104,8 +104,7 @@ export function buildRouteFlow(row: RouteRow, names: AccountNames = {}): RouteFl return { client: { value: row.client, ...(row.surface ? { surface: row.surface } : {}) }, requested: { - model: row.requestedModel ?? row.model, - ...(row.requestedAlias ? { alias: row.requestedAlias } : {}), + model: requestedOf(row), }, candidates, outcome, diff --git a/gui/src/pages/route-live/route-reasons.ts b/gui/src/pages/route-live/route-reasons.ts index 518e499cd91..2fc38e5b1b2 100644 --- a/gui/src/pages/route-live/route-reasons.ts +++ b/gui/src/pages/route-live/route-reasons.ts @@ -51,6 +51,12 @@ export const ROUTE_REASONS: Record>> = "jev-session-pin": "routeLive.whyJevSessionPin", "explicit-provider": "routeLive.whyExplicitProvider", "default-provider": "routeLive.whyDefaultProvider", + "explicit-provider-namespace": "routeLive.whyExplicitProvider", + "explicit-account": "routeLive.whyExplicitProvider", + "model-alias": "routeLive.whyModelAlias", + "model-pattern": "routeLive.whyModelPattern", + "native": "routeLive.whyNative", + "native-family": "routeLive.whyNative", }, }; diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts index cd03e74a876..f0358ddcbc9 100644 --- a/gui/src/pages/route-live/route-rows.ts +++ b/gui/src/pages/route-live/route-rows.ts @@ -135,6 +135,25 @@ export function rowAccountLabel(row: RouteRow): string | undefined { return row.accountLogLabel ?? row.accountTag ?? last?.accountLogLabel ?? last?.accountTag; } +const KEY_ACCOUNT_LABEL_RE = /^k[0-9a-f]{32}$/; + +/** An API-key account label is a 32-hex digest; show it as its provider plus a short fingerprint. */ +export function readableAccountLabel(label: string, provider: string): string { + return KEY_ACCOUNT_LABEL_RE.test(label) ? `${provider} #${label.slice(1, 7)}` : label; +} + +/** A combo row's own provider is "combo"; the account belongs to the provider of the final attempt. */ +export function servingProviderOf(row: RouteRow): string { + return row.attempts?.at(-1)?.provider ?? row.provider; +} + +/** What the client asked for. A combo row's alias names the target it landed on, not the combo. */ +export function requestedOf(row: RouteRow): string { + return row.routeDecision?.routeKind === "combo" + ? row.requestedModel ?? row.model + : row.requestedAlias ?? row.requestedModel ?? row.model; +} + export function servedModelOf(row: RouteRow): string { return row.servedModel ?? row.resolvedModel ?? row.model; } diff --git a/gui/tests/route-live-model.test.ts b/gui/tests/route-live-model.test.ts index add57d26172..3ee6048822e 100644 --- a/gui/tests/route-live-model.test.ts +++ b/gui/tests/route-live-model.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { buildRouteFlow, buildRouteSteps, summarizePool } from "../src/pages/route-live/flow-model"; import { groupRows } from "../src/pages/route-live/request-groups"; -import { cacheHitPercent, parseRouteRows, type RouteRow } from "../src/pages/route-live/route-rows"; +import { cacheHitPercent, parseRouteRows, readableAccountLabel, requestedOf, type RouteRow } from "../src/pages/route-live/route-rows"; const base = { timestamp: 1000, model: "m", provider: "p", status: 200, durationMs: 900 }; const row = (extra: Partial): RouteRow => ({ ...base, ...extra } as RouteRow); @@ -90,3 +90,18 @@ describe("route rows and groups", () => { { kind: "key", id: "k1" }, { kind: "admission", admission: "loopback" }]); }); }); + +describe("what the page names", () => { + test("a combo row shows the combo the client asked for, not the alias of the target it landed on", () => { + const combo = row({ model: "combo/steady", requestedModel: "combo/steady", requestedAlias: "mock-b/deepseek-chat", + routeDecision: { routeKind: "combo" } } as Partial); + expect(requestedOf(combo)).toBe("combo/steady"); + expect(buildRouteFlow(combo).requested.model).toBe("combo/steady"); + expect(requestedOf(row({ requestedModel: "claude-sonnet", requestedAlias: "sonnet" } as Partial))).toBe("sonnet"); + }); + + test("an API-key account digest reads as its provider plus a short fingerprint", () => { + expect(readableAccountLabel(`k${"6a46ff".padEnd(32, "0")}`, "mock-a")).toBe("mock-a #6a46ff"); + expect(readableAccountLabel("o1a2b3c", "xai")).toBe("o1a2b3c"); + }); +}); From 3fc3e6c519ed19aaa6ef4924eafbde8f2dd1eabb Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:57:12 -0500 Subject: [PATCH 06/12] fix(gui): an unused candidate says 'not needed' once, not twice --- gui/src/pages/route-live/FlowDiagram.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/gui/src/pages/route-live/FlowDiagram.tsx b/gui/src/pages/route-live/FlowDiagram.tsx index 0678fd527c4..7ea3751bb8a 100644 --- a/gui/src/pages/route-live/FlowDiagram.tsx +++ b/gui/src/pages/route-live/FlowDiagram.tsx @@ -23,8 +23,6 @@ function CandidateDetail({ candidate, localeTag }: { candidate: FlowCandidate; l parts.push(); } else if (candidate.status === "skipped" && candidate.reasonCode) { parts.push(); - } else if (candidate.status === "idle") { - parts.push(t(STATUS_TKEY.idle)); } if (candidate.status !== "skipped" && candidate.status !== "idle") { if (candidate.ttftMs !== undefined) parts.push(`${t("routeLive.colTtft")} ${formatDuration(candidate.ttftMs, localeTag)}`); From c2d6c4aebf6deeaa15540cc07695d866222c4ac2 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:58:23 -0500 Subject: [PATCH 07/12] =?UTF-8?q?docs(routing):=20describe=20the=20Models?= =?UTF-8?q?=20=E2=80=BA=20Live=20routing=20tab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/content/docs/guides/model-routing.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index 87e3ca11777..467cbcdc09e 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -152,6 +152,23 @@ Routing and catalog visibility are separate controls: } ``` +## Watching routing live + +The dashboard's **Models › Live routing** tab (`#models/live`) shows how each request was routed, +refreshing every few seconds while the tab is open. For the latest request, or one you select in +the list below it, you see: + +- **The route.** The client, then OpenCodex, then every candidate: the account or combo target that + answered, the ones that failed (with the HTTP status and the reason), and the ones that were + skipped before any send. A multi-account OAuth pool shows each account's state when the request + finished: paused, needing sign-in, cooling down, out of quota, or not listing the model. +- **Where the time went.** OpenCodex's own time, earlier failed attempts, the wait for the first + token, and streaming. Every segment is measured; DNS and TLS are not split out. + +The request list groups by request, session or API key and shows the account, model, effort, +duration, time to first token, tokens, cache-hit rate, tokens per second and estimated cost. +Combos and accounts keep their own pages; the tab links to them. + ## Tips - **Target a Codex account explicitly** with `/` (rule 1). That route From 483ae3cc33b5ccf0a40e18085f1edc25d0017f00 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:13:04 -0500 Subject: [PATCH 08/12] fix(gui): translate the live-routing labels French was still showing in English --- gui/src/i18n/route-live-copy.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index 7475e833f0c..d9c76eb8010 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -42,7 +42,7 @@ const rows = { modeSession: ["By session","세션별","Nach Sitzung","Par session","按会话","按工作階段","По сессиям","セッション別","Oturuma göre","Theo phiên","Por sessão"], modeKey: ["By key","키별","Nach Schlüssel","Par clé","按密钥","按金鑰","По ключам","キー別","Anahtara göre","Theo khóa","Por chave"], groupNoSession: ["No session ID","세션 ID 없음","Keine Sitzungs-ID","Sans ID de session","无会话 ID","無工作階段 ID","Без ID сессии","セッション ID なし","Oturum kimliği yok","Không có ID phiên","Sem ID de sessão"], - groupSession: ["Session {id}","세션 {id}","Sitzung {id}","Session {id}","会话 {id}","工作階段 {id}","Сессия {id}","セッション {id}","Oturum {id}","Phiên {id}","Sessão {id}"], + groupSession: ["Session {id}","세션 {id}","Sitzung {id}","Séance {id}","会话 {id}","工作階段 {id}","Сессия {id}","セッション {id}","Oturum {id}","Phiên {id}","Sessão {id}"], groupKey: ["Key {id}","키 {id}","Schlüssel {id}","Clé {id}","密钥 {id}","金鑰 {id}","Ключ {id}","キー {id}","Anahtar {id}","Khóa {id}","Chave {id}"], admLoopback: ["This computer (loopback)","이 컴퓨터 (loopback)","Dieser Computer (Loopback)","Cet ordinateur (loopback)","本机 (loopback)","本機 (loopback)","Этот компьютер (loopback)","このコンピューター (loopback)","Bu bilgisayar (loopback)","Máy này (loopback)","Este computador (loopback)"], admEnvironment: ["Environment key","환경 변수 키","Umgebungsschlüssel","Clé d’environnement","环境变量密钥","環境變數金鑰","Ключ из окружения","環境変数のキー","Ortam anahtarı","Khóa môi trường","Chave de ambiente"], @@ -54,7 +54,7 @@ const rows = { rowHint: ["Select a request to pin it above. Esc goes back to the latest.","요청을 선택하면 위에 고정돼요. Esc를 누르면 최근 요청으로 돌아가요.","Anfrage wählen, um sie oben festzuhalten. Esc springt zur neuesten zurück.","Sélectionnez une requête pour l’épingler en haut. Échap revient à la dernière.","点一个请求就会固定显示在上方。按 Esc 回到最新。","點一個請求就會固定顯示在上方。按 Esc 回到最新。","Выберите запрос, чтобы закрепить его вверху. Esc возвращает к последнему.","リクエストを選ぶと上に固定されます。Esc で最新に戻ります。","Bir isteği seçerek yukarıya sabitleyin. Esc en yeniye döner.","Chọn một yêu cầu để ghim lên trên. Nhấn Esc để về yêu cầu mới nhất.","Selecione uma requisição para fixá-la acima. Esc volta à mais recente."], colTime: ["Time","시간","Zeit","Heure","时间","時間","Время","時刻","Zaman","Thời gian","Hora"], colAccount: ["Account","계정","Konto","Compte","账号","帳號","Аккаунт","アカウント","Hesap","Tài khoản","Conta"], - colEffort: ["Effort","추론 강도","Aufwand","Effort","思考强度","思考強度","Усилие","推論強度","Efor","Mức suy luận","Esforço"], + colEffort: ["Effort","추론 강도","Aufwand","Niveau de réflexion","思考强度","思考強度","Усилие","推論強度","Efor","Mức suy luận","Esforço"], colDuration: ["Duration","소요 시간","Dauer","Durée","用时","用時","Время","所要時間","Süre","Thời lượng","Duração"], colTtft: ["First token","첫 토큰","Erstes Token","Premier jeton","首字","首字","Первый токен","最初のトークン","İlk token","Token đầu","Primeiro token"], colCache: ["Cache hit","캐시 적중","Cache-Treffer","Cache","缓存命中","快取命中","Кэш","キャッシュ","Önbellek","Cache","Cache"], @@ -74,9 +74,9 @@ const rows = { fServer: ["provider error","제공자 오류","Anbieterfehler","erreur du fournisseur","服务商出错","服務商出錯","ошибка провайдера","プロバイダーのエラー","sağlayıcı hatası","lỗi nhà cung cấp","erro do provedor"], fOverloaded: ["provider overloaded","제공자 과부하","Anbieter überlastet","fournisseur surchargé","服务商繁忙","服務商繁忙","провайдер перегружен","プロバイダーが混雑","sağlayıcı aşırı yüklü","nhà cung cấp quá tải","provedor sobrecarregado"], fCancelled: ["cancelled","취소됨","abgebrochen","annulé","已取消","已取消","отменено","キャンセル","iptal edildi","đã hủy","cancelado"], - colClient: ["Client","클라이언트","Client","Client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente"], + colClient: ["Client","클라이언트","Client","Logiciel client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente"], colModel: ["Model","모델","Modell","Modèle","模型","模型","Модель","モデル","Model","Mô hình","Modelo"], - colTokens: ["Tokens","토큰","Tokens","Tokens","Tokens","Tokens","Токены","トークン","Token","Token","Tokens"], + colTokens: ["Tokens","토큰","Tokens","Jetons","Tokens","Tokens","Токены","トークン","Token","Token","Tokens"], colRate: ["Speed","속도","Tempo","Vitesse","速度","速度","Скорость","速度","Hız","Tốc độ","Velocidade"], colCost: ["Cost","비용","Kosten","Coût","费用","費用","Стоимость","コスト","Maliyet","Chi phí","Custo"], colStatus: ["Status","상태","Status","Statut","状态","狀態","Статус","状態","Durum","Trạng thái","Status"], From 2d56dad2eddf9e788847ef38cf261bc214c4c2b7 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:42:34 -0500 Subject: [PATCH 09/12] feat(routing): measure how a request's context window is spent, as sizes only At the Responses, Messages and Chat Completions entry points the client body is walked once and its estimated tokens are split into system prompt, tools, skills, memory files (CLAUDE.md, AGENTS.md), files, tool results and per-turn conversation, following Magpie's classifier (MIT, yetone). Only numbers are kept; no prompt text is retained. The final in-memory request row carries the breakdown and the serving model's context window. --- scripts/test-layout/layout-usage.json | 2 + src/server/chat-completions.ts | 2 + src/server/claude-messages.ts | 2 + src/server/context-breakdown-classify.ts | 407 ++++++++++++++++++ src/server/context-breakdown.ts | 307 +++++++++++++ src/server/request-log-route-live.ts | 34 ++ src/server/request-log.ts | 7 +- src/server/responses/request-prepare.ts | 2 + tests/fixtures/test-layout-expected.json | 2 +- tests/usage/context-breakdown.test.ts | 340 +++++++++++++++ .../request-log-context-breakdown.test.ts | 66 +++ 11 files changed, 1167 insertions(+), 4 deletions(-) create mode 100644 src/server/context-breakdown-classify.ts create mode 100644 src/server/context-breakdown.ts create mode 100644 tests/usage/context-breakdown.test.ts create mode 100644 tests/usage/request-log-context-breakdown.test.ts diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index 207ba3725f5..5e89621e913 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -5,6 +5,8 @@ "request-log.test.ts": "usage", "request-log-account-roster.test.ts": "usage", "request-log-route-live-timing.test.ts": "usage", + "request-log-context-breakdown.test.ts": "usage", + "context-breakdown.test.ts": "usage", "oauth-accounts-log-label.test.ts": "oauth", "request-log-normalization.test.ts": "usage", "request-log-error-detail.test.ts": "usage", diff --git a/src/server/chat-completions.ts b/src/server/chat-completions.ts index 44691c9e57d..6cc1cc0afa7 100644 --- a/src/server/chat-completions.ts +++ b/src/server/chat-completions.ts @@ -61,6 +61,7 @@ import { linkRequestSessionLane, } from "./request-log-conversation"; import type { OcxConfig } from "../types"; +import { observeContextBreakdown } from "./context-breakdown"; import { DecompressedBodyTooLargeError, UnsupportedContentEncodingError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; import { addFinalRequestLog, @@ -206,6 +207,7 @@ async function handleChatCompletionsWithBudget( try { const rawBody = await readChatBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes)); assertChatCompletionsRoutingBody(rawBody); + observeContextBreakdown(logCtx, rawBody, "chat"); // Normalize foreign image shapes BEFORE routing. isNativeChatRouteEligible below // decides the pipeline from the image parts it can see, and the native path then // forwards this body as-is, so both must observe the same parts. A body with no diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 790493cac42..2f56e232ec7 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -84,6 +84,7 @@ import { evidenceFromBody } from "../routing/request-evidence"; import { resolveWireProtocolOverride } from "./adapter-resolve"; import type { OcxConfig } from "../types"; import { readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; +import { observeContextBreakdown } from "./context-breakdown"; import { addFinalRequestLog, httpStatusForRequestLogTerminal, recordFirstOutput, type RequestLogContext } from "./request-log"; import { createFinalRequestLog } from "./inference/final-log"; import { @@ -677,6 +678,7 @@ async function handleClaudeMessagesWithBudget( const advisorAdmissionPolicy = logIds?.advisorAdmissionPolicy ?? captureAdmissionPolicy(config, logIds?.admission); try { anthropicBody = await readAnthropicBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes)); + observeContextBreakdown(logCtx, anthropicBody, "messages"); clientModelLabel = clientFacingModelLabel(isRec(anthropicBody) ? anthropicBody.model : undefined); // Defensive [1m] strip (devlog 138): clients normally remove the context-variant // marker themselves; the 1M signal we act on is the anthropic-beta header. diff --git a/src/server/context-breakdown-classify.ts b/src/server/context-breakdown-classify.ts new file mode 100644 index 00000000000..563231a62e0 --- /dev/null +++ b/src/server/context-breakdown-classify.ts @@ -0,0 +1,407 @@ +/** + * Context-window classifier: sizes only, never content. + * + * The marker strings, regexes and file-read detection below are ported from Magpie's prompt + * classifier (internal/gateway/prompt.go), reduced to per-category totals and per-turn totals. + * + * Magpie is MIT licensed: + * + * MIT License + * + * Copyright (c) 2026 yetone + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** Estimated tokens per category for a request as received from the client. */ +export interface ContextBreakdownV1 { + v: 1; + parts: { system: number; tools: number; skills: number; memory: number; files: number; results: number; chat: number }; + /** Estimated tokens per conversation turn, oldest first; at most 48 entries. */ + turns: number[]; + /** Older turns beyond the 48 kept, plus any compaction summary, summed. */ + turnsEarlier?: number; + /** Number of tool definitions. */ + toolCount: number; + /** `previous_response_id` was set: earlier turns live upstream and are not in the body. */ + held?: true; +} + +export type Rec = Record; + +export function isRec(v: unknown): v is Rec { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +export function str(v: unknown): string { + return typeof v === "string" ? v : ""; +} + +const MAX_TURNS = 48; +/** What an image or document is taken to cost: about a 1092x1092 image on Anthropic. */ +export const IMAGE_TOKENS = 1600; +/** A call's arguments are parsed for a file read only when short enough to be a path or command. */ +const MAX_ARGS_PARSE = 8192; +const MAX_JSON_DEPTH = 24; + +/** About four ASCII characters a token, one token per other character (CJK, mostly). */ +export function tokensOfText(s: string): number { + let ascii = 0; + let other = 0; + for (let i = 0; i < s.length; i++) { + const c = s.charCodeAt(i); + if (c < 128) { + ascii++; + continue; + } + other++; + if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) { + const d = s.charCodeAt(i + 1); + if (d >= 0xdc00 && d <= 0xdfff) i++; + } + } + return Math.ceil(ascii / 4) + other; +} + +/** A string of serialized JSON or call arguments: length over four, no scan. */ +export function tokensOfBlob(s: string): number { + return Math.ceil(s.length / 4); +} + +function jsonChars(v: unknown, depth: number): number { + switch (typeof v) { + case "string": + return v.length + 2; + case "number": + return 5; + case "boolean": + return 5; + case "object": { + if (v === null) return 4; + if (depth >= MAX_JSON_DEPTH) return 8; + let n = 2; + if (Array.isArray(v)) { + for (let i = 0; i < v.length; i++) n += jsonChars(v[i], depth + 1) + 1; + return n; + } + for (const k in v as Rec) n += k.length + 4 + jsonChars((v as Rec)[k], depth + 1); + return n; + } + default: + return 0; + } +} + +/** Serialized size of a parsed JSON value over four, without serializing it. */ +export function tokensOfJson(v: unknown): number { + return Math.ceil(jsonChars(v, 0) / 4); +} + +// --- text: instruction files, skills, reminders, harness messages --- + +/** Claude Code: "Contents of /path/CLAUDE.md (project instructions, ...):" */ +const CONTENTS_OF = /^Contents of (\S.*?) \(([^()\n]*(?:\([^()\n]*\)[^()\n]*)*)\):[ \t]*$/gm; +/** OpenCode: "Instructions from: /path/AGENTS.md" */ +const INSTRUCTIONS_FROM = /^Instructions from: (\S.*?)[ \t]*$/gm; +/** Codex: "# AGENTS.md instructions for /path" */ +const AGENTS_FOR = /^# (\S+\.md) instructions for (\S.*?)[ \t]*\n/; +const SKILLS_LIST = "The following skills are available for use with the Skill tool:"; +const REMINDER_OPEN = ""; +const REMINDER_CLOSE = ""; +const REMINDERS = /]*)?>[\s\S]*?<\/system-reminder>/g; +/** What the user typed in the Codex app, after the context it puts first. */ +const MY_REQUEST = /^## My request(?: for Codex)?:[ \t]*\n?/gm; +const HARNESS_USER_LEADS = ["", "", "", ""]; +/** How a text the agent put in as the user begins; none of these is the user speaking. */ +const INJECTED_LEADS = [ + "", "", "", + "", "", "", "", "", "", + "Available agent types for the Agent tool:", "Available agent types and the tools they have access to:", + "New agent types are now available for the Agent tool:", + "The TodoWrite tool hasn't been used recently.", "The task tools haven't been used recently.", + "Conversation rewind applied.", "Workspace rewind applied.", +]; + +function trimLeftNewlines(s: string): string { + let i = 0; + while (i < s.length && s.charCodeAt(i) === 10) i++; + return i === 0 ? s : s.slice(i); +} + +/** True when the text is the user speaking, not something the agent injected for the model. */ +export function userSays(text: string): boolean { + let t = text; + if (t.includes("= 0) t = t.slice(end).trim(); + } + if (t === "" || AGENTS_FOR.test(t)) return false; + for (const lead of INJECTED_LEADS) if (t.startsWith(lead)) return false; + return true; +} + +// --- tool calls and what they read --- + +const READ_TOOLS = new Set(["Read", "read", "read_file", "ReadFile", "view", "View", "NotebookRead", "readFile", "open_file", "cat"]); +const PATH_KEYS = ["file_path", "path", "filePath", "target_file", "notebook_path", "file", "filename", "uri"]; +const READ_COMMANDS = new Set(["cat", "head", "tail", "nl", "bat", "less", "more"]); +const SHELL_WRAPPERS = ["bash -lc ", "bash -c ", "sh -c ", "zsh -lc "]; +const SHELL_OPERATORS = /[|;&><`$]/; +/** Codex's exec takes JavaScript: text(await tools.exec_command({cmd:"cat x"})). */ +const CMD_OF_EXEC = /\bcmd\s*:\s*"((?:[^"\\]|\\.)*)"/; + +function trimQuotes(s: string): string { + let a = 0; + let b = s.length; + while (a < b && (s[a] === '"' || s[a] === "'")) a++; + while (b > a && (s[b - 1] === '"' || s[b - 1] === "'")) b--; + return s.slice(a, b); +} + +/** The files a shell command reads, when all it does is read files: cat, head, tail, nl, bat, sed -n. */ +function filesOfCommand(command: string): string[] { + let cmd = command.trim(); + for (const pre of SHELL_WRAPPERS) { + if (cmd.startsWith(pre)) cmd = trimQuotes(cmd.slice(pre.length).trim()); + } + if (SHELL_OPERATORS.test(cmd)) { + const i = cmd.indexOf("&&"); + if (i >= 0 && cmd.startsWith("cd ") && !SHELL_OPERATORS.test(cmd.slice(i + 2))) cmd = cmd.slice(i + 2).trim(); + else return []; + } + const f = cmd.split(/\s+/).filter(Boolean); + if (f.length < 2) return []; + const head = f[0] ?? ""; + const sed = head === "sed" && f.includes("-n"); + if (!READ_COMMANDS.has(head) && !sed) return []; + const files: string[] = []; + for (let i = 1; i < f.length; i++) { + const a = trimQuotes(f[i] ?? ""); + if (a.startsWith("-")) { + if ((a === "-n" || a === "-c") && !sed && i + 1 < f.length) i++; + continue; + } + if (sed && a.endsWith("p") && /[0-9,]/.test(a) && !a.includes("/") && !a.includes(".")) continue; + if (/^[+-]?\d+$/.test(a)) continue; + files.push(a); + } + return files; +} + +/** Whether a tool call reads files, from its name and input (a parsed object or a JSON/JS string). */ +export function callReadsFiles(name: string, input: unknown): boolean { + let args: Rec | undefined; + let source = ""; + if (typeof input === "string") { + source = input; + if (input.length <= MAX_ARGS_PARSE && /^\s*\{/.test(input)) { + try { + const parsed: unknown = JSON.parse(input); + if (isRec(parsed)) args = parsed; + } catch { + // custom tool input is plain text or JavaScript + } + } + } else if (isRec(input)) { + args = input; + } + if (args && READ_TOOLS.has(name)) { + for (const k of PATH_KEYS) if (str(args[k]) !== "") return true; + } + let cmd = ""; + if (args) { + cmd = str(args.command) || str(args.cmd); + if (cmd === "" && Array.isArray(args.command) && args.command.every(x => typeof x === "string")) { + cmd = (args.command as string[]).join(" "); + } + } else if (source !== "" && source.length <= MAX_ARGS_PARSE) { + const m = CMD_OF_EXEC.exec(source); + if (m?.[1] !== undefined) { + try { + cmd = str(JSON.parse(`"${m[1]}"`)); + } catch { + cmd = m[1]; + } + } + } + return cmd !== "" && filesOfCommand(cmd).length > 0; +} + +// --- the accumulator --- + +/** + * Sums a request's token estimate by category and by turn. It holds numbers and the ids of + * file-reading calls (to class their results); no text outlives a call into it. + */ +export class BreakdownAccumulator { + system = 0; + tools = 0; + skills = 0; + memory = 0; + files = 0; + results = 0; + chatTotal = 0; + toolCount = 0; + held = false; + private compaction = 0; + private turn = 0; + private readonly turns: number[] = []; + private readonly readCalls = new Set(); + + newTurn(): void { + this.turn++; + } + + /** What the user and the model said, and the model's calls, on the current turn. */ + chat(tokens: number): void { + if (tokens <= 0) return; + if (this.turn === 0) this.turn = 1; + while (this.turns.length < this.turn) this.turns.push(0); + this.turns[this.turn - 1]! += tokens; + this.chatTotal += tokens; + } + + compacted(tokens: number): void { + if (tokens <= 0) return; + this.compaction += tokens; + this.chatTotal += tokens; + } + + tool(tokens: number, count = 1): void { + this.tools += tokens; + this.toolCount += count; + } + + noteCall(id: string, name: string, input: unknown): void { + if (id !== "" && callReadsFiles(name, input)) this.readCalls.add(id); + } + + /** What a tool answered: a file it read, or its other output. */ + result(callId: string, tokens: number): void { + if (tokens <= 0) return; + if (this.readCalls.has(callId)) this.files += tokens; + else this.results += tokens; + } + + file(tokens: number): void { + this.files += tokens; + } + + /** The agent's own prompt, with instruction files and the skills list taken out. */ + systemText(text: string): void { + const rest = this.splitSkills(this.splitMemory(text)); + if (rest.trim().startsWith("")) { + this.skills += tokensOfText(rest); + return; + } + if (rest.trim() === "") return; + this.system += tokensOfText(rest); + } + + /** A user's text: an instruction file or reminder the agent put in as the user, or what the user said. */ + userText(text: string): void { + const t = text.trim(); + if (t.startsWith(REMINDER_OPEN)) { + let rest = this.splitSkills(this.splitMemory(t)).trim(); + if (rest.startsWith(REMINDER_OPEN)) rest = rest.slice(REMINDER_OPEN.length); + if (rest.endsWith(REMINDER_CLOSE)) rest = rest.slice(0, rest.length - REMINDER_CLOSE.length); + rest = rest.trim(); + if (rest !== "") this.memory += tokensOfText(rest); + return; + } + if (AGENTS_FOR.test(t)) { + this.memory += tokensOfText(t); + return; + } + for (const lead of HARNESS_USER_LEADS) { + if (t.startsWith(lead)) { + this.system += tokensOfText(t); + return; + } + } + this.chat(tokensOfText(text)); + } + + private splitMemory(text: string): string { + if (!text.includes("Contents of ") && !text.includes("Instructions from: ")) return text; + const at: number[] = []; + for (const m of text.matchAll(CONTENTS_OF)) at.push(m.index); + for (const m of text.matchAll(INSTRUCTIONS_FROM)) at.push(m.index); + if (at.length === 0) return text; + at.sort((a, b) => a - b); + let rest = text.slice(0, at[0]); + for (let i = 0; i < at.length; i++) { + const end = i + 1 < at.length ? at[i + 1]! : text.length; + let chunk = text.slice(at[i], end); + // a reminder's closing tag and what follows it aren't the file's + const j = chunk.indexOf(REMINDER_CLOSE); + if (j >= 0) { + rest += chunk.slice(j); + chunk = chunk.slice(0, j); + } + this.memory += tokensOfText(chunk); + } + return rest; + } + + /** The skills list runs from its heading to the next blank line. */ + private splitSkills(text: string): string { + const at = text.indexOf(SKILLS_LIST); + if (at < 0) return text; + const items = trimLeftNewlines(text.slice(at + SKILLS_LIST.length)); + let end = text.length; + const j = items.indexOf("\n\n"); + if (j >= 0) end -= items.length - j; + this.skills += tokensOfText(text.slice(at, end)); + return text.slice(0, at) + trimLeftNewlines(text.slice(end)); + } + + finish(): ContextBreakdownV1 | undefined { + const total = this.system + this.tools + this.skills + this.memory + this.files + this.results + this.chatTotal; + if (total === 0 && this.toolCount === 0 && !this.held) return undefined; + let turns = this.turns; + let earlier = this.compaction; + if (turns.length > MAX_TURNS) { + const cut = turns.length - MAX_TURNS; + for (let i = 0; i < cut; i++) earlier += turns[i]!; + turns = turns.slice(cut); + } + return { + v: 1, + parts: { + system: this.system, + tools: this.tools, + skills: this.skills, + memory: this.memory, + files: this.files, + results: this.results, + chat: this.chatTotal, + }, + turns, + ...(earlier > 0 ? { turnsEarlier: earlier } : {}), + toolCount: this.toolCount, + ...(this.held ? { held: true as const } : {}), + }; + } +} diff --git a/src/server/context-breakdown.ts b/src/server/context-breakdown.ts new file mode 100644 index 00000000000..f28982bf7b7 --- /dev/null +++ b/src/server/context-breakdown.ts @@ -0,0 +1,307 @@ +/** + * Where a request's context window goes, per category and per turn, as numbers only. + * + * Read from the body as the client sent it (Responses, Anthropic Messages or Chat Completions), + * once per request, in one pass with no serialization of anything large. The result carries no + * text: an instruction file, a tool result or a user message contributes its size and is dropped. + * It must never throw into the request path, so every failure is `undefined`. + * + * The category rules come from Magpie's prompt classifier, MIT licensed, Copyright (c) 2026 + * yetone; the full notice is in context-breakdown-classify.ts, which holds the ported markers. + */ +import { + BreakdownAccumulator, + IMAGE_TOKENS, + isRec, + str, + tokensOfBlob, + tokensOfJson, + tokensOfText, + userSays, + type ContextBreakdownV1, + type Rec, +} from "./context-breakdown-classify"; + +export type { ContextBreakdownV1 } from "./context-breakdown-classify"; + +export type ContextBreakdownWire = "responses" | "messages" | "chat"; + +export function measureContextBreakdown(body: unknown, wire: ContextBreakdownWire): ContextBreakdownV1 | undefined { + try { + if (!isRec(body)) return undefined; + const acc = new BreakdownAccumulator(); + if (wire === "responses") readResponses(acc, body); + else if (wire === "messages") readMessages(acc, body); + else if (wire === "chat") readChat(acc, body); + else return undefined; + return acc.finish(); + } catch { + return undefined; + } +} + +/** Anything that carries the breakdown for a request: the request log context. */ +export interface ContextBreakdownCarrier { + contextBreakdown?: ContextBreakdownV1; +} + +/** First observer wins: a translated replay through another entry keeps the client's own reading. */ +export function observeContextBreakdown(carrier: ContextBreakdownCarrier, body: unknown, wire: ContextBreakdownWire): void { + if (carrier.contextBreakdown !== undefined) return; + const measured = measureContextBreakdown(body, wire); + if (measured) carrier.contextBreakdown = measured; +} + +// --- Anthropic Messages --- + +/** Content that is a string or a list of blocks, as blocks. */ +function blocksOf(c: unknown): Rec[] { + if (typeof c === "string") return [{ type: "text", text: c }]; + if (!Array.isArray(c)) return []; + return c.filter(isRec); +} + +function readMessages(acc: BreakdownAccumulator, body: Rec): void { + for (const s of blocksOf(body.system)) { + const text = str(s.text); + if (text.startsWith("x-anthropic-billing-header")) acc.system += tokensOfText(text); + else if (text !== "") acc.systemText(text); + } + if (Array.isArray(body.tools)) for (const t of body.tools) acc.tool(tokensOfJson(t)); + if (!Array.isArray(body.messages)) return; + for (const m of body.messages) { + if (!isRec(m)) continue; + const role = str(m.role); + const blocks = blocksOf(m.content); + if (role === "system" || role === "developer") { + for (const x of blocks) { + const text = str(x.text); + if (text !== "") acc.systemText(text); + } + continue; + } + if (role === "user") { + // a message that answers tool calls goes on with the turn; one where the user says something begins one + const answersCalls = blocks.some(x => x.type === "tool_result"); + if (!answersCalls && blocks.some(x => x.type === "text" && userSays(str(x.text)))) acc.newTurn(); + } + for (const x of blocks) messagesBlock(acc, role, x); + } +} + +function messagesBlock(acc: BreakdownAccumulator, role: string, x: Rec): void { + switch (x.type) { + case "text": + if (role === "user") acc.userText(str(x.text)); + else acc.chat(tokensOfText(str(x.text))); + return; + case "thinking": + acc.chat(tokensOfText(str(x.thinking))); + return; + case "redacted_thinking": + acc.chat(Math.floor(tokensOfBlob(str(x.data)) / 4)); + return; + case "tool_use": + case "server_tool_use": + acc.noteCall(str(x.id), str(x.name), x.input); + acc.chat(tokensOfText(str(x.name)) + tokensOfJson(x.input)); + return; + case "tool_result": + case "web_search_tool_result": + case "web_fetch_tool_result": + acc.result(str(x.tool_use_id), messagesResultTokens(acc, x.content)); + return; + case "image": + case "document": + if (x.type === "document" && isRec(x.source) && x.source.type !== "base64") acc.file(tokensOfJson(x.source)); + else acc.file(IMAGE_TOKENS); + return; + case "compaction": + acc.compacted(tokensOfJson(x)); + return; + default: + acc.chat(typeof x.text === "string" ? tokensOfText(x.text) : tokensOfJson(x)); + } +} + +/** A tool result's tokens; images and documents inside it are files and are counted there. */ +function messagesResultTokens(acc: BreakdownAccumulator, content: unknown): number { + if (typeof content === "string") return tokensOfText(content); + if (Array.isArray(content)) { + let n = 0; + for (const c of content) { + if (!isRec(c)) continue; + if (c.type === "image" || c.type === "document") acc.file(IMAGE_TOKENS); + else n += typeof c.text === "string" ? tokensOfText(c.text) : tokensOfJson(c); + } + return n; + } + return content === undefined || content === null ? 0 : tokensOfJson(content); +} + +// --- OpenAI Responses --- + +const IMAGE_PART_TYPES = new Set(["input_image", "input_file", "image_url", "image", "file"]); + +interface ContentPart { + text: string; + image: boolean; +} + +/** Message content that is a string or a list of parts, as parts. */ +function contentParts(c: unknown): ContentPart[] { + if (typeof c === "string") return [{ text: c, image: false }]; + if (!Array.isArray(c)) return []; + const out: ContentPart[] = []; + for (const p of c) { + if (isRec(p)) out.push({ text: str(p.text), image: typeof p.type === "string" && IMAGE_PART_TYPES.has(p.type) }); + } + return out; +} + +function readResponses(acc: BreakdownAccumulator, body: Rec): void { + acc.held = str(body.previous_response_id) !== ""; + const instructions = str(body.instructions); + if (instructions !== "") acc.systemText(instructions); + if (Array.isArray(body.tools)) for (const t of body.tools) responsesTool(acc, t); + const input = body.input; + if (typeof input === "string") { + acc.newTurn(); + acc.userText(input); + return; + } + if (Array.isArray(input)) for (const it of input) responsesItem(acc, it); +} + +/** A tool definition; a namespace of tools counts each member, Codex's own `functions` one by one. */ +function responsesTool(acc: BreakdownAccumulator, t: unknown): void { + if (!isRec(t)) return; + const members = Array.isArray(t.tools) ? t.tools : undefined; + if (t.type === "namespace" || (members !== undefined && members.length > 0)) { + const name = str(t.name) || (isRec(t.function) ? str(t.function.name) : "") || str(t.type); + if (name === "functions") { + for (const x of members ?? []) responsesTool(acc, x); + return; + } + acc.tool(tokensOfJson(t), Math.max(1, members?.length ?? 0)); + return; + } + acc.tool(tokensOfJson(t)); +} + +/** A call's arguments as the wire carries them: a JSON string, or an already parsed object. */ +function argumentTokens(args: unknown): number { + if (typeof args === "string") return tokensOfBlob(args); + return args === undefined || args === null ? 0 : tokensOfJson(args); +} + +function responsesItem(acc: BreakdownAccumulator, raw: unknown): void { + if (!isRec(raw)) return; + const type = str(raw.type) || (typeof raw.role === "string" ? "message" : ""); + switch (type) { + case "additional_tools": + if (Array.isArray(raw.tools)) for (const t of raw.tools) responsesTool(acc, t); + return; + case "message": + responsesMessage(acc, str(raw.role), contentParts(raw.content)); + return; + case "reasoning": { + let n = 0; + if (Array.isArray(raw.summary)) for (const s of raw.summary) if (isRec(s)) n += tokensOfText(str(s.text)); + // sealed reasoning: about three quarters of the base64 is what was sealed + n += Math.floor((str(raw.encrypted_content).length * 3) / 4 / 4); + acc.chat(n); + return; + } + case "function_call": + case "custom_tool_call": + case "local_shell_call": + case "tool_search_call": { + const input = type === "custom_tool_call" ? raw.input : type === "local_shell_call" ? raw.action : raw.arguments; + const name = str(raw.name); + acc.noteCall(str(raw.call_id), name, input); + acc.chat(tokensOfText(name) + argumentTokens(input)); + return; + } + case "function_call_output": + case "custom_tool_call_output": + case "local_shell_call_output": + case "tool_search_output": + if (type === "tool_search_output" && Array.isArray(raw.tools)) for (const t of raw.tools) responsesTool(acc, t); + acc.result(str(raw.call_id), outputTokens(acc, raw.output)); + return; + case "compaction": + case "compaction_summary": + acc.compacted(tokensOfJson(raw)); + return; + default: + acc.chat(tokensOfJson(raw)); + } +} + +function responsesMessage(acc: BreakdownAccumulator, role: string, parts: ContentPart[]): void { + if (role === "system" || role === "developer") { + for (const p of parts) if (p.text !== "") acc.systemText(p.text); + return; + } + if (role === "user") { + if (parts.some(p => p.image || userSays(p.text))) acc.newTurn(); + for (const p of parts) { + if (p.image) acc.file(IMAGE_TOKENS); + else acc.userText(p.text); + } + return; + } + for (const p of parts) acc.chat(tokensOfText(p.text)); +} + +/** A tool output's tokens: a string, a list of parts (images count as files), or an object. */ +function outputTokens(acc: BreakdownAccumulator, output: unknown): number { + if (typeof output === "string") return tokensOfText(output); + if (Array.isArray(output)) { + let n = 0; + for (const p of contentParts(output)) { + if (p.image) acc.file(IMAGE_TOKENS); + else n += tokensOfText(p.text); + } + return n; + } + return isRec(output) ? tokensOfJson(output) : 0; +} + +// --- OpenAI Chat Completions --- + +function readChat(acc: BreakdownAccumulator, body: Rec): void { + if (Array.isArray(body.tools)) for (const t of body.tools) responsesTool(acc, t); + if (!Array.isArray(body.messages)) return; + for (const m of body.messages) { + if (!isRec(m)) continue; + const role = str(m.role); + const parts = contentParts(m.content); + if (role === "tool" || role === "function") { + let n = 0; + for (const p of parts) { + if (p.image) acc.file(IMAGE_TOKENS); + else n += tokensOfText(p.text); + } + acc.result(str(m.tool_call_id), n); + continue; + } + if (role === "system" || role === "developer" || role === "user") { + responsesMessage(acc, role, parts); + continue; + } + // the model's reasoning, what it said and its calls + acc.chat(tokensOfText(str(m.reasoning_content))); + let said = 0; + for (const p of parts) said += tokensOfText(p.text); + acc.chat(said); + if (!Array.isArray(m.tool_calls)) continue; + for (const c of m.tool_calls) { + if (!isRec(c) || !isRec(c.function)) continue; + const name = str(c.function.name); + acc.noteCall(str(c.id), name, c.function.arguments); + acc.chat(tokensOfText(name) + argumentTokens(c.function.arguments)); + } + } +} diff --git a/src/server/request-log-route-live.ts b/src/server/request-log-route-live.ts index 399c9491ead..c7aac2de514 100644 --- a/src/server/request-log-route-live.ts +++ b/src/server/request-log-route-live.ts @@ -1,4 +1,6 @@ +import { vendorContextWindow } from "../codex/catalog/vendor-context"; import { OAUTH_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label"; +import type { ContextBreakdownV1 } from "./context-breakdown"; /** * Per-account state of a multi-account OAuth pool, captured once when the final request row is @@ -81,3 +83,35 @@ export function routeLiveTimingField(logCtx: RouteLiveTimingContext, start: numb ...(redaction !== undefined && Number.isFinite(redaction) && redaction >= 0 ? { privacyRedactionMs: redaction } : {}), }; } + +/** The client body's context-window breakdown, set once at the inbound entry (context-breakdown.ts). */ +export interface ContextBreakdownContext { + contextBreakdown?: ContextBreakdownV1; +} + +export interface ContextBreakdownEntryField { + contextBreakdown?: ContextBreakdownV1; + /** The serving model's context window in tokens, when the route's adapter knows it. */ + contextWindow?: number; +} + +/** + * Carries the breakdown to the final row, with the window of the model that served it. The window + * lookup is the caller's own (request-log.ts owns it) and runs only when a breakdown exists. + */ +export function contextBreakdownField( + logCtx: ContextBreakdownContext, + served: { adapter: string; model?: string } | undefined, + windowOf: (adapter: string, model: string | undefined) => number | undefined, +): ContextBreakdownEntryField { + const contextBreakdown = logCtx.contextBreakdown; + if (!contextBreakdown) return {}; + // The adapter-specific window wins; otherwise the bundled vendor table names most hosted models. + const contextWindow = served + ? windowOf(served.adapter, served.model) ?? (served.model ? vendorContextWindow(served.model) : undefined) + : undefined; + return { + contextBreakdown, + ...(contextWindow !== undefined && Number.isFinite(contextWindow) && contextWindow > 0 ? { contextWindow } : {}), + }; +} diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 35b1cdfa55a..52550327704 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -4,7 +4,7 @@ import { normalizeRecordedClient, type UsageClient } from "../usage/client"; import { anthropicAccountTagField, stampApiKeyAccountLabel, usesApiKeyAccount } from "../providers/label"; import { finalizeProviderCacheAffinity } from "./request-log-cache-affinity"; import { aggregateAttemptUsage } from "./request-log-attempt-usage"; -import { accountRosterField, routeLiveTimingField, type AccountRosterEntryField, type RouteLiveTimingContext, type RouteLiveTimingEntryField } from "./request-log-route-live"; +import { accountRosterField, contextBreakdownField, routeLiveTimingField, type AccountRosterEntryField, type ContextBreakdownContext, type ContextBreakdownEntryField, type RouteLiveTimingContext, type RouteLiveTimingEntryField } from "./request-log-route-live"; export { aggregateAttemptUsage } from "./request-log-attempt-usage"; import { KEY_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label"; @@ -126,7 +126,7 @@ export function cacheDiagnosticsObserving(): boolean { return cacheDiagnosticHooks()?.enabled() === true; } -export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyLogContext, RouteLiveTimingContext { +export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyLogContext, RouteLiveTimingContext, ContextBreakdownContext { model: string; provider: string; client?: UsageClient; @@ -330,7 +330,7 @@ export function rebindCacheDiagnosticBody( cacheDiagnosticHooks()?.rebind(body, draft); } -export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField, AccountRosterEntryField, RouteLiveTimingEntryField { +export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField, AccountRosterEntryField, RouteLiveTimingEntryField, ContextBreakdownEntryField { requestId: string; client?: UsageClient; /** The logical request this row belongs to (#4546); absent on rows written without a budget. */ @@ -1687,6 +1687,7 @@ function writeFinalRequestLog( ...(logCtx.routeDecision ? { routeDecision: logCtx.routeDecision } : {}), ...accountRosterField(isCombo ? attempts?.at(-1) : logCtx), ...(isCombo ? {} : routeLiveTimingField(logCtx, start)), + ...contextBreakdownField(logCtx, isCombo ? attempts?.at(-1) : { adapter: logCtx.providerAdapter ?? logCtx.provider, model: logCtx.model }, contextWindowForModel), ...(jevDecision ? { jevDecision } : {}), ...(claudeCompatibility ? { claudeCompatibility } : {}), ...(protocolTrace ? { protocolTrace } : {}), diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index 2645f795e0d..af9f01dbbdd 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -90,6 +90,7 @@ import { anthropicSessionKeyFromParts } from "../../oauth/anthropic-routing"; import { configuredAnthropicInstance } from "../../providers/anthropic-instance"; import { isTranslatorBudgetExceededError } from "../../lib/translator-budget"; import { bindTurnTerminationScope, rememberDeliveredFinalAnswer } from "../../responses/turn-termination"; +import { observeContextBreakdown } from "../context-breakdown"; import { noteCodexSelectionAffinity, observeCacheDiagnosticInbound, rebindCacheDiagnosticBody, requestLogSpeedLabel, readConfiguredCodexServiceTier } from "../request-log"; import type { RouteResult } from "../../router"; import { @@ -277,6 +278,7 @@ export async function prepareResponsesRequest( : options.promptCacheKeyIsSharedCohort === false ? "metadata-derived" : "caller", contextPrincipalIdOf(options.admission), ); + observeContextBreakdown(logCtx, body, "responses"); if (!concreteSelection && !options.compactionRoutingOverride && inboundWire === "responses") { options.compactionRoutingOverride = applyCompactionRoutingOverride(body, req.headers, config, { endpoint: "responses", diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index e99fa793a15..c643db9db3d 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1283,7 +1283,7 @@ "fixture-windows-runtime-preload.test.ts": "ci-workflows", "repo-hygiene.test.ts": "ci-workflows", "request-decompress.test.ts": "usage", "request-evidence.test.ts": "usage", "request-history-index.test.ts": "usage", "request-history-integrity.test.ts": "usage", - "request-log-attempt-identity.test.ts": "usage", "request-log-account-roster.test.ts": "usage", "request-log-route-live-timing.test.ts": "usage", "request-log-conversation.test.ts": "usage", + "request-log-attempt-identity.test.ts": "usage", "request-log-account-roster.test.ts": "usage", "request-log-route-live-timing.test.ts": "usage", "request-log-context-breakdown.test.ts": "usage", "context-breakdown.test.ts": "usage", "request-log-conversation.test.ts": "usage", "request-log-estimate-cap.test.ts": "usage", "request-log-jev.test.ts": "usage", "request-log-nonstream.test.ts": "usage", "request-log-protocol-trace.test.ts": "usage", "request-log-served-model.test.ts": "usage", "request-log-model-filter.test.ts": "usage", "request-log-generation-window.test.ts": "usage", diff --git a/tests/usage/context-breakdown.test.ts b/tests/usage/context-breakdown.test.ts new file mode 100644 index 00000000000..ea995c917c5 --- /dev/null +++ b/tests/usage/context-breakdown.test.ts @@ -0,0 +1,340 @@ +import { describe, expect, test } from "bun:test"; +import { measureContextBreakdown, observeContextBreakdown } from "../../src/server/context-breakdown"; + +/** ASCII only, so a string of n characters is exactly ceil(n / 4) tokens. */ +const tok = (s: string): number => Math.ceil(s.length / 4); +const fill = (n: number, ch = "a"): string => ch.repeat(n); +const sum = (xs: number[]): number => xs.reduce((a, b) => a + b, 0); + +const CLAUDE_MD_CHUNK = "Contents of /home/dev/.claude/CLAUDE.md (user's private global instructions for all projects):\n\nSENTINEL_MEMORY_BODY rules for the fixture\n"; +const REMINDER_PREAMBLE = "As you answer the user's questions, you can use the following context:"; +const SKILLS_LIST = "The following skills are available for use with the Skill tool:\n\n- skill-alpha: SENTINEL_SKILL does alpha\n- skill-beta: does beta"; +const OTHER_REMINDER = "Other reminder text SENTINEL_REMINDER"; + +describe("OpenAI Responses (Codex-style)", () => { + const instructions = fill(400); + const skillsDev = `\n${fill(800)}`; + const agentsMd = `# AGENTS.md instructions for /work/proj\n\n\nSENTINEL_AGENTS_BODY ${fill(300)}\n`; + const envContext = `\n/work/proj\n`; + const fileOut = fill(400, "f"); + const shellOut = fill(200, "s"); + const body = { + model: "gpt-6-sol", + instructions, + tools: [ + { type: "function", name: "shell", description: "run a command", parameters: { type: "object", properties: { command: { type: "array", items: { type: "string" } } } } }, + { type: "namespace", name: "mcp__github", tools: [{ type: "function", name: "a" }, { type: "function", name: "b" }] }, + ], + input: [ + { type: "message", role: "developer", content: [{ type: "input_text", text: skillsDev }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: agentsMd }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: envContext }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: "Fix the bug in the parser SENTINEL_USER" }] }, + { type: "function_call", call_id: "call_read", name: "shell", arguments: JSON.stringify({ command: ["bash", "-lc", "cat src/parser.ts"] }) }, + { type: "function_call_output", call_id: "call_read", output: fileOut }, + { type: "function_call", call_id: "call_test", name: "shell", arguments: JSON.stringify({ command: ["bash", "-lc", "npm test"] }) }, + { type: "function_call_output", call_id: "call_test", output: shellOut }, + { type: "message", role: "assistant", content: [{ type: "output_text", text: "Found it SENTINEL_ASSISTANT" }] }, + { type: "message", role: "user", content: [{ type: "input_image", image_url: "data:image/png;base64,AAAA" }, { type: "input_text", text: "Here is the screenshot" }] }, + ], + }; + + test("sorts a Codex request into the seven categories", () => { + const b = measureContextBreakdown(body, "responses")!; + expect(b.v).toBe(1); + expect(b.parts.system).toBe(tok(instructions) + tok(envContext)); + expect(b.parts.skills).toBe(tok(skillsDev)); + expect(b.parts.memory).toBe(tok(agentsMd)); + expect(b.parts.files).toBe(tok(fileOut) + 1600); + expect(b.parts.results).toBe(tok(shellOut)); + expect(b.parts.tools).toBeGreaterThan(40); + expect(b.toolCount).toBe(3); + expect(b.held).toBeUndefined(); + expect(b.parts.chat).toBe(sum(b.turns) + (b.turnsEarlier ?? 0)); + }); + + test("injected context is not a turn; each real user message begins one", () => { + const b = measureContextBreakdown(body, "responses")!; + // turn 1: the bug report, the calls, the reply; turn 2: the screenshot message + expect(b.turns).toHaveLength(2); + expect(b.turns[0]).toBeGreaterThan(b.turns[1]!); + expect(b.turns[1]).toBe(tok("Here is the screenshot")); + }); + + test("a shell command that only reads files makes its output a file, anything else a result", () => { + const run = (call: Record) => { + const b = measureContextBreakdown({ + input: [ + { type: call.type ?? "function_call", call_id: "c", name: "shell", ...call }, + { type: "function_call_output", call_id: "c", output: fill(40, "o") }, + ], + }, "responses")!; + return { files: b.parts.files, results: b.parts.results }; + }; + const asFile = { files: 10, results: 0 }; + const asResult = { files: 0, results: 10 }; + expect(run({ arguments: JSON.stringify({ command: "sed -n '1,80p' src/a.ts" }) })).toEqual(asFile); + expect(run({ arguments: JSON.stringify({ command: ["bash", "-lc", "head -n 40 src/a.ts"] }) })).toEqual(asFile); + expect(run({ arguments: JSON.stringify({ cmd: "cd /work && cat README.md" }) })).toEqual(asFile); + expect(run({ arguments: JSON.stringify({ command: "cat a.txt | wc -l" }) })).toEqual(asResult); + expect(run({ arguments: JSON.stringify({ command: "ls -la" }) })).toEqual(asResult); + expect(run({ arguments: JSON.stringify({ command: "sed -i s/a/b/ src/a.ts" }) })).toEqual(asResult); + expect(run({ arguments: "not json at all" })).toEqual(asResult); + expect(run({ type: "custom_tool_call", input: 'text(await tools.exec_command({cmd:"cat src/x.ts"}))', arguments: undefined })).toEqual(asFile); + }); + + test("a read tool's path argument makes its result a file", () => { + const b = measureContextBreakdown({ + input: [ + { type: "function_call", call_id: "c", name: "read_file", arguments: JSON.stringify({ path: "src/a.ts" }) }, + { type: "function_call_output", call_id: "c", output: fill(80) }, + { type: "function_call_output", call_id: "orphan", output: fill(80) }, + ], + }, "responses")!; + expect(b.parts.files).toBe(20); + expect(b.parts.results).toBe(20); + }); + + test("previous_response_id marks the earlier turns as held upstream", () => { + const b = measureContextBreakdown({ previous_response_id: "resp_SENTINEL", input: [{ role: "user", content: "hello there" }] }, "responses")!; + expect(b.held).toBe(true); + expect(b.turns).toHaveLength(1); + expect(measureContextBreakdown({ previous_response_id: "resp_x", input: [] }, "responses")?.held).toBe(true); + }); + + test("a plain string input is one user turn; reasoning and compaction are counted as chat", () => { + expect(measureContextBreakdown({ input: fill(40) }, "responses")!.turns).toEqual([10]); + const b = measureContextBreakdown({ + input: [ + { type: "compaction", encrypted_content: fill(400) }, + { role: "user", content: "go" }, + { type: "reasoning", summary: [{ type: "summary_text", text: fill(40) }], encrypted_content: fill(160) }, + ], + }, "responses")!; + expect(b.turnsEarlier).toBeGreaterThan(0); + expect(b.turns).toHaveLength(1); + expect(b.parts.chat).toBe(b.turns[0]! + b.turnsEarlier!); + expect(b.turns[0]).toBe(1 + 10 + 30); + }); + + test("the Codex app's IDE context ahead of '## My request' still counts as the user speaking", () => { + const b = measureContextBreakdown({ + input: [{ role: "user", content: [{ type: "input_text", text: "# Context from my IDE setup:\nopen tabs\n\n## My request for Codex:\nFix it" }] }], + }, "responses")!; + expect(b.turns).toHaveLength(1); + }); + + test("an OpenCode 'Instructions from:' file in the system prompt is memory", () => { + const file = "Instructions from: /work/AGENTS.md\nSENTINEL_RULES keep tests green\n"; + const lead = fill(40); + const b = measureContextBreakdown({ instructions: `${lead}\n${file}`, input: "hi" }, "responses")!; + expect(b.parts.memory).toBe(tok(file)); + expect(b.parts.system).toBe(tok(`${lead}\n`)); + }); +}); + +describe("Anthropic Messages (Claude Code-style)", () => { + const sysPrompt = `You are Claude Code. ${fill(380)}`; + const toolResultRead = fill(800, "r"); + const toolResultBash = fill(400, "b"); + const body = { + model: "claude-opus-5-5", + system: [ + { type: "text", text: "x-anthropic-billing-header: cc_version=9.9.9; cch=00000;" }, + { type: "text", text: sysPrompt }, + ], + tools: [ + { name: "Read", description: "Reads a file", input_schema: { type: "object", properties: { file_path: { type: "string" } } } }, + { name: "Bash", description: "Runs a command", input_schema: { type: "object", properties: { command: { type: "string" } } } }, + { name: "mcp__fs__list", description: "Lists", input_schema: { type: "object" } }, + ], + messages: [ + { + role: "user", + content: [ + { type: "text", text: `\n${REMINDER_PREAMBLE}\n${CLAUDE_MD_CHUNK}` }, + { type: "text", text: `\n${SKILLS_LIST}\n\n${OTHER_REMINDER}\n` }, + { type: "text", text: "Please read the config SENTINEL_USER" }, + ], + }, + { role: "assistant", content: [{ type: "text", text: "Reading." }, { type: "tool_use", id: "tu1", name: "Read", input: { file_path: "/proj/SENTINEL_PATH.ts" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "tu1", content: toolResultRead }] }, + { role: "assistant", content: [{ type: "tool_use", id: "tu2", name: "Bash", input: { command: "npm test" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "tu2", content: [{ type: "text", text: toolResultBash }] }] }, + { role: "assistant", content: "Done." }, + { role: "user", content: [{ type: "text", text: "Thanks, next task" }, { type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } }] }, + ], + }; + + test("sorts a Claude Code request into the seven categories", () => { + const b = measureContextBreakdown(body, "messages")!; + expect(b.parts.system).toBe(tok("x-anthropic-billing-header: cc_version=9.9.9; cch=00000;") + tok(sysPrompt)); + expect(b.parts.skills).toBe(tok(SKILLS_LIST)); + expect(b.parts.memory).toBe(tok(CLAUDE_MD_CHUNK) + tok(REMINDER_PREAMBLE) + tok("Other reminder text SENTINEL_REMINDER")); + expect(b.parts.files).toBe(tok(toolResultRead) + 1600); + expect(b.parts.results).toBe(tok(toolResultBash)); + expect(b.toolCount).toBe(3); + expect(b.parts.tools).toBeGreaterThan(30); + expect(b.parts.chat).toBe(sum(b.turns) + (b.turnsEarlier ?? 0)); + }); + + test("tool results continue a turn; only real user text begins one", () => { + const b = measureContextBreakdown(body, "messages")!; + expect(b.turns).toHaveLength(2); + expect(b.turns[1]).toBe(tok("Thanks, next task")); + }); + + test("keeps the last 48 turns and sums the older ones", () => { + const messages: unknown[] = []; + for (let i = 0; i < 50; i++) { + messages.push({ role: "user", content: fill(40) }); + messages.push({ role: "assistant", content: fill(20) }); + } + const b = measureContextBreakdown({ messages }, "messages")!; + expect(b.turns).toHaveLength(48); + expect(b.turns.every(t => t === 15)).toBe(true); + expect(b.turnsEarlier).toBe(30); + expect(b.parts.chat).toBe(50 * 15); + }); + + test("documents by reference count their source, base64 documents and images 1600, thinking counts as chat", () => { + const b = measureContextBreakdown({ + messages: [ + { role: "user", content: [{ type: "text", text: "see attachments" }, { type: "document", source: { type: "base64", media_type: "application/pdf", data: "AAAA" } }, { type: "document", source: { type: "url", url: "https://example.test/a.pdf" } }] }, + { role: "assistant", content: [{ type: "thinking", thinking: fill(40), signature: "sig" }, { type: "redacted_thinking", data: fill(160) }] }, + ], + }, "messages")!; + expect(b.parts.files).toBeGreaterThan(1600); + expect(b.parts.files).toBeLessThan(1700); + expect(b.parts.chat).toBe(tok("see attachments") + 10 + 10); + }); + + test("system as a plain string and system-role messages are system", () => { + const b = measureContextBreakdown({ system: fill(40), messages: [{ role: "system", content: fill(80) }, { role: "user", content: "hi" }] }, "messages")!; + expect(b.parts.system).toBe(10 + 20); + }); +}); + +describe("OpenAI Chat Completions", () => { + test("sorts messages, tool calls, tool results and image parts", () => { + const result = fill(120, "t"); + const b = measureContextBreakdown({ + model: "gpt-6-sol", + tools: [{ type: "function", function: { name: "read_file", description: "Reads", parameters: { type: "object", properties: { path: { type: "string" } } } } }], + messages: [ + { role: "system", content: fill(80) }, + { role: "user", content: "Open the notes SENTINEL_CHAT" }, + { role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "read_file", arguments: JSON.stringify({ path: "notes.md" }) } }] }, + { role: "tool", tool_call_id: "call_1", content: result }, + { role: "assistant", content: "Here they are" }, + { role: "user", content: [{ type: "text", text: "and this picture" }, { type: "image_url", image_url: { url: "https://example.test/a.png" } }] }, + ], + }, "chat")!; + expect(b.parts.system).toBe(20); + expect(b.parts.files).toBe(tok(result) + 1600); + expect(b.parts.results).toBe(0); + expect(b.toolCount).toBe(1); + expect(b.turns).toHaveLength(2); + expect(b.parts.chat).toBe(sum(b.turns)); + }); +}); + +describe("estimator", () => { + test("ASCII is four characters a token, everything else a token a character", () => { + expect(measureContextBreakdown({ input: "abcdefgh" }, "responses")!.parts.chat).toBe(2); + expect(measureContextBreakdown({ input: "abcde" }, "responses")!.parts.chat).toBe(2); + expect(measureContextBreakdown({ input: "你好世界你好世界你好abcdefgh" }, "responses")!.parts.chat).toBe(10 + 2); + // an astral character (a surrogate pair) is one character + expect(measureContextBreakdown({ input: "\u{1F600}\u{1F600}" }, "responses")!.parts.chat).toBe(2); + }); + + test("tool schemas are sized by walking them, not serializing them", () => { + const schema = { name: "t", description: fill(1000), input_schema: { type: "object", properties: { a: { type: "string", description: fill(1000) } } } }; + const walked = measureContextBreakdown({ tools: [schema], messages: [] }, "messages")!.parts.tools; + const serialized = Math.ceil(JSON.stringify(schema).length / 4); + expect(walked).toBeGreaterThan(serialized * 0.9); + expect(walked).toBeLessThan(serialized * 1.2); + }); + + test("a very deep tool schema does not overflow the stack", () => { + let deep: unknown = "leaf"; + for (let i = 0; i < 20000; i++) deep = { n: deep }; + expect(() => measureContextBreakdown({ tools: [deep], messages: [] }, "messages")).not.toThrow(); + }); +}); + +describe("failure behaviour", () => { + test("a body that is not a readable request is undefined, never a throw", () => { + const bad: Array<[unknown, "responses" | "messages" | "chat"]> = [ + [null, "responses"], [undefined, "messages"], ["text", "chat"], [42, "responses"], [[], "messages"], + [{}, "responses"], [{}, "messages"], [{}, "chat"], + [{ messages: "nope" }, "messages"], [{ messages: [null, 7, "x", []] }, "chat"], + [{ input: 42 }, "responses"], [{ input: [null, 1, "s"] }, "responses"], + [{ messages: [{ role: "user", content: { weird: true } }] }, "messages"], + [{ messages: [{ role: "assistant", tool_calls: "x" }] }, "chat"], + [{ input: "x" }, "unknown" as "responses"], + ]; + for (const [body, wire] of bad) expect(() => measureContextBreakdown(body, wire)).not.toThrow(); + expect(measureContextBreakdown(null, "responses")).toBeUndefined(); + expect(measureContextBreakdown({}, "responses")).toBeUndefined(); + expect(measureContextBreakdown({ messages: "nope" }, "messages")).toBeUndefined(); + expect(measureContextBreakdown({ messages: [null, 7, "x"] }, "chat")).toBeUndefined(); + expect(measureContextBreakdown({ input: 42 }, "responses")).toBeUndefined(); + expect(measureContextBreakdown({ input: "x" }, "unknown" as "responses")).toBeUndefined(); + }); + + test("a hostile getter that throws is swallowed", () => { + const body = { get messages(): unknown { throw new Error("boom"); } }; + expect(measureContextBreakdown(body, "messages")).toBeUndefined(); + }); +}); + +describe("privacy", () => { + test("the result holds numbers only: no fixture text, path or id survives", () => { + const messagesBody = { + system: [{ type: "text", text: "SENTINEL_SYSTEM prompt" }], + tools: [{ name: "SENTINEL_TOOL", description: "SENTINEL_TOOL_DESC", input_schema: { type: "object" } }], + messages: [ + { role: "user", content: [{ type: "text", text: `\n${CLAUDE_MD_CHUNK}` }, { type: "text", text: "SENTINEL_USER_TEXT" }] }, + { role: "assistant", content: [{ type: "tool_use", id: "SENTINEL_TOOL_USE_ID", name: "Read", input: { file_path: "/SENTINEL/path.ts" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "SENTINEL_TOOL_USE_ID", content: "SENTINEL_FILE_CONTENT" }] }, + ], + }; + const responsesBody = { + previous_response_id: "SENTINEL_RESP_ID", + instructions: "SENTINEL_INSTRUCTIONS", + input: [ + { type: "function_call", call_id: "SENTINEL_CALL", name: "SENTINEL_FN", arguments: '{"path":"SENTINEL_ARG"}' }, + { type: "function_call_output", call_id: "SENTINEL_CALL", output: "SENTINEL_OUT" }, + ], + }; + const out = [measureContextBreakdown(messagesBody, "messages"), measureContextBreakdown(responsesBody, "responses")]; + for (const b of out) { + expect(b).toBeDefined(); + expect(JSON.stringify(b)).not.toMatch(/SENTINEL|CLAUDE\.md|\/home\/|\.ts/); + const allNumbers = (v: unknown): boolean => + typeof v === "number" || typeof v === "boolean" || (Array.isArray(v) ? v.every(allNumbers) : typeof v === "object" && v !== null && Object.values(v).every(allNumbers)); + expect(allNumbers({ ...b, v: 1 })).toBe(true); + for (const key of Object.keys(b!)) expect(["v", "parts", "turns", "turnsEarlier", "toolCount", "held"]).toContain(key); + } + }); +}); + +describe("observeContextBreakdown", () => { + test("the first observer wins and a later one never overwrites", () => { + const ctx: { contextBreakdown?: ReturnType } = {}; + observeContextBreakdown(ctx as never, { messages: [{ role: "user", content: fill(40) }] }, "messages"); + const first = ctx.contextBreakdown; + expect(first?.parts.chat).toBe(10); + observeContextBreakdown(ctx as never, { input: fill(400) }, "responses"); + expect(ctx.contextBreakdown).toBe(first); + }); + + test("an unreadable body leaves the slot open for a later observer", () => { + const ctx: { contextBreakdown?: ReturnType } = {}; + observeContextBreakdown(ctx as never, "garbage", "messages"); + expect(ctx.contextBreakdown).toBeUndefined(); + observeContextBreakdown(ctx as never, { input: fill(40) }, "responses"); + expect(ctx.contextBreakdown?.parts.chat).toBe(10); + }); +}); diff --git a/tests/usage/request-log-context-breakdown.test.ts b/tests/usage/request-log-context-breakdown.test.ts new file mode 100644 index 00000000000..94ff8c82586 --- /dev/null +++ b/tests/usage/request-log-context-breakdown.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { observeContextBreakdown, type ContextBreakdownV1 } from "../../src/server/context-breakdown"; +import { addFinalRequestLog, clearRequestLogsForTests, type RequestLogEntry } from "../../src/server/request-log"; + +afterEach(() => clearRequestLogsForTests()); + +const breakdown: ContextBreakdownV1 = { + v: 1, + parts: { system: 10, tools: 20, skills: 5, memory: 6, files: 7, results: 8, chat: 9 }, + turns: [4, 5], + toolCount: 2, +}; + +function finalRow(extra: Record): RequestLogEntry { + const rows: RequestLogEntry[] = []; + addFinalRequestLog("ctx-row", Date.now(), { model: "gpt-5", provider: "openai", ...extra }, 200, undefined, row => rows.push(row)); + return rows[0]!; +} + +describe("context breakdown on the final request row", () => { + test("the breakdown rides to the row; the window is set only where the adapter knows it", () => { + const row = finalRow({ contextBreakdown: breakdown, provider: "devin", providerAdapter: "devin", model: "swe-2" }); + expect(row.contextBreakdown).toEqual(breakdown); + expect(row.contextWindow).toBe(262_000); + }); + + test("a hosted model the adapter does not size takes the bundled vendor window", () => { + const row = finalRow({ contextBreakdown: breakdown, model: "gpt-5" }); + expect(row.contextWindow).toBe(400_000); + }); + + test("an unknown window is left out, never guessed", () => { + const row = finalRow({ contextBreakdown: breakdown, model: "ocx-unknown-model-xyz" }); + expect(row.contextBreakdown).toEqual(breakdown); + expect("contextWindow" in row).toBe(false); + }); + + test("a row without a breakdown carries neither field", () => { + const row = finalRow({ provider: "devin", providerAdapter: "devin", model: "swe-2" }); + expect("contextBreakdown" in row).toBe(false); + expect("contextWindow" in row).toBe(false); + }); + + test("a combo row takes the window of the final attempt, not the combo's own provider", () => { + const attempt = (adapter: string, model: string, ordinal: number) => ({ + ordinal, provider: adapter, model, adapter, status: ordinal === 1 ? 429 : 200, durationMs: 5, + sendCount: 1, recoveryKinds: [], usageStatus: "unknown", + }); + const row = finalRow({ + comboId: "combo-1", + contextBreakdown: breakdown, + attempts: [attempt("openai-chat", "other", 1), attempt("devin", "swe-1-6", 2)], + }); + expect(row.contextWindow).toBe(200_000); + }); + + test("the first observer's reading is the one the row carries", () => { + const ctx: { contextBreakdown?: ContextBreakdownV1 } = {}; + observeContextBreakdown(ctx, { messages: [{ role: "user", content: "a".repeat(40) }] }, "messages"); + const first = ctx.contextBreakdown; + observeContextBreakdown(ctx, { input: "b".repeat(4000) }, "responses"); + expect(ctx.contextBreakdown).toBe(first); + const row = finalRow(ctx); + expect(row.contextBreakdown?.parts.chat).toBe(10); + }); +}); From 1e098e2f558508a40fdfe55125e8372876aa5af8 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:44:30 -0500 Subject: [PATCH 10/12] feat(gui): context-window breakdown and prompt-cache meter on the live routing view For the pinned or latest request the live routing view now draws a treemap of the context window: system prompt, tools, skills, memory files, files, tool results and each conversation turn, against the free space left in the serving model's window. Estimates are scaled to the token count the upstream reported when it reported one. A prompt-cache meter shows the hit rate, and an upstream that did not report cache reads says so instead of showing 0%. Layout follows Magpie's context card (MIT, yetone). --- gui/src/i18n/route-live-copy.ts | 25 +++ gui/src/pages/route-live/ContextCard.tsx | 177 ++++++++++++++++ gui/src/pages/route-live/RouteLive.tsx | 2 + gui/src/pages/route-live/context-tiles.ts | 242 ++++++++++++++++++++++ gui/src/pages/route-live/route-live.css | 59 ++++++ gui/src/pages/route-live/route-rows.ts | 51 ++++- gui/tests/route-live-context.test.ts | 166 +++++++++++++++ gui/tests/route-live-render.test.tsx | 44 ++++ 8 files changed, 760 insertions(+), 6 deletions(-) create mode 100644 gui/src/pages/route-live/ContextCard.tsx create mode 100644 gui/src/pages/route-live/context-tiles.ts create mode 100644 gui/tests/route-live-context.test.ts diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index d9c76eb8010..2cdfaedbdae 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -110,6 +110,31 @@ const rows = { timeStreaming: ["Streaming","스트리밍 출력","Streaming-Ausgabe","Diffusion de la réponse","流式输出","串流輸出","Потоковая передача","ストリーミング出力","Akış çıktısı","Phát trực tuyến","Transmissão da resposta"], timeReading: ["Waiting for the upstream reply","업스트림 응답 대기","Warten auf die Antwort des Anbieters","Attente de la réponse du fournisseur","等待上游回复","等待上游回覆","Ожидание ответа провайдера","上流の応答待ち","Sağlayıcının yanıtı bekleniyor","Chờ phản hồi từ nhà cung cấp","Esperando a resposta do provedor"], timeNone: ["The time split was not recorded for this request.","이 요청은 시간 내역이 기록되지 않았어요.","Für diese Anfrage wurde keine Zeitaufteilung erfasst.","La répartition du temps n’a pas été enregistrée pour cette requête.","这个请求没有记录时间分布。","這個請求沒有記錄時間分布。","Для этого запроса разбивка времени не записана.","このリクエストには時間の内訳が記録されていません。","Bu istek için zaman dökümü kaydedilmedi.","Yêu cầu này không ghi lại phân bổ thời gian.","A divisão de tempo não foi registrada para esta requisição."], + ctxHead: ["Context window {used} / {window}","컨텍스트 사용량 {used} / {window}","Kontextfenster {used} / {window}","Fenêtre de contexte {used} / {window}","上下文用量 {used} / {window}","上下文用量 {used} / {window}","Окно контекста {used} / {window}","コンテキスト使用量 {used} / {window}","Bağlam penceresi {used} / {window}","Cửa sổ ngữ cảnh {used} / {window}","Janela de contexto {used} / {window}"], + ctxHeadNoWindow: ["Context window {used}","컨텍스트 사용량 {used}","Kontextfenster {used}","Fenêtre de contexte {used}","上下文用量 {used}","上下文用量 {used}","Окно контекста {used}","コンテキスト使用量 {used}","Bağlam penceresi {used}","Cửa sổ ngữ cảnh {used}","Janela de contexto {used}"], + ctxFill: ["{pct} full","{pct} 사용","{pct} belegt","{pct} utilisé","已用 {pct}","已用 {pct}","занято {pct}","{pct} 使用","{pct} dolu","đã dùng {pct}","{pct} usado"], + ctxHealthOk: ["Plenty of room","여유 충분","Reichlich Platz","Large marge","还很宽裕","還很寬裕","Места много","余裕あり","Bol yer var","Còn rộng","Bastante espaço"], + ctxHealthFilling: ["Filling up","곧 가득 참","Füllt sich","Bientôt plein","快满了","快滿了","Заполняется","もうすぐいっぱい","Doluyor","Sắp đầy","Enchendo"], + ctxHealthNear: ["Near the limit","한도에 근접","Nahe am Limit","Proche de la limite","接近上限","接近上限","Почти предел","上限に近い","Sınıra yakın","Gần chạm giới hạn","Perto do limite"], + ctxWindowUnknown: ["This model's context window is not known.","이 모델의 컨텍스트 창 크기를 알 수 없어요.","Das Kontextfenster dieses Modells ist unbekannt.","La fenêtre de contexte de ce modèle est inconnue.","不知道这个模型的上下文窗口。","不知道這個模型的上下文視窗。","Размер контекстного окна этой модели неизвестен.","このモデルのコンテキストウィンドウは不明です。","Bu modelin bağlam penceresi bilinmiyor.","Chưa biết cửa sổ ngữ cảnh của mô hình này.","A janela de contexto deste modelo não é conhecida."], + ctxEstimated: ["Estimated","추정","Geschätzt","Estimé","估算","估算","Оценка","推定","Tahmin","Ước tính","Estimado"], + ctxEstimatedTitle: ["Sizes are estimated from the request and not scaled to the token count the provider reported.","크기는 요청 내용으로 추정한 값이며, 제공자가 보고한 토큰 수로 보정되지 않았어요.","Die Größen sind aus der Anfrage geschätzt und nicht an die vom Anbieter gemeldete Token-Zahl angepasst.","Les tailles sont estimées à partir de la requête, sans calage sur le nombre de jetons du fournisseur.","大小按请求内容估算,没有按上游报告的 token 数校准。","大小依請求內容估算,沒有按上游回報的 token 數校準。","Размеры оценены по запросу и не приведены к числу токенов, сообщённому провайдером.","サイズはリクエスト内容からの推定で、プロバイダーが報告したトークン数には合わせていません。","Boyutlar istekten tahmin edilmiştir; sağlayıcının bildirdiği token sayısına göre ayarlanmamıştır.","Kích thước được ước tính từ yêu cầu, chưa hiệu chỉnh theo số token mà nhà cung cấp báo.","Os tamanhos são estimados a partir da requisição e não foram ajustados à contagem de tokens do provedor."], + ctxHeld: ["Earlier turns are kept by the upstream and can't be seen here.","이전 턴은 업스트림이 보관하고 있어 여기서는 볼 수 없어요.","Frühere Runden liegen beim Anbieter und sind hier nicht sichtbar.","Les tours précédents sont conservés par le fournisseur et ne sont pas visibles ici.","上文由上游保存,这里看不到。","上文由上游保存,這裡看不到。","Предыдущие ходы хранит провайдер, здесь их не видно.","以前のターンは上流側で保持されており、ここでは見えません。","Önceki turlar sağlayıcıda tutulur, burada görünmez.","Các lượt trước do nhà cung cấp lưu giữ nên không xem được ở đây.","Os turnos anteriores ficam com o provedor e não aparecem aqui."], + ctxMapLabel: ["Context window breakdown","컨텍스트 창 구성","Aufschlüsselung des Kontextfensters","Répartition de la fenêtre de contexte","上下文窗口分布","上下文視窗分布","Состав окна контекста","コンテキストウィンドウの内訳","Bağlam penceresi dağılımı","Phân bổ cửa sổ ngữ cảnh","Composição da janela de contexto"], + ctxSystem: ["System prompt","시스템 프롬프트","Systemprompt","Prompt système","系统提示词","系統提示詞","Системный промпт","システムプロンプト","Sistem istemi","Prompt hệ thống","Prompt do sistema"], + ctxTools: ["Tools","도구","Tools","Outils","工具","工具","Инструменты","ツール","Araçlar","Công cụ","Ferramentas"], + ctxSkills: ["Skills","스킬","Skills","Compétences","技能","技能","Навыки","スキル","Beceriler","Kỹ năng","Skills"], + ctxMemory: ["Memory and AGENTS.md","메모리 및 AGENTS.md","Speicher und AGENTS.md","Mémoire et AGENTS.md","记忆与 AGENTS.md","記憶與 AGENTS.md","Память и AGENTS.md","メモリと AGENTS.md","Bellek ve AGENTS.md","Bộ nhớ và AGENTS.md","Memória e AGENTS.md"], + ctxFiles: ["Files","파일","Dateien","Fichiers","文件","檔案","Файлы","ファイル","Dosyalar","Tệp","Arquivos"], + ctxResults: ["Tool results","도구 결과","Tool-Ergebnisse","Résultats d’outils","工具结果","工具結果","Результаты инструментов","ツール結果","Araç sonuçları","Kết quả công cụ","Resultados de ferramentas"], + ctxChat: ["Conversation","대화 내용","Unterhaltung","Conversation","会话内容","對話內容","Диалог","会話","Konuşma","Hội thoại","Conversa"], + ctxTurn: ["Turn {n}","{n}번째 턴","Runde {n}","Tour {n}","第 {n} 轮","第 {n} 輪","Ход {n}","第 {n} ターン","{n}. tur","Lượt {n}","Turno {n}"], + ctxEarlier: ["Earlier turns","이전 턴","Frühere Runden","Tours précédents","更早的轮次","更早的輪次","Более ранние ходы","それ以前のターン","Önceki turlar","Các lượt trước","Turnos anteriores"], + ctxFree: ["Free space","남은 공간","Freier Platz","Espace libre","剩余空间","剩餘空間","Свободное место","空き容量","Boş alan","Dung lượng trống","Espaço livre"], + ctxCacheHead: ["Prompt cache","프롬프트 캐시","Prompt-Cache","Cache de prompt","提示词缓存","提示詞快取","Кэш промпта","プロンプトキャッシュ","İstem önbelleği","Bộ nhớ đệm prompt","Cache de prompt"], + ctxCacheHit: ["{pct} hit","적중 {pct}","{pct} Treffer","{pct} de réussite","命中 {pct}","命中 {pct}","попаданий {pct}","ヒット {pct}","{pct} isabet","trúng {pct}","{pct} de acerto"], + ctxCacheSplit: ["{cached} cached · {fresh} new","캐시 {cached} · 신규 {fresh}","{cached} gecacht · {fresh} neu","{cached} en cache · {fresh} nouveaux","{cached} 已缓存 · {fresh} 新的","{cached} 已快取 · {fresh} 新的","{cached} из кэша · {fresh} новых","キャッシュ済み {cached} · 新規 {fresh}","{cached} önbellekte · {fresh} yeni","{cached} đã cache · {fresh} mới","{cached} em cache · {fresh} novos"], + ctxCacheUnknown: ["The provider didn't report cache usage.","업스트림이 캐시 사용량을 알려주지 않았어요.","Der Anbieter hat keine Cache-Nutzung gemeldet.","Le fournisseur n’a pas signalé l’usage du cache.","上游没有报告缓存。","上游沒有回報快取。","Провайдер не сообщил об использовании кэша.","プロバイダーがキャッシュ使用量を報告していません。","Sağlayıcı önbellek kullanımını bildirmedi.","Nhà cung cấp không báo cáo việc dùng cache.","O provedor não informou o uso do cache."], } satisfies Record; export type RouteLiveCopyKey = `routeLive.${keyof typeof rows}`; diff --git a/gui/src/pages/route-live/ContextCard.tsx b/gui/src/pages/route-live/ContextCard.tsx new file mode 100644 index 00000000000..c51b8b7c4b4 --- /dev/null +++ b/gui/src/pages/route-live/ContextCard.tsx @@ -0,0 +1,177 @@ +/** + * "Context window" card for the selected request: what filled the model's window (system prompt, + * tools, skills, memory, files, tool results, each conversation turn), as a treemap plus a legend, + * and a prompt-cache meter. The idea and the layout follow Magpie's context card (MIT, + * Copyright (c) 2026 yetone); the markup is this page's own. + */ +import { useEffect, useMemo, useRef, useState } from "react"; +import { useI18n, LOCALES } from "../../i18n/shared"; +import type { RouteLiveCopyKey } from "../../i18n/route-live-copy"; +import { + calibrateContext, contextHealth, layoutTiles, type ContextCategory, type ContextHealth, type ContextTile, +} from "./context-tiles"; +import { formatCount, formatPercent } from "./route-format"; +import { cacheMeterOf, countedInputTokens, type RouteRow } from "./route-rows"; + +type Kind = ContextCategory | "free"; + +const KIND_LABEL = { + system: "routeLive.ctxSystem", + tools: "routeLive.ctxTools", + skills: "routeLive.ctxSkills", + memory: "routeLive.ctxMemory", + files: "routeLive.ctxFiles", + results: "routeLive.ctxResults", + chat: "routeLive.ctxChat", + free: "routeLive.ctxFree", +} as const satisfies Record; + +const HEALTH_LABEL = { + ok: "routeLive.ctxHealthOk", + filling: "routeLive.ctxHealthFilling", + near: "routeLive.ctxHealthNear", +} as const satisfies Record; + +const LEGEND_ORDER: readonly Kind[] = ["system", "tools", "skills", "memory", "files", "results", "chat", "free"]; +const DEFAULT_WIDTH = 640; +const TILE_GAP = 2; + +/** Magpie's box: 3.1:1 (2:1 when narrow), never shorter than 132px or taller than 232px. */ +function boxHeight(width: number): number { + return Math.min(232, Math.max(132, width / (width <= 520 ? 2 : 3.1))); +} + +function useBoxWidth() { + const ref = useRef(null); + const [width, setWidth] = useState(DEFAULT_WIDTH); + useEffect(() => { + const node = ref.current; + if (!node) return undefined; + const measure = () => { + const next = Math.round(node.getBoundingClientRect().width); + if (next > 0) setWidth(next); + }; + measure(); + if (typeof ResizeObserver === "undefined") return undefined; + const observer = new ResizeObserver(measure); + observer.observe(node); + return () => observer.disconnect(); + }, []); + return [ref, width] as const; +} + +function CacheMeter({ row }: { row: RouteRow }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const meter = cacheMeterOf(row); + if (!meter) { + return ( +

    + {t("routeLive.ctxCacheHead")} {t("routeLive.ctxCacheUnknown")} +

    + ); + } + const percent = (100 * meter.read) / meter.total; + return ( +
    + {t("routeLive.ctxCacheHead")} + {t("routeLive.ctxCacheHit", { pct: formatPercent(percent, localeTag) })} +
    + +
    + + {t("routeLive.ctxCacheSplit", { + cached: formatCount(meter.read, localeTag), fresh: formatCount(meter.total - meter.read, localeTag), + })} + +
    + ); +} + +function ContextCardBody({ row }: { row: RouteRow }) { + const { t, locale } = useI18n(); + const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; + const [boxRef, width] = useBoxWidth(); + const breakdown = row.contextBreakdown!; + const windowTokens = row.contextWindow; + const shares = useMemo(() => calibrateContext(breakdown, countedInputTokens(row)), [breakdown, row]); + const height = boxHeight(width); + const tiles = useMemo(() => layoutTiles(shares, windowTokens, width, height), [shares, windowTokens, width, height]); + + const base = Math.max(windowTokens ?? shares.used, shares.used, 1); + const fraction = windowTokens ? shares.used / windowTokens : undefined; + const share = (tokens: number) => { + const value = tokens / base; + return value > 0 && value < 0.01 ? `<${formatPercent(1, localeTag)}` : formatPercent(100 * value, localeTag); + }; + const tokensText = (tokens: number) => formatCount(Math.round(tokens), localeTag); + const nameOf = (tile: Pick) => { + if (tile.turn !== undefined) return t("routeLive.ctxTurn", { n: tile.turn }); + return tile.earlier ? t("routeLive.ctxEarlier") : t(KIND_LABEL[tile.kind]); + }; + const freeTokens = tiles.find(tile => tile.kind === "free")?.tokens; + const legend = LEGEND_ORDER.flatMap(kind => { + const tokens = kind === "free" ? freeTokens : shares.parts[kind]; + return tokens !== undefined && tokens > 0 ? [{ kind, tokens }] : []; + }); + + return ( +
    +
    +

    + {windowTokens + ? t("routeLive.ctxHead", { used: tokensText(shares.used), window: formatCount(windowTokens, localeTag) }) + : t("routeLive.ctxHeadNoWindow", { used: tokensText(shares.used) })} +

    + {fraction !== undefined && ( + + {t("routeLive.ctxFill", { pct: formatPercent(100 * fraction, localeTag) })} + {" · "} + {t(HEALTH_LABEL[contextHealth(fraction)])} + + )} + {!shares.calibrated && {t("routeLive.ctxEstimated")}} +
    + {windowTokens === undefined &&

    {t("routeLive.ctxWindowUnknown")}

    } + +
    + {tiles.map(tile => { + const name = nameOf(tile); + const label = `${name} ${tokensText(tile.tokens)} (${share(tile.tokens)})`; + return ( +
    + {tile.w >= 48 && tile.h >= 18 && {name}} + {tile.w >= 64 && tile.h >= 34 && {tokensText(tile.tokens)} · {share(tile.tokens)}} +
    + ); + })} +
    +
      + {legend.map(item => ( +
    • +
    • + ))} +
    + {shares.held &&

    {t("routeLive.ctxHeld")}

    } +
    + ); +} + +/** Hidden for a row that carries no breakdown (an older request, or a path that does not record one). */ +export function ContextCard({ row }: { row: RouteRow }) { + return row.contextBreakdown ? : null; +} diff --git a/gui/src/pages/route-live/RouteLive.tsx b/gui/src/pages/route-live/RouteLive.tsx index 83de99359d0..43f1071eef8 100644 --- a/gui/src/pages/route-live/RouteLive.tsx +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -5,6 +5,7 @@ import { useMemo, useState } from "react"; import { useI18n, LOCALES } from "../../i18n/shared"; import { EmptyState, Notice } from "../../ui"; +import { ContextCard } from "./ContextCard"; import { FlowDiagram } from "./FlowDiagram"; import { buildRouteFlow, candidateWho, summarizePool, type FlowOutcome, type RouteFlow } from "./flow-model"; import { FailedDetail, ReasonText } from "./ReasonText"; @@ -83,6 +84,7 @@ function Selected({ row, flow, pinned, onBack }: { row: RouteRow; flow: RouteFlo {flow.outcome.kind !== "local" && } + {row.routeDecision?.routeKind === "combo" &&

    {t("routeLive.linkCombos")}

    } ); diff --git a/gui/src/pages/route-live/context-tiles.ts b/gui/src/pages/route-live/context-tiles.ts new file mode 100644 index 00000000000..5571d1ec186 --- /dev/null +++ b/gui/src/pages/route-live/context-tiles.ts @@ -0,0 +1,242 @@ +/** + * Context-window breakdown model: calibration against the measured prompt size, health word, + * and the treemap layout. Pure, no React. + * + * The squarified layout, the share^0.35 easing of the used share and the tile floors are ported + * from Magpie's internal/gui/assets/context.js. + * + * MIT License + * Copyright (c) 2026 yetone + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +export const CONTEXT_CATEGORIES = ["system", "tools", "skills", "memory", "files", "results", "chat"] as const; +export type ContextCategory = (typeof CONTEXT_CATEGORIES)[number]; + +/** `contextBreakdown` on a /api/logs row: estimated tokens of the request as the client sent it. */ +export interface ContextBreakdown { + v: 1; + parts: Record; + /** Per conversation turn, oldest first. */ + turns: number[]; + /** Older turns summed together; their count is not known. */ + turnsEarlier?: number; + toolCount: number; + /** Earlier turns live upstream (previous_response_id) and are not in the body. */ + held?: true; +} + +export interface ContextShares { + parts: Record; + turns: number[]; + turnsEarlier: number; + /** Sum of the parts: the measured input when calibrated, else the estimate. */ + used: number; + calibrated: boolean; + held: boolean; + toolCount: number; +} + +/** + * Scale every part and turn by counted / estimated so the pieces add up to what the provider + * counted. A request with a held upstream history keeps its estimate: the counted input also + * holds turns this body never carried, so a uniform scale would inflate the parts we can see. + */ +export function calibrateContext(breakdown: ContextBreakdown, counted: number | undefined): ContextShares { + const estimated = CONTEXT_CATEGORIES.reduce((sum, category) => sum + breakdown.parts[category], 0); + const held = breakdown.held === true; + const calibrated = !held && counted !== undefined && counted > 0 && estimated > 0; + const factor = calibrated ? counted / estimated : 1; + const parts = {} as Record; + for (const category of CONTEXT_CATEGORIES) parts[category] = breakdown.parts[category] * factor; + return { + parts, + turns: breakdown.turns.map(turn => turn * factor), + turnsEarlier: (breakdown.turnsEarlier ?? 0) * factor, + used: estimated * factor, + calibrated, held, toolCount: breakdown.toolCount, + }; +} + +export type ContextHealth = "ok" | "filling" | "near"; + +/** <75% roomy, <90% filling up, else near the limit (Magpie's thresholds). */ +export function contextHealth(fraction: number): ContextHealth { + if (fraction < 0.75) return "ok"; + return fraction < 0.9 ? "filling" : "near"; +} + +export interface ContextTile { + kind: ContextCategory | "free"; + /** 1-based position among the turns this row lists; only on a per-turn chat tile. */ + turn?: number; + /** The merged tile for turns older than the listed ones. */ + earlier?: true; + tokens: number; + x: number; + y: number; + w: number; + h: number; +} + +/** Magpie's constants: item tile floor/threshold in px^2, most turn tiles, thinnest part/item tile. */ +const TILE_MIN_AREA = 1500; +const TILE_MAX_TURNS = 12; +const TILE_FLOOR_AREA = 700; +const PART_MIN_SIDE = 16; +const TURN_MIN_SIDE = 14; +const USED_MIN_LEN = 36; + +interface Cell { v: number; item: T } +interface Placed { item: T; x: number; y: number; w: number; h: number } + +/** Bruls, Huizing and van Wijk: rectangles with sides as near alike as possible, in `cells` order. */ +function squarify(cells: Array>, x: number, y: number, w: number, h: number): Array> { + const out: Array> = []; + const live = cells.filter(cell => cell.v > 0); + const total = live.reduce((sum, cell) => sum + cell.v, 0); + if (total <= 0 || w <= 0 || h <= 0) return out; + const k = (w * h) / total; + const worst = (row: Array>, side: number): number => { + let sum = 0; + let hi = 0; + let lo = Infinity; + for (const cell of row) { + const area = cell.v * k; + sum += area; + hi = Math.max(hi, area); + lo = Math.min(lo, area); + } + return Math.max((side * side * hi) / (sum * sum), (sum * sum) / (side * side * lo)); + }; + const lay = (row: Array>): void => { + const sum = row.reduce((s, cell) => s + cell.v * k, 0); + if (w >= h) { + const colW = sum / h; + let cy = y; + for (const cell of row) { + const cellH = (cell.v * k) / colW; + out.push({ item: cell.item, x, y: cy, w: colW, h: cellH }); + cy += cellH; + } + x += colW; + w -= colW; + } else { + const rowH = sum / w; + let cx = x; + for (const cell of row) { + const cellW = (cell.v * k) / rowH; + out.push({ item: cell.item, x: cx, y, w: cellW, h: rowH }); + cx += cellW; + } + y += rowH; + h -= rowH; + } + }; + let row: Array> = []; + for (const cell of live) { + const side = Math.min(w, h); + if (row.length === 0 || worst([...row, cell], side) <= worst(row, side)) { + row.push(cell); + continue; + } + lay(row); + row = [cell]; + } + if (row.length > 0) lay(row); + return out; +} + +/** No tile smaller than TILE_FLOOR_AREA px^2: a sliver cannot be pointed at. */ +function floored(cells: Array>, area: number): Array> { + const sum = cells.reduce((s, cell) => s + cell.v, 0); + const lo = (sum * TILE_FLOOR_AREA) / Math.max(1, area); + return cells.map(cell => ({ ...cell, v: Math.max(cell.v, lo) })); +} + +interface TurnItem { turn?: number; earlier?: true } + +/** The chat rect split per turn: latest turns each, older ones merged, or null when they would be slivers. */ +function chatTurnTiles(shares: ContextShares, rect: Placed): ContextTile[] | null { + const area = rect.w * rect.h; + const listed = shares.turns.length; + const whole = shares.turns.reduce((s, v) => s + v, 0) + shares.turnsEarlier; + if (listed === 0 || whole <= 0 || area < TILE_MIN_AREA * 2) return null; + for (let keep = Math.min(listed, TILE_MAX_TURNS); keep >= 1; keep--) { + const first = listed - keep; + const cells: Array> = []; + for (let i = listed - 1; i >= first; i--) cells.push({ v: shares.turns[i]!, item: { turn: i + 1 } }); + const older = shares.turnsEarlier + shares.turns.slice(0, first).reduce((s, v) => s + v, 0); + if (older > 0) cells.push({ v: older, item: { earlier: true } }); + cells.sort((a, b) => b.v - a.v); + const laid = squarify(floored(cells, area), rect.x, rect.y, rect.w, rect.h); + if (laid.length === 0 || laid.some(tile => Math.min(tile.w, tile.h) < TURN_MIN_SIDE)) continue; + const real = new Map(cells.map(cell => [cell.item, cell.v])); + return laid.map(tile => ({ + kind: "chat" as const, ...tile.item, tokens: (real.get(tile.item)! / whole) * shares.parts.chat, + x: tile.x, y: tile.y, w: tile.w, h: tile.h, + })); + } + return null; +} + +/** + * Lay the request out as tiles in a width x height box. Parts are squarified inside the used + * share of the window; the used share is drawn as share^0.35 of the box (at least 36px) so a mostly + * empty window still leaves room to read its tiles, and the free space fills the rest. An unknown + * window gets no free tile. The tiles cover the box exactly, without overlap. + */ +export function layoutTiles(shares: ContextShares, windowTokens: number | undefined, width: number, height: number): ContextTile[] { + if (!(width > 0) || !(height > 0)) return []; + const used = CONTEXT_CATEGORIES.reduce((sum, category) => sum + Math.max(0, shares.parts[category]), 0); + const scale = Math.max(windowTokens ?? used, used, 1); + const across = width >= height; + const long = across ? width : height; + const hasFree = used < scale; + let usedLen = long; + if (hasFree) { + const eased = used > 0 ? long * Math.pow(used / scale, 0.35) : 0; + usedLen = used > 0 ? Math.min(long, Math.max(eased, Math.min(long, USED_MIN_LEN))) : 0; + } + const tiles: ContextTile[] = []; + const usedRect: [number, number, number, number] = across ? [0, 0, usedLen, height] : [0, 0, width, usedLen]; + const present = CONTEXT_CATEGORIES.filter(category => shares.parts[category] > 0); + + if (present.length > 0) { + const cells = floored(present.map(category => ({ v: shares.parts[category], item: category })), usedRect[2] * usedRect[3]); + let placed = squarify(cells, ...usedRect); + for (let pass = 0; pass < 8; pass++) { + const thin = placed.filter(rect => Math.min(rect.w, rect.h) < PART_MIN_SIDE); + if (thin.length === 0) break; + for (const rect of thin) { + const cell = cells.find(c => c.item === rect.item)!; + cell.v *= (PART_MIN_SIDE / Math.max(1, Math.min(rect.w, rect.h))) * 1.05; + } + placed = squarify(cells, ...usedRect); + } + for (const rect of placed) { + const split = rect.item === "chat" ? chatTurnTiles(shares, rect) : null; + if (split) tiles.push(...split); + else tiles.push({ kind: rect.item, tokens: shares.parts[rect.item], x: rect.x, y: rect.y, w: rect.w, h: rect.h }); + } + } + if (hasFree) { + const free: [number, number, number, number] = across ? [usedLen, 0, width - usedLen, height] : [0, usedLen, width, height - usedLen]; + tiles.push({ kind: "free", tokens: scale - used, x: free[0], y: free[1], w: free[2], h: free[3] }); + } + return tiles; +} diff --git a/gui/src/pages/route-live/route-live.css b/gui/src/pages/route-live/route-live.css index b46d338ce6f..dc0617a3009 100644 --- a/gui/src/pages/route-live/route-live.css +++ b/gui/src/pages/route-live/route-live.css @@ -77,6 +77,65 @@ .rl-time-dot { flex: 0 0 auto; width: 8px; height: 8px; border-radius: 50%; } .rl-time-legend .rl-num { color: var(--muted); } +/* context window card: one hue per category, light and dark through light-dark() */ +.rl-ctx { + --rl-ctx-system: light-dark(#7c3aed, #a78bfa); + --rl-ctx-results: light-dark(#c2410c, #fb923c); + --rl-ctx-chat: light-dark(#4f46e5, #818cf8); + display: flex; flex-direction: column; gap: var(--space-2); +} +.rl-ctx-head { display: flex; align-items: baseline; gap: var(--space-3); flex-wrap: wrap; } +.rl-ctx-health { font-size: var(--text-label); font-weight: var(--weight-semibold); } +.rl-ctx-health--ok { color: var(--green); } +.rl-ctx-health--filling { color: var(--amber); } +.rl-ctx-health--near { color: var(--red); } +.rl-ctx-badge { + padding: 0 var(--space-1-5); border-radius: var(--radius-xs); border: 1px solid var(--border); + background: var(--raised); color: var(--muted); font-size: var(--text-caption); cursor: help; +} +.rl-ctx-cache { display: flex; align-items: center; gap: var(--space-2); flex-wrap: wrap; margin: 0; font-size: var(--text-label); } +.rl-ctx-cache-head { color: var(--muted); } +.rl-ctx-meter { flex: 0 1 160px; min-width: 80px; height: 6px; border-radius: 3px; overflow: hidden; background: var(--raised); border: 1px solid var(--border); } +.rl-ctx-meter > i { display: block; height: 100%; background: var(--green); } +.rl-ctx-map { position: relative; width: 100%; } +.rl-ctx-tile, .rl-ctx-dot { + --k: var(--muted); +} +.rl-ctx-tile--system { --k: var(--rl-ctx-system); } +.rl-ctx-tile--tools { --k: var(--blue); } +.rl-ctx-tile--skills { --k: var(--muted); } +.rl-ctx-tile--memory { --k: var(--amber); } +.rl-ctx-tile--files { --k: var(--green); } +.rl-ctx-tile--results { --k: var(--rl-ctx-results); } +.rl-ctx-tile--chat { --k: var(--rl-ctx-chat); } +.rl-ctx-tile--free { --k: var(--muted); } +.rl-ctx-tile { + position: absolute; box-sizing: border-box; overflow: hidden; display: flex; flex-direction: column; gap: 1px; + padding: var(--space-1-5) var(--space-2); border-radius: var(--radius-sm); cursor: default; + background: color-mix(in srgb, var(--k) 12%, var(--surface)); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--k) 30%, transparent); +} +.rl-ctx-tile:hover { background: color-mix(in srgb, var(--k) 20%, var(--surface)); } +.rl-ctx-tile--free { + background: repeating-linear-gradient(-45deg, color-mix(in srgb, var(--text) 6%, transparent) 0 1px, transparent 1px 6px), var(--surface); + box-shadow: inset 0 0 0 1px var(--border-soft); +} +.rl-ctx-tile-name { + font-size: var(--text-caption); font-weight: var(--weight-semibold); line-height: 1.25; + color: color-mix(in srgb, var(--k) 70%, var(--text)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.rl-ctx-tile-value { + font-size: var(--text-micro); line-height: 1.25; color: var(--muted); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.rl-ctx-legend { + list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); + font-size: var(--text-label); +} +.rl-ctx-legend li { display: flex; align-items: center; gap: var(--space-1-5); } +.rl-ctx-dot { flex: 0 0 auto; width: 8px; height: 8px; border-radius: 2px; background: var(--k); } +.rl-ctx-dot.rl-ctx-tile--free { background: transparent; border: 1px dashed var(--muted); } + /* request list */ .rl-list { display: flex; flex-direction: column; gap: var(--space-2); min-width: 0; overflow-x: auto; } .rl-rows { list-style: none; margin: 0; padding: 0; min-width: 880px; } diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts index f0358ddcbc9..4177fb78a66 100644 --- a/gui/src/pages/route-live/route-rows.ts +++ b/gui/src/pages/route-live/route-rows.ts @@ -12,6 +12,7 @@ import { type LogRouteDecision, } from "../log-route-decision"; import { cacheSplit } from "../logs-token-title"; +import { CONTEXT_CATEGORIES, type ContextBreakdown } from "./context-tiles"; import type { formatEstimatedUsd } from "../logs-cost-format"; export const ROUTE_LIVE_ROW_CAP = 200; @@ -64,6 +65,10 @@ export interface RouteRow extends LogEntryBase { totalTokens?: number; attempts?: RouteAttempt[]; accountRoster?: RouteRoster; + /** Estimated size of each part of the request as the client sent it (src/server/context-breakdown.ts). */ + contextBreakdown?: ContextBreakdown; + /** The serving model's context window in tokens, when known. */ + contextWindow?: number; accountLogLabel?: string; accountTag?: string; conversationId?: string; @@ -98,11 +103,33 @@ function parseRoster(value: unknown): RouteRoster | undefined { : { provider: value.provider, accounts, ...(value.truncated === true ? { truncated: true as const } : {}) }; } +const tokenCount = (value: unknown): value is number => finite(value) && value >= 0; + +/** A breakdown missing any part, or carrying a negative or non-numeric size, is dropped whole. */ +export function parseContextBreakdown(value: unknown): ContextBreakdown | undefined { + if (!isRecord(value) || value.v !== 1 || !isRecord(value.parts) || !Array.isArray(value.turns)) return undefined; + const parts = {} as ContextBreakdown["parts"]; + for (const category of CONTEXT_CATEGORIES) { + const size = value.parts[category]; + if (!tokenCount(size)) return undefined; + parts[category] = size; + } + if (!value.turns.every(tokenCount) || !tokenCount(value.toolCount)) return undefined; + return { + v: 1, parts, turns: value.turns, toolCount: value.toolCount, + ...(tokenCount(value.turnsEarlier) && value.turnsEarlier > 0 ? { turnsEarlier: value.turnsEarlier } : {}), + ...(value.held === true ? { held: true as const } : {}), + }; +} + function parseRow(raw: unknown): RouteRow | null { if (!isRecord(raw) || !finite(raw.timestamp) || typeof raw.model !== "string" || typeof raw.provider !== "string" || !finite(raw.status) || !finite(raw.durationMs)) return null; - const { attempts, accountRoster, ...rest } = raw; + const { attempts, accountRoster, contextBreakdown, contextWindow, ...rest } = raw; const row = { ...rest } as unknown as RouteRow; + const breakdown = parseContextBreakdown(contextBreakdown); + if (breakdown) row.contextBreakdown = breakdown; + if (finite(contextWindow) && contextWindow > 0) row.contextWindow = contextWindow; const parsedAttempts = parseAttempts(attempts); if (parsedAttempts) row.attempts = parsedAttempts; const roster = parseRoster(accountRoster); @@ -169,13 +196,25 @@ export function tokenTotal(row: RouteRow): number | undefined { return finite(explicit) ? Math.max(explicit, base) : base; } +/** Input tokens the provider counted, cached ones included. Undefined when the row has no usable usage. */ +export function countedInputTokens(row: Pick): number | undefined { + const input = row.usage?.inputTokens; + return finite(input) && input > 0 ? input : undefined; +} + +/** Cached vs total input tokens. Unknown cache detail stays undefined, never a zero read. */ +export function cacheMeterOf(row: RouteRow): { read: number; total: number } | undefined { + const usage = row.usage; + const total = countedInputTokens(row); + if (!usage || total === undefined) return undefined; + const { read } = cacheSplit({ provider: row.provider, usage: { inputTokens: total, outputTokens: usage.outputTokens ?? 0, ...usage } }); + return finite(read) ? { read: Math.min(total, Math.max(0, read)), total } : undefined; +} + /** Cache read share of the input, 0..100. Unknown cache detail stays undefined, never 0. */ export function cacheHitPercent(row: RouteRow): number | undefined { - const usage = row.usage; - if (!usage || !finite(usage.inputTokens) || usage.inputTokens <= 0) return undefined; - const { read } = cacheSplit({ provider: row.provider, usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens ?? 0, ...usage } }); - if (!finite(read)) return undefined; - return Math.min(100, Math.max(0, (100 * read) / usage.inputTokens)); + const meter = cacheMeterOf(row); + return meter ? (100 * meter.read) / meter.total : undefined; } export function tokPerSecondOf(row: RouteRow): { value: number; estimated: boolean } | undefined { diff --git a/gui/tests/route-live-context.test.ts b/gui/tests/route-live-context.test.ts new file mode 100644 index 00000000000..3db0bd114d3 --- /dev/null +++ b/gui/tests/route-live-context.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, test } from "bun:test"; +import { + calibrateContext, contextHealth, layoutTiles, type ContextBreakdown, type ContextTile, +} from "../src/pages/route-live/context-tiles"; +import { cacheHitPercent, cacheMeterOf, parseRouteRows, type RouteRow } from "../src/pages/route-live/route-rows"; + +const breakdown = (over: Partial = {}): ContextBreakdown => ({ + v: 1, + parts: { system: 100, tools: 100, skills: 0, memory: 0, files: 0, results: 0, chat: 200 }, + turns: [50, 150], toolCount: 4, ...over, +}); + +const area = (tiles: ContextTile[]) => tiles.reduce((sum, tile) => sum + tile.w * tile.h, 0); + +function overlap(a: ContextTile, b: ContextTile): number { + const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x); + const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y); + return w > 0 && h > 0 ? w * h : 0; +} + +function expectCovers(tiles: ContextTile[], width: number, height: number) { + expect(area(tiles)).toBeCloseTo(width * height, 3); + for (const tile of tiles) { + expect(tile.x).toBeGreaterThanOrEqual(-1e-6); + expect(tile.y).toBeGreaterThanOrEqual(-1e-6); + expect(tile.x + tile.w).toBeLessThanOrEqual(width + 1e-6); + expect(tile.y + tile.h).toBeLessThanOrEqual(height + 1e-6); + } + for (let i = 0; i < tiles.length; i++) { + for (let j = i + 1; j < tiles.length; j++) expect(overlap(tiles[i]!, tiles[j]!)).toBeLessThan(1e-3); + } +} + +describe("context calibration", () => { + test("scales every part and turn by counted / estimated and marks the result calibrated", () => { + const shares = calibrateContext(breakdown({ turnsEarlier: 10 }), 800); + expect(shares.calibrated).toBe(true); + expect(shares.used).toBeCloseTo(800, 6); + expect(shares.parts.system).toBeCloseTo(200, 6); + expect(shares.parts.chat).toBeCloseTo(400, 6); + expect(shares.turns[0]).toBeCloseTo(100, 6); + expect(shares.turns[1]).toBeCloseTo(300, 6); + expect(shares.turnsEarlier).toBeCloseTo(20, 6); + }); + + test("without a counted size the estimate stands and is marked as such", () => { + for (const counted of [undefined, 0]) { + const shares = calibrateContext(breakdown(), counted); + expect(shares.calibrated).toBe(false); + expect(shares.used).toBe(400); + expect(shares.parts.tools).toBe(100); + } + }); + + test("a held upstream history is not scaled: the counted input also holds turns this body never carried", () => { + const shares = calibrateContext(breakdown({ held: true }), 5000); + expect(shares.held).toBe(true); + expect(shares.calibrated).toBe(false); + expect(shares.used).toBe(400); + }); + + test("health words flip at 75% and 90%", () => { + expect([0.1, 0.749, 0.75, 0.899, 0.9, 1.2].map(contextHealth)).toEqual(["ok", "ok", "filling", "filling", "near", "near"]); + }); +}); + +describe("context treemap layout", () => { + const WIDTH = 600; + const HEIGHT = 200; + + test("draws the used share as share^0.35 and fills the rest with one free tile, covering the box exactly", () => { + const shares = calibrateContext(breakdown(), 4000); + const tiles = layoutTiles(shares, 200_000, WIDTH, HEIGHT); + expectCovers(tiles, WIDTH, HEIGHT); + const free = tiles.filter(tile => tile.kind === "free"); + expect(free).toHaveLength(1); + expect(free[0]!.tokens).toBeCloseTo(196_000, 3); + expect(free[0]!.x).toBeCloseTo(WIDTH * Math.pow(4000 / 200_000, 0.35), 3); + expect(tiles.filter(tile => tile.kind !== "free").reduce((sum, tile) => sum + tile.tokens, 0)).toBeCloseTo(4000, 3); + }); + + test("an unknown window, or a prompt past the window, has no free tile and the parts fill the box", () => { + const shares = calibrateContext(breakdown(), 4000); + for (const window of [undefined, 3000, 4000]) { + const tiles = layoutTiles(shares, window, WIDTH, HEIGHT); + expect(tiles.some(tile => tile.kind === "free")).toBe(false); + expectCovers(tiles, WIDTH, HEIGHT); + } + }); + + test("a tiny part still gets a tile large enough to point at", () => { + const parts = { system: 50_000, tools: 30_000, skills: 3, memory: 0, files: 0, results: 0, chat: 20_000 }; + const shares = calibrateContext(breakdown({ parts, turns: [], toolCount: 1 }), undefined); + const tiles = layoutTiles(shares, 200_000, WIDTH, HEIGHT); + expectCovers(tiles, WIDTH, HEIGHT); + const skills = tiles.find(tile => tile.kind === "skills")!; + expect(Math.min(skills.w, skills.h)).toBeGreaterThanOrEqual(14); + }); + + test("an empty prompt with a known window is one free tile", () => { + const parts = { system: 0, tools: 0, skills: 0, memory: 0, files: 0, results: 0, chat: 0 }; + const tiles = layoutTiles(calibrateContext(breakdown({ parts, turns: [] }), undefined), 1000, WIDTH, HEIGHT); + expect(tiles.map(tile => tile.kind)).toEqual(["free"]); + expectCovers(tiles, WIDTH, HEIGHT); + }); + + test("chat splits into per-turn tiles that add up to the chat part, with older turns merged", () => { + const turns = Array.from({ length: 20 }, (_, i) => 3000 + i * 100); + const chat = turns.reduce((s, v) => s + v, 0) + 500; + const big = breakdown({ + parts: { system: 20_000, tools: 10_000, skills: 0, memory: 0, files: 0, results: 0, chat }, + turns, turnsEarlier: 500, toolCount: 9, + }); + const tiles = layoutTiles(calibrateContext(big, undefined), 200_000, 900, 260); + expectCovers(tiles, 900, 260); + const chatTiles = tiles.filter(tile => tile.kind === "chat"); + const perTurn = chatTiles.filter(tile => tile.turn !== undefined); + expect(perTurn.length).toBeGreaterThan(1); + expect(perTurn.length).toBeLessThanOrEqual(12); + expect(perTurn.every(tile => Math.min(tile.w, tile.h) >= 14)).toBe(true); + expect(Math.max(...perTurn.map(tile => tile.turn!))).toBe(20); + expect(chatTiles.filter(tile => tile.earlier)).toHaveLength(1); + expect(chatTiles.reduce((sum, tile) => sum + tile.tokens, 0)).toBeCloseTo(chat, 3); + }); + + test("when the turns would be slivers, chat stays one tile", () => { + const tiles = layoutTiles(calibrateContext(breakdown(), undefined), 200_000, 80, 40); + expectCovers(tiles, 80, 40); + expect(tiles.filter(tile => tile.kind === "chat")).toHaveLength(1); + expect(tiles.find(tile => tile.kind === "chat")!.turn).toBeUndefined(); + }); +}); + +describe("cache meter and parsing", () => { + const row = (usage: RouteRow["usage"]) => ({ timestamp: 1, model: "m", provider: "anthropic", status: 200, durationMs: 5, usage }) as RouteRow; + + test("an unreported cache is unknown, a reported zero is a real 0%", () => { + expect(cacheMeterOf(row({ inputTokens: 1000, outputTokens: 10 }))).toBeUndefined(); + expect(cacheHitPercent(row({ inputTokens: 1000, outputTokens: 10 }))).toBeUndefined(); + expect(cacheMeterOf(row(undefined))).toBeUndefined(); + expect(cacheMeterOf(row({ inputTokens: 1000, outputTokens: 10, cacheReadInputTokens: 0 }))).toEqual({ read: 0, total: 1000 }); + expect(cacheMeterOf(row({ inputTokens: 1000, outputTokens: 10, cacheReadInputTokens: 250 }))).toEqual({ read: 250, total: 1000 }); + expect(cacheHitPercent(row({ inputTokens: 1000, outputTokens: 10, cacheReadInputTokens: 250 }))).toBe(25); + }); + + test("the parser keeps a valid breakdown and window and drops malformed ones", () => { + const base = { timestamp: 1, model: "m", provider: "p", status: 200, durationMs: 5 }; + const good = breakdown(); + const rows = parseRouteRows([ + { ...base, requestId: "good", timestamp: 9, contextBreakdown: { ...good, extra: "ignored", held: true, turnsEarlier: 5 }, contextWindow: 200_000 }, + { ...base, requestId: "negative", timestamp: 8, contextBreakdown: { ...good, parts: { ...good.parts, tools: -1 } }, contextWindow: -5 }, + { ...base, requestId: "missing", timestamp: 7, contextBreakdown: { ...good, parts: { system: 1 } }, contextWindow: "big" }, + { ...base, requestId: "turns", timestamp: 6, contextBreakdown: { ...good, turns: [1, "2"] }, contextWindow: 0 }, + { ...base, requestId: "version", timestamp: 5, contextBreakdown: { ...good, v: 2 } }, + { ...base, requestId: "shape", timestamp: 4, contextBreakdown: "nope", contextWindow: Number.NaN }, + { ...base, requestId: "old", timestamp: 3 }, + ]); + const byId = Object.fromEntries(rows.map(r => [r.requestId, r])); + expect(byId.good!.contextBreakdown).toEqual({ ...good, held: true, turnsEarlier: 5 }); + expect(byId.good!.contextWindow).toBe(200_000); + for (const id of ["negative", "missing", "turns", "version", "shape", "old"]) { + expect(byId[id]!.contextBreakdown).toBeUndefined(); + expect(byId[id]!.contextWindow).toBeUndefined(); + } + }); +}); diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 54a64145f9f..79caf658107 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -3,6 +3,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import type { ReactNode } from "react"; import { Window } from "happy-dom"; import { I18nContext, DICTS, interpolate, LOCALES, type Locale, type TFn } from "../src/i18n/shared"; +import { ContextCard } from "../src/pages/route-live/ContextCard"; import { FlowDiagram } from "../src/pages/route-live/FlowDiagram"; import { RequestList } from "../src/pages/route-live/RequestList"; import { RouteSteps } from "../src/pages/route-live/RouteSteps"; @@ -87,6 +88,49 @@ test("time bar lists each measured stage in order with its label, or a note when expect(bare.querySelector("p")?.textContent).toContain("没有记录时间分布"); }); +const withContext = (extra: Partial = {}) => ({ + ...failover, + usage: { inputTokens: 1000, outputTokens: 200, cacheReadInputTokens: 500 }, + contextWindow: 200_000, + contextBreakdown: { + v: 1, toolCount: 3, turns: [100, 250], + parts: { system: 100, tools: 200, skills: 0, memory: 50, files: 0, results: 300, chat: 350 }, + }, + ...extra, +}) as unknown as RouteRow; + +test("context card shows the used/window header, labelled tiles that fill the window, the legend and the cache meter", () => { + const doc = render(); + expect(doc.querySelector("h4")?.textContent).toMatch(/^上下文用量 .+ \/ .+$/); + expect(doc.querySelector(".rl-ctx-health")?.textContent).toContain("还很宽裕"); + expect(doc.querySelector(".rl-ctx-badge")).toBeNull(); + const labels = [...doc.querySelectorAll(".rl-ctx-tile")].map(tile => tile.getAttribute("aria-label") ?? ""); + expect(labels.some(label => label.startsWith("系统提示词 "))).toBe(true); + expect(labels.some(label => label.startsWith("第 2 轮 "))).toBe(true); + expect(labels.some(label => label.startsWith("剩余空间 "))).toBe(true); + expect([...doc.querySelectorAll(".rl-ctx-legend li > span:nth-child(2)")].map(s => s.textContent)).toEqual( + ["系统提示词", "工具", "记忆与 AGENTS.md", "工具结果", "会话内容", "剩余空间"]); + expect(doc.querySelector(".rl-ctx-cache")?.textContent).toContain("命中 50%"); + expect(doc.querySelector(".rl-ctx-cache")?.textContent).toContain("已缓存"); + expect(doc.querySelector(".rl-ctx-meter")?.getAttribute("aria-valuenow")).toBe("50"); +}); + +test("context card says so when the window is unknown, the sizes are estimated, the cache is unreported or the history is held", () => { + const bare = withContext({ usage: undefined, contextWindow: undefined }); + const doc = render(); + expect(doc.querySelector(".rl-ctx-badge")?.textContent).toBe("估算"); + expect(doc.body.textContent).toContain("不知道这个模型的上下文窗口"); + expect(doc.body.textContent).toContain("上文由上游保存,这里看不到"); + expect(doc.querySelector(".rl-ctx-cache")?.textContent).toContain("上游没有报告缓存"); + expect(doc.querySelector(".rl-ctx-meter")).toBeNull(); + expect(doc.body.textContent).not.toContain("命中 0%"); + expect([...doc.querySelectorAll(".rl-ctx-tile")].some(tile => tile.getAttribute("aria-label")?.startsWith("剩余空间"))).toBe(false); +}); + +test("context card is hidden for a row without a breakdown", () => { + expect(render().body.innerHTML).toBe(""); +}); + test.each(LOCALES)("every reason key the registry points at has copy in $code", ({ code }) => { for (const group of Object.values(ROUTE_REASONS)) { for (const key of Object.values(group)) expect(DICTS[code][key]?.length).toBeGreaterThan(0); From ab48182384daaa0304ca48390a8f05d9e4a494a3 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 18:59:38 -0500 Subject: [PATCH 11/12] docs(routing): describe the live context-window breakdown --- docs-site/src/content/docs/guides/model-routing.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index 467cbcdc09e..963386661cd 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -164,6 +164,10 @@ the list below it, you see: finished: paused, needing sign-in, cooling down, out of quota, or not listing the model. - **Where the time went.** OpenCodex's own time, earlier failed attempts, the wait for the first token, and streaming. Every segment is measured; DNS and TLS are not split out. +- **The context window.** Estimated tokens for the system prompt, tools, skills, memory files such + as `AGENTS.md` and `CLAUDE.md`, files, tool results and each conversation turn, against the free + space in the serving model's window, plus the prompt-cache hit rate. Only sizes are recorded, + never prompt text, and they live in memory with the request log. The request list groups by request, session or API key and shows the account, model, effort, duration, time to first token, tokens, cache-hit rate, tokens per second and estimated cost. From eb826d80814eaaa6e312e5f2d03976157833bf57 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 19:12:46 -0500 Subject: [PATCH 12/12] fix(gui): translate the French conversation label in the context card --- gui/src/i18n/route-live-copy.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index 2cdfaedbdae..df18210e1c5 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -127,7 +127,7 @@ const rows = { ctxMemory: ["Memory and AGENTS.md","메모리 및 AGENTS.md","Speicher und AGENTS.md","Mémoire et AGENTS.md","记忆与 AGENTS.md","記憶與 AGENTS.md","Память и AGENTS.md","メモリと AGENTS.md","Bellek ve AGENTS.md","Bộ nhớ và AGENTS.md","Memória e AGENTS.md"], ctxFiles: ["Files","파일","Dateien","Fichiers","文件","檔案","Файлы","ファイル","Dosyalar","Tệp","Arquivos"], ctxResults: ["Tool results","도구 결과","Tool-Ergebnisse","Résultats d’outils","工具结果","工具結果","Результаты инструментов","ツール結果","Araç sonuçları","Kết quả công cụ","Resultados de ferramentas"], - ctxChat: ["Conversation","대화 내용","Unterhaltung","Conversation","会话内容","對話內容","Диалог","会話","Konuşma","Hội thoại","Conversa"], + ctxChat: ["Conversation","대화 내용","Unterhaltung","Échanges","会话内容","對話內容","Диалог","会話","Konuşma","Hội thoại","Conversa"], ctxTurn: ["Turn {n}","{n}번째 턴","Runde {n}","Tour {n}","第 {n} 轮","第 {n} 輪","Ход {n}","第 {n} ターン","{n}. tur","Lượt {n}","Turno {n}"], ctxEarlier: ["Earlier turns","이전 턴","Frühere Runden","Tours précédents","更早的轮次","更早的輪次","Более ранние ходы","それ以前のターン","Önceki turlar","Các lượt trước","Turnos anteriores"], ctxFree: ["Free space","남은 공간","Freier Platz","Espace libre","剩余空间","剩餘空間","Свободное место","空き容量","Boş alan","Dung lượng trống","Espaço livre"],