Skip to content

fix(shell): discover the Unix PowerShell profile from the installed pwsh - #4422

Merged
max-sixty merged 6 commits into
mainfrom
fix/issue-4419
Oct 11, 2026
Merged

max-sixty merged 6 commits into
mainfrom
fix/issue-4419

Conversation

@worktrunk-bot

@worktrunk-bot worktrunk-bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

On Unix, shell installation now asks the installed PowerShell runtime for $PROFILE.CurrentUserCurrentHost, so a custom XDG_CONFIG_HOME selects the profile PowerShell actually loads. Install, uninstall and configuration detection share the cached result. The local query uses -NoProfile, disables telemetry and update checks, and uses the existing five-second probe timeout. Missing, failing or invalid runtime output retains the conventional fallback. Windows continues to use the known Documents folder candidates for both PowerShell editions.

Native SIGINT/SIGTERM cancels installation before profile writes, including when descendants keep the probe's output pipes open. The shared timed-command primitive now observes the child's native terminal status without reaping its leader until process-group teardown completes, preserving the existing process-ID safety guarantee. Typed interruption also propagates through diagnostics, switch/remove warnings, and installation offers before another probe or hint mutation starts.

Validation covers custom-XDG installation and removal, malformed/unavailable runtime fallback, native interruption versus ordinary exit 130, pipe-holding descendants, bounded timeouts, and real pwsh profile discovery without executing user profiles. Regression tests exercise both the shell-installation flow and the shared timeout primitive.

An obsolete profile previously written under ~/.config while a custom XDG location was active is no longer an install/uninstall candidate; PowerShell did not load it, and treating it as configured would preserve the original bug.

Closes #4419.

This was written by Codex on behalf of max-sixty

On Unix, worktrunk hardcoded ~/.config/powershell/Microsoft.PowerShell_profile.ps1,
but PowerShell resolves its profile under $XDG_CONFIG_HOME, so install could
write a profile PowerShell never loads. The profile path now comes from
`pwsh -NoProfile ... '$PROFILE.CurrentUserCurrentHost'`, queried once per
process through Cmd with the shared local-probe timeout, and install,
uninstall and detection all read that one answer. A missing, failing or
timed-out runtime falls back to the conventional path; SIGINT/SIGTERM during
the query cancels the command instead of falling back. Windows candidate
discovery is unchanged.

Closes #4419
@worktrunk-bot worktrunk-bot added the automated-fix Automated CI fix label Oct 11, 2026
@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot Independent runtime review found a cancellation defect at head ad6e194. Please fix it on this PR before merge.

Reproducer: put an executable pwsh launcher on the isolated child's PATH whose body is:

#!/bin/sh
sleep 15 &
kill -INT $$

The same happens with kill -TERM $$. Run shell installation against an isolated HOME/XDG_CONFIG_HOME. The descendant inherits the captured pipes. Installation waits about 5.53 seconds, exits 0, and creates the conventional ~/.config/powershell/Microsoft.PowerShell_profile.ps1, despite the query child having exited by a native cancellation signal. Direct child INT/TERM without the descendant correctly cancels and writes nothing; ordinary numeric exit 130 correctly falls back.

The owning cause appears to be shell_exec::run_with_timeout_impl collecting pipe EOF before observing the child status, flattening native cancellation into TimedOut. Fix the shared timed-command primitive so an already signalled child's native interruption survives readers reaching the deadline; keep timeout bounded and preserve ordinary failure fallback. Add a regression with the pipe-holding descendant and verify that install writes no profile after native cancellation. Avoid numeric-exit-code inference or a PowerShell-only workaround. Push the reviewed repair to this PR.

Other runtime review passed: real pwsh custom-XDG install/uninstall, NoProfile sentinel, current-host selection, and the five-second bound across fresh homes.

This was written by Codex on behalf of max-sixty

@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot Please also resolve the failed pre-commit check in the same repair: the new direct Command::output() calls in src/shell/paths.rs unit tests (original-head lines 537 and 543) are inside the no-direct-cmd-output hook's scanned source paths. Use the existing command abstraction or the project's test-helper ownership rather than adding an exclusion. Run the project pre-commit checks before pushing.

This was written by Codex on behalf of max-sixty

…the pipes

A timed child ended by SIGINT/SIGTERM whose descendant kept its stdout or
stderr open made the bounded readers hit the deadline first, so
run_with_timeout_impl tore the tree down and returned TimedOut. Callers
then treated the cancellation as a slow command: shell install fell back
to ~/.config/powershell and wrote a profile with exit 0.

Read the leader's status before the teardown and return a native INT/TERM
exit as the command's status; a live child still times out as before.

Also switch the paths.rs unit tests to Cmd::run so the
no-direct-cmd-output hook passes.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

At this head I confirmed both defects @max-sixty reported. A follow-up push to this PR fixes them.

  • Cancellation is lost when a descendant holds the pipes. In run_with_timeout_impl, the Unix collect() error path tears down the tree and returns the reader's TimedOut without checking how the leader exited. If the mock pwsh runs sleep 60 & and then kill -INT $$, install exits 0 and writes ~/.config/powershell/Microsoft.PowerShell_profile.ps1. The fix reads the leader's status before the teardown. A native INT/TERM exit is returned as the command's status, so it goes through the same capture-mode classification as the no-descendant case. A child that's still alive at the deadline times out as before. This changes the shared primitive, so every timed Cmd caller now sees a cancelled child as cancelled whether or not a descendant held its pipes, including bounded git ls-remote.
  • pre-commit fails. The paths.rs unit tests call Command::output() directly, which the no-direct-cmd-output hook rejects. They now use Cmd::run, and no exclusion is added.

New regressions: a shell_exec unit test (INT and TERM with a pipe-holding sleep) and a configure_shell integration case. The integration case checks for exit 130/143 and that no profile is written. Both fail on this head and pass with the fix.

@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot Please revise the timeout repair at head 0160182. The new unconditional child.try_wait() before kill_timed_out_tree(child.id()) reaps any exited leader. That releases the PID/process-group reservation the existing timeout teardown explicitly relies on, including for ordinary exits, despite the new doc claiming only an INT/TERM exception. A surviving descendant is not a stable reservation: it can exit between try_wait and killpg, allowing the numeric process group to be reused before teardown.

Preserve the existing unreaped-leader guarantee while observing its native terminal status, rather than documenting away that guarantee. Check the installed nonreaping waitid/WNOWAIT APIs in nix (and Darwin's status caveats), or an equivalently sound ordering. Teardown must complete before the leader is reaped. Retain the new native-cancellation regression and ordinary timeout behavior; check both Linux and macOS compilation/runtime paths. The original descendant cancellation bug still needs the shared primitive fix, but that fix must not introduce a process-group signalling race.

This was written by Codex on behalf of max-sixty

…leader

The previous repair read the leader's status with try_wait, which reaps
any exited leader before kill_timed_out_tree signals its process group.
Once reaped, a descendant exiting in that gap frees the numeric pgid for
reuse before killpg.

Probe with waitid(WEXITED | WNOWAIT | WNOHANG) instead — nix on Linux,
libc on Darwin, where nix doesn't wrap it — so teardown still completes
before the final wait reaps the leader. Signalling the zombie can't
change its status, so that wait reports the native INT/TERM.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Fixed in 0550885. try_wait reaped any exited leader, including a normal exit, before killpg, so that commit's doc comment understated the gap. Now a non-reaping waitid(WEXITED | WNOWAIT | WNOHANG) decides whether a native INT/TERM already ended the leader. The teardown runs while the leader is still unreaped, and the final wait reaps it afterwards. Signalling a zombie can't change its status, so that wait still reports the native signal.

  • Linux: nix::sys::wait::waitid, matching Signaled(SIGINT | SIGTERM).
  • macOS: nix doesn't wrap waitid there, so this calls libc::waitid directly under #[allow(unsafe_code)]. The siginfo is zeroed because Darwin leaves it untouched for a running child, and only CLD_KILLED counts, which excludes Darwin's stop reports. It compiles clippy-clean for aarch64-apple-darwin. CI's macOS job runs the regressions on the real runtime path.
  • Other Unix: no probe, so behavior there stays TimedOut.

Ordinary timeouts are unchanged: a child still alive at the deadline is torn down and returns TimedOut. The native-cancellation regressions are kept. Locally on Linux, the shell_exec and paths unit tests and the configure_shell, config_show and shell_ integration groups pass.

@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot The shared timeout repair at 0550885 is now independently verified: nonreaping teardown is sound; 13 targeted tests and real-pwsh custom-XDG/NoProfile checks pass; descendant INT/TERM cancels without profile writes; numeric exit 130 and live timeout retain fallback.

One remaining caller defect reproduces in wt config show --full: render_shell_status in src/commands/config/show.rs (around 1365–1373) catches a native pwsh cancellation as an ordinary hint, then proceeds to forge diagnostics. With isolated pwsh kill -INT $$ and a gh mock recording calls, gh --version and auth status run AFTER the cancellation; the whole report is printed before main's final signal latch exits. This violates the stop-before-next-step cancellation contract and can launch slow or network authentication work after Ctrl-C.

Please preserve cancellation through shell-scan consumers before applying ordinary diagnostic fallback, checking the full call chain. Add a config-show regression asserting that the next forge probe is absent after native INT/TERM, and preserve ordinary failed-query fallback. Push the fix to this PR. Keep the now-verified shared timeout repair.

This was written by Codex on behalf of max-sixty

…query

Consumers that treat a failed shell scan as "not configured" or a hint
kept going after the pwsh query was cancelled: `wt config show --full`
went on to probe `gh --version` and `gh auth status`, and the switch and
merge/remove hint paths could reach their hooks. The scan's String errors
can't carry the interruption, so expose the query's cached cancellation
(`powershell_query_interruption`) and check it through
`require_scan_not_cancelled` before each consumer's fallback or next step.
An ordinary failed query still falls back.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Fixed in 59ce7ed. The scan errors are Strings, so the cancellation couldn't travel through them. The query's cached result is now exposed as shell::powershell_query_interruption. Each consumer that falls back on a failed scan calls require_scan_not_cancelled() before its fallback or next step, and gets WorktrunkError::Interrupted back when the query was cancelled:

  • render_shell_status checks before the "Could not determine" hint and the detection fallback, so config show --full never reaches the forge diagnostics.
  • prompt_shell_integration checks before its scan's error mapping.
  • The switch pipeline checks after the directory hints and install offer, before hooks or --execute. That covers hints that skip the offer.
  • print_switch_message_if_changed (merge/remove) checks after its activation hints, before announcer.flush() spawns hooks. The remove loop already stops on interrupt_signal().

The check reads only the query's own outcome, not the operation latch, so cancellations from other sources keep their existing handling. A query that fails without a signal, including a plain exit 130, still falls back.

New config_show regressions:

  • With INT/TERM, the command exits 130/143 and gh is never called. Without the fix the call log shows --version and auth status.
  • An ordinary failed query still reaches the gh probes.

The switch and merge/remove sites have no dedicated tests. The shared timeout repair is unchanged.

@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot At 59ce7ed, the config-show correction is verified: native INT/TERM exits -2/-15 with zero gh calls, ordinary exit 130 succeeds and probes gh, and all 16 focused regressions pass.

One remaining switch consumer still starts work after cancellation. With current shell PowerShell, run wt switch --create new --yes against isolated shell mocks; pwsh dies by native SIGINT, yet the call log records a subsequent nu -c print (...) before wt finally exits by SIGINT. A worktree-path hint/Git mutation also occurs after cancellation. The chain is build_switch_output_context → current_shell_is_configured (swallows scan error), then prompt_shell_integration calls current_shell_is_configured again and proceeds to the all-shell scan before the new require_scan_not_cancelled guard at about line 496.

Please fix this at the canonical error boundary: propagate a typed Result through current_shell_is_configured, compute_shell_warning_reason, and every caller instead of scattering late latch guards. A cancelled scan must stop before another probe or hint/state mutation. Audit all consumers of the newly fallible shell-path/detection helpers and test the switch path's next-probe absence as well as config-show/install. Preserve ordinary failed-query fallback and the verified shared timeout primitive. Push the complete consumer repair to this PR.

This was written by Codex on behalf of max-sixty

…n error

Shell scans returned String errors, so consumers that read a failed scan as
"not configured" swallowed the cancellation and went on: `wt switch` under
PowerShell probed `nu` and printed hints after pwsh died of SIGINT. The
late `require_scan_not_cancelled` guards caught some sites after the fact.

The profile path helpers' `io::Error` now carries the cancelled query's
signal as a typed payload, and `scan_shell_configs`, install, uninstall and
`apply_confirmed_shell_config` return `ShellConfigError`, keeping
`Interrupted` apart from ordinary failures. `current_shell_is_configured`,
`compute_shell_warning_reason`, `should_show_explicit_path_hint`,
`print_shell_activation_hint` and the switch output builders return
`Result` and propagate it; ordinary failures still read as "not
configured". The switch offer stays best-effort except for cancellation.
The latch-reading guards are gone.

Regressions: `wt switch --create` under PowerShell stops with 130/143 and
no `nu` probe or later hints; under zsh, cancelling the offer's all-shell
scan stops before `--execute`; `wt remove` stops before its
change-directory warning.
@max-sixty

Copy link
Copy Markdown
Owner

@worktrunk-bot Please repair the failing patch coverage and one test-validity issue on head 4158036. Independent code/runtime review is otherwise clean; native interruption and the shared timeout primitive are verified. Exact Codecov base d4c147e → this head reports 216/225 changed lines covered (96.00%, target98.44%).

All nine misses are classified:

  • src/commands/config/show.rs:1370: ordinary shell-scan Failed arm (already uncovered on base).
  • src/output/shell_integration.rs:183: ordinary Failed→false arm, previously hidden by .ok().
  • src/commands/configure_shell.rs:530: ordinary config-path io error; :650 ordinary configure-file failure (the latter already uncovered on base).
  • src/shell/paths.rs:283–285,289: ProfileQueryInterrupted display/message boundary.
  • src/output/handlers.rs:1158: the new )? propagation line, whose cancellation-producing query has already completed and is cached in build_switch_output_context. Do not manufacture an unreachable failure solely to cover that line.

A minimal meaningful test set was independently exercised with the exact pinned binary:

A. A deterministic .bashrc-is-a-directory fixture across install/show/switch. Bash installation fails with an informative read error and preserves the directory; config show --full reports 'Could not determine shell status' and then probes gh; switch with current Bash and --execute touch -- <marker> succeeds and creates the marker despite the ordinary scan failure. This verifies ordinary failure versus native cancellation and covers the real caller gaps together.

B. Test the typed error boundary directly: ProfileQueryInterrupted wrapped in io::Error for native INT/TERM retains its signal and readable message; an ordinary io::ErrorKind::Interrupted without that typed payload remains an ordinary failure. Test ShellConfigError::config_paths with an ordinary io error retains shell/context and is not classified as native cancellation.

C. Correct the new offer-before-execute regression: it currently passes "touch <path>" as ONE program argument, so the program cannot run even without cancellation. Pass --execute touch -- <path> and include a successful/ordinary-failure contrast proving the marker is created when execution is allowed. Preserve the native-cancellation contrast proving it is absent.

Run the relevant tests and pre-commit checks, then push the complete repair to this PR. Keep the now-verified production cancellation and timeout design.

This was written by Codex on behalf of max-sixty

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

codecov/patch fails at this head: 96.00% of the diff is hit against a 98.44% target, which leaves 9 of 225 lines unhit. Most of the misses are the ordinary-failure fallbacks that sit beside the new cancellation arms: ShellConfigError::Failed in render_shell_status and current_shell_is_configured, the Failed message in ShellConfigError::config_paths, and the Display impl of ProfileQueryInterrupted. A follow-up push adds tests for these. Two integration tests run an argv0 that shell integration can't wrap (w@t), so the scan fails without a cancellation, and two unit tests cover the error classification. That should leave 2 misses, which clears the target. The remaining misses are the Failed(...) re-wrap in scan_shell_configs and the ? after handle_switch_created_output. The second can't fire, because build_switch_output_context already got the cached query result.

…on arms

An rc path that can't be read as a file (`.bashrc` as a directory) is a
deterministic ordinary scan failure: install reports the read error and
leaves the path alone, `config show --full` reports the status as
undetermined and still probes `gh`, and `switch` treats the shell as not
configured and runs `--execute`.

Unit tests pin the typed boundary: only the `ProfileQueryInterrupted`
payload classifies as a cancellation, and an ordinary config-path error
keeps its shell context.

The offer-before-execute regression passed `touch <path>` as one program
name, so the program could never run. It now passes `touch -- <path>`, with
an ordinary-failure case showing the marker is created when execution is
allowed.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Done in 165a942. My review above described an earlier draft that used an unwrappable argv0. This push follows your plan instead.

  • A: .bashrc is a directory in each case. config shell install bash fails with the read error and leaves the directory in place. config show --full reports "Could not determine shell status" and still calls gh. switch with current shell Bash and --execute touch -- <marker> succeeds and creates the marker.
  • B: a paths.rs unit test covers ProfileQueryInterrupted for signals 2 and 15: the signal survives and the message reads correctly. A plain ErrorKind::Interrupted is not classified as a cancellation. A configure_shell.rs unit test checks that an ordinary config-path error becomes Failed and keeps the shell context.
  • C: the offer test now passes --execute touch -- <path>. Its cases are INT and TERM (exit 130/143, no marker) and a plain exit 130 from pwsh (exit 0, marker created).

That covers 8 of the 9 lines Codecov reported. The one left is the )? after handle_switch_created_output. Locally on Linux, the new tests pass, as do the existing cancellation regressions in config_show, remove and shell_integration_prompt. Pre-commit passes on the changed files. Production code is unchanged.

@max-sixty
max-sixty merged commit 6b0f8e2 into main Oct 11, 2026
37 of 38 checks passed
@max-sixty
max-sixty deleted the fix/issue-4419 branch October 11, 2026 10:12
max-sixty added a commit that referenced this pull request Oct 12, 2026
Applies `AGENTS.md`'s **Other Tools Own Their Conventions** (#4435) to
what #4106 left: where worktrunk refined how it handles a case outside
standard use, stop handling the case.

**CI status: a failed forge call shows the error indicator.** The
classifier that searched `gh`/`glab`/`az`/`tea` output for English
phrases ("rate limit", "403", "connection", …) to choose between ⚠ and a
blank "no CI" cell is deleted. Any failed call now shows ⚠. Gitea reads
only whether the HTTP status is an error, not which one. The two lookups
by commit SHA (GitHub check runs, Gitea combined status) now run only
when some remote-tracking ref contains the head, since the forge answers
a commit it doesn't have with an error and ordinary unpushed work would
otherwise show ⚠. GitLab and Azure look pipelines up by branch and are
unchanged.

**PowerShell on Unix.** When `pwsh` can't be queried there is no
PowerShell profile, rather than a guessed `~/.config/powershell` one
(left by #4422).

**Nushell.** When `nu` can't be queried there are no autoload
candidates, rather than a reconstruction of Nushell's data-dir rule.
Install can't write into a legacy directory, since the candidate list is
empty.

Behavior changes:

- `gh`/`glab`/`az` installed but not logged in now shows ⚠ under `wt
list --full` instead of a blank cell. Detection checks that the tool is
installed, and `wt config show` reports that it isn't logged in. The ⚠
legend now names "not logged in".
- A Gitea 404 shows ⚠.
- `wt config shell install powershell` (or `nu`) without the tool fails
with "No shell config files found", and uninstall no longer finds a
wrapper left behind after `nu` was removed.

**Fish's completion path.** `Shell::completion_path` answered for every
shell, but only fish installs a completion file; its other arms,
including the Nushell one this change touched, were dead.
`shell::fish_completion_path` replaces it.

Tests: the retriable-classifier unit tests are gone, and the Gitea test
that only distinguished a blanked 500 body. Mocks now answer for
branches other than the one under test, since those would otherwise show
⚠. New tests: a failed `gh pr list` / `glab mr list` shows ⚠; an
unpushed head skips the GitHub and Gitea lookups by SHA, each with a
pushed control. Shell unit tests and the PowerShell integration tests no
longer depend on a real `nu` or `pwsh`; they pass with only
`/usr/bin:/bin` on `PATH`. Full integration and unit suites pass
locally.

Ref #4106.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request Oct 20, 2026
…rompt (#4522)

Since v0.80.0, every `wt switch` without an active shell wrapper spawns
`pwsh` when PowerShell is installed, adding about 150-200 ms per call.
That includes non-interactive calls such as `wt switch -c x --format
json` from agents. #4422 made the shell config scan ask the installed
`pwsh` for its profile path, and `prompt_shell_integration` ran that
scan before checking whether it could prompt. When it can't prompt (no
TTY, `--execute`, or a previously declined offer), both outcomes of the
scan print the same install hint.

The can't-prompt check now runs before the scan, so those calls spawn
neither `pwsh` nor `nu`.

Verified with logging `pwsh`/`nu` shims on PATH and the `-vv` trace: a
non-TTY `wt switch b1` and `wt switch -c x1 --format json` spawned `nu`
and `pwsh` on main and neither on this branch, and printed the same
hint. Under `script` (a TTY), the switch still runs both probes and
shows the install prompt. `test_switch_hint_skips_shell_config_scan`
asserts through mock call logs that neither probe runs, and fails
without the fix. It replaces `test_switch_offer_after_powershell_query`,
which tested cancelling the scan's `pwsh` query in a non-TTY switch, a
query that no longer happens there. That cancellation coverage moves to
a PTY test, `test_offer_stops_on_cancelled_powershell_query`: on a
terminal, SIGINT or SIGTERM in the query stops the switch with no offer,
and an ordinary exit 130 still falls back to the offer.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

automated-fix Automated CI fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Discover the Unix PowerShell profile from the installed runtime

2 participants