Skip to content

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

refactor(workflow): encapsulate dsh package patches into service/patch (#209)

Mao Mrcf01034e9615
diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rs
index 8ebf19bc..4577db5b 100644
--- a/src-tauri/src/service/mod.rs
+++ b/src-tauri/src/service/mod.rs
@@ -3,6 +3,7 @@ pub mod core;
pub mod download;
pub mod fs_guard;
pub mod migrate;
+pub(crate) mod patch;
pub mod plugin;
pub mod profile;
pub mod scheduler;
diff --git a/src-tauri/src/service/workflow/client_hmr_patch.rs b/src-tauri/src/service/patch/client_hmr.rs
similarity index 58%
rename from src-tauri/src/service/workflow/client_hmr_patch.rs
rename to src-tauri/src/service/patch/client_hmr.rs
index 001ec556..34dd2f45 100644
--- a/src-tauri/src/service/workflow/client_hmr_patch.rs
+++ b/src-tauri/src/service/patch/client_hmr.rs
@@ -5,11 +5,7 @@
//! debug 桌面端本来就直接联接本地插件源码,因此将该坏 hot-swap 降级为页面自动刷新:
//! 仍由 `/plugins/events` 精确触发,不轮询页面,也不会影响 release。
-use std::fs;
-use std::path::PathBuf;
-
-use crate::config;
-use crate::service::core::{active_source, local_core_package_dir, CoreSource};
+use crate::utils::{patch_dsh, PatchOutcome};
// HARDCODE:以下锚点绑定内置 DSH 0.1.1-rc.2 的 client-HMR bundle;仅 debug 生效。
const PATCH_MARKER: &str = "dsh-tauri-desktop: debug client plugin reload fallback";
@@ -24,12 +20,8 @@ const PATCHED: &str = r#"case "rebuilt":
window.location.reload();
break;"#;
-#[derive(Debug, PartialEq, Eq)]
-enum PatchOutcome {
- AlreadyPatched,
- AnchorMissing,
- Patched(String),
-}
+/// 相对活动核心安装目录的 client-hmr `lib/client.js` 包内路径。
+const CLIENT_HMR_CLIENT_JS: &str = "node_modules/@deepseek-ai/dsh-client-hmr/lib/client.js";
fn patch_source(source: &str) -> PatchOutcome {
if source.contains(PATCH_MARKER) {
@@ -44,39 +36,7 @@ fn patch_source(source: &str) -> PatchOutcome {
/// debug 启动前把损坏的插件 hot-swap 降级为自动页面刷新。
#[cfg(debug_assertions)]
pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
- let client_js = active_core_install_dir(app_handle)
- .join("node_modules/@deepseek-ai/dsh-client-hmr/lib/client.js");
- if !client_js.exists() {
- log::info!(
- "client-hmr client.js not found, skip debug reload patch: {}",
- client_js.display()
- );
- return Ok(());
- }
- let source = fs::read_to_string(&client_js)
- .map_err(|e| format!("CLIENT_HMR_PATCH_READ: {} failed: {e}", client_js.display()))?;
- match patch_source(&source) {
- PatchOutcome::AlreadyPatched => {
- log::info!("debug client plugin reload fallback already applied")
- }
- PatchOutcome::AnchorMissing => log::warn!(
- "debug client plugin reload fallback anchor missing, skip patch: {}",
- client_js.display()
- ),
- PatchOutcome::Patched(patched) => {
- fs::write(&client_js, patched).map_err(|e| {
- format!(
- "CLIENT_HMR_PATCH_WRITE: {} failed: {e}",
- client_js.display()
- )
- })?;
- log::info!(
- "debug client plugin reload fallback patched: {}",
- client_js.display()
- );
- }
- }
- Ok(())
+ patch_dsh(app_handle, CLIENT_HMR_CLIENT_JS, patch_source)
}
/// release 不修改客户端重载行为。
@@ -85,14 +45,6 @@ pub fn apply(_app_handle: &tauri::AppHandle) -> Result<(), String> {
Ok(())
}
-fn active_core_install_dir(app_handle: &tauri::AppHandle) -> PathBuf {
- match active_source(app_handle) {
- CoreSource::Local => local_core_package_dir(app_handle)
- .unwrap_or_else(|| config::get_dsh_install_path(app_handle)),
- CoreSource::App => config::get_dsh_install_path(app_handle),
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src-tauri/src/service/patch/mod.rs b/src-tauri/src/service/patch/mod.rs
new file mode 100644
index 00000000..e9552bc4
--- /dev/null
+++ b/src-tauri/src/service/patch/mod.rs
@@ -0,0 +1,14 @@
+//! dsh 包文件补丁集。
+//!
+//! 集中存放对活动核心安装目录下 `node_modules/<包>/...` 里的 JS 文件做的一次性
+//! 幂等补丁。每个补丁是一个子模块,只提供「纯函数式补丁判定 + apply 触发」;
+//! 「定位文件 → 读取 → 打补丁 → 写回」与对应日志由 [`crate::utils::patch_dsh`]
+//! 统一处理,避免每个补丁重复这份样板。
+//!
+//! 命名约定:子模块名不带 `_patch` 后缀(`renderer` / `session` / `workspace` /
+//! `client_hmr`),挂点统一为 `service::workflow::launch`,均为最佳努力、失败仅告警。
+
+pub(crate) mod client_hmr;
+pub(crate) mod renderer;
+pub(crate) mod session;
+pub(crate) mod workspace;
diff --git a/src-tauri/src/service/workflow/renderer_patch.rs b/src-tauri/src/service/patch/renderer.rs
similarity index 60%
rename from src-tauri/src/service/workflow/renderer_patch.rs
rename to src-tauri/src/service/patch/renderer.rs
index c3ee316e..bf19916d 100644
--- a/src-tauri/src/service/workflow/renderer_patch.rs
+++ b/src-tauri/src/service/patch/renderer.rs
@@ -6,15 +6,8 @@
//! 声明的槽,而这必须经过 SlotOutlet)。补丁在文件末尾的 `return module.exports;`
//! 前插入一行 `exports.SlotOutlet = SlotOutlet;`,与开发期手工补丁逐字节一致。
//!
-//! 目标选择:**活动核心**,而不是永远指向预打包核心。桌面端支持「本地核心」
-//! (用户在 PATH / 全局安装的 dsh,`CoreSource::Local`)与「预打包核心」
-//! (`CoreSource::App`)两种来源,运行时 web 应用通过 `$DSH_HOME/profiles/<档案>/
-//! node_modules/@deepseek-ai/dsh-client-ui-renderer`(对活动核心 renderer 的链接)
-//! 解析该模块。旧实现恒用 [`config::get_dsh_install_path`](预打包目录),本地核心
-//! 激活时会补到一个**永远不会被加载**的文件上——日志显示已注入,web 应用却仍拿到
-//! 未打补丁的 renderer,dsh-tauri-ui 于是降级为官方设置 dialog。因此这里按
-//! [`crate::service::core::active_source`] 选目录:本地核心用其包目录,预打包用
-//! 桌面端目录;两者回退逻辑与 [`crate::service::core::active_dsh_binary`] 一致。
+//! 目标选择:**活动核心**(本地核心或预打包核心),读写与幂等判定统一交给
+//! [`crate::utils::patch_dsh`];本模块只提供纯函数式补丁判定 [`patch_source`]。
//!
//! 幂等与容错:
//! - 目标已含 `exports.SlotOutlet` 即跳过——上游将来自己导出(或已提的一行 PR
@@ -26,25 +19,13 @@
//! 挂点:`service::workflow::launch` 启动 dsh 进程前,与 win_inspector / ensure_*
//! 自愈链同一位置(最佳努力,失败只告警)。
-use std::fs;
-use std::path::PathBuf;
-
-use crate::config;
-use crate::service::core::{active_source, local_core_package_dir, CoreSource};
+use crate::utils::{patch_dsh, PatchOutcome};
/// 导出锚点的关键字(所在行的前导缩进随版本变化,不做硬编码)。
const ANCHOR_KEYWORD: &str = "return module.exports;";
-/// 单条 renderer client.js 内容的补丁结果。
-#[derive(Debug, PartialEq, Eq)]
-enum PatchOutcome {
- /// 已含 `exports.SlotOutlet`,无需补丁(本补丁已生效或上游官方导出)。
- AlreadyPatched,
- /// 锚点缺失(上游布局变更),跳过;插件降级兜底,不阻断。
- AnchorMissing,
- /// 已插入导出行,携带补丁后的完整内容。
- Patched(String),
-}
+/// 相对活动核心安装目录的 renderer `lib/client.js` 包内路径。
+const RENDERER_CLIENT_JS: &str = "node_modules/@deepseek-ai/dsh-client-ui-renderer/lib/client.js";
/// 幂等补丁逻辑的纯函数部分(便于单测,不触碰文件系统)。
///
@@ -86,55 +67,7 @@ fn locate_return_module_exports(source: &str) -> Option<(usize, &str)> {
/// 对活动核心的 dsh-client-ui-renderer `lib/client.js` 应用补丁(幂等)。
/// 返回 Err 表示读/写失败;文件缺失、已打过、锚点变更均静默跳过(Ok)。
pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
- let client_js: PathBuf = active_core_renderer_client_js(app_handle);
- if !client_js.exists() {
- log::info!(
- "renderer client.js not found, skip SlotOutlet patch: {}",
- client_js.display()
- );
- return Ok(());
- }
- let source = fs::read_to_string(&client_js)
- .map_err(|e| format!("RENDERER_PATCH_READ: {} failed: {e}", client_js.display()))?;
- match patch_source(&source) {
- PatchOutcome::AlreadyPatched => {
- log::info!("renderer already exports SlotOutlet, skip patch");
- }
- PatchOutcome::AnchorMissing => {
- log::warn!(
- "renderer client.js anchor missing, skip SlotOutlet patch — plugin degrades to official settings dialog: {}",
- client_js.display()
- );
- }
- PatchOutcome::Patched(patched) => {
- fs::write(&client_js, patched).map_err(|e| {
- format!("RENDERER_PATCH_WRITE: {} failed: {e}", client_js.display())
- })?;
- log::info!(
- "renderer SlotOutlet export patched: {}",
- client_js.display()
- );
- }
- }
- Ok(())
-}
-
-/// 活动核心安装目录:本地核心用其包目录(全局安装路径),预打包用桌面端目录。
-///
-/// 与 [`crate::service::core::active_dsh_binary`] 的取舍一致——本地核心解析在
-/// 调用瞬间失效时回退预打包目录,绝不让旧实现那样恒打在一个不加载的文件上。
-fn active_core_install_dir(app_handle: &tauri::AppHandle) -> PathBuf {
- match active_source(app_handle) {
- CoreSource::Local => local_core_package_dir(app_handle)
- .unwrap_or_else(|| config::get_dsh_install_path(app_handle)),
- CoreSource::App => config::get_dsh_install_path(app_handle),
- }
-}
-
-/// 活动核心 renderer 的 `lib/client.js` 路径。
-fn active_core_renderer_client_js(app_handle: &tauri::AppHandle) -> PathBuf {
- active_core_install_dir(app_handle)
- .join("node_modules/@deepseek-ai/dsh-client-ui-renderer/lib/client.js")
+ patch_dsh(app_handle, RENDERER_CLIENT_JS, patch_source)
}
#[cfg(test)]
diff --git a/src-tauri/src/service/patch/session.rs b/src-tauri/src/service/patch/session.rs
new file mode 100644
index 00000000..a50c6191
--- /dev/null
+++ b/src-tauri/src/service/patch/session.rs
@@ -0,0 +1,61 @@
+//! Adds the missing public SessionStore removal primitive to the bundled DSH.
+//!
+//! The upstream store already owns the exact detach lifecycle; this patch only
+//! exposes a narrow id-based facade for desktop plugins to use safely.
+
+use crate::utils::{patch_dsh, PatchOutcome};
+
+const PATCH_MARKER: &str = "dsh-tauri-desktop: SessionStore.remove";
+const ANCHOR: &str =
+ "/** Remove one exact entered session and emit its paired disposal when announced. */";
+const INSERTION: &str = r#"/** Remove one live session by id and run its official detach lifecycle. */
+ remove(id) {
+ const entry = this.store.get(id);
+ if (entry === void 0) return false;
+ entry.detach();
+ return true;
+ }
+ /** Remove one exact entered session and emit its paired disposal when announced. */"#;
+
+/// 相对活动核心安装目录的 session `lib/index.js` 包内路径。
+const SESSION_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-session/lib/index.js";
+
+fn patch_source(source: &str) -> PatchOutcome {
+ if source.contains(PATCH_MARKER) {
+ return PatchOutcome::AlreadyPatched;
+ }
+ if !source.contains(ANCHOR) {
+ return PatchOutcome::AnchorMissing;
+ }
+ PatchOutcome::Patched(source.replacen(ANCHOR, &format!("{INSERTION} /* {PATCH_MARKER} */"), 1))
+}
+
+/// 对活动核心的 dsh-session `lib/index.js` 应用补丁(幂等)。
+/// 返回 Err 表示读/写失败;文件缺失、已打过、锚点变更均静默跳过(Ok)。
+pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
+ patch_dsh(app_handle, SESSION_INDEX_JS, patch_source)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn patches_remove_method() {
+ let source = format!("{ANCHOR}\n");
+ let PatchOutcome::Patched(patched) = patch_source(&source) else {
+ panic!("expected patch")
+ };
+ assert!(patched.contains("remove(id)"));
+ assert!(patched.contains(PATCH_MARKER));
+ }
+
+ #[test]
+ fn patch_is_idempotent() {
+ let source = format!("{ANCHOR}\n");
+ let PatchOutcome::Patched(patched) = patch_source(&source) else {
+ panic!("expected patch")
+ };
+ assert_eq!(patch_source(&patched), PatchOutcome::AlreadyPatched);
+ }
+}
diff --git a/src-tauri/src/service/workflow/workspace_patch.rs b/src-tauri/src/service/patch/workspace.rs
similarity index 63%
rename from src-tauri/src/service/workflow/workspace_patch.rs
rename to src-tauri/src/service/patch/workspace.rs
index 30b3d864..7bc07a93 100644
--- a/src-tauri/src/service/workflow/workspace_patch.rs
+++ b/src-tauri/src/service/patch/workspace.rs
@@ -5,11 +5,7 @@
//! `cwd === workspace.path` 过滤,导致合法 worktree 会话只能落入“未分组”。本补丁仅
//! 放宽显式 attach 后的归属保持;cwd 缺失、无法解析或不是目录的安全校验仍由上游保留。
-use std::fs;
-use std::path::PathBuf;
-
-use crate::config;
-use crate::service::core::{active_source, local_core_package_dir, CoreSource};
+use crate::utils::{patch_dsh, PatchOutcome};
// HARDCODE:以下锚点绑定内置 DSH 0.1.1-rc.2 的压缩后源码;锚点变化时安全跳过并告警。
const PATCH_MARKER: &str = "dsh-tauri-worktree: relaxed explicit workspace membership";
@@ -21,12 +17,8 @@ const ATTACH_PATCHED: &str = "/* dsh-tauri-worktree: relaxed explicit workspace
const MUTATE_ORIGINAL: &str = "const sessionIds = changed.sessionIds.filter((id) => this.host.sessionPath(id) === changed.path);";
const MUTATE_PATCHED: &str = "const sessionIds = changed.sessionIds; /* dsh-tauri-worktree: relaxed explicit workspace membership */";
-#[derive(Debug, PartialEq, Eq)]
-enum PatchOutcome {
- AlreadyPatched,
- AnchorMissing,
- Patched(String),
-}
+/// 相对活动核心安装目录的 workspace `lib/index.js` 包内路径。
+const WORKSPACE_INDEX_JS: &str = "node_modules/@deepseek-ai/dsh-workspace/lib/index.js";
fn patch_source(source: &str) -> PatchOutcome {
if source.contains(PATCH_MARKER) {
@@ -45,52 +37,10 @@ fn patch_source(source: &str) -> PatchOutcome {
PatchOutcome::Patched(patched)
}
+/// 对活动核心的 dsh-workspace `lib/index.js` 应用补丁(幂等)。
+/// 返回 Err 表示读/写失败;文件缺失、已打过、锚点变更均静默跳过(Ok)。
pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
- let workspace_js = active_core_install_dir(app_handle)
- .join("node_modules/@deepseek-ai/dsh-workspace/lib/index.js");
- if !workspace_js.exists() {
- log::info!(
- "workspace index.js not found, skip worktree membership patch: {}",
- workspace_js.display()
- );
- return Ok(());
- }
- let source = fs::read_to_string(&workspace_js).map_err(|e| {
- format!(
- "WORKSPACE_PATCH_READ: {} failed: {e}",
- workspace_js.display()
- )
- })?;
- match patch_source(&source) {
- PatchOutcome::AlreadyPatched => {
- log::info!("workspace worktree membership patch already applied")
- }
- PatchOutcome::AnchorMissing => log::warn!(
- "workspace worktree membership anchors missing, skip patch: {}",
- workspace_js.display()
- ),
- PatchOutcome::Patched(patched) => {
- fs::write(&workspace_js, patched).map_err(|e| {
- format!(
- "WORKSPACE_PATCH_WRITE: {} failed: {e}",
- workspace_js.display()
- )
- })?;
- log::info!(
- "workspace worktree membership patched: {}",
- workspace_js.display()
- );
- }
- }
- Ok(())
-}
-
-fn active_core_install_dir(app_handle: &tauri::AppHandle) -> PathBuf {
- match active_source(app_handle) {
- CoreSource::Local => local_core_package_dir(app_handle)
- .unwrap_or_else(|| config::get_dsh_install_path(app_handle)),
- CoreSource::App => config::get_dsh_install_path(app_handle),
- }
+ patch_dsh(app_handle, WORKSPACE_INDEX_JS, patch_source)
}
#[cfg(test)]
diff --git a/src-tauri/src/service/workflow/mod.rs b/src-tauri/src/service/workflow/mod.rs
index 4f998a12..f77b341e 100644
--- a/src-tauri/src/service/workflow/mod.rs
+++ b/src-tauri/src/service/workflow/mod.rs
@@ -1,11 +1,8 @@
-pub(crate) mod client_hmr_patch;
-pub(crate) mod renderer_patch;
pub mod status;
pub mod utils;
pub(crate) mod win_inspector;
#[cfg(windows)]
pub(crate) mod win_spawn;
-pub(crate) mod workspace_patch;
use crate::config;
use crate::service::download;
@@ -790,17 +787,22 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
// 活动核心的 dsh-client-ui-renderer lib/client.js,已含导出即跳过(幂等;核心
// 换版本后自动重打,上游官方导出后自动退休)。最佳努力:失败只告警,不阻断
// 启动——未打补丁时插件侧降级,官方设置 dialog 照常工作,绝不白屏。
- if let Err(e) = renderer_patch::apply(&app_handle) {
+ if let Err(e) = crate::service::patch::renderer::apply(&app_handle) {
log::warn!("renderer SlotOutlet patch failed: {e}");
}
+ // Expose an id-based SessionStore.remove facade so plugins can perform a
+ // real in-memory teardown instead of leaving deleted sessions ungrouped.
+ if let Err(e) = crate::service::patch::session::apply(&app_handle) {
+ log::warn!("SessionStore.remove patch failed: {e}");
+ }
// worktree 会话以隔离 cwd 执行,但产品归属仍是源 Workspace;放宽上游显式
// attach 的 cwd 相等约束,其他 cwd 有效性校验保持不变。最佳努力且幂等。
- if let Err(e) = workspace_patch::apply(&app_handle) {
+ if let Err(e) = crate::service::patch::workspace::apply(&app_handle) {
log::warn!("workspace worktree membership patch failed: {e}");
}
// 当前 DSH client-HMR 会卸载第三方插件却不重新挂载。debug 直接联接本地
// 插件源码,故将 rebuilt 降级为自动刷新页面;release 保持上游行为。
- if let Err(e) = client_hmr_patch::apply(&app_handle) {
+ if let Err(e) = crate::service::patch::client_hmr::apply(&app_handle) {
log::warn!("debug client plugin reload fallback patch failed: {e}");
}
// 预防性处理:pnpm 在无 TTY 环境(dsh-market 等子进程)下重装/更新插件时,
diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs
index 99f2e5b6..670dfa1b 100644
--- a/src-tauri/src/utils/mod.rs
+++ b/src-tauri/src/utils/mod.rs
@@ -1,5 +1,72 @@
+use std::path::PathBuf;
+
use tauri::{AppHandle, Manager, Runtime, WebviewWindow};
+use crate::config;
+use crate::service::core::{active_source, local_core_package_dir, CoreSource};
+
+/// 对某个 dsh 包文件的一次性幂等补丁判定结果。
+#[derive(Debug, PartialEq, Eq)]
+pub enum PatchOutcome {
+ /// 目标已含补丁标记(本补丁已生效,或上游官方已合并),无需再改。
+ AlreadyPatched,
+ /// 锚点缺失(上游布局变更),跳过并向调用方说明降级兜底。
+ AnchorMissing,
+ /// 已生成补丁后的完整内容。
+ Patched(String),
+}
+
+/// 活动核心安装目录:本地核心用其包目录(全局安装路径),预打包用桌面端目录。
+///
+/// 与 [`crate::service::core::active_dsh_binary`] 的取舍一致——本地核心解析在调用
+/// 瞬间失效时回退预打包目录,绝不让补丁打到永不加载的预打包文件上。
+fn active_core_install_dir(app_handle: &tauri::AppHandle) -> PathBuf {
+ match active_source(app_handle) {
+ CoreSource::Local => local_core_package_dir(app_handle)
+ .unwrap_or_else(|| config::get_dsh_install_path(app_handle)),
+ CoreSource::App => config::get_dsh_install_path(app_handle),
+ }
+}
+
+/// 对活动核心安装目录下的某个 dsh 包文件应用一次性幂等补丁。
+///
+/// - `rel_path`:相对活动核心安装目录的包内路径,例如
+/// `node_modules/@deepseek-ai/dsh-client-ui-renderer/lib/client.js`(即 `patch_dsh("packagename/xxx/xxx.js", ..)` 里的包路径)。
+/// - `patch`:纯函数式补丁判定,输入文件原文、返回 [`PatchOutcome`];只做内容变换,
+/// 不触碰文件系统,便于单测。
+///
+/// 统一处理「定位文件 → 读取 → 打补丁 → 写回」与对应的日志。文件缺失、已打过、
+/// 锚点变更均静默跳过并返回 Ok;只有真实读/写失败才返回 Err(不阻断启动的调用方
+/// 据此仅告警)。活动核心的判定与 [`active_core_install_dir`] 一致。
+pub fn patch_dsh(
+ app_handle: &tauri::AppHandle,
+ rel_path: &str,
+ patch: impl FnOnce(&str) -> PatchOutcome,
+) -> Result<(), String> {
+ let target = active_core_install_dir(app_handle).join(rel_path);
+ if !target.exists() {
+ log::info!("dsh patch target not found, skip: {}", target.display());
+ return Ok(());
+ }
+ let source = std::fs::read_to_string(&target)
+ .map_err(|e| format!("DSH_PATCH_READ: {} failed: {e}", target.display()))?;
+ match patch(&source) {
+ PatchOutcome::AlreadyPatched => {
+ log::info!("dsh patch already applied: {}", target.display());
+ }
+ PatchOutcome::AnchorMissing => {
+ log::warn!("dsh patch anchor missing, skip: {}", target.display());
+ }
+ PatchOutcome::Patched(patched) => {
+ std::fs::write(&target, patched).map_err(|e| {
+ format!("DSH_PATCH_WRITE: {} failed: {e}", target.display())
+ })?;
+ log::info!("dsh patch applied: {}", target.display());
+ }
+ }
+ Ok(())
+}
+
pub fn show_window<R: Runtime>(window: &WebviewWindow<R>) {
let _ = window.unminimize();
let _ = window.show();