Skip to content

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

fix(list): leave CI blank when the forge CLI isn't logged in (#4449)

Maximilian Roosf98bd11816e0
diff --git a/docs/src/content/docs/list.md b/docs/src/content/docs/list.md
index 0066c01a0..e6fed0b6e 100644
--- a/docs/src/content/docs/list.md
+++ b/docs/src/content/docs/list.md
@@ -119,10 +119,10 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az
| <span style='color:#a00'>#</span> red | `"failed"` | One or more checks failed |
| <span style='color:#a60'>#</span> yellow | `"conflicts"` | Merge conflicts with the target branch |
| <span style='color:#888'>#</span> gray | `"no-ci"` | No PR/MR, or no checks configured |
-| <span style='color:#a60'>⚠</span> yellow | `"error"` | CI status could not be fetched (not logged in, rate limit, network, etc.) |
+| <span style='color:#a60'>⚠</span> yellow | `"error"` | CI status could not be fetched (expired login, rate limit, network, etc.) |
| <span style='color:#a0a'>#</span> magenta | `"changes_requested"` | A reviewer requested changes |
| <span style='color:#0aa'>#</span> cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |
-| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |
+| (blank) | `pr` and `checks` absent | Branch never pushed, forge CLI not logged in to the host, or no PR/MR and no branch workflow |
The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/list.md b/plugins/worktrunk/skills/worktrunk/reference/list.md
index e76e7ecf0..5493106e9 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/list.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/list.md
@@ -105,10 +105,10 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az
| `#` red | `"failed"` | One or more checks failed |
| `#` yellow | `"conflicts"` | Merge conflicts with the target branch |
| `#` gray | `"no-ci"` | No PR/MR, or no checks configured |
-| `⚠` yellow | `"error"` | CI status could not be fetched (not logged in, rate limit, network, etc.) |
+| `⚠` yellow | `"error"` | CI status could not be fetched (expired login, rate limit, network, etc.) |
| `#` magenta | `"changes_requested"` | A reviewer requested changes |
| `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |
-| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |
+| (blank) | `pr` and `checks` absent | Branch never pushed, forge CLI not logged in to the host, or no PR/MR and no branch workflow |
The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.
diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.md
index e76e7ecf0..5493106e9 100644
--- a/skills/worktrunk/reference/list.md
+++ b/skills/worktrunk/reference/list.md
@@ -105,10 +105,10 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az
| `#` red | `"failed"` | One or more checks failed |
| `#` yellow | `"conflicts"` | Merge conflicts with the target branch |
| `#` gray | `"no-ci"` | No PR/MR, or no checks configured |
-| `⚠` yellow | `"error"` | CI status could not be fetched (not logged in, rate limit, network, etc.) |
+| `⚠` yellow | `"error"` | CI status could not be fetched (expired login, rate limit, network, etc.) |
| `#` magenta | `"changes_requested"` | A reviewer requested changes |
| `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |
-| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |
+| (blank) | `pr` and `checks` absent | Branch never pushed, forge CLI not logged in to the host, or no PR/MR and no branch workflow |
The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index b75208329..079a0e8cc 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -911,10 +911,10 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az
| `#` red | `"failed"` | One or more checks failed |
| `#` yellow | `"conflicts"` | Merge conflicts with the target branch |
| `#` gray | `"no-ci"` | No PR/MR, or no checks configured |
-| `⚠` yellow | `"error"` | CI status could not be fetched (not logged in, rate limit, network, etc.) |
+| `⚠` yellow | `"error"` | CI status could not be fetched (expired login, rate limit, network, etc.) |
| `#` magenta | `"changes_requested"` | A reviewer requested changes |
| `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |
-| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |
+| (blank) | `pr` and `checks` absent | Branch never pushed, forge CLI not logged in to the host, or no PR/MR and no branch workflow |
The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index a45ff9b3d..a5c06858d 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -386,28 +386,35 @@ mod tests {
fn test_render_ci_tool_status() {
// Installed and authenticated
let mut out = String::new();
- render_ci_tool_status(&mut out, "gh", "GitHub", true, true);
+ render_ci_tool_status(&mut out, "gh", "GitHub", Some("github.com"), true, true);
assert_snapshot!(out, @"○ gh installed & authenticated");
// Installed but not authenticated
let mut out = String::new();
- render_ci_tool_status(&mut out, "gh", "GitHub", true, false);
+ render_ci_tool_status(&mut out, "gh", "GitHub", Some("github.com"), true, false);
assert_snapshot!(out, @"
- ▲ gh installed but not authenticated
+ ▲ gh installed but not authenticated for github.com
↳ To authenticate, run gh auth login
");
// The auth-setup command differs by CLI: `tea` uses `tea login add`,
// `az` uses `az login`, the rest use `<tool> auth login`.
let mut out = String::new();
- render_ci_tool_status(&mut out, "tea", "Gitea", true, false);
+ render_ci_tool_status(
+ &mut out,
+ "tea",
+ "Gitea",
+ Some("gitea.example.com"),
+ true,
+ false,
+ );
assert_snapshot!(out, @"
- ▲ tea installed but not authenticated
+ ▲ tea installed but not authenticated for gitea.example.com
↳ To authenticate, run tea login add
");
let mut out = String::new();
- render_ci_tool_status(&mut out, "az", "Azure DevOps", true, false);
+ render_ci_tool_status(&mut out, "az", "Azure DevOps", None, true, false);
assert_snapshot!(out, @"
▲ az installed but not authenticated
↳ To authenticate, run az login
@@ -415,12 +422,12 @@ mod tests {
// Not installed
let mut out = String::new();
- render_ci_tool_status(&mut out, "glab", "GitLab", false, false);
+ render_ci_tool_status(&mut out, "glab", "GitLab", Some("gitlab.com"), false, false);
assert_snapshot!(out, @"○ glab not found (GitLab CI status unavailable)");
// glab installed and authenticated
let mut out = String::new();
- render_ci_tool_status(&mut out, "glab", "GitLab", true, true);
+ render_ci_tool_status(&mut out, "glab", "GitLab", Some("gitlab.com"), true, true);
assert_snapshot!(out, @"○ glab installed & authenticated");
}
}
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index e5c6c495f..2998abc64 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -15,7 +15,7 @@ use worktrunk::config::{
require_config_path, system_config_path,
};
use worktrunk::git::remote_ref::azure::azure_devops_extension_installed;
-use worktrunk::git::{ErrorExt, ForgeKind, Repository, WorktrunkError};
+use worktrunk::git::{ErrorExt, ForgeKind, Repository, WorktrunkError, remote_ref};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{
FileDetectionResult, Shell, ZshStartupScope, probe_zsh_compdef, scan_for_detection_details,
@@ -30,7 +30,7 @@ use crate::cli::{SwitchFormat, version_str};
use crate::commands::configure_shell::{
ConfigAction, ConfigureResult, ShellConfigError, scan_shell_configs,
};
-use crate::commands::list::ci_status::CiToolsStatus;
+use crate::commands::list::ci_status::{auth_host, tool_available};
use crate::help_pager::show_help_in_pager;
use crate::llm::test_commit_generation;
use crate::output;
@@ -584,49 +584,38 @@ fn render_diagnostics(out: &mut String, repo: Option<&Repository>) -> anyhow::Re
// else remote URL). Outside a repository there is no platform, so this
// falls through to the hint and the remaining checks still run.
match repo.and_then(|repo| Some((repo, repo.ci_platform(None)?))) {
- Some((_, ForgeKind::GitHub)) => {
- let ci_tools = CiToolsStatus::detect(None)?;
- render_ci_tool_status(
- out,
- "gh",
- "GitHub",
- ci_tools.gh_installed,
- ci_tools.gh_authenticated,
- );
- }
- Some((_, ForgeKind::GitLab)) => {
- let ci_tools = CiToolsStatus::detect(None)?;
- render_ci_tool_status(
- out,
- "glab",
- "GitLab",
- ci_tools.glab_installed,
- ci_tools.glab_authenticated,
- );
- }
- Some((_, ForgeKind::Gitea)) => {
- let ci_tools = CiToolsStatus::detect(None)?;
- render_ci_tool_status(
- out,
- "tea",
- "Gitea",
- ci_tools.tea_installed,
- ci_tools.tea_authenticated,
- );
- }
- Some((repo, ForgeKind::AzureDevOps)) => {
- let ci_tools = CiToolsStatus::detect(None)?;
- render_ci_tool_status(
- out,
- "az",
- "Azure DevOps",
- ci_tools.az_installed,
- ci_tools.az_authenticated,
- );
+ Some((repo, platform)) => {
+ let tool = platform.cli();
+ let installed = tool_available(tool, &["--version"]);
+ // The host CI status asks about: the primary remote's.
+ let remote_url = repo
+ .primary_remote()
+ .ok()
+ .and_then(|remote| repo.effective_remote_url(&remote));
+ let host = auth_host(repo, remote_url);
+ let authenticated = installed
+ && match &host {
+ Some(host) => remote_ref::is_authed_for(platform, host)?,
+ None => false,
+ };
+ let name = match platform {
+ ForgeKind::GitHub => "GitHub",
+ ForgeKind::GitLab => "GitLab",
+ ForgeKind::Gitea => "Gitea",
+ ForgeKind::AzureDevOps => "Azure DevOps",
+ };
+ // Azure CLI logins aren't per host.
+ let login_host = host
+ .as_deref()
+ .filter(|_| platform != ForgeKind::AzureDevOps);
+ render_ci_tool_status(out, tool, name, login_host, installed, authenticated);
// The whole `az repos` command group ships in the azure-devops
// extension, so an `az` without it reports no CI status however
// well it's authenticated — and only the user can install it.
- if ci_tools.az_installed && !azure_devops_extension_installed(repo.repo_path()?) {
+ if platform == ForgeKind::AzureDevOps
+ && installed
+ && !azure_devops_extension_installed(repo.repo_path()?)
+ {
writeln!(
out,
"{}",
@@ -1673,6 +1662,7 @@ pub(super) fn render_ci_tool_status(
out: &mut String,
tool: &str,
platform: &str,
+ host: Option<&str>,
installed: bool,
authenticated: bool,
) {
@@ -1682,6 +1672,10 @@ pub(super) fn render_ci_tool_status(
))
} else if authenticated {
info_message(cformat!("<bold>{tool}</> installed & authenticated"))
+ } else if let Some(host) = host {
+ warning_message(cformat!(
+ "<bold>{tool}</> installed but not authenticated for <bold>{host}</>"
+ ))
} else {
warning_message(cformat!("<bold>{tool}</> installed but not authenticated"))
};
diff --git a/src/commands/list/ci_status/gitea.rs b/src/commands/list/ci_status/gitea.rs
index e319fbd94..ad55008ef 100644
--- a/src/commands/list/ci_status/gitea.rs
+++ b/src/commands/list/ci_status/gitea.rs
@@ -19,7 +19,7 @@ use super::{
/// status reaches us — see the [`gitea`](worktrunk::git::remote_ref::gitea)
/// module docs.
///
-/// `is_tool_available` has already confirmed `tea` is on PATH, so a spawn
+/// `detect_ci` has already confirmed `tea` is on PATH, so a spawn
/// failure here is an OS-level edge case — fall through to `None` (no CI status
/// for this branch) rather than logging.
fn tea_api(repo: &Repository, path: &str) -> Option<Output> {
diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rs
index 527745f79..411316d8e 100644
--- a/src/commands/list/ci_status/github.rs
+++ b/src/commands/list/ci_status/github.rs
@@ -99,7 +99,7 @@ pub(super) fn detect_github(
};
if !output.status.success() {
- return Some(PrStatus::error());
+ return gh_failure(&output);
}
// gh pr list returns an array - find the first PR from our origin
@@ -192,6 +192,14 @@ fn prime_comments_cache(repo: &Repository, pr_info: &GitHubPrInfo) {
preview_cache::write_comments(repo, number as u32, updated_at, &entries);
}
+/// The CI status for a failed `gh` call: none when `gh` holds no login for
+/// the host it resolved for the request (its documented exit code 4), else the
+/// error indicator.
+fn gh_failure(output: &std::process::Output) -> Option<PrStatus> {
+ const AUTH_REQUIRED: i32 = 4;
+ (output.status.code() != Some(AUTH_REQUIRED)).then(PrStatus::error)
+}
+
/// Detect CI status for a commit using GitHub's check-runs API.
///
/// This queries all check runs for the commit SHA, giving us the same data
@@ -238,7 +246,7 @@ pub(super) fn detect_github_commit_checks(
};
if !output.status.success() {
- return Some(PrStatus::error());
+ return gh_failure(&output);
}
let checks: Vec<GitHubCheck> = parse_json(&output.stdout, "gh api check-runs", local_head)?;
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index c5fb5cd45..49d4c1a12 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -16,7 +16,7 @@ use super::layout::LinkStyle;
use anstyle::{AnsiColor, Color, Style};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
-use worktrunk::git::{BranchRef, RefType, Repository, parse_owner_repo};
+use worktrunk::git::{BranchRef, GitRemoteUrl, RefType, Repository, parse_owner_repo};
use worktrunk::shell_exec::Cmd;
use worktrunk::utils::epoch_now;
@@ -166,6 +166,13 @@ fn branch_owner_repo(repo: &Repository, branch: &CiBranchName) -> Option<(String
parse_owner_repo(&branch_remote_url(repo, branch)?)
}
+/// The host a forge CLI authenticates against for `remote_url`: the configured
+/// `forge.hostname` when set, else the URL's host.
+pub(crate) fn auth_host(repo: &Repository, remote_url: Option<String>) -> Option<String> {
+ repo.forge_hostname()
+ .or_else(|| Some(GitRemoteUrl::parse(&remote_url?)?.host().to_string()))
+}
+
/// Resolve the effective URL for a branch's remote without parsing.
///
/// Resolution chain:
@@ -191,64 +198,6 @@ fn branch_remote_url(repo: &Repository, branch: &CiBranchName) -> Option<String>
}
}
-/// Status of CI tools availability
-#[derive(Debug, Clone, Copy)]
-pub struct CiToolsStatus {
- /// gh is installed (can run --version)
- pub gh_installed: bool,
- /// gh is installed and authenticated
- pub gh_authenticated: bool,
- /// glab is installed (can run --version)
- pub glab_installed: bool,
- /// glab is installed and authenticated
- pub glab_authenticated: bool,
- /// tea is installed (can run --version)
- pub tea_installed: bool,
- /// tea is installed and has a login configured
- pub tea_authenticated: bool,
- /// az is installed (can run --version)
- pub az_installed: bool,
- /// az is installed and authenticated (logged in)
- pub az_authenticated: bool,
-}
-
-impl CiToolsStatus {
- /// Check which CI tools are available
- ///
- /// If `gitlab_host` is provided, checks glab auth status against that specific
- /// host instead of the default. This is important for self-hosted GitLab instances
- /// where the default host (gitlab.com) may be unreachable.
- pub fn detect(gitlab_host: Option<&str>) -> anyhow::Result<Self> {
- let gh_installed = tool_available("gh", &["--version"]);
- let gh_authenticated = gh_installed && tool_available("gh", &["auth", "status"]);
- let glab_installed = tool_available("glab", &["--version"]);
- let glab_authenticated = glab_installed
- && if let Some(host) = gitlab_host {
- tool_available("glab", &["auth", "status", "--hostname", host])
- } else {
- tool_available("glab", &["auth", "status"])
- };
- let tea_installed = tool_available("tea", &["--version"]);
- // The shared tea login probe reads local config through `logins list`.
- let tea_authenticated =
- tea_installed && worktrunk::git::remote_ref::gitea::has_any_login()?;
- let az_installed = tool_available("az", &["--version"]);
- // `az account show` exits non-zero when logged out — works whether or not
- // the azure-devops extension is installed.
- let az_authenticated = az_installed && tool_available("az", &["account", "show"]);
- Ok(Self {
- gh_installed,
- gh_authenticated,
- glab_installed,
- glab_authenticated,
- tea_installed,
- tea_authenticated,
- az_installed,
- az_authenticated,
- })
- }
-}
-
/// CI status from GitHub/GitLab checks
/// Matches the statusline.sh color scheme:
/// - Passed: Green (all checks passed)
diff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rs
index 6c72e5b1d..502e1d1b2 100644
--- a/src/commands/list/ci_status/platform.rs
+++ b/src/commands/list/ci_status/platform.rs
@@ -3,44 +3,53 @@
//! Given a [`ForgeKind`] (resolved by [`Repository::ci_platform`]), routes to
//! the GitHub (`gh`), GitLab (`glab`), Gitea (`tea`), or Azure DevOps (`az`)
//! backend and checks whether that CLI is installed.
+//!
+//! A failed call shows the error indicator only when the CLI holds a login for
+//! the forge's host. Without one, the user isn't using that CLI here, and the
+//! cell stays blank. `gh` says so itself, with exit code 4 for the host it
+//! resolved for the request; for the other CLIs, a login check reads local
+//! state for the remote's host. Either way, a lost connection still shows the
+//! error.
-use std::sync::OnceLock;
+use std::sync::LazyLock;
-use worktrunk::git::{ForgeKind, Repository};
+use dashmap::DashMap;
+use worktrunk::git::{ForgeKind, Repository, remote_ref};
-use super::{CiBranchName, PrStatus, azure, gitea, github, gitlab, tool_available};
+use super::{
+ CiBranchName, CiStatus, PrStatus, auth_host, azure, branch_remote_url, gitea, github, gitlab,
+ tool_available,
+};
-/// Cached availability of CI CLI tools (`gh`, `glab`, `tea`, `az`).
-///
-/// Probed once on first access via a `--version` check.
-static CI_TOOLS: OnceLock<CiToolsAvailable> = OnceLock::new();
+/// Whether each forge's CLI is installed, probed once per process.
+static INSTALLED: LazyLock<DashMap<ForgeKind, bool>> = LazyLock::new(DashMap::new);
-struct CiToolsAvailable {
- gh: bool,
- glab: bool,
- tea: bool,
- az: bool,
-}
-
-impl CiToolsAvailable {
- fn get() -> &'static Self {
- CI_TOOLS.get_or_init(|| Self {
- gh: tool_available("gh", &["--version"]),
- glab: tool_available("glab", &["--version"]),
- tea: tool_available("tea", &["--version"]),
- az: tool_available("az", &["--version"]),
- })
- }
-}
+/// Whether each forge's CLI holds a login for a host, asked once per process,
+/// and only once a call has failed.
+static LOGGED_IN: LazyLock<DashMap<(ForgeKind, String), bool>> = LazyLock::new(DashMap::new);
/// Whether the CLI tool for this platform is installed (cached).
fn is_tool_available(platform: ForgeKind) -> bool {
- match platform {
- ForgeKind::GitHub => CiToolsAvailable::get().gh,
- ForgeKind::GitLab => CiToolsAvailable::get().glab,
- ForgeKind::Gitea => CiToolsAvailable::get().tea,
- ForgeKind::AzureDevOps => CiToolsAvailable::get().az,
+ *INSTALLED
+ .entry(platform)
+ .or_insert_with(|| tool_available(platform.cli(), &["--version"]))
+}
+
+/// Whether the platform's CLI holds a login for the branch's forge host
+/// (cached). A host that can't be resolved, or a check that can't finish,
+/// counts as logged in, leaving the failure on display.
+fn is_logged_in(platform: ForgeKind, repo: &Repository, branch: &CiBranchName) -> bool {
+ // A `gh` call without a login never reaches here: the backend reads its
+ // exit code, which follows SSH host aliases where a check by host can't.
+ if platform == ForgeKind::GitHub {
+ return true;
}
+ let Some(host) = auth_host(repo, branch_remote_url(repo, branch)) else {
+ return true;
+ };
+ *LOGGED_IN
+ .entry((platform, host.clone()))
+ .or_insert_with(|| remote_ref::is_authed_for(platform, &host).unwrap_or(true))
}
/// Detect CI status from a PR/MR.
@@ -108,7 +117,8 @@ fn detect_branch(
/// Detect CI status: PR/MR first when the branch [may head one](may_head_pr),
/// then branch workflow/pipeline if `has_upstream`.
///
-/// Returns `None` if the CLI tool isn't installed or no CI status is found.
+/// Returns `None` if the CLI tool isn't installed, no CI status is found, or a
+/// call failed and the CLI holds no login for the host.
pub(super) fn detect_ci(
platform: ForgeKind,
repo: &Repository,
@@ -119,13 +129,16 @@ pub(super) fn detect_ci(
if !is_tool_available(platform) {
return None;
}
- if may_head_pr(repo, branch)
- && let Some(status) = detect_pr_mr(platform, repo, branch, local_head)
- {
- return Some(status);
- }
- if has_upstream {
- return detect_branch(platform, repo, branch, local_head);
+ let status = may_head_pr(repo, branch)
+ .then(|| detect_pr_mr(platform, repo, branch, local_head))
+ .flatten()
+ .or_else(|| {
+ has_upstream
+ .then(|| detect_branch(platform, repo, branch, local_head))
+ .flatten()
+ })?;
+ if status.ci_status == CiStatus::Error && !is_logged_in(platform, repo, branch) {
+ return None;
}
- None
+ Some(status)
}
diff --git a/src/git/ci_platform.rs b/src/git/ci_platform.rs
index 7bd1ebe80..ef5664e4d 100644
--- a/src/git/ci_platform.rs
+++ b/src/git/ci_platform.rs
@@ -14,7 +14,7 @@ use crate::git::{GitRemoteUrl, RefType, Repository};
/// classification, remote-ref dispatch, and CI dispatch. Unknown hosts stay
/// outside the enum as `None`; callers that expose an explicit `unknown` value
/// add it only at that output boundary.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::EnumString)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, strum::EnumString)]
#[strum(serialize_all = "lowercase")]
pub enum ForgeKind {
GitHub,
@@ -63,6 +63,16 @@ impl ForgeKind {
}
}
+ /// The CLI worktrunk drives for this forge.
+ pub const fn cli(self) -> &'static str {
+ match self {
+ Self::GitHub => "gh",
+ Self::GitLab => "glab",
+ Self::Gitea => "tea",
+ Self::AzureDevOps => "az",
+ }
+ }
+
/// PR/MR vocabulary for change requests on this forge.
pub const fn ref_type(self) -> RefType {
match self {
diff --git a/src/git/remote_ref/azure.rs b/src/git/remote_ref/azure.rs
index 2e7d4935f..c903c10bf 100644
--- a/src/git/remote_ref/azure.rs
+++ b/src/git/remote_ref/azure.rs
@@ -11,6 +11,18 @@ use crate::git::url::{GitRemoteUrl, authority_host};
use crate::git::{ForgeKind, Repository};
use crate::shell_exec::Cmd;
+/// Whether `az` is logged in.
+///
+/// `az account show` reads the local profile and exits non-zero when logged
+/// out, whether or not the azure-devops extension is installed. Returns
+/// `false` if `az` is not installed.
+pub fn is_logged_in() -> bool {
+ Cmd::new("az")
+ .args(["account", "show"])
+ .run()
+ .is_ok_and(|output| output.status.success())
+}
+
/// Construct an Azure DevOps remote URL for a repo.
///
/// Emits `https://{host}/{org}/{project}/_git/{repo}` for `dev.azure.com` and
diff --git a/src/git/remote_ref/gitea.rs b/src/git/remote_ref/gitea.rs
index 1ffe771f0..41d0f89a2 100644
--- a/src/git/remote_ref/gitea.rs
+++ b/src/git/remote_ref/gitea.rs
@@ -1,8 +1,8 @@
//! Gitea PR backend using the `tea` CLI. It also hosts the `tea`-facing helpers
//! other modules share: [`api_status`] (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.
+//! request from a resource) and [`is_authed_for`] — read by the switch
+//! dispatcher, `wt config show`, and the CI-status backend, so a change to one
+//! of them is not local.
//!
//! ## Reading the HTTP status
//!
@@ -314,8 +314,8 @@ pub fn fork_remote_url(host: &str, owner: &str, repo: &str) -> String {
/// Whether `tea` has a login configured for `host`.
///
-/// Used by the switch dispatcher for ambiguous forge hosts. Login discovery is
-/// local-only; the shared login probe below owns that contract.
+/// Login discovery is local-only; the shared login probe below owns that
+/// contract.
pub fn is_authed_for(host: &str) -> anyhow::Result<bool> {
Ok(load_logins()?.iter().any(|login| {
login.ssh_host.eq_ignore_ascii_case(host)
@@ -324,11 +324,6 @@ pub fn is_authed_for(host: &str) -> anyhow::Result<bool> {
}))
}
-/// Whether `tea` has any login configured, for host-agnostic diagnostics.
-pub fn has_any_login() -> anyhow::Result<bool> {
- Ok(!load_logins()?.is_empty())
-}
-
/// The login-list JSON carries display fields, with no authentication tokens.
#[derive(Debug, Deserialize)]
struct TeaLogin {
@@ -338,7 +333,7 @@ struct TeaLogin {
/// Ask tea to read its own local config, including its platform-specific paths
/// and legacy fallback. Unlike API login lookup, `logins list` does not
-/// refresh OAuth tokens or contact the server. Both auth consumers use this
+/// refresh OAuth tokens or contact the server. [`is_authed_for`] uses this
/// command so config discovery and YAML parsing remain tea's responsibility.
///
/// An absent or failing CLI means no known login, matching the auth probes for
diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rs
index 2feab8760..9e3f1f879 100644
--- a/src/git/remote_ref/github.rs
+++ b/src/git/remote_ref/github.rs
@@ -214,16 +214,14 @@ pub(super) fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result
/// Get the git protocol preference from `gh` (GitHub CLI).
fn use_ssh_protocol() -> bool {
- cli_config_value("gh", "git_protocol").as_deref() == Some("ssh")
+ cli_config_value("gh", &["git_protocol"]).as_deref() == Some("ssh")
}
/// Whether `gh` has an authentication token configured for `host`.
///
-/// Used by the switch dispatcher to decide which forge CLI to try when the
-/// remote URL doesn't unambiguously identify the forge (e.g. self-hosted on
-/// `git.example.com`). `gh auth token --hostname <host>` reads from
-/// `~/.config/gh/hosts.yml` and the OS keyring — no network. Returns `false`
-/// if `gh` is not installed.
+/// `gh auth token --hostname <host>` reads from `~/.config/gh/hosts.yml`, the
+/// OS keyring, and `GH_TOKEN` — no network. Returns `false` if `gh` is not
+/// installed.
pub fn is_authed_for(host: &str) -> bool {
Cmd::new("gh")
.args(["auth", "token", "--hostname", host])
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rs
index 0581bf7b4..5000df5ec 100644
--- a/src/git/remote_ref/gitlab.rs
+++ b/src/git/remote_ref/gitlab.rs
@@ -242,9 +242,19 @@ fn fetch_project_urls(
Ok((response.ssh_url_to_repo, response.http_url_to_repo))
}
+/// Whether `glab` has a token for `host`.
+///
+/// `glab config get token --host <host>` reads glab's config and its token
+/// environment variables — no network, unlike `glab auth status` — and prints
+/// nothing for a host without a token. Returns `false` if `glab` is not
+/// installed.
+pub fn is_authed_for(host: &str) -> bool {
+ cli_config_value("glab", &["token", "--host", host]).is_some_and(|token| !token.is_empty())
+}
+
/// Get the git protocol configured in `glab` (GitLab CLI).
pub fn git_protocol() -> String {
- cli_config_value("glab", "git_protocol")
+ cli_config_value("glab", &["git_protocol"])
.filter(|p| p == "ssh" || p == "https")
.unwrap_or_else(|| "https".to_string())
}
diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rs
index c37f00091..d337a4c86 100644
--- a/src/git/remote_ref/mod.rs
+++ b/src/git/remote_ref/mod.rs
@@ -114,6 +114,20 @@ pub fn fetch_info(
}
}
+/// Whether `forge`'s CLI holds a login for `host`.
+///
+/// Each CLI answers from its own local state, so the answer needs no network
+/// and a lost connection never reads as logged out. Azure CLI logins aren't
+/// per host, so `host` doesn't apply to Azure DevOps.
+pub fn is_authed_for(forge: ForgeKind, host: &str) -> anyhow::Result<bool> {
+ Ok(match forge {
+ ForgeKind::GitHub => github::is_authed_for(host),
+ ForgeKind::GitLab => gitlab::is_authed_for(host),
+ ForgeKind::Gitea => gitea::is_authed_for(host)?,
+ ForgeKind::AzureDevOps => azure::is_logged_in(),
+ })
+}
+
/// Get the fetch ref path for a forge PR/MR.
pub fn ref_path(forge: ForgeKind, number: u32) -> String {
match forge {
@@ -200,9 +214,11 @@ pub(super) fn extract_host_from_html_url(html_url: &str) -> anyhow::Result<Strin
.with_context(|| format!("Failed to parse host from PR URL: {html_url}"))
}
-pub(super) fn cli_config_value(tool: &str, key: &str) -> Option<String> {
+/// `<tool> config get <args>`, trimmed; `None` if the CLI can't answer.
+pub(super) fn cli_config_value(tool: &str, args: &[&str]) -> Option<String> {
Cmd::new(tool)
- .args(["config", "get", key])
+ .args(["config", "get"])
+ .args(args.iter().copied())
.run()
.ok()
.filter(|output| output.status.success())
diff --git a/src/testing/mock_commands.rs b/src/testing/mock_commands.rs
index 9415c1495..d6dd8ace3 100644
--- a/src/testing/mock_commands.rs
+++ b/src/testing/mock_commands.rs
@@ -269,6 +269,12 @@ pub fn tea_api_include_stderr(status: &str) -> String {
format!("HTTP/1.1 {status}\r\nContent-Type: application/json;charset=utf-8\r\n\r\n")
}
+/// `tea logins list --output json` holding a login for `gitea.example.com`,
+/// the host the Gitea CI tests use, so a failed call there shows the error
+/// indicator.
+pub const TEA_TEST_LOGINS: &str =
+ r#"[{"url":"https://gitea.example.com","ssh_host":"gitea.example.com"}]"#;
+
/// Create a mock cargo command for tests.
pub fn create_mock_cargo(bin_dir: &Path) {
MockConfig::new("cargo")
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index 1680195bb..da180096e 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -64,7 +64,7 @@ use crate::git::Repository;
use crate::shell_exec::{self, Cmd, INHERITED_GIT_PATH_VARS};
use path_slash::PathExt;
-use self::mock_commands::{MockConfig, MockResponse, tea_api_include_stderr};
+use self::mock_commands::{MockConfig, MockResponse, TEA_TEST_LOGINS, tea_api_include_stderr};
/// Path to the `wt` binary built by Cargo, pinned against concurrent builds.
///
@@ -2140,7 +2140,7 @@ impl TestRepo {
/// use `configure_mock_commands()` to add the mock bin to PATH for your commands.
///
/// The mock gh returns:
- /// - `gh auth status`: exits successfully (0)
+ /// - `gh auth token`: exits successfully (0)
/// - `gh pr list`: returns empty JSON array (no PRs found)
///
/// This prevents CI detection from blocking tests with network calls.
@@ -2153,9 +2153,9 @@ impl TestRepo {
/// Use this for `wt config show` tests that need deterministic BINARIES output.
/// Creates mocks where:
/// - `gh --version`: succeeds (installed)
- /// - `gh auth status`: fails (not authenticated)
+ /// - `gh auth token`: fails (not authenticated)
/// - `glab --version`: succeeds (installed)
- /// - `glab auth status`: fails (not authenticated)
+ /// - `glab config get token`: prints nothing (not authenticated)
pub fn setup_mock_ci_tools_unauthenticated(&mut self) {
let mock_bin = self.temp_dir.path().join("mock-bin");
std::fs::create_dir_all(&mock_bin).unwrap();
@@ -2169,7 +2169,7 @@ impl TestRepo {
// glab: installed but not authenticated
MockConfig::new("glab")
.version("glab version 1.0.0 (mock)")
- .command("auth", MockResponse::exit(1))
+ .command("config get token", MockResponse::output(""))
.write(&mock_bin);
// claude: not installed (don't create mock - which::which won't find it)
@@ -2638,7 +2638,7 @@ impl TestRepo {
// This allows triple-matching "mr view <iid>" to return the correct MR
let mut mock_config = MockConfig::new("glab")
.version("glab version 1.0.0 (mock)")
- .command("auth", MockResponse::exit(0))
+ .command("config get token", MockResponse::output("glpat-mock"))
.command("mr list", MockResponse::file("mr_list_data.json"));
// Parse MR array and create iid-specific view commands
@@ -2697,7 +2697,7 @@ impl TestRepo {
// (falls back to exit code 1)
MockConfig::new("glab")
.version("glab version 1.0.0 (mock)")
- .command("auth", MockResponse::exit(0))
+ .command("config get token", MockResponse::output("glpat-mock"))
.command("mr list", MockResponse::file("mr_list_data.json"))
// No "mr view" commands - will fall back to default exit code 1
.command("repo", MockResponse::output(&project_id_response))
@@ -2727,7 +2727,7 @@ impl TestRepo {
// glab mock: mr list returns empty (no MRs), ci list returns the pipeline
MockConfig::new("glab")
.version("glab version 1.0.0 (mock)")
- .command("auth", MockResponse::exit(0))
+ .command("config get token", MockResponse::output("glpat-mock"))
.command("mr list", MockResponse::output("[]")) // No MRs - triggers ci list fallback
.command("repo", MockResponse::output(&project_id_response))
.command("ci", MockResponse::output(pipeline_json))
@@ -2757,7 +2757,7 @@ impl TestRepo {
// glab mock: mr list returns empty (no MRs), ci list fails with rate limit
MockConfig::new("glab")
.version("glab version 1.0.0 (mock)")
- .command("auth", MockResponse::exit(0))
+ .command("config get token", MockResponse::output("glpat-mock"))
.command("mr list", MockResponse::output("[]")) // No MRs - triggers ci list fallback
.command("repo", MockResponse::output(&project_id_response))
.command(
@@ -2910,6 +2910,10 @@ impl TestRepo {
MockConfig::new("tea")
.version("tea version development (mock)")
+ .command(
+ "logins list --output",
+ MockResponse::output(TEA_TEST_LOGINS),
+ )
.command(
&pulls_path,
MockResponse::file("tea_pulls.json")
@@ -2951,6 +2955,10 @@ impl TestRepo {
MockConfig::new("tea")
.version("tea version development (mock)")
+ .command(
+ "logins list --output",
+ MockResponse::output(TEA_TEST_LOGINS),
+ )
.command("api", MockResponse::stderr(stderr).with_exit_code(1))
.command("_default", MockResponse::exit(1))
.write(&mock_bin);
@@ -2979,6 +2987,10 @@ impl TestRepo {
MockConfig::new("tea")
.version("tea version development (mock)")
+ .command(
+ "logins list --output",
+ MockResponse::output(TEA_TEST_LOGINS),
+ )
.command(
// Keep `&limit=20` in sync with `MAX_PRS_TO_FETCH` in
// `src/commands/list/ci_status/mod.rs`.
diff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rs
index 4df3aa8ab..14eb61f18 100644
--- a/tests/integration_tests/ci_status.rs
+++ b/tests/integration_tests/ci_status.rs
@@ -66,6 +66,7 @@ fn setup_mock_gh_with_api_data(
let mut gh = MockConfig::new("gh")
.version("gh version 2.0.0 (mock)")
+ .command("auth token", MockResponse::exit(0))
.command("pr list", MockResponse::output(pr_json));
for (command, response) in api_responses {
@@ -994,15 +995,51 @@ fn list_line(stdout: &str, branch: &str) -> String {
}
/// A failed PR/MR list shows the error indicator whatever the CLI printed, here
-/// an authentication failure that no retry would change.
+/// an authentication failure that no retry would change — when the CLI holds a
+/// login for the host. Without one, the cell stays blank: the user isn't using
+/// that CLI here. `gh` reports a missing login with exit code 4; `glab` is asked
+/// for a token for the remote's host.
#[rstest]
-#[case::github("gh", "pr list", "https://github.com/test-owner/test-repo.git")]
-#[case::gitlab("glab", "mr list", "https://gitlab.com/test-group/test-project.git")]
-fn test_list_full_failed_pr_list_shows_error(
+#[case::github(
+ "gh",
+ "pr list",
+ "https://github.com/test-owner/test-repo.git",
+ 1,
+ ("auth token", MockResponse::exit(0)),
+ true
+)]
+#[case::github_logged_out(
+ "gh",
+ "pr list",
+ "https://github.com/test-owner/test-repo.git",
+ 4,
+ ("auth token", MockResponse::exit(0)),
+ false
+)]
+#[case::gitlab(
+ "glab",
+ "mr list",
+ "https://gitlab.com/test-group/test-project.git",
+ 1,
+ ("config get token", MockResponse::output("glpat-mock")),
+ true
+)]
+#[case::gitlab_logged_out(
+ "glab",
+ "mr list",
+ "https://gitlab.com/test-group/test-project.git",
+ 1,
+ ("config get token", MockResponse::output("")),
+ false
+)]
+fn test_list_full_failed_pr_list(
mut repo: TestRepo,
#[case] tool: &str,
#[case] list_command: &str,
#[case] remote_url: &str,
+ #[case] list_exit_code: i32,
+ #[case] login: (&str, MockResponse),
+ #[case] shows_error: bool,
) {
repo.run_git(&["remote", "set-url", "origin", remote_url]);
repo.add_worktree("feature");
@@ -1010,12 +1047,14 @@ fn test_list_full_failed_pr_list_shows_error(
let mock_bin = repo.root_path().join("mock-bin");
std::fs::create_dir_all(&mock_bin).unwrap();
+ let (login_command, login_response) = login;
MockConfig::new(tool)
.version(&format!("{tool} version 2.0.0 (mock)"))
.command(
list_command,
- MockResponse::stderr("HTTP 401: Bad credentials").with_exit_code(1),
+ MockResponse::stderr("HTTP 401: Bad credentials").with_exit_code(list_exit_code),
)
+ .command(login_command, login_response)
.command("_default", MockResponse::output("[]"))
.write(&mock_bin);
@@ -1024,7 +1063,11 @@ fn test_list_full_failed_pr_list_shows_error(
let output = cmd.output().unwrap();
assert!(output.status.success(), "wt list should succeed");
let stdout = String::from_utf8_lossy(&output.stdout);
- assert!(list_line(&stdout, "feature").contains('⚠'), "{stdout}");
+ assert_eq!(
+ list_line(&stdout, "feature").contains('⚠'),
+ shows_error,
+ "{stdout}"
+ );
}
/// The Gitea commit-status lookup is by SHA too, so an unpushed head skips it
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 2ce326618..943b6ea79 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -1652,7 +1652,8 @@ fn test_config_show_full_gitea_remote(mut repo: TestRepo, temp_home: TempDir) {
/// command output. The mock replaces the external tea CLI, not our process
/// wiring or diagnostics logic.
#[rstest]
-#[case::login(r#"[{"name":"local","url":"https://forge.example.test","ssh_host":"","user":"alice","default":"true"}]"#, 0, true)]
+#[case::login(r#"[{"name":"local","url":"https://gitea.example.com","ssh_host":"","user":"alice","default":"true"}]"#, 0, true)]
+#[case::other_host(r#"[{"name":"local","url":"https://forge.example.test","ssh_host":"","user":"alice","default":"true"}]"#, 0, false)]
#[case::empty("[]", 0, false)]
#[case::invalid_json("not JSON", 0, false)]
#[case::invalid_shape(r#"[{"name":"missing-url"}]"#, 0, false)]
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_full_gitea_remote.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_full_gitea_remote.snap
index 67e3dbf73..8007128c1 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_full_gitea_remote.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_full_gitea_remote.snap
@@ -73,7 +73,7 @@ exit_code: 0
  Invoked as: [PROJECT_ROOT]/target/[BUILD_MODE]/wt
DIAGNOSTICS
-▲ tea installed but not authenticated
+▲ tea installed but not authenticated for gitea.example.com
↳ To authenticate, run tea login add
○ Up to date ([VERSION])
○ Commit generation not configured
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index 560ed00fd..83b5eb550 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -178,17 +178,17 @@ The leftmost column marks each row by physical presence, from most present to le
The CI column shows the branch's open PR/MR — #3035 on GitHub, Gitea, and Azure DevOps, !3035 on GitLab — colored by pipeline status, or a bare # when no number is available (e.g. branch workflows without a PR/MR). Green, blue, red, yellow, and gray show the pipeline state; magenta and cyan show the review state. checks object and review states give the JSON form of each value:
- Indicator Value Meaning
- ───────── ──────────────────── ─────────────────────────────────────────────────────────────────────────
- # green "passed" All checks passed
- # blue "running" Checks in progress
- # red "failed" One or more checks failed
- # yellow "conflicts" Merge conflicts with the target branch
- # gray "no-ci" No PR/MR, or no checks configured
- ⚠ yellow "error" CI status could not be fetched (not logged in, rate limit, network, etc.)
- # magenta "changes_requested" A reviewer requested changes
- # cyan "pending" A review is required (e.g. branch protection) but not yet given
- (blank) pr and checks absent Branch never pushed, or no PR/MR and no branch workflow
+ Indicator Value Meaning
+ ───────── ──────────────────── ────────────────────────────────────────────────────────────────────────────────────────────
+ # green "passed" All checks passed
+ # blue "running" Checks in progress
+ # red "failed" One or more checks failed
+ # yellow "conflicts" Merge conflicts with the target branch
+ # gray "no-ci" No PR/MR, or no checks configured
+ ⚠ yellow "error" CI status could not be fetched (expired login, rate limit, network, etc.)
+ # magenta "changes_requested" A reviewer requested changes
+ # cyan "pending" A review is required (e.g. branch protection) but not yet given
+ (blank) pr and checks absent Branch never pushed, forge CLI not logged in to the host, or no PR/MR and no branch workflow
The two remaining review states have no indicator of their own: "draft" only dims the cell and "approved" leaves the color unchanged.
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index 03e470cff..e3fe2fa4b 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -209,13 +209,13 @@ checks object and review states give the JSON form of each value:
# red "failed" One or more checks failed
# yellow "conflicts" Merge conflicts with the target branch
# gray "no-ci" No PR/MR, or no checks configured
- ⚠ yellow "error" CI status could not be fetched (not logged in,
+ ⚠ yellow "error" CI status could not be fetched (expired login,
rate limit, network, etc.)
# magenta "changes_requested" A reviewer requested changes
# cyan "pending" A review is required (e.g. branch protection)
but not yet given
- (blank) pr and checks absent Branch never pushed, or no PR/MR and no branch
- workflow
+ (blank) pr and checks absent Branch never pushed, forge CLI not logged in to
+ the host, or no PR/MR and no branch workflow
The two remaining review states have no indicator of their own: "draft" only
dims the cell and "approved" leaves the color unchanged.