Skip to content

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

86.5 KB
Raw Blame
//! shim 脚本内容生成:`dsh` / `pnpm` 的 cmd、ps1、sh 包装脚本构建函数。
//! 各构建函数是纯函数(便于测试),落盘见 [`super::write`]。
//! shim 文本必须全英文:cmd/ps1 按系统代码页解析,中文注释会乱码成命令执行。

use std::path::{Path, PathBuf};

use super::escape_path_ps1;
use super::escape_path_sh;
use super::portable_path_cmd;
#[cfg(not(windows))]
use super::templates::SH_USER_DSH_PRECEDENCE;
use super::templates::{
    CMD_NODE_RESOLVE, CMD_USER_DSH_PRECEDENCE, PS1_NODE_RESOLVE, PS1_USER_DSH_PRECEDENCE,
    SH_NODE_RESOLVE,
};

/// shim 内烘焙的依赖路径:全部来自运行时解析(依赖映射表 + 清单 `entry`),
/// 因此 shim 不再假设 AppData 下的 `dependencies/<name>` 布局,也不依赖
/// `APP_DIR` 推导——依赖可以被映射到任意位置(含 `resources/*` 捆绑副本)。
#[derive(Debug, Clone)]
pub struct ShimPaths {
    /// node 可执行文件绝对路径
    pub node_bin: PathBuf,
    /// dsh `bin.js` 绝对路径
    pub dsh_bin: PathBuf,
    /// pnpm `pnpm.cjs` 绝对路径
    pub pnpm_bin: PathBuf,
    /// 捆绑 MinGit 的 `cmd` 目录(系统 Git 缺 HTTPS helper 时注入 PATH)
    pub bundled_git_dir: Option<PathBuf>,
}

impl ShimPaths {
    /// node 所在目录(注入 PATH 用)
    fn node_dir(&self) -> PathBuf {
        self.node_bin
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_default()
    }

    fn git_dir(&self) -> PathBuf {
        self.bundled_git_dir.clone().unwrap_or_default()
    }
}

/// Windows `.cmd` 统一为 CRLF 行尾。
///
/// 批处理由 `cmd.exe` 按行解析,本文件被 `.gitattributes` 固定为 LF(`*.rs
/// text eol=lf`),Rust 多行字符串里的 LF 会原样落盘。LF-only 的 `.cmd` 在部分
/// Windows 环境下会让批处理 label/括号块的解析错位,命令以退出码 1 结束
/// (issue #581:`dsh plugin install` 因此全部失败)。所有 `.cmd` 内容在返回前
/// 转换,落盘即与手写的 Windows 批处理一致。
fn normalize_cmd_line_endings(content: String) -> String {
    content.replace("\r\n", "\n").replace('\n', "\r\n")
}

// ---------------------------------------------------------------------------
// dsh shim
// ---------------------------------------------------------------------------

/// Windows `dsh.cmd` 内容。`paths` 为解析后的依赖入口路径,`dsh_home` 为官方
/// `$DSH_HOME`(release 为 `~/.dsh`,生成时写死,与桌面端/官方一致)。
#[cfg_attr(debug_assertions, allow(dead_code))] // 仅 release 构建写入 dsh shim
pub fn build_cmd_shim(paths: &ShimPaths, dsh_home: &Path) -> String {
    normalize_cmd_line_endings(format!(
        r#"@echo off
rem DeepSeek Harness Desktop - dsh command shim (generated)
rem Do not edit: regenerated by the desktop app on install/startup.
setlocal
set "NODE_BIN={node_bin}"
set "NODE_DIR={node_dir}"
rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.
rem Never export it as GIT_DIR: that variable names a repository, not a bin dir.
set "SYSTEM_GIT_WORKS="
for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"
if not defined SYSTEM_GIT_WORKS if exist "{git_dir}\git.exe" set "PATH={git_dir};%PATH%"
{user_dsh}
set "DSH_BIN={dsh_bin}"
set "DSH_HOME={dsh_home}"
set "DSH_TELEMETRY_DISABLED=1"
{node_resolve}
:launch
if not exist "%DSH_BIN%" goto :no_cli
"%NODE%" "%DSH_BIN%" %*
exit /b %ERRORLEVEL%

:no_cli
echo [dsh] Harness CLI not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1

:no_node
echo [dsh] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1
"#,
        node_bin = portable_path_cmd(&paths.node_bin),
        node_dir = portable_path_cmd(&paths.node_dir()),
        git_dir = portable_path_cmd(&paths.git_dir()),
        dsh_bin = portable_path_cmd(&paths.dsh_bin),
        dsh_home = portable_path_cmd(dsh_home),
        user_dsh = CMD_USER_DSH_PRECEDENCE,
        node_resolve = CMD_NODE_RESOLVE,
    ))
}

/// Windows `dsh.ps1` 内容
#[cfg_attr(debug_assertions, allow(dead_code))] // 仅 release 构建写入 dsh shim
pub fn build_ps1_shim(paths: &ShimPaths, dsh_home: &Path) -> String {
    format!(
        r#"# DeepSeek Harness Desktop - dsh command shim (generated)
# Do not edit: regenerated by the desktop app on install/startup.
$ErrorActionPreference = "Stop"
$nodeBin = '{node_bin}'
$nodeDir = '{node_dir}'
$gitDir = '{git_dir}'
$dshBin = '{dsh_bin}'
# Use bundled MinGit only when system Git lacks its HTTPS transport helper.
$systemGitWorks = $false
try {{
    $gitExecPath = & git --exec-path 2> $null
    $systemGitWorks = ($LASTEXITCODE -eq 0) -and (Test-Path -LiteralPath (Join-Path $gitExecPath 'git-remote-https.exe'))
}} catch {{}}
if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe'))) {{
    $env:PATH = $gitDir + ';' + $env:PATH
}}
{user_dsh}
$dshHome = '{dsh_home}'
$env:DSH_TELEMETRY_DISABLED = '1'
{node_resolve}
if (-not (Test-Path -LiteralPath $dshBin)) {{
    Write-Error '[dsh] Harness CLI not found. Please run DeepSeek Harness Desktop to install it first.'
    exit 1
}}
$env:DSH_HOME = $dshHome
& $node $dshBin @args
exit $LASTEXITCODE
"#,
        node_bin = escape_path_ps1(&paths.node_bin),
        node_dir = escape_path_ps1(&paths.node_dir()),
        git_dir = escape_path_ps1(&paths.git_dir()),
        dsh_bin = escape_path_ps1(&paths.dsh_bin),
        user_dsh = PS1_USER_DSH_PRECEDENCE,
        node_resolve = PS1_NODE_RESOLVE,
        dsh_home = escape_path_ps1(dsh_home),
    )
}

/// Unix `dsh` shell 脚本内容(POSIX sh)
#[cfg(not(windows))]
#[cfg_attr(debug_assertions, allow(dead_code))] // 仅 release 构建写入 dsh shim
pub fn build_sh_shim(paths: &ShimPaths, dsh_home: &Path) -> String {
    format!(
        r#"#!/bin/sh
# DeepSeek Harness Desktop - dsh command shim (generated)
# Do not edit: regenerated by the desktop app on install/startup.
NODE_BIN='{node_bin}'
NODE_DIR='{node_dir}'
DSH_BIN='{dsh_bin}'
{user_dsh}
export DSH_HOME='{dsh_home}'
export DSH_TELEMETRY_DISABLED=1
{node_resolve}
if [ ! -f "$DSH_BIN" ]; then
  echo "[dsh] Harness CLI not found. Please run DeepSeek Harness Desktop to install it first." >&2
  exit 1
fi
exec "$NODE" "$DSH_BIN" "$@"
"#,
        node_bin = escape_path_sh(&paths.node_bin),
        node_dir = escape_path_sh(&paths.node_dir()),
        dsh_bin = escape_path_sh(&paths.dsh_bin),
        user_dsh = SH_USER_DSH_PRECEDENCE,
        dsh_home = escape_path_sh(dsh_home),
        node_resolve = SH_NODE_RESOLVE,
    )
}

// ---------------------------------------------------------------------------
// pnpm shim(额外带"用户 pnpm 优先"逻辑,见各函数注释)
//
// `DSH_PREFER_BUNDLED_PNPM=1`(应用内部插件安装注入,见 service/plugin/install.rs)
// 时改为捆绑版优先:跳过用户 pnpm 直接运行捆绑 pnpm.cjs,仅当捆绑缺失时回退
// 用户 pnpm。默认(未设置)行为不变:用户 pnpm 优先。
// ---------------------------------------------------------------------------

/// Windows `pnpm.cmd` 内容:优先转发用户自己安装的 pnpm(`where pnpm` 遍历、
/// 跳过本 shim 目录、只收 `.cmd/.exe/.bat`),否则用 node 运行捆绑 pnpm.cjs。
/// `DSH_PREFER_BUNDLED_PNPM=1` 时捆绑版优先(见模块头注)。
///
/// 实现要点:
/// - 不用 `findstr` 匹配路径(`\` 会被当正则转义导致过滤失效);
/// - 块内变量判断用 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!(
        r#"@echo off
rem DeepSeek Harness Desktop - pnpm command shim (generated)
rem Do not edit: regenerated by the desktop app on install/startup.
setlocal
set "NODE_BIN={node_bin}"
set "NODE_DIR={node_dir}"
set "PNPM_BIN={pnpm_bin}"
rem Runtime override: this file is read through the console code page, so a baked
rem path containing non-ASCII (e.g. user name) is corrupted on parse. The desktop
rem app passes the real path in DSH_PNPM_BIN, which arrives as UTF-16 and is safe.
if exist "%DSH_PNPM_BIN%" set "PNPM_BIN=%DSH_PNPM_BIN%"
rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.
rem Never export it as GIT_DIR: that variable names a repository, not a bin dir.
set "SYSTEM_GIT_WORKS="
for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"
if not defined SYSTEM_GIT_WORKS if exist "{git_dir}\git.exe" set "PATH={git_dir};%PATH%"

rem App-internal installs (DSH_PREFER_BUNDLED_PNPM=1) use the bundled pnpm,
rem falling back to the user's only when the bundled one is missing.
if "%DSH_PREFER_BUNDLED_PNPM%"=="1" (
  if exist "%PNPM_BIN%" goto :after_user
)

if "%DSH_PNPM_SHIM_GUARD%"=="1" if exist "%PNPM_BIN%" goto :after_user
set "DSH_PNPM_SHIM_GUARD=1"

rem Use the exact user pnpm discovered by the desktop app.
if defined DSH_PNPM (
  if exist "%DSH_PNPM%" goto :use_selected
)

rem Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.
rem Accept only executable extensions (.cmd/.exe/.bat), ignore extensionless shell scripts.
set "SELF_PREFIX=%~dp0"
set "SELF_PREFIX=%SELF_PREFIX:~0,-1%"
set "USER_PNPM="
for /f "delims=" %%p in ('where pnpm 2^>nul') do (
  if not defined USER_PNPM (
    if /i not "%%p"=="%SELF_PREFIX%\pnpm.cmd" (
      if /i not "%%p"=="%SELF_PREFIX%\pnpm.exe" (
        if /i not "%%p"=="%SELF_PREFIX%\pnpm.bat" (
          if /i "%%~xp"==".cmd" set "USER_PNPM=%%p"
          if /i "%%~xp"==".exe" set "USER_PNPM=%%p"
          if /i "%%~xp"==".bat" set "USER_PNPM=%%p"
        )
      )
    )
  )
)
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
if exist "%PNPM_BIN%" goto :forward_selected
if defined DSH_PNPM_SHIM_CHAIN goto :append_selected
set "DSH_PNPM_SHIM_CHAIN=1"
goto :forward_selected
:append_selected
if not "%DSH_PNPM_SHIM_CHAIN:~15,1%"=="" goto :reentry_limit
set "DSH_PNPM_SHIM_CHAIN=%DSH_PNPM_SHIM_CHAIN%1"
:forward_selected
"%DSH_PNPM%" %*
exit /b %ERRORLEVEL%

:use_user
if exist "%PNPM_BIN%" goto :forward_user
if defined DSH_PNPM_SHIM_CHAIN goto :append_user
set "DSH_PNPM_SHIM_CHAIN=1"
goto :forward_user
:append_user
if not "%DSH_PNPM_SHIM_CHAIN:~15,1%"=="" goto :reentry_limit
set "DSH_PNPM_SHIM_CHAIN=%DSH_PNPM_SHIM_CHAIN%1"
:forward_user
"%USER_PNPM%" %*
exit /b %ERRORLEVEL%

:reentry_limit
1>&2 echo [pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.
exit /b 1

:after_user
{node_resolve}
:launch
if not exist "%PNPM_BIN%" goto :no_pnpm
"%NODE%" "%PNPM_BIN%" %*
exit /b %ERRORLEVEL%

:no_pnpm
echo [pnpm] pnpm not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1

:no_node
echo [pnpm] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1
"#,
        node_bin = portable_path_cmd(&paths.node_bin),
        node_dir = portable_path_cmd(&paths.node_dir()),
        git_dir = portable_path_cmd(&paths.git_dir()),
        pnpm_bin = portable_path_cmd(&paths.pnpm_bin),
        node_resolve = CMD_NODE_RESOLVE,
    ))
}

/// Windows `pnpm.ps1` 内容:优先转发用户 pnpm(`Get-Command pnpm -All`,
/// 排除本 shim 目录),否则用 node 运行捆绑 pnpm.cjs。
/// `DSH_PREFER_BUNDLED_PNPM=1` 时捆绑版优先(见模块头注)。
#[cfg_attr(all(not(windows), not(test)), allow(dead_code))] // 仅 Windows 的 shim 落盘与单测使用
pub fn build_pnpm_ps1_shim(paths: &ShimPaths) -> String {
    format!(
        r#"# DeepSeek Harness Desktop - pnpm command shim (generated)
# Do not edit: regenerated by the desktop app on install/startup.
$ErrorActionPreference = "Stop"
$nodeBin = '{node_bin}'
$nodeDir = '{node_dir}'
$gitDir = '{git_dir}'
$pnpmBin = '{pnpm_bin}'
# Runtime override: the baked literal may be non-ASCII; the desktop app passes the
# real path in DSH_PNPM_BIN (see the cmd shim note).
if ($env:DSH_PNPM_BIN -and (Test-Path -LiteralPath $env:DSH_PNPM_BIN -PathType Leaf)) {{ $pnpmBin = $env:DSH_PNPM_BIN }}
# Use bundled MinGit only when system Git lacks its HTTPS transport helper.
$systemGitWorks = $false
try {{
    $gitExecPath = & git --exec-path 2> $null
    $systemGitWorks = ($LASTEXITCODE -eq 0) -and (Test-Path -LiteralPath (Join-Path $gitExecPath 'git-remote-https.exe'))
}} catch {{}}
if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe'))) {{
    $env:PATH = $gitDir + ';' + $env:PATH
}}

$hasBundled = Test-Path -LiteralPath $pnpmBin -PathType Leaf
$useBundled = $env:DSH_PREFER_BUNDLED_PNPM -eq '1' -and $hasBundled

if (-not $useBundled -and -not ($hasBundled -and $env:DSH_PNPM_SHIM_GUARD -eq '1')) {{
    # The guard must not outlive this call: `$env:` writes are process-wide, so a
    # forwarded pnpm would leave DSH_PNPM_SHIM_GUARD set in the caller's shell and
    # send every later pnpm call straight to the bundled one. The cmd shim is
    # immune through `setlocal`; PowerShell has no equivalent.
    $guardBefore = $env:DSH_PNPM_SHIM_GUARD
    $chainBefore = $env:DSH_PNPM_SHIM_CHAIN

    # Use the exact user pnpm discovered by the desktop app.
    if ($env:DSH_PNPM -and (Test-Path -LiteralPath $env:DSH_PNPM -PathType Leaf)) {{
        try {{
            if (-not $hasBundled) {{
                if ($chainBefore.Length -ge 16) {{
                    [Console]::Error.WriteLine('[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.')
                    exit 1
                }}
                $env:DSH_PNPM_SHIM_CHAIN = $chainBefore + '1'
            }}
            $env:DSH_PNPM_SHIM_GUARD = '1'
            & $env:DSH_PNPM @args
        }} finally {{
            $env:DSH_PNPM_SHIM_GUARD = $guardBefore
            $env:DSH_PNPM_SHIM_CHAIN = $chainBefore
        }}
        exit $LASTEXITCODE
    }}

    # Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.
    $selfDir = $PSScriptRoot.TrimEnd('\') + '\'
    $userPnpm = Get-Command pnpm -All -ErrorAction SilentlyContinue |
        Where-Object {{ $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) }} |
        Select-Object -First 1
    if ($userPnpm) {{
        try {{
            if (-not $hasBundled) {{
                if ($chainBefore.Length -ge 16) {{
                    [Console]::Error.WriteLine('[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls.')
                    exit 1
                }}
                $env:DSH_PNPM_SHIM_CHAIN = $chainBefore + '1'
            }}
            $env:DSH_PNPM_SHIM_GUARD = '1'
            & $userPnpm.Source @args
        }} finally {{
            $env:DSH_PNPM_SHIM_GUARD = $guardBefore
            $env:DSH_PNPM_SHIM_CHAIN = $chainBefore
        }}
        exit $LASTEXITCODE
    }}
}}

{node_resolve}

if (-not (Test-Path -LiteralPath $pnpmBin)) {{
    Write-Error '[pnpm] pnpm not found. Please run DeepSeek Harness Desktop to install it first.'
    exit 1
}}
& $node $pnpmBin @args
exit $LASTEXITCODE
"#,
        node_bin = escape_path_ps1(&paths.node_bin),
        node_dir = escape_path_ps1(&paths.node_dir()),
        git_dir = escape_path_ps1(&paths.git_dir()),
        pnpm_bin = escape_path_ps1(&paths.pnpm_bin),
        node_resolve = PS1_NODE_RESOLVE,
    )
}

/// Unix `pnpm` shell 脚本内容(POSIX sh):按 PATH 顺序转发第一个非本目录
/// 的用户 pnpm,否则用 node 运行捆绑 pnpm.cjs。`DSH_PREFER_BUNDLED_PNPM=1`
/// 时捆绑版优先(见模块头注)。
#[cfg_attr(all(windows, not(test)), allow(dead_code))]
pub fn build_pnpm_sh_shim(paths: &ShimPaths) -> String {
    format!(
        r#"#!/bin/sh
# DeepSeek Harness Desktop - pnpm command shim (generated)
# Do not edit: regenerated by the desktop app on install/startup.
NODE_BIN='{node_bin}'
NODE_DIR='{node_dir}'
PNPM_BIN='{pnpm_bin}'
# Runtime override: the desktop app passes the real bundled pnpm path here.
if [ -n "$DSH_PNPM_BIN" ] && [ -f "$DSH_PNPM_BIN" ]; then PNPM_BIN="$DSH_PNPM_BIN"; fi

USE_BUNDLED=
if [ "$DSH_PREFER_BUNDLED_PNPM" = "1" ] && [ -f "$PNPM_BIN" ]; then
  USE_BUNDLED=1
fi

if [ -z "$USE_BUNDLED" ] && ! {{ [ "$DSH_PNPM_SHIM_GUARD" = "1" ] && [ -f "$PNPM_BIN" ]; }}; then
  # Use the exact user pnpm discovered by the desktop app unless bundled was requested.
  if [ -n "$DSH_PNPM" ] && [ -x "$DSH_PNPM" ]; then
    if [ ! -f "$PNPM_BIN" ]; then
      if [ "${{#DSH_PNPM_SHIM_CHAIN}}" -ge 16 ]; then
        echo "[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls." >&2
        exit 1
      fi
      DSH_PNPM_SHIM_CHAIN="${{DSH_PNPM_SHIM_CHAIN}}1"
      export DSH_PNPM_SHIM_CHAIN
    fi
    DSH_PNPM_SHIM_GUARD=1
    export DSH_PNPM_SHIM_GUARD
    exec "$DSH_PNPM" "$@"
  fi

  # Prefer a user-installed pnpm (skip our own shim dir), fall back to bundled.
  SELF_DIR=$(cd "$(dirname "$0")" && pwd)
  IFS=:
  for dir in $PATH; do
    if [ "$dir" = "$SELF_DIR" ]; then
      continue
    fi
    if [ -x "$dir/pnpm" ]; then
      if [ ! -f "$PNPM_BIN" ]; then
        if [ "${{#DSH_PNPM_SHIM_CHAIN}}" -ge 16 ]; then
          echo "[pnpm] PNPM_REENTRY_LIMIT: Recursive forwarding exceeded 16 calls." >&2
          exit 1
        fi
        DSH_PNPM_SHIM_CHAIN="${{DSH_PNPM_SHIM_CHAIN}}1"
        export DSH_PNPM_SHIM_CHAIN
      fi
      DSH_PNPM_SHIM_GUARD=1
      export DSH_PNPM_SHIM_GUARD
      exec "$dir/pnpm" "$@"
    fi
  done
  unset IFS
fi

{node_resolve}

if [ ! -f "$PNPM_BIN" ]; then
  echo "[pnpm] pnpm not found. Please run DeepSeek Harness Desktop to install it first." >&2
  exit 1
fi
exec "$NODE" "$PNPM_BIN" "$@"
"#,
        node_bin = escape_path_sh(&paths.node_bin),
        node_dir = escape_path_sh(&paths.node_dir()),
        pnpm_bin = escape_path_sh(&paths.pnpm_bin),
        node_resolve = SH_NODE_RESOLVE,
    )
}

// ---------------------------------------------------------------------------
// npx / npm shim(用 node 运行 npm 自带的 cli 入口)
//
// 这两个名字在应用自身 bin 目录里必须存在:插件安装器与 MCP 服务端常以
// `cmd /c npx -y <pkg>` 拉起,而用户 PATH 上的 npx 可能是 npm 官方安装器留
// 下的相对路径包装(`%~dp0` 自指),一旦 node 不在同一目录就会静默失败或
// 长时间卡住。cli 入口按「与所选 node 同目录的 npm 安装」→「应用捆绑 node 的
// 同级 npm」→「PATH 上的用户 npx」顺序解析,全部只依赖已烘焙的绝对路径。
// ---------------------------------------------------------------------------

fn build_npm_cli_cmd_shim(
    paths: &ShimPaths,
    shim_name: &str,
    cli_file: &str,
    bundled_cli: &Path,
) -> String {
    normalize_cmd_line_endings(format!(
        r#"@echo off
rem DeepSeek Harness Desktop - {shim_name} command shim (generated)
rem Do not edit: regenerated by the desktop app on install/startup.
setlocal
set "NODE_BIN={node_bin}"
set "NODE_DIR={node_dir}"
rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.
rem Never export it as GIT_DIR: that variable names a repository, not a bin dir.
set "SYSTEM_GIT_WORKS="
for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"
if not defined SYSTEM_GIT_WORKS if exist "{git_dir}\git.exe" set "PATH={git_dir};%PATH%"
{node_resolve}
rem CMD_NODE_RESOLVE jumps here for every node it accepts, so the cli lookup
rem below must sit at :launch rather than after a separate label.
:launch
rem The cli entry ships with npm, so it is looked up next to the node that will
rem run it: a version manager's node directory may hold no npm at all, and a
rem relative wrapper cannot reach one.
set "NPM_CLI="
set "NPM_NODE_DIR="
if /i "%NODE%"=="node" goto :npm_node_from_path
for %%c in ("%NODE%") do set "NPM_NODE_DIR=%%~dpc"
goto :npm_node_dir_ready
:npm_node_from_path
for /f "delims=" %%c in ('where node 2^>nul') do if not defined NPM_NODE_DIR set "NPM_NODE_DIR=%%~dpc"
:npm_node_dir_ready
rem Issue #1042: version-manager launchers are not the actual Node installation.
for /f "delims=" %%c in ('""%NODE%" -p "process.execPath" 2^>nul"') do if exist "%%c" set "NPM_NODE_DIR=%%~dpc"
for %%c in (
  "%NPM_NODE_DIR%node_modules\npm\bin\{cli_file}"
  "%NPM_NODE_DIR%lib\node_modules\npm\bin\{cli_file}"
  "%NPM_NODE_DIR%..\lib\node_modules\npm\bin\{cli_file}"
) do if not defined NPM_CLI if exist "%%~c" set "NPM_CLI=%%~c"
if defined NPM_CLI goto :npm_run
rem The bundled runtime always carries its own npm installation.
if exist "{bundled_cli}" set "NPM_CLI={bundled_cli}"
if defined NPM_CLI goto :npm_run

rem No usable npm next to node: forward the user's own {shim_name} instead
rem (skipping our own shim dir, and only executable extensions).
set "SELF_PREFIX=%~dp0"
set "SELF_PREFIX=%SELF_PREFIX:~0,-1%"
set "USER_NPM="
for /f "delims=" %%p in ('where {shim_name} 2^>nul') do (
  if not defined USER_NPM (
    if /i not "%%p"=="%SELF_PREFIX%\{shim_name}.cmd" (
      if /i not "%%p"=="%SELF_PREFIX%\{shim_name}.exe" (
        if /i not "%%p"=="%SELF_PREFIX%\{shim_name}.bat" (
          if /i "%%~xp"==".cmd" set "USER_NPM=%%p"
          if /i "%%~xp"==".exe" set "USER_NPM=%%p"
          if /i "%%~xp"==".bat" set "USER_NPM=%%p"
        )
      )
    )
  )
)
if not defined USER_NPM goto :no_npm
if not defined DSH_NPM_SHIM_CHAIN goto :npm_forward_user
for %%c in ("%DSH_NPM_SHIM_CHAIN:;=" "%") do if /i "%%~c"=="%USER_NPM%" goto :npm_reentry_limit
:npm_forward_user
set "DSH_NPM_SHIM_CHAIN=%DSH_NPM_SHIM_CHAIN%;%USER_NPM%"
rem Forward by invoking the target directly, never through `call`: the extra
rem interpretation layer re-expands %* and mangles already-escaped arguments.
"%USER_NPM%" %*
exit /b %ERRORLEVEL%

:npm_run
if not exist "%NPM_CLI%" goto :no_npm
"%NODE%" "%NPM_CLI%" %*
exit /b %ERRORLEVEL%

:npm_reentry_limit
1>&2 echo [{shim_name}] NPM_REENTRY_LIMIT: Recursive forwarding revisited the same command.
exit /b 1

:no_npm
echo [{shim_name}] npm cli not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1

:no_node
echo [{shim_name}] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1
"#,
        node_bin = portable_path_cmd(&paths.node_bin),
        node_dir = portable_path_cmd(&paths.node_dir()),
        git_dir = portable_path_cmd(&paths.git_dir()),
        bundled_cli = portable_path_cmd(bundled_cli),
        shim_name = shim_name,
        cli_file = cli_file,
        node_resolve = CMD_NODE_RESOLVE,
    ))
}

/// Windows `npx.cmd` 内容(见 npx/npm shim 段注释)。
#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
pub fn build_npx_cmd_shim(paths: &ShimPaths) -> String {
    build_npm_cli_cmd_shim(
        paths,
        "npx",
        "npx-cli.js",
        &paths
            .node_dir()
            .join("node_modules")
            .join("npm")
            .join("bin")
            .join("npx-cli.js"),
    )
}

/// Windows `npm.cmd` 内容(见 npx/npm shim 段注释)。
#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
pub fn build_npm_cmd_shim(paths: &ShimPaths) -> String {
    build_npm_cli_cmd_shim(
        paths,
        "npm",
        "npm-cli.js",
        &paths
            .node_dir()
            .join("node_modules")
            .join("npm")
            .join("bin")
            .join("npm-cli.js"),
    )
}

fn build_npm_cli_ps1_shim(
    paths: &ShimPaths,
    shim_name: &str,
    cli_file: &str,
    bundled_cli: &Path,
) -> String {
    format!(
        r#"# DeepSeek Harness Desktop - {shim_name} command shim (generated)
# Do not edit: regenerated by the desktop app on install/startup.
$ErrorActionPreference = "Stop"
$nodeBin = '{node_bin}'
$nodeDir = '{node_dir}'
$gitDir = '{git_dir}'
# Use bundled MinGit only when system Git lacks its HTTPS transport helper.
$systemGitWorks = $false
try {{
    $gitExecPath = & git --exec-path 2> $null
    $systemGitWorks = ($LASTEXITCODE -eq 0) -and (Test-Path -LiteralPath (Join-Path $gitExecPath 'git-remote-https.exe'))
}} catch {{}}
if (-not $systemGitWorks -and $gitDir -and (Test-Path -LiteralPath (Join-Path $gitDir 'git.exe'))) {{
    $env:PATH = $gitDir + ';' + $env:PATH
}}
{node_resolve}
# The cli entry ships with npm, so it is looked up next to the node that will run
# it: a version manager's node directory may hold no npm at all, and a relative
# wrapper cannot reach one.
$nodePath = $node
if ($node -eq 'node') {{
    $nodeCommand = Get-Command node -ErrorAction SilentlyContinue
    if ($nodeCommand) {{ $nodePath = $nodeCommand.Source }}
}}
# Issue #1042: resolve the installation behind a version-manager launcher.
try {{
    $actualNode = & $node -p 'process.execPath' 2>$null
    if ($LASTEXITCODE -eq 0 -and $actualNode -is [string] -and (Test-Path -LiteralPath $actualNode -PathType Leaf)) {{ $nodePath = $actualNode }}
}} catch {{}}
$npmNodeDir = $null
if ($nodePath -and $nodePath -ne 'node') {{ $npmNodeDir = Split-Path -Parent $nodePath }}
$cli = $null
if ($npmNodeDir) {{
    foreach ($candidate in @(
        (Join-Path $npmNodeDir 'node_modules\npm\bin\{cli_file}'),
        (Join-Path $npmNodeDir 'lib\node_modules\npm\bin\{cli_file}'),
        (Join-Path $npmNodeDir '..\lib\node_modules\npm\bin\{cli_file}')
    )) {{
        if (-not $cli -and (Test-Path -LiteralPath $candidate -PathType Leaf)) {{ $cli = $candidate }}
    }}
}}
# The bundled runtime always carries its own npm installation.
if (-not $cli -and (Test-Path -LiteralPath '{bundled_cli}' -PathType Leaf)) {{ $cli = '{bundled_cli}' }}

if (-not $cli) {{
    # No usable npm next to node: forward the user's own {shim_name} instead
    # (skipping our own shim dir).
    $selfDir = $PSScriptRoot.TrimEnd('\') + '\'
    $userCommand = Get-Command {shim_name} -All -ErrorAction SilentlyContinue |
        Where-Object {{ $_.Source -and -not $_.Source.StartsWith($selfDir, [System.StringComparison]::OrdinalIgnoreCase) }} |
        Select-Object -First 1
    if ($userCommand) {{
        $chainBefore = $env:DSH_NPM_SHIM_CHAIN
        if ($chainBefore -and $chainBefore.Split(';') -contains $userCommand.Source) {{
            [Console]::Error.WriteLine('[{shim_name}] NPM_REENTRY_LIMIT: Recursive forwarding revisited the same command.')
            exit 1
        }}
        try {{
            $env:DSH_NPM_SHIM_CHAIN = $chainBefore + ';' + $userCommand.Source
            & $userCommand.Source @args
            $forwardExitCode = $LASTEXITCODE
        }} finally {{
            $env:DSH_NPM_SHIM_CHAIN = $chainBefore
        }}
        exit $forwardExitCode
    }}
    Write-Error '[{shim_name}] npm cli not found. Please run DeepSeek Harness Desktop to install it first.'
    exit 1
}}
& $node $cli @args
exit $LASTEXITCODE
"#,
        node_bin = escape_path_ps1(&paths.node_bin),
        node_dir = escape_path_ps1(&paths.node_dir()),
        git_dir = escape_path_ps1(&paths.git_dir()),
        bundled_cli = escape_path_ps1(bundled_cli),
        shim_name = shim_name,
        cli_file = cli_file,
        node_resolve = PS1_NODE_RESOLVE,
    )
}

/// Windows `npx.ps1` 内容(见 npx/npm shim 段注释)。
#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
pub fn build_npx_ps1_shim(paths: &ShimPaths) -> String {
    build_npm_cli_ps1_shim(
        paths,
        "npx",
        "npx-cli.js",
        &paths
            .node_dir()
            .join("node_modules")
            .join("npm")
            .join("bin")
            .join("npx-cli.js"),
    )
}

/// Windows `npm.ps1` 内容(见 npx/npm shim 段注释)。
#[cfg_attr(all(not(windows), not(test)), allow(dead_code))]
pub fn build_npm_ps1_shim(paths: &ShimPaths) -> String {
    build_npm_cli_ps1_shim(
        paths,
        "npm",
        "npm-cli.js",
        &paths
            .node_dir()
            .join("node_modules")
            .join("npm")
            .join("bin")
            .join("npm-cli.js"),
    )
}

#[cfg(test)]
mod tests {
    use super::super::test_util::{
        sample_app_dir, sample_dsh_home, sample_shim_paths, shim_paths_for, temp_dir,
    };
    use super::*;
    use std::path::PathBuf;

    #[cfg(windows)]
    #[test]
    fn cmd_shim_contains_baked_paths() {
        let paths = sample_shim_paths();
        let content = build_cmd_shim(&paths, &sample_dsh_home());
        assert!(content.contains(r"C:\Users\test\AppData\Roaming"));
        // 解析后的依赖入口直接烘焙进 shim(不再有 APP_DIR 相对拼接)
        assert!(content.contains(&paths.dsh_bin.to_string_lossy().to_string()));
        assert!(content.contains(&paths.node_bin.to_string_lossy().to_string()));
        assert!(content.contains(r"C:\Users\test\.dsh"));
        assert!(!content.contains("data/dsh"));
        assert!(content.contains("%*"));
    }

    #[test]
    fn cmd_shim_escapes_percent() {
        let dir = PathBuf::from(r"C:\Users\100%test\AppData\Roaming\dsh-tauri");
        let content = build_cmd_shim(&shim_paths_for(&dir), &sample_dsh_home());
        assert!(content.contains("100%%test"));
        assert!(!content.contains(r#"set "APP_DIR=C:\Users\100%test""#));
    }

    /// npx/npm shim 的 cli 入口必须按「与所选 node 同目录的 npm」优先解析,
    /// 且 PATH 上用户的同名命令只作最后兜底(排除本 shim 目录,防自指递归)。
    #[cfg(windows)]
    #[test]
    fn npm_cli_shims_resolve_cli_next_to_node() {
        for (shim_name, content) in [
            ("npx", build_npx_cmd_shim(&sample_shim_paths())),
            ("npm", build_npm_cmd_shim(&sample_shim_paths())),
        ] {
            let cli_file = format!("{shim_name}-cli.js");
            assert!(content.contains(&format!("- {shim_name} command shim")));
            assert!(content.contains("if not defined DSH_NODE goto :skip_dsh_node"));
            assert!(content.contains(&format!(
                "for /f \"delims=\" %%p in ('where {shim_name} 2^>nul') do ("
            )));
            assert!(content.contains(&format!("\"%SELF_PREFIX%\\{shim_name}.cmd\"")));
            assert!(content.contains(&format!("\"%SELF_PREFIX%\\{shim_name}.exe\"")));
            assert!(content.contains("\"%NODE%\" \"%NPM_CLI%\" %*"));
            assert!(content.contains("DSH_NPM_SHIM_CHAIN"));
            assert!(content.contains("if /i \"%%~c\"==\"%USER_NPM%\" goto :npm_reentry_limit"));
            let same_dir = content
                .find(&format!("%NPM_NODE_DIR%node_modules\\npm\\bin\\{cli_file}"))
                .expect("same-dir cli candidate");
            let lib_dir = content
                .find(&format!(
                    "%NPM_NODE_DIR%lib\\node_modules\\npm\\bin\\{cli_file}"
                ))
                .expect("lib cli candidate");
            let parent_lib = content
                .find(&format!(
                    "%NPM_NODE_DIR%..\\lib\\node_modules\\npm\\bin\\{cli_file}"
                ))
                .expect("parent lib cli candidate");
            let user_scan = content
                .find(&format!("where {shim_name} 2^>nul"))
                .expect("user shim scan");
            assert!(same_dir < lib_dir && lib_dir < parent_lib && parent_lib < user_scan);
            // 捆绑运行时同级始终带 npm 安装,是解析链的固定兜底
            let bundled = sample_shim_paths();
            let bundled_cli = bundled
                .node_bin
                .parent()
                .unwrap()
                .join("node_modules")
                .join("npm")
                .join("bin")
                .join(&cli_file);
            assert!(content.contains(&bundled_cli.to_string_lossy().to_string()));
        }
    }

    /// issue #581:Windows `.cmd` 必须全 CRLF。Rust 源码被 `.gitattributes`
    /// 固定为 LF,多行字符串里的裸 LF 会让部分环境下的 cmd.exe 解析
    /// label/括号块错位,`dsh plugin install` 因此整体失败。
    #[test]
    fn cmd_shims_use_crlf_line_endings() {
        for (name, content) in [
            (
                "dsh.cmd",
                build_cmd_shim(&sample_shim_paths(), &sample_dsh_home()),
            ),
            ("pnpm.cmd", build_pnpm_cmd_shim(&sample_shim_paths())),
            ("npx.cmd", build_npx_cmd_shim(&sample_shim_paths())),
            ("npm.cmd", build_npm_cmd_shim(&sample_shim_paths())),
        ] {
            assert!(content.contains("@echo off"), "{name}: missing header");
            let bytes = content.as_bytes();
            for (index, byte) in bytes.iter().enumerate() {
                if *byte == b'\n' {
                    assert!(
                        index > 0 && bytes[index - 1] == b'\r',
                        "{name}: unpaired LF at byte {index}"
                    );
                }
                if *byte == b'\r' {
                    assert_eq!(
                        bytes.get(index + 1),
                        Some(&b'\n'),
                        "{name}: unpaired CR at byte {index}"
                    );
                }
            }
        }
    }

    #[test]
    fn normalize_cmd_line_endings_converts_lone_lf_and_is_idempotent() {
        assert_eq!(normalize_cmd_line_endings("a\nb".into()), "a\r\nb");
        assert_eq!(normalize_cmd_line_endings("a\r\nb".into()), "a\r\nb");
        assert_eq!(
            normalize_cmd_line_endings("a\r\nb\nc".into()),
            "a\r\nb\r\nc"
        );
    }

    #[cfg(windows)]
    #[test]
    fn windows_shims_configure_bundled_git_without_shadowing_system_git() {
        let dsh_cmd = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());
        let dsh_ps1 = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());
        let pnpm_cmd = build_pnpm_cmd_shim(&sample_shim_paths());
        let pnpm_ps1 = build_pnpm_ps1_shim(&sample_shim_paths());

        let git_dir = sample_shim_paths()
            .bundled_git_dir
            .expect("bundled MinGit dir");
        let git_dir_text = git_dir.to_string_lossy().to_string();
        for content in [&dsh_cmd, &pnpm_cmd] {
            assert!(content.contains("git --exec-path 2^>nul"));
            assert!(content.contains("git-remote-https.exe"));
            // 捆绑 Git 目录直接内联进 PATH 注入行:导出 GIT_DIR 会污染子进程
            // (Git 把该变量当成仓库目录,`git init`/`git status` 直接失败)
            assert!(!content.contains("set \"GIT_DIR="));
            assert!(!content.contains("%GIT_DIR%"));
            assert!(content.contains(&format!("if exist \"{git_dir_text}\\git.exe\"")));
            assert!(content.contains(&format!("set \"PATH={git_dir_text};%PATH%\"")));
            assert!(content.contains(&git_dir_text));
            let system_probe = content.find("git --exec-path").expect("system Git probe");
            // 捆绑 Git 只在系统 Git 缺 HTTPS helper 时才注入 PATH:探测必须在前
            let bundled_git = content
                .find("if not defined SYSTEM_GIT_WORKS")
                .expect("bundled Git activation");
            assert!(system_probe < bundled_git);
        }
        for content in [&dsh_ps1, &pnpm_ps1] {
            assert!(content.contains("& git --exec-path 2> $null"));
            assert!(content.contains("git-remote-https.exe"));
            assert!(content.contains(&git_dir_text));
            assert!(content.contains("$env:PATH = $gitDir + ';' + $env:PATH"));
        }
    }

    /// 生成的 `dsh.cmd` 必须能真正跑起来,且不给子进程留下 `GIT_DIR`。
    ///
    /// 内联捆绑 Git 目录后,批处理里不再有 `set "GIT_DIR=..."`:`setlocal` 对未定义
    /// 变量不做展开,残留的 `%GIT_DIR%` 会让判断行退化成相对当前盘根的空路径。
    /// 这里用真实的 `cmd.exe` 跑一遍生成的 shim,由替身 node 回报它看到的变量值。
    #[cfg(windows)]
    #[test]
    fn generated_dsh_cmd_runs_and_leaves_no_git_dir() {
        let dir = temp_dir("cmd-git-dir");
        let paths = shim_paths_for(&dir);
        let git_dir = paths.bundled_git_dir.clone().expect("bundled MinGit dir");
        std::fs::create_dir_all(&git_dir).unwrap();
        std::fs::write(git_dir.join("git.exe"), b"MZ").unwrap();
        std::fs::create_dir_all(paths.dsh_bin.parent().unwrap()).unwrap();
        std::fs::write(&paths.dsh_bin, "// stub").unwrap();

        let node = dir.join("fake-node.cmd");
        std::fs::write(
            &node,
            "@echo off\r\nif \"%~2\"==\"--print-git-dir\" echo GIT_DIR=[%GIT_DIR%]\r\nexit /b 0\r\n",
        )
        .unwrap();

        let shim = dir.join("dsh.cmd");
        std::fs::write(&shim, build_cmd_shim(&paths, &sample_dsh_home())).unwrap();

        let mut command = std::process::Command::new("cmd");
        command.args(["/C", shim.to_str().unwrap(), "--print-git-dir"]);
        // 父进程带哨兵值:shim 若还导出捆绑目录,子进程看到的就不是它。
        // PATH 只留 System32:本机安装的 dsh shim 会被优先转发(用户优先级),
        // 那样测的就不是本次生成的脚本了。
        command.env("GIT_DIR", "sentinel-from-parent");
        command.env("DSH_NODE", &node);
        let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".to_string());
        command.env("PATH", Path::new(&system_root).join("System32"));
        let output = command.output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert!(
            output.status.success(),
            "generated dsh.cmd exited with {:?}: {stdout}",
            output.status
        );
        assert!(
            stdout.contains("GIT_DIR=[sentinel-from-parent]"),
            "the shim rewrote GIT_DIR of its child process: {stdout}"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn pnpm_cmd_shim_contains_user_precedence() {
        let paths = sample_shim_paths();
        let content = build_pnpm_cmd_shim(&paths);
        assert!(content.contains("pnpm command shim"));
        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#""%USER_PNPM%" %*"#));
        assert!(content.contains(":use_bundled"));
        assert!(content.contains(&paths.node_bin.to_string_lossy().to_string()));
        // 应用内部安装可经 DSH_PREFER_BUNDLED_PNPM=1 强制捆绑版(须在用户搜索前生效)
        assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));
        let env_at = content.find("DSH_PREFER_BUNDLED_PNPM").unwrap();
        let exact_at = content.find("if defined DSH_PNPM (").unwrap();
        let user_at = content.find("where pnpm").unwrap();
        assert!(env_at < exact_at && exact_at < user_at);
        assert_eq!(content.matches("if defined DSH_PNPM (").count(), 1);
    }

    /// 生成的 `npx.cmd` 必须能真正跑起来:所选 node 目录没有 npm 时回落到
    /// 捆绑运行时的 cli,由替身 node 回报它拿到的 cli 入口与参数。
    #[cfg(windows)]
    #[test]
    fn generated_npx_cmd_runs_with_bundled_cli() {
        let dir = temp_dir("npx-run");
        let paths = shim_paths_for(&dir);
        let cli = paths
            .node_bin
            .parent()
            .unwrap()
            .join("node_modules")
            .join("npm")
            .join("bin")
            .join("npx-cli.js");
        std::fs::create_dir_all(cli.parent().unwrap()).unwrap();
        std::fs::write(&cli, "// stub").unwrap();

        let node = dir.join("fake-node.cmd");
        std::fs::write(
            &node,
            "@echo off\r\necho CLI=[%~1] ARG=[%~2]\r\nexit /b 0\r\n",
        )
        .unwrap();

        let shim = dir.join("npx.cmd");
        std::fs::write(&shim, build_npx_cmd_shim(&paths)).unwrap();

        let mut command = std::process::Command::new("cmd");
        command.args(["/d", "/C", shim.to_str().unwrap(), "--version"]);
        command.env("DSH_NODE", &node);
        // PATH 只留 System32:本机 .nvmd 的坏 npx 与自建 shim 都不会被选中
        let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".to_string());
        command.env("PATH", Path::new(&system_root).join("System32"));
        let output = command.output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert!(
            output.status.success(),
            "generated npx.cmd exited with {:?}: {stdout} / {}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            stdout.contains(&format!("CLI=[{}]", cli.display())),
            "the shim did not pick the bundled npm cli: {stdout}"
        );
        assert!(stdout.contains("ARG=[--version]"), "{stdout}");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(windows)]
    async fn run_npm_shim_fixture(
        shim: &Path,
        node: &Path,
        path: &std::ffi::OsStr,
    ) -> std::process::Output {
        std::fs::write(
            shim.parent().unwrap().join("git.cmd"),
            "@echo off\r\nexit /b 1\r\n",
        )
        .unwrap();
        let system_root = std::env::var_os("SystemRoot").unwrap();
        let system32 = PathBuf::from(system_root).join("System32");
        let mut command = if shim.extension().unwrap() == "ps1" {
            let mut command = tokio::process::Command::new(
                system32.join("WindowsPowerShell/v1.0/powershell.exe"),
            );
            command.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]);
            command
        } else {
            let mut command = tokio::process::Command::new(system32.join("cmd.exe"));
            command.args(["/d", "/c"]);
            command
        };
        use std::os::windows::process::CommandExt;
        command.as_std_mut().creation_flags(0x08000000);
        tokio::time::timeout(
            std::time::Duration::from_secs(15),
            command
                .arg(shim)
                .arg("--version")
                .current_dir(shim.parent().unwrap())
                .env("DSH_NODE", node)
                .env("PATH", path)
                .env_remove("DSH_NPM_SHIM_CHAIN")
                .kill_on_drop(true)
                .output(),
        )
        .await
        .expect("npm shim must terminate within 15 seconds")
        .unwrap()
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn npm_shims_find_cli_at_actual_node_path_without_bundled_runtime() {
        let dir = tempfile::tempdir().unwrap();
        let root = dunce::canonicalize(dir.path()).unwrap();
        let shim_dir = root.join("desktop bin");
        let manager_dir = root.join("manager bin");
        let actual_dir = root.join("node version");
        for path in [&shim_dir, &manager_dir, &actual_dir] {
            std::fs::create_dir_all(path).unwrap();
        }
        let actual_node = actual_dir.join("node.exe");
        std::fs::write(&actual_node, "fixture").unwrap();
        let node = manager_dir.join("node.cmd");
        std::fs::write(
            &node,
            format!(
                "@echo off\r\nif \"%~1\"==\"-p\" (\r\n  echo {}\r\n  exit /b 0\r\n)\r\necho CLI=[%~1] ARG=[%~2]\r\nexit /b 37\r\n",
                actual_node.display()
            ),
        )
        .unwrap();
        let system32 = PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32");
        let path = std::env::join_paths([&shim_dir, &manager_dir, &system32]).unwrap();
        let paths = shim_paths_for(&root.join("missing app"));
        for (name, cmd, ps1) in [
            (
                "npx",
                build_npx_cmd_shim(&paths),
                build_npx_ps1_shim(&paths),
            ),
            (
                "npm",
                build_npm_cmd_shim(&paths),
                build_npm_ps1_shim(&paths),
            ),
        ] {
            let cli = actual_dir
                .join("node_modules")
                .join("npm")
                .join("bin")
                .join(format!("{name}-cli.js"));
            std::fs::create_dir_all(cli.parent().unwrap()).unwrap();
            std::fs::write(&cli, "fixture").unwrap();
            std::fs::write(
                manager_dir.join(format!("{name}.cmd")),
                format!("@echo off\r\necho FORWARDER\r\n{name} %*\r\n"),
            )
            .unwrap();
            for (extension, content) in [("cmd", cmd), ("ps1", ps1)] {
                let shim = shim_dir.join(format!("{name}.{extension}"));
                std::fs::write(&shim, content).unwrap();
                let output = run_npm_shim_fixture(&shim, &node, &path).await;
                let stdout = String::from_utf8_lossy(&output.stdout);
                assert_eq!(
                    output.status.code(),
                    Some(37),
                    "{shim:?}: {stdout} / {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                assert!(
                    stdout.contains(&format!("CLI=[{}] ARG=[--version]", cli.display())),
                    "{shim:?}: {stdout}"
                );
                assert!(!stdout.contains("FORWARDER"), "{shim:?}: {stdout}");
            }
        }
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn npm_shims_stop_forwarding_when_the_same_candidate_reenters() {
        let dir = tempfile::tempdir().unwrap();
        let root = dunce::canonicalize(dir.path()).unwrap();
        let shim_dir = root.join("desktop bin");
        let user_dir = root.join("user bin");
        std::fs::create_dir_all(&shim_dir).unwrap();
        std::fs::create_dir_all(&user_dir).unwrap();
        let node = root.join("node.cmd");
        std::fs::write(&node, "@echo off\r\nexit /b 1\r\n").unwrap();
        let system32 = PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32");
        let path = std::env::join_paths([&shim_dir, &user_dir, &system32]).unwrap();
        let paths = shim_paths_for(&root.join("missing app"));
        for (name, cmd, ps1) in [
            (
                "npx",
                build_npx_cmd_shim(&paths),
                build_npx_ps1_shim(&paths),
            ),
            (
                "npm",
                build_npm_cmd_shim(&paths),
                build_npm_ps1_shim(&paths),
            ),
        ] {
            std::fs::write(
                user_dir.join(format!("{name}.cmd")),
                format!("@echo off\r\necho FORWARDER\r\n{name} %*\r\n"),
            )
            .unwrap();
            for (extension, content) in [("cmd", cmd), ("ps1", ps1)] {
                let shim = shim_dir.join(format!("{name}.{extension}"));
                std::fs::write(&shim, content).unwrap();
                let output = run_npm_shim_fixture(&shim, &node, &path).await;
                assert_eq!(
                    output.status.code(),
                    Some(1),
                    "{shim:?}: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                assert_eq!(
                    String::from_utf8_lossy(&output.stdout)
                        .matches("FORWARDER")
                        .count(),
                    1,
                    "{shim:?}"
                );
                assert!(
                    String::from_utf8_lossy(&output.stderr).contains("NPM_REENTRY_LIMIT"),
                    "{shim:?}: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
            }
        }
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn npm_shims_allow_forwarding_to_a_different_candidate() {
        let dir = tempfile::tempdir().unwrap();
        let root = dunce::canonicalize(dir.path()).unwrap();
        let shim_dir = root.join("desktop bin");
        let first_dir = root.join("first user bin");
        let second_dir = root.join("second user bin");
        for path in [&shim_dir, &first_dir, &second_dir] {
            std::fs::create_dir_all(path).unwrap();
        }
        let node = root.join("node.cmd");
        std::fs::write(&node, "@echo off\r\nexit /b 1\r\n").unwrap();
        let system32 = PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32");
        let path = std::env::join_paths([&shim_dir, &first_dir, &second_dir, &system32]).unwrap();
        let next_path = std::env::join_paths([&shim_dir, &second_dir, &system32]).unwrap();
        let paths = shim_paths_for(&root.join("missing app"));
        for (name, cmd, ps1) in [
            (
                "npx",
                build_npx_cmd_shim(&paths),
                build_npx_ps1_shim(&paths),
            ),
            (
                "npm",
                build_npm_cmd_shim(&paths),
                build_npm_ps1_shim(&paths),
            ),
        ] {
            std::fs::write(
                first_dir.join(format!("{name}.cmd")),
                format!(
                    "@echo off\r\nset \"PATH={}\"\r\n{name} %*\r\n",
                    next_path.to_string_lossy()
                ),
            )
            .unwrap();
            std::fs::write(
                second_dir.join(format!("{name}.cmd")),
                "@echo off\r\necho TARGET=[%~1]\r\nexit /b 37\r\n",
            )
            .unwrap();
            for (extension, content) in [("cmd", cmd), ("ps1", ps1)] {
                let shim = shim_dir.join(format!("{name}.{extension}"));
                std::fs::write(&shim, content).unwrap();
                let output = run_npm_shim_fixture(&shim, &node, &path).await;
                assert_eq!(
                    output.status.code(),
                    Some(37),
                    "{shim:?}: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                assert_eq!(
                    String::from_utf8_lossy(&output.stdout).trim(),
                    "TARGET=[--version]",
                    "{shim:?}"
                );
            }
        }
    }

    /// 真实执行生成的 `npx.ps1`:DSH_NODE 指向的目录没有 npm 时回落到捆绑 cli。
    #[cfg(windows)]
    #[test]
    fn generated_npx_ps1_runs_with_bundled_cli() {
        let dir = temp_dir("npx-ps1-run");
        let paths = shim_paths_for(&dir);
        let cli = paths
            .node_bin
            .parent()
            .unwrap()
            .join("node_modules")
            .join("npm")
            .join("bin")
            .join("npx-cli.js");
        std::fs::create_dir_all(cli.parent().unwrap()).unwrap();
        std::fs::write(&cli, "// stub").unwrap();

        let node = dir.join("fake-node.cmd");
        std::fs::write(
            &node,
            "@echo off\r\necho CLI=[%~1] ARG=[%~2]\r\nexit /b 0\r\n",
        )
        .unwrap();

        let shim = dir.join("npx.ps1");
        std::fs::write(&shim, build_npx_ps1_shim(&paths)).unwrap();

        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let powershell =
            PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let output = std::process::Command::new(powershell)
            .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
            .arg(&shim)
            .arg("--version")
            .env("DSH_NODE", &node)
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert!(
            output.status.success(),
            "generated npx.ps1 exited with {:?}: {stdout} / {}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            stdout.contains(&format!("CLI=[{}]", cli.display())),
            "the ps1 shim did not pick the bundled npm cli: {stdout}"
        );
        assert!(stdout.contains("ARG=[--version]"), "{stdout}");

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// issue #130:真实执行生成的 cmd shim,确保用户 pnpm 的失败码不会因 cmd
    /// 括号块预展开 `%ERRORLEVEL%` 而被吞成 0。
    ///
    /// 临时目录必须取规范长路径:CI(windows-latest)的 TEMP 是 8.3 短路径
    /// (`C:\Users\RUNNER~1\...`),而 `where pnpm` 一律回长路径,shim 的自身
    /// 排除比对(`%~dp0` 对 `where` 输出)随即失效、把自身当用户 pnpm 转发一次,
    /// 本用例断言的「直达用户 pnpm」路径就不会被走到。
    #[cfg(windows)]
    #[test]
    fn pnpm_cmd_shim_propagates_user_exit_code_in_real_cmd() {
        let dir = dunce::canonicalize(temp_dir("pnpm-exit-code")).unwrap();
        let shim_dir = dir.join("desktop-bin");
        let user_dir = dir.join("user-bin");
        std::fs::create_dir_all(&shim_dir).unwrap();
        std::fs::create_dir_all(&user_dir).unwrap();
        let shim = shim_dir.join("pnpm.cmd");
        std::fs::write(
            &shim,
            build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),
        )
        .unwrap();
        std::fs::write(
            user_dir.join("pnpm.cmd"),
            "@echo off\r\necho REAL_USER_PNPM\r\nexit /b 37\r\n",
        )
        .unwrap();
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let system32 = PathBuf::from(&system_root).join("System32");
        let path = std::env::join_paths([&shim_dir, &user_dir, &system32]).unwrap();
        let output = std::process::Command::new(system32.join("cmd.exe"))
            .args(["/d", "/c"])
            .arg(&shim)
            .arg("--version")
            .env("PATH", path)
            .env("SystemRoot", system_root)
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(37));
        assert!(String::from_utf8_lossy(&output.stdout).contains("REAL_USER_PNPM"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// issue #121:选定 pnpm 即使不在子进程 PATH 中,也必须由 shim 执行。
    #[cfg(windows)]
    #[test]
    fn pnpm_cmd_shim_uses_selected_pnpm_with_restricted_path() {
        let dir = temp_dir("pnpm-selected");
        let selected = dir.join("selected pnpm.cmd");
        std::fs::write(
            &selected,
            "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 37\r\n",
        )
        .unwrap();
        let selected = dunce::canonicalize(&selected).unwrap();
        assert!(!selected.to_string_lossy().starts_with(r"\\?\"));
        let shim = dir.join("pnpm.cmd");
        std::fs::write(
            &shim,
            build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),
        )
        .unwrap();
        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", "/c"])
            .arg(&shim)
            .arg("probe-121")
            .env("PATH", &system32)
            .env("SystemRoot", system_root)
            .env("DSH_PNPM", &selected)
            .env("DSH_PREFER_BUNDLED_PNPM", "1")
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(37));
        assert!(String::from_utf8_lossy(&output.stdout).contains("SELECTED_PNPM probe-121"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// 回归:脚本内嵌套的 pnpm(`pnpm run` 再调 pnpm)会继承上一跳置位的重入
    /// 保护变量。捆绑版缺失时保护无法终止转发链,只有回退用户 pnpm 才对——
    /// 否则 `pnpm dev:desktop` 里的 `pnpm dev:plugins` 直接报 pnpm not found。
    #[cfg(windows)]
    #[test]
    fn pnpm_cmd_shim_keeps_user_fallback_when_guard_set_without_bundle() {
        let dir = temp_dir("pnpm-guard-no-bundle");
        let selected = dir.join("selected pnpm.cmd");
        std::fs::write(
            &selected,
            "@echo off\r\necho SELECTED_PNPM %*\r\nexit /b 37\r\n",
        )
        .unwrap();
        let selected = dunce::canonicalize(&selected).unwrap();
        let shim = dir.join("pnpm.cmd");
        std::fs::write(
            &shim,
            build_pnpm_cmd_shim(&shim_paths_for(&dir.join("app"))),
        )
        .unwrap();
        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", "/c"])
            .arg(&shim)
            .arg("probe-guard")
            .env("PATH", &system32)
            .env("SystemRoot", system_root)
            .env("DSH_PNPM", &selected)
            .env("DSH_PNPM_SHIM_GUARD", "1")
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(37));
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("SELECTED_PNPM probe-guard"),
            "unexpected stdout: {}",
            String::from_utf8_lossy(&output.stdout)
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// 两个变量同时存在且捆绑文件可用时,显式的捆绑策略必须优先。
    #[cfg(windows)]
    #[test]
    fn pnpm_cmd_shim_prefers_existing_bundle_over_selected_path() {
        let dir = temp_dir("pnpm-both-vars");
        let app_dir = dir.join("app");
        let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
        std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
        std::fs::write(&pnpm_bin, "fixture").unwrap();
        let selected = dir.join("selected.cmd");
        let node = dir.join("node.cmd");
        std::fs::write(&selected, "@echo off\r\necho SELECTED\r\n").unwrap();
        std::fs::write(&node, "@echo off\r\necho BUNDLED %*\r\nexit /b 0\r\n").unwrap();
        let shim = dir.join("pnpm.cmd");
        std::fs::write(&shim, build_pnpm_cmd_shim(&shim_paths_for(&app_dir))).unwrap();
        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", "/c"])
            .arg(&shim)
            .arg("both-vars")
            .env("PATH", &system32)
            .env("SystemRoot", system_root)
            .env("DSH_NODE", &node)
            .env("DSH_PNPM", &selected)
            .env("DSH_PREFER_BUNDLED_PNPM", "1")
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(output.status.success());
        assert!(stdout.contains("BUNDLED"));
        assert!(!stdout.contains("SELECTED"));
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn pnpm_ps1_shim_contains_user_precedence() {
        let paths = sample_shim_paths();
        let content = build_pnpm_ps1_shim(&paths);
        assert!(content.contains("Get-Command pnpm -All"));
        assert!(content.contains("$PSScriptRoot"));
        assert!(content.contains("$userPnpm.Source"));
        assert!(content.contains("@args"));
        assert!(content.contains(&format!(
            "$nodeBin = '{}'",
            paths.node_bin.to_string_lossy()
        )));
        assert!(content.contains("$env:DSH_PREFER_BUNDLED_PNPM"));
        assert!(content.contains("$env:DSH_PNPM"));
        let bundled_at = content.find("$useBundled =").unwrap();
        let exact_at = content.find("& $env:DSH_PNPM @args").unwrap();
        let path_at = content.find("Get-Command pnpm -All").unwrap();
        assert!(bundled_at < exact_at && exact_at < path_at);
    }

    #[cfg(windows)]
    #[test]
    fn pnpm_ps1_shim_dispatches_exact_path_with_spaces_args_and_exit_code() {
        let dir = temp_dir("pnpm-ps1-selected");
        let selected = dir.join("selected pnpm.cmd");
        std::fs::write(&selected, "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n").unwrap();
        let shim = dir.join("pnpm.ps1");
        std::fs::write(
            &shim,
            build_pnpm_ps1_shim(&shim_paths_for(&dir.join("app"))),
        )
        .unwrap();
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let powershell =
            PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let output = std::process::Command::new(powershell)
            .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
            .arg(&shim)
            .args(["alpha beta", "gamma"])
            .env("DSH_PNPM", &selected)
            .env("DSH_PREFER_BUNDLED_PNPM", "1")
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(37));
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("SELECTED:\"alpha beta\" gamma"),
            "unexpected stdout: {stdout:?}"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(windows)]
    #[test]
    fn pnpm_ps1_shim_prefers_existing_bundle_over_selected_path() {
        let dir = temp_dir("pnpm-ps1-both-vars");
        let app_dir = dir.join("app");
        let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
        std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
        std::fs::write(&pnpm_bin, "fixture").unwrap();
        let selected = dir.join("selected.cmd");
        let node = dir.join("node.cmd");
        std::fs::write(&selected, "@echo off\r\necho SELECTED\r\n").unwrap();
        std::fs::write(&node, "@echo off\r\necho BUNDLED %*\r\nexit /b 0\r\n").unwrap();
        let shim = dir.join("pnpm.ps1");
        std::fs::write(&shim, build_pnpm_ps1_shim(&shim_paths_for(&app_dir))).unwrap();
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let powershell =
            PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let output = std::process::Command::new(powershell)
            .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
            .arg(&shim)
            .arg("both-vars")
            .env("DSH_NODE", &node)
            .env("DSH_PNPM", &selected)
            .env("DSH_PREFER_BUNDLED_PNPM", "1")
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success(),
            "stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(stdout.contains("BUNDLED"), "unexpected stdout: {stdout:?}");
        assert!(!stdout.contains("SELECTED"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// 回归:ps1 侧同样禁止在捆绑版缺失时按重入保护直落捆绑版。
    #[cfg(windows)]
    #[test]
    fn pnpm_ps1_shim_keeps_user_fallback_when_guard_set_without_bundle() {
        let dir = temp_dir("pnpm-ps1-guard-no-bundle");
        let selected = dir.join("selected pnpm.cmd");
        std::fs::write(&selected, "@echo off\r\necho SELECTED:%*\r\nexit /b 37\r\n").unwrap();
        let shim = dir.join("pnpm.ps1");
        std::fs::write(
            &shim,
            build_pnpm_ps1_shim(&shim_paths_for(&dir.join("app"))),
        )
        .unwrap();
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let powershell =
            PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let output = std::process::Command::new(powershell)
            .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
            .arg(&shim)
            .arg("probe-guard")
            .env("DSH_PNPM", &selected)
            .env("DSH_PNPM_SHIM_GUARD", "1")
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(37));
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("SELECTED:probe-guard"),
            "unexpected stdout: {}",
            String::from_utf8_lossy(&output.stdout)
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// 回归:`$env:` 写入是进程级的,转发后必须还原重入保护——否则同一次
    /// PowerShell 会话里后续每个 pnpm 都直落捆绑版,捆绑缺失时误报未安装。
    #[cfg(windows)]
    #[test]
    fn pnpm_ps1_shim_restores_reentry_guard_after_forwarding() {
        let dir = temp_dir("pnpm-ps1-guard-restore");
        let target = dir.join("target.cmd");
        std::fs::write(&target, "@echo off\r\nexit /b 0\r\n").unwrap();
        let shim = dir.join("pnpm.ps1");
        std::fs::write(
            &shim,
            build_pnpm_ps1_shim(&shim_paths_for(&dir.join("app"))),
        )
        .unwrap();
        let driver = dir.join("driver.ps1");
        std::fs::write(
            &driver,
            format!(
                "& '{}' probe\n'GUARD=[' + $env:DSH_PNPM_SHIM_GUARD + ']'\nexit 0\n",
                shim.display()
            ),
        )
        .unwrap();
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let powershell =
            PathBuf::from(&system_root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
        let run = |guard: Option<&str>| {
            let mut command = std::process::Command::new(&powershell);
            command
                .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])
                .arg(&driver)
                .env("DSH_PNPM", &target)
                .env_remove("DSH_PNPM_SHIM_GUARD");
            if let Some(guard) = guard {
                command.env("DSH_PNPM_SHIM_GUARD", guard);
            }
            String::from_utf8_lossy(&command.output().unwrap().stdout).into_owned()
        };
        assert!(run(None).contains("GUARD=[]"), "guard not dropped");
        assert!(run(Some("0")).contains("GUARD=[0]"), "guard not restored");
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn pnpm_sh_shim_contains_user_precedence() {
        let paths = sample_shim_paths();
        let content = build_pnpm_sh_shim(&paths);
        assert!(content.starts_with("#!/bin/sh"));
        assert!(content.contains(r#"exec "$dir/pnpm" "$@""#));
        assert!(content.contains("SELF_DIR"));
        assert!(content.contains(r#"exec "$NODE" "$PNPM_BIN" "$@""#));
        assert!(content.contains(&format!("NODE_BIN='{}'", paths.node_bin.to_string_lossy())));
        assert!(content.contains("DSH_PREFER_BUNDLED_PNPM"));
        assert!(content.contains(r#"exec "$DSH_PNPM" "$@""#));
        let bundled_at = content.find("USE_BUNDLED=").unwrap();
        let exact_at = content.find(r#"exec "$DSH_PNPM" "$@""#).unwrap();
        let path_at = content.find("for dir in $PATH").unwrap();
        assert!(bundled_at < exact_at && exact_at < path_at);
    }

    #[cfg(unix)]
    #[test]
    fn pnpm_sh_shim_dispatches_exact_path_with_spaces_args_and_exit_code() {
        use std::os::unix::fs::PermissionsExt;

        let dir = temp_dir("pnpm-sh-selected");
        let selected = dir.join("selected pnpm");
        std::fs::write(
            &selected,
            "#!/bin/sh\nprintf 'SELECTED:%s\\n' \"$*\"\nexit 37\n",
        )
        .unwrap();
        let mut permissions = std::fs::metadata(&selected).unwrap().permissions();
        permissions.set_mode(0o700);
        std::fs::set_permissions(&selected, permissions).unwrap();
        let shim = dir.join("pnpm");
        std::fs::write(&shim, build_pnpm_sh_shim(&shim_paths_for(&dir.join("app")))).unwrap();
        let mut permissions = std::fs::metadata(&shim).unwrap().permissions();
        permissions.set_mode(0o700);
        std::fs::set_permissions(&shim, permissions).unwrap();

        let output = std::process::Command::new(&shim)
            .args(["alpha beta", "gamma"])
            .env("PATH", "/usr/bin:/bin")
            .env("DSH_PNPM", &selected)
            .env("DSH_PREFER_BUNDLED_PNPM", "1")
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(37));
        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            "SELECTED:alpha beta gamma\n"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(unix)]
    #[test]
    fn pnpm_sh_shim_prefers_existing_bundle_over_selected_path() {
        use std::os::unix::fs::PermissionsExt;

        let dir = temp_dir("pnpm-sh-both-vars");
        let app_dir = dir.join("app");
        let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
        std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
        std::fs::write(&pnpm_bin, "fixture").unwrap();
        let selected = dir.join("selected");
        let node = dir.join("node");
        std::fs::write(&selected, "#!/bin/sh\necho SELECTED\n").unwrap();
        std::fs::write(&node, "#!/bin/sh\necho BUNDLED \"$@\"\n").unwrap();
        for path in [&selected, &node] {
            let mut permissions = std::fs::metadata(path).unwrap().permissions();
            permissions.set_mode(0o700);
            std::fs::set_permissions(path, permissions).unwrap();
        }
        let shim = dir.join("pnpm");
        std::fs::write(&shim, build_pnpm_sh_shim(&shim_paths_for(&app_dir))).unwrap();
        let mut permissions = std::fs::metadata(&shim).unwrap().permissions();
        permissions.set_mode(0o700);
        std::fs::set_permissions(&shim, permissions).unwrap();

        let output = std::process::Command::new(&shim)
            .arg("both-vars")
            .env("PATH", "/usr/bin:/bin")
            .env("DSH_NODE", &node)
            .env("DSH_PNPM", &selected)
            .env("DSH_PREFER_BUNDLED_PNPM", "1")
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(output.status.success());
        assert!(stdout.contains("BUNDLED"));
        assert!(!stdout.contains("SELECTED"));
        let _ = std::fs::remove_dir_all(dir);
    }

    /// 三个平台的 pnpm shim 都必须带重入保护(见各模板注释)。
    #[test]
    fn pnpm_shims_guard_against_reentrant_forwarding() {
        let app_dir = sample_app_dir();
        for (name, content) in [
            ("pnpm.sh", build_pnpm_sh_shim(&shim_paths_for(&app_dir))),
            ("pnpm.cmd", build_pnpm_cmd_shim(&shim_paths_for(&app_dir))),
            ("pnpm.ps1", build_pnpm_ps1_shim(&shim_paths_for(&app_dir))),
        ] {
            assert!(
                content.contains("DSH_PNPM_SHIM_GUARD"),
                "{name}: missing re-entry guard"
            );
        }
        // 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%`
    /// 必须紧跟转发语句、且不得落进括号块(块解析会提前展开 `%ERRORLEVEL%`,把失败码
    /// 吞成 0/1)。
    ///
    /// 同时锁死 issue #715 的修复:转发**不得用 `call`**——批处理会把原始 `%*` 再展开
    /// 一次,`call` 即多出一层解释,使 execa 已按单层转义好的 `^` 翻倍成 `^^`。
    #[test]
    fn cmd_shim_forwarding_keeps_exit_code_and_never_uses_call() {
        let content = build_pnpm_cmd_shim(&sample_shim_paths());
        for target in [r#""%DSH_PNPM%""#, r#""%USER_PNPM%""#] {
            let expected = format!("{target} %*\r\nexit /b %ERRORLEVEL%\r\n");
            assert!(
                content.contains(&expected),
                "`{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` 形成死循环——安装子进程永不退出,应用表现为永久卡在
    /// 「Loading internal plugins…」且后端日志一行输出都没有。有保护时必须有界
    /// 结束并回退捆绑 pnpm。
    #[cfg(unix)]
    #[test]
    fn pnpm_sh_shim_breaks_self_referential_forward_loop() {
        use std::os::unix::fs::PermissionsExt;

        let dir = temp_dir("pnpm-sh-reentry");
        let app_dir = dir.join("app");
        let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
        std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
        std::fs::write(&pnpm_bin, "fixture").unwrap();

        let bin_dir = dir.join("bin");
        let loop_dir = dir.join("loop-bin");
        std::fs::create_dir_all(&bin_dir).unwrap();
        std::fs::create_dir_all(&loop_dir).unwrap();

        let node = dir.join("node");
        std::fs::write(&node, "#!/bin/sh\necho BUNDLED \"$@\"\n").unwrap();
        // 本 shim 落在 PATH 中,等价于桌面端把自身 shim 目录前置到子进程 PATH。
        let shim = bin_dir.join("pnpm");
        std::fs::write(&shim, build_pnpm_sh_shim(&shim_paths_for(&app_dir))).unwrap();
        // 模拟 mise shim:自身没有实现,只把调用交回 PATH 上的 pnpm。
        let forwarder = loop_dir.join("pnpm");
        std::fs::write(&forwarder, "#!/bin/sh\nexec pnpm \"$@\"\n").unwrap();

        for path in [&node, &shim, &forwarder] {
            let mut permissions = std::fs::metadata(path).unwrap().permissions();
            permissions.set_mode(0o700);
            std::fs::set_permissions(path, permissions).unwrap();
        }

        let path_env = std::env::join_paths([
            bin_dir.clone(),
            loop_dir.clone(),
            PathBuf::from("/usr/bin"),
            PathBuf::from("/bin"),
        ])
        .unwrap();
        let child = std::process::Command::new(&shim)
            .arg("reentry")
            .env("PATH", &path_env)
            .env("DSH_NODE", &node)
            .env("DSH_PNPM", &forwarder)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .spawn()
            .unwrap();
        // exec 保留 pid,因此超时后按 pid 一定杀得中循环中的那个进程。
        let pid = child.id();

        let (sender, receiver) = std::sync::mpsc::channel();
        let waiter = std::thread::spawn(move || {
            let output = child.wait_with_output();
            let _ = sender.send(output);
        });
        let output = match receiver.recv_timeout(std::time::Duration::from_secs(20)) {
            Ok(output) => output.unwrap(),
            Err(_) => {
                let _ = std::process::Command::new("kill")
                    .args(["-9", &pid.to_string()])
                    .status();
                let _ = waiter.join();
                let _ = std::fs::remove_dir_all(&dir);
                panic!(
                    "self-referential pnpm shim chain must terminate instead of looping forever"
                );
            }
        };
        let _ = waiter.join();

        assert!(output.status.success());
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("BUNDLED"),
            "re-entered shim must fall back to the bundled pnpm"
        );
        let _ = std::fs::remove_dir_all(dir);
    }

    /// issue #121:桌面端注入的 DSH_NODE(预检解析出的 node 路径)必须在
    /// 本地 node / 捆绑运行时解析之前被采用——shim 与应用预检保持一致。
    #[test]
    fn cmd_shim_prefers_dsh_node_before_local_node() {
        let content = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());
        let dsh_node_at = content.find("DSH_NODE").unwrap();
        let where_node_at = content.find("where node").unwrap();
        // `:node_dsh` 标签行(独占一行)位于 `:node_ok` 之后、`:use_bundled`
        // 之前;`goto :node_dsh` 引用出现在 `where node` 之前,不能作为定位点。
        let node_dsh_label_at = content.find("\n:node_dsh").unwrap();
        let node_ok_at = content.find("\n:node_ok").unwrap();
        assert!(
            dsh_node_at < where_node_at,
            "DSH_NODE must be checked before the local node search"
        );
        assert!(content.contains(r#"set "NODE=%DSH_NODE%""#));
        assert!(
            node_ok_at < node_dsh_label_at,
            "the :node_dsh label must come after :node_ok"
        );
        // Windows canonical paths may carry a \\?\ verbatim prefix; the shim
        // must strip it before launching node (issue: pnpm --version fails
        // with "The system cannot find the path specified.").
        assert!(content.contains("NODE:~0,4%"));
        assert!(content.contains("NODE:~4%"));
    }

    #[test]
    fn ps1_shim_prefers_dsh_node_before_local_node() {
        let content = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());
        let dsh_node_at = content.find("$env:DSH_NODE").unwrap();
        let local_at = content.find("Get-Command node").unwrap();
        assert!(
            dsh_node_at < local_at,
            "DSH_NODE must be checked before the local node search"
        );
        // Same verbatim-prefix stripping as the CMD shim.
        assert!(content.contains("StartsWith"));
        assert!(content.contains("Substring(4)"));
    }

    #[test]
    fn sh_shim_prefers_dsh_node_before_local_node() {
        #[cfg(not(windows))]
        {
            let content = build_sh_shim(&sample_shim_paths(), &sample_dsh_home());
            let dsh_node_at = content.find("$DSH_NODE").unwrap();
            let local_at = content.find("command -v node").unwrap();
            assert!(
                dsh_node_at < local_at,
                "DSH_NODE must be checked before the local node search"
            );
        }
    }

    /// 三种 shim 的版本门槛必须与应用预检及当前 DSH engines 保持一致。
    #[test]
    fn generated_shims_match_current_dsh_node_engine() {
        let cmd = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());
        let ps1 = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());

        assert!(cmd.contains(r#"findstr /r /x "v[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*""#));
        assert!(cmd.contains("EQU 22 if defined NODE_MINOR if %NODE_MINOR% GEQ 19"));
        assert!(!cmd.contains("NODE_MAJOR% EQU 23"));
        assert!(ps1.contains(r#"-match '^v(\d+)\.(\d+)\.(\d+)$'"#));
        assert!(ps1.contains("$major -eq 22 -and $minor -ge 19"));
        assert!(!ps1.contains("$major -eq 23"));
        assert!(SH_NODE_RESOLVE.contains(r#"awk '/^v[0-9]+\.[0-9]+\.[0-9]+$/"#));
        assert!(SH_NODE_RESOLVE.contains("$MAJOR\" -eq 22 ] && [ \"$MINOR\" -ge 19"));
        assert!(!SH_NODE_RESOLVE.contains("$MAJOR\" -eq 23"));
    }

    /// cmd shim 不得把 Node 预发布版本误判为满足稳定版 engines 范围。
    #[cfg(windows)]
    #[test]
    fn cmd_shim_rejects_prerelease_node_and_accepts_stable_boundaries() {
        let dir = temp_dir("node-version-boundary");
        let app_dir = dir.join("app");
        let pnpm_bin = app_dir.join("dependencies/pnpm/bin/pnpm.cjs");
        std::fs::create_dir_all(pnpm_bin.parent().unwrap()).unwrap();
        std::fs::write(&pnpm_bin, "fixture").unwrap();
        let shim = dir.join("pnpm.cmd");
        std::fs::write(&shim, build_pnpm_cmd_shim(&shim_paths_for(&app_dir))).unwrap();
        let node_dir = dir.join("local-node");
        std::fs::create_dir_all(&node_dir).unwrap();
        let node = node_dir.join("node.cmd");
        let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
        let system32 = PathBuf::from(&system_root).join("System32");
        let path = std::env::join_paths([&node_dir, &system32]).unwrap();

        for (version, accepted) in [
            ("v22.19.0", true),
            ("v22.19.0-rc.1", false),
            ("v23.11.1", false),
            ("v24.0.0", true),
            ("v24.0.0-nightly.1", false),
        ] {
            std::fs::write(
                &node,
                format!(
                    "@echo off\r\nif \"%~1\"==\"--version\" (\r\n  echo {version}\r\n  exit /b 0\r\n)\r\necho LOCAL_NODE_LAUNCHED\r\nexit /b 0\r\n"
                ),
            )
            .unwrap();
            let output = std::process::Command::new(system32.join("cmd.exe"))
                .args(["/d", "/c"])
                .arg(&shim)
                .arg("--version")
                .env("PATH", &path)
                .env("SystemRoot", &system_root)
                .env_remove("DSH_NODE")
                .env("DSH_PREFER_BUNDLED_PNPM", "1")
                .output()
                .unwrap();
            let stdout = String::from_utf8_lossy(&output.stdout);
            assert_eq!(
                output.status.success(),
                accepted,
                "version {version}, stdout: {stdout:?}, stderr: {:?}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert_eq!(stdout.contains("LOCAL_NODE_LAUNCHED"), accepted);
        }

        let _ = std::fs::remove_dir_all(dir);
    }

    #[cfg(windows)]
    #[test]
    fn ps1_shim_escapes_quotes() {
        let dir = PathBuf::from(r"C:\Users\o'brien\AppData\Roaming\dsh-tauri");
        let content = build_ps1_shim(&shim_paths_for(&dir), &sample_dsh_home());
        assert!(content.contains(r"o''brien"));
        // dsh_home 同样走 ps1 转义
        assert!(content.contains(r"C:\Users\test\.dsh"));
    }

    #[test]
    fn cmd_shim_prefers_user_dsh() {
        let content = build_cmd_shim(&sample_shim_paths(), &sample_dsh_home());
        assert!(content.contains("USER_DSH"));
        assert!(content.contains(r#"call "%USER_DSH%" %*"#));
        assert!(content.contains("SELF_PREFIX"));
        // 用户 dsh 优先转发应出现在捆绑启动之前
        let user_at = content.find("USER_DSH").unwrap();
        let bundled_at = content.find(":use_bundled").unwrap();
        assert!(user_at < bundled_at);
    }

    #[test]
    fn ps1_shim_prefers_user_dsh() {
        let content = build_ps1_shim(&sample_shim_paths(), &sample_dsh_home());
        assert!(content.contains("Get-Command dsh -All"));
        assert!(content.contains("$userDsh.Source"));
        assert!(content.contains("$PSScriptRoot"));
        // DSH_HOME 绑定只在捆绑启动分支注入(转发用户 dsh 时保留用户环境)
        let user_at = content.find("$userDsh").unwrap();
        let home_at = content.find("$env:DSH_HOME = $dshHome").unwrap();
        assert!(user_at < home_at);
    }

    #[test]
    fn sh_shim_prefers_user_dsh() {
        #[cfg(not(windows))]
        {
            let content = build_sh_shim(&sample_shim_paths(), &sample_dsh_home());
            assert!(content.contains(r#"exec "$dir/dsh" "$@""#));
            assert!(content.contains(r#"[ "$dir/dsh" -ef "$0" ]"#));
            // 用户 dsh 优先 > 注入 DSH_HOME
            let user_at = content.find(r#""$dir/dsh""#).unwrap();
            let home_at = content.find("export DSH_HOME").unwrap();
            assert!(user_at < home_at);
        }
    }
}