Skip to content

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

fix(preinstall): 修 shim 转发重复展开参数与 dsh plugin 动作动词重复

hairyf1ff1a59715a5
diff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rs
index 941c7677..991f30bc 100644
--- a/src-tauri/src/service/cli/shim/build.rs
+++ b/src-tauri/src/service/cli/shim/build.rs
@@ -188,7 +188,11 @@ exec "$NODE" "$DSH_BIN" "$@"
///
/// 实现要点:
/// - 不用 `findstr` 匹配路径(`\` 会被当正则转义导致过滤失效);
-/// - 块内变量判断用 for 变量(`%%~xp`)而非 `%VAR%`(块解析时机陷阱)。
+/// - 块内变量判断用 for 变量(`%%~xp`)而非 `%VAR%`(块解析时机陷阱);
+/// - 转发用户/选定 pnpm 时直接调用目标、**不得用 `call`**:批处理会把原始 `%*`
+/// 再展开一次,`call` 即多出一层解释,把调用方(execa 只按单层批处理转义)
+/// 已经转义好的 `^` 翻倍成 `^^`,`pnpm add "x@^0.21.1"` 因此整批失败
+/// (issue #715)。Unix 侧用 `exec` 转发本就没有多余层,此处与之一致。
#[cfg_attr(all(not(windows), not(test)), allow(dead_code))] // 仅 Windows 的 shim 落盘与单测使用
pub fn build_pnpm_cmd_shim(paths: &ShimPaths) -> String {
normalize_cmd_line_endings(format!(
@@ -219,9 +223,7 @@ rem Re-entry guard: DSH_PNPM, or the first pnpm found on PATH, may itself be a s
rem that resolves back through PATH into this file; forwarding twice would exec the
rem two shims into each other forever and the installer child would never exit.
rem Armed once here, before either forward, and checked on entry: a re-entered shim
-rem goes straight to the bundled pnpm. The forwarding blocks below therefore stay
-rem byte-identical to the issue #130 fix, whose exit-code propagation depends on
-rem `exit /b %ERRORLEVEL%` sitting directly after `call` outside any block.
+rem goes straight to the bundled pnpm.
if "%DSH_PNPM_SHIM_GUARD%"=="1" goto :after_user
set "DSH_PNPM_SHIM_GUARD=1"
@@ -252,12 +254,23 @@ if defined USER_PNPM goto :use_user
goto :after_user
+rem Forward by invoking the target directly, never through `call`. `cmd.exe` hands
+rem the raw `%*` to a batch file, which re-expands it once more, so `call` adds a
+rem second interpretation layer on top of the one the caller already accounted for.
+rem `dsh plugin` starts pnpm through execa, which caret-escapes every argument
+rem exactly once for the single batch hop it resolves (this shim); the extra layer
+rem turned `dsh-better-sidebar@^0.21.1` into `^^0.21.1` (issue #715: pnpm failed
+rem with ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER, so no preset plugin installed)
+rem and mangled `%`/`&` in other arguments as well. Handing `%*` straight to the
+rem target keeps arguments byte-identical. A batch target transfers control, so its
+rem exit code is ours; a `.exe`/`.com` target returns, and `exit /b %ERRORLEVEL%`
+rem still forwards its code (issue #130).
:use_selected
-call "%DSH_PNPM%" %*
+"%DSH_PNPM%" %*
exit /b %ERRORLEVEL%
:use_user
-call "%USER_PNPM%" %*
+"%USER_PNPM%" %*
exit /b %ERRORLEVEL%
:after_user
@@ -529,7 +542,7 @@ mod tests {
assert!(content.contains(&paths.pnpm_bin.to_string_lossy().to_string()));
assert!(content.contains("where pnpm"));
assert!(content.contains("SELF_PREFIX"));
- assert!(content.contains(r#"call "%USER_PNPM%" %*"#));
+ assert!(content.contains(r#""%USER_PNPM%" %*"#));
assert!(content.contains(":use_bundled"));
assert!(content.contains(&paths.node_bin.to_string_lossy().to_string()));
// 应用内部安装可经 DSH_PREFER_BUNDLED_PNPM=1 强制捆绑版(须在用户搜索前生效)
@@ -850,27 +863,115 @@ mod tests {
"{name}: missing re-entry guard"
);
}
- // cmd 在入口一次判断 + 一次置位;转发块保持 issue #130 修复时的原样。
+ // cmd 在入口一次判断 + 一次置位。
let cmd = build_pnpm_cmd_shim(&shim_paths_for(&app_dir));
assert_eq!(cmd.matches("DSH_PNPM_SHIM_GUARD").count(), 2);
assert_eq!(cmd.matches("set \"DSH_PNPM_SHIM_GUARD=1\"").count(), 1);
}
- /// 回归 issue #130:用户 pnpm 的退出码必须原样透出。`exit /b %ERRORLEVEL%`
- /// 一旦落进括号块,或与 `call` 之间插进别的语句,`%ERRORLEVEL%` 就会在块解析
- /// 时提前展开,失败码被吞成 0/1。这里锁死「call 之后紧跟 exit /b %ERRORLEVEL%」。
+ /// 回归 issue #130:用户 pnpm 的退出码必须原样透出,因此 `exit /b %ERRORLEVEL%`
+ /// 必须紧跟转发语句、且不得落进括号块(块解析会提前展开 `%ERRORLEVEL%`,把失败码
+ /// 吞成 0/1)。
+ ///
+ /// 同时锁死 issue #715 的修复:转发**不得用 `call`**——批处理会把原始 `%*` 再展开
+ /// 一次,`call` 即多出一层解释,使 execa 已按单层转义好的 `^` 翻倍成 `^^`。
#[test]
- fn cmd_shim_exit_code_stays_adjacent_to_call() {
+ fn cmd_shim_forwarding_keeps_exit_code_and_never_uses_call() {
let content = build_pnpm_cmd_shim(&sample_shim_paths());
- for call in [r#"call "%DSH_PNPM%" %*"#, r#"call "%USER_PNPM%" %*"#] {
- let expected = format!("{call}\r\nexit /b %ERRORLEVEL%\r\n");
+ for target in [r#""%DSH_PNPM%""#, r#""%USER_PNPM%""#] {
+ let expected = format!("{target} %*\r\nexit /b %ERRORLEVEL%\r\n");
assert!(
content.contains(&expected),
- "`{call}` must be followed directly by `exit /b %ERRORLEVEL%`"
+ "`{target} %*` must be followed directly by `exit /b %ERRORLEVEL%`"
+ );
+ assert!(
+ !content.contains(&format!("call {target}")),
+ "`call {target}` re-expands %* and doubles carets (issue #715)"
);
}
}
+ /// execa 的 `cmd.exe` 元字符转义:每个元字符前缀一个 `^`。
+ /// 见 execa `lib/arguments/command-file.js` 的 `escapeMetaChars`。
+ #[cfg(windows)]
+ fn execa_escape_meta_chars(value: &str) -> String {
+ const META_CHARS: &str = "()][%!^\"`<>&|;, *?";
+ let mut escaped = String::with_capacity(value.len());
+ for character in value.chars() {
+ if META_CHARS.contains(character) {
+ escaped.push('^');
+ }
+ escaped.push(character);
+ }
+ escaped
+ }
+
+ /// execa 对单个参数的转义。目标是 `.cmd`/`.bat` 时它会**双重**转义——只为
+ /// 「批处理会用 `%*` 再展开一次参数」这一层做补偿。测试参数不含反斜杠,
+ /// 故略去 execa 的反斜杠加倍步骤。
+ #[cfg(windows)]
+ fn execa_escape_argument(raw: &str) -> String {
+ execa_escape_meta_chars(&execa_escape_meta_chars(&format!("\"{raw}\"")))
+ }
+
+ /// 回归 issue #715 / #716:`dsh plugin add` 由 `@deepseek-ai/dsh-plugin-manager`
+ /// 经 execa 启动 pnpm,execa 解析到的是本 shim(`.cmd`),因此只按**单层**批处理
+ /// 转义参数。shim 若用 `call` 转发就多出一层 `%*` 再展开,`^` 被翻倍成 `^^`,pnpm
+ /// 报 `ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER`,预设插件整批装不上。
+ /// 这里按 execa 的转义规则构造命令行并真实执行 shim,断言目标收到的参数逐字节不变。
+ #[cfg(windows)]
+ #[test]
+ fn pnpm_cmd_shim_forwards_execa_escaped_caret_spec_unchanged() {
+ use std::os::windows::process::CommandExt;
+
+ let dir = temp_dir("pnpm-caret-forward");
+ let target = dir.join("user pnpm.cmd");
+ std::fs::write(
+ &target,
+ "@echo off\r\necho TARGET_ARGS=[%*]\r\nexit /b 0\r\n",
+ )
+ .unwrap();
+ let shim = dir.join("pnpm.cmd");
+ std::fs::write(
+ &shim,
+ build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),
+ )
+ .unwrap();
+
+ let spec = "dsh-better-sidebar@^0.21.1";
+ // execa 的命令行形如 `"<转义后的文件> <转义后的参数...>"`(整体再包一层引号)
+ let command_line = format!(
+ "\"{}\"",
+ [
+ execa_escape_meta_chars(&shim.to_string_lossy()),
+ execa_escape_argument("add"),
+ execa_escape_argument(spec),
+ ]
+ .join(" ")
+ );
+
+ let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
+ let system32 = PathBuf::from(&system_root).join("System32");
+ let output = std::process::Command::new(system32.join("cmd.exe"))
+ .args(["/d", "/s", "/c"])
+ .raw_arg(&command_line)
+ .env("DSH_PNPM", &target)
+ .env("SystemRoot", &system_root)
+ .output()
+ .unwrap();
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains(spec),
+ "forwarded arguments must keep the single caret, got: {stdout:?}"
+ );
+ assert!(
+ !stdout.contains("^^"),
+ "the shim must not re-expand %* into a doubled caret, got: {stdout:?}"
+ );
+ let _ = std::fs::remove_dir_all(dir);
+ }
+
/// 回归:`DSH_PNPM` 指向的 shim 若按 PATH 解析回本 shim(mise shims 的真实
/// 行为,见 `cli::path::pnpm` 的 mise 目录回退),没有重入保护时两者会互相
/// `exec` 形成死循环——安装子进程永不退出,应用表现为永久卡在
diff --git a/src-tauri/src/service/plugin/install/single.rs b/src-tauri/src/service/plugin/install/single.rs
index 7441a93e..1e36cf79 100644
--- a/src-tauri/src/service/plugin/install/single.rs
+++ b/src-tauri/src/service/plugin/install/single.rs
@@ -37,7 +37,10 @@ pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {
run_single_plugin_command(app_handle, id, "update", &update_pnpm_args(id)).await
}
-/// 升级时转发给 pnpm 的参数:`update <id> --latest`。
+/// 升级时转发给 pnpm 的参数:`<id> --latest`。
+///
+/// `update` 动词不写在这里:它由 [`single_plugin_args`] 作为动作统一放在参数最前,
+/// 重复一次会变成 `pnpm update update <id>`(见该函数的说明)。
///
/// `--latest` 不能省:profile 里的依赖 spec 通常是范围(`catalog:` 或 `^x.y.z`),
/// 裸 `pnpm update` 只在声明范围内取值——档案的 spec 是 `catalog:` 时范围来自
@@ -47,7 +50,7 @@ pub async fn update(app_handle: &AppHandle, id: &str) -> Result<(), String> {
/// pnpm 自己把 catalog 条目改写到新版本;git spec 不受影响(`--latest` 不会把
/// `github:owner/repo` 退化成 semver 范围,实测原样保留)。
fn update_pnpm_args(id: &str) -> Vec<String> {
- vec!["update".to_string(), id.to_string(), "--latest".to_string()]
+ vec![id.to_string(), "--latest".to_string()]
}
/// 依赖的「解析指纹」:profile `pnpm-lock.yaml` 当前 importer(`importers["."]`)
@@ -100,13 +103,8 @@ fn installed_package_version(profile: &Path, id: &str) -> Option<String> {
/// 卸载单个插件:`dsh plugin --profile <当前档案> remove <id>`
pub async fn remove(app_handle: &AppHandle, id: &str) -> Result<(), String> {
- let command_result = run_single_plugin_command(
- app_handle,
- id,
- "remove",
- &["remove".to_string(), id.to_string()],
- )
- .await;
+ let command_result =
+ run_single_plugin_command(app_handle, id, "remove", &[id.to_string()]).await;
// `dsh plugin remove` 以子进程退出码为准,可能出现「命令成功但插件仍在」的
// 边界(如 bundle 层残留、pnpm 静默失败);node_modules / lockfile 损坏时
// (典型:安装只写入了 profile 清单而产物缺失,见 issue #90)pnpm 甚至会
@@ -239,6 +237,24 @@ pub(crate) async fn uninstall_deprecated_plugins(app_handle: &AppHandle) -> Resu
}
}
+/// `dsh plugin` 的参数:`plugin --profile <档案> <action> <sub_args...>`。
+///
+/// `dsh plugin` 把 `--profile` 之后的参数**原样**转发给 pnpm(`dsh plugin --profile
+/// <name> <pnpm-args...>`),所以动作动词只能出现一次:`sub_args` 里再带一次动词,
+/// pnpm 收到的就是 `pnpm remove remove <id>`(issue #715 日志中的 `pnpm remove
+/// remove dshmarket`)——`remove` 会去找一个名为 `remove` 的依赖,卸载/升级因此
+/// 不生效甚至失败。
+fn single_plugin_args(profile: &str, action: &str, sub_args: &[String]) -> Vec<OsString> {
+ let mut args = vec![
+ OsString::from("plugin"),
+ OsString::from("--profile"),
+ OsString::from(profile),
+ OsString::from(action),
+ ];
+ args.extend(sub_args.iter().map(OsString::from));
+ args
+}
+
/// 执行单个插件的升级/卸载:准备环境 → 停止服务 → 运行 `dsh plugin` →
/// 失败记录错误、成功清除错误。
async fn run_single_plugin_command(
@@ -308,14 +324,12 @@ async fn run_single_plugin_command(
None
};
- let mut args = vec![
- dsh_bin.as_os_str().to_os_string(),
- OsString::from("plugin"),
- OsString::from("--profile"),
- OsString::from(active_profile(app_handle)),
- OsString::from(action),
- ];
- args.extend(sub_args.iter().map(OsString::from));
+ let mut args = vec![dsh_bin.as_os_str().to_os_string()];
+ args.extend(single_plugin_args(
+ &active_profile(app_handle),
+ action,
+ sub_args,
+ ));
let cwd = config::get_dsh_install_path(app_handle);
log::info!("Running dsh plugin {action} for {id}");
@@ -639,8 +653,45 @@ mod tests {
// 「退出码 0 但什么都没装」的假成功——正是 sidebar 0.18.1→0.19.0 不生效的根因。
assert_eq!(
update_pnpm_args("dsh-better-sidebar"),
- vec!["update", "dsh-better-sidebar", "--latest"]
+ vec!["dsh-better-sidebar", "--latest"]
+ );
+ }
+
+ /// 回归 issue #715:`dsh plugin` 把动作之后的参数原样转发给 pnpm,动作动词因此
+ /// 只能出现一次。升级/卸载曾把动词同时放进 `action` 与 `sub_args`,实际执行
+ /// `pnpm remove remove <id>`、`pnpm update update <id> --latest`。
+ #[test]
+ fn single_plugin_args_keep_the_pnpm_verb_once() {
+ let remove = single_plugin_args("tauri", "remove", &["dshmarket".to_string()]);
+ assert_eq!(
+ remove,
+ vec!["plugin", "--profile", "tauri", "remove", "dshmarket"]
+ );
+
+ let update = single_plugin_args("tauri", "update", &update_pnpm_args("dsh-better-sidebar"));
+ assert_eq!(
+ update,
+ vec![
+ "plugin",
+ "--profile",
+ "tauri",
+ "update",
+ "dsh-better-sidebar",
+ "--latest"
+ ]
);
+
+ for (action, args) in [("remove", &remove), ("update", &update)] {
+ let joined: Vec<String> = args
+ .iter()
+ .map(|argument| argument.to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(
+ joined.iter().filter(|argument| *argument == action).count(),
+ 1,
+ "{action} must appear exactly once in {joined:?}"
+ );
+ }
}
/// 造一个最小 profile:写入 `pnpm-lock.yaml` 与 `node_modules/dsh-probe/package.json`。
diff --git a/src-tauri/src/service/plugin/install/spec.rs b/src-tauri/src/service/plugin/install/spec.rs
index 117f1521..b5e3e5b3 100644
--- a/src-tauri/src/service/plugin/install/spec.rs
+++ b/src-tauri/src/service/plugin/install/spec.rs
@@ -248,6 +248,14 @@ mod tests {
preset_spec_for_install(&p, None, None).unwrap(),
"dsh-better-sidebar"
);
+
+ // issue #715:清单区间本身就带 `^`,拼接只能再加一个 `@`——出现 `^^` 会让 pnpm
+ // 报 ERR_PNPM_SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER,而预设插件共用同一条 `add`
+ // 调用,一个坏 spec 就让整批预设都装不上(应用卡在加载中,见 issue #716)。
+ for core in ["0.1.5-rc.3", "0.1.7-rc.1", "0.1.7-rc.2", "0.2.0"] {
+ let spec = preset_spec_for_install(&p, None, Some(core)).unwrap();
+ assert!(!spec.contains("^^"), "core={core}: {spec}");
+ }
}
#[test]