Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
test(picker): release --prs loading marker on parent exit, not a timer (#3532)
Worktrunk Bot203603909dac
diff --git a/src/testing/mock_commands.rs b/src/testing/mock_commands.rsindex ae9d66ffa..e0d14a9c5 100644--- a/src/testing/mock_commands.rs+++ b/src/testing/mock_commands.rs@@ -79,6 +79,7 @@ pub struct MockResponse {stderr: Option<String>,exit_code: i32,delay_ms: u64,+ hold_until_parent_exit: bool,}impl MockResponse {@@ -90,6 +91,7 @@ impl MockResponse {stderr: None,exit_code: 0,delay_ms: 0,+ hold_until_parent_exit: false,}}@@ -101,6 +103,7 @@ impl MockResponse {stderr: None,exit_code: 0,delay_ms: 0,+ hold_until_parent_exit: false,}}@@ -112,6 +115,7 @@ impl MockResponse {stderr: Some(text.to_string()),exit_code: 0,delay_ms: 0,+ hold_until_parent_exit: false,}}@@ -123,6 +127,7 @@ impl MockResponse {stderr: None,exit_code: code,delay_ms: 0,+ hold_until_parent_exit: false,}}@@ -145,6 +150,16 @@ impl MockResponse {self}+ /// Hold the response until the parent `wt` process exits, then exit without+ /// output. Pins a transient in-flight frame (e.g. the picker's+ /// `Loading open PRs…` marker) on screen for exactly the picker's lifetime,+ /// so a presence assertion never races boot latency. Overrides any delay or+ /// response body. See the `hold_until_parent_exit` docs in `mock-stub`.+ pub fn hold_until_parent_exit(mut self) -> Self {+ self.hold_until_parent_exit = true;+ self+ }+fn to_json(&self) -> serde_json::Value {let mut obj = serde_json::Map::new();if let Some(f) = &self.file {@@ -164,6 +179,9 @@ impl MockResponse {if self.delay_ms != 0 {obj.insert("delay_ms".to_string(), json!(self.delay_ms));}+ if self.hold_until_parent_exit {+ obj.insert("hold_until_parent_exit".to_string(), json!(true));+ }serde_json::Value::Object(obj)}}diff --git a/tests/helpers/mock-stub/src/main.rs b/tests/helpers/mock-stub/src/main.rsindex 3ae8e6223..7a9b1d274 100644--- a/tests/helpers/mock-stub/src/main.rs+++ b/tests/helpers/mock-stub/src/main.rs@@ -33,6 +33,12 @@//! - `exit_code`: exit with specified code (default 0)//! - `delay_ms`: sleep this long before responding (default 0), to simulate a//! slow command (e.g. a forge call the picker streams in behind its frame)+//! - `hold_until_parent_exit`: hold the response until the parent process (the+//! `wt` under test) exits, then exit without producing output. Lets a test+//! pin a *transient* frame — e.g. the picker's `Loading open PRs…` marker,+//! on screen only while a forge call is in flight — on screen for exactly as+//! long as the picker lives, with no fixed `delay_ms` to outguess boot+//! latency. Overrides `delay_ms` and any `file`/`output` response.use serde::Deserialize;use std::collections::HashMap;@@ -60,6 +66,45 @@ struct CommandResponse {exit_code: i32,#[serde(default)]delay_ms: u64,+ #[serde(default)]+ hold_until_parent_exit: bool,+}++/// Block until the parent process (the `wt` under test) exits, then return.+///+/// A test that asserts a *transient* frame — the picker's `Loading open PRs…`+/// marker, on screen only while a forge call is in flight — needs that frame to+/// stay up for exactly as long as the picker lives, with no fixed sleep to+/// outguess boot latency. This mock *is* the in-flight forge call: the picker's+/// fetch thread runs it with a piped stdout and blocks reading that pipe to EOF,+/// so as long as this process neither writes a full response nor exits, the+/// marker stays. When the test aborts the picker, `wt` detaches the fetch thread+/// and exits, which closes the read end of our stdout pipe; the next write here+/// then fails with `BrokenPipe`.+///+/// Polling for that write error is a *causal* parent-death signal — release is+/// tied to the parent exiting, not to a timer — and it needs no platform+/// primitive (`getppid` / `OpenProcess`), so it behaves identically on Unix and+/// Windows. Rust's runtime ignores `SIGPIPE`, so the broken write surfaces as an+/// `Err` rather than killing this process.+///+/// The one-byte probes written into stdout are harmless: this mode's contract is+/// that the parent aborts without ever parsing the response, and the fetch+/// thread drains the pipe until process exit, so the bytes are never observed. A+/// generous cap bounds a stuck orphan if the pipe somehow never breaks.+fn wait_for_parent_exit() {+ // 20ms per poll × 3000 = a 60s ceiling, far beyond any picker lifetime; it+ // exists only so a detached mock can't linger forever if detection fails.+ const MAX_POLLS: u32 = 3000;+ let mut stdout = io::stdout();+ for _ in 0..MAX_POLLS {+ match stdout.write_all(&[0]).and_then(|()| stdout.flush()) {+ // Write succeeded → the parent's read end is still open → still alive.+ Ok(()) => sleep(Duration::from_millis(20)),+ // BrokenPipe (or any other write failure) → the parent has exited.+ Err(_) => return,+ }+ }}/// Get command name from argv\[0\].@@ -139,6 +184,7 @@ fn main() {stderr: None,exit_code: 1,delay_ms: 0,+ hold_until_parent_exit: false,};// Try triple match first (e.g., "mr view 1", "mr view 2")@@ -170,6 +216,13 @@ fn main() {.or_else(|| config.commands.get("_default")).unwrap_or(&default_response);+ // Hold the response for the parent's whole lifetime, then exit without+ // output — the marker-clearing edge is the parent's death, not a timer.+ if response.hold_until_parent_exit {+ wait_for_parent_exit();+ exit(0);+ }+// Simulate a slow command (e.g. a forge call) so tests can observe the// caller's in-flight UI before the response lands.if response.delay_ms > 0 {diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rsindex 78b3417a4..bc0254158 100644--- a/tests/integration_tests/switch_picker.rs+++ b/tests/integration_tests/switch_picker.rs@@ -1469,32 +1469,48 @@ fn seed_ci_status(repo: &TestRepo, branch: &str, status_json: &str) {}/// Install a mock forge CLI (`gh`/`glab`) that answers the `--prs` list call-/// from a canned JSON file, and return env vars (mock on PATH + MOCK_CONFIG_DIR)-/// for a `wt switch --prs` PTY run. No network is touched. `list_delay_ms`-/// sleeps the list call (0 = instant) so a test can observe the picker's-/// in-flight loading marker before the rows land.-fn mock_forge_env(+/// from a canned JSON file with a caller-supplied response shape, and return env+/// vars (mock on PATH + MOCK_CONFIG_DIR) for a `wt switch --prs` PTY run. No+/// network is touched. The `list.json` file the response reads from is written+/// here, so `list_response` should be built with `MockResponse::file("list.json")`.+fn mock_forge_env_with(repo: &TestRepo,cli: &str,list_cmd: &str,list_json: &str,- list_delay_ms: u64,+ list_response: MockResponse,) -> Vec<(String, String)> {let mock_bin = repo.root_path().join("mock-bin");std::fs::create_dir_all(&mock_bin).unwrap();std::fs::write(mock_bin.join("list.json"), list_json).unwrap();MockConfig::new(cli).version(&format!("{cli} version 1.0.0 (mock)"))- .command(- list_cmd,- MockResponse::file("list.json").with_delay_ms(list_delay_ms),- )+ .command(list_cmd, list_response).command("_default", MockResponse::exit(1)).write(&mock_bin);forge_mock_env_vars(repo, &mock_bin)}+/// [`mock_forge_env_with`] with a fixed-delay list response. `list_delay_ms`+/// sleeps the list call (0 = instant) so a test can observe the picker's+/// in-flight loading marker before the rows land.+fn mock_forge_env(+ repo: &TestRepo,+ cli: &str,+ list_cmd: &str,+ list_json: &str,+ list_delay_ms: u64,+) -> Vec<(String, String)> {+ mock_forge_env_with(+ repo,+ cli,+ list_cmd,+ list_json,+ MockResponse::file("list.json").with_delay_ms(list_delay_ms),+ )+}+/// Env vars (mock-bin on PATH + `MOCK_CONFIG_DIR`) for a PTY `wt` run that should/// resolve `gh`/`glab` to a mock written into `mock_bin`. Shared by/// [`mock_forge_env`] and tests that build a richer mock (extra `pr view`@@ -1822,13 +1838,14 @@ fn test_switch_picker_preview_auto_refreshes_when_compute_lands(mut repo: TestRe}/// `wt switch --prs` shows a dim "↳ Loading open PRs…" marker on the header row-/// while the forge call is in flight. A delayed mock holds the PR list long-/// enough to observe the marker on the real screen before the rows land. The-/// picker captures and aborts at stabilize time — well before the delay-/// elapses — and the `--prs` thread is detached on exit (not joined), so the-/// test never pays the full delay. The marker's *clearing* once rows arrive is-/// covered by the `header_loading_marker_shows_until_cleared` unit test and the-/// negative assertion in `test_switch_picker_prs_github_list`.+/// while the forge call is in flight. The mock holds the PR list until `wt`+/// exits (`hold_until_parent_exit`), so the marker is on the real screen for+/// exactly the picker's lifetime and the presence assertion never races boot+/// latency. The picker captures and aborts at stabilize time, and the `--prs`+/// thread is detached on exit (not joined), so the test finishes in about a+/// second. The marker's *clearing* once rows arrive is covered by the+/// `header_loading_marker_shows_until_cleared` unit test and the negative+/// assertion in `test_switch_picker_prs_github_list`.#[rstest]fn test_switch_picker_prs_shows_loading_marker(mut repo: TestRepo) {repo.remove_fixture_worktrees();@@ -1839,9 +1856,35 @@ fn test_switch_picker_prs_shows_loading_marker(mut repo: TestRepo) {"https://github.com/owner/test-repo.git",]);let pr_json = r#"[{"number":42,"title":"Retry the flaky network test","headRefName":"fix/flaky","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42","body":""}]"#;- // 3s delay >> the ~1s capture, so the marker is still on screen when the- // helper snapshots and aborts.- let env_vars = mock_forge_env(&repo, "gh", "pr list", pr_json, 3000);+ // Hold the loading marker on screen for exactly the picker's lifetime — no+ // fixed delay to outguess boot latency. `hold_until_parent_exit` makes the+ // mocked `gh pr list` block until `wt` exits (it polls for its stdout pipe's+ // read end to close), so the transient "Loading open PRs" frame is present+ // for the entire window the helper could observe it, on any hardware. A+ // fixed `delay_ms` can't guarantee this: a 3s hold flaked on a loaded+ // Windows runner because `boot_picker_pty`'s skim-ready wait plus its initial+ // `wait_for_stable`, and the async worktree-column churn, ate the whole 3s+ // window, so by the time `send_input_awaiting_content` first polled for the+ // marker the mock had already returned and the rows had streamed in — the+ // marker was gone and the wait timed out at STABILIZE_TIMEOUT (30s). Bumping+ // the delay only widens the margin; tying release to parent death removes the+ // race outright.+ //+ // The picker still exits in well under a second: `exec_in_pty_capture_before_abort`+ // snapshots and sends Escape the instant the marker settles, and abort does+ // *not* join the background `--prs` fetch thread — the interactive teardown+ // ends it with `drop(prs_handle)` (see `run_picker` in+ // `src/commands/picker/mod.rs`: "don't join — the forge call may still be in+ // flight, and process exit terminates the thread"). When `wt` exits it closes+ // the mock's stdout pipe, the mock's next write fails with `BrokenPipe`, and+ // the mock exits — no orphaned sleeper left behind.+ let env_vars = mock_forge_env_with(+ &repo,+ "gh",+ "pr list",+ pr_json,+ MockResponse::file("list.json").hold_until_parent_exit(),+ );let result = exec_in_pty_capture_before_abort(wt_bin().to_str().unwrap(),