Skip to content

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

fix(gitea): key the tea api error shape on the envelope, not on a non-empty message (#3600)

Maximilian Roos10e8bad2c596
diff --git a/src/commands/list/ci_status/gitea.rs b/src/commands/list/ci_status/gitea.rs
index 43b5ea929..a2bfba0f5 100644
--- a/src/commands/list/ci_status/gitea.rs
+++ b/src/commands/list/ci_status/gitea.rs
@@ -5,6 +5,7 @@
use serde::Deserialize;
use std::process::Output;
+use worktrunk::git::remote_ref::gitea::api_error_message;
use worktrunk::git::{Repository, parse_owner_repo};
use super::{
@@ -33,18 +34,22 @@ fn tea_api(repo: &Repository, path: &str) -> Option<Output> {
/// — it copies the response body to stdout and exits 0 — so a non-zero exit
/// means `tea` itself failed (transport error, no login configured) and its
/// stderr names which, while every HTTP error arrives as a successful spawn
-/// carrying Gitea's `APIError` body in place of the resource. Branching on the
-/// exit code alone would let that body through as data: every field of
-/// [`GiteaCombinedStatus`] defaults, so a 500 would deserialize as "no
-/// statuses" and paint a blank CI cell.
+/// carrying Gitea's `APIError` body in place of the resource, which
+/// [`api_error_message`] classifies by shape. Branching on the exit code alone
+/// would let that body through as data: every field of [`GiteaCombinedStatus`]
+/// defaults, so a 500 would deserialize as "no statuses" and paint a blank CI
+/// cell.
+///
+/// A 500 whose message Gitea blanked comes back as an empty string — an error
+/// with nothing to sniff, which [`is_retriable_error`] reads as non-retriable,
+/// so the cell stays blank. That is the same cell the body would have produced
+/// as data, but reaching it as an error keeps the PR-list path from warning
+/// about a Gitea API change when the API in fact answered with an error.
fn tea_api_error(output: &Output) -> Option<String> {
if !output.status.success() {
return Some(output_error_text(output));
}
- serde_json::from_slice::<GiteaApiError>(&output.stdout)
- .ok()
- .map(|error| error.message)
- .filter(|message| !message.trim().is_empty())
+ api_error_message(&output.stdout)
}
/// Fetch the combined CI status for a commit SHA.
@@ -193,15 +198,6 @@ fn parse_gitea_status_state(state: &str) -> Option<CiStatus> {
}
}
-/// Gitea's `APIError` body, which the API returns in place of the resource
-/// whenever a request fails. `message` carries no `#[serde(default)]` so the
-/// shape only matches a real error body — the success shapes here (a PR array,
-/// a combined status) have no `message` field.
-#[derive(Debug, Deserialize)]
-struct GiteaApiError {
- message: String,
-}
-
/// Combined commit status from `GET /repos/{owner}/{repo}/commits/{ref}/status`.
#[derive(Debug, Deserialize)]
struct GiteaCombinedStatus {
@@ -290,8 +286,9 @@ mod tests {
/// `tea_api_error` reads the response shape, since the exit code carries
/// nothing: a PR array and a combined status are data, an `APIError` body
/// is the failure. Gitea blanks the message of a 500 for a non-admin token,
- /// which leaves nothing to sniff — that falls through to the data path,
- /// where the parse decides.
+ /// which leaves nothing to sniff but is still the error shape — it comes
+ /// back as an empty message rather than falling through to the data path,
+ /// where the PR-list parse would blame a Gitea API change.
#[test]
fn test_tea_api_error_reads_the_response_shape() {
// `ExitStatus::default()` is success on every platform, so these all
@@ -311,7 +308,17 @@ mod tests {
tea_api_error(&response(r#"{"message":"token does not have scope"}"#)),
Some("token does not have scope".to_string())
);
- assert_eq!(tea_api_error(&response(r#"{"message":" "}"#)), None);
+ // A production 500 for a non-admin token: the envelope, no text.
+ assert_eq!(
+ tea_api_error(&response(
+ r#"{"message":"","url":"https://gitea.example.com/api/swagger"}"#
+ )),
+ Some(String::new())
+ );
+ assert_eq!(
+ tea_api_error(&response(r#"{"message":" "}"#)),
+ Some(String::new())
+ );
}
#[test]
diff --git a/src/git/remote_ref/gitea.rs b/src/git/remote_ref/gitea.rs
index a80b696ec..162a85f9a 100644
--- a/src/git/remote_ref/gitea.rs
+++ b/src/git/remote_ref/gitea.rs
@@ -1,6 +1,10 @@
//! Gitea PR provider.
//!
-//! Implements `RemoteRefProvider` for Gitea Pull Requests using the `tea` CLI.
+//! Implements `RemoteRefProvider` for Gitea Pull Requests using the `tea` CLI,
+//! and hosts the `tea`-facing helpers other modules share: [`api_error_message`]
+//! (how every caller separates a failed request from a resource),
+//! [`is_authed_for`], and [`has_any_login`] — read by the switch dispatcher and
+//! the CI-status backend, so a change to one of them is not local.
//!
//! ## API path resolution
//!
@@ -55,10 +59,38 @@ struct TeaApiPrResponse {
/// whenever the request fails.
#[derive(Debug, Deserialize)]
struct TeaApiErrorResponse {
- #[serde(default)]
message: String,
}
+/// The message from Gitea's `APIError` body, or `None` when the response
+/// carries the resource.
+///
+/// `tea api` never reads the HTTP status — it copies the response body to
+/// stdout and exits 0 — so the body's *shape* is the only thing separating a
+/// failed request from a successful one, and the presence of a `message` key
+/// is that shape: none of the resources read here (a PR object, a PR array, a
+/// combined commit status) carries one.
+///
+/// The message's *content* is not part of the key. Gitea blanks a 500's
+/// message in production unless the token belongs to an admin, so that body
+/// arrives as `{"message":"","url":"…/api/swagger"}`; keying on a non-empty
+/// message would read it as the resource — a PR array that fails to parse, or
+/// a combined status whose fields all default to "no statuses".
+///
+/// `url` is not part of the key either, though `APIError` carries one: an error
+/// shape that omits it — Gitea has them, `APIInvalidTopicsError` being `message`
+/// plus `invalidTopics` — would read as the resource, the failure this key
+/// exists to prevent, while requiring it would only guard against a resource
+/// one day growing a `message` field.
+///
+/// Callers render the empty message themselves: what to say about an error the
+/// server won't describe depends on what the caller was doing.
+pub fn api_error_message(stdout: &[u8]) -> Option<String> {
+ serde_json::from_slice::<TeaApiErrorResponse>(stdout)
+ .ok()
+ .map(|error| error.message.trim().to_string())
+}
+
#[derive(Debug, Deserialize)]
struct TeaUser {
login: String,
@@ -130,28 +162,26 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
// carrying Gitea's `APIError` body instead of the PR. The response shape
// is what separates them, and it's the only thing that can: the status
// code never reaches us, and Gitea's message doesn't spell it either.
- let response: TeaApiPrResponse = match serde_json::from_slice(&output.stdout) {
- Ok(response) => response,
- Err(parse_error) => {
- let api_error = serde_json::from_slice::<TeaApiErrorResponse>(&output.stdout)
- .ok()
- .filter(|e| !e.message.trim().is_empty());
- if let Some(api_error) = api_error {
- bail!(
- "Gitea API error for PR #{} on {}/{}: {}",
- pr_number,
- parsed.owner(),
- parsed.repo(),
- api_error.message.trim()
- );
- }
- return Err(anyhow::Error::from(parse_error).context(format!(
- "Failed to parse Gitea API response for PR #{}. \
- This may indicate a Gitea API change.",
- pr_number
- )));
+ if let Some(message) = api_error_message(&output.stdout) {
+ let (owner, repo_name) = (parsed.owner(), parsed.repo());
+ if message.is_empty() {
+ bail!(
+ "Gitea API error for PR #{pr_number} on {owner}/{repo_name}, but the response \
+ carried no message — Gitea hides 500 messages from non-admin tokens"
+ );
}
- };
+ bail!("Gitea API error for PR #{pr_number} on {owner}/{repo_name}: {message}");
+ }
+
+ // Neither the resource nor an error envelope: report the parse failure,
+ // whose source names where the body diverged.
+ let response: TeaApiPrResponse = serde_json::from_slice(&output.stdout).with_context(|| {
+ format!(
+ "Failed to parse Gitea API response for PR #{}. \
+ This may indicate a Gitea API change.",
+ pr_number
+ )
+ })?;
// Check head.repo before extract_source_branch so deleted-source PRs hit
// the specific "source repository was deleted" message instead of falling
@@ -358,6 +388,36 @@ mod tests {
assert_eq!(provider.ref_type(), crate::git::RefType::Pr);
}
+ /// The `APIError` envelope is recognized by the presence of a `message`
+ /// key, not by what the message says: a 500 whose message Gitea blanked
+ /// for a non-admin token is still an error, not a PR.
+ #[test]
+ fn test_api_error_message_reads_the_response_shape() {
+ let error = |body: &str| api_error_message(body.as_bytes());
+
+ assert_eq!(
+ error(
+ r#"{"errors":null,"message":"token is required","url":"https://gitea.example.com/api/swagger"}"#
+ ),
+ Some("token is required".to_string())
+ );
+ assert_eq!(
+ error(r#"{"message":"","url":"https://gitea.example.com/api/swagger"}"#),
+ Some(String::new())
+ );
+ assert_eq!(error(r#"{"message":" "}"#), Some(String::new()));
+
+ // The resources read through `tea api` carry no `message`, so they
+ // stay data: a single PR, a PR array, a combined commit status.
+ assert_eq!(error(r#"{"title":"Fix login","state":"open"}"#), None);
+ assert_eq!(error("[]"), None);
+ assert_eq!(error(r#"{"state":"success","total_count":2}"#), None);
+
+ // Neither shape — the caller reports a parse failure, not an API error.
+ assert_eq!(error(r#"{"unexpected":1}"#), None);
+ assert_eq!(error("not json"), None);
+ }
+
#[test]
fn test_extract_source_branch_prefers_label() {
let head = TeaPrRef {
diff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rs
index 6a15d786a..94cfa0d49 100644
--- a/tests/integration_tests/ci_status.rs
+++ b/tests/integration_tests/ci_status.rs
@@ -12,7 +12,7 @@
use crate::common::{
TestRepo, make_snapshot_cmd,
mock_commands::{MockConfig, MockResponse},
- repo, setup_snapshot_settings,
+ repo, setup_snapshot_settings, wt_command,
};
use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
@@ -1178,6 +1178,14 @@ const GITEA_API_ERROR_BODY: &str = r#"{
"url": "https://gitea.example.com/api/swagger"
}"#;
+/// The same body a production Gitea sends a non-admin token for that 500:
+/// `APIError` with the message blanked. Only the envelope is left, which is
+/// what `api_error_message` keys on.
+const GITEA_BLANK_ERROR_BODY: &str = r#"{
+ "message": "",
+ "url": "https://gitea.example.com/api/swagger"
+}"#;
+
/// Build a one-PR `tea api .../pulls` response for the `feature` branch.
fn gitea_feature_pr_json(head_sha: &str, mergeable: bool) -> String {
format!(
@@ -1267,6 +1275,62 @@ fn test_list_full_with_gitea_commit_status_error_body(mut repo: TestRepo) {
);
}
+/// Run `wt list --full` against the given `tea api .../pulls` body and return
+/// stderr.
+///
+/// `RUST_LOG=warn` because `parse_json`'s warning is a `tracing` record and the
+/// stderr layer is off at the default verbosity; `-v` would turn it on but bury
+/// it under a template expansion per worktree.
+fn gitea_ci_status_stderr(repo: &mut TestRepo, head_sha: &str, pulls_json: &str) -> String {
+ repo.setup_mock_tea_with_ci_data(
+ "owner",
+ "test-repo",
+ head_sha,
+ pulls_json,
+ r#"{"state":"","total_count":0}"#,
+ );
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env("RUST_LOG", "warn");
+ cmd.args(["list", "--full"]).current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
+ assert!(output.status.success(), "wt list --full failed: {stderr}");
+ stderr
+}
+
+/// "May indicate a Gitea API change" is reserved for a body that is neither the
+/// resource nor the error envelope.
+///
+/// A blanked message is still the envelope, so the PR list never reads it as
+/// data. The CI cell is blank either way — an empty message isn't retriable —
+/// so what the key buys is the diagnosis: requiring a *non-empty* message let
+/// that body through to `parse_json`, which blamed a Gitea API change for a
+/// Gitea API error. The unknown-body case is the control: it pins where the
+/// warning does belong, and keeps the first case from passing merely because
+/// nothing logs at all.
+///
+/// One case per repo, not two runs in one: `wt list` caches CI status per
+/// branch for 30s, so a second run against the same HEAD never reaches `tea`.
+#[rstest]
+#[case::blank_message_is_still_an_error(GITEA_BLANK_ERROR_BODY, false)]
+#[case::unknown_body_is_a_parse_failure(r#"{"unexpected":1}"#, true)]
+fn test_list_full_gitea_parse_warning_is_reserved_for_unknown_bodies(
+ mut repo: TestRepo,
+ #[case] pulls_json: &str,
+ #[case] expect_parse_warning: bool,
+) {
+ let head_sha = setup_gitea_repo_with_feature(&mut repo);
+ let stderr = gitea_ci_status_stderr(&mut repo, &head_sha, pulls_json);
+
+ assert_eq!(
+ stderr.contains("Failed to parse tea api pulls JSON"),
+ expect_parse_warning,
+ "wrong diagnosis for {pulls_json}: {stderr}"
+ );
+}
+
/// `tea` itself failing on `tea api .../pulls` surfaces as an error indicator
/// rather than NoCI (exercises the `is_retriable_error` branch in
/// `detect_gitea_pr`). A transport failure is the case that does exit non-zero,
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 1950bb68b..70683a039 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -5475,6 +5475,43 @@ fn test_switch_pr_gitea_forbidden(#[from(repo_with_remote)] repo: TestRepo) {
});
}
+/// A 500 reaches the user as an API error, not as a parse failure. Gitea
+/// blanks the message of a 500 in production unless the token belongs to an
+/// admin, so the body arrives as the same `APIError` envelope with nothing in
+/// it — the shape still says the request failed, and the message says why
+/// there's no more to report.
+#[rstest]
+fn test_switch_pr_gitea_blank_error_message(#[from(repo_with_remote)] repo: TestRepo) {
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://gitea.example.com/owner/test-repo.git",
+ ]);
+
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+ copy_mock_binary(&mock_bin, "tea");
+
+ MockConfig::new("tea")
+ .version("tea version development (mock)")
+ .command(
+ "api",
+ MockResponse::output(
+ r#"{"errors":null,"message":"","url":"https://gitea.example.com/api/swagger"}"#,
+ ),
+ )
+ .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:101"], None);
+ configure_mock_cli_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_gitea_blank_error_message", cmd);
+ });
+}
+
// ============================================================================
// PR Syntax Tests on Azure DevOps remotes
//
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_gitea_blank_error_message.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_gitea_blank_error_message.snap
new file mode 100644
index 000000000..e3df61c05
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_gitea_blank_error_message.snap
@@ -0,0 +1,52 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "pr:101"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ 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_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 -----
+◎ Fetching PR #101...
+✗ Gitea API error for PR #101 on owner/test-repo, but the response carried no message — Gitea hides 500 messages from non-admin tokens