diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c4ce3cd0..30de751b 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2710,7 +2710,10 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" dependencies = [ + "bitflags 2.13.1", + "block2", "objc2", + "objc2-core-location", "objc2-foundation", ] @@ -4515,10 +4518,14 @@ name = "thinkwatch-lite" version = "2026.9.6" dependencies = [ "anyhow", + "block2", "http-body-util", "hyper", "hyper-util", "libc", + "objc2", + "objc2-foundation", + "objc2-user-notifications", "reqwest", "rustls", "semver", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 46950759..d42c9c3f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -63,6 +63,14 @@ strip = "symbols" # panic,而 abort 会让那层防护失效。 panic = "unwind" +# 系统通知走 UNUserNotificationCenter:能原地更新、撤回、点开落到对应页面(见 +# `notices/macos.rs`)。版本跟着 Tauri 自己用的那一套 +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = "0.6" +block2 = "0.6" +objc2-foundation = "0.3" +objc2-user-notifications = "0.3" + [dev-dependencies] # 去抖和限流要按时间测。**暂停时钟**,不是真的等一分钟 tokio = { version = "1", features = ["test-util", "macros", "rt-multi-thread"] } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 15d3a94b..5e008aa0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1258,6 +1258,7 @@ pub fn run() { dismiss_notice, notice_prefs, set_notice_pref, + take_pending_view, chatgpt::start_chatgpt_login, chatgpt::reopen_chatgpt_login, chatgpt::chatgpt_login_status, @@ -1323,10 +1324,21 @@ pub fn run() { announce_update(&handle); // 通知总线。**判定在这里,不在界面** —— 关窗即销毁 webview + // 系统通知:装好的应用用原生的(能原地更新、撤回、点开落到对应页面), + // `tauri dev` 这种不在应用包里的退回插件 + #[cfg(target_os = "macos")] + let system: Box = if notices::macos::available() { + notices::macos::install(handle.clone()); + Box::new(notices::macos::NativeSink) + } else { + Box::new(notices::SystemSink::new(handle.clone())) + }; + #[cfg(not(target_os = "macos"))] + let system: Box = Box::new(notices::SystemSink::new(handle.clone())); let notices = notices::Notices::new( vec![ Box::new(notices::sink::AppSink::new(handle.clone())), - Box::new(notices::SystemSink::new(handle.clone())), + system, ], Some(data_dir()), ); @@ -1634,6 +1646,12 @@ fn dismiss_notice(notices: tauri::State<'_, Arc>, key: String) notices.dismiss(&key); } +/// 点通知新建的窗口挂上之后,来取要落的那一页 +#[tauri::command] +fn take_pending_view() -> Option { + notices::take_pending_view() +} + /// 设置页上的一行:一类提醒,和它现在怎么对待 #[derive(serde::Serialize)] struct NoticePref { diff --git a/src-tauri/src/notices/macos/mod.rs b/src-tauri/src/notices/macos/mod.rs new file mode 100644 index 00000000..f524c48c --- /dev/null +++ b/src-tauri/src/notices/macos/mod.rs @@ -0,0 +1,74 @@ +//! macOS 的系统通知:`UNUserNotificationCenter`。 +//! +//! 换掉 `tauri-plugin-notification` 的理由只有一条:那个插件在桌面端**发出即不管** —— +//! 不能按 id 原地更新、不能撤回、点了没有回调,而总线的「同一件事只说一次、恢复时 +//! 撤回、点开落到能处理它的那一页」三件事都要靠这些。 +//! +//! # 2026-09-18 实测过的前提 +//! +//! - **没有团队 ID 的签名也能拿到授权**(临时签名即可;发布用的自签名证书只会更好)。 +//! 但应用得装在正式位置、在系统里登记过 —— 放在临时目录里的包,申请授权会被直接拒绝, +//! 连弹窗都没有 +//! - 菜单栏模式(没有窗口)照样能弹;同一个 identifier 再发是**原地替换**; +//! `removeDelivered` 能撤回;点通知能收到回调 +//! +//! 真正调通知中心的那几行在 [`un`],这里只是把它接到总线上。 + +pub mod un; + +use super::{Notice, Sink}; + +pub use un::available; + +/// 接上通知中心:点了通知就把窗口带回来,落到那一条对应的页面 +pub fn install(app: tauri::AppHandle) { + un::install(Box::new(move |key| { + super::open_from_notification(&app, &key) + })); +} + +/// macOS 原生的系统通知 +pub struct NativeSink; + +impl Sink for NativeSink { + fn show(&self, notice: &Notice) { + un::post( + notice.key.clone(), + notice.title.clone(), + notice.body.clone(), + thread_of(notice), + false, + ); + } + + /// **只更新弹过的那些**:没弹过的(被压下、只进应用内的)不该借更新的名义冒出来 + fn update(&self, notice: &Notice) { + if !notice.notified { + return; + } + let title = if notice.count > 1 { + format!("{}({} 次)", notice.title, notice.count) + } else { + notice.title.clone() + }; + un::post( + notice.key.clone(), + title, + notice.body.clone(), + thread_of(notice), + true, + ); + } + + fn withdraw(&self, key: &str) { + un::withdraw(key); + } +} + +/// 同一类的归在一起:用类别的标识做 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() +} diff --git a/src-tauri/src/notices/macos/un.rs b/src-tauri/src/notices/macos/un.rs new file mode 100644 index 00000000..f243d033 --- /dev/null +++ b/src-tauri/src/notices/macos/un.rs @@ -0,0 +1,134 @@ +//! `UNUserNotificationCenter` 的那几个调用。 +//! +//! **不依赖 Tauri,也不依赖总线** —— 这样它能被一个单独的小程序原样引用,换一个 +//! bundle id 在真机上验证,而不必动正在用的那个应用(同一个 bundle id、同一个数据 +//! 目录,两个一起跑会互相干扰)。 + +use std::sync::OnceLock; + +use block2::RcBlock; +use objc2::rc::Retained; +use objc2::runtime::{Bool, ProtocolObject}; +use objc2::{AnyThread, define_class, msg_send}; +use objc2_foundation::{NSArray, NSBundle, NSError, NSObject, NSObjectProtocol, NSString}; +use objc2_user_notifications::{ + UNAuthorizationOptions, UNMutableNotificationContent, UNNotification, + UNNotificationInterruptionLevel, UNNotificationPresentationOptions, UNNotificationRequest, + UNNotificationResponse, UNUserNotificationCenter, UNUserNotificationCenterDelegate, +}; + +/// 点了哪一条(它的 identifier)。**delegate 的回调里拿不到别的东西**,只能放这里 +type OnClick = Box; +static ON_CLICK: OnceLock = OnceLock::new(); + +/// 能不能用:只有装好的 `.app` 能用。`tauri dev` 那种不在应用包里的二进制, +/// 去拿通知中心会直接抛异常,进程退出 +pub fn available() -> bool { + let bundle = NSBundle::mainBundle(); + bundle.bundleIdentifier().is_some() && bundle.bundlePath().to_string().ends_with(".app") +} + +/// 接上通知中心。**要在启动时就调** —— 点通知把应用拉起来的那一次,delegate 得已经在了 +pub fn install(on_click: OnClick) { + let _ = ON_CLICK.set(on_click); + let delegate = Delegate::new(); + let center = UNUserNotificationCenter::currentNotificationCenter(); + center.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + // 通知中心只弱引用 delegate:**让它活到进程结束** + std::mem::forget(delegate); +} + +define_class!( + // SAFETY: NSObject 对子类没有额外要求;这个类没有实现 Drop + #[unsafe(super(NSObject))] + #[name = "ThinkWatchNoticeDelegate"] + struct Delegate; + + unsafe impl NSObjectProtocol for Delegate {} + + unsafe impl UNUserNotificationCenterDelegate for Delegate { + /// 应用在前台时收到通知:**只进通知中心,不弹横幅** —— 用户正看着界面, + /// 工具栏的提醒列表已经说了。设了 delegate 就必须实现这一条,否则前台一律不显示 + #[unsafe(method(userNotificationCenter:willPresentNotification:withCompletionHandler:))] + fn will_present( + &self, + _center: &UNUserNotificationCenter, + _notification: &UNNotification, + done: &block2::DynBlock, + ) { + done.call((UNNotificationPresentationOptions::List,)); + } + + /// 点了通知 + #[unsafe(method(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:))] + fn did_receive( + &self, + _center: &UNUserNotificationCenter, + response: &UNNotificationResponse, + done: &block2::DynBlock, + ) { + let key = response.notification().request().identifier().to_string(); + if let Some(f) = ON_CLICK.get() { + f(key); + } + done.call(()); + } + } +); + +impl Delegate { + fn new() -> Retained { + let this = Self::alloc().set_ivars(()); + // SAFETY: NSObject 的 init + unsafe { msg_send![super(this), init] } + } +} + +/// 发一条,或者替换同一个 `key` 的那一条。**先问授权**:第一次会弹系统询问,之后 +/// 立刻用存下的答案 —— 放在第一条要打断用户的提醒之前问,那时用户知道这是为了什么。 +/// +/// `quiet`:只是更新计数的那一次**不亮屏、不出声**,替换掉通知中心里那一条就好 +pub fn post(key: String, title: String, body: String, thread: String, quiet: bool) { + let center = UNUserNotificationCenter::currentNotificationCenter(); + let then = RcBlock::new(move |granted: Bool, _err: *mut NSError| { + if !granted.as_bool() { + // 用户没允许:提醒照样在应用里,不再追问 + return; + } + let content = UNMutableNotificationContent::new(); + content.setTitle(&NSString::from_str(&title)); + content.setBody(&NSString::from_str(&body)); + // 同一类的归在一起 + content.setThreadIdentifier(&NSString::from_str(&thread)); + content.setInterruptionLevel(if quiet { + UNNotificationInterruptionLevel::Passive + } else { + UNNotificationInterruptionLevel::Active + }); + let request = UNNotificationRequest::requestWithIdentifier_content_trigger( + &NSString::from_str(&key), + &content, + None, + ); + let center = UNUserNotificationCenter::currentNotificationCenter(); + let logged = RcBlock::new(|err: *mut NSError| { + // SAFETY: 通知中心给的要么是空指针,要么是一个有效的 NSError + if let Some(e) = unsafe { err.as_ref() } { + tracing::debug!("系统通知未能发出:{}", e.localizedDescription()); + } + }); + center.addNotificationRequest_withCompletionHandler(&request, Some(&logged)); + }); + center.requestAuthorizationWithOptions_completionHandler( + UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound, + &then, + ); +} + +/// 撤回:通知中心里的那一条,和还没发出去的那一条 +pub fn withdraw(key: &str) { + let center = UNUserNotificationCenter::currentNotificationCenter(); + let ids = NSArray::from_retained_slice(&[NSString::from_str(key)]); + center.removeDeliveredNotificationsWithIdentifiers(&ids); + center.removePendingNotificationRequestsWithIdentifiers(&ids); +} diff --git a/src-tauri/src/notices/mod.rs b/src-tauri/src/notices/mod.rs index 75a2be96..04176ff9 100644 --- a/src-tauri/src/notices/mod.rs +++ b/src-tauri/src/notices/mod.rs @@ -26,6 +26,8 @@ use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +#[cfg(target_os = "macos")] +pub mod macos; pub mod prefs; pub mod rules; pub mod sink; @@ -274,6 +276,15 @@ impl Notices { Ok(()) } + /// 这一条点开之后落在哪一页。**已经不在列表里的**(恢复了、被划掉了)按类别给 + 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()) + } + /// 界面要显示的那一份,最近的在前 pub fn list(&self) -> Vec { let g = self.state.lock().expect("锁未中毒"); @@ -548,6 +559,32 @@ fn take_token(state: &mut State, level: Level) -> bool { true } +/// 点通知之后要落到的那一页。**窗口这时可能根本不存在** —— 新建的界面挂上之后自己来取 +static PENDING_VIEW: Mutex> = Mutex::new(None); + +/// 点了系统通知:把窗口带回来,落到能处理这件事的那一页 +pub fn open_from_notification(app: &tauri::AppHandle, key: &str) { + use tauri::{Emitter, Manager}; + let view = app + .try_state::>() + .map(|n| n.view_of(key)) + .unwrap_or_else(|| rules::default_view(Category::of(key)).to_string()); + if let Ok(mut g) = PENDING_VIEW.lock() { + *g = Some(view.clone()); + } + // 通知的回调不在主线程上,建窗口要回到主线程 + let a = app.clone(); + let _ = app.run_on_main_thread(move || { + let _ = crate::show_main_window(&a); + let _ = a.emit("open-view", &view); + }); +} + +/// 取走待落的那一页。取一次就没了:下次开窗不该又跳过去 +pub fn take_pending_view() -> Option { + PENDING_VIEW.lock().ok().and_then(|mut g| g.take()) +} + fn now_ms() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/src-tauri/src/notices/rules.rs b/src-tauri/src/notices/rules.rs index 39e2cfbe..b21d502d 100644 --- a/src-tauri/src/notices/rules.rs +++ b/src-tauri/src/notices/rules.rs @@ -15,6 +15,16 @@ 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, + } +} + /// 这个键开着的时候,压下哪些键(前缀匹配)。 /// /// **网关不在服务时不必再说它下面每一家怎么了** —— 那时用户要做的只有一件事。 diff --git a/src-tauri/src/notices/sink.rs b/src-tauri/src/notices/sink.rs index 9adbf452..036806c7 100644 --- a/src-tauri/src/notices/sink.rs +++ b/src-tauri/src/notices/sink.rs @@ -39,12 +39,12 @@ impl Sink for AppSink { } } -/// 系统通知。 +/// 系统通知的退路:`tauri-plugin-notification`。 /// -/// **目前用的是 `tauri-plugin-notification`,它在桌面端只能「发出即不管」** —— -/// 不能按 id 原地更新、不能撤回、点了没有回调(2026-09-18 查过插件源码和上游 -/// issue)。所以这里的 `update` 和 `withdraw` 是空的:原地更新和恢复时撤回要等 -/// macOS 的原生实现(`UNUserNotificationCenter`),那时换掉这一个类型即可。 +/// **装好的 macOS 应用不走这里**,走 `macos::NativeSink`。这个插件在桌面端只能「发出即 +/// 不管」—— 不能按 id 原地更新、不能撤回、点了没有回调,所以 `update` 和 `withdraw` +/// 是空的。留着它是给 `tauri dev`(不在应用包里,原生通知中心拿不到)和还没有原生 +/// 实现的平台用。 pub struct SystemSink { app: tauri::AppHandle, } diff --git a/src/App.tsx b/src/App.tsx index 9b1098d3..cc18b014 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -500,6 +500,25 @@ export default function App() { }; }, []); + /* + 点了系统通知:落到能处理那件事的那一页。**窗口可能是为这一下新建的** —— + 那时事件已经错过了,所以挂上时先去取一次;已经开着的窗口收事件。 + 两条路都会把 Rust 那边存的清掉,下次开窗不会又跳过去。 + */ + useEffect(() => { + const go = (view: string | null) => { + if (view) setTab(view as Surface); + }; + void invoke("take_pending_view").then(go).catch(() => {}); + const un = listen("open-view", (e) => { + go(e.payload); + void invoke("take_pending_view").catch(() => {}); + }); + return () => { + un.then((f) => f()); + }; + }, []); + /** * 列表的键盘导航。 *