From 0f5916fcbf1d5f8f9476a52243e1ed7f6185a7a9 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:12:57 -0500 Subject: [PATCH 01/18] feat(gui): live routing tab: see which account answered, why others were skipped, and where the time went Original PR: #8730 --- .../src/content/docs/guides/model-routing.md | 17 ++ 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 | 122 +++++++++++ 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 | 77 +++++++ gui/src/pages/route-live/ReasonText.tsx | 18 ++ gui/src/pages/route-live/RequestList.tsx | 162 +++++++++++++++ gui/src/pages/route-live/RouteLive.tsx | 118 +++++++++++ gui/src/pages/route-live/RouteSteps.tsx | 54 +++++ gui/src/pages/route-live/TimeBar.tsx | 67 ++++++ gui/src/pages/route-live/flow-model.ts | 155 ++++++++++++++ gui/src/pages/route-live/request-groups.ts | 71 +++++++ gui/src/pages/route-live/route-format.ts | 57 ++++++ gui/src/pages/route-live/route-live.css | 109 ++++++++++ gui/src/pages/route-live/route-reasons.ts | 65 ++++++ gui/src/pages/route-live/route-rows.ts | 192 ++++++++++++++++++ gui/src/pages/route-live/slots.ts | 9 + gui/src/pages/route-live/time-parts.ts | 64 ++++++ 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 | 107 ++++++++++ gui/tests/route-live-render.test.tsx | 94 +++++++++ gui/tests/route-live-time.test.ts | 72 +++++++ scripts/test-layout/layout-usage.json | 3 + src/oauth/generic-account-failover.ts | 53 +++++ src/server/management/oauth-account-routes.ts | 3 +- src/server/request-log-route-live.ts | 83 ++++++++ src/server/request-log.ts | 7 +- tests/fixtures/test-layout-expected.json | 4 +- tests/gui/models-workspace-tabs.test.ts | 2 +- tests/oauth/oauth-accounts-log-label.test.ts | 74 +++++++ .../usage/request-log-account-roster.test.ts | 152 ++++++++++++++ .../request-log-route-live-timing.test.ts | 31 +++ 50 files changed, 2177 insertions(+), 30 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/TimeBar.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/time-parts.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 create mode 100644 gui/tests/route-live-time.test.ts 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 create mode 100644 tests/usage/request-log-route-live-timing.test.ts 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 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..d9c76eb8010 --- /dev/null +++ b/gui/src/i18n/route-live-copy.ts @@ -0,0 +1,122 @@ +/* + * 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}","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"], + 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","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"], + 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","Logiciel client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente"], + colModel: ["Model","모델","Modell","Modèle","模型","模型","Модель","モデル","Model","Mô hình","Modelo"], + 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"], + 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"], + 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"], + 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…"], + 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}`; + +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..7ea3751bb8a --- /dev/null +++ b/gui/src/pages/route-live/FlowDiagram.tsx @@ -0,0 +1,77 @@ +/** 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(); + } + 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..316fa4b4e8c --- /dev/null +++ b/gui/src/pages/route-live/RequestList.tsx @@ -0,0 +1,162 @@ +/** + * 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, readableAccountLabel, requestedOf, rowAccountLabel, servingProviderOf, 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 ?? 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 }: { + 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..83de99359d0 --- /dev/null +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -0,0 +1,118 @@ +/** + * 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 { TimeSection } from "./TimeBar"; +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 && } +
    + + + + + {flow.outcome.kind !== "local" && } + {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/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/flow-model.ts b/gui/src/pages/route-live/flow-model.ts new file mode 100644 index 00000000000..5c8c4fbf841 --- /dev/null +++ b/gui/src/pages/route-live/flow-model.ts @@ -0,0 +1,155 @@ +/** + * 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 { readableAccountLabel, requestedOf, 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 ? readableAccountLabel(c.accountLabel, c.provider) : 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: requestedOf(row), + }, + 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..e9920edb354 --- /dev/null +++ b/gui/src/pages/route-live/route-format.ts @@ -0,0 +1,57 @@ +/** 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); +} + +/** 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); +} + +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..b46d338ce6f --- /dev/null +++ b/gui/src/pages/route-live/route-live.css @@ -0,0 +1,109 @@ +/* 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); } + +/* 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; } +.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..2fc38e5b1b2 --- /dev/null +++ b/gui/src/pages/route-live/route-reasons.ts @@ -0,0 +1,65 @@ +/** + * 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", + "explicit-provider-namespace": "routeLive.whyExplicitProvider", + "explicit-account": "routeLive.whyExplicitProvider", + "model-alias": "routeLive.whyModelAlias", + "model-pattern": "routeLive.whyModelPattern", + "native": "routeLive.whyNative", + "native-family": "routeLive.whyNative", + }, +}; + +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..f0358ddcbc9 --- /dev/null +++ b/gui/src/pages/route-live/route-rows.ts @@ -0,0 +1,192 @@ +/** + * 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; + /** 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?: { + 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; +} + +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; +} + +/** 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/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/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..3ee6048822e --- /dev/null +++ b/gui/tests/route-live-model.test.ts @@ -0,0 +1,107 @@ +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, 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); + +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" }]); + }); +}); + +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"); + }); +}); diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx new file mode 100644 index 00000000000..54a64145f9f --- /dev/null +++ b/gui/tests/route-live-render.test.tsx @@ -0,0 +1,94 @@ +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 { 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"; + +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("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(); + }); +}); diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index f7c547b8f8d..207ba3725f5 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -3,6 +3,9 @@ "usage-filter-index.test.ts": "usage", "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", "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..399c9491ead --- /dev/null +++ b/src/server/request-log-route-live.ts @@ -0,0 +1,83 @@ +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 {}; + } +} + +/** 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 09bce7a2bd6..35b1cdfa55a 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, 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"; @@ -125,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; @@ -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, RouteLiveTimingEntryField { requestId: string; client?: UsageClient; /** The logical request this row belongs to (#4546); absent on rows written without a budget. */ @@ -1684,6 +1685,8 @@ function writeFinalRequestLog( ...(logCtx.transportPhase ? { transportPhase: logCtx.transportPhase } : {}), ...(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 ebfabf37355..e99fa793a15 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-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/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"); 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"); + }); +}); 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 146373d1b90516bd69ff08a55ae06db4a63ae68f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:14:44 -0500 Subject: [PATCH 02/18] feat(gui): context-window breakdown and prompt-cache meter on the live routing tab Original PR: #8731 --- .../src/content/docs/guides/model-routing.md | 4 + 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 ++ 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 +++ 20 files changed, 1931 insertions(+), 10 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 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/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. diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index d9c76eb8010..df18210e1c5 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","É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"], + 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); 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 329f65eded7fed2d26f87fb1ae0eeb9879f478ee Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:15:24 -0500 Subject: [PATCH 03/18] feat(usage): serve a read-only live meter on GET /v1/usage/live Original PR: #8735 --- .../docs/es/reference/management-api.md | 16 ++ .../content/docs/reference/management-api.md | 14 ++ .../docs/zh-cn/reference/management-api.md | 14 ++ .../docs/zh-tw/reference/management-api.md | 14 ++ scripts/test-layout/layout.json | 4 +- src/server/auth-cors.ts | 2 + src/server/index.ts | 2 + src/server/index/serve-options.ts | 10 + src/server/live-meter-handler.ts | 125 +++++++++++ src/usage/live-meter.ts | 138 ++++++++++++ structure/runtime.md | 2 +- structure/usage-client-attribution.md | 4 + tests/fixtures/test-layout-expected.json | 4 +- tests/server/api-key-attribution.test.ts | 2 +- tests/server/live-meter-handler.test.ts | 205 ++++++++++++++++++ .../loopback-listener-admission.test.ts | 6 + tests/usage/live-meter.test.ts | 108 +++++++++ 17 files changed, 664 insertions(+), 6 deletions(-) create mode 100644 src/server/live-meter-handler.ts create mode 100644 src/usage/live-meter.ts create mode 100644 tests/server/live-meter-handler.test.ts create mode 100644 tests/usage/live-meter.test.ts diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 830a877507d..1e942f2fbb0 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -394,6 +394,22 @@ Las solicitudes PUT válidas a `/api/selected-models` y `/api/model-presets` dev La visibilidad/selección exitosa escribe a `/api/disabled-models`, `/api/model-visibility`, `/api/selected-models` y `/api/model-presets` para informar los resultados de seguimiento en `catalogRefresh` y `clientIntegrations` cuando se ejecuta esa ruta de actualización. HTTP 200 y `ok: true` confirman la selección guardar; no garantizan todos los catálogos de clientes actualizados. Inspeccione `clientIntegrations[]` para `ok: false`, `client`, opcional Aparte `profileId`, y el rechazo `reason`; los detalles de recuperación también pueden incluir `refusalReason`, `snapshotPath` y `residual`. La página Modelos mantiene la selección guardada y muestra una advertencia de actualización del cliente por separado. Inspeccione las integraciones y resuelva el problema notificado antes de volver a intentar `ocx sync`. Los campos de resultado que faltan de un servidor antiguo no establecen una recuperación exitosa. + + +### Medidor en vivo (`GET /v1/usage/live`) + +Un endpoint de solo lectura del plano de datos informa de la solicitud completada más reciente: velocidad de salida, acierto de caché y ocupación del contexto. Un cliente, como un userscript de Codex de escritorio, puede consultarlo para mostrar esas cifras junto al compositor. Se admite exactamente igual que `/v1/models`: sin credencial en un enlace loopback, con una clave de datos (`x-opencodex-api-key`, `Authorization: Bearer` o `x-api-key`) en otro caso, y nunca con el token de administración. El origen de la página de Codex de escritorio `app://-` puede leer solo esta ruta (y su preflight); las demás rutas del plano de datos conservan sus reglas de origen. + +Consulta: `client=codex|claude|other` limita el resultado a una familia de clientes y `conversation=` a una conversación. El filtro de conversación acepta el id original, el resumen registrado o un enlace `codex://threads/`, y la respuesta nunca lo repite. El cuerpo es `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": }`. Un `Meter` contiene `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` y `timestamp`: solo números, nombres de modelo y proveedor y códigos de motivo. Las revisiones automáticas de aprobación (`codex-auto-review`) nunca se informan. + +Un valor es `null` (se muestra como `--`) en lugar de una estimación cuando no se puede medir: + +| Valor | `null` cuando | +| --- | --- | +| `speed` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. | +| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada o la lectura de caché solo existe en el cable. | +| `context.percent` | El uso falta o es estimado, o la ventana de contexto del modelo no está en el catálogo persistido de Codex (`context.reason` es `limit_unknown`). | + ### Cuentas OAuth, claves de proveedor y claves de plano de datos diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 53f32c3e469..23031f7e632 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -672,6 +672,20 @@ The Models page keeps the saved selection and shows a separate client-refresh wa Inspect Integrations and resolve the reported issue before retrying `ocx sync`. Missing outcome fields from an older server do not establish successful recovery. +### Live meter (`GET /v1/usage/live`) + +A read-only data-plane endpoint reports the newest completed request: output speed, cache hit and context fill. A client such as a Codex desktop userscript can poll it to show those numbers next to the composer. It is admitted exactly like `/v1/models`: no credential on a loopback bind, a data key (`x-opencodex-api-key`, `Authorization: Bearer` or `x-api-key`) otherwise, and never the admin token. The Codex desktop page origin `app://-` may read this one route (and its preflight); every other data-plane route keeps its existing origin rules. + +Query: `client=codex|claude|other` narrows the result to one client family, and `conversation=` to one conversation. The conversation filter accepts the raw id, the logged digest or a `codex://threads/` link, and the response never echoes it. The body is `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": }`. A `Meter` carries `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` and `timestamp`: numbers, model and provider names and reason codes only. Automatic approval reviews (`codex-auto-review`) are never reported. + +A value is `null` (shown as `--`) instead of a guess when it cannot be measured: + +| Value | `null` when | +| --- | --- | +| `speed` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent. Speed is output tokens over the generation window, never wall time. | +| `cache.percent` | Usage is missing or estimated, the input count is missing or the cache read is wire-only. | +| `context.percent` | Usage is missing or estimated, or the model's context window is not in the persisted Codex catalog (`context.reason` is `limit_unknown`). | + ### OAuth accounts, provider keys, and data-plane keys OAuth account rows always include `plan`: a validated upstream subscription label or `null` diff --git a/docs-site/src/content/docs/zh-cn/reference/management-api.md b/docs-site/src/content/docs/zh-cn/reference/management-api.md index 73c78e12265..2dcba3021f5 100644 --- a/docs-site/src/content/docs/zh-cn/reference/management-api.md +++ b/docs-site/src/content/docs/zh-cn/reference/management-api.md @@ -227,6 +227,20 @@ Aside 配置档的变更在这种情况下仍会保存一件事:确认之后 可靠的初始模型列表尚未确认时,有效的 `PUT /api/selected-models` 和 `PUT /api/model-presets` 请求也会返回 HTTP 409 和代码 `initial_model_selection_pending`。请使用 `GET /api/models` 等方式刷新模型列表,成功后再重试。 +### 实时指标(`GET /v1/usage/live`) + +只读的数据平面端点,返回最近一次已完成请求的输出速度、缓存命中率和上下文占用,例如供 Codex 桌面端用户脚本在输入框旁显示。准入与 `/v1/models` 完全相同:回环绑定无需凭据,否则需要数据密钥(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永远不接受管理令牌。Codex 桌面端页面来源 `app://-` 仅可读取这一条路由(及其预检),其他数据平面路由的来源规则不变。 + +查询参数:`client=codex|claude|other` 限定客户端类别,`conversation=` 限定单个会话;会话过滤接受原始 id、日志中的摘要或 `codex://threads/` 链接,响应不会回显它。响应体为 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有数字、模型与 provider 名称和原因码。自动审批审查(`codex-auto-review`)不会被报告。 + +无法测量时对应值为 `null`(显示为 `--`),绝不猜测: + +| 值 | 为 `null` 的情况 | +| --- | --- | +| `speed` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致。速度是输出 token 除以生成窗口,而不是墙钟时间。 | +| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取仅存在于线路层。 | +| `context.percent` | 用量缺失或为估算值,或该模型的上下文窗口不在已持久化的 Codex 目录中(`context.reason` 为 `limit_unknown`)。 | + ### OAuth 账户、provider 密钥和数据平面密钥 | 方法和路径 | 用途 | 典型错误 | diff --git a/docs-site/src/content/docs/zh-tw/reference/management-api.md b/docs-site/src/content/docs/zh-tw/reference/management-api.md index c2405560e68..371fb4d2eef 100644 --- a/docs-site/src/content/docs/zh-tw/reference/management-api.md +++ b/docs-site/src/content/docs/zh-tw/reference/management-api.md @@ -230,6 +230,20 @@ Aside 設定檔的變更在這種情況下仍會儲存一件事:確認之後 尚未確認可靠的初始模型清單時,有效的 `PUT /api/selected-models` 和 `PUT /api/model-presets` 請求也會回傳 HTTP 409 和代碼 `initial_model_selection_pending`。請使用 `GET /api/models` 等方式更新模型清單,成功後再重試。 +### 即時指標(`GET /v1/usage/live`) + +唯讀的資料平面端點,回傳最近一次已完成請求的輸出速度、快取命中率與上下文占用,例如供 Codex 桌面端使用者腳本在輸入框旁顯示。存取許可與 `/v1/models` 完全相同:回送綁定不需憑證,否則需要資料金鑰(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永遠不接受管理權杖。Codex 桌面端頁面來源 `app://-` 僅可讀取這一條路由(及其預檢),其他資料平面路由的來源規則不變。 + +查詢參數:`client=codex|claude|other` 限定用戶端類別,`conversation=` 限定單一對話;對話過濾接受原始 id、日誌中的摘要或 `codex://threads/` 連結,回應不會回顯它。回應本體為 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有數字、模型與供應商名稱和原因碼。自動核准審查(`codex-auto-review`)不會被回報。 + +無法量測時對應值為 `null`(顯示為 `--`),絕不猜測: + +| 值 | 為 `null` 的情況 | +| --- | --- | +| `speed` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 | +| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取僅存在於線路層。 | +| `context.percent` | 用量缺失或為估算值,或該模型的上下文視窗不在已持久化的 Codex 目錄中(`context.reason` 為 `limit_unknown`)。 | + ### OAuth 帳號、供應商金鑰與 data-plane 金鑰 | 方法與路徑 | 用途 | 主要錯誤 | diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 05605249cbe..fce0f1ecba4 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -23,7 +23,7 @@ "anthropic2-discovery-ownership.test.ts": "oauth", "codex-shim-runtime-preflight.test.ts": "codex-integration", "cli-anthropic2-account.test.ts": "cli", "anthropic2-catalog.test.ts": "codex-integration", "provider-anthropic-instance-quota.test.ts": "providers", "anthropic2-management.test.ts": "server", - "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search", + "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "live-meter.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search", "provider-anthropic-instance.test.ts": "providers", "config-anthropic-instance-pool.test.ts": "config", "oauth-anthropic-instance-registration.test.ts": "oauth", "oauth-anthropic-instance-refresh.test.ts": "oauth", "model-costs-pricing-cache.test.ts": "server", "model-costs-prompt-length-pricing.test.ts": "server", "cli-models-prompt-length-pricing.test.ts": "cli", "usage-prompt-length-pricing.test.ts": "usage", "claude-picker-upload.test.ts": "claude-integration", "claude-picker-linger.test.ts": "claude-integration", "messages-native-scope.test.ts": "claude-integration", "catalog-auto-review-row.test.ts": "codex-integration", @@ -1049,7 +1049,7 @@ "history-paginated-transition-destinations.test.ts": "codex-integration", "hub-gated-local-clients.test.ts": "cli", "hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli", - "hub-usage.test.ts": "server", + "hub-usage.test.ts": "server", "live-meter-handler.test.ts": "server", "hyperbolic-provider.test.ts": "providers", "identity-neutralize.test.ts": "adapters", "identity-subagent.test.ts": "adapters", diff --git a/src/server/auth-cors.ts b/src/server/auth-cors.ts index 7ea7487797e..49046566dfc 100644 --- a/src/server/auth-cors.ts +++ b/src/server/auth-cors.ts @@ -704,6 +704,8 @@ export const AUTH_MATRIX: readonly ApiAuthMatrixRow[] = [ { endpoint: "/v1/hub-state", bearer: "accepted", dedicated: "accepted", xApiKey: "accepted" }, // Usage additionally requires a configured key identity; unscoped environment keys are refused. { endpoint: "/v1/usage", bearer: "rejected", dedicated: "accepted", xApiKey: "rejected" }, + // The live meter reads the in-process request log only (numbers and model names), admitted like /v1/models. + { endpoint: "/v1/usage/live", bearer: "accepted", dedicated: "accepted", xApiKey: "accepted" }, ]; /** Whether `token` is the environment-provided management secret. */ diff --git a/src/server/index.ts b/src/server/index.ts index 6d2f25b2ee4..7350c366d34 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -413,6 +413,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe if (path === "/v1/audio/transcriptions") return req.method === "POST"; if (path === "/v1/audio/transcriptions/stream") return req.headers.get("upgrade")?.toLowerCase() === "websocket"; if (path === "/v1/alpha/search") return req.method === "POST"; + // Live meter (#8735): GET-only numbers from the local request log; Codex++ reads it here. + if (path === "/v1/usage/live") return req.method === "GET"; if (contextEndpoint(path)) return req.method === "POST"; if (path === "/v1/images/generations" || path === "/v1/images/edits") { return req.method === "POST"; diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index b943aab586d..b44cdb10626 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -405,6 +405,10 @@ export function createServeOptions(ctx: ServeOptionsContext) { if (readyzPath !== undefined) { return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy); } + if (url.pathname === "/v1/usage/live") { + const preflight = (await import("../live-meter-handler")).liveMeterPreflight(req, policy); + if (preflight) return preflight; + } // The exact Ollama-compatible paths are data-plane routes and take data-plane CORS. const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname); const allowed = managementPreflight @@ -795,6 +799,12 @@ export function createServeOptions(ctx: ServeOptionsContext) { ); } + if (url.pathname === "/v1/usage/live" && req.method === "GET") { + // Same admission as the model routes; the module adds only the Codex desktop origin for this read. + const { handleLiveMeterData } = await import("../live-meter-handler"); + return handleLiveMeterData(req, policy); + } + if (url.pathname === "/v1/usage" && req.method === "GET") { const { handleHubUsage } = await import("../hub-usage"); return handleHubUsage(req, config, policy); diff --git a/src/server/live-meter-handler.ts b/src/server/live-meter-handler.ts new file mode 100644 index 00000000000..0cf90079fa3 --- /dev/null +++ b/src/server/live-meter-handler.ts @@ -0,0 +1,125 @@ +/** + * Read-only live meter: generation speed, cache hit and context fill of the newest completed + * request, overall and per client family, served on the data-plane route `GET /v1/usage/live`. + * It is admitted like the proxy's own model requests, so the Codex desktop renderer (Codex++ + * userscript) can read it without the admin token. The projection is `src/usage/live-meter.ts`. + * + * The body carries numbers, model and provider names and reason codes only. A `conversation` + * filter narrows the rows but is never echoed, and neither is any stored conversation digest. + */ +import { readCatalog, readCodexCatalogPath } from "../codex/catalog"; +import { liveMeterFromEntry, selectLiveMeterEntries, type LiveMeter, type MeterClientFamily } from "../usage/live-meter"; +import { + corsHeaders, isAllowedRequestOrigin, isApiAuthRequired, isLoopbackRequestHost, resolveApiAuth, withCors, + type RequestPolicyView, +} from "./auth-cors"; +import { formatErrorResponse } from "../bridge/errors"; +import { matchesLogConversationId } from "./request-log-conversation"; +import { getRequestLogEntries, type RequestLogEntry } from "./request-log"; +import { statSync } from "node:fs"; + +/** The Codex desktop renderer's page origin; it may read this one route and nothing else. */ +export const LIVE_METER_APP_ORIGIN = "app://-"; + +export interface LiveMeterBody { + latest: LiveMeter | null; + byClient: Partial>; + generatedAt: number; +} + +export interface LiveMeterDeps { + entries?: () => readonly RequestLogEntry[]; + contextLimit?: (model: string) => number | null; + now?: () => number; +} + +const FAMILIES: readonly MeterClientFamily[] = ["codex", "claude", "other"]; + +let catalogCache: { path: string; mtimeMs: number; size: number; limits: Map } | null = null; + +/** Window of the model as the persisted Codex catalog states it, re-read only when the file changes. */ +export function catalogContextLimit(model: string, catalogPath: string = readCodexCatalogPath()): number | null { + let stat; + try { stat = statSync(catalogPath); } catch { return null; } + if (!catalogCache || catalogCache.path !== catalogPath || catalogCache.mtimeMs !== stat.mtimeMs || catalogCache.size !== stat.size) { + const limits = new Map(); + for (const row of readCatalog(catalogPath)?.models ?? []) { + const window = row.context_window; + if (typeof row.slug === "string" && typeof window === "number" && Number.isFinite(window) && window > 0) { + limits.set(row.slug, window); + } + } + catalogCache = { path: catalogPath, mtimeMs: stat.mtimeMs, size: stat.size, limits }; + } + return catalogCache.limits.get(model) ?? null; +} + +export function resetLiveMeterCatalogCacheForTests(): void { catalogCache = null; } + +export type LiveMeterResult = { status: 200; body: LiveMeterBody } | { status: 400; code: string; message: string }; + +export function buildLiveMeter(params: URLSearchParams, deps: LiveMeterDeps = {}): LiveMeterResult { + const bad = (message: string): LiveMeterResult => ({ status: 400, code: "live_meter_query_invalid", message }); + for (const key of params.keys()) { + if ((key !== "client" && key !== "conversation") || params.getAll(key).length !== 1) return bad("Unknown or repeated option"); + } + const client = params.get("client"); + if (client !== null && !(FAMILIES as readonly string[]).includes(client)) return bad("client must be codex, claude or other"); + const conversation = params.get("conversation"); + if (conversation !== null && !conversation.trim()) return bad("conversation must not be empty"); + const limitOf = deps.contextLimit ?? ((model: string) => catalogContextLimit(model)); + const selection = selectLiveMeterEntries( + (deps.entries ?? getRequestLogEntries)(), + conversation === null ? undefined : entry => matchesLogConversationId(entry.conversationId, conversation), + ); + const project = (entry: RequestLogEntry): LiveMeter => liveMeterFromEntry(entry, entry.model ? limitOf(entry.model) : null); + const byClient: LiveMeterBody["byClient"] = {}; + for (const family of FAMILIES) { + const entry = selection.byFamily[family]; + if (entry) byClient[family] = project(entry); + } + const filtered = client === null ? selection.overall : selection.byFamily[client as MeterClientFamily] ?? null; + return { status: 200, body: { + latest: filtered ? project(filtered) : null, + byClient: client === null ? byClient : (byClient[client as MeterClientFamily] ? { [client]: byClient[client as MeterClientFamily] } : {}), + generatedAt: (deps.now ?? Date.now)(), + } }; +} + +export function liveMeterResponse(params: URLSearchParams, deps?: LiveMeterDeps): Response { + const result = buildLiveMeter(params, deps); + const headers = { "cache-control": "no-store" }; + return result.status === 200 + ? Response.json(result.body, { headers }) + : Response.json({ error: { type: "invalid_request_error", code: result.code, message: result.message } }, { status: 400, headers }); +} + +/** `GET /v1/usage/live`: same admission as the proxy's model requests; never the admin token. */ +export async function handleLiveMeterData(req: Request, config: RequestPolicyView, deps?: LiveMeterDeps): Promise { + const appRenderer = req.headers.get("Origin") === LIVE_METER_APP_ORIGIN; + const reply = (response: Response, admittedOrigin = false): Response => { + const out = withCors(response, req, config); + if (admittedOrigin) out.headers.set("Access-Control-Allow-Origin", LIVE_METER_APP_ORIGIN); + return out; + }; + if (!resolveApiAuth(req, config)) return reply(formatErrorResponse(401, "authentication_error", "opencodex API key required")); + // The renderer is not loopback-by-origin; the loopback Host gate still binds it when no key is required. + const originOk = appRenderer + ? isApiAuthRequired(config) || isLoopbackRequestHost(req.headers.get("Host")) + : isAllowedRequestOrigin(req, config); + if (!originOk) return reply(formatErrorResponse(403, "origin_rejected", "cross-origin data-plane request blocked")); + return reply(liveMeterResponse(new URL(req.url).searchParams, deps), appRenderer); +} + +/** + * Preflight for the renderer's cross-origin read of `/v1/usage/live` (a key header makes it non-simple). + * `null` for every other origin, so the data-plane preflight policy is untouched. + */ +export function liveMeterPreflight(req: Request, config: RequestPolicyView): Response | null { + if (req.headers.get("Origin") !== LIVE_METER_APP_ORIGIN) return null; + if (!isApiAuthRequired(config) && !isLoopbackRequestHost(req.headers.get("Host"))) return null; + const headers = corsHeaders(req, config); + headers["Access-Control-Allow-Origin"] = LIVE_METER_APP_ORIGIN; + headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"; + return new Response(null, { status: 204, headers }); +} diff --git a/src/usage/live-meter.ts b/src/usage/live-meter.ts new file mode 100644 index 00000000000..e26fc5fc3fe --- /dev/null +++ b/src/usage/live-meter.ts @@ -0,0 +1,138 @@ +/** + * Live meter: generation speed, cache hit and context fill for ONE completed request row. + * + * Pure projection of a `RequestLogEntry`. Speed divides the upstream-reported output tokens + * by the recorded generation window (`genStartMs` .. `lastOutputMs`, request-log-generation-window.ts), + * never by wall time or first visible text. Anything that cannot be measured is `null` plus a + * closed reason code; nothing is estimated or guessed. Carries numbers, model and provider + * names only: no prompt text, account labels or identifiers. + * + * Ported from the Codex++ userscript reader (codexpp-andrew-extensions/meter/core.mjs); the + * reason vocabulary is the same. + */ +import type { RequestLogEntry } from "../server/request-log"; + +export type MeterSpeedReason = + | "no_matching_request" | "request_aborted" | "request_incomplete" | "request_failed" + | "usage_missing" | "tokens_estimated" | "output_missing" | "generation_timing_missing" + | "generation_window_too_short" | "invalid_generation_window"; + +export type MeterPercentReason = "usage_missing" | "tokens_estimated" | "input_missing" | "limit_unknown"; + +export interface LiveMeter { + speed: { value: number | null; reason: MeterSpeedReason | null }; + outputTokens: number | null; + generationMs: number | null; + cache: { readTokens: number | null; inputTokens: number | null; percent: number | null; reason: MeterPercentReason | null }; + context: { usedTokens: number | null; limitTokens: number | null; percent: number | null; reason: MeterPercentReason | null }; + model: string | null; + provider: string | null; + client: string | null; + timestamp: number | null; +} + +/** Rows that are not a conversation turn (automatic approval reviews) never become the meter. */ +export function isConversationMeterRow(entry: Pick): boolean { + return typeof entry.model === "string" && entry.model !== "codex-auto-review"; +} + +const count = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; + +function speed(entry: RequestLogEntry): LiveMeter["speed"] { + const none = (reason: MeterSpeedReason) => ({ value: null, reason }); + if (entry.closeReason === "client_cancel" || entry.status === 499) return none("request_aborted"); + if (entry.terminalStatus === "failed" || entry.terminalStatus === "incomplete" + || entry.closeReason === "body_stall" || entry.closeReason === "body_overflow") return none("request_incomplete"); + if (!(entry.status >= 200 && entry.status < 400)) return none("request_failed"); + if (!entry.usage || entry.usageStatus === "unsupported") return none("usage_missing"); + if (entry.usageStatus === "estimated" || entry.usage.estimated === true) return none("tokens_estimated"); + const tokens = entry.usage.outputTokens; + if (!(Number.isFinite(tokens) && tokens > 0)) return none("output_missing"); + const start = entry.genStartMs; + const end = entry.lastOutputMs; + if (!(typeof start === "number" && Number.isFinite(start) && start >= 0 && typeof end === "number" && Number.isFinite(end))) { + return none("generation_timing_missing"); + } + const window = end - start; + if (window < 1000) return none(window > 0 ? "generation_window_too_short" : "invalid_generation_window"); + if (Number.isFinite(entry.durationMs) && end > entry.durationMs + 10) return none("invalid_generation_window"); + return { value: (tokens * 1000) / window, reason: null }; +} + +/** + * `contextLimitTokens` is the model's window as the catalog knows it, supplied by the caller + * (a pure projection cannot look it up). `null` when unknown: the percentage is then `null`. + */ +export function liveMeterFromEntry(entry: RequestLogEntry, contextLimitTokens: number | null): LiveMeter { + const s = speed(entry); + const reported = !!entry.usage && entry.usageStatus !== "unsupported" + && entry.usageStatus !== "estimated" && entry.usage.estimated !== true; + const usageReason: MeterPercentReason | null = !entry.usage || entry.usageStatus === "unsupported" + ? "usage_missing" : reported ? null : "tokens_estimated"; + const usage = reported ? entry.usage : undefined; + const inputTokens = count(usage?.inputTokens); + const outputTokens = count(usage?.outputTokens); + const readTokens = count(usage?.cacheReadInputTokens ?? usage?.cachedInputTokens); + // `cacheReadInputTokens` is the read subset of `inputTokens`; a synthesized provenance is wire-only. + const cacheKnown = readTokens !== null && inputTokens !== null && inputTokens > 0 + && entry.cacheProvenance !== "synthesized" && readTokens <= inputTokens; + const used = count(usage?.contextTotalTokens) + ?? (inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null); + const limit = contextLimitTokens !== null && Number.isFinite(contextLimitTokens) && contextLimitTokens > 0 + ? contextLimitTokens : null; + return { + speed: s, + outputTokens, + generationMs: s.value !== null ? (entry.lastOutputMs as number) - (entry.genStartMs as number) : null, + cache: { + readTokens, inputTokens, + percent: cacheKnown ? (100 * readTokens) / inputTokens : null, + reason: cacheKnown ? null : usageReason ?? "input_missing", + }, + context: { + usedTokens: used, limitTokens: limit, + percent: used !== null && limit !== null ? Math.min(100, (100 * used) / limit) : null, + reason: used === null ? usageReason ?? "input_missing" : limit === null ? "limit_unknown" : null, + }, + model: entry.model ?? null, + provider: entry.provider ?? null, + client: entry.client ?? null, + timestamp: Number.isFinite(entry.timestamp) ? entry.timestamp : null, + }; +} + +export type MeterClientFamily = "codex" | "claude" | "other"; + +/** Family of a recorded client label; unknown or absent rows count only toward the overall meter. */ +export function meterClientFamily(client: string | undefined): MeterClientFamily | null { + if (!client || client === "unknown") return null; + if (client.startsWith("codex_")) return "codex"; + if (client.startsWith("claude_")) return "claude"; + return "other"; +} + +export interface LiveMeterSelection { + overall: RequestLogEntry | null; + byFamily: Partial>; +} + +/** + * Newest completed conversation row overall and per client family. The store is append-ordered + * but combo and retried rows can finish out of order, so recency is by `timestamp`. + * `matches` narrows to one conversation when the caller supplied one. + */ +export function selectLiveMeterEntries( + entries: readonly RequestLogEntry[], + matches: (entry: RequestLogEntry) => boolean = () => true, +): LiveMeterSelection { + const out: LiveMeterSelection = { overall: null, byFamily: {} }; + const newer = (a: RequestLogEntry | null | undefined, b: RequestLogEntry) => !a || b.timestamp >= a.timestamp; + for (const entry of entries) { + if (!isConversationMeterRow(entry) || !matches(entry)) continue; + if (newer(out.overall, entry)) out.overall = entry; + const family = meterClientFamily(entry.client); + if (family && newer(out.byFamily[family], entry)) out.byFamily[family] = entry; + } + return out; +} diff --git a/structure/runtime.md b/structure/runtime.md index 6598dab83f1..b2967808b9a 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -213,7 +213,7 @@ Enabled startup retains separate fresh ownership decisions. Explicit `sync` and `startServer` composes up to four sockets in one synchronous startup transaction: the public data listener, optional unauthenticated data-loopback and hub-management listeners, and the optional `hub-link` listener, which opens only for a recorded link and persists its concrete `127.0.0.1:`. HTTP Responses/Messages apply the [caller header contract](data-planes/inbound-compat.md#http-caller-conversation-identity) before turn admission and dispatch. Linked-machine data uses the [connection-bound relay contract](remote-link.md#connection-bound-relay-authentication); client-local credentials and routing policy remain unchanged. The data-loopback socket serves a fixed data-plane allowlist: Responses and its compact sibling, -the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, the realtime voice shapes, +the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, `GET /v1/usage/live`, the realtime voice shapes, and the Anthropic and OpenAI chat wires the host's own local clients speak — `POST /v1/messages`, `POST /v1/messages/count_tokens`, and `POST /v1/chat/completions`. It never serves `/api/*`, `/healthz`, `/readyz`, or GUI routes, so local management discovery has to use an authenticated diff --git a/structure/usage-client-attribution.md b/structure/usage-client-attribution.md index 42da962df1c..e10ef43c328 100644 --- a/structure/usage-client-attribution.md +++ b/structure/usage-client-attribution.md @@ -202,3 +202,7 @@ and the request-log hydration keep only `p` plus six lowercase hex digits and dr Per-account summaries still key on `accountLogLabel` and ignore the tag (`tests/usage/request-log-anthropic-account-tag.test.ts`). Remote Link rows may carry an optional `link` object (transport, continuation, hashed thread and turn refs) while the link WebSocket feature is on; it is validated in `src/usage/link-log-fields.ts` and spread into the row, the persisted entry and hydration, and described in `structure/remote-link.md`. + +## Live meter + +The client families (`codex_*`, `claude_*`, other) also scope the live meter. `src/server/live-meter-handler.ts` serves `GET /v1/usage/live`, the newest completed conversation row projected by `src/usage/live-meter.ts` (output tokens over the recorded generation window, cache read over input, context used over the persisted Codex catalog's `context_window`, cached by catalog mtime). Any measurement that is missing, estimated, failed or under 1 s is `null` with a reason code, never a guess; the body is numbers, model/provider names and reason codes only, and a `conversation` filter is never echoed. Admission is `resolveApiAuth` (the `/v1/models` set, never the admin token), and Origin `app://-` (the Codex desktop renderer) is additionally allowed for this GET and its preflight only, behind the same loopback Host gate; `isAllowedRequestOrigin` and every other route are unchanged. The unauthenticated data-loopback listener admits it as GET only, because that socket is where the Codex++ footer dials on a host whose public listener binds a non-loopback address. The route reads the in-process request log, so it adds no management route, CLI verb or ledger read. Covered by `tests/server/live-meter-handler.test.ts` and the `AUTH_MATRIX` row. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index c643db9db3d..8f3b5340036 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -180,7 +180,7 @@ "anthropic2-discovery-ownership.test.ts": "oauth", "codex-shim-runtime-preflight.test.ts": "codex-integration", "cli-anthropic2-account.test.ts": "cli", "anthropic2-catalog.test.ts": "codex-integration", "provider-anthropic-instance-quota.test.ts": "providers", "anthropic2-management.test.ts": "server", - "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search", + "management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "live-meter.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search", "provider-anthropic-instance.test.ts": "providers", "config-anthropic-instance-pool.test.ts": "config", "oauth-anthropic-instance-registration.test.ts": "oauth", "oauth-anthropic-instance-refresh.test.ts": "oauth", "claude-picker-upload.test.ts": "claude-integration", "claude-picker-linger.test.ts": "claude-integration", "model-costs-pricing-cache.test.ts": "server", @@ -954,7 +954,7 @@ "history-ocx-compaction-recovery.test.ts": "codex-integration", "history-paginated-openai-compat.test.ts": "codex-integration", "history-paginated-transition-destinations.test.ts": "codex-integration", "hub-gated-local-clients.test.ts": "cli", - "hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli", "hub-usage.test.ts": "server", + "hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli", "hub-usage.test.ts": "server", "live-meter-handler.test.ts": "server", "hyperbolic-provider.test.ts": "providers", "identity-neutralize.test.ts": "adapters", "identity-subagent.test.ts": "adapters", "init-backup-cleanup.test.ts": "service", "init-eof.test.ts": "service", "initial-model-selection.test.ts": "providers", diff --git a/tests/server/api-key-attribution.test.ts b/tests/server/api-key-attribution.test.ts index 81e330a51a2..ac1116b820d 100644 --- a/tests/server/api-key-attribution.test.ts +++ b/tests/server/api-key-attribution.test.ts @@ -738,7 +738,7 @@ describe("AUTH_MATRIX is true of the running server", () => { // from routing and the assertions below would be testing the method guard rather // than admission. /v1/catalog joined this set in #809. const isGet = row.endpoint === "/v1/models" || row.endpoint === "/v1/catalog" - || row.endpoint === "/v1/hub-state" || row.endpoint === "/v1/usage"; + || row.endpoint === "/v1/hub-state" || row.endpoint === "/v1/usage" || row.endpoint === "/v1/usage/live"; const live = row.endpoint === "/v1/live" || row.endpoint === "/v1/realtime/calls"; const audio = row.endpoint === "/v1/audio/transcriptions" || live ? new FormData() : null; if (audio) { diff --git a/tests/server/live-meter-handler.test.ts b/tests/server/live-meter-handler.test.ts new file mode 100644 index 00000000000..f731b40c1d4 --- /dev/null +++ b/tests/server/live-meter-handler.test.ts @@ -0,0 +1,205 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { buildLiveMeter, catalogContextLimit, handleLiveMeterData, liveMeterPreflight, resetLiveMeterCatalogCacheForTests } from "../../src/server/live-meter-handler"; +import { isAllowedRequestOrigin } from "../../src/server/auth-cors"; +import { normalizeLogConversationId } from "../../src/server/request-log-conversation"; +import { clearRequestLogsForTests, getRequestLogEntries, type RequestLogEntry } from "../../src/server/request-log"; +import { getDefaultConfig, saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS, removeTreeAfterBackgroundWork } from "../helpers/remove-tree"; + +const CONVERSATION = "thread-raw-id-7f3a"; +const DIGEST = normalizeLogConversationId(CONVERSATION)!; + +const row = (o: Partial = {}): RequestLogEntry => ({ + requestId: "r", timestamp: 100, model: "gpt-6-astra", provider: "native", client: "codex_desktop", status: 200, + durationMs: 10000, genStartMs: 2000, lastOutputMs: 8000, usageStatus: "reported", + usage: { inputTokens: 1000, outputTokens: 600, cacheReadInputTokens: 750 }, ...o, +} as RequestLogEntry); + +const entries = [ + row({ timestamp: 100, conversationId: DIGEST }), + row({ timestamp: 200, client: "claude_code", model: "claude-x", conversationId: "someone-else" }), + row({ timestamp: 300, client: "codex_cli", model: "codex-auto-review" }), + row({ timestamp: 150, client: "codex_cli", conversationId: DIGEST, usage: { inputTokens: 10, outputTokens: 5 } }), +]; +const deps = { entries: () => entries, contextLimit: (m: string) => (m === "gpt-6-astra" ? 872000 : null), now: () => 42 }; + +describe("live meter body", () => { + test("latest overall and per family, auto-review rows never selected", () => { + const r = buildLiveMeter(new URLSearchParams(), deps); + expect(r.status).toBe(200); + if (r.status !== 200) return; + expect(r.body.generatedAt).toBe(42); + expect(r.body.latest?.client).toBe("claude_code"); + expect(Object.keys(r.body.byClient).sort()).toEqual(["claude", "codex"]); + expect(r.body.byClient.codex?.timestamp).toBe(150); + expect(r.body.byClient.claude?.context).toMatchObject({ limitTokens: null, reason: "limit_unknown" }); + }); + + test("client filter narrows latest and byClient", () => { + const r = buildLiveMeter(new URLSearchParams("client=codex"), deps); + expect(r.status === 200 && r.body.latest?.timestamp).toBe(150); + expect(r.status === 200 && Object.keys(r.body.byClient)).toEqual(["codex"]); + const none = buildLiveMeter(new URLSearchParams("client=other"), deps); + expect(none.status === 200 && none.body).toEqual({ latest: null, byClient: {}, generatedAt: 42 }); + }); + + test("conversation filter accepts raw id, digest and thread link, and echoes none of them", () => { + for (const q of [CONVERSATION, DIGEST, `codex://threads/${CONVERSATION}`]) { + const r = buildLiveMeter(new URLSearchParams({ conversation: q }), deps); + expect(r.status === 200 && r.body.latest?.timestamp).toBe(150); + const text = JSON.stringify(r); + expect(text).not.toContain(CONVERSATION); + expect(text).not.toContain(DIGEST); + } + const miss = buildLiveMeter(new URLSearchParams({ conversation: "unknown" }), deps); + expect(miss.status === 200 && miss.body.latest).toBeNull(); + }); + + test("bad queries are 400 with a code, not an empty meter", () => { + for (const q of ["client=gemini", "conversation=", "client=codex&client=claude", "x=1"]) { + expect(buildLiveMeter(new URLSearchParams(q), deps)).toMatchObject({ status: 400, code: "live_meter_query_invalid" }); + } + }); + + test("no request yet means a null latest, not a zeroed meter", () => { + const r = buildLiveMeter(new URLSearchParams(), { ...deps, entries: () => [] }); + expect(r.status === 200 && r.body.latest).toBeNull(); + }); +}); + +describe("catalog context limit", () => { + let dir: string | undefined; + afterEach(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; + resetLiveMeterCatalogCacheForTests(); + }); + + test("maps client-facing slug to context_window and re-reads only when the file changes", () => { + dir = mkdtempSync(join(tmpdir(), "ocx-live-meter-")); + const path = join(dir, "opencodex-catalog.json"); + const catalog = (window: number) => JSON.stringify({ models: [ + { slug: "gpt-6-astra", context_window: window, max_context_window: 872000 }, + { slug: "google-vertex/gemini-4-argon", context_window: 1000000 }, + { slug: "no-window" }, + ] }); + writeFileSync(path, catalog(872000)); + expect(catalogContextLimit("gpt-6-astra", path)).toBe(872000); + expect(catalogContextLimit("google-vertex/gemini-4-argon", path)).toBe(1000000); + expect(catalogContextLimit("no-window", path)).toBeNull(); + expect(catalogContextLimit("missing", path)).toBeNull(); + writeFileSync(path, catalog(400000)); + const later = new Date(Date.now() + 5000); + utimesSync(path, later, later); + expect(catalogContextLimit("gpt-6-astra", path)).toBe(400000); + rmSync(path); + expect(catalogContextLimit("gpt-6-astra", path)).toBeNull(); + }); +}); + +describe("data-plane admission and CORS", () => { + const key = { id: "k", name: "k", key: "ocx_data_livemeterkey", createdAt: "2026-01-01" }; + const loopback = { hostname: "127.0.0.1", corsAllowOrigins: [], apiKeys: [] }; + const remote = { hostname: "0.0.0.0", corsAllowOrigins: [], apiKeys: [key] }; + const get = (url: string, headers: Record = {}) => new Request(url, { headers }); + + test("loopback needs no key and answers the Codex desktop origin with that exact origin", async () => { + const res = await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live", { origin: "app://-", host: "127.0.0.1:1" }), loopback, deps); + expect(res.status).toBe(200); + expect(res.headers.get("access-control-allow-origin")).toBe("app://-"); + expect(res.headers.get("cache-control")).toBe("no-store"); + expect((await res.json()).latest.client).toBe("claude_code"); + }); + + test("loopback still refuses a rebinding Host and any other foreign origin", async () => { + const rebound = await handleLiveMeterData(get("http://evil.test/v1/usage/live", { origin: "app://-", host: "evil.test" }), loopback, deps); + expect(rebound.status).toBe(403); + const foreign = await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live", { origin: "https://evil.test", host: "127.0.0.1:1" }), loopback, deps); + expect(foreign.status).toBe(403); + expect(foreign.headers.get("access-control-allow-origin")).not.toBe("https://evil.test"); + }); + + test("a non-loopback bind without a data key is rejected, with a key it is served", async () => { + const anon = await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { origin: "app://-" }), remote, deps); + expect(anon.status).toBe(401); + expect(anon.headers.get("access-control-allow-origin")).not.toBe("app://-"); + const wrong = await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { "x-opencodex-api-key": "nope" }), remote, deps); + expect(wrong.status).toBe(401); + for (const headers of [{ "x-opencodex-api-key": key.key }, { authorization: `Bearer ${key.key}` }, { "x-api-key": key.key }]) { + const ok = await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { origin: "app://-", ...headers }), remote, deps); + expect(ok.status).toBe(200); + expect(ok.headers.get("access-control-allow-origin")).toBe("app://-"); + } + }); + + test("the app origin is not admitted anywhere else: the data-plane origin policy is unchanged", () => { + expect(isAllowedRequestOrigin(get("http://127.0.0.1:1/v1/models", { origin: "app://-", host: "127.0.0.1:1" }), loopback)).toBe(false); + }); + + test("preflight answers only the Codex desktop origin, with GET only and the exact origin", () => { + const pre = (headers: Record, config = loopback) => liveMeterPreflight(new Request("http://127.0.0.1:1/v1/usage/live", { method: "OPTIONS", headers }), config); + const ok = pre({ origin: "app://-", host: "127.0.0.1:1", "access-control-request-headers": "x-opencodex-api-key" }); + expect(ok?.status).toBe(204); + expect(ok?.headers.get("access-control-allow-origin")).toBe("app://-"); + expect(ok?.headers.get("access-control-allow-methods")).toBe("GET, OPTIONS"); + expect(ok?.headers.get("access-control-allow-headers")).toContain("X-OpenCodex-API-Key"); + expect(pre({ origin: "https://evil.test", host: "127.0.0.1:1" })).toBeNull(); + expect(pre({ host: "127.0.0.1:1" })).toBeNull(); + expect(pre({ origin: "app://-", host: "evil.test" })).toBeNull(); + }); +}); + +describe("running server", () => { + const envKeys = ["OPENCODEX_HOME", "OPENCODEX_API_AUTH_TOKEN", "OPENCODEX_ADMIN_AUTH_TOKEN"] as const; + let saved: Record; + let home: string; + let codex: IsolatedCodexHome; + let server: ReturnType | undefined; + + beforeEach(() => { + saved = Object.fromEntries(envKeys.map(k => [k, process.env[k]])); + home = mkdtempSync(join(tmpdir(), "ocx-live-meter-server-")); + codex = installIsolatedCodexHome(); + process.env.OPENCODEX_HOME = home; + delete process.env.OPENCODEX_API_AUTH_TOKEN; + saveConfig({ ...getDefaultConfig(), port: 0, hostname: "127.0.0.1", providers: {} }); + clearRequestLogsForTests(); + }); + afterEach(async () => { + await server?.stop(true); + server = undefined; + clearRequestLogsForTests(); + for (const k of envKeys) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } + codex.restore(); + await removeTreeAfterBackgroundWork(home); + }, BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS); + + test("the route, its preflight and the rest of the data plane behave as specified for app://-", async () => { + server = startServer(0); + getRequestLogEntries().push(row({ timestamp: Date.now(), model: "unlisted-model" })); + const base = server.url; + const app = { origin: "app://-" }; + const res = await fetch(new URL("/v1/usage/live", base), { headers: app }); + expect(res.status).toBe(200); + expect(res.headers.get("access-control-allow-origin")).toBe("app://-"); + const body = await res.json(); + expect(body.latest).toMatchObject({ model: "unlisted-model", speed: { value: 100, reason: null }, context: { reason: "limit_unknown" } }); + expect(body.byClient.codex.model).toBe("unlisted-model"); + + const pre = await fetch(new URL("/v1/usage/live", base), { method: "OPTIONS", headers: { ...app, "access-control-request-method": "GET" } }); + expect(pre.status).toBe(204); + expect(pre.headers.get("access-control-allow-origin")).toBe("app://-"); + + const models = await fetch(new URL("/v1/models", base), { headers: app }); + expect(models.status).toBe(403); + const otherPre = await fetch(new URL("/v1/models", base), { method: "OPTIONS", headers: { ...app, "access-control-request-method": "GET" } }); + expect(otherPre.status).toBe(403); + const postRes = await fetch(new URL("/v1/usage/live", base), { method: "POST", headers: app }); + expect(postRes.status).not.toBe(200); + }, 60000); +}); diff --git a/tests/server/loopback-listener-admission.test.ts b/tests/server/loopback-listener-admission.test.ts index ea3075085f7..a03e9c07f68 100644 --- a/tests/server/loopback-listener-admission.test.ts +++ b/tests/server/loopback-listener-admission.test.ts @@ -118,6 +118,12 @@ describe("local client inference wires on the loopback listener (#4236)", () => ); }); + test("the live meter is a GET-only read on the loopback listener", () => { + // The Codex++ footer reads `http://127.0.0.1:/v1/usage/live`. On a hub whose public + // listener binds a tailnet address that is this socket, and the route 404ed here. + expect(source).toContain('if (path === "/v1/usage/live") return req.method === "GET";'); + }); + test("no /api route joins the allowlist", () => { // Management discovery is the other destination contract (authenticated ingress). A // reviewer condition on #4236: `/api/*` must never appear on this listener. diff --git a/tests/usage/live-meter.test.ts b/tests/usage/live-meter.test.ts new file mode 100644 index 00000000000..7832c4d397d --- /dev/null +++ b/tests/usage/live-meter.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, test } from "bun:test"; +import { liveMeterFromEntry, selectLiveMeterEntries } from "../../src/usage/live-meter"; +import type { RequestLogEntry } from "../../src/server/request-log"; + +const row = (o: Partial = {}): RequestLogEntry => ({ + requestId: "r", timestamp: 1, model: "fixture", provider: "p", status: 200, durationMs: 10000, + genStartMs: 2000, lastOutputMs: 8000, firstOutputMs: 7000, usageStatus: "reported", + usage: { inputTokens: 1000, outputTokens: 600, reasoningOutputTokens: 200 }, ...o, +} as RequestLogEntry); + +describe("live meter speed", () => { + test("output tokens over the generation window, reasoning counted once", () => { + const m = liveMeterFromEntry(row(), null); + expect(m.speed).toEqual({ value: 100, reason: null }); + expect(m.generationMs).toBe(6000); + expect(m.outputTokens).toBe(600); + }); + test("queue time, wall clock and first visible text do not enter the denominator", () => { + const a = liveMeterFromEntry(row(), null).speed.value; + expect(liveMeterFromEntry(row({ timestamp: 3_600_000, durationMs: 90000, firstOutputMs: 7900 }), null).speed.value).toBe(a); + expect(liveMeterFromEntry(row({ genStartMs: 62000, lastOutputMs: 68000, durationMs: 100000 }), null).speed.value).toBe(a); + }); + test("missing window never falls back to duration or first output", () => { + for (const d of [{ genStartMs: undefined }, { lastOutputMs: undefined }, { genStartMs: NaN }]) { + expect(liveMeterFromEntry(row(d), null).speed).toEqual({ value: null, reason: "generation_timing_missing" }); + } + }); + test("tiny or invalid windows are not printed as a rate", () => { + expect(liveMeterFromEntry(row({ genStartMs: 7950 }), null).speed.reason).toBe("generation_window_too_short"); + expect(liveMeterFromEntry(row({ genStartMs: 9000 }), null).speed.reason).toBe("invalid_generation_window"); + expect(liveMeterFromEntry(row({ genStartMs: -1 }), null).speed.reason).toBe("generation_timing_missing"); + expect(liveMeterFromEntry(row({ lastOutputMs: 10050 }), null).speed.reason).toBe("invalid_generation_window"); + }); + test("failed, truncated, cancelled and estimated requests stay unavailable with their reason", () => { + const cases: Array<[Partial, string]> = [ + [{ status: 502 }, "request_failed"], [{ terminalStatus: "incomplete" }, "request_incomplete"], + [{ terminalStatus: "failed" }, "request_incomplete"], [{ closeReason: "client_cancel" }, "request_aborted"], + [{ status: 499 }, "request_aborted"], [{ closeReason: "body_stall" }, "request_incomplete"], + [{ closeReason: "body_overflow" }, "request_incomplete"], [{ usageStatus: "estimated" }, "tokens_estimated"], + [{ usage: { inputTokens: 1, outputTokens: 5, estimated: true } }, "tokens_estimated"], + [{ usage: undefined }, "usage_missing"], [{ usageStatus: "unsupported" }, "usage_missing"], + [{ usage: { inputTokens: 1, outputTokens: 0 } }, "output_missing"], + ]; + for (const [delta, reason] of cases) { + const m = liveMeterFromEntry(row(delta), null); + expect(m.speed.value).toBeNull(); + expect(m.speed.reason).toBe(reason as never); + } + }); +}); + +describe("live meter cache and context", () => { + test("cache percent is cache-read over input, explicit zero stays a measurement", () => { + const hit = liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cacheReadInputTokens: 870 } }), null); + expect(hit.cache).toEqual({ readTokens: 870, inputTokens: 1000, percent: 87, reason: null }); + expect(liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cacheReadInputTokens: 0 } }), null).cache.percent).toBe(0); + expect(liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cachedInputTokens: 500 } }), null).cache.percent).toBe(50); + }); + test("cache is null, never guessed, when unreported, estimated or synthesized", () => { + expect(liveMeterFromEntry(row(), null).cache).toMatchObject({ percent: null, readTokens: null }); + expect(liveMeterFromEntry(row({ usageStatus: "estimated", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache) + .toMatchObject({ percent: null, reason: "tokens_estimated" }); + expect(liveMeterFromEntry(row({ cacheProvenance: "synthesized", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache.percent).toBeNull(); + }); + test("context used is input plus output, or the absolute context total when the provider gives one", () => { + const m = liveMeterFromEntry(row({ usage: { inputTokens: 380_000, outputTokens: 900 } }), 1_000_000); + expect(m.context).toEqual({ usedTokens: 380_900, limitTokens: 1_000_000, percent: 38.09, reason: null }); + const abs = liveMeterFromEntry(row({ usage: { inputTokens: 10, outputTokens: 5, contextTotalTokens: 200 } }), 1000); + expect(abs.context.usedTokens).toBe(200); + }); + test("an unknown or invalid limit leaves the percentage null but keeps the used count", () => { + for (const limit of [null, 0, -5, NaN]) { + const m = liveMeterFromEntry(row(), limit); + expect(m.context).toMatchObject({ usedTokens: 1600, limitTokens: null, percent: null, reason: "limit_unknown" }); + } + }); + test("estimated usage reports no context used", () => { + expect(liveMeterFromEntry(row({ usageStatus: "estimated" }), 1000).context) + .toMatchObject({ usedTokens: null, percent: null, reason: "tokens_estimated" }); + }); + test("the payload carries only numbers, model, provider and client", () => { + const m = liveMeterFromEntry(row({ client: "codex_desktop", accountLogLabel: "main", conversationId: "a".repeat(32) }), 1000); + expect(Object.keys(m).sort()).toEqual(["cache", "client", "context", "generationMs", "model", "outputTokens", "provider", "speed", "timestamp"]); + expect(JSON.stringify(m)).not.toContain("main"); + }); +}); + +describe("live meter selection", () => { + test("newest overall and per family; auto-review rows never win", () => { + const rows = [ + row({ requestId: "a", timestamp: 10, client: "codex_desktop" }), + row({ requestId: "b", timestamp: 20, client: "claude_code" }), + row({ requestId: "c", timestamp: 30, client: "codex_cli", model: "codex-auto-review" }), + row({ requestId: "d", timestamp: 15, client: "codex_cli" }), + row({ requestId: "e", timestamp: 40, client: "unknown" }), + ]; + const sel = selectLiveMeterEntries(rows); + expect(sel.overall?.requestId).toBe("e"); + expect(sel.byFamily.codex?.requestId).toBe("d"); + expect(sel.byFamily.claude?.requestId).toBe("b"); + expect(sel.byFamily.other).toBeUndefined(); + }); + test("a conversation matcher narrows the candidates", () => { + const rows = [row({ requestId: "a", timestamp: 10, conversationId: "x" }), row({ requestId: "b", timestamp: 20, conversationId: "y" })]; + expect(selectLiveMeterEntries(rows, e => e.conversationId === "x").overall?.requestId).toBe("a"); + expect(selectLiveMeterEntries(rows, () => false).overall).toBeNull(); + }); +}); From cc3467d0df59a810417eca0173d74a277f76b1d1 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Fri, 13 Nov 2026 20:51:47 -0500 Subject: [PATCH 04/18] fix(gui): live routing tab shows each fact once and draws the context to scale - Context card: replace the eased treemap (a 1%-full window drew about a fifth of a 232px box as used and the rest as hatched free space) with one stacked bar like "Where the time went", plus a legend with each part's share of the prompt. The fill stays in the header. - Remove the numbered steps list: it repeated the flow diagram line for line. Its one new fact, why the route was chosen, is a line under the flow. - Pool line lists only non-zero states and now counts out-of-quota and plan-lacks-model accounts, so the parts add up to the total. - Request list reuses the Logs column labels (~$, tok/s, ...) instead of a hard-coded "~$" and duplicate keys. - Loading uses DataSurfaceSkeleton like the neighbouring tabs; one-off px values use tokens; tool results get a hue distinct from memory. --- .../src/content/docs/guides/model-routing.md | 8 +- gui/src/i18n/route-live-copy.ts | 29 +-- gui/src/pages/route-live/ContextCard.tsx | 119 ++++--------- gui/src/pages/route-live/FlowDiagram.tsx | 2 +- gui/src/pages/route-live/RequestList.tsx | 10 +- gui/src/pages/route-live/RouteLive.tsx | 37 +++- gui/src/pages/route-live/RouteSteps.tsx | 54 ------ gui/src/pages/route-live/context-tiles.ts | 168 +----------------- gui/src/pages/route-live/flow-model.ts | 20 --- gui/src/pages/route-live/route-live.css | 50 ++---- gui/tests/route-live-context.test.ts | 90 +--------- gui/tests/route-live-model.test.ts | 7 +- gui/tests/route-live-render.test.tsx | 31 ++-- 13 files changed, 118 insertions(+), 507 deletions(-) delete mode 100644 gui/src/pages/route-live/RouteSteps.tsx diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index 963386661cd..849aed0dc46 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -161,12 +161,14 @@ 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. + finished: paused, needing sign-in, cooling down, out of quota, or not listing the model. When + the router recorded why it picked this route, that reason is shown under it. - **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, + as `AGENTS.md` and `CLAUDE.md`, files, tool results and the conversation, as one bar with each + part's share of the prompt, how full the serving model's window is, and 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, diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index df18210e1c5..4cdc628d88f 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -26,16 +26,15 @@ const rows = { 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."], + routeWhy: ["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}"], 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"], + poolHead: ["Pool {provider}: {total} accounts","풀 {provider}: 계정 {total}개","Pool {provider}: {total} Konten","Pool {provider} : {total} comptes","号池 {provider}:{total} 个账号","號池 {provider}:{total} 個帳號","Пул {provider}: {total} аккаунтов","プール {provider}:{total} アカウント","Havuz {provider}: {total} hesap","Nhóm {provider}: {total} tài khoản","Pool {provider}: {total} contas"], + poolAvailable: ["{n} available","사용 가능 {n}","{n} verfügbar","{n} disponibles","可用 {n}","可用 {n}","доступно {n}","利用可 {n}","{n} uygun","{n} sẵn sàng","{n} disponíveis"], + poolCooldown: ["{n} cooling","대기 중 {n}","{n} Abkühlung","{n} en pause temporaire","冷却 {n}","冷卻 {n}","на паузе после ошибок {n}","クールダウン {n}","{n} bekleme","{n} đang nghỉ","{n} em espera"], + poolPaused: ["{n} paused","일시중지 {n}","{n} pausiert","{n} suspendus","暂停 {n}","暫停 {n}","приостановлено {n}","一時停止 {n}","{n} duraklatıldı","{n} tạm dừng","{n} pausadas"], + poolReauth: ["{n} need sign-in","재로그인 필요 {n}","{n} brauchen Anmeldung","{n} à reconnecter","需重新登录 {n}","需重新登入 {n}","нужен вход {n}","要再ログイン {n}","{n} yeniden giriş gerek","{n} cần đăng nhập lại","{n} precisam entrar de novo"], + poolQuota: ["{n} out of quota","한도 소진 {n}","{n} Kontingent aufgebraucht","{n} quota épuisé","额度用尽 {n}","額度用盡 {n}","квота исчерпана {n}","クォータ切れ {n}","{n} kota doldu","{n} hết hạn mức","{n} sem cota"], + poolUnlisted: ["{n} without this model","이 모델 없음 {n}","{n} ohne dieses Modell","{n} sans ce modèle","不含此模型 {n}","不含此模型 {n}","без этой модели {n}","このモデルなし {n}","{n} bu model yok","{n} không có mô hình này","{n} sem este modelo"], 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"], @@ -52,10 +51,7 @@ const rows = { 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","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"], 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"], @@ -75,11 +71,6 @@ const rows = { 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","Logiciel client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente"], - colModel: ["Model","모델","Modell","Modèle","模型","模型","Модель","モデル","Model","Mô hình","Modelo"], - 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"], 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"], @@ -101,7 +92,6 @@ const rows = { 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…"], 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"], @@ -128,9 +118,6 @@ const rows = { 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","É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"], 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"], diff --git a/gui/src/pages/route-live/ContextCard.tsx b/gui/src/pages/route-live/ContextCard.tsx index c51b8b7c4b4..50f42477c5c 100644 --- a/gui/src/pages/route-live/ContextCard.tsx +++ b/gui/src/pages/route-live/ContextCard.tsx @@ -1,20 +1,16 @@ /** - * "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, + * "Context window" card for the selected request: what filled the prompt (system prompt, tools, + * skills, memory, files, tool results, conversation) as one stacked bar plus a legend, how full the + * model's window is, and a prompt-cache meter. The categories 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 { useMemo } 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 { CONTEXT_CATEGORIES, calibrateContext, contextHealth, type ContextCategory, type ContextHealth } 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", @@ -23,8 +19,7 @@ const KIND_LABEL = { files: "routeLive.ctxFiles", results: "routeLive.ctxResults", chat: "routeLive.ctxChat", - free: "routeLive.ctxFree", -} as const satisfies Record; +} as const satisfies Record; const HEALTH_LABEL = { ok: "routeLive.ctxHealthOk", @@ -32,34 +27,6 @@ const HEALTH_LABEL = { 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; @@ -94,29 +61,19 @@ function CacheMeter({ row }: { row: RouteRow }) { 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 used = Math.max(shares.used, 1); const fraction = windowTokens ? shares.used / windowTokens : undefined; + const tokensText = (tokens: number) => formatCount(Math.round(tokens), localeTag); + /** Share of the prompt, not of the window: the header already says how full the window is. */ const share = (tokens: number) => { - const value = tokens / base; + const value = tokens / used; 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 }] : []; - }); + const parts = CONTEXT_CATEGORIES.flatMap(kind => (shares.parts[kind] > 0 ? [{ kind, tokens: shares.parts[kind] }] : [])); return (
    @@ -136,37 +93,31 @@ function ContextCardBody({ row }: { row: RouteRow }) { {!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 => ( -
    • -
    • - ))} -
    + {parts.length > 0 && ( + <> + +
      + {parts.map(part => ( +
    • +
    • + ))} +
    + + )} {shares.held &&

    {t("routeLive.ctxHeld")}

    } + ); } diff --git a/gui/src/pages/route-live/FlowDiagram.tsx b/gui/src/pages/route-live/FlowDiagram.tsx index 7ea3751bb8a..e086a4ef139 100644 --- a/gui/src/pages/route-live/FlowDiagram.tsx +++ b/gui/src/pages/route-live/FlowDiagram.tsx @@ -26,7 +26,7 @@ function CandidateDetail({ candidate, localeTag }: { candidate: FlowCandidate; l } 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 (candidate.durationMs !== undefined) parts.push(`${t("logs.col.duration")} ${formatDuration(candidate.durationMs, localeTag)}`); } if (parts.length === 0) return null; return {parts.flatMap((part, i) => (i === 0 ? [part] : [" · ", part]))}; diff --git a/gui/src/pages/route-live/RequestList.tsx b/gui/src/pages/route-live/RequestList.tsx index 316fa4b4e8c..970c722467b 100644 --- a/gui/src/pages/route-live/RequestList.tsx +++ b/gui/src/pages/route-live/RequestList.tsx @@ -142,11 +142,11 @@ export function RequestList({ rows, pinnedKey, onPin, mode, onMode, names }: {

    {t("routeLive.rowHint")}

    {groups ? groups.map(group => { const open = !collapsed.has(group.id); diff --git a/gui/src/pages/route-live/RouteLive.tsx b/gui/src/pages/route-live/RouteLive.tsx index 43f1071eef8..86b2b9ceeb9 100644 --- a/gui/src/pages/route-live/RouteLive.tsx +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -1,17 +1,18 @@ /** * 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. + * asked, who answered, why the rest were skipped, then the list of recent requests. The flow + * diagram is the one account of the route; the lines around it only add what it cannot show. */ import { useMemo, useState } from "react"; import { useI18n, LOCALES } from "../../i18n/shared"; import { EmptyState, Notice } from "../../ui"; +import { DataSurfaceSkeleton } from "../../components/data-surface"; import { ContextCard } from "./ContextCard"; 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 { TimeSection } from "./TimeBar"; import { formatClock, formatDuration } from "./route-format"; import { rowKey, type RouteRow } from "./route-rows"; @@ -52,16 +53,34 @@ function OutcomeLine({ outcome, row }: { outcome: FlowOutcome; row: RouteRow }) } } -function PoolLine({ row }: { row: RouteRow }) { +/** Why the router picked this route, when it recorded a reason. */ +export function WhyLine({ row }: { row: RouteRow }) { + const { t } = useI18n(); + const reason = row.routeDecision?.selected?.reason; + if (!reason) return null; + return ( +

    + {withSlots(t("routeLive.routeWhy", { reason: "{reason}" }), { reason: })} +

    + ); +} + +export function PoolLine({ row }: { row: RouteRow }) { const { t } = useI18n(); const pool = summarizePool(row.accountRoster); if (!pool) return null; + const states = [ + [pool.available, "routeLive.poolAvailable"], [pool.cooldown, "routeLive.poolCooldown"], + [pool.paused, "routeLive.poolPaused"], [pool.needsReauth, "routeLive.poolReauth"], + [pool.quotaExhausted, "routeLive.poolQuota"], [pool.modelUnlisted, "routeLive.poolUnlisted"], + ] as const; + const bits = [ + t("routeLive.poolHead", { provider: pool.provider, total: pool.total }), + ...states.flatMap(([n, key]) => (n > 0 ? [t(key, { n })] : [])), + ]; return (

    - {t("routeLive.poolSummary", { - provider: pool.provider, total: pool.total, available: pool.available, - cooldown: pool.cooldown, paused: pool.paused, reauth: pool.needsReauth, - })} + {bits.join(" · ")} {row.accountRoster?.truncated && ` ${t("routeLive.poolTruncated")}`} {" "} {t("routeLive.linkAccounts")} @@ -81,8 +100,8 @@ function Selected({ row, flow, pinned, onBack }: { row: RouteRow; flow: RouteFlo + - {flow.outcome.kind !== "local" && } {row.routeDecision?.routeKind === "combo" &&

    {t("routeLive.linkCombos")}

    } @@ -105,7 +124,7 @@ export default function RouteLive({ apiBase, active }: { apiBase: string; active if (resource.data === undefined) { return resource.error ? {t("routeLive.loadFailed")} - :

    {t("routeLive.loading")}

    ; + : ; } if (rows.length === 0 || !selected || !flow) { return ; diff --git a/gui/src/pages/route-live/RouteSteps.tsx b/gui/src/pages/route-live/RouteSteps.tsx deleted file mode 100644 index 921a6bdc322..00000000000 --- a/gui/src/pages/route-live/RouteSteps.tsx +++ /dev/null @@ -1,54 +0,0 @@ -/** "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/context-tiles.ts b/gui/src/pages/route-live/context-tiles.ts index 5571d1ec186..fcc586ba4ec 100644 --- a/gui/src/pages/route-live/context-tiles.ts +++ b/gui/src/pages/route-live/context-tiles.ts @@ -1,9 +1,6 @@ /** - * 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. + * Context-window breakdown model: calibration against the measured prompt size and the health word. + * Pure, no React. The categories and thresholds are ported from Magpie's internal/gui/assets/context.js. * * MIT License * Copyright (c) 2026 yetone @@ -79,164 +76,3 @@ 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/flow-model.ts b/gui/src/pages/route-live/flow-model.ts index 5c8c4fbf841..603e8367334 100644 --- a/gui/src/pages/route-live/flow-model.ts +++ b/gui/src/pages/route-live/flow-model.ts @@ -111,26 +111,6 @@ export function buildRouteFlow(row: RouteRow, names: AccountNames = {}): RouteFl }; } -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; diff --git a/gui/src/pages/route-live/route-live.css b/gui/src/pages/route-live/route-live.css index dc0617a3009..374ebe96dd1 100644 --- a/gui/src/pages/route-live/route-live.css +++ b/gui/src/pages/route-live/route-live.css @@ -39,7 +39,7 @@ 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-body { display: flex; flex-direction: column; min-width: 0; gap: var(--space-0-5); } .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); } @@ -77,10 +77,10 @@ .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() */ +/* context window card: one hue per category, light and dark through light-dark(); the bar reuses .rl-time-bar */ .rl-ctx { --rl-ctx-system: light-dark(#7c3aed, #a78bfa); - --rl-ctx-results: light-dark(#c2410c, #fb923c); + --rl-ctx-results: light-dark(#be185d, #f472b6); --rl-ctx-chat: light-dark(#4f46e5, #818cf8); display: flex; flex-direction: column; gap: var(--space-2); } @@ -95,46 +95,22 @@ } .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 { flex: 0 1 160px; min-width: 80px; height: 6px; border-radius: var(--radius-2xs); 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-kind--system { --k: var(--rl-ctx-system); } +.rl-ctx-kind--tools { --k: var(--blue); } +.rl-ctx-kind--skills { --k: var(--muted); } +.rl-ctx-kind--memory { --k: var(--amber); } +.rl-ctx-kind--files { --k: var(--green); } +.rl-ctx-kind--results { --k: var(--rl-ctx-results); } +.rl-ctx-kind--chat { --k: var(--rl-ctx-chat); } +.rl-ctx-seg { flex: 1 1 0; min-width: 2px; background: var(--k); } .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); } +.rl-ctx-dot { flex: 0 0 auto; width: 8px; height: 8px; border-radius: var(--space-0-5); background: var(--k); } /* request list */ .rl-list { display: flex; flex-direction: column; gap: var(--space-2); min-width: 0; overflow-x: auto; } diff --git a/gui/tests/route-live-context.test.ts b/gui/tests/route-live-context.test.ts index 3db0bd114d3..659bce3db37 100644 --- a/gui/tests/route-live-context.test.ts +++ b/gui/tests/route-live-context.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { - calibrateContext, contextHealth, layoutTiles, type ContextBreakdown, type ContextTile, + calibrateContext, contextHealth, type ContextBreakdown, } from "../src/pages/route-live/context-tiles"; import { cacheHitPercent, cacheMeterOf, parseRouteRows, type RouteRow } from "../src/pages/route-live/route-rows"; @@ -10,27 +10,6 @@ const breakdown = (over: Partial = {}): ContextBreakdown => ({ 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); @@ -64,73 +43,6 @@ describe("context calibration", () => { }); }); -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; diff --git a/gui/tests/route-live-model.test.ts b/gui/tests/route-live-model.test.ts index 3ee6048822e..f96020d5c57 100644 --- a/gui/tests/route-live-model.test.ts +++ b/gui/tests/route-live-model.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { buildRouteFlow, buildRouteSteps, summarizePool } from "../src/pages/route-live/flow-model"; +import { buildRouteFlow, summarizePool } from "../src/pages/route-live/flow-model"; import { groupRows } from "../src/pages/route-live/request-groups"; import { cacheHitPercent, parseRouteRows, readableAccountLabel, requestedOf, type RouteRow } from "../src/pages/route-live/route-rows"; @@ -16,8 +16,6 @@ describe("route flow model", () => { 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", () => { @@ -31,8 +29,6 @@ describe("route flow model", () => { })); 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", () => { @@ -51,7 +47,6 @@ describe("route flow model", () => { 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 }); }); diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 79caf658107..43781f38ce8 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -6,7 +6,7 @@ import { I18nContext, DICTS, interpolate, LOCALES, type Locale, type TFn } from 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"; +import { PoolLine, WhyLine } from "../src/pages/route-live/RouteLive"; 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"; @@ -50,11 +50,20 @@ test("flow marks the answered account, the failed try with its reason, and a ski 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); +test("the why line shows an unknown reason code raw, in , instead of dropping it", () => { + const doc = render(); expect([...doc.querySelectorAll("code")].map(c => c.textContent)).toContain("some-future-reason"); + expect(render().body.innerHTML).toBe(""); +}); + +test("the pool line counts every state that is not zero, quota and plan included, and only those", () => { + const roster = { provider: "p", accounts: [ + { label: "oa", state: "available" }, { label: "ob", state: "quota-exhausted" }, + { label: "oc", state: "quota-exhausted" }, { label: "od", state: "model-unlisted" }] }; + const text = render(, "en").body.textContent ?? ""; + expect(text).toContain("Pool p: 4 accounts · 1 available · 2 out of quota · 1 without this model"); + expect(text).not.toContain("paused"); + expect(text).not.toContain("cooling"); }); test("request list groups by session, shows dashes for unknown metrics, and marks the pinned row", () => { @@ -99,17 +108,15 @@ const withContext = (extra: Partial = {}) => ({ ...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", () => { +test("context card shows the used/window header, one bar segment per filled part, 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-seg").length).toBe(5); expect([...doc.querySelectorAll(".rl-ctx-legend li > span:nth-child(2)")].map(s => s.textContent)).toEqual( - ["系统提示词", "工具", "记忆与 AGENTS.md", "工具结果", "会话内容", "剩余空间"]); + ["系统提示词", "工具", "记忆与 AGENTS.md", "工具结果", "会话内容"]); + expect(doc.querySelector(".rl-ctx-legend li .rl-num")?.textContent).toContain("10%"); 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"); @@ -124,7 +131,7 @@ test("context card says so when the window is unknown, the sizes are estimated, 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); + expect(doc.querySelector(".rl-ctx-health")).toBeNull(); }); test("context card is hidden for a row without a breakdown", () => { From 2aa903e8c1a0f8129de719f781cb87994fb26821 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:29:28 -0500 Subject: [PATCH 05/18] fix(usage): live meter reports no speed for retried rows and no hit rate for unobserved cache --- src/usage/live-meter.ts | 17 ++++++++++++----- tests/usage/live-meter.test.ts | 11 +++++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/usage/live-meter.ts b/src/usage/live-meter.ts index e26fc5fc3fe..76ba4e80f53 100644 --- a/src/usage/live-meter.ts +++ b/src/usage/live-meter.ts @@ -11,13 +11,14 @@ * reason vocabulary is the same. */ import type { RequestLogEntry } from "../server/request-log"; +import { cacheObservationFromUsage } from "./summary"; export type MeterSpeedReason = | "no_matching_request" | "request_aborted" | "request_incomplete" | "request_failed" | "usage_missing" | "tokens_estimated" | "output_missing" | "generation_timing_missing" - | "generation_window_too_short" | "invalid_generation_window"; + | "generation_window_too_short" | "invalid_generation_window" | "multiple_attempts"; -export type MeterPercentReason = "usage_missing" | "tokens_estimated" | "input_missing" | "limit_unknown"; +export type MeterPercentReason = "usage_missing" | "tokens_estimated" | "input_missing" | "limit_unknown" | "cache_unobserved"; export interface LiveMeter { speed: { value: number | null; reason: MeterSpeedReason | null }; @@ -49,6 +50,9 @@ function speed(entry: RequestLogEntry): LiveMeter["speed"] { if (entry.usageStatus === "estimated" || entry.usage.estimated === true) return none("tokens_estimated"); const tokens = entry.usage.outputTokens; if (!(Number.isFinite(tokens) && tokens > 0)) return none("output_missing"); + // A retried row sums output over every attempt, but its generation window is one span from the + // first attempt's first event to the last attempt's last delta, gaps between attempts included. + if ((entry.attempts?.length ?? 0) > 1) return none("multiple_attempts"); const start = entry.genStartMs; const end = entry.lastOutputMs; if (!(typeof start === "number" && Number.isFinite(start) && start >= 0 && typeof end === "number" && Number.isFinite(end))) { @@ -74,9 +78,11 @@ export function liveMeterFromEntry(entry: RequestLogEntry, contextLimitTokens: n const inputTokens = count(usage?.inputTokens); const outputTokens = count(usage?.outputTokens); const readTokens = count(usage?.cacheReadInputTokens ?? usage?.cachedInputTokens); - // `cacheReadInputTokens` is the read subset of `inputTokens`; a synthesized provenance is wire-only. + // `cacheReadInputTokens` is the read subset of `inputTokens`. Only an observed reading is a hit + // rate: a synthesized zero is wire-only and an unknown one was never measured (summary.ts). + const cacheObserved = !!usage && cacheObservationFromUsage(usage, entry.cacheProvenance).provenance === "observed"; const cacheKnown = readTokens !== null && inputTokens !== null && inputTokens > 0 - && entry.cacheProvenance !== "synthesized" && readTokens <= inputTokens; + && cacheObserved && readTokens <= inputTokens; const used = count(usage?.contextTotalTokens) ?? (inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null); const limit = contextLimitTokens !== null && Number.isFinite(contextLimitTokens) && contextLimitTokens > 0 @@ -88,7 +94,8 @@ export function liveMeterFromEntry(entry: RequestLogEntry, contextLimitTokens: n cache: { readTokens, inputTokens, percent: cacheKnown ? (100 * readTokens) / inputTokens : null, - reason: cacheKnown ? null : usageReason ?? "input_missing", + reason: cacheKnown ? null : usageReason + ?? (readTokens !== null && inputTokens !== null && inputTokens > 0 && !cacheObserved ? "cache_unobserved" : "input_missing"), }, context: { usedTokens: used, limitTokens: limit, diff --git a/tests/usage/live-meter.test.ts b/tests/usage/live-meter.test.ts index 7832c4d397d..e5a36b5d980 100644 --- a/tests/usage/live-meter.test.ts +++ b/tests/usage/live-meter.test.ts @@ -47,6 +47,12 @@ describe("live meter speed", () => { expect(m.speed.reason).toBe(reason as never); } }); + test("a retried row reports no speed: its window spans the gap between attempts", () => { + const attempt = { ordinal: 1, provider: "p", model: "fixture", adapter: "a", status: 200, durationMs: 1, sendCount: 1, recoveryKinds: [], usageStatus: "reported" }; + expect(liveMeterFromEntry(row({ attempts: [attempt, { ...attempt, ordinal: 2 }] } as Partial), null).speed) + .toEqual({ value: null, reason: "multiple_attempts" }); + expect(liveMeterFromEntry(row({ attempts: [attempt] } as Partial), null).speed).toEqual({ value: 100, reason: null }); + }); }); describe("live meter cache and context", () => { @@ -62,6 +68,11 @@ describe("live meter cache and context", () => { .toMatchObject({ percent: null, reason: "tokens_estimated" }); expect(liveMeterFromEntry(row({ cacheProvenance: "synthesized", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache.percent).toBeNull(); }); + test("unknown cache provenance is never a measured hit rate, zero counters included", () => { + const m = liveMeterFromEntry(row({ cacheProvenance: "unknown", usage: { inputTokens: 1000, outputTokens: 5, cacheReadInputTokens: 0 } }), null); + expect(m.cache).toEqual({ readTokens: 0, inputTokens: 1000, percent: null, reason: "cache_unobserved" }); + expect(liveMeterFromEntry(row({ cacheProvenance: "observed", usage: { inputTokens: 1000, outputTokens: 5, cacheReadInputTokens: 0 } }), null).cache.percent).toBe(0); + }); test("context used is input plus output, or the absolute context total when the provider gives one", () => { const m = liveMeterFromEntry(row({ usage: { inputTokens: 380_000, outputTokens: 900 } }), 1_000_000); expect(m.context).toEqual({ usedTokens: 380_900, limitTokens: 1_000_000, percent: 38.09, reason: null }); From 054f7a0ac4f332bd3292afb3d0199964489ea02f Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:29:40 -0500 Subject: [PATCH 06/18] fix(usage): a data key reads only its own requests on GET /v1/usage/live --- src/server/live-meter-handler.ts | 27 ++++++++++++++++++------- tests/server/live-meter-handler.test.ts | 16 +++++++++++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/server/live-meter-handler.ts b/src/server/live-meter-handler.ts index 0cf90079fa3..d17018f9d81 100644 --- a/src/server/live-meter-handler.ts +++ b/src/server/live-meter-handler.ts @@ -11,7 +11,7 @@ import { readCatalog, readCodexCatalogPath } from "../codex/catalog"; import { liveMeterFromEntry, selectLiveMeterEntries, type LiveMeter, type MeterClientFamily } from "../usage/live-meter"; import { corsHeaders, isAllowedRequestOrigin, isApiAuthRequired, isLoopbackRequestHost, resolveApiAuth, withCors, - type RequestPolicyView, + type DataPlaneAdmission, type RequestPolicyView, } from "./auth-cors"; import { formatErrorResponse } from "../bridge/errors"; import { matchesLogConversationId } from "./request-log-conversation"; @@ -58,7 +58,18 @@ export function resetLiveMeterCatalogCacheForTests(): void { catalogCache = null export type LiveMeterResult = { status: 200; body: LiveMeterBody } | { status: 400; code: string; message: string }; -export function buildLiveMeter(params: URLSearchParams, deps: LiveMeterDeps = {}): LiveMeterResult { +/** + * Rows the caller may see. A configured data key sees only the requests it sent, like `/v1/usage` + * (hub-usage.ts), so rows of other keys and keyless rows stay hidden from it. Loopback and the + * environment token are the operator and see every row. + */ +export function liveMeterRowVisible(admission: DataPlaneAdmission | undefined): (entry: RequestLogEntry) => boolean { + if (admission?.kind !== "configured") return () => true; + const keyId = admission.keyId; + return entry => entry.apiKeyId === keyId; +} + +export function buildLiveMeter(params: URLSearchParams, deps: LiveMeterDeps = {}, admission?: DataPlaneAdmission): LiveMeterResult { const bad = (message: string): LiveMeterResult => ({ status: 400, code: "live_meter_query_invalid", message }); for (const key of params.keys()) { if ((key !== "client" && key !== "conversation") || params.getAll(key).length !== 1) return bad("Unknown or repeated option"); @@ -68,9 +79,10 @@ export function buildLiveMeter(params: URLSearchParams, deps: LiveMeterDeps = {} const conversation = params.get("conversation"); if (conversation !== null && !conversation.trim()) return bad("conversation must not be empty"); const limitOf = deps.contextLimit ?? ((model: string) => catalogContextLimit(model)); + const visible = liveMeterRowVisible(admission); const selection = selectLiveMeterEntries( (deps.entries ?? getRequestLogEntries)(), - conversation === null ? undefined : entry => matchesLogConversationId(entry.conversationId, conversation), + conversation === null ? visible : entry => visible(entry) && matchesLogConversationId(entry.conversationId, conversation), ); const project = (entry: RequestLogEntry): LiveMeter => liveMeterFromEntry(entry, entry.model ? limitOf(entry.model) : null); const byClient: LiveMeterBody["byClient"] = {}; @@ -86,8 +98,8 @@ export function buildLiveMeter(params: URLSearchParams, deps: LiveMeterDeps = {} } }; } -export function liveMeterResponse(params: URLSearchParams, deps?: LiveMeterDeps): Response { - const result = buildLiveMeter(params, deps); +export function liveMeterResponse(params: URLSearchParams, deps?: LiveMeterDeps, admission?: DataPlaneAdmission): Response { + const result = buildLiveMeter(params, deps, admission); const headers = { "cache-control": "no-store" }; return result.status === 200 ? Response.json(result.body, { headers }) @@ -102,13 +114,14 @@ export async function handleLiveMeterData(req: Request, config: RequestPolicyVie if (admittedOrigin) out.headers.set("Access-Control-Allow-Origin", LIVE_METER_APP_ORIGIN); return out; }; - if (!resolveApiAuth(req, config)) return reply(formatErrorResponse(401, "authentication_error", "opencodex API key required")); + const admission = resolveApiAuth(req, config); + if (!admission) return reply(formatErrorResponse(401, "authentication_error", "opencodex API key required")); // The renderer is not loopback-by-origin; the loopback Host gate still binds it when no key is required. const originOk = appRenderer ? isApiAuthRequired(config) || isLoopbackRequestHost(req.headers.get("Host")) : isAllowedRequestOrigin(req, config); if (!originOk) return reply(formatErrorResponse(403, "origin_rejected", "cross-origin data-plane request blocked")); - return reply(liveMeterResponse(new URL(req.url).searchParams, deps), appRenderer); + return reply(liveMeterResponse(new URL(req.url).searchParams, deps, admission), appRenderer); } /** diff --git a/tests/server/live-meter-handler.test.ts b/tests/server/live-meter-handler.test.ts index f731b40c1d4..a2111d0606e 100644 --- a/tests/server/live-meter-handler.test.ts +++ b/tests/server/live-meter-handler.test.ts @@ -137,6 +137,22 @@ describe("data-plane admission and CORS", () => { } }); + test("a configured key sees only its own rows; the operator sees every row", async () => { + const other = { ...key, id: "k2", key: "ocx_data_livemeterother" }; + const config = { ...remote, apiKeys: [key, other] }; + const own = [row({ timestamp: 100, apiKeyId: "k" }), row({ timestamp: 200, apiKeyId: "k2", client: "claude_code" }), row({ timestamp: 300 })]; + const scoped = { ...deps, entries: () => own }; + const read = async (secret: string, query = "") => (await handleLiveMeterData( + get(`http://10.0.0.2:1/v1/usage/live${query}`, { "x-opencodex-api-key": secret }), config, scoped)).json(); + const mine = await read(key.key); + expect(mine.latest.timestamp).toBe(100); + expect(Object.keys(mine.byClient)).toEqual(["codex"]); + expect((await read(other.key)).latest.timestamp).toBe(200); + expect((await read(key.key, "?client=claude")).latest).toBeNull(); + const operator = buildLiveMeter(new URLSearchParams(), scoped, { kind: "loopback", source: "loopback" }); + expect(operator.status === 200 && operator.body.latest?.timestamp).toBe(300); + }); + test("the app origin is not admitted anywhere else: the data-plane origin policy is unchanged", () => { expect(isAllowedRequestOrigin(get("http://127.0.0.1:1/v1/models", { origin: "app://-", host: "127.0.0.1:1" }), loopback)).toBe(false); }); From 48319c05e1cf99d20f5b23f1028396d848c57a3d Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:29:52 -0500 Subject: [PATCH 07/18] fix(usage): context breakdown counts system images, legacy Chat functions and user text after a reminder --- src/server/context-breakdown-classify.ts | 27 ++++++++++++------- src/server/context-breakdown.ts | 12 ++++++++- tests/usage/context-breakdown.test.ts | 34 ++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/src/server/context-breakdown-classify.ts b/src/server/context-breakdown-classify.ts index 563231a62e0..a8a9cd91b04 100644 --- a/src/server/context-breakdown-classify.ts +++ b/src/server/context-breakdown-classify.ts @@ -321,15 +321,16 @@ export class BreakdownAccumulator { /** 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; + let t = text.trim(); + const leading = t.startsWith(REMINDER_OPEN); + // each leading reminder is memory; whatever the user wrote after them is still the user's + while (t.startsWith(REMINDER_OPEN)) { + const close = t.indexOf(REMINDER_CLOSE); + const end = close < 0 ? t.length : close + REMINDER_CLOSE.length; + this.reminder(t.slice(0, end)); + t = t.slice(end).trim(); } + if (t === "") return; if (AGENTS_FOR.test(t)) { this.memory += tokensOfText(t); return; @@ -340,7 +341,15 @@ export class BreakdownAccumulator { return; } } - this.chat(tokensOfText(text)); + this.chat(tokensOfText(leading ? t : text)); + } + + private reminder(span: string): void { + let rest = this.splitSkills(this.splitMemory(span)).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); } private splitMemory(text: string): string { diff --git a/src/server/context-breakdown.ts b/src/server/context-breakdown.ts index f28982bf7b7..64876d0be99 100644 --- a/src/server/context-breakdown.ts +++ b/src/server/context-breakdown.ts @@ -241,7 +241,10 @@ function responsesItem(acc: BreakdownAccumulator, raw: unknown): void { 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); + for (const p of parts) { + if (p.image) acc.file(IMAGE_TOKENS); + else if (p.text !== "") acc.systemText(p.text); + } return; } if (role === "user") { @@ -273,6 +276,8 @@ function outputTokens(acc: BreakdownAccumulator, output: unknown): number { function readChat(acc: BreakdownAccumulator, body: Rec): void { if (Array.isArray(body.tools)) for (const t of body.tools) responsesTool(acc, t); + // legacy Chat function calling: bare definitions, and one `function_call` per assistant message + if (Array.isArray(body.functions)) for (const f of body.functions) responsesTool(acc, f); if (!Array.isArray(body.messages)) return; for (const m of body.messages) { if (!isRec(m)) continue; @@ -296,6 +301,11 @@ function readChat(acc: BreakdownAccumulator, body: Rec): void { let said = 0; for (const p of parts) said += tokensOfText(p.text); acc.chat(said); + if (isRec(m.function_call)) { + const name = str(m.function_call.name); + acc.noteCall("", name, m.function_call.arguments); + acc.chat(tokensOfText(name) + argumentTokens(m.function_call.arguments)); + } if (!Array.isArray(m.tool_calls)) continue; for (const c of m.tool_calls) { if (!isRec(c) || !isRec(c.function)) continue; diff --git a/tests/usage/context-breakdown.test.ts b/tests/usage/context-breakdown.test.ts index ea995c917c5..f7f6245c34c 100644 --- a/tests/usage/context-breakdown.test.ts +++ b/tests/usage/context-breakdown.test.ts @@ -117,6 +117,13 @@ describe("OpenAI Responses (Codex-style)", () => { expect(b.turns[0]).toBe(1 + 10 + 30); }); + test("an image-only developer message is measured as a file", () => { + const b = measureContextBreakdown({ input: [{ role: "developer", content: [{ type: "input_image", image_url: "data:image/png;base64,AAAA" }] }] }, "responses")!; + expect(b).toBeDefined(); + expect(b.parts.files).toBe(1600); + expect(b.parts.system).toBe(0); + }); + 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" }] }], @@ -209,6 +216,16 @@ describe("Anthropic Messages (Claude Code-style)", () => { expect(b.parts.chat).toBe(tok("see attachments") + 10 + 10); }); + test("text after a reminder in the same block is the user speaking, and begins a turn", () => { + const b = measureContextBreakdown({ + messages: [{ role: "user", content: [{ type: "text", text: `${fill(40, "r")} +${fill(80, "u")}` }] }], + }, "messages")!; + expect(b.parts.memory).toBe(10); + expect(b.turns).toEqual([20]); + expect(b.parts.chat).toBe(20); + }); + 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); @@ -237,6 +254,23 @@ describe("OpenAI Chat Completions", () => { expect(b.turns).toHaveLength(2); expect(b.parts.chat).toBe(sum(b.turns)); }); + + test("legacy functions and function_call count as tools and the call, the result as a result", () => { + const fn = { name: "lookup", description: "Looks things up", parameters: { type: "object", properties: { q: { type: "string" } } } }; + const args = JSON.stringify({ q: fill(40) }); + const b = measureContextBreakdown({ + functions: [fn], + messages: [ + { role: "user", content: "look it up" }, + { role: "assistant", content: null, function_call: { name: "lookup", arguments: args } }, + { role: "function", name: "lookup", content: fill(80, "f") }, + ], + }, "chat")!; + expect(b.toolCount).toBe(1); + expect(b.parts.tools).toBeGreaterThan(0); + expect(b.parts.results).toBe(20); + expect(b.turns).toEqual([tok("look it up") + tok("lookup") + tok(args)]); + }); }); describe("estimator", () => { From 28bf90020aae3ab70f45536bf748d1ba0c88d024 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:30:02 -0500 Subject: [PATCH 08/18] fix(gui): live routing rows name each metric for screen readers and size context from the serving attempt --- gui/src/pages/route-live/ContextCard.tsx | 4 ++-- gui/src/pages/route-live/RequestList.tsx | 21 +++++++++++++-------- gui/src/pages/route-live/route-rows.ts | 12 ++++++++++++ gui/tests/route-live-context.test.ts | 11 ++++++++++- gui/tests/route-live-render.test.tsx | 7 ++++++- 5 files changed, 43 insertions(+), 12 deletions(-) diff --git a/gui/src/pages/route-live/ContextCard.tsx b/gui/src/pages/route-live/ContextCard.tsx index 50f42477c5c..c3bb0df9313 100644 --- a/gui/src/pages/route-live/ContextCard.tsx +++ b/gui/src/pages/route-live/ContextCard.tsx @@ -9,7 +9,7 @@ import { useI18n, LOCALES } from "../../i18n/shared"; import type { RouteLiveCopyKey } from "../../i18n/route-live-copy"; import { CONTEXT_CATEGORIES, calibrateContext, contextHealth, type ContextCategory, type ContextHealth } from "./context-tiles"; import { formatCount, formatPercent } from "./route-format"; -import { cacheMeterOf, countedInputTokens, type RouteRow } from "./route-rows"; +import { cacheMeterOf, contextInputTokens, type RouteRow } from "./route-rows"; const KIND_LABEL = { system: "routeLive.ctxSystem", @@ -63,7 +63,7 @@ function ContextCardBody({ row }: { row: RouteRow }) { const localeTag = LOCALES.find(l => l.code === locale)?.htmlLang; const breakdown = row.contextBreakdown!; const windowTokens = row.contextWindow; - const shares = useMemo(() => calibrateContext(breakdown, countedInputTokens(row)), [breakdown, row]); + const shares = useMemo(() => calibrateContext(breakdown, contextInputTokens(row)), [breakdown, row]); const used = Math.max(shares.used, 1); const fraction = windowTokens ? shares.used / windowTokens : undefined; diff --git a/gui/src/pages/route-live/RequestList.tsx b/gui/src/pages/route-live/RequestList.tsx index 970c722467b..3997cb64592 100644 --- a/gui/src/pages/route-live/RequestList.tsx +++ b/gui/src/pages/route-live/RequestList.tsx @@ -67,6 +67,10 @@ function GroupHead({ label, stats, open, onToggle, localeTag }: { ); } +function Field({ label }: { label: string }) { + return {label}: ; +} + function RequestRow({ row, pinned, names, localeTag, onPin }: { row: RouteRow; pinned: boolean; names: AccountNames; localeTag?: string; onPin: (key: string) => void; }) { @@ -90,14 +94,15 @@ function RequestRow({ row, pinned, names, localeTag, onPin }: { {servedModelOf(row)} {tries > 1 && {t("routeLive.rowTries", { count: tries })}} - {effortText(row)} - {formatDuration(row.durationMs, localeTag)} - {row.firstOutputMs === undefined ? DASH : formatDuration(row.firstOutputMs, localeTag)} - {tokens === undefined ? DASH : formatCount(tokens, localeTag)} - {cache === undefined ? DASH : formatPercent(cache, localeTag)} - {rate ? formatRate(rate.value, rate.estimated, localeTag) : DASH} - {cost === undefined ? DASH : formatEstimatedUsdValue(cost, t, localeTag)} - {row.status} + {/* The column headings are aria-hidden, so each value carries its own name for screen readers. */} + {effortText(row)} + {formatDuration(row.durationMs, localeTag)} + {row.firstOutputMs === undefined ? DASH : formatDuration(row.firstOutputMs, localeTag)} + {tokens === undefined ? DASH : formatCount(tokens, localeTag)} + {cache === undefined ? DASH : formatPercent(cache, localeTag)} + {rate ? formatRate(rate.value, rate.estimated, localeTag) : DASH} + {cost === undefined ? DASH : formatEstimatedUsdValue(cost, t, localeTag)} + {row.status} ); diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts index 4177fb78a66..466f35c9994 100644 --- a/gui/src/pages/route-live/route-rows.ts +++ b/gui/src/pages/route-live/route-rows.ts @@ -33,6 +33,8 @@ export interface RouteAttempt { accountLogLabel?: string; accountTag?: string; errorCode?: string; + /** This attempt's own usage; the row's `usage` sums every attempt of a retried request. */ + usage?: { inputTokens?: number }; } export interface RouteRoster { @@ -202,6 +204,16 @@ export function countedInputTokens(row: Pick): number | undef return finite(input) && input > 0 ? input : undefined; } +/** + * Input the serving model held, for sizing its context. A retried row's `usage` sums every + * attempt, so it reads the final attempt's own; without that, undefined (the estimate stands). + */ +export function contextInputTokens(row: Pick): number | undefined { + if ((row.attempts?.length ?? 0) <= 1) return countedInputTokens(row); + const input = row.attempts!.at(-1)?.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; diff --git a/gui/tests/route-live-context.test.ts b/gui/tests/route-live-context.test.ts index 659bce3db37..59005db6601 100644 --- a/gui/tests/route-live-context.test.ts +++ b/gui/tests/route-live-context.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"; import { calibrateContext, contextHealth, type ContextBreakdown, } from "../src/pages/route-live/context-tiles"; -import { cacheHitPercent, cacheMeterOf, parseRouteRows, type RouteRow } from "../src/pages/route-live/route-rows"; +import { cacheHitPercent, cacheMeterOf, contextInputTokens, parseRouteRows, type RouteRow } from "../src/pages/route-live/route-rows"; const breakdown = (over: Partial = {}): ContextBreakdown => ({ v: 1, @@ -55,6 +55,15 @@ describe("cache meter and parsing", () => { expect(cacheHitPercent(row({ inputTokens: 1000, outputTokens: 10, cacheReadInputTokens: 250 }))).toBe(25); }); + test("a retried row sizes its context from the serving attempt, not the summed usage", () => { + const attempt = (inputTokens?: number) => ({ provider: "p", model: "m", status: 200, ...(inputTokens === undefined ? {} : { usage: { inputTokens } }) }); + const summed = { ...row({ inputTokens: 80_000, outputTokens: 10 }) }; + expect(contextInputTokens({ ...summed, attempts: [attempt(40_000), attempt(40_000)] })).toBe(40_000); + expect(contextInputTokens({ ...summed, attempts: [attempt(40_000), attempt()] })).toBeUndefined(); + expect(contextInputTokens({ ...summed, attempts: [attempt(80_000)] })).toBe(80_000); + expect(contextInputTokens(summed)).toBe(80_000); + }); + 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(); diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 43781f38ce8..29a0a27801f 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -75,7 +75,10 @@ test("request list groups by session, shows dashes for unknown metrics, and mark 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"); + // headings are aria-hidden, so each value names itself for screen readers + expect(flat.querySelector(".rl-bad")?.textContent).toBe(`${translator("zh")("logs.col.status")}: 500`); + expect(flat.querySelector(".rl-bad .sr-only")?.textContent).toBe(`${translator("zh")("logs.col.status")}: `); + expect([...flat.querySelectorAll("button.rl-row")[0]!.querySelectorAll(".sr-only")].map(s => s.textContent)).toContain(`${translator("zh")("routeLive.colTtft")}: `); const grouped = list("session"); expect(grouped.querySelectorAll(".rl-group-head").length).toBe(2); expect(grouped.querySelector(".rl-group-head")?.getAttribute("aria-expanded")).toBe("true"); @@ -100,6 +103,8 @@ test("time bar lists each measured stage in order with its label, or a note when const withContext = (extra: Partial = {}) => ({ ...failover, usage: { inputTokens: 1000, outputTokens: 200, cacheReadInputTokens: 500 }, + // a retried row sizes its context from the serving attempt's own usage + attempts: [failover.attempts![0], { ...failover.attempts![1], usage: { inputTokens: 1000 } }], contextWindow: 200_000, contextBreakdown: { v: 1, toolCount: 3, turns: [100, 250], From a1cdae831c96679cb420efe10216cfff6de9f6fc Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:30:15 -0500 Subject: [PATCH 09/18] docs(usage): live meter key scope, multiple_attempts and cache_unobserved reasons --- docs-site/src/content/docs/es/reference/management-api.md | 6 +++--- docs-site/src/content/docs/reference/management-api.md | 6 +++--- .../src/content/docs/zh-cn/reference/management-api.md | 6 +++--- .../src/content/docs/zh-tw/reference/management-api.md | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 1e942f2fbb0..9473675f201 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -398,7 +398,7 @@ La visibilidad/selección exitosa escribe a `/api/disabled-models`, `/api/model- ### Medidor en vivo (`GET /v1/usage/live`) -Un endpoint de solo lectura del plano de datos informa de la solicitud completada más reciente: velocidad de salida, acierto de caché y ocupación del contexto. Un cliente, como un userscript de Codex de escritorio, puede consultarlo para mostrar esas cifras junto al compositor. Se admite exactamente igual que `/v1/models`: sin credencial en un enlace loopback, con una clave de datos (`x-opencodex-api-key`, `Authorization: Bearer` o `x-api-key`) en otro caso, y nunca con el token de administración. El origen de la página de Codex de escritorio `app://-` puede leer solo esta ruta (y su preflight); las demás rutas del plano de datos conservan sus reglas de origen. +Un endpoint de solo lectura del plano de datos informa de la solicitud completada más reciente: velocidad de salida, acierto de caché y ocupación del contexto. Un cliente, como un userscript de Codex de escritorio, puede consultarlo para mostrar esas cifras junto al compositor. Se admite exactamente igual que `/v1/models`: sin credencial en un enlace loopback, con una clave de datos (`x-opencodex-api-key`, `Authorization: Bearer` o `x-api-key`) en otro caso, y nunca con el token de administración. Una clave de datos configurada solo ve las solicitudes enviadas con esa clave; un llamador loopback y el token de entorno ven todas las solicitudes. El origen de la página de Codex de escritorio `app://-` puede leer solo esta ruta (y su preflight); las demás rutas del plano de datos conservan sus reglas de origen. Consulta: `client=codex|claude|other` limita el resultado a una familia de clientes y `conversation=` a una conversación. El filtro de conversación acepta el id original, el resumen registrado o un enlace `codex://threads/`, y la respuesta nunca lo repite. El cuerpo es `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": }`. Un `Meter` contiene `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` y `timestamp`: solo números, nombres de modelo y proveedor y códigos de motivo. Las revisiones automáticas de aprobación (`codex-auto-review`) nunca se informan. @@ -406,8 +406,8 @@ Un valor es `null` (se muestra como `--`) en lugar de una estimación cuando no | Valor | `null` cuando | | --- | --- | -| `speed` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. | -| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada o la lectura de caché solo existe en el cable. | +| `speed` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente; la solicitud se reintentó en más de un intento (`multiple_attempts`), cuya ventana abarcaría la pausa entre ellos. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. | +| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada, o la lectura de caché no se observó: solo existe en el cable o su procedencia es desconocida (`cache.reason` es `cache_unobserved`). | | `context.percent` | El uso falta o es estimado, o la ventana de contexto del modelo no está en el catálogo persistido de Codex (`context.reason` es `limit_unknown`). | diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 23031f7e632..7307f99290a 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -674,7 +674,7 @@ outcome fields from an older server do not establish successful recovery. ### Live meter (`GET /v1/usage/live`) -A read-only data-plane endpoint reports the newest completed request: output speed, cache hit and context fill. A client such as a Codex desktop userscript can poll it to show those numbers next to the composer. It is admitted exactly like `/v1/models`: no credential on a loopback bind, a data key (`x-opencodex-api-key`, `Authorization: Bearer` or `x-api-key`) otherwise, and never the admin token. The Codex desktop page origin `app://-` may read this one route (and its preflight); every other data-plane route keeps its existing origin rules. +A read-only data-plane endpoint reports the newest completed request: output speed, cache hit and context fill. A client such as a Codex desktop userscript can poll it to show those numbers next to the composer. It is admitted exactly like `/v1/models`: no credential on a loopback bind, a data key (`x-opencodex-api-key`, `Authorization: Bearer` or `x-api-key`) otherwise, and never the admin token. A configured data key sees only the requests sent with that key; a loopback caller and the environment token see every request. The Codex desktop page origin `app://-` may read this one route (and its preflight); every other data-plane route keeps its existing origin rules. Query: `client=codex|claude|other` narrows the result to one client family, and `conversation=` to one conversation. The conversation filter accepts the raw id, the logged digest or a `codex://threads/` link, and the response never echoes it. The body is `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": }`. A `Meter` carries `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` and `timestamp`: numbers, model and provider names and reason codes only. Automatic approval reviews (`codex-auto-review`) are never reported. @@ -682,8 +682,8 @@ A value is `null` (shown as `--`) instead of a guess when it cannot be measured: | Value | `null` when | | --- | --- | -| `speed` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent. Speed is output tokens over the generation window, never wall time. | -| `cache.percent` | Usage is missing or estimated, the input count is missing or the cache read is wire-only. | +| `speed` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent; the request was retried across more than one attempt (`multiple_attempts`), whose window would span the gap between them. Speed is output tokens over the generation window, never wall time. | +| `cache.percent` | Usage is missing or estimated, the input count is missing, or the cache read was not observed: wire-only or of unknown provenance (`cache.reason` is `cache_unobserved`). | | `context.percent` | Usage is missing or estimated, or the model's context window is not in the persisted Codex catalog (`context.reason` is `limit_unknown`). | ### OAuth accounts, provider keys, and data-plane keys diff --git a/docs-site/src/content/docs/zh-cn/reference/management-api.md b/docs-site/src/content/docs/zh-cn/reference/management-api.md index 2dcba3021f5..1a598c2730b 100644 --- a/docs-site/src/content/docs/zh-cn/reference/management-api.md +++ b/docs-site/src/content/docs/zh-cn/reference/management-api.md @@ -229,7 +229,7 @@ Aside 配置档的变更在这种情况下仍会保存一件事:确认之后 ### 实时指标(`GET /v1/usage/live`) -只读的数据平面端点,返回最近一次已完成请求的输出速度、缓存命中率和上下文占用,例如供 Codex 桌面端用户脚本在输入框旁显示。准入与 `/v1/models` 完全相同:回环绑定无需凭据,否则需要数据密钥(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永远不接受管理令牌。Codex 桌面端页面来源 `app://-` 仅可读取这一条路由(及其预检),其他数据平面路由的来源规则不变。 +只读的数据平面端点,返回最近一次已完成请求的输出速度、缓存命中率和上下文占用,例如供 Codex 桌面端用户脚本在输入框旁显示。准入与 `/v1/models` 完全相同:回环绑定无需凭据,否则需要数据密钥(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永远不接受管理令牌。已配置的数据密钥只能看到用该密钥发出的请求;回环调用方和环境令牌可以看到所有请求。Codex 桌面端页面来源 `app://-` 仅可读取这一条路由(及其预检),其他数据平面路由的来源规则不变。 查询参数:`client=codex|claude|other` 限定客户端类别,`conversation=` 限定单个会话;会话过滤接受原始 id、日志中的摘要或 `codex://threads/` 链接,响应不会回显它。响应体为 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有数字、模型与 provider 名称和原因码。自动审批审查(`codex-auto-review`)不会被报告。 @@ -237,8 +237,8 @@ Aside 配置档的变更在这种情况下仍会保存一件事:确认之后 | 值 | 为 `null` 的情况 | | --- | --- | -| `speed` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致。速度是输出 token 除以生成窗口,而不是墙钟时间。 | -| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取仅存在于线路层。 | +| `speed` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致;请求经过多次尝试(`multiple_attempts`),其窗口会包含尝试之间的间隔。速度是输出 token 除以生成窗口,而不是墙钟时间。 | +| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取并非实测:仅存在于线路层或来源未知(`cache.reason` 为 `cache_unobserved`)。 | | `context.percent` | 用量缺失或为估算值,或该模型的上下文窗口不在已持久化的 Codex 目录中(`context.reason` 为 `limit_unknown`)。 | ### OAuth 账户、provider 密钥和数据平面密钥 diff --git a/docs-site/src/content/docs/zh-tw/reference/management-api.md b/docs-site/src/content/docs/zh-tw/reference/management-api.md index 371fb4d2eef..7ab8b07356b 100644 --- a/docs-site/src/content/docs/zh-tw/reference/management-api.md +++ b/docs-site/src/content/docs/zh-tw/reference/management-api.md @@ -232,7 +232,7 @@ Aside 設定檔的變更在這種情況下仍會儲存一件事:確認之後 ### 即時指標(`GET /v1/usage/live`) -唯讀的資料平面端點,回傳最近一次已完成請求的輸出速度、快取命中率與上下文占用,例如供 Codex 桌面端使用者腳本在輸入框旁顯示。存取許可與 `/v1/models` 完全相同:回送綁定不需憑證,否則需要資料金鑰(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永遠不接受管理權杖。Codex 桌面端頁面來源 `app://-` 僅可讀取這一條路由(及其預檢),其他資料平面路由的來源規則不變。 +唯讀的資料平面端點,回傳最近一次已完成請求的輸出速度、快取命中率與上下文占用,例如供 Codex 桌面端使用者腳本在輸入框旁顯示。存取許可與 `/v1/models` 完全相同:回送綁定不需憑證,否則需要資料金鑰(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永遠不接受管理權杖。已設定的資料金鑰只能看到用該金鑰送出的請求;回送呼叫方與環境權杖可以看到所有請求。Codex 桌面端頁面來源 `app://-` 僅可讀取這一條路由(及其預檢),其他資料平面路由的來源規則不變。 查詢參數:`client=codex|claude|other` 限定用戶端類別,`conversation=` 限定單一對話;對話過濾接受原始 id、日誌中的摘要或 `codex://threads/` 連結,回應不會回顯它。回應本體為 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有數字、模型與供應商名稱和原因碼。自動核准審查(`codex-auto-review`)不會被回報。 @@ -240,8 +240,8 @@ Aside 設定檔的變更在這種情況下仍會儲存一件事:確認之後 | 值 | 為 `null` 的情況 | | --- | --- | -| `speed` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 | -| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取僅存在於線路層。 | +| `speed` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致;請求經過多次嘗試(`multiple_attempts`),其視窗會包含嘗試之間的間隔。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 | +| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取並非實測:僅存在於線路層或來源未知(`cache.reason` 為 `cache_unobserved`)。 | | `context.percent` | 用量缺失或為估算值,或該模型的上下文視窗不在已持久化的 Codex 目錄中(`context.reason` 為 `limit_unknown`)。 | ### OAuth 帳號、供應商金鑰與 data-plane 金鑰 From e2edfc546addf582e2245fda52a60143cf96d2ca Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:31:03 -0500 Subject: [PATCH 10/18] docs(structure): data-loopback allowlist names the context relays and the live-meter preflight --- structure/runtime.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/structure/runtime.md b/structure/runtime.md index b2967808b9a..9b410e5e094 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -213,7 +213,7 @@ Enabled startup retains separate fresh ownership decisions. Explicit `sync` and `startServer` composes up to four sockets in one synchronous startup transaction: the public data listener, optional unauthenticated data-loopback and hub-management listeners, and the optional `hub-link` listener, which opens only for a recorded link and persists its concrete `127.0.0.1:`. HTTP Responses/Messages apply the [caller header contract](data-planes/inbound-compat.md#http-caller-conversation-identity) before turn admission and dispatch. Linked-machine data uses the [connection-bound relay contract](remote-link.md#connection-bound-relay-authentication); client-local credentials and routing policy remain unchanged. The data-loopback socket serves a fixed data-plane allowlist: Responses and its compact sibling, -the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, `GET /v1/usage/live`, the realtime voice shapes, +the native search relay, the standalone Images POSTs, keyed file/stream transcription, `GET /v1/models`, `GET /v1/usage/live` (and its `OPTIONS` preflight), the context relays' `POST /v1/alpha/history/v2/*` and `/v1/alpha/notes/v2/*` endpoints (`contextEndpoint`; dispatched only with the context opt-in), the realtime voice shapes, and the Anthropic and OpenAI chat wires the host's own local clients speak — `POST /v1/messages`, `POST /v1/messages/count_tokens`, and `POST /v1/chat/completions`. It never serves `/api/*`, `/healthz`, `/readyz`, or GUI routes, so local management discovery has to use an authenticated From 35b4a77f585b6e2efd9cf5cb42756d7b5fdb179d Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Sat, 14 Nov 2026 01:59:11 -0500 Subject: [PATCH 11/18] fix(server): the loopback listener admits the live-meter preflight --- src/server/index.ts | 4 ++-- .../server/loopback-listener-admission.test.ts | 7 ++++--- .../loopback-listener-integration.test.ts | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/server/index.ts b/src/server/index.ts index 7350c366d34..2020493b2fb 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -413,8 +413,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe if (path === "/v1/audio/transcriptions") return req.method === "POST"; if (path === "/v1/audio/transcriptions/stream") return req.headers.get("upgrade")?.toLowerCase() === "websocket"; if (path === "/v1/alpha/search") return req.method === "POST"; - // Live meter (#8735): GET-only numbers from the local request log; Codex++ reads it here. - if (path === "/v1/usage/live") return req.method === "GET"; + // Live meter (#8735): numbers from the local request log; Codex++ reads it here (OPTIONS: its key-header preflight). + if (path === "/v1/usage/live") return req.method === "GET" || req.method === "OPTIONS"; if (contextEndpoint(path)) return req.method === "POST"; if (path === "/v1/images/generations" || path === "/v1/images/edits") { return req.method === "POST"; diff --git a/tests/server/loopback-listener-admission.test.ts b/tests/server/loopback-listener-admission.test.ts index a03e9c07f68..20ff6e38bd8 100644 --- a/tests/server/loopback-listener-admission.test.ts +++ b/tests/server/loopback-listener-admission.test.ts @@ -118,10 +118,11 @@ describe("local client inference wires on the loopback listener (#4236)", () => ); }); - test("the live meter is a GET-only read on the loopback listener", () => { + test("the live meter is a read (and its preflight) on the loopback listener", () => { // The Codex++ footer reads `http://127.0.0.1:/v1/usage/live`. On a hub whose public - // listener binds a tailnet address that is this socket, and the route 404ed here. - expect(source).toContain('if (path === "/v1/usage/live") return req.method === "GET";'); + // listener binds a tailnet address that is this socket, and the route 404ed here. A key + // header makes the renderer preflight first, so OPTIONS is admitted for this path too. + expect(source).toContain('if (path === "/v1/usage/live") return req.method === "GET" || req.method === "OPTIONS";'); }); test("no /api route joins the allowlist", () => { diff --git a/tests/server/loopback-listener-integration.test.ts b/tests/server/loopback-listener-integration.test.ts index a1f2d9f13a5..d1b4409cdf4 100644 --- a/tests/server/loopback-listener-integration.test.ts +++ b/tests/server/loopback-listener-integration.test.ts @@ -318,6 +318,23 @@ describe("unauthenticated loopback listener", () => { } }); + test("answers the Codex desktop renderer's live-meter preflight", async () => { + const loopbackPort = await freePort(); + saveConfig(baseConfig(loopbackPort)); + const server = await startLoopbackTestServer(loopbackPort); + try { + const pre = await fetch(`http://127.0.0.1:${loopbackPort}/v1/usage/live`, { + method: "OPTIONS", + headers: { origin: "app://-", "access-control-request-method": "GET", "access-control-request-headers": "x-opencodex-api-key" }, + }); + expect(pre.status).toBe(204); + expect(pre.headers.get("access-control-allow-origin")).toBe("app://-"); + expect(pre.headers.get("access-control-allow-methods")).toBe("GET, OPTIONS"); + } finally { + await server.stop(true); + } + }); + test("refuses connections on a non-loopback interface", async () => { const address = firstNonLoopbackIPv4(); if (!address) { From 2e2191d2625e4a6ac2d786a6aa41b184e4ef7a59 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Mon, 16 Nov 2026 23:37:37 -0500 Subject: [PATCH 12/18] docs(es): mirror the live routing section in the Spanish model routing guide --- .../content/docs/es/guides/model-routing.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs-site/src/content/docs/es/guides/model-routing.md b/docs-site/src/content/docs/es/guides/model-routing.md index e492d1a1717..179ab169e4a 100644 --- a/docs-site/src/content/docs/es/guides/model-routing.md +++ b/docs-site/src/content/docs/es/guides/model-routing.md @@ -78,6 +78,32 @@ El enrutamiento y la visibilidad del catálogo son controles separados: } ``` + + +## Ver el enrutamiento en vivo + +La pestaña **Models › Live routing** del panel (`#models/live`) muestra cómo se enrutó cada solicitud +y se actualiza cada pocos segundos mientras está abierta. Para la última solicitud, o la que elija en +la lista de abajo, verá: + +- **La ruta.** El cliente, luego OpenCodex, luego cada candidato: la cuenta o el destino del combo que + respondió, los que fallaron (con el estado HTTP y el motivo) y los que se omitieron antes de enviar. + Un grupo OAuth de varias cuentas muestra el estado de cada cuenta al terminar la solicitud: pausada, + pendiente de iniciar sesión, en enfriamiento, sin cuota o sin listar el modelo. Cuando el enrutador + registró por qué eligió esta ruta, ese motivo aparece debajo. +- **En qué se fue el tiempo.** El tiempo propio de OpenCodex, los intentos fallidos anteriores, la + espera del primer token y el streaming. Cada segmento se mide; DNS y TLS no se separan. +- **La ventana de contexto.** Tokens estimados para el prompt del sistema, las herramientas, las + skills, los archivos de memoria como `AGENTS.md` y `CLAUDE.md`, los archivos, los resultados de + herramientas y la conversación, en una barra con la parte del prompt de cada uno, lo llena que está + la ventana del modelo que respondió y la tasa de aciertos de la caché de prompts. Solo se registran + tamaños, nunca el texto del prompt, y se guardan en memoria con el registro de solicitudes. + +La lista de solicitudes agrupa por solicitud, sesión o clave API y muestra la cuenta, el modelo, el +esfuerzo, la duración, el tiempo hasta el primer token, los tokens, la tasa de aciertos de caché, los +tokens por segundo y el costo estimado. Los combos y las cuentas conservan sus propias páginas; la +pestaña enlaza a ellas. + ## Propinas From 1989f00c55dcc9be149d158544d9b2bfd99ddeac Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Mon, 16 Nov 2026 23:37:47 -0500 Subject: [PATCH 13/18] test(usage): name the context breakdown test so the usage- seed places it --- scripts/test-layout/layout-usage.json | 2 +- tests/fixtures/test-layout-expected.json | 2 +- ...ontext-breakdown.test.ts => usage-context-breakdown.test.ts} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename tests/usage/{context-breakdown.test.ts => usage-context-breakdown.test.ts} (100%) diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index 5e89621e913..b1d61ab8578 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -6,7 +6,7 @@ "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", + "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/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 8f3b5340036..4e4ed8c2501 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-context-breakdown.test.ts": "usage", "context-breakdown.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", "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/usage-context-breakdown.test.ts similarity index 100% rename from tests/usage/context-breakdown.test.ts rename to tests/usage/usage-context-breakdown.test.ts From 36cda3f701dfaed8a73ee3e6b694a34ba761364c Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Mon, 16 Nov 2026 23:37:57 -0500 Subject: [PATCH 14/18] fix(gui): native meter for the cache hit rate; combos link built from modelsTabHash --- gui/src/pages/route-live/ContextCard.tsx | 7 +------ gui/src/pages/route-live/RouteLive.tsx | 3 ++- gui/src/pages/route-live/route-live.css | 10 ++++++++-- gui/tests/route-live-render.test.tsx | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/gui/src/pages/route-live/ContextCard.tsx b/gui/src/pages/route-live/ContextCard.tsx index c3bb0df9313..22aeffcbfc0 100644 --- a/gui/src/pages/route-live/ContextCard.tsx +++ b/gui/src/pages/route-live/ContextCard.tsx @@ -43,12 +43,7 @@ function CacheMeter({ row }: { row: RouteRow }) {
    {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), diff --git a/gui/src/pages/route-live/RouteLive.tsx b/gui/src/pages/route-live/RouteLive.tsx index 86b2b9ceeb9..b44ae8ee388 100644 --- a/gui/src/pages/route-live/RouteLive.tsx +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -18,6 +18,7 @@ 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 { modelsTabHash } from "../models-tab"; import "./route-live.css"; function OutcomeLine({ outcome, row }: { outcome: FlowOutcome; row: RouteRow }) { @@ -104,7 +105,7 @@ function Selected({ row, flow, pinned, onBack }: { row: RouteRow; flow: RouteFlo {flow.outcome.kind !== "local" && } - {row.routeDecision?.routeKind === "combo" &&

    {t("routeLive.linkCombos")}

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

    {t("routeLive.linkCombos")}

    } ); } diff --git a/gui/src/pages/route-live/route-live.css b/gui/src/pages/route-live/route-live.css index 374ebe96dd1..06fcb6908a2 100644 --- a/gui/src/pages/route-live/route-live.css +++ b/gui/src/pages/route-live/route-live.css @@ -95,8 +95,14 @@ } .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: var(--radius-2xs); overflow: hidden; background: var(--raised); border: 1px solid var(--border); } -.rl-ctx-meter > i { display: block; height: 100%; background: var(--green); } +/* A native : each engine's pseudo-elements sit in their own rule, since one unknown + selector drops the whole rule. */ +.rl-ctx-meter { appearance: none; display: block; flex: 0 1 160px; min-width: 80px; height: 6px; margin: 0; border-radius: var(--radius-2xs); overflow: hidden; background: var(--raised); border: 1px solid var(--border); } +.rl-ctx-meter::-webkit-meter-bar { height: 100%; border: 0; border-radius: 0; background: var(--raised); } +.rl-ctx-meter::-webkit-meter-optimum-value { background: var(--green); } +.rl-ctx-meter::-webkit-meter-suboptimum-value { background: var(--green); } +.rl-ctx-meter::-webkit-meter-even-less-good-value { background: var(--green); } +.rl-ctx-meter::-moz-meter-bar { background: var(--green); } .rl-ctx-kind--system { --k: var(--rl-ctx-system); } .rl-ctx-kind--tools { --k: var(--blue); } .rl-ctx-kind--skills { --k: var(--muted); } diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 29a0a27801f..48c891a9cfd 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -124,7 +124,7 @@ test("context card shows the used/window header, one bar segment per filled part expect(doc.querySelector(".rl-ctx-legend li .rl-num")?.textContent).toContain("10%"); 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"); + expect(doc.querySelector("meter.rl-ctx-meter")?.getAttribute("value")).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", () => { From 902e69bc293a52e8f8646e60fe16ae0926c7e076 Mon Sep 17 00:00:00 2001 From: "Andrew (agent)" Date: Thu, 19 Nov 2026 01:21:32 -0500 Subject: [PATCH 15/18] fix(live-routing): gate context breakdown on live observation and drop privacyRedactionMs --- .../content/docs/es/guides/model-routing.md | 5 +- .../src/content/docs/guides/model-routing.md | 4 +- gui/src/i18n/route-live-copy.ts | 1 - gui/src/pages/route-live/TimeBar.tsx | 3 +- gui/src/pages/route-live/route-live.css | 1 - gui/src/pages/route-live/route-rows.ts | 1 - gui/src/pages/route-live/time-parts.ts | 11 ++- gui/src/pages/route-live/use-route-live.ts | 2 +- gui/tests/route-live-render.test.tsx | 6 +- gui/tests/route-live-time.test.ts | 17 ++--- src/server/chat-completions.ts | 4 +- src/server/claude-messages.ts | 4 +- src/server/context-breakdown.ts | 21 ++++++ src/server/index/serve-options.ts | 12 +--- src/server/live-meter-handler.ts | 5 +- src/server/management/logs-usage-routes.ts | 2 + src/server/request-log-route-live.ts | 11 +-- src/server/responses/request-prepare.ts | 4 +- tests/server/live-meter-handler.test.ts | 71 +++++++++++++++++++ .../request-log-context-breakdown.test.ts | 2 +- .../request-log-route-live-timing.test.ts | 7 -- tests/usage/usage-context-breakdown.test.ts | 31 +++++++- 22 files changed, 156 insertions(+), 69 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/model-routing.md b/docs-site/src/content/docs/es/guides/model-routing.md index 179ab169e4a..e00175602d5 100644 --- a/docs-site/src/content/docs/es/guides/model-routing.md +++ b/docs-site/src/content/docs/es/guides/model-routing.md @@ -96,8 +96,9 @@ la lista de abajo, verá: - **La ventana de contexto.** Tokens estimados para el prompt del sistema, las herramientas, las skills, los archivos de memoria como `AGENTS.md` y `CLAUDE.md`, los archivos, los resultados de herramientas y la conversación, en una barra con la parte del prompt de cada uno, lo llena que está - la ventana del modelo que respondió y la tasa de aciertos de la caché de prompts. Solo se registran - tamaños, nunca el texto del prompt, y se guardan en memoria con el registro de solicitudes. + la ventana del modelo que respondió y la tasa de aciertos de la caché de prompts. El desglose del + contexto se mide solo mientras la pestaña o `GET /v1/usage/live` se haya leído recientemente; solo + se registran tamaños, nunca el texto del prompt, y se guardan en memoria con el registro de solicitudes. La lista de solicitudes agrupa por solicitud, sesión o clave API y muestra la cuenta, el modelo, el esfuerzo, la duración, el tiempo hasta el primer token, los tokens, la tasa de aciertos de caché, los diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index 849aed0dc46..9a799fd0b25 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -168,8 +168,8 @@ the list below it, you see: - **The context window.** Estimated tokens for the system prompt, tools, skills, memory files such as `AGENTS.md` and `CLAUDE.md`, files, tool results and the conversation, as one bar with each part's share of the prompt, how full the serving model's window is, and the prompt-cache hit - rate. Only sizes are recorded, - never prompt text, and they live in memory with the request log. + rate. Context breakdowns are measured only while the tab or `GET /v1/usage/live` has been read + recently; 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. diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index 4cdc628d88f..2488330def0 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -93,7 +93,6 @@ 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."], 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"], diff --git a/gui/src/pages/route-live/TimeBar.tsx b/gui/src/pages/route-live/TimeBar.tsx index c00605f5f49..d43ca88cd4b 100644 --- a/gui/src/pages/route-live/TimeBar.tsx +++ b/gui/src/pages/route-live/TimeBar.tsx @@ -10,11 +10,10 @@ import { timeParts, type TimePart, type TimePartKind, type TimeRow } from "./tim type Side = "ocx" | "earlier" | "upstream"; const PART_SIDE: Record = { - privacy: "ocx", internal: "ocx", earlier: "earlier", upstreamWait: "upstream", streaming: "upstream", reading: "upstream", + 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", diff --git a/gui/src/pages/route-live/route-live.css b/gui/src/pages/route-live/route-live.css index 06fcb6908a2..ee53a8646cd 100644 --- a/gui/src/pages/route-live/route-live.css +++ b/gui/src/pages/route-live/route-live.css @@ -65,7 +65,6 @@ } .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; } diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts index 466f35c9994..51db0a27629 100644 --- a/gui/src/pages/route-live/route-rows.ts +++ b/gui/src/pages/route-live/route-rows.ts @@ -53,7 +53,6 @@ export interface RouteRow extends LogEntryBase { 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 index 504b8420b47..ce42a897275 100644 --- a/gui/src/pages/route-live/time-parts.ts +++ b/gui/src/pages/route-live/time-parts.ts @@ -5,8 +5,7 @@ * (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 + * internal time before the final attempt started, minus 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 @@ -14,14 +13,14 @@ */ import type { RouteRow } from "./route-rows"; -export type TimePartKind = "privacy" | "internal" | "earlier" | "upstreamWait" | "streaming" | "reading"; +export type TimePartKind = "internal" | "earlier" | "upstreamWait" | "streaming" | "reading"; export interface TimePart { kind: TimePartKind; ms: number; } -export type TimeRow = Pick; +export type TimeRow = Pick; export const MIN_PART_MS = 0.1; @@ -40,16 +39,14 @@ export function timeParts(row: TimeRow): TimePart[] | null { 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 internal = Math.max(0, sendMs - earlier); 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 diff --git a/gui/src/pages/route-live/use-route-live.ts b/gui/src/pages/route-live/use-route-live.ts index 27d99a333a7..15a70dc723c 100644 --- a/gui/src/pages/route-live/use-route-live.ts +++ b/gui/src/pages/route-live/use-route-live.ts @@ -10,7 +10,7 @@ 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 }); + const res = await fetch(`${apiBase}/api/logs?limit=${ROUTE_LIVE_ROW_CAP}&live=1`, { signal }); if (!res.ok) throw new Error(String(res.status)); return parseRouteRows(await res.json()); }, diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 48c891a9cfd..267a6efabb1 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -87,14 +87,14 @@ test("request list groups by session, shows dashes for unknown metrics, and mark 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, + ...failover, upstreamSendMs: 1010, 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); + ["OpenCodex 内部", "之前的尝试", "等上游第一个字", "流式输出"]); + expect(doc.querySelectorAll(".rl-time-seg").length).toBe(4); const bare = render(); expect(bare.querySelector(".rl-time-bar")).toBeNull(); expect(bare.querySelector("p")?.textContent).toContain("没有记录时间分布"); diff --git a/gui/tests/route-live-time.test.ts b/gui/tests/route-live-time.test.ts index bc95ddb0f6f..ed65595c01a 100644 --- a/gui/tests/route-live-time.test.ts +++ b/gui/tests/route-live-time.test.ts @@ -13,22 +13,13 @@ describe("timeParts", () => { ]); }); - 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, + durationMs: 3000, upstreamSendMs: 1010, 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: "internal", ms: 10 }, { kind: "earlier", ms: 1000 }, { kind: "upstreamWait", ms: 700 }, { kind: "streaming", ms: 1290 }, ]); }); @@ -57,9 +48,9 @@ describe("timeParts", () => { 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 })], + durationMs: 1000, upstreamSendMs: 0.05, attempts: [attempt({ durationMs: 999.95, firstOutputMs: 2000 })], })); - expect(parts).toEqual([{ kind: "privacy", ms: 3 }, { kind: "upstreamWait", ms: 2000 }]); + expect(parts).toEqual([{ kind: "upstreamWait", ms: 2000 }]); }); test("no usable timing returns null", () => { diff --git a/src/server/chat-completions.ts b/src/server/chat-completions.ts index 35020d5ad68..93d3fc333f4 100644 --- a/src/server/chat-completions.ts +++ b/src/server/chat-completions.ts @@ -62,7 +62,7 @@ import { linkRequestSessionLane, } from "./request-log-conversation"; import type { OcxConfig } from "../types"; -import { observeContextBreakdown } from "./context-breakdown"; +import { isLiveRoutingRecentlyObserved, observeContextBreakdown } from "./context-breakdown"; import { DecompressedBodyTooLargeError, UnsupportedContentEncodingError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; import { addFinalRequestLog, @@ -210,7 +210,7 @@ async function handleChatCompletionsWithBudget( try { const rawBody = await readChatBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes)); assertChatCompletionsRoutingBody(rawBody); - observeContextBreakdown(logCtx, rawBody, "chat"); + if (isLiveRoutingRecentlyObserved()) 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 22dc83f66e8..6c61cb7a187 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -86,7 +86,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 { isLiveRoutingRecentlyObserved, observeContextBreakdown } from "./context-breakdown"; import { addFinalRequestLog, httpStatusForRequestLogTerminal, recordFirstOutput, type RequestLogContext } from "./request-log"; import { createFinalRequestLog } from "./inference/final-log"; import { @@ -697,7 +697,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"); + if (isLiveRoutingRecentlyObserved()) 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.ts b/src/server/context-breakdown.ts index 64876d0be99..0f04eb48cfb 100644 --- a/src/server/context-breakdown.ts +++ b/src/server/context-breakdown.ts @@ -26,6 +26,27 @@ export type { ContextBreakdownV1 } from "./context-breakdown-classify"; export type ContextBreakdownWire = "responses" | "messages" | "chat"; +/** Window during which a Live routing tab or `/v1/usage/live` read keeps breakdown scanning active. */ +export const LIVE_ROUTING_OBSERVED_TTL_MS = 120_000; + +let lastLiveRoutingObservedAt: number | null = null; + +/** Record that the Live routing tab or `GET /v1/usage/live` was read. */ +export function markLiveRoutingObserved(now = Date.now()): void { + if (Number.isFinite(now)) lastLiveRoutingObservedAt = now; +} + +/** True while Live routing or `GET /v1/usage/live` has been read within the active window. */ +export function isLiveRoutingRecentlyObserved(now = Date.now()): boolean { + return lastLiveRoutingObservedAt !== null + && now >= lastLiveRoutingObservedAt + && now - lastLiveRoutingObservedAt <= LIVE_ROUTING_OBSERVED_TTL_MS; +} + +export function resetLiveRoutingObservedForTests(): void { + lastLiveRoutingObservedAt = null; +} + export function measureContextBreakdown(body: unknown, wire: ContextBreakdownWire): ContextBreakdownV1 | undefined { try { if (!isRec(body)) return undefined; diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index b6630179744..9b88f1590b5 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -417,10 +417,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { if (readyzPath !== undefined) { return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy); } - if (url.pathname === "/v1/usage/live") { - const preflight = (await import("../live-meter-handler")).liveMeterPreflight(req, policy); - if (preflight) return preflight; - } + if (url.pathname === "/v1/usage/live") { const r = (await import("../live-meter-handler")).liveMeterPreflight(req, policy); if (r) return r; } // The exact Ollama-compatible paths are data-plane routes and take data-plane CORS. const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname); // Gemini routes are data-plane paths too (never under /api/), so they take the data-plane branch. @@ -840,12 +837,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { ); } - if (url.pathname === "/v1/usage/live" && req.method === "GET") { - // Same admission as the model routes; the module adds only the Codex desktop origin for this read. - const { handleLiveMeterData } = await import("../live-meter-handler"); - return handleLiveMeterData(req, policy); - } - + if (url.pathname === "/v1/usage/live" && req.method === "GET") return (await import("../live-meter-handler")).handleLiveMeterData(req, policy); if (url.pathname === "/v1/usage" && req.method === "GET") { const { handleHubUsage } = await import("../hub-usage"); return handleHubUsage(req, config, policy); diff --git a/src/server/live-meter-handler.ts b/src/server/live-meter-handler.ts index d17018f9d81..d34bb9d0be9 100644 --- a/src/server/live-meter-handler.ts +++ b/src/server/live-meter-handler.ts @@ -14,6 +14,7 @@ import { type DataPlaneAdmission, type RequestPolicyView, } from "./auth-cors"; import { formatErrorResponse } from "../bridge/errors"; +import { markLiveRoutingObserved } from "./context-breakdown"; import { matchesLogConversationId } from "./request-log-conversation"; import { getRequestLogEntries, type RequestLogEntry } from "./request-log"; import { statSync } from "node:fs"; @@ -121,7 +122,9 @@ export async function handleLiveMeterData(req: Request, config: RequestPolicyVie ? isApiAuthRequired(config) || isLoopbackRequestHost(req.headers.get("Host")) : isAllowedRequestOrigin(req, config); if (!originOk) return reply(formatErrorResponse(403, "origin_rejected", "cross-origin data-plane request blocked")); - return reply(liveMeterResponse(new URL(req.url).searchParams, deps, admission), appRenderer); + const response = liveMeterResponse(new URL(req.url).searchParams, deps, admission); + if (response.status === 200) markLiveRoutingObserved(); + return reply(response, appRenderer); } /** diff --git a/src/server/management/logs-usage-routes.ts b/src/server/management/logs-usage-routes.ts index a3aefdac65e..8823ea445f5 100644 --- a/src/server/management/logs-usage-routes.ts +++ b/src/server/management/logs-usage-routes.ts @@ -68,6 +68,7 @@ import { } from "../../lib/debug-settings"; import type { OcxClaudeCodeConfig, OcxConfig, OcxCustomModel, OcxProviderConfig } from "../../types"; import { drainAndShutdown } from "../lifecycle"; +import { markLiveRoutingObserved } from "../context-breakdown"; import { getRequestLogEntries, queryRequestLogs, type RequestLogEntry } from "../request-log"; import { decodeRequestLogCursor, selectRequestLogPoll } from "../request-log-cursor"; import { estimateComboCost, estimateRequestCost, normalizeCostTokens, tokensPerSecond } from "../../usage/cost"; @@ -131,6 +132,7 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise= start ? sendAt - start : undefined; - const redaction = logCtx.privacyRedactionMs; - return { - ...(upstreamSendMs !== undefined ? { upstreamSendMs } : {}), - ...(redaction !== undefined && Number.isFinite(redaction) && redaction >= 0 ? { privacyRedactionMs: redaction } : {}), - }; + return upstreamSendMs !== undefined ? { upstreamSendMs } : {}; } /** The client body's context-window breakdown, set once at the inbound entry (context-breakdown.ts). */ diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index cb26655dbec..ff738e74f19 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -91,7 +91,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 { isLiveRoutingRecentlyObserved, observeContextBreakdown } from "../context-breakdown"; import { beginRequestAttempt, finishRequestAttempt, markLocalRequestLogRefusal, noteAttemptSend, noteCodexSelectionAffinity, observeCacheDiagnosticInbound, rebindCacheDiagnosticBody, requestLogSpeedLabel, readConfiguredCodexServiceTier, usageFromResponsesPayload } from "../request-log"; import type { PersistedUsageAttempt } from "../../usage/log"; import type { RouteResult } from "../../router"; @@ -281,7 +281,7 @@ export async function prepareResponsesRequest( : options.promptCacheKeyIsSharedCohort === false ? "metadata-derived" : "caller", contextPrincipalIdOf(options.admission), ); - observeContextBreakdown(logCtx, body, "responses"); + if (isLiveRoutingRecentlyObserved()) observeContextBreakdown(logCtx, body, "responses"); if (!concreteSelection && !options.compactionRoutingOverride && inboundWire === "responses") { options.compactionRoutingOverride = applyCompactionRoutingOverride(body, req.headers, config, { endpoint: "responses", diff --git a/tests/server/live-meter-handler.test.ts b/tests/server/live-meter-handler.test.ts index a2111d0606e..4a7e1204c63 100644 --- a/tests/server/live-meter-handler.test.ts +++ b/tests/server/live-meter-handler.test.ts @@ -3,6 +3,7 @@ import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { buildLiveMeter, catalogContextLimit, handleLiveMeterData, liveMeterPreflight, resetLiveMeterCatalogCacheForTests } from "../../src/server/live-meter-handler"; +import { isLiveRoutingRecentlyObserved, resetLiveRoutingObservedForTests } from "../../src/server/context-breakdown"; import { isAllowedRequestOrigin } from "../../src/server/auth-cors"; import { normalizeLogConversationId } from "../../src/server/request-log-conversation"; import { clearRequestLogsForTests, getRequestLogEntries, type RequestLogEntry } from "../../src/server/request-log"; @@ -103,6 +104,7 @@ describe("catalog context limit", () => { }); describe("data-plane admission and CORS", () => { + afterEach(() => resetLiveRoutingObservedForTests()); const key = { id: "k", name: "k", key: "ocx_data_livemeterkey", createdAt: "2026-01-01" }; const loopback = { hostname: "127.0.0.1", corsAllowOrigins: [], apiKeys: [] }; const remote = { hostname: "0.0.0.0", corsAllowOrigins: [], apiKeys: [key] }; @@ -168,6 +170,19 @@ describe("data-plane admission and CORS", () => { expect(pre({ host: "127.0.0.1:1" })).toBeNull(); expect(pre({ origin: "app://-", host: "evil.test" })).toBeNull(); }); + + test("only an admitted 200 live-meter read marks live routing as observed", async () => { + resetLiveRoutingObservedForTests(); + expect(isLiveRoutingRecentlyObserved()).toBe(false); + expect((await handleLiveMeterData(get("http://10.0.0.2:1/v1/usage/live", { origin: "app://-" }), remote, deps)).status).toBe(401); + expect(isLiveRoutingRecentlyObserved()).toBe(false); + expect((await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live", { origin: "https://evil.test", host: "127.0.0.1:1" }), loopback, deps)).status).toBe(403); + expect(isLiveRoutingRecentlyObserved()).toBe(false); + expect((await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live?client=bogus", { origin: "app://-", host: "127.0.0.1:1" }), loopback, deps)).status).toBe(400); + expect(isLiveRoutingRecentlyObserved()).toBe(false); + expect((await handleLiveMeterData(get("http://127.0.0.1:1/v1/usage/live", { origin: "app://-", host: "127.0.0.1:1" }), loopback, deps)).status).toBe(200); + expect(isLiveRoutingRecentlyObserved()).toBe(true); + }); }); describe("running server", () => { @@ -185,11 +200,13 @@ describe("running server", () => { delete process.env.OPENCODEX_API_AUTH_TOKEN; saveConfig({ ...getDefaultConfig(), port: 0, hostname: "127.0.0.1", providers: {} }); clearRequestLogsForTests(); + resetLiveRoutingObservedForTests(); }); afterEach(async () => { await server?.stop(true); server = undefined; clearRequestLogsForTests(); + resetLiveRoutingObservedForTests(); for (const k of envKeys) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } codex.restore(); await removeTreeAfterBackgroundWork(home); @@ -218,4 +235,58 @@ describe("running server", () => { const postRes = await fetch(new URL("/v1/usage/live", base), { method: "POST", headers: app }); expect(postRes.status).not.toBe(200); }, 60000); + + test("context breakdown scanning stays idle until /v1/usage/live or Live routing /api/logs?live=1 is read", async () => { + process.env.OPENCODEX_ADMIN_AUTH_TOKEN = "admin-secret"; + const admin = { "x-opencodex-api-key": "admin-secret" }; + server = startServer(0); + const base = server.url; + const json = { "content-type": "application/json" }; + const sendAllThreeWires = async () => { + await fetch(new URL("/v1/responses", base), { + method: "POST", + headers: json, + body: JSON.stringify({ model: "missing-model", input: "hello world from responses" }), + }); + await fetch(new URL("/v1/chat/completions", base), { + method: "POST", + headers: json, + body: JSON.stringify({ model: "missing-model", messages: [{ role: "user", content: "hello world from chat" }] }), + }); + await fetch(new URL("/v1/messages", base), { + method: "POST", + headers: json, + body: JSON.stringify({ model: "missing-model", max_tokens: 16, messages: [{ role: "user", content: "hello world from messages" }] }), + }); + }; + + // Idle at startup: none of the three inbound wires scan prompt bodies. + await sendAllThreeWires(); + const idleRows = getRequestLogEntries(); + expect(idleRows.length).toBeGreaterThanOrEqual(3); + for (const entry of idleRows) expect(entry.contextBreakdown).toBeUndefined(); + + // Plain /api/logs reads (Home, Logs, CLI) do not activate scanning. + expect((await fetch(new URL("/api/logs?limit=5", base), { headers: admin })).status).toBe(200); + expect(isLiveRoutingRecentlyObserved()).toBe(false); + + // Reading GET /v1/usage/live activates context-breakdown scanning for subsequent turns. + expect((await fetch(new URL("/v1/usage/live", base), { headers: { origin: "app://-" } })).status).toBe(200); + expect(isLiveRoutingRecentlyObserved()).toBe(true); + clearRequestLogsForTests(); + await sendAllThreeWires(); + const liveMeterRows = getRequestLogEntries(); + expect(liveMeterRows.length).toBeGreaterThanOrEqual(3); + expect(liveMeterRows.filter(entry => entry.contextBreakdown !== undefined).length).toBe(3); + + // Polling GET /api/logs?live=1 from the Live routing tab also activates scanning. + resetLiveRoutingObservedForTests(); + clearRequestLogsForTests(); + expect(isLiveRoutingRecentlyObserved()).toBe(false); + expect((await fetch(new URL("/api/logs?limit=5&live=1", base), { headers: admin })).status).toBe(200); + expect(isLiveRoutingRecentlyObserved()).toBe(true); + await sendAllThreeWires(); + const liveTabRows = getRequestLogEntries(); + expect(liveTabRows.filter(entry => entry.contextBreakdown !== undefined).length).toBe(3); + }, 60000); }); diff --git a/tests/usage/request-log-context-breakdown.test.ts b/tests/usage/request-log-context-breakdown.test.ts index 94ff8c82586..63af661f984 100644 --- a/tests/usage/request-log-context-breakdown.test.ts +++ b/tests/usage/request-log-context-breakdown.test.ts @@ -21,7 +21,7 @@ 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); + expect(row.contextWindow).toBe(850_000); }); test("a hosted model the adapter does not size takes the bundled vendor window", () => { diff --git a/tests/usage/request-log-route-live-timing.test.ts b/tests/usage/request-log-route-live-timing.test.ts index 4394d15c5f0..fc97ed81ad8 100644 --- a/tests/usage/request-log-route-live-timing.test.ts +++ b/tests/usage/request-log-route-live-timing.test.ts @@ -16,16 +16,9 @@ describe("live routing timing on the final request row", () => { 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(); }); }); diff --git a/tests/usage/usage-context-breakdown.test.ts b/tests/usage/usage-context-breakdown.test.ts index f7f6245c34c..dba5de2ec0b 100644 --- a/tests/usage/usage-context-breakdown.test.ts +++ b/tests/usage/usage-context-breakdown.test.ts @@ -1,5 +1,12 @@ -import { describe, expect, test } from "bun:test"; -import { measureContextBreakdown, observeContextBreakdown } from "../../src/server/context-breakdown"; +import { afterEach, describe, expect, test } from "bun:test"; +import { + isLiveRoutingRecentlyObserved, + LIVE_ROUTING_OBSERVED_TTL_MS, + markLiveRoutingObserved, + measureContextBreakdown, + observeContextBreakdown, + resetLiveRoutingObservedForTests, +} 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); @@ -372,3 +379,23 @@ describe("observeContextBreakdown", () => { expect(ctx.contextBreakdown?.parts.chat).toBe(10); }); }); + +describe("live routing observation gate", () => { + afterEach(() => resetLiveRoutingObservedForTests()); + + test("stays inactive until marked and expires after the observation TTL", () => { + resetLiveRoutingObservedForTests(); + expect(isLiveRoutingRecentlyObserved(10_000)).toBe(false); + markLiveRoutingObserved(Number.NaN); + expect(isLiveRoutingRecentlyObserved(10_000)).toBe(false); + + markLiveRoutingObserved(10_000); + expect(isLiveRoutingRecentlyObserved(9_999)).toBe(false); + expect(isLiveRoutingRecentlyObserved(10_000)).toBe(true); + expect(isLiveRoutingRecentlyObserved(10_000 + LIVE_ROUTING_OBSERVED_TTL_MS)).toBe(true); + expect(isLiveRoutingRecentlyObserved(10_000 + LIVE_ROUTING_OBSERVED_TTL_MS + 1)).toBe(false); + + resetLiveRoutingObservedForTests(); + expect(isLiveRoutingRecentlyObserved(10_000)).toBe(false); + }); +}); From 53cf68fb2cd849ec6ca009d09878c94331ba569b Mon Sep 17 00:00:00 2001 From: Andrew Wang Date: Sat, 21 Nov 2026 06:50:41 -0500 Subject: [PATCH 16/18] test(gui): count six Models tabs after merging upstream overall tab with live routing --- gui/tests/models-workspace-panels.test.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/tests/models-workspace-panels.test.tsx b/gui/tests/models-workspace-panels.test.tsx index 0b43c8547fd..5567da126f7 100644 --- a/gui/tests/models-workspace-panels.test.tsx +++ b/gui/tests/models-workspace-panels.test.tsx @@ -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(5); + expect(tabs(container)).toHaveLength(6); expect(panel(container, "catalog")).toBeTruthy(); releaseCatalog(); await act(async () => { await Promise.resolve(); }); - expect(tabs(container)).toHaveLength(5); + expect(tabs(container)).toHaveLength(6); } 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(5); + expect(tabs(container)).toHaveLength(6); // "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(5); + expect(tabs(container)).toHaveLength(6); await act(async () => { (container.querySelector("#models-tab-routing") as HTMLButtonElement).click(); }); From 3ad37a81caf05cabde9c076592e172a37b6a8209 Mon Sep 17 00:00:00 2001 From: Andrew Wang Date: Wed, 25 Nov 2026 08:58:40 +0000 Subject: [PATCH 17/18] fix: address live routing review feedback --- .../content/docs/es/guides/model-routing.md | 8 +- .../docs/es/reference/management-api.md | 6 +- .../src/content/docs/guides/model-routing.md | 6 +- .../content/docs/reference/management-api.md | 6 +- .../docs/zh-cn/reference/management-api.md | 6 +- .../docs/zh-tw/reference/management-api.md | 6 +- gui/src/i18n/es.ts | 2 + gui/src/i18n/route-live-copy.ts | 233 +++++++++--------- gui/src/pages/route-live/ContextCard.tsx | 2 +- gui/src/pages/route-live/RouteLive.tsx | 11 +- gui/src/pages/route-live/route-rows.ts | 2 +- gui/tests/route-live-model.test.ts | 9 +- gui/tests/route-live-render.test.tsx | 56 ++++- src/server/context-breakdown-classify.ts | 31 ++- src/server/context-breakdown.ts | 6 +- src/server/responses/request-prepare.ts | 4 +- src/usage/live-meter.ts | 13 +- structure/usage-client-attribution.md | 8 +- tests/usage/live-meter.test.ts | 24 +- tests/usage/usage-context-breakdown.test.ts | 26 ++ 20 files changed, 290 insertions(+), 175 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/model-routing.md b/docs-site/src/content/docs/es/guides/model-routing.md index e00175602d5..724b9e44e98 100644 --- a/docs-site/src/content/docs/es/guides/model-routing.md +++ b/docs-site/src/content/docs/es/guides/model-routing.md @@ -96,9 +96,11 @@ la lista de abajo, verá: - **La ventana de contexto.** Tokens estimados para el prompt del sistema, las herramientas, las skills, los archivos de memoria como `AGENTS.md` y `CLAUDE.md`, los archivos, los resultados de herramientas y la conversación, en una barra con la parte del prompt de cada uno, lo llena que está - la ventana del modelo que respondió y la tasa de aciertos de la caché de prompts. El desglose del - contexto se mide solo mientras la pestaña o `GET /v1/usage/live` se haya leído recientemente; solo - se registran tamaños, nunca el texto del prompt, y se guardan en memoria con el registro de solicitudes. + la ventana del modelo que respondió y la tasa de aciertos de la caché de prompts. Si el proveedor + conserva los turnos anteriores, se muestra el desglose visible, sin porcentaje de ocupación ni + indicador de estado de la ventana. El desglose del contexto solo se mide si se ha consultado + recientemente la pestaña o `GET /v1/usage/live`; solo se guardan los tamaños, nunca el texto del + prompt, en memoria junto con el registro de solicitudes. La lista de solicitudes agrupa por solicitud, sesión o clave API y muestra la cuenta, el modelo, el esfuerzo, la duración, el tiempo hasta el primer token, los tokens, la tasa de aciertos de caché, los diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index b04720796c3..f3cc3d519d8 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -461,9 +461,9 @@ Un valor es `null` (se muestra como `--`) en lugar de una estimación cuando no | Valor | `null` cuando | | --- | --- | -| `speed` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente; la solicitud se reintentó en más de un intento (`multiple_attempts`), cuya ventana abarcaría la pausa entre ellos. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. | -| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada, o la lectura de caché no se observó: solo existe en el cable o su procedencia es desconocida (`cache.reason` es `cache_unobserved`). | -| `context.percent` | El uso falta o es estimado, o la ventana de contexto del modelo no está en el catálogo persistido de Codex (`context.reason` es `limit_unknown`). | +| `speed.value` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente; la solicitud se reintentó en más de un intento (`multiple_attempts`), cuya ventana abarcaría la pausa entre ellos. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. | +| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada, o la lectura de caché no se informó, solo existe en el protocolo o su procedencia es desconocida (`cache.reason` es `cache_unobserved`). | +| `context.percent` | El uso falta o es estimado, la ventana de contexto del modelo no está en el catálogo persistido de Codex (`context.reason` es `limit_unknown`), o la solicitud tuvo más de un intento (`context.reason` es `multiple_attempts`). | diff --git a/docs-site/src/content/docs/guides/model-routing.md b/docs-site/src/content/docs/guides/model-routing.md index def074a63f6..f32ce16a9e6 100644 --- a/docs-site/src/content/docs/guides/model-routing.md +++ b/docs-site/src/content/docs/guides/model-routing.md @@ -173,8 +173,10 @@ the list below it, you see: - **The context window.** Estimated tokens for the system prompt, tools, skills, memory files such as `AGENTS.md` and `CLAUDE.md`, files, tool results and the conversation, as one bar with each part's share of the prompt, how full the serving model's window is, and the prompt-cache hit - rate. Context breakdowns are measured only while the tab or `GET /v1/usage/live` has been read - recently; only sizes are recorded, never prompt text, and they live in memory with the request log. + rate. If the provider holds earlier turns, the tab shows the visible breakdown but no window + fill percentage or health label. Context breakdowns are measured only while the tab or + `GET /v1/usage/live` has been read recently; only sizes, never prompt text, are kept 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. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index d5a97003b7a..4a1f23788c0 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -722,9 +722,9 @@ A value is `null` (shown as `--`) instead of a guess when it cannot be measured: | Value | `null` when | | --- | --- | -| `speed` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent; the request was retried across more than one attempt (`multiple_attempts`), whose window would span the gap between them. Speed is output tokens over the generation window, never wall time. | -| `cache.percent` | Usage is missing or estimated, the input count is missing, or the cache read was not observed: wire-only or of unknown provenance (`cache.reason` is `cache_unobserved`). | -| `context.percent` | Usage is missing or estimated, or the model's context window is not in the persisted Codex catalog (`context.reason` is `limit_unknown`). | +| `speed.value` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent; the request was retried across more than one attempt (`multiple_attempts`), whose window would span the gap between them. Speed is output tokens over the generation window, never wall time. | +| `cache.percent` | Usage is missing or estimated, the input count is missing, or the cache read was absent, wire-only or of unknown provenance (`cache.reason` is `cache_unobserved`). | +| `context.percent` | Usage is missing or estimated, the model's context window is not in the persisted Codex catalog (`context.reason` is `limit_unknown`), or the request used more than one attempt (`context.reason` is `multiple_attempts`). | ### OAuth accounts, provider keys, and data-plane keys diff --git a/docs-site/src/content/docs/zh-cn/reference/management-api.md b/docs-site/src/content/docs/zh-cn/reference/management-api.md index 1a598c2730b..29b0ca8c947 100644 --- a/docs-site/src/content/docs/zh-cn/reference/management-api.md +++ b/docs-site/src/content/docs/zh-cn/reference/management-api.md @@ -237,9 +237,9 @@ Aside 配置档的变更在这种情况下仍会保存一件事:确认之后 | 值 | 为 `null` 的情况 | | --- | --- | -| `speed` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致;请求经过多次尝试(`multiple_attempts`),其窗口会包含尝试之间的间隔。速度是输出 token 除以生成窗口,而不是墙钟时间。 | -| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取并非实测:仅存在于线路层或来源未知(`cache.reason` 为 `cache_unobserved`)。 | -| `context.percent` | 用量缺失或为估算值,或该模型的上下文窗口不在已持久化的 Codex 目录中(`context.reason` 为 `limit_unknown`)。 | +| `speed.value` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致;请求经过多次尝试(`multiple_attempts`),其窗口会包含尝试之间的间隔。速度是输出 token 除以生成窗口,而不是墙钟时间。 | +| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取未报告、仅存在于线路层或来源未知(`cache.reason` 为 `cache_unobserved`)。 | +| `context.percent` | 用量缺失或为估算值、该模型的上下文窗口不在已持久化的 Codex 目录中(`context.reason` 为 `limit_unknown`),或请求经过多次尝试(`context.reason` 为 `multiple_attempts`)。 | ### OAuth 账户、provider 密钥和数据平面密钥 diff --git a/docs-site/src/content/docs/zh-tw/reference/management-api.md b/docs-site/src/content/docs/zh-tw/reference/management-api.md index 7ab8b07356b..7e5660349d2 100644 --- a/docs-site/src/content/docs/zh-tw/reference/management-api.md +++ b/docs-site/src/content/docs/zh-tw/reference/management-api.md @@ -240,9 +240,9 @@ Aside 設定檔的變更在這種情況下仍會儲存一件事:確認之後 | 值 | 為 `null` 的情況 | | --- | --- | -| `speed` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致;請求經過多次嘗試(`multiple_attempts`),其視窗會包含嘗試之間的間隔。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 | -| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取並非實測:僅存在於線路層或來源未知(`cache.reason` 為 `cache_unobserved`)。 | -| `context.percent` | 用量缺失或為估算值,或該模型的上下文視窗不在已持久化的 Codex 目錄中(`context.reason` 為 `limit_unknown`)。 | +| `speed.value` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致;請求經過多次嘗試(`multiple_attempts`),其視窗會包含嘗試之間的間隔。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 | +| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取未回報、僅存在於線路層或來源未知(`cache.reason` 為 `cache_unobserved`)。 | +| `context.percent` | 用量缺失或為估算值、該模型的上下文視窗不在已持久化的 Codex 目錄中(`context.reason` 為 `limit_unknown`),或請求經過多次嘗試(`context.reason` 為 `multiple_attempts`)。 | ### OAuth 帳號、供應商金鑰與 data-plane 金鑰 diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index 3d87942a15d..c6c86022dfa 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { routeLiveCopy } from "./route-live-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -145,6 +146,7 @@ export const es = { ...connectionsCopy("es"), ...modelsV2Copy("es"), ...modelsOverallCopy("es"), + ...routeLiveCopy("es"), ...accountsV2Copy("es"), ...subagentsV2Copy("es"), ...usageV2Copy("es"), diff --git a/gui/src/i18n/route-live-copy.ts b/gui/src/i18n/route-live-copy.ts index 2488330def0..b242986b131 100644 --- a/gui/src/i18n/route-live-copy.ts +++ b/gui/src/i18n/route-live-copy.ts @@ -3,124 +3,125 @@ * `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 locales = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"] as const; +type Locale = (typeof locales)[number]; +type CopyRow = { readonly [I in keyof T]: string }; +type Row = CopyRow; 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"], - routeWhy: ["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}"], - 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"], - poolHead: ["Pool {provider}: {total} accounts","풀 {provider}: 계정 {total}개","Pool {provider}: {total} Konten","Pool {provider} : {total} comptes","号池 {provider}:{total} 个账号","號池 {provider}:{total} 個帳號","Пул {provider}: {total} аккаунтов","プール {provider}:{total} アカウント","Havuz {provider}: {total} hesap","Nhóm {provider}: {total} tài khoản","Pool {provider}: {total} contas"], - poolAvailable: ["{n} available","사용 가능 {n}","{n} verfügbar","{n} disponibles","可用 {n}","可用 {n}","доступно {n}","利用可 {n}","{n} uygun","{n} sẵn sàng","{n} disponíveis"], - poolCooldown: ["{n} cooling","대기 중 {n}","{n} Abkühlung","{n} en pause temporaire","冷却 {n}","冷卻 {n}","на паузе после ошибок {n}","クールダウン {n}","{n} bekleme","{n} đang nghỉ","{n} em espera"], - poolPaused: ["{n} paused","일시중지 {n}","{n} pausiert","{n} suspendus","暂停 {n}","暫停 {n}","приостановлено {n}","一時停止 {n}","{n} duraklatıldı","{n} tạm dừng","{n} pausadas"], - poolReauth: ["{n} need sign-in","재로그인 필요 {n}","{n} brauchen Anmeldung","{n} à reconnecter","需重新登录 {n}","需重新登入 {n}","нужен вход {n}","要再ログイン {n}","{n} yeniden giriş gerek","{n} cần đăng nhập lại","{n} precisam entrar de novo"], - poolQuota: ["{n} out of quota","한도 소진 {n}","{n} Kontingent aufgebraucht","{n} quota épuisé","额度用尽 {n}","額度用盡 {n}","квота исчерпана {n}","クォータ切れ {n}","{n} kota doldu","{n} hết hạn mức","{n} sem cota"], - poolUnlisted: ["{n} without this model","이 모델 없음 {n}","{n} ohne dieses Modell","{n} sans ce modèle","不含此模型 {n}","不含此模型 {n}","без этой модели {n}","このモデルなし {n}","{n} bu model yok","{n} không có mô hình này","{n} sem este modelo"], - 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}","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"], - 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."], - colAccount: ["Account","계정","Konto","Compte","账号","帳號","Аккаунт","アカウント","Hesap","Tài khoản","Conta"], - 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","Logiciel client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente"], - 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"], - 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"], - 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."], - 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"], - 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."], - 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","Échanges","会话内容","對話內容","Диалог","会話","Konuşma","Hội thoại","Conversa"], - 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."], + tab: ["Live routing","실시간 라우팅","Live-Routing","Routage en direct","实时路由","即時路由","Маршрутизация вживую","ライブルーティング","Canlı yönlendirme","Định tuyến trực tiếp","Roteamento ao vivo","Enrutamiento en 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.","Consulta qué cuenta respondió a cada solicitud y por qué se omitieron las demás. Se actualiza cada pocos segundos mientras esta pestaña está abierta."], + 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.","No se pudieron cargar las solicitudes recientes."], + 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.","Aún no hay solicitudes. Envía una a través de OpenCodex para ver su ruta aquí."], + 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","Cómo se enrutó la última solicitud"], + 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","Cómo se enrutó la solicitud de las {time}"], + 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","Volver a la última solicitud"], + 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}","{who} · {model} respondió en {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","{count} intentos; {who} respondió al final"], + outcomeFailed: ["{status} · {reason}","{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)","{status} · {reason} (después de {count} intentos)"], + 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.","OpenCodex respondió directamente. No se envió nada a un proveedor."], + 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","Ruta de la solicitud seleccionada: cliente, OpenCodex y luego los 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.","No se registraron candidatos para esta solicitud."], + statusAnswered: ["Answered","응답함","Geantwortet","A répondu","已回答","已回答","Ответил","応答","Yanıtladı","Đã trả lời","Respondeu","Respondió"], + statusFailed: ["Failed","실패","Fehlgeschlagen","Échec","失败","失敗","Ошибка","失敗","Başarısız","Thất bại","Falhou","Falló"], + statusSkipped: ["Skipped","건너뜀","Übersprungen","Ignoré","已跳过","已跳過","Пропущен","スキップ","Atlandı","Bỏ qua","Ignorado","Omitido"], + statusIdle: ["Not needed","필요 없었음","Nicht nötig","Pas nécessaire","没用上","沒用上","Не понадобился","不要","Gerekmedi","Không cần","Não precisou","No fue necesario"], + routeWhy: ["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}","Por qué se eligió: {reason}"], + 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","Los grupos de enrutamiento se administran en Modelos › Combos"], + poolHead: ["Pool {provider}: {total} accounts","풀 {provider}: 계정 {total}개","Pool {provider}: {total} Konten","Pool {provider} : {total} comptes","号池 {provider}:{total} 个账号","號池 {provider}:{total} 個帳號","Пул {provider}: {total} аккаунтов","プール {provider}:{total} アカウント","Havuz {provider}: {total} hesap","Nhóm {provider}: {total} tài khoản","Pool {provider}: {total} contas","Grupo {provider}: {total} cuentas"], + poolAvailable: ["{n} available","사용 가능 {n}","{n} verfügbar","{n} disponibles","可用 {n}","可用 {n}","доступно {n}","利用可 {n}","{n} uygun","{n} sẵn sàng","{n} disponíveis","{n} disponibles"], + poolCooldown: ["{n} cooling","대기 중 {n}","{n} Abkühlung","{n} en pause temporaire","冷却 {n}","冷卻 {n}","на паузе после ошибок {n}","クールダウン {n}","{n} bekleme","{n} đang nghỉ","{n} em espera","{n} en espera"], + poolPaused: ["{n} paused","일시중지 {n}","{n} pausiert","{n} suspendus","暂停 {n}","暫停 {n}","приостановлено {n}","一時停止 {n}","{n} duraklatıldı","{n} tạm dừng","{n} pausadas","{n} en pausa"], + poolReauth: ["{n} need sign-in","재로그인 필요 {n}","{n} brauchen Anmeldung","{n} à reconnecter","需重新登录 {n}","需重新登入 {n}","нужен вход {n}","要再ログイン {n}","{n} yeniden giriş gerek","{n} cần đăng nhập lại","{n} precisam entrar de novo","{n} requieren iniciar sesión"], + poolQuota: ["{n} out of quota","한도 소진 {n}","{n} Kontingent aufgebraucht","{n} quota épuisé","额度用尽 {n}","額度用盡 {n}","квота исчерпана {n}","クォータ切れ {n}","{n} kota doldu","{n} hết hạn mức","{n} sem cota","{n} sin cuota"], + poolUnlisted: ["{n} without this model","이 모델 없음 {n}","{n} ohne dieses Modell","{n} sans ce modèle","不含此模型 {n}","不含此模型 {n}","без этой модели {n}","このモデルなし {n}","{n} bu model yok","{n} không có mô hình này","{n} sem este modelo","{n} sin este modelo"], + linkAccounts: ["Open accounts","계정 열기","Konten öffnen","Ouvrir les comptes","打开账号页","開啟帳號頁","Открыть аккаунты","アカウントを開く","Hesapları aç","Mở tài khoản","Abrir contas","Abrir cuentas"], + modeLabel: ["Group requests","요청 묶기","Anfragen gruppieren","Grouper les requêtes","分组方式","分組方式","Группировка","グループ化","Gruplama","Nhóm yêu cầu","Agrupar requisições","Agrupar solicitudes"], + modeRequest: ["By request","요청별","Nach Anfrage","Par requête","按请求","按請求","По запросам","リクエスト別","İsteğe göre","Theo yêu cầu","Por requisição","Por solicitud"], + modeSession: ["By session","세션별","Nach Sitzung","Par session","按会话","按工作階段","По сессиям","セッション別","Oturuma göre","Theo phiên","Por sessão","Por sesión"], + modeKey: ["By key","키별","Nach Schlüssel","Par clé","按密钥","按金鑰","По ключам","キー別","Anahtara göre","Theo khóa","Por chave","Por clave"], + 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","Sin ID de sesión"], + groupSession: ["Session {id}","세션 {id}","Sitzung {id}","Séance {id}","会话 {id}","工作階段 {id}","Сессия {id}","セッション {id}","Oturum {id}","Phiên {id}","Sessão {id}","Sesión {id}"], + groupKey: ["Key {id}","키 {id}","Schlüssel {id}","Clé {id}","密钥 {id}","金鑰 {id}","Ключ {id}","キー {id}","Anahtar {id}","Khóa {id}","Chave {id}","Clave {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)","Este equipo (loopback)"], + admEnvironment: ["Environment key","환경 변수 키","Umgebungsschlüssel","Clé d’environnement","环境变量密钥","環境變數金鑰","Ключ из окружения","環境変数のキー","Ortam anahtarı","Khóa môi trường","Chave de ambiente","Clave del entorno"], + admUnknown: ["Unknown key","알 수 없는 키","Unbekannter Schlüssel","Clé inconnue","未知密钥","未知金鑰","Неизвестный ключ","不明なキー","Bilinmeyen anahtar","Khóa không rõ","Chave desconhecida","Clave desconocida"], + groupCount: ["{count} requests","요청 {count}개","{count} Anfragen","{count} requêtes","{count} 个请求","{count} 個請求","Запросов: {count}","{count} 件","{count} istek","{count} yêu cầu","{count} requisições","{count} solicitudes"], + groupTokens: ["{value} tokens","토큰 {value}","{value} Tokens","{value} jetons","{value} tokens","{value} tokens","{value} токенов","{value} トークン","{value} token","{value} token","{value} tokens","Tokens: {value}"], + groupCache: ["{value} cache hit","캐시 적중 {value}","{value} Cache-Treffer","{value} de cache","缓存命中 {value}","快取命中 {value}","кэш {value}","キャッシュ {value}","Önbellek {value}","Cache {value}","Cache {value}","{value} de aciertos de caché"], + listLabel: ["Recent requests","최근 요청","Letzte Anfragen","Requêtes récentes","最近的请求","最近的請求","Недавние запросы","最近のリクエスト","Son istekler","Yêu cầu gần đây","Requisições recentes","Solicitudes recientes"], + 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.","Selecciona una solicitud para fijarla arriba. Pulsa Esc para volver a la última."], + colAccount: ["Account","계정","Konto","Compte","账号","帳號","Аккаунт","アカウント","Hesap","Tài khoản","Conta","Cuenta"], + colTtft: ["First token","첫 토큰","Erstes Token","Premier jeton","首字","首字","Первый токен","最初のトークン","İlk token","Token đầu","Primeiro token","Primer token"], + colCache: ["Cache hit","캐시 적중","Cache-Treffer","Cache","缓存命中","快取命中","Кэш","キャッシュ","Önbellek","Cache","Cache","Aciertos de caché"], + 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","era el siguiente destino del 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","obtuvo la mejor puntuación según la política de enrutamiento"], + 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","en espera tras varios errores"], + rDisabled: ["turned off","꺼져 있음","ausgeschaltet","désactivé","已关闭","已關閉","отключён","オフ","kapalı","đã tắt","desativado","desactivado"], + 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","otro destino tenía prioridad"], + rPaused: ["paused by you","사용자가 일시중지함","von dir pausiert","mis en pause par vous","已被你暂停","已被你暫停","приостановлен вами","一時停止中","duraklatıldı","bạn đã tạm dừng","pausada por você","lo pusiste en pausa"], + 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","requiere volver a iniciar sesión"], + rQuotaExhausted: ["quota used up","사용량 한도 소진","Kontingent aufgebraucht","quota épuisé","额度用尽","額度用盡","квота исчерпана","クォータ切れ","kota doldu","hết hạn mức","cota esgotada","cuota agotada"], + 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","el plan no incluye 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","límite de solicitudes alcanzado"], + 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","sin cuota o 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","requiere volver a iniciar sesión"], + 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","supera la ventana de contexto del modelo"], + fServer: ["provider error","제공자 오류","Anbieterfehler","erreur du fournisseur","服务商出错","服務商出錯","ошибка провайдера","プロバイダーのエラー","sağlayıcı hatası","lỗi nhà cung cấp","erro do provedor","error del proveedor"], + fOverloaded: ["provider overloaded","제공자 과부하","Anbieter überlastet","fournisseur surchargé","服务商繁忙","服務商繁忙","провайдер перегружен","プロバイダーが混雑","sağlayıcı aşırı yüklü","nhà cung cấp quá tải","provedor sobrecarregado","proveedor saturado"], + fCancelled: ["cancelled","취소됨","abgebrochen","annulé","已取消","已取消","отменено","キャンセル","iptal edildi","đã hủy","cancelado","cancelado"], + colClient: ["Client","클라이언트","Client","Logiciel client","客户端","用戶端","Клиент","クライアント","İstemci","Máy khách","Cliente","Cliente"], + 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","Clave 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","ningún destino cumplió los requisitos, así que se usó el primero"], + 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","se redirigió porque el modelo solicitado está bloqueado"], + 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","la conversación está en un ciclo de llamadas a herramientas, así que se mantuvo en el mismo 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","esta sesión conserva el destino con el que empezó"], + 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","el nombre del modelo indicaba este proveedor"], + 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","el nombre del modelo es un alias 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","el nombre del modelo coincide con una regla de enrutamiento"], + 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","es un modelo nativo y va directamente a su servicio"], + 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","no se indicó un proveedor, así que se usó el predeterminado"], + 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","aún no está 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","ya se probó para esta solicitud"], + 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","no admite algo que esta solicitud necesita, como herramientas o imágenes"], + 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","supera el límite de costo"], + 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","no hay una ruta disponible ahora"], + fPermission: ["access denied","접근 거부","Zugriff verweigert","accès refusé","没有权限","沒有權限","доступ запрещён","アクセス拒否","erişim reddedildi","bị từ chối truy cập","acesso negado","acceso denegado"], + 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","modelo no encontrado"], + fTimeout: ["timed out","시간 초과","Zeitüberschreitung","délai dépassé","超时","逾時","время ожидания истекло","タイムアウト","zaman aşımı","hết thời gian","tempo esgotado","tiempo de espera agotado"], + detailFailed: ["{status} · {reason}","{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","{count} intentos"], + 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.","Solo se muestran las primeras 16 cuentas."], + 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","En qué se fue el tiempo"], + timeInternal: ["OpenCodex internal","OpenCodex 내부","OpenCodex intern","Interne OpenCodex","OpenCodex 内部","OpenCodex 內部","Внутри OpenCodex","OpenCodex 内部処理","OpenCodex iç işlem","Nội bộ OpenCodex","Interno do OpenCodex","Tiempo interno de OpenCodex"], + timeEarlier: ["Earlier attempts","이전 시도","Frühere Versuche","Essais précédents","之前的尝试","之前的嘗試","Предыдущие попытки","それ以前の試行","Önceki denemeler","Các lần thử trước","Tentativas anteriores","Intentos 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","Espera del primer token"], + timeStreaming: ["Streaming","스트리밍 출력","Streaming-Ausgabe","Diffusion de la réponse","流式输出","串流輸出","Потоковая передача","ストリーミング出力","Akış çıktısı","Phát trực tuyến","Transmissão da resposta","Transmisión"], + 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","Espera de la respuesta del proveedor"], + 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.","No se registró el desglose de tiempo de esta solicitud."], + 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}","Ventana 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}","Ventana de contexto {used}"], + ctxFill: ["{pct} full","{pct} 사용","{pct} belegt","{pct} utilisé","已用 {pct}","已用 {pct}","занято {pct}","{pct} 使用","{pct} dolu","đã dùng {pct}","{pct} usado","{pct} ocupado"], + ctxHealthOk: ["Plenty of room","여유 충분","Reichlich Platz","Large marge","还很宽裕","還很寬裕","Места много","余裕あり","Bol yer var","Còn rộng","Bastante espaço","Queda mucho espacio"], + ctxHealthFilling: ["Filling up","곧 가득 참","Füllt sich","Bientôt plein","快满了","快滿了","Заполняется","もうすぐいっぱい","Doluyor","Sắp đầy","Enchendo","Se está llenando"], + 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","Cerca del límite"], + 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.","Se desconoce la ventana de contexto de este modelo."], + ctxEstimated: ["Estimated","추정","Geschätzt","Estimé","估算","估算","Оценка","推定","Tahmin","Ước tính","Estimado","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.","Los tamaños se estiman a partir de la solicitud y no se ajustan al recuento de tokens del proveedor."], + 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.","El proveedor conserva los turnos anteriores y no se pueden ver aquí."], + 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","Desglose de la ventana de contexto"], + ctxSystem: ["System prompt","시스템 프롬프트","Systemprompt","Prompt système","系统提示词","系統提示詞","Системный промпт","システムプロンプト","Sistem istemi","Prompt hệ thống","Prompt do sistema","Prompt del sistema"], + ctxTools: ["Tools","도구","Tools","Outils","工具","工具","Инструменты","ツール","Araçlar","Công cụ","Ferramentas","Herramientas"], + ctxSkills: ["Skills","스킬","Skills","Compétences","技能","技能","Навыки","スキル","Beceriler","Kỹ năng","Skills","Habilidades"], + 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","Memoria y AGENTS.md"], + ctxFiles: ["Files","파일","Dateien","Fichiers","文件","檔案","Файлы","ファイル","Dosyalar","Tệp","Arquivos","Archivos"], + ctxResults: ["Tool results","도구 결과","Tool-Ergebnisse","Résultats d’outils","工具结果","工具結果","Результаты инструментов","ツール結果","Araç sonuçları","Kết quả công cụ","Resultados de ferramentas","Resultados de herramientas"], + ctxChat: ["Conversation","대화 내용","Unterhaltung","Échanges","会话内容","對話內容","Диалог","会話","Konuşma","Hội thoại","Conversa","Conversación"], + ctxCacheHead: ["Prompt cache","프롬프트 캐시","Prompt-Cache","Cache de prompt","提示词缓存","提示詞快取","Кэш промпта","プロンプトキャッシュ","İstem önbelleği","Bộ nhớ đệm prompt","Cache de prompt","Caché de prompts"], + ctxCacheHit: ["{pct} hit","적중 {pct}","{pct} Treffer","{pct} de réussite","命中 {pct}","命中 {pct}","попаданий {pct}","ヒット {pct}","{pct} isabet","trúng {pct}","{pct} de acerto","{pct} de aciertos"], + 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","{cached} en caché · {fresh} nuevos"], + 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.","El proveedor no informó el uso de la caché."], } 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 index 22aeffcbfc0..9046a1a2673 100644 --- a/gui/src/pages/route-live/ContextCard.tsx +++ b/gui/src/pages/route-live/ContextCard.tsx @@ -61,7 +61,7 @@ function ContextCardBody({ row }: { row: RouteRow }) { const shares = useMemo(() => calibrateContext(breakdown, contextInputTokens(row)), [breakdown, row]); const used = Math.max(shares.used, 1); - const fraction = windowTokens ? shares.used / windowTokens : undefined; + const fraction = windowTokens && !shares.held ? shares.used / windowTokens : undefined; const tokensText = (tokens: number) => formatCount(Math.round(tokens), localeTag); /** Share of the prompt, not of the window: the header already says how full the window is. */ const share = (tokens: number) => { diff --git a/gui/src/pages/route-live/RouteLive.tsx b/gui/src/pages/route-live/RouteLive.tsx index b44ae8ee388..f176fa97d93 100644 --- a/gui/src/pages/route-live/RouteLive.tsx +++ b/gui/src/pages/route-live/RouteLive.tsx @@ -127,14 +127,15 @@ export default function RouteLive({ apiBase, active }: { apiBase: string; active ? {t("routeLive.loadFailed")} : ; } - if (rows.length === 0 || !selected || !flow) { - return ; - } return (
    {resource.error != null && !resource.lastAttemptOk && {t("routeLive.loadFailed")}} - setPinnedKey(null)} /> - + {selected && flow ? ( + <> + setPinnedKey(null)} /> + + + ) : }
    ); } diff --git a/gui/src/pages/route-live/route-rows.ts b/gui/src/pages/route-live/route-rows.ts index 51db0a27629..d6d2115f59c 100644 --- a/gui/src/pages/route-live/route-rows.ts +++ b/gui/src/pages/route-live/route-rows.ts @@ -237,6 +237,6 @@ export function tokPerSecondOf(row: RouteRow): { value: number; estimated: boole export function costUsdOf(row: RouteRow): number | undefined { const cost = row.displayMetrics?.cost; if (cost?.kind !== "value") return undefined; - const total = cost.estimate.cost.total; + const total = cost.estimate?.cost?.total; return finite(total) && total >= 0 ? total : undefined; } diff --git a/gui/tests/route-live-model.test.ts b/gui/tests/route-live-model.test.ts index f96020d5c57..958e946b973 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, summarizePool } from "../src/pages/route-live/flow-model"; import { groupRows } from "../src/pages/route-live/request-groups"; -import { cacheHitPercent, parseRouteRows, readableAccountLabel, requestedOf, type RouteRow } from "../src/pages/route-live/route-rows"; +import { cacheHitPercent, costUsdOf, 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); @@ -69,6 +69,13 @@ describe("route rows and groups", () => { expect(rows[0]!.attempts).toHaveLength(1); }); + test("incomplete or invalid cost metrics are unavailable, but a measured zero is retained", () => { + const cost = (estimate?: unknown) => ({ ...base, displayMetrics: { cost: { kind: "value", estimate } } }); + const rows = parseRouteRows({ logs: [cost(), cost({}), cost({ cost: null }), + cost({ cost: { total: -1 } }), cost({ cost: { total: "1" } }), cost({ cost: { total: 0 } })] }); + expect(rows.map(costUsdOf)).toEqual([undefined, undefined, undefined, undefined, undefined, 0]); + }); + 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 }, diff --git a/gui/tests/route-live-render.test.tsx b/gui/tests/route-live-render.test.tsx index 267a6efabb1..fea8aa27a30 100644 --- a/gui/tests/route-live-render.test.tsx +++ b/gui/tests/route-live-render.test.tsx @@ -1,12 +1,13 @@ import { expect, test } from "bun:test"; import { renderToStaticMarkup } from "react-dom/server"; -import type { ReactNode } from "react"; +import { act, 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 { PoolLine, WhyLine } from "../src/pages/route-live/RouteLive"; +import { clearClientResourceStoresForTests, invalidateClientResource } from "../src/client-resource"; +import RouteLive, { PoolLine, WhyLine } from "../src/pages/route-live/RouteLive"; 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"; @@ -72,13 +73,15 @@ test("request list groups by session, shows dashes for unknown metrics, and mark {}} 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("—"); + const region = flat.querySelector(`section[aria-label="${translator("zh")("routeLive.listLabel")}"]`)!; + const rowButtons = [...region.querySelectorAll("li button[aria-pressed]")]; + expect(rowButtons).toHaveLength(2); + expect(rowButtons.find(button => button.textContent?.includes(failover.model))?.getAttribute("aria-pressed")).toBe("true"); + expect(rowButtons[0]!.textContent).toContain("—"); // headings are aria-hidden, so each value names itself for screen readers expect(flat.querySelector(".rl-bad")?.textContent).toBe(`${translator("zh")("logs.col.status")}: 500`); expect(flat.querySelector(".rl-bad .sr-only")?.textContent).toBe(`${translator("zh")("logs.col.status")}: `); - expect([...flat.querySelectorAll("button.rl-row")[0]!.querySelectorAll(".sr-only")].map(s => s.textContent)).toContain(`${translator("zh")("routeLive.colTtft")}: `); + expect([...rowButtons[0]!.querySelectorAll(".sr-only")].map(s => s.textContent)).toContain(`${translator("zh")("routeLive.colTtft")}: `); const grouped = list("session"); expect(grouped.querySelectorAll(".rl-group-head").length).toBe(2); expect(grouped.querySelector(".rl-group-head")?.getAttribute("aria-expanded")).toBe("true"); @@ -143,6 +146,47 @@ test("context card is hidden for a row without a breakdown", () => { expect(render().body.innerHTML).toBe(""); }); +test("held history keeps the estimated breakdown but not fill or health, even with a known window", () => { + const row = withContext(); + const doc = render(); + expect(doc.querySelector(".rl-ctx-legend")).not.toBeNull(); + expect(doc.querySelector(".rl-ctx-badge")).not.toBeNull(); + expect(doc.body.textContent).toContain(translator("zh")("routeLive.ctxHeld")); + expect(doc.querySelector(".rl-ctx-health")).toBeNull(); +}); + +test("a failed refresh remains visible after a successful empty response", async () => { + const win = new Window(); + const apiBase = "http://route-live.test"; + let failed = false; + const globals = { window: win, document: win.document, IS_REACT_ACT_ENVIRONMENT: true, + fetch: async () => failed ? new Response(null, { status: 503 }) : Response.json({ logs: [] }) }; + const previous = Object.fromEntries(Object.keys(globals).map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); + for (const [key, value] of Object.entries(globals)) Object.defineProperty(globalThis, key, { configurable: true, value }); + const { createRoot } = await import("react-dom/client"); + const root = createRoot(document.body); + const t = translator("en"); + try { + await act(async () => root.render( + , + )); + expect(document.body.textContent).toContain(t("routeLive.empty")); + expect(document.body.textContent).not.toContain(t("routeLive.loadFailed")); + failed = true; + await act(async () => invalidateClientResource(`route-live:rows:${apiBase}`)); + expect(document.body.textContent).toContain(t("routeLive.empty")); + expect(document.body.textContent).toContain(t("routeLive.loadFailed")); + } finally { + await act(async () => root.unmount()); + clearClientResourceStoresForTests(); + win.close(); + for (const [key, descriptor] of Object.entries(previous)) { + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + } +}); + 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/src/server/context-breakdown-classify.ts b/src/server/context-breakdown-classify.ts index a8a9cd91b04..8e82a6504a8 100644 --- a/src/server/context-breakdown-classify.ts +++ b/src/server/context-breakdown-classify.ts @@ -127,19 +127,26 @@ 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 = ["", "", "", ""]; +const NOTIFICATION_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 userTextCategory(text: string): "chat" | "memory" | "results" | "system" { + if (AGENTS_FOR.test(text)) return "memory"; + if (NOTIFICATION_LEADS.some(lead => text.startsWith(lead))) return "results"; + if (INJECTED_LEADS.some(lead => text.startsWith(lead))) return "system"; + return "chat"; +} + function trimLeftNewlines(s: string): string { let i = 0; while (i < s.length && s.charCodeAt(i) === 10) i++; @@ -156,9 +163,7 @@ export function userSays(text: string): boolean { for (const m of t.matchAll(MY_REQUEST)) end = m.index + m[0].length; if (end >= 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; + return t !== "" && userTextCategory(t) === "chat"; } // --- tool calls and what they read --- @@ -331,17 +336,9 @@ export class BreakdownAccumulator { t = t.slice(end).trim(); } if (t === "") 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(leading ? t : text)); + const category = userTextCategory(t); + if (category === "chat") this.chat(tokensOfText(leading ? t : text)); + else this[category] += tokensOfText(t); } private reminder(span: string): void { diff --git a/src/server/context-breakdown.ts b/src/server/context-breakdown.ts index 0f04eb48cfb..cc6e3967aa7 100644 --- a/src/server/context-breakdown.ts +++ b/src/server/context-breakdown.ts @@ -102,9 +102,11 @@ function readMessages(acc: BreakdownAccumulator, body: Rec): void { continue; } if (role === "user") { - // a message that answers tool calls goes on with the turn; one where the user says something begins one + // Tool answers continue the turn; direct user text or attachments start a new one. const answersCalls = blocks.some(x => x.type === "tool_result"); - if (!answersCalls && blocks.some(x => x.type === "text" && userSays(str(x.text)))) acc.newTurn(); + if (!answersCalls && blocks.some(x => + x.type === "image" || x.type === "document" || (x.type === "text" && userSays(str(x.text))) + )) acc.newTurn(); } for (const x of blocks) messagesBlock(acc, role, x); } diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index fbff52e3691..aa7ffaacec7 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -292,9 +292,7 @@ export async function prepareResponsesRequest( options.clientModelLabel ??= clientFacingModelLabel(originalSelector); redactHostedImageDisplayPaths(body); observeCacheDiagnosticInbound( - logCtx, - body, - req.headers, + logCtx, body, req.headers, options.promptCacheKeyIsSharedCohort === true ? "system-derived" : options.promptCacheKeyIsSharedCohort === false ? "metadata-derived" : "caller", diff --git a/src/usage/live-meter.ts b/src/usage/live-meter.ts index 76ba4e80f53..dc7eb38f81b 100644 --- a/src/usage/live-meter.ts +++ b/src/usage/live-meter.ts @@ -19,13 +19,14 @@ export type MeterSpeedReason = | "generation_window_too_short" | "invalid_generation_window" | "multiple_attempts"; export type MeterPercentReason = "usage_missing" | "tokens_estimated" | "input_missing" | "limit_unknown" | "cache_unobserved"; +type MeterContextReason = MeterPercentReason | "multiple_attempts"; export interface LiveMeter { speed: { value: number | null; reason: MeterSpeedReason | null }; outputTokens: number | null; generationMs: number | null; cache: { readTokens: number | null; inputTokens: number | null; percent: number | null; reason: MeterPercentReason | null }; - context: { usedTokens: number | null; limitTokens: number | null; percent: number | null; reason: MeterPercentReason | null }; + context: { usedTokens: number | null; limitTokens: number | null; percent: number | null; reason: MeterContextReason | null }; model: string | null; provider: string | null; client: string | null; @@ -83,7 +84,9 @@ export function liveMeterFromEntry(entry: RequestLogEntry, contextLimitTokens: n const cacheObserved = !!usage && cacheObservationFromUsage(usage, entry.cacheProvenance).provenance === "observed"; const cacheKnown = readTokens !== null && inputTokens !== null && inputTokens > 0 && cacheObserved && readTokens <= inputTokens; - const used = count(usage?.contextTotalTokens) + // Aggregate usage across attempts describes spend, not a single model window. + const multipleAttempts = (entry.attempts?.length ?? 0) > 1; + const used = multipleAttempts ? null : count(usage?.contextTotalTokens) ?? (inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null); const limit = contextLimitTokens !== null && Number.isFinite(contextLimitTokens) && contextLimitTokens > 0 ? contextLimitTokens : null; @@ -95,12 +98,14 @@ export function liveMeterFromEntry(entry: RequestLogEntry, contextLimitTokens: n readTokens, inputTokens, percent: cacheKnown ? (100 * readTokens) / inputTokens : null, reason: cacheKnown ? null : usageReason - ?? (readTokens !== null && inputTokens !== null && inputTokens > 0 && !cacheObserved ? "cache_unobserved" : "input_missing"), + ?? (inputTokens !== null && inputTokens > 0 && (readTokens === null || !cacheObserved) + ? "cache_unobserved" : "input_missing"), }, context: { usedTokens: used, limitTokens: limit, percent: used !== null && limit !== null ? Math.min(100, (100 * used) / limit) : null, - reason: used === null ? usageReason ?? "input_missing" : limit === null ? "limit_unknown" : null, + reason: multipleAttempts ? "multiple_attempts" + : used === null ? usageReason ?? "input_missing" : limit === null ? "limit_unknown" : null, }, model: entry.model ?? null, provider: entry.provider ?? null, diff --git a/structure/usage-client-attribution.md b/structure/usage-client-attribution.md index 2d0a2f1c65d..deebe5834bd 100644 --- a/structure/usage-client-attribution.md +++ b/structure/usage-client-attribution.md @@ -255,4 +255,10 @@ status and latency. It does not inspect source payloads or report token usage; s ## Live meter -The client families (`codex_*`, `claude_*`, other) also scope the live meter. `src/server/live-meter-handler.ts` serves `GET /v1/usage/live`, the newest completed conversation row projected by `src/usage/live-meter.ts` (output tokens over the recorded generation window, cache read over input, context used over the persisted Codex catalog's `context_window`, cached by catalog mtime). Any measurement that is missing, estimated, failed or under 1 s is `null` with a reason code, never a guess; the body is numbers, model/provider names and reason codes only, and a `conversation` filter is never echoed. Admission is `resolveApiAuth` (the `/v1/models` set, never the admin token), and Origin `app://-` (the Codex desktop renderer) is additionally allowed for this GET and its preflight only, behind the same loopback Host gate; `isAllowedRequestOrigin` and every other route are unchanged. The unauthenticated data-loopback listener admits it as GET only, because that socket is where the Codex++ footer dials on a host whose public listener binds a non-loopback address. The route reads the in-process request log, so it adds no management route, CLI verb or ledger read. Covered by `tests/server/live-meter-handler.test.ts` and the `AUTH_MATRIX` row. +The client families (`codex_*`, `claude_*`, other) also scope the live meter. `src/server/live-meter-handler.ts` serves `GET /v1/usage/live`, the newest completed conversation row projected by `src/usage/live-meter.ts`. Unavailable values are `null` with a reason, never a guess: + +- Speed requires a successful, complete request, reported output usage, and a single recorded generation window of at least one second. +- Cache hit rate requires usable input usage and an observed cache-read count; an observed zero is valid. +- Context fill requires reported usage from a single attempt and the model's `context_window` in the persisted Codex catalog (cached by mtime). Aggregate retry usage cannot fill one model window. + +The body is numbers, model/provider names and reason codes only, and a `conversation` filter is never echoed. Admission is `resolveApiAuth` (the `/v1/models` set, never the admin token), and Origin `app://-` (the Codex desktop renderer) is additionally allowed for this GET and its preflight only, behind the same loopback Host gate; `isAllowedRequestOrigin` and every other route are unchanged. The unauthenticated data-loopback listener admits it as GET only, because that socket is where the Codex++ footer dials on a host whose public listener binds a non-loopback address. The route reads the in-process request log, so it adds no management route, CLI verb or ledger read. Covered by `tests/server/live-meter-handler.test.ts` and the `AUTH_MATRIX` row. diff --git a/tests/usage/live-meter.test.ts b/tests/usage/live-meter.test.ts index e5a36b5d980..d2c5b807f8d 100644 --- a/tests/usage/live-meter.test.ts +++ b/tests/usage/live-meter.test.ts @@ -63,7 +63,10 @@ describe("live meter cache and context", () => { expect(liveMeterFromEntry(row({ usage: { inputTokens: 1000, outputTokens: 5, cachedInputTokens: 500 } }), null).cache.percent).toBe(50); }); test("cache is null, never guessed, when unreported, estimated or synthesized", () => { - expect(liveMeterFromEntry(row(), null).cache).toMatchObject({ percent: null, readTokens: null }); + expect(liveMeterFromEntry(row(), null).cache) + .toEqual({ percent: null, readTokens: null, inputTokens: 1000, reason: "cache_unobserved" }); + expect(liveMeterFromEntry(row({ usage: { inputTokens: 0, outputTokens: 5 } }), null).cache.reason) + .toBe("input_missing"); expect(liveMeterFromEntry(row({ usageStatus: "estimated", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache) .toMatchObject({ percent: null, reason: "tokens_estimated" }); expect(liveMeterFromEntry(row({ cacheProvenance: "synthesized", usage: { inputTokens: 10, outputTokens: 1, cacheReadInputTokens: 5 } }), null).cache.percent).toBeNull(); @@ -79,6 +82,25 @@ describe("live meter cache and context", () => { const abs = liveMeterFromEntry(row({ usage: { inputTokens: 10, outputTokens: 5, contextTotalTokens: 200 } }), 1000); expect(abs.context.usedTokens).toBe(200); }); + test("retried requests do not use aggregated usage to fill one context window", () => { + const attempt = { ordinal: 1, provider: "p", model: "fixture", adapter: "a", status: 502, durationMs: 1, + sendCount: 1, recoveryKinds: [], usageStatus: "reported", usage: { inputTokens: 40_000, outputTokens: 50 } } as const; + const m = liveMeterFromEntry(row({ + attempts: [{ ...attempt, recoveryKinds: [] }, { ...attempt, ordinal: 2, status: 200, recoveryKinds: [] }], + usage: { inputTokens: 80_000, outputTokens: 100 }, + }), 64_000); + expect(m.context).toEqual({ usedTokens: null, limitTokens: 64_000, percent: null, reason: "multiple_attempts" }); + expect(m.outputTokens).toBe(100); + }); + test("a failed or subsecond request can still report measured cache and context", () => { + const usage = { inputTokens: 1000, outputTokens: 600, cacheReadInputTokens: 500 }; + for (const delta of [{ status: 502 }, { genStartMs: 7950 }]) { + const m = liveMeterFromEntry(row({ usage, ...delta }), 3200); + expect(m.speed.value).toBeNull(); + expect(m.cache.percent).toBe(50); + expect(m.context.percent).toBe(50); + } + }); test("an unknown or invalid limit leaves the percentage null but keeps the used count", () => { for (const limit of [null, 0, -5, NaN]) { const m = liveMeterFromEntry(row(), limit); diff --git a/tests/usage/usage-context-breakdown.test.ts b/tests/usage/usage-context-breakdown.test.ts index dba5de2ec0b..d20075bc1ca 100644 --- a/tests/usage/usage-context-breakdown.test.ts +++ b/tests/usage/usage-context-breakdown.test.ts @@ -233,6 +233,32 @@ ${fill(80, "u")}` }] }], expect(b.parts.chat).toBe(20); }); + test("injected notifications before and after a user message count as results, not turns", () => { + const before = "done"; + const after = "finished"; + const b = measureContextBreakdown({ + messages: [{ role: "user", content: before }, { role: "user", content: fill(80) }, { role: "user", content: after }], + }, "messages")!; + expect(b.parts.results).toBe(tok(before) + tok(after)); + expect(b.turns).toEqual([20]); + expect(b.parts.chat).toBe(20); + }); + + test.each(["image", "document"])("a direct %s alone starts a user turn, but tool result media does not", type => { + const attachment = { type, source: { type: "base64", data: "AAAA" } }; + const b = measureContextBreakdown({ + messages: [ + { role: "user", content: fill(40) }, + { role: "user", content: [{ type: "tool_result", content: [attachment] }] }, + { role: "assistant", content: fill(20) }, + { role: "user", content: [attachment] }, + { role: "assistant", content: fill(80) }, + ], + }, "messages")!; + expect(b.turns).toEqual([15, 20]); + expect(b.parts.files).toBe(3200); + }); + 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); From 9e2231f88d9c51eea82140c66830e9169b2fcb27 Mon Sep 17 00:00:00 2001 From: Andrew Wang Date: Wed, 25 Nov 2026 09:03:36 +0000 Subject: [PATCH 18/18] fix: classify the read-only live meter for body admission --- src/server/inbound-body-admission.ts | 3 ++- structure/transports/byte-accounting.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/server/inbound-body-admission.ts b/src/server/inbound-body-admission.ts index 9d413108922..e84c4f60973 100644 --- a/src/server/inbound-body-admission.ts +++ b/src/server/inbound-body-admission.ts @@ -32,7 +32,7 @@ export const CONFIGURABLE_JSON_BODY_ROUTES: ReadonlySet = new Set([ /** * Loopback routes deliberately outside this gate. Audio uploads, realtime/live - * control and the model list do not read JSON under `maxInboundBodyBytes`, so + * control, the model list and live usage do not read JSON under `maxInboundBodyBytes`, so * reserving that allowance for them would refuse traffic the limit never covered. */ export const UNGATED_LOOPBACK_ROUTES: ReadonlySet = new Set([ @@ -42,6 +42,7 @@ export const UNGATED_LOOPBACK_ROUTES: ReadonlySet = new Set([ "/v1/realtime", "/v1/realtime/calls", "/v1/live", + "/v1/usage/live", ]); export class InboundBodyCapacityError extends Error { diff --git a/structure/transports/byte-accounting.md b/structure/transports/byte-accounting.md index 60cdcfb7d65..bb965a52126 100644 --- a/structure/transports/byte-accounting.md +++ b/structure/transports/byte-accounting.md @@ -130,6 +130,7 @@ combo/translation calls share their HTTP owner's reservation rather than reservi The exact POST routes are Responses, compact, Chat Completions, Messages, count_tokens, image generations/edits and alpha search. Image/search/count_tokens retain their configured per-body limits. Management, audio, context relay and WebSocket frames retain their independent contracts. +The read-only `GET /v1/usage/live` route and its preflight do not read a JSON body or use the upload budget. Capacity pressure queues at most 32 unread uploads in FIFO order for at most 120 seconds. Returning unused allowance or settling a lease wakes eligible waiters; abort and timeout detach their timers/listeners without changing another owner's reservation. A disconnect after a grant