DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(desktop): add native notification bridge for harness iframe
hairyf990496bf257c
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 4d62732b..d9d4f6f6 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -79,6 +79,28 @@ dependencies = ["x11rb",]+[[package]]+name = "ashpd"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39"+dependencies = [+ "async-fs",+ "async-net",+ "enumflags2",+ "futures-channel",+ "futures-util",+ "rand",+ "raw-window-handle",+ "serde",+ "serde_repr",+ "url",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "zbus",+]+[[package]]name = "async-broadcast"version = "0.7.2"@@ -117,6 +139,17 @@ dependencies = ["slab",]+[[package]]+name = "async-fs"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"+dependencies = [+ "async-lock",+ "blocking",+ "futures-lite",+]+[[package]]name = "async-io"version = "2.6.0"@@ -146,6 +179,17 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "async-net"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"+dependencies = [+ "async-io",+ "blocking",+ "futures-lite",+]+[[package]]name = "async-process"version = "2.5.0"@@ -775,19 +819,23 @@ dependencies = ["async-trait","flate2","futures-util",+ "image","log","reqwest 0.12.28",+ "rfd","serde","serde_json",- "sha2","tar","tauri","tauri-build","tauri-plugin-clipboard-manager","tauri-plugin-fs",+ "tauri-plugin-notification","tauri-plugin-opener","tauri-plugin-store","tokio",+ "webview2-com",+ "windows-core 0.61.2","windows-sys 0.61.2","zip",]@@ -908,6 +956,15 @@ dependencies = ["syn 3.0.3",]+[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading",+]+[[package]]name = "dlopen2"version = "0.8.2"@@ -2328,6 +2385,20 @@ version = "0.4.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"+[[package]]+name = "mac-notification-sys"+version = "0.6.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"+dependencies = [+ "cc",+ "log",+ "objc2",+ "objc2-foundation",+ "time",+ "uuid",+]+[[package]]name = "markup5ever"version = "0.38.0"@@ -2468,6 +2539,20 @@ dependencies = ["memchr",]+[[package]]+name = "notify-rust"+version = "4.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c5b4c1b4f2aa9f25f63a7a49d3dd0ed567b3670da15330a66b29434be899b891"+dependencies = [+ "futures-lite",+ "log",+ "mac-notification-sys",+ "serde",+ "tauri-winrt-notification",+ "zbus",+]+[[package]]name = "num-conv"version = "0.2.2"@@ -2849,7 +2934,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700"dependencies = ["base64ct",- "rand_core",+ "rand_core 0.6.4","subtle",]@@ -3011,6 +3096,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"+[[package]]name = "portable-atomic"version = "1.15.0"@@ -3041,6 +3132,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"+[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]+[[package]]name = "precomputed-hash"version = "0.1.1"@@ -3151,12 +3251,41 @@ version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]+[[package]]name = "rand_core"version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]+[[package]]name = "raw-window-handle"version = "0.6.2"@@ -3309,6 +3438,30 @@ dependencies = ["web-sys",]+[[package]]+name = "rfd"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"+dependencies = [+ "ashpd",+ "block2",+ "dispatch2",+ "js-sys",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "pollster",+ "raw-window-handle",+ "urlencoding",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows-sys 0.60.2",+]+[[package]]name = "ring"version = "0.17.14"@@ -3465,6 +3618,12 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"+[[package]]name = "scopeguard"version = "1.2.0"@@ -4190,6 +4349,25 @@ dependencies = ["url",]+[[package]]+name = "tauri-plugin-notification"+version = "2.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01fc2c5ff41105bd1f7242d8201fdf3efd70749b82fa013a17f2126357d194cc"+dependencies = [+ "log",+ "notify-rust",+ "rand",+ "serde",+ "serde_json",+ "serde_repr",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.20",+ "time",+ "url",+]+[[package]]name = "tauri-plugin-opener"version = "2.5.4"@@ -4328,6 +4506,17 @@ dependencies = ["toml 1.1.4+spec-1.1.0",]+[[package]]+name = "tauri-winrt-notification"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"+dependencies = [+ "thiserror 2.0.20",+ "windows",+ "windows-version",+]+[[package]]name = "tempfile"version = "3.27.0"@@ -4851,6 +5040,12 @@ dependencies = ["serde_derive",]+[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+[[package]]name = "urlpattern"version = "0.3.0"@@ -5043,6 +5238,7 @@ dependencies = ["cc","downcast-rs","rustix",+ "scoped-tls","smallvec","wayland-sys",]@@ -5101,6 +5297,8 @@ version = "0.31.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"dependencies = [+ "dlib",+ "log","pkg-config",]@@ -6065,6 +6263,7 @@ dependencies = ["endi","enumflags2","serde",+ "url","winnow 1.0.4","zcheapstr","zvariant_derive",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex f503ab15..41712bd1 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -29,6 +29,8 @@ tauri-plugin-opener = "2"tauri-plugin-fs = "2"tauri-plugin-store = "2"tauri-plugin-clipboard-manager = "2"+tauri-plugin-notification = "2"+image = { version = "0.25", default-features = false, features = [ "png" ] }serde = { version = "1", features = [ "derive" ] }serde_json = "1"log = "0.4"@@ -40,11 +42,13 @@ zip = "0.6"futures-util = "0.3"flate2 = "1"tar = "0.4"-sha2 = "0.10"async-trait = "0.1"tokio = { version = "1", features = [ "full" ] }[target.'cfg(windows)'.dependencies]+rfd = "0.16"+webview2-com = "0.38"+windows-core = "0.61"windows-sys = { version = "0.61", features = ["Win32_Foundation","Win32_Security",diff --git a/src-tauri/src/core/utils/mod.rs b/src-tauri/src/core/utils/mod.rsindex 52f60c48..693e31b4 100644--- a/src-tauri/src/core/utils/mod.rs+++ b/src-tauri/src/core/utils/mod.rs@@ -6,3 +6,11 @@ pub fn show_window<R: Runtime>(window: &WebviewWindow<R>) {let _ = window.set_focus();}+pub fn app_icon_temp_path(app: &tauri::AppHandle) -> Option<std::path::PathBuf> {+ let icon = app.default_window_icon()?;+ let path = std::env::temp_dir().join(format!("dsh-notification-{}.png", std::process::id()));+ let rgba = icon.rgba().to_vec();+ let img = image::RgbaImage::from_raw(icon.width(), icon.height(), rgba)?;+ img.save(&path).ok()?;+ Some(path)+}\ No newline at end of filediff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsnew file mode 100644index 00000000..d25c1c36--- /dev/null+++ b/src-tauri/src/desktop/builder.rs@@ -0,0 +1,236 @@+#[cfg(windows)]+use std::sync::atomic::{AtomicBool, Ordering};+#[cfg(windows)]+use std::sync::Arc;++use tauri::{+ ipc::Invoke,+ menu::{Menu, MenuEvent, MenuItem},+ tray::{MouseButton, TrayIconBuilder, TrayIconEvent},+ Manager, Runtime, WebviewUrl, WebviewWindowBuilder, Wry,+};++use crate::core::utils::show_window;+use crate::desktop::window::{on_download, on_new_window};+#[cfg(windows)]+use crate::desktop::window::on_page_load;++/// setup app+pub fn setup(app_handle: tauri::AppHandle) {+ // 启动进程监控(tick 检测 dsh 服务状态)+ crate::service::scheduler::start(&app_handle);++ // 开机自启动:已安装且开启 auto_start 时拉起服务+ let app_for_start = app_handle.clone();+ tauri::async_runtime::spawn(async move {+ let setting = crate::config::get_store_dat_setting(&app_for_start);+ if !setting.auto_start {+ log::debug!("auto_start disabled, skipping startup");+ return;+ }+ if let Err(e) = crate::service::workflow::start(app_for_start).await {+ log::error!("start failed: {}", e);+ }+ });++ // 命令行集成自愈:已安装且开启时,确保 shim 与 PATH 注册完整+ // (shim 被删除、PATH 条目丢失等情况下自动重建)+ tauri::async_runtime::spawn(async move {+ let setting = crate::config::get_store_dat_setting(&app_handle);+ if !setting.installed || !setting.cli_link_enabled {+ return;+ }+ if let Err(e) = crate::service::cli::ensure(&app_handle) {+ log::warn!("cli link self-heal failed: {e}");+ }+ });+}++/// setup tray+pub fn tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> {+ // 使用默认窗口图标+ let icon = app.default_window_icon().unwrap().clone();++ // 构建菜单+ let menu = Menu::with_items(+ app,+ &[+ &MenuItem::with_id(app, "open", "打开面板", true, None::<&str>)?,+ &MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?,+ ],+ )?;++ fn handle_menu_event<R: Runtime>(app: &tauri::AppHandle<R>, event: &MenuEvent) {+ match event.id().as_ref() {+ "open" => {+ if let Some(window) = app.get_webview_window("main") {+ show_window(&window);+ }+ }+ "quit" => {+ app.exit(0);+ }+ _ => {}+ }+ }++ fn handle_tray_icon_event<R: Runtime>(tray: &tauri::tray::TrayIcon<R>, event: &TrayIconEvent) {+ let app = tray.app_handle();+ if let TrayIconEvent::Click {+ button: MouseButton::Left,+ ..+ } = event+ {+ if let Some(window) = app.get_webview_window("main") {+ show_window(&window);+ }+ }+ }++ // 构建托盘图标+ let _ = TrayIconBuilder::new()+ .icon(icon)+ .menu(&menu)+ .show_menu_on_left_click(false)+ .tooltip("Deepseek Harness Desktop")+ .on_menu_event(move |app, event| handle_menu_event(app, &event))+ .on_tray_icon_event(move |tray, event| handle_tray_icon_event(tray, &event))+ .build(app)?;++ Ok(())+}++/// 构建主窗口。+///+/// 主窗口在这里手动创建(不再从 tauri.conf.json 声明):+/// config 声明的窗口无法挂载 on_download,而内嵌 iframe 的 dsh 页面+/// 触发下载时 WebView2 静默保存、用户零感知,需要接管下载以给出反馈。+pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::WebviewWindow<Wry>> {+ let app_handle = app.clone();++ #[cfg(windows)]+ let _notification_handlers_registered = Arc::new(AtomicBool::new(false));+ #[cfg(windows)]+ let notification_handlers_registered_for_page = _notification_handlers_registered.clone();++ let webview_builder =+ WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))+ .title("Deepseek Harness Desktop")+ .inner_size(1280.0, 840.0)+ .min_inner_size(860.0, 620.0)+ .resizable(true)+ .decorations(true)+ // 恢复 iframe 内 HTML5 拖拽(拖入图片/拖动元素):+ // Tauri 默认注册 wry drag_drop_handler → WebView2 SetAllowExternalDrop(false)+ // 并注入 IDropTarget 接管拖放,iframe 内拖拽被禁用。+ // 注意不能用 .drag_and_drop(false):它只设置 tao 窗口层的拖放开关+ // (tauri issue #13761),不影响 webview 层,拖拽依旧失效;+ // disable_drag_drop_handler 才能关掉 wry 的接管(等价于旧配置 dragDropEnabled: false)。+ .disable_drag_drop_handler()+ // 接管内嵌 iframe 的 window.open() / target=_blank 新窗口请求:+ // WebView2 里这类请求走 NewWindowRequested,wry 在没有 handler 时+ // 直接 SetHandled(true) 吞掉(点了没反应)——dshmarket 等预设插件的+ // “源码”按钮在桌面端因此无法跳转(浏览器里正常)。+ // 这里把 http(s) 链接交给系统浏览器打开,其余协议一律拒绝。+ .on_new_window(move |url, features| on_new_window(app_handle.clone(), url, features))+ .on_download(|webview, event| on_download(webview, event));++ #[cfg(windows)]+ let webview_builder = webview_builder.on_page_load(move |webview_window, payload| {+ on_page_load(+ webview_window,+ payload,+ notification_handlers_registered_for_page.clone(),+ )+ });++ // 非 Windows(macOS/Linux)没有 WebView2 的 FrameCreated/ContentLoading 流程,+ // 直接用 Tauri 的 initialization_script_for_all_frames 把通知桥注入所有 frame。+ #[cfg(not(windows))]+ let webview_builder = webview_builder+ .initialization_script_for_all_frames(crate::desktop::notification::NOTIFICATION_SHIM_JS);++ let webview_window = webview_builder.build()?;++ #[cfg(windows)]+ {+ if !_notification_handlers_registered.swap(true, Ordering::SeqCst) {+ log::info!("[notification] scheduling handler registration from setup");+ let webview_for_dialog = webview_window.clone();+ if let Err(e) = webview_window.with_webview(move |webview| {+ if let Err(e) = crate::desktop::notification::enable_notification_permissions(+ webview,+ webview_for_dialog,+ ) {+ log::warn!("[webview] failed to enable notification permission: {e}");+ }+ }) {+ log::warn!("[webview] failed to schedule notification permission setup: {e}");+ }+ }+ }++ Ok(webview_window)+}++// configure invoke handler+pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {+ tauri::generate_handler![+ crate::bridge::cmd::install_dependencies,+ crate::bridge::cmd::check_dsh_update,+ crate::bridge::cmd::launch_harness,+ crate::bridge::cmd::shutdown_harness,+ crate::bridge::cmd::restart_harness,+ crate::bridge::cmd::get_dsh_status,+ crate::bridge::cmd::get_preinstall_plugins,+ crate::bridge::cmd::install_preinstall_plugins,+ crate::bridge::cmd::cancel_preinstall_plugins,+ crate::bridge::cmd::skip_preinstall_plugins,+ crate::bridge::cmd::open_preinstall_repo,+ crate::bridge::cmd::proxy_health_check,+ crate::bridge::cmd::get_runtime_info,+ crate::bridge::cmd::get_app_config,+ crate::bridge::cmd::update_app_config,+ crate::bridge::cmd::get_cli_link_status,+ crate::bridge::cmd::open_in_browser,+ crate::bridge::cmd::copy_service_url,+ crate::bridge::cmd::reveal_data_dir,+ crate::bridge::cmd::reveal_in_folder,+ crate::bridge::cmd::read_service_logs,+ crate::bridge::cmd::clear_service_logs,+ crate::bridge::cmd::set_language,+ crate::bridge::cmd::toggle_sidebar,+ crate::bridge::cmd::get_dsh_theme,+ crate::desktop::notification::show_native_notification,+ ]+}++// configure tauri builder+pub fn builder() -> tauri::Builder<tauri::Wry> {+ tauri::Builder::default()+ .setup(|app| {+ let app_handle = app.handle().clone();+ build_main_window(&app_handle)?;+ tray(&app_handle)?;+ setup(app_handle.clone());+ Ok(())+ })+ // 点击关闭按钮时隐藏到托盘而不是退出程序+ .on_window_event(|window, event| {+ if let tauri::WindowEvent::CloseRequested { api, .. } = event {+ api.prevent_close();+ let _ = window.hide();+ }+ })+ // Opener plugin+ .plugin(tauri_plugin_opener::init())+ // Notification plugin(Windows 上以 tauri-winrt-notification 实现点击回调,+ // 注册官方插件保留跨平台回退能力)+ .plugin(tauri_plugin_notification::init())+ // FS plugin+ .plugin(tauri_plugin_fs::init())+ // Simple Store plugin+ .plugin(tauri_plugin_store::Builder::new().build())+ // Clipboard plugin+ .plugin(tauri_plugin_clipboard_manager::init())+}diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rsnew file mode 100644index 00000000..704414e4--- /dev/null+++ b/src-tauri/src/desktop/mod.rs@@ -0,0 +1,7 @@+pub mod builder;+pub mod notification;+pub mod payload;+pub mod window;++pub use builder::{builder, handler, setup, tray};+pub use notification::show_native_notification;diff --git a/src-tauri/src/desktop/notification.rs b/src-tauri/src/desktop/notification.rsnew file mode 100644index 00000000..3efa32e1--- /dev/null+++ b/src-tauri/src/desktop/notification.rs@@ -0,0 +1,340 @@+#[cfg(windows)]+use tauri::Manager;++use crate::{core::utils::app_icon_temp_path, desktop::payload::NativeNotificationPayload};++/// 如果 DSH 插件仍有兜底走浏览器 Notification,则保持“已授权”假象,+/// 并让每次 `new Notification(...)` 转成发给宿主窗口的 postMessage。+pub(crate) const NOTIFICATION_SHIM_JS: &str = r#"(function () {+ if (window.__dsh_native_notification_bridge__) return;+ window.__dsh_native_notification_bridge__ = true;++ var hostHidden = false;+ var pendingOnClicks = {};++ function setHostHidden(hidden) {+ hidden = !!hidden;+ if (hostHidden === hidden) return;+ hostHidden = hidden;+ try { document.dispatchEvent(new Event('visibilitychange')); } catch (_) {}+ }++ function send(message) {+ try {+ window.parent.postMessage(Object.assign({ source: 'dsh-notification-bridge' }, message), '*');+ } catch (_) {}+ }++ function sessionIdFromTag(tag) {+ var m = /^dsh-notification-(?:pending-)?(.+)-\d+$/.exec(tag || '');+ return m ? m[1] : '';+ }++ function DshNativeNotification(title, options) {+ options = options || {};+ this.title = String(title || '');+ this.options = options;+ this.tag = options.tag || '';+ this.onclick = null;+ this.onclose = null;+ this.onerror = null;+ this.onshow = null;++ if (this.tag) pendingOnClicks[this.tag] = this;++ send({+ type: 'dsh://native-notification',+ title: this.title,+ body: String(options.body || ''),+ tag: this.tag,+ requireInteraction: !!options.requireInteraction,+ sessionId: options.sessionId || sessionIdFromTag(this.tag),+ href: location.href,+ origin: location.origin+ });+ }++ DshNativeNotification.permission = 'granted';+ DshNativeNotification.requestPermission = function () {+ return Promise.resolve('granted');+ };+ DshNativeNotification.prototype.close = function () {+ if (this.tag) send({ type: 'dsh://close-notification', tag: this.tag });+ };++ window.Notification = DshNativeNotification;++ // 属性拦截:让 iframe 中的 visibilityState 强行跟随桌面宿主状态+ (function installHiddenOverrides() {+ var descMap = {+ hidden: { configurable: true, get: function () { return hostHidden; } },+ visibilityState: { configurable: true, get: function () { return hostHidden ? 'hidden' : 'visible'; } }+ };+ [document, Object.getPrototypeOf(document)].forEach(function (target) {+ if (!target) return;+ try {+ Object.defineProperty(target, 'hidden', descMap.hidden);+ Object.defineProperty(target, 'visibilityState', descMap.visibilityState);+ } catch (_) {}+ });+ })();++ window.addEventListener('blur', function () { setHostHidden(true); });+ window.addEventListener('focus', function () { setHostHidden(false); });++ // 查找并聚焦对应的 Session+ function tryFocusSession(sessionId, title) {+ if (!sessionId && !title) return;++ if (typeof window.__dsh_focusSession === 'function') {+ try { window.__dsh_focusSession(sessionId); return; } catch (_) {}+ }++ if (sessionId) {+ var el = document.querySelector('[data-session-id="' + sessionId + '"], [data-session="' + sessionId + '"], [data-id="' + sessionId + '"]');+ if (el) { el.click(); return; }+ }++ if (title) {+ var trimmedTitle = String(title).trim();+ var nodes = document.querySelectorAll('button, [role="button"], li, a');+ for (var i = 0; i < nodes.length; i++) {+ if (nodes[i].offsetParent !== null && nodes[i].textContent.trim() === trimmedTitle) {+ nodes[i].click();+ return;+ }+ }+ }+ }++ window.addEventListener('message', function (event) {+ var data = event.data;+ if (!data || typeof data !== 'object') return;++ switch (data.type) {+ case 'dsh://visibility-state':+ setHostHidden(data.hidden);+ break;+ case 'dsh://focus-session':+ tryFocusSession(data.sessionId, data.title);+ break;+ case 'dsh://notification-clicked':+ var instance = pendingOnClicks[data.tag];+ if (instance && typeof instance.onclick === 'function') {+ try { instance.onclick(new Event('click')); } catch (_) {}+ }+ break;+ }+ });+})();"#;++/// 在 Rust 侧显示一条系统原生通知。+#[tauri::command]+pub fn show_native_notification(+ app: tauri::AppHandle,+ payload: NativeNotificationPayload,+) -> Result<(), String> {+ use tauri_plugin_notification::NotificationExt;++ let mut builder = app+ .notification()+ .builder()+ .title(payload.title)+ .body(payload.body);++ if let Some(icon_path) = app_icon_temp_path(&app) {+ builder = builder.icon(icon_path.to_string_lossy().into_owned());+ }++ if let Some(id) = payload.tag.as_deref().and_then(|t| t.parse::<i32>().ok()) {+ builder = builder.id(id);+ }++ builder.show().map_err(|e| e.to_string())+}++/// 在 Windows WebView2 中接管 iframe 内的通知请求并注入原生通知桥。+#[cfg(windows)]+pub fn enable_notification_permissions(+ webview: tauri::webview::PlatformWebview,+ parent: tauri::WebviewWindow<tauri::Wry>,+) -> Result<(), Box<dyn std::error::Error>> {+ use rfd::{MessageButtons, MessageDialog, MessageDialogResult};+ use webview2_com::{+ ExecuteScriptCompletedHandler, FrameContentLoadingEventHandler, FrameCreatedEventHandler,+ FramePermissionRequestedEventHandler,+ Microsoft::Web::WebView2::Win32::{+ ICoreWebView2Frame3, ICoreWebView2Profile4, ICoreWebView2_13, ICoreWebView2_4,+ COREWEBVIEW2_PERMISSION_KIND, COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS,+ COREWEBVIEW2_PERMISSION_STATE_ALLOW, COREWEBVIEW2_PERMISSION_STATE_DEFAULT,+ COREWEBVIEW2_PERMISSION_STATE_DENY,+ },+ PermissionRequestedEventHandler, SetPermissionStateCompletedHandler,+ };+ use windows_core::{Interface, HSTRING};++ log::info!("[notification] registering WebView2 notification handlers");++ fn ask_notification_permission(parent: &tauri::WebviewWindow<tauri::Wry>) -> bool {+ MessageDialog::new()+ .set_parent(parent)+ .set_title("允许发送通知?")+ .set_description("DSH 页面请求发送桌面通知。是否允许?")+ .set_buttons(MessageButtons::YesNo)+ .show()+ == MessageDialogResult::Yes+ }++ fn notification_origins(parent: &tauri::WebviewWindow<tauri::Wry>) -> Vec<String> {+ let mut origins = vec![+ crate::config::get_dsh_service_url(crate::config::DSH_PORT),+ crate::config::get_dsh_service_url(crate::config::DSH_DEV_PORT),+ ];+ let store_port = crate::config::get_store_dat_setting(parent.app_handle()).port;+ let store_origin = crate::config::get_dsh_service_url(store_port);+ if !origins.contains(&store_origin) {+ origins.push(store_origin);+ }+ origins+ }++ unsafe fn reset_persisted_notification_permissions(+ webview2: &webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2,+ origins: &[String],+ ) -> Result<(), Box<dyn std::error::Error>> {+ let webview13 = webview2.cast::<ICoreWebView2_13>()?;+ let profile = webview13.Profile()?;+ let Ok(profile4) = profile.cast::<ICoreWebView2Profile4>() else {+ log::warn!("[notification] ICoreWebView2Profile4 cast failed; skip reset.");+ return Ok(());+ };++ for origin in origins {+ let origin_str = origin.clone();+ let hstring = HSTRING::from(origin.as_str());+ // HSTRING 是引用计数类型,克隆只增加引用计数、共享底层缓冲区。+ // 回调(completed handler)是异步调用的,让克隆句柄随回调一起持有,+ // 避免 set_permission_state(&hstring) 借用的句柄在回调存活期内失效。+ let hstring_for_callback = hstring.clone();++ log::info!("[notification] resetting persisted notification permission for {origin_str}");+ profile4.SetPermissionState(+ COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS,+ &hstring,+ COREWEBVIEW2_PERMISSION_STATE_DEFAULT,+ &SetPermissionStateCompletedHandler::create(Box::new(move |result| {+ if let Err(e) = result {+ log::warn!("[notification] failed to reset permission for {origin_str}: {e}");+ } else {+ log::info!("[notification] reset permission for {origin_str}");+ }+ // 持有 HSTRING 直到回调销毁,确保异步调用期间 PCWSTR 安全且无内存泄漏+ let _ = &hstring_for_callback;+ Ok(())+ })),+ )?;+ }+ Ok(())+ }++ unsafe fn setup_frame_handlers(+ frame3: ICoreWebView2Frame3,+ parent: tauri::WebviewWindow<tauri::Wry>,+ ) {+ let parent_for_frame = parent.clone();+ let mut permission_token = 0i64;++ let _ = frame3.add_PermissionRequested(+ &FramePermissionRequestedEventHandler::create(Box::new(move |_, args| {+ if let Some(args) = args {+ let mut kind = COREWEBVIEW2_PERMISSION_KIND::default();+ args.PermissionKind(&mut kind)?;++ if kind == COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS {+ let allow = ask_notification_permission(&parent_for_frame);+ let state = if allow {+ COREWEBVIEW2_PERMISSION_STATE_ALLOW+ } else {+ COREWEBVIEW2_PERMISSION_STATE_DENY+ };+ args.SetState(state)?;+ args.SetHandled(true)?;+ }+ }+ Ok(())+ })),+ &mut permission_token,+ );++ let frame_for_injection = frame3.clone();+ let mut content_token = 0i64;++ let _ = frame3.add_ContentLoading(+ &FrameContentLoadingEventHandler::create(Box::new(move |_, _| {+ let script = HSTRING::from(NOTIFICATION_SHIM_JS);+ let _ = frame_for_injection.ExecuteScript(+ &script,+ &ExecuteScriptCompletedHandler::create(Box::new(|_, _| Ok(()))),+ );+ Ok(())+ })),+ &mut content_token,+ );+ }++ let origins = notification_origins(&parent);+ let mut token = 0i64;++ unsafe {+ let controller = webview.controller();+ let webview2 = controller.CoreWebView2()?;++ if let Err(e) = reset_persisted_notification_permissions(&webview2, &origins) {+ log::warn!("[notification] failed to reset permissions: {e}");+ }++ // 1. 处理顶级页面权限请求+ let parent_for_top = parent.clone();+ webview2.add_PermissionRequested(+ &PermissionRequestedEventHandler::create(Box::new(move |_, args| {+ if let Some(args) = args {+ let mut kind = COREWEBVIEW2_PERMISSION_KIND::default();+ args.PermissionKind(&mut kind)?;++ if kind == COREWEBVIEW2_PERMISSION_KIND_NOTIFICATIONS {+ let state = if ask_notification_permission(&parent_for_top) {+ COREWEBVIEW2_PERMISSION_STATE_ALLOW+ } else {+ COREWEBVIEW2_PERMISSION_STATE_DENY+ };+ args.SetState(state)?;+ }+ }+ Ok(())+ })),+ &mut token,+ )?;++ // 2. 处理 iframe 页面权限与 JS 脚本注入+ if let Ok(webview4) = webview2.cast::<ICoreWebView2_4>() {+ let mut frame_created_token = 0i64;+ let parent_for_frame_created = parent.clone();++ webview4.add_FrameCreated(+ &FrameCreatedEventHandler::create(Box::new(move |_, args| {+ if let Some(args) = args {+ if let Ok(frame) = args.Frame() {+ if let Ok(frame3) = frame.cast::<ICoreWebView2Frame3>() {+ setup_frame_handlers(frame3, parent_for_frame_created.clone());+ }+ }+ }+ Ok(())+ })),+ &mut frame_created_token,+ )?;+ }+ }++ Ok(())+}\ No newline at end of filediff --git a/src-tauri/src/desktop/payload.rs b/src-tauri/src/desktop/payload.rsnew file mode 100644index 00000000..6f328129--- /dev/null+++ b/src-tauri/src/desktop/payload.rs@@ -0,0 +1,20 @@+/// 下载完成事件载荷:`on_download` 的 Finished 分支向前端 emit,+/// 由桌面外壳展示"已保存 + 打开文件夹"提示(iframe 内的下载对用户不可见)。+#[derive(Clone, serde::Serialize)]+pub struct DownloadFinishedPayload {+ /// 原始下载地址(dsh 的 /api/session.export?sessionId=...)+ pub(crate) url: String,+ /// 保存到本地的完整路径;失败或平台拿不到路径时为 None+ pub(crate) path: Option<String>,+ /// 下载是否成功+ pub(crate) success: bool,+}++/// iframe 内 DSH 页面发来的原生通知请求载荷。+#[derive(serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct NativeNotificationPayload {+ pub(crate) title: String,+ pub(crate) body: String,+ pub(crate) tag: Option<String>,+}diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rsnew file mode 100644index 00000000..0fe58788--- /dev/null+++ b/src-tauri/src/desktop/window.rs@@ -0,0 +1,94 @@+#[cfg(windows)]+use std::sync::atomic::AtomicBool;+#[cfg(windows)]+use std::sync::Arc;++use tauri::{+ webview::{DownloadEvent, NewWindowFeatures, NewWindowResponse},+ Emitter, Runtime, Url, Webview,+};+#[cfg(windows)]+use tauri::webview::{PageLoadEvent, PageLoadPayload};+#[cfg(windows)]+use tauri::{WebviewWindow, Wry};+use tauri_plugin_opener::OpenerExt;++use crate::config;+use crate::desktop::payload::DownloadFinishedPayload;++/// 接管内嵌 iframe 的 `window.open()` / `target=_blank` 新窗口请求:+/// WebView2 里这类请求走 NewWindowRequested,wry 在没有 handler 时直接吞掉。+/// 这里把 http(s) 链接交给系统浏览器打开,其余协议一律拒绝。+pub fn on_new_window<R: Runtime>(+ app_handle: tauri::AppHandle<R>,+ url: Url,+ _features: NewWindowFeatures,+) -> NewWindowResponse<R> {+ if matches!(url.scheme(), "http" | "https") {+ if let Err(e) = app_handle.opener().open_url(url.to_string(), None::<&str>) {+ log::warn!("[new-window] open in browser failed {e}");+ }+ } else {+ log::debug!("[new-window] denied {url}");+ }+ NewWindowResponse::Deny+}++/// 接管下载:保存到系统下载目录,重名时自动加 " (n)" 后缀,+/// 完成后向前端 emit `harness-download-finished`。+pub fn on_download<R: Runtime>(webview: Webview<R>, event: DownloadEvent<'_>) -> bool {+ match event {+ DownloadEvent::Requested { url, destination } => {+ *destination = config::unique_download_path(destination);+ log::info!("[download] requested {} -> {}", url, destination.display());+ true+ }+ DownloadEvent::Finished { url, path, success } => {+ let path_str = path.as_ref().map(|p| p.to_string_lossy().to_string());+ let payload = DownloadFinishedPayload {+ url: url.to_string(),+ path: path_str,+ success,+ };+ let _ = webview.emit("harness-download-finished", payload);+ log::info!(+ "[download] finished {} success={} path={:?}",+ url,+ success,+ path+ );+ true+ }+ // DownloadEvent 为 #[non_exhaustive],预留未来变体+ _ => true,+ }+}++#[cfg(windows)]+pub fn on_page_load(+ webview_window: WebviewWindow<Wry>,+ payload: PageLoadPayload<'_>,+ notification_handlers_registered_for_page: Arc<AtomicBool>,+) {+ // Windows 依赖 WebView2 的 FramePermissionRequested / FrameCreated 机制,+ // 需要在页面加载时注册;非 Windows 已在 build_main_window 里通过+ // initialization_script_for_all_frames 注入,这里不需要再做处理。+ if payload.event() == PageLoadEvent::Started+ && !notification_handlers_registered_for_page.swap(+ true,+ std::sync::atomic::Ordering::SeqCst,+ )+ {+ log::info!("[notification] top-level page load started; scheduling handler registration");+ let parent = webview_window.clone();+ if let Err(e) = webview_window.with_webview(move |platform| {+ if let Err(e) =+ crate::desktop::notification::enable_notification_permissions(platform, parent)+ {+ log::warn!("[webview] failed to enable notification permission: {e}");+ }+ }) {+ log::warn!("[webview] failed to schedule notification permission setup: {e}");+ }+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex c6a0340f..37a957d8 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,247 +1,17 @@mod bridge;mod config;mod core;+pub mod desktop;mod logger;mod service;mod task;-use core::utils::show_window;-use tauri::{- ipc::Invoke,- menu::{Menu, MenuEvent, MenuItem},- tray::{MouseButton, TrayIconBuilder, TrayIconEvent},- webview::{DownloadEvent, NewWindowResponse},- Emitter, Manager, Runtime, WebviewUrl, WebviewWindowBuilder, Wry,-};-use tauri_plugin_opener::OpenerExt;--/// 下载完成事件载荷:`on_download` 的 Finished 分支向前端 emit,-/// 由桌面外壳展示"已保存 + 打开文件夹"提示(iframe 内的下载对用户不可见)。-#[derive(Clone, serde::Serialize)]-struct DownloadFinishedPayload {- /// 原始下载地址(dsh 的 /api/session.export?sessionId=...)- url: String,- /// 保存到本地的完整路径;失败或平台拿不到路径时为 None- path: Option<String>,- /// 下载是否成功- success: bool,-}--// setup app-fn setup(app_handle: tauri::AppHandle) {- // 启动进程监控(tick 检测 dsh 服务状态)- service::scheduler::start(&app_handle);-- // 开机自启动:已安装且开启 auto_start 时拉起服务- let app_for_start = app_handle.clone();- tauri::async_runtime::spawn(async move {- let setting = config::get_store_dat_setting(&app_for_start);- if !setting.auto_start {- log::debug!("auto_start disabled, skipping startup");- return;- }- if let Err(e) = service::workflow::start(app_for_start).await {- log::error!("start failed: {}", e);- }- });-- // 命令行集成自愈:已安装且开启时,确保 shim 与 PATH 注册完整- // (shim 被删除、PATH 条目丢失等情况下自动重建)- tauri::async_runtime::spawn(async move {- let setting = config::get_store_dat_setting(&app_handle);- if !setting.installed || !setting.cli_link_enabled {- return;- }- if let Err(e) = service::cli::ensure(&app_handle) {- log::warn!("cli link self-heal failed: {e}");- }- });-}--// setup tray-fn tray<R: Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<()> {- // 使用默认窗口图标- let icon = app.default_window_icon().unwrap().clone();-- // 构建菜单- let menu = Menu::with_items(- app,- &[- &MenuItem::with_id(app, "open", "打开面板", true, None::<&str>)?,- &MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?,- ],- )?;-- fn handle_menu_event<R: Runtime>(app: &tauri::AppHandle<R>, event: &MenuEvent) {- match event.id().as_ref() {- "open" => {- if let Some(window) = app.get_webview_window("main") {- show_window(&window);- }- }- "quit" => {- app.exit(0);- }- _ => {}- }- }-- fn handle_tray_icon_event<R: Runtime>(tray: &tauri::tray::TrayIcon<R>, event: &TrayIconEvent) {- let app = tray.app_handle();- if let TrayIconEvent::Click {- button: MouseButton::Left,- ..- } = event- {- if let Some(window) = app.get_webview_window("main") {- show_window(&window);- }- }- }-- // 构建托盘图标- let _ = TrayIconBuilder::new()- .icon(icon)- .menu(&menu)- .show_menu_on_left_click(false)- .tooltip("Deepseek Harness Desktop")- .on_menu_event(move |app, event| handle_menu_event(app, &event))- .on_tray_icon_event(move |tray, event| handle_tray_icon_event(tray, &event))- .build(app)?;-- Ok(())-}--// configure invoke handler-fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {- tauri::generate_handler![- bridge::cmd::install_dependencies,- bridge::cmd::check_dsh_update,- bridge::cmd::launch_harness,- bridge::cmd::shutdown_harness,- bridge::cmd::restart_harness,- bridge::cmd::get_dsh_status,- bridge::cmd::get_preinstall_plugins,- bridge::cmd::install_preinstall_plugins,- bridge::cmd::cancel_preinstall_plugins,- bridge::cmd::skip_preinstall_plugins,- bridge::cmd::open_preinstall_repo,- bridge::cmd::proxy_health_check,- bridge::cmd::get_runtime_info,- bridge::cmd::get_app_config,- bridge::cmd::update_app_config,- bridge::cmd::get_cli_link_status,- bridge::cmd::open_in_browser,- bridge::cmd::copy_service_url,- bridge::cmd::reveal_data_dir,- bridge::cmd::reveal_in_folder,- bridge::cmd::read_service_logs,- bridge::cmd::clear_service_logs,- bridge::cmd::set_language,- bridge::cmd::toggle_sidebar,- bridge::cmd::get_dsh_theme,- ]-}--// configure tauri builder-fn builder() -> tauri::Builder<tauri::Wry> {- tauri::Builder::default()- // 主窗口在这里手动创建(不再从 tauri.conf.json 声明):- // config 声明的窗口无法挂载 on_download,而内嵌 iframe 的 dsh 页面- // 触发下载时 WebView2 静默保存、用户零感知,需要接管下载以给出反馈。- .setup(|app| {- let app_handle = app.handle().clone();- WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))- .title("Deepseek Harness Desktop")- .inner_size(1280.0, 840.0)- .min_inner_size(860.0, 620.0)- .resizable(true)- .decorations(true)- // 恢复 iframe 内 HTML5 拖拽(拖入图片/拖动元素):- // Tauri 默认注册 wry drag_drop_handler → WebView2 SetAllowExternalDrop(false)- // 并注入 IDropTarget 接管拖放,iframe 内拖拽被禁用。- // 注意不能用 .drag_and_drop(false):它只设置 tao 窗口层的拖放开关- // (tauri issue #13761),不影响 webview 层,拖拽依旧失效;- // disable_drag_drop_handler 才能关掉 wry 的接管(等价于旧配置 dragDropEnabled: false)。- .disable_drag_drop_handler()- // 接管内嵌 iframe 的 window.open() / target=_blank 新窗口请求:- // WebView2 里这类请求走 NewWindowRequested,wry 在没有 handler 时- // 直接 SetHandled(true) 吞掉(点了没反应)——dshmarket 等预设插件的- // “源码”按钮在桌面端因此无法跳转(浏览器里正常)。- // 这里把 http(s) 链接交给系统浏览器打开,其余协议一律拒绝。- .on_new_window(move |url, _features| {- if matches!(url.scheme(), "http" | "https") {- if let Err(e) = app_handle.opener().open_url(url.to_string(), None::<&str>) {- log::warn!("[new-window] open in browser failed {e}");- }- } else {- log::debug!("[new-window] denied {url}");- }- NewWindowResponse::Deny- })- .on_download(|webview, event| match event {- DownloadEvent::Requested { url, destination } => {- // 接管下载:保存到系统下载目录,重名时自动加 " (n)" 后缀- *destination = config::unique_download_path(destination);- log::info!(- "[download] requested {} -> {}",- url,- destination.display()- );- true- }- DownloadEvent::Finished {- url,- path,- success,- } => {- let path_str = path.as_ref().map(|p| p.to_string_lossy().to_string());- let payload = DownloadFinishedPayload {- url: url.to_string(),- path: path_str,- success,- };- let _ = webview.emit("harness-download-finished", payload);- log::info!(- "[download] finished {} success={} path={:?}",- url,- success,- path- );- true- }- // DownloadEvent 为 #[non_exhaustive],预留未来变体- _ => true,- })- .build()?;- tray(app.handle())?;- setup(app.handle().clone());- Ok(())- })- // 点击关闭按钮时隐藏到托盘而不是退出程序- .on_window_event(|window, event| {- if let tauri::WindowEvent::CloseRequested { api, .. } = event {- api.prevent_close();- let _ = window.hide();- }- })- // Opener plugin- .plugin(tauri_plugin_opener::init())- // FS plugin- .plugin(tauri_plugin_fs::init())- // Simple Store plugin- .plugin(tauri_plugin_store::Builder::new().build())- // Clipboard plugin- .plugin(tauri_plugin_clipboard_manager::init())-}--// run apppub fn run() {// 初始化日志系统logger::init();- builder()- .invoke_handler(handler())+ desktop::builder()+ .invoke_handler(desktop::handler()).build(tauri::generate_context!()).expect("error while building tauri application").run(|app_handle, event| {