Skip to content

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

feat(win): integrate win32 terminal inspector workflow and plugin preinstall

hairyf581f7a68e140
diff --git a/AGENTS.md b/AGENTS.md
index 7f79b363..c87d4b8a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,6 +2,9 @@
DeepSeek Harness desktop (Tauri 2 + React 18), embeds the Harness UI served at `http://127.0.0.1:3080`.
+- **端口隔离**:release 默认 `3080`,debug(`pnpm tauri dev` / `cargo build`)默认 `3081`,由 `config::setting::default_port()` 用 `cfg!(debug_assertions)` 区分,避免开发时与已运行的桌面端争用端口。
+- **Windows 极简模式**:预装插件流程(`service/plugin`)对 Windows 用户列出「修复」项(`dsh-win-terminal-inspector`,黄色 chip 默认勾选),确认后 `dsh plugin add github:clearkurt/dsh-win-terminal-inspector` 从 GitHub 安装(桌面端**不内置**插件源码);随后 `service/workflow/win_inspector.rs`(仅 Windows,幂等)写入 profile `cordis.patch.yml` 挂载行并创作 `$DSH_HOME/.agent-presets/minimal-win/` 用户 preset(Git Bash + danger-full-access,因为 agent preset 组成不受 profile patch 管辖)。
+
- Prioritize using customized components from src/components, hero-ui.
- This will help minimize the need for writing custom classes.
- If you write new content, you need to handle i18n en keys
diff --git a/src-tauri/resources/dsh-win-terminal-inspector/LICENSE b/src-tauri/resources/dsh-win-terminal-inspector/LICENSE
deleted file mode 100644
index e52bd125..00000000
--- a/src-tauri/resources/dsh-win-terminal-inspector/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2026 clearkurt
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rs
index b2faf84e..663d34c5 100644
--- a/src-tauri/src/bridge/cmd.rs
+++ b/src-tauri/src/bridge/cmd.rs
@@ -142,6 +142,12 @@ pub async fn install_preinstall_plugins(
Ok(())
}
+/// 取消正在进行的预装插件安装(网络抖动/限流卡住时用户点“取消”)。
+#[tauri::command]
+pub async fn cancel_preinstall_plugins(app_handle: AppHandle) {
+ plugin::cancel(&app_handle).await;
+}
+
/// 跳过预装插件引导:仅记录状态,不再弹出
#[tauri::command]
pub async fn skip_preinstall_plugins(app_handle: AppHandle) -> Result<(), String> {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 48ea69ec..c6a0340f 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -123,6 +123,7 @@ fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
bridge::cmd::get_dsh_status,
bridge::cmd::get_preinstall_plugins,
bridge::cmd::install_preinstall_plugins,
+ bridge::cmd::cancel_preinstall_plugins,
bridge::cmd::skip_preinstall_plugins,
bridge::cmd::open_preinstall_repo,
bridge::cmd::proxy_health_check,
diff --git a/src-tauri/src/service/plugin/mod.rs b/src-tauri/src/service/plugin/mod.rs
index 697e1875..b1f14668 100644
--- a/src-tauri/src/service/plugin/mod.rs
+++ b/src-tauri/src/service/plugin/mod.rs
@@ -17,6 +17,8 @@ use std::io::{BufRead, BufReader, Read};
use std::path::PathBuf;
#[cfg(not(windows))]
use std::process::{Command, Stdio};
+#[cfg(windows)]
+use std::process::{Command, Stdio};
use tauri::{AppHandle, Emitter, Manager, WebviewWindow};
/// Windows 进程句柄包装:原始句柄是 `*mut c_void`(非 Send),
@@ -35,23 +37,53 @@ 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,
-}];
+/// `spec` 为传给 `dsh plugin add` 的包名/依赖形式(npm 包名或 git 依赖形式);
+/// `id` 是前端主键与仓库跳转查找用(与 spec 不同:id 必须是合法的 npm 依赖名,
+/// 而 git 依赖的主键是包内的 name 字段,二者可能不一致)。
+const PREINSTALL: &[PreinstallPluginInfo] = &[
+ // Windows 极简模式修复(issue #12):注入 win32 terminal inspector。
+ // 仅 Windows 用户可见;chip 显示为黄色「修复」并默认勾选;确认后走
+ // `dsh plugin add` 从 GitHub 安装(插件代码不随桌面端仓库内置),随后由
+ // win_inspector::apply 写入 profile patch 行并创作 minimal-win 用户 preset。
+ PreinstallPluginInfo {
+ id: "dsh-win-terminal-inspector",
+ spec: "github:clearkurt/dsh-win-terminal-inspector",
+ name: "Windows Terminal Inspector",
+ description:
+ "Fix Minimal mode on Windows: injects the win32 ProcessInspector that persistent shells require (upstream throws `terminal inspection is unsupported on platform win32`). · 修复 Windows 极简模式:注入 persistent shell 必需的 win32 进程监视(上游在 win32 上直接抛错)。",
+ repo_url: "https://github.com/clearkurt/dsh-win-terminal-inspector",
+ recommended: false,
+ fix: true,
+ win_only: true,
+ },
+ PreinstallPluginInfo {
+ id: "dshmarket",
+ spec: "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,
+ fix: false,
+ win_only: false,
+ },
+];
/// 预装插件静态信息(不含运行时检测的 installed 状态)
struct PreinstallPluginInfo {
+ /// 前端主键 / 仓库跳转查找键
id: &'static str,
+ /// 传给 `dsh plugin add` 的依赖形式(npm 包名或 git 依赖形式)
+ spec: &'static str,
name: &'static str,
description: &'static str,
repo_url: &'static str,
+ /// 绿色「推荐」chip,默认勾选(普通推荐插件)
recommended: bool,
+ /// 黄色「修复」chip,默认勾选(Windows 极简模式修复项)
+ fix: bool,
+ /// 仅 Windows 平台列出
+ win_only: bool,
}
/// 预装插件列表项(含已安装检测结果),序列化给前端
@@ -63,6 +95,8 @@ pub struct PreinstallPlugin {
pub description: String,
pub repo_url: String,
pub recommended: bool,
+ /// 是否为「修复」类项(前端渲染黄色 chip,默认勾选)
+ pub fix: bool,
pub installed: bool,
}
@@ -83,6 +117,11 @@ pub fn repo_url_of(id: &str) -> Option<&'static str> {
PREINSTALL.iter().find(|p| p.id == id).map(|p| p.repo_url)
}
+/// 预装清单中某 id 对应的安装依赖形式(npm 包名或 git 依赖形式)
+fn spec_of(id: &str) -> Option<&'static str> {
+ PREINSTALL.iter().find(|p| p.id == id).map(|p| p.spec)
+}
+
/// 预装插件所在的 profile 目录($DSH_HOME/profiles/web)
fn profile_dir(app_handle: &AppHandle) -> PathBuf {
config::get_dsh_data_path(app_handle)
@@ -122,17 +161,21 @@ fn list_installed(app_handle: &AppHandle) -> HashSet<String> {
set
}
-/// 预装插件列表(含 installed 状态),前端渲染用
+/// 预装插件列表(含 installed 状态),前端渲染用。
+/// `win_only` 项仅在 Windows 平台列出(如 Windows 极简模式修复)。
pub fn list(app_handle: &AppHandle) -> Vec<PreinstallPlugin> {
let installed = list_installed(app_handle);
+ let is_windows = cfg!(windows);
PREINSTALL
.iter()
+ .filter(|p| !p.win_only || is_windows)
.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,
+ fix: p.fix,
installed: installed.contains(p.id),
})
.collect()
@@ -149,7 +192,6 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
return Err(format!("PREINSTALL_INVALID_ID: {id}"));
}
}
-
// 确保 pnpm/dsh shim 存在(只落盘文件、不注册用户 PATH),
// 让 dsh plugin 内部转发的 `pnpm` 在子进程 PATH 中可解析。
cli::ensure_shims(app_handle)?;
@@ -199,9 +241,11 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
envs.insert("PATH".to_string(), joined.to_string_lossy().into_owned());
}
- // 命令:`node <dsh_bin.js> plugin --profile web add <ids...>`
+ // 命令:`node <dsh_bin.js> plugin --profile web add <specs...>`
// 注意脚本路径必须是第一个参数(node 会把首个非选项参数当作脚本加载,
// 漏掉它会出现 `Cannot find module '.../dependencies/dsh/plugin'`)。
+ // 传给 dsh 的是依赖形式(spec)而非 id:git 依赖形式(github:owner/repo)
+ // 通过 pnpm 安装,主键是包内 name 字段,可能与界面 id 不一致。
let mut args: Vec<OsString> = vec![dsh_bin.as_os_str().to_os_string()];
args.extend([
OsString::from("plugin"),
@@ -209,7 +253,13 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
OsString::from(PREINSTALL_PROFILE),
OsString::from("add"),
]);
- args.extend(ids.iter().map(OsString::from));
+ args.extend(
+ ids.iter()
+ .map(|id| spec_of(id).ok_or_else(|| format!("PREINSTALL_INVALID_ID: {id}")))
+ .collect::<Result<Vec<_>, String>>()?
+ .iter()
+ .map(OsString::from),
+ );
let cwd = config::get_dsh_install_path(app_handle);
log::info!("Running dsh plugin install for {ids:?}");
@@ -222,10 +272,82 @@ pub async fn install(app_handle: &AppHandle, ids: &[String]) -> Result<(), Strin
));
}
+ // Windows 极简模式修复:插件已装入 profile 后,写入 patch 行挂载
+ // win32 inspector,并创作 minimal-win 用户 preset(Git Bash)。
+ if ids.iter().any(|id| id == "dsh-win-terminal-inspector") {
+ if let Err(e) = workflow::win_inspector::apply(app_handle) {
+ log::warn!("win inspector apply failed after install: {e}");
+ }
+ }
+
log::info!("Preinstall plugins installed successfully: {ids:?}");
Ok(())
}
+/// 取消正在进行的预装插件安装:强制结束 dsh plugin 进程树。
+///
+/// `dsh plugin add` 会经 pnpm 拉取依赖,网络抖动/GitHub 限流(429)时可能长时间
+/// 卡在重试;给用户取消入口,避免一直等待。通过 Windows CIM 匹配“正在跑
+/// `plugin ... add` 的 node 进程”并整树强杀(subprocess 派生的 git / pnpm 会一起
+/// 结束;taskkill /T 也能避免 DLL 驻留)。仅在 Windows 有意义,非 Windows 无操作。
+pub async fn cancel(app_handle: &AppHandle) {
+ // 仅预装场景需要取消;非 Windows 直接返回
+ if !cfg!(windows) {
+ return;
+ }
+
+ let window = match app_handle.get_webview_window("main") {
+ Some(w) => w,
+ None => return,
+ };
+
+ #[cfg(windows)]
+ {
+ // 结束占用中/等待中的 dsh plugin add 进程树(匹配命令行里的 add 意图,
+ // 避免误杀无关 node 进程;executable 限定在 dsh 打包目录下)。
+ let base = crate::config::get_dsh_install_path(app_handle)
+ .to_string_lossy()
+ .replace('\\', "\\\\");
+ let ps_cmd = format!(
+ "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Where-Object {{ ($_.CommandLine -like '*plugin*--profile*web*add*') -and ($_.ExecutablePath -like '{base}\\*') }} | ForEach-Object {{ taskkill /PID $_.ProcessId /T /F 2>$null }}"
+ );
+
+ let mut cmd = Command::new("powershell");
+ cmd.args([
+ "-NoProfile",
+ "-NonInteractive",
+ "-WindowStyle",
+ "Hidden",
+ "-Command",
+ &ps_cmd,
+ ]);
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
+ cmd.stdout(Stdio::null());
+ cmd.stderr(Stdio::null());
+
+ if let Err(e) = cmd.output() {
+ log::warn!("failed to run preinstall cancel: {e}");
+ }
+ }
+
+ // 通知前端安装已被取消,回到可重试的选择态
+ let _ = window.emit(
+ preinstall_cancel_event(),
+ PreinstallCancelPayload {},
+ );
+}
+
+/// 前端监听“安装已取消”事件名
+fn preinstall_cancel_event() -> &'static str {
+ "preinstall-cancelled"
+}
+
+/// 取消事件载荷(预留扩展字段)
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PreinstallCancelPayload {}
+
/// 启动 `dsh plugin` 进程并等待结束,返回退出码;输出实时转发事件。
async fn run_plugin_process(
node: &std::path::Path,
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index f0d90489..8e9590ff 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -1,5 +1,6 @@
pub mod status;
pub mod utils;
+pub(crate) mod win_inspector;
#[cfg(windows)]
pub(crate) mod win_spawn;
@@ -119,7 +120,7 @@ pub async fn start(app_handle: tauri::AppHandle) -> Result<(), String> {
log::debug!("Checking Harness running status");
let port_in_use = is_port_in_use(setting.port);
- let dsh_running = is_dsh_running().await;
+ let dsh_running = is_dsh_running(setting.port).await;
if port_in_use && !dsh_running {
log::info!("Harness is not running, but port is in use, stopping harness");
@@ -174,7 +175,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
}
// 避免重复启动(配合启动守卫,确保并发调用只拉起一个进程)
- if is_dsh_running().await {
+ if is_dsh_running(setting.port).await {
log::info!("Harness is already running, skipping launch");
return Ok(());
}
@@ -201,6 +202,12 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// 构造环境变量:隔离的 $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}"))?;
+
+ // Windows 极简模式修复的自愈:插件已装入 profile 时确保 patch 挂载行与
+ // minimal-win 用户 preset 落盘(幂等)。最佳努力:失败只告警,不阻断启动。
+ if let Err(e) = win_inspector::apply(&app_handle) {
+ log::warn!("win32 terminal support apply 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());
@@ -282,7 +289,7 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
tauri::async_runtime::spawn(async move {
for _ in 0..15 {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
- if is_dsh_running().await {
+ if is_dsh_running(setting.port).await {
break;
}
}
@@ -347,7 +354,7 @@ pub async fn install(
// 不停止的话覆盖解压必然失败(Windows os error 32)。
// 注意不能只依赖 HTTP 探测:服务崩溃/失去响应时探测不到,但 node
// 进程可能仍存活并持有 DLL,因此探测不到时也要强制清理。
- if is_dsh_running().await {
+ if is_dsh_running(config::get_store_dat_setting(app_handle).port).await {
log::info!("Stopping running Harness service before installation");
stop(app_handle.clone()).await?;
} else {
diff --git a/src-tauri/src/service/workflow/win_inspector.rs b/src-tauri/src/service/workflow/win_inspector.rs
new file mode 100644
index 00000000..f1a5a372
--- /dev/null
+++ b/src-tauri/src/service/workflow/win_inspector.rs
@@ -0,0 +1,388 @@
+//! Windows 极简模式(Minimal)修复:win32 terminal inspector 挂载 + 用户 preset。
+//!
+//! 极简模式在 Windows 上有两层故障,本模块处理后一层(挂载与 preset 落盘),
+//! 前一层(插件安装)走预装插件流程(`service/plugin`):
+//!
+//! 1. **终端检查缺失**:`@deepseek-ai/dsh-subprocess-local` 的
+//! `createProcessInspector()` 只在 linux/darwin 实现,win32 上 persistent
+//! shell spawn 时在 PTY 之前直接 throw
+//! `subprocess-local: terminal inspection is unsupported on platform win32`
+//! (上游未修,见 issue #12)。
+//! 修复:社区插件 [clearkurt/dsh-win-terminal-inspector](MIT)包装运行时
+//! 实例的 `spawnTerminal`,利用公开测试钩子 `terminalInspector` 注入
+//! `WindowsProcessInspector`,不修改任何 node_modules 官方包。该插件由预装
+//! 向导通过 `dsh plugin add github:clearkurt/dsh-win-terminal-inspector`
+//! 装入 profile 的 node_modules(Git 依赖,主键即包名),**桌面端仓库不内置
+//! 任何插件源码**;本模块随后写入 profile 的 `cordis.patch.yml` 挂载行
+//! (裸包名经 node_modules 父级解析),并创作 Windows 用户 preset。
+//!
+//! 2. **preset 自身在 Windows 不可用**:agent preset 的组成(`agent.cordis.yml`)
+//! 由每次会话直接从磁盘文件挂载(`dsh-agent-presets::mountPreset`),
+//! **不受 profile 的 `cordis.patch.yml` 管辖**——在 patch 里覆写
+//! `terminal-bash` 行不会作用到极简模式;且 shipped preset 是只读的、
+//! 升级会被覆盖。按官方规则,正确的做法是在用户根
+//! `${DSH_HOME}/.agent-presets/<id>/` **创作一个用户 preset**(复制 minimal
+//! 后做 Windows 修正):
+//! - `terminal-bash.shellPath` 指向本机 Git Bash(默认 `/bin/bash` 在
+//! Windows 上不是有效路径,spawn 必败);
+//! - persistent-shell 组内放一个 `sandbox-policy`(`danger-full-access`):
+//! Git Bash(MSYS)在 `workspace-write` 的受限令牌下无法初始化信号管道
+//! (cygheap/ACL 错误),必须让 shell 在非受限令牌下运行。
+//! 代价:该 preset 的 shell 不受文件沙箱约束(与 clearkurt 的 minimal-win
+//! 方案一致);若要在受限模式下用 Git Bash,需改官方
+//! `dsh-sandbox-windows-acl` 的令牌构造,属后续工作。
+//!
+//! 幂等:patch 与 preset 均为“已存在即跳过”;`apply` 仅在插件确实已装入
+//! profile 时才会写 patch(避免挂载一个不存在的包导致 loader 报错)。
+
+#[cfg(windows)]
+mod imp {
+ use std::fs;
+ use std::path::{Path, PathBuf};
+
+ /// 插件在 profile package.json dependencies 中的依赖名(Git 依赖的主键)。
+ const PLUGIN_DEP_NAME: &str = "dsh-win-terminal-inspector";
+
+ /// cordis.patch.yml 追加的挂载行(顶层数组的一个 `- insert:` 元素)。
+ /// name 用裸包名:经 profile 目录的 node_modules 父级解析到安装的插件。
+ const PATCH_ENTRY: &str = concat!(
+ "- insert:\n",
+ " - id: win-terminal-inspector\n",
+ " name: dsh-win-terminal-inspector\n",
+ );
+
+ /// 注入判定标记:patch 中出现该字符串即视为已挂载。
+ const PATCH_MARKER: &str = "dsh-win-terminal-inspector";
+
+ /// 用户 preset 目录名(`$DSH_HOME/.agent-presets/<id>/`)。
+ const WIN_PRESET_ID: &str = "minimal-win";
+
+ /// 候选 Git Bash 安装位置(常见路径 + 环境变量覆盖)。
+ const GIT_BASH_CANDIDATES: [&str; 4] = [
+ r"C:\Program Files\Git\bin\bash.exe",
+ r"C:\Program Files\Git\usr\bin\bash.exe",
+ r"C:\Program Files (x86)\Git\bin\bash.exe",
+ r"C:\Program Files (x86)\Git\usr\bin\bash.exe",
+ ];
+
+ /// web profile 目录:`<DSH_HOME>/profiles/web`。
+ fn profile_dir(app_handle: &tauri::AppHandle) -> PathBuf {
+ crate::config::get_dsh_data_path(app_handle)
+ .join("profiles")
+ .join("web")
+ }
+
+ /// dsh 用户数据目录(`$DSH_HOME`)。
+ fn dsh_home(app_handle: &tauri::AppHandle) -> PathBuf {
+ crate::config::get_dsh_data_path(app_handle)
+ }
+
+ /// 写入一个文件及其父目录,返回错误信息。
+ fn write_file(path: &Path, content: &str) -> Result<(), String> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)
+ .map_err(|e| format!("create parent dir failed: {e}"))?;
+ }
+ fs::write(path, content).map_err(|e| format!("write {} failed: {e}", path.display()))
+ }
+
+ /// 插件是否已装入 profile:读取 profile 清单的 `dependencies` 键。
+ fn is_plugin_installed(profile: &Path) -> bool {
+ let Ok(content) = fs::read_to_string(profile.join("package.json")) else {
+ return false;
+ };
+ let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&content) else {
+ return false;
+ };
+ manifest
+ .get("dependencies")
+ .and_then(serde_json::Value::as_object)
+ .map(|deps| deps.contains_key(PLUGIN_DEP_NAME))
+ .unwrap_or(false)
+ }
+
+ /// 幂等地写入 web profile 的 `cordis.patch.yml` 挂载行。
+ fn ensure_patch(profile: &Path) -> Result<(), String> {
+ let patch_path = profile.join("cordis.patch.yml");
+ let existing = fs::read_to_string(&patch_path).unwrap_or_default();
+
+ // 已挂载则跳过(幂等)。
+ if existing.contains(PATCH_MARKER) {
+ return Ok(());
+ }
+
+ // dsh 可能以“流式空列表 `[]` + 注释头”初始化该文件;块式条目直接追到
+ // `[]` 后面会产生非法 YAML(“end of the stream or a document separator
+ // is expected”),因此先把单独成行的 `[]` 去掉再追加。
+ let cleaned = existing
+ .lines()
+ .filter(|line| line.trim() != "[]")
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ let mut out = cleaned;
+ if !out.trim().is_empty() && !out.ends_with('\n') {
+ out.push('\n');
+ }
+ out.push_str(PATCH_ENTRY);
+
+ write_file(&patch_path, &out).map_err(|e| format!("PATCH_WRITE_FAILED: {e}"))
+ }
+
+ /// 在本机查找 Git Bash 可执行文件(环境变量优先,其次常见安装路径)。
+ fn find_git_bash() -> Option<PathBuf> {
+ if let Ok(p) = std::env::var("DSH_GIT_BASH_PATH") {
+ let candidate = PathBuf::from(p);
+ if candidate.is_file() {
+ return Some(candidate);
+ }
+ }
+ GIT_BASH_CANDIDATES
+ .iter()
+ .map(PathBuf::from)
+ .find(|p| p.is_file())
+ }
+
+ /// 渲染 Windows 版极简 preset 的元数据(preset.yml)。
+ fn render_preset_meta() -> String {
+ concat!(
+ "name: 极简模式 (Windows)\n",
+ "description: 仅提供持久 bash(Git Bash)与 str_replace_editor 的双工具编码 Agent;Windows 专用(含 win32 终端检查与非受限令牌)。\n",
+ "order: 3\n",
+ )
+ .to_string()
+ }
+
+ /// 渲染 Windows 版极简 preset 的组成(agent.cordis.yml)。
+ ///
+ /// 基于 shipped `minimal` preset 复制,做两处 Windows 修正:
+ /// 1. `persistent-shell` 组内加 `sandbox-policy`(danger-full-access):
+ /// Git Bash 在 workspace-write 受限令牌下无法初始化(MSYS 信号管道 ACL),
+ /// 必须以非受限令牌运行;
+ /// 2. `terminal-bash` 的 `shellPath` 指向本机 Git Bash,并固定
+ /// `--noprofile --norc -i`(登录 shell 会覆写 PS1,破坏受控提示符契约)。
+ fn render_composition(shell_path: &str) -> String {
+ let shell_path = shell_path.replace('\'', "''"); // YAML 单引号标量:单引号双写
+ format!(
+ r#"# Windows 版极简模式:基于 shipped `minimal` preset 复制并修正。
+# 1) terminal-bash 的 shellPath 指向本机 Git Bash(默认 /bin/bash 在
+# Windows 上不是有效路径);
+# 2) persistent-shell 组内沙箱策略固定为 danger-full-access:Git Bash
+# (MSYS)在 workspace-write 的受限令牌下无法初始化信号管道
+# (cygheap/ACL),shell 必须运行在非受限令牌下。
+
+- id: persona
+ name: '@deepseek-ai/dsh-persona'
+ config:
+ text: You are a helpful software engineer assistant.
+ complete: true
+ includeRuntimeContext: false
+
+- id: persistent-shell
+ name: cordis:group
+ group: true
+ isolate:
+ terminals: true
+ sandboxPolicy: true
+ config:
+ - id: pty
+ name: '@deepseek-ai/dsh-terminal'
+
+ - id: sandbox-policy
+ name: '@deepseek-ai/dsh-sandbox-policy'
+ config:
+ mode: danger-full-access
+ workspaceRoot: !!js process.env.DSH_CWD ?? process.cwd()
+
+ - id: terminal-bash
+ name: '@deepseek-ai/dsh-terminal-bash'
+ config:
+ timeoutMs: 300000
+ shellPath: '{}'
+ shellArgs: ['--noprofile', '--norc', '-i']
+
+ - id: persistent-bash
+ name: '@deepseek-ai/dsh-tool-bash-persistent'
+ config:
+ timeoutMs: 300000
+ description: |-
+ Run commands in a bash shell (Git Bash on Windows)
+ * This shell runs unconfined (danger-full-access): no file sandbox on shell commands.
+ * State is persistent across command calls and discussions with the user.
+
+- id: filesystem
+ name: cordis:group
+ group: true
+ isolate:
+ fs: true
+ config:
+ - id: fs-local
+ name: '@deepseek-ai/dsh-fs-local'
+ config:
+ cwd: !!js process.env.DSH_CWD ?? process.cwd()
+
+ - id: str-replace-editor
+ name: '@deepseek-ai/dsh-tool-str-replace-editor'
+ config:
+ maxOutputChars: 16000
+"#,
+ shell_path
+ )
+ }
+
+ /// 在用户根创作 Windows 版极简 preset(`$DSH_HOME/.agent-presets/minimal-win/`)。
+ ///
+ /// 幂等:目录已存在则视为用户已拥有该 preset,跳过(shipped preset 之外的
+ /// 用户根由用户自己管理,升级不覆盖)。Git Bash 未安装时跳过并告警,
+ /// 不阻断主流程。
+ fn ensure_win_minimal_preset(app_handle: &tauri::AppHandle) -> Result<(), String> {
+ let Some(git_bash) = find_git_bash() else {
+ log::warn!(
+ "Git Bash not found; skipping minimal-win preset authoring (DSH_GIT_BASH_PATH to override)"
+ );
+ return Ok(());
+ };
+
+ let dir = dsh_home(app_handle)
+ .join(".agent-presets")
+ .join(WIN_PRESET_ID);
+ let composition = dir.join("agent.cordis.yml");
+ if composition.exists() {
+ log::info!("minimal-win preset already exists, leaving as-is");
+ return Ok(());
+ }
+
+ let shell = git_bash.to_string_lossy().into_owned();
+ write_file(&composition, &render_composition(&shell))?;
+ write_file(&dir.join("preset.yml"), &render_preset_meta())?;
+ log::info!(
+ "minimal-win preset authored at {} (shell: {})",
+ dir.display(),
+ git_bash.display()
+ );
+ Ok(())
+ }
+
+ /// 应用 Windows 极简模式修复的落盘部分:挂载 patch 行 + 创作用户 preset。
+ ///
+ /// 仅在插件已装入 profile 时写 patch(避免挂载不存在的包);preset 仅在
+ /// Git Bash 存在时创作。均为幂等,失败只返回错误、由调用方决定是否告警。
+ pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
+ let profile = profile_dir(app_handle);
+ if !is_plugin_installed(&profile) {
+ log::debug!(
+ "win terminal inspector not installed in profile, skipping patch/preset apply"
+ );
+ return Ok(());
+ }
+
+ ensure_patch(&profile)?;
+ ensure_win_minimal_preset(app_handle)?;
+ log::info!("win32 terminal support applied to {:?}", profile.display());
+ Ok(())
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ fn temp_dir(tag: &str) -> PathBuf {
+ std::env::temp_dir().join(format!("win-inspector-test-{}-{tag}", std::process::id()))
+ }
+
+ #[test]
+ fn patch_append_strips_flow_empty_list() {
+ // dsh 可能把 patch 文件初始化为“注释头 + []”
+ let dir = temp_dir("a");
+ std::fs::create_dir_all(&dir).unwrap();
+ let patch = dir.join("cordis.patch.yml");
+ std::fs::write(&patch, "# header comment\n[]\n").unwrap();
+
+ ensure_patch(&dir).unwrap();
+ let out = std::fs::read_to_string(&patch).unwrap();
+ // `[]` 行被移除、挂载行存在、且没有残留 `[]`
+ assert!(!out.contains("[]"));
+ assert!(out.contains("- insert:"));
+ assert!(out.contains("win-terminal-inspector"));
+
+ // 幂等:再次调用不重复追加
+ ensure_patch(&dir).unwrap();
+ let again = std::fs::read_to_string(&patch).unwrap();
+ assert_eq!(out, again);
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn patch_append_preserves_existing_block_entries() {
+ let dir = temp_dir("b");
+ std::fs::create_dir_all(&dir).unwrap();
+ let patch = dir.join("cordis.patch.yml");
+ std::fs::write(&patch, "- id: some-row\n config:\n a: 1\n").unwrap();
+
+ ensure_patch(&dir).unwrap();
+ let out = std::fs::read_to_string(&patch).unwrap();
+ assert!(out.contains("some-row"));
+ assert!(out.contains("win-terminal-inspector"));
+
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn patch_uses_bare_package_name() {
+ let dir = temp_dir("c");
+ std::fs::create_dir_all(&dir).unwrap();
+ ensure_patch(&dir).unwrap();
+ let out = std::fs::read_to_string(dir.join("cordis.patch.yml")).unwrap();
+ assert!(out.contains("name: dsh-win-terminal-inspector"));
+ std::fs::remove_dir_all(&dir).ok();
+ }
+
+ #[test]
+ fn composition_renders_windows_fixes() {
+ let yaml = render_composition(r"C:\Program Files\Git\bin\bash.exe");
+ assert!(yaml.contains("shellPath: 'C:\\Program Files\\Git\\bin\\bash.exe'"));
+ assert!(yaml.contains("mode: danger-full-access"));
+ assert!(yaml.contains("sandboxPolicy: true"));
+ assert!(yaml.contains("--noprofile"));
+ assert!(yaml.contains("dsh-tool-bash-persistent"));
+ assert!(yaml.contains("dsh-terminal-bash"));
+ }
+
+ #[test]
+ fn plugin_installed_reads_manifest_deps() {
+ let dir = temp_dir("d");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(
+ dir.join("package.json"),
+ r#"{"name":"dsh-profile-web","dependencies":{"dsh-win-terminal-inspector":"github:clearkurt/dsh-win-terminal-inspector"}}"#,
+ )
+ .unwrap();
+ assert!(is_plugin_installed(&dir));
+
+ let empty = temp_dir("e");
+ std::fs::create_dir_all(&empty).unwrap();
+ std::fs::write(empty.join("package.json"), r#"{"name":"dsh-profile-web"}"#).unwrap();
+ assert!(!is_plugin_installed(&empty));
+
+ std::fs::remove_dir_all(&dir).ok();
+ std::fs::remove_dir_all(&empty).ok();
+ }
+ }
+}
+
+#[cfg(not(windows))]
+mod imp {
+ /// 非 Windows 平台无操作:插件在运行时自身也会按 platform 判空。
+ pub fn apply(_app_handle: &tauri::AppHandle) -> Result<(), String> {
+ Ok(())
+ }
+}
+
+/// 应用 Windows 极简模式修复的落盘部分(仅 Windows 生效,幂等)。
+///
+/// 由预装插件安装流程在安装成功、以及服务启动自愈时调用;插件未装入 profile
+/// 时无操作。
+pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
+ imp::apply(app_handle)
+}
\ No newline at end of file
diff --git a/src/components/preinstall-setup.tsx b/src/components/preinstall-setup.tsx
index 818d67a7..c7817ef4 100644
--- a/src/components/preinstall-setup.tsx
+++ b/src/components/preinstall-setup.tsx
@@ -1,5 +1,5 @@
import type { PreinstallPlugin } from '../store/modules/harness'
-import { CircleInfo } from '@gravity-ui/icons'
+import { CircleInfo, Copy, Xmark } from '@gravity-ui/icons'
import { Button, Card, Checkbox, Chip } from '@heroui/react'
import { invoke } from '@tauri-apps/api/core'
import { useEffect, useState } from 'react'
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
import { harness } from '../store/modules/harness'
+import { toast } from '../utils/toast'
/**
* 预装插件引导页:首次安装(或老版本升级)后展示推荐插件列表,
@@ -44,6 +45,11 @@ function PluginRow({ plugin, checked, disabled, onToggle, onOpenRepo }: {
{t('preinstall.recommend')}
</Chip>
</If>
+ <If cond={plugin.fix && !plugin.installed}>
+ <Chip size="sm" variant="soft" color="warning" className="font-medium">
+ {t('preinstall.fix')}
+ </Chip>
+ </If>
<If cond={plugin.installed}>
<Chip size="sm" variant="soft" color="success" className="font-medium">
{t('preinstall.installed')}
@@ -67,25 +73,51 @@ function PluginRow({ plugin, checked, disabled, onToggle, onOpenRepo }: {
)
}
-/** 日志控制台:dsh plugin 进程输出,样式与安装/加载页日志面板一致 */
+/** 日志控制台:dsh plugin 进程输出,顶部带复制按钮,样式与安装/加载页日志面板一致 */
function LogPanel({ logs }: { logs: readonly string[] }) {
const { t } = useTranslation()
+ const text = logs.join('\n')
+
+ async function copyLogs() {
+ try {
+ await navigator.clipboard.writeText(text || '')
+ toast(t('messages.log_copied'), {})
+ }
+ catch (err) {
+ console.error('[Harness] copy preinstall logs failed:', err)
+ }
+ }
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 className="overflow-hidden rounded-lg border border-line bg-log-bg">
+ {/* 面板头:复制日志(右上角) */}
+ <div className="flex items-center justify-end border-b border-line/40 bg-panel2/60 px-2 py-1">
+ <Button
+ size="sm"
+ variant="ghost"
+ isIconOnly
+ className="size-6 min-w-6 rounded-md"
+ aria-label={t('buttons.copy')}
+ onPress={copyLogs}
+ >
+ <Copy className="size-3.5" />
+ </Button>
+ </div>
+ <div
+ className="max-h-[240px] min-h-[112px] overflow-y-auto 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>
</div>
)
}
@@ -102,11 +134,11 @@ export default function PreinstallSetup() {
void harness.loadPreinstallPlugins()
}, [])
- // 默认勾选:未安装的推荐插件(当前即 DSH Market)。
+ // 默认勾选:未安装的推荐插件 +「修复」类项(当前为 Windows 极简模式修复)。
// 派生计算而非在加载回调里 setState,避免与 store 的加载去重守卫竞争,
// 保证插件到位后默认勾选必定生效(用户手动调整后以用户选择为准)。
const effectiveSelected = !touched
- ? new Set(preinstall.plugins.filter(p => !p.installed && p.recommended).map(p => p.id))
+ ? new Set(preinstall.plugins.filter(p => !p.installed && (p.recommended || p.fix)).map(p => p.id))
: selected
function toggle(id: string, checked: boolean) {
@@ -231,6 +263,19 @@ export default function PreinstallSetup() {
<p className="text-xs leading-[18px] text-load-muted">{t('preinstall.installing')}</p>
</div>
<LogPanel logs={preinstall.logs} />
+ {/* 取消安装:网络抖动/限流(429)时可能长时间卡在重试,给用户退出入口 */}
+ <div className="flex items-center justify-center">
+ <Button
+ className="rounded-md"
+ size="sm"
+ variant="tertiary"
+ onPress={harness.cancelPreinstall}
+ isDisabled={preinstall.cancelling}
+ >
+ <Xmark className="size-3.5" />
+ {preinstall.cancelling ? t('preinstall.cancelling') : t('preinstall.cancel')}
+ </Button>
+ </div>
</div>
</If>
</div>
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index cc12e2bc..1e939f47 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -27,10 +27,13 @@
"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.fix": "Fix",
"preinstall.installed": "Installed",
"preinstall.confirm": "Install",
"preinstall.skip": "Skip",
"preinstall.installing": "Installing plugins...",
+ "preinstall.cancel": "Cancel",
+ "preinstall.cancelling": "Cancelling...",
"preinstall.open_repo": "Open repository of {{name}}",
"preinstall.failed": "Installation failed",
"preinstall.empty": "No preinstalled plugins available.",
@@ -90,6 +93,7 @@
"buttons.refresh_logs": "Refresh",
"messages.copy_success": "URL copied to clipboard",
+ "messages.log_copied": "Logs copied to clipboard",
"messages.copy_failed": "Failed to copy URL",
"messages.port_changed": "Port changed",
"messages.port_restart_hint": "It takes effect after the service restarts. Restart now?",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index d38af0b9..3686d4f8 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -27,10 +27,13 @@
"preinstall.title": "安装推荐插件",
"preinstall.subtitle": "选择要在启动前安装的插件,之后也可以在设置中的插件市场里管理。",
"preinstall.recommend": "推荐",
+ "preinstall.fix": "修复",
"preinstall.installed": "已安装",
"preinstall.confirm": "确定",
"preinstall.skip": "跳过",
"preinstall.installing": "正在安装插件...",
+ "preinstall.cancel": "取消",
+ "preinstall.cancelling": "正在取消...",
"preinstall.open_repo": "打开 {{name}} 的仓库",
"preinstall.failed": "安装失败",
"preinstall.empty": "暂无可预装的插件。",
@@ -90,6 +93,7 @@
"buttons.refresh_logs": "刷新",
"messages.copy_success": "地址已复制到剪贴板",
+ "messages.log_copied": "日志已复制到剪贴板",
"messages.copy_failed": "复制地址失败",
"messages.port_changed": "端口已更改",
"messages.port_restart_hint": "重启服务后生效,是否立即重启?",
diff --git a/src/store/modules/harness/store.ts b/src/store/modules/harness/store.ts
index ca9e7a3d..522a9796 100644
--- a/src/store/modules/harness/store.ts
+++ b/src/store/modules/harness/store.ts
@@ -88,6 +88,8 @@ export const harness = defineStore({
plugins: [] as PreinstallPlugin[],
loading: false,
installing: false,
+ /** 用户触发了“取消”但仍需等后端结束进程树 */
+ cancelling: false,
logs: [] as string[],
error: '',
},
@@ -364,6 +366,30 @@ export const harness = defineStore({
finally {
unlisten?.()
this.preinstall.installing = false
+ this.preinstall.cancelling = false
+ }
+ },
+
+ /**
+ * 取消正在进行的预装插件安装:网络抖动/拉包限流(429)时可能长时间卡在
+ * pnpm 重试;调用后端强杀插件安装进程树,回到可重试的选择态。
+ */
+ async cancelPreinstall() {
+ if (!this.preinstall.installing || this.preinstall.cancelling)
+ return
+ // 后端结束进程树导致 `install_preinstall_plugins` 提前返回并进入 catch,
+ // 通过 installing=false 让其回到列表态而不是报错态。
+ this.preinstall.cancelling = true
+ try {
+ await invoke('cancel_preinstall_plugins')
+ await listen<unknown>('preinstall-cancelled', () => {
+ this.preinstall.installing = false
+ this.preinstall.cancelling = false
+ })
+ }
+ catch (err) {
+ console.error('[Harness] cancel preinstall failed:', err)
+ this.preinstall.cancelling = false
}
},
diff --git a/src/store/modules/harness/types.ts b/src/store/modules/harness/types.ts
index cfb76353..fc1a7abe 100644
--- a/src/store/modules/harness/types.ts
+++ b/src/store/modules/harness/types.ts
@@ -11,8 +11,9 @@ export interface PreinstallPlugin {
description: string
repo_url: string
recommended: boolean
+ /** “修复”类项(Windows 极简模式修复):黄色 chip,默认勾选 */
+ fix: boolean
installed: boolean
- default: boolean
}
/** Rust 侧 preinstall-log 事件载荷(dsh plugin 进程输出行) */