Skip to content

fix(terminal): expand environment variables in Windows PATH - #11987

Merged
OrcaWin merged 2 commits into
stablyai:mainfrom
siddqamar:fix/windows-path-expansion-11788
Aug 3, 2026
Merged

OrcaWin merged 2 commits into
stablyai:mainfrom
siddqamar:fix/windows-path-expansion-11788

Conversation

@siddqamar

@siddqamar siddqamar commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes Windows terminal command lookup when PATH contains variables such as %LOCALAPPDATA%, %USERPROFILE%, or %NVM_HOME%.

Expansion now applies at the final environment assembly boundary for local, daemon, and Windows SSH relay PTYs. Agent Teams PATH promotion also normalizes its requested shim path so it cannot reintroduce an unexpanded segment after expansion.

Closes #11788.

Screenshots

No visual change.

Testing

  • Focused Vitest suite: 359 passed, 38 skipped
  • Native Windows Electron E2E: terminal-windows-path-expansion.spec.ts (1 passed)
  • Full TypeScript typecheck (node, CLI, web)
  • Oxlint on all changed files
  • Added regressions for local, daemon, relay, persisted PATH merging, case-insensitive/unknown/empty variables, and post-expansion Agent Teams PATH promotion

pnpm lint passed code-quality, type-aware, reliability, max-lines, and bundled-guide checks, then stopped on pre-existing stale generated skill manifests unrelated to this diff.

Adversarial Review

Reviewed all PATH mutation points after environment assembly. The original implementation expanded too early in local and daemon PTYs, allowing Agent Teams shim promotion to prepend the raw %VAR% segment again. The takeover moves expansion to the last PATH mutation boundary and expands the promoted requested segment before deduplication.

The relay fresh-spawn and revive paths have no later Windows PATH mutation. Non-Windows paths remain unchanged. Windows SSH relays expand on the remote Windows host; Linux/macOS relays do not apply Windows syntax.

Security Audit

The implementation only substitutes %NAME% references from the existing environment before PTY spawning. Unknown variables remain unchanged. It adds no command execution, IPC, authentication, secret handling, or dependencies.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5b502d2e-ec8c-42ce-bc3b-6a400e58069d

📥 Commits

Reviewing files that changed from the base of the PR and between 12d74259c7febc24738022432005183cb64dc48e and dfb84e9.

📒 Files selected for processing (7)
  • src/main/cli/cli-installer.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pty/windows-environment-path.test.ts
  • src/main/pty/windows-environment-path.ts

📝 Walkthrough

Walkthrough

The change adds shared Windows environment-variable expansion for %NAME% references, including case-insensitive lookup and Windows-only PATH updates. Persisted PATH processing and CLI installation use the shared helpers. Daemon, local provider, and relay PTY environments expand PATH variables before spawning. Unit, integration, and Windows-only end-to-end tests cover these behaviors.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The platform-specific Electron preload marker URL change is not part of the linked PATH expansion issue. Move the preload marker URL fix to a separate PR, or document why it is required for the Windows PATH expansion tests.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: expanding environment variables in the Windows PATH.
Description check ✅ Passed The description includes all required sections, completed validation checks, test coverage, cross-platform review, security review, and implementation notes.
Linked Issues check ✅ Passed The PR satisfies [#11788] by expanding Windows PATH variables before local, daemon, and relay PTY spawning while preserving unknown variables.

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 Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

Adds centralized Windows environment variable expansion for PTY PATH values, fixing terminal command lookup when PATH entries contain %LOCALAPPDATA%, %USERPROFILE%, or other unexpanded references. The fix consolidates two pre-existing duplicate expandWindowsEnvironmentVariables implementations into a shared module and applies expansion consistently at all three PTY spawn boundaries (local, daemon, SSH relay).

  • New shared module windows-environment-expansion.ts exports expandWindowsEnvironmentVariables (expands any %VAR% string) and expandWindowsPathEnvironmentVariables (expands only Path/PATH keys, Windows-only, takes a snapshot before expanding so multiple PATH variants are all resolved against the original env).
  • Three PTY spawn sites (local-pty-provider.ts, pty-subprocess.ts, pty-handler.ts) now call expandWindowsPathEnvironmentVariables just before spawning, and mergeWindowsPathSegments also calls it so deduplication compares fully-resolved segments.
  • browser-window-close-policy.ts changes the sentinel URL to include a C: drive letter on Windows to fix a fileURLToPath crash found during validation.

Confidence Score: 5/5

Safe to merge — the change is Windows-only, well-tested at unit and integration level, and macOS/Linux PTY paths are entirely unaffected.

The expansion logic is correct: it snapshots the env before mutating, expands only Path/PATH keys, preserves unknown %VAR% tokens verbatim, and is guarded by a platform === 'win32' check at every call site. All three PTY spawn boundaries (local, daemon, relay) are covered by dedicated tests. The only finding is a minor test hygiene issue in the E2E spec where temp files are created at module load time rather than inside beforeAll.

Files Needing Attention: tests/e2e/terminal-windows-path-expansion.spec.ts — module-level temp dir setup could leak files in non-run scenarios.

Important Files Changed

Filename Overview
src/shared/windows-environment-expansion.ts New shared module; correct case-insensitive lookup, snapshot prevents in-place mutation interference, non-recursive expansion matches Windows behavior, graceful unknown-variable pass-through.
src/main/pty/windows-environment-path.ts Removed local duplicate; added expandWindowsPathEnvironmentVariables call at top of mergeWindowsPathSegments so segment deduplication compares fully-resolved paths.
src/main/cli/cli-installer.ts Removed local expandWindowsEnvironmentVariables duplicate; now imports from shared module — pure refactor, behavior identical on all call sites.
src/main/daemon/pty-subprocess.ts Single expandWindowsPathEnvironmentVariables(env) call added before PTY spawn; correctly placed after all env scrubbing/merging steps.
src/main/providers/local-pty-provider.ts Expansion added after buildSpawnEnv; idempotent when buildPtyHostEnv has already expanded via mergeWindowsPathSegments.
src/relay/pty-handler.ts Expansion added at end of env-assembly in buildSpawnEnv, covering the SSH relay PTY path.
src/shared/browser-window-close-policy.ts Sentinel URL now conditionally includes C: drive letter on Windows to avoid fileURLToPath crash; platform check uses typeof process guard for renderer safety.
tests/e2e/terminal-windows-path-expansion.spec.ts End-to-end test for Windows path expansion; temp dir and .cmd probe file are created at module load time rather than inside beforeAll, which can leave orphaned files if the module is loaded without running tests.
src/relay/pty-handler.test.ts Added platform save/restore in beforeEach/afterEach, mocked forceKillPosixPtyProcessGroups and processHasChildren to fix test isolation, plus new Windows expansion assertion.
src/shared/windows-environment-expansion.test.ts New unit tests cover case-insensitive lookup, empty-value expansion, multi-casing PATH keys, and non-Windows no-op — good coverage of the shared module.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[PTY spawn request with env containing %VAR% in PATH] --> B{Spawn path}
    B --> C[local-pty-provider.ts]
    B --> D[pty-subprocess.ts]
    B --> E[relay/pty-handler.ts]
    C --> F[buildPtyHostEnv]
    F --> G[mergePersistedWindowsPath]
    G --> H[mergeWindowsPathSegments]
    H --> I[expandWindowsPathEnvironmentVariables]
    C --> M[expandWindowsPathEnvironmentVariables idempotent second pass]
    D --> I
    E --> I
    I --> N{platform === win32?}
    N -->|No| O[no-op: macOS/Linux unchanged]
    N -->|Yes| P[snapshot env, expand Path/PATH keys only]
    P --> Q[%VAR% resolved or left verbatim if unknown]
Loading

Reviews (2): Last reviewed commit: "fix(browser): make close-policy sentinel..." | Re-trigger Greptile

Comment on lines +17 to +21
): string {
return value.replace(/%([^%]+)%/g, (match, name: string) => {
return getEnvironmentVariable(env, name) ?? match
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Silent behavior change: empty environment variables are now expanded

The two previous expandWindowsEnvironmentVariables implementations both used a truthiness guard — env[envKey] ? env[envKey] : match — which meant a variable set to an empty string was NOT expanded (the %VAR% token was left verbatim). The new implementation uses ?? match, where typeof '' === 'string' is true, so an empty-string variable now collapses its token to "". For PATH segments this is harmless, but callers that relied on the old behavior — e.g. cli-installer.ts used the function in a normalizeWindowsPath helper — will silently get different output. Worth confirming this change is intentional everywhere the function was previously called.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That context is helpful — glad the fileURLToPath crash has a fix, and moving platform-specific normalization into the main process would be a cleaner boundary.

To close the loop on my original comment: the empty-string expansion behavior change (?? match vs. the old truthiness guard) is a separate, narrower concern. If you're confident none of the prior call sites relied on empty variables being left unexpanded, then the current implementation is fine. The ?? match fallback is actually the more correct behavior semantically — it just differs from what callers may have depended on historically.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The C: sentinel change fixes a separate Windows fileURLToPath startup crash discovered while validating this PR. We will consider moving platform-specific normalization into the main process so the shared marker remains platform-neutral.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Silent behavior change: empty environment variables are now expanded

The two previous expandWindowsEnvironmentVariables implementations both used a truthiness guard — env[envKey] ? env[envKey] : match — which meant a variable set to an empty string was NOT expanded (the %VAR% token was left verbatim). The new implementation uses ?? match, where typeof '' === 'string' is true, so an empty-string variable now collapses its token to "". For PATH segments this is harmless, but callers that relied on the old behavior — e.g. cli-installer.ts used the function in a normalizeWindowsPath helper — will silently get different output. Worth confirming this change is intentional everywhere the function was previously called.

Intentional. Defined empty variables expand to an empty string, while unknown variables remain unchanged. This behavior is covered by the added regression test.

@OrcaWin
OrcaWin force-pushed the fix/windows-path-expansion-11788 branch from 12d7425 to dfb84e9 Compare August 3, 2026 08:00
@OrcaWin
OrcaWin merged commit f3c824b into stablyai:main Aug 3, 2026
@siddqamar
siddqamar deleted the fix/windows-path-expansion-11788 branch August 9, 2026 14:21
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…#11987)

* fix(terminal): expand variables in Windows PATH

* fix(terminal): preserve expanded Windows PATH at spawn

---------

Co-authored-by: OrcaWin <[email protected]>
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.

[Bug]: Windows PATH variables (%LOCALAPPDATA%, %USERPROFILE%, etc.) are not expanded in spawned shells

2 participants