Skip to content

fix(shell-ready): honor user's ZDOTDIR (XDG-layout fix) - #1737

Merged
nwparker merged 1 commit into
stablyai:mainfrom
prateek:prateek/fix-zdotdir-xdg-bug
May 14, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
prateek:prateek/fix-zdotdir-xdg-bug

Conversation

@prateek

@prateek prateek commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1739

Summary

The shell-ready zsh wrapper sources ~/.zshenv but throws away the ZDOTDIR it computes, then sources ~/.zshrc instead of $ZDOTDIR/.zshrc. Users who follow the canonical XDG idiom (export ZDOTDIR="${ZDOTDIR:-$XDG_CONFIG_HOME/zsh}" in ~/.zshenv) end up with an empty config inside any Orca PTY that flows through getShellReadyLaunchConfig (startup-command PTYs) or getAttributionShellLaunchConfig (attribution-shim PTYs). Both routes share the same wrapper rcfiles, so both routes are fixed by the same template change. SSH PTYs get the fix via the daemon mirror.

The fix:

  1. Save the spawn-env ORCA_ORIG_ZDOTDIR for fallback.
  2. unset ZDOTDIR so the user's .zshenv can fire the ${ZDOTDIR:-...} default expansion.
  3. Source ~/.zshenv inside a function, so an early return (e.g. [[ -o interactive ]] || return, common in dotfiles) exits only the function — not our wrapper.
  4. Recapture ORCA_ORIG_ZDOTDIR from whatever the user's .zshenv resolved ZDOTDIR to, falling back to the saved spawn-env value, then $HOME.
  5. Re-pin ZDOTDIR to the wrapper dir (baked into the template, not pulled from a captured variable, so the wrapper still works if a future caller forgets to set ZDOTDIR in the spawn env).

The renderer-side template (src/main/providers/local-pty-shell-ready.ts) and the daemon mirror (src/main/daemon/shell-ready.ts) get the same treatment.

Test plan

Automated (vitest, 38/38 passing locally):

  • Existing recursion-guard / self-loop tests still pass in both files.
  • New unit test pins the four load-bearing template lines (unset ZDOTDIR, function wrapper, recapture, baked re-pin).
  • New unit test covers getAttributionShellLaunchConfig: same wrapper bytes on disk, same ZDOTDIR / ORCA_ORIG_ZDOTDIR in the launch env, ORCA_SHELL_READY_MARKER=0, supportsReadyMarker=false.
  • New zsh-subprocess tests (gated on which zsh, skipped on Windows / missing zsh) source the generated .zshenv in a temp HOME and assert the resulting ZDOTDIR / ORCA_ORIG_ZDOTDIR:
    • XDG case (user .zshenv exports ZDOTDIR=$XDG_CONFIG_HOME/zsh)
    • Early-return case (user .zshenv does return 0 before setting anything)
    • Spawn-env preservation (no ZDOTDIR set by user .zshenv, spawn-env ORCA_ORIG_ZDOTDIR survives)
    • HOME fallback (no spawn-env, no user-set ZDOTDIR)
    • Self-loop normalization (user .zshenv itself echoes a wrapper-shaped ZDOTDIR), including pathological multi-trailing-slash variants

Manual:

  • Mac with ~/.zshenv exporting ZDOTDIR=$XDG_CONFIG_HOME/zsh and a function defined in ~/.config/zsh/.zshrc. Spotlight-launch Orca, then orca terminal create --worktree active --command "<that function>". Function resolves.
  • Same Mac, vanilla ~/.zshrc, no XDG layout. Same command still works (regression check).
  • Nested case: launch an Orca terminal, then from inside it run orca terminal create --command "...". Recursion guard still fires — no recursion limit exceeded from zsh.

Risk

  • ~/.zshenv is sourced once per wrapper invocation, same as before. The change is when it runs (now before the wrapper has committed to a ZDOTDIR), not how many times.
  • For vanilla users (.zshenv doesn't touch ZDOTDIR), the recapture falls through to the saved spawn-env value, which is what the old code already used. No observable change.
  • For XDG users, ORCA_ORIG_ZDOTDIR ends up at their XDG dir, and the downstream .zprofile / .zshrc / .zlogin source the right files.
  • Exported / typeset -g variables set by user .zshenv propagate out of the function unchanged (zsh's default scope is global). See the trade-offs section below for the bare local / typeset caveat.
  • The recursion guard moves from "before sourcing user .zshenv" to "after the recapture." Behavior is preserved: if user .zshenv somehow exports a wrapper-shaped ZDOTDIR, it gets normalized away before the downstream rcfiles run.
  • SSH PTYs (the daemon runs on the remote host) get the fix via the daemon mirror — no separate change needed.
  • _orca_spawn_orig_zdotdir is a top-level shell variable (not function-scoped). It lives in the same scope as user .zshenv, so a .zshenv that explicitly clobbers it (extremely unlikely given the underscore prefix) loses the spawn-env fallback path.

Known function-scope trade-offs

Sourcing ~/.zshenv inside __orca_source_user_zshenv means a few zsh constructs at the top level of user .zshenv behave function-scoped under the wrapper that they wouldn't under a vanilla zsh launch. None are silent breakages; all have a documented escape hatch:

  • setopt LOCAL_OPTIONS / LOCAL_TRAPS revert at function exit.
  • TRAPEXIT / trap '...' EXIT inside ~/.zshenv fires on function return, not shell exit. Move such traps to ~/.zprofile or ~/.zshrc.
  • Bare local / typeset (without -g) in ~/.zshenv becomes function-local. Use typeset -g or export if the binding needs to outlive ~/.zshenv.

These trade-offs are inherent to early-return survival — sourcing ~/.zshenv directly at top level would let [[ -o interactive ]] || return abort the entire wrapper, which is a worse failure mode (no ready marker, broken startup commands, broken attribution shim).

Out of scope

  • Bash users: the standard bash startup chain has no ZDOTDIR-style indirection. Users with custom layouts already source from ~/.bash_profile, which the wrapper sources directly. No analogous fix is needed in the bash wrapper.
  • Windows: ensureShellReadyWrappers() already short-circuits on process.platform === 'win32'.
  • resolveOriginalZdotdir() (Node side): unchanged. It still strips wrapper-shaped values out of the spawn env so we don't poison the recapture fallback.

🤖 Generated with Claude Code

…e right rcfiles

The wrapper .zshenv used to capture ORCA_ORIG_ZDOTDIR before sourcing the
user's ~/.zshenv, so users who set ZDOTDIR=$XDG_CONFIG_HOME/zsh in .zshenv
ended up with the wrapper sourcing ~/.zshrc instead of
~/.config/zsh/.zshrc. Functions, aliases, and PATH edits silently
disappeared inside every shell-ready PTY (startup-command, attribution
shim, SSH).

Reorder: clear ZDOTDIR, source user .zshenv inside a function (so an early
`return` doesn't abort our wrapper), recapture from user-resolved →
spawn-env → HOME, then re-pin ZDOTDIR to the wrapper dir baked into the
template. Trailing-slash normalization now matches the Node-side
normalizer. Same change in the renderer- and daemon-side wrappers.

New zsh-subprocess tests (gated on `which zsh`) cover the XDG case,
early-return survival in user .zshenv, spawn-env preservation, HOME
fallback, and self-loop normalization including pathological multi-
trailing-slash paths.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@AmethystLiang
AmethystLiang requested a review from Jinwoo-H May 13, 2026 20:34
@nwparker
nwparker merged commit 11f24f1 into stablyai:main May 14, 2026
1 check passed
nwparker added a commit that referenced this pull request May 14, 2026
Reverts #1737 because sourcing user .zshenv inside a wrapper function can change zsh scoping behavior for common startup-file patterns. We will revisit with a safer targeted fix.
@nwparker

Copy link
Copy Markdown
Contributor

I reverted this in #1864. After a more careful re-review, I think I merged #1737 too early.

The concern is not the goal of honoring ZDOTDIR itself; that is still valid. The concern is the implementation detail where Orca sources the user .zshenv inside a wrapper function. That can change normal zsh scoping behavior for common startup-file patterns, e.g. typeset -U path / path=(...), because typeset becomes function-scoped. That is too risky for shell startup.

I filed #1866 to revisit this with a safer implementation that preserves normal zsh startup semantics while still supporting XDG-style ZDOTDIR setups.

@prateek

prateek commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@nwparker thanks for catching this one! You were spot on — top-level zsh constructs in user .zshenv (typeset -U path, setopt LOCAL_OPTIONS, TRAPEXIT) were getting trapped in the function scope. Glad we found it before XDG users started hitting weird behavior in the wild.

Came back with a subshell-based fix in #1947. The subshell forks a child process so user .zshenv runs at its top level, not nested in a function. Side-effects stay isolated, early returns work, and typeset -U / setopt behave correctly. Feels like a much cleaner approach.

Also went much deeper on test coverage this time — 64 tests covering edge cases the original missed (directory existence, trailing slash variants, whitespace-only values, stderr noise from broken configs). Built a small snapshot framework along the way to keep the tests readable, which was kind of fun to write.

Take a look whenever you get a chance!

@AmethystLiang

Copy link
Copy Markdown
Contributor

also now in the latest release. yayy. thx a lot!

nwparker pushed a commit to prateek/orca that referenced this pull request May 26, 2026
Fixes stablyai#1866

This reimplements PR stablyai#1737 (reverted in stablyai#1864) with a safer approach
that preserves normal zsh startup semantics.

**Core fix**: Discover ZDOTDIR by sourcing user ~/.zshenv in a subshell
instead of inside a wrapper function. This preserves top-level zsh
scoping for common patterns like `typeset -U path` that broke in the
original implementation.

**Shell safety improvements**:
- Use `printf '%s\n'` instead of `echo` for capturing ZDOTDIR (handles
  special characters in paths safely)
- Subshell isolates early returns and side effects from wrapper

**Code quality**:
- Extract duplicated zsh wrapper template to `src/main/shell-templates.ts`
- Both local-pty and daemon paths now share identical wrapper logic

**Test coverage**:
- Add live zsh subprocess tests that spawn real zsh to verify:
  - XDG ZDOTDIR discovery works
  - `typeset -U path` in .zshrc preserves top-level scoping
  - Early returns in .zshenv don't crash the wrapper
  - Vanilla (non-XDG) configs fall back to HOME correctly
- Template structure tests validate subshell discovery logic

Before (broken):
```zsh
__orca_source_user_zshenv() {
  source "$HOME/.zshenv"  # typeset becomes function-scoped
}
```

After (fixed):
```zsh
_orca_discovered_zdotdir=$(
  unset ZDOTDIR
  [[ -f "$HOME/.zshenv" ]] && source "$HOME/.zshenv" 2>/dev/null
  printf '%s\n' "${ZDOTDIR}"
)
export ORCA_ORIG_ZDOTDIR="${_orca_discovered_zdotdir:-${_orca_spawn_orig_zdotdir:-$HOME}}"
```

The subshell sources .zshenv at top-level (preserving normal scoping),
captures only the ZDOTDIR value, then exits. User rcfiles (.zshrc, etc.)
are still sourced at the wrapper's top level, so all scoping works normally.

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
nwparker added a commit that referenced this pull request May 26, 2026
#1947)

* fix(shell-ready): honor ZDOTDIR without breaking zsh scoping

Fixes #1866

This reimplements PR #1737 (reverted in #1864) with a safer approach
that preserves normal zsh startup semantics.

**Core fix**: Discover ZDOTDIR by sourcing user ~/.zshenv in a subshell
instead of inside a wrapper function. This preserves top-level zsh
scoping for common patterns like `typeset -U path` that broke in the
original implementation.

**Shell safety improvements**:
- Use `printf '%s\n'` instead of `echo` for capturing ZDOTDIR (handles
  special characters in paths safely)
- Subshell isolates early returns and side effects from wrapper

**Code quality**:
- Extract duplicated zsh wrapper template to `src/main/shell-templates.ts`
- Both local-pty and daemon paths now share identical wrapper logic

**Test coverage**:
- Add live zsh subprocess tests that spawn real zsh to verify:
  - XDG ZDOTDIR discovery works
  - `typeset -U path` in .zshrc preserves top-level scoping
  - Early returns in .zshenv don't crash the wrapper
  - Vanilla (non-XDG) configs fall back to HOME correctly
- Template structure tests validate subshell discovery logic

Before (broken):
```zsh
__orca_source_user_zshenv() {
  source "$HOME/.zshenv"  # typeset becomes function-scoped
}
```

After (fixed):
```zsh
_orca_discovered_zdotdir=$(
  unset ZDOTDIR
  [[ -f "$HOME/.zshenv" ]] && source "$HOME/.zshenv" 2>/dev/null
  printf '%s\n' "${ZDOTDIR}"
)
export ORCA_ORIG_ZDOTDIR="${_orca_discovered_zdotdir:-${_orca_spawn_orig_zdotdir:-$HOME}}"
```

The subshell sources .zshenv at top-level (preserving normal scoping),
captures only the ZDOTDIR value, then exits. User rcfiles (.zshrc, etc.)
are still sourced at the wrapper's top level, so all scoping works normally.

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>

* Add shell-script-literal test framework and improvements

Adds a new declarative test framework for shell-ready tests that uses
literal shell scripts (copy-pastable into terminals) with inline snapshots.

Framework features:
- Shell scripts as string literals with # Run: marker to split setup/test
- Direct script execution (no brittle parsing) via temp files
- Path normalization for reproducible snapshots (<HOME>, <WRAPPER_DIR>)
- Auto-detects shell from command, supports bash/zsh/sh
- Inline snapshot testing with vitest toMatchInlineSnapshot()

Code quality improvements:
- Extract escapeRegex to shared string-utils.ts (deduplicates 2 copies)
- Refactor shell-templates.ts for readability (condense comments, add structure)
- Pre-compile regex patterns to avoid hot-path allocation
- Fix path normalization to sort by length (prevent nested path corruption)
- Fix actualUserHome handling to skip empty values

All tests passing (64/64 shell-ready tests, 55/55 affected tests).

Files added:
- src/main/providers/__tests__/shell-ready-framework/shell-script-test.ts
- src/main/providers/__tests__/shell-ready-framework/README.md
- src/main/providers/__tests__/shell-ready-framework-example.test.ts
- src/shared/string-utils.ts

Files modified:
- src/main/shell-templates.ts (readability cleanup)
- src/main/codex/config-toml-trust.ts (use shared escapeRegex)
- src/main/daemon/shell-ready.test.ts (updated for new framework)
- src/main/providers/local-pty-shell-ready.test.ts (updated for new framework)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>

* fix(shell-ready): preserve zshenv semantics

---------

Co-authored-by: Claude Sonnet 4.5 <[email protected]>
Co-authored-by: Neil <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…e right rcfiles (stablyai#1737)

The wrapper .zshenv used to capture ORCA_ORIG_ZDOTDIR before sourcing the
user's ~/.zshenv, so users who set ZDOTDIR=$XDG_CONFIG_HOME/zsh in .zshenv
ended up with the wrapper sourcing ~/.zshrc instead of
~/.config/zsh/.zshrc. Functions, aliases, and PATH edits silently
disappeared inside every shell-ready PTY (startup-command, attribution
shim, SSH).

Reorder: clear ZDOTDIR, source user .zshenv inside a function (so an early
`return` doesn't abort our wrapper), recapture from user-resolved →
spawn-env → HOME, then re-pin ZDOTDIR to the wrapper dir baked into the
template. Trailing-slash normalization now matches the Node-side
normalizer. Same change in the renderer- and daemon-side wrappers.

New zsh-subprocess tests (gated on `which zsh`) cover the XDG case,
early-return survival in user .zshenv, spawn-env preservation, HOME
fallback, and self-loop normalization including pathological multi-
trailing-slash paths.

Co-authored-by: Claude Opus 4.7 <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Reverts stablyai#1737 because sourcing user .zshenv inside a wrapper function can change zsh scoping behavior for common startup-file patterns. We will revisit with a safer targeted fix.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#1737) (stablyai#1947)

* fix(shell-ready): honor ZDOTDIR without breaking zsh scoping

Fixes stablyai#1866

This reimplements PR stablyai#1737 (reverted in stablyai#1864) with a safer approach
that preserves normal zsh startup semantics.

**Core fix**: Discover ZDOTDIR by sourcing user ~/.zshenv in a subshell
instead of inside a wrapper function. This preserves top-level zsh
scoping for common patterns like `typeset -U path` that broke in the
original implementation.

**Shell safety improvements**:
- Use `printf '%s\n'` instead of `echo` for capturing ZDOTDIR (handles
  special characters in paths safely)
- Subshell isolates early returns and side effects from wrapper

**Code quality**:
- Extract duplicated zsh wrapper template to `src/main/shell-templates.ts`
- Both local-pty and daemon paths now share identical wrapper logic

**Test coverage**:
- Add live zsh subprocess tests that spawn real zsh to verify:
  - XDG ZDOTDIR discovery works
  - `typeset -U path` in .zshrc preserves top-level scoping
  - Early returns in .zshenv don't crash the wrapper
  - Vanilla (non-XDG) configs fall back to HOME correctly
- Template structure tests validate subshell discovery logic

Before (broken):
```zsh
__orca_source_user_zshenv() {
  source "$HOME/.zshenv"  # typeset becomes function-scoped
}
```

After (fixed):
```zsh
_orca_discovered_zdotdir=$(
  unset ZDOTDIR
  [[ -f "$HOME/.zshenv" ]] && source "$HOME/.zshenv" 2>/dev/null
  printf '%s\n' "${ZDOTDIR}"
)
export ORCA_ORIG_ZDOTDIR="${_orca_discovered_zdotdir:-${_orca_spawn_orig_zdotdir:-$HOME}}"
```

The subshell sources .zshenv at top-level (preserving normal scoping),
captures only the ZDOTDIR value, then exits. User rcfiles (.zshrc, etc.)
are still sourced at the wrapper's top level, so all scoping works normally.

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>

* Add shell-script-literal test framework and improvements

Adds a new declarative test framework for shell-ready tests that uses
literal shell scripts (copy-pastable into terminals) with inline snapshots.

Framework features:
- Shell scripts as string literals with # Run: marker to split setup/test
- Direct script execution (no brittle parsing) via temp files
- Path normalization for reproducible snapshots (<HOME>, <WRAPPER_DIR>)
- Auto-detects shell from command, supports bash/zsh/sh
- Inline snapshot testing with vitest toMatchInlineSnapshot()

Code quality improvements:
- Extract escapeRegex to shared string-utils.ts (deduplicates 2 copies)
- Refactor shell-templates.ts for readability (condense comments, add structure)
- Pre-compile regex patterns to avoid hot-path allocation
- Fix path normalization to sort by length (prevent nested path corruption)
- Fix actualUserHome handling to skip empty values

All tests passing (64/64 shell-ready tests, 55/55 affected tests).

Files added:
- src/main/providers/__tests__/shell-ready-framework/shell-script-test.ts
- src/main/providers/__tests__/shell-ready-framework/README.md
- src/main/providers/__tests__/shell-ready-framework-example.test.ts
- src/shared/string-utils.ts

Files modified:
- src/main/shell-templates.ts (readability cleanup)
- src/main/codex/config-toml-trust.ts (use shared escapeRegex)
- src/main/daemon/shell-ready.test.ts (updated for new framework)
- src/main/providers/local-pty-shell-ready.test.ts (updated for new framework)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>

* fix(shell-ready): preserve zshenv semantics

---------

Co-authored-by: Claude Sonnet 4.5 <[email protected]>
Co-authored-by: Neil <[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.

shell-ready zsh wrapper drops user's ZDOTDIR before sourcing .zshenv (XDG layout broken)

3 participants