From b58da06d2b9be97807762beaca1f4dcac9812691 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:13:47 +0800 Subject: [PATCH] feat: screens that stay current without polling, and a menu bar that shows what is running An audit of every live-updating screen found one timed poll that core already pushes for, several screens that never changed once open, events the app ignored, and a push channel that could lose events silently. Core v0.25.0 (ThinkWatch-Core#102) adds what was missing on its side; this uses it. Lost events - core now tells a subscriber that fell behind (events_dropped), and the Rust bridge sends the same marker when it reconnects after a drop. useRequests takes the in-flight snapshot again and re-reads the history; a row still "in progress" that the history already has gets its ending from the stored row (mergeHistory), so a lost ending no longer leaves a row running forever. useLive resyncs its in-progress count and refills the chart, every useCoreEvent page refreshes, and App re-reads the overview. Polling replaced - The Upstreams page stops asking every 30 s. Quota comes straight from quota_seen; the 24-hour requests, cost and TTFB are re-read after requests land and when the window regains focus. - Quota resets are moments (resets_at_ms), and countdowns are recomputed locally as time passes. A window whose reset has passed is no longer shown as current, in the table, the ChatGPT account section and the menu bar. Screens that did not update - Opening a request that is still running shows what is known so far and follows it; the row is complete once its priced event arrives, which core sends in the same lock as the database write. Replay, content and usage say they are available when the request ends. - An open session refreshes as its requests land; the Keys page's last used and 24-hour usage follow requests; the MCP page rescans on scan_alert and clients_changed. - The Upstreams table shows a rejected credential and a needed sign-in, and the proxy table shows the failure the gateway found, whichever of that and a manual test is newer. The overview is re-read on auth_changed, proxy_changed, credential_expired and the first quota report for an upstream. - The traffic list takes the upstream from request_routed, so a request that failed over is attributed to the upstream that served it. Rust side - The menu bar's second line shows the requests in progress and the output rate (tokens per second of generation, over requests finished in the last minute) instead of hard-coded blanks; both are counted from events, and ticks recompute them without asking core. - A core binary that cannot run is a state (failed:) with the reason and a retry, instead of "starting" forever, plus a critical notice. A wedged core that was replaced leaves an in-app notice. The first autostart hint is a system notification that respects the notice mode; before, it went to a webview that is never open at login. - Tauri events nobody listened to are gone: core-restarting, core-safe-mode, core-failed, core-wedged, app-exiting, first-autostart. Pin core v0.25.0 (control API 8). Co-Authored-By: Claude Opus 5 --- src-tauri/Cargo.lock | 8 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/control.rs | 7 +- src-tauri/src/lib.rs | 249 +++++++++++++++++------ src-tauri/src/notices/macos/mod.rs | 10 + src-tauri/src/notices/mod.rs | 15 +- src-tauri/src/notices/rules.rs | 49 ++++- src-tauri/src/notices/sink.rs | 14 ++ src-tauri/src/notices/tests.rs | 45 +++- src-tauri/src/supervisor/mod.rs | 48 ++++- src-tauri/src/tally.rs | 260 ++++++++++++++++++++++++ src/App.i18n.tsx | 2 + src/App.tsx | 27 ++- src/Connect.i18n.ts | 2 + src/Connect.tsx | 9 + src/RequestDrawer.i18n.tsx | 10 + src/RequestDrawer.tsx | 109 ++++++++-- src/events.test.ts | 96 +++++++++ src/format.test.ts | 17 ++ src/format.ts | 12 ++ src/keys/KeysPage.tsx | 19 ++ src/mcp/McpPage.tsx | 27 ++- src/types.ts | 99 ++++++++- src/upstreams/ChatgptAccountSection.tsx | 6 +- src/upstreams/ProxyTable.tsx | 33 ++- src/upstreams/UpstreamTable.i18n.ts | 11 + src/upstreams/UpstreamTable.tsx | 48 ++++- src/upstreams/UpstreamsPage.tsx | 43 +++- src/upstreams/labels.ts | 7 + src/useCoreEvent.ts | 5 +- src/useLive.ts | 16 +- src/useNow.ts | 16 ++ src/useRequests.ts | 172 +++++++++++----- 33 files changed, 1292 insertions(+), 201 deletions(-) create mode 100644 src-tauri/src/tally.rs create mode 100644 src/useNow.ts diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 235ee20a..1ce88780 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4982,8 +4982,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.24.1" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.24.1#ef802fe1a3a0ba4f95a6b680dadfe61476c4f7be" +version = "0.25.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.25.0#ce8c4071eda99b08ac2d463c47f7829ce71103a2" dependencies = [ "serde", "serde_json", @@ -4992,8 +4992,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.24.1" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.24.1#ef802fe1a3a0ba4f95a6b680dadfe61476c4f7be" +version = "0.25.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.25.0#ce8c4071eda99b08ac2d463c47f7829ce71103a2" dependencies = [ "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index abdde7bd..8a957df4 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -31,7 +31,7 @@ tauri-plugin-deep-link = "2" # 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制 # 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从 # 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。 -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.24.1" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.25.0" } anyhow = "1" libc = "0.2" diff --git a/src-tauri/src/control.rs b/src-tauri/src/control.rs index ddd0056e..5388b865 100644 --- a/src-tauri/src/control.rs +++ b/src-tauri/src/control.rs @@ -1055,12 +1055,14 @@ impl ControlClient { Ok(serde_json::from_slice(&body)?) } - /// 订阅事件流,逐条交给回调。 + /// 订阅事件流,逐条交给回调。`on_open` 在流接通的那一刻调一次:调用方据此 + /// 分得清哪一次是重连 —— 断开的那一段里发生的事,流不会再说一遍。 /// /// 断开就返回 —— **重连由调用方决定**。守护那边已经有退避逻辑了, /// 这里再来一套会变成两套互相不知道对方存在的重试。 - pub async fn subscribe_events(&self, mut on_event: F) -> Result<()> + pub async fn subscribe_events(&self, on_open: O, mut on_event: F) -> Result<()> where + O: FnOnce() + Send, F: FnMut(tw_api::Event) + Send, { let stream = tokio::net::UnixStream::connect(&self.socket).await?; @@ -1075,6 +1077,7 @@ impl ControlClient { .header(hyper::header::ACCEPT, "text/event-stream") .body(String::new())?; let mut resp = sender.send_request(req).await?; + on_open(); let mut buf = String::new(); while let Some(frame) = resp.frame().await { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2efc9030..6a917e2d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -26,6 +26,7 @@ pub mod prefs; pub mod routing; pub mod security; pub mod supervisor; +pub mod tally; pub mod theme; pub mod update; pub mod upstreams; @@ -59,6 +60,8 @@ pub struct AppState { /// 现在由事件叫醒。`Notify` 攒一个许可,所以一串请求只会换来一次 /// 重收,不是一串。 pub menubar: Arc, + /// 菜单栏第二行的两个数:正在跑几个请求、最近的输出速率。事件桥喂它 + pub tally: Arc>, } /// twcore 在哪。 @@ -245,6 +248,7 @@ fn describe_state(s: &CoreState) -> String { CoreState::Restarting { attempt, in_ms } => format!("restarting:{attempt}:{in_ms}"), CoreState::SafeMode => "safe_mode".into(), CoreState::Stopped => "stopped".into(), + CoreState::Failed { reason } => format!("failed:{reason}"), } } @@ -1606,6 +1610,7 @@ pub fn run() { core_missing: located.as_ref().err().map(|e| format!("{e:#}")), supervising: supervising.clone(), menubar: Arc::new(tokio::sync::Notify::new()), + tally: Default::default(), }); // **状态变化推给界面,不要让它来问。**「core 起来没、是不是 @@ -1760,7 +1765,6 @@ pub fn run() { // core 是我们 spawn 的子进程,`kill_on_drop` 会带走它。 // 但显式说一句,因为这条是「一个程序」原则的另一半。 tracing::info!("退出,core 跟着走"); - let _ = app.emit("app-exiting", ()); } } }); @@ -1804,7 +1808,11 @@ async fn heartbeat_loop(socket: PathBuf, sup: Arc, app: tauri::AppHa tracing::warn!(consecutive, "core 没回心跳"); } Verdict::Wedged => { - let _ = app.emit("core-wedged", ()); + // 自己好了的一次卡顿不打断人(和偶发崩溃一个待遇),但在提醒列表里 + // 留一条:用户那几秒看到的失败,要有地方说得清是为什么 + if let Some(n) = app.try_state::>() { + n.ingest(notices::rules::wedged(), notices::now_ms()); + } if let Err(e) = sup.report_wedged().await { tracing::debug!("换掉卡死的 core 失败:{e:#}"); } @@ -1821,43 +1829,108 @@ async fn heartbeat_loop(socket: PathBuf, sup: Arc, app: tauri::AppHa /// 断线就重连,但**退避要克制**:core 重启期间 socket 必然连不上,这是 /// 预期状态而不是故障。1 秒一次的重试既不会刷屏,也不会让用户在 core /// 恢复后还盯着一个空列表等太久。 +/// +/// **重新连上时补报一条「丢过事件」**(`EventsDropped`,条数记 0:丢了多少不知道)。 +/// 断开的那一段里发生的事,事件流不会再说一遍 —— 界面和菜单栏要各自对一次账, +/// 否则那段时间里结束的请求,会一直显示成进行中。 async fn bridge_events(socket: PathBuf, app: tauri::AppHandle) { + let mut connected_before = false; loop { let client = ControlClient::new(socket.clone()); - let a = app.clone(); + let opened = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (a, b, o) = (app.clone(), app.clone(), opened.clone()); + let resumed = connected_before; let r = client - .subscribe_events(move |ev| { - // **在客户端弹批准提示的同一瞬间弹一条通知**。 - // 这是网关位置独有的能力:只有我们同时知道「这个调用长 - // 什么样」和「它来自哪个上游」。用户看到批准提示的同时 - // 看到这条,判断质量完全不一样。 - if let Some(n) = a.try_state::>() { - n.on_event(&ev); - } - // 菜单栏上那两个数只跟这几种事件有关:花了多少(请求 - // 落地之后存储层才算得出来)、额度还剩多少。别的事件 - // 叫醒它只是让它白跑一趟。 - if matches!( - ev, - tw_api::Event::RequestFinished { .. } - | tw_api::Event::RequestFailed { .. } - | tw_api::Event::RequestCancelled { .. } - | tw_api::Event::QuotaSeen { .. } - | tw_api::Event::ConfigReloaded { .. } - ) && let Some(st) = a.try_state::() - { - st.menubar.notify_one(); - } - let _ = a.emit("core-event", &ev); - }) + .subscribe_events( + move || { + o.store(true, std::sync::atomic::Ordering::SeqCst); + if resumed { + let lost = tw_api::Event::EventsDropped { + id: 0, + count: 0, + at_ms: notices::now_ms(), + }; + resync_tally(&b); + let _ = b.emit("core-event", &lost); + } + }, + move |ev| { + // **在客户端弹批准提示的同一瞬间弹一条通知**。 + // 这是网关位置独有的能力:只有我们同时知道「这个调用长 + // 什么样」和「它来自哪个上游」。用户看到批准提示的同时 + // 看到这条,判断质量完全不一样。 + if let Some(n) = a.try_state::>() { + n.on_event(&ev); + } + if let Some(st) = a.try_state::() { + if let Ok(mut t) = st.tally.lock() { + t.on_event(&ev, std::time::Instant::now()); + } + // 菜单栏上那几个数只跟这几种事件有关:花了多少(请求 + // 落地之后存储层才算得出来)、额度还剩多少、进行中几个。 + // 别的事件叫醒它只是让它白跑一趟。 + if matches!( + ev, + tw_api::Event::RequestStarted { .. } + | tw_api::Event::RequestFinished { .. } + | tw_api::Event::RequestFailed { .. } + | tw_api::Event::RequestCancelled { .. } + | tw_api::Event::QuotaSeen { .. } + | tw_api::Event::ConfigReloaded { .. } + ) { + st.menubar.notify_one(); + } + } + // core 说这个订阅者掉过队:进行中的那几个按快照重数 + if matches!(ev, tw_api::Event::EventsDropped { .. }) { + resync_tally(&a); + } + let _ = a.emit("core-event", &ev); + }, + ) .await; if let Err(e) = r { tracing::debug!("事件流断开:{e:#}"); } + // 接通过才算连上过:core 重启期间那几轮连不上的不算 + connected_before |= opened.load(std::sync::atomic::Ordering::SeqCst); tokio::time::sleep(std::time::Duration::from_secs(1)).await; } } +/// 菜单栏上「进行中几个」按 core 的快照重数一遍(`/in-flight`)。 +/// +/// **先开始记账再去问**:问的这会儿开始、结束的请求记在一边,快照到了一起合进去 +/// (见 `Tally::finish_resync`)。 +fn resync_tally(app: &tauri::AppHandle) { + let Some(st) = app.try_state::() else { + return; + }; + if let Ok(mut t) = st.tally.lock() { + t.begin_resync(); + } + let a = app.clone(); + tauri::async_runtime::spawn(async move { + let Some(st) = a.try_state::() else { + return; + }; + let Ok(open) = st.control.in_flight().await else { + if let Ok(mut t) = st.tally.lock() { + t.abandon_resync(); + } + return; + }; + let ids = open.iter().filter_map(|e| match e { + tw_api::Event::RequestStarted { id, .. } => Some(*id), + _ => None, + }); + if let Ok(mut t) = st.tally.lock() { + t.finish_resync(ids); + } + st.menubar.notify_one(); + }); +} + /// 第一次检查之前先等一会儿。 /// /// **不在启动那一刻查。**冷启动那几秒 CPU 和网络都在忙别的 —— 网关要起 @@ -1950,7 +2023,17 @@ fn maybe_notify_first_autostart(app: &tauri::AppHandle) { if std::fs::write(&marker, "1").is_err() { return; } - let _ = app.emit("first-autostart", ()); + // 窗口这时没开:只有系统通知说得到 + if let Some(n) = app.try_state::>() { + n.announce( + "autostart", + tr!("ThinkWatch 已在菜单栏运行", "ThinkWatch Is Running in the Menu Bar"), + tr!( + "开机时已自动启动。窗口关闭后,应用仍在菜单栏中运行。", + "It started at login. When the window is closed, the app keeps running in the menu bar." + ), + ); + } tracing::info!("首次开机自启,已提示一次"); } @@ -2255,6 +2338,10 @@ fn build_tray_menu(app: &tauri::AppHandle, f: &TrayFacts) -> tauri::Result() else { return; }; - let next = collect_menubar_state(&state).await; + let (next, resets_at) = collect_menubar_state(&state).await; // 托盘菜单跟着一起更。**只在内容真的变了的时候重建** —— 而且 // macOS 上菜单正开着时重建会把它收起来,用户点到一半菜单没了。 let facts = collect_tray_facts(&state, &next).await; @@ -2306,9 +2393,32 @@ async fn menubar_loop(tray: tauri::tray::TrayIcon, app: tauri::AppHandle) { // 等一个理由。**两路都要等** —— 只等事件的话,core 挂了之后 // 菜单栏会停在最后那个数字上,而那正是最该说实话的时候。 - tokio::select! { - _ = wake.notified() => {} - _ = core_rx.changed() => {} + loop { + let ticking = prev.status == menubar::Status::Normal + && (resets_at.is_some() || prev.tokens_per_sec.is_some()); + tokio::select! { + _ = wake.notified() => break, + _ = core_rx.changed() => break, + _ = tokio::time::sleep(MENUBAR_TICK), if ticking => { + let now = notices::now_ms(); + // 重置的时刻到了:那份额度已经作废,整个重收一遍 + if resets_at.is_some_and(|at| at <= now) { + break; + } + let mut tick = prev.clone(); + tick.quota_reset_in_secs = resets_at.map(|at| (at - now) / 1000); + if let Some(st) = app.try_state::() + && let Ok(mut t) = st.tally.lock() + { + tick.tokens_per_sec = t.tokens_per_sec(std::time::Instant::now()); + tick.active = t.active(); + } + if tick.needs_redraw(&prev) { + draw_menubar(&tray, &tick); + prev = tick; + } + } + } } // 攒一下。`Notify` 只攒一个许可,所以这三秒里来多少条事件, // 醒来之后也只多跑一轮。 @@ -2331,28 +2441,40 @@ fn draw_menubar(tray: &tauri::tray::TrayIcon, next: &menubar::MenuBarState) { let _ = tray.set_icon_as_template(template); } -async fn collect_menubar_state(state: &tauri::State<'_, AppState>) -> menubar::MenuBarState { +/// 收一帧要画的数。另外交回额度的重置时刻:倒计时要靠它随时间往下走。 +async fn collect_menubar_state( + state: &tauri::State<'_, AppState>, +) -> (menubar::MenuBarState, Option) { let core = state.supervisor.state(); let status = match core { CoreState::Running { .. } => menubar::Status::Normal, CoreState::Starting | CoreState::Restarting { .. } => menubar::Status::Starting, - CoreState::SafeMode | CoreState::Stopped => menubar::Status::Disconnected, + CoreState::SafeMode | CoreState::Stopped | CoreState::Failed { .. } => { + menubar::Status::Disconnected + } }; if !matches!(status, menubar::Status::Normal) { // core 没在跑的时候,上一次的数字已经不代表现在了。**显示破折号 // 而不是一个凝固的旧值** —— 后者会让人以为它还在更新。 - return menubar::MenuBarState { - active: 0, - status, - ..Default::default() - }; + return ( + menubar::MenuBarState { + active: 0, + status, + ..Default::default() + }, + None, + ); } // **订阅额度优先。**有它说明这是个订阅账号,而对他「今天花了 $0.00」 // 是句废话。按量付费的账号根本没有那些响应头。 + let now = notices::now_ms(); let quota = state.control.quota().await.unwrap_or_default(); let tightest = quota .iter() .flat_map(|p| p.windows.iter()) + // **过了重置时刻的窗口不算数**:手上的百分比是重置之前的,下一个请求才会 + // 带来新的 + .filter(|w| w.resets_at_ms.is_none_or(|at| at > now)) .max_by(|a, b| a.used_percent.total_cmp(&b.used_percent)); // 花费从库里来。拿不到就是「不知道」——**画一个 $0.00 会是一个断言: @@ -2370,20 +2492,30 @@ async fn collect_menubar_state(state: &tauri::State<'_, AppState>) -> menubar::M .map(|s| s.cost_micros_exact as f64 / 1e6) }; - menubar::MenuBarState { - cost_today, - quota_percent: tightest.map(|w| w.used_percent), - quota_reset_in_secs: tightest.and_then(|w| w.reset_in_secs), - quota_warning: tightest.is_some_and(|w| { - matches!( - w.status.as_deref(), - Some("allowed_warning") | Some("rejected") - ) - }), - tokens_per_sec: None, - active: 0, - status, - } + let resets_at = tightest.and_then(|w| w.resets_at_ms); + // 第二行:进行中几个、最近的输出速率。事件桥一直在数,这里读一下就有 + let (active, tokens_per_sec) = state + .tally + .lock() + .map(|mut t| (t.active(), t.tokens_per_sec(std::time::Instant::now()))) + .unwrap_or((0, None)); + ( + menubar::MenuBarState { + cost_today, + quota_percent: tightest.map(|w| w.used_percent), + quota_reset_in_secs: resets_at.map(|at| at.saturating_sub(now) / 1000), + quota_warning: tightest.is_some_and(|w| { + matches!( + w.status.as_deref(), + Some("allowed_warning") | Some("rejected") + ) + }), + tokens_per_sec, + active, + status, + }, + resets_at, + ) } /// 数据目录。**只有这一处**决定它在哪 —— 写第二遍就会漂,而漂掉的那处 @@ -2403,17 +2535,14 @@ fn default_socket() -> PathBuf { async fn supervise(sup: Arc, app: tauri::AppHandle) { let mut safe = false; loop { + // 每一次转换都随 `core-state` 推给界面(见 setup 里那一段),这里不再另发 match sup.run_once(safe).await { - Ok(supervisor::Next::Again) => { - let _ = app.emit("core-restarting", ()); - continue; - } + Ok(supervisor::Next::Again) => continue, Ok(supervisor::Next::Stop) => break, Ok(supervisor::Next::SafeMode) => { // 进安全模式:**必须打断用户并自动开窗**。这时候网关 // 已经不转发了,他所有的 AI 客户端都在瞎。 safe = true; - let _ = app.emit("core-safe-mode", ()); if let Some(w) = app.get_webview_window("main") { let _ = w.show(); let _ = w.set_focus(); @@ -2422,9 +2551,9 @@ async fn supervise(sup: Arc, app: tauri::AppHandle) { } Err(e) => { // 起不来(多半是二进制路径不对)。这不是「core 在崩」, - // 别用重启循环去掩盖它。 + // 别用重启循环去掩盖它:守护停下,状态是 `Failed`,界面上 + // 说原因、给重试 tracing::error!("core 起不来:{e:#}"); - let _ = app.emit("core-failed", format!("{e:#}")); break; } } diff --git a/src-tauri/src/notices/macos/mod.rs b/src-tauri/src/notices/macos/mod.rs index bcd69af1..73a246b6 100644 --- a/src-tauri/src/notices/macos/mod.rs +++ b/src-tauri/src/notices/macos/mod.rs @@ -66,6 +66,16 @@ impl Sink for NativeSink { fn withdraw(&self, key: &str) { un::withdraw(key); } + + fn announce(&self, key: &str, title: &str, body: &str) { + un::post( + key.to_string(), + title.to_string(), + body.to_string(), + thread_of(key), + false, + ); + } } /// 同一种的归在一起:用键的种类(冒号前那段)做 thread diff --git a/src-tauri/src/notices/mod.rs b/src-tauri/src/notices/mod.rs index efd5eba0..75f87e41 100644 --- a/src-tauri/src/notices/mod.rs +++ b/src-tauri/src/notices/mod.rs @@ -323,6 +323,19 @@ impl Notices { } } + /// 告知一件事:**不是一个待处理的问题**,不进提醒列表,只弹一条系统通知。 + /// + /// 给那种窗口没开、而用户该知道一下的时刻用(第一次开机自启)。用户选了「只在 + /// 应用内」或者关掉提醒的,就不弹 —— 那是他说了不要被打断。 + pub fn announce(&self, key: &str, title: &str, body: &str) { + if self.mode() != Mode::System { + return; + } + for s in &self.sinks { + s.announce(key, title, body); + } + } + /// 走一遍那五关。 pub fn ingest(self: &Arc, signal: Signal, at_ms: u64) { match signal.change { @@ -596,7 +609,7 @@ pub fn take_pending_view() -> Option { PENDING_VIEW.lock().ok().and_then(|mut g| g.take()) } -fn now_ms() -> u64 { +pub fn now_ms() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as u64) diff --git a/src-tauri/src/notices/rules.rs b/src-tauri/src/notices/rules.rs index 51b734b1..79bef88f 100644 --- a/src-tauri/src/notices/rules.rs +++ b/src-tauri/src/notices/rules.rs @@ -104,13 +104,15 @@ pub fn from_event(ev: &Event) -> Vec { Event::QuotaExhausted { provider, window, - reset_in_secs, + resets_at_ms, .. } => { - let reset = reset_in_secs.map(after).unwrap_or_default(); + // core 给的是重置的时刻:按现在去数还有多久 + let secs = resets_at_ms.map(|at| at.saturating_sub(super::now_ms()) / 1000); + let reset = secs.map(after).unwrap_or_default(); // 几分钟后就恢复的窗口不值得打断 —— 用户等一会儿就好了 - let level = match reset_in_secs { - Some(s) if *s <= 300 => Level::Info, + let level = match secs { + Some(s) if s <= 300 => Level::Info, _ => Level::Warning, }; vec![ @@ -457,6 +459,24 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec { .now() .suppressing(suppresses("gateway")), ], + // 程序本身运行不了:不会自己好,转发已经停了 + CoreState::Failed { .. } => vec![ + Signal::raised( + "gateway", + Level::Critical, + tr!("网关无法启动", "Gateway Cannot Start"), + ) + .body( + tr!( + "core 程序未能运行,转发已停止。打开窗口可以查看原因并重试。", + "The core program could not run, so forwarding has stopped. Open the window to see why and try again." + ) + .to_string(), + ) + .view(SETTINGS) + .now() + .suppressing(suppresses("gateway")), + ], // 偶发崩溃自己好了就别打扰人;连着崩说明不是偶发 CoreState::Restarting { attempt, .. } if *attempt >= 3 => vec![ Signal::raised( @@ -478,6 +498,27 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec { } } +/// core 活着但不回心跳,被换掉了。 +/// +/// **只进应用内**:自己好了的一次卡顿和一次偶发崩溃一个待遇,不打断人。但那几秒里 +/// 用户看到的失败要有地方说得清,所以留一条。同一件事再发生只累计次数 +pub fn wedged() -> Signal { + Signal::raised( + "wedged", + Level::Info, + tr!("网关曾无响应,已重启", "Gateway Stopped Responding and Was Restarted"), + ) + .body( + tr!( + "网关连续几次没有响应,已自动重启。重启期间的请求可能失败。", + "The gateway did not respond several times in a row and was restarted automatically. Requests during the restart may have failed." + ) + .to_string(), + ) + .view(SETTINGS) + .now() +} + /// `5h` / `weekly` → 「5 小时」「每周」(英文是 `5-hour`、`weekly`)。认不出来的原样用 fn window_label(w: &str) -> String { match w { diff --git a/src-tauri/src/notices/sink.rs b/src-tauri/src/notices/sink.rs index 036806c7..a3428a52 100644 --- a/src-tauri/src/notices/sink.rs +++ b/src-tauri/src/notices/sink.rs @@ -17,6 +17,9 @@ pub trait Sink: Send + Sync { fn withdraw(&self, _key: &str) {} /// 现在开着的全部。界面按这一份重画 fn listed(&self, _all: &[Notice]) {} + /// 告知一件事(见 `Notices::announce`)。**只有系统通知这一端要做什么**: + /// 它不是一个待处理的问题,界面里的列表不收它 + fn announce(&self, _key: &str, _title: &str, _body: &str) {} } /// 界面里的通知中心。**窗口关着时照样调**:内容在 Rust 这边留着, @@ -79,4 +82,15 @@ impl Sink for SystemSink { .body(¬ice.body) .show(); } + + fn announce(&self, _key: &str, title: &str, body: &str) { + use tauri_plugin_notification::NotificationExt; + let _ = self + .app + .notification() + .builder() + .title(title) + .body(body) + .show(); + } } diff --git a/src-tauri/src/notices/tests.rs b/src-tauri/src/notices/tests.rs index e9e891b4..7b811422 100644 --- a/src-tauri/src/notices/tests.rs +++ b/src-tauri/src/notices/tests.rs @@ -383,6 +383,12 @@ fn only_an_edit_made_outside_the_app_is_reported() { assert!(s[0].body.contains("第 4 行"), "{}", s[0].body); } +/// `secs` 秒之后重置的那个时刻。**多给半秒**:规则拿到事件时按那一刻的时钟数, +/// 测试从造事件到读结果之间走掉的那几毫秒,不该让「2 小时」变成「1 小时 59 分」 +fn resets_in(secs: u64) -> Option { + Some(super::now_ms() + secs * 1000 + 500) +} + #[test] fn a_window_that_resets_in_a_moment_is_not_worth_interrupting() { let quota = |secs: u64| { @@ -390,7 +396,7 @@ fn a_window_that_resets_in_a_moment_is_not_worth_interrupting() { id: 1, provider: "chatgpt".into(), window: "5h".into(), - reset_in_secs: Some(secs), + resets_at_ms: resets_in(secs), at_ms: T0, })[0] .clone() @@ -413,13 +419,13 @@ fn a_quota_report_below_the_limit_clears_that_window() { tw_api::QuotaWindow { window: "weekly".into(), used_percent: 21.0, - reset_in_secs: None, + resets_at_ms: None, status: None, }, tw_api::QuotaWindow { window: "5h".into(), used_percent: 100.0, - reset_in_secs: Some(600), + resets_at_ms: resets_in(600), status: Some("rejected".into()), }, ], @@ -455,7 +461,7 @@ fn quota_exhausted(window: &str, reset_in_secs: Option) -> tw_api::Event { id: 1, provider: "chatgpt".into(), window: window.into(), - reset_in_secs, + resets_at_ms: reset_in_secs.and_then(resets_in), at_ms: T0, } } @@ -557,13 +563,17 @@ fn in_english_no_rule_writes_a_chinese_word() { attempt: 3, in_ms: 1_000, }, + CoreState::Failed { + reason: "/Applications/ThinkWatch.app/twcore could not be run".into(), + }, ]; with_lang(Lang::En, || { let mut signals: Vec = events.iter().flat_map(rules::from_event).collect(); signals.extend(states.iter().flat_map(rules::from_core_state)); + signals.push(rules::wedged()); assert_eq!( signals.len(), - events.len() + states.len(), + events.len() + states.len() + 1, "每一件都该说一句" ); for s in &signals { @@ -722,3 +732,28 @@ fn a_listen_change_that_did_not_take_is_raised_and_one_that_did_clears_it() { "换成了就收起来,不另发一条" ); } + +/// core 程序本身运行不了:**不会自己好**,转发已经停了 —— 和安全模式一样要打断人 +#[test] +fn a_core_that_cannot_start_interrupts() { + use crate::supervisor::CoreState; + let s = rules::from_core_state(&CoreState::Failed { + reason: "无法运行 /x/twcore:No such file or directory (os error 2)".into(), + }); + assert_eq!(s.len(), 1); + assert_eq!(s[0].key, "gateway"); + assert_eq!(s[0].level, Level::Critical); + // 连上之后撤掉:和别的网关状态共用一个键 + assert_eq!( + rules::from_core_state(&CoreState::Running { pid: 1 })[0].key, + "gateway" + ); +} + +/// core 卡住被换掉:自己好了的一次卡顿不打断人,只在应用内留一条 +#[test] +fn a_wedged_core_that_was_replaced_is_recorded_without_interrupting() { + let s = rules::wedged(); + assert_eq!(s.level, Level::Info); + assert!(!s.body.is_empty()); +} diff --git a/src-tauri/src/supervisor/mod.rs b/src-tauri/src/supervisor/mod.rs index 4a42abba..6f217404 100644 --- a/src-tauri/src/supervisor/mod.rs +++ b/src-tauri/src/supervisor/mod.rs @@ -36,6 +36,13 @@ pub enum CoreState { SafeMode, /// UI 主动停的,不再重启 Stopped, + /// 拉不起来:程序运行不了(找不到、没有执行权限、不是这台机器能跑的)。 + /// + /// **这不是「core 在崩」**,重启循环掩盖不了它,所以守护停下来等用户点重试。 + /// 原因要带着:界面上只写「正在启动」的话,用户会一直等下去 + Failed { + reason: String, + }, } /// 一次 core 退出之后,守护循环下一步做什么。 @@ -139,10 +146,12 @@ impl Supervisor { "Core is starting; try again in a moment" )) } - CoreState::SafeMode | CoreState::Stopped => anyhow::bail!(tr!( - "core 未运行,无法重启", - "Core is not running and cannot be restarted" - )), + CoreState::SafeMode | CoreState::Stopped | CoreState::Failed { .. } => { + anyhow::bail!(tr!( + "core 未运行,无法重启", + "Core is not running and cannot be restarted" + )) + } }; self.intentional.store(true, Ordering::SeqCst); // SIGTERM 而不是 SIGKILL:给它机会把 socket 和 lock 文件清掉。 @@ -218,11 +227,24 @@ impl Supervisor { let args = self.command_args(safe); let started = Instant::now(); - let mut child = tokio::process::Command::new(&self.binary) + let spawned = tokio::process::Command::new(&self.binary) .args(&args) // core 的日志走它自己的 stderr;UI 侧只需要知道它活着。 .kill_on_drop(true) - .spawn()?; + .spawn(); + let mut child = match spawned { + Ok(c) => c, + Err(e) => { + let path = self.binary.display(); + self.set(CoreState::Failed { + reason: tr!( + format!("无法运行 {path}:{e}"), + format!("{path} could not be run: {e}") + ), + }); + return Err(e.into()); + } + }; if let Some(pid) = child.id() { self.set(CoreState::Running { pid }); @@ -300,6 +322,20 @@ mod tests { ) } + /// 程序运行不了:**停在「无法启动」、带着原因**,不是停在「正在启动」。以前停在 + /// 后者,界面上一直说「请稍候」,而这件事等多久都不会好。 + #[tokio::test] + async fn a_binary_that_cannot_run_leaves_the_reason_in_the_state() { + let s = sup(); + assert!(s.run_once(false).await.is_err()); + match s.state() { + CoreState::Failed { reason } => { + assert!(reason.contains("/nonexistent/twcore"), "{reason}"); + } + other => panic!("该是无法启动,实际 {other:?}"), + } + } + #[test] fn the_command_always_carries_our_pid() { // 「让用户认为他俩就是一个程序」的落点:UI 没了 core 跟着退。 diff --git a/src-tauri/src/tally.rs b/src-tauri/src/tally.rs new file mode 100644 index 00000000..7bad35ff --- /dev/null +++ b/src-tauri/src/tally.rs @@ -0,0 +1,260 @@ +//! 菜单栏第二行的两个数:正在跑几个请求、最近的输出速率。 +//! +//! **事件桥喂它,菜单栏读它。**两个数只靠事件就数得出来,不必为它们去问 core: +//! 开始和结局记进行中的,响应头带着首字节用了多久,结束事件里有总耗时和用量。 + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::time::{Duration, Instant}; + +use tw_api::Event; + +/// 输出速率看最近这么久里跑完的请求 +pub const RATE_WINDOW: Duration = Duration::from_secs(60); + +#[derive(Default)] +pub struct Tally { + /// 开始了、还没有结局的 + open: HashSet, + /// 首字节用了多久,毫秒。生成用时要从总耗时里减掉它 + ttfb: HashMap, + /// 最近跑完的:(什么时候结束的,输出了多少 token,生成用了多少毫秒) + done: VecDeque<(Instant, u64, u64)>, + /// 正在按快照对账:快照在路上时事件流上见到的开始和结局,快照到了再合进去 + since: Option, +} + +#[derive(Default)] +struct Seen { + started: HashSet, + ended: HashSet, +} + +impl Tally { + pub fn on_event(&mut self, ev: &Event, now: Instant) { + match ev { + Event::RequestStarted { id, .. } => { + self.open.insert(*id); + if let Some(s) = &mut self.since { + s.started.insert(*id); + } + } + Event::RequestHeaders { id, ttfb_ms, .. } => { + self.ttfb.insert(*id, *ttfb_ms); + } + Event::RequestFinished { + id, + duration_ms, + usage, + .. + } => { + let ttfb = self.end(*id); + // **只数跑完了的。**取消的、断掉的输出不全,拿来算速率只会偏低 + if let (Some(u), Some(ttfb)) = (usage, ttfb) { + let gen_ms = duration_ms.saturating_sub(ttfb); + if u.output > 0 && gen_ms > 0 { + self.done.push_back((now, u.output, gen_ms)); + } + } + self.forget(now); + } + Event::RequestFailed { id, .. } | Event::RequestCancelled { id, .. } => { + self.end(*id); + } + _ => {} + } + } + + /// 结局到了:不再在跑。返回它首字节用了多久 + fn end(&mut self, id: u64) -> Option { + self.open.remove(&id); + if let Some(s) = &mut self.since { + s.ended.insert(id); + } + self.ttfb.remove(&id) + } + + /// 开始按快照对账(事件流丢过事件、或者重新连上之后)。**先调它再去问快照**: + /// 问的这会儿开始、结束的请求记在一边,快照到了一起合进去 + pub fn begin_resync(&mut self) { + self.since = Some(Seen::default()); + } + + /// 快照没问到:不对了,照旧按事件数 + pub fn abandon_resync(&mut self) { + self.since = None; + } + + /// 快照到了:此刻还在跑的那些(`/in-flight` 的开始事件),加上等快照这会儿 + /// 开始的,减去这会儿结束的 + pub fn finish_resync(&mut self, snapshot: impl IntoIterator) { + let seen = self.since.take().unwrap_or_default(); + let mut open: HashSet = snapshot.into_iter().collect(); + open.extend(seen.started); + for id in &seen.ended { + open.remove(id); + } + self.ttfb.retain(|id, _| open.contains(id)); + self.open = open; + } + + /// 进行中的请求数 + pub fn active(&self) -> u32 { + self.open.len() as u32 + } + + /// 最近一分钟跑完的请求,平均每秒生成多少 token。 + /// + /// **量的是生成的快慢**:每个请求的输出除以它生成用的时间(总耗时减去首字节), + /// 按 token 加权。拿「一分钟里输出了多少」去除以六十的话,一个跑了一分钟才结束的 + /// 长请求,要等它结束之后才把速率一次性摊进来,数字跟着请求的长短忽高忽低。 + /// + /// **这一分钟里没有跑完的请求就是 None**,不是 0:菜单栏那时退回别的读数。 + pub fn tokens_per_sec(&mut self, now: Instant) -> Option { + self.forget(now); + let (tokens, ms) = self + .done + .iter() + .fold((0u64, 0u64), |(t, m), (_, out, gen_ms)| { + (t + out, m + gen_ms) + }); + (ms > 0).then(|| (tokens.saturating_mul(1000) / ms).min(u32::MAX as u64) as u32) + } + + fn forget(&mut self, now: Instant) { + while self + .done + .front() + .is_some_and(|(at, _, _)| now.saturating_duration_since(*at) > RATE_WINDOW) + { + self.done.pop_front(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn started(id: u64) -> Event { + Event::RequestStarted { + id, + client: "c".into(), + client_hint: None, + session_fp: None, + peer: None, + key_masked: None, + provider: "p".into(), + billing: "per-token".into(), + model: "m".into(), + method: "POST".into(), + path: "/v1/messages".into(), + at_ms: 0, + } + } + + fn headers(id: u64, ttfb_ms: u64) -> Event { + Event::RequestHeaders { + id, + status: 200, + ttfb_ms, + } + } + + fn finished(id: u64, duration_ms: u64, output: u64) -> Event { + Event::RequestFinished { + id, + model: "m".into(), + status: 200, + bytes: 1, + duration_ms, + usage: Some(tw_api::UsageView { + input: 10, + output, + ..Default::default() + }), + } + } + + #[test] + fn it_counts_what_is_running() { + let mut t = Tally::default(); + let now = Instant::now(); + t.on_event(&started(1), now); + t.on_event(&started(2), now); + assert_eq!(t.active(), 2); + t.on_event(&finished(1, 1_000, 10), now); + t.on_event( + &Event::RequestCancelled { + id: 2, + model: "m".into(), + status: None, + bytes: 0, + duration_ms: 5, + usage: None, + }, + now, + ); + assert_eq!(t.active(), 0); + } + + /// **量的是生成的快慢**:首字节之前那一段不算。两个请求按 token 加权 + #[test] + fn the_rate_is_output_over_generation_time() { + let mut t = Tally::default(); + let now = Instant::now(); + // 首字节 1 秒,之后 2 秒生成了 100 个 + t.on_event(&started(1), now); + t.on_event(&headers(1, 1_000), now); + t.on_event(&finished(1, 3_000, 100), now); + assert_eq!(t.tokens_per_sec(now), Some(50)); + // 又一个:1 秒生成了 50 个。合起来 150 个 / 3 秒 + t.on_event(&started(2), now); + t.on_event(&headers(2, 500), now); + t.on_event(&finished(2, 1_500, 50), now); + assert_eq!(t.tokens_per_sec(now), Some(50)); + } + + /// 一分钟之前跑完的不算;**没有就是没有**,不是 0 + #[test] + fn an_idle_minute_has_no_rate() { + let mut t = Tally::default(); + let then = Instant::now(); + assert_eq!(t.tokens_per_sec(then), None); + t.on_event(&started(1), then); + t.on_event(&headers(1, 100), then); + t.on_event(&finished(1, 1_100, 40), then); + assert_eq!(t.tokens_per_sec(then), Some(40)); + assert_eq!( + t.tokens_per_sec(then + RATE_WINDOW + Duration::from_secs(1)), + None + ); + } + + /// 没见过响应头的(订阅之前就开始了)不知道生成用了多久,不瞎算 + #[test] + fn a_request_without_its_headers_does_not_make_up_a_rate() { + let mut t = Tally::default(); + let now = Instant::now(); + t.on_event(&finished(9, 2_000, 100), now); + assert_eq!(t.tokens_per_sec(now), None); + } + + /// 快照在路上时开始、结束的都要算进去:开始的补上,结束的去掉 + #[test] + fn a_resync_keeps_what_happened_while_the_snapshot_was_on_its_way() { + let mut t = Tally::default(); + let now = Instant::now(); + // 丢过事件:1 号的结局没收到,还挂在进行中 + t.on_event(&started(1), now); + t.begin_resync(); + // 问快照的这会儿:3 号开始了,2 号结束了 + t.on_event(&started(3), now); + t.on_event(&finished(2, 10, 0), now); + // 快照里是 2 号(问的时候还在跑)和 4 号(订阅之前就开始了) + t.finish_resync([2, 4]); + let mut open: Vec<_> = t.open.iter().copied().collect(); + open.sort(); + assert_eq!(open, [3, 4], "1 号早结束了、2 号刚结束"); + assert_eq!(t.active(), 2); + } +} diff --git a/src/App.i18n.tsx b/src/App.i18n.tsx index df36ba49..8b20f04a 100644 --- a/src/App.i18n.tsx +++ b/src/App.i18n.tsx @@ -39,6 +39,7 @@ export const appText = messages( safeMode: "安全模式 · 网关未运行", safeModeShort: "安全模式", stopped: "已停止", + cannotStart: "无法启动", // 工具栏 collapseRail: "收起源列表", @@ -166,6 +167,7 @@ export const appText = messages( safeMode: "Safe mode · Gateway stopped", safeModeShort: "Safe\u00a0mode", stopped: "Stopped", + cannotStart: "Cannot start", collapseRail: "Collapse sidebar", expandRail: "Expand sidebar", diff --git a/src/App.tsx b/src/App.tsx index c8768794..81c4ee8c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -38,6 +38,7 @@ import { import { RequestTable } from "./traffic/RequestTable"; import { SessionPanel } from "./traffic/SessionPanel"; import { useSessions } from "./traffic/useSessions"; +import { useCoreEvent } from "./useCoreEvent"; import { groupAt, groupBySession } from "./traffic/grouping"; import Dashboard from "./Dashboard"; import RequestDrawer from "./RequestDrawer"; @@ -102,6 +103,9 @@ const DAY_MS = 24 * 3_600_000; */ const MAX_TRIES = 8; +/** 概览的几个重读理由挨着到时,等这么久再读:一串只读一次 */ +const COALESCE_MS = 100; + /** core 的状态字符串来自 Rust 侧的 CoreState,见 supervisor/mod.rs。 */ /** * 主窗口的几个面。 @@ -235,6 +239,8 @@ function describeCore(raw: string): { // 安全模式必须显眼:这时候网关不转发了,用户所有的 AI 客户端都在瞎。 if (raw === "safe_mode") return { text: t.safeMode, short: t.safeModeShort, tone: "bad" }; + // 程序运行不了。原因在连接那一面上说(见 Connect 的 `trouble`) + if (raw.startsWith("failed:")) return { text: t.cannotStart, short: t.cannotStart, tone: "bad" }; return { text: t.stopped, short: t.stopped, tone: "bad" }; } @@ -256,6 +262,7 @@ export default function App() { rotated, clearRotated, clearAlerts, + upstreamState, } = useRequests(); // 排序与过滤。默认按时间倒序 —— 那是「刚才发生了什么」,也是打开这 // 一页最常见的意图。 @@ -317,6 +324,14 @@ export default function App() { new Set(allRows.map((r) => r.hint ?? "")).size > 1 || allRows.some((r) => r.peer); const searchRef = useRef(null); + /* + **任务还在进行的话,详情要跟得上。**打开一次会话多半是想看这次花了多少,而 + 那时它往往还在跑:有请求落地就重读(按事件节流,和会话列表同一个节奏)。 + */ + const [sessionTick, setSessionTick] = useState(0); + useCoreEvent(["request_finished", "request_failed", "request_cancelled"], () => { + if (openSession !== null) setSessionTick((n) => n + 1); + }); useEffect(() => { if (openSession === null) { setSessionDetail(null); @@ -337,7 +352,7 @@ export default function App() { return () => { alive = false; }; - }, [openSession]); + }, [openSession, sessionTick]); useEffect(() => { try { window.localStorage.setItem("tw-grouped", grouped ? "on" : "off"); @@ -667,7 +682,12 @@ export default function App() { * · 网关换了监听地址,或者没换成(`listening`)—— 配置换进去之后监听器 * 才开始换,只跟着配置版本重读,读到的是换之前的地址 * · 守护状态变了 —— 重启之后监听地址和 pid 都可能不一样 + * · 上游的现状变了(`upstreamState`):凭据被拒或恢复、代理不通或恢复、要 + * 重新登录、计费方式随第一次额度变成订阅制;事件流丢过事件也算 * · 用户自己刚改完东西(`nudge`) + * + * **一串触发只读一次。**启动时每个上游会连着来两条模型事件,每条都立刻重读 + * 的话,读到的是同一份概览;隔一小会儿再读,这一串就只剩最后一次。 */ useEffect(() => { let alive = true; @@ -711,12 +731,13 @@ export default function App() { /* 概览拿不到不影响状态那一半 —— 连上了就是连上了 */ } }; - void read(); + const kick = setTimeout(() => void read(), COALESCE_MS); return () => { alive = false; + clearTimeout(kick); if (timer) clearTimeout(timer); }; - }, [reloads, nudge, health, models, listening, core, setStatus, setOv]); + }, [reloads, nudge, health, models, listening, upstreamState, core, setStatus, setOv]); const c = describeCore(core); /** 连上过、又断了。**只在这时候挂那条带子** */ diff --git a/src/Connect.i18n.ts b/src/Connect.i18n.ts index ace4168f..dc740482 100644 --- a/src/Connect.i18n.ts +++ b/src/Connect.i18n.ts @@ -3,6 +3,7 @@ import { messages } from "@/i18n"; export const connectText = messages( { missing: "未找到 core 程序", + failed: "core 程序无法运行", restarting: (attempt: string) => `core 已退出,正在进行第 ${attempt} 次重启`, retryIn: (secs: number) => `${secs} 秒后重试`, safeMode: "安全模式:网关未运行", @@ -17,6 +18,7 @@ export const connectText = messages( }, { missing: "The core program was not found", + failed: "The core program could not run", restarting: (attempt: string) => `core exited; restarting (attempt ${attempt})`, retryIn: (secs: number) => `Retrying in ${secs} s`, safeMode: "Safe mode: the gateway is not running", diff --git a/src/Connect.tsx b/src/Connect.tsx index 71710c9f..19f488b3 100644 --- a/src/Connect.tsx +++ b/src/Connect.tsx @@ -37,6 +37,15 @@ export interface Trouble { */ export function trouble(raw: string, tries: number): Trouble | null { const t = textOf(connectText); + // core 程序运行不了:**原因要说出来**,等多久也不会自己好,所以给重试 + if (raw.startsWith("failed:")) { + return { + what: t.failed, + next: raw.slice("failed:".length), + bad: true, + retry: true, + }; + } if (raw.startsWith("missing:")) { return { what: t.missing, diff --git a/src/RequestDrawer.i18n.tsx b/src/RequestDrawer.i18n.tsx index 24a30eed..202860c3 100644 --- a/src/RequestDrawer.i18n.tsx +++ b/src/RequestDrawer.i18n.tsx @@ -48,6 +48,7 @@ export const requestDrawerText = messages( times: (n: number) => `出现 ${n} 次`, droppedTip: "目标格式不支持这些字段,发送前已移除。", status: "状态", + inProgress: "进行中", cancelled: "已取消:客户端在响应结束前断开连接", bytes: "字节", @@ -58,6 +59,7 @@ export const requestDrawerText = messages( failover: (failed: number) => `已发生故障转移:前 ${failed} 个上游失败,已自动切换至下一个上游。`, noRouting: "此请求没有路由信息", + routingPending: "路由尚未完成", noRoutingTip: "网关本地应答的请求、被路由规则拒绝的请求,以及上游应答之前客户端就断开的请求,不记录路由信息。", possibleCauses: "可能原因", @@ -65,6 +67,7 @@ export const requestDrawerText = messages( request: "请求", response: "响应", notSaved: "未保存", + afterEnd: "请求结束后可查看", notSavedTip: "此记录已超过保留期限。", size: (n: number) => `${n.toLocaleString()} 字节`, truncated: "仅保存开头部分", @@ -72,6 +75,7 @@ export const requestDrawerText = messages( showAll: "展开全部", // 用量。**没有用量、没有价格、估算,各说各的** + usagePending: "请求结束后可查看用量和费用", cancelledBeforeUsage: "客户端在上游报告用量前断开连接", failedBeforeUsage: "请求在上游报告用量前失败", noUsage: "上游未报告用量", @@ -109,6 +113,7 @@ export const requestDrawerText = messages( originalColumn: (upstream: string) => `${upstream}(原请求)`, replayColumn: (upstream: string) => `${upstream}(重放)`, duration: "耗时", + replayPending: "请求结束后可重放", }, { title: "Request details", @@ -140,6 +145,7 @@ export const requestDrawerText = messages( times: (n: number) => `${n} times`, droppedTip: "The target format does not support these fields; they were removed before sending.", status: "Status", + inProgress: "In progress", cancelled: "Canceled: the client disconnected before the response finished", bytes: "Bytes", @@ -151,6 +157,7 @@ export const requestDrawerText = messages( ? "Failover occurred: the first upstream failed, and the request was switched to the next upstream automatically." : `Failover occurred: the first ${failed} upstreams failed, and the request was switched to the next upstream automatically.`, noRouting: "No routing information for this request", + routingPending: "Routing has not finished yet", noRoutingTip: "Requests answered locally by the gateway, requests refused by a routing rule, and requests whose client disconnected before any upstream answered carry no routing information.", possibleCauses: "Possible causes", @@ -158,12 +165,14 @@ export const requestDrawerText = messages( request: "Request", response: "Response", notSaved: "Not saved", + afterEnd: "Available when the request ends", notSavedTip: "This record is past its retention period.", size: (n: number) => (n === 1 ? "1 byte" : `${n.toLocaleString()} bytes`), truncated: "only the beginning was saved", collapse: "Collapse", showAll: "Show all", + usagePending: "Usage and cost are available when the request ends", cancelledBeforeUsage: "The client disconnected before the upstream reported usage", failedBeforeUsage: "The request failed before the upstream reported usage", noUsage: "The upstream did not report usage", @@ -206,5 +215,6 @@ export const requestDrawerText = messages( originalColumn: (upstream: string) => `${upstream} (original)`, replayColumn: (upstream: string) => `${upstream} (replay)`, duration: "Total time", + replayPending: "Replay is available when the request ends", }, ); diff --git a/src/RequestDrawer.tsx b/src/RequestDrawer.tsx index bd483911..2585ea98 100644 --- a/src/RequestDrawer.tsx +++ b/src/RequestDrawer.tsx @@ -1,15 +1,18 @@ -import { useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; import { Tip } from "@/ui/tip"; import { cn } from "@/lib/utils"; import { invoke } from "@tauri-apps/api/core"; import { usd, type BodyView, + type CoreEvent, type Overview, type ReplayQuote, type ReplayResult, type RequestDetail, } from "./types"; +import { Badge } from "@/ui/badge"; import { Button } from "@/ui/button"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; import { Spinner } from "@/ui/spinner"; @@ -55,7 +58,16 @@ function Row({ label, value }: { label: string; value: React.ReactNode }) { * 展开会淹没一切 —— 而用户点开这个抽屉是为了看**这一次**发生了什么 * (详情抽屉)。 */ -function Body({ b, title }: { b: BodyView | null; title: string }) { +function Body({ + b, + title, + pending = false, +}: { + b: BodyView | null; + title: string; + /** 请求还在跑:没有它是因为还没到,不是过了保留期 */ + pending?: boolean; +}) { const t = useText(requestDrawerText); const [open, setOpen] = useState(false); const pretty = useMemo(() => (b ? prettyJson(b.text, b.truncated) : null), [b]); @@ -63,12 +75,16 @@ function Body({ b, title }: { b: BodyView | null; title: string }) { return (
{title}
-

- {t.notSaved} - - {t.details} - -

+ {pending ? ( +

{t.afterEnd}

+ ) : ( +

+ {t.notSaved} + + {t.details} + +

+ )}
); } @@ -180,23 +196,52 @@ export default function RequestDrawer({ const [d, setD] = useState(null); const [tab, setTab] = useState("timeline"); - useEffect(() => { - let alive = true; - (async () => { + // 换了一条就清掉上一条:取回来之前不该还画着别的请求 + useEffect(() => setD(null), [id]); + const load = useCallback( + async (alive: () => boolean) => { try { // Tauri 的 invoke 用字符串 reject,不是 Error const x = await invoke("request_detail", { id }); - if (alive) { - setD(x); - } + if (alive()) setD(x); } catch (e) { - if (alive) toast.error(errorText(e)); + if (alive()) toast.error(errorText(e)); } - })(); + }, + [id], + ); + useEffect(() => { + let alive = true; + void load(() => alive); + return () => { + alive = false; + }; + }, [load]); + + /* + **还在跑的请求,跟着它往下走。**点开的往往正是那个跑了很久的请求:响应头 + 到了有状态码,路由走完有尝试链,计价事件到了就是落库的那一刻 —— 那条事件 + 和写库在同一把锁里,这时再取,拿到的一定是完整的一份。 + */ + const running = d?.in_flight === true; + useEffect(() => { + if (!running) return; + let alive = true; + const un = listen("core-event", (e) => { + const ev = e.payload; + const mine = + (ev.kind === "request_headers" || + ev.kind === "request_routed" || + ev.kind === "request_priced") && + ev.id === id; + // 事件流丢过事件的话,结局可能就在里面 + if (mine || ev.kind === "events_dropped") void load(() => alive); + }); return () => { alive = false; + void un.then((f) => f()); }; - }, [id]); + }, [running, id, load]); const r = d?.row; @@ -222,6 +267,7 @@ export default function RequestDrawer({ {new Date(r.at_ms).toLocaleTimeString()} )} + {running && {t.inProgress}} {/* **关闭按钮在 header 这一行里,不用 Sheet 自带的那个。** @@ -259,7 +305,12 @@ export default function RequestDrawer({
- + {/* 重放要和原来那一次的结果并排比,而它还没有结果 */} + {running ? ( +

{t.replayPending}

+ ) : ( + + )}
@@ -275,13 +326,18 @@ export default function RequestDrawer({ ) } /> - + @@ -364,6 +420,9 @@ export default function RequestDrawer({ ) : r.cancelled ? ( // 不是失败,不标红:上游没有出错,是客户端先断开了 {r.status ?? "—"} · {t.cancelled} + ) : running ? ( + // 响应头到了就有状态码,流还在往下走 + r.status != null ? `${r.status} · ${t.inProgress}` : t.inProgress ) : ( (r.status ?? "—") ) @@ -421,6 +480,9 @@ export default function RequestDrawer({ )}
+ ) : running ? ( + // 还没走完:尝试链在那一跳有了结果之后才有 +

{t.routingPending}

) : (

{t.noRouting} @@ -434,13 +496,16 @@ export default function RequestDrawer({

- +
- {r.input_tokens == null && r.cancelled ? ( + {running ? ( + // 用量在结局里才到,费用在落库时才算 +

{t.usagePending}

+ ) : r.input_tokens == null && r.cancelled ? ( // 这时候不能说「上游没有报用量」—— 它还没来得及报,客户端就走了

{t.cancelledBeforeUsage}

) : r.input_tokens == null && r.error ? ( diff --git a/src/events.test.ts b/src/events.test.ts index 4be26b35..d389b6df 100644 --- a/src/events.test.ts +++ b/src/events.test.ts @@ -4,8 +4,10 @@ import { applyInFlight, interruptInFlight, type CoreEvent, + type HistoryRow, type RequestRow, } from "./types"; +import { mergeHistory } from "./useRequests"; import { coreText, plain } from "@/i18n/core.i18n"; import { setLang } from "@/i18n"; @@ -293,3 +295,97 @@ describe("core 停下时还在跑的行", () => { ); }); }); + +describe("故障转移之后的上游", () => { + /** + * 开始事件里写的是首选的候选。**服务它的是尝试链的最后一跳** —— 不改的话, + * 实时列表上这一行归给了失败的那一家,和落库之后的历史对不上。 + */ + it("以尝试链的最后一跳为准", () => { + const rows = new Map(); + applyEvent(rows, started({ provider: "relay" })); + applyEvent(rows, { + kind: "request_routed", + id: 1, + rule: "catch-all", + group: "__all__", + attempts: [ + { provider: "relay", outcome: "status", status: 503, ms: 40 }, + { provider: "official", outcome: "served", status: 200, ms: 900 }, + ], + billing: "per-token", + }); + expect(rows.get(1)?.provider).toBe("official"); + }); +}); + +/** 库里读回来的一行。默认是一次正常结束的请求 */ +function stored(over: Partial = {}): HistoryRow { + return { + id: 1, + at_ms: 1_000_000, + client: "claude-code", + provider: "official", + model: "claude-sonnet-4-5", + path: "/v1/messages", + status: 200, + ttfb_ms: 800, + duration_ms: 4_000, + bytes: 1_234, + input_tokens: 100, + output_tokens: 20, + cache_read_tokens: null, + cache_write_tokens: null, + cost_micros: 1_500, + cost_estimated: false, + error: null, + local: false, + cancelled: false, + billing: "per-token", + ...over, + }; +} + +describe("丢了结局的行,由库里补上", () => { + /** + * **记录只在结局到了才落库**,所以库里有它就说明它结束了。结局事件没送到 + * (事件流丢过事件、或者重连的间隙里)的话,不按库里补上,这一行永远在跑。 + */ + it("还在进行中的行按库里记上结局", () => { + const rows = new Map(); + applyEvent(rows, started({ provider: "relay" })); + mergeHistory(rows, [stored()], "本地应答"); + const r = rows.get(1); + expect(r?.state).toBe("done"); + expect(r?.durationMs).toBe(4_000); + expect(r?.bytes).toBe(1_234); + // 上游以库里的为准:服务它的是 official,不是开始时首选的 relay + expect(r?.provider).toBe("official"); + expect(r?.costMicros).toBe(1_500); + }); + + it("失败的记成失败,带着原因", () => { + const rows = new Map(); + applyEvent(rows, started()); + const why = { code: "gw.upstream.status", args: {}, text: "Upstream `relay` answered 503." }; + mergeHistory(rows, [stored({ status: null, error: why, input_tokens: null })], "本地应答"); + expect(rows.get(1)?.state).toBe("failed"); + expect(rows.get(1)?.error).toEqual(why); + }); + + /** 已经有结局的行不动它的结局:实时那一份和库里是同一个结局 */ + it("已经结束的行不改结局", () => { + const rows = new Map(); + applyEvent(rows, started()); + applyEvent(rows, { + kind: "request_cancelled", + id: 1, + model: "claude-sonnet-4-5", + bytes: 10, + duration_ms: 300, + }); + mergeHistory(rows, [stored({ cancelled: true })], "本地应答"); + expect(rows.get(1)?.state).toBe("cancelled"); + expect(rows.get(1)?.durationMs).toBe(300); + }); +}); diff --git a/src/format.test.ts b/src/format.test.ts index 503ca93f..6645df21 100644 --- a/src/format.test.ts +++ b/src/format.test.ts @@ -6,6 +6,7 @@ import { latency, money, repeated, + resetAt, resetIn, statusTone, tokens, @@ -226,6 +227,22 @@ describe("额度重置时间", () => { expect(resetIn(undefined)).toBeNull(); }); + /** + * core 给的是重置的时刻。**按现在去数**:同一个时刻,过一会儿再看要少一截 —— + * 以前拿到的是「还有多少秒」,存下来就是一个不会走的倒计时。 + */ + it("从时刻数到现在", () => { + const at = 1_758_000_000_000 + 3 * 3600_000; + expect(resetAt(at, 1_758_000_000_000)).toBe("3 小时后"); + expect(resetAt(at, 1_758_000_000_000 + 2 * 3600_000)).toBe("1 小时后"); + expect(resetAt(at, at)).toBe("刚刚"); + }); + /** 时刻过去了,窗口已经重置过:手上的额度是重置之前的,不能再说「多久后」 */ + it("过去的时刻不说", () => { + expect(resetAt(1_000, 2_000)).toBeNull(); + expect(resetAt(null, 2_000)).toBeNull(); + }); + /** 英文跟在动词后面(resets in 3 h),单位和中文一样短,天数分单复数 */ it("英文按调用那一刻的语言说", () => { setLang("en"); diff --git a/src/format.ts b/src/format.ts index 43cd5a07..758c4fee 100644 --- a/src/format.ts +++ b/src/format.ts @@ -226,3 +226,15 @@ export function resetIn(secs: number | null | undefined): string | null { if (hours < 24) return t.hours(hours); return t.days(Math.round(secs / 86400)); } + +/** + * 额度还有多久重置:`resetIn` 的时刻版。 + * + * core 给的是重置的**时刻**。它已经过去的话返回 null:那个窗口已经重置过了, + * 手上这份额度是重置之前的,不能再拿来说「多久后」。 + */ +export function resetAt(atMs: number | null | undefined, nowMs: number): string | null { + if (atMs == null) return null; + const secs = (atMs - nowMs) / 1000; + return secs < 0 ? null : resetIn(secs); +} diff --git a/src/keys/KeysPage.tsx b/src/keys/KeysPage.tsx index c9ee7187..ab606e75 100644 --- a/src/keys/KeysPage.tsx +++ b/src/keys/KeysPage.tsx @@ -33,6 +33,7 @@ import type { Overview, } from "@/types"; import { invoke } from "@tauri-apps/api/core"; +import { useCoreEvent } from "@/useCoreEvent"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; import { api } from "./api"; @@ -120,6 +121,24 @@ export default function KeysPage({ load(); }, [load, ov]); + /* + **最近使用和 24 小时用量跟着请求走。**配好一个客户端之后来这一页,为的就是 + 看那把密钥有没有在用 —— 请求落地之后重读这两样。在后台重读,读不到就保持 + 原样,不弹错误。接管状态跟着客户端配置的变化重读。 + */ + const loadUse = useCallback(() => { + api + .listKeys() + .then(setKeys) + .catch(() => {}); + api + .keyUsage(Date.now() - DAY_MS) + .then(setUsage) + .catch(() => {}); + }, []); + useCoreEvent(["request_finished", "request_failed", "request_cancelled"], loadUse); + useCoreEvent(["clients_changed"], load); + // 从客户端页点过来:那一行出现了就滚过去、亮一下,然后把这个请求交还 useEffect(() => { if (!focus || !keys.some((k) => k.name === focus)) return; diff --git a/src/mcp/McpPage.tsx b/src/mcp/McpPage.tsx index 97e28557..98634def 100644 --- a/src/mcp/McpPage.tsx +++ b/src/mcp/McpPage.tsx @@ -9,6 +9,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; import { useText } from "@/i18n"; import { errorText } from "@/i18n/core.i18n"; import type { AdoptResponse, McpOpRequest, McpTargetView, PlanView, ScanFinding, ScanResponse } from "@/types"; +import { useCoreEvent } from "@/useCoreEvent"; import { Extensions } from "./Extensions"; import { Findings } from "./Findings"; import { Matrix, McpConfirm } from "./Matrix"; @@ -45,26 +46,38 @@ export default function McpPage({ const [busy, setBusy] = useState(false); const [pending, setPending] = useState<{ req: McpOpRequest; plan: PlanView } | null>(null); + const fetchAll = useCallback(async () => { + const [scan, ts] = await Promise.all([ + invoke("scan_configs", { projects: [] }), + invoke("mcp_targets"), + ]); + setData(scan); + setTargets(ts); + }, []); const load = useCallback(async () => { setBusy(true); try { - const [scan, ts] = await Promise.all([ - invoke("scan_configs", { projects: [] }), - invoke("mcp_targets"), - ]); - setData(scan); - setTargets(ts); + await fetchAll(); } catch (e) { toast.error(errorText(e)); } finally { setBusy(false); } - }, []); + }, [fetchAll]); useEffect(() => { void load(); }, [load]); + /* + **配置文件变了就重扫。**扫描告警说的是磁盘上多了一个可疑的东西,客户端配置 + 变了说的是矩阵里某一格变了 —— 两件事发生时这一页可能正开着,而列表还是打开 + 那一刻扫的那一份。在后台重扫,不动「忙」的状态:用户可能正在确认一次改动。 + */ + useCoreEvent(["scan_alert", "clients_changed"], () => { + fetchAll().catch(() => {}); + }); + /** 点了格子。**先算一份改动**,不直接写 —— 和接管同一条纪律 */ async function ask(req: McpOpRequest) { setBusy(true); diff --git a/src/types.ts b/src/types.ts index 9e7cd839..7f073e1e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -227,7 +227,60 @@ export type CoreEvent = provider?: string; error?: string; at_ms: number; - }; + } + /** + * 路由走完了:命中哪条规则、试过哪几家、最终服务的那家怎么收钱。 + * + * 流量列表拿它改「上游」那一列:开始事件里的是首选的候选,故障转移之后服务它 + * 的是尝试链的最后一跳。 + */ + | { + kind: "request_routed"; + id: number; + rule: string; + group?: string | null; + attempts: AttemptView[]; + billing: string; + } + /** 上游在响应头里报了订阅额度。**事件里就是完整的数**,不用回查 */ + | { kind: "quota_seen"; id: number; provider: string; windows: QuotaWindow[]; at_ms: number } + /** 某个额度窗口用完了 */ + | { + kind: "quota_exhausted"; + id: number; + provider: string; + window: string; + resets_at_ms?: number | null; + at_ms: number; + } + /** 网关发现一个代理不通了,或者又通了。现状在概览的 `ProxyView.unreachable` 里 */ + | { + kind: "proxy_changed"; + id: number; + proxy: string; + state: "reachable" | "unreachable"; + failed?: L1Stage | null; + detail?: Msg | null; + at_ms: number; + } + /** 上游拒绝了凭据,或者又接受了。现状在概览的 `ProviderView.auth_rejected` 里 */ + | { + kind: "auth_changed"; + id: number; + provider: string; + state: "accepted" | "rejected"; + status?: number | null; + at_ms: number; + } + /** OAuth 凭据失效,要重新登录。现状在概览的 `oauth.needs_login` 里 */ + | { kind: "credential_expired"; id: number; provider: string; detail: string; at_ms: number } + /** + * 事件流丢了 `count` 条事件:只靠事件维护的状态要整体对一次账。 + * + * 两个来源:core 那边这个订阅者跟不上;或者桌面版和 core 之间的连接断过又 + * 接上 —— 那时 `count` 是 0,丢了多少不知道。 + */ + | { kind: "events_dropped"; id: number; count: number; at_ms: number }; /** `done` 之外都不会留下上游 */ export type LoginStatus = "pending" | "done" | "failed" | "expired" | "cancelled"; @@ -381,6 +434,14 @@ export function applyEvent(rows: Map, ev: CoreEvent): void { } break; } + case "request_routed": { + // 开始事件里的是首选的候选。**故障转移之后服务它的是另一家** —— 尝试链的 + // 最后一跳,和落库那一行归的是同一家 + const r = rows.get(ev.id); + const last = ev.attempts[ev.attempts.length - 1]; + if (r && last) r.provider = last.provider; + break; + } case "locally_answered": case "config_reloaded": case "listen_changed": @@ -389,8 +450,14 @@ export function applyEvent(rows: Map, ev: CoreEvent): void { case "clients_changed": case "health_changed": case "models_changed": - // 都不进请求列表。配置事件、扫描告警、熔断状态说的都是「现在 - // 什么情况」,而这张表装的是「刚才发生过什么」。App 单独接。 + case "quota_seen": + case "quota_exhausted": + case "proxy_changed": + case "auth_changed": + case "credential_expired": + case "events_dropped": + // 都不进请求列表。配置事件、扫描告警、熔断、额度、凭据、代理说的都是 + // 「现在什么情况」,而这张表装的是「刚才发生过什么」。App 单独接。 break; case "secrets_found": { const r = rows.get(ev.id); @@ -727,6 +794,11 @@ export interface RequestDetail { row: HistoryRow; request_body: BodyView | null; response_body: BodyView | null; + /** + * 请求还在跑。记录要等结局才落库,这时的 `row` 是到目前为止知道的那些:耗时、 + * 用量、费用、响应体都还没有。这个请求的计价事件到了再取一次,就是完整的 + */ + in_flight: boolean; } @@ -839,6 +911,20 @@ export interface ProxyView { has_auth: boolean; /** 哪些上游在用它。删之前要知道,改名时它们会跟着改 */ used_by: string[]; + /** + * 网关发现它不通了:经它转发的请求连不上之后检过一次。之后经它的请求成功了、 + * 或者再检一次通了,就又没有了。**网关不定时探测**,没有它不等于刚测过是通的 + */ + unreachable?: ProxyFault | null; +} + +/** 网关发现一个代理不通时,检出来的样子 */ +export interface ProxyFault { + /** 卡在哪一步。说不出来的没有 */ + failed?: L1Stage | null; + detail: Msg; + /** 什么时候检的 */ + at_ms: number; } /** 一类客户端辅助请求的处置 */ @@ -1024,6 +1110,8 @@ export interface ProviderView { model_count: number; disabled: boolean; health: "ok" | "open"; + /** 上游拒绝了凭据:最近一次得到答复的请求回的状态码(401 / 403)。没被拒是空的 */ + auth_rejected?: number | null; /** 配置里写明的计费方式。null = 自动识别 */ billing?: string | null; /** 实际按什么计费 */ @@ -2053,6 +2141,7 @@ export interface QuotaWindow { /** `5h` / `7d`(Anthropic)/ `weekly`(Codex) */ window: string; used_percent: number; - reset_in_secs: number | null; - status: string | null; + /** 什么时候重置,Unix 毫秒。是时刻,不是「还有多少秒」。上游没说就没有 */ + resets_at_ms?: number | null; + status?: string | null; } diff --git a/src/upstreams/ChatgptAccountSection.tsx b/src/upstreams/ChatgptAccountSection.tsx index c8f703b8..c453907b 100644 --- a/src/upstreams/ChatgptAccountSection.tsx +++ b/src/upstreams/ChatgptAccountSection.tsx @@ -16,7 +16,8 @@ import { Input } from "@/ui/input"; import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; import { Progress } from "@/ui/progress"; import { Spinner } from "@/ui/spinner"; -import { resetIn } from "@/format"; +import { resetAt, resetIn } from "@/format"; +import { useNow } from "@/useNow"; import type { ChatgptUsage, Overview, ProviderView, ResetCredits, ResetCreditView } from "@/types"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; @@ -53,6 +54,7 @@ export function ChatgptAccountSection({ }) { const t = useText(chatgptAccountText); const common = useText(commonText); + const now = useNow(); /** 上游的状态词。认不出来的原样显示 —— 编不出来的说法比一个陌生的词更糟 */ const status: Record = t.status; /** 用一张卡的结果 */ @@ -153,7 +155,7 @@ export function ChatgptAccountSection({ ) : usage && usage.windows.length > 0 ? (
{usage.windows.map((w) => { - const reset = resetIn(w.reset_in_secs); + const reset = resetAt(w.resets_at_ms, now); return (
diff --git a/src/upstreams/ProxyTable.tsx b/src/upstreams/ProxyTable.tsx index c9dd4c91..bdb31cf5 100644 --- a/src/upstreams/ProxyTable.tsx +++ b/src/upstreams/ProxyTable.tsx @@ -8,15 +8,15 @@ import { TableHeader, TableRow, } from "@/ui/table"; -import type { L1Result, ProxyView } from "@/types"; +import type { L1Result, ProxyFault, ProxyView } from "@/types"; import { useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; -import { l1ErrorText, proxyKindLabel } from "./labels"; +import { l1ErrorText, proxyFaultText, proxyKindLabel } from "./labels"; import { NameChips, StatusDot } from "./parts"; import { proxyTableText } from "./ProxyTable.i18n"; -/** 一个代理最近一次检测的结果。`running` = 正在检测 */ -export type ProxyCheck = { running: true } | { running: false; result: L1Result }; +/** 一个代理最近一次手动检测的结果。`running` = 正在检测;`at` = 什么时候测完的 */ +export type ProxyCheck = { running: true } | { running: false; result: L1Result; at: number }; export function ProxyTable({ proxies, @@ -67,7 +67,7 @@ export function ProxyTable({ - + @@ -81,10 +81,19 @@ export function ProxyTable({ ); } -function Connectivity({ check }: { check: ProxyCheck | undefined }) { +/** + * 通不通。**两个来源,哪个新用哪个**:用户手动测的,和网关转发失败之后自己检出来的。 + * 网关检出不通的时候,列上不能还挂着一小时前手动测出的「通」。 + */ +function Connectivity({ + check, + fault, +}: { + check: ProxyCheck | undefined; + fault: ProxyFault | null | undefined; +}) { const t = useText(proxyTableText); - if (!check) return {t.notChecked}; - if (check.running) { + if (check?.running) { return ( @@ -92,6 +101,14 @@ function Connectivity({ check }: { check: ProxyCheck | undefined }) { ); } + if (fault && (!check || fault.at_ms > check.at)) { + return ( + + {t.unreachable} + + ); + } + if (!check) return {t.notChecked}; const r = check.result; if (!r.ok) { return ( diff --git a/src/upstreams/UpstreamTable.i18n.ts b/src/upstreams/UpstreamTable.i18n.ts index 2a20511e..bc8f6c81 100644 --- a/src/upstreams/UpstreamTable.i18n.ts +++ b/src/upstreams/UpstreamTable.i18n.ts @@ -9,6 +9,11 @@ export const upstreamTableText = messages( ttfb: "首字节 P50", disabled: "已停用", circuitOpen: "熔断中", + authRejected: "凭据被拒", + authRejectedTip: (status: number) => + `上游返回未授权(${status}),该上游的凭据可能已失效。`, + needsLogin: "需要重新登录", + needsLoginTip: "账号的登录已失效。重新登录之前,经此上游的请求都会失败。", actions: (name: string) => `${name} 的操作`, check: "检测连接", linkTest: "链路测速", @@ -37,6 +42,12 @@ export const upstreamTableText = messages( ttfb: "TTFB P50", disabled: "Disabled", circuitOpen: "Circuit open", + authRejected: "Credential rejected", + authRejectedTip: (status: number) => + `The upstream returned an unauthorized response (${status}). The credential for this upstream may no longer be valid.`, + needsLogin: "Sign in again", + needsLoginTip: + "The account's sign-in has expired. Until the account is signed in again, requests through this upstream will fail.", actions: (name: string) => `Actions for ${name}`, check: "Check connection", linkTest: "Connection test", diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index 48e16bf5..c9b5699e 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -12,7 +12,9 @@ import { TableHeader, TableRow, } from "@/ui/table"; -import { resetIn } from "@/format"; +import { resetAt } from "@/format"; +import { Tip } from "@/ui/tip"; +import { useNow } from "@/useNow"; import { Spinner } from "@/ui/spinner"; import { textOf, useText } from "@/i18n"; import { commonText } from "@/i18n/common.i18n"; @@ -64,6 +66,8 @@ export function UpstreamTable({ actions: UpstreamActions; }) { const t = useText(upstreamTableText); + // 额度的「多久后重置」随时间走:重画就行,不用再问 core + const now = useNow(); return ( @@ -102,9 +106,25 @@ export function UpstreamTable({ )} {p.disabled ? ( {t.disabled} - ) : p.health === "open" ? ( - {t.circuitOpen} - ) : null} + ) : ( + <> + {/* + 熔断看不见凭据的问题:4xx 不算失败,凭据坏掉的上游永远不会熔断。 + 这两个要自己说 + */} + {p.oauth?.needs_login && ( + + {t.needsLogin} + + )} + {p.auth_rejected != null && ( + + {t.authRejected} + + )} + {p.health === "open" && {t.circuitOpen}} + + )} {/* 协议、地址、出站方式是同一件事的三个部分:这一家在哪、怎么连。 @@ -113,7 +133,7 @@ export function UpstreamTable({ actions.editModels(p.name)} /> - + @@ -232,16 +252,28 @@ function ModelsCell({ p, onEdit }: { p: ProviderView; onEdit: () => void }) { * 而计费方式(订阅制)在额度条出现的那一刻已经不言自明。**上游没报过额度就 * 退回说计费方式**:画一根 0% 的空条等于说「一点没用」,而事实是不知道。 */ -function QuotaCell({ p, stats }: { p: ProviderView; stats: UpstreamStats | null }) { +function QuotaCell({ + p, + stats, + now, +}: { + p: ProviderView; + stats: UpstreamStats | null; + now: number; +}) { const t = useText(upstreamTableText); - const windows = stats?.quotas.find((q) => q.provider === p.name)?.windows ?? []; + // **过了重置时刻的窗口不算数**:手上的百分比是重置之前的,下一个请求才会带来 + // 新的。拿它画一根满格的条,说的是一件已经不成立的事 + const windows = (stats?.quotas.find((q) => q.provider === p.name)?.windows ?? []).filter( + (w) => w.resets_at_ms == null || w.resets_at_ms > now, + ); // 最紧张的那个窗口:先到的那条线决定什么时候用完 const tight = windows.reduce<(typeof windows)[number] | null>( (a, w) => (!a || w.used_percent > a.used_percent ? w : a), null, ); if (tight && !p.disabled) { - const reset = resetIn(tight.reset_in_secs); + const reset = resetAt(tight.resets_at_ms, now); return (
diff --git a/src/upstreams/UpstreamsPage.tsx b/src/upstreams/UpstreamsPage.tsx index 43a7786c..964d2ece 100644 --- a/src/upstreams/UpstreamsPage.tsx +++ b/src/upstreams/UpstreamsPage.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useRef, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; import { ActivityIcon, CircleAlertIcon, PlusIcon, RefreshCwIcon, ServerIcon, ZapIcon } from "lucide-react"; import { toast } from "sonner"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/ui/alert"; @@ -15,7 +16,8 @@ import { Spinner } from "@/ui/spinner"; import { Switch } from "@/ui/switch"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/ui/tabs"; import { useText } from "@/i18n"; -import type { ChatgptUsage, Overview, PricingStatus } from "@/types"; +import type { ChatgptUsage, CoreEvent, Overview, PricingStatus } from "@/types"; +import { useCoreEvent } from "@/useCoreEvent"; import { api, type UpstreamStats } from "./api"; import { ChatgptLoginDialog } from "./ChatgptLoginDialog"; import { DeleteDialog, type Referrer } from "./DeleteDialog"; @@ -98,11 +100,41 @@ export default function UpstreamsPage({ .catch((e) => toast.error(errorText(e))); }, []); + /** + * 24 小时的请求数、费用和首字节耗时。 + * + * **请求落地之后重读**,不按时间轮询:这几个数只在请求落地时才变。随时间变的 + * 只有 24 小时这个窗口本身在往前滑 —— 长时间没有请求时没有事件叫醒它,窗口 + * 重新拿到焦点时补一次。 + */ useEffect(() => { loadStats(); - const t = setInterval(loadStats, 30_000); - return () => clearInterval(t); + window.addEventListener("focus", loadStats); + return () => window.removeEventListener("focus", loadStats); }, [loadStats]); + useCoreEvent(["request_finished", "request_failed", "request_cancelled"], loadStats); + + /** + * 订阅额度。**事件里就是完整的数**(和 `/quota` 同一份),收到直接换上: + * 额度变的那一刻就是这条事件到的那一刻。 + */ + useEffect(() => { + const un = listen("core-event", (e) => { + const ev = e.payload; + if (ev.kind !== "quota_seen") return; + setStats( + (s) => + s && { + ...s, + quotas: [ + ...s.quotas.filter((q) => q.provider !== ev.provider), + { provider: ev.provider, windows: ev.windows }, + ], + }, + ); + }); + return () => void un.then((f) => f()); + }, []); /** * 账号类上游:**打开这一页时问一次它自己。** @@ -112,7 +144,7 @@ export default function UpstreamsPage({ * 或者这个账号今天还没被用过时,不问就什么都没有。 * * **每个上游只问一次。**问一次是一次真实调用;失败了也不再问 —— 连不上时 - * 三十秒重试一轮,只会把错误刷满日志。 + * 反复重试,只会把错误刷满日志。 */ const [accounts, setAccounts] = useState>({}); const askedUsage = useRef(new Set()); @@ -192,13 +224,14 @@ export default function UpstreamsPage({ proxy: { name: x.name, kind: x.kind, addr: x.addr, auth: { mode: "keep" } }, current: x.name, }); - setChecks((c) => ({ ...c, [name]: { running: false, result } })); + setChecks((c) => ({ ...c, [name]: { running: false, result, at: Date.now() } })); } catch (e) { setChecks((c) => ({ ...c, [name]: { running: false, result: { target: name, ok: false, segments: [], total_ms: 0, error: plain(errorText(e)) }, + at: Date.now(), }, })); } diff --git a/src/upstreams/labels.ts b/src/upstreams/labels.ts index 56b5c37f..57cc9a01 100644 --- a/src/upstreams/labels.ts +++ b/src/upstreams/labels.ts @@ -14,6 +14,7 @@ import type { PriceFields, PriceSourceView, ProviderView, + ProxyFault, } from "@/types"; import { labelsText } from "./labels.i18n"; @@ -181,6 +182,12 @@ export function quotaWindowLabel(window: string): string { } /** 建连的一步。对着代理的那几步带上「代理」,代理握手本身不用 */ +/** 网关检出一个代理不通时的原因,写法和 `l1ErrorText` 一样:卡在哪一步,为什么 */ +export function proxyFaultText(f: ProxyFault): string { + const t = textOf(labelsText); + const error = coreText(f.detail); + return f.failed ? t.stageError(l1StageLabel(f.failed), error) : error; +} export function l1StageLabel(s: L1Stage): string { const t = textOf(labelsText); const step = t.l1Steps[s.step] ?? s.step; diff --git a/src/useCoreEvent.ts b/src/useCoreEvent.ts index 5d33def6..41effb01 100644 --- a/src/useCoreEvent.ts +++ b/src/useCoreEvent.ts @@ -17,6 +17,9 @@ import type { CoreEvent } from "./types"; * * 每个页面自己订阅,不从 App 一层层传下去:Tauri 的事件通道本来就支持 * 多个监听者,而「这一页关心哪几种事件」写在这一页里才看得懂。 + * + * **事件流丢过事件(`events_dropped`)也回调**:丢掉的那几条里可能正有这一页 + * 关心的,当它们发生过,重读一次。 */ export function useCoreEvent( kinds: readonly CoreEvent["kind"][], @@ -30,7 +33,7 @@ export function useCoreEvent( const want = kinds.join(","); useEffect(() => { - const set = new Set(want.split(",")); + const set = new Set([...want.split(","), "events_dropped"]); let timer: ReturnType | null = null; const un = listen("core-event", (e) => { if (!set.has(e.payload.kind) || timer) return; diff --git a/src/useLive.ts b/src/useLive.ts index ed4b88d1..ff3f7ddd 100644 --- a/src/useLive.ts +++ b/src/useLive.ts @@ -55,6 +55,9 @@ export const LIVE_REACH_MS = 3 * LIVE_SIGMA_MS; */ export const LIVE_FRAME_MS = LIVE_BUCKET_MS / 10; +/** 事件流丢过事件之后,等这么久再从库里补:丢掉的那些结局落库要一点时间 */ +const REFILL_MS = 2_500; + /** 连续高斯的积分是 σ√2π。除掉它、再换算到秒,核就读作「每秒多少」 */ const PER_SECOND = 1_000 / (LIVE_SIGMA_MS * Math.sqrt(2 * Math.PI)); const TWO_SIGMA_SQ = 2 * LIVE_SIGMA_MS * LIVE_SIGMA_MS; @@ -207,6 +210,14 @@ export function useLive(active: boolean, windowMs: number) { }); } if (!failedAlready(ev.id)) fails.current.push({ id: ev.id, at: Date.now() }); + } else if (ev.kind === "events_dropped") { + /* + **丢过事件:进行中的重新对账,丢掉的结局从库里补进曲线。**落库要一点 + 时间,等一会儿再补;补的时候按 id 去重,事件流上已经画了的不会画两遍。 + */ + void resync(); + setTimeout(() => void seed(), REFILL_MS); + return; } else { return; } @@ -250,7 +261,7 @@ export function useLive(active: boolean, windowMs: number) { /* 先挂事件流再补历史:反过来的话,这两者之间结束的请求谁都不记。 */ - void (async () => { + const seed = async () => { try { // 挂上了再补 —— `listen` 是异步注册的,理由同上 await un; @@ -301,7 +312,8 @@ export function useLive(active: boolean, windowMs: number) { } catch { // 读不到就只画事件流那一半,和补这一段之前一样 } - })(); + }; + void seed(); const h = setInterval(() => { const cut = Date.now() - windowMs; diff --git a/src/useNow.ts b/src/useNow.ts new file mode 100644 index 00000000..4aa85a5a --- /dev/null +++ b/src/useNow.ts @@ -0,0 +1,16 @@ +import { useEffect, useState } from "react"; + +/** + * 现在的时刻,每隔一段时间更新一次。 + * + * **给只随时间变化的文字用**,比如额度的「多久后重置」:数据没变,是时间在走。 + * 用它的组件自己重画,不去问 core —— 问了也是同一个答案。 + */ +export function useNow(periodMs = 30_000): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const h = setInterval(() => setNow(Date.now()), periodMs); + return () => clearInterval(h); + }, [periodMs]); + return now; +} diff --git a/src/useRequests.ts b/src/useRequests.ts index 1c6501c8..f668e023 100644 --- a/src/useRequests.ts +++ b/src/useRequests.ts @@ -15,6 +15,82 @@ import { import { marksFromEvents } from "./security/marks"; import { requestsText } from "./useRequests.i18n"; +/** + * 库里读回来的记录并进当前列表。 + * + * **只补,不覆盖。**实时那一行更全 —— 脱敏和可疑工具调用只在事件里有,库里没有。 + * 合并的方向是「历史只添信息」,两个例外:还在「进行中」的行按库里记上结局,上游 + * 以库里的为准(理由写在循环里)。 + * + * `localLabel`:本地应答那几行的「上游」一栏写什么。 + */ +export function mergeHistory( + rows: Map, + history: HistoryRow[], + localLabel: string, +): void { + for (const h of history) { + const cur = rows.get(h.id); + if (cur) { + /* + **还在「进行中」的行,库里已经有了它**:记录只在结局到了才落库,所以它 + 确实结束了,只是结局事件没送到(事件流丢过事件、或者在重连的间隙里)。 + 按库里的补上结局,不然这一行永远在跑。 + */ + if (cur.state === "in_flight") { + cur.state = h.error ? "failed" : h.cancelled ? "cancelled" : "done"; + if (h.status != null) cur.status = h.status; + cur.durationMs = h.duration_ms ?? undefined; + cur.bytes = h.bytes ?? undefined; + cur.error = h.error ?? undefined; + } + // 上游以库里的为准:故障转移之后服务它的是尝试链的最后一跳 + if (!h.local) cur.provider = h.provider; + cur.model ??= h.model || undefined; + if (h.input_tokens != null) cur.inputTokens = h.input_tokens; + if (h.output_tokens != null) cur.outputTokens = h.output_tokens; + if (h.cost_micros != null) { + cur.costMicros = h.cost_micros; + cur.costEstimated = h.cost_estimated; + } + cur.translated ??= h.translated ?? undefined; + // **会话 id 只有库里有。**事件里那个是指纹,差着起始时刻 + cur.session = h.session ?? cur.session; + const marks = marksFromEvents(h.security); + cur.secrets ??= marks.secrets; + cur.flagged ??= marks.flagged; + cur.hint ??= h.client_hint ?? undefined; + cur.peer ??= h.peer ?? undefined; + cur.keyMasked ??= h.key_masked ?? undefined; + continue; + } + rows.set(h.id, { + id: h.id, + client: h.client, + provider: h.local ? localLabel : h.provider, + model: h.model || undefined, + path: h.path, + atMs: h.at_ms, + state: h.error ? "failed" : h.cancelled ? "cancelled" : "done", + status: h.status ?? undefined, + ttfbMs: h.ttfb_ms ?? undefined, + durationMs: h.duration_ms ?? undefined, + bytes: h.bytes ?? undefined, + inputTokens: h.input_tokens ?? undefined, + outputTokens: h.output_tokens ?? undefined, + costMicros: h.cost_micros ?? undefined, + costEstimated: h.cost_estimated, + error: h.error ?? undefined, + translated: h.translated ?? undefined, + session: h.session ?? undefined, + hint: h.client_hint ?? undefined, + peer: h.peer ?? undefined, + keyMasked: h.key_masked ?? undefined, + ...marksFromEvents(h.security), + }); + } +} + /** 列表上限。超过就丢最老的 —— 实时视图不是历史,历史在 SQLite 里。 */ const MAX_ROWS = 500; @@ -112,6 +188,14 @@ export function useRequests() { * 监听器才开始换,只跟着配置版本重读状态,读到的是换之前的地址。 */ const [listening, setListening] = useState(0); + /** + * 上游的现状变了几次:凭据被拒或者恢复、代理不通或者恢复、要重新登录、第一次 + * 报额度(没写明计费方式的,从这一刻起按订阅制算)。**这些都在概览里**,App + * 据此重读。事件流丢过事件时也算一次:丢掉的里面可能就有它们。 + */ + const [upstreamState, setUpstreamState] = useState(0); + /** 这次开窗以来报过额度的上游。只有第一次会改变计费方式 */ + const quotaSeen = useRef(new Set()); /** @@ -120,8 +204,7 @@ export function useRequests() { * **只在开窗时用一次。**在此之前它还兼着「回库把价钱取回来」—— * 因为价钱不在事件流里。core 现在会报 `request_priced`,那条路没了。 * - * **只补,不覆盖。**实时那一行更全 —— 脱敏和可疑工具调用只在事件里有, - * 库里没有。合并的方向必须是「历史只添信息」。 + * 怎么并见 `mergeHistory`:历史只添信息,结局没送到的行按库里补上。 */ const pull = useCallback(async () => { // Tauri 的 invoke 用字符串 reject,不是 Error @@ -135,52 +218,7 @@ export function useRequests() { const history = await invoke("recent_requests", { limit: 2000, }); - for (const h of history) { - const cur = store.current.get(h.id); - if (cur) { - cur.model ??= h.model || undefined; - if (h.input_tokens != null) cur.inputTokens = h.input_tokens; - if (h.output_tokens != null) cur.outputTokens = h.output_tokens; - if (h.cost_micros != null) { - cur.costMicros = h.cost_micros; - cur.costEstimated = h.cost_estimated; - } - cur.translated ??= h.translated ?? undefined; - // **会话 id 只有库里有。**事件里那个是指纹,差着起始时刻 - cur.session = h.session ?? cur.session; - const marks = marksFromEvents(h.security); - cur.secrets ??= marks.secrets; - cur.flagged ??= marks.flagged; - cur.hint ??= h.client_hint ?? undefined; - cur.peer ??= h.peer ?? undefined; - cur.keyMasked ??= h.key_masked ?? undefined; - continue; - } - store.current.set(h.id, { - id: h.id, - client: h.client, - provider: h.local ? textOf(requestsText).answeredLocally : h.provider, - model: h.model || undefined, - path: h.path, - atMs: h.at_ms, - state: h.error ? "failed" : h.cancelled ? "cancelled" : "done", - status: h.status ?? undefined, - ttfbMs: h.ttfb_ms ?? undefined, - durationMs: h.duration_ms ?? undefined, - bytes: h.bytes ?? undefined, - inputTokens: h.input_tokens ?? undefined, - outputTokens: h.output_tokens ?? undefined, - costMicros: h.cost_micros ?? undefined, - costEstimated: h.cost_estimated, - error: h.error ?? undefined, - translated: h.translated ?? undefined, - session: h.session ?? undefined, - hint: h.client_hint ?? undefined, - peer: h.peer ?? undefined, - keyMasked: h.key_masked ?? undefined, - ...marksFromEvents(h.security), - }); - } + mergeHistory(store.current, history, textOf(requestsText).answeredLocally); setRows([...store.current.values()].sort((a, b) => b.id - a.id)); }, []); @@ -249,6 +287,16 @@ export function useRequests() { if (ev.kind === "health_changed") setHealth((n) => n + 1); if (ev.kind === "models_changed") setModels((n) => n + 1); if (ev.kind === "listen_changed") setListening((n) => n + 1); + if ( + ev.kind === "auth_changed" || + ev.kind === "proxy_changed" || + ev.kind === "credential_expired" || + ev.kind === "events_dropped" || + (ev.kind === "quota_seen" && !quotaSeen.current.has(ev.provider)) + ) { + setUpstreamState((n) => n + 1); + } + if (ev.kind === "quota_seen") quotaSeen.current.add(ev.provider); if (ev.kind === "locally_answered") local += 1; if (ev.kind === "config_rejected") setRejected(ev); if (ev.kind === "scan_alert") setAlerts((prev) => [...ev.alerts, ...prev].slice(0, 50)); @@ -264,13 +312,17 @@ export function useRequests() { } if (local > 0) setLocallyAnswered((n) => n + local); publish(); - // 落地一批就发一次「可以重算聚合了」。**已经排上的不再往后推** - if (landed && !settle.current) { - settle.current = setTimeout(() => { - settle.current = null; - setSettled((n) => n + 1); - }, SETTLE_MS); - } + // 落地一批就发一次「可以重算聚合了」 + if (landed) settleSoon(); + }; + + /** 过一会儿发一次「库里可以重算了」。**已经排上的不再往后推** */ + const settleSoon = () => { + if (settle.current) return; + settle.current = setTimeout(() => { + settle.current = null; + setSettled((n) => n + 1); + }, SETTLE_MS); }; const schedule = () => { @@ -303,6 +355,15 @@ export function useRequests() { } pending.current.push(ev); schedule(); + /* + **丢过事件,就整体对一次账。**进行中的问 core 要快照;丢掉的那些结局落库 + 要一点时间,到时候照「落地之后对账」的那条路从库里补 —— 补的时候还在 + 「进行中」的行会按库里的记上结局(见 `pull`)。 + */ + if (ev.kind === "events_dropped") { + void resync(); + settleSoon(); + } }); const resync = async () => { const mark: SeenSince = { started: new Set(), ended: new Set() }; @@ -356,6 +417,7 @@ export function useRequests() { health, models, listening, + upstreamState, locallyAnswered, rejected, reloads,