Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ide): Git tab with branches, merged-into, pull request and CI state

rubenluetke10-beepf8176c6b3195
diff --git a/jarvis/agentic_ide/git_overview.py b/jarvis/agentic_ide/git_overview.py
new file mode 100644
index 0000000000..6572b1aba4
--- /dev/null
+++ b/jarvis/agentic_ide/git_overview.py
@@ -0,0 +1,672 @@
+"""Branches, pull requests and CI of a workspace's repository, in one answer.
+
+The IDE's Git tab lists a project's branches and, for each one, three
+separate facts that are easy to mix up:
+
+* **Merged** — local git knows a branch is contained in a target branch
+ (``git for-each-ref --merged``), and GitHub knows a pull request was merged
+ (which also covers squash merges, where git ancestry says nothing).
+* **Pull request** — the state of the branch's pull request on GitHub: draft,
+ open, in the merge queue, merged, or closed without a merge.
+* **CI** — the checks on the branch's newest pushed commit: pending, running,
+ passed or failed. Green checks never mean "merged"; the two are reported
+ apart on purpose.
+
+Local git is read on every call (a handful of fast plumbing commands). GitHub
+is read through the ``gh`` CLI with ONE GraphQL query per repository and
+cached per repository, so N open panes polling one project cost one network
+call per minute — shorter while a check is still running, because that is
+exactly when the user is waiting for the answer.
+
+Degrades, never raises: no git, not a repository, no ``gh``, ``gh`` not signed
+in, no GitHub remote — each comes back as ``available=False`` or
+``github.available=False`` with one plain sentence. Raw ``gh`` error text is
+logged, never returned: it may carry account or host details.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import threading
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+_GIT_TIMEOUT_S = 8.0
+_GH_TIMEOUT_S = 25.0
+#: Most local branches listed; the newest by commit date win.
+MAX_BRANCHES = 60
+#: Most GitHub-only branches listed beside the local ones.
+MAX_REMOTE_ONLY = 30
+#: Most target branches a "merged into" check runs against (one git call each).
+MAX_MERGE_TARGETS = 4
+#: Pull requests kept per branch (the most relevant first).
+MAX_PRS_PER_BRANCH = 3
+#: Failed or running check names kept for a tooltip.
+MAX_CHECK_NAMES = 6
+
+#: How long one GitHub answer is reused while nothing is in flight ...
+GITHUB_TTL_S = 60.0
+#: ... and while a check runs or a pull request waits in the merge queue.
+GITHUB_BUSY_TTL_S = 20.0
+#: A forced refresh still reuses an answer this young.
+GITHUB_MIN_REFRESH_S = 5.0
+
+_QUERY = """
+query($owner: String!, $name: String!) {
+ repository(owner: $owner, name: $name) {
+ url
+ pullRequests(first: 40, orderBy: {field: UPDATED_AT, direction: DESC}) {
+ nodes {
+ number title url state isDraft isCrossRepository
+ headRefName headRefOid baseRefName mergedAt updatedAt
+ isInMergeQueue
+ mergeQueueEntry { position }
+ commits(last: 1) { nodes { commit { oid statusCheckRollup { ...Rollup } } } }
+ }
+ }
+ refs(refPrefix: "refs/heads/", first: 60,
+ orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) {
+ nodes {
+ name
+ target { ... on Commit { oid committedDate statusCheckRollup { ...Rollup } } }
+ }
+ }
+ }
+}
+fragment Rollup on StatusCheckRollup {
+ state
+ contexts(first: 40) {
+ totalCount
+ nodes {
+ __typename
+ ... on CheckRun {
+ name status conclusion detailsUrl
+ checkSuite { workflowRun { url } }
+ }
+ ... on StatusContext { context state targetUrl }
+ }
+ }
+}
+"""
+
+# CheckRun.status values that have not started yet.
+_QUEUED = {"QUEUED", "PENDING", "WAITING", "REQUESTED", "EXPECTED"}
+# CheckRun.conclusion values that count as a pass.
+_PASSED = {"SUCCESS", "NEUTRAL", "SKIPPED"}
+
+
+# ------------------------------------------------------------------ model
+
+
+@dataclass(slots=True)
+class CiStatus:
+ #: ``none`` | ``pending`` | ``running`` | ``success`` | ``failure``
+ state: str = "none"
+ #: Where a click goes: the failing / running workflow run, or the checks page.
+ url: str = ""
+ total: int = 0
+ passed: int = 0
+ failed: int = 0
+ running: int = 0
+ pending: int = 0
+ #: The commit the checks ran on (12 chars).
+ commit: str = ""
+ #: Names of the failed checks (or the running ones while nothing failed).
+ names: list[str] = field(default_factory=list)
+
+
+@dataclass(slots=True)
+class PullRequest:
+ number: int
+ title: str
+ url: str
+ #: ``draft`` | ``open`` | ``queued`` | ``merged`` | ``closed``
+ state: str
+ base: str
+ head: str
+ head_oid: str = ""
+ merged_at: str = ""
+ updated_at: str = ""
+ #: 1-based place in the merge queue while ``state == "queued"``.
+ queue_position: int | None = None
+ ci: CiStatus = field(default_factory=CiStatus)
+
+
+@dataclass(slots=True)
+class MergedInto:
+ target: str
+ #: ``git`` (ancestry) or ``pull_request`` (GitHub merged its PR).
+ via: str
+ number: int | None = None
+ url: str = ""
+
+
+@dataclass(slots=True)
+class BranchRow:
+ name: str
+ current: bool = False
+ #: Only on GitHub, no local branch of that name.
+ remote_only: bool = False
+ upstream: str = ""
+ ahead: int = 0
+ behind: int = 0
+ head: str = ""
+ committed_at: int = 0
+ #: The checkout this branch is open in, when it is another worktree.
+ worktree: str = ""
+ #: The branch exists on GitHub (from the GitHub answer; False when unknown).
+ on_github: bool = False
+ merged_into: list[MergedInto] = field(default_factory=list)
+ pull_requests: list[PullRequest] = field(default_factory=list)
+ #: CI of the branch's newest pushed commit (its open PR's, when it has one).
+ ci: CiStatus = field(default_factory=CiStatus)
+ #: The local branch has commits that CI has not seen yet.
+ ci_stale: bool = False
+
+
+@dataclass(slots=True)
+class GitHubState:
+ available: bool = False
+ reason: str = ""
+ repo_url: str = ""
+ #: Epoch seconds of the GitHub answer in use.
+ fetched_at: float = 0.0
+
+
+@dataclass(slots=True)
+class RepoOverview:
+ available: bool
+ reason: str = ""
+ root: str = ""
+ branch: str = ""
+ detached: bool = False
+ head: str = ""
+ default_branch: str = ""
+ branches: list[BranchRow] = field(default_factory=list)
+ remote_branches: list[BranchRow] = field(default_factory=list)
+ truncated: bool = False
+ github: GitHubState = field(default_factory=GitHubState)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+# ------------------------------------------------------------------ plumbing
+
+
+def _run(args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S, program: str = "git"):
+ env = dict(os.environ)
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env["GH_PROMPT_DISABLED"] = "1"
+ env["GH_NO_UPDATE_NOTIFIER"] = "1"
+ command = ["git", "-c", "core.quotePath=false", *args] if program == "git" else [program, *args]
+ try:
+ return subprocess.run(
+ command,
+ cwd=str(cwd),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ check=False,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except FileNotFoundError: # git/gh not installed: callers report it as unavailable
+ return None
+ except subprocess.TimeoutExpired:
+ logger.info("Git overview: {} did not answer in time in {}", program, cwd)
+ return None
+
+
+def _out(args: list[str], cwd: Path) -> str | None:
+ result = _run(args, cwd)
+ if result is None or result.returncode != 0:
+ return None
+ return result.stdout
+
+
+# ------------------------------------------------------------------ CI
+
+
+def ci_from_rollup(rollup: dict[str, Any] | None, commit: str = "") -> CiStatus:
+ """Fold a GitHub ``statusCheckRollup`` into one CI verdict with counts."""
+ ci = CiStatus(commit=commit[:12])
+ if not rollup:
+ return ci
+ contexts = rollup.get("contexts") or {}
+ failed_names: list[str] = []
+ running_names: list[str] = []
+ failed_url = running_url = pending_url = first_url = ""
+ for node in contexts.get("nodes") or []:
+ if not isinstance(node, dict):
+ continue
+ if node.get("__typename") == "StatusContext":
+ name = str(node.get("context") or "")
+ url = str(node.get("targetUrl") or "")
+ state = str(node.get("state") or "").upper()
+ kind = (
+ "success"
+ if state == "SUCCESS"
+ else "failure"
+ if state in {"FAILURE", "ERROR"}
+ else "pending"
+ )
+ else:
+ name = str(node.get("name") or "")
+ run = ((node.get("checkSuite") or {}).get("workflowRun") or {}).get("url")
+ url = str(run or node.get("detailsUrl") or "")
+ status = str(node.get("status") or "").upper()
+ conclusion = str(node.get("conclusion") or "").upper()
+ if status == "COMPLETED":
+ kind = "success" if conclusion in _PASSED else "failure"
+ elif status == "IN_PROGRESS":
+ kind = "running"
+ else:
+ kind = "pending" if status in _QUEUED or not status else "running"
+ ci.total += 1
+ first_url = first_url or url
+ if kind == "success":
+ ci.passed += 1
+ elif kind == "failure":
+ ci.failed += 1
+ failed_names.append(name)
+ failed_url = failed_url or url
+ elif kind == "running":
+ ci.running += 1
+ running_names.append(name)
+ running_url = running_url or url
+ else:
+ ci.pending += 1
+ pending_url = pending_url or url
+ rollup_state = str(rollup.get("state") or "").upper()
+ if ci.failed or rollup_state in {"FAILURE", "ERROR"}:
+ ci.state = "failure"
+ elif ci.running:
+ ci.state = "running"
+ elif ci.pending or rollup_state in {"PENDING", "EXPECTED"}:
+ ci.state = "pending"
+ elif ci.total or rollup_state == "SUCCESS":
+ ci.state = "success"
+ # The page shows at most 40 checks; the rollup's own count is the truth.
+ total = contexts.get("totalCount")
+ if isinstance(total, int) and total > ci.total:
+ ci.total = total
+ ci.names = (failed_names or running_names)[:MAX_CHECK_NAMES]
+ ci.url = failed_url or running_url or pending_url or first_url
+ return ci
+
+
+def _pr_state(node: dict[str, Any]) -> str:
+ state = str(node.get("state") or "").upper()
+ if state == "MERGED":
+ return "merged"
+ if state == "CLOSED":
+ return "closed"
+ if node.get("isInMergeQueue") or node.get("mergeQueueEntry"):
+ return "queued"
+ return "draft" if node.get("isDraft") else "open"
+
+
+# Most relevant first: what is still moving, then what landed, then the rest.
+_PR_RANK = {"queued": 0, "open": 1, "draft": 2, "merged": 3, "closed": 4}
+
+
+@dataclass(slots=True)
+class _GitHubSnapshot:
+ ok: bool
+ reason: str = ""
+ repo_url: str = ""
+ fetched_at: float = 0.0
+ prs: list[PullRequest] = field(default_factory=list)
+ #: Branch name → (tip oid, CI of that tip).
+ refs: dict[str, tuple[str, CiStatus]] = field(default_factory=dict)
+
+ @property
+ def busy(self) -> bool:
+ states = [pr.ci.state for pr in self.prs] + [ci.state for _, ci in self.refs.values()]
+ return any(state in {"pending", "running"} for state in states) or any(
+ pr.state == "queued" for pr in self.prs
+ )
+
+
+def parse_github(payload: dict[str, Any], fetched_at: float = 0.0) -> _GitHubSnapshot:
+ """The parts of the GraphQL answer the tab shows."""
+ repo = ((payload or {}).get("data") or {}).get("repository")
+ if not isinstance(repo, dict):
+ return _GitHubSnapshot(ok=False, reason="GitHub did not return this repository.")
+ snap = _GitHubSnapshot(ok=True, repo_url=str(repo.get("url") or ""), fetched_at=fetched_at)
+ for node in (repo.get("pullRequests") or {}).get("nodes") or []:
+ if not isinstance(node, dict) or node.get("isCrossRepository"):
+ continue
+ commits = (node.get("commits") or {}).get("nodes") or []
+ commit = (commits[0] or {}).get("commit") if commits else None
+ commit = commit if isinstance(commit, dict) else {}
+ entry = node.get("mergeQueueEntry") or {}
+ snap.prs.append(
+ PullRequest(
+ number=int(node.get("number") or 0),
+ title=str(node.get("title") or ""),
+ url=str(node.get("url") or ""),
+ state=_pr_state(node),
+ base=str(node.get("baseRefName") or ""),
+ head=str(node.get("headRefName") or ""),
+ head_oid=str(node.get("headRefOid") or "")[:12],
+ merged_at=str(node.get("mergedAt") or ""),
+ updated_at=str(node.get("updatedAt") or ""),
+ queue_position=entry.get("position") if isinstance(entry, dict) else None,
+ ci=ci_from_rollup(commit.get("statusCheckRollup"), str(commit.get("oid") or "")),
+ )
+ )
+ for node in (repo.get("refs") or {}).get("nodes") or []:
+ if not isinstance(node, dict) or not node.get("name"):
+ continue
+ target = node.get("target") or {}
+ oid = str(target.get("oid") or "")
+ snap.refs[str(node["name"])] = (
+ oid[:12],
+ ci_from_rollup(target.get("statusCheckRollup"), oid),
+ )
+ return snap
+
+
+def _gh_failure_reason(stderr: str) -> str:
+ text = stderr.lower()
+ if "auth login" in text or "not logged" in text or "authentication" in text:
+ return "The GitHub CLI (gh) is not signed in."
+ if "known github host" in text or "no git remotes" in text or "set-default" in text:
+ return "This repository has no GitHub remote gh can use."
+ if "could not resolve to a repository" in text:
+ return "GitHub does not know this repository, or this account cannot see it."
+ if "rate limit" in text:
+ return "GitHub's rate limit is reached; it resets within the hour."
+ return "GitHub could not be reached."
+
+
+def _fetch_github(root: Path) -> _GitHubSnapshot:
+ now = time.time()
+ if shutil.which("gh") is None:
+ return _GitHubSnapshot(
+ ok=False, reason="The GitHub CLI (gh) is not installed.", fetched_at=now
+ )
+ result = _run(
+ [
+ "api",
+ "graphql",
+ "-F",
+ "owner={owner}",
+ "-F",
+ "name={repo}",
+ "-f",
+ f"query={_QUERY}",
+ ],
+ root,
+ timeout=_GH_TIMEOUT_S,
+ program="gh",
+ )
+ if result is None:
+ return _GitHubSnapshot(ok=False, reason="GitHub did not answer in time.", fetched_at=now)
+ if result.returncode != 0:
+ # Logged for the maintainer, never shown: it may name the account or host.
+ logger.debug("Git overview: gh graphql failed: {}", (result.stderr or "").strip()[:500])
+ return _GitHubSnapshot(
+ ok=False, reason=_gh_failure_reason(result.stderr or ""), fetched_at=now
+ )
+ try:
+ payload = json.loads(result.stdout or "{}")
+ except json.JSONDecodeError: # answered as github.available=False with a reason
+ return _GitHubSnapshot(
+ ok=False, reason="GitHub sent an answer that could not be read.", fetched_at=now
+ )
+ return parse_github(payload, fetched_at=now)
+
+
+class _GitHubCache:
+ """One GitHub answer per repository, shared by every pane and window."""
+
+ def __init__(self) -> None:
+ self._guard = threading.Lock()
+ self._locks: dict[str, threading.Lock] = {}
+ self._entries: dict[str, _GitHubSnapshot] = {}
+
+ def _fresh(self, snap: _GitHubSnapshot | None, now: float, force: bool) -> bool:
+ if snap is None:
+ return False
+ age = now - snap.fetched_at
+ if force:
+ return age < GITHUB_MIN_REFRESH_S
+ return age < (GITHUB_BUSY_TTL_S if snap.busy else GITHUB_TTL_S)
+
+ def _load(self, key: str, root: Path, lock: threading.Lock, force: bool) -> _GitHubSnapshot:
+ # One fetch per repository at a time; everyone else waits for its answer.
+ with lock:
+ snap = self._entries.get(key)
+ if self._fresh(snap, time.time(), force):
+ assert snap is not None
+ return snap
+ snap = _fetch_github(root)
+ self._entries[key] = snap
+ return snap
+
+ def get(self, key: str, root: Path, *, force: bool = False) -> _GitHubSnapshot:
+ with self._guard:
+ lock = self._locks.setdefault(key, threading.Lock())
+ snap = self._entries.get(key)
+ if snap is None or force:
+ return self._load(key, root, lock, force)
+ if not self._fresh(snap, time.time(), False) and not lock.locked():
+ # Stale-while-revalidate: a poll never waits seconds for GitHub;
+ # it gets the last answer now and the new one on its next tick.
+ threading.Thread(
+ target=self._load,
+ args=(key, root, lock, False),
+ name="git-overview-github",
+ daemon=True,
+ ).start()
+ return snap
+
+ def clear(self) -> None:
+ with self._guard:
+ self._entries.clear()
+
+
+_CACHE = _GitHubCache()
+
+
+def clear_cache() -> None:
+ _CACHE.clear()
+
+
+# ------------------------------------------------------------------ local git
+
+
+def _default_branch(root: Path, names: set[str], current: str) -> str:
+ head = _out(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], root)
+ if head and head.strip():
+ return head.strip().split("/", 1)[-1]
+ for candidate in ("main", "master", "trunk", "develop"):
+ if candidate in names:
+ return candidate
+ return current
+
+
+def _local_branches(root: Path, current: str) -> list[BranchRow]:
+ text = _out(
+ [
+ "for-each-ref",
+ "--sort=-committerdate",
+ "--format=%(refname:short)%09%(objectname)%09%(upstream:short)%09"
+ "%(upstream:track,nobracket)%09%(committerdate:unix)%09%(worktreepath)",
+ "refs/heads",
+ ],
+ root,
+ )
+ rows: list[BranchRow] = []
+ for line in (text or "").splitlines():
+ name, oid, upstream, track, stamp, tree = ([*line.split("\t"), "", "", "", "", ""])[:6]
+ if not name:
+ continue
+ row = BranchRow(
+ name=name,
+ current=name == current,
+ upstream=upstream,
+ head=oid[:12],
+ committed_at=int(stamp) if stamp.isdigit() else 0,
+ )
+ for part in track.split(","):
+ word, _, count = part.strip().partition(" ")
+ if word == "ahead" and count.isdigit():
+ row.ahead = int(count)
+ elif word == "behind" and count.isdigit():
+ row.behind = int(count)
+ if tree and not row.current:
+ row.worktree = str(Path(tree))
+ rows.append(row)
+ return rows
+
+
+def _resolve_target(root: Path, target: str, local: set[str]) -> str | None:
+ """The ref a "merged into ``target``" check reads: the local branch, else origin's."""
+ if target in local:
+ return f"refs/heads/{target}"
+ ref = f"refs/remotes/origin/{target}"
+ return ref if _out(["rev-parse", "--verify", "--quiet", ref], root) is not None else None
+
+
+def _merged_by_git(root: Path, targets: list[str], local: set[str]) -> dict[str, list[str]]:
+ """Branch name → targets whose history already contains all of its commits.
+
+ A branch whose tip IS the target's tip (just created from it, or fast-
+ forwarded) holds no work of its own and is not reported as merged.
+ """
+ merged: dict[str, list[str]] = {}
+ for target in targets:
+ ref = _resolve_target(root, target, local)
+ if ref is None:
+ continue
+ tip = (_out(["rev-parse", ref], root) or "").strip()
+ text = _out(
+ [
+ "for-each-ref",
+ f"--merged={ref}",
+ "--format=%(refname:short)%09%(objectname)",
+ "refs/heads",
+ ],
+ root,
+ )
+ for line in (text or "").splitlines():
+ name, _, oid = line.partition("\t")
+ if name and name != target and oid.strip() != tip:
+ merged.setdefault(name, []).append(target)
+ return merged
+
+
+# ------------------------------------------------------------------ assembly
+
+
+def _remote_name(row: BranchRow) -> str:
+ """The branch's name on GitHub: its upstream on origin, else its own name."""
+ if row.upstream.startswith("origin/"):
+ return row.upstream[len("origin/") :]
+ return row.name
+
+
+def _attach_github(row: BranchRow, remote: str, snap: _GitHubSnapshot) -> None:
+ prs = [pr for pr in snap.prs if pr.head == remote]
+ prs.sort(key=lambda pr: (_PR_RANK.get(pr.state, 9), -pr.number))
+ row.pull_requests = prs[:MAX_PRS_PER_BRANCH]
+ ref = snap.refs.get(remote)
+ row.on_github = ref is not None
+ live = next((pr for pr in prs if pr.state in {"queued", "open", "draft"}), None)
+ if live is not None and live.ci.state != "none":
+ row.ci = live.ci
+ elif ref is not None:
+ row.ci = ref[1]
+ if row.ci.url == "" and row.ci.state != "none" and live is not None:
+ row.ci.url = f"{live.url}/checks"
+ if row.ci.state != "none" and row.head and row.ci.commit:
+ row.ci_stale = row.ci.commit != row.head[: len(row.ci.commit)]
+ # A merged pull request counts when the branch has not moved past it since.
+ for pr in prs:
+ if pr.state != "merged" or any(m.target == pr.base for m in row.merged_into):
+ continue
+ if row.remote_only or not pr.head_oid or row.head.startswith(pr.head_oid[:7]):
+ row.merged_into.append(
+ MergedInto(target=pr.base, via="pull_request", number=pr.number, url=pr.url)
+ )
+
+
+def overview(folder: str | Path, *, refresh: bool = False, github: bool = True) -> RepoOverview:
+ """Branches of the repository ``folder`` is in, with merge, PR and CI state."""
+ path = Path(folder).expanduser()
+ if not path.is_dir():
+ return RepoOverview(available=False, reason="The workspace folder is missing.")
+ if shutil.which("git") is None:
+ return RepoOverview(available=False, reason="Git is not installed.")
+ top = _out(["rev-parse", "--show-toplevel"], path)
+ if not top or not top.strip():
+ return RepoOverview(available=False, reason="This folder is not a git repository.")
+ root = Path(top.strip())
+ info = RepoOverview(available=True, root=str(root))
+
+ head = (_out(["symbolic-ref", "--quiet", "--short", "HEAD"], root) or "").strip()
+ info.branch = head
+ info.detached = not head
+ info.head = (_out(["rev-parse", "--short=12", "HEAD"], root) or "").strip()
+
+ rows = _local_branches(root, head)
+ local = {row.name for row in rows}
+ info.default_branch = _default_branch(root, local, head)
+
+ snap: _GitHubSnapshot | None = None
+ if github:
+ common = (
+ _out(["rev-parse", "--path-format=absolute", "--git-common-dir"], root) or ""
+ ).strip()
+ snap = _CACHE.get(os.path.normcase(common or str(root)), root, force=refresh)
+ info.github = GitHubState(
+ available=snap.ok,
+ reason=snap.reason,
+ repo_url=snap.repo_url,
+ fetched_at=snap.fetched_at,
+ )
+
+ # Current and default branch always make the list, however old they are.
+ keep = {head, info.default_branch}
+ pinned = [row for row in rows if row.name in keep]
+ rest = [row for row in rows if row.name not in keep]
+ info.truncated = len(rows) > MAX_BRANCHES
+ rows = pinned + rest[: max(0, MAX_BRANCHES - len(pinned))]
+
+ targets = [info.default_branch] if info.default_branch else []
+ for pr in snap.prs if snap and snap.ok else []:
+ if pr.base and pr.base not in targets and pr.base in local:
+ targets.append(pr.base)
+ merged = _merged_by_git(root, targets[:MAX_MERGE_TARGETS], local)
+ for row in rows:
+ row.merged_into = [MergedInto(target=t, via="git") for t in merged.get(row.name, [])]
+ if snap is not None and snap.ok:
+ _attach_github(row, _remote_name(row), snap)
+ info.branches = rows
+
+ if snap is not None and snap.ok:
+ known = {_remote_name(row) for row in rows} | local
+ for name, (oid, _ci) in snap.refs.items():
+ if name in known:
+ continue
+ row = BranchRow(name=name, remote_only=True, head=oid)
+ _attach_github(row, name, snap)
+ info.remote_branches.append(row)
+ if len(info.remote_branches) >= MAX_REMOTE_ONLY:
+ break
+ return info
diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.py
index 1e9012aa8d..1e4067796c 100644
--- a/jarvis/ui/web/agentic_ide_git_routes.py
+++ b/jarvis/ui/web/agentic_ide_git_routes.py
@@ -3,6 +3,7 @@
Endpoints (all under ``/api/agentic-ide/git``)::
GET /inspect Branch, changes, ahead/behind, branches, worktrees
+ GET /overview A workspace's branches with merged-into, PR and CI state
POST /prepare Git half of opening a workspace or an agent
POST /commit Stage everything and commit
POST /push Push the current branch (sets upstream once)
@@ -25,7 +26,7 @@ from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
-from jarvis.agentic_ide import git_ops
+from jarvis.agentic_ide import git_ops, git_overview
from jarvis.agentic_ide.git_ops import GitError, PrepareMode
from jarvis.agentic_ide.session import get_registry
@@ -73,6 +74,24 @@ def inspect_folder(folder: str = Query(..., min_length=1)) -> dict:
raise _fail(exc) from exc
[email protected]("/overview", summary="Branches of a workspace's repository with PR and CI state")
+def workspace_overview(
+ workspace_id: str = Query(..., min_length=1),
+ refresh: bool = Query(False, description="Re-read GitHub now instead of the cached answer"),
+) -> dict:
+ """What the IDE's Git tab lists: every branch, what it is merged into, its
+ pull requests and its CI — local git always, GitHub through ``gh`` when it
+ is installed and signed in (cached per repository, see ``git_overview``).
+
+ Workspace-scoped on purpose: the folder comes from the open workspace, so
+ this cannot be pointed at an arbitrary path on the machine.
+ """
+ session = get_registry().get(workspace_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="Workspace not found.")
+ return git_overview.overview(session.folder, refresh=refresh).to_dict()
+
+
@router.post("/prepare", summary="Prepare a checkout for a new workspace or agent")
def prepare_checkout(req: PrepareRequest) -> dict:
try:
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx
new file mode 100644
index 0000000000..c5dafec9b9
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx
@@ -0,0 +1,181 @@
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { GitOverviewTab } from "./GitOverviewTab";
+import type { BranchRow, CiStatus, RepoOverview } from "./gitOverviewApi";
+import { openExternalUrl } from "@/lib/openExternal";
+import { useEventStore } from "@/store/events";
+import { useIdeChatStore } from "@/store/ideChat";
+
+vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn(async () => true) }));
+
+const noCi: CiStatus = { state: "none", url: "", total: 0, passed: 0, failed: 0, running: 0, pending: 0, commit: "", names: [] };
+
+function branch(name: string, extra: Partial<BranchRow> = {}): BranchRow {
+ return {
+ name,
+ current: false,
+ remote_only: false,
+ upstream: `origin/${name}`,
+ ahead: 0,
+ behind: 0,
+ head: "abc123def456",
+ committed_at: 0,
+ worktree: "",
+ on_github: true,
+ merged_into: [],
+ pull_requests: [],
+ ci: noCi,
+ ci_stale: false,
+ ...extra,
+ };
+}
+
+const pr = (number: number, state: "draft" | "open" | "queued" | "merged" | "closed", ci: CiStatus = noCi) => ({
+ number,
+ title: `Change ${number}`,
+ url: `https://github.com/o/r/pull/${number}`,
+ state,
+ base: "main",
+ head: "x",
+ head_oid: "",
+ merged_at: "",
+ updated_at: "",
+ queue_position: state === "queued" ? 2 : null,
+ ci,
+});
+
+const OVERVIEW: RepoOverview = {
+ available: true,
+ reason: "",
+ root: "/code/app",
+ branch: "feature/wip",
+ detached: false,
+ head: "abc123def456",
+ default_branch: "main",
+ truncated: false,
+ github: { available: true, reason: "", repo_url: "https://github.com/o/r", fetched_at: Date.now() / 1000 },
+ branches: [
+ branch("feature/wip", {
+ current: true,
+ ahead: 2,
+ pull_requests: [pr(7, "open")],
+ ci: { ...noCi, state: "running", url: "https://github.com/o/r/actions/runs/7", total: 3, passed: 1, running: 2, names: ["tests"] },
+ }),
+ branch("main", { ci: { ...noCi, state: "success", total: 4, passed: 4, url: "https://github.com/o/r/actions/runs/1" } }),
+ branch("feature/done", {
+ merged_into: [{ target: "main", via: "pull_request", number: 5, url: "" }],
+ pull_requests: [pr(5, "merged")],
+ ci: { ...noCi, state: "success", total: 2, passed: 2 },
+ }),
+ branch("feature/queued", { pull_requests: [pr(8, "queued")] }),
+ branch("feature/draft", { pull_requests: [pr(9, "draft")] }),
+ branch("feature/dropped", {
+ pull_requests: [pr(4, "closed")],
+ ci: { ...noCi, state: "failure", total: 2, passed: 1, failed: 1, names: ["lint"], url: "https://github.com/o/r/actions/runs/4" },
+ }),
+ ],
+ remote_branches: [branch("only-remote", { remote_only: true, upstream: "" })],
+};
+
+let answer: unknown = OVERVIEW;
+const calls: string[] = [];
+
+beforeEach(() => {
+ answer = OVERVIEW;
+ calls.length = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL) => {
+ calls.push(String(input));
+ return new Response(JSON.stringify(answer), { status: 200, headers: { "Content-Type": "application/json" } });
+ }),
+ );
+ useEventStore.setState({ activeSection: "agentic-ide" });
+ useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/code/app" }, stagedPane: null });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.mocked(openExternalUrl).mockClear();
+});
+
+const row = (name: string) => screen.getAllByTestId("git-branch-row").find((el) => el.dataset.branch === name)!;
+
+describe("GitOverviewTab", () => {
+ it("lists the workspace's branches and marks the checked-out one", async () => {
+ render(<GitOverviewTab />);
+ const rows = await screen.findAllByTestId("git-branch-row");
+ expect(rows.map((el) => el.dataset.branch)).toEqual([
+ "feature/wip",
+ "main",
+ "feature/done",
+ "feature/queued",
+ "feature/draft",
+ "feature/dropped",
+ ]);
+ expect(row("feature/wip").dataset.current).toBe("true");
+ expect(row("main").dataset.current).toBeUndefined();
+ expect(screen.getByTestId("git-current-branch").textContent).toBe("feature/wip");
+ expect(calls[0]).toContain("/api/agentic-ide/git/overview?workspace_id=w1");
+ });
+
+ it("shows each pull request state with GitHub's colour", async () => {
+ render(<GitOverviewTab />);
+ await screen.findAllByTestId("git-branch-row");
+ const state = (name: string) => within(row(name)).getByTestId("git-pr").querySelector("[data-pr-state]");
+ expect(state("feature/wip")?.getAttribute("class")).toContain("text-success");
+ expect(state("feature/done")?.getAttribute("class")).toContain("--gh-merged");
+ expect(state("feature/queued")?.getAttribute("class")).toContain("text-warning");
+ expect(state("feature/draft")?.getAttribute("class")).toContain("text-muted-foreground");
+ expect(state("feature/dropped")?.getAttribute("class")).toContain("text-destructive");
+ expect(state("feature/dropped")?.getAttribute("data-pr-state")).toBe("closed");
+ });
+
+ it("keeps CI apart from merging: a merged branch still shows its own green check", async () => {
+ render(<GitOverviewTab />);
+ await screen.findAllByTestId("git-branch-row");
+ const done = row("feature/done");
+ expect(within(done).getByTestId("git-merged-into").dataset.target).toBe("main");
+ expect(within(done).getByTestId("git-ci").querySelector("[data-ci-state]")?.getAttribute("data-ci-state")).toBe("success");
+ expect(within(row("main")).queryByTestId("git-merged-into")).toBeNull();
+ expect(within(row("feature/wip")).getByTestId("git-ci").querySelector("[data-ci-state]")?.getAttribute("data-ci-state")).toBe("running");
+ expect(within(row("feature/dropped")).getByTestId("git-ci").querySelector("[data-ci-state]")?.getAttribute("data-ci-state")).toBe("failure");
+ // No checks at all shows nothing rather than a misleading icon.
+ expect(within(row("feature/queued")).queryByTestId("git-ci")).toBeNull();
+ });
+
+ it("opens the pull request and the CI run in the browser", async () => {
+ render(<GitOverviewTab />);
+ await screen.findAllByTestId("git-branch-row");
+ fireEvent.click(within(row("feature/wip")).getByTestId("git-pr"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/pull/7");
+ fireEvent.click(within(row("feature/dropped")).getByTestId("git-ci"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/actions/runs/4");
+ });
+
+ it("explains every icon in its tooltip", async () => {
+ render(<GitOverviewTab />);
+ await screen.findAllByTestId("git-branch-row");
+ fireEvent.mouseEnter(within(row("feature/dropped")).getByTestId("git-ci").parentElement!);
+ const tip = await screen.findByRole("tooltip");
+ expect(tip.textContent).toContain("CI failed");
+ expect(tip.textContent).toContain("lint");
+ });
+
+ it("folds GitHub-only branches away until asked, and forces a GitHub read on refresh", async () => {
+ render(<GitOverviewTab />);
+ await screen.findAllByTestId("git-branch-row");
+ expect(screen.queryAllByTestId("git-branch-row").some((el) => el.dataset.branch === "only-remote")).toBe(false);
+ fireEvent.click(screen.getByTestId("git-remote-toggle"));
+ expect(row("only-remote")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("git-refresh"));
+ await vi.waitFor(() => expect(calls.some((url) => url.includes("refresh=true"))).toBe(true));
+ });
+
+ it("says why when the folder is not a repository", async () => {
+ answer = { ...OVERVIEW, available: false, reason: "This folder is not a git repository.", branches: [], remote_branches: [] };
+ render(<GitOverviewTab />);
+ expect((await screen.findByTestId("git-unavailable")).textContent).toContain("not a git repository");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx
new file mode 100644
index 0000000000..cabcef9f3b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx
@@ -0,0 +1,482 @@
+import { useEffect, useState, type ReactNode, type SVGProps } from "react";
+import {
+ ChevronRight,
+ CircleCheck,
+ CircleDashed,
+ CircleDot,
+ CircleHelp,
+ CircleX,
+ ExternalLink,
+ FolderGit2,
+ GitBranch,
+ GitMerge,
+ GitPullRequest,
+ GitPullRequestClosed,
+ GitPullRequestDraft,
+ Loader2,
+ RefreshCw,
+} from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { openExternalUrl } from "@/lib/openExternal";
+import { cn } from "@/lib/utils";
+import { QuickTooltip } from "@/components/ui/tooltip";
+import { useEventStore } from "@/store/events";
+import { useIdeChatStore } from "@/store/ideChat";
+import {
+ fetchGitOverview,
+ type BranchRow,
+ type CiState,
+ type CiStatus,
+ type PullRequest,
+ type PullRequestState,
+ type RepoOverview,
+} from "./gitOverviewApi";
+
+/**
+ * Local git is cheap and read on every tick; GitHub is cached per repository
+ * on the backend (shorter while a check runs), so this cadence never turns
+ * into one GitHub call per tick.
+ */
+const POLL_MS = 15_000;
+const POLL_JITTER_MS = 3_000;
+
+// GitHub's pull request colours: open green, merged purple, closed red, the
+// merge queue amber, a draft grey. Each maps to a theme token that has a light
+// and a dark value — `--gh-merged` is the one hue the app had no job for yet.
+const PR_TONE: Record<PullRequestState, string> = {
+ draft: "text-muted-foreground",
+ open: "text-success",
+ queued: "text-warning",
+ merged: "text-[hsl(var(--gh-merged))]",
+ closed: "text-destructive",
+};
+
+/** GitHub's merge-queue mark: the merge glyph with the arm still dashed — waiting to land. */
+function MergeQueueIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={2}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ {...props}
+ >
+ <circle cx="18" cy="18" r="3" />
+ <circle cx="6" cy="6" r="3" />
+ <path d="M6 21V9" />
+ <path d="M6 9a9 9 0 0 0 9 9" strokeDasharray="2.5 3" />
+ </svg>
+ );
+}
+
+const PR_ICON: Record<PullRequestState, (props: SVGProps<SVGSVGElement>) => ReactNode> = {
+ draft: (props) => <GitPullRequestDraft {...props} />,
+ open: (props) => <GitPullRequest {...props} />,
+ queued: (props) => <MergeQueueIcon {...props} />,
+ merged: (props) => <GitMerge {...props} />,
+ closed: (props) => <GitPullRequestClosed {...props} />,
+};
+
+// CI gets shapes GitHub uses for checks — a circle that is dashed, spinning,
+// ticked or crossed — so a green tick can never be read as the purple merge.
+const CI_TONE: Record<CiState, string> = {
+ none: "text-muted-foreground/60",
+ pending: "text-warning",
+ running: "text-warning",
+ success: "text-success",
+ failure: "text-destructive",
+};
+
+function CiIcon({ state, className }: { state: CiState; className?: string }) {
+ const cls = cn("h-4 w-4", CI_TONE[state], className);
+ if (state === "running") return <Loader2 className={cn(cls, "animate-spin motion-reduce:animate-none")} aria-hidden />;
+ if (state === "success") return <CircleCheck className={cls} aria-hidden />;
+ if (state === "failure") return <CircleX className={cls} aria-hidden />;
+ return <CircleDashed className={cls} aria-hidden />;
+}
+
+function useGitOverview(workspaceId: string | null) {
+ const [data, setData] = useState<RepoOverview | null>(null);
+ const [error, setError] = useState("");
+ const [loading, setLoading] = useState(false);
+ const [force, setForce] = useState(0);
+ useEffect(() => {
+ setData(null);
+ setError("");
+ }, [workspaceId]);
+ useEffect(() => {
+ if (!workspaceId) return;
+ let alive = true;
+ let timer: number | undefined;
+ let refresh = force > 0;
+ const tick = async () => {
+ if (useEventStore.getState().activeSection === "agentic-ide") {
+ setLoading(true);
+ try {
+ const next = await fetchGitOverview(workspaceId, refresh);
+ refresh = false;
+ if (alive) {
+ setData(next);
+ setError("");
+ }
+ } catch (err) {
+ // Keep the last answer on screen; the next tick tries again.
+ if (alive) setError((err as Error).message);
+ } finally {
+ if (alive) setLoading(false);
+ }
+ }
+ if (alive) timer = window.setTimeout(tick, POLL_MS + Math.random() * POLL_JITTER_MS);
+ };
+ void tick();
+ return () => {
+ alive = false;
+ window.clearTimeout(timer);
+ };
+ }, [workspaceId, force]);
+ return { data, error, loading, refresh: () => setForce((value) => value + 1) };
+}
+
+/** An icon that opens a GitHub page; a plain span when there is nowhere to go. */
+function LinkIcon({
+ url,
+ tip,
+ label,
+ testId,
+ children,
+}: {
+ url: string;
+ tip: string;
+ label: string;
+ testId: string;
+ children: ReactNode;
+}) {
+ const body = url ? (
+ <button
+ type="button"
+ data-testid={testId}
+ aria-label={label}
+ onClick={(event) => {
+ event.stopPropagation();
+ void openExternalUrl(url);
+ }}
+ className="inline-flex h-6 min-w-6 items-center justify-center gap-0.5 rounded-md px-1 hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ {children}
+ </button>
+ ) : (
+ <span data-testid={testId} aria-label={label} className="inline-flex h-6 min-w-6 items-center justify-center gap-0.5 px-1">
+ {children}
+ </span>
+ );
+ return (
+ <QuickTooltip content={tip} side="bottom" className="inline-flex shrink-0">
+ {body}
+ </QuickTooltip>
+ );
+}
+
+function prStateLabel(t: (key: string) => string, pr: PullRequest): string {
+ if (pr.state === "queued" && pr.queue_position) return fill(t("ide_side_panel.git.pr.queued_position"), { n: pr.queue_position });
+ return t(`ide_side_panel.git.pr.${pr.state}`);
+}
+
+function PullRequestBadge({ prs }: { prs: PullRequest[] }) {
+ const t = useT();
+ const [pr, ...others] = prs;
+ if (!pr) return null;
+ const Icon = PR_ICON[pr.state];
+ const lines = [
+ fill(t("ide_side_panel.git.pr_tooltip"), { state: prStateLabel(t, pr), number: pr.number, title: pr.title, base: pr.base }),
+ ...others.map((other) => `#${other.number} · ${prStateLabel(t, other)}`),
+ t("ide_side_panel.git.click_pr"),
+ ];
+ return (
+ <LinkIcon url={pr.url} tip={lines.join("\n")} label={`${prStateLabel(t, pr)} #${pr.number}`} testId="git-pr">
+ <Icon className={cn("h-4 w-4", PR_TONE[pr.state])} data-pr-state={pr.state} aria-hidden />
+ <span className={cn("font-mono text-[11px] tabular-nums", PR_TONE[pr.state])}>#{pr.number}</span>
+ </LinkIcon>
+ );
+}
+
+function CiBadge({ ci, stale }: { ci: CiStatus; stale: boolean }) {
+ const t = useT();
+ if (ci.state === "none") return null;
+ const lines = [
+ t(`ide_side_panel.git.ci.${ci.state}`),
+ fill(t("ide_side_panel.git.ci_counts"), {
+ passed: ci.passed,
+ total: ci.total,
+ failed: ci.failed,
+ running: ci.running,
+ pending: ci.pending,
+ }),
+ ];
+ if (ci.names.length > 0) {
+ const key = ci.state === "failure" ? "ide_side_panel.git.ci_failed_names" : "ide_side_panel.git.ci_running_names";
+ lines.push(fill(t(key), { names: ci.names.join(", ") }));
+ }
+ if (stale && ci.commit) lines.push(fill(t("ide_side_panel.git.ci_stale"), { commit: ci.commit.slice(0, 7) }));
+ if (ci.url) lines.push(t("ide_side_panel.git.click_ci"));
+ return (
+ <LinkIcon url={ci.url} tip={lines.join("\n")} label={t(`ide_side_panel.git.ci.${ci.state}`)} testId="git-ci">
+ <span data-ci-state={ci.state} className={cn("inline-flex", stale && "opacity-60")}>
+ <CiIcon state={ci.state} />
+ </span>
+ </LinkIcon>
+ );
+}
+
+function MergedChips({ row }: { row: BranchRow }) {
+ const t = useT();
+ if (row.merged_into.length === 0) return null;
+ return (
+ <>
+ {row.merged_into.map((merged) => {
+ const tip =
+ merged.via === "pull_request"
+ ? fill(t("ide_side_panel.git.merged_pr"), { target: merged.target, number: merged.number ?? "" })
+ : fill(t("ide_side_panel.git.merged_git"), { target: merged.target });
+ return (
+ <QuickTooltip key={merged.target} content={tip} side="bottom" className="inline-flex min-w-0">
+ <span
+ data-testid="git-merged-into"
+ data-target={merged.target}
+ className="inline-flex min-w-0 items-center gap-0.5 text-[10.5px] text-[hsl(var(--gh-merged))]"
+ >
+ <GitMerge className="h-3 w-3 shrink-0" aria-hidden />
+ <span className="truncate">{fill(t("ide_side_panel.git.merged_short"), { target: merged.target })}</span>
+ </span>
+ </QuickTooltip>
+ );
+ })}
+ </>
+ );
+}
+
+function BranchLine({ row, isDefault }: { row: BranchRow; isDefault: boolean }) {
+ const t = useT();
+ const meta: string[] = [];
+ if (row.upstream && (row.ahead || row.behind)) {
+ meta.push(fill(t("ide_side_panel.git.ahead_behind"), { ahead: row.ahead, behind: row.behind }));
+ }
+ const unpushed = !row.remote_only && !row.upstream && !row.on_github;
+ const nameTip = [
+ row.name,
+ row.current ? t("ide_side_panel.git.current") : "",
+ isDefault ? t("ide_side_panel.git.default") : "",
+ row.worktree ? fill(t("ide_side_panel.git.in_worktree"), { path: row.worktree }) : "",
+ row.upstream ? fill(t("ide_side_panel.git.tracks"), { upstream: row.upstream, ahead: row.ahead, behind: row.behind }) : "",
+ unpushed ? t("ide_side_panel.git.not_pushed") : "",
+ ]
+ .filter(Boolean)
+ .join("\n");
+ const BranchIcon = row.current ? CircleDot : GitBranch;
+ return (
+ <li
+ data-testid="git-branch-row"
+ data-branch={row.name}
+ data-current={row.current || undefined}
+ className={cn("flex min-h-9 items-center gap-2 px-3 py-1", row.current && "bg-accent/10")}
+ >
+ <BranchIcon className={cn("h-4 w-4 shrink-0", row.current ? "text-accent" : "text-muted-foreground")} aria-hidden />
+ <span className="flex min-w-0 flex-1 flex-col leading-tight">
+ <QuickTooltip content={nameTip} side="bottom" className="flex min-w-0 items-center gap-1.5">
+ <span className={cn("truncate font-mono text-[12.5px]", row.current ? "font-semibold text-foreground" : "text-foreground")}>
+ {row.name}
+ </span>
+ {isDefault && (
+ <span className="shrink-0 rounded border border-border px-1 text-[9.5px] uppercase tracking-wide text-muted-foreground">
+ {t("ide_side_panel.git.default_badge")}
+ </span>
+ )}
+ </QuickTooltip>
+ {(row.merged_into.length > 0 || meta.length > 0 || row.worktree || unpushed) && (
+ <span className="flex min-w-0 items-center gap-2 text-[10.5px] text-muted-foreground">
+ <MergedChips row={row} />
+ {meta.length > 0 && <span className="shrink-0 tabular-nums">{meta.join(" · ")}</span>}
+ {row.worktree && <span className="shrink-0">{t("ide_side_panel.git.worktree_badge")}</span>}
+ {unpushed && <span className="shrink-0">{t("ide_side_panel.git.local_only")}</span>}
+ </span>
+ )}
+ </span>
+ <PullRequestBadge prs={row.pull_requests} />
+ <CiBadge ci={row.ci} stale={row.ci_stale} />
+ </li>
+ );
+}
+
+function Legend() {
+ const t = useT();
+ const pr = (["draft", "open", "queued", "merged", "closed"] as const).map((state) => {
+ const Icon = PR_ICON[state];
+ return (
+ <li key={state} className="flex items-center gap-1.5">
+ <Icon className={cn("h-3.5 w-3.5", PR_TONE[state])} aria-hidden />
+ {t(`ide_side_panel.git.pr.${state}`)}
+ </li>
+ );
+ });
+ const ci = (["pending", "running", "success", "failure"] as const).map((state) => (
+ <li key={state} className="flex items-center gap-1.5">
+ <CiIcon state={state} className="h-3.5 w-3.5 animate-none" />
+ {t(`ide_side_panel.git.ci.${state}`)}
+ </li>
+ ));
+ return (
+ <div data-testid="git-legend" className="grid grid-cols-2 gap-x-3 gap-y-1 px-3 pb-2 text-[10.5px] text-muted-foreground">
+ <ul className="space-y-1">{pr}</ul>
+ <ul className="space-y-1">
+ {ci}
+ <li className="flex items-center gap-1.5">
+ <GitMerge className="h-3.5 w-3.5 text-[hsl(var(--gh-merged))]" aria-hidden />
+ {t("ide_side_panel.git.legend_merged")}
+ </li>
+ </ul>
+ </div>
+ );
+}
+
+function sinceLabel(t: (key: string) => string, fetchedAt: number): string {
+ const seconds = Math.max(0, Math.round(Date.now() / 1000 - fetchedAt));
+ if (seconds < 60) return fill(t("ide_side_panel.git.seconds_ago"), { n: seconds });
+ return fill(t("ide_side_panel.git.minutes_ago"), { n: Math.round(seconds / 60) });
+}
+
+/**
+ * The Git tab: the open workspace's branches, the checked-out one marked,
+ * what each is merged into, its pull request and — separately — its CI.
+ * Every icon explains itself on hover and opens its GitHub page on click.
+ */
+export function GitOverviewTab() {
+ const t = useT();
+ const workspace = useIdeChatStore((state) => state.workspace);
+ const workspaceId = workspace?.id ?? null;
+ const { data, error, loading, refresh } = useGitOverview(workspaceId);
+ const [showRemote, setShowRemote] = useState(false);
+ const [showLegend, setShowLegend] = useState(false);
+
+ if (!workspace) {
+ return <p className="px-4 py-6 text-center text-xs text-muted-foreground">{t("ide_side_panel.git.no_workspace")}</p>;
+ }
+ const github = data?.github;
+ const repoName = (data?.root || workspace.path).replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? workspace.name;
+
+ return (
+ <section data-testid="ide-git-tab" aria-label={t("ide_side_panel.git.aria")} className="flex h-full min-h-0 flex-col">
+ <div className="shrink-0 space-y-1.5 border-b border-border/60 px-3 pb-2.5 pt-3">
+ <div className="flex items-center gap-2">
+ <FolderGit2 className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="min-w-0 truncate text-sm font-semibold text-foreground">{repoName}</span>
+ {data?.available && (
+ <span
+ data-testid="git-current-branch"
+ className="flex min-w-0 shrink items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground"
+ >
+ <GitBranch className="h-3 w-3 shrink-0" aria-hidden />
+ <span className="truncate">{data.detached ? data.head.slice(0, 7) : data.branch}</span>
+ </span>
+ )}
+ <span className="ml-auto flex shrink-0 items-center">
+ {github?.repo_url && (
+ <LinkIcon url={github.repo_url} tip={t("ide_side_panel.git.open_repo")} label={t("ide_side_panel.git.open_repo")} testId="git-open-repo">
+ <ExternalLink className="h-3.5 w-3.5 text-muted-foreground" />
+ </LinkIcon>
+ )}
+ <QuickTooltip content={t("ide_side_panel.git.legend")} side="bottom" className="inline-flex">
+ <button
+ type="button"
+ aria-label={t("ide_side_panel.git.legend")}
+ aria-pressed={showLegend}
+ onClick={() => setShowLegend((value) => !value)}
+ className={cn(
+ "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ showLegend && "bg-secondary text-foreground",
+ )}
+ >
+ <CircleHelp className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ </QuickTooltip>
+ <QuickTooltip content={t("ide_side_panel.git.refresh")} side="bottom" className="inline-flex">
+ <button
+ type="button"
+ data-testid="git-refresh"
+ aria-label={t("ide_side_panel.git.refresh")}
+ onClick={refresh}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <RefreshCw className={cn("h-3.5 w-3.5", loading && "animate-spin motion-reduce:animate-none")} aria-hidden />
+ </button>
+ </QuickTooltip>
+ </span>
+ </div>
+ {github && (
+ <p data-testid="git-github-state" className="truncate text-[10.5px] text-muted-foreground">
+ {github.available
+ ? fill(t("ide_side_panel.git.github_updated"), { when: sinceLabel(t, github.fetched_at) })
+ : fill(t("ide_side_panel.git.github_off"), { reason: github.reason })}
+ </p>
+ )}
+ </div>
+ {showLegend && (
+ <div className="shrink-0 border-b border-border/60 pt-2">
+ <Legend />
+ </div>
+ )}
+ <div className="min-h-0 flex-1 overflow-y-auto py-1">
+ {!data ? (
+ error ? (
+ <p className="px-4 py-6 text-center text-xs text-destructive">{error}</p>
+ ) : (
+ <p className="flex items-center justify-center gap-2 px-4 py-6 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
+ {t("ide_side_panel.git.loading")}
+ </p>
+ )
+ ) : !data.available ? (
+ <p data-testid="git-unavailable" className="px-4 py-6 text-center text-xs text-muted-foreground">
+ {data.reason}
+ </p>
+ ) : (
+ <>
+ <ul aria-label={t("ide_side_panel.git.branches")}>
+ {data.branches.map((row) => (
+ <BranchLine key={row.name} row={row} isDefault={row.name === data.default_branch} />
+ ))}
+ </ul>
+ {data.truncated && (
+ <p className="px-3 py-2 text-[11px] text-muted-foreground">
+ {fill(t("ide_side_panel.git.truncated"), { n: data.branches.length })}
+ </p>
+ )}
+ {data.remote_branches.length > 0 && (
+ <div className="mt-1 border-t border-border/60">
+ <button
+ type="button"
+ data-testid="git-remote-toggle"
+ aria-expanded={showRemote}
+ onClick={() => setShowRemote((value) => !value)}
+ className="flex w-full items-center gap-1.5 px-3 py-2 text-left text-[11px] font-medium text-muted-foreground hover:text-foreground"
+ >
+ <ChevronRight className={cn("h-3.5 w-3.5 transition-transform", showRemote && "rotate-90")} aria-hidden />
+ {fill(t("ide_side_panel.git.remote_only"), { n: data.remote_branches.length })}
+ </button>
+ {showRemote && (
+ <ul aria-label={fill(t("ide_side_panel.git.remote_only"), { n: data.remote_branches.length })}>
+ {data.remote_branches.map((row) => (
+ <BranchLine key={row.name} row={row} isDefault={false} />
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ {error && <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>}
+ </>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts
new file mode 100644
index 0000000000..8f8ac688ca
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts
@@ -0,0 +1,106 @@
+/**
+ * The Git tab's one read: a workspace repository's branches with what each is
+ * merged into, its pull requests and its CI (`GET /api/agentic-ide/git/overview`).
+ *
+ * Mirrors `jarvis/agentic_ide/git_overview.py`. Merged, pull request and CI
+ * are three separate facts on purpose — passing checks never mean "merged".
+ */
+
+export type PullRequestState = "draft" | "open" | "queued" | "merged" | "closed";
+export type CiState = "none" | "pending" | "running" | "success" | "failure";
+
+export interface CiStatus {
+ state: CiState;
+ /** The failing / running workflow run, or the pull request's checks page. */
+ url: string;
+ total: number;
+ passed: number;
+ failed: number;
+ running: number;
+ pending: number;
+ /** The commit the checks ran on (12 chars). */
+ commit: string;
+ /** Failed checks, or the running ones while nothing failed. */
+ names: string[];
+}
+
+export interface PullRequest {
+ number: number;
+ title: string;
+ url: string;
+ state: PullRequestState;
+ base: string;
+ head: string;
+ head_oid: string;
+ merged_at: string;
+ updated_at: string;
+ queue_position: number | null;
+ ci: CiStatus;
+}
+
+export interface MergedInto {
+ target: string;
+ /** `git`: its commits are in the target; `pull_request`: GitHub merged its PR. */
+ via: "git" | "pull_request";
+ number: number | null;
+ url: string;
+}
+
+export interface BranchRow {
+ name: string;
+ current: boolean;
+ remote_only: boolean;
+ upstream: string;
+ ahead: number;
+ behind: number;
+ head: string;
+ committed_at: number;
+ /** Another checkout this branch is open in. */
+ worktree: string;
+ on_github: boolean;
+ merged_into: MergedInto[];
+ /** Most relevant first: queued, open, draft, merged, closed. */
+ pull_requests: PullRequest[];
+ ci: CiStatus;
+ /** Local commits CI has not seen yet. */
+ ci_stale: boolean;
+}
+
+export interface GitHubState {
+ available: boolean;
+ reason: string;
+ repo_url: string;
+ /** Epoch seconds of the GitHub answer in use. */
+ fetched_at: number;
+}
+
+export interface RepoOverview {
+ available: boolean;
+ reason: string;
+ root: string;
+ branch: string;
+ detached: boolean;
+ head: string;
+ default_branch: string;
+ branches: BranchRow[];
+ remote_branches: BranchRow[];
+ truncated: boolean;
+ github: GitHubState;
+}
+
+export async function fetchGitOverview(workspaceId: string, refresh = false): Promise<RepoOverview> {
+ const query = new URLSearchParams({ workspace_id: workspaceId });
+ if (refresh) query.set("refresh", "true");
+ const res = await fetch(`/api/agentic-ide/git/overview?${query.toString()}`);
+ if (!res.ok) {
+ let message = `Request failed (${res.status}).`;
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ if (typeof body.detail === "string") message = body.detail;
+ } catch {
+ /* keep the status-code message */
+ }
+ throw new Error(message);
+ }
+ return (await res.json()) as RepoOverview;
+}
diff --git a/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx b/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx
index 861c70fc41..200abd676b 100644
--- a/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx
+++ b/jarvis/ui/web/frontend/src/components/ui/tooltip.tsx
@@ -141,7 +141,8 @@ export function QuickTooltip({
// --popover with the strong rim and the only shadow the system
// allows — not the card surface it used to borrow.
"pointer-events-none z-[70] rounded-lg border border-border-strong bg-popover px-2.5 py-1.5 shadow-float",
- "text-sm text-popover-foreground",
+ // Multi-line content (a status with its details) keeps its line breaks.
+ "whitespace-pre-line text-sm text-popover-foreground",
position && "animate-in fade-in-0 zoom-in-95 duration-100",
)}
>
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 08e7880df4..061cf96d33 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5806,11 +5806,61 @@
"unchanged": "Seit dem letzten Commit unverändert."
},
"tabs": {
+ "git": "Git",
"agents": "Agents",
"files": "Ordner",
"changes": "Änderungen",
"office": "Büro"
},
+ "git": {
+ "aria": "Branches, Pull Requests und CI",
+ "no_workspace": "Wähle einen Workspace, um seine Branches zu sehen.",
+ "loading": "Lese Branches aus Git und GitHub …",
+ "refresh": "Jetzt aus Git und GitHub aktualisieren",
+ "branches": "Branches",
+ "legend": "Was die Symbole bedeuten",
+ "legend_merged": "Branch in ein Ziel gemergt",
+ "open_repo": "Repository auf GitHub öffnen",
+ "remote_only": "Nur auf GitHub ({n})",
+ "truncated": "Es werden die {n} zuletzt geänderten Branches gezeigt.",
+ "current": "In diesem Workspace ausgecheckt",
+ "default": "Standard-Branch des Repositorys",
+ "default_badge": "Standard",
+ "in_worktree": "In einem anderen Worktree ausgecheckt: {path}",
+ "worktree_badge": "anderer Worktree",
+ "tracks": "Folgt {upstream}: {ahead} voraus, {behind} zurück",
+ "ahead_behind": "↑{ahead} ↓{behind}",
+ "not_pushed": "Noch nicht zu GitHub gepusht",
+ "local_only": "nur lokal",
+ "merged_short": "in {target}",
+ "merged_git": "In {target} gemergt: Jeder Commit dieses Branches ist in {target} enthalten.",
+ "merged_pr": "Über Pull Request #{number} in {target} gemergt.",
+ "pr": {
+ "draft": "Pull Request im Entwurf",
+ "open": "Offener Pull Request",
+ "queued": "In der Merge-Warteschlange",
+ "queued_position": "In der Merge-Warteschlange, Platz {n}",
+ "merged": "Pull Request gemergt",
+ "closed": "Ohne Merge geschlossen"
+ },
+ "pr_tooltip": "{state} #{number} nach {base}\n{title}",
+ "click_pr": "Klicken, um den Pull Request auf GitHub zu öffnen.",
+ "ci": {
+ "pending": "CI wartet auf den Start",
+ "running": "CI läuft",
+ "success": "CI erfolgreich",
+ "failure": "CI fehlgeschlagen"
+ },
+ "ci_counts": "{passed} von {total} Prüfungen bestanden · {failed} fehlgeschlagen · {running} laufen · {pending} warten",
+ "ci_failed_names": "Fehlgeschlagen: {names}",
+ "ci_running_names": "Läuft: {names}",
+ "ci_stale": "Diese Prüfungen liefen auf {commit}; neuere lokale Commits sind noch nicht gepusht.",
+ "click_ci": "Klicken, um den CI-Lauf zu öffnen.",
+ "github_updated": "GitHub-Stand von {when}",
+ "github_off": "Kein GitHub-Status: {reason}",
+ "seconds_ago": "vor {n} s",
+ "minutes_ago": "vor {n} min"
+ },
"office": {
"failed": "Die Büro-Karte konnte nicht laden.",
"retry": "Erneut versuchen"
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 197e08fd59..8586172d3f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5839,11 +5839,61 @@
"unchanged": "Unchanged since the last commit."
},
"tabs": {
+ "git": "Git",
"agents": "Agents",
"files": "Folder",
"changes": "Changes",
"office": "Office"
},
+ "git": {
+ "aria": "Branches, pull requests and CI",
+ "no_workspace": "Select a workspace to see its branches.",
+ "loading": "Reading branches from git and GitHub…",
+ "refresh": "Refresh from git and GitHub now",
+ "branches": "Branches",
+ "legend": "What the symbols mean",
+ "legend_merged": "Branch merged into a target",
+ "open_repo": "Open the repository on GitHub",
+ "remote_only": "Only on GitHub ({n})",
+ "truncated": "Showing the {n} most recently changed branches.",
+ "current": "Checked out in this workspace",
+ "default": "The repository's default branch",
+ "default_badge": "default",
+ "in_worktree": "Checked out in another worktree: {path}",
+ "worktree_badge": "other worktree",
+ "tracks": "Tracks {upstream}: {ahead} ahead, {behind} behind",
+ "ahead_behind": "↑{ahead} ↓{behind}",
+ "not_pushed": "Not pushed to GitHub yet",
+ "local_only": "local only",
+ "merged_short": "in {target}",
+ "merged_git": "Merged into {target}: every commit of this branch is in {target}.",
+ "merged_pr": "Merged into {target} through pull request #{number}.",
+ "pr": {
+ "draft": "Draft pull request",
+ "open": "Open pull request",
+ "queued": "In the merge queue",
+ "queued_position": "In the merge queue, position {n}",
+ "merged": "Pull request merged",
+ "closed": "Closed without merging"
+ },
+ "pr_tooltip": "{state} #{number} into {base}\n{title}",
+ "click_pr": "Click to open the pull request on GitHub.",
+ "ci": {
+ "pending": "CI waiting to start",
+ "running": "CI running",
+ "success": "CI passed",
+ "failure": "CI failed"
+ },
+ "ci_counts": "{passed} of {total} checks passed · {failed} failed · {running} running · {pending} waiting",
+ "ci_failed_names": "Failed: {names}",
+ "ci_running_names": "Running: {names}",
+ "ci_stale": "These checks ran on {commit}; newer local commits are not pushed yet.",
+ "click_ci": "Click to open the CI run.",
+ "github_updated": "GitHub status from {when}",
+ "github_off": "No GitHub status: {reason}",
+ "seconds_ago": "{n} s ago",
+ "minutes_ago": "{n} min ago"
+ },
"office": {
"failed": "The office map could not load.",
"retry": "Try again"
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 264fe92457..c1f22bba67 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5806,11 +5806,61 @@
"unchanged": "Sin cambios desde el último commit."
},
"tabs": {
+ "git": "Git",
"agents": "Agentes",
"files": "Carpeta",
"changes": "Cambios",
"office": "Oficina"
},
+ "git": {
+ "aria": "Ramas, pull requests y CI",
+ "no_workspace": "Selecciona un espacio de trabajo para ver sus ramas.",
+ "loading": "Leyendo ramas de git y GitHub…",
+ "refresh": "Actualizar ahora desde git y GitHub",
+ "branches": "Ramas",
+ "legend": "Qué significan los símbolos",
+ "legend_merged": "Rama fusionada en un destino",
+ "open_repo": "Abrir el repositorio en GitHub",
+ "remote_only": "Solo en GitHub ({n})",
+ "truncated": "Se muestran las {n} ramas con cambios más recientes.",
+ "current": "Activa en este espacio de trabajo",
+ "default": "La rama principal del repositorio",
+ "default_badge": "principal",
+ "in_worktree": "Activa en otro worktree: {path}",
+ "worktree_badge": "otro worktree",
+ "tracks": "Sigue a {upstream}: {ahead} por delante, {behind} por detrás",
+ "ahead_behind": "↑{ahead} ↓{behind}",
+ "not_pushed": "Aún no se ha subido a GitHub",
+ "local_only": "solo local",
+ "merged_short": "en {target}",
+ "merged_git": "Fusionada en {target}: todos los commits de esta rama están en {target}.",
+ "merged_pr": "Fusionada en {target} mediante el pull request #{number}.",
+ "pr": {
+ "draft": "Pull request en borrador",
+ "open": "Pull request abierto",
+ "queued": "En la cola de fusión",
+ "queued_position": "En la cola de fusión, posición {n}",
+ "merged": "Pull request fusionado",
+ "closed": "Cerrado sin fusionar"
+ },
+ "pr_tooltip": "{state} #{number} hacia {base}\n{title}",
+ "click_pr": "Haz clic para abrir el pull request en GitHub.",
+ "ci": {
+ "pending": "CI esperando a empezar",
+ "running": "CI en curso",
+ "success": "CI superado",
+ "failure": "CI fallido"
+ },
+ "ci_counts": "{passed} de {total} comprobaciones superadas · {failed} fallidas · {running} en curso · {pending} en espera",
+ "ci_failed_names": "Fallidas: {names}",
+ "ci_running_names": "En curso: {names}",
+ "ci_stale": "Estas comprobaciones se ejecutaron en {commit}; hay commits locales más nuevos sin subir.",
+ "click_ci": "Haz clic para abrir la ejecución de CI.",
+ "github_updated": "Estado de GitHub de {when}",
+ "github_off": "Sin estado de GitHub: {reason}",
+ "seconds_ago": "hace {n} s",
+ "minutes_ago": "hace {n} min"
+ },
"office": {
"failed": "No se pudo cargar el mapa de la oficina.",
"retry": "Reintentar"
diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.css
index e6f5c5f173..374624a70d 100644
--- a/jarvis/ui/web/frontend/src/index.css
+++ b/jarvis/ui/web/frontend/src/index.css
@@ -555,6 +555,11 @@ label,
--diff-del: 344 78% 42%; /* #BE1744 */
--diff-del-bg: 350 100% 69%; /* #FF617B, read at 22 % */
+ /* GitHub's "merged" purple, for the IDE Git tab's merged pull requests and
+ merged-into marks. Open, closed and queued reuse success, destructive
+ and warning; merged is the one GitHub state the set had no hue for. */
+ --gh-merged: 262 69% 58%; /* #8250DF — GitHub light */
+
--radius: 0.75rem;
/* --- Effect channels (see the note above) ---------------------------- */
@@ -744,6 +749,7 @@ label,
--diff-add-bg: 143 43% 44%; /* #3FA266, read at 18 % */
--diff-del: 350 96% 71%; /* #FC6B83 */
--diff-del-bg: 336 100% 36%; /* #B80049, read at 20 % */
+ --gh-merged: 262 89% 72%; /* #A371F7 — GitHub dark; see :root */
--accent-rgb: 61 139 255;
--scrim-rgb: 0 0 0;
diff --git a/tests/unit/agentic_ide/test_git_overview.py b/tests/unit/agentic_ide/test_git_overview.py
new file mode 100644
index 0000000000..7c5033cc94
--- /dev/null
+++ b/tests/unit/agentic_ide/test_git_overview.py
@@ -0,0 +1,285 @@
+"""The IDE Git tab's data: branches, merged-into, pull requests and CI."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import git_overview
+from jarvis.agentic_ide.git_overview import ci_from_rollup, parse_github
+
+needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")
+
+
[email protected](autouse=True)
+def _isolated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("GIT_AUTHOR_NAME", "Test")
+ monkeypatch.setenv("GIT_AUTHOR_EMAIL", "[email protected]")
+ monkeypatch.setenv("GIT_COMMITTER_NAME", "Test")
+ monkeypatch.setenv("GIT_COMMITTER_EMAIL", "[email protected]")
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(tmp_path / "gitconfig"))
+ git_overview.clear_cache()
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, capture_output=True, text=True, check=True, encoding="utf-8"
+ ).stdout.strip()
+
+
+def _commit(root: Path, name: str) -> None:
+ (root / name).write_text(name, encoding="utf-8")
+ _git(root, "add", name)
+ _git(root, "commit", "-q", "-m", name)
+
+
+def repo(tmp_path: Path) -> Path:
+ root = tmp_path / "project"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ _commit(root, "a.txt")
+ # feature/done: merged into main with a merge commit.
+ _git(root, "switch", "-q", "-c", "feature/done")
+ _commit(root, "b.txt")
+ _git(root, "switch", "-q", "main")
+ _git(root, "merge", "-q", "--no-ff", "-m", "merge done", "feature/done")
+ # feature/wip: work main does not have yet.
+ _git(root, "switch", "-q", "-c", "feature/wip")
+ _commit(root, "c.txt")
+ # feature/fresh: just created from main, no work of its own.
+ _git(root, "branch", "feature/fresh", "main")
+ return root
+
+
+def _rollup(*nodes: dict, state: str = "", total: int | None = None) -> dict:
+ return {
+ "state": state,
+ "contexts": {
+ "totalCount": total if total is not None else len(nodes),
+ "nodes": list(nodes),
+ },
+ }
+
+
+def _run(name: str, status: str, conclusion: str | None = None, url: str = "") -> dict:
+ return {
+ "__typename": "CheckRun",
+ "name": name,
+ "status": status,
+ "conclusion": conclusion,
+ "detailsUrl": url + "/job",
+ "checkSuite": {"workflowRun": {"url": url}},
+ }
+
+
+# ------------------------------------------------------------------ CI
+
+
+def test_ci_failure_wins_and_links_the_failed_run() -> None:
+ ci = ci_from_rollup(
+ _rollup(
+ _run("lint", "COMPLETED", "SUCCESS", "https://x/runs/1"),
+ _run("tests", "IN_PROGRESS", None, "https://x/runs/2"),
+ _run("build", "COMPLETED", "FAILURE", "https://x/runs/3"),
+ ),
+ "abcdef0123456789",
+ )
+ assert (ci.state, ci.passed, ci.running, ci.failed, ci.total) == ("failure", 1, 1, 1, 3)
+ assert ci.url == "https://x/runs/3"
+ assert ci.names == ["build"]
+ assert ci.commit == "abcdef012345"
+
+
+def test_ci_running_beats_queued_and_queued_is_pending() -> None:
+ running = ci_from_rollup(
+ _rollup(_run("a", "QUEUED"), _run("b", "IN_PROGRESS", url="https://x/runs/9"))
+ )
+ assert running.state == "running"
+ assert running.url == "https://x/runs/9"
+ assert ci_from_rollup(_rollup(_run("a", "QUEUED"), _run("b", "WAITING"))).state == "pending"
+
+
+def test_ci_success_counts_skipped_and_status_contexts() -> None:
+ ci = ci_from_rollup(
+ _rollup(
+ _run("a", "COMPLETED", "SUCCESS"),
+ _run("b", "COMPLETED", "SKIPPED"),
+ {"__typename": "StatusContext", "context": "ext", "state": "SUCCESS", "targetUrl": "u"},
+ )
+ )
+ assert (ci.state, ci.passed, ci.total) == ("success", 3, 3)
+
+
+def test_ci_trusts_the_rollup_beyond_the_first_page() -> None:
+ ci = ci_from_rollup(_rollup(_run("a", "COMPLETED", "SUCCESS"), state="FAILURE", total=55))
+ assert ci.state == "failure"
+ assert ci.total == 55
+
+
+def test_ci_without_checks_is_none() -> None:
+ assert ci_from_rollup(None).state == "none"
+ assert ci_from_rollup(_rollup()).state == "none"
+
+
+# ------------------------------------------------------------------ GitHub parse
+
+
+def _pr(number: int, head: str, **extra: object) -> dict:
+ node = {
+ "number": number,
+ "title": f"PR {number}",
+ "url": f"https://github.com/o/r/pull/{number}",
+ "state": "OPEN",
+ "isDraft": False,
+ "isCrossRepository": False,
+ "headRefName": head,
+ "headRefOid": "",
+ "baseRefName": "main",
+ "mergedAt": None,
+ "updatedAt": "2026-09-29T00:00:00Z",
+ "isInMergeQueue": False,
+ "mergeQueueEntry": None,
+ "commits": {"nodes": []},
+ }
+ node.update(extra)
+ return node
+
+
+def _payload(prs: list[dict], refs: list[dict] | None = None) -> dict:
+ return {
+ "data": {
+ "repository": {
+ "url": "https://github.com/o/r",
+ "pullRequests": {"nodes": prs},
+ "refs": {"nodes": refs or []},
+ }
+ }
+ }
+
+
+def test_pull_request_states_cover_the_five_github_states() -> None:
+ snap = parse_github(
+ _payload(
+ [
+ _pr(1, "a", isDraft=True),
+ _pr(2, "b"),
+ _pr(3, "c", isInMergeQueue=True, mergeQueueEntry={"position": 2}),
+ _pr(4, "d", state="MERGED", mergedAt="2026-09-28T00:00:00Z"),
+ _pr(5, "e", state="CLOSED"),
+ _pr(6, "fork", isCrossRepository=True),
+ ]
+ )
+ )
+ assert [(pr.number, pr.state) for pr in snap.prs] == [
+ (1, "draft"),
+ (2, "open"),
+ (3, "queued"),
+ (4, "merged"),
+ (5, "closed"),
+ ]
+ assert snap.prs[2].queue_position == 2
+ assert snap.busy # a queued PR is worth re-reading sooner
+
+
+def test_unreadable_payload_is_unavailable() -> None:
+ assert parse_github({"data": {"repository": None}}).ok is False
+
+
+def test_gh_failure_reasons_are_fixed_sentences() -> None:
+ reason = git_overview._gh_failure_reason("To get started with GitHub CLI, run: gh auth login")
+ assert reason == "The GitHub CLI (gh) is not signed in."
+ assert git_overview._gh_failure_reason("secret host detail") == "GitHub could not be reached."
+
+
+# ------------------------------------------------------------------ local git
+
+
+@needs_git
+def test_overview_marks_current_default_and_merged_branches(repo: Path) -> None:
+ info = git_overview.overview(repo, github=False)
+ assert info.available
+ assert (info.branch, info.default_branch) == ("feature/wip", "main")
+ by_name = {row.name: row for row in info.branches}
+ assert by_name["feature/wip"].current
+ assert [m.target for m in by_name["feature/done"].merged_into] == ["main"]
+ assert by_name["feature/done"].merged_into[0].via == "git"
+ # Work main lacks, and a branch with no work of its own: neither is "merged".
+ assert by_name["feature/wip"].merged_into == []
+ assert by_name["feature/fresh"].merged_into == []
+ assert by_name["main"].merged_into == []
+
+
+@needs_git
+def test_overview_of_a_plain_folder_is_unavailable(tmp_path: Path) -> None:
+ info = git_overview.overview(tmp_path, github=False)
+ assert not info.available
+ assert "not a git repository" in info.reason
+
+
+@needs_git
+def test_overview_joins_pull_requests_ci_and_squash_merges(
+ repo: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ wip_head = _git(repo, "rev-parse", "feature/wip")
+ fresh_head = _git(repo, "rev-parse", "feature/fresh")
+ calls: list[Path] = []
+
+ def fake_fetch(root: Path) -> git_overview._GitHubSnapshot:
+ calls.append(root)
+ snap = parse_github(
+ _payload(
+ [
+ _pr(
+ 7,
+ "feature/wip",
+ headRefOid=wip_head,
+ commits={
+ "nodes": [
+ {
+ "commit": {
+ "oid": wip_head,
+ "statusCheckRollup": _rollup(
+ _run("tests", "IN_PROGRESS", url="https://x/runs/7")
+ ),
+ }
+ }
+ ]
+ },
+ ),
+ # A squash-merged PR whose branch has not moved since.
+ _pr(8, "feature/fresh", state="MERGED", headRefOid=fresh_head),
+ _pr(9, "only-remote", state="CLOSED"),
+ ],
+ refs=[
+ {"name": "main", "target": {"oid": "0" * 40, "statusCheckRollup": None}},
+ {"name": "only-remote", "target": {"oid": "1" * 40, "statusCheckRollup": None}},
+ ],
+ ),
+ fetched_at=git_overview.time.time(),
+ )
+ return snap
+
+ monkeypatch.setattr(git_overview, "_fetch_github", fake_fetch)
+ info = git_overview.overview(repo)
+ by_name = {row.name: row for row in info.branches}
+
+ wip = by_name["feature/wip"]
+ assert [(pr.number, pr.state) for pr in wip.pull_requests] == [(7, "open")]
+ assert (wip.ci.state, wip.ci.url, wip.ci_stale) == ("running", "https://x/runs/7", False)
+
+ fresh = by_name["feature/fresh"]
+ assert [(m.target, m.via, m.number) for m in fresh.merged_into] == [("main", "pull_request", 8)]
+
+ assert by_name["main"].on_github
+ assert [row.name for row in info.remote_branches] == ["only-remote"]
+ assert info.remote_branches[0].pull_requests[0].state == "closed"
+ assert info.github.available and info.github.repo_url == "https://github.com/o/r"
+
+ # A second read inside the TTL reuses the answer instead of calling GitHub again.
+ git_overview.overview(repo)
+ assert len(calls) == 1