Skip to content

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

fix(switch): pr:NNNN fails for same-repo PRs in repos without fetch refspecs (#965)

Andoni Alonso957c8f6e58f6
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index beed7c222..383bdb657 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -95,7 +95,7 @@ fn resolve_remote_ref(
return resolve_fork_ref(repo, provider, number, &info);
}
- // Same-repo ref: for PRs, fetch the branch; for MRs, just use the branch name
+ // Same-repo ref: fetch the branch to ensure remote tracking refs exist
resolve_same_repo_ref(repo, &info)
}
@@ -274,38 +274,50 @@ fn resolve_same_repo_ref(
) -> anyhow::Result<ResolvedTarget> {
use worktrunk::git::remote_ref::PlatformData;
- // For GitHub PRs, fetch the branch to ensure remote refs are up-to-date
- if let PlatformData::GitHub {
- host,
- base_owner,
- base_repo,
- ..
- } = &info.platform_data
- {
- let remote = repo
- .find_remote_for_repo(Some(host), base_owner, base_repo)
- .ok_or_else(|| {
- let suggested_url = worktrunk::git::remote_ref::github::fork_remote_url(
- host, base_owner, base_repo,
- );
- GitError::NoRemoteForRepo {
+ // Find the remote for the same-repo PR/MR and fetch the branch with an
+ // explicit refspec. This ensures the remote tracking branch is created even
+ // in repos with limited fetch refspecs (single-branch clones, bare repos).
+ let remote = match &info.platform_data {
+ PlatformData::GitHub {
+ host,
+ base_owner,
+ base_repo,
+ ..
+ } => {
+ let suggested_url =
+ worktrunk::git::remote_ref::github::fork_remote_url(host, base_owner, base_repo);
+ repo.find_remote_for_repo(Some(host), base_owner, base_repo)
+ .ok_or_else(|| GitError::NoRemoteForRepo {
owner: base_owner.clone(),
repo: base_repo.clone(),
suggested_url,
- }
- })?;
- let branch = &info.source_branch;
-
- eprintln!(
- "{}",
- progress_message(cformat!("Fetching <bold>{branch}</> from {remote}..."))
- );
- // Use -- to prevent branch names starting with - from being interpreted as flags
- repo.run_command(&["fetch", "--", &remote, branch])
- .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;
- }
+ })?
+ }
+ PlatformData::GitLab {
+ host,
+ base_owner,
+ base_repo,
+ ..
+ } => repo
+ .find_remote_for_repo(Some(host), base_owner, base_repo)
+ .ok_or_else(|| GitError::NoRemoteForRepo {
+ owner: base_owner.clone(),
+ repo: base_repo.clone(),
+ suggested_url: format!("https://{host}/{base_owner}/{base_repo}.git"),
+ })?,
+ };
- // For GitLab same-repo MRs, we just use the branch name directly
+ let branch = &info.source_branch;
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Fetching <bold>{branch}</> from {remote}..."))
+ );
+ // Explicit refspec creates/updates the remote-tracking ref even when it's outside
+ // the configured fetch refspec (e.g., single-branch clones, bare repos).
+ let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
+ // Use -- to prevent branch names starting with - from being interpreted as flags
+ repo.run_command(&["fetch", "--", &remote, &refspec])
+ .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;
Ok(ResolvedTarget {
branch: info.source_branch.clone(),
@@ -722,12 +734,31 @@ pub fn execute_switch(
let worktree_path_str = worktree_path.to_string_lossy();
let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];
+ // For DWIM fallback: when the branch doesn't exist locally,
+ // git worktree add relies on DWIM to auto-create it from a
+ // remote tracking branch. DWIM fails in repos without configured
+ // fetch refspecs (bare repos, single-branch clones). Explicitly
+ // create from the tracking ref in that case.
+ let tracking_ref;
+
if *create_branch {
args.push("-b");
args.push(&branch);
if let Some(base) = base_branch {
args.push(base);
}
+ } else if !local_branch_existed {
+ // Explicit -b when there's exactly one remote tracking ref.
+ // Git's DWIM relies on the fetch refspec including this branch,
+ // which may not hold in single-branch clones or bare repos.
+ let remotes = branch_handle.remotes().unwrap_or_default();
+ if remotes.len() == 1 {
+ tracking_ref = format!("{}/{}", remotes[0], branch);
+ args.extend(["-b", &branch, tracking_ref.as_str()]);
+ } else {
+ // Multiple or zero remotes: let git's DWIM handle (or error)
+ args.push(&branch);
+ }
} else {
args.push(&branch);
}
@@ -763,7 +794,7 @@ pub fn execute_switch(
branch_handle.unset_upstream()?;
}
- // Report tracking info only if git's DWIM created the branch from a remote
+ // Report tracking info when the branch was auto-created from a remote
let from_remote = if !create_branch && !local_branch_existed {
branch_handle.upstream()?
} else {
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index f68178754..5e9bf898a 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -23,14 +23,13 @@ pub enum SwitchResult {
/// Created new worktree at the given path
Created {
path: PathBuf,
- /// True if we used `-b` to create a new branch (--create flag)
+ /// True if the user requested branch creation (--create flag)
created_branch: bool,
/// Base branch when creating new branch (e.g., "main")
base_branch: Option<String>,
/// Absolute path to base branch's worktree (POSIX format for shell compatibility)
base_worktree_path: Option<String>,
- /// Remote tracking branch if created from remote (e.g., "origin/feature")
- /// This is set when git's DWIM created a local branch from a remote
+ /// Remote tracking branch if auto-created from remote (e.g., "origin/feature")
from_remote: Option<String>,
},
}
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rs
index 155423573..802108e27 100644
--- a/src/git/remote_ref/gitlab.rs
+++ b/src/git/remote_ref/gitlab.rs
@@ -155,6 +155,16 @@ fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefIn
let is_cross_repo = response.source_project_id != response.target_project_id;
+ // Parse host/owner/repo from the web URL (always available from the MR API).
+ // e.g., "https://gitlab.com/owner/repo/-/merge_requests/101" → host/owner/repo
+ let (project_url, _) = response
+ .web_url
+ .split_once("/-/")
+ .with_context(|| format!("GitLab MR URL missing /-/ separator: {}", response.web_url))?;
+ let parsed_url = crate::git::GitRemoteUrl::parse(project_url).ok_or_else(|| {
+ anyhow::anyhow!("Failed to parse GitLab project from MR URL: {project_url}")
+ })?;
+
// Don't fetch project URLs here - defer until after branch_tracks_ref check
// in switch.rs, which often short-circuits (branch already configured).
// Use fetch_gitlab_project_urls() when URLs are actually needed.
@@ -171,6 +181,9 @@ fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefIn
url: response.web_url,
fork_push_url: None, // Populated later by fetch_gitlab_project_urls if needed
platform_data: PlatformData::GitLab {
+ host: parsed_url.host().to_string(),
+ base_owner: parsed_url.owner().to_string(),
+ base_repo: parsed_url.repo().to_string(),
source_project_id: response.source_project_id,
target_project_id: response.target_project_id,
},
diff --git a/src/git/remote_ref/info.rs b/src/git/remote_ref/info.rs
index ae38c11e3..413357621 100644
--- a/src/git/remote_ref/info.rs
+++ b/src/git/remote_ref/info.rs
@@ -24,6 +24,12 @@ pub enum PlatformData {
},
/// GitLab-specific data.
GitLab {
+ /// GitLab host (e.g., "gitlab.com", "gitlab.example.com").
+ host: String,
+ /// Owner/namespace of the base (target) project.
+ base_owner: String,
+ /// Name of the base (target) project.
+ base_repo: String,
/// Source project ID (used for deferred URL fetching).
source_project_id: u64,
/// Target project ID (used for deferred URL fetching).
@@ -229,6 +235,9 @@ mod tests {
url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),
fork_push_url: Some("[email protected]:contributor/repo.git".to_string()),
platform_data: PlatformData::GitLab {
+ host: "gitlab.com".to_string(),
+ base_owner: "owner".to_string(),
+ base_repo: "repo".to_string(),
source_project_id: 456,
target_project_id: 123,
},
@@ -277,6 +286,9 @@ mod tests {
url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),
fork_push_url: Some("[email protected]:contributor/repo.git".to_string()),
platform_data: PlatformData::GitLab {
+ host: "gitlab.com".to_string(),
+ base_owner: "owner".to_string(),
+ base_repo: "repo".to_string(),
source_project_id: 456,
target_project_id: 123,
},
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index baedcc1c4..c15858a15 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -119,6 +119,24 @@ fn test_switch_dwim_from_remote(#[from(repo_with_remote)] repo: TestRepo) {
snapshot_switch("switch_dwim_from_remote", &repo, &["dwim-feature"]);
}
+/// When a branch exists on multiple remotes, DWIM should fail with an error
+/// since git can't determine which remote to track.
+#[rstest]
+fn test_switch_dwim_ambiguous_remotes(#[from(repo_with_remote)] mut repo: TestRepo) {
+ // Add a second remote
+ repo.setup_custom_remote("upstream", "main");
+
+ // Create a branch on both remotes (no local branch)
+ repo.run_git(&["branch", "shared-feature"]);
+ repo.run_git(&["push", "origin", "shared-feature"]);
+ repo.run_git(&["push", "upstream", "shared-feature"]);
+ repo.run_git(&["branch", "-D", "shared-feature"]);
+
+ // Now shared-feature exists on origin and upstream but not locally
+ // DWIM can't pick — git worktree add should error
+ snapshot_switch("switch_dwim_ambiguous_remotes", &repo, &["shared-feature"]);
+}
+
/// When creating a new branch from a remote tracking branch (e.g., origin/main),
/// the new branch should NOT track the remote base branch.
/// This prevents accidental `git push` to the base branch (e.g., pushing to main).
@@ -1551,6 +1569,76 @@ fn test_switch_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
});
}
+/// Test same-repo PR with a limited fetch refspec (single-branch clone scenario).
+///
+/// In repos with a limited refspec (e.g., `+refs/heads/main:refs/remotes/origin/main`),
+/// `git fetch origin <branch>` only updates FETCH_HEAD but doesn't create the remote
+/// tracking branch. This caused `wt switch pr:101` to fail with "No branch named X".
+#[rstest]
+fn test_switch_pr_same_repo_limited_refspec(#[from(repo_with_remote)] mut repo: TestRepo) {
+ // Create a feature branch and push it to the remote
+ repo.add_worktree("feature-auth");
+ repo.run_git(&["push", "origin", "feature-auth"]);
+
+ let bare_url = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["config", "remote.origin.url"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+
+ // Set origin URL to GitHub-style so find_remote_for_repo() can match owner/test-repo
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ // Redirect github.com URLs to the local bare remote
+ repo.run_git(&[
+ "config",
+ &format!("url.{}.insteadOf", bare_url),
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ // Restrict fetch refspec to only main, simulating a single-branch clone
+ repo.run_git(&[
+ "config",
+ "remote.origin.fetch",
+ "+refs/heads/main:refs/remotes/origin/main",
+ ]);
+
+ let gh_response = r#"{
+ "title": "Fix authentication bug in login flow",
+ "user": {"login": "alice"},
+ "state": "open",
+ "draft": false,
+ "head": {
+ "ref": "feature-auth",
+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}
+ },
+ "base": {
+ "ref": "main",
+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}
+ },
+ "html_url": "https://github.com/owner/test-repo/pull/101"
+ }"#;
+
+ let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_same_repo_limited_refspec", cmd);
+ });
+}
+
/// Test same-repo PR when origin points to a different repo (no remote for PR's repo)
///
/// User scenario:
@@ -2421,6 +2509,33 @@ fn test_switch_mr_base_conflict(repo: TestRepo) {
fn test_switch_mr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
// Create a feature branch and push it
repo.add_worktree("feature-auth");
+ repo.run_git(&["push", "origin", "feature-auth"]);
+
+ let bare_url = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["config", "remote.origin.url"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+
+ // Set origin URL to GitLab-style so find_remote_for_repo() can match owner/test-repo
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://gitlab.com/owner/test-repo.git",
+ ]);
+
+ // Redirect gitlab.com URLs to the local bare remote
+ repo.run_git(&[
+ "config",
+ &format!("url.{}.insteadOf", bare_url),
+ "https://gitlab.com/owner/test-repo.git",
+ ]);
// glab api projects/:id/merge_requests/<number> format
let glab_response = r#"{
@@ -2444,6 +2559,156 @@ fn test_switch_mr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
});
}
+/// Test same-repo MR with a limited fetch refspec (single-branch clone scenario).
+///
+/// In repos with a limited refspec (e.g., `+refs/heads/main:refs/remotes/origin/main`),
+/// `git fetch origin <branch>` only updates FETCH_HEAD but doesn't create the remote
+/// tracking branch. This caused `wt switch mr:101` to fail with "No branch named X".
+#[rstest]
+fn test_switch_mr_same_repo_limited_refspec(#[from(repo_with_remote)] mut repo: TestRepo) {
+ // Create a feature branch and push it to the remote
+ repo.add_worktree("feature-auth");
+ repo.run_git(&["push", "origin", "feature-auth"]);
+
+ let bare_url = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["config", "remote.origin.url"])
+ .output()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+
+ // Set origin URL to GitLab-style so find_remote_for_repo() can match owner/test-repo
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://gitlab.com/owner/test-repo.git",
+ ]);
+
+ // Redirect gitlab.com URLs to the local bare remote
+ repo.run_git(&[
+ "config",
+ &format!("url.{}.insteadOf", bare_url),
+ "https://gitlab.com/owner/test-repo.git",
+ ]);
+
+ // Restrict fetch refspec to only main, simulating a single-branch clone
+ repo.run_git(&[
+ "config",
+ "remote.origin.fetch",
+ "+refs/heads/main:refs/remotes/origin/main",
+ ]);
+
+ let glab_response = r#"{
+ "title": "Fix authentication bug in login flow",
+ "author": {"username": "alice"},
+ "state": "opened",
+ "draft": false,
+ "source_branch": "feature-auth",
+ "source_project_id": 123,
+ "target_project_id": 123,
+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
+ }"#;
+
+ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
+ configure_mock_glab_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_mr_same_repo_limited_refspec", cmd);
+ });
+}
+
+/// Test same-repo MR when origin points to a different repo (no remote for MR's repo)
+///
+/// User scenario:
+/// 1. User has origin pointing to their fork (contributor/test-repo)
+/// 2. MR !101 is a same-repo MR on the upstream (owner/test-repo)
+/// 3. No remote exists for owner/test-repo -> error with hint to add upstream
+#[rstest]
+fn test_switch_mr_same_repo_no_remote(#[from(repo_with_remote)] repo: TestRepo) {
+ // Set origin to point to a DIFFERENT repo than where the MR is
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://gitlab.com/contributor/test-repo.git",
+ ]);
+
+ let glab_response = r#"{
+ "title": "Fix authentication bug in login flow",
+ "author": {"username": "alice"},
+ "state": "opened",
+ "draft": false,
+ "source_branch": "feature-auth",
+ "source_project_id": 123,
+ "target_project_id": 123,
+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"
+ }"#;
+
+ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
+ configure_mock_glab_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_mr_same_repo_no_remote", cmd);
+ });
+}
+
+/// Test same-repo MR with malformed web_url (missing /-/ separator)
+#[rstest]
+fn test_switch_mr_malformed_web_url_no_separator(#[from(repo_with_remote)] repo: TestRepo) {
+ let glab_response = r#"{
+ "title": "Fix bug",
+ "author": {"username": "alice"},
+ "state": "opened",
+ "draft": false,
+ "source_branch": "feature",
+ "source_project_id": 123,
+ "target_project_id": 123,
+ "web_url": "https://gitlab.com/owner/test-repo/merge_requests/101"
+ }"#;
+
+ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
+ configure_mock_glab_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_mr_malformed_web_url", cmd);
+ });
+}
+
+/// Test same-repo MR with unparsable project URL (has /-/ but no owner/repo)
+#[rstest]
+fn test_switch_mr_malformed_web_url_no_project(#[from(repo_with_remote)] repo: TestRepo) {
+ let glab_response = r#"{
+ "title": "Fix bug",
+ "author": {"username": "alice"},
+ "state": "opened",
+ "draft": false,
+ "source_branch": "feature",
+ "source_project_id": 123,
+ "target_project_id": 123,
+ "web_url": "https://gitlab.com/-/merge_requests/101"
+ }"#;
+
+ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);
+ configure_mock_glab_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_mr_malformed_web_url_no_project", cmd);
+ });
+}
+
/// Test error when MR is not found
#[rstest]
fn test_switch_mr_not_found(#[from(repo_with_remote)] repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snap b/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snap
new file mode 100644
index 000000000..0b0329284
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_dwim_ambiguous_remotes.snap
@@ -0,0 +1,43 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - shared-feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Failed to create worktree for shared-feature
+  fatal: invalid reference: shared-feature
+  (git worktree add _REPO_.shared-feature shared-feature failed, exit code 128)
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_malformed_web_url.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_malformed_web_url.snap
new file mode 100644
index 000000000..f0dec18f8
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_malformed_web_url.snap
@@ -0,0 +1,42 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "mr:101"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching MR !101...
+✗ GitLab MR URL missing /-/ separator: https://gitlab.com/owner/test-repo/merge_requests/101
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_malformed_web_url_no_project.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_malformed_web_url_no_project.snap
new file mode 100644
index 000000000..7ebdc775a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_malformed_web_url_no_project.snap
@@ -0,0 +1,42 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "mr:101"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching MR !101...
+✗ Failed to parse GitLab project from MR URL: https://gitlab.com
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snap
index 54094b348..850b2a32c 100644
--- a/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snap
+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snap
@@ -13,6 +13,7 @@ info:
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
GIT_TERMINAL_PROMPT: "0"
HOME: "[TEST_HOME]"
LANG: C
@@ -40,5 +41,6 @@ exit_code: 0
◎ Fetching MR !101...
  Fix authentication bug in login flow (!101)
  by @alice · opened · feature-auth · https://gitlab.com/owner/test-repo/-/merge_requests/101
+◎ Fetching feature-auth from origin...
▲ Worktree for feature-auth @ _REPO_.feature-auth, but cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo_limited_refspec.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo_limited_refspec.snap
new file mode 100644
index 000000000..850b2a32c
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo_limited_refspec.snap
@@ -0,0 +1,46 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "mr:101"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Fetching MR !101...
+  Fix authentication bug in login flow (!101)
+  by @alice · opened · feature-auth · https://gitlab.com/owner/test-repo/-/merge_requests/101
+◎ Fetching feature-auth from origin...
+▲ Worktree for feature-auth @ _REPO_.feature-auth, but cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo_no_remote.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo_no_remote.snap
new file mode 100644
index 000000000..d4f5c8759
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo_no_remote.snap
@@ -0,0 +1,45 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "mr:101"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching MR !101...
+  Fix authentication bug in login flow (!101)
+  by @alice · opened · feature-auth · https://gitlab.com/owner/test-repo/-/merge_requests/101
+✗ No remote found for owner/test-repo
+↳ Add the remote: git remote add upstream https://gitlab.com/owner/test-repo.git
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo_limited_refspec.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo_limited_refspec.snap
new file mode 100644
index 000000000..5ca619279
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo_limited_refspec.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/switch.rs
+assertion_line: 1613
+info:
+ program: wt
+ args:
+ - switch
+ - "pr:101"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101...
+  Fix authentication bug in login flow (#101)
+  by @alice · open · feature-auth · https://github.com/owner/test-repo/pull/101
+◎ Fetching feature-auth from origin...
+▲ Worktree for feature-auth @ _REPO_.feature-auth, but cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install