Skip to content

Fix PowerShell worktree terminal cwd#7435

Open
mattemusacchio wants to merge 1 commit into
stablyai:mainfrom
mattemusacchio:fix/powershell-worktree-cwd
Open

Fix PowerShell worktree terminal cwd#7435
mattemusacchio wants to merge 1 commit into
stablyai:mainfrom
mattemusacchio:fix/powershell-worktree-cwd

Conversation

@mattemusacchio

Copy link
Copy Markdown

Summary

Fix Windows PowerShell terminal launches so Orca restores the selected worktree cwd after user profiles load.

Root cause: Orca already passes the worktree path as the PTY cwd, but a user's PowerShell profile can run Set-Location and move the interactive shell elsewhere before Codex, Claude, OpenCode, or a plain terminal prompt starts. The PowerShell bootstrap now re-applies the validated cwd with Set-Location -LiteralPath ... after profile loading and before startup commands are delivered.

Screenshots

No visual change.

Testing

  • pnpm lint
    • Fails on current main with an unrelated switch-exhaustiveness error in src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx:35:5.
    • Also ran targeted lint for the changed files: pnpm oxlint src/main/providers/windows-shell-args.ts src/main/providers/windows-shell-args.test.ts --quiet
  • pnpm typecheck
  • pnpm test
    • Full suite has unrelated Windows/environment failures on current main (for example /bin/sh ENOENT, symlink EPERM, unrelated snapshots/fixture assertions).
    • Regression coverage for this fix passed: pnpm vitest run --config config/vitest.config.ts src/main/providers/windows-shell-args.test.ts src/main/runtime/orca-runtime-terminal-cwd.test.ts
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Manual validation: launched Orca dev on Windows with a PowerShell profile that normally changes directory, opened a worktree terminal, and confirmed Get-Location stays in the selected worktree instead of the profile's default directory.

AI Review Report

Codex reviewed the change for the terminal startup flow and checked:

  • Windows PowerShell and PowerShell Core behavior: cwd restoration is appended to the encoded bootstrap after profiles load and before startup commands are embedded or delivered.
  • macOS/Linux compatibility: non-Windows shells keep their existing code paths; the new helper only affects the PowerShell branch.
  • WSL/Git Bash/cmd behavior: existing wsl.exe, Git Bash, and cmd.exe launch paths are unchanged.
  • Path handling: cwd values are still normalized/validated before spawn; the bootstrap uses PowerShell literal quoting and -LiteralPath so spaces and apostrophes do not become globbing or injection issues.
  • Agent compatibility: Codex/Claude/OpenCode-style startup commands still append after the bootstrap, so agent CLIs launch from the intended worktree cwd.
  • Performance: no extra process spawn or filesystem scan is introduced; this only adds one PowerShell built-in command to startup.

No follow-up code changes were needed after review.

Security Audit

Reviewed command execution and path handling risks:

  • The cwd is not user-executed text; it is encoded into the PowerShell bootstrap using existing shell-literal quoting (quoteStartupArg(..., 'powershell')).
  • Set-Location -LiteralPath avoids wildcard expansion and handles special path characters safely.
  • The existing validateWorkingDirectory and guarded cwd resolution remain in place before spawning the PTY.
  • The change does not touch auth, secrets, network access, IPC boundaries, or dependency versions.
  • Remote/SSH paths are not newly trusted; this only changes the native Windows PowerShell launch branch.

Follow-up: none known.

Notes

  • This specifically fixes Windows PowerShell profiles that force a default directory such as Documents\Workspace, causing Orca worktree terminals and agent launches to start outside the selected worktree.
  • X handle: @mattemusacchio

@mattemusacchio mattemusacchio changed the title [codex] Fix PowerShell worktree terminal cwd Fix PowerShell worktree terminal cwd Jul 5, 2026
@mattemusacchio mattemusacchio marked this pull request as ready for review July 5, 2026 15:26
@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR modifies PowerShell shell argument generation on Windows to restore the launch working directory after profile loading. A new helper, getPowerShellRestoreCwdCommand, builds a literal Set-Location command appended to the existing OSC 133 bootstrap payload within getPowerShellEncodedCommand, which now accepts a cwd parameter. The call site passes nativeCwd accordingly. Corresponding tests are updated to decode the base64/UTF-16LE encoded PowerShell command and assert on decoded substrings and ordering rather than exact encoded byte matches, including verification of quoting for paths containing single quotes.

Changes

Cohort / File(s) Summary
PowerShell cwd restoration — src/main/providers/windows-shell-args.ts Added getPowerShellRestoreCwdCommand helper; updated getPowerShellEncodedCommand to accept cwd and append restore command to bootstrap; updated call site to pass nativeCwd
PowerShell cwd restoration — src/main/providers/windows-shell-args.test.ts Removed exact-match imports; added decodePowerShellCommand helper; updated assertions across multiple tests to decode and inspect PowerShell script content and ordering

Sequence Diagram(s)

sequenceDiagram
  participant resolveWindowsShellLaunchArgs
  participant getPowerShellEncodedCommand
  participant getPowerShellRestoreCwdCommand
  resolveWindowsShellLaunchArgs->>getPowerShellEncodedCommand: call with nativeCwd
  getPowerShellEncodedCommand->>getPowerShellRestoreCwdCommand: build restore command(cwd)
  getPowerShellRestoreCwdCommand-->>getPowerShellEncodedCommand: Set-Location -LiteralPath command
  getPowerShellEncodedCommand-->>resolveWindowsShellLaunchArgs: encoded bootstrap + restore command
Loading

Related PRs: None identified.

Suggested labels: windows, powershell, tests

Suggested reviewers: None identified.

Poem
A rabbit hops through PowerShell's maze,
Restoring paths through profile-loading days,
Set-Location whispers where we began,
Decoded scripts confirm the plan,
Cwd remembered, hop hop, hooray!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly names the main change: restoring the PowerShell worktree terminal cwd.
Description check ✅ Passed The description follows the template and includes summary, screenshots, testing, AI review, security audit, and 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: aaafb973-b15f-483f-a3e8-200ba5275a8d

📥 Commits

Reviewing files that changed from the base of the PR and between 492bbe3 and cadc852.

📒 Files selected for processing (2)
  • src/main/providers/windows-shell-args.test.ts
  • src/main/providers/windows-shell-args.ts

Comment on lines +71 to +77
function getPowerShellRestoreCwdCommand(cwd: string): string {
return [
'',
'# Profiles can change location; restore the PTY cwd after profile loading.',
`Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction SilentlyContinue`
].join('\n')
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Silent Set-Location failure leaves cwd unrestored with no diagnostic.

-ErrorAction SilentlyContinue means that if the worktree path is unavailable at shell-start time (e.g. deleted mid-launch), the entire fix silently no-ops and the user is left in whatever directory the profile switched to — with no signal that the restore failed. Since this is precisely the scenario the PR is meant to prevent, consider at least surfacing a warning (e.g. Write-Warning to stderr) instead of fully swallowing the error, so the failure mode is visible rather than silently regressing to the pre-fix behavior.

💡 Optional: surface a diagnostic on restore failure
 function getPowerShellRestoreCwdCommand(cwd: string): string {
   return [
     '',
     '# Profiles can change location; restore the PTY cwd after profile loading.',
-    `Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction SilentlyContinue`
+    `try { Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction Stop } catch { Write-Warning "Failed to restore working directory: $_" }`
   ].join('\n')
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function getPowerShellRestoreCwdCommand(cwd: string): string {
return [
'',
'# Profiles can change location; restore the PTY cwd after profile loading.',
`Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction SilentlyContinue`
].join('\n')
}
function getPowerShellRestoreCwdCommand(cwd: string): string {
return [
'',
'# Profiles can change location; restore the PTY cwd after profile loading.',
`try { Set-Location -LiteralPath ${quoteStartupArg(cwd, 'powershell')} -ErrorAction Stop } catch { Write-Warning "Failed to restore working directory: $_" }`
].join('\n')
}

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.

2 participants