Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

feat(switch): browse open PRs/MRs in the interactive picker (#3128)

Maximilian Roos81f9260a4644
diff --git a/CLAUDE.md b/CLAUDE.md
index 479b776d4..50090aba0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -102,9 +102,11 @@ Before adding an accessor that could reach the wire (`gh`, `glab`, `git fetch`,
What currently reaches the wire:
- `wt list --full`, `wt list statusline` — CI status
+- `wt switch` (interactive picker, no target) — per-row CI status, primed from the local cache then fetched live and streamed into the rows
- generating a branch summary with a `commit.generation` command
- generating a commit message with a `commit.generation` command
- `wt switch pr:<n>`, `wt switch mr:<n>` — host API to resolve the PR/MR, then `git fetch` of its branch
+- `wt switch --prs` — one `gh pr list` / `glab mr list` to populate the interactive picker (streamed in after the frame paints)
- `wt config show --full` — version check against GitHub
- the first `Repository::default_branch()` per repo — `git ls-remote` (above)
diff --git a/docs/content/switch.md b/docs/content/switch.md
index f8622a74c..19d44ca85 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -56,9 +56,9 @@ Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched a
## Interactive picker
-When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview.
+When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview. The candidate set widens with `--branches` (local branches without worktrees), `--remotes` (remote branches), and `--prs` (open PRs/MRs — see below).
-The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.
+The CI column shows each row's PR/MR CI and review status, the same as [`wt list --full`](@/list.md).
<figure class="demo">
<picture>
@@ -76,7 +76,7 @@ The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the
| `Enter` | Switch to selected worktree |
| `Alt-c` | Create new worktree named as entered text |
| `Esc` | Cancel |
-| `Alt-1`–`Alt-5` | Jump to a preview tab |
+| `Alt-1`–`Alt-6` | Jump to a preview tab |
| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |
| `Alt-p` | Toggle preview panel |
| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |
@@ -86,13 +86,14 @@ Plain digits go to the filter, so a branch name containing a number can be typed
Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `@` to the current worktree. The other sigils don't filter cleanly — `^` and `|` are skim's prefix-anchor and OR query operators (so `^` matches every row and `|` none), and `/` matches most rows because every worktree path contains it.
-**Preview tabs** — jump with `Alt-1`–`Alt-5`, or cycle with `Tab`/`Shift-Tab`:
+**Preview tabs:**
1. **HEAD±** — Diff of uncommitted changes
2. **log** — Recent commits; commits already on the default branch have dimmed hashes
3. **main…±** — Diff of changes since the merge-base with the default branch
4. **remote⇅** — Ahead/behind diff vs upstream tracking branch
5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)
+6. **pr** — The selected row's PR/MR, for any row whose branch has one
**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:
@@ -107,12 +108,14 @@ Available on Unix only (macOS, Linux). On Windows, use `wt list` or `wt switch <
The `pr:<number>` / `mr:<number>` shortcut and the PR/MR's web URL both resolve to its branch. For same-repo PRs/MRs, worktrunk switches to the branch directly. For fork PRs/MRs, it fetches the ref (`refs/pull/N/head` or `refs/merge-requests/N/head`) and configures `pushRemote` to the fork URL.
-{{ terminal(cmd="wt switch pr:101 # GitHub PR #101|||wt switch https://github.com/owner/repo/pull/101 # ...the same PR, by URL|||wt switch mr:101 # GitLab MR !101|||wt switch https://gitlab.com/owner/repo/-/merge_requests/101 # ...the same MR, by URL") }}
+{{ terminal(cmd="wt switch pr:101 # GitHub PR #101|||wt switch https://github.com/owner/repo/pull/101 # ...the same PR, by URL|||wt switch mr:101 # GitLab MR !101|||wt switch https://gitlab.com/owner/repo/-/merge_requests/101 # ...the same MR, by URL|||wt switch --prs # Browse open PRs/MRs in the picker") }}
Both work anywhere a branch is accepted, including `--base`. The `--create` flag cannot be used with a PR/MR reference since the branch already exists.
If the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.
+The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch.
+
Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](@/config.md#forge-platform) for Gitea, Azure DevOps, and other supported platforms.
## When wt switch fails
@@ -199,6 +202,9 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=c>--remotes</span></b>
Include remote branches
+ <b><span class=c>--prs</span></b>
+ Include open PRs/MRs
+
<b><span class=g>Automation:</span></b>
<b><span class=c>--no-hooks</span></b>
Skip hooks
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index 862598deb..7a71cab4a 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -59,9 +59,9 @@ Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched a
## Interactive picker
-When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview.
+When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview. The candidate set widens with `--branches` (local branches without worktrees), `--remotes` (remote branches), and `--prs` (open PRs/MRs — see below).
-The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.
+The CI column shows each row's PR/MR CI and review status, the same as [`wt list --full`](https://worktrunk.dev/list/).
**Keybindings:**
@@ -72,7 +72,7 @@ The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the
| `Enter` | Switch to selected worktree |
| `Alt-c` | Create new worktree named as entered text |
| `Esc` | Cancel |
-| `Alt-1`–`Alt-5` | Jump to a preview tab |
+| `Alt-1`–`Alt-6` | Jump to a preview tab |
| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |
| `Alt-p` | Toggle preview panel |
| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |
@@ -82,13 +82,14 @@ Plain digits go to the filter, so a branch name containing a number can be typed
Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `@` to the current worktree. The other sigils don't filter cleanly — `^` and `|` are skim's prefix-anchor and OR query operators (so `^` matches every row and `|` none), and `/` matches most rows because every worktree path contains it.
-**Preview tabs** — jump with `Alt-1`–`Alt-5`, or cycle with `Tab`/`Shift-Tab`:
+**Preview tabs:**
1. **HEAD±** — Diff of uncommitted changes
2. **log** — Recent commits; commits already on the default branch have dimmed hashes
3. **main…±** — Diff of changes since the merge-base with the default branch
4. **remote⇅** — Ahead/behind diff vs upstream tracking branch
5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)
+6. **pr** — The selected row's PR/MR, for any row whose branch has one
**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:
@@ -108,12 +109,15 @@ $ wt switch pr:101 # GitHub PR #101
$ wt switch https://github.com/owner/repo/pull/101 # ...the same PR, by URL
$ wt switch mr:101 # GitLab MR !101
$ wt switch https://gitlab.com/owner/repo/-/merge_requests/101 # ...the same MR, by URL
+$ wt switch --prs # Browse open PRs/MRs in the picker
```
Both work anywhere a branch is accepted, including `--base`. The `--create` flag cannot be used with a PR/MR reference since the branch already exists.
If the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.
+The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch.
+
Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](https://worktrunk.dev/config/#forge-platform) for Gitea, Azure DevOps, and other supported platforms.
## When wt switch fails
@@ -194,6 +198,9 @@ Picker Options:
--remotes
Include remote branches
+ --prs
+ Include open PRs/MRs
+
Automation:
--no-hooks
Skip hooks
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 03cfb0acf..5b8dc8a3a 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -342,6 +342,10 @@ pub(crate) struct SwitchArgs {
#[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "execute", "execute_args", "clobber"])]
pub(crate) remotes: bool,
+ /// Include open PRs/MRs
+ #[arg(long, help_heading = "Picker Options", conflicts_with_all = ["create", "base", "execute", "execute_args", "clobber"])]
+ pub(crate) prs: bool,
+
/// Create a new branch
#[arg(short = 'c', long, requires = "branch")]
pub(crate) create: bool,
@@ -633,9 +637,9 @@ Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched a
## Interactive picker
-When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview.
+When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview. The candidate set widens with `--branches` (local branches without worktrees), `--remotes` (remote branches), and `--prs` (open PRs/MRs — see below).
-The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.
+The CI column shows each row's PR/MR CI and review status, the same as [`wt list --full`](@/list.md).
<!-- demo: wt-switch-picker.gif 1600x800 -->
**Keybindings:**
@@ -647,7 +651,7 @@ The CI column shows cached PR/MR status when earlier runs (`wt list --full`, the
| `Enter` | Switch to selected worktree |
| `Alt-c` | Create new worktree named as entered text |
| `Esc` | Cancel |
-| `Alt-1`–`Alt-5` | Jump to a preview tab |
+| `Alt-1`–`Alt-6` | Jump to a preview tab |
| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |
| `Alt-p` | Toggle preview panel |
| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |
@@ -657,13 +661,14 @@ Plain digits go to the filter, so a branch name containing a number can be typed
Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `@` to the current worktree. The other sigils don't filter cleanly — `^` and `|` are skim's prefix-anchor and OR query operators (so `^` matches every row and `|` none), and `/` matches most rows because every worktree path contains it.
-**Preview tabs** — jump with `Alt-1`–`Alt-5`, or cycle with `Tab`/`Shift-Tab`:
+**Preview tabs:**
1. **HEAD±** — Diff of uncommitted changes
2. **log** — Recent commits; commits already on the default branch have dimmed hashes
3. **main…±** — Diff of changes since the merge-base with the default branch
4. **remote⇅** — Ahead/behind diff vs upstream tracking branch
5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](@/config.md#commit)
+6. **pr** — The selected row's PR/MR, for any row whose branch has one
**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:
@@ -683,12 +688,15 @@ $ wt switch pr:101 # GitHub PR #101
$ wt switch https://github.com/owner/repo/pull/101 # ...the same PR, by URL
$ wt switch mr:101 # GitLab MR !101
$ wt switch https://gitlab.com/owner/repo/-/merge_requests/101 # ...the same MR, by URL
+$ wt switch --prs # Browse open PRs/MRs in the picker
```
Both work anywhere a branch is accepted, including `--base`. The `--create` flag cannot be used with a PR/MR reference since the branch already exists.
If the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.
+The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch.
+
Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](@/config.md#forge-platform) for Gitea, Azure DevOps, and other supported platforms.
## When wt switch fails
diff --git a/src/commands/list/CLAUDE.md b/src/commands/list/CLAUDE.md
index 935d4311d..9d194f808 100644
--- a/src/commands/list/CLAUDE.md
+++ b/src/commands/list/CLAUDE.md
@@ -40,9 +40,9 @@ Default: defer to post-skeleton. Only add a pre-skeleton operation when the
skeleton literally cannot render without the data. Current exceptions, all
small local reads: column sizing (the CI column's cached width hint), custom
`[list.custom-columns]` expansion (values come from the in-memory config snapshot and
-must be measured for layout), and the picker's cache-only CI fill (the CiStatus
-task is skipped there, so the cache read is the column's entire data source).
-Template expansion and other file I/O wait; new columns can render a
+must be measured for layout), and the picker's CI cache prime (paints the column
+instantly; the live CiStatus task the picker runs refreshes each cell behind the
+first frame). Template expansion and other file I/O wait; new columns can render a
placeholder until data arrives.
## Benchmarking Skeleton Time
diff --git a/src/commands/list/ci_status/azure.rs b/src/commands/list/ci_status/azure.rs
index b02080bba..735d892ed 100644
--- a/src/commands/list/ci_status/azure.rs
+++ b/src/commands/list/ci_status/azure.rs
@@ -134,6 +134,7 @@ pub(super) fn detect_azure_pr(
ci_status,
source: CiSource::PullRequest,
is_stale,
+ is_priming: false,
url,
number: Some(PrRef::pr(u64::from(pr.pull_request_id))),
review_state: None,
@@ -214,6 +215,7 @@ pub(super) fn detect_azure_pipeline(
ci_status,
source: CiSource::Branch,
is_stale,
+ is_priming: false,
url: web_url,
number: None,
review_state: None,
diff --git a/src/commands/list/ci_status/gitea.rs b/src/commands/list/ci_status/gitea.rs
index ebc33f0fa..22408c714 100644
--- a/src/commands/list/ci_status/gitea.rs
+++ b/src/commands/list/ci_status/gitea.rs
@@ -118,6 +118,7 @@ pub(super) fn detect_gitea_pr(
ci_status,
source: CiSource::PullRequest,
is_stale,
+ is_priming: false,
url: Some(pr.html_url.clone()),
number: pr.number.map(PrRef::pr),
review_state: None,
@@ -139,6 +140,7 @@ pub(super) fn detect_gitea_commit_status(
ci_status,
source: CiSource::Branch,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state: None,
diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rs
index d96a9a934..0d36e7619 100644
--- a/src/commands/list/ci_status/github.rs
+++ b/src/commands/list/ci_status/github.rs
@@ -127,6 +127,7 @@ pub(super) fn detect_github(
ci_status,
source: CiSource::PullRequest,
is_stale,
+ is_priming: false,
url: pr_info.url.clone(),
number: pr_info.number.map(PrRef::pr),
review_state: pr_info.review_state(),
@@ -194,6 +195,7 @@ pub(super) fn detect_github_commit_checks(
ci_status,
source: CiSource::Branch,
is_stale: false, // We're querying by SHA, so always current
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -207,7 +209,7 @@ pub(super) fn detect_github_commit_checks(
///
/// Note: We don't include `state` because we already filter with `--state open`.
#[derive(Debug, Deserialize)]
-pub(super) struct GitHubPrInfo {
+pub(crate) struct GitHubPrInfo {
pub number: Option<u64>,
#[serde(rename = "headRefOid")]
pub head_ref_oid: Option<String>,
@@ -230,7 +232,7 @@ pub(super) struct GitHubPrInfo {
/// Owner info for the head repository of a PR.
#[derive(Debug, Deserialize)]
-pub(super) struct HeadRepositoryOwner {
+pub(crate) struct HeadRepositoryOwner {
/// The login (username/org name) of the repository owner.
pub login: String,
}
@@ -249,7 +251,7 @@ pub(super) struct HeadRepositoryOwner {
/// `gh run list` for branch-based CI (branches without PRs), keeping the single-call approach
/// here is simpler overall.
#[derive(Debug, Deserialize)]
-pub(super) struct GitHubCheck {
+pub(crate) struct GitHubCheck {
/// CheckRun only: "COMPLETED", "IN_PROGRESS", "QUEUED", etc.
pub status: Option<String>,
/// CheckRun only: "SUCCESS", "FAILURE", "CANCELLED", "SKIPPED", etc.
@@ -283,6 +285,30 @@ impl GitHubPrInfo {
Some(checks) => aggregate_github_checks(checks),
}
}
+
+ /// Build a [`PrStatus`] from this open-PR entry, for callers that already
+ /// hold the open-PR list (the `--prs` picker) and want the same CI-column
+ /// treatment [`detect_github`] produces per branch. PR rows have no local
+ /// checkout to diff against, so the result is never marked stale.
+ ///
+ /// Only the `--prs` picker calls this, and the picker is unix-only.
+ #[cfg(unix)]
+ pub(crate) fn open_pr_status(&self) -> PrStatus {
+ let ci_status = if self.merge_state_status.as_deref() == Some("DIRTY") {
+ CiStatus::Conflicts
+ } else {
+ self.ci_status()
+ };
+ PrStatus {
+ ci_status,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ is_priming: false,
+ url: self.url.clone(),
+ number: self.number.map(PrRef::pr),
+ review_state: self.review_state(),
+ }
+ }
}
/// Aggregate CI status from multiple GitHub checks (case-insensitive).
@@ -350,6 +376,24 @@ pub(super) fn aggregate_github_checks(checks: &[GitHubCheck]) -> CiStatus {
mod tests {
use super::*;
+ /// A `DIRTY` merge state (merge conflicts) reports `Conflicts` regardless of
+ /// the check rollup — the `--prs` picker's CI column treatment.
+ #[cfg(unix)]
+ #[test]
+ fn open_pr_status_dirty_merge_state_reports_conflicts() {
+ let pr = GitHubPrInfo {
+ number: Some(7),
+ head_ref_oid: None,
+ merge_state_status: Some("DIRTY".to_string()),
+ status_check_rollup: None,
+ url: None,
+ head_repository_owner: None,
+ review_decision: None,
+ is_draft: None,
+ };
+ assert_eq!(pr.open_pr_status().ci_status, CiStatus::Conflicts);
+ }
+
#[test]
fn test_github_pr_info_ci_status() {
// No checks = NoCI
diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rs
index 845595532..6f6668e3a 100644
--- a/src/commands/list/ci_status/gitlab.rs
+++ b/src/commands/list/ci_status/gitlab.rs
@@ -183,6 +183,7 @@ pub(super) fn detect_gitlab(
ci_status: CiStatus::Error,
source: CiSource::PullRequest,
is_stale: mr_entry.sha != local_head,
+ is_priming: false,
url: mr_entry.web_url.clone(),
number: Some(PrRef::mr(mr_entry.iid)),
review_state: mr_entry.review_state(),
@@ -195,6 +196,7 @@ pub(super) fn detect_gitlab(
ci_status,
source: CiSource::PullRequest,
is_stale,
+ is_priming: false,
url: mr_entry.web_url.clone(),
number: Some(PrRef::mr(mr_entry.iid)),
review_state: mr_entry.review_state(),
@@ -263,6 +265,7 @@ pub(super) fn detect_gitlab_pipeline(
ci_status,
source: CiSource::Branch,
is_stale,
+ is_priming: false,
url: pipeline.web_url.clone(),
number: None,
review_state: None,
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index 4f4a3dd47..9f4a3bdf4 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -83,6 +83,9 @@ impl CiBranchName {
// Re-export public types
pub(crate) use cache::{CachedCiStatus, MaxPrNumber};
+// Only the `--prs` picker consumes this re-export, and the picker is unix-only.
+#[cfg(unix)]
+pub(crate) use github::GitHubPrInfo;
/// Maximum number of PRs/MRs to fetch when filtering by source repository.
///
@@ -104,7 +107,7 @@ const MAX_PRS_TO_FETCH: u8 = 20;
/// - Prompting for user input
/// - Using TTY-specific output formatting
/// - Opening browsers for authentication
-fn non_interactive_cmd(program: &str) -> Cmd {
+pub(crate) fn non_interactive_cmd(program: &str) -> Cmd {
Cmd::new(program)
.env_remove("CLICOLOR_FORCE")
.env_remove("GH_FORCE_TTY")
@@ -117,7 +120,7 @@ fn non_interactive_cmd(program: &str) -> Cmd {
///
/// On Windows, CreateProcessW (via Cmd) searches PATH for .exe files.
/// We provide .exe mocks in tests via mock-stub, so this works consistently.
-fn tool_available(tool: &str, args: &[&str]) -> bool {
+pub(crate) fn tool_available(tool: &str, args: &[&str]) -> bool {
Cmd::new(tool)
.args(args.iter().copied())
.run()
@@ -367,6 +370,13 @@ pub struct PrStatus {
pub source: CiSource,
/// True if local HEAD differs from remote HEAD (unpushed changes)
pub is_stale: bool,
+ /// True for the picker's cache-prime placeholder: the number is shown
+ /// from cache while the live `CiStatus` task refreshes, but the cached
+ /// CI color isn't yet trusted, so the cell renders neutral-dim instead of
+ /// green/red until the fetch overwrites it. Set only by
+ /// [`populate_from_cache`]; a transient render hint, never cached.
+ #[serde(skip)]
+ pub is_priming: bool,
/// URL to the PR/MR (if available)
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
@@ -421,6 +431,12 @@ impl PrStatus {
/// Get the style for this PR status (color + dimming for stale/draft)
pub fn style(&self) -> Style {
+ // Cache-prime placeholder: the number is real but the cached color is
+ // a guess the live fetch is about to overwrite, so render neutral-dim
+ // (no green/red) rather than assert a CI verdict we don't yet trust.
+ if self.is_priming {
+ return Style::new().dimmed();
+ }
let style = Style::new().fg_color(Some(Color::Ansi(self.color())));
if self.is_stale || self.review_state == Some(ReviewState::Draft) {
style.dimmed()
@@ -488,6 +504,7 @@ impl PrStatus {
ci_status: CiStatus::Error,
source: CiSource::Branch,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -594,41 +611,34 @@ impl PrStatus {
}
}
-/// Fill `pr_status` on items from the CI cache without touching the network.
+/// Prime `pr_status` on items from the CI cache without touching the network.
+///
+/// The interactive picker fetches CI live, but a cached result is local data,
+/// so priming it lets the CI column and `pr` tab show cached status on the
+/// first frame while the live `CiStatus` task refreshes each row behind it. A valid
+/// entry (HEAD unchanged, within TTL) is used as-is. An expired entry that
+/// names a PR/MR is kept with `is_priming` set: a PR/MR number is stable per
+/// branch *identity*, so it still identifies the PR, but the cached CI color
+/// may be outdated, so `is_priming` renders the number neutral-dim (no
+/// green/red) until the live fetch overwrites it. An expired entry without a
+/// number is dropped — a stale dot conveys nothing but the outdated color.
///
-/// The interactive picker skips the `CiStatus` task — fetching would put
-/// network latency inside a synchronous TUI — but cached results are local
-/// data. A valid entry (HEAD unchanged, within TTL) is used as-is. An
-/// expired entry that names a PR/MR is kept with `is_stale` set: a PR/MR
-/// number is stable per branch *identity*, so it still identifies the PR
-/// even when the pipeline color may be outdated, and `is_stale` renders it
-/// dimmed like the existing unpushed-changes treatment. (Deleting a branch
-/// and reusing its name can leave the old PR's number showing dimmed until
-/// the next fetching surface — `wt list --full`, the statusline — rewrites
-/// the entry; the picker accepts that brief skew rather than fetching.) An
-/// expired entry without a number is dropped — a stale dot conveys nothing
-/// but the outdated color.
+/// Rows with no usable cache entry are left `None` (pending): the live task
+/// fills them, so they must not be resolved to "no PR" here.
///
/// `item.branch` is the cache key for every row shape: local worktrees and
/// branches cache under the bare name, remote rows under `origin/...` —
/// the same `full_name` the `CiStatus` task writes.
-///
-/// Returns whether any row gained a status; the caller allocates the CI
-/// column only in that case. The cache read is the column's complete data
-/// source — no task will fill cells in later — so when the column will
-/// render, every remaining row resolves to "checked, nothing to show"
-/// (blank) rather than staying in the pending-placeholder state.
-pub(crate) fn populate_from_cache(repo: &Repository, items: &mut [super::model::ListItem]) -> bool {
+pub(crate) fn populate_from_cache(repo: &Repository, items: &mut [super::model::ListItem]) {
// Common never-fetched case (no `wt list --full`/statusline run yet):
// skip the per-row file probes entirely.
if !CachedCiStatus::cache_dir_exists(repo) {
- return false;
+ return;
}
let Ok(repo_path) = repo.current_worktree().root() else {
- return false;
+ return;
};
let now_secs = epoch_now();
- let mut any = false;
for item in items.iter_mut() {
let Some(branch) = item.branch.as_deref() else {
continue;
@@ -637,24 +647,19 @@ pub(crate) fn populate_from_cache(repo: &Repository, items: &mut [super::model::
continue;
};
if cached.is_valid(&item.head, now_secs, &repo_path) {
- any |= cached.status.is_some();
item.pr_status = Some(cached.status);
} else if let Some(stale) = cached.status.filter(|s| s.number.is_some()) {
+ // Show the number now, but render it neutral-dim: the cached color
+ // is stale and the live task will overwrite this cell shortly.
+ // `is_stale` (a SHA mismatch) carries through from the cache as-is —
+ // the live fetch recomputes it; `is_priming` alone drives the
+ // placeholder rendering, so this never fabricates a SHA mismatch.
item.pr_status = Some(Some(PrStatus {
- is_stale: true,
+ is_priming: true,
..stale
}));
- any = true;
- }
- }
- if any {
- for item in items.iter_mut() {
- if item.pr_status.is_none() {
- item.pr_status = Some(None);
- }
}
}
- any
}
#[cfg(test)]
@@ -705,6 +710,7 @@ mod tests {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -715,6 +721,7 @@ mod tests {
ci_status: CiStatus::Running,
source: CiSource::Branch,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -725,6 +732,7 @@ mod tests {
ci_status: CiStatus::Error,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -740,6 +748,7 @@ mod tests {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: Some("https://github.com/owner/repo/pull/123".to_string()),
number: Some(PrRef::pr(123)),
review_state: None,
@@ -828,18 +837,40 @@ mod tests {
#[test]
fn test_pr_status_style() {
- // Stale status gets dimmed
- let stale = PrStatus {
- ci_status: CiStatus::Running,
- source: CiSource::Branch,
- is_stale: true,
+ let passed = |is_stale: bool, is_priming: bool| PrStatus {
+ ci_status: CiStatus::Passed,
+ source: CiSource::PullRequest,
+ is_stale,
+ is_priming,
url: None,
- number: None,
+ number: Some(PrRef::pr(12)),
review_state: None,
};
- let style = stale.style();
- // Just verify it doesn't panic and returns a style
- let _ = format!("{style}test{style:#}");
+ let green = "\u{1b}[32m";
+ let dim = "\u{1b}[2m";
+
+ // Fresh verdict: green, not dimmed.
+ let fresh = passed(false, false).format_cell(3, false);
+ assert!(
+ fresh.contains(green) && !fresh.contains(dim),
+ "fresh: green, no dim: {fresh:?}"
+ );
+
+ // SHA-mismatch stale keeps its verdict color, dimmed — `wt list` flags a
+ // failing/passing pushed commit even when local HEAD has moved on.
+ let stale = passed(true, false).format_cell(3, false);
+ assert!(
+ stale.contains(green) && stale.contains(dim),
+ "stale: green + dim: {stale:?}"
+ );
+
+ // Cache-prime placeholder: dimmed and neutral — the number shows, but no
+ // green/red is asserted until the live fetch lands.
+ let priming = passed(false, true).format_cell(3, false);
+ assert!(
+ priming.contains(dim) && !priming.contains(green),
+ "priming: dim, neutral: {priming:?}"
+ );
}
#[test]
@@ -848,6 +879,7 @@ mod tests {
ci_status,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state,
@@ -958,6 +990,7 @@ mod tests {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: None,
number: number.map(PrRef::pr),
review_state: None,
@@ -1013,7 +1046,7 @@ mod tests {
ListItem::new_branch("ddd".to_string(), "fresh-none".to_string()),
ListItem::new_branch("eee".to_string(), "uncached".to_string()),
];
- assert!(populate_from_cache(repo, &mut items));
+ populate_from_cache(repo, &mut items);
let fresh = items[0].pr_status.as_ref().unwrap().as_ref().unwrap();
assert_eq!(fresh.number.unwrap().number, 123);
@@ -1021,24 +1054,28 @@ mod tests {
let expired = items[1].pr_status.as_ref().unwrap().as_ref().unwrap();
assert_eq!(expired.number.unwrap().number, 77);
- assert!(expired.is_stale, "expired entries render dimmed");
+ assert!(expired.is_priming, "expired entries render neutral-dim");
+ // Same HEAD, only TTL expired — not a SHA mismatch, so `is_stale` stays
+ // as cached (false). The neutral-dim comes from `is_priming`, not a
+ // fabricated `is_stale`.
+ assert!(!expired.is_stale);
assert!(
- matches!(items[2].pr_status, Some(None)),
- "expired dot conveys only its outdated color — resolved to blank"
+ items[2].pr_status.is_none(),
+ "expired dot with no number conveys nothing — left pending for the live fetch"
);
assert!(
matches!(items[3].pr_status, Some(None)),
- "fresh no-CI entry marks the cell as resolved-empty"
+ "a valid no-CI entry resolves the cell to empty"
);
assert!(
- matches!(items[4].pr_status, Some(None)),
- "no task will fill the cell later — blank, not pending"
+ items[4].pr_status.is_none(),
+ "uncached row stays pending — the live fetch will fill it"
);
}
#[test]
- fn test_populate_from_cache_head_moved_keeps_number_as_stale() {
+ fn test_populate_from_cache_head_moved_primes_number() {
let test = TestRepo::new();
let repo = &test.repo;
@@ -1055,27 +1092,30 @@ mod tests {
"new-head".to_string(),
"feature".to_string(),
)];
- assert!(populate_from_cache(repo, &mut items));
+ populate_from_cache(repo, &mut items);
let status = items[0].pr_status.as_ref().unwrap().as_ref().unwrap();
assert_eq!(status.number.unwrap().number, 9);
- assert!(status.is_stale);
+ // Primed as a placeholder: the number shows now, but neutral-dim — the
+ // cached color isn't asserted until the live fetch refreshes it (which
+ // is also where `is_stale` is recomputed against the moved HEAD).
+ assert!(status.is_priming);
}
#[test]
- fn test_populate_from_cache_without_usable_entries_returns_false() {
- // No cache at all
+ fn test_populate_from_cache_leaves_uncached_rows_pending() {
+ // No cache at all: the row stays pending for the live fetch.
let test = TestRepo::new();
let mut items = vec![ListItem::new_branch(
"aaa".to_string(),
"feature".to_string(),
)];
- assert!(!populate_from_cache(&test.repo, &mut items));
+ populate_from_cache(&test.repo, &mut items);
assert!(items[0].pr_status.is_none());
- // Only a fresh "no CI" entry: the cell resolves to empty, but no row
- // gained a status, so the CI column shouldn't be allocated.
+ // A fresh "no CI" entry is a real cache hit, so it resolves the cell
+ // to empty rather than leaving it pending for the live fetch.
seed_cache(&test.repo, "feature", None, epoch_now(), "aaa");
- assert!(!populate_from_cache(&test.repo, &mut items));
+ populate_from_cache(&test.repo, &mut items);
assert!(matches!(items[0].pr_status, Some(None)));
}
}
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index db212d22d..2d7311d24 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -466,18 +466,24 @@ pub trait PickerProgressHandler: Send + Sync {
/// before any task results arrive. `rendered` is one entry per item,
/// with fast fields (branch, path, head) populated and blank
/// placeholders for slow cells. `header` is the column-header line;
- /// the handler calls `render()` / `plain_text()` as needed.
+ /// the handler calls `render()` / `plain_text()` as needed. `grid` is
+ /// the layout's column geometry, for rows rendered outside collect
+ /// (the picker's `--prs` rows align their cells to it).
fn on_skeleton(
&self,
items: Vec<super::model::ListItem>,
rendered: Vec<String>,
header: worktrunk::styling::StyledLine,
+ grid: super::layout::ColumnGrid,
);
/// Fired after a single task result updates row `idx`. `rendered` is the
/// new line — write it through the item's shared state and wake the picker
- /// to repaint (skim 4.x renders on demand, not on a timer).
- fn on_update(&self, idx: usize, rendered: String);
+ /// to repaint (skim 4.x renders on demand, not on a timer). `item` is the
+ /// row's current model carrying the just-updated fields; the picker reads
+ /// `pr_status` from it to feed the live `pr` preview tab, which cannot see
+ /// the frozen skeleton snapshot.
+ fn on_update(&self, idx: usize, rendered: String, item: &super::model::ListItem);
/// Fired at the 200ms reveal deadline. One pre-rendered line per row,
/// with the placeholder promoted from blank to `·`: rows that have
@@ -794,9 +800,10 @@ pub fn collect(
collect_deadline,
list_width,
progressive_handler,
- // Picker is the only `Resolved` caller and runs the same fast
- // bucket as default `wt list` (skips BranchDiff/CiStatus), so
- // it also opts out of the untracked-inclusive working diff.
+ // Picker is the only `Resolved` caller. Like default `wt list` it
+ // opts out of the untracked-inclusive working diff; unlike it, the
+ // picker keeps the CiStatus task (see `handle_picker`'s skip set),
+ // so this is not the same bucket.
false,
),
ShowConfig::DeferredToParallel {
@@ -1137,27 +1144,22 @@ pub fn collect(
Err(e) => return Err(e),
};
- // The picker skips the networked CiStatus task, but cached statuses are
- // local data: fill rows from `.git/wt/cache/ci-status/` so PR/MR numbers
- // appear in the picker without touching the wire. The CI column is
- // allocated only when some row actually had a usable cache entry —
- // `layout_skip_tasks` diverges from `effective_skip_tasks` exactly then
- // (the skip set still governs task spawning; this copy only tells layout
- // which columns will have data).
- let mut layout_skip_tasks = effective_skip_tasks.clone();
- if progressive_handler.is_some()
- && effective_skip_tasks.contains(&TaskKind::CiStatus)
- && super::ci_status::populate_from_cache(repo, &mut all_items)
- {
- layout_skip_tasks.remove(&TaskKind::CiStatus);
+ // The picker primes its CI cells from the local cache so the column paints
+ // instantly, then the live `CiStatus` task (which the picker keeps — see
+ // `handle_picker`) overwrites each cell as results stream in. Uncached rows
+ // stay pending until the fetch reports, exactly like the other progressive
+ // columns. `wt list` drives its progressive render through `progressive_state`,
+ // not a handler, so the prime is picker-only.
+ if progressive_handler.is_some() {
+ super::ci_status::populate_from_cache(repo, &mut all_items);
}
// CI column width hint: the largest PR/MR number any previous fetch saw
// (one small file read — cheap enough for the pre-skeleton budget, and
- // the skeleton can't size the column without it). Also covers the
- // cache-populated picker rows: `detect` re-ratchets on every cache hit,
- // so the stored maximum is at least as wide as any cached number.
- let max_pr_number = (!layout_skip_tasks.contains(&TaskKind::CiStatus))
+ // the skeleton can't size the column without it). Whatever fetch wrote a
+ // cache entry also ratcheted this maximum, so the hint already covers any
+ // number the prime above reads back.
+ let max_pr_number = (!effective_skip_tasks.contains(&TaskKind::CiStatus))
.then(|| super::ci_status::MaxPrNumber::read(repo))
.flatten();
@@ -1166,7 +1168,7 @@ pub fn collect(
// terminal — the rest belongs to the preview pane.
let layout = super::layout::calculate_layout_with_width(
&all_items,
- &layout_skip_tasks,
+ &effective_skip_tasks,
list_width
.or_else(crate::display::terminal_width)
.unwrap_or(usize::MAX),
@@ -1269,7 +1271,12 @@ pub fn collect(
.iter()
.map(|item| layout.render_skeleton_row(item, placeholder).render())
.collect();
- handler.on_skeleton(all_items.clone(), skeletons, layout.render_header_line());
+ handler.on_skeleton(
+ all_items.clone(),
+ skeletons,
+ layout.render_header_line(),
+ layout.column_grid(),
+ );
// Mirror the `wt list` progressive-table marker so `wt-perf phases`
// sees the same boundary across both commands.
worktrunk::trace::instant("Skeleton rendered");
@@ -1674,7 +1681,7 @@ pub fn collect(
}
if let Some(handler) = progressive_handler.as_ref() {
- handler.on_update(item_idx, rendered);
+ handler.on_update(item_idx, rendered, item);
}
}
results::DrainEvent::Reveal { items } => {
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rs
index 785dbd18d..dd7fa84f8 100644
--- a/src/commands/list/json_output.rs
+++ b/src/commands/list/json_output.rs
@@ -633,6 +633,7 @@ mod tests {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: Some("https://github.com/org/repo/pull/123".to_string()),
number: Some(PrRef::pr(123)),
review_state: None,
@@ -670,6 +671,7 @@ mod tests {
ci_status: CiStatus::Failed,
source: CiSource::Branch,
is_stale: true,
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -697,6 +699,7 @@ mod tests {
ci_status,
source: CiSource::Branch,
is_stale: false,
+ is_priming: false,
url: None,
number: None,
review_state: None,
@@ -716,6 +719,7 @@ mod tests {
ci_status: CiStatus::Passed,
source: CiSource::PullRequest,
is_stale: false,
+ is_priming: false,
url: Some("https://git.example.com/org/repo/pull/7".to_string()),
number: Some(PrRef::pr(7)),
review_state: None,
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 5943954ee..16be5f3e4 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -527,6 +527,51 @@ pub struct LayoutConfig {
pub status_position_mask: super::model::PositionMask,
}
+/// `Send + Sync` snapshot of the column geometry: `(kind, start, width)` per
+/// visible column, in display order. `LayoutConfig` itself can't cross
+/// threads, so renderers running outside `collect` — the picker's `--prs`
+/// thread — take this snapshot to place their cells on the same grid as the
+/// worktree rows.
+// The grid is built on every platform (`collect` hands it to `on_skeleton`),
+// but only the unix-only `--prs` picker reads its columns to align PR rows — so
+// the fields/accessor are dead on non-unix.
+#[cfg_attr(not(unix), allow(dead_code))]
+#[derive(Clone, Debug, Default)]
+pub struct ColumnGrid {
+ pub columns: Vec<GridColumn>,
+}
+
+#[cfg_attr(not(unix), allow(dead_code))]
+#[derive(Clone, Copy, Debug)]
+pub struct GridColumn {
+ pub kind: ColumnKind,
+ pub start: usize,
+ pub width: usize,
+}
+
+impl ColumnGrid {
+ #[cfg_attr(not(unix), allow(dead_code))]
+ pub fn column(&self, kind: ColumnKind) -> Option<GridColumn> {
+ self.columns.iter().copied().find(|col| col.kind == kind)
+ }
+}
+
+impl LayoutConfig {
+ pub fn column_grid(&self) -> ColumnGrid {
+ ColumnGrid {
+ columns: self
+ .columns
+ .iter()
+ .map(|col| GridColumn {
+ kind: col.kind,
+ start: col.start,
+ width: col.width,
+ })
+ .collect(),
+ }
+ }
+}
+
/// The user's column configuration for one render: which columns to show and
/// the resolved custom columns available to render.
///
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 110d3eb56..a05cfffa4 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -331,10 +331,10 @@ impl LayoutConfig {
return col.render_text_cell(text, None);
}
ColumnKind::CiStatus if item.pr_status.is_some() => {
- // Resolved before the skeleton only by the picker's
- // cache-only fill, where no task will repaint the cell;
- // `wt list` never sets pr_status this early and keeps
- // the placeholder arm below.
+ // Set before the skeleton only by the picker's cache prime —
+ // render it now for an instant first paint; the live CiStatus
+ // task repaints the cell as it lands. `wt list` never sets
+ // pr_status this early and keeps the placeholder arm below.
return match &item.pr_status {
Some(Some(pr_status)) => {
let mut ci = StyledLine::new();
@@ -416,12 +416,11 @@ impl ColumnLayout {
// presence gradient, glyph still primary. All single-width
// ASCII — the gutter must dodge skim's `width_cjk` clipping.
//
- // TODO(pr-rows): PR rows (open PRs with no local branch) land
- // on a separate branch; add a `#` arm to `ItemKind::gutter_glyph`
- // (and a matching `#` in the Status upstream column). Not done
- // here — PR rows don't exist on this branch, and the picker
- // skips CI/PR detection (a network call), so a `#` driven by PR
- // status would never render in the picker.
+ // PR rows (open PRs with no local branch, `wt switch --prs`)
+ // also carry a gutter sigil — a dim `#` — but they're a picker
+ // source (`PrSkimItem`), not a `ListItem`, so they render their
+ // gutter in `commands::picker::prs` (`PR_GUTTER_SIGIL`) rather
+ // than through this `ItemKind` match.
let mut cell = StyledLine::new();
// `glyph` + trailing space = the two-cell sigil; the bare glyph
// also feeds the picker's fuzzy-search text (`gutter_glyph`).
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 0c90e0cad..f57164c40 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -4,6 +4,7 @@
use std::borrow::Cow;
use std::collections::HashSet;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use ansi_to_tui::IntoText;
@@ -15,6 +16,15 @@ use skim::prelude::*;
use worktrunk::git::Repository;
use worktrunk::styling::INFO_SYMBOL;
+use super::super::list::ci_status::{PrRef, PrStatus};
+use super::super::list::model::ListItem;
+use super::log_formatter::{
+ FIELD_DELIM, batch_fetch_stats, format_log_output, process_log_with_dimming, strip_hash_markers,
+};
+use super::pager::{diff_pager, pipe_through_pager};
+use super::preview::{PreviewMode, PreviewStateData};
+use super::preview_cache;
+
/// Parse a pre-rendered ANSI string into a single ratatui `Line` for skim's
/// item list. skim's `DisplayContext::to_line` only applies match-highlight
/// styling to plain text, so the picker — whose rows already carry SGR color
@@ -26,7 +36,7 @@ use worktrunk::styling::INFO_SYMBOL;
/// `bg = Reset`, which would override skim's `highlight_line` fill and leave the
/// selected row's gray highlight (`current_bg`) full of holes. Leaving `bg`
/// unset lets the line-level current-row background show through uniformly.
-fn ansi_to_line(s: &str) -> Line<'static> {
+pub(super) fn ansi_to_line(s: &str) -> Line<'static> {
match s.into_text() {
Ok(text) => Line::from(
text.lines
@@ -42,14 +52,6 @@ fn ansi_to_line(s: &str) -> Line<'static> {
}
}
-use super::super::list::model::ListItem;
-use super::log_formatter::{
- FIELD_DELIM, batch_fetch_stats, format_log_output, process_log_with_dimming, strip_hash_markers,
-};
-use super::pager::{diff_pager, pipe_through_pager};
-use super::preview::{PreviewMode, PreviewStateData};
-use super::preview_cache;
-
/// Cache key for pre-computed previews: (branch_name, mode).
pub(super) type PreviewCacheKey = (String, PreviewMode);
@@ -57,15 +59,35 @@ pub(super) type PreviewCacheKey = (String, PreviewMode);
/// Shared across all WorktreeSkimItems for background pre-computation.
pub(super) type PreviewCache = Arc<DashMap<PreviewCacheKey, String>>;
+/// Per-row live `pr_status` for the `pr` tab, shared with the collect handler.
+/// Primed from the CI cache at skeleton time, then overwritten as the live
+/// `CiStatus` task reports (`progressive_handler::PickerHandler::on_update`).
+/// `None` = the fetch hasn't reported yet (Loading); `Some(None)` = no PR;
+/// `Some(Some(status))` = a PR/MR with status.
+pub(super) type PrStatusSlot = Arc<Mutex<Option<Option<PrStatus>>>>;
+
/// Prefix on a worktree-backed item's `output()` token. Detached worktrees
/// all share the `(detached)` branch label, so `output()` returns the
/// worktree path (which is unique) behind this prefix instead.
pub(super) const WORKTREE_OUTPUT_PREFIX: &str = "worktree-path:";
+/// A `--prs` picker's header shows a dim "loading…" line while the forge call
+/// is still in flight, since its rows arrive (~1s) after the local rows. The
+/// `--prs` thread clears `pending` and repaints once the fetch resolves (rows
+/// sent, no PRs, or error). Absent (`None`) on non-`--prs` pickers, where every
+/// row is present at skeleton.
+pub(super) struct HeaderLoading {
+ pub pending: Arc<AtomicBool>,
+ /// Pre-rendered dim "loading…" line (ANSI). Shown *in place of* the column
+ /// labels, not appended — a full-width header would clip the suffix.
+ pub marker_ansi: String,
+}
+
/// Header item for column names (non-selectable)
pub(super) struct HeaderSkimItem {
pub display_text: String,
pub display_text_with_ansi: String,
+ pub loading: Option<HeaderLoading>,
}
impl SkimItem for HeaderSkimItem {
@@ -74,6 +96,14 @@ impl SkimItem for HeaderSkimItem {
}
fn display(&self, _context: DisplayContext) -> Line<'_> {
+ // While the --prs fetch is in flight, show the loading line in place of
+ // the column labels — appending would clip off the right edge of a
+ // full-width header. The labels return when the rows land.
+ if let Some(loading) = &self.loading
+ && loading.pending.load(Ordering::Relaxed)
+ {
+ return ansi_to_line(&loading.marker_ansi);
+ }
ansi_to_line(&self.display_text_with_ansi)
}
@@ -148,6 +178,20 @@ pub(super) struct WorktreeSkimItem {
pub item: Arc<ListItem>,
/// Shared cache for pre-computed previews (all modes)
pub preview_cache: PreviewCache,
+ /// Whether this branch has an upstream tracking ref, for the tab-4
+ /// (remote⇅) empty state. A SYNCHRONOUS skeleton-time fact read from
+ /// `Repository::local_branches()` at construction — never from the async
+ /// `item.upstream`, which is `None` until the row pipeline lands and would
+ /// lock the tab bar into a stale state (see `TabAvailability`).
+ pub has_upstream: bool,
+ /// Whether `[commit.generation]` summaries are configured, for the tab-5
+ /// (summary) empty state. A process-wide static fact (`llm_command.is_some()`).
+ pub summaries_enabled: bool,
+ /// Live CI status for the `pr` tab, shared with the collect handler. Unlike
+ /// the frozen `item` snapshot (whose `pr_status` never updates after
+ /// skeleton), this slot is primed from the cache and then overwritten as the
+ /// `CiStatus` task streams in — so the `pr` tab reflects the live fetch.
+ pub pr_status: PrStatusSlot,
}
impl SkimItem for WorktreeSkimItem {
@@ -175,56 +219,222 @@ impl SkimItem for WorktreeSkimItem {
fn preview(&self, context: PreviewContext<'_>) -> ItemPreview {
let mode = PreviewStateData::read_mode();
- // Build preview: tabs header + content
- let mut result = Self::render_preview_tabs(mode);
- result.push_str(&self.preview_for_mode(mode, context.width, context.height));
+ // Build preview: tabs header + content. `has_upstream` and
+ // `summaries_enabled` are synchronous skeleton-time facts (see
+ // `TabAvailability`); `pr` reads the row's live status slot, refreshed as
+ // the `CiStatus` task streams in, so it can change between selections.
+ // The `pr` tab dims only once the fetch reports no PR — while loading or
+ // with a PR it stays available.
+ let pr = self.pr_preview();
+ let avail = TabAvailability::worktree(
+ self.has_upstream,
+ self.summaries_enabled,
+ !matches!(pr, PrPreview::NoPr),
+ );
+ let mut result = render_preview_tabs(mode, avail);
+ result.push_str(&match mode {
+ PreviewMode::Pr => self.render_pr_pane(pr),
+ _ => self.preview_for_mode(mode, context.width, context.height),
+ });
ItemPreview::AnsiText(result)
}
}
-impl WorktreeSkimItem {
- /// Render the tab header for the preview window
- ///
- /// Shows all preview modes as tabs, with the current mode bolded
- /// and unselected modes dimmed. Controls shown below in normal text
- /// for visual distinction from inactive tabs.
- pub(super) fn render_preview_tabs(mode: PreviewMode) -> String {
- // Full SGR reset (\x1b[0m) after each styled span. color_print's `</>`
- // emits only \x1b[22m (intensity reset); pairing it with an explicit
- // [0m keeps dim/bold from bleeding across the dividers and into the rest
- // of the line in the list and preview panels. Same reason the
- // `compute_*_preview` helpers below scatter `{reset}` after each styled
- // span.
- let reset = Reset;
+/// The `pr` tab's state for a worktree row, derived from the row's live CI
+/// status slot ([`WorktreeSkimItem::pr_status`]).
+enum PrPreview {
+ /// The live CI fetch hasn't reported for this branch yet, and no cache
+ /// primed it — the tab shows a "fetching" hint rather than claiming the
+ /// branch has no PR.
+ Loading,
+ /// The fetch reported no PR (no CI, or a branch workflow with no PR/MR
+ /// number) — the tab dims and shows "… has no PR".
+ NoPr,
+ /// The branch has a PR/MR. The `PrRef` rides alongside the status so the
+ /// reference is structurally guaranteed (a status with no `number` is
+ /// `NoPr`, not `HasPr`) — `render_worktree_pr` needs no fallback.
+ HasPr(PrRef, PrStatus),
+}
- /// Format a tab label with bold (active) or dimmed (inactive) styling
- fn format_tab(label: &str, is_active: bool) -> String {
- if is_active {
- cformat!("<bold>{}</>", label)
- } else {
- cformat!("<dim>{}</>", label)
- }
+/// Which preview tabs have renderable content for the selected row.
+///
+/// Empty tabs are de-emphasized in the bar (number dimmed). Skim computes a
+/// preview once per selection and cannot re-query it mid-selection (see
+/// `loading_placeholder`). `upstream` and `summary` are synchronous
+/// skeleton-time facts, read to avoid locking the bar into a stale state:
+/// `upstream` reads `Repository::local_branches()` (the pre-skeleton
+/// `for-each-ref` scan), NOT the async `item.upstream`; `summary` reads the
+/// process-wide `[commit.generation]` flag, NOT the async `item.summary`. `pr`
+/// reads the row's live status slot (primed from the CI cache, then refreshed
+/// by the `CiStatus` task — see [`WorktreeSkimItem::pr_status`]), so it can
+/// change between selections: it dims once the fetch reports no PR, and stays
+/// available while loading or with a PR. `--prs` rows always render their PR.
+#[derive(Debug, Clone, Copy)]
+pub(super) struct TabAvailability {
+ working_tree: bool,
+ log: bool,
+ branch_diff: bool,
+ upstream: bool,
+ summary: bool,
+ pr: bool,
+}
+
+impl TabAvailability {
+ /// A worktree-backed row: working-tree/log/branch-diff always render; the
+ /// upstream and summary tabs depend on synchronous skeleton-time facts; the
+ /// `pr` tab is available unless the live fetch has reported no PR for this
+ /// branch (see [`WorktreeSkimItem::pr_preview`]).
+ pub(super) fn worktree(has_upstream: bool, summaries_enabled: bool, pr: bool) -> Self {
+ Self {
+ working_tree: true,
+ log: true,
+ branch_diff: true,
+ upstream: has_upstream,
+ summary: summaries_enabled,
+ pr,
}
+ }
- let tab1 = format_tab("1: HEAD±", mode == PreviewMode::WorkingTree);
- let tab2 = format_tab("2: log", mode == PreviewMode::Log);
- let tab3 = format_tab("3: main…±", mode == PreviewMode::BranchDiff);
- let tab4 = format_tab("4: remote⇅", mode == PreviewMode::UpstreamDiff);
- let tab5 = format_tab("5: summary", mode == PreviewMode::Summary);
-
- // Controls use dim yellow to distinguish from dimmed (white) tabs.
- // The tab numbers above are the alt-N accelerators (bare digits type
- // into the query); Tab/shift-tab cycle the same tabs.
- let controls = cformat!(
- "<dim,yellow>Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>"
- );
+ /// A `--prs` row: it carries no local worktree, so only the PR tab has
+ /// content; tabs 1-5 are empty.
+ pub(super) fn pull_request() -> Self {
+ Self {
+ working_tree: false,
+ log: false,
+ branch_diff: false,
+ upstream: false,
+ summary: false,
+ pr: true,
+ }
+ }
+}
- // End each tab and controls with full reset to prevent style bleeding
- // into dividers and preview content
- format!(
- "{tab1}{reset} | {tab2}{reset} | {tab3}{reset} | {tab4}{reset} | {tab5}{reset}\n{controls}{reset}\n\n"
- )
+/// Render the preview tab bar, shared by worktree rows and `--prs` rows.
+///
+/// Every tab always keeps its `N: label` text — only the formatting varies, so
+/// the accelerators stay discoverable. Two **orthogonal** signals carry through
+/// the styling: the **number's** brightness says whether the tab is selectable
+/// (normal = has content, dim = empty for this row — see `TabAvailability`),
+/// and the **label's** weight says whether it's the active mode (bold = active,
+/// dim = inactive). The two compose independently: an empty tab dims its number
+/// whether or not it's selected, but the active tab's label still bolds — so an
+/// active-but-empty tab (dim number, bold label) stays distinct from an
+/// inactive-empty one (dim number, dim label), and the selected tab is always
+/// identifiable even when it has nothing to show (its pane, e.g. "… has no PR",
+/// says the rest).
+pub(super) fn render_preview_tabs(mode: PreviewMode, avail: TabAvailability) -> String {
+ // Full SGR reset (\x1b[0m) after each styled span. color_print's `</>`
+ // emits only \x1b[22m (intensity reset); pairing it with an explicit [0m
+ // keeps dim/bold from bleeding across the dividers and into the rest of the
+ // line in the list and preview panels. Same reason the `compute_*_preview`
+ // helpers below scatter `{reset}` after each styled span.
+ let reset = Reset;
+
+ /// Format one tab, keeping the `N: label` text in every state so the
+ /// accelerator never disappears. The number and label carry the two
+ /// orthogonal signals independently: the number dims when the tab is empty
+ /// (not selectable), and the label bolds on the active tab. They compose,
+ /// so an active-but-empty tab is dim-number + bold-label — distinct from an
+ /// inactive-empty one (dim-number + dim-label).
+ fn format_tab(number: u8, label: &str, is_active: bool, has_content: bool) -> String {
+ let number = if has_content {
+ format!("{number}:")
+ } else {
+ cformat!("<dim>{number}:</>")
+ };
+ let label = if is_active {
+ cformat!("<bold>{label}</>")
+ } else {
+ cformat!("<dim>{label}</>")
+ };
+ format!("{number} {label}")
+ }
+
+ let tab1 = format_tab(
+ 1,
+ "HEAD±",
+ mode == PreviewMode::WorkingTree,
+ avail.working_tree,
+ );
+ let tab2 = format_tab(2, "log", mode == PreviewMode::Log, avail.log);
+ let tab3 = format_tab(
+ 3,
+ "main…±",
+ mode == PreviewMode::BranchDiff,
+ avail.branch_diff,
+ );
+ let tab4 = format_tab(
+ 4,
+ "remote⇅",
+ mode == PreviewMode::UpstreamDiff,
+ avail.upstream,
+ );
+ let tab5 = format_tab(5, "summary", mode == PreviewMode::Summary, avail.summary);
+ let tab6 = format_tab(6, "pr", mode == PreviewMode::Pr, avail.pr);
+
+ // Controls use dim yellow to distinguish from dimmed (white) tabs.
+ // The tab numbers above are the alt-N accelerators (bare digits type
+ // into the query); Tab/shift-tab cycle the same tabs.
+ let controls = cformat!(
+ "<dim,yellow>Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>"
+ );
+
+ // End each tab and controls with full reset to prevent style bleeding
+ // into dividers and preview content
+ format!(
+ "{tab1}{reset} | {tab2}{reset} | {tab3}{reset} | {tab4}{reset} | {tab5}{reset} | {tab6}{reset}\n{controls}{reset}\n\n"
+ )
+}
+
+/// The `pr` pane for a worktree row whose branch has a PR/MR. Renders the
+/// reference and URL from the async CI fetch. The `url` label pads to the same
+/// width as the `--prs` rows' pane (`PrSkimItem::pr_pane`) so the two read
+/// alike.
+///
+/// TODO(pr-preview-worktree-body): the CI-column fetch doesn't pull the PR
+/// title or description (just number/status/url), so this pane can't show them
+/// the way the `--prs` rows' pane does. Widen that fetch's `--json` (or add a
+/// per-row PR fetch) to fold them in.
+fn render_worktree_pr(branch: &str, pr_ref: PrRef, status: &PrStatus) -> String {
+ let reset = Reset;
+ let mut out = cformat!("<bold>{pr_ref}</>{reset} {branch}\n\n");
+ if let Some(url) = &status.url {
+ out.push_str(&cformat!("<dim>url</>{reset} {url}\n"));
+ }
+ out
+}
+
+impl WorktreeSkimItem {
+ /// Derive the `pr` tab's state from the row's live `pr_status` slot. The
+ /// slot is primed from the CI cache at skeleton time and overwritten as the
+ /// `CiStatus` task reports: `None` = no result yet (Loading); `Some(None)`,
+ /// or a status carrying no PR/MR `number` (a bare branch workflow), = no PR;
+ /// a status with a `number` = a real PR.
+ fn pr_preview(&self) -> PrPreview {
+ match &*self.pr_status.lock().unwrap() {
+ None => PrPreview::Loading,
+ Some(None) => PrPreview::NoPr,
+ Some(Some(status)) => match status.number {
+ Some(pr_ref) => PrPreview::HasPr(pr_ref, status.clone()),
+ None => PrPreview::NoPr,
+ },
+ }
+ }
+
+ /// Render the `pr` tab's pane from the derived [`PrPreview`] state.
+ fn render_pr_pane(&self, pr: PrPreview) -> String {
+ let reset = Reset;
+ let branch = self.item.branch_name();
+ match pr {
+ PrPreview::Loading => cformat!(
+ "○ Fetching PR status for <bold>{branch}</>{reset}… press <bold>alt-6</>{reset} to refresh\n"
+ ),
+ PrPreview::NoPr => {
+ cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no PR\n")
+ }
+ PrPreview::HasPr(pr_ref, status) => render_worktree_pr(branch, pr_ref, &status),
+ }
}
/// Render preview for the given mode with specified dimensions.
@@ -263,6 +473,9 @@ impl WorktreeSkimItem {
PreviewMode::BranchDiff => ("Loading", "branch diff"),
PreviewMode::UpstreamDiff => ("Loading", "upstream diff"),
PreviewMode::Summary => ("Generating", "summary"),
+ // The `pr` tab has no background task — `preview()` renders it from
+ // the row's cached `pr_status` via `render_pr_pane`, never here.
+ PreviewMode::Pr => unreachable!("pr tab renders via render_pr_pane"),
};
let key = mode as u8;
format!("○ {verb} {label}. Press alt-{key} again to refresh.\n")
@@ -301,6 +514,10 @@ impl WorktreeSkimItem {
false,
),
PreviewMode::Summary => (Self::loading_placeholder(PreviewMode::Summary), false),
+ // PR previews never precompute (no git/LLM work) — the orchestrator
+ // never spawns this mode, and `preview()` renders the `pr` pane from
+ // the row's cached `pr_status`.
+ PreviewMode::Pr => unreachable!("pr tab is never precomputed"),
}
}
@@ -697,16 +914,75 @@ mod tests {
#[test]
fn test_render_preview_tabs() {
- // All PreviewMode variants: verify tab labels, active styling, and structure
+ // Each mode active, on a worktree row with upstream + summaries
+ // enabled but no PR (tabs 1-5 available; tab 6 dim). The active
+ // mode's label is bold, inactive available labels dim, and on the
+ // `pr` iteration tab 6 is active-but-empty — exercising the rule that
+ // emptiness dims even the active tab. Verifies labels and structure.
+ let wt = TabAvailability::worktree(true, true, false);
for (name, mode) in [
("working_tree", PreviewMode::WorkingTree),
("log", PreviewMode::Log),
("branch_diff", PreviewMode::BranchDiff),
("upstream_diff", PreviewMode::UpstreamDiff),
("summary", PreviewMode::Summary),
+ ("pr", PreviewMode::Pr),
] {
- assert_snapshot!(name, WorktreeSkimItem::render_preview_tabs(mode));
+ assert_snapshot!(name, render_preview_tabs(mode, wt));
}
+
+ // Empty states: a worktree row with no upstream and summaries disabled
+ // dims tabs 4 and 5 (number dim too); a --prs row dims tabs 1-5.
+ assert_snapshot!(
+ "empty_upstream_and_summary",
+ render_preview_tabs(
+ PreviewMode::WorkingTree,
+ TabAvailability::worktree(false, false, false)
+ )
+ );
+ assert_snapshot!(
+ "pr_row",
+ render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request())
+ );
+ }
+
+ #[test]
+ fn header_loading_marker_shows_until_cleared() {
+ // `--prs` mode: the header carries a dim "loading…" marker while the
+ // forge call is in flight, dropped once the `--prs` thread clears the
+ // shared flag.
+ let pending = Arc::new(AtomicBool::new(true));
+ let header = HeaderSkimItem {
+ display_text: "Branch CI".to_string(),
+ display_text_with_ansi: "Branch CI".to_string(),
+ loading: Some(HeaderLoading {
+ pending: Arc::clone(&pending),
+ marker_ansi: " loading open PRs…".to_string(),
+ }),
+ };
+ let text = |h: &HeaderSkimItem| {
+ h.display(DisplayContext::default())
+ .spans
+ .iter()
+ .map(|s| s.content.as_ref().to_string())
+ .collect::<String>()
+ };
+
+ assert!(
+ text(&header).contains("loading open PRs"),
+ "marker shows while pending"
+ );
+
+ pending.store(false, Ordering::Relaxed);
+ let cleared = text(&header);
+ assert!(
+ !cleared.contains("loading"),
+ "marker gone once cleared: {cleared:?}"
+ );
+ assert!(
+ cleared.contains("Branch"),
+ "column header remains: {cleared:?}"
+ );
}
#[test]
@@ -718,6 +994,9 @@ mod tests {
("branch_diff", PreviewMode::BranchDiff),
("upstream_diff", PreviewMode::UpstreamDiff),
("summary", PreviewMode::Summary),
+ // `Pr` isn't backed by the preview cache — it renders from the
+ // row's live `pr_status` slot via `render_pr_pane`, so the
+ // `loading_placeholder` path never covers it.
] {
assert_snapshot!(
format!("loading_placeholder_{name}"),
@@ -746,6 +1025,9 @@ mod tests {
branch_name: "feature".to_string(),
item: Arc::clone(&item),
preview_cache,
+ has_upstream: false,
+ summaries_enabled: false,
+ pr_status: Arc::new(Mutex::new(None)),
}
};
@@ -757,6 +1039,9 @@ mod tests {
branch_name: "feature".to_string(),
item: Arc::clone(&item),
preview_cache,
+ has_upstream: false,
+ summaries_enabled: false,
+ pr_status: Arc::new(Mutex::new(None)),
}
};
@@ -770,6 +1055,71 @@ mod tests {
);
}
+ #[test]
+ fn worktree_pr_tab_reflects_live_status() {
+ use crate::commands::list::ci_status::{CiSource, CiStatus, PrRef, ReviewState};
+
+ let status = |number: Option<PrRef>, url: Option<&str>| PrStatus {
+ ci_status: CiStatus::Passed,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ is_priming: false,
+ url: url.map(String::from),
+ number,
+ review_state: Some(ReviewState::Approved),
+ };
+ // Build a row whose live `pr_status` slot carries a given state — what
+ // the picker primes from the cache and then overwrites as the fetch lands.
+ let row = |pr_status: Option<Option<PrStatus>>| {
+ let item = ListItem::new_branch("abc".into(), "feature".into());
+ WorktreeSkimItem {
+ search_text: String::new(),
+ rendered: Arc::new(Mutex::new(String::new())),
+ branch_name: "feature".into(),
+ item: Arc::new(item),
+ preview_cache: Arc::new(DashMap::new()),
+ has_upstream: false,
+ summaries_enabled: false,
+ pr_status: Arc::new(Mutex::new(pr_status)),
+ }
+ };
+
+ // No result yet (outer `None`) → Loading; the pane shows a fetching hint.
+ let loading = row(None);
+ assert!(matches!(loading.pr_preview(), PrPreview::Loading));
+ assert!(
+ loading
+ .render_pr_pane(loading.pr_preview())
+ .contains("Fetching PR status")
+ );
+
+ // Cache reports no PR (`Some(None)`) → NoPr.
+ let no_pr = row(Some(None));
+ assert!(matches!(no_pr.pr_preview(), PrPreview::NoPr));
+ assert!(
+ no_pr
+ .render_pr_pane(no_pr.pr_preview())
+ .contains("has no PR")
+ );
+
+ // A cached PR carries a `number` → the pane shows the reference and URL.
+ let has_pr = row(Some(Some(status(
+ Some(PrRef::pr(42)),
+ Some("https://github.com/o/r/pull/42"),
+ ))));
+ assert!(matches!(has_pr.pr_preview(), PrPreview::HasPr(..)));
+ let pane = has_pr.render_pr_pane(has_pr.pr_preview());
+ assert!(pane.contains("#42"), "reference: {pane:?}");
+ assert!(
+ pane.contains("https://github.com/o/r/pull/42"),
+ "url: {pane:?}"
+ );
+
+ // Cached branch CI with no PR `number` → NoPr.
+ let branch_ci = row(Some(Some(status(None, None))));
+ assert!(matches!(branch_ci.pr_preview(), PrPreview::NoPr));
+ }
+
/// Helper: build a test repo with `main` at the initial commit, then a
/// second commit so branches can diverge from it.
fn repo_with_main() -> (worktrunk::testing::TestRepo, Repository) {
@@ -1063,8 +1413,15 @@ mod tests {
#[test]
fn test_render_preview_tabs_ansi_codes() {
- // Test that ANSI escape sequences properly reset to prevent style bleeding
- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::WorkingTree);
+ // Test that ANSI escape sequences properly reset to prevent style bleeding.
+ // The per-tab `{reset}` is appended in the outer format regardless of a
+ // tab's internal styling, so the reset/divider counts hold whether a tab
+ // is active (bold label), inactive-available (dim label), or empty (dim
+ // number + label — here tab 6, pr).
+ let output = render_preview_tabs(
+ PreviewMode::WorkingTree,
+ TabAvailability::worktree(true, true, false),
+ );
let first_line = output.lines().next().unwrap();
let second_line = output.lines().nth(1).unwrap();
@@ -1073,13 +1430,13 @@ mod tests {
// This prevents bold/dim from bleeding into the " | " dividers
let full_reset = "\x1b[0m";
- // Count resets - should have one after each of the 5 tabs
- assert_eq!(first_line.matches(full_reset).count(), 5);
+ // Count resets - should have one after each of the 6 tabs
+ assert_eq!(first_line.matches(full_reset).count(), 6);
// The sequence should be: style + text + [22m + [0m + divider
// Check that dividers come after full resets
let parts: Vec<&str> = first_line.split(" | ").collect();
- assert_eq!(parts.len(), 5);
+ assert_eq!(parts.len(), 6);
assert!(parts.iter().all(|part| part.ends_with(full_reset)));
// Controls line should end with full reset to ensure clean state for preview content
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 6b8e32c15..77121f30d 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -95,6 +95,7 @@ mod preview;
pub(crate) mod preview_cache;
mod preview_orchestrator;
mod progressive_handler;
+mod prs;
mod summary;
use std::cell::RefCell;
@@ -469,6 +470,7 @@ fn approved_removal_plan(
pub fn handle_picker(
cli_branches: bool,
cli_remotes: bool,
+ cli_prs: bool,
change_dir_flag: Option<bool>,
format: SwitchFormat,
) -> anyhow::Result<()> {
@@ -491,6 +493,9 @@ pub fn handle_picker(
let change_dir = change_dir_flag.unwrap_or_else(|| config.switch.cd());
let show_branches = cli_branches || config.list.branches();
let show_remotes = cli_remotes || config.list.remotes();
+ // Flag-only: listing PRs always reaches the forge, so it stays opt-in
+ // per invocation rather than defaulting on via config.
+ let show_prs = cli_prs;
worktrunk::trace::instant("Picker config resolved");
// Initialize preview mode state file (auto-cleanup on drop)
@@ -541,17 +546,17 @@ pub fn handle_picker(
orchestrator.spawn_preview(Arc::new(item), PreviewMode::WorkingTree, dims);
}
- // Skip expensive operations — BranchDiff walks history per item,
- // CiStatus hits the network. Both are slow enough that waiting for
- // them adds perceptible cost for a modest column-population win.
- // Cached CI statuses still appear: when the CiStatus task is skipped
- // under a progressive handler, collect fills rows from the CI cache
- // (one local file read per branch, no fetch), so PR/MR numbers from
- // recent `wt list --full` or statusline runs show in the picker.
+ // Skip BranchDiff — it walks history per item for a column the picker
+ // doesn't surface. Keep the CiStatus task: the picker primes its CI cells
+ // from the local cache so the first frame shows cached status (see
+ // `populate_from_cache`), then this task fetches live and streams each row's
+ // status in behind the frame — the same 30–60s-TTL cache plus live fetch as
+ // `wt list --full`. The picker's lifetime is bounded by the user, so a slow forge call
+ // never blocks anything (see the "Network Access" notes in CLAUDE.md). The
+ // `pr` preview tab reads the same live status. `--prs` rows carry their own
+ // number from the explicit `--prs` forge call.
let skip_tasks: std::collections::HashSet<collect::TaskKind> =
- [collect::TaskKind::BranchDiff, collect::TaskKind::CiStatus]
- .into_iter()
- .collect();
+ [collect::TaskKind::BranchDiff].into_iter().collect();
// Per-task command timeout (bounds any single git invocation) from
// shared `[list]` config. Still applies in progressive mode.
@@ -566,12 +571,15 @@ pub fn handle_picker(
// ~50/50; Down gives the list the full width. Passed to `collect` so
// the skeleton layout matches the picker's actual render width.
// The picker requires a TTY, so detection essentially always succeeds;
- // the unlimited-width fallback just keeps the math total.
+ // the unlimited-width fallback just keeps the math total. Skim
+ // prefixes every line with a 2-column cursor gutter ("> "), so rows that
+ // use the full width would otherwise spill into its ".." truncation.
let terminal_width = crate::display::terminal_width().unwrap_or(usize::MAX);
let skim_list_width = match state.initial_layout {
PreviewLayout::Right => terminal_width / 2,
PreviewLayout::Down => terminal_width,
- };
+ }
+ .saturating_sub(2);
// Estimate item count for the preview window spec (only the Down
// layout depends on it). Every row over MAX_VISIBLE_ITEMS is a no-op
@@ -677,11 +685,11 @@ pub fn handle_picker(
.color("fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108")
.cmd_collector(Rc::new(RefCell::new(collector)) as Rc<RefCell<dyn CommandCollector>>)
.bind(vec![
- // Preview-tab switching. Bare digits 1-5 are intentionally NOT
+ // Preview-tab switching. Bare digits 1-6 are intentionally NOT
// bound — they flow to the query input so a number can be typed
// (a PR number, or digits within a branch name). Two ways to
// switch tabs remain:
- // * alt-1..alt-5 jump straight to a tab. skim 4.x parses
+ // * alt-1..alt-6 jump straight to a tab. skim 4.x parses
// `alt-<digit>` natively via crossterm; an unparsable bind is
// just logged and dropped.
// * tab / shift-tab cycle forward / backward (below).
@@ -705,8 +713,12 @@ pub fn handle_picker(
"alt-5:execute-silent(echo 5 > {0})+refresh-preview",
state_path_str
),
+ format!(
+ "alt-6:execute-silent(echo 6 > {0})+refresh-preview",
+ state_path_str
+ ),
// Cycle tabs with tab / shift-tab. The state file holds the current
- // digit; `tr` rotates it (1→2→3→4→5→1 forward, the reverse for
+ // digit; `tr` rotates it (1→2→3→4→5→6→1 forward, the reverse for
// btab) with wraparound, via a temp file + rename so the read and
// write don't race on one path. Two hard constraints shape this:
// * Paren-free — skim 4.x parses an `execute-silent(…)` body by
@@ -733,19 +745,19 @@ pub fn handle_picker(
// report (`btab` / `shift-btab` / `shift-tab`) so the override holds
// regardless of terminal. (Plain Tab is unambiguous — `Tab+NONE`.)
format!(
- "tab:execute-silent(tr 12345 23451 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
+ "tab:execute-silent(tr 123456 234561 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
state_path_str
),
format!(
- "btab:execute-silent(tr 12345 51234 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
+ "btab:execute-silent(tr 123456 612345 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
state_path_str
),
format!(
- "shift-btab:execute-silent(tr 12345 51234 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
+ "shift-btab:execute-silent(tr 123456 612345 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
state_path_str
),
format!(
- "shift-tab:execute-silent(tr 12345 51234 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
+ "shift-tab:execute-silent(tr 123456 612345 < {0} > {0}.tmp; mv {0}.tmp {0})+refresh-preview",
state_path_str
),
// Create new worktree with query as branch name (alt-c for "create")
@@ -776,12 +788,23 @@ pub fn handle_picker(
// `Skim::run_with` returns and stderr is safe again).
let stashed_warnings: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ // Column-geometry handoff: the collect thread fills it at skeleton time,
+ // the `--prs` thread reads it to align PR rows with the worktree rows.
+ let grid_slot = Arc::new(prs::GridSlot::new());
+
// skim 4.x repaints on demand, so the collect handler needs a handle to
// skim's event loop to surface in-place row updates. The picker fills this
// once `Skim::init_tui` has run (inside `run_skim`); until then the handler
// simply skips its render pokes. See `progressive_handler` module docstring.
let render_tx: Arc<OnceLock<tokio::sync::mpsc::Sender<Event>>> = Arc::new(OnceLock::new());
+ // `--prs` loading flag, shared between the header (shows a "loading…"
+ // marker while true) and the `--prs` thread (clears it when the forge call
+ // resolves). `Some` exactly when that thread spawns below, so the marker
+ // tracks its lifetime.
+ let prs_loading: Option<Arc<AtomicBool>> =
+ (show_prs && !is_preview_bench).then(|| Arc::new(AtomicBool::new(true)));
+
// Concrete type so the dry-run dump can read the handler's rendered rows.
let handler: Arc<progressive_handler::PickerHandler> =
Arc::new(progressive_handler::PickerHandler {
@@ -790,6 +813,7 @@ pub fn handle_picker(
last_render_poke: Mutex::new(Instant::now()),
shared_items: Arc::clone(&shared_items),
rendered_slots: std::sync::OnceLock::new(),
+ pr_status_slots: std::sync::OnceLock::new(),
preview_cache: Arc::clone(&preview_cache),
orchestrator: Arc::clone(&orchestrator),
preview_dims,
@@ -797,6 +821,8 @@ pub fn handle_picker(
summary_hint,
stashed_warnings: Arc::clone(&stashed_warnings),
deferred_items: std::sync::OnceLock::new(),
+ grid_slot: Arc::clone(&grid_slot),
+ prs_loading: prs_loading.clone(),
});
// Spawn collect on a background thread. The handler holds the only
@@ -828,10 +854,45 @@ pub fn handle_picker(
.context("Failed to spawn picker-collect thread")?;
worktrunk::trace::instant("Picker collect spawned");
- // Drop main-thread copies so the bg thread's `tx` clone is the last
- // sender (its drop is what signals EOF to skim's reader). The dry run keeps
- // the handler: skim never runs there, so the EOF contract doesn't apply,
- // and the dump below reads its rendered rows.
+ // PR/MR streaming (`--prs`). One forge call on its own thread that holds
+ // another `tx` clone, so the picker frame paints from local worktree data
+ // immediately and PR rows stream in (~1s) when the call returns. The
+ // clone defers EOF: skim's reader sees end-of-stream only once both this
+ // thread and the collect thread drop their senders. The dry-run runs it
+ // (joined below) so the fetch/render path is exercised headlessly — the only
+ // way it gets coverage, since the interactive picker's skim-abort exit never
+ // flushes a profile. Only the preview-bench skips it: that path measures the
+ // preview workload and must not reach the network.
+ let prs_handle = if let Some(prs_loading) = prs_loading.clone() {
+ let prs_tx = tx.clone();
+ let prs_repo = repo.clone();
+ let prs_warnings = Arc::clone(&stashed_warnings);
+ let prs_grid = Arc::clone(&grid_slot);
+ let prs_render_tx = Arc::clone(&render_tx);
+ Some(
+ std::thread::Builder::new()
+ .name("picker-prs".into())
+ .spawn(move || {
+ prs::stream_open_prs(
+ &prs_repo,
+ skim_list_width,
+ &prs_tx,
+ &prs_warnings,
+ &prs_grid,
+ &prs_loading,
+ &prs_render_tx,
+ );
+ })
+ .context("Failed to spawn picker-prs thread")?,
+ )
+ } else {
+ None
+ };
+
+ // Drop main-thread copies so the bg threads' `tx` clones are the last
+ // senders (their drop is what signals EOF to skim's reader). The dry run
+ // keeps the handler: skim never runs there, so the EOF contract doesn't
+ // apply, and the dump below reads its rendered rows.
drop(tx);
let dry_run_handler = is_dry_run.then_some(handler);
@@ -845,6 +906,14 @@ pub fn handle_picker(
if skip_tui {
drop(rx);
let _ = bg_handle.join();
+ // Join the `--prs` thread (present only for the dry-run, not the bench)
+ // so its forge fetch and row render run to completion before we dump
+ // and exit — this normal-exit path is what gives the streaming code its
+ // coverage. The PR rows it built went nowhere (`rx` is dropped); the
+ // dump is the worktree-preview cache, unchanged.
+ if let Some(handle) = prs_handle {
+ let _ = handle.join();
+ }
orchestrator.wait_for_idle();
if is_dry_run {
drain_stashed_warnings(&stashed_warnings);
@@ -880,6 +949,10 @@ pub fn handle_picker(
// are read-only.
let output = run_skim(options, rx, &render_tx, &state.path);
drop(bg_handle);
+ // Same rationale as `bg_handle`: don't join — the forge call may still be
+ // in flight, and process exit terminates the thread (its `gh`/`glab`
+ // subprocess is read-only).
+ drop(prs_handle);
// Skim has released the terminal — emit any warnings that collect's bg
// thread stashed during the run. Late warnings (e.g. drain timeouts)
@@ -1483,12 +1556,16 @@ pub mod tests {
/// Build a `WorktreeSkimItem` from a snapshot `ListItem`.
fn picker_item(branch_name: &str, item: ListItem) -> Arc<dyn SkimItem> {
+ let pr_status = Arc::new(Mutex::new(item.pr_status.clone()));
Arc::new(WorktreeSkimItem {
search_text: branch_name.to_string(),
rendered: Arc::new(Mutex::new(String::new())),
branch_name: branch_name.to_string(),
item: Arc::new(item),
preview_cache: Arc::new(dashmap::DashMap::new()),
+ has_upstream: false,
+ summaries_enabled: false,
+ pr_status,
}) as Arc<dyn SkimItem>
}
diff --git a/src/commands/picker/preview.rs b/src/commands/picker/preview.rs
index 212854ed1..c7c1266b2 100644
--- a/src/commands/picker/preview.rs
+++ b/src/commands/picker/preview.rs
@@ -7,18 +7,26 @@ use std::path::PathBuf;
/// Preview modes for the interactive selector
///
-/// Each mode shows a different aspect of the worktree:
+/// Each mode shows a different aspect of the selected row:
/// 1. WorkingTree: Uncommitted changes (git diff HEAD --stat)
/// 2. Log: Commit history since diverging from the default branch (git log with merge-base)
/// 3. BranchDiff: Line diffs since the merge-base with the default branch (git diff --stat DEFAULT…)
/// 4. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)
/// 5. Summary: LLM-generated branch summary (requires [commit.generation] config)
+/// 6. Pr: The selected row's PR/MR, rendered from already-fetched data (no network)
+///
+/// A mode whose content is structurally absent for the current row is rendered
+/// de-emphasized in the tab bar (see `TabAvailability` / `render_preview_tabs`):
+/// tab 4 when the branch has no upstream, tab 5 when summaries are disabled,
+/// tabs 1-5 on a `--prs` row (no local worktree), and tab 6 on a worktree row
+/// (PR previews render only on `--prs` rows).
///
/// Loosely aligned with `wt list` columns, though not a perfect match:
/// - Tab 1 corresponds to "HEAD±" column
/// - Tab 2 shows commits (related to "main↕" counts)
/// - Tab 3 corresponds to "main…± (--full)" column
/// - Tab 4 corresponds to "Remote⇅" column
+/// - Tab 6 corresponds to the "CI" column's PR/MR
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) enum PreviewMode {
WorkingTree = 1,
@@ -26,6 +34,7 @@ pub(super) enum PreviewMode {
BranchDiff = 3,
UpstreamDiff = 4,
Summary = 5,
+ Pr = 6,
}
impl PreviewMode {
@@ -35,6 +44,7 @@ impl PreviewMode {
3 => Self::BranchDiff,
4 => Self::UpstreamDiff,
5 => Self::Summary,
+ 6 => Self::Pr,
_ => Self::WorkingTree,
}
}
@@ -157,7 +167,7 @@ impl PreviewLayout {
/// Preview state persistence (mode only, layout auto-detected)
///
-/// State file format: Single digit representing preview mode (1-5)
+/// State file format: Single digit representing preview mode (1-6)
pub(super) struct PreviewStateData;
impl PreviewStateData {
@@ -224,6 +234,7 @@ mod tests {
assert_eq!(PreviewMode::from_u8(3), PreviewMode::BranchDiff);
assert_eq!(PreviewMode::from_u8(4), PreviewMode::UpstreamDiff);
assert_eq!(PreviewMode::from_u8(5), PreviewMode::Summary);
+ assert_eq!(PreviewMode::from_u8(6), PreviewMode::Pr);
// Invalid values default to WorkingTree
assert_eq!(PreviewMode::from_u8(0), PreviewMode::WorkingTree);
assert_eq!(PreviewMode::from_u8(99), PreviewMode::WorkingTree);
diff --git a/src/commands/picker/preview_orchestrator.rs b/src/commands/picker/preview_orchestrator.rs
index 7839ca307..be55d2284 100644
--- a/src/commands/picker/preview_orchestrator.rs
+++ b/src/commands/picker/preview_orchestrator.rs
@@ -78,6 +78,13 @@ impl PreviewOrchestrator {
}
}
+ /// The repository this orchestrator computes previews against. Exposed so
+ /// `on_skeleton` can read the cached local-branch inventory
+ /// (`local_branches()`) for synchronous tab-availability facts.
+ pub(super) fn repo(&self) -> &Repository {
+ &self.repo
+ }
+
/// Spawn a preview compute task. Returns immediately.
///
/// Idempotent on the cache key: if another task already populated it,
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index f344bc31a..a907e6763 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -32,9 +32,12 @@
//! that pool's injector while row tasks are still landing on
//! workers' local deques during drain.
+use std::collections::HashSet;
+use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
+use color_print::cformat;
use skim::prelude::*;
use worktrunk::styling::{StyledLine, strip_osc8_hyperlinks};
@@ -44,7 +47,7 @@ use worktrunk::styling::{StyledLine, strip_osc8_hyperlinks};
/// `Event::Render` bypasses skim's own frame-rate cap, so we cap it here.
const RENDER_THROTTLE: Duration = Duration::from_millis(16);
-use super::items::{HeaderSkimItem, PreviewCache, WorktreeSkimItem};
+use super::items::{HeaderLoading, HeaderSkimItem, PrStatusSlot, PreviewCache, WorktreeSkimItem};
use super::preview_orchestrator::PreviewOrchestrator;
use crate::commands::list::collect::PickerProgressHandler;
use crate::commands::list::model::ListItem;
@@ -73,6 +76,11 @@ pub(super) struct PickerHandler {
/// One `Arc<Mutex<String>>` per data row — same Arcs `WorktreeSkimItem`
/// holds. Set once in `on_skeleton`, read lock-free thereafter.
pub(super) rendered_slots: OnceLock<Box<[Arc<Mutex<String>>]>>,
+ /// One live `pr_status` slot per data row — same `PrStatusSlot` Arcs the
+ /// `WorktreeSkimItem`s hold. Set once in `on_skeleton` (primed from the
+ /// cache-filled snapshot), then written by `on_update` as the `CiStatus`
+ /// task reports, so the `pr` tab reflects the live fetch.
+ pub(super) pr_status_slots: OnceLock<Box<[PrStatusSlot]>>,
pub(super) preview_cache: PreviewCache,
pub(super) orchestrator: Arc<PreviewOrchestrator>,
pub(super) preview_dims: (usize, usize),
@@ -89,6 +97,13 @@ pub(super) struct PickerHandler {
/// to fan out the bulk preview pre-compute for items 1..N. Set once
/// (`OnceLock`) because skeletons fire exactly once per collect.
pub(super) deferred_items: OnceLock<Vec<Arc<ListItem>>>,
+ /// Handoff of the layout's column geometry to the `--prs` thread, which
+ /// renders PR rows on the same grid as the worktree rows.
+ pub(super) grid_slot: Arc<super::prs::GridSlot>,
+ /// Shared with the header: `Some(true)` while the `--prs` forge call is in
+ /// flight, so the header shows a "loading…" marker. The `--prs` thread
+ /// clears it when the fetch resolves. `None` on non-`--prs` pickers.
+ pub(super) prs_loading: Option<Arc<AtomicBool>>,
}
impl PickerHandler {
@@ -114,21 +129,60 @@ impl PickerHandler {
}
impl PickerProgressHandler for PickerHandler {
- fn on_skeleton(&self, items: Vec<ListItem>, rendered: Vec<String>, header: StyledLine) {
+ fn on_skeleton(
+ &self,
+ items: Vec<ListItem>,
+ rendered: Vec<String>,
+ header: StyledLine,
+ grid: crate::commands::list::layout::ColumnGrid,
+ ) {
debug_assert_eq!(items.len(), rendered.len());
+ self.grid_slot.set(grid);
let mut slots: Vec<Arc<Mutex<String>>> = Vec::with_capacity(items.len());
+ let mut pr_slots: Vec<PrStatusSlot> = Vec::with_capacity(items.len());
let mut skim_items: Vec<Arc<dyn SkimItem>> = Vec::with_capacity(items.len() + 1);
let mut list_items: Vec<Arc<ListItem>> = Vec::with_capacity(items.len());
+ // Synchronous skeleton-time tab-availability facts (see `TabAvailability`).
+ // Branches with an upstream tracking ref drive the tab-4 (remote⇅) empty
+ // state, read from the pre-skeleton `for-each-ref` inventory — never the
+ // async `item.upstream`. A `local_branches()` failure yields the empty set
+ // (every branch reads as no-upstream); preview rendering must not error.
+ let upstream_branches: HashSet<String> = self
+ .orchestrator
+ .repo()
+ .local_branches()
+ .map(|branches| {
+ branches
+ .iter()
+ .filter(|b| b.upstream_short.is_some())
+ .map(|b| b.name.clone())
+ .collect()
+ })
+ .unwrap_or_default();
+ let summaries_enabled = self.llm_command.is_some();
+
// Header row — non-selectable via `header_lines(1)` on the options.
+ // In `--prs` mode it shows a dim "loading open PRs…" line (in place of
+ // the column labels) until the forge call's rows land — wording mirrors
+ // the empty-list "No open PRs found".
+ let loading = self.prs_loading.as_ref().map(|pending| {
+ let noun = super::prs::forge_noun(self.orchestrator.repo());
+ HeaderLoading {
+ pending: Arc::clone(pending),
+ marker_ansi: cformat!(" <dim>loading open {noun}…</>"),
+ }
+ });
skim_items.push(Arc::new(HeaderSkimItem {
display_text: header.plain_text(),
display_text_with_ansi: header.render(),
+ loading,
}) as Arc<dyn SkimItem>);
for (item, rendered_line) in items.into_iter().zip(rendered) {
let branch_name = item.branch_name().to_string();
+ let has_upstream = upstream_branches.contains(&branch_name);
let path_str = item
.worktree_path()
.map(|p| p.to_string_lossy().into_owned())
@@ -155,12 +209,21 @@ impl PickerProgressHandler for PickerHandler {
let item_arc = Arc::new(item);
list_items.push(Arc::clone(&item_arc));
+ // Prime the live slot from the (cache-filled) snapshot so the `pr`
+ // tab paints instantly; `on_update` overwrites it as the CiStatus
+ // task reports.
+ let pr_status_arc: PrStatusSlot = Arc::new(Mutex::new(item_arc.pr_status.clone()));
+ pr_slots.push(Arc::clone(&pr_status_arc));
+
skim_items.push(Arc::new(WorktreeSkimItem {
search_text,
rendered: rendered_arc,
branch_name,
item: item_arc,
preview_cache: Arc::clone(&self.preview_cache),
+ has_upstream,
+ summaries_enabled,
+ pr_status: pr_status_arc,
}) as Arc<dyn SkimItem>);
}
@@ -168,6 +231,7 @@ impl PickerProgressHandler for PickerHandler {
// (which reads `shared_items`) sees a populated list the moment
// skim calls `CommandCollector::invoke`.
let _ = self.rendered_slots.set(slots.into_boxed_slice());
+ let _ = self.pr_status_slots.set(pr_slots.into_boxed_slice());
*self.shared_items.lock().unwrap() = skim_items.clone();
// skim 4.x's item channel carries Vec batches; the skeleton is a single
@@ -200,12 +264,20 @@ impl PickerProgressHandler for PickerHandler {
let _ = self.deferred_items.set(list_items);
}
- fn on_update(&self, idx: usize, rendered: String) {
+ fn on_update(&self, idx: usize, rendered: String, item: &ListItem) {
if let Some(slots) = self.rendered_slots.get()
&& let Some(slot) = slots.get(idx)
{
*slot.lock().unwrap() = strip_osc8_hyperlinks(&rendered);
}
+ // Mirror the row's current CI status into its live slot so the `pr`
+ // tab reflects the fetch as it lands. Cheap clone; `pr_status` is
+ // `None` until the CiStatus task reports, then `Some(..)`.
+ if let Some(slots) = self.pr_status_slots.get()
+ && let Some(slot) = slots.get(idx)
+ {
+ *slot.lock().unwrap() = item.pr_status.clone();
+ }
self.request_render(false);
}
@@ -260,6 +332,7 @@ mod tests {
last_render_poke: Mutex::new(Instant::now()),
shared_items,
rendered_slots: OnceLock::new(),
+ pr_status_slots: OnceLock::new(),
preview_cache,
orchestrator,
preview_dims: (80, 24),
@@ -267,6 +340,8 @@ mod tests {
summary_hint: Some("disabled".to_string()),
stashed_warnings: Arc::new(Mutex::new(Vec::new())),
deferred_items: OnceLock::new(),
+ grid_slot: Arc::new(super::super::prs::GridSlot::new()),
+ prs_loading: None,
};
(handler, test, rx)
}
@@ -277,6 +352,10 @@ mod tests {
line
}
+ fn grid() -> crate::commands::list::layout::ColumnGrid {
+ crate::commands::list::layout::ColumnGrid::default()
+ }
+
/// Skeleton → update → reveal: verifies that each event writes through
/// to the shared `rendered` string the `WorktreeSkimItem` holds. Skim
/// reads these strings each time it repaints (which `request_render`
@@ -290,7 +369,7 @@ mod tests {
];
let rendered = vec!["skel-one".to_string(), "skel-two".to_string()];
- handler.on_skeleton(items, rendered, header("hdr"));
+ handler.on_skeleton(items, rendered, header("hdr"), grid());
// Header + 2 items sent to skim as one batch.
let received = rx.recv().expect("skeleton batch");
@@ -301,10 +380,26 @@ mod tests {
assert_eq!(*slots[0].lock().unwrap(), "skel-one");
assert_eq!(*slots[1].lock().unwrap(), "skel-two");
- // on_update rewrites a single slot (the second item here).
- handler.on_update(1, "updated-two".into());
+ // pr_status slots start primed from the (empty) snapshots.
+ let pr_slots = handler.pr_status_slots.get().unwrap();
+ assert!(pr_slots[0].lock().unwrap().is_none());
+ assert!(pr_slots[1].lock().unwrap().is_none());
+
+ // on_update rewrites a single render slot (the second item here) and
+ // mirrors that item's CI status into its pr_status slot.
+ let mut updated = ListItem::new_branch("bbb".into(), "two".into());
+ updated.pr_status = Some(None);
+ handler.on_update(1, "updated-two".into(), &updated);
assert_eq!(*slots[0].lock().unwrap(), "skel-one", "row 0 untouched");
assert_eq!(*slots[1].lock().unwrap(), "updated-two");
+ assert!(
+ matches!(&*pr_slots[1].lock().unwrap(), Some(None)),
+ "row 1 pr status mirrored from the updated item"
+ );
+ assert!(
+ pr_slots[0].lock().unwrap().is_none(),
+ "row 0 pr status untouched"
+ );
// on_reveal rewrites every slot — slot writes are idempotent
// through `Mutex<String>`, so unconditional updates are safe.
@@ -328,6 +423,7 @@ mod tests {
items,
vec!["skel-a".into(), "skel-b".into()],
header("Branch Status"),
+ grid(),
);
let received = rx.recv().expect("skeleton batch");
@@ -360,6 +456,7 @@ mod tests {
items,
vec!["skel-local".into(), "skel-remote".into()],
header("hdr"),
+ grid(),
);
let received = rx.recv().expect("skeleton batch");
@@ -464,7 +561,7 @@ mod tests {
];
let rendered = vec!["s1".into(), "s2".into(), "s3".into()];
- handler.on_skeleton(items, rendered, header("hdr"));
+ handler.on_skeleton(items, rendered, header("hdr"), grid());
handler.orchestrator.wait_for_idle();
// Static Summary hint primed for every item at skeleton time.
@@ -557,7 +654,7 @@ mod tests {
// left to defer; on_collect_complete must not add any entries.
let (handler, _test, _rx) = make_handler();
let items = vec![ListItem::new_branch("aaa".into(), "solo".into())];
- handler.on_skeleton(items, vec!["s1".into()], header("hdr"));
+ handler.on_skeleton(items, vec!["s1".into()], header("hdr"), grid());
handler.orchestrator.wait_for_idle();
let before = handler.preview_cache.iter().count();
for mode in [
diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rs
new file mode 100644
index 000000000..d2e718a1e
--- /dev/null
+++ b/src/commands/picker/prs.rs
@@ -0,0 +1,1278 @@
+//! Open PR/MR picker source (`wt switch --prs`).
+//!
+//! Widens the interactive picker with the repository's open pull requests
+//! (GitHub) or merge requests (GitLab). Each row's `output()` is the
+//! `pr:{N}` / `mr:{N}` shortcut, so selection routes through the exact same
+//! [`SwitchPipeline`](super::super::worktree::SwitchPipeline) as
+//! `wt switch pr:{N}` — fetch the ref, switch to its branch. No new switch
+//! logic: the shortcut parsing in `commands::worktree::switch` already
+//! resolves both same-repo and fork PRs/MRs.
+//!
+//! # Streaming
+//!
+//! The list is a single forge call (`gh pr list` / `glab mr list`) run on a
+//! dedicated thread that holds a clone of skim's item channel. The picker
+//! frame paints instantly from local worktree data; PR rows appear when the
+//! call returns (~1s). The thread's sender drop is part of the picker's
+//! EOF contract — skim's reader sees end-of-stream only once every sender
+//! drops — see [`super::handle_picker`].
+//!
+//! # Alignment
+//!
+//! PR rows render on the same column grid as the worktree rows: a dim `#`
+//! gutter sigil (see [`PR_GUTTER_SIGIL`]), the head branch in the Branch
+//! column, and the number — in the CI column when the layout has one, else
+//! just after the branch so it never hides. The PR title and author have no
+//! worktree-column equivalent, so they stay off the row (in the `pr` preview
+//! tab) rather than misaligning the grid — see [`render_grid_row`]. The geometry
+//! ([`ColumnGrid`]) is computed by the collect thread at skeleton time and
+//! handed over through a [`GridSlot`]; the skeleton (~50ms) beats the forge
+//! call (~1s), so the wait is nominal. Without a grid (handoff timed out, or
+//! collect never produced a skeleton) rows fall back to a freeform line.
+//!
+//! # Scope
+//!
+//! GitHub and GitLab only. Gitea and Azure DevOps support `pr:{N}` for a
+//! single known number but have no listing path here yet.
+
+use std::borrow::Cow;
+use std::path::Path;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Condvar, Mutex, OnceLock};
+use std::time::Duration;
+
+use anstyle::{Reset, Style};
+use anyhow::Context;
+use color_print::cformat;
+use ratatui::text::Line;
+use serde::Deserialize;
+use skim::prelude::*;
+use unicode_width::UnicodeWidthStr;
+use worktrunk::git::{CiPlatform, Repository};
+use worktrunk::styling::{INFO_SYMBOL, StyledLine, format_with_gutter, warning_message};
+
+use super::super::list::ci_status::{
+ CiSource, CiStatus, GitHubPrInfo, PrRef, PrStatus, ReviewState, non_interactive_cmd,
+ tool_available,
+};
+use super::super::list::columns::ColumnKind;
+use super::super::list::layout::ColumnGrid;
+use super::items::{TabAvailability, ansi_to_line, render_preview_tabs};
+use super::preview::{PreviewMode, PreviewStateData};
+
+/// One-shot handoff of the picker's column geometry from the collect thread
+/// (which computes the layout at skeleton time) to the `--prs` thread (which
+/// renders rows once the forge call returns). First write wins — an alt-r
+/// reload re-fires the skeleton at the same width, so later grids are
+/// identical.
+pub(super) struct GridSlot {
+ grid: Mutex<Option<ColumnGrid>>,
+ ready: Condvar,
+}
+
+impl GridSlot {
+ pub(super) fn new() -> Self {
+ Self {
+ grid: Mutex::new(None),
+ ready: Condvar::new(),
+ }
+ }
+
+ pub(super) fn set(&self, grid: ColumnGrid) {
+ let mut slot = self.grid.lock().unwrap();
+ if slot.is_none() {
+ *slot = Some(grid);
+ }
+ self.ready.notify_all();
+ }
+
+ /// Block until the grid is set or `timeout` elapses. The timeout covers
+ /// collect exiting without a skeleton (zero items, error) — the rows
+ /// then render freeform rather than never.
+ fn wait(&self, timeout: Duration) -> Option<ColumnGrid> {
+ let (slot, _) = self
+ .ready
+ .wait_timeout_while(self.grid.lock().unwrap(), timeout, |grid| grid.is_none())
+ .unwrap();
+ slot.clone()
+ }
+}
+
+/// Open PRs/MRs to list. One page is one API call; 50 covers any repo a human
+/// browses interactively without paginating.
+const MAX_PRS: u8 = 50;
+
+/// Gutter sigil for a `--prs` row — a PR/MR with no local branch or worktree.
+/// `#` completes the picker's gutter scheme alongside worktree rows
+/// (`@`/`^`/`+`) and branch rows (`/` local, `|` remote — see
+/// `BranchScope::gutter_sigil`), rendered dim and single-width ASCII to match
+/// them and dodge skim's `width_cjk` clipping. The trailing space pads the
+/// 2-cell gutter column.
+const PR_GUTTER_SIGIL: &str = "# ";
+
+/// Whether a listed ref is a GitHub PR or a GitLab MR. Drives the `output()`
+/// shortcut (`pr:`/`mr:`) and the row label.
+#[derive(Clone, Copy)]
+enum RefKind {
+ Pr,
+ Mr,
+}
+
+impl RefKind {
+ /// Shortcut prefix understood by `wt switch` (`pr` / `mr`).
+ fn shortcut(self) -> &'static str {
+ match self {
+ RefKind::Pr => "pr",
+ RefKind::Mr => "mr",
+ }
+ }
+}
+
+/// One open PR/MR, normalized across forges for the picker row.
+struct PrEntry {
+ number: u32,
+ title: String,
+ head_branch: String,
+ author: String,
+ is_draft: bool,
+ url: Option<String>,
+ kind: RefKind,
+ /// PR/MR description (GitHub `body`, GitLab `description`), rendered as
+ /// markdown in the `pr` preview tab. Rides the one list call — empty when
+ /// the forge returns no body.
+ body: String,
+ /// CI + review status for the CI column, built from the same forge call.
+ /// `None` when the forge can't supply it in one call (the row then keeps
+ /// its `#N` in the title instead of the CI column).
+ status: Option<PrStatus>,
+}
+
+impl PrEntry {
+ /// The forge-correct reference: `#N` on GitHub, `!N` on GitLab. Shared by
+ /// the row and preview renderers so both pick the sigil from one place.
+ fn pr_ref(&self) -> PrRef {
+ match self.kind {
+ RefKind::Pr => PrRef::pr(u64::from(self.number)),
+ RefKind::Mr => PrRef::mr(u64::from(self.number)),
+ }
+ }
+}
+
+/// Stream the open PRs/MRs into the picker, then clear the header's "loading…"
+/// marker — whatever the outcome.
+///
+/// The forge call drives [`fetch_and_stream`]; this wrapper owns the marker so
+/// every exit (rows sent, no PRs, or error) drops it and repaints. The
+/// success path's row send already wakes skim, but the empty/error paths send
+/// nothing, so without the poke the marker would linger until the next
+/// keystroke.
+pub(super) fn stream_open_prs(
+ repo: &Repository,
+ list_width: usize,
+ tx: &SkimItemSender,
+ stashed_warnings: &Mutex<Vec<String>>,
+ grid_slot: &GridSlot,
+ prs_loading: &AtomicBool,
+ render_tx: &OnceLock<tokio::sync::mpsc::Sender<Event>>,
+) {
+ fetch_and_stream(repo, list_width, tx, stashed_warnings, grid_slot);
+
+ prs_loading.store(false, Ordering::Relaxed);
+ if let Some(tx) = render_tx.get() {
+ let _ = tx.try_send(Event::Render);
+ }
+}
+
+/// Fetch open PRs/MRs, build picker rows, and stream them into skim.
+///
+/// On failure (forge unsupported, CLI missing/unauthenticated, network error)
+/// the reason is stashed for display after skim releases the terminal — the
+/// picker stays usable with its worktree rows.
+fn fetch_and_stream(
+ repo: &Repository,
+ list_width: usize,
+ tx: &SkimItemSender,
+ stashed_warnings: &Mutex<Vec<String>>,
+ grid_slot: &GridSlot,
+) {
+ let entries = match fetch_open_prs(repo) {
+ Ok(entries) => entries,
+ Err(e) => {
+ stashed_warnings
+ .lock()
+ .unwrap()
+ .push(warning_message(format!("{e:#}")).to_string());
+ return;
+ }
+ };
+
+ if entries.is_empty() {
+ let noun = forge_noun(repo);
+ stashed_warnings
+ .lock()
+ .unwrap()
+ .push(warning_message(format!("No open {noun} found")).to_string());
+ return;
+ }
+
+ // The forge call above (~1s) almost always outlasts the skeleton
+ // (~50ms), so this returns immediately; the wait covers a mocked forge
+ // CLI winning the race.
+ let grid = grid_slot.wait(Duration::from_secs(5));
+
+ // skim 4.x takes a batch per send; the forge call already returned every
+ // row, so stream them in one shot.
+ let items: Vec<Arc<dyn SkimItem>> = entries
+ .into_iter()
+ .map(|entry| {
+ Arc::new(PrSkimItem::new(entry, list_width, grid.as_ref())) as Arc<dyn SkimItem>
+ })
+ .collect();
+ let _ = tx.send(items);
+}
+
+/// Plural noun for the forge's change-request — "PRs" on GitHub, "MRs" on
+/// GitLab. Used for the empty-list message and the header "loading…" marker,
+/// where there's no entry to read the kind from.
+pub(super) fn forge_noun(repo: &Repository) -> &'static str {
+ match repo.ci_platform(None) {
+ Some(CiPlatform::GitLab) => "MRs",
+ _ => "PRs",
+ }
+}
+
+/// Dispatch to the forge that hosts this repository's primary remote.
+fn fetch_open_prs(repo: &Repository) -> anyhow::Result<Vec<PrEntry>> {
+ let repo_root = repo
+ .current_worktree()
+ .root()
+ .context("Failed to resolve worktree root for --prs")?;
+
+ match repo.ci_platform(None) {
+ Some(CiPlatform::GitHub) => fetch_github(&repo_root),
+ Some(CiPlatform::GitLab) => fetch_gitlab(&repo_root),
+ Some(other) => {
+ anyhow::bail!("--prs supports GitHub and GitLab; this repository's forge is {other}")
+ }
+ None => anyhow::bail!("--prs could not determine the forge from the remote URL"),
+ }
+}
+
+#[derive(Deserialize)]
+struct GhPr {
+ title: String,
+ #[serde(rename = "headRefName")]
+ head_ref_name: String,
+ #[serde(default)]
+ author: GhAuthor,
+ /// PR description; shown in the `pr` preview tab. Rides the one list call.
+ #[serde(default)]
+ body: String,
+ /// CI/review fields reused via the shared `gh pr list` mapping: number,
+ /// `isDraft`, `url`, `statusCheckRollup`, `reviewDecision`,
+ /// `mergeStateStatus`. Flattened so one parse feeds both display and the
+ /// CI-column status.
+ #[serde(flatten)]
+ info: GitHubPrInfo,
+}
+
+#[derive(Deserialize, Default)]
+struct GhAuthor {
+ #[serde(default)]
+ login: String,
+}
+
+fn fetch_github(repo_root: &Path) -> anyhow::Result<Vec<PrEntry>> {
+ if !tool_available("gh", &["--version"]) {
+ anyhow::bail!("gh CLI not found; install gh to browse PRs with --prs");
+ }
+
+ let output = non_interactive_cmd("gh")
+ .args([
+ "pr",
+ "list",
+ "--state",
+ "open",
+ "--limit",
+ &MAX_PRS.to_string(),
+ "--json",
+ // CI/review fields and the description ride the one call; no extra round-trip.
+ "number,title,headRefName,author,isDraft,url,body,statusCheckRollup,reviewDecision,mergeStateStatus",
+ ])
+ .current_dir(repo_root)
+ .run()
+ .context("Failed to run gh pr list")?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("gh pr list failed: {}", stderr.trim());
+ }
+
+ parse_github_prs(&output.stdout)
+}
+
+/// Map `gh pr list --json …` output to picker entries.
+fn parse_github_prs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {
+ let prs: Vec<GhPr> =
+ serde_json::from_slice(stdout).context("Failed to parse gh pr list JSON")?;
+
+ Ok(prs
+ .into_iter()
+ .map(|pr| PrEntry {
+ number: pr.info.number.unwrap_or(0) as u32,
+ title: pr.title,
+ head_branch: pr.head_ref_name,
+ author: pr.author.login,
+ is_draft: pr.info.is_draft == Some(true),
+ url: pr.info.url.clone(),
+ kind: RefKind::Pr,
+ body: pr.body,
+ status: Some(pr.info.open_pr_status()),
+ })
+ .collect())
+}
+
+#[derive(Deserialize)]
+struct GlabMr {
+ iid: u32,
+ title: String,
+ #[serde(default)]
+ source_branch: String,
+ #[serde(default)]
+ author: GlabAuthor,
+ #[serde(default)]
+ draft: bool,
+ #[serde(default)]
+ web_url: Option<String>,
+ /// MR description; shown in the `pr` preview tab. Rides the one list call.
+ #[serde(default)]
+ description: String,
+ /// Coarse merge/CI signal the list call carries (full pipeline status
+ /// needs a per-MR `glab mr view`, which `--prs` avoids).
+ #[serde(default)]
+ detailed_merge_status: Option<String>,
+}
+
+#[derive(Deserialize, Default)]
+struct GlabAuthor {
+ #[serde(default)]
+ username: String,
+}
+
+fn fetch_gitlab(repo_root: &Path) -> anyhow::Result<Vec<PrEntry>> {
+ if !tool_available("glab", &["--version"]) {
+ anyhow::bail!("glab CLI not found; install glab to browse MRs with --prs");
+ }
+
+ let output = non_interactive_cmd("glab")
+ .args([
+ "mr",
+ "list",
+ "--per-page",
+ &MAX_PRS.to_string(),
+ "--output",
+ "json",
+ ])
+ .current_dir(repo_root)
+ .run()
+ .context("Failed to run glab mr list")?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("glab mr list failed: {}", stderr.trim());
+ }
+
+ parse_gitlab_mrs(&output.stdout)
+}
+
+/// Map `glab mr list --output json` output to picker entries.
+fn parse_gitlab_mrs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {
+ let mrs: Vec<GlabMr> =
+ serde_json::from_slice(stdout).context("Failed to parse glab mr list JSON")?;
+
+ Ok(mrs
+ .into_iter()
+ .map(|mr| {
+ let status = gitlab_mr_status(
+ mr.iid,
+ mr.draft,
+ mr.detailed_merge_status.as_deref(),
+ mr.web_url.clone(),
+ );
+ PrEntry {
+ number: mr.iid,
+ title: mr.title,
+ head_branch: mr.source_branch,
+ author: mr.author.username,
+ is_draft: mr.draft,
+ url: mr.web_url,
+ kind: RefKind::Mr,
+ body: mr.description,
+ status: Some(status),
+ }
+ })
+ .collect())
+}
+
+/// Best-effort MR status from the single `glab mr list` call. The list payload
+/// carries `draft` and `detailed_merge_status` but not pipeline detail (that
+/// needs a per-MR `glab mr view`, which `--prs` avoids), so CI is coarse:
+/// conflicts and a still-running merge pipeline are the only states the list
+/// reports. `not_approved` maps to a pending review; draft outranks it.
+fn gitlab_mr_status(
+ iid: u32,
+ draft: bool,
+ detailed_merge_status: Option<&str>,
+ url: Option<String>,
+) -> PrStatus {
+ let ci_status = match detailed_merge_status {
+ Some("broken_status") | Some("conflict") => CiStatus::Conflicts,
+ Some("ci_still_running") => CiStatus::Running,
+ _ => CiStatus::NoCI,
+ };
+ let review_state = if draft {
+ Some(ReviewState::Draft)
+ } else if detailed_merge_status == Some("not_approved") {
+ Some(ReviewState::Pending)
+ } else {
+ None
+ };
+ PrStatus {
+ ci_status,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ is_priming: false,
+ url,
+ number: Some(PrRef::mr(u64::from(iid))),
+ review_state,
+ }
+}
+
+/// A picker row for one open PR/MR. Distinct from `WorktreeSkimItem`: it
+/// carries no `ListItem` and resolves to a `pr:`/`mr:` shortcut rather than a
+/// branch or worktree path.
+pub(super) struct PrSkimItem {
+ /// What skim's fuzzy matcher sees: kind, number, title, branch, author.
+ search_text: String,
+ /// ANSI-colored display line — cells on the worktree rows' column grid,
+ /// or a freeform line when no grid is available.
+ rendered: String,
+ /// Selection result — the `pr:{N}` / `mr:{N}` shortcut. Routed verbatim
+ /// through `resolve_identifier` → `SwitchPipeline`.
+ output_token: String,
+ /// The tab-6 (`pr`) pane: PR/MR metadata and web URL, built once at
+ /// construction from already-fetched data. A `--prs` row has no local
+ /// worktree, so tabs 1-5 render an empty placeholder instead.
+ pr_pane: String,
+}
+
+impl PrSkimItem {
+ fn new(entry: PrEntry, list_width: usize, grid: Option<&ColumnGrid>) -> Self {
+ let label = entry.kind.shortcut();
+ let output_token = format!("{label}:{}", entry.number);
+
+ // Trailing gutter glyph (the `#` from `PR_GUTTER_SIGIL`, sans pad) so
+ // typing `#` filters to PR/MR rows, matching how the worktree/branch
+ // rows fold their sigil in (see `progressive_handler` `on_skeleton`).
+ let gutter = PR_GUTTER_SIGIL.trim_end();
+ let search_text = format!(
+ "{label} {} {} {} {} {gutter}",
+ entry.number, entry.title, entry.head_branch, entry.author
+ );
+
+ let rendered = match grid {
+ Some(grid) => render_grid_row(&entry, grid, list_width),
+ None => render_freeform_row(&entry, list_width),
+ };
+
+ let pr_ref = entry.pr_ref();
+ let PrEntry {
+ title,
+ head_branch,
+ author,
+ is_draft,
+ url,
+ body,
+ ..
+ } = entry;
+ // A full `{reset}` (\x1b[0m) closes every styled span: skim's ANSI
+ // parser drops color_print's `</>` (SGR 22/39), so without it the
+ // header's bold and each label's dim bleed across the values and on
+ // down the pane. Same workaround as `pr_row_empty_placeholder` and the
+ // `compute_*` preview helpers; see `render_preview_tabs` for the why.
+ let reset = Reset;
+ let mut pr_pane = cformat!(
+ "<bold>{pr_ref}</>{reset} {title}\n\n<dim>branch</>{reset} {head_branch}\n<dim>author</>{reset} @{author}\n"
+ );
+ if is_draft {
+ pr_pane.push_str(&cformat!(
+ "<dim>state</>{reset} <yellow>draft</>{reset}\n"
+ ));
+ }
+ if let Some(url) = url {
+ pr_pane.push_str(&cformat!("<dim>url</>{reset} {url}\n"));
+ }
+ pr_pane.push_str(&render_pr_description(&body, list_width));
+
+ Self {
+ search_text,
+ rendered,
+ output_token,
+ pr_pane,
+ }
+ }
+}
+
+/// The PR/MR description block for the `pr` preview pane: the body rendered as
+/// markdown (bold headers, styled lists and inline code — the same renderer the
+/// `summary` tab uses) and quoted in the house gutter ([`format_with_gutter`],
+/// a bg-color bar that closes each line with a full `\x1b[0m`, skim-safe). The
+/// whole body renders; the preview pane scrolls (`ctrl-u`/`ctrl-d`) through a
+/// long one. Empty body → empty string, so the block is skipped. The leading
+/// `\x1b[0m` is a defensive boundary so the first gutter line renders clean
+/// regardless of what precedes it (the metadata lines already reset their own
+/// spans).
+///
+/// `width` is the list width, a close proxy for the preview pane width in both
+/// layouts (Right splits ~50/50; Down gives list and preview the full width).
+/// The markdown wraps to the gutter's inner width (the bar plus its pad take
+/// two columns) so the gutter's own wrap is a no-op rather than re-breaking the
+/// already-styled lines.
+fn render_pr_description(body: &str, width: usize) -> String {
+ let body = body.trim();
+ if body.is_empty() {
+ return String::new();
+ }
+ let reset = Reset;
+ let rendered =
+ crate::md_help::render_markdown_in_help_with_width(body, Some(width.saturating_sub(2)));
+ let gutter = format_with_gutter(&rendered, Some(width));
+ format!("\n{reset}{gutter}\n")
+}
+
+/// The pane for tabs 1-5 on a `--prs` row. The head branch isn't checked out
+/// locally, so there's no working tree / log / diff to show — point the user
+/// at the `pr` tab, which holds the PR/MR metadata.
+fn pr_row_empty_placeholder() -> String {
+ let reset = Reset;
+ cformat!(
+ "{INFO_SYMBOL}{reset} Not checked out locally — press <bold>alt-6</>{reset} for PR details, Enter to fetch & switch\n"
+ )
+}
+
+/// Place the PR's cells on the worktree rows' grid so every column lines up:
+/// a dim `#` gutter sigil (see `PR_GUTTER_SIGIL`), the head branch in the
+/// Branch column, and the number.
+///
+/// The number is the row's identity, so it always shows. With a CI column it
+/// rides there, colored by CI + review state like worktree rows' PR numbers
+/// (`format_cell`). The picker only allocates a CI column when some worktree
+/// row had a cached status, so without one — a repo with no CI cache — the
+/// number falls back to a dim reference just after the Branch column rather
+/// than hiding.
+///
+/// The PR title and author are NOT on the row — they have no worktree-column
+/// equivalent, so showing them would either misalign PR rows against worktree
+/// rows or overrun the status columns. They live in the `pr` preview tab
+/// instead (see `PrSkimItem::pr_pane`); the title still feeds `search_text`, so
+/// fuzzy matching on it works even though it isn't displayed. The other
+/// worktree-data columns PR rows leave blank (status, diffs, URL, age) are a
+/// follow-up — see TODO(pr-row-columns).
+fn render_grid_row(entry: &PrEntry, grid: &ColumnGrid, list_width: usize) -> String {
+ let dim = Style::new().dimmed();
+ let mut segments: Vec<(usize, StyledLine)> = Vec::new();
+
+ if let Some(col) = grid.column(ColumnKind::Gutter) {
+ let mut cell = StyledLine::new();
+ cell.push_styled(PR_GUTTER_SIGIL, dim);
+ segments.push((col.start, cell));
+ }
+
+ let branch_col = grid.column(ColumnKind::Branch);
+ if let Some(col) = branch_col {
+ let mut cell = StyledLine::new();
+ cell.push_raw(entry.head_branch.clone());
+ segments.push((col.start, cell.truncate_to_width(col.width)));
+ }
+
+ match grid.column(ColumnKind::CiStatus).zip(entry.status.as_ref()) {
+ Some((col, status)) => {
+ let mut cell = StyledLine::new();
+ cell.push_raw(status.format_cell(col.width, false));
+ segments.push((col.start, cell));
+ }
+ None => {
+ // No CI column — show the dim reference after the branch so the
+ // number never hides.
+ let start = branch_col.map_or(0, |col| col.start + col.width + 2);
+ let mut cell = StyledLine::new();
+ cell.push_styled(entry.pr_ref().to_string(), dim);
+ segments.push((
+ start,
+ cell.truncate_to_width(list_width.saturating_sub(start)),
+ ));
+ }
+ }
+
+ // All cells sit in fixed columns within the pane (branch truncates to its
+ // column, the number is fixed-width), so the row can't overflow.
+ segments.sort_by_key(|(start, _)| *start);
+ let mut line = StyledLine::new();
+ for (start, cell) in segments {
+ line.pad_to(start);
+ line.extend(cell);
+ }
+ line.render()
+}
+
+/// Freeform row for when no grid is available: `#N branch`. Like the grid row,
+/// the title and author live only in the preview; the `pr_ref` already carries
+/// the `#`/`!` sigil, so no separate gutter marker is needed.
+fn render_freeform_row(entry: &PrEntry, list_width: usize) -> String {
+ let pr_ref = entry.pr_ref();
+ let prefix_plain = format!("{pr_ref} ");
+ let branch_budget = list_width.saturating_sub(prefix_plain.width()).max(8);
+ let head_branch = crate::display::truncate_to_width(&entry.head_branch, branch_budget);
+ cformat!("<bold>{pr_ref}</> <cyan>{head_branch}</>")
+}
+
+// TODO(pr-row-columns): fill the worktree-data columns PR rows leave blank.
+// The status, branch-diff, and age columns have no PR equivalent in the
+// `gh pr list` / `glab mr list` payload today, but some map cleanly: the PR's
+// CI conclusion could drive a status glyph, and the PR's age its own column.
+// Each needs a field added to the row-list `--json` (cheap, one call) or a
+// derived value — keep them off the flexible region so the grid stays aligned.
+//
+// TODO(pr-preview-log): give the `log` tab (and ideally `summary`) content on
+// `--prs` rows. The body/description rides the one `gh pr list` call cheaply,
+// but a commit log does not: for a checked-out branch it's a local `git log`,
+// but a `--prs` head branch isn't fetched, so the commits need either a fetch
+// or `gh pr view <n> --json commits` / `glab mr view`. That payload is too
+// heavy to fold into the row-list call (commits for ~50 PRs), so it must load
+// in the background per row — which `--prs` rows don't do yet: today the whole
+// row, `pr_pane` included, is built once when the list call returns. The
+// mechanism would mirror the worktree rows' `PreviewOrchestrator` cache: a
+// shared map the `preview()` callback reads, populated off-thread, with a
+// "loading…" placeholder on a miss (skim re-queries on selection/tab change).
+// Remote-branch rows (`--remotes`) are the cheap half — their commits are
+// already fetched, so their `log` tab is a plain local `git log`.
+//
+// TODO(pr-preview-comments): add a `7: comments` tab showing the PR/MR
+// discussion, rendered with the house gutter per comment (author + body, like
+// `render_pr_description`). Needs the same background per-row fetch as the log
+// (`gh pr view <n> --json comments`), and a 7th tab widens the preview tab bar
+// — already ~63 cols with six numbered tabs — so it clips sooner on narrow
+// (≤~125-col, Right-layout) previews. Weigh an abbreviated/scrolling tab bar
+// alongside it.
+impl SkimItem for PrSkimItem {
+ fn text(&self) -> Cow<'_, str> {
+ Cow::Borrowed(&self.search_text)
+ }
+
+ fn display(&self, _context: DisplayContext) -> Line<'_> {
+ ansi_to_line(&self.rendered)
+ }
+
+ fn output(&self) -> Cow<'_, str> {
+ Cow::Borrowed(&self.output_token)
+ }
+
+ fn preview(&self, _context: PreviewContext<'_>) -> ItemPreview {
+ // Share the worktree rows' tab bar. A `--prs` row has content only on
+ // the `pr` tab (tabs 1-5 empty → de-emphasized); the active tab is the
+ // same global digit, so an empty tab shows the placeholder until the
+ // user presses alt-6 / Tab.
+ let mode = PreviewStateData::read_mode();
+ let mut result = render_preview_tabs(mode, TabAvailability::pull_request());
+ if mode == PreviewMode::Pr {
+ result.push_str(&self.pr_pane);
+ } else {
+ result.push_str(&pr_row_empty_placeholder());
+ }
+ ItemPreview::AnsiText(result)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(kind: RefKind, number: u32, title: &str) -> PrEntry {
+ let number_ref = match kind {
+ RefKind::Pr => PrRef::pr(u64::from(number)),
+ RefKind::Mr => PrRef::mr(u64::from(number)),
+ };
+ PrEntry {
+ number,
+ title: title.to_string(),
+ head_branch: "feature/auth".to_string(),
+ author: "alice".to_string(),
+ is_draft: false,
+ url: Some("https://github.com/owner/repo/pull/123".to_string()),
+ kind,
+ body: String::new(),
+ status: Some(PrStatus {
+ ci_status: CiStatus::Passed,
+ source: CiSource::PullRequest,
+ is_stale: false,
+ is_priming: false,
+ url: None,
+ number: Some(number_ref),
+ review_state: None,
+ }),
+ }
+ }
+
+ /// Grid that includes a CI column (the picker's layout once CiStatus is no
+ /// longer skipped). Gutter 0–2, Branch 2–22, Status 24–32, CI 34–40.
+ fn grid_with_ci() -> ColumnGrid {
+ ColumnGrid {
+ columns: vec![
+ grid_col(ColumnKind::Gutter, 0, 2),
+ grid_col(ColumnKind::Branch, 2, 20),
+ grid_col(ColumnKind::Status, 24, 8),
+ grid_col(ColumnKind::CiStatus, 34, 6),
+ ],
+ }
+ }
+
+ #[test]
+ fn output_token_is_the_switch_shortcut() {
+ let pr = PrSkimItem::new(entry(RefKind::Pr, 123, "Fix the flaky test"), 120, None);
+ assert_eq!(pr.output(), "pr:123");
+
+ let mr = PrSkimItem::new(entry(RefKind::Mr, 7, "Add caching"), 120, None);
+ assert_eq!(mr.output(), "mr:7");
+ }
+
+ #[test]
+ fn search_text_covers_number_title_branch_author() {
+ let pr = PrSkimItem::new(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);
+ let text = pr.text();
+ assert!(text.contains("42"));
+ assert!(text.contains("Speed up startup"));
+ assert!(text.contains("feature/auth"));
+ assert!(text.contains("alice"));
+ // Gutter glyph folded in so `#` filters to PR/MR rows.
+ assert!(text.trim_end().ends_with('#'), "gutter glyph: {text:?}");
+ }
+
+ /// `#` is a plain literal under skim's default engine (unlike `^`/`|`), so
+ /// it filters to PR/MR rows and leaves worktree/branch rows out. Companion
+ /// to `progressive_handler`'s `gutter_glyphs_filter_under_skims_default_engine`.
+ #[test]
+ fn hash_sigil_filters_to_pr_rows_under_skims_default_engine() {
+ struct TextItem(String);
+ impl SkimItem for TextItem {
+ fn text(&self) -> Cow<'_, str> {
+ Cow::Borrowed(&self.0)
+ }
+ }
+ let matches = |haystack: &dyn SkimItem| -> bool {
+ AndOrEngineFactory::new(ExactOrFuzzyEngineFactory::builder().build())
+ .create_engine("#")
+ .match_item(haystack)
+ .is_some()
+ };
+
+ let pr = PrSkimItem::new(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);
+ assert!(matches(&pr), "# selects the PR row");
+ // A worktree-style row carries no `#` in its folded search_text.
+ assert!(
+ !matches(&TextItem("cur /tmp/cur @".into())),
+ "# must not match a worktree row"
+ );
+ }
+
+ #[test]
+ fn freeform_row_shows_reference_and_branch_only() {
+ // No grid: the freeform fallback shows reference and branch. The title
+ // and author have no column, so they stay off the row — but the title
+ // still feeds `search_text`.
+ let pr = PrSkimItem::new(entry(RefKind::Pr, 1, "Retry the flaky test"), 80, None);
+ let row = plain(&pr.rendered);
+ assert!(row.contains("feature/auth"), "branch on the row: {row:?}");
+ assert!(row.contains("#1"), "reference on the row: {row:?}");
+ assert!(
+ !row.contains("Retry the flaky test"),
+ "title stays off the row: {row:?}"
+ );
+ assert!(!row.contains("@alice"), "author stays off the row: {row:?}");
+ assert!(
+ pr.text().contains("Retry the flaky test"),
+ "title searchable"
+ );
+ }
+
+ #[test]
+ fn freeform_row_truncates_a_long_branch_to_the_pane() {
+ // The branch absorbs the remaining width after the reference and
+ // truncates so the row stays inside the pane.
+ let mut e = entry(RefKind::Pr, 1, "Title");
+ e.head_branch = "a-very-long-branch-name-that-would-otherwise-overflow".to_string();
+ let pr = PrSkimItem::new(e, 40, None);
+ let row = plain(&pr.rendered);
+ assert!(row.contains("#1"), "reference survives: {row:?}");
+ assert!(row.contains('…'), "branch truncated: {row:?}");
+ assert!(row.width() <= 40, "row within pane: {row:?}");
+ }
+
+ #[test]
+ fn draft_prs_are_flagged_in_the_preview() {
+ // The row carries no title or inline flag, so a draft shows in the pr
+ // pane (and, with a CI column, as the dimmed number — see
+ // `grid_row_with_ci_dims_drafts_instead_of_flagging_them`).
+ let mut e = entry(RefKind::Pr, 9, "WIP refactor");
+ e.is_draft = true;
+ let pr = PrSkimItem::new(e, 120, None);
+ assert!(pr.pr_pane.contains("draft"));
+ }
+
+ use super::super::super::list::layout::GridColumn;
+
+ fn grid_col(kind: ColumnKind, start: usize, width: usize) -> GridColumn {
+ GridColumn { kind, start, width }
+ }
+
+ /// Gutter 0–2, Branch 2–22, Status 24–32, Summary 34–64, Message 66–96 —
+ /// the shape `calculate_layout_with_width` produces for the picker.
+ fn grid() -> ColumnGrid {
+ ColumnGrid {
+ columns: vec![
+ grid_col(ColumnKind::Gutter, 0, 2),
+ grid_col(ColumnKind::Branch, 2, 20),
+ grid_col(ColumnKind::Status, 24, 8),
+ grid_col(ColumnKind::Summary, 34, 30),
+ grid_col(ColumnKind::Message, 66, 30),
+ ],
+ }
+ }
+
+ fn plain(rendered: &str) -> String {
+ use ansi_str::AnsiStr;
+ rendered.ansi_strip().to_string()
+ }
+
+ /// Display column where `needle` starts (unicode-width-aware, so an
+ /// earlier multi-byte ellipsis doesn't skew the position).
+ fn display_col(text: &str, needle: &str) -> usize {
+ let byte_idx = text
+ .find(needle)
+ .unwrap_or_else(|| panic!("{needle:?} not found in {text:?}"));
+ text[..byte_idx].width()
+ }
+
+ #[test]
+ fn grid_row_places_cells_on_layout_columns() {
+ // grid() has no CI column, so the number falls back to just after the
+ // Branch column (which ends at 22, so the reference lands at 24). The
+ // title and author stay off the row.
+ let pr = PrSkimItem::new(
+ entry(RefKind::Pr, 123, "Fix the flaky test"),
+ 120,
+ Some(&grid()),
+ );
+ let text = plain(&pr.rendered);
+ // The dim `#` gutter sigil sits at column 0; branch in the Branch column.
+ assert!(text.starts_with("# feature/auth"));
+ assert_eq!(display_col(&text, "feature/auth"), 2, "branch column");
+ assert_eq!(
+ display_col(&text, "#123"),
+ 24,
+ "number falls back to after the branch"
+ );
+ assert!(
+ !text.contains("Fix the flaky test"),
+ "no title on the row: {text:?}"
+ );
+ assert!(!text.contains("@alice"), "no author on the row: {text:?}");
+ }
+
+ #[test]
+ fn grid_row_truncates_long_branch_to_its_column() {
+ let mut e = entry(RefKind::Pr, 5, "Title");
+ e.head_branch = "a-very-long-branch-name-overflowing".to_string();
+ let pr = PrSkimItem::new(e, 120, Some(&grid_with_ci()));
+ let text = plain(&pr.rendered);
+ // The branch is shortened to its column; the number still lands in CI.
+ assert!(text.contains('…'));
+ assert_eq!(display_col(&text, "#5"), 34, "number in CI column");
+ }
+
+ #[test]
+ fn rows_use_the_forge_sigil_for_the_reference() {
+ // GitLab MRs render `!N`, not `#N` — matching `PrRef` everywhere else
+ // (the CI column, `wt list`). The CI-column number, freeform row, and
+ // preview all derive the sigil from `PrEntry::pr_ref`.
+ let mr = PrSkimItem::new(
+ entry(RefKind::Mr, 42, "Add caching"),
+ 120,
+ Some(&grid_with_ci()),
+ );
+ let row = plain(&mr.rendered);
+ assert!(row.contains("!42"), "grid row uses ! for MRs: {row:?}");
+ assert!(
+ !row.contains("#42"),
+ "grid row must not use # for MRs: {row:?}"
+ );
+ assert!(mr.pr_pane.contains("!42"), "preview uses ! for MRs");
+
+ let mr_freeform = PrSkimItem::new(entry(RefKind::Mr, 42, "Add caching"), 120, None);
+ assert!(
+ plain(&mr_freeform.rendered).contains("!42"),
+ "freeform row uses !"
+ );
+
+ // GitHub PRs keep `#N`.
+ let pr = PrSkimItem::new(
+ entry(RefKind::Pr, 42, "Add caching"),
+ 120,
+ Some(&grid_with_ci()),
+ );
+ assert!(
+ plain(&pr.rendered).contains("#42"),
+ "grid row uses # for PRs"
+ );
+ }
+
+ #[test]
+ fn grid_row_stays_within_the_list_pane() {
+ // Even with a long branch the row stays inside the pane: the branch
+ // truncates to its column and nothing flexible follows.
+ let no_flexible = ColumnGrid {
+ columns: vec![
+ grid_col(ColumnKind::Gutter, 0, 2),
+ grid_col(ColumnKind::Branch, 2, 20),
+ ],
+ };
+ let mut e = entry(RefKind::Pr, 1, "Title");
+ e.head_branch = "a-very-long-branch-name-that-runs-past-the-edge".to_string();
+ let pr = PrSkimItem::new(e, 60, Some(&no_flexible));
+ let text = plain(&pr.rendered);
+ assert!(text.width() <= 60);
+ // Skim's overflow check uses CJK widths, where the truncation `…`
+ // counts as 2 — the row must pass it too or skim repaints the last
+ // two columns as `..`.
+ assert!(text.width_cjk() <= 60);
+ }
+
+ #[test]
+ fn grid_row_places_the_number_in_the_ci_column() {
+ let pr = PrSkimItem::new(
+ entry(RefKind::Pr, 123, "Fix the flaky test"),
+ 120,
+ Some(&grid_with_ci()),
+ );
+ let text = plain(&pr.rendered);
+ // The number sits in the CI column (start 34), aligned with worktree
+ // rows; the title is not on the row at all.
+ assert_eq!(display_col(&text, "#123"), 34, "number in CI column");
+ assert!(!text.contains("Fix"), "title stays off the row: {text:?}");
+ }
+
+ #[test]
+ fn grid_row_omits_the_title_even_with_a_message_column() {
+ // The title stays off the row regardless of layout — even when a
+ // Message column (where worktree rows show their commit subject) is
+ // present, only the gutter, branch, and CI number land.
+ let grid = ColumnGrid {
+ columns: vec![
+ grid_col(ColumnKind::Gutter, 0, 2),
+ grid_col(ColumnKind::Branch, 2, 20),
+ grid_col(ColumnKind::CiStatus, 24, 6),
+ grid_col(ColumnKind::Message, 32, 40),
+ ],
+ };
+ let pr = PrSkimItem::new(
+ entry(RefKind::Pr, 42, "Retry the flaky test"),
+ 120,
+ Some(&grid),
+ );
+ let text = plain(&pr.rendered);
+ assert_eq!(display_col(&text, "feature/auth"), 2, "branch");
+ assert_eq!(display_col(&text, "#42"), 24, "number in CI column");
+ assert!(
+ !text.contains("Retry the flaky test"),
+ "title stays off the row: {text:?}"
+ );
+ }
+
+ #[test]
+ fn grid_row_dims_drafts_via_the_ci_number() {
+ // A draft shows only as the dimmed number in the CI column (review
+ // state Draft) — never as a "draft" word on the row.
+ let mut e = entry(RefKind::Pr, 9, "WIP");
+ e.is_draft = true;
+ if let Some(status) = e.status.as_mut() {
+ status.review_state = Some(ReviewState::Draft);
+ }
+ let pr = PrSkimItem::new(e, 120, Some(&grid_with_ci()));
+ let text = plain(&pr.rendered);
+ assert!(
+ !text.contains("draft"),
+ "no draft flag on the row: {text:?}"
+ );
+ assert_eq!(display_col(&text, "#9"), 34, "number still in CI column");
+ }
+
+ #[test]
+ fn parse_github_builds_ci_and_review_status() {
+ // statusCheckRollup → CI status; reviewDecision → review state; both
+ // ride the single `gh pr list` call.
+ let json = br#"[
+ {"number":10,"title":"t","headRefName":"b","statusCheckRollup":[{"status":"COMPLETED","conclusion":"SUCCESS"}],"reviewDecision":"APPROVED"}
+ ]"#;
+ let entries = parse_github_prs(json).unwrap();
+ let status = entries[0].status.as_ref().expect("status built");
+ assert_eq!(status.ci_status, CiStatus::Passed);
+ assert_eq!(status.review_state, Some(ReviewState::Approved));
+ assert_eq!(status.number.map(|r| r.to_string()).as_deref(), Some("#10"));
+ }
+
+ #[test]
+ fn parse_gitlab_builds_coarse_status_from_the_list_call() {
+ // The single `glab mr list` call carries draft + detailed_merge_status,
+ // not pipeline detail: draft dims, conflict reports Conflicts.
+ let json = br#"[
+ {"iid":3,"title":"t","source_branch":"b","draft":true,"detailed_merge_status":"conflict"}
+ ]"#;
+ let entries = parse_gitlab_mrs(json).unwrap();
+ let status = entries[0].status.as_ref().expect("status built");
+ assert_eq!(status.ci_status, CiStatus::Conflicts);
+ assert_eq!(status.review_state, Some(ReviewState::Draft));
+ assert_eq!(status.number.map(|r| r.to_string()).as_deref(), Some("!3"));
+ }
+
+ #[test]
+ fn parse_gitlab_running_pipeline_and_pending_review() {
+ // `ci_still_running` → Running CI; a non-draft `not_approved` MR maps to
+ // a pending review (draft would outrank it).
+ let json = br#"[
+ {"iid":4,"title":"t","source_branch":"b","draft":false,"detailed_merge_status":"ci_still_running"},
+ {"iid":5,"title":"t","source_branch":"b","draft":false,"detailed_merge_status":"not_approved"}
+ ]"#;
+ let entries = parse_gitlab_mrs(json).unwrap();
+ assert_eq!(
+ entries[0].status.as_ref().unwrap().ci_status,
+ CiStatus::Running
+ );
+ assert_eq!(
+ entries[1].status.as_ref().unwrap().review_state,
+ Some(ReviewState::Pending)
+ );
+ }
+
+ #[test]
+ fn parse_github_maps_fields_including_fork_author_and_draft() {
+ // Two PRs: one ready from a fork, one draft. Mirrors the
+ // `gh pr list --json number,title,headRefName,author,isDraft,url` shape.
+ let json = br#"[
+ {"number":2964,"title":"ci: freshen","headRefName":"fix/ci","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/o/r/pull/2964","body":"Bumps the CI image and re-pins actions."},
+ {"number":2969,"title":"wip","headRefName":"wip-branch","author":{"login":"forkuser"},"isDraft":true,"url":"https://github.com/o/r/pull/2969"}
+ ]"#;
+ let entries = parse_github_prs(json).unwrap();
+ assert_eq!(entries.len(), 2);
+
+ assert_eq!(entries[0].number, 2964);
+ assert_eq!(entries[0].title, "ci: freshen");
+ assert_eq!(entries[0].head_branch, "fix/ci");
+ assert_eq!(entries[0].author, "octocat");
+ assert!(!entries[0].is_draft);
+ assert!(matches!(entries[0].kind, RefKind::Pr));
+ assert_eq!(entries[0].body, "Bumps the CI image and re-pins actions.");
+
+ assert_eq!(entries[1].number, 2969);
+ assert!(entries[1].is_draft);
+ assert_eq!(entries[1].author, "forkuser");
+ // Absent `body` defaults to empty — the description block is skipped.
+ assert_eq!(entries[1].body, "");
+ }
+
+ #[test]
+ fn parse_github_tolerates_missing_optional_fields() {
+ // `author` can be absent (ghost user / deleted account); `url` and
+ // `isDraft` default. The row must still parse.
+ let json = br#"[{"number":1,"title":"t","headRefName":"b"}]"#;
+ let entries = parse_github_prs(json).unwrap();
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].author, "");
+ assert!(entries[0].url.is_none());
+ assert!(!entries[0].is_draft);
+ }
+
+ #[test]
+ fn parse_github_empty_list_is_empty() {
+ assert!(parse_github_prs(b"[]").unwrap().is_empty());
+ }
+
+ #[test]
+ fn fetch_open_prs_bails_without_a_forge_remote() {
+ // A repo with no remote can't be classified as GitHub or GitLab, so
+ // `--prs` reports that instead of shelling out to gh/glab.
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ let err = match fetch_open_prs(&test.repo) {
+ Ok(_) => panic!("expected --prs to bail without a forge remote"),
+ Err(e) => e,
+ };
+ assert!(
+ err.to_string().contains("could not determine the forge"),
+ "unexpected error: {err:#}"
+ );
+ }
+
+ #[test]
+ fn fetch_open_prs_bails_on_an_unsupported_forge() {
+ // A recognized-but-unsupported forge (here Gitea, by its host) reports
+ // the GitHub/GitLab limitation rather than shelling out.
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ test.run_git(&["remote", "add", "origin", "https://gitea.com/o/r.git"]);
+ let err = match fetch_open_prs(&test.repo) {
+ Ok(_) => panic!("expected --prs to bail on an unsupported forge"),
+ Err(e) => e,
+ };
+ assert!(
+ err.to_string().contains("supports GitHub and GitLab"),
+ "unexpected error: {err:#}"
+ );
+ }
+
+ #[test]
+ fn stream_open_prs_clears_loading_and_pokes_render_on_bail() {
+ // No forge remote → the fetch bails, but the wrapper still drops the
+ // header's loading marker and wakes skim. Without the poke the marker
+ // would linger past the (failed) fetch until the next keystroke.
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ let (tx, _rx): (SkimItemSender, SkimItemReceiver) = unbounded();
+ let warnings = Mutex::new(Vec::new());
+ let grid = GridSlot::new();
+ let loading = AtomicBool::new(true);
+ let (rtx, mut rrx) = tokio::sync::mpsc::channel(8);
+ let render_tx = OnceLock::new();
+ render_tx.set(rtx).unwrap();
+
+ stream_open_prs(&test.repo, 80, &tx, &warnings, &grid, &loading, &render_tx);
+
+ assert!(!loading.load(Ordering::Relaxed), "loading flag cleared");
+ assert!(matches!(rrx.try_recv(), Ok(Event::Render)), "render poked");
+ }
+
+ #[test]
+ fn parse_gitlab_maps_iid_source_branch_and_username() {
+ // `glab mr list --output json`: iid (not number), source_branch,
+ // author.username, draft, web_url.
+ let json = br#"[
+ {"iid":7,"title":"Add caching","source_branch":"feat/cache","author":{"username":"alice"},"draft":false,"web_url":"https://gitlab.com/o/r/-/merge_requests/7","description":"Caches the dependency graph between jobs."},
+ {"iid":8,"title":"WIP","source_branch":"wip","author":{"username":"bob"},"draft":true,"web_url":"https://gitlab.com/o/r/-/merge_requests/8"}
+ ]"#;
+ let entries = parse_gitlab_mrs(json).unwrap();
+ assert_eq!(entries.len(), 2);
+
+ assert_eq!(entries[0].number, 7);
+ assert_eq!(entries[0].head_branch, "feat/cache");
+ assert_eq!(entries[0].author, "alice");
+ assert!(matches!(entries[0].kind, RefKind::Mr));
+ assert_eq!(entries[0].body, "Caches the dependency graph between jobs.");
+ // GitLab's `description` maps to the same `body` slot; absent → empty.
+ assert_eq!(entries[1].body, "");
+ // The MR's `output()` shortcut uses the iid.
+ assert_eq!(
+ PrSkimItem::new(entries.into_iter().next().unwrap(), 120, None).output(),
+ "mr:7"
+ );
+ }
+
+ #[test]
+ fn parse_invalid_json_errors() {
+ assert!(parse_github_prs(b"not json").is_err());
+ assert!(parse_gitlab_mrs(b"not json").is_err());
+ }
+
+ #[test]
+ fn description_empty_or_blank_renders_nothing() {
+ // No body, or whitespace-only — the block is skipped entirely so the
+ // pane doesn't show an empty gutter.
+ assert_eq!(render_pr_description("", 80), "");
+ assert_eq!(render_pr_description(" \n\t \n", 80), "");
+ }
+
+ #[test]
+ fn description_wraps_into_the_house_gutter() {
+ let out = render_pr_description("Fixes the flaky retry logic.", 80);
+ // Leading full reset clears inherited style; the house gutter sets a
+ // bg color and closes each line with a skim-safe `\x1b[0m`.
+ assert!(out.starts_with("\n\x1b[0m"), "leading reset: {out:?}");
+ assert!(out.contains("\x1b[107m"), "house gutter bg: {out:?}");
+ assert!(
+ out.contains("Fixes the flaky retry logic."),
+ "body: {out:?}"
+ );
+ }
+
+ #[test]
+ fn description_renders_the_whole_body() {
+ // One word per line so each survives as its own gutter line; the pane
+ // scrolls, so the full body renders with no truncation hint.
+ let body = (0..50)
+ .map(|i| format!("- word{i}"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let out = render_pr_description(&body, 80);
+ assert!(!out.contains("more line"), "no truncation hint: {out:?}");
+ assert!(out.contains("word0"), "head kept: {out:?}");
+ assert!(out.contains("word49"), "tail kept: {out:?}");
+ }
+
+ #[test]
+ fn description_renders_markdown() {
+ // Markdown is styled, not shown verbatim: a bold span carries the SGR-1
+ // termimad emits, and the literal `**` markers are gone.
+ let out = render_pr_description("Fixes the **flaky** retry.", 80);
+ assert!(out.contains("\x1b[1m"), "bold rendered: {out:?}");
+ assert!(!out.contains("**"), "markers consumed: {out:?}");
+ }
+
+ #[test]
+ fn pr_pane_shows_description_only_when_present() {
+ let mut with_body = entry(RefKind::Pr, 1, "t");
+ with_body.body = "A short summary of the change.".to_string();
+ let pr = PrSkimItem::new(with_body, 120, Some(&grid()));
+ assert!(pr.pr_pane.contains("A short summary of the change."));
+ assert!(pr.pr_pane.contains("\x1b[107m"), "gutter present");
+
+ // The base fixture has an empty body — no gutter, no description.
+ let plain_pr = PrSkimItem::new(entry(RefKind::Pr, 2, "t"), 120, Some(&grid()));
+ assert!(
+ !plain_pr.pr_pane.contains("\x1b[107m"),
+ "no gutter when empty"
+ );
+ }
+
+ #[test]
+ fn preview_renders_tabs_and_placeholder_off_the_pr_tab() {
+ // With no per-process preview-state file, `read_mode()` returns the
+ // default (WorkingTree) — empty on a --prs row — so `preview()` renders
+ // the shared tab bar plus the "not checked out" placeholder. Drives the
+ // real `SkimItem::preview` (the `--prs` streaming path is too async to
+ // exercise it reliably under a PTY); `PreviewContext` is ignored by the
+ // impl, so a minimal one suffices.
+ let pr = PrSkimItem::new(entry(RefKind::Pr, 7, "Title"), 120, Some(&grid()));
+ let ctx = PreviewContext {
+ query: "",
+ cmd_query: "",
+ width: 80,
+ height: 24,
+ current_index: 0,
+ current_selection: "",
+ selected_indices: &[],
+ selections: &[],
+ };
+ let ItemPreview::AnsiText(text) = pr.preview(ctx) else {
+ panic!("expected AnsiText preview");
+ };
+ assert!(text.contains("6: pr"), "tab bar present: {text:?}");
+ assert!(
+ text.contains("Not checked out locally"),
+ "placeholder present: {text:?}"
+ );
+ }
+}
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap
index fdf831b6a..b2bf037a5 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__branch_diff.snap
@@ -1,6 +1,6 @@
---
source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+expression: "render_preview_tabs(mode, wt)"
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap
new file mode 100644
index 000000000..ad4bbc3a9
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__empty_upstream_and_summary.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/picker/items.rs
+expression: "render_preview_tabs(PreviewMode::WorkingTree,\nTabAvailability::worktree(false, false, false))"
+---
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap
index 624b27fa8..97cd24349 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__log.snap
@@ -1,6 +1,6 @@
---
source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+expression: "render_preview_tabs(mode, wt)"
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap
new file mode 100644
index 000000000..566a4283d
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/picker/items.rs
+expression: "render_preview_tabs(mode, wt)"
+---
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap
new file mode 100644
index 000000000..eb1373b8b
--- /dev/null
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__pr_row.snap
@@ -0,0 +1,6 @@
+---
+source: src/commands/picker/items.rs
+expression: "render_preview_tabs(PreviewMode::Pr, TabAvailability::pull_request())"
+---
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap
index 998befbeb..1b5d6cca0 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__summary.snap
@@ -1,6 +1,6 @@
---
source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+expression: "render_preview_tabs(mode, wt)"
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap
index a4e86b769..0c92992fc 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__upstream_diff.snap
@@ -1,6 +1,6 @@
---
source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+expression: "render_preview_tabs(mode, wt)"
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap b/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap
index 8a16bfb45..68ed18b74 100644
--- a/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap
+++ b/src/commands/picker/snapshots/wt__commands__picker__items__tests__working_tree.snap
@@ -1,6 +1,6 @@
---
source: src/commands/picker/items.rs
-expression: "WorktreeSkimItem::render_preview_tabs(mode)"
+expression: "render_preview_tabs(mode, wt)"
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 1985130c1..4eae6a95e 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1851,6 +1851,7 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>
return crate::commands::handle_picker(
args.branches,
args.remotes,
+ args.prs,
change_dir_flag,
args.format,
);
@@ -1860,7 +1861,7 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>
{
use worktrunk::git::WorktrunkError;
// Suppress unused variable warnings on Windows
- let _ = (args.branches, args.remotes, change_dir_flag);
+ let _ = (args.branches, args.remotes, args.prs, change_dir_flag);
crate::commands::print_windows_picker_unavailable();
return Err(WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into());
diff --git a/src/main.rs b/src/main.rs
index 34ea44872..ce217ef26 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -672,7 +672,7 @@ fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {
// Deprecated: show warning and delegate to handle_picker
warn_select_deprecated();
worktrunk::config::suppress_warnings();
- handle_picker(branches, remotes, None, SwitchFormat::Text)
+ handle_picker(branches, remotes, false, None, SwitchFormat::Text)
}
#[cfg(not(unix))]
diff --git a/src/testing/mock_commands.rs b/src/testing/mock_commands.rs
index 31a3483b5..833b44fb4 100644
--- a/src/testing/mock_commands.rs
+++ b/src/testing/mock_commands.rs
@@ -78,6 +78,7 @@ pub struct MockResponse {
output: Option<String>,
stderr: Option<String>,
exit_code: i32,
+ delay_ms: u64,
}
impl MockResponse {
@@ -88,6 +89,7 @@ impl MockResponse {
output: None,
stderr: None,
exit_code: 0,
+ delay_ms: 0,
}
}
@@ -98,6 +100,7 @@ impl MockResponse {
output: Some(text.to_string()),
stderr: None,
exit_code: 0,
+ delay_ms: 0,
}
}
@@ -108,6 +111,7 @@ impl MockResponse {
output: None,
stderr: Some(text.to_string()),
exit_code: 0,
+ delay_ms: 0,
}
}
@@ -118,6 +122,7 @@ impl MockResponse {
output: None,
stderr: None,
exit_code: code,
+ delay_ms: 0,
}
}
@@ -133,6 +138,13 @@ impl MockResponse {
self
}
+ /// Sleep this long before responding, to simulate a slow command (e.g. a
+ /// forge call) so a test can observe the caller's in-flight UI.
+ pub fn with_delay_ms(mut self, ms: u64) -> Self {
+ self.delay_ms = ms;
+ self
+ }
+
fn to_json(&self) -> serde_json::Value {
let mut obj = serde_json::Map::new();
if let Some(f) = &self.file {
@@ -149,6 +161,9 @@ impl MockResponse {
{
obj.insert("exit_code".to_string(), json!(self.exit_code));
}
+ if self.delay_ms != 0 {
+ obj.insert("delay_ms".to_string(), json!(self.delay_ms));
+ }
serde_json::Value::Object(obj)
}
}
diff --git a/tests/helpers/mock-stub/src/main.rs b/tests/helpers/mock-stub/src/main.rs
index cc12f7347..a951fcfd6 100644
--- a/tests/helpers/mock-stub/src/main.rs
+++ b/tests/helpers/mock-stub/src/main.rs
@@ -31,6 +31,8 @@
//! - `output`: output literal string to stdout
//! - `stderr`: output literal string to stderr
//! - `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)
use serde::Deserialize;
use std::collections::HashMap;
@@ -39,6 +41,8 @@ use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::exit;
+use std::thread::sleep;
+use std::time::Duration;
#[derive(Debug, Deserialize)]
struct Config {
@@ -54,6 +58,8 @@ struct CommandResponse {
stderr: Option<String>,
#[serde(default)]
exit_code: i32,
+ #[serde(default)]
+ delay_ms: u64,
}
/// Get command name from argv\[0\].
@@ -103,6 +109,7 @@ fn main() {
output: None,
stderr: None,
exit_code: 1,
+ delay_ms: 0,
};
// Try triple match first (e.g., "mr view 1", "mr view 2")
@@ -134,6 +141,12 @@ fn main() {
.or_else(|| config.commands.get("_default"))
.unwrap_or(&default_response);
+ // 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 {
+ sleep(Duration::from_millis(response.delay_ms));
+ }
+
if let Some(file) = &response.file {
let file_path = config_dir.join(file);
match fs::read_to_string(&file_path) {
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 9648103f5..64500c1de 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -2316,6 +2316,122 @@ fn set_github_remote_url(repo: &TestRepo) {
]);
}
+/// Install a mock forge CLI (`gh`/`glab`) answering the `--prs` list call
+/// (`pr list` / `mr list`) from a canned JSON file. Returns the mock bin dir.
+#[cfg(unix)]
+fn setup_mock_forge_list(
+ repo: &TestRepo,
+ cli: &str,
+ list_cmd: &str,
+ list_json: &str,
+) -> std::path::PathBuf {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+ 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"))
+ .command("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+ mock_bin
+}
+
+/// `wt switch --prs` in the headless dry-run (`WORKTRUNK_PICKER_DRY_RUN`)
+/// exercises the full forge fetch + row-render path — `stream_open_prs`,
+/// `fetch_github`, `parse_github_prs`, `PrSkimItem::new`, `render_grid_row`,
+/// `render_pr_description` — as a normal-exit subprocess, so its coverage is
+/// captured. (The interactive picker exits via skim's abort, which never
+/// flushes a profile, so its `--prs` code is otherwise unmeasurable.) The mock
+/// `gh pr list` keeps it off the network.
+#[cfg(unix)]
+#[rstest]
+fn test_switch_prs_dry_run_github(repo: TestRepo) {
+ // Pin the forge explicitly so detection needs no remote/network.
+ repo.write_project_config("[forge]\nplatform = \"github\"\n");
+ let pr_json = r#"[{"number":42,"title":"Retry the flaky test","headRefName":"fix/flaky","author":{"login":"octocat"},"isDraft":false,"url":"https://github.com/owner/test-repo/pull/42","body":"Wraps the request in a retry so the suite stops flaking."}]"#;
+ let mock_bin = setup_mock_forge_list(&repo, "gh", "pr list", pr_json);
+
+ 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 (github) failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ // The forge call ran (no "could not determine the forge" warning).
+ assert!(
+ !String::from_utf8_lossy(&output.stderr).contains("could not determine the forge"),
+ "forge not detected:\n{}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+}
+
+/// GitLab counterpart of [`test_switch_prs_dry_run_github`], covering the
+/// `fetch_gitlab` / `parse_gitlab_mrs` / `gitlab_mr_status` path via a mocked
+/// `glab mr list`.
+#[cfg(unix)]
+#[rstest]
+fn test_switch_prs_dry_run_gitlab(repo: TestRepo) {
+ repo.write_project_config("[forge]\nplatform = \"gitlab\"\n");
+ let mr_json = r#"[{"iid":7,"title":"Cache the dependency graph","source_branch":"feat/cache","author":{"username":"alice"},"draft":false,"web_url":"https://gitlab.com/owner/test-repo/-/merge_requests/7","detailed_merge_status":"ci_still_running","description":"Speeds up CI by caching deps between jobs."}]"#;
+ let mock_bin = setup_mock_forge_list(&repo, "glab", "mr list", mr_json);
+
+ 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 (gitlab) failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+}
+
+/// An empty forge list still runs `stream_open_prs` to completion, exercising
+/// the empty-list branch and `forge_noun` (`_ => "PRs"` on GitHub).
+#[cfg(unix)]
+#[rstest]
+fn test_switch_prs_dry_run_empty(repo: TestRepo) {
+ repo.write_project_config("[forge]\nplatform = \"github\"\n");
+ let mock_bin = setup_mock_forge_list(&repo, "gh", "pr list", "[]");
+
+ 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 (empty) failed:\nstderr: {}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+}
+
+/// GitLab empty list — exercises `forge_noun`'s `GitLab => "MRs"` arm.
+#[cfg(unix)]
+#[rstest]
+fn test_switch_prs_dry_run_empty_gitlab(repo: TestRepo) {
+ repo.write_project_config("[forge]\nplatform = \"gitlab\"\n");
+ let mock_bin = setup_mock_forge_list(&repo, "glab", "mr list", "[]");
+
+ 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 (empty gitlab) failed:\nstderr: {}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+}
+
/// Helper to set up mock gh for PR tests with custom PR response.
///
/// The response should be in `gh api repos/{owner}/{repo}/pulls/{number}` format:
diff --git a/tests/integration_tests/switch_picker.rs b/tests/integration_tests/switch_picker.rs
index d95edc4ed..85fd50407 100644
--- a/tests/integration_tests/switch_picker.rs
+++ b/tests/integration_tests/switch_picker.rs
@@ -24,6 +24,7 @@
//! - **Stabilization detection** waits for screen to stop changing
//! - **Content expectations** wait for async preview content to load (e.g., "diff --git")
+use crate::common::mock_commands::{MockConfig, MockResponse};
use crate::common::{TestRepo, repo, wt_bin};
use insta::assert_snapshot;
use portable_pty::CommandBuilder;
@@ -491,16 +492,22 @@ fn switch_picker_settings(repo: &TestRepo) -> insta::Settings {
// reverse video — see `skim::previewer::Previewer::draw`. We don't see the
// reverse-video attribute (vt100's `rows()` strips it), so it lands on screen
// as bare `N/M` overlapping the tab header text. content.len() varies with
- // terminal width and preview content height, so normalize it to a fixed
- // placeholder.
+ // terminal width and preview content height, so it must be normalized.
//
- // The previewer right-aligns the indicator at `screen_width - len - 1` and
- // can land flush against the truncated `summary` tab label (e.g.
- // `summa1/28`) — width_cjk's treatment of ambiguous-width glyphs (±, …, ⇅)
- // shifts how much of `5: summary` survives truncation. Strip leading
- // whitespace too so the placeholder is stable across that variance.
- settings.add_filter(r"(?m)summary?\w*\s*\d+/\d+[ \t]*$", "summary [N/M]");
- settings.add_filter(r"(?m)\s+\d+/\d+[ \t]*$", " [N/M]");
+ // The previewer right-aligns the indicator at `screen_width - len - 1`, so
+ // it overwrites a variable-width chunk at the right edge of the tab bar. With
+ // all six numbered tabs the bar fills the 60-col preview pane, so the chunk
+ // covers tab 6 (`6: pr`), its ` | ` divider, and a few trailing chars of tab
+ // 5 — how many depends on the indicator's digit count (`5: summary1/46` vs
+ // `5: summar1/286`). Anchor on the always-visible left portion (through
+ // `5: summ`, well inside the pane) and rewrite the corrupted tail to the
+ // canonical full bar. The exact per-tab styling (bold/plain/dim) is asserted
+ // by the `items.rs` unit snapshots; here we only need a stable marker that
+ // the bar rendered with tab 6 present.
+ settings.add_filter(
+ r"(?m)^(1: HEAD± \| 2: log \| 3: main…± \| 4: remote⇅ \| 5: summ).*$",
+ "${1}ary | 6: pr [N/M]",
+ );
// Commit hashes (7-8 hex chars)
settings.add_filter(r"\b[0-9a-f]{7,8}\b", "[HASH]");
@@ -927,11 +934,173 @@ fn test_switch_picker_preview_panel_summary(mut repo: TestRepo) {
});
}
+/// 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(
+ repo: &TestRepo,
+ cli: &str,
+ list_cmd: &str,
+ list_json: &str,
+ list_delay_ms: u64,
+) -> 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("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+
+ let mut env_vars = repo.test_env_vars();
+ env_vars.push((
+ "MOCK_CONFIG_DIR".to_string(),
+ mock_bin.display().to_string(),
+ ));
+ let base_path = std::env::var("PATH").unwrap_or_default();
+ env_vars.push((
+ "PATH".to_string(),
+ format!("{}:{base_path}", mock_bin.display()),
+ ));
+ env_vars
+}
+
+/// `wt switch --prs` on a GitHub repo: the open-PR list streams into the picker
+/// via a mocked `gh pr list`. Asserts the PR row reaches the list (the `#42`
+/// reference in the CI column), which deterministically exercises the whole
+/// fetch → stream → render path (`fetch_open_prs`, `fetch_github`,
+/// `parse_github_prs`, `stream_open_prs`, `PrSkimItem::new`, `render_grid_row`,
+/// `render_pr_description`). The title isn't on the row — it lives in the `pr`
+/// preview tab so the columns align — so the row's stable substring is `#42`.
+/// The full list isn't snapshotted because the worktree rows' CI cells fill
+/// asynchronously.
+#[rstest]
+fn test_switch_picker_prs_github_list(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "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":"Wraps the request in a retry so the suite stops flaking."}]"#;
+ let env_vars = mock_forge_env(&repo, "gh", "pr list", pr_json, 0);
+
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--prs"],
+ repo.root_path(),
+ &env_vars,
+ // Wait for the PR row to stream into the list (the `#42` content gate),
+ // then assert on the row itself — deterministic, with no dependency on
+ // selecting an async-arrived row.
+ &[("", Some("#42"))],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+ let (list, _preview) = result.panels();
+ // `#42` in the CI column; the head branch is truncated in the narrow list.
+ assert!(list.contains("#42"), "PR number in list:\n{list}");
+ // The title is NOT on the row — it lives in the preview so columns align.
+ assert!(
+ !list.contains("Retry the flaky network test"),
+ "PR title should stay off the row:\n{list}"
+ );
+ // The header's loading marker is gone once the rows have streamed in.
+ assert!(
+ !list.contains("loading open PRs"),
+ "loading marker cleared once rows arrived:\n{list}"
+ );
+}
+
+/// `wt switch --prs` on a GitLab repo: the open-MR list streams in via a mocked
+/// `glab mr list`. Covers the GitLab fetch path (`fetch_gitlab`,
+/// `parse_gitlab_mrs`, `gitlab_mr_status`).
+#[rstest]
+fn test_switch_picker_prs_gitlab_list(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://gitlab.com/owner/test-repo.git",
+ ]);
+ let mr_json = r#"[{"iid":7,"title":"Cache the dependency graph","source_branch":"feat/cache","author":{"username":"alice"},"draft":false,"web_url":"https://gitlab.com/owner/test-repo/-/merge_requests/7","detailed_merge_status":"ci_still_running","description":"Speeds up CI by caching deps between jobs."}]"#;
+ let env_vars = mock_forge_env(&repo, "glab", "mr list", mr_json, 0);
+
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--prs"],
+ repo.root_path(),
+ &env_vars,
+ // `!7` (GitLab MR ref) is the row's stable substring; the title lives in
+ // the preview, not the row.
+ &[("", Some("!7"))],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+ let (list, _preview) = result.panels();
+ // `!7` (GitLab MR ref) in the CI column; source branch truncates.
+ assert!(list.contains("!7"), "MR number in list:\n{list}");
+ assert!(
+ !list.contains("Cache the dependency graph"),
+ "MR title should stay off the row:\n{list}"
+ );
+}
+
+/// `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`.
+#[rstest]
+fn test_switch_picker_prs_shows_loading_marker(mut repo: TestRepo) {
+ repo.remove_fixture_worktrees();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "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);
+
+ let result = exec_in_pty_capture_before_abort(
+ wt_bin().to_str().unwrap(),
+ &["switch", "--prs"],
+ repo.root_path(),
+ &env_vars,
+ // The loading line paints at skeleton, before the (slow) forge call
+ // returns its rows.
+ &[("", Some("loading open PRs"))],
+ );
+
+ assert_valid_abort_exit_code(result.exit_code);
+ let (list, _preview) = result.panels();
+ assert!(
+ list.contains("loading open PRs"),
+ "loading line on the header while --prs fetches:\n{list}"
+ );
+ // The PR row hasn't streamed in yet — still inside the delayed forge call.
+ assert!(!list.contains("#42"), "rows not yet streamed in:\n{list}");
+}
+
#[rstest]
fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {
// Tab cycles the preview tab forward. From the default HEAD± tab (1), one
- // Tab lands on the log tab (2), proving the `tr 12345 23451` rotation in the
- // keybinding runs under the real shell. (alt-1..alt-5 jump directly; the
+ // Tab lands on the log tab (2), proving the `tr 123456 234561` rotation in
+ // the keybinding runs under the real shell. (alt-1..alt-6 jump directly; the
// panel tests above cover those — this covers the cycle path.)
repo.remove_fixture_worktrees();
repo.run_git(&["remote", "remove", "origin"]);
@@ -984,9 +1153,9 @@ fn test_switch_picker_preview_cycle_tab_forward(mut repo: TestRepo) {
#[rstest]
fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {
- // Forward cycling wraps 5 → 1: from the summary tab (reached via Alt-5),
- // one Tab returns to the HEAD± tab. This covers the `5 → 1` end of the
- // `tr 12345 23451` map, the half most easily typo'd away.
+ // Forward cycling wraps 6 → 1: from the pr tab (reached via Alt-6), one Tab
+ // returns to the HEAD± tab. This covers the `6 → 1` end of the
+ // `tr 123456 234561` map, the half most easily typo'd away.
repo.remove_fixture_worktrees();
repo.run_git(&["remote", "remove", "origin"]);
let feature_path = repo.add_worktree("feature");
@@ -1024,8 +1193,8 @@ fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {
// Cursor-navigation select: see test_switch_picker_preview_panel_uncommitted
// for the matcher-lag rationale.
("\x1b[B", None), // Down: move cursor to `feature`
- ("\x1b5", Some("Configure")), // Alt-5: jump to summary (5)
- ("\t", Some("no uncommitted changes")), // Tab: wrap 5 → HEAD± (1)
+ ("\x1b6", Some("PR")), // Alt-6: jump to pr (6); "Fetching PR status"/"has no PR"
+ ("\t", Some("no uncommitted changes")), // Tab: wrap 6 → HEAD± (1)
],
);
@@ -1034,15 +1203,15 @@ fn test_switch_picker_preview_cycle_tab_forward_wraps(mut repo: TestRepo) {
let (_list, preview) = result.panels();
assert!(
preview.contains("no uncommitted changes"),
- "Tab from the summary tab should wrap to the HEAD± tab; preview was:\n{preview}"
+ "Tab from the pr tab should wrap to the HEAD± tab; preview was:\n{preview}"
);
}
#[rstest]
fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {
// Shift-Tab cycles backward and wraps: from the default HEAD± tab (1), one
- // Shift-Tab lands on the summary tab (5), exercising the reverse rotation
- // `tr 12345 51234` including the 1 → 5 wraparound.
+ // Shift-Tab lands on the pr tab (6), exercising the reverse rotation
+ // `tr 123456 612345` including the 1 → 6 wraparound.
repo.remove_fixture_worktrees();
repo.run_git(&["remote", "remove", "origin"]);
let feature_path = repo.add_worktree("feature");
@@ -1076,17 +1245,21 @@ fn test_switch_picker_preview_cycle_shift_tab_wraps(mut repo: TestRepo) {
&[
// Cursor-navigation select: see test_switch_picker_preview_panel_uncommitted
// for the matcher-lag rationale.
- ("\x1b[B", None), // Down: move cursor to `feature`
- ("\x1b[Z", Some("Configure")), // Shift-Tab: HEAD± → summary (wrap)
+ ("\x1b[B", None), // Down: move cursor to `feature`
+ ("\x1b[Z", Some("PR")), // Shift-Tab: HEAD± → pr (wrap); "Fetching PR status"/"has no PR"
],
);
assert_valid_abort_exit_code(result.exit_code);
let (_list, preview) = result.panels();
+ // The worktree row has no remote and no CI cache, so its `pr` pane is either
+ // "Fetching PR status …" (the live fetch hasn't reported yet) or "feature
+ // has no PR" (it reported nothing) — both confirm Shift-Tab wrapped to the
+ // pr tab.
assert!(
- preview.contains("Configure"),
- "Shift-Tab should wrap to the summary tab; preview was:\n{preview}"
+ preview.contains("Fetching PR status") || preview.contains("has no PR"),
+ "Shift-Tab should wrap to the pr tab; preview was:\n{preview}"
);
}
diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rs
index c65bdd82c..621a391b7 100644
--- a/tests/integration_tests/switch_picker_dry_run.rs
+++ b/tests/integration_tests/switch_picker_dry_run.rs
@@ -57,10 +57,11 @@ fn test_picker_dry_run_dumps_cache_json(mut repo: TestRepo) {
}
}
-/// Cached CI statuses surface PR numbers in picker rows without any network
-/// access: the picker skips the CiStatus task, and collect fills `pr_status`
-/// from `.git/wt/cache/ci-status/` instead. A fresh entry renders its
-/// number; a branch without one renders an empty CI cell.
+/// A fresh cached CI status surfaces a PR number in picker rows without any
+/// network access: the picker primes rows from `.git/wt/cache/ci-status/`, and
+/// the live `CiStatus` task's `detect` reads the same fresh entry through its
+/// own cache rather than calling the forge. A branch without an entry renders
+/// an empty CI cell.
#[rstest]
fn test_picker_dry_run_shows_cached_pr_numbers(mut repo: TestRepo) {
repo.add_worktree("feature-a");
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index c889aadc9..8bf72a5db 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -90,6 +90,9 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--remotes
Include remote branches
+ --prs
+ Include open PRs/MRs
+
Automation:
--no-hooks
Skip hooks
@@ -169,9 +172,9 @@ Shortcuts also apply to --base. For a fork PR/MR, the head commit is fet
Interactive picker
-When called without arguments, wt switch opens an interactive picker to browse and select worktrees with live preview.
+When called without arguments, wt switch opens an interactive picker to browse and select worktrees with live preview. The candidate set widens with --branches (local branches without worktrees), --remotes (remote branches), and --prs (open PRs/MRs — see below).
-The CI column shows cached PR/MR status when earlier runs (wt list --full, the statusline) have fetched it — the picker never fetches CI status itself. An entry whose branch has moved or whose TTL has passed keeps its PR/MR number, dimmed.
+The CI column shows each row's PR/MR CI and review status, the same as wt list --full.
Keybindings:
@@ -182,7 +185,7 @@ The CI column shows cached PR/MR status when earlier runs (wt list --full[0
Enter Switch to selected worktree
Alt-c Create new worktree named as entered text
Esc Cancel
- Alt-1–Alt-5 Jump to a preview tab
+ Alt-1–Alt-6 Jump to a preview tab
Tab/Shift-Tab Cycle preview tabs forward/backward
Alt-p Toggle preview panel
Ctrl-u/Ctrl-d Scroll preview up/down
@@ -191,13 +194,14 @@ Plain digits go to the filter, so a branch name containing a number can be typed
Typing a gutter sigil filters by row kind: + narrows to linked worktrees and @ to the current worktree. The other sigils don't filter cleanly — ^ and | are skim's prefix-anchor and OR query operators (so ^ matches every row and | none), and / matches most rows because every worktree path contains it.
-Preview tabs — jump with Alt-1–Alt-5, or cycle with Tab/Shift-Tab:
+Preview tabs:
1. HEAD± — Diff of uncommitted changes
2. log — Recent commits; commits already on the default branch have dimmed hashes
3. main…± — Diff of changes since the merge-base with the default branch
4. remote⇅ — Ahead/behind diff vs upstream tracking branch
5. summary — LLM-generated branch summary; requires [list] summary = true and commit.generation
+6. pr — The selected row's PR/MR, for any row whose branch has one
Pager configuration: The preview panel pipes diff output through git's pager. Override in user config:
@@ -214,11 +218,14 @@ The pr:<number> / mr:<number> shortcut and the PR/MR's web URL b
  wt switch https://github.com/owner/repo/pull/101 # ...the same PR, by URL
  wt switch mr:101 # GitLab MR !101
  wt switch https://gitlab.com/owner/repo/-/merge_requests/101 # ...the same MR, by URL
+  wt switch --prs # Browse open PRs/MRs in the picker
Both work anywhere a branch is accepted, including --base. The --create flag cannot be used with a PR/MR reference since the branch already exists.
If the PR or MR is on a fork, the local branch uses its branch name directly, so git push works normally. A pre-existing local branch with that name tracking something else requires renaming first.
+The --prs flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker. Each row resolves to the same pr:/mr: shortcut, so selecting one fetches the ref and switches to its branch.
+
Requires gh (GitHub), glab (GitLab), or an equivalent CLI installed and authenticated; see forge platform for Gitea, Azure DevOps, and other supported platforms.
When wt switch fails
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
index 8a9e4b0cc..e16d41354 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
@@ -51,6 +51,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Picker Options:
--branches Include branches without worktrees
--remotes Include remote branches
+ --prs Include open PRs/MRs
Automation:
--no-hooks Skip hooks
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_list.snap
index c15ab1d07..b596398ef 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_list.snap
@@ -3,5 +3,5 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅ Commit
-> @ main ^ [HASH]
+ Branch Status HEAD± main↕ Remote⇅ CI
+> @ main ^
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap
index 469734ed2..65ccf912d 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_abort_escape_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
○ main has no uncommitted changes
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_list.snap
index 8f3d7d57c..44d7ac6aa 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_list.snap
@@ -3,7 +3,7 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅ Age
-> @ main ^ [TIME]
- + feature-one _ [TIME]
- + feature-two _ [TIME]
+ Branch Status HEAD± main↕ CI Age
+> @ main ^ [TIME]
+ + feature-one _ [TIME]
+ + feature-two _ [TIME]
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap
index 469734ed2..65ccf912d 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_multiple_worktrees_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
○ main has no uncommitted changes
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_list.snap
index 45e829097..c4317ad87 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_list.snap
@@ -3,6 +3,6 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅ Commit
- @ main ^ [HASH]
-> + feature ↑ ↑5 [HASH]
+ Branch Status HEAD± main↕ Remote⇅ CI
+ @ main ^
+> + feature ↑ ↑5
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap
index 95e6f8aaa..940867780 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_log_preview.snap
@@ -2,8 +2,8 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
* [HASH] +1 [TIME] (feature) Add file 5 with content
* [HASH] +1 [TIME] Add file 4 with content
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_list.snap
index b8c1ff5cd..f23a2e684 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_list.snap
@@ -3,6 +3,6 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅ Commit
- @ main ^ [HASH]
-> + feature ↑ ↑2 [HASH]
+ Branch Status HEAD± main↕ Remote⇅ CI
+ @ main ^
+> + feature ↑ ↑2
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap
index 2ca4c65d8..100f86d90 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_main_diff_preview.snap
@@ -2,8 +2,8 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
feature_code.rs | 6 ++++++
tests.rs | 4 ++++
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap
index 3aee70002..83cfda2ef 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_list.snap
@@ -3,6 +3,6 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅ Commit
- @ main ^ [HASH]
-> + feature ↑ ↑1 [HASH]
+ Branch Status HEAD± main↕ Remote⇅ CI
+ @ main ^
+> + feature ↑ ↑1
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap
index f8c9cfb3b..157a39b00 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_summary_preview.snap
@@ -2,8 +2,8 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
Configure [commit.generation] command to enable LLM summari
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_list.snap
index 563c0ffdf..317472037 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_list.snap
@@ -3,6 +3,6 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅ Commit
- @ main ^ [HASH]
-> + feature ! ↑ +3 -1 ↑1 [HASH]
+ Branch Status HEAD± main↕ Remote⇅ CI
+ @ main ^
+> + feature ! ↑ +3 -1 ↑1
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap
index 694ab0864..3329d6b64 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_preview_uncommitted_preview.snap
@@ -2,8 +2,8 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
tracked.txt | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_list.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_list.snap
index 9f4fc68a4..0d021330f 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_list.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_list.snap
@@ -3,7 +3,7 @@ source: tests/integration_tests/switch_picker.rs
expression: list
---
>
- Branch Status HEAD± main↕ Remote⇅
+ Branch Status HEAD± main↕ CI
> @ main ^
+ active-worktree _
/ orphan-branch /_
diff --git a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap
index 469734ed2..65ccf912d 100644
--- a/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap
+++ b/tests/snapshots/integration__integration_tests__switch_picker__switch_picker_with_branches_preview.snap
@@ -2,7 +2,7 @@
source: tests/integration_tests/switch_picker.rs
expression: preview
---
-1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary
-Enter: switch | Tab/alt-1…5: preview | alt-c: create | Esc:
+1: HEAD± | 2: log | 3: main…± | 4: remote⇅ | 5: summary | 6: pr [N/M]
+Enter: switch | Tab/alt-1…6: preview | alt-c: create | Esc:
○ main has no uncommitted changes