Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(switch): forward the forge CLI's own error text (#3605)
Maximilian Roos32f380a27bd3
diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rsindex 72e1b8edc..76ef20f44 100644--- a/src/git/remote_ref/github.rs+++ b/src/git/remote_ref/github.rs@@ -49,12 +49,16 @@ struct GhApiPrResponse {html_url: String,}-/// Error response from GitHub API.+/// The status GitHub reports in an API error body.+///+/// Not what separates an error from a PR — `gh` exits non-zero for that. This+/// selects the one failure worth a message of our own (a 404); every other+/// status forwards, so the struct needs no other field. `status` carries no+/// `#[serde(default)]` because an error body that omits it isn't the shape this+/// type describes, and a failed parse and an unmatched status both land on the+/// same forwarding path.#[derive(Debug, Deserialize)]struct GhApiErrorResponse {- #[serde(default)]- message: String,- #[serde(default)]status: String,}@@ -147,31 +151,27 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI})?;if !output.status.success() {- if let Ok(error_response) = serde_json::from_slice::<GhApiErrorResponse>(&output.stdout) {- match error_response.status.as_str() {- "404" => {- let hint = if source == "gh default" {- "Check that `gh repo set-default` points to the correct repository."- } else {- "If the PR is on a different repository, \- run `gh repo set-default` to set the default \- or configure a different primary remote."- };- bail!(- "PR #{pr_number} not found on {owner}/{repo_name} ({source}). \- {hint}",- );- }- "401" => bail!("GitHub CLI not authenticated; run gh auth login"),- "403" => {- let message_lower = error_response.message.to_lowercase();- if message_lower.contains("rate limit") {- bail!("GitHub API rate limit exceeded; wait a few minutes and retry");- }- bail!("GitHub API access forbidden: {}", error_response.message);- }- _ => {}- }+ // A 404 is the one GitHub failure we can describe better than `gh` can:+ // it answers about the owner/repo *we* picked, and which repo that is —+ // and where the pick came from — is ours to report, not gh's. Auth,+ // permissions, and rate limits are forwarded instead, since gh's line+ // ("gh: Bad credentials (HTTP 401)") carries the status and GitHub's own+ // message. See the module docs.+ if serde_json::from_slice::<GhApiErrorResponse>(&output.stdout)+ .is_ok_and(|error| error.status == "404")+ {+ let hint = if source == "gh default" {+ "Check that `gh repo set-default` points to the correct repository."+ } else {+ "If the PR is on a different repository, \+ run `gh repo set-default` to set the default \+ or configure a different primary remote."+ };+ return Err(cli_api_error(+ RefType::Pr,+ format!("PR #{pr_number} not found on {owner}/{repo_name} ({source}). {hint}"),+ &output,+ ));}return Err(cli_api_error(diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rsindex 361aeb37c..543b1f969 100644--- a/src/git/remote_ref/gitlab.rs+++ b/src/git/remote_ref/gitlab.rs@@ -80,15 +80,6 @@ struct GlabProject {http_url_to_repo: Option<String>,}-/// Error response from GitLab API.-#[derive(Debug, Deserialize)]-struct GlabApiErrorResponse {- #[serde(default)]- message: String,- #[serde(default)]- error: String,-}-/// Fetch MR information from GitLab using the `glab` CLI.fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {let api_path = format!("projects/:id/merge_requests/{}", mr_number);@@ -103,24 +94,10 @@ fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefIn})?;if !output.status.success() {- if let Ok(error_response) = serde_json::from_slice::<GlabApiErrorResponse>(&output.stdout) {- let error_text = if !error_response.message.is_empty() {- &error_response.message- } else {- &error_response.error- };-- if error_text.starts_with("404") {- bail!("MR !{} not found", mr_number);- }- if error_text.starts_with("401") {- bail!("GitLab CLI not authenticated; run glab auth login");- }- if error_text.starts_with("403") {- bail!("GitLab API access forbidden for MR !{}", mr_number);- }- }-+ // GitLab puts the status only inside the message text+ // (`{"message":"401 Unauthorized"}`), so classifying here would mean+ // matching prose — and there is nothing to say afterwards that glab's own+ // line doesn't already: `glab: 401 Unauthorized (HTTP 401)`. Forward it.return Err(cli_api_error(RefType::Mr,format!("glab api failed for MR !{}", mr_number),diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rsindex 159d24d14..8280df61a 100644--- a/src/git/remote_ref/mod.rs+++ b/src/git/remote_ref/mod.rs@@ -22,6 +22,39 @@//! # }//! ```//!+//! # Error Messages+//!+//! When a forge CLI reports a failure, the message the user sees is the CLI's+//! own, in a gutter under one line of our context — see `cli_api_error` below.+//! `gh` and `glab` both render an API failure as the API's own message plus the+//! status (`gh: Not Found (HTTP 404)`, `glab: 401 Unauthorized (HTTP 401)`);+//! `az` writes its own prose, which names the remedy where there is one. Either+//! way that line stays accurate across locale, CLI version, and API rewording in+//! a way our paraphrase of it would not.+//!+//! A provider writes a message of its own only where the CLI structurally cannot+//! report the condition:+//!+//! - **GitHub's 404** answers about an owner/repo that is *our* choice — from+//! `gh repo set-default` or from a remote — so it often means the choice was+//! wrong rather than that the PR is missing. `gh` reports the miss; only we+//! know what we asked for and where the question came from.+//! - **Azure DevOps' missing extension** is a precondition, not a guess: the+//! whole `az repos` command group ships in the `azure-devops` extension, and+//! `az extension list` answers for it. `az` itself never names it.+//!+//! Everything else forwards. Reading more nicely than the CLI does not qualify:+//! "GitLab CLI not authenticated" restated `glab: 401 Unauthorized (HTTP 401)`+//! with the status dropped, and cost a `starts_with("401")` test against prose+//! to select it.+//!+//! Where a provider still classifies, it keys on structure and falls through to+//! forwarding when the structure isn't there: `gh` puts a `status` field in its+//! error body, while `glab` puts the status only inside the message text, so+//! there is nothing there to key on. Gitea is the one provider whose response+//! *shape* is the error channel at all, because `tea api` copies the body to+//! stdout and exits 0 whatever the status — see [`gitea`].+//!//! # Platform-Specific Notes//!//! ## GitHub@@ -129,6 +162,11 @@ pub(super) fn run_cli_api(request: CliApiRequest<'_>) -> anyhow::Result<Output>}}+/// The CLI's own account of the failure: stderr when it wrote any, else stdout.+///+/// `gh` and `glab` write a formatted line to stderr (`gh: Not Found (HTTP 404)`)+/// and the raw API body to stdout, so preferring stderr picks the human form+/// over the JSON. The stdout fallback covers a CLI that writes only a body.pub(super) fn cli_api_error_details(output: &Output) -> String {let stderr = String::from_utf8_lossy(&output.stderr);if stderr.trim().is_empty() {@@ -138,6 +176,15 @@ pub(super) fn cli_api_error_details(output: &Output) -> String {}}+/// Wrap a failed forge-CLI invocation, rendering `message` above the CLI's own+/// output in a gutter.+///+/// Every provider's failure path ends here, and forwarding is the default:+/// `message` names the request we made ("gh api failed for PR #123") and the+/// gutter carries the CLI's verdict on it. A provider with something of its own+/// to say — the cases in the module docs — passes it as `message` rather than+/// bailing, so its words are added to the CLI's rather than substituted for+/// them.pub(super) fn cli_api_error(ref_type: RefType, message: String, output: &Output) -> anyhow::Error {GitError::CliApiError {ref_type,diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 5b54f265e..dd3b3bec1 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -3610,6 +3610,41 @@ fn test_switch_pr_not_found(#[from(repo_with_remote)] repo: TestRepo) {});}+/// A 404 is the one GitHub failure worded by us rather than forwarded from+/// `gh`, because it answers about an owner/repo we chose — so the message has to+/// name where that choice came from. With `gh repo set-default` configured, that+/// is the default, and the remedy is to check it rather than the remotes.+#[rstest]+fn test_switch_pr_not_found_gh_default(#[from(repo_with_remote)] repo: TestRepo) {+ set_github_remote_url(&repo);+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ copy_mock_binary(&mock_bin, "gh");++ MockConfig::new("gh")+ .version("gh version 2.0.0 (mock)")+ .command(+ "repo set-default --view",+ MockResponse::output("owner/other-repo\n"),+ )+ .command(+ "api",+ MockResponse::output(r#"{"message":"Not Found","status":"404"}"#)+ .with_stderr("gh: Not Found (HTTP 404)")+ .with_exit_code(1),+ )+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:9999"], None);+ configure_mock_cli_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_pr_not_found_gh_default", cmd);+ });+}+/// Regression: when the GitHub remote is *non-primary* (origin is GitLab,/// `upstream` is GitHub), `wt switch pr:N` must derive owner/repo from the/// GitHub remote, not the primary. The mock answers only the upstream's API@@ -6404,12 +6439,15 @@ fn test_switch_mr_not_found(#[from(repo_with_remote)] repo: TestRepo) {// Copy mock-stub binary as "glab"copy_mock_binary(&mock_bin, "glab");- // Configure glab api to return 404 error (JSON on stdout like real GitLab API)+ // Configure glab api to return 404 error (JSON on stdout, human-readable on+ // stderr — glab formats the API's own message as `glab: <message> (HTTP N)`)MockConfig::new("glab").version("glab version 1.40.0 (mock)").command("api",- MockResponse::output(r#"{"message":"404 Not found"}"#).with_exit_code(1),+ MockResponse::output(r#"{"message":"404 Not found"}"#)+ .with_stderr("glab: 404 Not found (HTTP 404)")+ .with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -6430,12 +6468,15 @@ fn test_switch_mr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "glab");- // Configure glab api to return 401 error (JSON on stdout like real GitLab API)+ // Configure glab api to return 401 error (JSON on stdout, human-readable on+ // stderr — the shape a real `glab api` produces for a rejected token)MockConfig::new("glab").version("glab version 1.40.0 (mock)").command("api",- MockResponse::output(r#"{"message":"401 Unauthorized"}"#).with_exit_code(1),+ MockResponse::output(r#"{"message":"401 Unauthorized"}"#)+ .with_stderr("glab: 401 Unauthorized (HTTP 401)")+ .with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snapindex 69d0698aa..1e0f19312 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snap@@ -7,8 +7,10 @@ info:- "mr:101"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"@@ -35,6 +37,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -47,4 +50,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching MR !101...[39m-[31m✗[39m [31mGitLab CLI not authenticated; run glab auth login[39m+[31m✗[39m [31mglab api failed for MR !101[39m+[107m [0m glab: 401 Unauthorized (HTTP 401)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snapindex c45f2f17b..9e4e72cce 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snap@@ -7,8 +7,10 @@ info:- "mr:9999"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"@@ -35,6 +37,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -47,4 +50,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching MR !9999...[39m-[31m✗[39m [31mMR !9999 not found[39m+[31m✗[39m [31mglab api failed for MR !9999[39m+[107m [0m glab: 404 Not found (HTTP 404)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snapindex 174730b9c..ab4497fb6 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snap@@ -7,8 +7,10 @@ info:- "pr:101"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"@@ -35,6 +37,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -47,4 +50,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching PR #101...[39m-[31m✗[39m [31mGitHub CLI not authenticated; run gh auth login[39m+[31m✗[39m [31mgh api failed for PR #101[39m+[107m [0m gh: Requires authentication (HTTP 401)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snapindex edf8fc5b1..601d48f70 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snap@@ -7,8 +7,10 @@ info:- "pr:9999"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"@@ -35,6 +37,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -48,3 +51,4 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching PR #9999...[39m[31m✗[39m [31mPR #9999 not found on owner/test-repo (github remote). If the PR is on a different repository, run `gh repo set-default` to set the default or configure a different primary remote.[39m+[107m [0m gh: Not Found (HTTP 404)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found_gh_default.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found_gh_default.snapnew file mode 100644index 000000000..9ba7b08aa--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found_gh_default.snap@@ -0,0 +1,54 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "pr:9999"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ 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_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching PR #9999...[39m+[31m✗[39m [31mPR #9999 not found on owner/other-repo (gh default). Check that `gh repo set-default` points to the correct repository.[39m+[107m [0m gh: Not Found (HTTP 404)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snapindex 6cb1a2ff0..f15df09a1 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snap@@ -7,8 +7,10 @@ info:- "pr:101"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"@@ -35,6 +37,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -47,4 +50,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching PR #101...[39m-[31m✗[39m [31mGitHub API rate limit exceeded; wait a few minutes and retry[39m+[31m✗[39m [31mgh api failed for PR #101[39m+[107m [0m gh: API rate limit exceeded (HTTP 403)