.
+ */
+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","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}`;
+
+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 dbbbf3e7523..97844755f90 100644
--- a/gui/src/i18n/ru.ts
+++ b/gui/src/i18n/ru.ts
@@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy";
import { accountProbeCopy } from "./account-probe-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 { remoteLinkChildCopy } from "./remote-link-child-copy";
import { gatewayClientsCopy } from "./gateway-clients-copy";
@@ -141,6 +142,7 @@ export const ru: Record = {
...accountProbeCopy("ru"),
...shellV2Copy("ru"),
...codexCliUpdateCopy("ru"),
+ ...routeLiveCopy("ru"),
...remoteLinkDiagnosticsCopy("ru"),
...remoteLinkChildCopy("ru"),
...gatewayClientsCopy("ru"),
diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts
index a38e5db3d26..c68b64e4a3c 100644
--- a/gui/src/i18n/tr.ts
+++ b/gui/src/i18n/tr.ts
@@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy";
import { accountProbeCopy } from "./account-probe-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 { remoteLinkChildCopy } from "./remote-link-child-copy";
import { gatewayClientsCopy } from "./gateway-clients-copy";
@@ -142,6 +143,7 @@ export const tr: Record = {
...accountProbeCopy("tr"),
...shellV2Copy("tr"),
...codexCliUpdateCopy("tr"),
+ ...routeLiveCopy("tr"),
...remoteLinkDiagnosticsCopy("tr"),
...remoteLinkChildCopy("tr"),
...gatewayClientsCopy("tr"),
diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts
index ce4758d3694..68a5208bde6 100644
--- a/gui/src/i18n/vi.ts
+++ b/gui/src/i18n/vi.ts
@@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy";
import { accountProbeCopy } from "./account-probe-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 { remoteLinkChildCopy } from "./remote-link-child-copy";
import { gatewayClientsCopy } from "./gateway-clients-copy";
@@ -143,6 +144,7 @@ export const vi: Record = {
...accountProbeCopy("vi"),
...shellV2Copy("vi"),
...codexCliUpdateCopy("vi"),
+ ...routeLiveCopy("vi"),
...remoteLinkDiagnosticsCopy("vi"),
...remoteLinkChildCopy("vi"),
...gatewayClientsCopy("vi"),
diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts
index fa94798639e..90173e6f717 100644
--- a/gui/src/i18n/zh-TW.ts
+++ b/gui/src/i18n/zh-TW.ts
@@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy";
import { accountProbeCopy } from "./account-probe-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 { remoteLinkChildCopy } from "./remote-link-child-copy";
import { gatewayClientsCopy } from "./gateway-clients-copy";
@@ -139,6 +140,7 @@ export const zhTW: Record = {
...accountProbeCopy("zh-TW"),
...shellV2Copy("zh-TW"),
...codexCliUpdateCopy("zh-TW"),
+ ...routeLiveCopy("zh-TW"),
...remoteLinkDiagnosticsCopy("zh-TW"),
...remoteLinkChildCopy("zh-TW"),
...gatewayClientsCopy("zh-TW"),
diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts
index 5d3a9a107c7..6027b5d4f30 100644
--- a/gui/src/i18n/zh.ts
+++ b/gui/src/i18n/zh.ts
@@ -2,6 +2,7 @@ import { desktopCompatibilityCopy } from "./desktop-compatibility-copy";
import { accountProbeCopy } from "./account-probe-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 { remoteLinkChildCopy } from "./remote-link-child-copy";
import { gatewayClientsCopy } from "./gateway-clients-copy";
@@ -141,6 +142,7 @@ export const zh: Record = {
...accountProbeCopy("zh"),
...shellV2Copy("zh"),
...codexCliUpdateCopy("zh"),
+ ...routeLiveCopy("zh"),
...remoteLinkDiagnosticsCopy("zh"),
...remoteLinkChildCopy("zh"),
...gatewayClientsCopy("zh"),
diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx
index e7ac6bfd515..1442f8ce1fc 100644
--- a/gui/src/pages/Models.tsx
+++ b/gui/src/pages/Models.tsx
@@ -34,6 +34,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";
@@ -118,6 +119,7 @@ type CachedModelsPage = {
const SUBTITLE_TKEY: Record = {
catalog: ["modelsV2.ledeCatalog", "models.subtitle"],
overall: ["modelsOverall.lede"],
+ live: ["routeLive.subtitle"],
combos: ["modelsV2.ledeCombos", "models.subtitle.combos"],
routing: ["models.subtitle.routing"],
compatibility: ["models.subtitle.compatibility"],
@@ -2691,6 +2693,26 @@ export default function Models({ apiBase, restartEpoch = 0, connected = false, c
)}
+
+ {mounted.has("live") && (
+
+
+
+ )}
+
+
;
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 b93ba4a9dd4..3d344d8a859 100644
--- a/gui/src/pages/models-tab-strip.tsx
+++ b/gui/src/pages/models-tab-strip.tsx
@@ -19,6 +19,7 @@ import {
const TAB_LABEL: Record = {
catalog: "models.tab.catalog",
overall: "models.tab.overall",
+ 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 cfd08b06a7f..32acffdd453 100644
--- a/gui/src/pages/models-tab.ts
+++ b/gui/src/pages/models-tab.ts
@@ -14,10 +14,10 @@ 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" | "overall" | "combos" | "routing" | "compatibility";
+export type ModelsTab = "catalog" | "overall" | "live" | "combos" | "routing" | "compatibility";
/** "overall" (every model across providers, one list) sits beside the per-provider catalog. */
-export const MODELS_TABS: readonly ModelsTab[] = ["catalog", "overall", "combos", "routing", "compatibility"];
+export const MODELS_TABS: readonly ModelsTab[] = ["catalog", "overall", "live", "combos", "routing", "compatibility"];
export function modelsTabHash(tab: ModelsTab): string {
return tab === "catalog" ? "models" : `models/${tab}`;
@@ -36,6 +36,7 @@ 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/overall") return "overall";
+ 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/ContextCard.tsx b/gui/src/pages/route-live/ContextCard.tsx
new file mode 100644
index 00000000000..9046a1a2673
--- /dev/null
+++ b/gui/src/pages/route-live/ContextCard.tsx
@@ -0,0 +1,123 @@
+/**
+ * "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 { useMemo } from "react";
+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, contextInputTokens, type RouteRow } from "./route-rows";
+
+const KIND_LABEL = {
+ system: "routeLive.ctxSystem",
+ tools: "routeLive.ctxTools",
+ skills: "routeLive.ctxSkills",
+ memory: "routeLive.ctxMemory",
+ files: "routeLive.ctxFiles",
+ results: "routeLive.ctxResults",
+ chat: "routeLive.ctxChat",
+} as const satisfies Record;
+
+const HEALTH_LABEL = {
+ ok: "routeLive.ctxHealthOk",
+ filling: "routeLive.ctxHealthFilling",
+ near: "routeLive.ctxHealthNear",
+} as const satisfies Record;
+
+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 breakdown = row.contextBreakdown!;
+ const windowTokens = row.contextWindow;
+ const shares = useMemo(() => calibrateContext(breakdown, contextInputTokens(row)), [breakdown, row]);
+
+ const used = Math.max(shares.used, 1);
+ 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) => {
+ const value = tokens / used;
+ return value > 0 && value < 0.01 ? `<${formatPercent(1, localeTag)}` : formatPercent(100 * value, localeTag);
+ };
+ const parts = CONTEXT_CATEGORIES.flatMap(kind => (shares.parts[kind] > 0 ? [{ kind, tokens: shares.parts[kind] }] : []));
+
+ 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")}
}
+ {parts.length > 0 && (
+ <>
+
+
+ {parts.map(part => (
+ -
+
+ {t(KIND_LABEL[part.kind])}
+ {tokensText(part.tokens)} · {share(part.tokens)}
+
+ ))}
+
+ >
+ )}
+ {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/FlowDiagram.tsx b/gui/src/pages/route-live/FlowDiagram.tsx
new file mode 100644
index 00000000000..e086a4ef139
--- /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("logs.col.duration")} ${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}}
+
+
+
+
+
+ OpenCodex
+ {flow.requested.alias ?? flow.requested.model}
+
+
+
+ {candidates.length === 0 ? (
+ {t("routeLive.noCandidates")}
+ ) : (
+
+ {candidates.map(c => (
+ -
+
+
+
+ {candidateWho(c)}
+
{c.model}
+ {t(STATUS_TKEY[c.status])}
+
+
+
+
+ ))}
+
+ )}
+
+ );
+}
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..3997cb64592
--- /dev/null
+++ b/gui/src/pages/route-live/RequestList.tsx
@@ -0,0 +1,167 @@
+/**
+ * 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 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;
+}) {
+ 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..f176fa97d93
--- /dev/null
+++ b/gui/src/pages/route-live/RouteLive.tsx
@@ -0,0 +1,141 @@
+/**
+ * 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. 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 { 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 { modelsTabHash } from "../models-tab";
+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")}
;
+ }
+}
+
+/** 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 (
+
+ {bits.join(" · ")}
+ {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" && }
+
+ );
+}
+
+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")}
+ : ;
+ }
+ return (
+
+ {resource.error != null && !resource.lastAttemptOk && {t("routeLive.loadFailed")} }
+ {selected && flow ? (
+ <>
+ setPinnedKey(null)} />
+
+ >
+ ) : }
+
+ );
+}
diff --git a/gui/src/pages/route-live/TimeBar.tsx b/gui/src/pages/route-live/TimeBar.tsx
new file mode 100644
index 00000000000..d43ca88cd4b
--- /dev/null
+++ b/gui/src/pages/route-live/TimeBar.tsx
@@ -0,0 +1,66 @@
+/**
+ * "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 = {
+ internal: "ocx", earlier: "earlier", upstreamWait: "upstream", streaming: "upstream", reading: "upstream",
+};
+
+const PART_LABEL = {
+ 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 => (
+ -
+
+ {t(PART_LABEL[part.kind])}
+ {formatPartDuration(part.ms, localeTag)}
+
+ ))}
+
+ >
+ );
+}
+
+/** 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/context-tiles.ts b/gui/src/pages/route-live/context-tiles.ts
new file mode 100644
index 00000000000..fcc586ba4ec
--- /dev/null
+++ b/gui/src/pages/route-live/context-tiles.ts
@@ -0,0 +1,78 @@
+/**
+ * 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
+ *
+ * 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";
+}
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..603e8367334
--- /dev/null
+++ b/gui/src/pages/route-live/flow-model.ts
@@ -0,0 +1,135 @@
+/**
+ * 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 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..ee53a8646cd
--- /dev/null
+++ b/gui/src/pages/route-live/route-live.css
@@ -0,0 +1,149 @@
+/* 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: 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); }
+.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-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); }
+
+/* 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(#be185d, #f472b6);
+ --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); }
+/* 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); }
+.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: 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; }
+.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..d6d2115f59c
--- /dev/null
+++ b/gui/src/pages/route-live/route-rows.ts
@@ -0,0 +1,242 @@
+/**
+ * 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 { CONTEXT_CATEGORIES, type ContextBreakdown } from "./context-tiles";
+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;
+ /** This attempt's own usage; the row's `usage` sums every attempt of a retried request. */
+ usage?: { inputTokens?: number };
+}
+
+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;
+ requestedEffort?: string;
+ effectiveEffort?: string;
+ usage?: {
+ inputTokens?: number;
+ outputTokens?: number;
+ totalTokens?: number;
+ cachedInputTokens?: number;
+ cacheReadInputTokens?: number;
+ cacheCreationInputTokens?: number;
+ };
+ 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;
+ 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 } : {}) };
+}
+
+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, 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);
+ 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;
+}
+
+/** 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;
+}
+
+/**
+ * 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;
+ 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 meter = cacheMeterOf(row);
+ return meter ? (100 * meter.read) / meter.total : undefined;
+}
+
+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..ce42a897275
--- /dev/null
+++ b/gui/src/pages/route-live/time-parts.ts
@@ -0,0 +1,61 @@
+/**
+ * "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.
+ *
+ * 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
+ * reading replaces upstreamWait + streaming when no first output was seen
+ */
+import type { RouteRow } from "./route-rows";
+
+export type TimePartKind = "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 earlier = attempts.slice(0, -1).reduce((sum, attempt) => sum + (measured(attempt.durationMs) ?? 0), 0);
+ 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: "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..15a70dc723c
--- /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}&live=1`, { 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 cc9e9bfe2dd..bdbfc513d65 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 five tabs in strip", async () => {
+test("4. keyboard traversal covers six tabs in strip", async () => {
installLabFetch();
const { root, container } = await mountModels();
try {
const tabs = [...container.querySelectorAll('[role="tab"]')] as HTMLButtonElement[];
- expect(tabs).toHaveLength(5);
+ expect(tabs).toHaveLength(6);
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 f92f34604b1..5567da126f7 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 five tabs with the catalog selected on the bare hash", async () => {
+test("the strip renders all six 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-overall", "models-tab-combos", "models-tab-routing", "models-tab-compatibility",
+ "models-tab-catalog", "models-tab-overall", "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(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.
@@ -226,13 +226,13 @@ test("every rendered panel is wired to its tab", async () => {
installFetch();
const { container, root } = await mountModels();
try {
- for (const id of ["overall", "combos", "routing", "compatibility"]) {
+ for (const id of ["overall", "live", "combos", "routing", "compatibility"]) {
await act(async () => {
(container.querySelector(`#models-tab-${id}`) as HTMLButtonElement).click();
});
await act(async () => { await Promise.resolve(); });
}
- for (const id of ["catalog", "overall", "combos", "routing", "compatibility"]) {
+ for (const id of ["catalog", "overall", "live", "combos", "routing", "compatibility"]) {
const p = panel(container, id)!;
expect(p.getAttribute("role")).toBe("tabpanel");
expect(p.getAttribute("aria-labelledby")).toBe(`models-tab-${id}`);
@@ -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();
});
diff --git a/gui/tests/route-live-context.test.ts b/gui/tests/route-live-context.test.ts
new file mode 100644
index 00000000000..59005db6601
--- /dev/null
+++ b/gui/tests/route-live-context.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, test } from "bun:test";
+import {
+ calibrateContext, contextHealth, type ContextBreakdown,
+} from "../src/pages/route-live/context-tiles";
+import { cacheHitPercent, cacheMeterOf, contextInputTokens, 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,
+});
+
+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("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("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();
+ 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-model.test.ts b/gui/tests/route-live-model.test.ts
new file mode 100644
index 00000000000..958e946b973
--- /dev/null
+++ b/gui/tests/route-live-model.test.ts
@@ -0,0 +1,109 @@
+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, 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);
+
+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");
+ });
+
+ 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]]);
+ });
+
+ 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(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("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 },
+ 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..fea8aa27a30
--- /dev/null
+++ b/gui/tests/route-live-render.test.tsx
@@ -0,0 +1,194 @@
+import { expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+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 { 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";
+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("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", () => {
+ 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");
+ 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([...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");
+});
+
+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, 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(4);
+ const bare = render( );
+ expect(bare.querySelector(".rl-time-bar")).toBeNull();
+ expect(bare.querySelector("p")?.textContent).toContain("没有记录时间分布");
+});
+
+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],
+ 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, 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();
+ 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", "工具结果", "会话内容"]);
+ 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("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", () => {
+ 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.querySelector(".rl-ctx-health")).toBeNull();
+});
+
+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/gui/tests/route-live-time.test.ts b/gui/tests/route-live-time.test.ts
new file mode 100644
index 00000000000..ed65595c01a
--- /dev/null
+++ b/gui/tests/route-live-time.test.ts
@@ -0,0 +1,63 @@
+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("failover: earlier attempts are subtracted from the time before the final attempt", () => {
+ const parts = timeParts(row({
+ durationMs: 3000, upstreamSendMs: 1010,
+ attempts: [attempt({ status: 429, durationMs: 1000 }), attempt({ durationMs: 1990, firstOutputMs: 700 })],
+ }));
+ expect(parts).toEqual([
+ { kind: "internal", ms: 10 }, { 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, attempts: [attempt({ durationMs: 999.95, firstOutputMs: 2000 })],
+ }));
+ expect(parts).toEqual([{ 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 05ce1c30f46..59777f44ece 100644
--- a/scripts/test-layout/layout-usage.json
+++ b/scripts/test-layout/layout-usage.json
@@ -6,6 +6,11 @@
"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",
+ "request-log-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",
"provider-failure-detail.test.ts": "usage",
diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json
index c9abac57f5c..2b04013a882 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-windows.test.ts": "server",
+ "hub-usage.test.ts": "server", "hub-usage-windows.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/oauth/generic-account-failover.ts b/src/oauth/generic-account-failover.ts
index 64aaf5d452c..458f9f10eb0 100644
--- a/src/oauth/generic-account-failover.ts
+++ b/src/oauth/generic-account-failover.ts
@@ -49,6 +49,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;
@@ -430,6 +433,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/auth-cors.ts b/src/server/auth-cors.ts
index de7944dcec8..9c5ad31d6f9 100644
--- a/src/server/auth-cors.ts
+++ b/src/server/auth-cors.ts
@@ -710,6 +710,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" },
// Usage windows require a configured, single-provider key with full model scope.
{ endpoint: "/v1/usage/windows", bearer: "accepted", dedicated: "accepted", xApiKey: "rejected" },
];
diff --git a/src/server/chat-completions.ts b/src/server/chat-completions.ts
index c0c6fe51648..af0f6bd09eb 100644
--- a/src/server/chat-completions.ts
+++ b/src/server/chat-completions.ts
@@ -63,6 +63,7 @@ import {
linkRequestSessionLane,
} from "./request-log-conversation";
import type { OcxConfig } from "../types";
+import { isLiveRoutingRecentlyObserved, observeContextBreakdown } from "./context-breakdown";
import { DecompressedBodyTooLargeError, UnsupportedContentEncodingError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress";
import {
addFinalRequestLog,
@@ -214,6 +215,7 @@ async function handleChatCompletionsWithBudget(
try {
const rawBody = await readChatBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes));
assertChatCompletionsRoutingBody(rawBody);
+ 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 14bca0b4867..fe2ac7d7f17 100644
--- a/src/server/claude-messages.ts
+++ b/src/server/claude-messages.ts
@@ -86,6 +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 { isLiveRoutingRecentlyObserved, observeContextBreakdown } from "./context-breakdown";
import { addFinalRequestLog, httpStatusForRequestLogTerminal, recordFirstOutput, type RequestLogContext } from "./request-log";
import { createFinalRequestLog } from "./inference/final-log";
import {
@@ -696,6 +697,7 @@ async function handleClaudeMessagesWithBudget(
const advisorAdmissionPolicy = logIds?.advisorAdmissionPolicy ?? captureAdmissionPolicy(config, logIds?.admission);
try {
anthropicBody = await readAnthropicBody(req, translatorBudget, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes));
+ 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-classify.ts b/src/server/context-breakdown-classify.ts
new file mode 100644
index 00000000000..8e82a6504a8
--- /dev/null
+++ b/src/server/context-breakdown-classify.ts
@@ -0,0 +1,413 @@
+/**
+ * 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 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++;
+ 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();
+ }
+ return t !== "" && userTextCategory(t) === "chat";
+}
+
+// --- 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 {
+ 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;
+ const category = userTextCategory(t);
+ if (category === "chat") this.chat(tokensOfText(leading ? t : text));
+ else this[category] += tokensOfText(t);
+ }
+
+ 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 {
+ 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..cc6e3967aa7
--- /dev/null
+++ b/src/server/context-breakdown.ts
@@ -0,0 +1,340 @@
+/**
+ * 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";
+
+/** 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;
+ 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") {
+ // 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 === "image" || x.type === "document" || (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.image) acc.file(IMAGE_TOKENS);
+ else 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);
+ // 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;
+ 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 (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;
+ 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/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/src/server/index.ts b/src/server/index.ts
index 822dbe4734b..51058ff08f4 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -418,6 +418,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): 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/src/server/index/serve-options.ts b/src/server/index/serve-options.ts
index d5cc04ea2c0..bb36f231b26 100644
--- a/src/server/index/serve-options.ts
+++ b/src/server/index/serve-options.ts
@@ -415,6 +415,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 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,6 +841,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
);
}
+ 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
new file mode 100644
index 00000000000..d34bb9d0be9
--- /dev/null
+++ b/src/server/live-meter-handler.ts
@@ -0,0 +1,141 @@
+/**
+ * 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 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";
+
+/** 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 };
+
+/**
+ * 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");
+ }
+ 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 visible = liveMeterRowVisible(admission);
+ const selection = selectLiveMeterEntries(
+ (deps.entries ?? getRequestLogEntries)(),
+ 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"] = {};
+ 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, admission?: DataPlaneAdmission): Response {
+ const result = buildLiveMeter(params, deps, admission);
+ 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;
+ };
+ 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"));
+ const response = liveMeterResponse(new URL(req.url).searchParams, deps, admission);
+ if (response.status === 200) markLiveRoutingObserved();
+ return reply(response, 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/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` 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; measured, never derived. */
+export interface RouteLiveTimingContext {
+ /** Epoch ms the final physical attempt started; set by whoever opens the attempt. */
+ activeAttemptStartedAt?: number;
+}
+
+export interface RouteLiveTimingEntryField {
+ /** ms from request start until the final attempt started; includes earlier failed attempts. */
+ upstreamSendMs?: 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;
+ return upstreamSendMs !== undefined ? { upstreamSendMs } : {};
+}
+
+/** 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 da38b7991bb..b3fbbbc185b 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, 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 { attemptAccountChanged, sealRequestAttemptIdentity } from "./request-log-account-rotation";
@@ -127,7 +128,7 @@ export function cacheDiagnosticsObserving(): boolean {
return cacheDiagnosticHooks()?.enabled() === true;
}
-export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyLogContext, CommittedComboLogFields {
+export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyLogContext, CommittedComboLogFields, RouteLiveTimingContext, ContextBreakdownContext {
model: string;
provider: string;
client?: UsageClient;
@@ -336,7 +337,7 @@ export function rebindCacheDiagnosticBody(
cacheDiagnosticHooks()?.rebind(body, draft);
}
-export interface RequestLogEntry extends UpstreamErrorDiagnostics, LinkRequestLogCarrier, RequestBodyEntryField {
+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. */
@@ -1697,6 +1698,9 @@ 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)),
+ ...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 abcafd661cd..aa7ffaacec7 100644
--- a/src/server/responses/request-prepare.ts
+++ b/src/server/responses/request-prepare.ts
@@ -103,6 +103,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 { 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";
@@ -291,14 +292,13 @@ 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",
contextPrincipalIdOf(options.admission),
);
+ if (isLiveRoutingRecentlyObserved()) observeContextBreakdown(logCtx, body, "responses");
if (!concreteSelection && !options.compactionRoutingOverride && inboundWire === "responses") {
options.compactionRoutingOverride = applyCompactionRoutingOverride(body, req.headers, config, {
endpoint: "responses",
diff --git a/src/usage/live-meter.ts b/src/usage/live-meter.ts
new file mode 100644
index 00000000000..dc7eb38f81b
--- /dev/null
+++ b/src/usage/live-meter.ts
@@ -0,0 +1,150 @@
+/**
+ * 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";
+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" | "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: MeterContextReason | 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");
+ // 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))) {
+ 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`. 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
+ && cacheObserved && readTokens <= inputTokens;
+ // 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;
+ 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
+ ?? (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: multipleAttempts ? "multiple_attempts"
+ : 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 8562eacb29e..1e682c19847 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` (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` — plus the Gemini wire, each path with its own method. It never serves `/api/*`,
`/healthz`, `/readyz`, or GUI routes, so local management discovery has to use an authenticated
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
diff --git a/structure/usage-client-attribution.md b/structure/usage-client-attribution.md
index d5549a00a27..deebe5834bd 100644
--- a/structure/usage-client-attribution.md
+++ b/structure/usage-client-attribution.md
@@ -252,3 +252,13 @@ Remote Link rows may carry an optional `link` object (transport, continuation, h
Opted-in native Gemini delivery uses `src/server/gemini-native-log.ts` for client and admission attribution,
status and latency. It does not inspect source payloads or report token usage; see
[Native Gemini Inbound](data-planes/gemini-native.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`. 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/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json
index 26fb6ff56e0..644abdc374c 100644
--- a/tests/fixtures/test-layout-expected.json
+++ b/tests/fixtures/test-layout-expected.json
@@ -198,7 +198,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",
@@ -1016,7 +1016,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-usage-windows.test.ts": "server",
+ "hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli", "hub-usage.test.ts": "server", "hub-usage-windows.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",
@@ -1195,7 +1195,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",
@@ -1365,7 +1365,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-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/gui/models-workspace-tabs.test.ts b/tests/gui/models-workspace-tabs.test.ts
index 1e1089f05e6..e3c6849d84f 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/overall", "models/combos", "models/routing", "models/compatibility"]);
+ expect([...MODELS_TAB_HASHES]).toEqual(["models/overall", "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");
@@ -59,6 +59,7 @@ describe("readModelsTab", () => {
test("maps every nested hash to its tab", () => {
expect(readModelsTab("#models")).toBe("catalog");
expect(readModelsTab("#models/overall")).toBe("overall");
+ expect(readModelsTab("#models/live")).toBe("live");
expect(readModelsTab("#models/combos")).toBe("combos");
expect(readModelsTab("#models/routing")).toBe("routing");
expect(readModelsTab("#models/compatibility")).toBe("compatibility");
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/server/api-key-attribution.test.ts b/tests/server/api-key-attribution.test.ts
index fd07e5585e7..5ea301cbacd 100644
--- a/tests/server/api-key-attribution.test.ts
+++ b/tests/server/api-key-attribution.test.ts
@@ -740,7 +740,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/usage/windows";
+ || row.endpoint === "/v1/hub-state" || row.endpoint === "/v1/usage" || row.endpoint === "/v1/usage/live" || row.endpoint === "/v1/usage/windows";
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..4a7e1204c63
--- /dev/null
+++ b/tests/server/live-meter-handler.test.ts
@@ -0,0 +1,292 @@
+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 { 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";
+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", () => {
+ 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] };
+ 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("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);
+ });
+
+ 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();
+ });
+
+ 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", () => {
+ 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();
+ 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);
+ }, 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);
+
+ 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/server/loopback-listener-admission.test.ts b/tests/server/loopback-listener-admission.test.ts
index 5aed34d1219..77c044e84e3 100644
--- a/tests/server/loopback-listener-admission.test.ts
+++ b/tests/server/loopback-listener-admission.test.ts
@@ -118,6 +118,13 @@ describe("local client inference wires on the loopback listener (#4236)", () =>
);
});
+ 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. 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("the Gemini wire is admitted per path with its own HTTP method", () => {
// `ocx connect agy` writes the loopback port, so without this entry every agy call 404s on a
// hub whose public listener binds a tailnet address. The handlers resolve admission from the
diff --git a/tests/server/loopback-listener-integration.test.ts b/tests/server/loopback-listener-integration.test.ts
index 75d9e6d74c4..a77ddccb147 100644
--- a/tests/server/loopback-listener-integration.test.ts
+++ b/tests/server/loopback-listener-integration.test.ts
@@ -325,6 +325,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) {
diff --git a/tests/usage/live-meter.test.ts b/tests/usage/live-meter.test.ts
new file mode 100644
index 00000000000..d2c5b807f8d
--- /dev/null
+++ b/tests/usage/live-meter.test.ts
@@ -0,0 +1,141 @@
+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);
+ }
+ });
+ 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", () => {
+ 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)
+ .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();
+ });
+ 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 });
+ 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);
+ 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();
+ });
+});
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-context-breakdown.test.ts b/tests/usage/request-log-context-breakdown.test.ts
new file mode 100644
index 00000000000..63af661f984
--- /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(850_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);
+ });
+});
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..fc97ed81ad8
--- /dev/null
+++ b/tests/usage/request-log-route-live-timing.test.ts
@@ -0,0 +1,24 @@
+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("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();
+ });
+});
diff --git a/tests/usage/usage-context-breakdown.test.ts b/tests/usage/usage-context-breakdown.test.ts
new file mode 100644
index 00000000000..d20075bc1ca
--- /dev/null
+++ b/tests/usage/usage-context-breakdown.test.ts
@@ -0,0 +1,427 @@
+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);
+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("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" }] }],
+ }, "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("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("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);
+ });
+});
+
+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));
+ });
+
+ 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", () => {
+ 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);
+ });
+});
+
+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);
+ });
+});