Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(switch): show a "couldn't load" pane when a --prs preview fetch fails (#3189)
Maximilian Roos001a20e53d8e
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rsindex 55840fb33..9c6a38bf7 100644--- a/src/commands/picker/preview_orchestrator.rs+++ b/src/commands/picker/preview_orchestrator.rs@@ -160,11 +160,12 @@ impl PreviewOrchestrator {////// Idempotent on `key` (short-circuits on a cache hit) and runs `compute`/// outside any DashMap lock, like `spawn_preview`. A `None` or empty result- /// is deliberately NOT cached: the slot stays empty rather than pinning a- /// blank pane, so a later `spawn_compute` with the same key recomputes. The- /// `--prs` callers spawn once per row and never re-invoke, so in practice an- /// uncached failure leaves the tab on its loading placeholder until the- /// picker reopens.+ /// is deliberately NOT cached: the slot stays empty (read as "still+ /// loading"), so a later `spawn_compute` with the same key recomputes. The+ /// `--prs` callers spawn once per row and never re-invoke, so they convert a+ /// failed fetch into a terminal "couldn't load" pane and hand that back as+ /// `Some(..)` rather than `None` — an uncached `None` would strand the tab on+ /// its loading placeholder until the picker reopens.pub(super) fn spawn_compute<F>(&self, key: PreviewCacheKey, compute: F)whereF: FnOnce(&Repository) -> Option<String> + Send + 'static,diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rsindex d1f6eb977..8331ec988 100644--- a/src/commands/picker/prs.rs+++ b/src/commands/picker/prs.rs@@ -49,7 +49,7 @@ use serde::Deserialize;use skim::prelude::*;use unicode_width::UnicodeWidthStr;use worktrunk::git::{CiPlatform, Repository};-use worktrunk::styling::{INFO_SYMBOL, StyledLine, warning_message};+use worktrunk::styling::{INFO_SYMBOL, StyledLine, WARNING_SYMBOL, warning_message};use super::super::list::ci_status::{CiSource, CiStatus, GitHubPrInfo, PrRef, PrStatus, ReviewState, non_interactive_cmd,@@ -281,9 +281,11 @@ fn fetch_and_stream(/// Spawn the deferred per-row preview fetches for one `--prs` row, keyed by the/// row's `pr:{N}` / `mr:{N}` token so [`PrSkimItem::preview`] reads them back./// Each is fire-and-forget on `COLLECT_POOL`, spawned once per row. `preview()`-/// only reads the cache, so a forge failure leaves the slot empty and the tab-/// keeps its loading placeholder until the picker reopens — there's no in-session-/// retry (see [`PreviewOrchestrator::spawn_compute`]).+/// only reads the cache, and the fetch runs once per row with no in-session+/// retry, so each closure resolves to a terminal pane: the rendered content, or+/// [`pr_unavailable_pane`] when the forge fetch fails. A failure therefore shows+/// a "couldn't load" pane (cleared on the next picker open), never a perpetual+/// loading placeholder (see [`PreviewOrchestrator::spawn_compute`]).////// Both tabs are spawned eagerly, once per row, for all rows — so a `--prs` open/// queues up to `2 × MAX_PRS` (~100) per-PR forge calls. This is deliberate and@@ -304,18 +306,24 @@ fn spawn_pr_previews(let head_oid = entry.head_oid.clone();let head_branch = entry.head_branch.clone();orchestrator.spawn_compute((token.clone(), PreviewMode::Log), move |repo| {- compute_pr_log(- repo,- kind,- number,- head_oid.as_deref(),- &head_branch,- width,- height,+ Some(+ compute_pr_log(+ repo,+ kind,+ number,+ head_oid.as_deref(),+ &head_branch,+ width,+ height,+ )+ .unwrap_or_else(|| pr_unavailable_pane("commit log")),)});orchestrator.spawn_compute((token, PreviewMode::Comments), move |repo| {- compute_pr_comments(repo, kind, number, width)+ Some(+ compute_pr_comments(repo, kind, number, width)+ .unwrap_or_else(|| pr_unavailable_pane("comments")),+ )});}@@ -660,9 +668,10 @@ fn pr_row_empty_placeholder() -> String {/// Placeholder for a `--prs` row's deferred tab while its background fetch is/// still in flight. skim can't re-query a preview on its own, so the hint points/// at the accelerator that re-reads the cache once the fetch lands — the same-/// contract as the worktree rows' `loading_placeholder`. A failed fetch (spawned-/// once per row) leaves the slot empty, so this placeholder persists until the-/// picker reopens; the refresh hint is a no-op then.+/// contract as the worktree rows' `loading_placeholder`. Shown only during the+/// in-flight window: once the fetch resolves, a terminal pane replaces it — the+/// rendered content or [`pr_unavailable_pane`] on failure — so it never persists+/// past the fetch.fn pr_deferred_loading(mode: PreviewMode) -> String {let reset = Reset;let (label, key) = match mode {@@ -676,12 +685,26 @@ fn pr_deferred_loading(mode: PreviewMode) -> String {)}+/// Terminal pane for a `--prs` deferred tab whose background fetch failed (forge+/// CLI missing/unauthenticated, network error, unparsable JSON). The deferred+/// closures cache this in place of an empty slot, so the tab shows a clear+/// "couldn't load" rather than [`pr_deferred_loading`]'s spinner forever: the+/// fetch is spawned once per row and never retried in-session (see+/// [`spawn_pr_previews`]), so a `None` left uncached would strand the tab on+/// "Loading…". The warning glyph distinguishes it from the benign info states+/// (`No commits` / `No comments`); reopening the picker starts a fresh cache and+/// re-fetches.+fn pr_unavailable_pane(label: &str) -> String {+ let reset = Reset;+ cformat!("{WARNING_SYMBOL}{reset} Couldn't load {label} — reopen the picker to retry\n")+}+/// Run a forge CLI and return its stdout, or `None` on any failure (root/// unresolvable, spawn error, non-zero exit). Shared by the deferred `log` //// `comments` fetches: a PR runs `gh <gh_args>`, an MR runs `glab <glab_args>`./// Runs off-thread on `COLLECT_POOL`, never on skim's UI thread; a `None` result-/// leaves the cache slot empty so the tab keeps its loading placeholder (see-/// [`PreviewOrchestrator::spawn_compute`]).+/// signals a failed fetch, which the deferred-preview closures turn into a+/// terminal [`pr_unavailable_pane`] (see [`spawn_pr_previews`]).fn fetch_forge_json(repo: &Repository,kind: RefKind,@@ -849,8 +872,8 @@ fn render_commit_lines(commits: &[(String, String)], width: usize) -> String {/// `glab api …/merge_requests/<n>/notes?sort=asc` (GitLab, human notes). `sort=asc`/// matches GitHub's oldest-first order (GitLab defaults to newest-first), and/// `--paginate` follows every page so a long thread isn't capped at GitLab's-/// default page size. Returns `None` on any failure, leaving the slot empty so-/// the tab keeps its loading placeholder.+/// default page size. Returns `None` on any failure; the caller maps that to a+/// terminal [`pr_unavailable_pane`] (see [`spawn_pr_previews`]).fn compute_pr_comments(repo: &Repository,kind: RefKind,@@ -1076,18 +1099,6 @@ fn render_freeform_row(entry: &PrEntry, list_width: usize) -> String {// summary would feed those commits (or the PR body) through the same// `[commit.generation]` LLM path the worktree `summary` tab uses, keyed and// cached the same way via `spawn_pr_previews`.-//-// TODO(pr-preview-fetch-error): on a forge-fetch failure the deferred `log` /-// `comments` slot stays empty (`spawn_compute` drops a `None`), and since the-// fetch is spawned once per row and `preview()` only reads the cache, the tab-// shows the "Loading…" placeholder for the rest of the session — there's no-// in-session retry, so the hint to press the key again is a no-op. Cache a-// terminal "couldn't load" pane on failure instead, so the tab distinguishes-// in-flight from failed; this needs the PR-row closures (or `spawn_compute`) to-// signal failure vs. a genuinely-empty result. The same terminal-pane path-// would also give the orphan-root local-head case (a present head sharing no-// merge-base with the default branch, which `compute_log_for_head` renders as-// "has no commits") a clear outcome rather than a misleading one.impl SkimItem for PrSkimItem {fn text(&self) -> Cow<'_, str> {Cow::Borrowed(&self.search_text)@@ -1774,8 +1785,9 @@ mod tests {#[test]fn render_commits_invalid_json_is_none() {- // A forge that returns junk yields `None`, so `spawn_compute` leaves the- // slot empty rather than caching garbage.+ // A forge that returns junk yields `None` from the renderer; the deferred+ // closure maps that to a couldn't-load pane (`pr_unavailable_pane`) rather+ // than caching garbage.assert!(render_github_commits(b"not json", 80).is_none());assert!(render_gitlab_commits(b"not json", 80).is_none());}@@ -1841,6 +1853,31 @@ mod tests {assert_eq!(pr.cached_pane(PreviewMode::Comments), "rendered thread");}+ #[test]+ fn unavailable_pane_reads_as_a_clear_failure() {+ // A failed deferred fetch caches this terminal pane instead of leaving+ // the slot empty, so the tab shows a clear "couldn't load" rather than+ // `pr_deferred_loading`'s spinner forever. It names the tab, drops the+ // "press alt-N again" refresh hint (there's no in-session retry — only+ // reopening the picker re-fetches), and carries the warning glyph that+ // sets it apart from the benign info states ("No commits"/"No comments").+ let pane = pr_unavailable_pane("commit log");+ let stripped = plain(&pane);+ assert!(+ stripped.contains("Couldn't load commit log"),+ "names the tab: {stripped:?}"+ );+ assert!(+ !stripped.contains("Loading"),+ "not a loading state: {stripped:?}"+ );+ assert!(+ stripped.contains("reopen the picker"),+ "points at the only retry: {stripped:?}"+ );+ assert!(stripped.contains('▲'), "warning glyph: {stripped:?}");+ }+#[test]fn render_github_comments_threads_author_time_and_body() {// Each comment renders an author + relative-time header and its body indiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 4a68a6fa0..2d0784471 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -2435,11 +2435,11 @@ fn test_switch_prs_dry_run_github_log_tab(repo: TestRepo) {/// the API when the commit is present.////// The same run pins the deferred-fetch failure contract: the `comments` tab has-/// no local path, so its forge fetch fails here, and `spawn_compute` leaves the-/// slot empty rather than caching a blank pane (the present Log entry proves the-/// row was built, so the absent Comments entry is a genuine miss, not a row that-/// never streamed). Nothing re-spawns it — the tab keeps its loading placeholder-/// for the session.+/// no local path, so its forge fetch fails here (`pr view` → exit 1), and the+/// closure caches a terminal "couldn't load" pane rather than leaving the slot+/// empty — so the present Log entry (local fast path) and the present, non-empty+/// Comments entry (failure pane) both prove the row streamed and resolved. The+/// tab shows a clear failure for the session, never a perpetual loading spinner.#[cfg(unix)]#[rstest]fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {@@ -2486,16 +2486,77 @@ fn test_switch_prs_dry_run_github_log_tab_local(repo: TestRepo) {);// The comments tab has no local path, so its forge fetch failed (pr view →- // exit 1) and `spawn_compute` cached nothing — the failure leaves the slot- // empty rather than pinning a blank pane. Mode 7 is Comments.+ // exit 1); the closure caches a terminal "couldn't load" pane rather than+ // leaving the slot empty. Mode 7 is Comments. A non-empty entry here can only+ // be that failure pane — a successful comments fetch is impossible with+ // `pr view` rigged to exit 1.+ let comments_entry = entries+ .iter()+ .find(|e| e["branch"] == "pr:42" && e["mode"] == 7)+ .unwrap_or_else(|| {+ panic!("failed comments fetch must cache a couldn't-load pane:\n{stdout}")+ });assert!(- !entries- .iter()- .any(|e| e["branch"] == "pr:42" && e["mode"] == 7),- "failed comments fetch must leave the slot empty, not cache a blank pane:\n{stdout}"+ comments_entry["bytes"].as_u64().unwrap_or(0) > 0,+ "couldn't-load pane rendered non-empty: {comments_entry}");}+/// A `--prs` row whose deferred fetches all fail caches a terminal "couldn't+/// load" pane for each tab rather than leaving the slot empty (which would+/// strand the tab on its loading spinner for the session — there's no in-session+/// retry). Here the PR carries no `headRefOid`, so the `log` tab can't take the+/// local fast path and must hit the forge API, and `gh pr view` is rigged to+/// exit 1 — so both the `log` (mode 2) and `comments` (mode 7) cache entries are+/// present and non-empty, each the couldn't-load pane.+#[cfg(unix)]+#[rstest]+fn test_switch_prs_dry_run_github_deferred_fetch_failure(repo: TestRepo) {+ repo.write_project_config("[forge]\nplatform = \"github\"\n");+ // No headRefOid → the log tab can't render locally and must hit the forge.+ let pr_json = r#"[{"number":42,"title":"No local head","headRefName":"fix/flaky","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42"}]"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ fs::write(mock_bin.join("list.json"), pr_json).unwrap();+ MockConfig::new("gh")+ .version("gh version 1.0.0 (mock)")+ .command("pr list", MockResponse::file("list.json"))+ // Both deferred fetches (`pr view --json commits` / `--json comments`)+ // fail, so each tab falls back to the couldn't-load pane.+ .command("pr view", MockResponse::exit(1))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let mut cmd = repo.wt_command();+ cmd.args(["switch", "--prs"]);+ cmd.env("WORKTRUNK_PICKER_DRY_RUN", "1");+ configure_mock_cli_env(&mut cmd, &mock_bin);+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "dry-run --prs deferred-failure run failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );++ let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8");+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("stdout is valid JSON");+ let entries = parsed["entries"].as_array().expect("entries array");+ // Both deferred tabs cached a terminal couldn't-load pane (non-empty), never+ // an empty slot. Modes: 2 = Log, 7 = Comments.+ for (mode, tab) in [(2, "log"), (7, "comments")] {+ let entry = entries+ .iter()+ .find(|e| e["branch"] == "pr:42" && e["mode"] == mode)+ .unwrap_or_else(|| panic!("no pr:42 {tab} cache entry in dump:\n{stdout}"));+ assert!(+ entry["bytes"].as_u64().unwrap_or(0) > 0,+ "{tab} couldn't-load pane rendered non-empty: {entry}"+ );+ }+}+/// The `comments` tab (7) loads the PR discussion in the background, the same/// way the `log` tab loads commits: `spawn_pr_previews` fires `gh pr view <n>/// --json comments` keyed by the row's `pr:{N}` token. A `{branch:"pr:42",