Skip to content

fix: preserve native foreground job control - #4400

Merged
max-sixty merged 6 commits into
mainfrom
codex/native-foreground-jobs
Oct 8, 2026
Merged

max-sixty merged 6 commits into
mainfrom
codex/native-foreground-jobs

Conversation

@max-sixty

@max-sixty max-sixty commented Oct 8, 2026 •

Copy link
Copy Markdown
Owner

Foreground hooks could hang when they changed terminal settings: Worktrunk created a separate process group without giving it the terminal, so the kernel stopped the child with SIGTTOU. Foreground commands now stay in the caller's native job group, consistently for single and concurrent commands. Terminal access, Ctrl-C and job suspension follow the shell's native behavior.

Design

  • signal_forwarder owns foreground cancellation and child admission. Native SIGINT/SIGTERM deaths stop later hooks and worktree steps; a child that catches Ctrl-C keeps its ordinary exit semantics, including exit code 130. SIGTERM addressed to wt cancels its owned work even when a child catches it.
  • shell_exec and concurrent output share that lifecycle. Output drains stop on cancellation; complete buffered stdin uses an anonymous temporary file instead of writer threads. Real process pipelines remain pipes. Buffered stdin therefore requires temporary storage and is seekable.
  • Help and preview pagers use Git's pager selection and the same process primitives. Interactive pager cancellation propagates silently, and preview deadlines cover output and child waits.
  • Shell wrappers apply directory directives and clean temporary files while preserving native interrupt behavior. Nushell integration now requires 0.113 or newer and uses native finally cleanup.

Nushell 0.116's finally itself can abort a noninteractive script after Ctrl-C even when the child catches it and exits successfully. Worktrunk's directory change and cleanup still complete; the same script-continuation difference reproduces in a minimal Nushell try/finally without Worktrunk.

Bash applies aborted-line cleanup through a writable PROMPT_COMMAND. With a readonly prompt command or set -a, it applies ordinary cleanup while preserving that configuration; Ctrl-C can leave the pending directory directive unapplied.

The main behavioral coverage uses real children and PTYs: terminal ownership/settings, raw and caught Ctrl-C, PID-targeted cancellation, stopped jobs, concurrent output, pagers, and generated shell wrappers. Module contracts describe ownership and platform differences.

Validation

The complete project pre-merge gate passes locally, including the real-shell/PTY suite, Clippy, formatting, locked dependencies, and documentation checks. The change also received an independent Opus correctness and simplicity review, with fixes reviewed through convergence. macOS runtime validation is local; Linux and Windows run in CI.

Closes #4389. Thanks to @user753 for the reproduction.

This was written by Codex on behalf of max-sixty

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The new fish case shell_wrapper_preserves_native_compound_interrupts::case_3 fails on every Linux job (test (linux), both full-tests (ubuntu-24.04, …) legs, code-coverage), always at foreground_jobs.rs:1322 with left: "0", right: "130". The Linux legs install fish from apt, which is fish 3.7.0 on Ubuntu 24.04. The comment the fish wrapper relies on ("Fish cancels an interactive function when its child dies from SIGINT") doesn't hold there.

On fish 3.7.0 in an interactive pty, a child that dies from SIGINT at top level aborts the rest of the input line. That makes the test's top-level reference report native_continues = false. When the same child dies inside a function, the function returns 130 and the rest of the line keeps running. So wt raw; printf … > wrapper-raw-status; printf next > … runs to completion through the wrapper, and the following line's $status is 0 (from printf), not 130:

python3 -c '<raw SIGINT>'; touch cont0            # cont0 not created (line aborted)
function f; python3 -c '<raw SIGINT>'; return $status; end
f; echo $status > st1                             # st1 = 130 (line continued)

The pre-PR wrapper was also a function, so this isn't a user-facing regression on fish 3.x. The test's reference just doesn't model it. Taking the "native" reference from a plain fish function wrapping the raw child, rather than a top-level command, would compare like with like on both fish 3.x and the Homebrew fish the macOS leg installs. The template comment could also say which fish versions it describes.

Use a matching native function reference for compound interruption tests.
Keep Fish cleanup ahead of caller continuation and give Bash one cleanup
owner for normal completion, the next prompt, and an owned shell exit.
Preserve prompt attributes, callback scope, native exit status and child
environment; format captured values separately from literal cleanup code.

Record the actual directive paths in wrapper tests, exercise system Bash
and protected prompt configurations, and wait for foreground admission
before PID-only alias cancellation checks.

> _This was written by Codex on behalf of max-sixty_

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The fish fix passes on fish 3.7.0 locally. This head has two red checks:

  • feature-powerset fails in test_prune_preserves_failure_diagnostic_after_sibling_interrupt::case_2_later_interrupt, a test this PR adds, at assert!(barriers.join("b-one-ready").exists()) (job). Worker a waits only for b-two-ready before it fails. The prune-remove:a span can therefore complete before b's one hook has touched b-one-ready, so the assertion depends on spawn timing. The inline suggestion makes a wait for both barriers. The other test legs passed at this head, which is consistent with a race.
  • codecov/patch is failing. Per AGENTS.md (Coverage), it needs either a fix or explicit approval before merge.

The bash rewrite also drops two comments that the zsh template still has: why the COMPLETE check has to stay in the wrapper, and why the cleanup uses builtin cd (#2643). Without them, a later "simplification" could move the check into the binary or turn builtin cd back into cd. The suggestions restore both, and the three bash snapshots need refreshing after applying them. The cd comment goes above cleanup_body+=' because its apostrophes would end the single-quoted body.

Comment thread tests/integration_tests/step_prune.rs Resolved
Comment thread templates/bash.sh Resolved
Comment thread templates/bash.sh Resolved
Dump LLVM profiles before native signal death in coverage builds, retaining
SIGINT/SIGTERM exit semantics while measuring cancellation and output drains.
Register the tool-provided cfg and keep the profiler call out of normal builds.

Wait for both concurrent sibling hooks before triggering prune failure. Add
pager invalid-output and browser-launch isolation regressions, and restore the
Bash completion and builtin-cd rationale with generated snapshots.
worktrunk-bot
worktrunk-bot previously approved these changes Oct 8, 2026
Use a short PR branch name that remains visible after first-paint clipping.
The previous label rendered as brows… in the list pane, so the readiness
wait could never match it even with the cursor correctly on the PR row.
Keep the exact URL, launcher output isolation and no-fallback assertions.
@worktrunk-bot
worktrunk-bot dismissed their stale review October 8, 2026 19:29

CI failed at 6c2555a — the new test_switch_picker_open_url_keeps_launcher_output_out_of_terminal timed out on Linux (row rendered as 'brows…'). 1200388 targets this; the next review covers it.

worktrunk-bot
worktrunk-bot previously approved these changes Oct 8, 2026
Route quiet and visible output through one cancellation, reader-join and
exit-classification path. Extend the real descendant-held-pipe regression
to cover cancellation before the presentation threshold, retaining queued
diagnostics without waiting for descendant EOF.
@worktrunk-bot
worktrunk-bot dismissed their stale review October 8, 2026 19:51

codecov/patch failed on 1200388 (90.92% of diff hit, target 98.44%); AGENTS.md requires explicit approval to merge past it. The queued review evaluates the new head.

@max-sixty

Copy link
Copy Markdown
Owner Author

@worktrunk-bot The maintainer has approved the codecov/patch exception for commit 2c5737a78c5de3487c07130f5793fd4980b66f55: patch coverage is 91.23% against 98.44%, with 98.39% overall coverage. All other CI checks pass. The remaining misses were audited; they are mostly system-error cleanup and moved code. Please refresh your review on this commit with that exception settled.

This was written by Codex on behalf of max-sixty

@max-sixty
max-sixty merged commit cd6732e into main Oct 8, 2026
43 of 44 checks passed
@max-sixty
max-sixty deleted the codex/native-foreground-jobs branch October 8, 2026 23:31
This was referenced Oct 9, 2026
max-sixty added a commit that referenced this pull request Oct 20, 2026
…#4519)

Since v0.80.0, an unusable `TMPDIR` broke every command that passes
input to a child: background hooks never spawned ("Failed to prepare
detached input"), `wt step for-each` failed, `wt list` lost the
working-tree diff of a worktree with untracked files (`git add
--pathspec-from-file=-` failed), and background `wt remove` exited 1
after already removing the worktree. #4400 moved this input from a pipe
to an anonymous temp file, even when it was empty.

The temp file exists so that no writer thread can block on a child that
doesn't read its input. A pipe meets that requirement when the whole
input fits in its buffer, so on Unix `buffered_stdin` now writes the
input into a fresh pipe with a nonblocking writer before spawn and
closes the writer. Only input larger than the pipe buffer (64 KiB on
macOS and Linux) falls back to the temp file, and that case still needs
a usable `TMPDIR`. Windows keeps the temp file.

Verified with the release-review repros: with `TMPDIR=/nonexistent/dir`,
the post-start hook runs, `for-each` succeeds, `wt list` shows the dirty
worktree, and `wt remove` exits 0, matching v0.80.0. The existing list
TMPDIR test now adds an untracked file and requires empty stderr, and a
new remove test covers the detached cleanup; both fail without the fix.
The existing `test_cmd_with_stdin` covers empty input and a 1.7 MB input
that takes the temp-file path.

> _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
…ERM (#4523)

Since v0.80.0, an alias whose child dies by a signal other than
SIGINT/SIGTERM (for example `crash = "kill -KILL $$"`, or a segfaulting
program) exits 128+N with no output. v0.80.0 printed `✗ Killed by signal
N`. #4352 and #4400 limited interrupt classification to SIGINT/SIGTERM,
so these deaths now reach `alias_error_wrapper`, which turns every child
exit code into a silent `AlreadyDisplayed`. wt exits normally rather
than dying by the signal, so the shell reports nothing either.

`alias_error_wrapper` now maps a child exit with a physical signal to
`WorktrunkError::Interrupted`, the variant custom subcommands (`wt-foo`)
already use for the same case. It renders `Killed by signal N` and exits
128+N. SIGINT and SIGTERM still short-circuit earlier and are re-raised
for the shell to report, as AGENTS.md "Signal Handling" specifies, so
`kill -TERM $$` stays silent from wt. Hooks and `wt step for-each`
already report the signal in their own failure lines and are unchanged.

Verified with the release-review repros: SEGV and KILL aliases print `✗
Killed by signal 11` / `9` and exit 139 / 137, matching v0.80.0, for
single, multi-step and concurrent aliases; `exit 2` stays silent. The
new unix-only `test_step_alias_killed_by_signal` snapshot fails without
the fix.

> _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
…ected (#4525)

Since #4400 rewrote the Nushell wrapper around `try … finally`,
redirecting the stdout of a `wt` command that prints nothing there
aborts the wrapper. `nu --no-config-file -c 'source init.nu; cd repo; wt
switch --create y o> /dev/null; print $env.PWD'` prints `repo.y` on
v0.80.0, but on main it fails with `nu::shell::cant_convert ... can't
convert nothing to string` at the `try {`, stops the script, and loses
the cd.

Nushell 0.116 fails to convert a `try … finally` that evaluates to
nothing under `o>` or `o+e>`. A plain `try`, `| ignore` and `e>` are
unaffected. The wrapper's `try … finally` now evaluates to a record
holding the exit code and captured stdout, and the wrapper returns
stdout or propagates the failure after the block, as v0.80.0 did. A
failure's stdout still prints inside the block, so a failing cd
directive can't drop it, and the `finally` still applies the directive
and removes the temp files on Ctrl-C. Returning `""` from the empty
branch would also have avoided the error, but it prints a blank line
when `wt switch` is the last command of a `nu -c` script.

Verified with nu 0.116.0 against v0.80.0, main and this branch: `o>
/dev/null`, `o> file`, `| ignore`, `e> /dev/null`, `o+e> /dev/null`,
plain and captured (`let x = (wt switch …)`) calls, a stdout-producing
command redirected and piped, a failing command (exit 1 with no source
trace, with and without `o>`), and `--execute` under `o>` all match
v0.80.0 on this branch. Main fails the `o> /dev/null`, `o> file`, `o+e>`
and `--execute` under `o>` cases. An interactive PTY session runs `wt
switch` with and without `o> /dev/null` and changes directory both
times. The new `test_nu_wrapper_redirected_stdout_applies_cd` fails on
main with the same `cant_convert` error and passes here. The nushell,
shell-wrapper, init and foreground-job integration tests (291) pass with
`--features shell-integration-tests`.

> _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
…4533)

## What regressed

Since v0.80.0, Ctrl-C during `wt remove a b c` no longer stops the batch
when the pre-remove hook catches SIGINT and exits normally, as
pre-commit does (`trap '...' INT; exit 130`). Reproduced with a hook
that traps INT, exits 130 and otherwise sleeps, plus a process-group
SIGINT: v0.80.0 stops at `a` and keeps every worktree; current main
removes `b` and `c`, branches included, and runs their hooks. `wt step
prune` did the same with a hook that exits 0 after catching the key:
every candidate was removed and wt exited 0.

Two changes combined. #4400 moved foreground children into the caller's
native job group and followed the shell's wait-and-cooperative-exit
rule, so a child that handles the key keeps its own exit status. #4357
made a multi-target remove continue past a failing target.

## The rule

Max chose the batch-runner convention (make, ninja, cargo) over the
shell's: Ctrl-C that wt itself receives stops the current command. The
terminal delivers SIGINT to the whole foreground job, so wt receives the
key alongside the child. A shell waits and exits only if the child died
of the signal, because the child might be an interactive program using
Ctrl-C as input. A batch runner's steps aren't interactive, and the user
pressing Ctrl-C means "stop the batch". For a destructive loop like
remove or prune, that rule is also the one the data-safety principle
asks for.

The child still handles the key its own way, and wt never signals it for
INT. Once the child exits, the command starts nothing more and exits
interrupted (native SIGINT re-raise / 130), whatever status the child
chose. Numeric exit codes such as 130 are still never read as
cancellation; wt's own receipt is the evidence.

## What changes

- `src/signal_forwarder.rs`: the existing per-operation cancellation
(`CommandOperation`) gains a SIGINT flag beside its SIGTERM one.
Foreground scopes register it, so the scope reports cancellation when
its child exits, and later admissions in the same command are refused.
The output drain's fresh flag, which existed to ignore keys the children
had already handled, is gone.
- Covered loops: hook pipelines (including Warn-strategy post-* hooks),
multi-step aliases, `for-each`, multi-target `remove` and `prune`.
- A command's final interactive child keeps the key as input and its own
exit status: help and `config show` pagers, `--execute` programs and
custom `wt-*` subcommands opt in through `Cmd::hand_off_terminal`
(`TerminalInterrupt::ChildInput`). So does an alias's last serial step
(`ForegroundStdin::HandOff`), since the alias is the whole command;
`agent = "claude"` keeps claude's status after the user stops a turn
with Ctrl-C. Otherwise pressing Ctrl-C in `less`, a REPL started by `-x`
or such an alias, then quitting normally, would turn into exit 130.
Earlier alias steps, concurrent groups and every hook step still cancel.
- Unchanged: between children, idle SIGINT still kills wt natively.
Detached background hooks, timeout-bounded captures in their own process
group and the picker hold no foreground scope. A SIGINT sent only to wt
is still not forwarded to the child; wt waits for it to finish, then
stops. Windows is unchanged: wt installs no console Ctrl-C handler, so
the default handler already ends wt and nothing more starts.
- AGENTS.md "Signal Handling" and the `signal_forwarder` / `shell_exec`
/ `concurrent` module docs state the new rule.

## Verification

- New unix integration tests, each pressing Ctrl-C (a group SIGINT)
after wt has admitted a child that catches it: `remove` with a hook
exiting 130 and with one exiting 0 keeps both targets; a post-start
pipeline doesn't run its next step after a step exits 130; `for-each`
visits one worktree when the child exits 0. All four fail on the old
semantics. `test_alias_last_step_keeps_status_after_caught_ctrl_c`
covers the alias handoff. The exit-0 remove case also fails if the scope
stops reporting the latch and only refuses later admissions, since the
current target would still be removed.
- Existing tests that asserted the old rule now assert cancellation: the
PTY `caught_keyboard_interrupt_cancels_following_step`,
`test_alias_pid_signal_policy` (PID-only INT) and
`test_alias_group_sigint_does_not_escalate`. The children still handle
every key exactly once and wt never dies while they run.
`test_alias_caught_sigint_preserves_successful_descendant_output` is
deleted because its premise is the old rule. The pager and
custom-subcommand cases in
`custom_commands_and_help_pagers_preserve_native_signals` pass
unchanged.
- The alias signal harness moved to `tests/common` as `SignalJob` for
reuse.
- `cargo nextest run --all-features` (5377 passed), `cargo clippy
--all-targets --all-features -- -D warnings`, pre-commit on the changed
files. Manual repro of remove and prune before and after.

> _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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Foreground hooks get stopped by SIGTTOU when they change terminal settings, so wt merge hangs

2 participants