Abort kills claude_cli process group and cancels plan/ask dialogs #237

Merged
hermes merged 1 commits from fix-abort-claude-cli into main 2026-11-25 11:40:50 +00:00
Collaborator

With the claude_cli provider, bash runs inside claude -p; abort killed only claude, not its children, and the ExitPlanMode/AskUserQuestion dialogs ignored abort.

  • claude in own process group, killed on stream drop; reader stops on drop
  • exit_plan / ask race against abort
  • TUI clears choose/doc/perm popups on run end
  • test: dropping stream kills child; fix broken abort_during_tool_round test (used echo instead of slow)

Tests: all.sh minus fmt/clippy/comment-lint steps green (fmt/clippy fail on main with the local toolchain in untouched code).

With the claude_cli provider, bash runs inside `claude -p`; abort killed only claude, not its children, and the ExitPlanMode/AskUserQuestion dialogs ignored abort. - claude in own process group, killed on stream drop; reader stops on drop - exit_plan / ask race against abort - TUI clears choose/doc/perm popups on run end - test: dropping stream kills child; fix broken abort_during_tool_round test (used echo instead of slow) Tests: all.sh minus fmt/clippy/comment-lint steps green (fmt/clippy fail on main with the local toolchain in untouched code).
hermes added 1 commit 2026-11-25 09:07:40 +00:00
- claude -p runs in its own process group; dropping the stream kills the group (its Bash children survived kill_on_drop)
- reader task stops when the stream is dropped
- exit_plan/AskUserQuestion race the question against abort
- TUI clears choose/doc/perm popups when a run ends
- fix abort_during_tool_round test (tu() always built echo calls, slow never ran)

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Flaky or vacuous test

Test is gated #[cfg(unix)] but relies on /proc/{pid}/stat, which exists only on Linux. On macOS and BSD, read_to_string always returns Err, so the loop hits Err(_) => return on the first iteration and the test passes without checking anything. Gate it with #[cfg(target_os = "linux")], or use libc::kill(pid, 0) and check for ESRCH. The pid-file wait loop (loop { ... sleep(20ms) }) has no timeout, so if the spawner fails or the file is never written, the test hangs forever instead of failing. Wrap it in a bounded loop or tokio::time::timeout. The temp dir hx-kill-<pid> is never removed.

let pid = loop {
    if let Ok(x) = std::fs::read_to_string(&pidf)
        && let Ok(n) = x.trim().parse::<u32>()
    {
        break n;
    }
    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
};
drop(s);
for _ in 0..100 {
    match std::fs::read_to_string(format!("/proc/{pid}/stat")) {
        Err(_) => return,
        Ok(x) if x.rsplit(") ").next().is_some_and(|r| r.starts_with('Z')) => return,
        _ => {}
    }
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
panic!("child {pid} survived: {:?}", std::fs::read_to_string(format!("/proc/{pid}/stat")));
Abort vs cancel ambiguity

choose_or_abort(...).await.ok()?? collapses abort, user cancel, and a dropped channel into the same None. Verify the caller of ask and exit_plan does not report an abort to the model as a normal "user declined" tool result, and that the agent loop checks the abort flag right after the tool returns. Otherwise the model may keep running after an abort. Also confirm that choose_or_abort cancels the pending state.choose request, so the UI popup is not left orphaned until Ui::Done.

let r = choose_or_abort(
    cx,
    crate::Question {
        text: text.into(),
        options: options.collect(),
        multi: q["multiSelect"].as_bool().unwrap_or(false),
        other: true,
        plan: None,
    },
)
.await
.ok()??;
Popup cleanup timing

Popups are cleared only on Ui::Done, so after abort they stay visible until the run fully ends. Dropping choose, doc, and perm here also drops their response senders. Verify that nothing still waiting on them treats the drop as an approval or default answer, especially perm. Also verify that Done from an old run cannot clear a popup that belongs to a newer run.

app.choose = None;
app.doc = None;
app.perm = None;
## PR Reviewer Guide 🔍 Here are some key observations to aid the review process: <table> <tr><td>⏱️&nbsp;<strong>Estimated effort to review</strong>: 3 🔵🔵🔵⚪⚪</td></tr> <tr><td>🧪&nbsp;<strong>PR contains tests</strong></td></tr> <tr><td>🔒&nbsp;<strong>No security concerns identified</strong></td></tr> <tr><td>⚡&nbsp;<strong>Recommended focus areas for review</strong><br><br> <details><summary><a href='https://git.jokresner.de/johannes/hx/src/branch/fix-abort-claude-cli/crates/hx-ai/src/claude_cli.rs#L470-L487'><strong>Flaky or vacuous test</strong></a> Test is gated `#[cfg(unix)]` but relies on `/proc/{pid}/stat`, which exists only on Linux. On macOS and BSD, `read_to_string` always returns `Err`, so the loop hits `Err(_) => return` on the first iteration and the test passes without checking anything. Gate it with `#[cfg(target_os = "linux")]`, or use `libc::kill(pid, 0)` and check for `ESRCH`. The pid-file wait loop (`loop { ... sleep(20ms) }`) has no timeout, so if the spawner fails or the file is never written, the test hangs forever instead of failing. Wrap it in a bounded loop or `tokio::time::timeout`. The temp dir `hx-kill-<pid>` is never removed. </summary> ```rust let pid = loop { if let Ok(x) = std::fs::read_to_string(&pidf) && let Ok(n) = x.trim().parse::<u32>() { break n; } tokio::time::sleep(std::time::Duration::from_millis(20)).await; }; drop(s); for _ in 0..100 { match std::fs::read_to_string(format!("/proc/{pid}/stat")) { Err(_) => return, Ok(x) if x.rsplit(") ").next().is_some_and(|r| r.starts_with('Z')) => return, _ => {} } tokio::time::sleep(std::time::Duration::from_millis(50)).await; } panic!("child {pid} survived: {:?}", std::fs::read_to_string(format!("/proc/{pid}/stat"))); ``` </details> <details><summary><a href='https://git.jokresner.de/johannes/hx/src/branch/fix-abort-claude-cli/crates/hx-core/src/approve.rs#L255-L266'><strong>Abort vs cancel ambiguity</strong></a> `choose_or_abort(...).await.ok()??` collapses abort, user cancel, and a dropped channel into the same `None`. Verify the caller of `ask` and `exit_plan` does not report an abort to the model as a normal "user declined" tool result, and that the agent loop checks the abort flag right after the tool returns. Otherwise the model may keep running after an abort. Also confirm that `choose_or_abort` cancels the pending `state.choose` request, so the UI popup is not left orphaned until `Ui::Done`. </summary> ```rust let r = choose_or_abort( cx, crate::Question { text: text.into(), options: options.collect(), multi: q["multiSelect"].as_bool().unwrap_or(false), other: true, plan: None, }, ) .await .ok()??; ``` </details> <details><summary><a href='https://git.jokresner.de/johannes/hx/src/branch/fix-abort-claude-cli/crates/hx-tui/src/lib.rs#L624-L626'><strong>Popup cleanup timing</strong></a> Popups are cleared only on `Ui::Done`, so after abort they stay visible until the run fully ends. Dropping `choose`, `doc`, and `perm` here also drops their response senders. Verify that nothing still waiting on them treats the drop as an approval or default answer, especially `perm`. Also verify that `Done` from an old run cannot clear a popup that belongs to a newer run. </summary> ```rust app.choose = None; app.doc = None; app.perm = None; ``` </details> </td></tr> </table>

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Test passes vacuously on non-Linux Unix

The test checks liveness via /proc/{pid}/stat, which exists only on Linux. On macOS
and BSD, read_to_string always returns Err, so the loop hits Err(_) => return right
after drop(s). The test then passes without verifying that the child was killed.
Gate the test on Linux, or use kill(pid, 0).

crates/hx-ai/src/claude_cli.rs [442-444]

-#[cfg(unix)]
+#[cfg(target_os = "linux")]
 #[tokio::test]
 async fn dropping_the_stream_kills_claude_and_its_children() {
Suggestion importance[1-10]: 6

__

Why: Valid: /proc/{pid}/stat exists only on Linux, so on macOS/BSD read_to_string returns Err and the test returns early without verifying the kill. Gating on target_os = "linux" prevents a false pass, though it only affects test reliability on non-Linux platforms.

Low
Stale pid file can cause false pass

The dir is keyed only by process ID and never cleaned. A pid file left by an earlier
run with the same PID is read immediately as a valid number. That PID is usually
dead, so the test passes without checking the real child. Remove the stale dir
before creating it.

crates/hx-ai/src/claude_cli.rs [445-447]

 let dir = std::env::temp_dir().join(format!("hx-kill-{}", std::process::id()));
+let _ = std::fs::remove_dir_all(&dir);
 std::fs::create_dir_all(&dir).unwrap();
 let pidf = dir.join("pid");
Suggestion importance[1-10]: 5

__

Why: Valid: the dir is keyed only by std::process::id() and never cleaned, so a stale pid file from a prior run with the same PID could be read immediately and make the test pass without checking the real child. Removing the dir first is a cheap fix, but PID reuse across runs is a fairly rare edge case.

Low
## PR Code Suggestions ✨ <!-- 742f2a1 --> Explore these optional code suggestions: <table><thead><tr><td><strong>Category</strong></td><td align=left><strong>Suggestion&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </strong></td><td align=center><strong>Impact</strong></td></tr><tbody><tr><td rowspan=2>General</td> <td> <details><summary>Test passes vacuously on non-Linux Unix</summary> ___ **The test checks liveness via <code>/proc/{pid}/stat</code>, which exists only on Linux. On macOS <br>and BSD, <code>read_to_string</code> always returns <code>Err</code>, so the loop hits <code>Err(_) => return</code> right <br>after <code>drop(s)</code>. The test then passes without verifying that the child was killed. <br>Gate the test on Linux, or use <code>kill(pid, 0)</code>.** [crates/hx-ai/src/claude_cli.rs [442-444]](https://git.jokresner.de/johannes/hx/src/branch/fix-abort-claude-cli/crates/hx-ai/src/claude_cli.rs#L442-L444) ```diff -#[cfg(unix)] +#[cfg(target_os = "linux")] #[tokio::test] async fn dropping_the_stream_kills_claude_and_its_children() { ``` <details><summary>Suggestion importance[1-10]: 6</summary> __ Why: Valid: `/proc/{pid}/stat` exists only on Linux, so on macOS/BSD `read_to_string` returns `Err` and the test returns early without verifying the kill. Gating on `target_os = "linux"` prevents a false pass, though it only affects test reliability on non-Linux platforms. </details></details></td><td align=center>Low </td></tr><tr><td> <details><summary>Stale pid file can cause false pass</summary> ___ **The dir is keyed only by process ID and never cleaned. A <code>pid</code> file left by an earlier <br>run with the same PID is read immediately as a valid number. That PID is usually <br>dead, so the test passes without checking the real child. Remove the stale dir <br>before creating it.** [crates/hx-ai/src/claude_cli.rs [445-447]](https://git.jokresner.de/johannes/hx/src/branch/fix-abort-claude-cli/crates/hx-ai/src/claude_cli.rs#L445-L447) ```diff let dir = std::env::temp_dir().join(format!("hx-kill-{}", std::process::id())); +let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let pidf = dir.join("pid"); ``` <details><summary>Suggestion importance[1-10]: 5</summary> __ Why: Valid: the dir is keyed only by `std::process::id()` and never cleaned, so a stale `pid` file from a prior run with the same PID could be read immediately and make the test pass without checking the real child. Removing the dir first is a cheap fix, but PID reuse across runs is a fairly rare edge case. </details></details></td><td align=center>Low </td></tr></tr></tbody></table>
hermes merged commit c2ce0e3fe4 into main 2026-11-25 11:40:50 +00:00
Sign in to join this conversation.
No Reviewers
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: johannes/hx#237