import { FormEvent, startTransition, useEffect, useState } from "react"; type PageKey = "overview" | "requests" | "profiles" | "rules" | "logs"; type Tone = "" | "success" | "error"; type ReasoningMatchMode = "formula_518n_minus_2" | "manual"; type AuthMode = "passthrough" | "fixed_bearer" | "manual_bearer" | "auth_json"; type GatewayConfig = { profile_name?: string; image_profile_name?: string; listen_host?: string; listen_port?: number; management_access_key?: string; management_access_key_configured?: boolean; upstream_base_url?: string; upstream_auth_mode?: string; upstream_auth_env?: string | null; upstream_auth_json_key?: string | null; image_base_url?: string; image_auth_mode?: string; image_auth_env?: string | null; image_auth_json_key?: string | null; request_history_limit?: number; model_remap?: string; endpoints?: string[]; reasoning_match_mode?: ReasoningMatchMode; reasoning_equals?: number[]; retryable_status_codes?: number[]; retryable_error_messages?: string[]; upstream_fetch_retry_attempts?: number; upstream_fetch_retry_backoff_ms?: number; non_stream_status_code?: number; log_match?: boolean; }; type Metrics = { started_at?: string; persistent_since?: string | null; total_proxy_request_count?: number; inspected_response_count?: number; matched_response_count?: number; reasoning_516_count?: number; reasoning_516_ratio?: number; token_totals?: { input_tokens?: number; output_tokens?: number; total_tokens?: number; reasoning_tokens?: number; cached_tokens?: number; }; observed_reasoning_counts?: Record; observed_reasoning_counts_total_keys?: number; observed_reasoning_counts_omitted?: number; }; type StatusPayload = { ok: boolean; listen?: string; config?: GatewayConfig; state?: { provider_name?: string; codex_current_base_url?: string; latest_backup_path?: string; }; paths?: { config_path?: string; profiles_dir?: string; image_profiles_dir?: string; log_path?: string; thread_rules_path?: string; }; metrics?: Metrics; }; type Usage = { input_tokens?: number | null; output_tokens?: number | null; total_tokens?: number | null; reasoning_tokens?: number | null; cached_tokens?: number | null; }; type RequestEntry = { seq: number; request_id?: string | null; response_id?: string | null; thread_id?: string | null; lifecycle_state?: string | null; started_at?: string; first_response_at?: string | null; first_response_delay_ms?: number | null; finished_at?: string | null; last_activity_at?: string | null; duration_ms?: number | null; profile_name?: string; method?: string; path?: string; request_body_bytes?: number | null; response_bytes_received?: number | null; model?: string | null; requested_model?: string | null; forwarded_model?: string | null; reasoning_effort?: string | null; reasoning_summary?: string | null; response_stream?: boolean; stream_chunk_count?: number | null; usage_last_updated_at?: string | null; upstream_attempt_count?: number | null; reasoning_guard_enabled?: boolean; reasoning_guard_thread_override?: string | null; reasoning_retry_enabled?: boolean; reasoning_retry_query_count?: number | null; reasoning_retry_round_count?: number | null; reasoning_retry_current_round?: number | null; reasoning_retry_current_width?: number | null; reasoning_retry_current_firsts?: Array<{ round?: number | null; slot?: number | null; first_response_at?: string | null; first_response_delay_ms?: number | null; outcome?: string | null; status_code?: number | null; upstream_status_code?: number | null; reasoning_tokens?: number | null; matched?: boolean | null; }> | null; reasoning_retry_winner_round?: number | null; reasoning_retry_winner_slot?: number | null; reasoning_retry_stop_reason?: string | null; reasoning_retry_thread_mode?: string | null; reasoning_retry_extra_inspected_count?: number | null; reasoning_retry_extra_matched_count?: number | null; reasoning_retry_extra_usage?: Usage | null; reasoning_retry_extra_reasoning_counts?: Record | null; matched?: boolean; status_code?: number | null; upstream_status_code?: number | null; upstream?: { origin?: string; path?: string; route?: "default" | "images" | string; auth_mode?: string; auth_source?: string; authorization_configured?: boolean; status?: number; content_type?: string; } | null; reasoning_tokens?: number | null; usage?: Usage | null; error?: string | null; }; type RequestsPayload = { total_entries?: number; latest_seq?: number; entries?: RequestEntry[]; }; type ThreadRuleEntry = { thread_id: string; reasoning_intercept_enabled: boolean; updated_at?: string | null; }; type ThreadRulesPayload = { ok: boolean; thread_rules_path?: string; rules?: ThreadRuleEntry[]; saved_rule?: ThreadRuleEntry | null; removed_rule?: ThreadRuleEntry | null; message?: string; }; type ProfileFormModel = { listen_host?: string; listen_port?: string; upstream_base_url?: string; auth_mode?: string; auth_env?: string; auth_file?: string; manual_secret_file?: string; manual_secret_configured?: boolean; auth_json_path?: string; auth_json_key?: string; request_history_limit?: string; model_remap?: string; reasoning_match_mode?: ReasoningMatchMode; reasoning_equals?: string; retryable_status_codes?: string; retryable_error_messages?: string[]; upstream_fetch_retry_attempts?: string; upstream_fetch_retry_backoff_ms?: string; endpoints?: string[]; }; type Profile = { name: string; active: boolean; file_path?: string; summary?: { listen_host?: string; listen_port?: string; upstream_base_url?: string; auth_mode?: string; auth_source?: string; request_history_limit?: string; model_remap?: string; reasoning_match_mode?: ReasoningMatchMode; reasoning_equals?: string; }; form?: ProfileFormModel; }; type ImageProfileFormModel = { base_url?: string; auth_mode?: string; auth_env?: string; auth_file?: string; manual_secret_file?: string; manual_secret_configured?: boolean; auth_json_path?: string; auth_json_key?: string; }; type ImageProfile = { name: string; active: boolean; file_path?: string; summary?: { base_url?: string; auth_mode?: string; auth_source?: string; }; form?: ImageProfileFormModel; }; type ProfilesPayload = { profiles_dir?: string; active_profile?: string; applied_profile?: { profile?: string; hot_swapped?: boolean; listen?: string; upstream_base_url?: string; } | null; profiles?: Profile[]; }; type ImageProfilesPayload = { image_profiles_dir?: string; active_image_profile?: string; applied_image_profile?: { image_profile?: string; hot_swapped?: boolean; image_base_url?: string; } | null; image_profiles?: ImageProfile[]; }; type LogEntry = { seq: number; at?: string; message?: string; }; type LogsPayload = { total_entries?: number; latest_seq?: number; entries?: LogEntry[]; }; type MessageState = { text: string; tone: Tone; }; type ProfileFormState = { name: string; listen_host: string; listen_port: string; upstream_base_url: string; auth_mode: AuthMode; auth_env: string; auth_file: string; manual_secret: string; manual_secret_file: string; manual_secret_configured: boolean; auth_json_path: string; auth_json_key: string; request_history_limit: string; model_remap: string; reasoning_match_mode: ReasoningMatchMode; reasoning_equals: string; retryable_status_codes: string; retryable_error_messages: string; upstream_fetch_retry_attempts: string; upstream_fetch_retry_backoff_ms: string; endpoints: string; }; type ImageProfileFormState = { name: string; base_url: string; auth_mode: AuthMode; auth_env: string; auth_file: string; manual_secret: string; manual_secret_file: string; manual_secret_configured: boolean; auth_json_path: string; auth_json_key: string; }; type RuleFormState = { reasoning_match_mode: ReasoningMatchMode; reasoning_equals: string; retryable_status_codes: string; retryable_error_messages: string; upstream_fetch_retry_attempts: string; upstream_fetch_retry_backoff_ms: string; endpoints: string; non_stream_status_code: string; log_match: boolean; }; const api = { status: "/__codex_retry_gateway/api/status", config: "/__codex_retry_gateway/api/config", logs: "/__codex_retry_gateway/api/logs", requests: "/__codex_retry_gateway/api/requests", threadRules: "/__codex_retry_gateway/api/thread-rules", profiles: "/__codex_retry_gateway/api/profiles", profileProbe: "/__codex_retry_gateway/api/profiles/probe", profileSwitch: "/__codex_retry_gateway/api/profiles/switch", imageProfiles: "/__codex_retry_gateway/api/image-profiles", imageProfileProbe: "/__codex_retry_gateway/api/image-profiles/probe", imageProfileSwitch: "/__codex_retry_gateway/api/image-profiles/switch", restore: "/__codex_retry_gateway/api/restore", }; const ACCESS_KEY_STORAGE_KEY = "codex_retry_gateway_access_key"; const REQUEST_PAGE_SIZE = 20; const LOG_PAGE_SIZE = 200; const zhNumberFormatter = new Intl.NumberFormat("zh-CN"); const zhTimestampFormatter = new Intl.DateTimeFormat("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", }); type ProfileProbePayload = { ok: boolean; profile?: string; image_profile?: string; upstream_base_url?: string; image_base_url?: string; auth_mode?: string; auth_source?: string; authorization_configured?: boolean; model_remap?: string; probes?: Array<{ kind?: string; target?: string; status?: number; requested_model?: string; forwarded_model?: string; content_type?: string; body_preview?: string; }>; }; const pageCopy: Record = { overview: { title: "概览", subtitle: "当前 gateway 运行态,以及基于持久请求记录回灌的累计统计。", index: "01", }, requests: { title: "请求", subtitle: "每次请求的时间戳、状态、token usage 和命中情况。", index: "02", }, profiles: { title: "Profiles", subtitle: "文本和图片上游分别保存、探测与热切换,互不改写对方配置。", index: "03", }, rules: { title: "规则", subtitle: "热更新当前拦截规则;profile 默认规则请在 Profiles 页保存。", index: "04", }, logs: { title: "日志", subtitle: "当前进程的实时日志,不含请求正文或响应正文。", index: "05", }, }; const defaultProfileForm: ProfileFormState = { name: "", listen_host: "100.115.235.115", listen_port: "4610", upstream_base_url: "", auth_mode: "passthrough", auth_env: "CODEX_RETRY_GATEWAY_UPSTREAM_API_KEY", auth_file: "", manual_secret: "", manual_secret_file: "", manual_secret_configured: false, auth_json_path: "", auth_json_key: "OPENAI_API_KEY", request_history_limit: "0", model_remap: "", reasoning_match_mode: "formula_518n_minus_2", reasoning_equals: "516,1034,1552", retryable_status_codes: "429,503", retryable_error_messages: "Selected model is at capacity. Please try a different model.\nstream disconnected before completion: Concurrency limit exceeded for account, please retry later", upstream_fetch_retry_attempts: "5", upstream_fetch_retry_backoff_ms: "350", endpoints: "/responses\n/chat/completions\n/v1/responses\n/v1/chat/completions", }; const defaultImageProfileForm: ImageProfileFormState = { name: "", base_url: "", auth_mode: "fixed_bearer", auth_env: "CODEX_RETRY_GATEWAY_IMAGE_API_KEY", auth_file: "", manual_secret: "", manual_secret_file: "", manual_secret_configured: false, auth_json_path: "", auth_json_key: "OPENAI_API_KEY", }; function numberFormat(value: unknown) { return typeof value === "number" && Number.isFinite(value) ? zhNumberFormatter.format(value) : "-"; } function timestamp(value?: string | null) { if (!value) { return "-"; } const date = new Date(value); return Number.isNaN(date.getTime()) ? value : zhTimestampFormatter.format(date); } function durationSeconds(value?: number | null) { return typeof value === "number" && Number.isFinite(value) ? `${(value / 1000).toFixed(2)} s` : "-"; } function compactDurationSeconds(value?: number | null) { if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) { return "?"; } const seconds = value / 1000; if (seconds >= 100) { return `${seconds.toFixed(0)}s`; } return `${seconds.toFixed(1).replace(/\\.0$/, "")}s`; } function secondsSince(startedAt: string | null | undefined, updatedAt: string | null | undefined) { if (!startedAt || !updatedAt) { return "-"; } const startedMs = new Date(startedAt).getTime(); const updatedMs = new Date(updatedAt).getTime(); if (Number.isNaN(startedMs) || Number.isNaN(updatedMs)) { return "-"; } return `${Math.max(0, (updatedMs - startedMs) / 1000).toFixed(1)} s`; } function bytesFormat(value?: number | null) { if (typeof value !== "number" || !Number.isFinite(value)) { return "-"; } if (value < 1024) { return `${value} B`; } if (value < 1024 * 1024) { return `${(value / 1024).toFixed(1)} KB`; } return `${(value / 1024 / 1024).toFixed(2)} MB`; } function lifecycleTone(value?: string | null) { if (value === "finish") { return ""; } if (value === "receive_first") { return "warn"; } return "pending"; } function percent(value?: number) { return typeof value === "number" && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : "0.00%"; } function effectiveInputTokens(inputTokens?: number | null, cachedTokens?: number | null) { if (typeof inputTokens !== "number" || !Number.isFinite(inputTokens)) { return null; } const cached = typeof cachedTokens === "number" && Number.isFinite(cachedTokens) ? cachedTokens : 0; return Math.max(0, inputTokens - cached); } function cachedRatio(inputTokens?: number | null, cachedTokens?: number | null) { if (typeof inputTokens !== "number" || !Number.isFinite(inputTokens) || inputTokens <= 0) { return null; } const cached = typeof cachedTokens === "number" && Number.isFinite(cachedTokens) ? cachedTokens : 0; return Math.max(0, Math.min(1, cached / inputTokens)); } function requestPrimaryId(entry: RequestEntry) { return entry.response_id || entry.request_id || "-"; } function hasReasoningRetryInfo(entry: RequestEntry) { return Boolean( entry.reasoning_retry_enabled || entry.reasoning_retry_thread_mode || entry.reasoning_retry_query_count || entry.reasoning_retry_round_count || entry.reasoning_retry_stop_reason, ); } function retryRoundWidthText(entry: RequestEntry) { const round = entry.reasoning_retry_current_round || entry.reasoning_retry_round_count || 0; const width = entry.reasoning_retry_current_width || 0; if (!round) { return "-"; } return width ? `${numberFormat(round)}(${numberFormat(width)})` : numberFormat(round); } function retryFirstLabel(first: NonNullable[number], fallbackRound?: number | null) { const round = first.round ?? fallbackRound ?? null; const slot = first.slot ?? null; if (typeof round === "number" && Number.isInteger(round)) { if (typeof slot === "number" && Number.isInteger(slot) && slot > 1) { return `${numberFormat(round)}-${numberFormat(slot)}`; } return numberFormat(round); } if (typeof slot === "number" && Number.isInteger(slot)) { return `#${numberFormat(slot)}`; } return "?"; } function retryFirstText( first: NonNullable[number], fallbackRound?: number | null, ) { const delay = durationSeconds(first.first_response_delay_ms); const outcome = first.outcome || "pending"; const reasoning = typeof first.reasoning_tokens === "number" ? ` r${numberFormat(first.reasoning_tokens)}` : ""; const status = typeof first.status_code === "number" ? ` ${first.status_code}` : ""; return `${retryFirstLabel(first, fallbackRound)} ${delay} ${outcome}${status}${reasoning}`; } function retryFirstCompactText( first: NonNullable[number], ) { return compactDurationSeconds(first.first_response_delay_ms); } function formatRetryStopReason(value?: string | null) { const reason = `${value || ""}`.trim(); if (!reason) { return "-"; } const labels: Record = { success: "成功", missing_thread_id: "缺少 thread_id", thread_guard_disabled: "thread 已关闭拦截", completed_without_retry: "未触发调度", reasoning_guard: "reasoning 命中", retryable_upstream_error: "上游可重试错误", fatal: "致命错误", exhausted_without_winner: "无赢家", }; return labels[reason] || reason; } function formatRetryThreadMode(value?: string | null) { const mode = `${value || ""}`.trim(); if (!mode || mode === "disabled") { return "未启用"; } if (mode === "thread_guard_disabled") { return "thread 已关闭拦截"; } if (mode === "thread_id") { return "按 thread_id"; } if (mode === "missing_thread_id") { return "缺少 thread_id"; } return mode; } function sortedReasoningCounts(value?: Record | null) { return Object.entries(value || {}).sort((left, right) => { const countDelta = Number(right[1] || 0) - Number(left[1] || 0); if (countDelta !== 0) { return countDelta; } return Number(left[0] || 0) - Number(right[0] || 0); }); } function formatThreadGuardOverride(value?: string | null) { const override = `${value || ""}`.trim(); if (override === "disabled") { return "已关闭"; } if (override === "enabled") { return "强制开启"; } return "默认开启"; } function threadGuardBadgeTone(value?: string | null) { const override = `${value || ""}`.trim(); if (override === "disabled") { return "warn"; } if (override === "enabled") { return "success"; } return ""; } function splitList(value: string) { return value .split(/[\s,]+/) .map((item) => item.trim()) .filter(Boolean); } function splitLines(value: string) { return value .split(/\r?\n/) .map((item) => item.trim()) .filter(Boolean); } function normalizeReasoningMode(value: unknown): ReasoningMatchMode { return value === "manual" ? "manual" : "formula_518n_minus_2"; } function formatReasoningMode(mode: ReasoningMatchMode) { return mode === "manual" ? "manual" : "518n-2"; } function formatReasoningRule(mode: ReasoningMatchMode, reasoningEquals?: string) { if (mode === "manual") { return reasoningEquals || "-"; } return "516, 1034, 1552, ..."; } async function fetchJson(url: string, options?: RequestInit): Promise { const headers = new Headers(options?.headers || {}); const accessKey = window.localStorage.getItem(ACCESS_KEY_STORAGE_KEY)?.trim(); if (accessKey && !headers.has("x-codex-retry-gateway-key")) { headers.set("x-codex-retry-gateway-key", accessKey); } const response = await fetch(url, { cache: "no-store", ...options, headers }); const payload = await response.json(); if (!response.ok) { throw new Error(payload?.error?.message || "请求失败"); } return payload as T; } function profileFormFromStatus(status: StatusPayload | null): ProfileFormState { const config = status?.config || {}; return { ...defaultProfileForm, listen_host: config.listen_host || defaultProfileForm.listen_host, listen_port: String(config.listen_port || defaultProfileForm.listen_port), upstream_base_url: config.upstream_base_url || "", auth_mode: (config.upstream_auth_mode as ProfileFormState["auth_mode"]) || "passthrough", auth_env: config.upstream_auth_env || defaultProfileForm.auth_env, manual_secret: "", manual_secret_file: "", manual_secret_configured: false, auth_json_key: config.upstream_auth_json_key || defaultProfileForm.auth_json_key, request_history_limit: String(config.request_history_limit ?? defaultProfileForm.request_history_limit), model_remap: config.model_remap || "", reasoning_match_mode: normalizeReasoningMode(config.reasoning_match_mode), reasoning_equals: Array.isArray(config.reasoning_equals) ? config.reasoning_equals.join(",") : defaultProfileForm.reasoning_equals, retryable_status_codes: Array.isArray(config.retryable_status_codes) ? config.retryable_status_codes.join(",") : defaultProfileForm.retryable_status_codes, retryable_error_messages: Array.isArray(config.retryable_error_messages) ? config.retryable_error_messages.join("\n") : defaultProfileForm.retryable_error_messages, upstream_fetch_retry_attempts: String( config.upstream_fetch_retry_attempts ?? defaultProfileForm.upstream_fetch_retry_attempts, ), upstream_fetch_retry_backoff_ms: String( config.upstream_fetch_retry_backoff_ms ?? defaultProfileForm.upstream_fetch_retry_backoff_ms, ), endpoints: Array.isArray(config.endpoints) ? config.endpoints.join("\n") : defaultProfileForm.endpoints, }; } function profileFormFromProfile(profile: Profile): ProfileFormState { const form = profile.form || {}; return { ...defaultProfileForm, name: profile.name, listen_host: form.listen_host || "", listen_port: form.listen_port || "", upstream_base_url: form.upstream_base_url || "", auth_mode: (form.auth_mode as ProfileFormState["auth_mode"]) || "passthrough", auth_env: form.auth_env || "", auth_file: form.auth_file || "", manual_secret: "", manual_secret_file: form.manual_secret_file || "", manual_secret_configured: Boolean(form.manual_secret_configured), auth_json_path: form.auth_json_path || "", auth_json_key: form.auth_json_key || "OPENAI_API_KEY", request_history_limit: form.request_history_limit || defaultProfileForm.request_history_limit, model_remap: form.model_remap || "", reasoning_match_mode: normalizeReasoningMode(form.reasoning_match_mode), reasoning_equals: form.reasoning_equals || defaultProfileForm.reasoning_equals, retryable_status_codes: form.retryable_status_codes || defaultProfileForm.retryable_status_codes, retryable_error_messages: Array.isArray(form.retryable_error_messages) ? form.retryable_error_messages.join("\n") : defaultProfileForm.retryable_error_messages, upstream_fetch_retry_attempts: form.upstream_fetch_retry_attempts || defaultProfileForm.upstream_fetch_retry_attempts, upstream_fetch_retry_backoff_ms: form.upstream_fetch_retry_backoff_ms || defaultProfileForm.upstream_fetch_retry_backoff_ms, endpoints: Array.isArray(form.endpoints) ? form.endpoints.join("\n") : "", }; } function imageProfileFormFromStatus(status: StatusPayload | null): ImageProfileFormState { const config = status?.config || {}; return { ...defaultImageProfileForm, name: config.image_profile_name || "", base_url: config.image_base_url || "", auth_mode: (config.image_auth_mode as AuthMode) || defaultImageProfileForm.auth_mode, auth_env: config.image_auth_env || defaultImageProfileForm.auth_env, auth_json_key: config.image_auth_json_key || defaultImageProfileForm.auth_json_key, }; } function imageProfileFormFromProfile(profile: ImageProfile): ImageProfileFormState { const form = profile.form || {}; return { ...defaultImageProfileForm, name: profile.name, base_url: form.base_url || "", auth_mode: (form.auth_mode as AuthMode) || defaultImageProfileForm.auth_mode, auth_env: form.auth_env || defaultImageProfileForm.auth_env, auth_file: form.auth_file || "", manual_secret: "", manual_secret_file: form.manual_secret_file || "", manual_secret_configured: Boolean(form.manual_secret_configured), auth_json_path: form.auth_json_path || "", auth_json_key: form.auth_json_key || defaultImageProfileForm.auth_json_key, }; } function ruleFormFromStatus(status: StatusPayload | null): RuleFormState { const config = status?.config || {}; return { reasoning_match_mode: normalizeReasoningMode(config.reasoning_match_mode), reasoning_equals: Array.isArray(config.reasoning_equals) ? config.reasoning_equals.join(", ") : "", retryable_status_codes: Array.isArray(config.retryable_status_codes) ? config.retryable_status_codes.join(", ") : defaultProfileForm.retryable_status_codes, retryable_error_messages: Array.isArray(config.retryable_error_messages) ? config.retryable_error_messages.join("\n") : defaultProfileForm.retryable_error_messages, upstream_fetch_retry_attempts: String( config.upstream_fetch_retry_attempts ?? defaultProfileForm.upstream_fetch_retry_attempts, ), upstream_fetch_retry_backoff_ms: String( config.upstream_fetch_retry_backoff_ms ?? defaultProfileForm.upstream_fetch_retry_backoff_ms, ), endpoints: Array.isArray(config.endpoints) ? config.endpoints.join("\n") : "", non_stream_status_code: String(config.non_stream_status_code || 502), log_match: Boolean(config.log_match), }; } export default function App() { useEffect(() => { const url = new URL(window.location.href); const accessKey = url.searchParams.get("key")?.trim(); if (!accessKey) { return; } window.localStorage.setItem(ACCESS_KEY_STORAGE_KEY, accessKey); url.searchParams.delete("key"); window.history.replaceState({}, "", url.toString()); }, []); const [page, setPage] = useState(() => { const hash = window.location.hash.replace("#", "") as PageKey; return pageCopy[hash] ? hash : "overview"; }); const [status, setStatus] = useState(null); const [requests, setRequests] = useState([]); const [requestsTotal, setRequestsTotal] = useState(0); const [requestsMeta, setRequestsMeta] = useState("正在读取请求记录..."); const [threadRules, setThreadRules] = useState([]); const [threadRulesMeta, setThreadRulesMeta] = useState("正在读取 thread 规则..."); const [profiles, setProfiles] = useState([]); const [profilesMeta, setProfilesMeta] = useState("正在读取 profiles..."); const [imageProfiles, setImageProfiles] = useState([]); const [imageProfilesMeta, setImageProfilesMeta] = useState("正在读取图片 profiles..."); const [logs, setLogs] = useState("正在读取日志..."); const [logsMeta, setLogsMeta] = useState("正在读取日志..."); const [latestLogSeq, setLatestLogSeq] = useState(0); const [requestQuery, setRequestQuery] = useState(""); const [requestFilter, setRequestFilter] = useState("all"); const [requestLimit, setRequestLimit] = useState(REQUEST_PAGE_SIZE); const [ruleForm, setRuleForm] = useState(ruleFormFromStatus(null)); const [profileForm, setProfileForm] = useState(defaultProfileForm); const [imageProfileForm, setImageProfileForm] = useState(defaultImageProfileForm); const [ruleMessage, setRuleMessage] = useState({ text: "", tone: "" }); const [threadRuleMessage, setThreadRuleMessage] = useState({ text: "", tone: "" }); const [profileMessage, setProfileMessage] = useState({ text: "", tone: "" }); const [profileProbeResult, setProfileProbeResult] = useState(null); const [imageProfileMessage, setImageProfileMessage] = useState({ text: "", tone: "" }); const [imageProfileProbeResult, setImageProfileProbeResult] = useState(null); const [probingProfile, setProbingProfile] = useState(""); const [deletingProfile, setDeletingProfile] = useState(""); const [switchingTo, setSwitchingTo] = useState(""); const [probingImageProfile, setProbingImageProfile] = useState(""); const [deletingImageProfile, setDeletingImageProfile] = useState(""); const [switchingImageTo, setSwitchingImageTo] = useState(""); const [restoreRequested, setRestoreRequested] = useState(false); const [shouldSyncProfileFormToActive, setShouldSyncProfileFormToActive] = useState(true); const [shouldSyncImageProfileFormToActive, setShouldSyncImageProfileFormToActive] = useState(true); const [threadRuleBusyThreadId, setThreadRuleBusyThreadId] = useState(""); const metrics = status?.metrics || {}; const tokens = metrics.token_totals || {}; const currentPage = pageCopy[page]; const effectiveInputTotal = effectiveInputTokens(tokens.input_tokens, tokens.cached_tokens); const cachedTotalRatio = cachedRatio(tokens.input_tokens, tokens.cached_tokens); const reasoningChips = Object.entries(metrics.observed_reasoning_counts || {}).sort( (left, right) => Number(right[1]) - Number(left[1]), ); async function loadStatus(refreshRuleForm = false) { const payload = await fetchJson(api.status); startTransition(() => { setStatus(payload); if (refreshRuleForm) { setRuleForm(ruleFormFromStatus(payload)); setProfileForm(profileFormFromStatus(payload)); setImageProfileForm(imageProfileFormFromStatus(payload)); } }); } async function loadRequests(limitOverride = requestLimit) { const url = new URL(api.requests, window.location.origin); url.searchParams.set("limit", String(limitOverride)); if (requestQuery.trim()) { url.searchParams.set("query", requestQuery.trim()); } if (requestFilter !== "all") { url.searchParams.set("filter", requestFilter); } const payload = await fetchJson(url.toString()); const entries = payload.entries || []; startTransition(() => { setRequests(entries); setRequestsTotal(payload.total_entries ?? entries.length); setRequestsMeta( `查询命中 ${payload.total_entries ?? entries.length} 条,当前展示最近 ${entries.length} 条,最新序号 ${payload.latest_seq ?? 0}。`, ); }); } async function loadThreadRules() { const payload = await fetchJson(api.threadRules); const rules = payload.rules || []; startTransition(() => { setThreadRules(rules); setThreadRulesMeta(`当前覆盖 ${rules.length} 个 thread;文件:${payload.thread_rules_path || "-"}`); }); } async function loadProfiles() { const [payload, imagePayload] = await Promise.all([ fetchJson(api.profiles), fetchJson(api.imageProfiles), ]); const items = payload.profiles || []; const imageItems = imagePayload.image_profiles || []; startTransition(() => { setProfiles(items); setProfilesMeta(`目录:${payload.profiles_dir || "-"};当前运行:${payload.active_profile || "-"}。`); setImageProfiles(imageItems); setImageProfilesMeta(`目录:${imagePayload.image_profiles_dir || "-"};当前运行:${imagePayload.active_image_profile || "未配置"}。`); }); } async function loadLogs(incremental = false) { const url = new URL(api.logs, window.location.origin); if (incremental && latestLogSeq > 0) { url.searchParams.set("since_seq", String(latestLogSeq)); } else { url.searchParams.set("limit", String(LOG_PAGE_SIZE)); } const payload = await fetchJson(url.toString()); const rendered = (payload.entries || []) .map((entry) => `${entry.at || "-"} ${entry.message || ""}`) .join("\n"); startTransition(() => { setLogs((current) => { if (!incremental || latestLogSeq === 0) { return rendered || "当前还没有日志。"; } return rendered ? `${current.trim()}\n${rendered}` : current; }); setLogsMeta(`已载入 ${payload.total_entries ?? payload.entries?.length ?? 0} 条日志,最新序号 ${payload.latest_seq ?? latestLogSeq}。`); if (typeof payload.latest_seq === "number") { setLatestLogSeq(payload.latest_seq); } }); } async function loadPageData(targetPage: PageKey, { incrementalLogs = true } = {}) { if (targetPage === "requests") { await loadRequests(); return; } if (targetPage === "rules") { await loadThreadRules(); return; } if (targetPage === "profiles") { await loadProfiles(); return; } if (targetPage === "logs") { await loadLogs(incrementalLogs && latestLogSeq > 0); } } async function refreshLiveData(targetPage: PageKey = page) { if (restoreRequested || switchingTo || switchingImageTo) { return; } const tasks: Array> = [loadStatus(false)]; if (targetPage !== "overview") { tasks.push(loadPageData(targetPage, { incrementalLogs: true })); } await Promise.all(tasks); } useEffect(() => { window.location.hash = page; }, [page]); useEffect(() => { if (page === "profiles") { setShouldSyncProfileFormToActive(true); setShouldSyncImageProfileFormToActive(true); } }, [page]); useEffect(() => { const onHashChange = () => { const next = window.location.hash.replace("#", "") as PageKey; if (pageCopy[next]) { setPage(next); } }; window.addEventListener("hashchange", onHashChange); return () => window.removeEventListener("hashchange", onHashChange); }, []); useEffect(() => { loadStatus(true).catch((error) => { setRuleMessage({ text: error?.message || String(error), tone: "error" }); }); }, []); useEffect(() => { const timer = window.setInterval(() => { loadStatus(false).catch((error) => { setRuleMessage({ text: error?.message || String(error), tone: "error" }); }); }, 10000); return () => window.clearInterval(timer); }, [restoreRequested, switchingTo, switchingImageTo]); useEffect(() => { if (page !== "requests" && page !== "logs" && page !== "rules") { return; } const timer = window.setInterval(() => { loadPageData(page, { incrementalLogs: true }).catch((error) => { if (page === "rules") { setThreadRuleMessage({ text: error?.message || String(error), tone: "error" }); return; } setRuleMessage({ text: error?.message || String(error), tone: "error" }); }); }, 2500); return () => window.clearInterval(timer); }, [page, requestQuery, requestFilter, latestLogSeq, requestLimit]); useEffect(() => { if (page === "overview" || page === "requests") { return; } loadPageData(page, { incrementalLogs: false }).catch((error) => { if (page === "rules") { setThreadRuleMessage({ text: error?.message || String(error), tone: "error" }); return; } setRuleMessage({ text: error?.message || String(error), tone: "error" }); }); }, [page]); useEffect(() => { if (page !== "profiles" || !shouldSyncProfileFormToActive) { return; } const activeProfile = profiles.find((profile) => profile.active); if (!activeProfile) { return; } setProfileForm(profileFormFromProfile(activeProfile)); setProfileMessage({ text: "", tone: "" }); setShouldSyncProfileFormToActive(false); }, [page, profiles, shouldSyncProfileFormToActive]); useEffect(() => { if (page !== "profiles" || !shouldSyncImageProfileFormToActive) { return; } const activeProfile = imageProfiles.find((profile) => profile.active); if (!activeProfile) { return; } setImageProfileForm(imageProfileFormFromProfile(activeProfile)); setImageProfileMessage({ text: "", tone: "" }); setShouldSyncImageProfileFormToActive(false); }, [page, imageProfiles, shouldSyncImageProfileFormToActive]); async function saveRules(event: FormEvent) { event.preventDefault(); setRuleMessage({ text: "正在保存配置...", tone: "" }); try { const payload = await fetchJson(api.config, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ reasoning_match_mode: ruleForm.reasoning_match_mode, reasoning_equals: splitList(ruleForm.reasoning_equals) .map((value) => Number.parseInt(value, 10)) .filter((value) => Number.isInteger(value)), retryable_status_codes: splitList(ruleForm.retryable_status_codes) .map((value) => Number.parseInt(value, 10)) .filter((value) => Number.isInteger(value)), retryable_error_messages: splitLines(ruleForm.retryable_error_messages), upstream_fetch_retry_attempts: Number.parseInt(ruleForm.upstream_fetch_retry_attempts, 10), upstream_fetch_retry_backoff_ms: Number.parseInt(ruleForm.upstream_fetch_retry_backoff_ms, 10), endpoints: splitLines(ruleForm.endpoints), non_stream_status_code: Number.parseInt(ruleForm.non_stream_status_code, 10), log_match: ruleForm.log_match, }), }); setStatus(payload); setRuleForm(ruleFormFromStatus(payload)); setRuleMessage({ text: "配置已保存,并已对当前 gateway 立即生效。", tone: "success" }); } catch (error) { setRuleMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } } async function updateThreadRule(threadId: string, reasoningInterceptEnabled: boolean) { if (!threadId.trim()) { return; } setThreadRuleBusyThreadId(threadId); setThreadRuleMessage({ text: reasoningInterceptEnabled ? `正在为 ${threadId} 开启拦截...` : `正在为 ${threadId} 关闭拦截...`, tone: "", }); try { const payload = await fetchJson(api.threadRules, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ thread_id: threadId, reasoning_intercept_enabled: reasoningInterceptEnabled, }), }); setThreadRules(payload.rules || []); setThreadRulesMeta(`当前覆盖 ${(payload.rules || []).length} 个 thread;文件:${payload.thread_rules_path || "-"}`); setThreadRuleMessage({ text: payload.message || (reasoningInterceptEnabled ? "thread 已开启拦截" : "thread 已关闭拦截"), tone: "success", }); await Promise.all([loadStatus(false), loadRequests(requestLimit), loadThreadRules()]); } catch (error) { setThreadRuleMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } finally { setThreadRuleBusyThreadId(""); } } async function restoreThreadRule(threadId: string) { if (!threadId.trim()) { return; } setThreadRuleBusyThreadId(threadId); setThreadRuleMessage({ text: `正在恢复 ${threadId} 的默认策略...`, tone: "" }); try { const payload = await fetchJson(`${api.threadRules}/${encodeURIComponent(threadId)}`, { method: "DELETE", }); setThreadRules(payload.rules || []); setThreadRulesMeta(`当前覆盖 ${(payload.rules || []).length} 个 thread;文件:${payload.thread_rules_path || "-"}`); setThreadRuleMessage({ text: payload.message || "thread 已恢复默认拦截策略", tone: "success" }); await Promise.all([loadStatus(false), loadRequests(requestLimit), loadThreadRules()]); } catch (error) { setThreadRuleMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } finally { setThreadRuleBusyThreadId(""); } } useEffect(() => { setRequestLimit(REQUEST_PAGE_SIZE); }, [requestQuery, requestFilter]); useEffect(() => { if (page !== "requests") { return; } const timer = window.setTimeout(() => { loadRequests(requestLimit).catch((error) => { setRuleMessage({ text: error?.message || String(error), tone: "error" }); }); }, 180); return () => window.clearTimeout(timer); }, [page, requestQuery, requestFilter, requestLimit]); async function saveProfile(event: FormEvent) { event.preventDefault(); setProfileMessage({ text: "正在保存 profile...", tone: "" }); try { const payload = await fetchJson(api.profiles, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: profileForm.name, listen_host: profileForm.listen_host, listen_port: Number.parseInt(profileForm.listen_port, 10), upstream_base_url: profileForm.upstream_base_url, auth_mode: profileForm.auth_mode, auth_env: profileForm.auth_env, auth_file: profileForm.auth_file, manual_secret: profileForm.manual_secret, manual_secret_file: profileForm.manual_secret_file, manual_secret_configured: profileForm.manual_secret_configured, auth_json_path: profileForm.auth_json_path, auth_json_key: profileForm.auth_json_key, request_history_limit: Number.parseInt(profileForm.request_history_limit, 10), model_remap: profileForm.model_remap, reasoning_match_mode: profileForm.reasoning_match_mode, reasoning_equals: splitList(profileForm.reasoning_equals), retryable_status_codes: splitList(profileForm.retryable_status_codes), retryable_error_messages: splitLines(profileForm.retryable_error_messages), upstream_fetch_retry_attempts: Number.parseInt(profileForm.upstream_fetch_retry_attempts, 10), upstream_fetch_retry_backoff_ms: Number.parseInt(profileForm.upstream_fetch_retry_backoff_ms, 10), endpoints: splitLines(profileForm.endpoints), }), }); setProfiles(payload.profiles || []); setProfilesMeta(`目录:${payload.profiles_dir || "-"};当前运行:${payload.active_profile || "-"}。`); setProfileForm((current) => ({ ...current, manual_secret: "", manual_secret_configured: current.auth_mode === "manual_bearer", })); setProfileMessage({ text: payload.applied_profile ? "profile 已保存,并已对当前运行实例后台热应用。" : "profile 已保存。需要运行它时,点击左侧卡片里的“切换”。", tone: "success", }); } catch (error) { setProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } } function editProfile(profile: Profile) { setShouldSyncProfileFormToActive(false); setProfileForm(profileFormFromProfile(profile)); setProfileMessage({ text: "编辑后保存 profile env;如果保存的是当前运行 profile,后端会直接后台热应用。", tone: "" }); } async function switchProfile(profile: Profile) { if (profile.active) { return; } if (!window.confirm(`切换到 profile "${profile.name}" 会尝试后台热切换,不重启当前 gateway。确定继续吗?`)) { return; } setSwitchingTo(profile.name); try { await fetchJson(api.profileSwitch, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ profile: profile.name }), }); waitForProfile(profile.name); } catch (error) { setSwitchingTo(""); setProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } } async function probeProfile(profile: Profile) { setProbingProfile(profile.name); setProfileMessage({ text: `正在探测 profile ${profile.name}...`, tone: "" }); try { const payload = await fetchJson(api.profileProbe, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ profile: profile.name, model: "gpt-5.5-fast", input: "ping", }), }); setProfileProbeResult(payload); setProfileMessage({ text: `profile ${profile.name} 探针已完成,不影响当前运行实例。`, tone: "success" }); } catch (error) { setProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } finally { setProbingProfile(""); } } async function removeProfile(profile: Profile) { if (profile.active) { setProfileMessage({ text: "当前运行的 profile 不能直接删除;请先切换到其他 profile。", tone: "error" }); return; } if (!window.confirm(`删除 profile "${profile.name}" 会移除对应 env 文件。确定继续吗?`)) { return; } setDeletingProfile(profile.name); try { const payload = await fetchJson(`${api.profiles}/${encodeURIComponent(profile.name)}`, { method: "DELETE", }); setProfiles(payload.profiles || []); setProfilesMeta(`目录:${payload.profiles_dir || "-"};当前运行:${payload.active_profile || "-"}。`); if (profileForm.name === profile.name) { setProfileForm(defaultProfileForm); } if (profileProbeResult?.profile === profile.name) { setProfileProbeResult(null); } setProfileMessage({ text: `profile ${profile.name} 已删除。`, tone: "success" }); } catch (error) { setProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } finally { setDeletingProfile(""); } } async function saveImageProfile(event: FormEvent) { event.preventDefault(); setImageProfileMessage({ text: "正在保存图片 profile...", tone: "" }); try { const payload = await fetchJson(api.imageProfiles, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: imageProfileForm.name, base_url: imageProfileForm.base_url, auth_mode: imageProfileForm.auth_mode, auth_env: imageProfileForm.auth_env, auth_file: imageProfileForm.auth_file, manual_secret: imageProfileForm.manual_secret, manual_secret_file: imageProfileForm.manual_secret_file, manual_secret_configured: imageProfileForm.manual_secret_configured, auth_json_path: imageProfileForm.auth_json_path, auth_json_key: imageProfileForm.auth_json_key, }), }); setImageProfiles(payload.image_profiles || []); setImageProfilesMeta(`目录:${payload.image_profiles_dir || "-"};当前运行:${payload.active_image_profile || "未配置"}。`); setImageProfileForm((current) => ({ ...current, manual_secret: "", manual_secret_configured: current.auth_mode === "manual_bearer", })); setImageProfileMessage({ text: payload.applied_image_profile ? "图片 profile 已保存,并已对当前运行实例后台热应用。" : "图片 profile 已保存。需要运行它时,点击左侧卡片里的“切换”。", tone: "success", }); } catch (error) { setImageProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } } function editImageProfile(profile: ImageProfile) { setShouldSyncImageProfileFormToActive(false); setImageProfileForm(imageProfileFormFromProfile(profile)); setImageProfileMessage({ text: "编辑后保存图片 profile env;如果保存的是当前运行 profile,后端会直接后台热应用。", tone: "" }); } async function switchImageProfile(profile: ImageProfile) { if (profile.active) { return; } if (!window.confirm(`切换到图片 profile "${profile.name}" 会立即改写 /images/* 的上游,不重启 gateway。确定继续吗?`)) { return; } setSwitchingImageTo(profile.name); try { await fetchJson(api.imageProfileSwitch, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ profile: profile.name }), }); waitForImageProfile(profile.name); } catch (error) { setSwitchingImageTo(""); setImageProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } } async function probeImageProfile(profile: ImageProfile) { setProbingImageProfile(profile.name); setImageProfileMessage({ text: `正在探测图片 profile ${profile.name}...`, tone: "" }); try { const payload = await fetchJson(api.imageProfileProbe, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ profile: profile.name }), }); setImageProfileProbeResult(payload); setImageProfileMessage({ text: `图片 profile ${profile.name} 探针已完成,不影响当前运行实例。`, tone: "success" }); } catch (error) { setImageProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } finally { setProbingImageProfile(""); } } async function removeImageProfile(profile: ImageProfile) { if (profile.active) { setImageProfileMessage({ text: "当前运行的图片 profile 不能直接删除;请先切换到其他图片 profile。", tone: "error" }); return; } if (!window.confirm(`删除图片 profile "${profile.name}" 会移除对应 env 文件。确定继续吗?`)) { return; } setDeletingImageProfile(profile.name); try { const payload = await fetchJson(`${api.imageProfiles}/${encodeURIComponent(profile.name)}`, { method: "DELETE", }); setImageProfiles(payload.image_profiles || []); setImageProfilesMeta(`目录:${payload.image_profiles_dir || "-"};当前运行:${payload.active_image_profile || "未配置"}。`); if (imageProfileForm.name === profile.name) { setImageProfileForm(defaultImageProfileForm); } if (imageProfileProbeResult?.image_profile === profile.name) { setImageProfileProbeResult(null); } setImageProfileMessage({ text: `图片 profile ${profile.name} 已删除。`, tone: "success" }); } catch (error) { setImageProfileMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } finally { setDeletingImageProfile(""); } } function waitForProfile(profileName: string) { const deadline = Date.now() + 12000; const tick = async () => { if (Date.now() > deadline) { setSwitchingTo(""); setProfileMessage({ text: "热切换已提交,但暂时没有看到当前实例切到目标 profile。", tone: "error" }); return; } try { const payload = await fetchJson(api.status); if (payload.config?.profile_name === profileName) { setSwitchingTo(""); setShouldSyncProfileFormToActive(true); Promise.all([loadStatus(true), loadProfiles()]).catch(() => {}); return; } } catch { // keep polling } window.setTimeout(tick, 500); }; window.setTimeout(tick, 300); } function waitForImageProfile(profileName: string) { const deadline = Date.now() + 12000; const tick = async () => { if (Date.now() > deadline) { setSwitchingImageTo(""); setImageProfileMessage({ text: "图片热切换已提交,但暂时没有看到当前实例切到目标 profile。", tone: "error" }); return; } try { const payload = await fetchJson(api.status); if (payload.config?.image_profile_name === profileName) { setSwitchingImageTo(""); setShouldSyncImageProfileFormToActive(true); Promise.all([loadStatus(true), loadProfiles()]).catch(() => {}); return; } } catch { // keep polling } window.setTimeout(tick, 500); }; window.setTimeout(tick, 300); } async function restoreConfig() { if (!window.confirm("恢复后会关闭当前 gateway,并把 Codex 配置切回原上游。确定继续吗?")) { return; } setRestoreRequested(true); setRuleMessage({ text: "正在触发恢复,页面很快会失联...", tone: "" }); try { await fetchJson(api.restore, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({}), }); setRuleMessage({ text: "恢复脚本已启动,等待 gateway 关闭。", tone: "success" }); } catch (error) { setRestoreRequested(false); setRuleMessage({ text: error instanceof Error ? error.message : String(error), tone: "error" }); } } return ( <>

{currentPage.title}

{currentPage.subtitle}

status api
{page === "overview" && (
{reasoningChips.length === 0 ? ( 还没有 reasoning 观测 ) : ( <> {reasoningChips.map(([reasoning, count]) => ( reasoning {reasoning}: {count} ))} {(metrics.observed_reasoning_counts_omitted || 0) > 0 ? ( 其余 {metrics.observed_reasoning_counts_omitted} 项未展开 ) : null} )}
)} {page === "requests" && (
setRequestQuery(event.target.value)} />
} >
{requests.length === 0 ? (
没有匹配的请求记录。
) : ( requests.map((entry) => { const usage = entry.usage || {}; const upstream = entry.upstream || {}; const statusTone = entry.error ? "error" : entry.matched ? "warn" : ""; const effectiveInput = effectiveInputTokens(usage.input_tokens, usage.cached_tokens); const cachedHitRatio = cachedRatio(usage.input_tokens, usage.cached_tokens); const showReasoningRetry = hasReasoningRetryInfo(entry); const retryReasoningCounts = sortedReasoningCounts(entry.reasoning_retry_extra_reasoning_counts); const retryCurrentFirsts = Array.isArray(entry.reasoning_retry_current_firsts) ? entry.reasoning_retry_current_firsts : []; const threadRuleBusy = Boolean(entry.thread_id) && threadRuleBusyThreadId === entry.thread_id; return (
{entry.status_code ?? "-"} {entry.profile_name || status?.config?.profile_name || "-"} {entry.lifecycle_state || "sent"} {timestamp(entry.started_at)} {retryCurrentFirsts.length > 0 ? ( {retryCurrentFirsts.map((first, index) => ( {retryFirstCompactText(first)} ))} ) : ( {durationSeconds(entry.first_response_delay_ms)} )} {durationSeconds(entry.duration_ms)} {timestamp(entry.last_activity_at || entry.usage_last_updated_at)} {bytesFormat(entry.request_body_bytes)} {entry.response_stream ? `${numberFormat(entry.stream_chunk_count)} chunk / ${bytesFormat(entry.response_bytes_received)} / ${secondsSince(entry.started_at, entry.last_activity_at || entry.usage_last_updated_at || entry.finished_at)}` : "-"} {showReasoningRetry ? ( 重打 {`${retryRoundWidthText(entry)} / ${numberFormat(entry.reasoning_retry_query_count || 0)}q`} ) : null} {timestamp(entry.finished_at)}
{`${entry.method || "-"} ${entry.path || "-"}`} {entry.response_stream ? "stream" : "non-stream"} id {requestPrimaryId(entry)} thread {entry.thread_id || "-"}
{entry.matched ? matched : pass} {entry.error ? error : null} guard {formatThreadGuardOverride(entry.reasoning_guard_thread_override)} {showReasoningRetry ? ( retry {formatRetryStopReason(entry.reasoning_retry_stop_reason)} ) : null}
{entry.requested_model || entry.model || "-"} {entry.forwarded_model && entry.forwarded_model !== entry.requested_model ? `转发为 ${entry.forwarded_model}` : entry.forwarded_model || "-"} {entry.reasoning_effort ? `强度 ${entry.reasoning_effort}` : "强度 -"} {entry.reasoning_summary ? ` / summary ${entry.reasoning_summary}` : ""}
{`${upstream.origin || "-"}${upstream.path || ""}`} {upstream.auth_mode || "-"} / {upstream.auth_source || "-"} {upstream.authorization_configured === false ? " / no auth" : ""} 重试 {numberFormat(entry.upstream_attempt_count)} 次 {entry.upstream_status_code ? ` / upstream ${entry.upstream_status_code}` : ""}
in {numberFormat(effectiveInput)} out {numberFormat(usage.output_tokens)} cached {numberFormat(usage.cached_tokens)}{cachedHitRatio !== null ? ` (${percent(cachedHitRatio)})` : ""} reasoning {numberFormat(entry.reasoning_tokens ?? usage.reasoning_tokens)} total {numberFormat(usage.total_tokens)}
{`response ${entry.response_id || "-"}`} {`request ${entry.request_id || "-"}`} {`thread ${entry.thread_id || "-"}`} {entry.thread_id ? (
{entry.reasoning_guard_thread_override && entry.reasoning_guard_thread_override !== "default" ? ( ) : null}
) : null}
{showReasoningRetry ? (
{formatRetryThreadMode(entry.reasoning_retry_thread_mode)} guard {formatThreadGuardOverride(entry.reasoning_guard_thread_override)} schedule 1,1,2,2,4,4... / query {numberFormat(entry.reasoning_retry_query_count || 0)} {" / "} round {retryRoundWidthText(entry)} winner {entry.reasoning_retry_winner_round && entry.reasoning_retry_winner_slot ? `round ${entry.reasoning_retry_winner_round} slot ${entry.reasoning_retry_winner_slot}` : "-"} {" / "} stop {formatRetryStopReason(entry.reasoning_retry_stop_reason)} extra matched {numberFormat(entry.reasoning_retry_extra_matched_count || 0)} {" / "} inspected {numberFormat(entry.reasoning_retry_extra_inspected_count || 0)} {" / "} extra reasoning {numberFormat(entry.reasoning_retry_extra_usage?.reasoning_tokens)} {retryReasoningCounts.length > 0 ? (
{retryReasoningCounts.slice(0, 4).map(([reasoning, count]) => ( {reasoning}: {numberFormat(count)} ))}
) : null} {retryCurrentFirsts.length > 0 ? (
{retryCurrentFirsts.map((first, index) => ( {retryFirstText(first, entry.reasoning_retry_current_round)} ))}
) : null}
) : null}
); }) )}
)} {page === "profiles" && (
{ setShouldSyncProfileFormToActive(false); setProfileForm(profileFormFromStatus(status)); setProfileMessage({ text: "", tone: "" }); }} > 新建文本 Profile } >
{profiles.length === 0 ? (
当前还没有 profile env 文件。
) : ( profiles.map((profile) => (

{profile.name}

{profile.file_path || ""}
{profile.active ? 当前运行 : 可切换}
)) )}
setProfileForm({ ...profileForm, name: event.target.value })} />
setProfileForm({ ...profileForm, listen_host: event.target.value })} /> setProfileForm({ ...profileForm, listen_port: event.target.value })} />
setProfileForm({ ...profileForm, upstream_base_url: event.target.value })} />