Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat: first-run wizard to install recommended plugins

hairyf0629d7cadb3d
diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rs
index 3a9d7072..b2faf84e 100644
--- a/src-tauri/src/bridge/cmd.rs
+++ b/src-tauri/src/bridge/cmd.rs
@@ -1,6 +1,7 @@
use crate::config;
use crate::service::cli;
use crate::service::download::{self, Installable};
+use crate::service::plugin;
use crate::service::workflow;
use tauri::{AppHandle, Manager};
use tauri_plugin_clipboard_manager::ClipboardExt;
@@ -119,6 +120,47 @@ pub fn get_dsh_status() -> workflow::status::Status {
workflow::status::get_status()
}
+/// 获取预装插件列表(含已安装检测结果),首次启动引导界面渲染用
+#[tauri::command]
+pub async fn get_preinstall_plugins(
+ app_handle: AppHandle,
+) -> Result<Vec<plugin::PreinstallPlugin>, String> {
+ Ok(plugin::list(&app_handle))
+}
+
+/// 安装选中的预装插件(`dsh plugin --profile web add <ids...>`),
+/// 进程输出实时通过 `preinstall-log` 事件推送;成功后标记引导完成。
+#[tauri::command]
+pub async fn install_preinstall_plugins(
+ app_handle: AppHandle,
+ ids: Vec<String>,
+) -> Result<(), String> {
+ plugin::install(&app_handle, &ids).await?;
+ let mut setting = config::get_store_dat_setting(&app_handle);
+ setting.preinstall_done = true;
+ config::set_store_dat_setting(&app_handle, setting);
+ Ok(())
+}
+
+/// 跳过预装插件引导:仅记录状态,不再弹出
+#[tauri::command]
+pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String> {
+ let mut setting = config::get_store_dat_setting(&app_handle);
+ setting.preinstall_done = true;
+ config::set_store_dat_setting(&app_handle, setting);
+ Ok(())
+}
+
+/// 在系统浏览器中打开预装插件的仓库地址(仅允许预装清单内的 id)
+#[tauri::command]
+pub async fn open_preinstall_repo(app_handle: AppHandle, id: String) -> Result<(), String> {
+ let url = plugin::repo_url_of(&id).ok_or_else(|| format!("PREINSTALL_INVALID_ID: {id}"))?;
+ app_handle
+ .opener()
+ .open_url(url, None::<&str>)
+ .map_err(|e| e.to_string())
+}
+
/// 健康检查(通过 Rust 代理,避免 WebView CORS 问题)
#[tauri::command]
pub async fn proxy_health_check(app_handle: AppHandle) -> Result<String, String> {
diff --git a/src-tauri/src/config/setting.rs b/src-tauri/src/config/setting.rs
index 7a61b96d..a9cbfecc 100644
--- a/src-tauri/src/config/setting.rs
+++ b/src-tauri/src/config/setting.rs
@@ -15,6 +15,9 @@ pub struct Setting {
/// 命令行集成开关:安装后在用户 PATH 中注册 `dsh` 命令
#[serde(default = "default_cli_link_enabled")]
pub cli_link_enabled: bool,
+ /// 预装插件引导是否已完成(确认安装或跳过都算完成,之后不再弹出)
+ #[serde(default)]
+ pub preinstall_done: bool,
}
/// 命令行集成默认开启(开发者工具场景,安装完成即可用)
@@ -31,6 +34,7 @@ impl Default for Setting {
language: "zh-CN".to_string(),
dsh_pkg_commit: None,
cli_link_enabled: default_cli_link_enabled(),
+ preinstall_done: false,
}
}
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 4d0d49c0..6c8ef3dd 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -120,6 +120,10 @@ fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
bridge::cmd::shutdown_harness,
bridge::cmd::restart_harness,
bridge::cmd::get_dsh_status,
+ bridge::cmd::get_preinstall_plugins,
+ bridge::cmd::install_preinstall_plugins,
+ bridge::cmd::skip_preinstall_plugins,
+ bridge::cmd::open_preinstall_repo,
bridge::cmd::proxy_health_check,
bridge::cmd::get_runtime_info,
bridge::cmd::get_app_config,
diff --git a/src-tauri/src/service/cli/core.rs b/src-tauri/src/service/cli/core.rs
index a14f6084..1c3ae425 100644
--- a/src-tauri/src/service/cli/core.rs
+++ b/src-tauri/src/service/cli/core.rs
@@ -58,6 +58,17 @@ pub fn ensure(app_handle: &AppHandle) -> Result<CliLinkStatus, String> {
Ok(get_status(app_handle))
}
+/// 仅确保 shim 文件存在(写入 bin 目录,不注册用户 PATH)。
+///
+/// 供预装插件等应用内部流程使用:需要 `pnpm`/`dsh` 可被子进程解析,
+/// 但不希望改动用户的 PATH 注册(避免与"命令行集成"开关状态不一致)。
+pub fn ensure_shims(app_handle: &AppHandle) -> Result<(), String> {
+ let bin_dir = get_bin_dir(app_handle);
+ write_shims(app_handle, &bin_dir)?;
+ log::info!("dsh/pnpm shims ensured at {}", bin_dir.display());
+ Ok(())
+}
+
/// 禁用并清理命令行集成(删除 shim + 移除 PATH 注册)
pub fn remove(app_handle: &AppHandle) -> Result<CliLinkStatus, String> {
let bin_dir = get_bin_dir(app_handle);
diff --git a/src-tauri/src/service/cli/mod.rs b/src-tauri/src/service/cli/mod.rs
index 271c4f4d..a7827569 100644
--- a/src-tauri/src/service/cli/mod.rs
+++ b/src-tauri/src/service/cli/mod.rs
@@ -24,5 +24,5 @@ mod core;
mod path;
mod shim;
-pub use core::{ensure, get_status, remove, CliLinkStatus};
-pub use path::find_user_pnpm;
+pub use core::{ensure, ensure_shims, get_status, remove, CliLinkStatus};
+pub use path::{find_user_pnpm, get_bin_dir};
diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rs
index e0ba936d..bff4b931 100644
--- a/src-tauri/src/service/mod.rs
+++ b/src-tauri/src/service/mod.rs
@@ -1,4 +1,5 @@
pub mod cli;
pub mod download;
+pub mod plugin;
pub mod scheduler;
pub mod workflow;
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
new file mode 100644
index 00000000..dc286a32
--- /dev/null
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -0,0 +1,390 @@
+//! 预装插件:首次启动引导安装官方推荐插件(当前为 DSH Market)。
+//!
+//! 安装通过 `dsh plugin --profile web add <pkg>` 完成:该子命令是 pnpm 转发器,
+//! 会在 `$DSH_HOME/profiles/web` 初始化 profile 并执行 `pnpm add`,随后把声明了
+//! `dsh.bundle` 的依赖写入 profile 的 bundles 层,使插件在下次启动时加载。
+//! 进程输出逐行通过 `preinstall-log` 事件实时推送给前端日志面板。
+//!
+//! 新增预装插件只需往 [`PREINSTALL`] 静态清单追加一项,界面与安装逻辑自动生效。
+
+use crate::config;
+use crate::service::cli;
+use crate::service::workflow;
+use serde::Serialize;
+use std::collections::{HashMap, HashSet};
+use std::ffi::OsString;
+use std::io::{BufRead, BufReader, Read};
+use std::path::PathBuf;
+#[cfg(not(windows))]
+use std::process::{Command, Stdio};
+use tauri::{AppHandle, Emitter, Manager, WebviewWindow};
+
+/// Windows 进程句柄包装:原始句柄是 `*mut c_void`(非 Send),
+/// 但 `WaitForSingleObject`/`GetExitCodeProcess` 均为线程安全的系统调用,
+/// 包一层以安全地移入 `spawn_blocking` 等待进程退出。
+#[cfg(windows)]
+struct WaitableHandle(windows_sys::Win32::Foundation::HANDLE);
+
+#[cfg(windows)]
+unsafe impl Send for WaitableHandle {}
+
+/// 预装插件安装到的 profile(与 dsh 服务启动的 profile 一致)
+const PREINSTALL_PROFILE: &str = "web";
+
+/// 前端监听的控制台事件名(进程输出行)
+const PREINSTALL_LOG_EVENT: &str = "preinstall-log";
+
+/// 预装插件静态清单:以后新增预装插件在此追加,界面与安装逻辑自动渲染。
+/// `id` 为传给 `dsh plugin add` 的包名(npm 包名或 git 依赖形式)。
+const PREINSTALL: &[PreinstallPluginInfo] = &[PreinstallPluginInfo {
+ id: "dshmarket",
+ name: "DSH Market",
+ description:
+ "Visual plugin market inside DeepSeek Harness — browse, search, and one-click install community plugins. · DSH 可视化插件市场:逛一逛,点一下,装好。",
+ repo_url: "https://github.com/dsh-market/dsh-market",
+ recommended: true,
+}];
+
+/// 预装插件静态信息(不含运行时检测的 installed 状态)
+struct PreinstallPluginInfo {
+ id: &'static str,
+ name: &'static str,
+ description: &'static str,
+ repo_url: &'static str,
+ recommended: bool,
+}
+
+/// 预装插件列表项(含已安装检测结果),序列化给前端
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PreinstallPlugin {
+ pub id: String,
+ pub name: String,
+ pub description: String,
+ pub repo_url: String,
+ pub recommended: bool,
+ pub installed: bool,
+}
+
+/// 进程输出行事件载荷
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PreinstallLogPayload {
+ pub line: String,
+}
+
+/// id 是否属于预装清单(安装与打开仓库前均需校验,避免执行任意包名)
+pub fn is_known_id(id: &str) -> bool {
+ PREINSTALL.iter().any(|p| p.id == id)
+}
+
+/// 预装清单中某 id 对应的仓库地址
+pub fn repo_url_of(id: &str) -> Option<&'static str> {
+ PREINSTALL.iter().find(|p| p.id == id).map(|p| p.repo_url)
+}
+
+/// 预装插件所在的 profile 目录($DSH_HOME/profiles/web)
+fn profile_dir(app_handle: &AppHandle) -> PathBuf {
+ config::get_dsh_data_path(app_handle)
+ .join("profiles")
+ .join(PREINSTALL_PROFILE)
+}
+
+/// 已安装的插件 id 集合:读取 profile 清单的 `dependencies` 键与 `bundles` 列表。
+/// profile 尚未初始化(未安装过任何插件)时视为空集合。
+fn list_installed(app_handle: &AppHandle) -> HashSet<String> {
+ let manifest_path = profile_dir(app_handle).join("package.json");
+ let Ok(content) = std::fs::read_to_string(&manifest_path) else {
+ return HashSet::new();
+ };
+ let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&content) else {
+ return HashSet::new();
+ };
+ let mut set = HashSet::new();
+ if let Some(deps) = manifest
+ .get("dependencies")
+ .and_then(serde_json::Value::as_object)
+ {
+ set.extend(deps.keys().cloned());
+ }
+ if let Some(bundles) = manifest
+ .get("dsh")
+ .and_then(|v| v.get("profile"))
+ .and_then(|v| v.get("bundles"))
+ .and_then(serde_json::Value::as_array)
+ {
+ for item in bundles {
+ if let Some(name) = item.as_str() {
+ set.insert(name.to_string());
+ }
+ }
+ }
+ set
+}
+
+/// 预装插件列表(含 installed 状态),前端渲染用
+pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {
+ let installed = list_installed(app_handle);
+ PREINSTALL
+ .iter()
+ .map(|p| PreinstallPlugin {
+ id: p.id.to_string(),
+ name: p.name.to_string(),
+ description: p.description.to_string(),
+ repo_url: p.repo_url.to_string(),
+ recommended: p.recommended,
+ installed: installed.contains(p.id),
+ })
+ .collect()
+}
+
+/// 校验并安装选中的预装插件:`dsh plugin --profile web add <ids...>`,
+/// 进程输出逐行通过 `preinstall-log` 事件转发给前端日志面板。
+pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), String> {
+ if ids.is_empty() {
+ return Err("PREINSTALL_EMPTY: no plugins selected".to_string());
+ }
+ for id in ids {
+ if !is_known_id(id) {
+ return Err(format!("PREINSTALL_INVALID_ID: {id}"));
+ }
+ }
+
+ // 确保 pnpm/dsh shim 存在(只落盘文件、不注册用户 PATH),
+ // 让 dsh plugin 内部转发的 `pnpm` 在子进程 PATH 中可解析。
+ cli::ensure_shims(app_handle)?;
+
+ let node = config::get_node_binary_path(app_handle);
+ let dsh_bin = config::get_dsh_binary_path(app_handle);
+ if !node.exists() {
+ return Err("NODE_NOT_FOUND: Node.js runtime missing".to_string());
+ }
+ if !dsh_bin.exists() {
+ return Err("HARNESS_NOT_FOUND: dsh CLI missing".to_string());
+ }
+
+ // 新增/变更 bundle 需要服务重启才会加载:安装前先停掉正在运行的服务,
+ // 后续 launch 会以全新进程加载新插件(首次安装场景服务尚未启动,跳过)。
+ if workflow::utils::is_dsh_running().await {
+ log::info!("Stopping running harness service before installing preinstall plugins");
+ if let Err(e) = workflow::stop(app_handle.clone()).await {
+ log::warn!("failed to stop harness before preinstall: {e}");
+ }
+ }
+
+ let window = app_handle
+ .get_webview_window("main")
+ .ok_or("WINDOW_NOT_FOUND: main window missing")?;
+
+ // 子进程环境:DSH_HOME 指向应用数据目录,PATH 前置 shim 与 node 目录,
+ // 关闭颜色输出让日志面板保持纯文本。
+ let bin_dir = cli::get_bin_dir(app_handle);
+ let mut envs: HashMap<String, String> = HashMap::new();
+ envs.insert(
+ "DSH_HOME".to_string(),
+ config::get_dsh_data_path(app_handle)
+ .to_string_lossy()
+ .into_owned(),
+ );
+ envs.insert("DSH_TELEMETRY_DISABLED".to_string(), "1".to_string());
+ envs.insert("NO_COLOR".to_string(), "1".to_string());
+ let mut paths = vec![bin_dir];
+ if let Some(node_dir) = node.parent() {
+ paths.push(node_dir.to_path_buf());
+ }
+ paths.extend(std::env::split_paths(
+ &std::env::var_os("PATH").unwrap_or_default(),
+ ));
+ if let Ok(joined) = std::env::join_paths(paths) {
+ envs.insert("PATH".to_string(), joined.to_string_lossy().into_owned());
+ }
+
+ // 命令:`node <dsh_bin.js> plugin --profile web add <ids...>`
+ // 注意脚本路径必须是第一个参数(node 会把首个非选项参数当作脚本加载,
+ // 漏掉它会出现 `Cannot find module '.../dependencies/dsh/plugin'`)。
+ let mut args: Vec<OsString> = vec![dsh_bin.as_os_str().to_os_string()];
+ args.extend([
+ OsString::from("plugin"),
+ OsString::from("--profile"),
+ OsString::from(PREINSTALL_PROFILE),
+ OsString::from("add"),
+ ]);
+ args.extend(ids.iter().map(OsString::from));
+
+ let cwd = config::get_dsh_install_path(app_handle);
+ log::info!("Running dsh plugin install for {ids:?}");
+
+ let exit_code = run_plugin_process(&node, &args, &cwd, &envs, &window).await?;
+ if exit_code != 0 {
+ log::error!("dsh plugin install failed with exit code {exit_code}");
+ return Err(format!(
+ "PREINSTALL_FAILED: dsh plugin exited with code {exit_code}"
+ ));
+ }
+
+ log::info!("Preinstall plugins installed successfully: {ids:?}");
+ Ok(())
+}
+
+/// 启动 `dsh plugin` 进程并等待结束,返回退出码;输出实时转发事件。
+async fn run_plugin_process(
+ node: &std::path::Path,
+ args: &[OsString],
+ cwd: &std::path::Path,
+ envs: &HashMap<String, String>,
+ window: &WebviewWindow,
+) -> Result<i32, String> {
+ #[cfg(windows)]
+ {
+ let (stdout, stderr, handle) =
+ workflow::win_spawn::spawn_with_hidden_console_tracked(node, args, Some(cwd), envs)
+ .map_err(|e| format!("PREINSTALL_SPAWN: {e}"))?;
+ spawn_line_emitter(Box::new(stdout), window.clone());
+ spawn_line_emitter(Box::new(stderr), window.clone());
+
+ let handle = WaitableHandle(handle);
+ let exit_code = tauri::async_runtime::spawn_blocking(move || {
+ use windows_sys::Win32::Foundation::CloseHandle;
+ use windows_sys::Win32::System::Threading::{
+ GetExitCodeProcess, WaitForSingleObject, INFINITE,
+ };
+ // 整体 move 包装结构(而非其字段),确保闭包按包装类型捕获(Send)
+ let handle = handle;
+ unsafe {
+ let wait = WaitForSingleObject(handle.0, INFINITE);
+ let mut code: u32 = 0;
+ if GetExitCodeProcess(handle.0, &mut code) == 0 {
+ code = wait;
+ }
+ CloseHandle(handle.0);
+ code as i32
+ }
+ })
+ .await
+ .map_err(|e| format!("PREINSTALL_WAIT: {e}"))?;
+
+ // 读取线程会在进程及其后代关闭管道写端后读到 EOF,稍等片刻避免遗漏尾部日志
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ Ok(exit_code)
+ }
+
+ #[cfg(not(windows))]
+ {
+ let mut child = Command::new(node)
+ .args(args)
+ .envs(envs)
+ .current_dir(cwd)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|e| format!("PREINSTALL_SPAWN: {e}"))?;
+ if let Some(stdout) = child.stdout.take() {
+ spawn_line_emitter(Box::new(stdout), window.clone());
+ }
+ if let Some(stderr) = child.stderr.take() {
+ spawn_line_emitter(Box::new(stderr), window.clone());
+ }
+
+ let exit_code = tauri::async_runtime::spawn_blocking(move || {
+ let status = child
+ .wait()
+ .ok()
+ .map(|s| s.code().unwrap_or(1))
+ .unwrap_or(1);
+ status
+ })
+ .await
+ .map_err(|e| format!("PREINSTALL_WAIT: {e}"))?;
+
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ Ok(exit_code)
+ }
+}
+
+/// 在独立线程中逐行读取进程输出并通过 `preinstall-log` 事件转发。
+/// `std::process` 的 stdout/stderr 读取端实现了 `Read + Send`,
+/// 两种平台实现(File / ChildStdout)统一装箱处理。
+fn spawn_line_emitter(reader: Box<dyn Read + Send>, window: WebviewWindow) {
+ std::thread::spawn(move || {
+ let buf = BufReader::new(reader);
+ for line in buf.lines() {
+ let Ok(line) = line else { break };
+ let _ = window.emit(
+ PREINSTALL_LOG_EVENT,
+ PreinstallLogPayload {
+ line: line.trim_end().to_string(),
+ },
+ );
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn static_list_contains_dshmarket() {
+ assert!(is_known_id("dshmarket"));
+ assert_eq!(
+ repo_url_of("dshmarket"),
+ Some("https://github.com/dsh-market/dsh-market")
+ );
+ assert!(!is_known_id("unknown-package"));
+ }
+
+ #[test]
+ fn list_installed_parses_manifest() {
+ // 构造临时 profile 清单并校验依赖/bundles 解析
+ let dir = std::env::temp_dir().join(format!("dsh-plugin-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let manifest = serde_json::json!({
+ "name": "dsh-profile-web",
+ "private": true,
+ "dependencies": {
+ "dshmarket": "1.0.0",
+ "@deepseek-ai/dsh-base": "1.0.0"
+ },
+ "dsh": {
+ "profile": {
+ "bundles": ["@deepseek-ai/dsh-base", "dshmarket"]
+ }
+ }
+ });
+ std::fs::write(
+ dir.join("package.json"),
+ serde_json::to_string(&manifest).unwrap(),
+ )
+ .unwrap();
+
+ // 直接调用内部解析逻辑(list_installed 依赖 AppHandle,仅测解析函数)
+ let content = std::fs::read_to_string(dir.join("package.json")).unwrap();
+ let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
+ let mut set = HashSet::new();
+ if let Some(deps) = parsed
+ .get("dependencies")
+ .and_then(serde_json::Value::as_object)
+ {
+ set.extend(deps.keys().cloned());
+ }
+ if let Some(bundles) = parsed
+ .get("dsh")
+ .and_then(|v| v.get("profile"))
+ .and_then(|v| v.get("bundles"))
+ .and_then(serde_json::Value::as_array)
+ {
+ for item in bundles {
+ if let Some(name) = item.as_str() {
+ set.insert(name.to_string());
+ }
+ }
+ }
+
+ assert!(set.contains("dshmarket"));
+ assert!(set.contains("@deepseek-ai/dsh-base"));
+ assert_eq!(set.len(), 2);
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/src-tauri/src/service/workflow/win_spawn.rs b/src-tauri/src/service/workflow/win_spawn.rs
index ae602bbe..56659dd6 100644
--- a/src-tauri/src/service/workflow/win_spawn.rs
+++ b/src-tauri/src/service/workflow/win_spawn.rs
@@ -7,8 +7,7 @@
//!
//! 这里改用 `CREATE_NEW_CONSOLE` + `STARTF_USESHOWWINDOW`/`SW_HIDE` 给 node
//! 分配一个隐藏的控制台:node 及其所有后代进程共享这个隐藏控制台,不再弹窗。
-
-#![cfg(windows)]
+//! 模块声明处已按 `#[cfg(windows)]` 门控,仅在 Windows 构建中编译。
use std::collections::HashMap;
use std::ffi::OsString;
@@ -42,6 +41,22 @@ pub fn spawn_with_hidden_console(
current_dir: Option<&Path>,
envs: &HashMap<String, String>,
) -> io::Result<(File, File)> {
+ let (stdout, stderr, handle) =
+ spawn_with_hidden_console_tracked(program, args, current_dir, envs)?;
+ unsafe {
+ CloseHandle(handle);
+ }
+ Ok((stdout, stderr))
+}
+
+/// 同 [`spawn_with_hidden_console`],但额外返回进程句柄,供调用方等待进程
+/// 结束并读取退出码(预装插件安装等需要判断成败的场景)。
+pub fn spawn_with_hidden_console_tracked(
+ program: &Path,
+ args: &[OsString],
+ current_dir: Option<&Path>,
+ envs: &HashMap<String, String>,
+) -> io::Result<(File, File, HANDLE)> {
unsafe {
// 1. 创建 stdout / stderr 匿名管道(写端可继承,交给子进程)
let pipe_attrs = SECURITY_ATTRIBUTES {
@@ -142,13 +157,13 @@ pub fn spawn_with_hidden_console(
return Err(io::Error::last_os_error());
}
- // 进程句柄不再需要(停止服务时按端口清理),关闭避免泄漏
+ // 进程句柄不再需要时由调用方负责关闭(tracked 调用方等待退出后关闭;
+ // 非 tracked 由包装函数立即关闭)。关闭线程句柄避免泄漏
CloseHandle(process_info.hThread);
- CloseHandle(process_info.hProcess);
let stdout = File::from_raw_handle(stdout_read as RawHandle);
let stderr = File::from_raw_handle(stderr_read as RawHandle);
- Ok((stdout, stderr))
+ Ok((stdout, stderr, process_info.hProcess))
}
}
diff --git a/src/components/debug-sidebar.tsx b/src/components/debug-sidebar.tsx
index 2be7efed..12f5e847 100644
--- a/src/components/debug-sidebar.tsx
+++ b/src/components/debug-sidebar.tsx
@@ -77,7 +77,7 @@ function InfoRow({ term, children }: { term: string, children: ReactNode }) {
export default function DebugSidebar() {
const { t, i18n } = useTranslation()
const { sidebarOpen } = useStore(setting)
- const { serviceRunning, busyAction } = useStore(harness)
+ const { serviceRunning, busyAction, preinstall } = useStore(harness)
const [info, setInfo] = useState<RuntimeInfo | null>(null)
const [cliLinkEnabled, setCliLinkEnabled] = useState(true)
const [port, setPort] = useState(3080)
@@ -466,6 +466,21 @@ export default function DebugSidebar() {
</div>
</SectionCard>
+ {/* 预装插件(重新打开预设引导) */}
+ <SectionCard>
+ <SectionTitle>{t('preinstall.settings_title')}</SectionTitle>
+ <p className="text-xs leading-relaxed text-muted">{t('preinstall.settings_hint')}</p>
+ <Button
+ size="sm"
+ variant="primary"
+ className="rounded-md"
+ onPress={harness.openPreinstall}
+ isDisabled={busyAction !== null || preinstall.installing}
+ >
+ {t('preinstall.open_preset')}
+ </Button>
+ </SectionCard>
+
{/* 日志 */}
<SectionCard>
<SectionTitle
diff --git a/src/components/harness-webview.tsx b/src/components/harness-webview.tsx
index bf27fc94..8dfc896b 100644
--- a/src/components/harness-webview.tsx
+++ b/src/components/harness-webview.tsx
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next'
import { useStore } from 'valtio-define'
import { harness } from '../store/modules/harness'
import Loadable from './loadable'
+import PreinstallSetup from './preinstall-setup'
import Setup from './setup'
/**
@@ -30,6 +31,15 @@ export default function HarnessWebview() {
)
}
+ // 预装插件引导:独立于安装/加载界面,渲染推荐插件列表与安装控制台
+ if (status === 'preinstall') {
+ return (
+ <main className="relative w-full bg-canvas">
+ <PreinstallSetup />
+ </main>
+ )
+ }
+
if (status !== 'ready') {
return (
<main className="relative w-full bg-canvas">
diff --git a/src/components/preinstall-setup.tsx b/src/components/preinstall-setup.tsx
new file mode 100644
index 00000000..818d67a7
--- /dev/null
+++ b/src/components/preinstall-setup.tsx
@@ -0,0 +1,239 @@
+import type { PreinstallPlugin } from '../store/modules/harness'
+import { CircleInfo } from '@gravity-ui/icons'
+import { Button, Card, Checkbox, Chip } from '@heroui/react'
+import { invoke } from '@tauri-apps/api/core'
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { If } from 'react-if-lite'
+import { useStore } from 'valtio-define'
+import { harness } from '../store/modules/harness'
+
+/**
+ * 预装插件引导页:首次安装(或老版本升级)后展示推荐插件列表,
+ * 用户确认后调用 `dsh plugin` 安装(日志实时回流到控制台),
+ * 或跳过;两者都会标记完成并继续启动服务。
+ */
+
+/** 插件列表的一行:勾选框 + 名称 + 推荐/已安装标签 + 仓库跳转按钮 */
+function PluginRow({ plugin, checked, disabled, onToggle, onOpenRepo }: {
+ plugin: PreinstallPlugin
+ checked: boolean
+ disabled: boolean
+ onToggle: (id: string, checked: boolean) => void
+ onOpenRepo: (id: string) => void
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex items-center justify-between gap-3 border-b border-line/40 px-4 py-3 last:border-b-0">
+ <Checkbox
+ isSelected={checked || plugin.installed}
+ isDisabled={disabled || plugin.installed}
+ onChange={isSelected => onToggle(plugin.id, isSelected)}
+ className="min-w-0 flex-1"
+ >
+ <Checkbox.Content className="min-w-0">
+ <Checkbox.Control className="bg-panel2 rounded-md">
+ <Checkbox.Indicator className="rounded-md" />
+ </Checkbox.Control>
+ <span className="min-w-0">
+ <span className={`flex min-w-0 items-center gap-2 text-sm font-medium ${plugin.installed ? 'text-muted line-through' : 'text-ink'}`}>
+ <span className="truncate">{plugin.name}</span>
+ <If cond={plugin.recommended && !plugin.installed}>
+ <Chip size="sm" variant="soft" color="success" className="font-medium">
+ {t('preinstall.recommend')}
+ </Chip>
+ </If>
+ <If cond={plugin.installed}>
+ <Chip size="sm" variant="soft" color="success" className="font-medium">
+ {t('preinstall.installed')}
+ </Chip>
+ </If>
+ </span>
+ </span>
+ </Checkbox.Content>
+ </Checkbox>
+ <Button
+ isIconOnly
+ size="sm"
+ variant="ghost"
+ className="shrink-0 rounded-md"
+ aria-label={t('preinstall.open_repo', { name: plugin.name })}
+ onPress={() => onOpenRepo(plugin.id)}
+ >
+ <CircleInfo className="size-4" />
+ </Button>
+ </div>
+ )
+}
+
+/** 日志控制台:dsh plugin 进程输出,样式与安装/加载页日志面板一致 */
+function LogPanel({ logs }: { logs: readonly string[] }) {
+ const { t } = useTranslation()
+
+ return (
+ <div
+ className="max-h-[240px] min-h-[112px] overflow-y-auto rounded-lg border border-line bg-log-bg px-3.5 py-2.5 text-left font-mono text-xs leading-[1.7]"
+ aria-label={t('ui.install_log')}
+ >
+ <If cond={logs.length > 0} else={<p className="m-0 text-load-muted">{t('ui.waiting_logs')}</p>}>
+ {logs.slice(-100).map((line, index) => (
+ // 日志行内容可能重复,以 index 区分 key
+ // eslint-disable-next-line react/no-array-index-key
+ <p key={`${line}-${index}`} className="m-0 flex gap-2 overflow-hidden text-ellipsis whitespace-nowrap text-log-ink">
+ <span className="shrink-0 text-accent select-none">›</span>
+ <span className="min-w-0 overflow-hidden text-ellipsis">{line}</span>
+ </p>
+ ))}
+ </If>
+ </div>
+ )
+}
+
+export default function PreinstallSetup() {
+ const { t } = useTranslation()
+ const { preinstall } = useStore(harness)
+ // 用户手动调整后的选择(一旦交互即接管默认勾选)
+ const [selected, setSelected] = useState<Set<string>>(() => new Set())
+ const [touched, setTouched] = useState(false)
+
+ // 进入引导页时拉取插件列表
+ useEffect(() => {
+ void harness.loadPreinstallPlugins()
+ }, [])
+
+ // 默认勾选:未安装的推荐插件(当前即 DSH Market)。
+ // 派生计算而非在加载回调里 setState,避免与 store 的加载去重守卫竞争,
+ // 保证插件到位后默认勾选必定生效(用户手动调整后以用户选择为准)。
+ const effectiveSelected = !touched
+ ? new Set(preinstall.plugins.filter(p => !p.installed && p.recommended).map(p => p.id))
+ : selected
+
+ function toggle(id: string, checked: boolean) {
+ setTouched(true)
+ setSelected((prev) => {
+ const next = new Set(prev)
+ if (checked) {
+ next.add(id)
+ }
+ else {
+ next.delete(id)
+ }
+ return next
+ })
+ }
+
+ function openRepo(id: string) {
+ void invoke('open_preinstall_repo', { id }).catch((err) => {
+ console.error('[Harness] open preinstall repo failed:', err)
+ })
+ }
+
+ function handleConfirm() {
+ void harness.confirmPreinstall([...effectiveSelected])
+ }
+
+ function handleSkip() {
+ void harness.skipPreinstall()
+ }
+
+ // 可选中的插件(未安装项)勾选数,用于禁用"确定"
+ const selectableCount = preinstall.plugins.filter(p => !p.installed).length
+ const selectedCount = [...effectiveSelected].filter(id => preinstall.plugins.some(p => p.id === id && !p.installed)).length
+ const installing = preinstall.installing
+
+ return (
+ <div className="flex h-full w-full items-center justify-center bg-canvas">
+ <div className="flex w-[min(560px,88vw)] flex-col gap-5">
+ <header className="flex flex-col items-center gap-1.5 text-center">
+ <h1 className="text-base font-semibold tracking-[0.08em] text-load-ink">{t('preinstall.title')}</h1>
+ <p className="max-w-[440px] text-xs leading-5 text-load-muted">{t('preinstall.subtitle')}</p>
+ </header>
+
+ <If
+ cond={installing}
+ else={(
+ // 安装失败时不叠加插件列表,只展示错误 + 日志 + 重试/跳过
+ <If
+ cond={preinstall.error !== ''}
+ else={(
+ <>
+ {/* 插件列表 */}
+ <Card className="p-0 rounded-md">
+ <If
+ cond={preinstall.plugins.length > 0}
+ else={(
+ <p className="text-center text-xs text-load-muted">{t('preinstall.empty')}</p>
+ )}
+ >
+ {preinstall.plugins.map(plugin => (
+ <PluginRow
+ key={plugin.id}
+ plugin={plugin}
+ checked={effectiveSelected.has(plugin.id)}
+ disabled={installing}
+ onToggle={toggle}
+ onOpenRepo={openRepo}
+ />
+ ))}
+ </If>
+ </Card>
+
+ {/* 操作区:跳过 / 确定 */}
+ <div className="flex items-center justify-end gap-2">
+ <Button className="rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing}>
+ {t('preinstall.skip')}
+ </Button>
+ <Button
+ className="rounded-md"
+ size="sm"
+ variant="primary"
+ onPress={handleConfirm}
+ isDisabled={installing || selectedCount === 0 || selectableCount === 0}
+ >
+ {t('preinstall.confirm')}
+ </Button>
+ </div>
+ </>
+ )}
+ >
+ {/* 安装失败:错误信息 + 日志 + 操作 */}
+ <div className="flex flex-col gap-2.5">
+ <div className="flex flex-col gap-2 rounded-lg border border-danger/30 bg-danger/5 px-3.5 py-3">
+ <p className="text-xs font-medium text-danger">{t('preinstall.failed')}</p>
+ <p className="max-h-[120px] overflow-y-auto break-all font-mono text-[11px] leading-relaxed text-load-muted">
+ {preinstall.error}
+ </p>
+ </div>
+ <LogPanel logs={preinstall.logs} />
+ <div className="flex items-center justify-end gap-2">
+ <Button className="rounded-md" size="sm" variant="tertiary" onPress={handleSkip} isDisabled={installing}>
+ {t('preinstall.skip')}
+ </Button>
+ <Button
+ className="rounded-md"
+ size="sm"
+ variant="primary"
+ onPress={handleConfirm}
+ isDisabled={installing || selectedCount === 0 || selectableCount === 0}
+ >
+ {t('app.retry')}
+ </Button>
+ </div>
+ </div>
+ </If>
+ )}
+ >
+ {/* 安装中:与 Loadable 加载页一致的指示样式(spinner 在上、文案在下,图标旁不加文字) */}
+ <div className="flex flex-col gap-2.5">
+ <div className="flex flex-col items-center gap-3">
+ <span className="h-5 w-5 animate-load-spin rounded-full border-2 border-load-ring border-t-load-ink" />
+ <p className="text-xs leading-[18px] text-load-muted">{t('preinstall.installing')}</p>
+ </div>
+ <LogPanel logs={preinstall.logs} />
+ </div>
+ </If>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/setup.tsx b/src/components/setup.tsx
index 1c304849..954c01c8 100644
--- a/src/components/setup.tsx
+++ b/src/components/setup.tsx
@@ -1,6 +1,6 @@
import type { SetupStatus } from '../store/modules/harness'
import type { IconComponent } from './loadable'
-import { ArrowDownToLine, CircleCheck, CircleExclamation, Magnifier, Rocket } from '@gravity-ui/icons'
+import { ArrowDownToLine, CircleCheck, CircleExclamation, CircleInfo, Magnifier, Rocket } from '@gravity-ui/icons'
import { useTranslation } from 'react-i18next'
import { useStore } from 'valtio-define'
import { harness } from '../store/modules/harness'
@@ -11,6 +11,7 @@ const STATUS_ICONS: Record<SetupStatus, IconComponent> = {
checking: Magnifier,
installing: ArrowDownToLine,
starting: Rocket,
+ preinstall: CircleInfo,
ready: CircleCheck,
error: CircleExclamation,
}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index f9e8a5cd..cc12e2bc 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -24,6 +24,20 @@
"status.loading": "Loading plugins…",
"status.loading_plugins": "Loading plugins…",
+ "preinstall.title": "Install recommended plugins",
+ "preinstall.subtitle": "Choose which plugins to install before starting. You can manage them later from Settings → Plugin Market.",
+ "preinstall.recommend": "Recommended",
+ "preinstall.installed": "Installed",
+ "preinstall.confirm": "Install",
+ "preinstall.skip": "Skip",
+ "preinstall.installing": "Installing plugins...",
+ "preinstall.open_repo": "Open repository of {{name}}",
+ "preinstall.failed": "Installation failed",
+ "preinstall.empty": "No preinstalled plugins available.",
+ "preinstall.settings_title": "Recommended Plugins",
+ "preinstall.settings_hint": "Reopen the preset wizard to re-select or install recommended plugins.",
+ "preinstall.open_preset": "Open Preset",
+
"update.available": "A new version {{tag}} is available. Update now?",
"update.now": "Update Now",
"update.later": "Later",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 0e4f00be..d38af0b9 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -24,6 +24,20 @@
"status.loading": "Loading plugins…",
"status.loading_plugins": "Loading plugins…",
+ "preinstall.title": "安装推荐插件",
+ "preinstall.subtitle": "选择要在启动前安装的插件,之后也可以在设置中的插件市场里管理。",
+ "preinstall.recommend": "推荐",
+ "preinstall.installed": "已安装",
+ "preinstall.confirm": "确定",
+ "preinstall.skip": "跳过",
+ "preinstall.installing": "正在安装插件...",
+ "preinstall.open_repo": "打开 {{name}} 的仓库",
+ "preinstall.failed": "安装失败",
+ "preinstall.empty": "暂无可预装的插件。",
+ "preinstall.settings_title": "预装插件",
+ "preinstall.settings_hint": "重新打开预设引导,可重新选择或安装推荐的插件。",
+ "preinstall.open_preset": "打开预设",
+
"update.available": "发现新版本 {{tag}},是否立即更新?",
"update.now": "立即更新",
"update.later": "稍后",
diff --git a/src/store/index.ts b/src/store/index.ts
index 6a9953f6..89b64038 100644
--- a/src/store/index.ts
+++ b/src/store/index.ts
@@ -17,6 +17,8 @@ export { harness } from './modules/harness'
export type {
InstallerState,
InstallProgress,
+ PreinstallLogPayload,
+ PreinstallPlugin,
SetupStatus,
SidebarBusyAction,
} from './modules/harness'
diff --git a/src/store/modules/harness/index.ts b/src/store/modules/harness/index.ts
index 6f4366ec..d12a4514 100644
--- a/src/store/modules/harness/index.ts
+++ b/src/store/modules/harness/index.ts
@@ -1,2 +1,9 @@
export { harness } from './store'
-export type { InstallerState, InstallProgress, SetupStatus, SidebarBusyAction } from './types'
+export type {
+ InstallerState,
+ InstallProgress,
+ PreinstallLogPayload,
+ PreinstallPlugin,
+ SetupStatus,
+ SidebarBusyAction,
+} from './types'
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index 26c7f4fd..ca9e7a3d 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -1,5 +1,12 @@
import type { UnlistenFn } from '@tauri-apps/api/event'
-import type { InstallerState, InstallProgress, SetupStatus, SidebarBusyAction } from './types'
+import type {
+ InstallerState,
+ InstallProgress,
+ PreinstallLogPayload,
+ PreinstallPlugin,
+ SetupStatus,
+ SidebarBusyAction,
+} from './types'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import i18next from 'i18next'
@@ -76,6 +83,14 @@ export const harness = defineStore({
status: 'ready' as SetupStatus,
installer: initialInstaller,
errorMsg: '',
+ /** 预装插件引导状态:列表/安装进度/日志/错误 */
+ preinstall: {
+ plugins: [] as PreinstallPlugin[],
+ loading: false,
+ installing: false,
+ logs: [] as string[],
+ error: '',
+ },
serviceUrl: 'http://127.0.0.1:3080',
/** 带时间戳的 iframe 地址(boot 时生成一次,避免缓存) */
iframeSrc: '',
@@ -182,7 +197,10 @@ export const harness = defineStore({
this.iframeSrc = generateTimestampedUrl(runtimeInfo.service_url)
// 已安装过则跳过安装界面,避免每次启动都闪现"正在安装依赖..."
- const config = await invoke<{ installed: boolean }>('get_app_config')
+ const config = await invoke<{
+ installed: boolean
+ preinstall_done: boolean
+ }>('get_app_config')
// 仅首次使用需要检测环境/安装依赖;之后直接进入页面
if (!config.installed) {
@@ -191,6 +209,15 @@ export const harness = defineStore({
await invoke('install_dependencies')
}
+ // 预装插件引导:首次安装完成或老版本升级后出现(装完/跳过后才拉起服务)。
+ // 注意:老用户升级后 installed 已为 true,但 preinstall_done 未置位,
+ // 此时也能看到新增的预装插件列表。
+ if (!config.preinstall_done) {
+ this.status = 'preinstall'
+ await this.loadPreinstallPlugins()
+ return
+ }
+
await this.launchAndWait()
if (token !== bootToken)
@@ -292,6 +319,86 @@ export const harness = defineStore({
this.busyAction = null
}
},
+
+ /** 拉取预装插件列表(含已安装检测),供首次启动引导界面渲染 */
+ async loadPreinstallPlugins(): Promise<PreinstallPlugin[]> {
+ if (this.preinstall.loading)
+ return this.preinstall.plugins
+ this.preinstall.loading = true
+ try {
+ this.preinstall.plugins = await invoke<PreinstallPlugin[]>('get_preinstall_plugins')
+ }
+ catch (err) {
+ console.error('[Harness] failed to load preinstall plugins:', err)
+ }
+ finally {
+ this.preinstall.loading = false
+ }
+ return this.preinstall.plugins
+ },
+
+ /** 预装安装日志流:dsh plugin 进程输出逐行追加 */
+ async listenPreinstallLog(): Promise<UnlistenFn> {
+ return listen<PreinstallLogPayload>('preinstall-log', (e) => {
+ this.preinstall.logs = [...this.preinstall.logs, e.payload.line].slice(-200)
+ })
+ },
+
+ /** 确认安装选中的预装插件:流式日志,完成后继续启动服务 */
+ async confirmPreinstall(ids: string[]) {
+ if (this.preinstall.installing || ids.length === 0)
+ return
+ this.preinstall.installing = true
+ this.preinstall.error = ''
+ this.preinstall.logs = []
+ let unlisten: UnlistenFn | null = null
+ try {
+ unlisten = await this.listenPreinstallLog()
+ await invoke('install_preinstall_plugins', { ids })
+ await this.continueAfterPreinstall()
+ }
+ catch (err) {
+ console.error('[Harness] preinstall failed:', err)
+ this.preinstall.error = String(err)
+ }
+ finally {
+ unlisten?.()
+ this.preinstall.installing = false
+ }
+ },
+
+ /** 跳过预装插件引导:记录状态后继续启动服务 */
+ async skipPreinstall() {
+ if (this.preinstall.installing)
+ return
+ try {
+ await invoke('skip_preinstall_plugins')
+ await this.continueAfterPreinstall()
+ }
+ catch (err) {
+ console.error('[Harness] skip preinstall failed:', err)
+ this.preinstall.error = String(err)
+ }
+ },
+
+ /** 预装引导结束后的收尾:拉起服务等待就绪,并静默检查更新 */
+ async continueAfterPreinstall() {
+ await this.launchAndWait()
+ void updater.checkForUpdate()
+ },
+
+ /**
+ * 从侧边栏重新打开预装插件引导:可重新选择/安装推荐插件。
+ * 关闭引导(确定/跳过)后回到正常启动流程,服务若在运行则保持原状态。
+ */
+ async openPreinstall() {
+ if (this.preinstall.installing)
+ return
+ this.preinstall.error = ''
+ this.preinstall.logs = []
+ this.status = 'preinstall'
+ await this.loadPreinstallPlugins()
+ },
},
})
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index 8c325aa0..cfb76353 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -1,9 +1,25 @@
/** 安装/启动流程阶段状态 */
-export type SetupStatus = 'checking' | 'installing' | 'starting' | 'ready' | 'error'
+export type SetupStatus = 'checking' | 'installing' | 'starting' | 'preinstall' | 'ready' | 'error'
/** 侧边栏忙碌标记:标识当前正在执行的服务操作 */
export type SidebarBusyAction = 'restart' | 'shutdown' | 'start' | 'openBrowser' | null
+/** 预装插件列表项(与 Rust service::plugin::PreinstallPlugin 对齐) */
+export interface PreinstallPlugin {
+ id: string
+ name: string
+ description: string
+ repo_url: string
+ recommended: boolean
+ installed: boolean
+ default: boolean
+}
+
+/** Rust 侧 preinstall-log 事件载荷(dsh plugin 进程输出行) */
+export interface PreinstallLogPayload {
+ line: string
+}
+
/** 安装器展示状态 */
export interface InstallerState {
title: string