Skip to content

fix(build): run build:native with a standalone pnpm binary - #11738

Closed
Gldywn wants to merge 4 commits into
stablyai:mainfrom
Gldywn:fix-build-native-pnpm-execpath
Closed

Gldywn wants to merge 4 commits into
stablyai:mainfrom
Gldywn:fix-build-native-pnpm-execpath

Conversation

@Gldywn

@Gldywn Gldywn commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

pnpm build:native fails on any machine where pnpm is installed as a standalone native binary.

config/scripts/build-native-for-platform.mjs assumed process.env.npm_execpath is always a JavaScript file and ran it through Node:

const command = npmExecPath ? process.execPath : (win32 ? 'pnpm.cmd' : 'pnpm')
const args = npmExecPath ? [npmExecPath, 'run', scriptName] : ['run', scriptName]

That holds when pnpm comes from the npm package. It does not hold for @pnpm/exe, which the official installer, Homebrew and mise all use: there npm_execpath points at a ~60 MB Mach-O (or PE) executable, so Node is handed a binary to parse as JavaScript and dies with SyntaxError: Invalid or unexpected token. The whole build:native step, and therefore pnpm build, is unusable for those contributors.

CI never caught this because every workflow installs pnpm through pnpm/action-setup@v6, which provides the JavaScript build. npm_execpath ends in .cjs there, the process.execPath branch is correct, and everything passes. The bug is invisible in CI and reproduces only locally.

The fix routes through Node only when npm_execpath actually looks like JavaScript (/\.[cm]?js$/i), and otherwise executes npm_execpath directly, which also preserves the exact pinned pnpm version instead of falling back to whatever is on PATH. The unset case keeps today's pnpm / pnpm.cmd fallback.

The invocation logic moved into an exported resolvePnpmInvocation(scriptName, npmExecPath, platform) so it can be unit tested, and the top-level build flow now sits behind the repo's existing import.meta.url === pathToFileURL(process.argv[1]).href entry guard (the idiom already used by 19 other scripts in config/scripts) so the module is importable from a test without executing the build.

Verified end to end: pnpm run build:native now reaches build:computer-macos instead of dying with SyntaxError.

Screenshots

No visual change — this is a build script, with no UI surface.

Testing

  • pnpm lint — oxfmt --check, oxlint root, oxlint code-quality-native and oxlint --type-aware all clean
  • pnpm test — new test file passes 5/5
  • pnpm typecheck — does not cover these files; config/scripts is in no tsconfig include
  • pnpm build — see note
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

config/scripts/build-native-for-platform.test.mjs covers every shape npm_execpath can take: a .cjs path (the CI path, which must not regress), a native @pnpm/exe binary (the bug), unset on both darwin and win32, and a Windows .cmd. It is picked up by CI automatically — config/vitest.config.ts already includes config/scripts/**/*.test.mjs.

Note on pnpm build: it cannot complete on the machine this was developed on, because build:native is precisely what was broken. The five other steps (typecheck, build:relay, build:cli, build:electron-vite, build:web-from-renderer) were each run individually and all pass. CI runs the full build.

AI Review Report

Reviewed by a second agent against five questions: regex correctness, Windows .cmd handling, regression risk on the CI-exercised path, whether the tests are real, and cross-platform assumptions.

It confirmed the detection logic and the Windows quoting are correct, and — the important one — that the previous working JavaScript-pnpm path is behaviorally identical, so the CI regression risk is nil. That was the main risk worth checking: every CI job in the repo depends on that branch continuing to behave exactly as before.

It raised three low findings. Two were investigated and deliberately not acted on:

  • The import.meta.url entry guard can in theory no-op under a symlinked or case-mismatched invocation. Real, but that idiom appears in 19 files under config/scripts; changing it here alone would make this file inconsistent with the repo. It is a repo-wide topic, not something this PR introduced.
  • The tests assert resolvePnpmInvocation's return value without spying on spawnSync. Extracting a pure function and testing its contract is a deliberate design choice.

The third was acted on, in the second commit. The Windows shell branch is unreachable in production: runPnpmScript is only called after the entry path has already exited on win32, and resolvePnpmInvocation has no other consumers, so needsShell can never be true at runtime. Two tests asserting Windows behavior therefore implied a Windows coverage that does not exist. Rather than delete four correct lines, the branch now carries a why-comment stating it is unreachable today and kept so a future Windows caller cannot reintroduce the CVE-2024-27980 spawn failure, and the win32 tests moved under a describe named win32 resolver contract, unreachable from the build:native entry path so the runner output states the framing instead of implying support.

Cross-platform (macOS, Linux, Windows): the change is about spawning correctly on all three. macOS and Linux take the direct-execution path; Windows keeps the shell: true handling required since Node refused .cmd/.bat spawns as part of the CVE-2024-27980 fix. No new path handling, no shell-specific string building beyond that quoting.

SSH / remote / local: build:native is a local packaging step; it does not run against remote or SSH hosts.

Agent / integration / git-provider compatibility: not touched.

Performance: none — this resolves a command once per script invocation.

UI quality: not applicable, no UI surface.

Security Audit

Low risk. The one security-relevant aspect is the Windows shell: true branch, since spawning through a shell is where argument injection normally appears. It was reviewed specifically: the shell path is only taken for a .cmd/.bat command, the command is quoted, and the only arguments are the literal string run plus a script name that comes from this file's own call sites (build:computer-macos, build:notification-status-macos), never from user input or the environment. npm_execpath itself is set by the package manager, not by untrusted input.

No input handling, auth, secrets, IPC or dependency changes. No follow-up needed.

Notes

No behavior change for anyone whose pnpm is the JavaScript build, which includes all of CI.

The pnpm build checkbox is unchecked above for the honest reason that this PR is the fix for what blocks it locally.

Related

Independent of, and mergeable in any order with, the pnpm settings migration in the linked PR below. Same theme — this repo's pnpm integration drifting from the behavior of the pinned [email protected] — but no dependency between them, and no shared files.

See #11736.

Gldywn added 2 commits July 31, 2026 00:37
npm_execpath is only a JS entry when pnpm comes from the npm package.
Under @pnpm/exe (standalone installer, Homebrew, mise) it points at a
native executable, so handing it to process.execPath made Node parse a
Mach-O/PE binary as JavaScript and fail with 'SyntaxError: Invalid or
unexpected token'. CI never hit this because pnpm/action-setup installs
the JS build.

Route through Node only for a .js/.cjs/.mjs npm_execpath, otherwise
execute npm_execpath directly so the pinned pnpm version is preserved,
and spawn Windows .cmd/.bat entries through a shell since Node refuses
them otherwise.
build:native exits on win32 before it ever calls runPnpmScript, so the
.cmd/.bat shell handling in withWindowsShell cannot fire in production.
Keep it as a guard against a future Windows caller reintroducing the
CVE-2024-27980 spawn failure, but say so, and group the two win32 cases
under a resolver-contract describe so they stop reading as proof that
Windows is covered end to end.
The entry guard compared process.argv[1], which keeps the symlinked path,
against import.meta.filename, which Node resolves to the realpath. Behind
a symlinked checkout the two never matched, so the script fell through and
exited 0 without building anything: a silent no-op worse than the crash it
replaced. Compare the realpath of both sides instead.

Also surface result.error, so a spawn that never starts (missing pnpm,
non-executable npm_execpath) reports its cause instead of exiting 1 mute,
and fold the duplicated spawn-and-exit tails into one helper.

Cover the guard with tests: a symlinked entry path resolves, and on linux
the script spawned through a symlink still reaches its build flow.
@Gldywn
Gldywn marked this pull request as ready for review July 31, 2026 08:54
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 92701224-94ec-429a-84ad-fa9e32155cdf

📥 Commits

Reviewing files that changed from the base of the PR and between cc0abe7 and 5961437.

📒 Files selected for processing (2)
  • config/scripts/build-native-for-platform.mjs
  • config/scripts/build-native-for-platform.test.mjs
🚧 Files skipped from review as they are similar to previous changes (2)
  • config/scripts/build-native-for-platform.test.mjs
  • config/scripts/build-native-for-platform.mjs

📝 Walkthrough

Walkthrough

The native build script resolves pnpm through JavaScript entry points, native executables, PATH fallback, and Windows shell scripts. It centralizes process execution and spawn-error handling. It uses realpath-based entry-point detection, runs the Windows launcher through Node, and preserves platform-specific build branching. Tests cover command resolution, symlink-aware entry detection, invalid paths, and Linux execution through a symlink.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary fix: running the native build with a standalone pnpm binary.
Description check ✅ Passed The description covers the required sections, explains the change, documents testing limits, and includes AI review, security, and platform notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes pnpm build:native crashing with SyntaxError: Invalid or unexpected token when pnpm is installed as a standalone native binary (@pnpm/exe, Homebrew, mise), by detecting whether npm_execpath points at a JavaScript file before routing it through Node. The CI path (pnpm as a .cjs file) is behaviourally identical to before.

  • Core fix in resolvePnpmInvocation: JS_ENTRY_PATTERN = /\.[cm]?js$/i gates the "run through process.execPath" branch; any other execpath (native binary, no extension) is executed directly, avoiding Node trying to parse a Mach-O/PE binary as JavaScript.
  • isEntryPoint with realpathSync: replaces the previous raw import.meta.url string compare with symlink-resolving realpathSync calls inside a try/catch, and the whole top-level side effect is now guarded by it so the module is importable from tests.
  • Tests: five cases in the new test file cover .cjs (CI path), native binary (the bug), unset on darwin/win32, and .cmd; the win32 describe block is explicitly labelled as testing the resolver contract rather than a reachable production path.

Confidence Score: 5/5

Safe to merge — the CI-exercised path (JS-based pnpm) is unchanged, and the new native-binary path is well-tested with no logic errors found.

The detection regex correctly distinguishes .cjs/.mjs/.js from native binaries, the isEntryPoint guard makes the module importable without side effects, and the previously flagged realpathSync ENOENT risk is now covered by the try/catch. The Windows quoting is correct. No functional regressions identified.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
config/scripts/build-native-for-platform.mjs Refactors pnpm invocation to detect JS vs native binary via file-extension regex, adds isEntryPoint export with symlink-safe realpathSync, and moves top-level side effects behind the entry guard — all clean with no logic errors found.
config/scripts/build-native-for-platform.test.mjs New test file covering all npm_execpath shapes (.cjs, native binary, unset, win32 .cmd), plus entry-guard symlink round-trip on Linux; tests are honest about the win32 resolver being unreachable from production entry paths.

Reviews (2): Last reviewed commit: "fix(build): harden the entry guard and W..." | Re-trigger Greptile

isEntryPoint is exported, so it can be handed a path that no longer
exists; realpathSync then threw ENOENT instead of answering the question.
A path that cannot be resolved is not this module, so return false.

Double any quote embedded in the Windows command before wrapping it, the
cmd.exe escape convention. Windows forbids a quote in a path name so no
real npm_execpath can hit this, but the routine is exported and the
quoting is only correct if it holds for its whole input domain.

Both review comments from greptile-apps on PR stablyai#11738.
@Jinwoo-H

Copy link
Copy Markdown
Contributor

Correction: the intended reference is the standalone pnpm npm_execpath failure. We are taking ownership in issue #16655 and will reimplement safely on current main. No contributor action is requested; your credit remains preserved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants