diff --git a/README.md b/README.md index 86464ca8..4f9ff17e 100644 --- a/README.md +++ b/README.md @@ -129,9 +129,10 @@ step-by-step instructions. The menu bar shows today's cost and the output rate; for a subscription account it shows the quota used and the time until it resets instead. System -notifications report when the gateway stops forwarding, an upstream becomes -unreachable, a subscription quota runs out or a credential stops working; each -kind can be set to a system notification, in-app only, or off. +notifications report when the gateway stops forwarding, a subscription quota +runs out or a credential stops working; an unreachable upstream, which a +fallback usually covers, is only listed in the app. Notices as a whole can be +set to system notifications, in-app only, or off.

diff --git a/README.zh-CN.md b/README.zh-CN.md index dc335762..6cc9394c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -113,8 +113,8 @@ Cursor、Continue 与 Gemini CLI 提供逐步的手动配置说明。 ### 菜单栏与系统通知 菜单栏常驻显示今日费用与输出速率;使用订阅账号时改为显示额度用量与重置倒计时。 -网关停止转发、上游无法连接、订阅额度用完、凭据失效等情况会发送系统通知,每一类 -都可以设为系统通知、仅在应用内显示或关闭。 +网关停止转发、订阅额度用完、凭据失效等情况会发送系统通知;上游无法连接多半有回退 +接住,只记录在应用内。提醒可以整体设为系统通知、仅在应用内显示或关闭。

diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index ab835a4b..da400c85 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4982,8 +4982,8 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "tw-api" -version = "0.15.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.15.0#3da23865e7db8cc0504f9fa28cb5b97974f59647" +version = "0.16.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.16.0#f724f304613d63739e980af6898e6301a876cf4c" dependencies = [ "serde", "serde_json", @@ -4992,8 +4992,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.15.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.15.0#3da23865e7db8cc0504f9fa28cb5b97974f59647" +version = "0.16.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.16.0#f724f304613d63739e980af6898e6301a876cf4c" dependencies = [ "serde", "serde_json", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index a8b3f5a1..d1f72ab0 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.15.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.16.0" } anyhow = "1" libc = "0.2" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fa0b6daf..a42cdb41 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1467,8 +1467,8 @@ pub fn run() { upstreams::test_proxy, notices_list, dismiss_notice, - notice_prefs, - set_notice_pref, + notice_mode, + set_notice_mode, take_pending_view, keys::list_keys, keys::create_key, @@ -1575,6 +1575,7 @@ pub fn run() { system, ], Some(data_dir()), + saved.notices, ); app.manage(notices.clone()); app.manage(AppState { @@ -1886,44 +1887,29 @@ fn take_pending_view() -> Option { notices::take_pending_view() } -/// 设置页上的一行:一类提醒,和它现在怎么对待 -#[derive(serde::Serialize)] -struct NoticePref { - category: notices::Category, - label: &'static str, - mode: notices::Mode, -} - -fn notice_prefs_view(n: ¬ices::Notices) -> Vec { - n.modes() - .into_iter() - .map(|(category, mode)| NoticePref { - category, - label: category.label(), - mode, - }) - .collect() -} - +/// 提醒现在是哪一档 #[tauri::command] -fn notice_prefs(notices: tauri::State<'_, Arc>) -> Vec { - notice_prefs_view(¬ices) +fn notice_mode(notices: tauri::State<'_, Arc>) -> notices::Mode { + notices.mode() } -/// 改一类提醒的对待方式。**返回改完之后的全部**,界面以它为准 +/// 换一档。**先存盘再生效**:存不进去的话,界面弹回去,总线也还是原来那一档。 +/// 工具栏的铃铛听 `notice-mode-changed` —— 关掉之后它不该还在那儿 #[tauri::command] -fn set_notice_pref( +fn set_notice_mode( + app: tauri::AppHandle, notices: tauri::State<'_, Arc>, - category: notices::Category, mode: notices::Mode, -) -> Result, String> { - notices.set_mode(category, mode).map_err(|e| { +) -> Result { + prefs::update(&data_dir(), |p| p.notices = mode).map_err(|e| { tr!( - format!("无法保存设置:{e}"), - format!("The setting could not be saved: {e}") + format!("无法保存设置:{e:#}"), + format!("The setting could not be saved: {e:#}") ) })?; - Ok(notice_prefs_view(¬ices)) + notices.set_mode(mode); + let _ = app.emit("notice-mode-changed", mode); + Ok(mode) } /// 第一次开机自启之后提示一次「我在菜单栏这儿」,之后永不再弹。 diff --git a/src-tauri/src/notices/macos/mod.rs b/src-tauri/src/notices/macos/mod.rs index 8cb608de..bcd69af1 100644 --- a/src-tauri/src/notices/macos/mod.rs +++ b/src-tauri/src/notices/macos/mod.rs @@ -36,7 +36,7 @@ impl Sink for NativeSink { notice.key.clone(), notice.title.clone(), notice.body.clone(), - thread_of(notice), + thread_of(¬ice.key), false, ); } @@ -58,7 +58,7 @@ impl Sink for NativeSink { notice.key.clone(), title, notice.body.clone(), - thread_of(notice), + thread_of(¬ice.key), true, ); } @@ -68,10 +68,7 @@ impl Sink for NativeSink { } } -/// 同一类的归在一起:用类别的标识做 thread -fn thread_of(notice: &Notice) -> String { - serde_json::to_value(notice.category) - .ok() - .and_then(|v| v.as_str().map(str::to_string)) - .unwrap_or_default() +/// 同一种的归在一起:用键的种类(冒号前那段)做 thread +fn thread_of(key: &str) -> String { + key.split(':').next().unwrap_or(key).to_string() } diff --git a/src-tauri/src/notices/mod.rs b/src-tauri/src/notices/mod.rs index a1038f1e..efd5eba0 100644 --- a/src-tauri/src/notices/mod.rs +++ b/src-tauri/src/notices/mod.rs @@ -17,6 +17,12 @@ //! //! 恢复默认**静默撤回**:一条撤不回来的通知,代价是用户把整个应用的通知关掉。 //! +//! # 用户能调的只有一个开关 +//! +//! 系统通知 / 仅在应用内 / 关闭([`Mode`]),**不分类**。哪一类该不该打断人, +//! 由上面这几关和每条规则给的级别决定 —— 那是这里的判断,不该变成设置页上的 +//! 一长串下拉。 +//! //! # 平台 //! //! 投递是 [`Sink`],系统通知只是其中一个实现。Windows 要加的是一个 sink, @@ -28,12 +34,10 @@ use std::time::{Duration, Instant}; #[cfg(target_os = "macos")] pub mod macos; -pub mod prefs; pub mod rules; pub mod sink; mod store; -pub use prefs::{Category, Mode}; pub use sink::{Sink, SystemSink}; /// 去抖:故障类要持续这么久才说。用户已经在等结果的那几件事不等(见 [`Signal::hold`]) @@ -70,6 +74,18 @@ impl Level { } } +/// 提醒怎么对待。存在应用设置里(`app.json`),出厂是系统通知 +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Mode { + /// 级别够的弹系统通知,全部进应用内的提醒列表 + System, + /// 只进应用内的提醒列表 + App, + /// 不记录,工具栏也不放铃铛 + Off, +} + /// 出事了,还是恢复了 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Change { @@ -146,8 +162,6 @@ impl Signal { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Notice { pub key: String, - /// 属于哪一类。「不再通知此类」按它来 - pub category: Category, pub level: Level, pub title: String, pub body: String, @@ -190,26 +204,25 @@ struct State { pub struct Notices { state: Mutex, sinks: Vec>, - /// 每一类怎么对待 - prefs: Mutex, - /// 落盘的目录。关窗期间发生的事要留得住,设置也在这里 + /// 用户选的那一档。**存盘不归这里管**:它和其他应用设置在同一个文件里 + mode: Mutex, + /// 落盘的目录。关窗期间发生的事要留得住 dir: Option, } const OPEN_FILE: &str = "notices.json"; -const PREFS_FILE: &str = "notice-prefs.json"; impl Notices { /// `dir` 是留存的目录;`None` 表示只在内存里(测试用) - pub fn new(sinks: Vec>, dir: Option) -> Arc { + pub fn new( + sinks: Vec>, + dir: Option, + mode: Mode, + ) -> Arc { let open = dir .as_deref() .map(|d| store::load(&d.join(OPEN_FILE))) .unwrap_or_default(); - let prefs = dir - .as_deref() - .map(|d| prefs::load(&d.join(PREFS_FILE))) - .unwrap_or_default(); Arc::new(Self { state: Mutex::new(State { open: open @@ -229,60 +242,46 @@ impl Notices { ..Default::default() }), sinks, - prefs: Mutex::new(prefs), + mode: Mutex::new(mode), dir, }) } - /// 每一类现在怎么对待,按设置页的顺序 - pub fn modes(&self) -> Vec<(Category, Mode)> { - let p = self.prefs.lock().expect("锁未中毒"); - Category::ALL.iter().map(|c| (*c, p.mode(*c))).collect() + pub fn mode(&self) -> Mode { + *self.mode.lock().expect("锁未中毒") } - /// 改一类的对待方式。**改成「关闭」时,这一类挂着的也一并撤掉** —— 用户说的是 - /// 「这类事别再出现」,留着一条旧的等于没听见 - pub fn set_mode(&self, category: Category, mode: Mode) -> std::io::Result<()> { - let saved = { - let mut p = self.prefs.lock().expect("锁未中毒"); - p.set(category, mode); - p.clone() - }; - if let Some(dir) = &self.dir { - prefs::save(&dir.join(PREFS_FILE), &saved)?; + /// 换一档。**只动内存**,存盘由调用方和其他应用设置一起做。 + /// + /// 换成「关闭」时,挂着的也一并撤掉 —— 用户说的是「别再出现」,留着一条旧的 + /// 等于没听见。换成「仅在应用内」不撤:已经弹出去的那几条是事实,还在去抖的 + /// 那些到点时会看到新的一档,不再弹。 + pub fn set_mode(&self, mode: Mode) { + *self.mode.lock().expect("锁未中毒") = mode; + if mode != Mode::Off { + return; } - if mode == Mode::Off { - let gone: Vec = { - let mut g = self.state.lock().expect("锁未中毒"); - let keys: Vec = g - .open - .values() - .filter(|o| o.notice.category == category) - .map(|o| o.notice.key.clone()) - .collect(); - for k in &keys { - g.open.remove(k); - } - keys - }; - for k in &gone { - for s in &self.sinks { - s.withdraw(k); - } + let gone: Vec = { + let mut g = self.state.lock().expect("锁未中毒"); + g.held_back = 0; + g.open.drain().map(|(k, _)| k).collect() + }; + for k in &gone { + for s in &self.sinks { + s.withdraw(k); } - self.persist(); - self.changed(); } - Ok(()) + self.persist(); + self.changed(); } - /// 这一条点开之后落在哪一页。**已经不在列表里的**(恢复了、被划掉了)按类别给 + /// 这一条点开之后落在哪一页。**已经不在列表里的**(恢复了、被划掉了)按键的种类给 pub fn view_of(&self, key: &str) -> String { self.state .lock() .ok() .and_then(|g| g.open.get(key).and_then(|o| o.notice.view.clone())) - .unwrap_or_else(|| rules::default_view(Category::of(key)).to_string()) + .unwrap_or_else(|| rules::default_view(key).to_string()) } /// 界面要显示的那一份,最近的在前 @@ -333,8 +332,7 @@ impl Notices { } fn raise(self: &Arc, signal: Signal, at_ms: u64) { - let category = Category::of(&signal.key); - let mode = self.prefs.lock().expect("锁未中毒").mode(category); + let mode = self.mode(); if mode == Mode::Off { return; } @@ -360,7 +358,6 @@ impl Notices { }, None => Notice { key: signal.key.clone(), - category, level: signal.level, title: signal.title.clone(), body: signal.body.clone(), @@ -373,7 +370,7 @@ impl Notices { }; // 抖动中、被抑制、或者已经弹过:只留记号 let quiet = muted.is_some_and(|until| now < until) || suppressed || notice.notified; - // 用户说了「只进应用内」的,级别再高也不打断 + // 用户选了「仅在应用内」的,级别再高也不打断 let wants = mode == Mode::System && signal.level.interrupts() && !quiet; let due = (wants && signal.hold).then(|| now + HOLD); let deliver = wants && !signal.hold && take_token(&mut g, signal.level); @@ -406,6 +403,8 @@ impl Notices { let me = self.clone(); tokio::spawn(async move { tokio::time::sleep_until(at.into()).await; + // 等的这一分钟里用户可能换了一档 + let wants = me.mode() == Mode::System; let notice = { let mut g = me.state.lock().expect("锁未中毒"); match g.open.get_mut(&key) { @@ -413,7 +412,7 @@ impl Notices { Some(o) if o.due == Some(at) && !o.notice.notified => { let level = o.notice.level; o.due = None; - if !take_token(&mut g, level) { + if !wants || !take_token(&mut g, level) { None } else { g.open.get(&key).map(|o| o.notice.clone()) @@ -503,7 +502,6 @@ impl Notices { for s in &self.sinks { s.show(&Notice { key: format!("{key}:recovered"), - category: was.notice.category, level: Level::Info, title: tr!( format!("{}已恢复", was.notice.title), @@ -581,7 +579,7 @@ pub fn open_from_notification(app: &tauri::AppHandle, key: &str) { let view = app .try_state::>() .map(|n| n.view_of(key)) - .unwrap_or_else(|| rules::default_view(Category::of(key)).to_string()); + .unwrap_or_else(|| rules::default_view(key).to_string()); if let Ok(mut g) = PENDING_VIEW.lock() { *g = Some(view.clone()); } diff --git a/src-tauri/src/notices/prefs.rs b/src-tauri/src/notices/prefs.rs deleted file mode 100644 index 3b3b261d..00000000 --- a/src-tauri/src/notices/prefs.rs +++ /dev/null @@ -1,138 +0,0 @@ -//! 每一类提醒怎么对待:弹系统通知、只进应用内、还是不要。 -//! -//! **按类,不按条。**「不再提醒这一条」对一个明天还会再发生的事没有意义;用户 -//! 真正要表达的是「这一类事别打断我」。 - -use std::collections::BTreeMap; -use std::path::Path; - -/// 提醒的类别。**和去重键的前缀一一对应**(见 [`Category::of`]) -#[derive( - Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, -)] -#[serde(rename_all = "snake_case")] -pub enum Category { - /// 网关停止转发 - Gateway, - /// 上游无法连接 - Upstream, - /// 订阅额度用完 - Quota, - /// 凭据失效、被拒绝、写不回配置 - Credential, - /// 代理不通 - Proxy, - /// 可疑的工具调用、客户端配置里出现的可疑内容 - Security, - /// 配置文件没过校验 - Config, - /// 磁盘空间不足 - Storage, -} - -impl Category { - /// 设置页上的顺序:先是「什么都用不了了」,再是「某一处要处理」 - pub const ALL: [Category; 8] = [ - Category::Gateway, - Category::Upstream, - Category::Quota, - Category::Credential, - Category::Proxy, - Category::Security, - Category::Config, - Category::Storage, - ]; - - /// 去重键属于哪一类 - pub fn of(key: &str) -> Category { - let kind = key.split(':').next().unwrap_or(key); - match kind { - "gateway" => Category::Gateway, - "upstream" => Category::Upstream, - "quota" => Category::Quota, - "credential" | "auth" | "writeback" => Category::Credential, - "proxy" => Category::Proxy, - "toolwall" | "scan" => Category::Security, - "storage" => Category::Storage, - // 认不出来的归到配置:那是唯一一个不挂在某个对象上的类 - _ => Category::Config, - } - } - - /// 设置页上的名字。**那是网页里的一行**,英文按网页的规矩用句首大写 - pub fn label(self) -> &'static str { - match self { - Category::Gateway => tr!("网关停止转发", "Gateway stops forwarding"), - Category::Upstream => tr!("上游无法连接", "Upstream unreachable"), - Category::Quota => tr!("订阅额度用完", "Subscription quota used up"), - Category::Credential => tr!("凭据失效或被拒绝", "Credential expired or rejected"), - Category::Proxy => tr!("代理不通", "Proxy unreachable"), - Category::Security => tr!( - "可疑的工具调用与客户端配置", - "Suspicious tool calls and client configuration" - ), - Category::Config => tr!("配置文件未通过校验", "Config file failed validation"), - Category::Storage => tr!("磁盘空间不足", "Low disk space"), - } - } - - /// 出厂设置。 - /// - /// **上游无法连接默认只进应用内**:多数人配了回退,一家上游挂了请求照样有人接, - /// 为一次被接住的故障打断用户不值得;而熔断信号本身就会随流量开开合合。 - fn default_mode(self) -> Mode { - match self { - Category::Upstream => Mode::App, - _ => Mode::System, - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Mode { - /// 弹系统通知(级别够的话) - System, - /// 只进应用内的提醒列表 - App, - /// 不记录 - Off, -} - -/// 用户改过的那几类。**没改过的不存**,出厂设置变了会跟着变 -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub struct Prefs { - #[serde(default)] - modes: BTreeMap, -} - -impl Prefs { - pub fn mode(&self, c: Category) -> Mode { - self.modes.get(&c).copied().unwrap_or(c.default_mode()) - } - - pub fn set(&mut self, c: Category, m: Mode) { - if m == c.default_mode() { - self.modes.remove(&c); - } else { - self.modes.insert(c, m); - } - } -} - -/// 读不出来就按出厂设置:一份坏掉的设置不该挡住提醒 -pub fn load(file: &Path) -> Prefs { - std::fs::read(file) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()) - .unwrap_or_default() -} - -pub fn save(file: &Path, p: &Prefs) -> std::io::Result<()> { - if let Some(dir) = file.parent() { - std::fs::create_dir_all(dir)?; - } - let mut text = serde_json::to_vec_pretty(p).map_err(std::io::Error::other)?; - text.push(b'\n'); - std::fs::write(file, text) -} diff --git a/src-tauri/src/notices/rules.rs b/src-tauri/src/notices/rules.rs index 184bd39a..5b1af154 100644 --- a/src-tauri/src/notices/rules.rs +++ b/src-tauri/src/notices/rules.rs @@ -42,13 +42,13 @@ const UPSTREAMS: &str = "upstreams"; const SECURITY: &str = "security"; const CONFIG: &str = "config"; -/// 一类提醒默认落在哪一页(那一条已经不在列表里时用) -pub fn default_view(c: super::Category) -> &'static str { - use super::Category; - match c { - Category::Gateway | Category::Config | Category::Storage => CONFIG, - Category::Security => SECURITY, - Category::Upstream | Category::Quota | Category::Credential | Category::Proxy => UPSTREAMS, +/// 一个键默认落在哪一页(那一条已经不在列表里时用)。按键的种类,也就是冒号前那段 +pub fn default_view(key: &str) -> &'static str { + match key.split(':').next().unwrap_or(key) { + "upstream" | "quota" | "credential" | "auth" | "writeback" | "proxy" => UPSTREAMS, + "toolwall" | "scan" => SECURITY, + // 网关、配置文件,以及认不出来的:设置页至少能看到网关在不在跑 + _ => CONFIG, } } @@ -118,13 +118,16 @@ pub fn from_event(ev: &Event) -> Vec { .map(|w| Signal::cleared(format!("quota:{provider}:{}", w.window))) .collect(), // **熔断打开才算出事。**冷却到点的那条 `closed` 只是「可以再试」,不是恢复了 —— - // 当成恢复的话,一家一直不通的上游每分钟开合一次,去抖永远等不满 + // 当成恢复的话,一家一直不通的上游每分钟开合一次,去抖永远等不满。 + // + // **只进应用内**:多数人配了回退,一家上游挂了请求照样有人接,为一次被接住的 + // 故障打断用户不值得;而熔断信号本身就会随流量开开合合 Event::HealthChanged { provider, state, .. } if state == "open" => vec![ Signal::raised( format!("upstream:{provider}"), - Level::Warning, + Level::Info, tr!( format!("上游「{provider}」无法连接"), format!("Upstream “{provider}” Unreachable") @@ -241,32 +244,6 @@ pub fn from_event(ev: &Event) -> Vec { .view(UPSTREAMS), ] } - Event::StorageChanged { - level, free_bytes, .. - } => { - if level == "ok" { - return vec![Signal::cleared("storage")]; - } - let title = if level == "stopped" { - tr!( - "磁盘空间严重不足,已停止记录", - "Disk Space Critically Low, Recording Stopped" - ) - } else { - tr!( - "磁盘空间不足,已停止保存请求正文", - "Disk Space Low, Request Bodies No Longer Saved" - ) - }; - vec![ - Signal::raised("storage", Level::Warning, title) - .body(tr!( - format!("剩余 {}。转发不受影响。", size(*free_bytes)), - format!("{} free. Forwarding is not affected.", size(*free_bytes)) - )) - .view(CONFIG), - ] - } // **界面自己写坏的不报**:那是一次保存失败,保存那条路自己会说 Event::ConfigRejected { origin, @@ -457,14 +434,3 @@ fn after(secs: u64) -> String { format!(" and resets in about {n} {unit_en}{plural}") ) } - -/// 「1.2 GB」 -fn size(bytes: u64) -> String { - const GB: f64 = 1024.0 * 1024.0 * 1024.0; - let gb = bytes as f64 / GB; - if gb >= 1.0 { - format!("{gb:.1} GB") - } else { - format!("{} MB", bytes / 1024 / 1024) - } -} diff --git a/src-tauri/src/notices/tests.rs b/src-tauri/src/notices/tests.rs index afbea1d0..1c3e08a2 100644 --- a/src-tauri/src/notices/tests.rs +++ b/src-tauri/src/notices/tests.rs @@ -35,7 +35,7 @@ fn bed() -> Bed { let shown = rec.shown.clone(); let withdrawn = rec.withdrawn.clone(); Bed { - bus: Notices::new(vec![Box::new(rec)], None), + bus: Notices::new(vec![Box::new(rec)], None, Mode::System), shown, withdrawn, } @@ -205,67 +205,86 @@ async fn what_is_dismissed_stays_dismissed_until_it_happens_again() { assert_eq!(b.titles().len(), 2, "划掉之后再次发生要重新说"); } -// ---------------------------------------------------------------- 每一类的设置 +// ---------------------------------------------------------------- 开关 #[tokio::test] -async fn a_category_turned_off_is_not_even_recorded() { +async fn turned_off_nothing_is_even_recorded() { let b = bed(); - b.bus.set_mode(Category::Quota, Mode::Off).unwrap(); + b.bus.set_mode(Mode::Off); b.bus.ingest(quota("relay"), T0); + b.bus.ingest( + Signal::raised("gateway", Level::Critical, "网关未在转发").now(), + T0 + 1, + ); assert!(b.titles().is_empty()); - assert!(b.bus.list().is_empty(), "关闭的一类不该留在列表里"); + assert!(b.bus.list().is_empty(), "关闭之后不该留在列表里"); } #[tokio::test] -async fn a_category_kept_in_the_app_is_listed_but_never_interrupts() { +async fn in_the_app_only_it_is_listed_but_never_interrupts() { let b = bed(); - b.bus.set_mode(Category::Quota, Mode::App).unwrap(); + b.bus.set_mode(Mode::App); b.bus.ingest(quota("relay"), T0); - assert!(b.titles().is_empty(), "只进应用内的不该弹"); - assert_eq!(b.bus.list().len(), 1); - assert_eq!(b.bus.list()[0].category, Category::Quota); + b.bus.ingest( + Signal::raised("gateway", Level::Critical, "网关未在转发").now(), + T0 + 1, + ); + assert!(b.titles().is_empty(), "仅在应用内的,级别再高也不弹"); + assert_eq!(b.bus.list().len(), 2); } #[tokio::test] -async fn turning_a_category_off_takes_what_is_open_with_it() { +async fn turning_notices_off_takes_everything_open_with_it() { let b = bed(); b.bus.ingest(quota("relay"), T0); b.bus.ingest( Signal::raised("proxy:hk", Level::Warning, "代理「hk」不通").now(), T0 + 1, ); - b.bus.set_mode(Category::Quota, Mode::Off).unwrap(); - let keys: Vec = b.bus.list().into_iter().map(|n| n.key).collect(); - assert_eq!(keys, ["proxy:hk"]); - assert!( - b.withdrawn - .lock() - .unwrap() - .contains(&"quota:relay:weekly".to_string()) + b.bus.set_mode(Mode::Off); + assert!(b.bus.list().is_empty()); + let mut withdrawn = b.withdrawn.lock().unwrap().clone(); + withdrawn.sort(); + assert_eq!(withdrawn, ["proxy:hk", "quota:relay:weekly"]); +} + +/// 去抖的那一分钟里换成了「仅在应用内」:到点时照新的一档办 +#[tokio::test(start_paused = true)] +async fn a_notice_still_on_hold_does_not_pop_after_switching_to_the_app() { + let b = bed(); + b.bus.ingest( + Signal::raised("proxy:hk", Level::Warning, "代理「hk」不通"), + T0, ); + tokio::time::advance(Duration::from_secs(20)).await; + b.bus.set_mode(Mode::App); + tokio::time::advance(Duration::from_secs(90)).await; + tokio::task::yield_now().await; + assert!(b.titles().is_empty(), "{:?}", b.titles()); + assert_eq!(b.bus.list().len(), 1, "列表里照样留着"); } +/// 点开一条已经不在列表里的通知,落到能处理它的那一页 #[test] -fn every_key_belongs_to_the_category_its_setting_is_shown_under() { - for (key, c) in [ - ("gateway", Category::Gateway), - ("upstream:relay", Category::Upstream), - ("quota:chatgpt:5h", Category::Quota), - ("credential:chatgpt", Category::Credential), - ("auth:relay", Category::Credential), - ("writeback:claude-max", Category::Credential), - ("proxy:hk", Category::Proxy), - ("toolwall:relay", Category::Security), - ("scan", Category::Security), - ("config", Category::Config), - ("storage", Category::Storage), +fn every_key_lands_on_the_page_that_handles_it() { + for (key, view) in [ + ("gateway", "config"), + ("config", "config"), + ("upstream:relay", "upstreams"), + ("quota:chatgpt:5h", "upstreams"), + ("credential:chatgpt", "upstreams"), + ("auth:relay", "upstreams"), + ("writeback:claude-max", "upstreams"), + ("proxy:hk", "upstreams"), + ("toolwall:relay", "security"), + ("scan", "security"), ] { - assert_eq!(Category::of(key), c, "{key}"); + assert_eq!(rules::default_view(key), view, "{key}"); } } #[tokio::test(start_paused = true)] -async fn an_unreachable_upstream_stays_in_the_app_by_default_and_needs_real_evidence_to_clear() { +async fn an_unreachable_upstream_is_only_listed_and_needs_real_evidence_to_clear() { let b = bed(); let health = |state: &str| tw_api::Event::HealthChanged { id: 1, @@ -278,7 +297,7 @@ async fn an_unreachable_upstream_stays_in_the_app_by_default_and_needs_real_evid b.bus.on_event(&health("closed")); tokio::time::advance(Duration::from_secs(90)).await; tokio::task::yield_now().await; - assert!(b.titles().is_empty(), "多数人配了回退,默认不打断"); + assert!(b.titles().is_empty(), "多数人配了回退,不打断"); assert_eq!(b.bus.list().len(), 1, "冷却结束不该把它撤掉"); // 这家真的又接下了一个请求 @@ -470,18 +489,6 @@ fn in_english_no_rule_writes_a_chinese_word() { )), at_ms: T0, }, - tw_api::Event::StorageChanged { - id: 1, - level: "stopped".into(), - free_bytes: 200 * 1024 * 1024, - at_ms: T0, - }, - tw_api::Event::StorageChanged { - id: 1, - level: "metadata_only".into(), - free_bytes: 3 * 1024 * 1024 * 1024, - at_ms: T0, - }, tw_api::Event::ConfigRejected { id: 1, stage: "schema".into(), @@ -532,9 +539,6 @@ fn in_english_no_rule_writes_a_chinese_word() { assert!(!s.title.ends_with('.'), "{}", s.title); assert!(s.body.ends_with('.'), "{}", s.body); } - for c in Category::ALL { - assert!(!has_chinese(c.label()), "{c:?}: {}", c.label()); - } }); } diff --git a/src-tauri/src/prefs.rs b/src-tauri/src/prefs.rs index a4fa0d2a..d355f1bc 100644 --- a/src-tauri/src/prefs.rs +++ b/src-tauri/src/prefs.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use crate::i18n::Lang; +use crate::notices::Mode; use crate::theme::Theme; /// 设置文件,放在数据目录里。 @@ -30,6 +31,8 @@ pub struct Prefs { pub language: Option, /// 界面外观。`None` 是跟随系统,理由同上。 pub theme: Option, + /// 提醒:系统通知 / 仅在应用内 / 关闭。**只有这一个,不分类。** + pub notices: Mode, } impl Default for Prefs { @@ -38,6 +41,7 @@ impl Default for Prefs { check_updates: true, language: None, theme: None, + notices: Mode::System, } } } @@ -98,6 +102,7 @@ mod tests { assert!(p.check_updates); assert_eq!(p.language, None); assert_eq!(p.theme, None); + assert_eq!(p.notices, Mode::System); std::fs::remove_dir_all(&dir).unwrap(); } @@ -120,9 +125,11 @@ mod tests { let dir = tmp(); update(&dir, |p| p.language = Some(Lang::En)).unwrap(); update(&dir, |p| p.check_updates = false).unwrap(); + update(&dir, |p| p.notices = Mode::Off).unwrap(); let p = load(&dir); assert_eq!(p.language, Some(Lang::En)); assert!(!p.check_updates); + assert_eq!(p.notices, Mode::Off); std::fs::remove_dir_all(&dir).unwrap(); } @@ -133,6 +140,7 @@ mod tests { check_updates: true, language: Some(Lang::Zh), theme: Some(Theme::Dark), + notices: Mode::App, }; save(&dir, &want).unwrap(); assert_eq!(load(&dir), want); diff --git a/src/Dashboard.i18n.tsx b/src/Dashboard.i18n.tsx index 316b0afd..ca429e2f 100644 --- a/src/Dashboard.i18n.tsx +++ b/src/Dashboard.i18n.tsx @@ -128,7 +128,8 @@ export const dashboardText = messages( enforceTip: "如需替换为占位符,请在「安全 › 防护」中将出站脱敏切换到「拦截」。", enforce: "启用拦截", - /** 接在存储状态那句后面 */ + /** 后面可能接「。转发不受影响。」,所以不带句号 */ + recordingUnavailable: "请求记录未能启动", forwardingUnaffected: "。转发不受影响。", }, { @@ -248,6 +249,7 @@ export const dashboardText = messages( "To replace them with placeholders, switch outbound redaction to Enforce in Security › Protection.", enforce: "Switch to Enforce", + recordingUnavailable: "Request recording could not start", forwardingUnaffected: ". Forwarding is not affected.", }, ); diff --git a/src/Dashboard.tsx b/src/Dashboard.tsx index 42bc16ec..4018f932 100644 --- a/src/Dashboard.tsx +++ b/src/Dashboard.tsx @@ -13,7 +13,7 @@ import { ToggleGroup, ToggleGroupItem } from "@/ui/toggle-group"; import { Skeleton } from "@/ui/skeleton"; import { LIVE_BUCKET_MS, LIVE_REACH_MS, LIVE_SIGMA_MS, useLive } from "./useLive"; import { useCountUp } from "./useCountUp"; -import { secretLabel, storageText } from "./labels"; +import { secretLabel } from "./labels"; import { useText } from "@/i18n"; import { dashboardText } from "./Dashboard.i18n"; @@ -1107,10 +1107,10 @@ export default function Dashboard({ {open != null && setOpen(null)} />} {/* 存储状态。**正常时不显示** —— 没问题的时候不该占地方 */} - {d.storage && d.storage.level !== "ok" && ( + {d.storage && !d.storage.recording && ( - {storageText(d.storage.level)} + {t.recordingUnavailable} {!d.storage.forwarding_affected && t.forwardingUnaffected} diff --git a/src/NoticeSettings.i18n.ts b/src/NoticeSettings.i18n.ts index d238bb24..4d6b0689 100644 --- a/src/NoticeSettings.i18n.ts +++ b/src/NoticeSettings.i18n.ts @@ -3,14 +3,12 @@ import { messages } from "@/i18n"; export const noticeSettingsText = messages( { title: "提醒", - note: "选择「系统通知」的类别在需要处理时弹出系统通知,其余只记录在工具栏的提醒列表中。", system: "系统通知", app: "仅在应用内", off: "关闭", }, { title: "Notices", - note: "Categories set to System notification show a system notification when they need attention; the rest are only recorded in the Notices list in the toolbar.", system: "System notification", app: "In app only", off: "Off", diff --git a/src/NoticeSettings.tsx b/src/NoticeSettings.tsx index 4a822990..f743b5bc 100644 --- a/src/NoticeSettings.tsx +++ b/src/NoticeSettings.tsx @@ -1,50 +1,40 @@ import { useEffect, useState } from "react"; import { invoke } from "@tauri-apps/api/core"; import { toast } from "sonner"; -import { NativeSelect, NativeSelectOption } from "@/ui/native-select"; +import { Segmented } from "@/upstreams/parts"; import { useText } from "@/i18n"; import { noticeSettingsText } from "./NoticeSettings.i18n"; import { errorText } from "@/i18n/core.i18n"; export type NoticeMode = "system" | "app" | "off"; -export interface NoticePref { - category: string; - label: string; - mode: NoticeMode; -} - -export const modes = (t: typeof noticeSettingsText.zh): { id: NoticeMode; label: string }[] => [ - { id: "system", label: t.system }, - { id: "app", label: t.app }, - { id: "off", label: t.off }, -]; - /** - * 设置里的「提醒」:每一类怎么对待。 + * 设置里的「提醒」:系统通知 / 仅在应用内 / 关闭。 * - * **按类,不按条** —— 「不再提醒这一条」对明天还会再发生的事没有意义。 + * **只有一个开关,不分类。**哪件事该打断人是通知总线的判断(见 + * `src-tauri/src/notices`),不该变成设置页上的一长串下拉。三档固定, + * 所以和外观一样摆成三个按钮。 */ export default function NoticeSettings() { const t = useText(noticeSettingsText); - const [prefs, setPrefs] = useState(null); + const [mode, setMode] = useState(null); useEffect(() => { - void invoke("notice_prefs") - .then(setPrefs) + void invoke("notice_mode") + .then(setMode) .catch(() => {}); }, []); - if (!prefs) return null; + if (!mode) return null; - async function set(category: string, mode: NoticeMode) { - const before = prefs; - // 先画上,以后端返回的为准 —— 写不进去的时候要弹回去 - setPrefs((p) => p?.map((x) => (x.category === category ? { ...x, mode } : x)) ?? p); + async function choose(next: NoticeMode) { + const before = mode; + // 先画上,以后端返回的为准 —— 存不进去的时候要弹回去 + setMode(next); try { - setPrefs(await invoke("set_notice_pref", { category, mode })); + setMode(await invoke("set_notice_mode", { mode: next })); } catch (e) { - setPrefs(before); + setMode(before); toast.error(errorText(e)); } } @@ -52,28 +42,16 @@ export default function NoticeSettings() { return (

{t.title}

-

- {t.note} -

-
- {prefs.map((p) => ( -
- - void set(p.category, e.target.value as NoticeMode)} - > - {modes(t).map((m) => ( - - {m.label} - - ))} - -
- ))} +
+ + value={mode} + options={[ + { id: "system", label: t.system }, + { id: "app", label: t.app }, + { id: "off", label: t.off }, + ]} + onChange={(v) => void choose(v)} + />
); diff --git a/src/Notices.i18n.ts b/src/Notices.i18n.ts index c4f5f815..b823d329 100644 --- a/src/Notices.i18n.ts +++ b/src/Notices.i18n.ts @@ -2,19 +2,15 @@ import { messages } from "@/i18n"; export const noticesText = messages( { - quieted: "此类提醒今后仅在应用内显示,可在设置中更改", bell: (n: number) => (n > 0 ? `提醒,${n} 项` : "提醒"), title: "提醒", empty: "暂无提醒", - quiet: "不再弹出此类", dismiss: (title: string) => `忽略「${title}」`, }, { - quieted: "Notices of this kind now appear in the app only. This can be changed in Settings.", bell: (n: number) => (n > 0 ? `Notices, ${n}` : "Notices"), title: "Notices", empty: "No notices", - quiet: "Show this kind in app only", dismiss: (title: string) => `Dismiss “${title}”`, }, ); diff --git a/src/Notices.tsx b/src/Notices.tsx index 0a0d247c..2dc342f8 100644 --- a/src/Notices.tsx +++ b/src/Notices.tsx @@ -4,19 +4,16 @@ import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { Button } from "@/ui/button"; import { Popover, PopoverContent, PopoverTrigger } from "@/ui/popover"; -import { toast } from "sonner"; import { when } from "@/format"; import { cn } from "@/lib/utils"; import { useText } from "@/i18n"; import { noticesText } from "./Notices.i18n"; import { commonText } from "@/i18n/common.i18n"; -import { errorText } from "@/i18n/core.i18n"; +import type { NoticeMode } from "./NoticeSettings"; /** 一条提醒。判定在 Rust 侧,这里只负责显示 */ export interface Notice { key: string; - /** 属于哪一类。「不再弹出此类」按它来 */ - category: string; level: "info" | "warning" | "critical"; title: string; body: string; @@ -43,6 +40,8 @@ export function Notices({ onNavigate }: { onNavigate: (view: string) => void }) const [open, setOpen] = useState(false); /** 这一次是不是用鼠标点开的。决定打开时焦点进不进面板,见 onOpenAutoFocus */ const byMouse = useRef(false); + // 提醒关掉了就不放铃铛:列表永远是空的,留着它只是占地方 + const [mode, setMode] = useState(null); const load = useCallback(() => { invoke("notices_list") @@ -58,20 +57,23 @@ export function Notices({ onNavigate }: { onNavigate: (view: string) => void }) return () => void un.then((f) => f()); }, [load]); + useEffect(() => { + invoke("notice_mode") + .then(setMode) + .catch(() => setMode("system")); + const un = listen("notice-mode-changed", (e) => setMode(e.payload)); + return () => void un.then((f) => f()); + }, []); + function dismiss(key: string) { setList((l) => l.filter((n) => n.key !== key)); void invoke("dismiss_notice", { key }); } - /** 这一类以后只记录、不弹出。**按类**:同一类事明天还会再发生 */ - function quiet(category: string) { - invoke("set_notice_pref", { category, mode: "app" }) - .then(() => toast.success(t.quieted)) - .catch((e) => toast.error(errorText(e))); - } - const urgent = list.filter((n) => n.level !== "info").length; + if (mode === "off") return null; + return ( @@ -158,24 +160,7 @@ export function Notices({ onNavigate }: { onNavigate: (view: string) => void }) )}

{n.body &&

{n.body}

} -

- {when(n.at_ms)} - {n.notified && ( - <> - {" · "} - - - )} -

+

{when(n.at_ms)}