Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(scripts): pnpm 原生二进制发行版下开发脚本不再把 pnpm 交给 node 执行 (#804)
Kafeifeiba8258beb2ba
diff --git a/scripts/__tests__/ensure-deps.test.mjs b/scripts/__tests__/ensure-deps.test.mjsindex 711d7909fb..d660a0c310 100644--- a/scripts/__tests__/ensure-deps.test.mjs+++ b/scripts/__tests__/ensure-deps.test.mjs@@ -4,7 +4,10 @@ import os from 'node:os';import path from 'node:path';import test from 'node:test';-import { findMissingSubmoduleWorkspaceFiles } from '../ensure-deps.mjs';+import {+ findMissingSubmoduleWorkspaceFiles,+ resolvePnpmInstallInvocation,+} from '../ensure-deps.mjs';test('detects an uninitialized protocol submodule before pnpm scans workspaces', () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-ensure-deps-'));@@ -25,3 +28,73 @@ test('detects an uninitialized protocol submodule before pnpm scans workspaces',fs.rmSync(root, { recursive: true, force: true });}});++test('runs a native pnpm binary directly instead of feeding it to node', () => {+ // pnpm 的原生二进制发行版把 npm_execpath 指向可执行文件本身;交给 node 会抛+ // SyntaxError: Invalid or unexpected token,自动修复依赖那一步直接失败。+ const nativePath = '/Users/dev/Library/pnpm/pnpm';+ assert.deepEqual(+ resolvePnpmInstallInvocation(['install'], { npm_execpath: nativePath }, () => true, { platform: 'darwin' }),+ { command: nativePath, args: ['install'], shell: false, displayCommand: 'pnpm install' },+ );+});++test('keeps running a JS pnpm entry through the current node', () => {+ const jsEntry = '/usr/local/lib/node_modules/pnpm/bin/pnpm.cjs';+ assert.deepEqual(+ resolvePnpmInstallInvocation(+ ['install'],+ { npm_execpath: jsEntry },+ () => true,+ { execPath: '/usr/local/bin/node', platform: 'darwin' },+ ),+ {+ command: '/usr/local/bin/node',+ args: [jsEntry, 'install'],+ shell: false,+ displayCommand: 'pnpm install',+ },+ );+});++test('falls back to PATH when npm_execpath is missing or stale', () => {+ assert.deepEqual(+ resolvePnpmInstallInvocation(['install'], {}, () => true, { platform: 'darwin' }),+ { command: 'pnpm', args: ['install'], shell: false, displayCommand: 'pnpm install' },+ );+ // Windows 的 restart 管线新开 cmd.exe:残留路径不可用时必须让 cmd 走 PATH/PATHEXT。+ assert.deepEqual(+ resolvePnpmInstallInvocation(+ ['install'],+ { npm_execpath: 'C:/stale/pnpm.cmd' },+ () => false,+ { platform: 'win32', comSpec: 'C:/Windows/System32/cmd.exe' },+ ),+ {+ command: 'C:/Windows/System32/cmd.exe',+ args: [+ '/d',+ '/s',+ '/v:off',+ '/c',+ '""%CINDY_PNPM_CMD_ARG_0%" "%CINDY_PNPM_CMD_ARG_1%""',+ ],+ env: {+ CINDY_PNPM_CMD_ARG_0: 'pnpm',+ CINDY_PNPM_CMD_ARG_1: 'install',+ },+ shell: false,+ windowsVerbatimArguments: true,+ displayCommand: 'pnpm install',+ },+ );+});++test('does not derive platform from environment variables', () => {+ assert.deepEqual(+ resolvePnpmInstallInvocation(['install'], { platform: 'win32', Platform: 'x64' }, () => true, {+ platform: 'darwin',+ }),+ { command: 'pnpm', args: ['install'], shell: false, displayCommand: 'pnpm install' },+ );+});diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjsindex 96d4207711..b64e288df1 100644--- a/scripts/__tests__/test-workspaces.test.mjs+++ b/scripts/__tests__/test-workspaces.test.mjs@@ -39,7 +39,6 @@ import {planRuns,printSummary,readAllFiles,- resolvePnpmInvocation,resolveOutputStream,runCommand,runPlannedTests,@@ -48,6 +47,10 @@ import {validateManifest,validateManifestCoverage,} from "../test-workspaces.mjs";+import {+ resolvePnpmInvocation,+ usablePnpmExecPath,+} from "../shared/pnpm-invocation.mjs";const ROOT = path.resolve(fileURLToPath(new URL("../..", import.meta.url)));@@ -1105,7 +1108,7 @@ test("test gate lock timeout uses a distinct temporary-failure exit code", async}});-test("resolvePnpmInvocation uses current pnpm through node when npm_execpath is present on any platform", () => {+test("resolvePnpmInvocation uses current pnpm through node when npm_execpath points at a JS entry on any platform", () => {assert.deepEqual(resolvePnpmInvocation(["--dir", "apps/server", "run", "test"], {execPath: "C:/node/node.exe",@@ -1138,17 +1141,162 @@ test("resolvePnpmInvocation uses current pnpm through node when npm_execpath is);});+test("resolvePnpmInvocation runs a native pnpm binary directly instead of feeding it to node", () => {+ // pnpm 的原生二进制发行版(standalone 安装)把 npm_execpath 指向可执行文件本身;+ // 交给 node 会抛 SyntaxError: Invalid or unexpected token,把整轮测试变成假失败。+ assert.deepEqual(+ resolvePnpmInvocation(["--dir", "/repo/apps/server", "run", "test"], {+ execPath: "/usr/local/bin/node",+ npmExecPath:+ "/Users/dev/Library/pnpm/.tools/@pnpm+macos-arm64/10.33.2/node_modules/@pnpm/macos-arm64/pnpm",+ platform: "darwin",+ }),+ {+ command:+ "/Users/dev/Library/pnpm/.tools/@pnpm+macos-arm64/10.33.2/node_modules/@pnpm/macos-arm64/pnpm",+ args: ["--dir", "/repo/apps/server", "run", "test"],+ shell: false,+ },+ );+ assert.deepEqual(+ resolvePnpmInvocation(["--version"], {+ execPath: "/usr/bin/node",+ npmExecPath: "/home/dev/.local/share/pnpm/pnpm",+ platform: "linux",+ }),+ {+ command: "/home/dev/.local/share/pnpm/pnpm",+ args: ["--version"],+ shell: false,+ },+ );+ assert.deepEqual(+ resolvePnpmInvocation(["--version"], {+ execPath: "C:/node/node.exe",+ npmExecPath: "C:/Users/dev/AppData/Local/pnpm/pnpm.exe",+ platform: "win32",+ }),+ {+ command: "C:/Users/dev/AppData/Local/pnpm/pnpm.exe",+ args: ["--version"],+ shell: false,+ },+ );+});++test("resolvePnpmInvocation invokes Windows command wrappers through cmd.exe", () => {+ // .cmd/.bat 通过 cmd.exe 执行,同时逐字传递 /c 命令串。+ for (const npmExecPath of [+ "C:/Program Files/nodejs/pnpm.cmd",+ "C:/Program Files/nodejs/pnpm.bat",+ ]) {+ assert.deepEqual(+ resolvePnpmInvocation(["--version"], {+ execPath: "C:/node/node.exe",+ npmExecPath,+ platform: "win32",+ comSpec: "C:/Windows/System32/cmd.exe",+ }),+ {+ command: "C:/Windows/System32/cmd.exe",+ args: [+ "/d",+ "/s",+ "/v:off",+ "/c",+ '""%CINDY_PNPM_CMD_ARG_0%" "%CINDY_PNPM_CMD_ARG_1%""',+ ],+ env: {+ CINDY_PNPM_CMD_ARG_0: npmExecPath,+ CINDY_PNPM_CMD_ARG_1: "--version",+ },+ shell: false,+ windowsVerbatimArguments: true,+ },+ );+ }+});++test("resolvePnpmInvocation quotes Windows command wrapper arguments", () => {+ assert.deepEqual(+ resolvePnpmInvocation(+ [+ "--dir",+ 'C:/Users/First Last/repo & "tools"!/%literal%/apps/server',+ "run",+ "test",+ ],+ {+ npmExecPath: "C:/Program Files/nodejs/pnpm.cmd",+ platform: "win32",+ comSpec: "C:/Windows/System32/cmd.exe",+ },+ ),+ {+ command: "C:/Windows/System32/cmd.exe",+ args: [+ "/d",+ "/s",+ "/v:off",+ "/c",+ '""%CINDY_PNPM_CMD_ARG_0%" "%CINDY_PNPM_CMD_ARG_1%" "%CINDY_PNPM_CMD_ARG_2%" "%CINDY_PNPM_CMD_ARG_3%" "%CINDY_PNPM_CMD_ARG_4%""',+ ],+ env: {+ CINDY_PNPM_CMD_ARG_0: "C:/Program Files/nodejs/pnpm.cmd",+ CINDY_PNPM_CMD_ARG_1: "--dir",+ CINDY_PNPM_CMD_ARG_2: 'C:/Users/First Last/repo & ""tools""!/%literal%/apps/server',+ CINDY_PNPM_CMD_ARG_3: "run",+ CINDY_PNPM_CMD_ARG_4: "test",+ },+ shell: false,+ windowsVerbatimArguments: true,+ },+ );+});++test("usablePnpmExecPath rejects paths that are not a present pnpm entry", () => {+ const present = () => true;+ assert.equal(usablePnpmExecPath(undefined, present), undefined);+ assert.equal(usablePnpmExecPath("", present), undefined);+ // 名字不是 pnpm:npm_execpath 可能残留自 npm/yarn 的生命周期脚本。+ assert.equal(usablePnpmExecPath("/usr/local/bin/npm-cli.js", present), undefined);+ // 路径不存在:Windows 的 restart 管线新开 cmd.exe 时见过残留的旧路径。+ assert.equal(usablePnpmExecPath("/gone/pnpm.cjs", () => false), undefined);+ assert.equal(+ usablePnpmExecPath("/home/dev/.local/share/pnpm/pnpm", present),+ "/home/dev/.local/share/pnpm/pnpm",+ );+});+test("resolvePnpmInvocation fallback shell behavior is explicit per platform", () => {assert.deepEqual(resolvePnpmInvocation(["--version"], {execPath: "node",+ npmExecPath: undefined,platform: "win32",+ comSpec: "C:/Windows/System32/cmd.exe",}),- { command: "pnpm", args: ["--version"], shell: true },+ {+ command: "C:/Windows/System32/cmd.exe",+ args: [+ "/d",+ "/s",+ "/v:off",+ "/c",+ '""%CINDY_PNPM_CMD_ARG_0%" "%CINDY_PNPM_CMD_ARG_1%""',+ ],+ env: {+ CINDY_PNPM_CMD_ARG_0: "pnpm",+ CINDY_PNPM_CMD_ARG_1: "--version",+ },+ shell: false,+ windowsVerbatimArguments: true,+ },);assert.deepEqual(resolvePnpmInvocation(["--version"], {execPath: "node",+ npmExecPath: undefined,platform: "darwin",}),{ command: "pnpm", args: ["--version"], shell: false },@@ -1156,6 +1304,7 @@ test("resolvePnpmInvocation fallback shell behavior is explicit per platform", (assert.deepEqual(resolvePnpmInvocation(["--version"], {execPath: "node",+ npmExecPath: undefined,platform: "linux",}),{ command: "pnpm", args: ["--version"], shell: false },diff --git a/scripts/desktop-dev-runner.mjs b/scripts/desktop-dev-runner.mjsindex 278fb5fccf..162a2d2405 100644--- a/scripts/desktop-dev-runner.mjs+++ b/scripts/desktop-dev-runner.mjs@@ -8,6 +8,8 @@ import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { resolvePnpmInvocation, usablePnpmExecPath } from './shared/pnpm-invocation.mjs';+const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const mode = process.argv[2];if (mode !== 'remote' && mode !== 'local') {@@ -16,26 +18,23 @@ if (mode !== 'remote' && mode !== 'local') {}const devScript = mode === 'local' ? 'dev:desktop' : 'dev:desktop:remote';-const pnpmExecPath = process.env.npm_execpath;-const hasPnpmExecPath = Boolean(- pnpmExecPath && /pnpm/i.test(path.basename(pnpmExecPath)) && fs.existsSync(pnpmExecPath),-);// The restart pipeline opens a fresh Windows cmd.exe. That environment does-// not always carry npm_execpath, and Node cannot spawn a command shim with the-// default shell:false behavior. Let cmd.exe resolve the extension-neutral-// command through PATH/PATHEXT so both pnpm.cmd and standalone pnpm.exe-// installations work.-const command = hasPnpmExecPath ? process.execPath : 'pnpm';-const args = hasPnpmExecPath- ? [pnpmExecPath, devScript]- : [devScript];+// not always carry npm_execpath, and may carry a stale one, so the path is+// validated before use; resolvePnpmInvocation then decides how to execute it+// (JS entry via node, native binary directly, command wrapper through PATH),+// and falls back to PATH/PATHEXT resolution when nothing usable is left.+const invocation = resolvePnpmInvocation([devScript], {+ npmExecPath: usablePnpmExecPath(process.env.npm_execpath, fs.existsSync),+});+const { command, args } = invocation;const child = spawn(command, args, {cwd: rootDir,- env: { ...process.env, COREPACK_ENABLE_AUTO_PIN: '0' },+ env: { ...process.env, COREPACK_ENABLE_AUTO_PIN: '0', ...(invocation.env ?? {}) },stdio: 'inherit',windowsHide: false,- shell: process.platform === 'win32' && !hasPnpmExecPath,+ shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,});child.once('error', (error) => {diff --git a/scripts/desktop-worker-benchmark.mjs b/scripts/desktop-worker-benchmark.mjsindex 4be224f7fe..cf65e84205 100644--- a/scripts/desktop-worker-benchmark.mjs+++ b/scripts/desktop-worker-benchmark.mjs@@ -6,10 +6,10 @@ import { performance } from 'node:perf_hooks';import { fileURLToPath } from 'node:url';import manifest from './test-workspaces.config.mjs';+import { resolvePnpmInvocation } from './shared/pnpm-invocation.mjs';import {buildPnpmArgs,normalizeRelPath,- resolvePnpmInvocation,runCommand,} from './test-workspaces.mjs';@@ -187,7 +187,9 @@ async function runSample({ workers, iteration, top }) {try {const result = await runCommand(invocation.command, invocation.args, {cwd,+ env: invocation.env ? { ...process.env, ...invocation.env } : undefined,shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,stdout: null,stderr: null,});diff --git a/scripts/ensure-deps.mjs b/scripts/ensure-deps.mjsindex 2eefb9164f..6c0018b780 100644--- a/scripts/ensure-deps.mjs+++ b/scripts/ensure-deps.mjs@@ -32,6 +32,8 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { spawnSync } from 'node:child_process';+import { resolvePnpmInvocation, usablePnpmExecPath } from './shared/pnpm-invocation.mjs';+const ROOT = path.resolve(fileURLToPath(new URL('..', import.meta.url)));const ENTRY_FILE = fileURLToPath(import.meta.url);const log = (msg) => console.log(`\x1b[36m[ensure-deps]\x1b[0m ${msg}`);@@ -296,7 +298,9 @@ function runInstall(args = ['install']) {const result = spawnSync(invocation.command, invocation.args, {cwd: ROOT,stdio: 'inherit',- env: createElectronInstallEnv(),+ env: { ...createElectronInstallEnv(), ...(invocation.env ?? {}) },+ shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,});if (result.error || result.status !== 0) {if (result.error) err(result.error.message);@@ -321,17 +325,16 @@ function createElectronInstallEnv() {};}-function resolvePnpmInstallInvocation(args) {- const baseDisplay = `pnpm ${args.join(' ')}`;- const npmExecPath = process.env.npm_execpath;- if (npmExecPath && /pnpm/i.test(path.basename(npmExecPath)) && fs.existsSync(npmExecPath)) {- return {- command: process.execPath,- args: [npmExecPath, ...args],- displayCommand: baseDisplay,- };- }- return { command: 'pnpm', args, displayCommand: baseDisplay };+export function resolvePnpmInstallInvocation(args, env = process.env, exists = fs.existsSync, options = {}) {+ // npm_execpath 只保证是路径:JS 入口能交给 node,原生二进制发行版必须直接执行,+ // Windows 命令包装通过 cmd.exe/ComSpec 解析 PATH/PATHEXT——判定统一收敛在 resolvePnpmInvocation。+ const invocation = resolvePnpmInvocation(args, {+ npmExecPath: usablePnpmExecPath(env.npm_execpath, exists),+ execPath: options.execPath,+ platform: options.platform,+ comSpec: options.comSpec,+ });+ return { ...invocation, displayCommand: `pnpm ${args.join(' ')}` };}function runElectronInstallJs(root = ROOT) {diff --git a/scripts/shared/pnpm-invocation.mjs b/scripts/shared/pnpm-invocation.mjsnew file mode 100644index 0000000000..70cdb396ac--- /dev/null+++ b/scripts/shared/pnpm-invocation.mjs@@ -0,0 +1,85 @@+import path from "node:path";++/**+ * 解析「该怎么调用 pnpm」。+ *+ * `npm_execpath` 只保证是一个路径,不保证是脚本:corepack/npm 安装的 pnpm 指向 JS 入口+ * (`pnpm.cjs`),而原生二进制发行版(`get.pnpm.io` 的 standalone 安装,以及 pnpm 自管+ * `packageManager` 版本时下载的 `@pnpm/<platform>` 包)指向可执行文件本身。把后者交给+ * `node` 会让它按 JS 解析 Mach-O/PE,抛 `SyntaxError: Invalid or unexpected token`——+ * pnpm 根本没启动,调用方看到的却是命令的失败输出,极易误判成业务错误。+ */+const JS_ENTRY_EXTENSIONS = new Set([".js", ".cjs", ".mjs"]);+// Windows 上只有这两类扩展能被 spawn 直接拉起;.cmd/.bat 这类命令包装+// 通过 cmd.exe 解析 PATH/PATHEXT,避免 shell:true 拼接参数数组。+const WINDOWS_DIRECT_EXEC_EXTENSIONS = new Set([".exe", ".com"]);+const WINDOWS_CMD_ARG_ENV_PREFIX = "CINDY_PNPM_CMD_ARG_";++/**+ * @param {string[]} args 传给 pnpm 的参数+ * @param {{ npmExecPath?: string, npm_execpath?: string, execPath?: string, platform?: NodeJS.Platform | string, comSpec?: string }} options+ * 允许注入 npmExecPath/execPath/platform 覆写,便于测试;生产路径默认从 Node runtime 取 platform。+ * @returns {{ command: string, args: string[], shell: boolean, windowsVerbatimArguments?: boolean, env?: Record<string, string> }}+ */+export function resolvePnpmInvocation(args, options = {}) {+ const hasNpmExecPathOption =+ Object.prototype.hasOwnProperty.call(options, "npmExecPath") ||+ Object.prototype.hasOwnProperty.call(options, "npm_execpath");+ const npmExecPath = hasNpmExecPathOption+ ? (options.npmExecPath ?? options.npm_execpath)+ : process.env.npm_execpath;+ const execPath = options.execPath ?? process.execPath;+ const platform = options.platform ?? process.platform;+ const isWindows = platform === "win32";+ if (npmExecPath) {+ const extension = path.extname(npmExecPath).toLowerCase();+ if (JS_ENTRY_EXTENSIONS.has(extension))+ return { command: execPath, args: [npmExecPath, ...args], shell: false };+ if (!isWindows || WINDOWS_DIRECT_EXEC_EXTENSIONS.has(extension))+ return { command: npmExecPath, args, shell: false };+ return resolveWindowsPnpmThroughCmd(npmExecPath, args, options.comSpec);+ }+ if (isWindows) return resolveWindowsPnpmThroughCmd("pnpm", args, options.comSpec);+ return { command: "pnpm", args, shell: isWindows };+}++function resolveWindowsPnpmThroughCmd(pnpmCommand, args, comSpec = process.env.ComSpec) {+ const env = {};+ const commandLine = [pnpmCommand, ...args]+ .map((arg, index) => {+ const name = `${WINDOWS_CMD_ARG_ENV_PREFIX}${index}`;+ env[name] = escapeWindowsCmdEnvArg(arg);+ return quoteWindowsCmdExpansion(name);+ })+ .join(" ");+ return {+ command: comSpec || "cmd.exe",+ args: ["/d", "/s", "/v:off", "/c", `"${commandLine}"`],+ env,+ shell: false,+ windowsVerbatimArguments: true,+ };+}++function quoteWindowsCmdExpansion(name) {+ return `"%${name}%"`;+}++function escapeWindowsCmdEnvArg(arg) {+ return String(arg).replace(/"/g, '""');+}++/**+ * 判断 `npm_execpath` 是否可用:它可能残留自另一个环境,或指向已删除的文件+ * (Windows 的 restart 管线新开 cmd.exe 时就见过)。不可用时返回 undefined,+ * 交给 {@link resolvePnpmInvocation} 退回 PATH 解析。+ *+ * @param {string | undefined} npmExecPath+ * @param {(target: string) => boolean} exists+ * @returns {string | undefined}+ */+export function usablePnpmExecPath(npmExecPath, exists) {+ if (!npmExecPath) return undefined;+ if (!/pnpm/i.test(path.basename(npmExecPath))) return undefined;+ return exists(npmExecPath) ? npmExecPath : undefined;+}diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjsindex 99d34faebb..21df61e40d 100644--- a/scripts/test-workspaces.mjs+++ b/scripts/test-workspaces.mjs@@ -4,6 +4,7 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";import { fileURLToPath } from "node:url";+import { resolvePnpmInvocation } from "./shared/pnpm-invocation.mjs";import {acquireTestGateLock,shouldUseTestGateLock,@@ -428,16 +429,6 @@ function describeTierStatus(manifestWorkspaces, tier) {return entries.length ? entries.join(" ") : "Tier is not declared in manifest.";}-export function resolvePnpmInvocation(args, env = process.env) {- const npmExecPath = env.npmExecPath ?? env.npm_execpath;- const execPath = env.execPath ?? process.execPath;- if (npmExecPath)- return { command: execPath, args: [npmExecPath, ...args], shell: false };- const platform = env.platform ?? process.platform;- const isWindows = platform === "win32";- return { command: "pnpm", args, shell: isWindows };-}-export function classifyFailure({ stage, exitCode, output }) {if (stage === "preflight") return "PREFLIGHT_FAILED";if (exitCode === 0) return null;@@ -565,7 +556,9 @@ export function runCommand(command, args, options = {}) {return new Promise((resolve) => {const child = spawn(command, args, {cwd: options.cwd,+ env: options.env,shell: options.shell,+ windowsVerbatimArguments: options.windowsVerbatimArguments,windowsHide: true,});const output = createBoundedOutputBuffer(options.maxOutputChars);@@ -805,7 +798,9 @@ export async function runPlannedTests({invocation.args,{cwd,+ env: invocation.env ? { ...process.env, ...invocation.env } : undefined,shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,stdout: reporter ? null : undefined,stderr: reporter ? null : undefined,},@@ -848,7 +843,9 @@ export async function runPlannedTests({invocation.args,{cwd,+ env: invocation.env ? { ...process.env, ...invocation.env } : undefined,shell: invocation.shell,+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,stdout: reporter ? null : undefined,stderr: reporter ? null : undefined,},