DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
refactor: align src-tauri structure with early n8n-based damn-reports
hairyf32200f2c5320
diff --git a/README.md b/README.mdindex 74f73aec..6ccadefc 100644--- a/README.md+++ b/README.md@@ -73,10 +73,10 @@ pnpm icons包含:- `runtime/`:Node.js 运行时-- `dsh-core/`:Harness 发行版-- `dsh-home/`:Harness 用户数据(`$DSH_HOME`,含 profile、会话、设置)+- `dependencies/dsh/`:Harness 发行版(`deepseek-harness-pkg` zip 解压)+- `data/dsh/`:Harness 用户数据(`$DSH_HOME`,含 profile、会话、设置)- `logs/`:应用与 dsh 服务日志-- `config/`:桌面端配置(端口、自启动)+- `.store.dat`:桌面端配置(端口、自启动、语言,由 tauri-plugin-store 管理)## 安全声明diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 016fcf24..1a2aec42 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -16,29 +16,29 @@│ invoke 命令 + 事件┌───────────────┴────────────────────────────────┐│ Tauri Rust 后端 │-│ installer : 下载并校验 dsh-core zip │-│ manager : Node 运行时 + dsh 进程管理 │-│ downloader : 带进度的下载与解压 │-│ health : 127.0.0.1:3080 健康检查 │+│ bridge : invoke 命令(cmd.rs) │+│ config : 常量 / 运行时路径 / 设置 │+│ service : download 安装器 + workflow 进程 │+│ task : tick 检测 dsh 服务状态 │└───────┬──────────────────────┬─────────────────┘│ │- <app-data>/runtime <app-data>/dsh-core- (Node.js v22.22.0) (@hairyf/... zip 解压)+ <app-data>/runtime <app-data>/dependencies/dsh+ (Node.js v22.22.0) (deepseek-harness-pkg zip 解压)│ │└──────────┬───────────┘▼dsh --profile web --host 127.0.0.1 --port 3080- │ DSH_HOME=<app-data>/dsh-home+ │ DSH_HOME=<app-data>/data/dsh▼http://127.0.0.1:3080/ ← iframe```## 启动流程-1. 检查/下载 Node.js 运行时(`nodejs.org`,失败回退 `npmmirror`);-2. 检查/下载 `dsh-core-<os>-<arch>.zip`(GitHub Release,SHA-256 校验);-3. 解压到 `<app-data>/dsh-core`;-4. 以隔离的 `$DSH_HOME` 启动 `dsh --profile web`;+1. 检查/下载 Node.js 运行时(`nodejs.org`,`service/download` 带进度解压);+2. 检查/下载 `deepseek-harness-pkg-<os>.zip`(GitHub Release);+3. 解压到 `<app-data>/dependencies/dsh`;+4. 以隔离的 `$DSH_HOME`(`<app-data>/data/dsh`)启动 `dsh --profile web`;5. 轮询健康检查,就绪后在前端 iframe 中加载 UI。## 数据目录@@ -47,15 +47,23 @@- macOS:`~/Library/Application Support/io.github.hairyf.deepseek-harness-desktop/`- Linux:`~/.local/share/io.github.hairyf.deepseek-harness-desktop/`-包含:`runtime/`(Node.js)、`dsh-core/`(harness 发行版)、`dsh-home/`(harness 用户数据)、-`logs/`、`config/`。+包含:`runtime/`(Node.js)、`dependencies/dsh/`(harness 发行版)、+`data/dsh/`(harness 用户数据)、`logs/`、`.store.dat`(桌面设置)。## 目录说明```textsrc/ React 前端(状态机、侧边栏、i18n)-src-tauri/src/api/ Rust 命令与 harness 生命周期-src-tauri/src/services/ 下载器与进程管理器+src-tauri/src/bridge/ invoke 命令(cmd.rs)+src-tauri/src/config/ 常量 / 运行时路径 / 设置(store)+src-tauri/src/service/ download 安装器 + workflow 进程生命周期+src-tauri/src/task/ 定时检测 dsh 服务状态+src-tauri/src/logger/ 简易日志系统(SimpleLogger)docs/PKG-CONTRACT.md deepseek-harness-pkg 发布契约public/favicon.svg 应用图标源(黑标白底圆角,pnpm icons 生成)```++> 后端目录与文件命名对齐早期依赖 n8n 的+> [damn-reports](https://github.com/hairyf/damn-reports)(提交 `c818b79`):+> `bridge/`、`config/`、`core/`、`logger/`、`service/download/`、+> `service/workflow/`、`task/`。diff --git a/docs/PKG-CONTRACT.md b/docs/PKG-CONTRACT.mdindex 318018cb..8ca603df 100644--- a/docs/PKG-CONTRACT.md+++ b/docs/PKG-CONTRACT.md@@ -38,7 +38,7 @@ zip 是自包含的 npm 项目,**顶层目录直接就是包内容**(没有└─ .bin/dsh # bin shim(桌面端不使用,直接跑 lib/bin.js)```-桌面端解压到 `<app-data>/dsh-core/`,并直接调用+桌面端解压到 `<app-data>/dependencies/dsh/`,并直接调用`node_modules/@deepseek-ai/dsh/lib/bin.js` 作为 CLI 入口。## 3. 清单字段diff --git a/src-tauri/.gitignore b/src-tauri/.gitignorenew file mode 100644index 00000000..b21bd681--- /dev/null+++ b/src-tauri/.gitignore@@ -0,0 +1,7 @@+# Generated by Cargo+# will have compiled files and executables+/target/++# Generated by Tauri+# will have schema files for capabilities auto-completion+/gen/schemasdiff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 0cb02467..c04c5f6f 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -58,15 +58,6 @@ version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"-[[package]]-name = "arbitrary"-version = "1.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"-dependencies = [- "derive_arbitrary",-]-[[package]]name = "arboard"version = "3.6.1"@@ -266,6 +257,12 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]name = "bit-set"version = "0.8.0"@@ -392,11 +389,12 @@ dependencies = [[[package]]name = "bzip2"-version = "0.5.2"+version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "49ecfb22d906f800d4fe833b6282cf4dc1c298f5057ca0b5445e5c209735ca47"+checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"dependencies = ["bzip2-sys",+ "libc",][[package]]@@ -573,9 +571,9 @@ dependencies = [[[package]]name = "constant_time_eq"-version = "0.3.1"+version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"+checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"[[package]]name = "cookie"@@ -646,21 +644,6 @@ dependencies = ["libc",]-[[package]]-name = "crc"-version = "3.4.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"-dependencies = [- "crc-catalog",-]--[[package]]-name = "crc-catalog"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"-[[package]]name = "crc32fast"version = "1.5.0"@@ -789,10 +772,10 @@ dependencies = [name = "deepseek-harness-desktop"version = "0.1.0"dependencies = [+ "async-trait","flate2","futures-util",- "libc",- "once_cell",+ "log","reqwest 0.12.28","serde","serde_json",@@ -803,18 +786,11 @@ dependencies = ["tauri-plugin-clipboard-manager","tauri-plugin-fs","tauri-plugin-opener",- "thiserror 2.0.20",+ "tauri-plugin-store","tokio",- "url","zip",]-[[package]]-name = "deflate64"-version = "0.1.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"-[[package]]name = "defmt"version = "1.1.1"@@ -855,17 +831,6 @@ dependencies = ["serde_core",]-[[package]]-name = "derive_arbitrary"-version = "1.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-]-[[package]]name = "derive_more"version = "2.1.1"@@ -1499,11 +1464,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"dependencies = ["cfg-if",- "js-sys","libc","r-efi 5.3.0","wasip2",- "wasm-bindgen",][[package]]@@ -2364,27 +2327,6 @@ version = "0.4.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"-[[package]]-name = "lzma-rs"-version = "0.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "297e814c836ae64db86b36cf2a557ba54368d03f6afcd7d947c266692f71115e"-dependencies = [- "byteorder",- "crc",-]--[[package]]-name = "lzma-sys"-version = "0.1.20"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5fda04ab3764e6cde78b9974eec4f779acaba7c4e84b36eca3cf77c581b85d27"-dependencies = [- "cc",- "libc",- "pkg-config",-]-[[package]]name = "markup5ever"version = "0.38.0"@@ -2899,14 +2841,27 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "password-hash"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700"+dependencies = [+ "base64ct",+ "rand_core",+ "subtle",+]+[[package]]name = "pbkdf2"-version = "0.12.2"+version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"+checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917"dependencies = ["digest","hmac",+ "password-hash",+ "sha2",][[package]]@@ -3195,6 +3150,12 @@ version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"+[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+[[package]]name = "raw-window-handle"version = "0.6.2"@@ -4250,6 +4211,22 @@ dependencies = ["zbus",]+[[package]]+name = "tauri-plugin-store"+version = "2.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6708afbe549f176b712066e71648ba8fafba20789453718260c7ca356733cb0c"+dependencies = [+ "dunce",+ "serde",+ "serde_json",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.20",+ "tokio",+ "tracing",+]+[[package]]name = "tauri-runtime"version = "2.11.3"@@ -5835,15 +5812,6 @@ dependencies = ["rustix",]-[[package]]-name = "xz2"-version = "0.1.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "388c44dc09d76f1536602ead6d325eb532f5c122f17782bd57fb47baeeb767e2"-dependencies = [- "lzma-sys",-]-[[package]]name = "yoke"version = "0.8.3"@@ -5983,20 +5951,6 @@ name = "zeroize"version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"-dependencies = [- "zeroize_derive",-]--[[package]]-name = "zeroize_derive"-version = "1.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"-dependencies = [- "proc-macro2",- "quote",- "syn 2.0.119",-][[package]]name = "zerotrie"@@ -6033,31 +5987,21 @@ dependencies = [[[package]]name = "zip"-version = "2.4.2"+version = "0.6.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"+checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"dependencies = ["aes",- "arbitrary",+ "byteorder","bzip2","constant_time_eq","crc32fast","crossbeam-utils",- "deflate64",- "displaydoc","flate2",- "getrandom 0.3.4","hmac",- "indexmap 2.14.0",- "lzma-rs",- "memchr","pbkdf2","sha1",- "thiserror 2.0.20","time",- "xz2",- "zeroize",- "zopfli","zstd",]@@ -6067,33 +6011,22 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"-[[package]]-name = "zopfli"-version = "0.8.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"-dependencies = [- "bumpalo",- "crc32fast",- "log",- "simd-adler32",-]-[[package]]name = "zstd"-version = "0.13.3"+version = "0.11.2+zstd.1.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"+checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4"dependencies = ["zstd-safe",][[package]]name = "zstd-safe"-version = "7.2.4"+version = "5.0.2+zstd.1.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"+checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db"dependencies = [+ "libc","zstd-sys",]diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 778a417a..1fd81f06 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -6,29 +6,37 @@ authors = ["deepseek-harness-desktop contributors"]edition = "2021"[lib]-name = "deepseek_harness_desktop_lib"-crate-type = ["staticlib", "cdylib", "rlib"]+# The `_lib` suffix may seem redundant but it is necessary+# to make the lib name unique and wouldn't conflict with the bin name.+# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519+name = "main"+crate-type = [+ "staticlib",+ "cdylib",+ "rlib"+][build-dependencies]tauri-build = { version = "2", features = [] }[dependencies]-tauri = { version = "2", features = ["macos-private-api", "image-ico", "image-png"] }+tauri = { version = "2", features = [+ "tray-icon",+ "image-png",+ "devtools"+] }tauri-plugin-opener = "2"tauri-plugin-fs = "2"+tauri-plugin-store = "2"tauri-plugin-clipboard-manager = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"-once_cell = "1"-thiserror = "2"-tokio = { version = "1", features = ["full"] }+log = "0.4"reqwest = { version = "0.12", features = ["json", "stream"] }-zip = "2"+zip = "0.6"futures-util = "0.3"flate2 = "1"tar = "0.4"sha2 = "0.10"-url = "2"--[target.'cfg(unix)'.dependencies]-libc = "0.2"+async-trait = "0.1"+tokio = { version = "1", features = ["full"] }diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 7cab0507..22008d65 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -8,7 +8,18 @@"core:event:allow-listen","core:event:allow-unlisten","core:app:allow-version",+ "core:app:allow-default-window-icon",+ "core:window:default",+ "core:window:allow-show",+ "core:window:allow-hide",+ "core:window:allow-set-focus",+ "core:window:allow-unminimize",+ "core:window:allow-unmaximize","opener:default",+ "opener:allow-open-url",+ "opener:allow-default-urls",+ "opener:allow-reveal-item-in-dir",+ "store:default","clipboard-manager:allow-write-text"]}diff --git a/src-tauri/capabilities/desktop.json b/src-tauri/capabilities/desktop.jsonnew file mode 100644index 00000000..5c839cd8--- /dev/null+++ b/src-tauri/capabilities/desktop.json@@ -0,0 +1,12 @@+{+ "identifier": "desktop-capability",+ "platforms": [+ "macOS",+ "windows",+ "linux"+ ],+ "windows": [+ "main"+ ],+ "permissions": []+}diff --git a/src-tauri/resources/README.md b/src-tauri/resources/README.mdindex 99394a9e..4f1dae62 100644--- a/src-tauri/resources/README.md+++ b/src-tauri/resources/README.md@@ -7,10 +7,10 @@ directory (the Tauri app-data dir for identifier`io.github.hairyf.deepseek-harness-desktop`, e.g. `%APPDATA%/io.github.hairyf.deepseek-harness-desktop/` on Windows):- `runtime/` — the bundled Node.js runtime (downloaded on first run)-- `dsh-core/` — the packaged DeepSeek Harness distribution (downloaded from the+- `dependencies/dsh/` — the packaged DeepSeek Harness distribution (downloaded from the`hairyf/deepseek-harness-pkg` release feed)-- `dsh-home/` — the isolated `$DSH_HOME` used by the running `dsh` process+- `data/dsh/` — the isolated `$DSH_HOME` used by the running `dsh` process- `logs/` — application and `dsh` service logs-- `config/` — desktop settings (port, auto-start, etc.)+- `.store.dat` — desktop settings (port, auto-start, language, etc.)No manual Node.js or pnpm installation is required.diff --git a/src-tauri/src/api/commands.rs b/src-tauri/src/api/commands.rsdeleted file mode 100644index 81deba91..00000000--- a/src-tauri/src/api/commands.rs+++ /dev/null@@ -1,180 +0,0 @@-//! Tauri commands exposed to the frontend.--use tauri::{AppHandle, Manager, Runtime, Window};-use tauri_plugin_clipboard_manager::ClipboardExt;-use tauri_plugin_opener::OpenerExt;--use crate::api::harness;-use crate::api::utils;-use crate::i18n;--/// Check whether the harness package is installed.-#[tauri::command]-pub async fn is_installed<R: Runtime>(app: AppHandle<R>) -> bool {- println!("[cmd] is_installed");- harness::is_installed(&app)-}--/// Set up the bundled Node.js runtime.-#[tauri::command]-pub async fn setup_runtime<R: Runtime>(window: Window<R>) -> Result<(), String> {- println!("[cmd] setup_runtime");- harness::setup_runtime(window).await.map_err(|e| e.to_string())-}--/// One-shot install of the Node runtime and the harness package, streaming-/// `install-progress` events to the installer page.-#[tauri::command]-pub async fn install_dependencies<R: Runtime>(window: Window<R>) -> Result<(), String> {- println!("[cmd] install_dependencies");- harness::install_dependencies(window).await.map_err(|e| e.to_string())-}--/// Download and install the packaged harness distribution.-#[tauri::command]-pub async fn setup_harness<R: Runtime>(window: Window<R>) -> Result<(), String> {- println!("[cmd] setup_harness");- harness::setup_harness(window).await.map_err(|e| e.to_string())-}--/// Launch the local dsh service.-#[tauri::command]-pub async fn launch_harness<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {- println!("[cmd] launch_harness");- harness::launch_harness(&app).map_err(|e| e.to_string())-}--/// Stop the local dsh service.-#[tauri::command]-pub fn shutdown_harness() -> Result<(), String> {- harness::shutdown_harness().map_err(|e| e.to_string())-}--/// Health check through the Rust proxy.-#[tauri::command]-pub async fn proxy_health_check<R: Runtime>(app: AppHandle<R>) -> Result<String, String> {- println!("[cmd] proxy_health_check");- let port = utils::active_port(&app);- harness::proxy_health_check(port).await.map_err(|e| e.to_string())-}--/// Runtime/version/diagnostic info for the sidebar.-#[tauri::command]-pub async fn get_runtime_info<R: Runtime>(app: AppHandle<R>) -> Result<harness::RuntimeInfo, String> {- println!("[cmd] get_runtime_info");- let config = harness::AppConfig::load(&app);- Ok(harness::runtime_info(&app, &config))-}--/// Current desktop configuration.-#[tauri::command]-pub async fn get_app_config<R: Runtime>(app: AppHandle<R>) -> Result<harness::AppConfig, String> {- Ok(harness::AppConfig::load(&app))-}--/// Update desktop configuration.-#[tauri::command]-pub async fn update_app_config<R: Runtime>(- app: AppHandle<R>,- port: Option<u16>,- auto_start: Option<bool>,-) -> Result<harness::AppConfig, String> {- let mut config = harness::AppConfig::load(&app);- if let Some(port) = port {- if port == 0 {- return Err("port must be a positive number".to_string());- }- config.port = port;- }- if let Some(auto_start) = auto_start {- config.auto_start = auto_start;- }- config.save(&app).map_err(|e| e.to_string())?;- Ok(config)-}--/// Open the harness UI in the system browser.-#[tauri::command]-pub async fn open_in_browser<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {- let url = harness::service_url(utils::active_port(&app));- app.opener().open_url(url, None::<&str>).map_err(|e| e.to_string())-}--/// Copy the harness URL to the clipboard.-#[tauri::command]-pub async fn copy_service_url<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {- let url = harness::service_url(utils::active_port(&app));- app.clipboard().write_text(url).map_err(|e| e.to_string())-}--/// Reveal the app data directory in the system file manager.-#[tauri::command]-pub async fn reveal_data_dir<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| e.to_string())?;-- let command = if cfg!(windows) {- std::process::Command::new("explorer")- .arg(&app_data_dir)- .spawn()- } else if cfg!(target_os = "macos") {- std::process::Command::new("open").arg(&app_data_dir).spawn()- } else {- std::process::Command::new("xdg-open").arg(&app_data_dir).spawn()- };- command.map_err(|e| format!("{}: {e}", i18n::t("download.failed")))?;- Ok(())-}--/// Tail the dsh service log file.-#[tauri::command]-pub async fn read_service_logs<R: Runtime>(- app: AppHandle<R>,- max_bytes: Option<usize>,-) -> Result<String, String> {- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| e.to_string())?;- let log_path = app_data_dir.join("logs").join("dsh-web.log");- if !log_path.exists() {- return Ok(String::new());- }-- let content = std::fs::read_to_string(&log_path).map_err(|e| e.to_string())?;- let max_bytes = max_bytes.unwrap_or(64 * 1024);- if content.len() <= max_bytes {- Ok(content)- } else {- Ok(content[content.len() - max_bytes..].to_string())- }-}--/// Reset the dsh service log file.-#[tauri::command]-pub async fn clear_service_logs<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| e.to_string())?;- let log_path = app_data_dir.join("logs").join("dsh-web.log");- std::fs::write(&log_path, "").map_err(|e| e.to_string())-}--/// Set the backend language for Rust-side error strings.-#[tauri::command]-pub fn set_language(lang: String) {- let l = match lang.to_lowercase().as_str() {- "en" => i18n::Lang::En,- _ => i18n::Lang::Zh,- };- i18n::set_language(l);-}--/// Toggle the sidebar (parity command; layout state lives in the frontend).-#[tauri::command]-pub async fn toggle_sidebar() -> Result<bool, String> {- Ok(true)-}diff --git a/src-tauri/src/api/harness/constants.rs b/src-tauri/src/api/harness/constants.rsdeleted file mode 100644index 97fec5b0..00000000--- a/src-tauri/src/api/harness/constants.rs+++ /dev/null@@ -1,67 +0,0 @@-//! Constants shared by the harness setup/launch pipeline.--use std::time::Duration;--/// Bundled Node.js runtime version. Satisfies the harness requirement of-/// v22.15.0+ / v23.8.0+ and the upstream `@deepseek-ai/dsh` engines-/// (`^22.19.0 || >=24.0.0`).-pub const NODEJS_VERSION: &str = "v22.22.0";--/// Lowest Node.js version accepted by the packaged harness.-pub const MINIMUM_NODE_VERSION: &str = "22.15.0";--/// Official Node.js download base.-pub const NODEJS_BASE_URL: &str = "https://nodejs.org/dist/";--/// npmmirror (Taobao) Node.js mirror, used as a fallback for slow networks.-pub const NODEJS_NPMMIRROR_URL: &str = "https://npmmirror.com/mirrors/node/";--/// Host the harness web server binds to.-pub const DSH_SERVICE_HOST: &str = "127.0.0.1";--/// Default harness web server port (dsh default: 3080).-pub const DSH_SERVICE_PORT: &str = "3080";--/// Directory (under the app data dir) used as the isolated `$DSH_HOME`.-pub const DSH_HOME_DIR_NAME: &str = "dsh-home";--/// DeepSeek Harness packaged distribution release feed (GitHub API).-pub const PKG_GITHUB_API_URL: &str =- "https://api.github.com/repos/hairyf/deepseek-harness-pkg/releases/latest";--/// User-Agent used for GitHub API requests.-pub const PKG_GITHUB_USER_AGENT: &str = "deepseek-harness-desktop";--/// Direct asset download base for the packaged harness.-pub const PKG_DOWNLOAD_BASE_URL: &str =- "https://github.com/hairyf/deepseek-harness-pkg/releases/latest/download";--/// Proxy prefix used as a fallback for GitHub asset downloads.-pub const GH_PROXY_PREFIX: &str = "https://gh-proxy.com/";--/// Directory that holds the extracted harness package (under app data dir).-pub const DSH_CORE_DIR: &str = "dsh-core";--/// Relative path of the `dsh` CLI entry inside the harness package.-pub const DSH_ENTRY_RELATIVE: &str = "node_modules/@deepseek-ai/dsh/lib/bin.js";--/// Relative path of the harness package manifest inside the harness package.-pub const DSH_MANIFEST_RELATIVE: &str = "package.json";--/// Health-check timeouts for the harness web server.-pub const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(5);-pub const HEALTH_CHECK_RETRIES: usize = 3;-pub const HEALTH_CHECK_RETRY_DELAY: Duration = Duration::from_millis(500);--/// Build the health-check endpoints for a given port.-pub fn health_check_endpoints(port: u16) -> Vec<String> {- vec![- format!("http://127.0.0.1:{port}/"),- format!("http://localhost:{port}/"),- ]-}--/// Build the service URL (what the webview and user actions use).-pub fn service_url(port: u16) -> String {- format!("http://{}:{}", DSH_SERVICE_HOST, port)-}diff --git a/src-tauri/src/api/harness/error.rs b/src-tauri/src/api/harness/error.rsdeleted file mode 100644index 1e78c110..00000000--- a/src-tauri/src/api/harness/error.rs+++ /dev/null@@ -1,32 +0,0 @@-//! Error type for the harness module.--use thiserror::Error;--#[derive(Debug, Error)]-pub enum DshError {- #[error("{0}")]- Path(String),-- #[error("{0}")]- Config(String),-- #[error("{0}")]- Installation(String),-- #[error("{0}")]- Process(String),-- #[error("hash mismatch: expected {expected}, got {actual}")]- HashMismatch { expected: String, actual: String },-- #[error(transparent)]- Io(#[from] std::io::Error),-- #[error(transparent)]- Reqwest(#[from] reqwest::Error),-- #[error(transparent)]- Json(#[from] serde_json::Error),-}--pub type DshResult<T> = Result<T, DshError>;diff --git a/src-tauri/src/api/harness/installer.rs b/src-tauri/src/api/harness/installer.rsdeleted file mode 100644index beeeae6e..00000000--- a/src-tauri/src/api/harness/installer.rs+++ /dev/null@@ -1,287 +0,0 @@-//! Installer for the packaged DeepSeek Harness distribution.-//!-//! The packaged distribution is produced by the-//! `hairyf/deepseek-harness-pkg` repository and published as a GitHub release-//! with one zip per platform/architecture:-//!-//! ```text-//! dsh-core-<os>-<arch>.zip-//! ```-//!-//! The zip contains a single `dsh-core/` directory whose layout is documented-//! in `docs/PKG-CONTRACT.md` (entry CLI, `node_modules`, and a manifest-//! describing the exact `dsh` version and entry path).--use crate::i18n;-use serde::Deserialize;-use sha2::{Digest, Sha256};-use std::collections::HashMap;-use std::env;-use std::fs;-use std::io::{self, Read};-use std::path::{Path, PathBuf};-use tauri::{AppHandle, Manager, Runtime};-use zip::ZipArchive;--use super::constants::*;-use super::error::{DshError, DshResult};--/// Manifest of the packaged harness distribution (see `docs/PKG-CONTRACT.md`).-#[derive(Debug, Clone, Deserialize)]-pub struct DshManifest {- pub name: Option<String>,- pub version: Option<String>,- pub dependencies: Option<HashMap<String, String>>,- #[serde(rename = "dsh")]- pub dsh: Option<DshManifestSection>,-}--#[derive(Debug, Clone, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct DshManifestSection {- pub dsh_version: Option<String>,- pub node_min_version: Option<String>,- pub entry: Option<String>,- pub platform: Option<String>,- pub arch: Option<String>,-}--/// Metadata for one GitHub release asset.-#[derive(Debug, Clone)]-pub struct ReleaseAsset {- pub name: String,- /// `sha256:...` digest reported by the GitHub release.- pub digest: Option<String>,- pub browser_download_url: String,-}--/// Installs and validates the packaged harness into the app data directory.-pub struct DshInstaller {- platform: String,- arch: String,- app_data_dir: PathBuf,-}--impl DshInstaller {- pub fn new<R: Runtime>(app: &AppHandle<R>) -> DshResult<Self> {- let platform = match env::consts::OS {- "windows" => "windows",- "macos" => "macos",- "linux" => "linux",- other => return Err(DshError::Config(format!("unsupported OS: {other}"))),- };- let arch = match env::consts::ARCH {- "x86_64" => "x64",- "aarch64" => "arm64",- other => return Err(DshError::Config(format!("unsupported arch: {other}"))),- };- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| DshError::Path(e.to_string()))?;- Ok(Self { platform: platform.to_string(), arch: arch.to_string(), app_data_dir })- }-- pub fn asset_name(&self) -> String {- pkg_asset_name(&self.platform, &self.arch)- }-- pub fn zip_path(&self) -> PathBuf {- self.app_data_dir.join(self.asset_name())- }-- pub fn core_dir(&self) -> PathBuf {- self.app_data_dir.join(DSH_CORE_DIR)- }-- /// Candidate download URLs: direct GitHub release first, proxy fallback.- pub fn download_urls(&self) -> Vec<String> {- let direct = format!("{}/{}", PKG_DOWNLOAD_BASE_URL, self.asset_name());- vec![direct.clone(), format!("{GH_PROXY_PREFIX}{direct}")]- }-- /// The dsh CLI entry inside the extracted package.- pub fn entry_path(&self) -> PathBuf {- match self.read_manifest().ok().and_then(|m| m.dsh).and_then(|d| d.entry) {- Some(entry) if !entry.is_empty() => self.core_dir().join(entry),- _ => self.core_dir().join(DSH_ENTRY_RELATIVE),- }- }-- pub fn is_installed(&self) -> bool {- self.entry_path().exists()- }-- /// Read the harness manifest embedded in the extracted package.- pub fn read_manifest(&self) -> DshResult<DshManifest> {- let manifest_path = self.core_dir().join(DSH_MANIFEST_RELATIVE);- let content = fs::read_to_string(&manifest_path).map_err(|e| {- DshError::Config(format!("{}: {e}", i18n::t("harness.manifest_invalid")))- })?;- serde_json::from_str(&content)- .map_err(|e| DshError::Config(format!("{}: {e}", i18n::t("harness.manifest_invalid"))))- }-- /// Resolve the packaged dsh version (used by the UI).- pub fn dsh_version(&self) -> Option<String> {- let manifest = self.read_manifest().ok()?;- if let Some(version) = manifest.dsh.as_ref().and_then(|d| d.dsh_version.clone()) {- return Some(version);- }- manifest- .dependencies- .as_ref()- .and_then(|deps| deps.get("@deepseek-ai/dsh").cloned())- .map(|value| value.trim_start_matches(['^', '~', '=', '>', '<']).to_string())- }-- /// Minimum Node.js version required by the packaged harness.- pub fn node_min_version(&self) -> String {- self.read_manifest()- .ok()- .and_then(|m| m.dsh)- .and_then(|d| d.node_min_version)- .unwrap_or_else(|| MINIMUM_NODE_VERSION.to_string())- }-- /// Download the harness package zip (when needed, after hash verification).- pub async fn download_package<R: Runtime>(- &self,- tracker: &super::progress::ProgressTracker<'_, R>,- ) -> DshResult<()> {- println!("[dsh] installing harness package: {}", self.asset_name());-- let remote_sha = fetch_latest_asset(&self.platform, &self.arch).await?;- if self.should_download(remote_sha.as_deref())? {- let buffer = super::progress::tracked_download(tracker, &self.download_urls())- .await- .map_err(DshError::Installation)?;- if let Some(parent) = self.zip_path().parent() {- fs::create_dir_all(parent)?;- }- fs::write(&self.zip_path(), &buffer)?;- println!("[dsh] harness package downloaded: {} bytes", buffer.len());- }- Ok(())- }-- fn should_download(&self, remote_sha: Option<&str>) -> DshResult<bool> {- let path = self.zip_path();- if !path.exists() {- return Ok(true);- }- let Some(remote_hash) = remote_sha else {- // No remote hash available: trust the local zip.- return Ok(false);- };-- let local_hash = calculate_file_sha256(&path)?;- if local_hash == remote_hash {- println!("[dsh] local archive verified, skipping download");- Ok(false)- } else {- println!(- "[dsh] hash mismatch (local {local_hash} != remote {remote_hash}), re-downloading"- );- let _ = fs::remove_file(&path);- Ok(true)- }- }-- pub fn clean_and_extract(&self) -> DshResult<()> {- let final_dir = self.core_dir();- if final_dir.exists() {- fs::remove_dir_all(&final_dir)?;- }- fs::create_dir_all(&final_dir)?;- extract_zip_file(&self.zip_path(), &final_dir)?;- Ok(())- }-}--/// The release asset name for a platform/architecture pair.-pub fn pkg_asset_name(platform: &str, arch: &str) -> String {- let suffix = match (platform, arch) {- ("windows", _) => "windows".to_string(),- ("macos", "x86_64") => "macos-x64".to_string(),- ("macos", "aarch64") => "macos-arm64".to_string(),- ("linux", _) => "linux".to_string(),- _ => format!("{platform}-{arch}"),- };- format!("deepseek-harness-pkg-{suffix}.zip")-}--/// Fetch the release metadata for the packaged harness and find the asset that-/// matches the current platform/architecture.-pub async fn fetch_latest_asset(platform: &str, arch: &str) -> DshResult<Option<String>> {- let target = pkg_asset_name(platform, arch);- let client = reqwest::Client::new();- let response = client- .get(PKG_GITHUB_API_URL)- .header("User-Agent", PKG_GITHUB_USER_AGENT)- .header("Accept", "application/vnd.github.v3+json")- .send()- .await?;-- if !response.status().is_success() {- println!("[dsh] GitHub API returned {}; skipping hash verification", response.status());- return Ok(None);- }-- let json: serde_json::Value = response.json().await?;- let assets = json["assets"].as_array();- let Some(assets) = assets else {- return Ok(None);- };-- for asset in assets {- if asset["name"].as_str() == Some(target.as_str()) {- return Ok(asset["digest"].as_str().and_then(|d| d.strip_prefix("sha256:")).map(String::from));- }- }-- println!("[dsh] asset {target} not found in the release; skipping hash verification");- Ok(None)-}--/// Extract a zip archive safely (no path traversal).-fn extract_zip_file(archive_path: &Path, target_dir: &Path) -> DshResult<()> {- let file = fs::File::open(archive_path)?;- let mut archive = ZipArchive::new(file)- .map_err(|e| DshError::Installation(format!("invalid zip archive: {e}")))?;-- for i in 0..archive.len() {- let mut file = archive- .by_index(i)- .map_err(|e| DshError::Installation(format!("read zip entry failed: {e}")))?;- let outpath = match file.enclosed_name() {- Some(path) => target_dir.join(path),- None => continue,- };-- if file.is_dir() {- fs::create_dir_all(&outpath)?;- } else {- if let Some(p) = outpath.parent() {- fs::create_dir_all(p)?;- }- let mut outfile = fs::File::create(&outpath)?;- io::copy(&mut file, &mut outfile)?;- }- }- Ok(())-}--pub fn calculate_file_sha256(file_path: &Path) -> DshResult<String> {- let mut file = fs::File::open(file_path)?;- let mut hasher = Sha256::new();- let mut buffer = [0; 8192];- loop {- let bytes_read = file.read(&mut buffer)?;- if bytes_read == 0 {- break;- }- hasher.update(&buffer[..bytes_read]);- }- Ok(format!("{:x}", hasher.finalize()))-}diff --git a/src-tauri/src/api/harness/mod.rs b/src-tauri/src/api/harness/mod.rsdeleted file mode 100644index 8c159b6c..00000000--- a/src-tauri/src/api/harness/mod.rs+++ /dev/null@@ -1,201 +0,0 @@-//! Harness lifecycle: runtime setup, package install, launch, and shutdown.--pub mod constants;-pub mod error;-pub mod installer;-pub mod progress;-pub mod state;--pub use constants::*;-pub use error::{DshError, DshResult};-pub use installer::{DshInstaller, DshManifest, ReleaseAsset};-pub use progress::{ProgressPayload, ProgressTracker};-pub use state::{- construct_dsh_envs, runtime_info, AppConfig, DshHealthChecker, RuntimeInfo,-};--use crate::services::{downloader, manager};-use crate::i18n;-use std::fs;-use tauri::{AppHandle, Manager, Runtime, Window};--/// Check whether the harness package is already installed.-pub fn is_installed<R: Runtime>(app: &AppHandle<R>) -> bool {- DshInstaller::new(app).map(|i| i.is_installed()).unwrap_or(false)-}--/// Set up the bundled Node.js runtime (download + verify).-pub async fn setup_runtime<R: Runtime>(window: Window<R>) -> DshResult<()> {- let app_handle = window.app_handle();- let app_data_dir = app_handle- .path()- .app_data_dir()- .map_err(|e| DshError::Path(e.to_string()))?;- let runtime_dir = app_data_dir.join("runtime");-- let node_path = manager::get_node_binary_path(runtime_dir.clone());- let compatible = node_path.exists() && manager::is_runtime_compatible(&runtime_dir);- if compatible {- println!("[dsh] compatible Node runtime already present, skipping download");- return Ok(());- }-- if runtime_dir.exists() {- println!("[dsh] outdated runtime found, forcing reinstall");- let _ = fs::remove_dir_all(&runtime_dir);- }-- let urls = manager::get_node_download_urls().map_err(DshError::Installation)?;- let mut last_error: Option<String> = None;- for url in urls {- println!("[dsh] downloading Node runtime from {url}");- match downloader::download_file(window.clone(), vec![url.clone()], runtime_dir.clone(), "runtime").await {- Ok(()) => {- if manager::is_runtime_compatible(&runtime_dir) {- println!("[dsh] Node runtime ready");- return Ok(());- }- last_error = Some(i18n::t("runtime.incompatible"));- }- Err(err) => {- eprintln!("[dsh] runtime download failed ({url}): {err}");- last_error = Some(err);- }- }- }-- Err(DshError::Installation(last_error.unwrap_or_else(|| i18n::t("runtime.unsupported_platform"))))-}--/// Download and install the packaged harness distribution.-pub async fn setup_harness<R: Runtime>(window: Window<R>) -> DshResult<()> {- install_dependencies(window).await-}--/// One-shot install flow with phase-tracked progress, mirroring the reference-/// installer: 4 phases (download + extract for the Node runtime, download +-/// extract for the harness package). Already-installed phases are skipped.-pub async fn install_dependencies<R: Runtime>(window: Window<R>) -> DshResult<()> {- let app_handle = window.app_handle();- let app_data_dir = app_handle- .path()- .app_data_dir()- .map_err(|e| DshError::Path(e.to_string()))?;-- let mut tracker = ProgressTracker::new(&window, 4);-- // --- Phase 1+2: Node.js runtime -------------------------------------- let runtime_dir = app_data_dir.join("runtime");- let node_path = manager::get_node_binary_path(runtime_dir.clone());- if node_path.exists() && manager::is_runtime_compatible(&runtime_dir) {- println!("[install] Node runtime already compatible, skipping");- tracker.skip_phases(2);- } else {- if runtime_dir.exists() {- let _ = fs::remove_dir_all(&runtime_dir);- }-- tracker.start_phase(- "download",- &format!("{} {}", i18n::t("install.downloading"), i18n::t("runtime.title")),- );- let urls = manager::get_node_download_urls().map_err(DshError::Installation)?;- let buffer = progress::tracked_download(&tracker, &urls)- .await- .map_err(DshError::Installation)?;- tracker.end_phase();-- tracker.start_phase(- "extract",- &format!("{} {}", i18n::t("install.extracting"), i18n::t("runtime.title")),- );- downloader::extract_archive_to_dir(&buffer, &runtime_dir)- .map_err(DshError::Installation)?;- if !manager::is_runtime_compatible(&runtime_dir) {- return Err(DshError::Installation(i18n::t("runtime.incompatible")));- }- tracker.end_phase();- }-- // --- Phase 3+4: harness package --------------------------------------- let installer = DshInstaller::new(&app_handle)?;- if installer.is_installed() {- println!("[install] harness package already installed, skipping");- tracker.skip_phases(2);- } else {- tracker.start_phase(- "download",- &format!("{} {}", i18n::t("install.downloading"), i18n::t("harness.title")),- );- installer.download_package(&tracker).await?;- tracker.end_phase();-- tracker.start_phase(- "extract",- &format!("{} {}", i18n::t("install.extracting"), i18n::t("harness.title")),- );- installer.clean_and_extract()?;- if !installer.is_installed() {- return Err(DshError::Installation(i18n::t("harness.core_not_found")));- }- tracker.end_phase();- }-- tracker.update(100.0, i18n::t("install.done"), "install complete".to_string());- println!(- "[install] dependencies ready (dsh {})",- installer.dsh_version().unwrap_or_else(|| "?".into())- );- Ok(())-}--/// Launch the local `dsh web` service.-pub fn launch_harness<R: Runtime>(app: &AppHandle<R>) -> DshResult<()> {- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| DshError::Path(e.to_string()))?;- let installer = DshInstaller::new(app)?;-- let runtime_dir = app_data_dir.join("runtime");- let node_path = manager::get_node_binary_path(runtime_dir);- if !node_path.exists() {- return Err(DshError::Installation(i18n::t("runtime.not_found")));- }-- let entry_path = installer.entry_path();- if !entry_path.exists() {- return Err(DshError::Installation(i18n::t("harness.core_not_found")));- }-- let config = AppConfig::load(app);- let envs = construct_dsh_envs(app, config.port)?;- let log_path = app_data_dir.join("logs").join("dsh-web.log");- let core_dir = installer.core_dir();-- manager::start_dsh(- &node_path,- &entry_path,- &core_dir,- envs,- DSH_SERVICE_HOST,- config.port,- &log_path,- )- .map_err(DshError::Process)-}--/// Stop the running harness service.-pub fn shutdown_harness() -> DshResult<()> {- let mut process_manager = manager::PROCESS_MANAGER- .lock()- .map_err(|_| DshError::Process(i18n::t("process.manager_poisoned")))?;- process_manager.kill_child();- println!("[dsh] service stopped");- Ok(())-}--/// Health check through the Rust proxy (avoids webview CORS surprises).-pub async fn proxy_health_check(port: u16) -> DshResult<String> {- DshHealthChecker::check(port).await-}diff --git a/src-tauri/src/api/harness/progress.rs b/src-tauri/src/api/harness/progress.rsdeleted file mode 100644index 0ee38895..00000000--- a/src-tauri/src/api/harness/progress.rs+++ /dev/null@@ -1,171 +0,0 @@-//! Install progress tracking and streaming download, modeled on the early-//! n8n-based `hairyf/damn-reports` installer: one `install-progress` event-//! stream drives the download/install page in the frontend.--use futures_util::StreamExt;-use serde::Serialize;-use std::sync::Mutex;-use std::time::{Duration, Instant};-use tauri::{Emitter, Runtime, Window};--const USER_AGENT: &str =- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (deepseek-harness-desktop)";--/// Payload of the `install-progress` event consumed by the installer page.-#[derive(Clone, Serialize)]-#[serde(rename_all = "camelCase")]-pub struct ProgressPayload {- pub title: String,- pub detail: String,- pub log: String,- pub r#type: String,- /// Global progress across all install phases (0.0 - 100.0).- pub percentage: f64,- /// Progress of the current phase (0.0 - 100.0).- pub progress: f64,-}--/// Divides installation into phases (e.g. download + extract per component)-/// and reports global progress through `install-progress` events.-pub struct ProgressTracker<'a, R: Runtime> {- window: &'a Window<R>,- total_phases: usize,- current_phase: usize,- current_title: String,- current_type: String,- last_emit_time: Mutex<Option<Instant>>,-}--impl<'a, R: Runtime> ProgressTracker<'a, R> {- pub fn new(window: &'a Window<R>, total_phases: usize) -> Self {- Self {- window,- total_phases,- current_phase: 0,- current_title: String::from("preparing"),- current_type: String::new(),- last_emit_time: Mutex::new(None),- }- }-- /// Switch to a new phase and set its headline title.- pub fn start_phase(&mut self, r#type: &str, title: &str) {- self.current_title = title.to_string();- self.current_type = r#type.to_string();- }-- /// Mark the current phase as complete.- pub fn end_phase(&mut self) {- if self.current_phase < self.total_phases {- self.current_phase += 1;- }- }-- /// Skip a phase (used when a component is already installed).- pub fn skip_phases(&mut self, count: usize) {- self.current_phase = (self.current_phase + count).min(self.total_phases);- }-- /// `stage_pct`: progress of the current phase (0.0 - 100.0).- /// `detail`: main line shown under the title (e.g. "Downloaded 12.3 MB / 51.5 MB").- /// `log`: one line appended to the terminal-style log panel.- pub fn update(&self, stage_pct: f64, detail: String, log: String) {- let now = Instant::now();- let mut last_emit = match self.last_emit_time.lock() {- Ok(guard) => guard,- Err(_) => return,- };- if let Some(last_time) = *last_emit {- if now.duration_since(last_time) < Duration::from_millis(50) {- return;- }- }- *last_emit = Some(now);-- let phase_weight = 100.0 / self.total_phases.max(1) as f64;- let global_pct =- (self.current_phase as f64 * phase_weight) + (stage_pct * phase_weight / 100.0);-- let _ = self.window.emit(- "install-progress",- ProgressPayload {- title: self.current_title.clone(),- r#type: self.current_type.clone(),- percentage: global_pct.min(100.0),- progress: stage_pct.min(100.0),- detail,- log,- },- );- }-}--/// Stream a download from the first URL that succeeds, reporting progress.-pub async fn tracked_download<R: Runtime>(- tracker: &ProgressTracker<'_, R>,- urls: &[String],-) -> Result<Vec<u8>, String> {- if urls.is_empty() {- return Err("download: empty URL list".to_string());- }-- let client = reqwest::Client::builder()- .user_agent(USER_AGENT)- .connect_timeout(Duration::from_secs(20))- .build()- .map_err(|e| format!("create HTTP client failed: {e}"))?;-- let mut last_error: Option<String> = None;- for url in urls {- match download_one(tracker, &client, url).await {- Ok(bytes) => return Ok(bytes),- Err(err) => {- eprintln!("[install] download failed ({url}): {err}");- last_error = Some(err);- }- }- }- Err(last_error.unwrap_or_else(|| "download failed".to_string()))-}--async fn download_one<R: Runtime>(- tracker: &ProgressTracker<'_, R>,- client: &reqwest::Client,- url: &str,-) -> Result<Vec<u8>, String> {- let response = client- .get(url)- .send()- .await- .map_err(|e| format!("HTTP request failed '{url}': {e}"))?;- if !response.status().is_success() {- return Err(format!("download failed: HTTP {} for '{url}'", response.status()));- }-- let total_size = response.content_length().unwrap_or(0);- let mut stream = response.bytes_stream();- let mut buffer = Vec::new();- let mut downloaded: u64 = 0;-- while let Some(chunk_result) = stream.next().await {- let chunk = chunk_result.map_err(|e| format!("download stream error: {e}"))?;- buffer.extend_from_slice(&chunk);- downloaded += chunk.len() as u64;-- if total_size > 0 {- let pct = (downloaded as f64 / total_size as f64) * 100.0;- tracker.update(- pct,- format!(- "{} {:.1} MB / {:.1} MB",- crate::i18n::t("install.downloaded"),- downloaded as f64 / 1_000_000.0,- total_size as f64 / 1_000_000.0- ),- format!("Download {url}"),- );- }- }-- Ok(buffer)-}diff --git a/src-tauri/src/api/harness/state.rs b/src-tauri/src/api/harness/state.rsdeleted file mode 100644index 166089fa..00000000--- a/src-tauri/src/api/harness/state.rs+++ /dev/null@@ -1,141 +0,0 @@-//! Env construction, health checks, desktop settings, and runtime info.--use crate::i18n;-use serde::{Deserialize, Serialize};-use std::collections::HashMap;-use std::fs;-use std::path::PathBuf;-use tauri::{AppHandle, Manager, Runtime};--use super::constants::*;-use super::error::{DshError, DshResult};-use super::installer::DshInstaller;--/// Persistent desktop settings.-#[derive(Debug, Clone, Serialize, Deserialize)]-#[serde(default)]-pub struct AppConfig {- pub port: u16,- pub auto_start: bool,-}--impl Default for AppConfig {- fn default() -> Self {- Self {- port: DSH_SERVICE_PORT.parse().unwrap_or(3080),- auto_start: true,- }- }-}--impl AppConfig {- fn path(app_data_dir: &PathBuf) -> PathBuf {- app_data_dir.join("config").join("config.json")- }-- pub fn load<R: Runtime>(app: &AppHandle<R>) -> AppConfig {- let path = Self::path(&app.path().app_data_dir().unwrap_or_default());- fs::read_to_string(&path)- .ok()- .and_then(|content| serde_json::from_str(&content).ok())- .unwrap_or_default()- }-- pub fn save<R: Runtime>(&self, app: &AppHandle<R>) -> DshResult<()> {- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| DshError::Path(e.to_string()))?;- let path = Self::path(&app_data_dir);- if let Some(parent) = path.parent() {- fs::create_dir_all(parent)?;- }- let content = serde_json::to_string_pretty(self)?;- fs::write(&path, content)?;- Ok(())- }-}--/// Environment variables passed to the `dsh web` process.-pub fn construct_dsh_envs<R: Runtime>(- app: &AppHandle<R>,- port: u16,-) -> DshResult<HashMap<String, String>> {- let app_data_dir = app- .path()- .app_data_dir()- .map_err(|e| DshError::Path(e.to_string()))?;- let dsh_home = app_data_dir.join(DSH_HOME_DIR_NAME);- fs::create_dir_all(&dsh_home)?;-- let mut envs = HashMap::new();- // Isolate all harness user data inside the desktop app data directory.- envs.insert("DSH_HOME".to_string(), dsh_home.to_string_lossy().into_owned());- // Privacy default: disable telemetry unless the user opts in.- envs.insert("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string());- envs.insert("NO_COLOR".to_string(), "1".to_string());- // Port is passed as a CLI flag in manager::start_dsh; keep it here for parity.- envs.insert("DSH_WEB_PORT".to_string(), port.to_string());- Ok(envs)-}--/// Health check for the harness web server.-pub struct DshHealthChecker;--impl DshHealthChecker {- pub async fn check(port: u16) -> DshResult<String> {- let client = reqwest::Client::builder()- .timeout(HEALTH_CHECK_TIMEOUT)- .build()?;-- for endpoint in health_check_endpoints(port) {- match client.get(&endpoint).send().await {- Ok(response) => {- let status = response.status();- let body = response.text().await.unwrap_or_default();- if status.is_success() {- return Ok(format!("healthy - {status} - {}", body.chars().take(80).collect::<String>()));- }- }- Err(err) => {- eprintln!("[dsh] health check {endpoint}: {err}");- }- }- }- Err(DshError::Process(i18n::t("harness.health_unhealthy")))- }-}--/// Version/diagnostic info surfaced in the sidebar.-#[derive(Debug, Clone, Serialize)]-pub struct RuntimeInfo {- pub app_version: String,- pub dsh_version: Option<String>,- pub node_version: String,- pub service_url: String,- pub data_dir: String,- pub log_path: String,- pub platform: String,- pub arch: String,-}--pub fn runtime_info<R: Runtime>(app: &AppHandle<R>, config: &AppConfig) -> RuntimeInfo {- let app_data_dir = app- .path()- .app_data_dir()- .map(|p| p.to_string_lossy().into_owned())- .unwrap_or_default();- let installer = DshInstaller::new(app).ok();- let node_version = crate::services::manager::get_bundled_node_version();-- RuntimeInfo {- app_version: app.package_info().version.to_string(),- dsh_version: installer.as_ref().and_then(|i| i.dsh_version()),- node_version,- service_url: service_url(config.port),- data_dir: app_data_dir.clone(),- log_path: PathBuf::from(&app_data_dir).join("logs").join("dsh-web.log").to_string_lossy().into_owned(),- platform: std::env::consts::OS.to_string(),- arch: std::env::consts::ARCH.to_string(),- }-}diff --git a/src-tauri/src/api/mod.rs b/src-tauri/src/api/mod.rsdeleted file mode 100644index aa1dc517..00000000--- a/src-tauri/src/api/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod commands;-pub mod harness;-pub mod utils;--pub use harness::{DshError, DshResult};diff --git a/src-tauri/src/api/utils.rs b/src-tauri/src/api/utils.rsdeleted file mode 100644index d8e4f1be..00000000--- a/src-tauri/src/api/utils.rs+++ /dev/null@@ -1,9 +0,0 @@-//! Small shared helpers for the API layer.--use crate::api::harness::AppConfig;-use tauri::{AppHandle, Runtime};--/// Resolve the currently configured service port.-pub fn active_port<R: Runtime>(app: &AppHandle<R>) -> u16 {- AppConfig::load(app).port-}diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rsnew file mode 100644index 00000000..baf6ef97--- /dev/null+++ b/src-tauri/src/bridge/cmd.rs@@ -0,0 +1,182 @@+use crate::config;+use crate::service::workflow;+use tauri::{AppHandle, Manager};+use tauri_plugin_clipboard_manager::ClipboardExt;+use tauri_plugin_opener::OpenerExt;++/// 一键安装依赖(Node.js 运行时 + 打包的 Harness 发行版)+///+/// 启动逻辑由前端显式调用 `launch_harness` 完成,避免重复拉起进程。+#[tauri::command]+pub async fn install_dependencies(app_handle: AppHandle) -> Result<(), String> {+ let mut setting = config::get_store_dat_setting(&app_handle);+ if setting.installed {+ log::debug!("Already installed, skipping installation");+ return Ok(());+ }+ if workflow::status::get_status() == workflow::status::Status::Installing {+ log::info!("Installation process already running, skipping");+ return Ok(());+ }+ log::debug!("Not installed detected, starting installation process");+ workflow::status::set_status(workflow::status::Status::Installing);+ workflow::status::emit_status(&app_handle);+ workflow::install(&app_handle).await?;+ log::debug!("Installation completed, marked as installed");+ setting.installed = true;+ config::set_store_dat_setting(&app_handle, setting);+ Ok(())+}++/// 启动 Harness 服务+#[tauri::command]+pub async fn launch_harness(app_handle: AppHandle) -> Result<(), String> {+ workflow::launch(app_handle).await+}++/// 停止 Harness 服务+#[tauri::command]+pub async fn shutdown_harness(app_handle: AppHandle) -> Result<(), String> {+ workflow::stop(app_handle).await+}++/// 重启 Harness 服务+#[tauri::command]+pub async fn restart_harness(app_handle: AppHandle) -> Result<(), String> {+ workflow::restart(app_handle).await+}++/// 获取当前 Harness 服务状态+#[tauri::command]+pub fn get_dsh_status() -> workflow::status::Status {+ workflow::status::get_status()+}++/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)+#[tauri::command]+pub async fn proxy_health_check(app_handle: AppHandle) -> Result<String, String> {+ let port = config::get_store_dat_setting(&app_handle).port;+ workflow::proxy_health_check(port).await+}++/// 运行时/版本/诊断信息(侧边栏展示)+#[tauri::command]+pub async fn get_runtime_info(app_handle: AppHandle) -> Result<config::RuntimeInfo, String> {+ let port = config::get_store_dat_setting(&app_handle).port;+ Ok(config::runtime_info(&app_handle, port))+}++/// 当前桌面端配置+#[tauri::command]+pub async fn get_app_config(app_handle: AppHandle) -> Result<config::Setting, String> {+ Ok(config::get_store_dat_setting(&app_handle))+}++/// 更新桌面端配置+#[tauri::command]+pub async fn update_app_config(+ app_handle: AppHandle,+ port: Option<u16>,+ auto_start: Option<bool>,+) -> Result<config::Setting, String> {+ let mut setting = config::get_store_dat_setting(&app_handle);+ if let Some(port) = port {+ if port == 0 {+ return Err("port must be a positive number".to_string());+ }+ setting.port = port;+ }+ if let Some(auto_start) = auto_start {+ setting.auto_start = auto_start;+ }+ config::set_store_dat_setting(&app_handle, setting.clone());+ Ok(setting)+}++/// 在系统浏览器中打开 Harness 界面+#[tauri::command]+pub async fn open_in_browser(app_handle: AppHandle) -> Result<(), String> {+ let url = config::get_dsh_service_url(config::get_store_dat_setting(&app_handle).port);+ app_handle+ .opener()+ .open_url(url, None::<&str>)+ .map_err(|e| e.to_string())+}++/// 复制 Harness 服务地址到剪贴板+#[tauri::command]+pub async fn copy_service_url(app_handle: AppHandle) -> Result<(), String> {+ let url = config::get_dsh_service_url(config::get_store_dat_setting(&app_handle).port);+ app_handle+ .clipboard()+ .write_text(url)+ .map_err(|e| e.to_string())+}++/// 在系统文件管理器中打开数据目录+#[tauri::command]+pub async fn reveal_data_dir(app_handle: AppHandle) -> Result<(), String> {+ let app_data_dir = app_handle+ .path()+ .app_data_dir()+ .map_err(|e| e.to_string())?;++ if cfg!(windows) {+ std::process::Command::new("explorer")+ .arg(&app_data_dir)+ .spawn()+ .map_err(|e| e.to_string())?;+ } else if cfg!(target_os = "macos") {+ std::process::Command::new("open")+ .arg(&app_data_dir)+ .spawn()+ .map_err(|e| e.to_string())?;+ } else {+ std::process::Command::new("xdg-open")+ .arg(&app_data_dir)+ .spawn()+ .map_err(|e| e.to_string())?;+ }+ Ok(())+}++/// 读取 dsh 服务日志+#[tauri::command]+pub async fn read_service_logs(+ app_handle: AppHandle,+ max_bytes: Option<usize>,+) -> Result<String, String> {+ let log_path = config::get_service_log_path(&app_handle);+ if !log_path.exists() {+ return Ok(String::new());+ }++ let content = std::fs::read_to_string(&log_path).map_err(|e| e.to_string())?;+ let max_bytes = max_bytes.unwrap_or(64 * 1024);+ if content.len() <= max_bytes {+ Ok(content)+ } else {+ Ok(content[content.len() - max_bytes..].to_string())+ }+}++/// 清空 dsh 服务日志+#[tauri::command]+pub async fn clear_service_logs(app_handle: AppHandle) -> Result<(), String> {+ let log_path = config::get_service_log_path(&app_handle);+ std::fs::write(&log_path, "").map_err(|e| e.to_string())+}++/// 保存界面语言偏好+#[tauri::command]+pub fn set_language(app_handle: AppHandle, lang: String) {+ let mut setting = config::get_store_dat_setting(&app_handle);+ setting.language = lang;+ config::set_store_dat_setting(&app_handle, setting);+}++/// 切换侧边栏(布局状态保存在前端,保留该命令以对齐参考实现)+#[tauri::command]+pub async fn toggle_sidebar() -> Result<bool, String> {+ Ok(true)+}diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rsnew file mode 100644index 00000000..52958ec9--- /dev/null+++ b/src-tauri/src/bridge/mod.rs@@ -0,0 +1 @@+pub mod cmd;diff --git a/src-tauri/src/config/constants.rs b/src-tauri/src/config/constants.rsnew file mode 100644index 00000000..ec7049a7--- /dev/null+++ b/src-tauri/src/config/constants.rs@@ -0,0 +1,37 @@+use std::time::Duration;++/// 捆绑的 Node.js 运行时版本(满足 v22.15.0+ / v23.8.0+ 的要求)+pub const NODE_VERSION: &str = "v22.22.0";+/// 打包的 Harness 要求的最低 Node.js 版本+pub const MINIMUM_NODE_VERSION: &str = "22.15.0";++/// Node.js 官方下载地址+pub const NODE_BASE_URL: &str = "https://nodejs.org/dist/";+/// npmmirror 镜像(备用下载源)+pub const NODE_NPMMIRROR_URL: &str = "https://npmmirror.com/mirrors/node/";++/// GitHub 下载代理前缀(备用下载源)+pub const GITHUB_PROXY_PREFIX: &str = "https://gh-proxy.com/";++/// 打包的 DeepSeek Harness 发行版下载地址(GitHub Release)+pub const DSH_CORE_URL: &str =+ "https://github.com/hairyf/deepseek-harness-pkg/releases/latest/download/";++/// Harness 服务地址与默认端口+pub const DSH_HOST: &str = "http://127.0.0.1";+pub const DSH_PORT: u16 = 3080;++/// 安装目录与 CLI 入口(相对安装目录)+pub const DSH_CORE_DIR: &str = "dsh";+pub const DSH_ENTRY_RELATIVE: &str = "node_modules/@deepseek-ai/dsh/lib/bin.js";+pub const DSH_MANIFEST_RELATIVE: &str = "package.json";++/// 数据目录名($DSH_HOME 的相对目录)+pub const DSH_DATA_DIR_NAME: &str = "dsh";++/// 简单 Store 持久化+pub const STORE_DAT_FILE: &str = ".store.dat";+pub const STORE_SETTING_KEY: &str = "setting";++/// 健康检查超时+pub const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(5);diff --git a/src-tauri/src/config/format.rs b/src-tauri/src/config/format.rsnew file mode 100644index 00000000..c44c5a92--- /dev/null+++ b/src-tauri/src/config/format.rs@@ -0,0 +1,11 @@+use crate::config::{DSH_HOST, DSH_PORT};++/// 获取 Harness 服务基础地址+pub fn get_dsh_base_url() -> String {+ format!("{}:{}", DSH_HOST, DSH_PORT)+}++/// 获取指定端口的 Harness 服务地址+pub fn get_dsh_service_url(port: u16) -> String {+ format!("{}:{}", DSH_HOST, port)+}diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rsnew file mode 100644index 00000000..b9ba1276--- /dev/null+++ b/src-tauri/src/config/mod.rs@@ -0,0 +1,10 @@+mod constants;+mod format;+mod runtime;+mod setting;+mod utils;++pub use constants::*;+pub use format::*;+pub use runtime::*;+pub use setting::*;diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rsnew file mode 100644index 00000000..e1187ecd--- /dev/null+++ b/src-tauri/src/config/runtime.rs@@ -0,0 +1,189 @@+use serde::Serialize;+use std::env;+use std::fs;+use std::path::PathBuf;+use tauri::{AppHandle, Manager, Runtime};++use super::constants::*;+use super::format::get_dsh_service_url;+use super::utils::search_node_binary;++/// 获取 App Data 基础目录+fn get_base_dir<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {+ app_handle+ .path()+ .app_data_dir()+ .expect("Failed to resolve app data directory")+}++/// Node.js 运行时下载地址+pub fn get_node_download_url() -> Result<String, String> {+ let arch = env::consts::ARCH;+ let os = env::consts::OS;++ // 抽象文件名逻辑+ let filename = match (os, arch) {+ ("macos", "aarch64") => format!("node-{}-darwin-arm64.tar.gz", NODE_VERSION),+ ("macos", "x86_64") => format!("node-{}-darwin-x64.tar.gz", NODE_VERSION),+ ("windows", _) => format!("node-{}-win-x64.zip", NODE_VERSION),+ _ => return Err(format!("Unsupported platform: {} {}", os, arch)),+ };++ Ok(format!("{}/{}/{}", NODE_BASE_URL, NODE_VERSION, filename))+}++/// 打包的 DeepSeek Harness 发行版下载地址+pub fn get_dsh_download_url() -> Result<String, String> {+ let arch = env::consts::ARCH;+ let os = env::consts::OS;++ // 根据平台和架构生成文件名+ let filename = match (os, arch) {+ ("windows", _) => "deepseek-harness-pkg-windows.zip".to_string(),+ ("macos", "aarch64") => "deepseek-harness-pkg-macos-arm64.zip".to_string(),+ ("macos", "x86_64") => "deepseek-harness-pkg-macos-x64.zip".to_string(),+ ("linux", _) => "deepseek-harness-pkg-linux.zip".to_string(),+ _ => return Err(format!("Unsupported platform: {} {}", os, arch)),+ };++ Ok(format!("{}{}", DSH_CORE_URL, filename))+}++/// Node.js 二进制路径(安装后)+pub fn get_node_binary_path(app_handle: &tauri::AppHandle) -> PathBuf {+ let runtime_dir = get_node_install_path(app_handle);+ // 使用 cfg 宏在编译时确定文件名+ let (rel_path, bin_name) = if cfg!(windows) {+ ("", "node.exe")+ } else {+ ("bin", "node")+ };+ let direct_path = runtime_dir.join(rel_path).join(bin_name);+ if direct_path.exists() {+ direct_path+ } else {+ // 只有在直接路径不存在时才进行开销较大的递归搜索+ search_node_binary(&runtime_dir, bin_name).unwrap_or(direct_path)+ }+}++pub fn get_node_install_path(app_handle: &tauri::AppHandle) -> PathBuf {+ get_base_dir(app_handle).join("runtime")+}++/// Harness 发行版安装目录+pub fn get_dsh_install_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {+ get_base_dir(app_handle).join("dependencies").join(DSH_CORE_DIR)+}++/// dsh CLI 入口+pub fn get_dsh_binary_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {+ get_dsh_install_path(app_handle).join(DSH_ENTRY_RELATIVE)+}++/// Harness 发行版清单路径+pub fn get_dsh_package_json_path<R: Runtime>(app_handle: &AppHandle<R>) -> PathBuf {+ get_dsh_install_path(app_handle).join(DSH_MANIFEST_RELATIVE)+}++/// Harness 用户数据目录($DSH_HOME)+pub fn get_dsh_data_path(app_handle: &tauri::AppHandle) -> PathBuf {+ get_base_dir(app_handle).join("data").join(DSH_DATA_DIR_NAME)+}++/// dsh 服务日志文件路径+pub fn get_service_log_path(app_handle: &tauri::AppHandle) -> PathBuf {+ get_base_dir(app_handle).join("logs").join("dsh-web.log")+}++/// 捆绑的 Node.js 版本号+pub fn get_bundled_node_version() -> String {+ NODE_VERSION.trim_start_matches('v').to_string()+}++fn parse_node_version(output: &str) -> Option<(u64, u64, u64)> {+ let version = output.trim().trim_start_matches('v');+ let mut parts = version.split('.');+ let major = parts.next()?.parse().ok()?;+ let minor = parts.next()?.parse().ok()?;+ let patch = parts.next()?.parse().ok()?;+ Some((major, minor, patch))+}++/// 兼容性规则:v22.15.0+ 或 v23.8.0+(v24+ 也满足)+fn is_supported_node_version(version: &str) -> bool {+ let Some((major, minor, _patch)) = parse_node_version(version) else {+ return false;+ };+ match major {+ 22 => minor >= 15,+ 23 => minor >= 8,+ major if major >= 24 => true,+ _ => false,+ }+}++/// 运行 `node --version` 并判断运行时是否兼容+pub fn is_runtime_compatible(app_handle: &tauri::AppHandle) -> bool {+ let node = get_node_binary_path(app_handle);+ if !node.exists() {+ return false;+ }+ let output = match std::process::Command::new(&node).arg("--version").output() {+ Ok(out) => out,+ Err(_) => return false,+ };+ if !output.status.success() {+ return false;+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ is_supported_node_version(stdout.trim())+}++/// 从打包的 Harness 清单读取 dsh 版本(界面展示用)+pub fn get_dsh_version<R: Runtime>(app_handle: &AppHandle<R>) -> Option<String> {+ let manifest_path = get_dsh_package_json_path(app_handle);+ let content = fs::read_to_string(&manifest_path).ok()?;+ let manifest: serde_json::Value = serde_json::from_str(&content).ok()?;+ manifest+ .get("dependencies")+ .and_then(|deps| deps.get("@deepseek-ai/dsh"))+ .and_then(|value| value.as_str())+ .map(|value| value.trim_start_matches(['^', '~', '=', '>', '<']).to_string())+}++/// 侧边栏展示的运行时/版本/诊断信息+#[derive(Debug, Clone, Serialize)]+pub struct RuntimeInfo {+ pub app_version: String,+ pub dsh_version: Option<String>,+ pub node_version: String,+ pub service_url: String,+ pub data_dir: String,+ pub log_path: String,+ pub platform: String,+ pub arch: String,+}++pub fn runtime_info<R: Runtime>(app: &AppHandle<R>, port: u16) -> RuntimeInfo {+ let app_data_dir = app+ .path()+ .app_data_dir()+ .map(|p| p.to_string_lossy().into_owned())+ .unwrap_or_default();++ RuntimeInfo {+ app_version: app.package_info().version.to_string(),+ dsh_version: get_dsh_version(app),+ node_version: get_bundled_node_version(),+ service_url: get_dsh_service_url(port),+ data_dir: app_data_dir.clone(),+ log_path: PathBuf::from(&app_data_dir)+ .join("logs")+ .join("dsh-web.log")+ .to_string_lossy()+ .into_owned(),+ platform: env::consts::OS.to_string(),+ arch: env::consts::ARCH.to_string(),+ }+}diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rsnew file mode 100644index 00000000..0f8a0ca2--- /dev/null+++ b/src-tauri/src/config/setting.rs@@ -0,0 +1,50 @@+use super::constants::*;+use serde::{Deserialize, Serialize};+use tauri::{AppHandle, Emitter};+use tauri_plugin_store::StoreExt;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub struct Setting {+ pub installed: bool,+ pub port: u16,+ pub auto_start: bool,+ pub language: String,+}++impl Default for Setting {+ fn default() -> Self {+ Self {+ installed: false,+ port: DSH_PORT,+ auto_start: true,+ language: "zh-CN".to_string(),+ }+ }+}++pub fn set_store_dat_setting(app_handle: &AppHandle, setting: Setting) {+ let store = app_handle+ .store(STORE_DAT_FILE)+ .expect("Failed to load store");+ store.set(STORE_SETTING_KEY, serde_json::to_value(&setting).unwrap());+ store.save().expect("Failed to save store");+ app_handle+ .emit("setting_updated", &serde_json::to_value(&setting).unwrap())+ .expect("Failed to emit event");+}++pub fn get_store_dat_setting(app_handle: &AppHandle) -> Setting {+ let store = app_handle+ .store(STORE_DAT_FILE)+ .expect("Failed to load store");+ let raw = store.get(STORE_SETTING_KEY);+ let value = raw.as_ref().and_then(|v| {+ v.as_str()+ .and_then(|s| serde_json::from_str(s).ok())+ .or_else(|| Some(v.clone()))+ });+ value+ .and_then(|v| serde_json::from_value(v).ok())+ .unwrap_or_else(Setting::default)+}diff --git a/src-tauri/src/config/utils.rs b/src-tauri/src/config/utils.rsnew file mode 100644index 00000000..e8264ce8--- /dev/null+++ b/src-tauri/src/config/utils.rs@@ -0,0 +1,31 @@+use std::path::PathBuf;++/// 递归搜索 node 二进制文件+pub fn search_node_binary(dir: &PathBuf, target: &str) -> Option<PathBuf> {+ use std::fs;++ if let Ok(entries) = fs::read_dir(dir) {+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ // 递归搜索子目录+ if let Some(found) = search_node_binary(&path, target) {+ return Some(found);+ }+ } else if path.file_name().and_then(|n| n.to_str()) == Some("node")+ || path.file_name().and_then(|n| n.to_str()) == Some("node.exe")+ {+ // 找到 node 或 node.exe 文件+ return Some(path);+ }+ }+ }++ // 如果没找到,尝试拼接目标路径+ let candidate = dir.join(target);+ if candidate.exists() {+ return Some(candidate);+ }++ None+}diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rsnew file mode 100644index 00000000..b5614dd8--- /dev/null+++ b/src-tauri/src/core/mod.rs@@ -0,0 +1 @@+pub mod utils;diff --git a/src-tauri/src/core/utils/mod.rs b/src-tauri/src/core/utils/mod.rsnew file mode 100644index 00000000..72fbcb8d--- /dev/null+++ b/src-tauri/src/core/utils/mod.rs@@ -0,0 +1,11 @@+use tauri::{Runtime, WebviewWindow};++pub fn show_window<R: Runtime>(window: &WebviewWindow<R>) {+ let _ = window.unminimize();+ let _ = window.show();+ let _ = window.set_focus();+}++pub fn navigate<R: Runtime>(window: &WebviewWindow<R>, path: &str) {+ let _ = window.eval(&format!("window.location.href = '{}'", path));+}diff --git a/src-tauri/src/i18n.rs b/src-tauri/src/i18n.rsdeleted file mode 100644index 60e3b397..00000000--- a/src-tauri/src/i18n.rs+++ /dev/null@@ -1,59 +0,0 @@-//! Minimal backend i18n for user-facing errors.-//!-//! The frontend owns the rich UI language state; the backend only needs a few-//! translated strings for errors that may surface in logs or returned messages.--use std::sync::atomic::{AtomicU8, Ordering};--#[derive(Clone, Copy, PartialEq, Eq)]-pub enum Lang {- Zh,- En,-}--static CURRENT_LANG: AtomicU8 = AtomicU8::new(0); // 0 = zh, 1 = en--pub fn set_language(lang: Lang) {- CURRENT_LANG.store(match lang {- Lang::Zh => 0,- Lang::En => 1,- }, Ordering::SeqCst);-}--fn lang() -> Lang {- if CURRENT_LANG.load(Ordering::SeqCst) == 1 {- Lang::En- } else {- Lang::Zh- }-}--/// Look up a translation key. Keys are grouped by domain with `_` separators.-pub fn t(key: &str) -> String {- let (zh, en): (&str, &str) = match key {- "runtime.unsupported_platform" => ("不支持当前平台/架构", "Unsupported platform/architecture"),- "runtime.title" => ("Node.js 运行时", "Node.js runtime"),- "runtime.not_found" => ("Node.js 运行时不存在,请先完成安装", "Node.js runtime not found, run setup first"),- "runtime.incompatible" => ("Node.js 运行时版本过低,需要 v22.15.0+ 或 v23.8.0+", "Node.js runtime is too old, need v22.15.0+ or v23.8.0+"),- "harness.title" => ("DeepSeek Harness 核心", "DeepSeek Harness core"),- "harness.core_not_found" => ("未找到 DeepSeek Harness 核心包,请先完成安装", "DeepSeek Harness core package not found, run setup first"),- "harness.manifest_invalid" => ("Harness 包清单无效", "Invalid harness package manifest"),- "harness.asset_not_found" => ("发布资源中未找到匹配的平台包", "No matching platform asset found in the release"),- "harness.hash_mismatch" => ("下载文件哈希校验失败", "Downloaded file hash verification failed"),- "harness.start_failed" => ("启动 DeepSeek Harness 服务失败", "Failed to start DeepSeek Harness service"),- "harness.health_unhealthy" => ("DeepSeek Harness 服务未就绪", "DeepSeek Harness service is not ready"),- "process.manager_poisoned" => ("进程管理器状态异常", "Process manager state is corrupted"),- "config.load_failed" => ("读取配置失败", "Failed to load configuration"),- "config.save_failed" => ("保存配置失败", "Failed to save configuration"),- "download.failed" => ("下载失败", "Download failed"),- "install.downloading" => ("正在下载", "Downloading"),- "install.extracting" => ("正在解压", "Extracting"),- "install.downloaded" => ("已下载", "Downloaded"),- "install.done" => ("依赖已安装完毕", "Dependencies installed"),- _ => (key, key),- };- match lang() {- Lang::Zh => zh.to_string(),- Lang::En => en.to_string(),- }-}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex b4f1ce64..8c8d849b 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1,46 +1,139 @@-pub mod api;-pub mod i18n;-pub mod services;+mod bridge;+mod config;+mod core;+mod logger;+mod service;+mod task;-use tauri::RunEvent;+use core::utils::show_window;+use tauri::{+ ipc::Invoke,+ menu::{Menu, MenuEvent, MenuItem},+ tray::{MouseButton, TrayIconBuilder, TrayIconEvent},+ Manager, Runtime, Wry,+};-#[cfg_attr(mobile, tauri::mobile_entry_point)]-pub fn run() {- let builder = tauri::Builder::default()+// setup app+fn setup(app_handle: tauri::AppHandle) {+ // 启动进程监控(tick 检测 dsh 服务状态)+ service::scheduler::start(&app_handle);++ // 开机自启动:已安装且开启 auto_start 时拉起服务+ tauri::async_runtime::spawn(async move {+ let setting = config::get_store_dat_setting(&app_handle);+ if !setting.auto_start {+ log::debug!("auto_start disabled, skipping startup");+ return;+ }+ if let Err(e) = service::workflow::start(app_handle).await {+ log::error!("start 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();+ match event {+ TrayIconEvent::Click {+ button: MouseButton::Left,+ ..+ } => {+ 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::launch_harness,+ bridge::cmd::shutdown_harness,+ bridge::cmd::restart_harness,+ bridge::cmd::get_dsh_status,+ bridge::cmd::proxy_health_check,+ bridge::cmd::get_runtime_info,+ bridge::cmd::get_app_config,+ bridge::cmd::update_app_config,+ bridge::cmd::open_in_browser,+ bridge::cmd::copy_service_url,+ bridge::cmd::reveal_data_dir,+ bridge::cmd::read_service_logs,+ bridge::cmd::clear_service_logs,+ bridge::cmd::set_language,+ bridge::cmd::toggle_sidebar,+ ]+}++// configure tauri builder+fn builder() -> tauri::Builder<tauri::Wry> {+ tauri::Builder::default()+ // 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())- .invoke_handler(tauri::generate_handler![- api::commands::is_installed,- api::commands::setup_runtime,- api::commands::install_dependencies,- api::commands::setup_harness,- api::commands::launch_harness,- api::commands::shutdown_harness,- api::commands::proxy_health_check,- api::commands::get_runtime_info,- api::commands::get_app_config,- api::commands::update_app_config,- api::commands::open_in_browser,- api::commands::copy_service_url,- api::commands::reveal_data_dir,- api::commands::read_service_logs,- api::commands::clear_service_logs,- api::commands::set_language,- api::commands::toggle_sidebar,- ]);-- builder- .build(tauri::generate_context!())- .expect("error while running tauri application")- .run(|_app, event| handle_app_run_event(event));}-fn handle_app_run_event(event: RunEvent) {- if let RunEvent::ExitRequested { .. } = event {- if let Err(err) = api::harness::shutdown_harness() {- eprintln!("[dsh] failed to stop harness on exit: {err}");- }- println!("[dsh] application exiting, harness stopped");- }+// run app+pub fn run() {+ // 初始化日志系统+ logger::init();++ builder()+ .setup(|app| {+ tray(&app.handle()).unwrap();+ setup(app.handle().clone());+ Ok(())+ })+ .invoke_handler(handler())+ .run(tauri::generate_context!())+ .expect("error while running tauri application");}diff --git a/src-tauri/src/logger/mod.rs b/src-tauri/src/logger/mod.rsnew file mode 100644index 00000000..54f2eb3d--- /dev/null+++ b/src-tauri/src/logger/mod.rs@@ -0,0 +1,86 @@+use log::{Level, LevelFilter, Metadata, Record};+use std::io::Write;+use std::sync::atomic::{AtomicU8, Ordering};++/// 日志级别映射到数字+const TRACE: u8 = 0;+const DEBUG: u8 = 1;+const INFO: u8 = 2;+const WARN: u8 = 3;+const ERROR: u8 = 4;++static FILTER_LEVEL: AtomicU8 = AtomicU8::new(DEBUG);++/// 自定义日志格式化器+struct SimpleLogger;++impl log::Log for SimpleLogger {+ fn enabled(&self, metadata: &Metadata) -> bool {+ let current_level = FILTER_LEVEL.load(Ordering::Relaxed);+ let record_level = match metadata.level() {+ Level::Trace => TRACE,+ Level::Debug => DEBUG,+ Level::Info => INFO,+ Level::Warn => WARN,+ Level::Error => ERROR,+ };+ record_level >= current_level+ }++ fn log(&self, record: &Record) {+ if self.enabled(record.metadata()) {+ // 从模块路径中提取模块名+ let module_path = record.module_path().unwrap_or("unknown");++ // 格式化输出: [Module]: content+ let output = format!("[{}]: {}\n", module_path, record.args());++ // 输出到 stderr (错误级别) 或 stdout (其他级别)+ match record.level() {+ Level::Error => {+ let mut stderr = std::io::stderr();+ let _ = stderr.write_all(output.as_bytes());+ let _ = stderr.flush();+ }+ _ => {+ let mut stdout = std::io::stdout();+ let _ = stdout.write_all(output.as_bytes());+ let _ = stdout.flush();+ }+ }+ }+ }++ fn flush(&self) {+ let _ = std::io::stdout().flush();+ let _ = std::io::stderr().flush();+ }+}++static LOGGER: SimpleLogger = SimpleLogger;++/// 初始化日志系统+///+/// 默认日志级别为 Info,可以通过环境变量 RUST_LOG 控制+/// 例如: RUST_LOG=debug 或 RUST_LOG=service::workflow=debug+pub fn init() {+ // 从环境变量读取日志级别,默认为 info+ let log_level = std::env::var("RUST_LOG")+ .unwrap_or_else(|_| "info".to_string())+ .to_lowercase();++ let filter = match log_level.as_str() {+ "trace" => TRACE,+ "debug" => DEBUG,+ "info" => INFO,+ "warn" => WARN,+ "error" => ERROR,+ _ => INFO,+ };++ FILTER_LEVEL.store(filter, Ordering::Relaxed);++ log::set_logger(&LOGGER)+ .map(|()| log::set_max_level(LevelFilter::Trace))+ .expect("Failed to initialize logger");+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 3bd69a5c..0f126e2a 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -2,5 +2,5 @@#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]fn main() {- deepseek_harness_desktop_lib::run();+ main::run()}diff --git a/src-tauri/src/service/download/core.rs b/src-tauri/src/service/download/core.rsnew file mode 100644index 00000000..ad581331--- /dev/null+++ b/src-tauri/src/service/download/core.rs@@ -0,0 +1,169 @@+use futures_util::StreamExt;+use std::fs;+use std::path::PathBuf;++use crate::service::download::ProgressTracker;+use tauri::Runtime;++/// 下载文件到内存+///+/// # 参数+/// - `tracker`: 进度追踪器+/// - `url`: 要下载的文件 URL+///+/// # 返回+/// 成功返回文件内容 `Ok(Vec<u8>)`,失败返回错误信息+pub async fn download_file<'a, R: Runtime>(+ tracker: &'a ProgressTracker<'a, R>,+ url: String,+) -> Result<Vec<u8>, String> {+ log::info!("Starting file download: {}", url);+ // 创建具备 User-Agent 的客户端+ let client = reqwest::Client::builder()+ .user_agent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (deepseek-harness-desktop)")+ .connect_timeout(std::time::Duration::from_secs(20))+ .build()+ .map_err(|e| {+ log::error!("Failed to create HTTP client: {}", e);+ e.to_string()+ })?;++ let res = client.get(&url).send().await.map_err(|e| {+ log::error!("Download request failed: {}", e);+ e.to_string()+ })?;++ if !res.status().is_success() {+ log::error!("Download failed with HTTP status: {}", res.status());+ return Err(format!("Download failed: HTTP {}", res.status()));+ }++ // 下载流处理并写入内存+ let total_size = res.content_length().unwrap_or(0);+ log::debug!("File size: {} bytes", total_size);+ let mut downloaded: u64 = 0;+ let mut stream = res.bytes_stream();+ let mut buffer = Vec::new();+ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| {+ log::error!("Download stream read error: {}", e);+ e.to_string()+ })?;+ buffer.extend_from_slice(&chunk);+ downloaded += chunk.len() as u64;+ let progress_pct = (downloaded as f64 / total_size as f64) * 100.0;+ tracker.update(+ progress_pct,+ format!(+ "已下载 {:.1} MB / {:.1} MB",+ downloaded as f64 / 1_000_000.0,+ total_size as f64 / 1_000_000.0+ ),+ format!("Download {}", url),+ );+ }++ log::info!("Download completed, {} bytes total", downloaded);+ Ok(buffer)+}++/// 确保解压文件到指定目录+///+/// # 参数+/// - `tracker`: 进度追踪器+/// - `name`: 文件名+/// - `buffer`: 压缩文件内容+/// - `dest`: 解压目标目录+///+/// # 返回+/// 成功返回 `Ok(())`,失败返回错误信息+pub fn ensure_extract<'a, R: Runtime>(+ tracker: &'a ProgressTracker<'a, R>,+ name: String,+ buffer: Vec<u8>,+ dest: PathBuf,+) -> Result<(), String> {+ log::info!("Starting file extraction: {} -> {:?}", name, dest);+ use super::extractor::{extract_tgz, extract_zip};+ use super::utils::flatten_directory;++ // 判断文件类型+ let pure_name = name.split('?').next().unwrap_or(&name).to_lowercase();+ let is_tgz = pure_name.ends_with(".tar.gz") || pure_name.ends_with(".tgz");+ let is_zip = pure_name.ends_with(".zip");+ log::debug!("File type: tgz={}, zip={}", is_tgz, is_zip);++ // 目标是文件,跳过,直接写入文件+ if !is_tgz && !is_zip {+ log::debug!("Non-compressed file, writing directly");+ if let Some(parent) = dest.parent() {+ fs::create_dir_all(parent).map_err(|e| {+ log::error!("Failed to create parent directory: {}", e);+ e.to_string()+ })?;+ }+ fs::write(&dest, &buffer).map_err(|e| {+ log::error!("Failed to write file: {}", e);+ e.to_string()+ })?;+ tracker.update(+ 100.0,+ format!("已写入: {}", "100%"),+ format!("File written: {}", dest.display()),+ );+ log::info!("File write completed: {}", dest.display());+ return Ok(());+ }++ // 清理并准备目标目录+ if dest.exists() {+ log::debug!("Destination directory exists, cleaning");+ fs::remove_dir_all(&dest).ok();+ }+ fs::create_dir_all(&dest).map_err(|e| {+ log::error!("Failed to create destination directory: {}", e);+ e.to_string()+ })?;++ // 根据文件类型解压+ if is_tgz {+ log::debug!("Using tgz extractor");+ extract_tgz(tracker, &buffer, &dest)?;+ } else {+ log::debug!("Using zip extractor");+ extract_zip(tracker, &buffer, &dest)?;+ }++ // 处理解压后的"套娃"文件夹+ log::debug!("Flattening directory structure");+ flatten_directory(&dest).map_err(|e| {+ log::error!("Failed to flatten directory: {}", e);+ e.to_string()+ })?;++ // 权限修复与隔离属性移除 (仅限 Unix/macOS)+ #[cfg(unix)]+ {+ use super::utils::fix_recursive_permissions;+ // 递归赋予可执行权限 (755)+ log::debug!("Fixing file permissions");+ fix_recursive_permissions(&dest).map_err(|e| {+ log::error!("Failed to fix permissions: {}", e);+ format!("Failed to fix permissions: {}", e)+ })?;++ // macOS 移除 quarantine 属性+ #[cfg(target_os = "macos")]+ {+ use std::process::Command;+ log::debug!("Removing macOS quarantine attribute");+ if let Some(path_str) = dest.to_str() {+ let _ = Command::new("xattr")+ .args(["-cr", path_str])+ .output();+ }+ }+ }++ Ok(())+}diff --git a/src-tauri/src/service/download/extractor.rs b/src-tauri/src/service/download/extractor.rsnew file mode 100644index 00000000..ef4f78ed--- /dev/null+++ b/src-tauri/src/service/download/extractor.rs@@ -0,0 +1,151 @@+use std::fs;+use std::io::copy;+use std::io::Cursor;+use std::path::PathBuf;++use crate::service::download::ProgressTracker;+use tauri::Runtime;++/// 解压 ZIP 文件到指定目录+pub fn extract_zip<'a, R: Runtime>(+ tracker: &ProgressTracker<'a, R>,+ buffer: &[u8],+ dest: &PathBuf,+) -> Result<(), String> {+ log::debug!("Starting ZIP extraction to: {:?}", dest);+ let mut archive = zip::ZipArchive::new(Cursor::new(buffer)).map_err(|e| {+ log::error!("Invalid ZIP format: {}", e);+ format!("Invalid ZIP format: {}", e)+ })?;++ let total_files = archive.len();+ log::debug!("ZIP file contains {} files", total_files);++ for i in 0..total_files {+ // 1. 获取当前文件+ let mut file = archive.by_index(i).map_err(|e| e.to_string())?;++ // 2. 获取并清理输出路径(防止路径穿越漏洞)+ let outpath = match file.enclosed_name() {+ Some(path) => dest.join(path),+ None => continue,+ };++ // 3. 打印进度和当前文件名(格式:Extract 路径/文件)+ let relative_path = outpath+ .strip_prefix(dest)+ .ok()+ .and_then(|p| p.to_str())+ .map(|s| s.replace('\\', "/"))+ .unwrap_or_else(|| {+ outpath+ .file_name()+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_default()+ });+ let progress_pct = ((i + 1) as f64 / total_files as f64) * 100.0;+ tracker.update(+ progress_pct,+ format!("已解压 {:.1}%", progress_pct),+ format!("Extract {}", relative_path),+ );++ // 4. 处理目录或文件+ if file.is_dir() {+ fs::create_dir_all(&outpath).map_err(|e| {+ log::error!("Failed to create directory {:?}: {}", outpath, e);+ e.to_string()+ })?;+ } else {+ // 无条件创建所有父目录(避免竞态条件和路径问题)+ if let Some(p) = outpath.parent() {+ fs::create_dir_all(&p).map_err(|e| {+ log::error!(+ "Failed to create parent directory {:?}: {} (file: {:?})",+ p,+ e,+ outpath+ );+ format!("Failed to create parent directory {:?}: {}", p, e)+ })?;+ }+ let mut outfile = fs::File::create(&outpath).map_err(|e| {+ log::error!(+ "Failed to create file {:?}: {} (parent exists: {})",+ outpath,+ e,+ outpath.parent().map(|p| p.exists()).unwrap_or(false)+ );+ format!("Failed to create file {:?}: {}", outpath, e)+ })?;+ copy(&mut file, &mut outfile).map_err(|e| {+ log::error!("Failed to copy file {:?}: {}", outpath, e);+ e.to_string()+ })?;+ }++ // 设置权限(仅限 Unix 系统可选)+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Some(mode) = file.unix_mode() {+ fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).ok();+ }+ }+ }+ log::info!("ZIP extraction completed, {} files total", total_files);+ Ok(())+}++/// 解压 TGZ 文件到指定目录+pub fn extract_tgz<'a, R: Runtime>(+ tracker: &ProgressTracker<'a, R>,+ buffer: &[u8],+ dest: &PathBuf,+) -> Result<(), String> {+ log::debug!("Starting TGZ extraction to: {:?}", dest);+ use flate2::read::GzDecoder;+ use tar::Archive;++ let tar_gz = GzDecoder::new(Cursor::new(buffer));+ let mut archive = Archive::new(tar_gz);++ // 使用 entries() 替代 unpack() 以便手动控制+ let entries = archive.entries().map_err(|e| {+ log::error!("Failed to read TGZ entries: {}", e);+ e.to_string()+ })?;++ let mut file_count = 0;+ for entry_result in entries {+ let mut entry = entry_result.map_err(|e| {+ log::error!("Failed to read TGZ entry: {}", e);+ e.to_string()+ })?;+ let path = entry.path().map(|p| p.to_path_buf()).map_err(|e| {+ log::error!("Failed to get entry path: {}", e);+ e.to_string()+ })?;++ // 打印当前解压的文件名(格式:Extract 路径/文件)+ // -1.0 表示未知进度(让前端持续增加)+ let relative_path = path.to_string_lossy().replace('\\', "/");+ // 对于 TGZ,由于无法提前知道文件总数,使用文件计数来估算进度+ let estimated_pct = (file_count as f64 / (file_count + 1) as f64) * 100.0;+ tracker.update(+ -1.0,+ format!("已解压 {:.1}%", estimated_pct),+ format!("Extract {}", relative_path),+ );++ // 执行解压+ entry.unpack_in(dest).map_err(|e| {+ log::error!("Failed to unpack entry {:?}: {}", path, e);+ e.to_string()+ })?;+ file_count += 1;+ }++ log::info!("TGZ extraction completed, {} files total", file_count);+ Ok(())+}diff --git a/src-tauri/src/service/download/installable.rs b/src-tauri/src/service/download/installable.rsnew file mode 100644index 00000000..9dad42be--- /dev/null+++ b/src-tauri/src/service/download/installable.rs@@ -0,0 +1,50 @@+use crate::config;+use async_trait::async_trait;+use std::path::PathBuf;+use tauri::AppHandle;++#[async_trait]+pub trait Installable: Send + Sync {+ fn title(&self) -> &str;+ fn check_installed(&self, app: &AppHandle) -> bool;+ fn get_download_url(&self) -> Result<String, String>;+ fn get_install_path(&self, app: &AppHandle) -> PathBuf;+}++// --- Node.js 实现 ---+pub struct Nodejs;++#[async_trait]+impl Installable for Nodejs {+ fn title(&self) -> &str {+ "运行环境"+ }+ fn get_download_url(&self) -> Result<String, String> {+ config::get_node_download_url()+ }+ fn get_install_path(&self, app: &AppHandle) -> PathBuf {+ config::get_node_install_path(app)+ }+ fn check_installed(&self, app: &AppHandle) -> bool {+ config::get_node_binary_path(app).exists() && config::is_runtime_compatible(app)+ }+}++// --- DeepSeek Harness 实现 ---+pub struct Dsh;++#[async_trait]+impl Installable for Dsh {+ fn title(&self) -> &str {+ "Harness 核心"+ }+ fn get_download_url(&self) -> Result<String, String> {+ config::get_dsh_download_url()+ }+ fn get_install_path(&self, app: &AppHandle) -> PathBuf {+ config::get_dsh_install_path(app)+ }+ fn check_installed(&self, app: &AppHandle) -> bool {+ config::get_dsh_binary_path(app).exists()+ }+}diff --git a/src-tauri/src/service/download/mod.rs b/src-tauri/src/service/download/mod.rsnew file mode 100644index 00000000..69e6b778--- /dev/null+++ b/src-tauri/src/service/download/mod.rs@@ -0,0 +1,10 @@+mod core;+mod extractor;+mod installable;+mod progress;+mod utils;++// 导出公共接口+pub use core::{download_file, ensure_extract};+pub use installable::{Installable, Dsh, Nodejs};+pub use progress::ProgressTracker;diff --git a/src-tauri/src/service/download/progress.rs b/src-tauri/src/service/download/progress.rsnew file mode 100644index 00000000..622503d2--- /dev/null+++ b/src-tauri/src/service/download/progress.rs@@ -0,0 +1,89 @@+use serde::Serialize;+use std::sync::Mutex;+use std::time::{Duration, Instant};+use tauri::{Emitter, Runtime, WebviewWindow};++#[derive(Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ProgressPayload {+ pub title: String,+ pub detail: String,+ pub log: String,+ pub r#type: String,+ pub percentage: f64,+ // 子任务进度+ pub progress: f64,+}++pub struct ProgressTracker<'a, R: Runtime> {+ window: &'a WebviewWindow<R>,+ total_phases: usize,+ current_phase: usize,+ current_title: String,+ current_type: String,+ last_emit_time: Mutex<Option<Instant>>,+}++impl<'a, R: Runtime> ProgressTracker<'a, R> {+ pub fn new(window: &'a WebviewWindow<R>, task_count: usize) -> Self {+ Self {+ window,+ total_phases: task_count,+ current_phase: 0,+ current_title: String::from("准备中..."),+ current_type: String::from(""),+ last_emit_time: Mutex::new(None),+ }+ }++ /// 切换阶段,并设置大标题+ pub fn start_phase(&mut self, r#type: &str, title: &str) {+ self.current_title = title.to_string();+ self.current_type = r#type.to_string();+ }++ /// 完成一个阶段+ pub fn end_phase(&mut self) {+ if self.current_phase < self.total_phases {+ self.current_phase += 1;+ }+ }++ /// stage_pct: 当前子任务的进度 (0.0 - 100.0)+ /// detail: 用于显示的主要信息 (如 "已下载 xx MB / xx MB" 或 "已解压 30%")+ /// log: 用于在 log 窗口显示的文字 (如 "Download http://..." 或 "Extract xx/xx/xx")+ pub fn update(&self, stage_pct: f64, detail: String, log: String) {+ let now = Instant::now();+ let mut last_emit = self.last_emit_time.lock().unwrap();++ // 节流处理:如果距离上次发送不足 50ms,则跳过+ if let Some(last_time) = *last_emit {+ if now.duration_since(last_time) < Duration::from_millis(50) {+ return;+ }+ }++ *last_emit = Some(now);++ let phase_weight = 100.0 / self.total_phases as f64;+ let global_pct =+ (self.current_phase as f64 * phase_weight) + (stage_pct * phase_weight / 100.0);++ let _ = self.window.emit(+ "install-progress",+ ProgressPayload {+ title: self.current_title.clone(),+ r#type: self.current_type.clone(),+ percentage: global_pct,+ progress: stage_pct,+ detail,+ log,+ },+ );+ }++ /// 跳过指定数量的阶段+ pub fn skip_phases(&mut self, count: usize) {+ self.current_phase = (self.current_phase + count).min(self.total_phases);+ }+}diff --git a/src-tauri/src/service/download/utils.rs b/src-tauri/src/service/download/utils.rsnew file mode 100644index 00000000..028ac25c--- /dev/null+++ b/src-tauri/src/service/download/utils.rs@@ -0,0 +1,95 @@+use std::fs;+use std::io;+use std::path::{Path, PathBuf};++#[cfg(unix)]+use std::os::unix::fs::PermissionsExt;++/// 递归设置权限 (rwxr-xr-x)+#[cfg(unix)]+pub fn fix_recursive_permissions(path: &Path) -> io::Result<()> {+ // 设置当前路径权限+ let mut perms = fs::metadata(path)?.permissions();+ perms.set_mode(0o755);+ fs::set_permissions(path, perms)?;++ // 如果是目录,递归处理子项+ if path.is_dir() {+ for entry in fs::read_dir(path)? {+ fix_recursive_permissions(&entry?.path())?;+ }+ }+ Ok(())+}++const PRESERVE_DIRS: &[&str] = &["node_modules", ".git"];++pub fn flatten_directory(dest: &PathBuf) -> Result<(), String> {+ // 1. 寻找唯一合法的子目录+ let sub_dirs: Vec<PathBuf> = fs::read_dir(dest)+ .map_err(|e| e.to_string())?+ .filter_map(|e| e.ok())+ .map(|e| e.path())+ .filter(|path| {+ if !path.is_dir() {+ return false;+ }++ // 检查文件名(过滤隐藏文件和保留目录)+ path.file_name()+ .and_then(|n| n.to_str())+ .map(|name| !name.starts_with('.') && !PRESERVE_DIRS.contains(&name))+ .unwrap_or(false)+ })+ .collect();++ // 如果不满足“只有一个子目录”的条件,直接返回+ if sub_dirs.len() != 1 {+ return Ok(());+ }++ let sub_dir = &sub_dirs[0];+ log::debug!("Flattening subdirectory: {:?}", sub_dir);++ // 2. 移动子目录下的内容+ for entry in fs::read_dir(sub_dir).map_err(|e| e.to_string())? {+ let entry = entry.map_err(|e| e.to_string())?;+ let from = entry.path();+ let file_name = entry.file_name();+ let to = dest.join(&file_name);++ force_move(&from, &to).map_err(|e| {+ let msg = format!("Failed to move {:?} to {:?}: {}", from, to, e);+ log::error!("{}", msg);+ msg+ })?;+ }++ // 3. 清理空的子目录+ if let Err(e) = fs::remove_dir(sub_dir) {+ log::warn!("Could not remove empty directory {:?}: {}", sub_dir, e);+ }++ Ok(())+}++/// 辅助函数:强制移动文件或目录(如果目标存在则覆盖)+fn force_move(from: &Path, to: &Path) -> io::Result<()> {+ // 尝试直接重命名+ if let Err(err) = fs::rename(from, to) {+ // 如果失败是因为目标已存在 (通常是目录冲突或跨文件系统)+ if to.exists() {+ log::debug!("Target exists, removing: {:?}", to);+ if to.is_dir() {+ fs::remove_dir_all(to)?;+ } else {+ fs::remove_file(to)?;+ }+ // 删除目标后再次尝试重命名+ fs::rename(from, to)?;+ } else {+ return Err(err);+ }+ }+ Ok(())+}diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rsnew file mode 100644index 00000000..d69e5fe6--- /dev/null+++ b/src-tauri/src/service/mod.rs@@ -0,0 +1,3 @@+pub mod download;+pub mod scheduler;+pub mod workflow;diff --git a/src-tauri/src/service/scheduler/mod.rs b/src-tauri/src/service/scheduler/mod.rsnew file mode 100644index 00000000..6f6704e0--- /dev/null+++ b/src-tauri/src/service/scheduler/mod.rs@@ -0,0 +1,22 @@+use std::time::Duration;+use tauri::AppHandle;+use tokio::time;++pub fn start(app_handle: &AppHandle) {+ log::info!("Starting dsh process monitor");+ let app_handle_clone = app_handle.clone();+ tauri::async_runtime::spawn(async move {+ scheduler_permanent_loop(app_handle_clone).await;+ });+}++async fn scheduler_permanent_loop(app_handle: AppHandle) {+ let mut interval = time::interval(Duration::from_secs(1));++ loop {+ crate::task::tick_check_dsh_process::trigger(app_handle.clone())+ .await+ .unwrap();+ interval.tick().await;+ }+}diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rsnew file mode 100644index 00000000..b3394c92--- /dev/null+++ b/src-tauri/src/service/workflow/mod.rs@@ -0,0 +1,297 @@+pub mod status;+pub mod utils;++use crate::config;+use crate::service::download;+use crate::service::workflow::utils::{is_dsh_running, is_port_in_use, spawn_output_readers};+use std::collections::HashMap;+use std::fs;+use std::process::{Command, Stdio};+use tauri::Manager;++/// 检测并启动 Harness 服务+pub async fn start(app_handle: tauri::AppHandle) -> Result<(), String> {+ let setting = config::get_store_dat_setting(&app_handle);+ let node_binary_path = config::get_node_binary_path(&app_handle);+ let dsh_binary_path = config::get_dsh_binary_path(&app_handle);++ if !setting.installed {+ log::debug!("Harness not installed, skipping startup");+ return Ok(());+ }+ if !node_binary_path.exists() || !dsh_binary_path.exists() {+ let mut setting = config::get_store_dat_setting(&app_handle);+ setting.installed = false;+ config::set_store_dat_setting(&app_handle, setting);+ log::debug!("Harness not installed, skipping startup");+ return Ok(());+ }++ log::debug!("Checking Harness running status");+ let port_in_use = is_port_in_use(setting.port);+ let dsh_running = is_dsh_running().await;++ if port_in_use && !dsh_running {+ log::info!("Harness is not running, but port is in use, stopping harness");+ stop(app_handle.clone()).await?;+ return Ok(());+ }++ if dsh_running {+ log::info!("Harness is already running");+ status::set_status(status::Status::Running);+ status::emit_status(&app_handle);+ return Ok(());+ }++ log::info!("Starting Harness service");+ status::set_status(status::Status::Starting);+ status::emit_status(&app_handle);+ launch(app_handle).await?;+ // 之后由 scheduler/task/tick_check_dsh_process/mod.rs 检测状态++ Ok(())+}++/// 重启 Harness 服务+pub async fn restart(app_handle: tauri::AppHandle) -> Result<(), String> {+ log::info!("Restarting Harness service");++ // 1. 停止现有服务+ stop(app_handle.clone()).await?;++ // 2. 重新启动+ start(app_handle).await?;++ Ok(())+}++/// 启动 Harness 服务进程+pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {+ let setting = config::get_store_dat_setting(&app_handle);+ let node_binary_path = config::get_node_binary_path(&app_handle);+ let dsh_binary_path = config::get_dsh_binary_path(&app_handle);++ log::debug!("Checking Node.js path: {:?}", node_binary_path);+ if !node_binary_path.exists() {+ log::error!("Node.js not installed");+ return Err("NODE_NOT_FOUND: Node.js not installed".to_string());+ }+ log::debug!("Checking Harness path: {:?}", dsh_binary_path);+ if !dsh_binary_path.exists() {+ log::error!("Harness not installed");+ return Err("HARNESS_NOT_FOUND: Harness not installed".to_string());+ }++ // 避免重复启动(竞态由启动前的端口/健康检查兜底)+ if is_dsh_running().await {+ log::info!("Harness is already running, skipping launch");+ return Ok(());+ }++ #[cfg(unix)]+ {+ let _ = Command::new("pkill").arg("-9").arg("node").output();+ }++ // 构造环境变量:隔离的 $DSH_HOME + 隐私默认(关闭遥测)+ let dsh_home = config::get_dsh_data_path(&app_handle);+ fs::create_dir_all(&dsh_home).map_err(|e| format!("create dsh home failed: {e}"))?;+ let mut envs: HashMap<String, String> = HashMap::new();+ envs.insert("DSH_HOME".to_string(), dsh_home.to_string_lossy().into_owned());+ envs.insert("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string());+ envs.insert("NO_COLOR".to_string(), "1".to_string());+ envs.insert("DSH_WEB_PORT".to_string(), setting.port.to_string());++ // 扩展 PATH,让 dsh 及其子进程能找到 node+ if let Some(node_dir) = node_binary_path.parent() {+ if let Some(existing_path) = std::env::var_os("PATH") {+ let mut paths = vec![node_dir.to_path_buf()];+ paths.extend(std::env::split_paths(&existing_path));+ if let Ok(new_path) = std::env::join_paths(paths) {+ envs.insert("PATH".to_string(), new_path.to_string_lossy().into_owned());+ }+ }+ }++ // 日志文件(前端日志面板读取)+ let log_path = config::get_service_log_path(&app_handle);+ fs::create_dir_all(log_path.parent().unwrap_or(std::path::Path::new(".")))+ .map_err(|e| format!("create log dir failed: {e}"))?;++ let mut cmd = Command::new(&node_binary_path);+ cmd.arg(&dsh_binary_path)+ .arg("--profile")+ .arg("web")+ .arg("--host")+ .arg("127.0.0.1")+ .arg("--port")+ .arg(&setting.port.to_string())+ .envs(&envs)+ .current_dir(config::get_dsh_install_path(&app_handle))+ // 核心修正:提供一个空的 stdin 防止 setRawMode 报错+ .stdin(Stdio::null())+ // 使用管道捕获输出,以便在子线程中读取+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());++ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x08000000);+ }++ log::info!("Starting Harness process");+ match cmd.spawn() {+ Ok(mut child) => {+ log::info!("Harness process started successfully");+ // 获取 stdout 和 stderr,并启动读取线程+ let stdout = child.stdout.take();+ let stderr = child.stderr.take();+ spawn_output_readers(stdout, stderr, log_path);++ Ok(())+ }+ Err(e) => {+ log::error!("Failed to start process: {}", e);+ Err(format!("Failed to start process: {}", e))+ }+ }+}++/// 停止 Harness 服务+pub async fn stop(app_handle: tauri::AppHandle) -> Result<(), String> {+ log::info!("Stopping Harness service...");+ let port = config::get_store_dat_setting(&app_handle).port;++ #[cfg(unix)]+ {+ // 使用 lsof 找到占用端口的进程并强制结束+ let _ = Command::new("sh")+ .arg("-c")+ .arg(format!("lsof -ti:{} | xargs kill -9", port))+ .output();+ }++ #[cfg(windows)]+ {+ // 使用 PowerShell 清理端口占用进程(更稳定)+ let ps_cmd = format!(+ "Get-NetTCPConnection -LocalPort {} -ErrorAction SilentlyContinue | ForEach-Object {{ Stop-Process -Id $_.OwningProcess -Force }}",+ port+ );++ let mut cmd = Command::new("powershell");+ // 使用 -WindowStyle Hidden 和 -NoProfile -NonInteractive 确保不显示窗口+ cmd.args([+ "-NoProfile",+ "-NonInteractive",+ "-WindowStyle",+ "Hidden",+ "-Command",+ &ps_cmd,+ ]);++ // 隐藏 PowerShell 窗口,避免弹出黑色控制台窗口+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW++ // 重定向 stdout 和 stderr 到空,进一步确保不显示窗口+ cmd.stdout(Stdio::null());+ cmd.stderr(Stdio::null());++ let output = cmd.output();++ if let Err(e) = output {+ log::error!("Windows stop error: {}", e);+ }+ }++ // 给系统一点时间释放端口 (重要!)+ tokio::time::sleep(std::time::Duration::from_millis(800)).await;++ status::set_status(status::Status::Stopped);+ status::emit_status(&app_handle);+ Ok(())+}++/// 安装环境(Node.js 运行时 + 打包的 Harness 发行版)+pub async fn install(app_handle: &tauri::AppHandle) -> Result<(), String> {+ log::info!("Starting installation process");+ let window = app_handle+ .get_webview_window("main")+ .ok_or("Failed to get main window")?;+ log::debug!("Main window obtained");+ let mut tracker = download::ProgressTracker::new(&window, 4);+ let tasks: Vec<Box<dyn download::Installable>> =+ vec![Box::new(download::Nodejs), Box::new(download::Dsh)];+ log::info!("Task list created, {} tasks total", tasks.len());++ for (index, task) in tasks.iter().enumerate() {+ log::debug!("Processing task {}/{}", index + 1, tasks.len());+ if task.check_installed(app_handle) {+ log::debug!("Task {} already installed, skipping", index + 1);+ tracker.skip_phases(2);+ continue;+ }++ log::info!("Task {} not installed, starting installation", index + 1);++ // 1. 下载+ tracker.start_phase("download", &format!("正在下载 {}", task.title()));+ let url = task.get_download_url()?;+ log::debug!("Download URL: {}", url);+ let name = url.split('/').last().unwrap().to_string();+ log::debug!("File name: {}", name);+ let buffer = download::download_file(&tracker, url).await?;+ log::info!("Download completed, file size: {} bytes", buffer.len());+ tracker.end_phase();++ // 2. 解压+ tracker.start_phase("extract", &format!("正在解压 {}", task.title()));+ let dest = task.get_install_path(app_handle);+ log::debug!("Installation path: {:?}", dest);+ download::ensure_extract(&tracker, name, buffer, dest)?;+ log::info!("Extraction completed");+ tracker.end_phase();+ }++ log::info!("All installation tasks completed");+ tracker.update(+ 100.0,+ "依赖已安装完毕".to_string(),+ "All tasks completed".into(),+ );++ Ok(())+}++/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)+pub async fn proxy_health_check(port: u16) -> Result<String, String> {+ let client = reqwest::Client::builder()+ .timeout(config::HEALTH_CHECK_TIMEOUT)+ .build()+ .map_err(|e| e.to_string())?;++ for endpoint in [+ format!("http://127.0.0.1:{port}/"),+ format!("http://127.0.0.1:{port}/healthz"),+ ] {+ match client.get(&endpoint).send().await {+ Ok(response) => {+ let status = response.status();+ let body = response.text().await.unwrap_or_default();+ if status.is_success() {+ return Ok(format!(+ "healthy - {status} - {}",+ body.chars().take(80).collect::<String>()+ ));+ }+ }+ Err(err) => {+ log::debug!("Health check {endpoint}: {err}");+ }+ }+ }+ Err("HARNESS_NOT_READY: Harness service is not ready".to_string())+}diff --git a/src-tauri/src/service/workflow/status.rs b/src-tauri/src/service/workflow/status.rsnew file mode 100644index 00000000..3db1b67f--- /dev/null+++ b/src-tauri/src/service/workflow/status.rs@@ -0,0 +1,32 @@+use std::sync::{Mutex, OnceLock};+use tauri::AppHandle;+use tauri::Emitter;++#[derive(Debug, Clone, serde::Serialize, PartialEq)]+pub enum Status {+ Initial,+ Installing,+ Starting,+ Running,+ Stopped,+}++// 使用静态变量在模块内部管理状态+static DSH_STATUS: OnceLock<Mutex<Status>> = OnceLock::new();++pub fn get_status_lock() -> &'static Mutex<Status> {+ DSH_STATUS.get_or_init(|| Mutex::new(Status::Initial))+}++pub fn set_status(status: Status) {+ *get_status_lock().lock().unwrap() = status;+}++pub fn emit_status(app_handle: &AppHandle) {+ let status = get_status();+ let _ = app_handle.emit("dsh-status-updated", &status);+}++pub fn get_status() -> Status {+ get_status_lock().lock().unwrap().clone()+}diff --git a/src-tauri/src/service/workflow/utils.rs b/src-tauri/src/service/workflow/utils.rsnew file mode 100644index 00000000..9dc3706e--- /dev/null+++ b/src-tauri/src/service/workflow/utils.rs@@ -0,0 +1,109 @@+use std::io::{BufRead, BufReader, Write};+use std::net::{SocketAddr, TcpStream};+use std::path::PathBuf;+use std::process::{ChildStderr, ChildStdout};+use std::thread;+use std::time::Duration;++/// 检查 Harness 是否真正在运行+pub async fn is_dsh_running() -> bool {+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(2))+ .build()+ .ok(); // 将 Result 转为 Option++ // 如果 client 创建失败,直接返回 false+ let client = match client {+ Some(c) => c,+ None => return false,+ };++ use crate::config::get_dsh_base_url;+ let url = format!("{}/", get_dsh_base_url());++ // 发送请求并判断是否就绪+ let check_status = async {+ let resp = client.get(&url).send().await.ok()?;+ if resp.status() != reqwest::StatusCode::OK {+ return None;+ }+ Some(true)+ };++ check_status.await.unwrap_or(false)+}++/// 检查指定端口是否被占用(通过尝试连接来判断)+pub fn is_port_in_use(port: u16) -> bool {+ // 尝试连接到端口,设置较短的超时时间(100ms)以快速检测+ let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().unwrap_or_else(|_| {+ // 如果解析失败,返回一个默认地址(虽然不太可能发生)+ "127.0.0.1:0".parse().unwrap()+ });++ match TcpStream::connect_timeout(&addr, Duration::from_millis(100)) {+ Ok(_) => true, // 连接成功,端口被占用(有服务在监听)+ Err(_) => false, // 连接失败或超时,端口未被占用+ }+}++/// 在独立线程中读取子进程的输出,同时写入日志文件+///+/// # 参数+/// - `stdout`: 子进程的标准输出+/// - `stderr`: 子进程的标准错误输出+/// - `log_path`: 前端日志面板读取的日志文件+pub fn spawn_output_readers(+ stdout: Option<ChildStdout>,+ stderr: Option<ChildStderr>,+ log_path: PathBuf,+) {+ // 在独立线程中读取 stdout+ if let Some(stdout) = stdout {+ let log_path = log_path.clone();+ thread::spawn(move || {+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ match line {+ Ok(line) => {+ log::info!("[dsh::stdout]: {}", line);+ append_log(&log_path, &line);+ }+ Err(e) => {+ log::error!("Failed to read dsh stdout: {}", e);+ break;+ }+ }+ }+ });+ }++ // 在独立线程中读取 stderr+ if let Some(stderr) = stderr {+ thread::spawn(move || {+ let reader = BufReader::new(stderr);+ for line in reader.lines() {+ match line {+ Ok(line) => {+ log::warn!("[dsh::stderr]: {}", line);+ append_log(&log_path, &line);+ }+ Err(e) => {+ log::error!("Failed to read dsh stderr: {}", e);+ break;+ }+ }+ }+ });+ }+}++fn append_log(log_path: &PathBuf, line: &str) {+ if let Ok(mut file) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(log_path)+ {+ let _ = writeln!(file, "{}", line);+ }+}diff --git a/src-tauri/src/services/downloader.rs b/src-tauri/src/services/downloader.rsdeleted file mode 100644index 924d66f7..00000000--- a/src-tauri/src/services/downloader.rs+++ /dev/null@@ -1,362 +0,0 @@-//! Download helper with progress events, URL fallback, and archive extraction.--use futures_util::StreamExt;-use std::fs;-use std::io::Cursor;-use std::path::{Path, PathBuf};-use std::time::{Duration, Instant};-use tauri::{Emitter, Runtime, Window};--#[cfg(unix)]-use std::os::unix::fs::PermissionsExt;--const USER_AGENT: &str =- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (deepseek-harness-desktop)";--/// Minimum progress delta (percent) before a new event is emitted.-const PROGRESS_UPDATE_MIN_INCREMENT: f64 = 0.5;-/// Minimum time between progress events (ms).-const PROGRESS_UPDATE_MIN_INTERVAL_MS: u64 = 150;--#[cfg(unix)]-const EXECUTABLE_PERMISSIONS_MODE: u32 = 0o755;--#[derive(Clone, serde::Serialize)]-struct Progress {- progress: f64,- download_type: String,-}--#[derive(Clone, serde::Serialize)]-pub struct ExtractionStart {- pub download_type: String,-}--struct DownloadConfig {- urls: Vec<String>,- destination: PathBuf,- download_type: String,- is_archive: bool,- destination_is_file: bool,-}--/// Download from the first URL that succeeds.-///-/// * `destination` is a directory when the payload is an archive that should be-/// extracted in place, or a file path otherwise.-pub async fn download_file<R: Runtime>(- window: Window<R>,- urls: Vec<String>,- dest: PathBuf,- download_type: &str,-) -> Result<(), String> {- if urls.is_empty() {- return Err("download: empty URL list".to_string());- }-- let config = analyze_download_config(&urls, &dest, download_type);- let mut last_error: Option<String> = None;-- for url in &config.urls {- let cfg = DownloadConfig { urls: vec![url.clone()], ..clone_config(&config) };- match process_downloaded_content(&window, &cfg).await {- Ok(()) => {- finalize_download(&window, &config);- return Ok(());- }- Err(err) => {- eprintln!("[downloader] URL '{url}' failed: {err}");- last_error = Some(err);- }- }- }-- Err(last_error.unwrap_or_else(|| "download failed".to_string()))-}--fn clone_config(config: &DownloadConfig) -> DownloadConfig {- DownloadConfig {- urls: Vec::new(),- destination: config.destination.clone(),- download_type: config.download_type.clone(),- is_archive: config.is_archive,- destination_is_file: config.destination_is_file,- }-}--fn analyze_download_config(urls: &[String], dest: &Path, download_type: &str) -> DownloadConfig {- let pure_url = urls.first().map(|u| u.split('?').next().unwrap_or(u).to_lowercase());- let is_archive = pure_url- .as_deref()- .is_some_and(|u| [".tar.gz", ".tgz", ".zip"].iter().any(|ext| u.ends_with(ext)));- let destination_is_file = dest.extension().is_some() && dest.parent().is_some();-- DownloadConfig {- urls: urls.to_vec(),- destination: dest.to_path_buf(),- download_type: download_type.to_string(),- is_archive,- destination_is_file,- }-}--async fn download_with_progress<R: Runtime>(- window: &Window<R>,- config: &DownloadConfig,-) -> Result<Vec<u8>, String> {- let client = create_http_client()?;- let response = fetch_http_response(&client, &config.urls[0]).await?;- validate_http_response(&response, &config.urls[0])?;-- let total_size = response.content_length().unwrap_or(0);- let mut stream = response.bytes_stream();- let mut buffer = Vec::new();- let mut downloaded: u64 = 0;-- let mut last_emit_time = Instant::now();- let mut last_emit_progress = -1.0;-- while let Some(chunk_result) = stream.next().await {- let chunk = chunk_result.map_err(|e| format!("download stream error: {e}"))?;- buffer.extend_from_slice(&chunk);- downloaded += chunk.len() as u64;-- if total_size > 0 {- update_progress_if_needed(- window,- downloaded,- total_size,- &config.download_type,- &mut last_emit_time,- &mut last_emit_progress,- );- }- }-- Ok(buffer)-}--fn create_http_client() -> Result<reqwest::Client, String> {- reqwest::Client::builder()- .user_agent(USER_AGENT)- .connect_timeout(Duration::from_secs(20))- .build()- .map_err(|e| format!("create HTTP client failed: {e}"))-}--async fn fetch_http_response(- client: &reqwest::Client,- url: &str,-) -> Result<reqwest::Response, String> {- client- .get(url)- .send()- .await- .map_err(|e| format!("HTTP request failed '{url}': {e}"))-}--fn validate_http_response(response: &reqwest::Response, url: &str) -> Result<(), String> {- if response.status().is_success() {- Ok(())- } else {- Err(format!("download failed: HTTP {} for '{url}'", response.status()))- }-}--fn update_progress_if_needed<R: Runtime>(- window: &Window<R>,- downloaded: u64,- total: u64,- download_type: &str,- last_emit_time: &mut Instant,- last_emit_progress: &mut f64,-) {- let progress = (downloaded as f64 / total as f64) * 100.0;- let time_elapsed = last_emit_time.elapsed() >= Duration::from_millis(PROGRESS_UPDATE_MIN_INTERVAL_MS);- let progress_increased = progress - *last_emit_progress >= PROGRESS_UPDATE_MIN_INCREMENT;-- if time_elapsed || progress_increased {- let _ = window.emit(- "download-progress",- Progress {- progress,- download_type: download_type.to_string(),- },- );- *last_emit_progress = progress;- *last_emit_time = Instant::now();- }-}--async fn process_downloaded_content<R: Runtime>(- window: &Window<R>,- config: &DownloadConfig,-) -> Result<(), String> {- let buffer = download_with_progress(window, config).await?;-- if config.is_archive && !config.destination_is_file {- handle_archive_download(window, config, &buffer)- } else {- handle_file_download(config, &buffer)- }-}--fn handle_archive_download<R: Runtime>(- window: &Window<R>,- config: &DownloadConfig,- buffer: &[u8],-) -> Result<(), String> {- prepare_destination_directory(&config.destination)?;- let _ = window.emit(- "extraction-start",- ExtractionStart {- download_type: config.download_type.clone(),- },- );-- extract_archive(buffer, &config.destination)?;- flatten_single_directory(&config.destination)?;- fix_permissions_if_needed(&config.destination)?;-- Ok(())-}--fn handle_file_download(config: &DownloadConfig, buffer: &[u8]) -> Result<(), String> {- ensure_parent_directory_exists(&config.destination)?;- fs::write(&config.destination, buffer)- .map_err(|e| format!("write file '{}' failed: {e}", config.destination.display()))-}--/// Extract a downloaded archive into `dest` (cleaning it first), flattening a-/// single wrapping directory and fixing permissions.-pub fn extract_archive_to_dir(buffer: &[u8], dest: &Path) -> Result<(), String> {- prepare_destination_directory(dest)?;- extract_archive(buffer, dest)?;- flatten_single_directory(dest)?;- fix_permissions_if_needed(dest)?;- Ok(())-}--fn prepare_destination_directory(dest: &Path) -> Result<(), String> {- if dest.exists() {- fs::remove_dir_all(dest).map_err(|e| format!("clean dir '{}' failed: {e}", dest.display()))?;- }- fs::create_dir_all(dest).map_err(|e| format!("create dir '{}' failed: {e}", dest.display()))-}--fn ensure_parent_directory_exists(file_path: &Path) -> Result<(), String> {- if let Some(parent) = file_path.parent() {- fs::create_dir_all(parent)- .map_err(|e| format!("create parent dir '{}' failed: {e}", parent.display()))?;- }- Ok(())-}--fn extract_archive(buffer: &[u8], dest: &Path) -> Result<(), String> {- if buffer.starts_with(&[0x1f, 0x8b]) {- extract_tar_gz(buffer, dest)- } else {- extract_zip(buffer, dest)- }-}--fn extract_zip(buffer: &[u8], dest: &Path) -> Result<(), String> {- let mut archive =- zip::ZipArchive::new(Cursor::new(buffer)).map_err(|e| format!("invalid zip: {e}"))?;- archive.extract(dest).map_err(|e| format!("zip extract failed: {e}"))-}--fn extract_tar_gz(buffer: &[u8], dest: &Path) -> Result<(), String> {- use flate2::read::GzDecoder;- use tar::Archive;-- let tar_gz = GzDecoder::new(Cursor::new(buffer));- let mut archive = Archive::new(tar_gz);- archive.unpack(dest).map_err(|e| format!("tar.gz extract failed: {e}"))-}--/// Flatten a single top-level directory so extraction lands directly in `dest`.-fn flatten_single_directory(dest: &Path) -> Result<(), String> {- let entries: Vec<_> = fs::read_dir(dest)- .map_err(|e| format!("read dir '{}' failed: {e}", dest.display()))?- .filter_map(Result::ok)- .collect();-- let directories: Vec<_> = entries- .iter()- .filter(|entry| {- entry.path().is_dir()- && entry- .file_name()- .to_str()- .is_some_and(|n| !n.starts_with('.'))- })- .collect();-- if directories.len() == 1 {- let sub_dir = directories[0].path();- flatten_directory_contents(&sub_dir, dest)?;- fs::remove_dir(&sub_dir).map_err(|e| format!("remove dir '{}' failed: {e}", sub_dir.display()))?;- }- Ok(())-}--fn flatten_directory_contents(source_dir: &Path, target_dir: &Path) -> Result<(), String> {- let entries = fs::read_dir(source_dir)- .map_err(|e| format!("read dir '{}' failed: {e}", source_dir.display()))?;- for entry_result in entries {- let entry = entry_result.map_err(|e| format!("read dir entry failed: {e}"))?;- let from = entry.path();- let to = target_dir.join(entry.file_name());- fs::rename(&from, &to).map_err(|e| {- format!("move '{}' to '{}' failed: {e}", from.display(), to.display())- })?;- }- Ok(())-}--#[cfg_attr(not(unix), allow(unused_variables))]-fn fix_permissions_if_needed(dest: &Path) -> Result<(), String> {- #[cfg(unix)]- {- fix_recursive_permissions(dest).map_err(|e| format!("fix permissions failed: {e}"))?;- #[cfg(target_os = "macos")]- remove_macos_quarantine_attribute(dest);- }- Ok(())-}--#[cfg(unix)]-fn fix_recursive_permissions(path: &Path) -> std::io::Result<()> {- if path.is_dir() {- for entry in fs::read_dir(path)? {- fix_recursive_permissions(&entry.path())?;- }- } else {- let mut permissions = fs::metadata(path)?.permissions();- permissions.set_mode(EXECUTABLE_PERMISSIONS_MODE);- fs::set_permissions(path, permissions)?;- }- Ok(())-}--#[cfg(target_os = "macos")]-fn remove_macos_quarantine_attribute(path: &Path) {- let _ = path.to_str().and_then(|p| {- std::process::Command::new("xattr")- .args(["-cr", p])- .output()- .ok()- });-}--/// Emit a final 100% progress event after a successful download.-fn finalize_download<R: Runtime>(window: &Window<R>, config: &DownloadConfig) {- let _ = window.emit(- "download-progress",- Progress {- progress: 100.0,- download_type: config.download_type.clone(),- },- );-}diff --git a/src-tauri/src/services/manager.rs b/src-tauri/src/services/manager.rsdeleted file mode 100644index 0d46c1bf..00000000--- a/src-tauri/src/services/manager.rs+++ /dev/null@@ -1,228 +0,0 @@-//! Node.js runtime management and the dsh service process manager.--use crate::api::harness::constants::*;-use crate::i18n;-use once_cell::sync::Lazy;-use std::collections::HashMap;-use std::env;-use std::fs;-use std::path::{Path, PathBuf};-use std::process::{Child, Command, Stdio};-use std::sync::Mutex;--#[cfg(windows)]-use std::os::windows::process::CommandExt;--/// Windows process creation flag: do not open a console window.-#[cfg(windows)]-const WINDOWS_CREATE_NO_WINDOW_FLAG: u32 = 0x0800_0000;--/// Global process manager for the running dsh service.-pub static PROCESS_MANAGER: Lazy<Mutex<ProcessManager>> =- Lazy::new(|| Mutex::new(ProcessManager::new()));--/// Tracks the spawned `dsh web` child process.-pub struct ProcessManager {- child: Option<Child>,- pid: Option<u32>,-}--impl ProcessManager {- pub fn new() -> Self {- ProcessManager { child: None, pid: None }- }-- pub fn set_child(&mut self, child: Child) {- self.pid = Some(child.id());- self.child = Some(child);- }-- /// Terminate the child and (where possible) its whole process tree.- pub fn kill_child(&mut self) {- if let Some(pid) = self.pid {- kill_process_tree(pid);- }- if let Some(mut child) = self.child.take() {- let _ = child.kill();- let _ = child.wait();- }- self.pid = None;- }-- pub fn is_running(&self) -> bool {- self.child.is_some()- }-}--#[cfg(windows)]-fn kill_process_tree(pid: u32) {- let _ = Command::new("taskkill")- .args(["/PID", &pid.to_string(), "/T", "/F"])- .output();-}--#[cfg(unix)]-fn kill_process_tree(pid: u32) {- // The child was spawned as its own process-group leader, so a negative pid- // signals the whole group.- let _ = unsafe { libc::kill(-(pid as i32), libc::SIGTERM) };-}--// --- Node.js runtime helpers ---------------------------------------------------/// Map the current platform/arch to Node's official distribution naming.-fn node_platform_arch() -> Result<(String, String), String> {- let platform = env::consts::OS;- let arch = env::consts::ARCH;- let ext = if platform == "windows" { "zip" } else { "tar.gz" };- let name = match (platform, arch) {- ("macos", "aarch64") => "darwin-arm64",- ("macos", "x86_64") => "darwin-x64",- ("linux", "aarch64") => "linux-arm64",- ("linux", "x86_64") => "linux-x64",- ("windows", "x86_64" | "aarch64") => "win-x64",- _ => return Err(i18n::t("runtime.unsupported_platform")),- };- Ok((format!("node-{}-{name}.{ext}", NODEJS_VERSION), ext.to_string()))-}--/// Candidate download URLs (official first, npmmirror as fallback).-pub fn get_node_download_urls() -> Result<Vec<String>, String> {- let (file_name, _) = node_platform_arch()?;- let mut urls = vec![format!("{}{}/{}", NODEJS_BASE_URL, NODEJS_VERSION, file_name)];- urls.push(format!("{}{}/{}", NODEJS_NPMMIRROR_URL, NODEJS_VERSION, file_name));- Ok(urls)-}--/// Locate the node binary inside an extracted runtime directory.-pub fn get_node_binary_path(runtime_dir: PathBuf) -> PathBuf {- let candidates = if env::consts::OS == "windows" {- vec![runtime_dir.join("node.exe"), runtime_dir.join("bin/node.exe")]- } else {- vec![runtime_dir.join("bin/node"), runtime_dir.join("node")]- };- for candidate in candidates {- if candidate.exists() {- return candidate;- }- }- runtime_dir.join(if env::consts::OS == "windows" { "node.exe" } else { "bin/node" })-}--fn parse_node_version(output: &str) -> Option<(u64, u64, u64)> {- let version = output.trim().trim_start_matches('v');- let mut parts = version.split('.');- let major = parts.next()?.parse().ok()?;- let minor = parts.next()?.parse().ok()?;- let patch = parts.next()?.parse().ok()?;- Some((major, minor, patch))-}--/// Compatibility rule from the packaged harness: v22.15.0+ or v23.8.0+ (v24+ also fine).-fn is_supported_node_version(version: &str) -> bool {- let Some((major, minor, _patch)) = parse_node_version(version) else {- return false;- };- match major {- 22 => minor >= 15,- 23 => minor >= 8,- major if major >= 24 => true,- _ => false,- }-}--/// Run `node --version` and report whether it is compatible.-pub fn is_runtime_compatible(runtime_dir: &Path) -> bool {- let node = get_node_binary_path(runtime_dir.to_path_buf());- if !node.exists() {- return false;- }- let output = match Command::new(&node).arg("--version").output() {- Ok(out) => out,- Err(_) => return false,- };- if !output.status.success() {- return false;- }- let stdout = String::from_utf8_lossy(&output.stdout);- is_supported_node_version(stdout.trim())-}--/// The Node.js version bundled by the desktop app.-pub fn get_bundled_node_version() -> String {- NODEJS_VERSION.trim_start_matches('v').to_string()-}--// --- dsh service launch --------------------------------------------------------/// Spawn `dsh --profile web` with the bundled node binary.-///-/// `envs` may include `DSH_HOME` and other harness variables. `PATH` is-/// extended with the node binary directory so tools spawned by the harness can-/// find node.-pub fn start_dsh(- node_path: &Path,- entry_path: &Path,- cwd: &Path,- mut envs: HashMap<String, String>,- host: &str,- port: u16,- log_path: &Path,-) -> Result<(), String> {- if !node_path.exists() {- return Err(i18n::t("runtime.not_found"));- }- if !entry_path.exists() {- return Err(i18n::t("harness.core_not_found"));- }-- if let Some(node_dir) = node_path.parent() {- if let Some(existing_path) = env::var_os("PATH") {- let mut paths = vec![node_dir.to_path_buf()];- paths.extend(env::split_paths(&existing_path));- if let Ok(new_path) = env::join_paths(paths) {- envs.insert("PATH".to_string(), new_path.to_string_lossy().into_owned());- }- }- }-- fs::create_dir_all(log_path.parent().unwrap_or(Path::new(".")))- .map_err(|e| format!("create log dir failed: {e}"))?;- let log_file = fs::OpenOptions::new()- .create(true)- .append(true)- .open(log_path)- .map_err(|e| format!("open log file failed: {e}"))?;-- let mut command = Command::new(node_path);- command- .arg(entry_path)- .args(["--profile", "web", "--host", host, "--port", &port.to_string()])- .envs(&envs)- .current_dir(cwd)- .stdin(Stdio::null())- .stdout(Stdio::from(log_file.try_clone().map_err(|e| format!("clone log failed: {e}"))?))- .stderr(Stdio::from(log_file));-- #[cfg(windows)]- command.creation_flags(WINDOWS_CREATE_NO_WINDOW_FLAG);-- #[cfg(unix)]- {- use std::os::unix::process::CommandExt;- command.process_group(0);- }-- let child = command.spawn().map_err(|e| {- format!("{}: {e}", i18n::t("harness.start_failed"))- })?;-- let mut manager = PROCESS_MANAGER- .lock()- .map_err(|_| i18n::t("process.manager_poisoned"))?;- manager.kill_child();- manager.set_child(child);-- println!("[dsh] service launched (pid={:?})", manager.pid);- Ok(())-}diff --git a/src-tauri/src/services/mod.rs b/src-tauri/src/services/mod.rsdeleted file mode 100644index 2fc39ac0..00000000--- a/src-tauri/src/services/mod.rs+++ /dev/null@@ -1,2 +0,0 @@-pub mod downloader;-pub mod manager;diff --git a/src-tauri/src/task/mod.rs b/src-tauri/src/task/mod.rsnew file mode 100644index 00000000..69627ded--- /dev/null+++ b/src-tauri/src/task/mod.rs@@ -0,0 +1 @@+pub mod tick_check_dsh_process;diff --git a/src-tauri/src/task/tick_check_dsh_process/mod.rs b/src-tauri/src/task/tick_check_dsh_process/mod.rsnew file mode 100644index 00000000..4577a872--- /dev/null+++ b/src-tauri/src/task/tick_check_dsh_process/mod.rs@@ -0,0 +1,23 @@+use crate::service::workflow::{+ status::{self, Status},+ utils,+};+use tauri::AppHandle;++/// 检测 dsh 进程状态并更新+///+/// 使用 HTTP 请求检测 Harness 服务是否真正就绪,就绪后更新全局状态+pub async fn trigger(app_handle: AppHandle) -> Result<(), Box<dyn std::error::Error>> {+ let current_status = status::get_status();++ let is_dsh_running = utils::is_dsh_running().await;+ log::trace!("DSH status check: dsh_running={}", is_dsh_running);++ // 只有当当前状态为运行中时,才更新状态+ if is_dsh_running && current_status != Status::Running {+ status::set_status(Status::Running);+ status::emit_status(&app_handle);+ }++ Ok(())+}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 07358816..6fd59436 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -24,8 +24,7 @@],"security": {"csp": "default-src 'self'; connect-src 'self' http://127.0.0.1:* ws://127.0.0.1:*; frame-src http://127.0.0.1:*; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self'"- },- "macOSPrivateApi": true+ }},"bundle": {"active": true,