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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(git): turn the Git tab into a control center for git and GitHub (#600)
Ruben Lütkeefc596d51c8b
diff --git a/jarvis/agentic_ide/git_local.py b/jarvis/agentic_ide/git_local.pynew file mode 100644index 0000000000..d6864e8d70--- /dev/null+++ b/jarvis/agentic_ide/git_local.py@@ -0,0 +1,672 @@+"""A repository's local state, read fast enough to poll.++The IDE's Git tab asks for the same repository every few seconds, from every+open pane. Reading it costs a handful of ``git`` processes, and the expensive+part — every branch with how far it is ahead of / behind its upstream and the+default branch — only changes when a ref moves. So this module splits the read+in two:++* **Branches** are read once and reused until the repository's refs change.+ The check is a walk over the ref files' timestamps (no process), so an+ unchanged repository costs a few milliseconds instead of half a second.+* **The checkout** (uncommitted changes, ahead/behind of the current branch) is+ one ``git status`` per read, shared by callers that ask within a second.++A cold read runs its git commands side by side. Nothing here raises: a folder+that is not a repository, or a machine without git, answers ``None``.+"""++from __future__ import annotations++import os+import shutil+import subprocess+import threading+import time+from collections.abc import Callable+from dataclasses import 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+#: A status answer this young is shared instead of read again (N panes, one repository).+STATUS_SHARE_S = 1.0+#: Branches are re-read at least this often even when no ref file changed.+BRANCHES_MAX_AGE_S = 30.0+#: Where a repository's paths are remembered before git is asked again.+_PATHS_TTL_S = 60.0+#: Default-branch names tried when ``origin/HEAD`` does not say.+_DEFAULT_CANDIDATES = ("main", "master", "trunk", "develop")+++class Job:+ """One call on a daemon thread, so a cold read runs its git commands side by side.++ Daemon threads on purpose: a hung git must never keep the app from exiting.+ """++ def __init__(self, target: Callable[..., Any], *args: Any) -> None:+ self._value: Any = None+ self._error: BaseException | None = None+ self._thread = threading.Thread(+ target=self._work, args=(target, args), name="git-local", daemon=True+ )+ self._thread.start()++ def _work(self, target: Callable[..., Any], args: tuple[Any, ...]) -> None:+ try:+ self._value = target(*args)+ except BaseException as exc: # re-raised in the caller by result()+ self._error = exc++ def result(self) -> Any:+ self._thread.join()+ if self._error is not None:+ raise self._error+ return self._value+++# ------------------------------------------------------------------ plumbing+++def run_git(+ args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S, stdin: str | None = None+):+ """One git call that never prompts; None when git is missing or hangs."""+ env = dict(os.environ)+ env["GIT_TERMINAL_PROMPT"] = "0"+ # Reading must never take the index lock away from the person's own git.+ env["GIT_OPTIONAL_LOCKS"] = "0"+ try:+ return subprocess.run(+ ["git", "-c", "core.quotePath=false", *args],+ cwd=str(cwd),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=timeout,+ check=False,+ env=env,+ input=stdin,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except FileNotFoundError: # git not installed: callers report it as unavailable+ return None+ except subprocess.TimeoutExpired:+ logger.info("Git: `git {}` did not answer in time in {}", args[0] if args else "", cwd)+ return None+++def git_out(args: list[str], cwd: Path) -> str | None:+ result = run_git(args, cwd)+ if result is None or result.returncode != 0:+ return None+ return result.stdout+++# ------------------------------------------------------------------ model+++@dataclass(slots=True)+class LocalBranch:+ name: str+ head: str = ""+ upstream: str = ""+ ahead: int = 0+ behind: int = 0+ #: The upstream is configured but no longer exists on the remote.+ upstream_gone: bool = False+ committed_at: int = 0+ #: The folder this branch is checked out in ("" when it is nowhere).+ worktree: str = ""+ #: Commits it has that the default branch lacks / lacks that it has; None when unknown.+ base_ahead: int | None = None+ base_behind: int | None = None+ #: Targets whose history already contains all of its commits.+ merged_into: list[str] = field(default_factory=list)+++@dataclass(slots=True)+class Checkout:+ """The folder's own state: what is uncommitted and how it stands to its remote."""++ branch: str = ""+ detached: bool = False+ #: No commit yet (a fresh ``git init``).+ unborn: bool = False+ head: str = ""+ upstream: str = ""+ ahead: int = 0+ behind: int = 0+ #: Files with any uncommitted change; one both staged and edited counts once.+ files: int = 0+ staged: int = 0+ unstaged: int = 0+ untracked: int = 0+ conflicted: int = 0+ #: ``merge`` | ``rebase`` | ``cherry-pick`` | ``revert`` | ``bisect`` while one is unfinished.+ operation: str = ""+ stashes: int = 0+ #: Epoch seconds of the last ``git fetch`` (0 when never).+ last_fetch: int = 0+ has_remote: bool = False+++@dataclass(slots=True)+class LocalState:+ root: Path+ checkout: Checkout+ default_branch: str = ""+ #: What ``base_ahead`` / ``base_behind`` compare with (``origin/main``), "" when unknown.+ base_ref: str = ""+ branches: list[LocalBranch] = field(default_factory=list)+ #: Remote-tracking branch (``origin/main``) → the commit it points at.+ remote_heads: dict[str, str] = field(default_factory=dict)+++@dataclass(slots=True)+class RepoPaths:+ root: Path+ #: This checkout's git directory (``.git``, or ``.git/worktrees/<name>``).+ git_dir: Path+ #: The directory every worktree of the repository shares.+ common_dir: Path+++# ------------------------------------------------------------------ locating++_paths_guard = threading.Lock()+_paths: dict[str, tuple[float, RepoPaths]] = {}+++def locate(folder: str | Path) -> RepoPaths | None:+ """The repository ``folder`` is in; None when it is not one (or git is missing)."""+ path = Path(folder).expanduser()+ if not path.is_dir() or shutil.which("git") is None:+ return None+ key = os.path.normcase(str(path))+ now = time.monotonic()+ with _paths_guard:+ hit = _paths.get(key)+ if hit and now - hit[0] < _PATHS_TTL_S and hit[1].git_dir.is_dir():+ return hit[1]+ text = git_out(["rev-parse", "--show-toplevel", "--git-dir", "--git-common-dir"], path)+ lines = [line.strip() for line in (text or "").splitlines() if line.strip()]+ if len(lines) < 3:+ with _paths_guard:+ _paths.pop(key, None)+ return None++ def absolute(value: str) -> Path:+ candidate = Path(value)+ return candidate if candidate.is_absolute() else (path / candidate)++ found = RepoPaths(+ root=Path(lines[0]), git_dir=absolute(lines[1]), common_dir=absolute(lines[2])+ )+ with _paths_guard:+ _paths[key] = (now, found)+ return found+++# ------------------------------------------------------------------ fingerprint+++def _stamp(path: Path) -> tuple[int, int]:+ try:+ info = path.stat()+ except OSError: # the file does not exist (no packed refs yet, no fetch yet)+ return (0, 0)+ return (info.st_mtime_ns, info.st_size)+++def _walk(folder: Path, into: list[tuple[str, int, int]]) -> None:+ try:+ entries = sorted(os.scandir(folder), key=lambda entry: entry.name)+ except OSError: # no such directory (a repository without remotes): nothing to add+ return+ for entry in entries:+ try:+ info = entry.stat()+ is_dir = entry.is_dir()+ except OSError: # deleted between the listing and the stat: the next read sees it gone+ continue+ into.append((entry.path, info.st_mtime_ns, info.st_size))+ if is_dir:+ _walk(Path(entry.path), into)+++def refs_fingerprint(paths: RepoPaths) -> tuple:+ """Changes whenever a branch, a remote-tracking ref, HEAD or a worktree does.++ Git moves a ref by renaming a lock file over it, so both the file's and its+ directory's timestamp change; packed and reftable storage change their own+ files. Reading timestamps costs no process.+ """+ marks: list[tuple[str, int, int]] = []+ for name in ("HEAD", "packed-refs", "config"):+ marks.append((name, *_stamp(paths.common_dir / name)))+ if paths.git_dir != paths.common_dir:+ marks.append(("worktree-HEAD", *_stamp(paths.git_dir / "HEAD")))+ _walk(paths.common_dir / "refs" / "heads", marks)+ _walk(paths.common_dir / "refs" / "remotes", marks)+ _walk(paths.common_dir / "reftable", marks)+ try:+ trees = sorted(os.scandir(paths.common_dir / "worktrees"), key=lambda entry: entry.name)+ except OSError: # no linked worktrees+ trees = []+ for tree in trees:+ marks.append((tree.name, *_stamp(Path(tree.path) / "HEAD")))+ # Rewritten when the worktree's folder is moved.+ marks.append((f"{tree.name}/gitdir", *_stamp(Path(tree.path) / "gitdir")))+ # The reflog grows with every move of HEAD, even two inside one timestamp tick.+ marks.append(("logs/HEAD", *_stamp(paths.common_dir / "logs" / "HEAD")))+ return tuple(marks)+++# ------------------------------------------------------------------ branches++# None until the first read; False on a git older than 2.41 (no ``ahead-behind`` atom).+_ahead_behind_ok: bool | None = None+++def _parse_track(text: str) -> tuple[int, int, bool]:+ ahead = behind = 0+ gone = False+ for part in text.split(","):+ word, _, count = part.strip().partition(" ")+ if word == "ahead" and count.isdigit():+ ahead = int(count)+ elif word == "behind" and count.isdigit():+ behind = int(count)+ elif word == "gone":+ gone = True+ return ahead, behind, gone+++def _read_heads(root: Path) -> list[LocalBranch] | None:+ """Every local branch; None when git did not answer (never cached as "no branches")."""+ text = git_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,+ )+ if text is None:+ return None+ rows: list[LocalBranch] = []+ for line in text.splitlines():+ name, oid, upstream, track, stamp, tree = ([*line.split("\t"), "", "", "", "", ""])[:6]+ if not name:+ continue+ ahead, behind, gone = _parse_track(track)+ rows.append(+ LocalBranch(+ name=name,+ head=oid,+ upstream=upstream,+ ahead=ahead,+ behind=behind,+ upstream_gone=gone,+ committed_at=int(stamp) if stamp.isdigit() else 0,+ worktree=str(Path(tree)) if tree else "",+ )+ )+ return rows+++def _read_remote_heads(root: Path) -> dict[str, str]:+ text = git_out(+ ["for-each-ref", "--format=%(refname:short)%09%(objectname)", "refs/remotes"], root+ )+ heads: dict[str, str] = {}+ for line in (text or "").splitlines():+ name, _, oid = line.partition("\t")+ if name and oid and not name.endswith("/HEAD"):+ heads[name] = oid.strip()+ return heads+++def _read_origin_default(root: Path) -> str:+ text = git_out(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], root)+ return text.strip().split("/", 1)[-1] if text and text.strip() else ""+++def _pair(text: str) -> tuple[int, int] | None:+ ahead, _, behind = text.strip().partition(" ")+ return (int(ahead), int(behind)) if ahead.isdigit() and behind.isdigit() else None+++def _read_ahead_behind(+ root: Path, refs: list[str]+) -> dict[str, list[tuple[int, int] | None]] | None:+ """Branch → (ahead, behind) against each of ``refs``, in one history walk.++ None on a git without the ``ahead-behind`` atom; the caller then falls back+ to one ``--merged`` listing and reports no counts.+ """+ global _ahead_behind_ok+ if not refs or _ahead_behind_ok is False:+ return None+ atoms = "%09".join(f"%(ahead-behind:{ref})" for ref in refs)+ result = run_git(["for-each-ref", f"--format=%(refname:short)%09{atoms}", "refs/heads"], root)+ if result is None:+ return None+ if result.returncode != 0:+ if "unknown field name" in (result.stderr or ""):+ _ahead_behind_ok = False+ return None+ _ahead_behind_ok = True+ counts: dict[str, list[tuple[int, int] | None]] = {}+ for line in result.stdout.splitlines():+ name, *cells = line.split("\t")+ if name:+ counts[name] = [_pair(cell) for cell in cells]+ return counts+++def merged_into(root: Path, target_ref: str) -> dict[str, str]:+ """Branch name → tip, for every branch whose commits ``target_ref`` already has."""+ text = git_out(+ [+ "for-each-ref",+ f"--merged={target_ref}",+ "--format=%(refname:short)%09%(objectname)",+ "refs/heads",+ ],+ root,+ )+ found: dict[str, str] = {}+ for line in (text or "").splitlines():+ name, _, oid = line.partition("\t")+ if name:+ found[name] = oid.strip()+ return found+++@dataclass(slots=True)+class _Branches:+ fingerprint: tuple+ taken_at: float+ default_branch: str+ base_ref: str+ rows: list[LocalBranch]+ remote_heads: dict[str, str]+++def _read_branches(paths: RepoPaths, current: str, fingerprint: tuple) -> _Branches | None:+ root = paths.root+ default = _read_origin_default(root)+ heads_job = Job(_read_heads, root)+ remotes_job = Job(_read_remote_heads, root)+ # Counted while the branch list is still being read; the guess holds+ # whenever the default branch exists both here and on the remote.+ guess = [f"refs/heads/{default}", f"refs/remotes/origin/{default}"] if default else []+ counts_job = Job(_read_ahead_behind, root, guess) if guess else None+ rows, remote_heads = heads_job.result(), remotes_job.result()+ if rows is None:+ if counts_job is not None:+ counts_job.result()+ return None+ names = {row.name: row for row in rows}+ if not default:+ default = next((name for name in _DEFAULT_CANDIDATES if name in names), current)++ # The default branch as this computer has it, and as the remote does: a+ # branch whose commits are in either is merged.+ targets: list[str] = []+ if default and default in names:+ targets.append(f"refs/heads/{default}")+ if default and f"origin/{default}" in remote_heads:+ targets.append(f"refs/remotes/origin/{default}")+ base_ref = ""+ if targets:+ base_ref = f"origin/{default}" if targets[-1].startswith("refs/remotes/") else default+ tips = [+ names[default].head if ref.startswith("refs/heads/") else remote_heads[f"origin/{default}"]+ for ref in targets+ ]++ counts = counts_job.result() if counts_job is not None else None+ if targets != guess:+ counts = _read_ahead_behind(root, targets)+ if counts is not None:+ for row in rows:+ cells = counts.get(row.name) or []+ pairs = [cell for cell in cells if cell is not None]+ if pairs:+ row.base_ahead, row.base_behind = pairs[-1]+ if row.name == default:+ continue+ # Tip equal to the target's: created from it, no work of its own — not "merged".+ if any(+ cell is not None and cell[0] == 0 and row.head != tips[index]+ for index, cell in enumerate(cells[: len(tips)])+ ):+ row.merged_into = [default]+ else:+ for index, ref in enumerate(targets):+ for name, oid in merged_into(root, ref).items():+ row = names.get(name)+ if (+ row is not None+ and name != default+ and oid != tips[index]+ and not row.merged_into+ ):+ row.merged_into = [default]+ return _Branches(+ fingerprint=fingerprint,+ taken_at=time.monotonic(),+ default_branch=default,+ base_ref=base_ref,+ rows=rows,+ remote_heads=remote_heads,+ )+++# ------------------------------------------------------------------ checkout+++def _parse_status(text: str, checkout: Checkout) -> None:+ """Fill ``checkout`` from ``git status --porcelain=v2 --branch``."""+ for line in text.splitlines():+ if line.startswith("# branch.oid "):+ oid = line[len("# branch.oid ") :].strip()+ checkout.unborn = oid == "(initial)"+ checkout.head = "" if checkout.unborn else oid[:12]+ elif line.startswith("# branch.head "):+ head = line[len("# branch.head ") :].strip()+ checkout.detached = head == "(detached)"+ checkout.branch = "" if checkout.detached else head+ elif line.startswith("# branch.upstream "):+ checkout.upstream = line[len("# branch.upstream ") :].strip()+ elif line.startswith("# branch.ab "):+ ahead, _, behind = line[len("# branch.ab ") :].strip().partition(" ")+ if ahead[1:].isdigit() and behind[1:].isdigit():+ checkout.ahead, checkout.behind = int(ahead[1:]), int(behind[1:])+ elif line.startswith(("1 ", "2 ")):+ xy = line[2:4]+ checkout.files += 1+ if xy[:1] != ".":+ checkout.staged += 1+ if xy[1:2] != ".":+ checkout.unstaged += 1+ elif line.startswith("u "):+ checkout.files += 1+ checkout.conflicted += 1+ elif line.startswith("? "):+ checkout.files += 1+ checkout.untracked += 1+++def _operation(git_dir: Path) -> str:+ if (git_dir / "rebase-merge").is_dir() or (git_dir / "rebase-apply").is_dir():+ return "rebase"+ for marker, name in (+ ("MERGE_HEAD", "merge"),+ ("CHERRY_PICK_HEAD", "cherry-pick"),+ ("REVERT_HEAD", "revert"),+ ("BISECT_LOG", "bisect"),+ ):+ if (git_dir / marker).exists():+ return name+ return ""+++def _count_lines(path: Path) -> int:+ try:+ with path.open("rb") as handle:+ return sum(1 for _ in handle)+ except OSError: # no stash was ever made+ return 0+++def _has_remote(common_dir: Path) -> bool:+ try:+ return "[remote " in (common_dir / "config").read_text(encoding="utf-8", errors="replace")+ except OSError: # unreadable config: offer nothing that needs a remote+ return False+++def _read_checkout(paths: RepoPaths) -> Checkout | None:+ """The checkout's state; None when git did not answer."""+ checkout = Checkout()+ text = git_out(["status", "--porcelain=v2", "--branch", "--untracked-files=normal"], paths.root)+ if text is None:+ return None+ _parse_status(text, checkout)+ checkout.operation = _operation(paths.git_dir)+ checkout.stashes = _count_lines(paths.common_dir / "logs" / "refs" / "stash")+ checkout.last_fetch = _stamp(paths.common_dir / "FETCH_HEAD")[0] // 1_000_000_000+ checkout.has_remote = _has_remote(paths.common_dir)+ return checkout+++# ------------------------------------------------------------------ cache+++@dataclass(slots=True)+class _Entry:+ lock: threading.Lock = field(default_factory=threading.Lock)+ branches: _Branches | None = None+ checkout: Checkout | None = None+ checkout_at: float = 0.0+++_guard = threading.Lock()+_entries: dict[str, _Entry] = {}+++def forget(folder: str | Path | None = None) -> None:+ """Drop what is remembered (about one folder's repository, or everything)."""+ with _guard:+ if folder is None:+ _entries.clear()+ else:+ _entries.pop(os.path.normcase(str(Path(folder).expanduser())), None)+ if folder is None:+ with _paths_guard:+ _paths.clear()+++def read(folder: str | Path, *, fresh: bool = False) -> LocalState | None:+ """The repository ``folder`` is in; None when there is none to read.++ ``fresh`` re-reads everything now (after an action changed the repository).+ The branch rows are copies: callers may annotate them.+ """+ paths = locate(folder)+ if paths is None:+ return None+ key = os.path.normcase(str(paths.root))+ with _guard:+ entry = _entries.setdefault(key, _Entry())+ # One read per repository at a time; a second caller waits and reuses it.+ with entry.lock:+ now = time.monotonic()+ checkout_job = None+ if fresh or entry.checkout is None or now - entry.checkout_at >= STATUS_SHARE_S:+ checkout_job = Job(_read_checkout, paths)+ fingerprint = refs_fingerprint(paths)+ branches = entry.branches+ stale = (+ fresh+ or branches is None+ or branches.fingerprint != fingerprint+ or now - branches.taken_at >= BRANCHES_MAX_AGE_S+ )+ if checkout_job is not None:+ read_now = checkout_job.result()+ if read_now is not None:+ entry.checkout = read_now+ entry.checkout_at = time.monotonic()+ else:+ # Git did not answer: show what was last known, and ask again next time.+ logger.debug("Git: status of {} could not be read", paths.root)+ entry.checkout_at = 0.0+ checkout = entry.checkout or Checkout()+ if stale:+ read_branches = _read_branches(paths, checkout.branch, fingerprint)+ if read_branches is not None:+ branches = entry.branches = read_branches+ else:+ logger.debug("Git: branches of {} could not be read", paths.root)+ if branches is None:+ # Nothing was ever read and git is not answering: an empty repository+ # for this one call, remembered nowhere.+ branches = _Branches(+ fingerprint=(),+ taken_at=0.0,+ default_branch="",+ base_ref="",+ rows=[],+ remote_heads={},+ )+ return LocalState(+ root=paths.root,+ checkout=checkout,+ default_branch=branches.default_branch or checkout.branch,+ base_ref=branches.base_ref,+ branches=[+ LocalBranch(+ name=row.name,+ head=row.head,+ upstream=row.upstream,+ ahead=row.ahead,+ behind=row.behind,+ upstream_gone=row.upstream_gone,+ committed_at=row.committed_at,+ worktree=row.worktree,+ base_ahead=row.base_ahead,+ base_behind=row.base_behind,+ merged_into=list(row.merged_into),+ )+ for row in branches.rows+ ],+ remote_heads=branches.remote_heads,+ )+++def missing_commits(root: Path, oids: list[str]) -> set[str]:+ """The commits of ``oids`` this computer does not have (so: not fetched yet)."""+ wanted = [oid for oid in dict.fromkeys(oids) if oid]+ if not wanted:+ return set()+ result = run_git(["cat-file", "--batch-check"], root, stdin="\n".join(wanted) + "\n")+ if result is None or result.returncode != 0:+ return set()+ missing: set[str] = set()+ for oid, line in zip(wanted, result.stdout.splitlines(), strict=False):+ if line.rstrip().endswith(" missing"):+ missing.add(oid)+ return missingdiff --git a/jarvis/agentic_ide/git_ops.py b/jarvis/agentic_ide/git_ops.pyindex 7dc8f440f0..9ba3d7f705 100644--- a/jarvis/agentic_ide/git_ops.py+++ b/jarvis/agentic_ide/git_ops.py@@ -668,12 +668,16 @@ def commit_all(folder: str | Path, message: str) -> str:return _ok(["rev-parse", "--short", "HEAD"], root).strip()-def push(folder: str | Path) -> str:- """Push the current branch, setting its upstream on the first push."""+def push(folder: str | Path, branch: str = "") -> str:+ """Push the current branch — or ``branch``, without checking it out — setting+ its upstream on the first push."""path = _folder(folder)info = inspect(path)if not info.is_repo:raise GitError(f"{path.name} is not a git repository.", code="not_repo")+ other = normalize_branch(branch)+ if other and other != info.branch:+ return _push_other(info, other)if info.detached or not info.branch:raise GitError("Check out a branch before pushing.", code="detached")root = Path(info.root)@@ -692,6 +696,237 @@ def push(folder: str | Path) -> str:return f"{remote}/{info.branch}"+def _push_other(info: RepoInfo, branch: str) -> str:+ """Push a branch that is not the one checked out here."""+ root = Path(info.root)+ known = next((entry for entry in info.branches if entry.name == branch), None)+ if known is None:+ raise GitError(f"There is no local branch called {branch}.", code="not_found")+ if not info.remotes:+ raise GitError("This repository has no remote to push to.", code="no_remote")+ remote, _, target = known.upstream.partition("/")+ if not target or remote not in info.remotes:+ remote = "origin" if "origin" in info.remotes else info.remotes[0]+ target = branch+ _ok(+ ["push", "--set-upstream", remote, f"refs/heads/{branch}:refs/heads/{target}"],+ root,+ timeout=_NETWORK_TIMEOUT_S,+ what="push",+ )+ return f"{remote}/{target}"+++def pull(folder: str | Path, *, rebase: bool = False) -> str:+ """Bring the current branch up to date with its upstream. Returns a summary.++ The default only fast-forwards, so it can never rewrite or lose a commit;+ a branch that has diverged answers ``code="diverged"`` and the caller+ offers ``rebase``. A rebase that conflicts is aborted, never left half-done.+ """+ path = _folder(folder)+ info = inspect(path)+ if not info.is_repo:+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")+ if info.detached or not info.branch:+ raise GitError("Check out a branch before pulling.", code="detached")+ if not info.upstream:+ raise GitError(+ f"{info.branch} has no branch on the remote to pull from.", code="no_upstream"+ )+ root = Path(info.root)+ if not rebase:+ # --no-rebase: a configured pull.rebase must not turn this into a rewrite.+ result = _run(["pull", "--ff-only", "--no-rebase"], root, timeout=_NETWORK_TIMEOUT_S)+ if result.returncode == 0:+ return f"{info.branch} is up to date with {info.upstream}."+ # Asked of git itself, not read from its wording (which follows the locale).+ after = inspect(path)+ if after.ahead > 0 and after.behind > 0:+ raise GitError(+ f"{info.branch} and {info.upstream} have both moved on. "+ "Rebase your commits onto the remote ones to continue.",+ code="diverged",+ )+ raise GitError(f"Git could not pull: {_reason(result)}")+ if info.staged or info.unstaged or info.conflicted:+ raise GitError("Commit your changes first, then rebase.", code="dirty")+ # =merges: a local merge commit is replayed as a merge, not flattened away.+ result = _run(["pull", "--rebase=merges"], root, timeout=_NETWORK_TIMEOUT_S)+ if result.returncode != 0:+ conflicts = _run(["diff", "--name-only", "--diff-filter=U"], root).stdout.split()+ _run(["rebase", "--abort"], root)+ if conflicts:+ shown = ", ".join(conflicts[:5]) + (" …" if len(conflicts) > 5 else "")+ raise GitError(+ f"Rebasing {info.branch} onto {info.upstream} conflicts in {shown}. "+ "Nothing was changed.",+ code="conflict",+ )+ raise GitError(f"Git could not rebase: {_reason(result)}")+ return f"Rebased {info.branch} onto {info.upstream}."+++def update_branch(folder: str | Path, branch: str) -> str:+ """Fast-forward a local branch to its upstream without switching to it."""+ path = _folder(folder)+ info = inspect(path)+ if not info.is_repo:+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")+ name = normalize_branch(branch)+ if name == info.branch:+ return pull(path)+ known = next((entry for entry in info.branches if entry.name == name), None)+ if known is None:+ raise GitError(f"There is no local branch called {name}.", code="not_found")+ remote, _, target = known.upstream.partition("/")+ if not target:+ raise GitError(f"{name} has no branch on the remote to update from.", code="no_upstream")+ root = Path(info.root)+ if known.worktree:+ if not Path(known.worktree).is_dir():+ raise GitError(+ f"The worktree {known.worktree} no longer exists — prune it.", code="prunable"+ )+ # A checked-out branch moves only inside its own checkout.+ result = _run(+ ["pull", "--ff-only", "--no-rebase"],+ Path(known.worktree),+ timeout=_NETWORK_TIMEOUT_S,+ )+ else:+ result = _run(+ ["fetch", remote, f"refs/heads/{target}:refs/heads/{name}"],+ root,+ timeout=_NETWORK_TIMEOUT_S,+ )+ if result.returncode != 0:+ # Commits the upstream lacks, counted by git — not read from its wording.+ own = _run(["rev-list", "--count", f"{known.upstream}..refs/heads/{name}"], root)+ if own.returncode == 0 and own.stdout.strip() not in {"", "0"}:+ raise GitError(+ f"{name} has commits {known.upstream} lacks, so it cannot simply be moved forward.",+ code="diverged",+ )+ raise GitError(f"Git could not update {name}: {_reason(result)}")+ return f"{name} is up to date with {known.upstream}."+++def unique_commits(root: Path, branch: str, *, ignoring: str = "") -> int:+ """Commits only ``branch`` has — in no other local branch and on no remote.++ ``ignoring`` names a remote-tracking branch (``origin/feature``) that does+ not count as "elsewhere": the copy that is about to be deleted as well.+ -1 when git cannot say (treated as "there may be some").+ """+ # A pattern for --branches is relative to refs/heads, one for --remotes to refs/remotes.+ elsewhere = [f"--exclude={branch}", "--branches"]+ if ignoring:+ elsewhere.append(f"--exclude={ignoring}")+ elsewhere.append("--remotes")+ result = _run(+ ["rev-list", "--count", f"refs/heads/{branch}", "--not", *elsewhere],+ root,+ )+ text = result.stdout.strip()+ return int(text) if result.returncode == 0 and text.isdigit() else -1+++def delete_branch(+ folder: str | Path,+ branch: str,+ *,+ force: bool = False,+ merged: bool = False,+ remote: bool = False,+ with_worktree: bool = False,+ open_folders: list[str] | None = None,+) -> str:+ """Delete a local branch. Returns a summary.++ Refuses the current and the default branch. A branch whose commits exist+ nowhere else answers ``code="unmerged"`` unless ``merged`` (the caller has+ proof its pull request was merged) or ``force`` — the UI asks a second,+ explicit question first. ``remote`` also deletes the branch on the remote.++ A branch checked out in a linked worktree is refused unless+ ``with_worktree``; then that worktree goes too, but only when it holds no+ uncommitted change and no workspace is open in it (``open_folders``).+ """+ path = _folder(folder)+ info = inspect(path)+ if not info.is_repo:+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")+ name = normalize_branch(branch)+ known = next((entry for entry in info.branches if entry.name == name), None)+ if known is None:+ raise GitError(f"There is no local branch called {name}.", code="not_found")+ if name == info.branch:+ raise GitError(+ f"{name} is the branch you are on. Switch to another one first.", code="current"+ )+ if name == info.default_branch:+ raise GitError(f"{name} is the default branch and stays.", code="invalid")+ root = Path(info.root)+ tree = next((entry for entry in info.worktrees if entry.branch == name), None)+ if tree is not None:+ if not with_worktree or tree.main:+ raise GitError(+ f"{name} is checked out in {tree.path}. Remove that worktree first.",+ code="checked_out",+ )+ if worktree_in_use(tree.path, open_folders or []):+ raise GitError(+ f"A workspace is still open in {Path(tree.path).name}. Close it first.",+ code="in_use",+ )+ target_remote, _, target = known.upstream.partition("/")+ also_remote = remote and bool(target) and target_remote in info.remotes+ if not force and not merged:+ # Deleting the remote branch too: its copy is no longer a place the work survives.+ unique = unique_commits(root, name, ignoring=known.upstream if also_remote else "")+ if unique != 0:+ plural = "" if unique == 1 else "s"+ count = f"{unique} commit{plural}" if unique > 0 else "commits"+ raise GitError(+ f"{name} has {count} that exist nowhere else. Delete it anyway?", code="unmerged"+ )+ if tree is not None:+ # Never forced: uncommitted work in the worktree keeps both it and the branch.+ remove_worktree(path, tree.path)+ root = Path(info.main_root or info.root)+ _ok(["branch", "-D", name], root, what=f"delete {name}")+ summary = f"Deleted {name}."+ if also_remote:+ result = _run(["push", target_remote, "--delete", target], root, timeout=_NETWORK_TIMEOUT_S)+ if result.returncode == 0:+ summary = f"Deleted {name} here and on {target_remote}."+ elif "remote ref does not exist" not in (result.stderr or ""):+ summary += f" It could not be deleted on {target_remote}: {_reason(result)}"+ logger.info("Agentic IDE git: {}", summary)+ return summary+++def branch_tip(folder: str | Path, branch: str) -> str:+ """The commit a local branch points at, or "" when there is no such branch."""+ path = _folder(folder)+ result = _run(["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], path)+ return result.stdout.strip() if result.returncode == 0 else ""+++def first_subject(folder: str | Path, branch: str, base: str) -> str:+ """A pull request title for ``branch``: the subject of its oldest own commit."""+ path = _folder(folder)+ own = _run(+ ["log", "--reverse", "--format=%s", "-n", "50", f"{base}..refs/heads/{branch}"], path+ )+ lines = [line.strip() for line in own.stdout.splitlines() if line.strip()]+ if own.returncode == 0 and lines:+ return lines[0]+ last = _run(["log", "--format=%s", "-n", "1", f"refs/heads/{branch}"], path)+ return last.stdout.strip() if last.returncode == 0 and last.stdout.strip() else branch++def fetch(folder: str | Path) -> None:path = _folder(folder)root = repo_root(path)diff --git a/jarvis/agentic_ide/git_overview.py b/jarvis/agentic_ide/git_overview.pyindex 65c9cf2ab0..da825def46 100644--- a/jarvis/agentic_ide/git_overview.py+++ b/jarvis/agentic_ide/git_overview.py@@ -12,11 +12,13 @@ separate facts that are easy to mix up:passed or failed. Green checks never mean "merged"; the two are reportedapart on purpose.-Local git is read on every call (a handful of fast plumbing commands). GitHub+Local git comes from :mod:`jarvis.agentic_ide.git_local`: the branch list is+reused until a ref moves, so a poll of an unchanged repository costs one+``git status``. GitHubis read for the repository the person picked for this folder ONCE(:mod:`jarvis.agentic_ide.github_link`), with their existing GitHub-connection, in ONE GraphQL query per repository, cached per repository: N open-panes polling one project cost one network call per minute — shorter while a+connection, in a few GraphQL queries asked side by side, cached per repository: N open+panes polling one project cost one GitHub read per minute — shorter while acheck is still running, because that is exactly when the user is waiting.Degrades, never raises: no git, not a repository, GitHub not connected, no@@ -39,7 +41,7 @@ from typing import Anyfrom loguru import logger-from jarvis.agentic_ide import github_link+from jarvis.agentic_ide import git_local, github_linkfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS_GIT_TIMEOUT_S = 8.0@@ -64,20 +66,44 @@ GITHUB_BUSY_TTL_S = 20.0#: A forced refresh still reuses an answer this young.GITHUB_MIN_REFRESH_S = 5.0-_QUERY = """+# GitHub is asked three things side by side instead of in one query. One+# query for all of it takes about ten seconds on a repository with many checks+# per commit — the edge of GitHub's own time limit, where it answers 504. Each+# part alone is well inside it, and the slowest one sets the wait.++#: Every open pull request with the CI of its newest commit.+_OPEN_QUERY = """query($owner: String!, $name: String!) {repository(owner: $owner, name: $name) {url- pullRequests(first: 40, orderBy: {field: UPDATED_AT, direction: DESC}) {+ pullRequests(first: 50, states: OPEN, orderBy: {field: UPDATED_AT, direction: DESC}) {nodes {- number title url state isDraft isCrossRepository- headRefName headRefOid baseRefName mergedAt updatedAt- isInMergeQueue- mergeQueueEntry { position }+ ...PullRequestRowcommits(last: 1) { nodes { commit { oid statusCheckRollup { ...Rollup } } } }}}- refs(refPrefix: "refs/heads/", first: 60,+ }+}+"""++#: What recently landed or was dropped — the state alone, no CI.+_RECENT_QUERY = """+query($owner: String!, $name: String!) {+ repository(owner: $owner, name: $name) {+ pullRequests(first: 60, states: [MERGED, CLOSED],+ orderBy: {field: UPDATED_AT, direction: DESC}) {+ nodes { ...PullRequestRow }+ }+ }+}+"""++#: CI of the most recently changed branches (the ones without a pull request need it).+_REFS_CI_QUERY = """+query($owner: String!, $name: String!) {+ repository(owner: $owner, name: $name) {+ url+ refs(refPrefix: "refs/heads/", first: 30,orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) {nodes {name@@ -86,6 +112,19 @@ query($owner: String!, $name: String!) {}}}+"""++_PR_FRAGMENT = """+fragment PullRequestRow on PullRequest {+ number title url state isDraft isCrossRepository+ headRefName headRefOid baseRefName mergedAt updatedAt+ isInMergeQueue mergeable reviewDecision+ author { login }+ mergeQueueEntry { position }+}+"""++_ROLLUP_FRAGMENT = """fragment Rollup on StatusCheckRollup {statecontexts(first: 40) {@@ -156,6 +195,13 @@ class PullRequest:#: 1-based place in the merge queue while ``state == "queued"``.queue_position: int | None = Noneci: CiStatus = field(default_factory=CiStatus)+ #: GitHub cannot merge it as it is: it conflicts with its base.+ conflicting: bool = False+ #: ``approved`` | ``changes_requested`` | ``review_required`` | "" (no review rule).+ review: str = ""+ author: str = ""+ #: Opened from a fork: its branch is not one of this repository's.+ fork: bool = False@dataclass(slots=True)@@ -188,6 +234,15 @@ class BranchRow:ci: CiStatus = field(default_factory=CiStatus)#: The local branch has commits that CI has not seen yet.ci_stale: bool = False+ #: The upstream is configured but was deleted on the remote.+ upstream_gone: bool = False+ #: GitHub has commits on this branch that were not fetched yet, so+ #: ``behind`` undercounts until the next fetch.+ unfetched: bool = False+ #: Commits it has that the default branch lacks, and the other way round+ #: (against ``RepoOverview.base_ref``); None when git cannot say.+ base_ahead: int | None = None+ base_behind: int | None = None@dataclass(slots=True)@@ -206,6 +261,8 @@ class GitHubState:repo_url: str = ""#: Epoch seconds of the GitHub answer in use.fetched_at: float = 0.0+ #: A newer answer is being read right now; the tab asks again shortly.+ refreshing: bool = False@dataclass(slots=True)@@ -221,6 +278,12 @@ class RepoOverview:remote_branches: list[BranchRow] = field(default_factory=list)truncated: bool = Falsegithub: GitHubState = field(default_factory=GitHubState)+ #: The folder's own state: uncommitted changes, ahead/behind, last fetch.+ checkout: git_local.Checkout = field(default_factory=git_local.Checkout)+ #: What ``base_ahead`` / ``base_behind`` compare with (``origin/main``).+ base_ref: str = ""+ #: Every pull request that is still open, the ones needing a look first.+ pull_requests: list[PullRequest] = field(default_factory=list)def to_dict(self) -> dict[str, Any]:return asdict(self)@@ -375,9 +438,15 @@ def parse_github(payload: dict[str, Any], fetched_at: float = 0.0) -> _GitHubSnaif 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"):+ nodes = [+ *((repo.get("openPullRequests") or {}).get("nodes") or []),+ *((repo.get("pullRequests") or {}).get("nodes") or []),+ ]+ seen: set[int] = set()+ for node in nodes:+ if not isinstance(node, dict) or int(node.get("number") or 0) in seen:continue+ seen.add(int(node.get("number") or 0))commits = (node.get("commits") or {}).get("nodes") or []commit = (commits[0] or {}).get("commit") if commits else Nonecommit = commit if isinstance(commit, dict) else {}@@ -395,6 +464,10 @@ def parse_github(payload: dict[str, Any], fetched_at: float = 0.0) -> _GitHubSnaupdated_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 "")),+ conflicting=str(node.get("mergeable") or "").upper() == "CONFLICTING",+ review=str(node.get("reviewDecision") or "").lower(),+ author=str((node.get("author") or {}).get("login") or ""),+ fork=bool(node.get("isCrossRepository")),))for node in (repo.get("refs") or {}).get("nodes") or []:@@ -423,21 +496,62 @@ def _iso_to_unix(value: str) -> int:return 0+def _repository(payload: dict[str, Any]) -> dict[str, Any]:+ repo = ((payload or {}).get("data") or {}).get("repository")+ return repo if isinstance(repo, dict) else {}++def _fetch_github(repo: str, token: str) -> _GitHubSnapshot:now = time.time()owner, _, name = repo.partition("/")- try:- payload = github_link.graphql(token, _QUERY, {"owner": owner, "name": name})- except github_link.GitHubError as exc: # shown in the tab as github.reason/code- return _GitHubSnapshot(ok=False, reason=str(exc), code=exc.code, fetched_at=now)- snap = parse_github(payload, fetched_at=now)- if snap.ok:- _add_all_refs(snap, token, owner, name)+ variables = {"owner": owner, "name": name}++ def ask(query: str) -> dict[str, Any] | github_link.GitHubError:+ try:+ return github_link.graphql(token, query, variables)+ except github_link.GitHubError as exc: # handed back to the caller below+ return exc++ open_job = git_local.Job(ask, _OPEN_QUERY + _PR_FRAGMENT + _ROLLUP_FRAGMENT)+ recent_job = git_local.Job(ask, _RECENT_QUERY + _PR_FRAGMENT)+ refs_job = git_local.Job(ask, _REFS_CI_QUERY + _ROLLUP_FRAGMENT)+ names_job = git_local.Job(_all_refs, token, owner, name)+ opened, recent, refs = open_job.result(), recent_job.result(), refs_job.result()+ names = names_job.result()+ for answer in (opened, refs):+ if isinstance(answer, github_link.GitHubError): # shown in the tab as github.reason/code+ return _GitHubSnapshot(ok=False, reason=str(answer), code=answer.code, fetched_at=now)+ if isinstance(recent, github_link.GitHubError):+ # Open pull requests and CI landed; only "merged" marks are missing this round.+ logger.debug("Git overview: recent pull requests failed: {}", recent.code)+ recent = {}+ open_repo, refs_repo = _repository(opened), _repository(refs)+ if not open_repo and not refs_repo:+ return _GitHubSnapshot(+ ok=False, reason="GitHub did not return this repository.", fetched_at=now+ )+ merged = {+ "data": {+ "repository": {+ "url": open_repo.get("url") or refs_repo.get("url") or "",+ "openPullRequests": open_repo.get("pullRequests") or {},+ "pullRequests": _repository(recent).get("pullRequests") or {},+ "refs": refs_repo.get("refs") or {},+ }+ }+ }+ snap = parse_github(merged, fetched_at=now)+ for ref_name, oid, stamp in names:+ if ref_name not in snap.refs:+ snap.refs[ref_name] = (oid, CiStatus())+ if stamp:+ snap.ref_dates.setdefault(ref_name, stamp)return snap-def _add_all_refs(snap: _GitHubSnapshot, token: str, owner: str, name: str) -> None:- """Add every other GitHub branch (without CI) to ``snap``, page by page."""+def _all_refs(token: str, owner: str, name: str) -> list[tuple[str, str, int]]:+ """Every GitHub branch as (name, tip, commit time), without CI, page by page."""+ found: list[tuple[str, str, int]] = []after: str | None = Nonefor _ in range(MAX_REF_PAGES):try:@@ -445,25 +559,26 @@ def _add_all_refs(snap: _GitHubSnapshot, token: str, owner: str, name: str) -> Ntoken, _REFS_QUERY, {"owner": owner, "name": name, "after": after})except github_link.GitHubError as exc:- # The CI-bearing first page already landed; older branches just stay hidden.+ # The CI-bearing branches still land; older ones just stay hidden.logger.debug("Git overview: branch list page failed: {}", exc.code)- return- repo = ((payload or {}).get("data") or {}).get("repository") or {}- refs = repo.get("refs") or {}+ break+ refs = _repository(payload).get("refs") or {}for node in refs.get("nodes") or []:if not isinstance(node, dict) or not node.get("name"):continue- ref_name = str(node["name"])target = node.get("target") or {}- if ref_name not in snap.refs:- snap.refs[ref_name] = (str(target.get("oid") or "")[:12], CiStatus())- stamp = _iso_to_unix(str(target.get("committedDate") or ""))- if stamp:- snap.ref_dates.setdefault(ref_name, stamp)+ found.append(+ (+ str(node["name"]),+ str(target.get("oid") or "")[:12],+ _iso_to_unix(str(target.get("committedDate") or "")),+ )+ )page = refs.get("pageInfo") or {}after = page.get("endCursor")if not page.get("hasNextPage") or not after:- return+ break+ return foundclass _GitHubCache:@@ -473,63 +588,104 @@ class _GitHubCache: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:+ #: Repositories whose answer is known to be outdated (a push, a new pull request).+ self._expired: set[str] = set()+ #: Repositories with a background read on its way.+ self._inflight: set[str] = set()+ #: When a read last failed while an older good answer was kept.+ self._failed: dict[str, float] = {}++ def _fresh(self, key: str, snap: _GitHubSnapshot | None, now: float, force: bool) -> bool:+ if snap is None or key in self._expired:return False- age = now - snap.fetched_at+ age = now - max(snap.fetched_at, self._failed.get(key, 0.0))if force:return age < GITHUB_MIN_REFRESH_Sreturn age < (GITHUB_BUSY_TTL_S if snap.busy else GITHUB_TTL_S)def _load(self, key: str, token: str, 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(key, token)- self._entries[key] = snap- return snap+ try:+ with lock:+ snap = self._entries.get(key)+ if self._fresh(key, snap, time.time(), force):+ assert snap is not None+ return snap+ with self._guard:+ # Whatever expires it from here on is newer than this read.+ self._expired.discard(key)+ fetched = _fetch_github(key, token)+ with self._guard:+ if fetched.ok or snap is None or not snap.ok:+ self._entries[key] = fetched+ self._failed.pop(key, None)+ else:+ # GitHub was unreachable for a moment: what was read+ # before stays on screen, and the next try waits a turn.+ self._failed[key] = time.time()+ fetched = snap+ return fetched+ finally:+ with self._guard:+ self._inflight.discard(key)++ def _in_background(self, key: str, token: str, lock: threading.Lock, force: bool) -> None:+ with self._guard:+ if key in self._inflight:+ return+ self._inflight.add(key)+ threading.Thread(+ target=self._load,+ args=(key, token, lock, force),+ name="git-overview-github",+ daemon=True,+ ).start()def get(self, key: str, token: str, *, force: bool = False, wait: bool = True) -> _GitHubSnapshot | None:"""``key`` is the repository (``owner/name``).- With ``wait=False`` a repository read for the first time answers None at- once and loads in the background: the first GitHub read takes seconds,- and the local branches should not wait for it.+ With ``wait=False`` nothing waits for GitHub, which takes seconds: a+ repository read for the first time answers None and loads in the+ background, and a forced refresh answers with what is known while the+ new answer is on its way (:meth:`loading` says so)."""with self._guard:lock = self._locks.setdefault(key, threading.Lock())snap = self._entries.get(key)- if force or (snap is None and wait):+ if wait and (force or snap is None):return self._load(key, token, lock, force)if snap is None:- if not lock.locked():- threading.Thread(- target=self._load,- args=(key, token, lock, False),- name="git-overview-github",- daemon=True,- ).start()+ self._in_background(key, token, lock, False)return None- if not self._fresh(snap, time.time(), False) and not lock.locked():+ if not self._fresh(key, snap, time.time(), force):# 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, token, lock, False),- name="git-overview-github",- daemon=True,- ).start()+ self._in_background(key, token, lock, force)return snap+ def loading(self, key: str) -> bool:+ """A background read of ``key`` is on its way."""+ with self._guard:+ return key in self._inflight++ def peek(self, key: str) -> _GitHubSnapshot | None:+ """The answer already in memory, however old; never a network call."""+ with self._guard:+ return self._entries.get(key)++ def expire(self, key: str) -> None:+ """Keep showing the answer, but read a new one at the next chance."""+ with self._guard:+ if key in self._entries:+ self._expired.add(key)+def clear(self) -> None:with self._guard:self._entries.clear()+ self._expired.clear()+ self._failed.clear()_CACHE = _GitHubCache()@@ -537,54 +693,19 @@ _CACHE = _GitHubCache()def clear_cache() -> None:_CACHE.clear()+ git_local.forget()-# ------------------------------------------------------------------ local git+def clear_github(folder: str | Path) -> None:+ """Mark GitHub's answer for ``folder``'s repository as outdated — after a+ push or a new pull request it is. The tab keeps showing it and gets the new+ one as soon as it is read."""+ repo = github_link.bound_repository(folder)+ if repo:+ _CACHE.expire(repo)-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+# ------------------------------------------------------------------ local gitdef _resolve_target(root: Path, target: str, local: set[str]) -> str | None:@@ -598,8 +719,9 @@ def _resolve_target(root: Path, target: str, local: set[str]) -> str | 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.+ For pull request bases other than the default branch (that one comes with+ the branch list). A branch whose tip IS the target's tip holds no work of+ its own and is not reported as merged."""merged: dict[str, list[str]] = {}for target in targets:@@ -607,22 +729,31 @@ def _merged_by_git(root: Path, targets: list[str], local: set[str]) -> dict[str,if ref is None:continuetip = (_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:+ for name, oid in git_local.merged_into(root, ref).items():+ if name != target and oid != tip:merged.setdefault(name, []).append(target)return merged+def _row(branch: git_local.LocalBranch, current: str) -> BranchRow:+ row = BranchRow(+ name=branch.name,+ current=branch.name == current,+ upstream=branch.upstream,+ ahead=branch.ahead,+ behind=branch.behind,+ head=branch.head[:12],+ committed_at=branch.committed_at,+ upstream_gone=branch.upstream_gone,+ base_ahead=branch.base_ahead,+ base_behind=branch.base_behind,+ merged_into=[MergedInto(target=target, via="git") for target in branch.merged_into],+ )+ if branch.worktree and not row.current:+ row.worktree = branch.worktree+ return row++# ------------------------------------------------------------------ assembly@@ -634,7 +765,7 @@ def _remote_name(row: BranchRow) -> str:def _attach_github(row: BranchRow, remote: str, snap: _GitHubSnapshot) -> None:- prs = [pr for pr in snap.prs if pr.head == remote]+ prs = [pr for pr in snap.prs if pr.head == remote and not pr.fork]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)@@ -687,6 +818,7 @@ def _github_for(state.code = snap.codestate.repo_url = snap.repo_url or f"https://github.com/{state.repo}"state.fetched_at = snap.fetched_at+ state.refreshing = _CACHE.loading(state.repo)return snap if snap.ok else None@@ -728,20 +860,24 @@ def overview(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():+ state = git_local.read(path, fresh=refresh)+ if state is None: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()+ root = state.root+ head = state.checkout.branch+ info = RepoOverview(+ available=True,+ root=str(root),+ branch=head,+ detached=state.checkout.detached,+ head=state.checkout.head,+ default_branch=state.default_branch,+ checkout=state.checkout,+ base_ref=state.base_ref,+ )- rows = _local_branches(root, head)+ rows = [_row(branch, head) for branch in state.branches]local = {row.name for row in rows}- info.default_branch = _default_branch(root, local, head)snap: _GitHubSnapshot | None = Noneif github:@@ -754,18 +890,22 @@ def overview(info.truncated = len(rows) > MAX_BRANCHESrows = pinned + rest[: max(0, MAX_BRANCHES - len(pinned))]- targets = [info.default_branch] if info.default_branch else []+ # Pull request bases other than the default branch (which the branch list covers).+ targets: list[str] = []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)+ if pr.base and pr.base != info.default_branch and pr.base in local:+ if pr.base not in targets:+ targets.append(pr.base)+ extra = _merged_by_git(root, targets[: MAX_MERGE_TARGETS - 1], local) if targets else {}for row in rows:- row.merged_into = [MergedInto(target=t, via="git") for t in merged.get(row.name, [])]+ for target in extra.get(row.name, []):+ row.merged_into.append(MergedInto(target=target, via="git"))if snap is not None and snap.ok:_attach_github(row, _remote_name(row), snap)info.branches = rowsif snap is not None and snap.ok:+ _mark_unfetched(root, rows, state.remote_heads, snap)known = {_remote_name(row) for row in rows} | localfor name, (oid, _ci) in snap.refs.items():if name in known:@@ -779,4 +919,67 @@ def overview(break# Newest first, like the local list; the later pages arrive in name order.info.remote_branches.sort(key=lambda row: row.committed_at, reverse=True)+ info.pull_requests = _open_pull_requests(snap)return info+++#: Open pull requests listed in the tab (the ones needing a look come first).+MAX_OPEN_PRS = 60+++def _pr_urgency(pr: PullRequest) -> int:+ """Lower sorts first: what is broken, then what moves, then what waits."""+ if pr.ci.state == "failure" or pr.conflicting:+ return 0+ if pr.review == "changes_requested":+ return 1+ if pr.state == "queued":+ return 2+ if pr.ci.state in {"running", "pending"}:+ return 3+ return 5 if pr.state == "draft" else 4+++def _open_pull_requests(snap: _GitHubSnapshot) -> list[PullRequest]:+ live = [pr for pr in snap.prs if pr.state in {"queued", "open", "draft"}]+ live.sort(key=lambda pr: pr.updated_at, reverse=True)+ live.sort(key=_pr_urgency)+ return live[:MAX_OPEN_PRS]+++def _mark_unfetched(+ root: Path, rows: list[BranchRow], remote_heads: dict[str, str], snap: _GitHubSnapshot+) -> None:+ """Flag branches whose GitHub tip this computer has not fetched yet.++ A tip that differs from the remote-tracking ref is not enough: right after+ a push GitHub's cached answer is the older one. Only a commit that is not+ in the local object store proves there is something to fetch.+ """+ candidates: dict[str, list[BranchRow]] = {}+ for row in rows:+ if not row.upstream.startswith("origin/"):+ continue+ ref = snap.refs.get(_remote_name(row))+ tracked = remote_heads.get(row.upstream, "")+ if ref is None or not ref[0] or not tracked or tracked.startswith(ref[0]):+ continue+ candidates.setdefault(ref[0], []).append(row)+ for oid in git_local.missing_commits(root, list(candidates)):+ for row in candidates[oid]:+ row.unfetched = True+++def merged_pull_request(folder: str | Path, branch: str, head: str) -> int | None:+ """The merged pull request that carried exactly ``head`` of ``branch``, if GitHub+ already told us about one (no network call): proof that deleting the branch+ loses nothing even though git ancestry cannot see a squash merge."""+ repo = github_link.bound_repository(folder)+ snap = _CACHE.peek(repo) if repo else None+ if snap is None or not snap.ok or not head:+ return None+ for pr in snap.prs:+ if pr.state == "merged" and pr.head == branch and not pr.fork and pr.head_oid:+ if head.startswith(pr.head_oid[:7]):+ return pr.number+ return Nonediff --git a/jarvis/agentic_ide/github_pulls.py b/jarvis/agentic_ide/github_pulls.pynew file mode 100644index 0000000000..07565ba11c--- /dev/null+++ b/jarvis/agentic_ide/github_pulls.py@@ -0,0 +1,78 @@+"""Open a pull request with the person's existing GitHub connection.++The Git tab opens a pull request for a pushed branch without the GitHub CLI:+the same credential that reads pull requests and CI+(:mod:`jarvis.agentic_ide.github_link`) creates one through GitHub's GraphQL+API. Failures come back as one sentence — GitHub's own where it has one+("A pull request already exists for …").+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from jarvis.agentic_ide import github_link+from jarvis.agentic_ide.github_link import GitHubError++_REPOSITORY_ID = """+query($owner: String!, $name: String!) {+ repository(owner: $owner, name: $name) { id }+}+"""++_CREATE = """+mutation($input: CreatePullRequestInput!) {+ createPullRequest(input: $input) { pullRequest { number url } }+}+"""+++@dataclass(slots=True)+class CreatedPullRequest:+ number: int+ url: str+++def _first_error(payload: dict[str, Any]) -> str:+ errors = payload.get("errors")+ if isinstance(errors, list):+ for error in errors:+ if isinstance(error, dict) and error.get("message"):+ return str(error["message"])+ return ""+++def create(+ repo: str, token: str, *, head: str, base: str, title: str, draft: bool = False+) -> CreatedPullRequest:+ """Open a pull request from ``head`` into ``base`` of ``repo`` (``owner/name``)."""+ owner, _, name = repo.partition("/")+ if not owner or not name:+ raise GitHubError("Pick this folder's GitHub repository first.", code="needs_repo")+ found = github_link.graphql(token, _REPOSITORY_ID, {"owner": owner, "name": name})+ repository = ((found.get("data") or {}).get("repository") or {}).get("id")+ if not repository:+ raise GitHubError(+ "GitHub does not know this repository, or this account cannot see it.",+ code="repo_missing",+ )+ payload = github_link.graphql(+ token,+ _CREATE,+ {+ "input": {+ "repositoryId": repository,+ "baseRefName": base,+ "headRefName": head,+ "title": title,+ "draft": draft,+ }+ },+ )+ created = ((payload.get("data") or {}).get("createPullRequest") or {}).get("pullRequest")+ if not isinstance(created, dict) or not created.get("url"):+ raise GitHubError(+ _first_error(payload) or "GitHub could not open the pull request.", code="refused"+ )+ return CreatedPullRequest(number=int(created.get("number") or 0), url=str(created["url"]))diff --git a/jarvis/agentic_ide/thread_folders.py b/jarvis/agentic_ide/thread_folders.pyindex ea0b8dfe6f..651d134f2c 100644--- a/jarvis/agentic_ide/thread_folders.py+++ b/jarvis/agentic_ide/thread_folders.py@@ -38,7 +38,7 @@ def _known_roots() -> list[Path]:try:from jarvis.agentic_ide.session import get_registry- roots += [str(session.folder) for session in get_registry().sessions() if session.folder]+ roots += [str(session.folder) for session in get_registry().sessions if session.folder]except Exception as exc: # noqa: BLE001 - no registry (a bare test app) leaves the projectslogger.debug("Agentic IDE: workspace list unreadable for a folder check: {}", exc)return [path for path in (_resolved(root) for root in roots) if path is not None]diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.pyindex 2c628dfffa..6d93ddd6db 100644--- a/jarvis/ui/web/agentic_ide_git_routes.py+++ b/jarvis/ui/web/agentic_ide_git_routes.py@@ -17,13 +17,21 @@ Endpoints (all under ``/api/agentic-ide/git``)::POST /push Push the current branch (sets upstream once)POST /fetch Fetch every remotePOST /pull-request Open a PR with the GitHub CLI+ POST /pull Fast-forward a workspace's branch (or rebase it, when asked)+ POST /switch Check out another branch in a workspace's folder+ POST /branch/push Push a workspace's current branch, or a named one+ POST /branch/update Fast-forward a branch to its upstream without switching to it+ POST /branch/delete Delete a branch (asks again when its commits exist nowhere else)+ POST /branch/pull-request Open a PR with the GitHub connection (or the GitHub CLI)POST /merge Merge a branch back into its targetPOST /worktrees/remove Remove a linked worktree (asks again when dirty)POST /worktrees/prune Forget worktrees deleted by hand-Every route takes the folder it works on — a workspace folder, a project path-or a worktree — and runs git in the anyio threadpool (plain ``def`` handlers),-never on the event loop. Loopback-only like the rest of the IDE API.+The older routes take the folder they work on — a workspace folder, a project+path or a worktree. The Git tab's own actions (pull, switch, ``/branch/*``) take+the id of an open workspace instead, so they can only ever act on a repository+the person has open. All of them run git in the anyio threadpool (plain ``def``+handlers), never on the event loop. Loopback-only like the rest of the IDE API.A failed git call answers 422 with ``{"detail": {"message", "code"}}`` so theUI can offer the follow-up it has for that code (``dirty`` → "remove anyway?").@@ -43,6 +51,7 @@ from jarvis.agentic_ide import (git_ops,git_overview,github_link,+ github_pulls,github_status,)from jarvis.agentic_ide.git_ops import GitError, PrepareMode@@ -54,6 +63,16 @@ from jarvis.ui.web.surface_security import is_loopback_requestrouter = APIRouter(prefix="/api/agentic-ide/git", tags=["agentic-ide-git"])+def _open_folders() -> list[str]:+ """Every folder something is running in: each workspace, and each pane's own+ checkout (an agent's worktree) — none of them may be removed under it."""+ folders: list[str] = []+ for session in get_registry().sessions:+ folders.append(session.folder)+ folders.extend(pane.cwd(session.folder) for pane in session.terminals)+ return folders++def _fail(exc: GitError) -> HTTPException:return HTTPException(status_code=422, detail={"message": str(exc), "code": exc.code})@@ -77,6 +96,34 @@ class PullRequestRequest(FolderRequest):draft: bool = False+class WorkspaceRequest(BaseModel):+ workspace_id: str = Field(..., min_length=1, description="The open workspace to act in")+++class PullBranchRequest(WorkspaceRequest):+ rebase: bool = Field(False, description="Rebase local commits onto the remote ones")+++class BranchRequest(WorkspaceRequest):+ branch: str = Field(..., min_length=1, max_length=300)+++class PushBranchRequest(WorkspaceRequest):+ branch: str = Field("", max_length=300, description="Branch to push; current if empty")+++class DeleteBranchRequest(BranchRequest):+ force: bool = Field(False, description="Delete even when its commits exist nowhere else")+ remote: bool = Field(False, description="Also delete the branch on the remote")+ with_worktree: bool = Field(False, description="Also remove its clean, unused worktree")+++class BranchPullRequestRequest(WorkspaceRequest):+ branch: str = Field("", max_length=300, description="Branch to open it from; current if empty")+ title: str = Field("", max_length=300)+ draft: bool = False++class MergeRequest(FolderRequest):into: str = Field("", max_length=200, description="Target branch; default branch if empty")@@ -362,6 +409,133 @@ def open_pull_request(req: PullRequestRequest) -> dict:return {"ok": True, "url": url}+# The Git tab's actions. Each names an open workspace, never a path: the folder+# comes from the workspace, so none of them can be pointed elsewhere on the machine.++[email protected]("/pull", summary="Bring a workspace's branch up to date with its remote")+def pull_branch(req: PullBranchRequest) -> dict:+ """Fast-forward only unless ``rebase``; a conflicting rebase is aborted."""+ folder = _workspace_folder(req.workspace_id)+ try:+ message = git_ops.pull(folder, rebase=req.rebase)+ except GitError as exc:+ raise _fail(exc) from exc+ return {"ok": True, "message": message}++[email protected]("/switch", summary="Check out another branch in a workspace's folder")+def switch_branch(req: BranchRequest) -> dict:+ folder = _workspace_folder(req.workspace_id)+ try:+ prepared = git_ops.prepare(folder, "switch_branch", branch=req.branch)+ except GitError as exc:+ raise _fail(exc) from exc+ return {"ok": True, "branch": prepared.branch, "message": prepared.message}++[email protected]("/branch/push", summary="Push a workspace's current branch, or a named one")+def push_workspace_branch(req: PushBranchRequest) -> dict:+ folder = _workspace_folder(req.workspace_id)+ try:+ upstream = git_ops.push(folder, req.branch)+ except GitError as exc:+ raise _fail(exc) from exc+ git_overview.clear_github(folder)+ return {"ok": True, "upstream": upstream}++[email protected]("/branch/update", summary="Fast-forward a branch to its upstream")+def update_branch(req: BranchRequest) -> dict:+ folder = _workspace_folder(req.workspace_id)+ try:+ message = git_ops.update_branch(folder, req.branch)+ except GitError as exc:+ raise _fail(exc) from exc+ return {"ok": True, "message": message}+++ "/branch/delete",+ summary="Delete a local branch",+ openapi_extra={"x-jarvis-dangerous": True},+)+def delete_branch(req: DeleteBranchRequest) -> dict:+ """Delete a branch whose work is safe elsewhere; ask again otherwise.++ "Safe" is decided here, not by the caller: every commit is in another+ branch or on a remote that stays, or GitHub merged the pull request that+ carried exactly this tip. Anything else answers ``unmerged`` until ``force``.+ """+ folder = _workspace_folder(req.workspace_id)+ try:+ name = git_ops.normalize_branch(req.branch)+ tip = git_ops.branch_tip(folder, name)+ merged = git_overview.merged_pull_request(folder, name, tip) is not None+ message = git_ops.delete_branch(+ folder,+ name,+ force=req.force,+ merged=merged,+ remote=req.remote,+ with_worktree=req.with_worktree,+ open_folders=_open_folders(),+ )+ except GitError as exc:+ raise _fail(exc) from exc+ if req.remote:+ git_overview.clear_github(folder)+ return {"ok": True, "message": message}+++def _create_pull_request(folder: Path, req: BranchPullRequestRequest) -> str:+ """Push the branch if needed and open its pull request. Returns the URL.++ Uses the GitHub connection the Git tab already reads with; without one (or+ before a repository was picked for the folder) the GitHub CLI opens it.+ """+ cred = github_link.credential()+ repo = github_link.bound_repository(folder)+ wanted = git_ops.normalize_branch(req.branch)+ info = git_ops.inspect(folder)+ if cred is None or not repo:+ if wanted and wanted != info.branch:+ raise GitError("Connect GitHub to open this pull request.", code="not_connected")+ return git_ops.create_pull_request(folder, title=req.title, draft=req.draft)+ branch = wanted or info.branch+ if not info.is_repo or not branch:+ raise GitError("Check out a branch before opening a pull request.", code="detached")+ if branch == info.default_branch:+ raise GitError(+ f"{branch} is the default branch — open the pull request from a feature branch.",+ code="invalid",+ )+ upstream = git_ops.push(folder, branch)+ head = upstream.partition("/")[2] or branch+ base_ref = f"origin/{info.default_branch}"+ if base_ref not in info.remote_branches:+ base_ref = info.default_branch+ title = req.title.strip() or git_ops.first_subject(folder, branch, base_ref)+ try:+ created = github_pulls.create(+ repo, cred.token, head=head, base=info.default_branch, title=title, draft=req.draft+ )+ except github_link.GitHubError as exc:+ raise GitError(str(exc), code=exc.code) from exc+ return created.url++[email protected]("/branch/pull-request", summary="Open a pull request for a workspace's branch")+def open_branch_pull_request(req: BranchPullRequestRequest) -> dict:+ folder = _workspace_folder(req.workspace_id)+ try:+ url = _create_pull_request(folder, req)+ except GitError as exc:+ raise _fail(exc) from exc+ git_overview.clear_github(folder)+ return {"ok": True, "url": url}++@router.post("/merge", summary="Merge the current branch back into its target")def merge_branch(req: MergeRequest) -> dict:try:@@ -377,8 +551,7 @@ def merge_branch(req: MergeRequest) -> dict:openapi_extra={"x-jarvis-dangerous": True},)def remove_worktree(req: RemoveWorktreeRequest) -> dict:- open_folders = [session.folder for session in get_registry().sessions]- if git_ops.worktree_in_use(req.worktree, open_folders):+ if git_ops.worktree_in_use(req.worktree, _open_folders()):raise HTTPException(status_code=422,detail={diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/AttentionList.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/AttentionList.tsxnew file mode 100644index 0000000000..4c1c5d48f7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/AttentionList.tsx@@ -0,0 +1,77 @@+import { Check, CircleX, GitMerge, TriangleAlert, type LucideIcon } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import type { AttentionItem, AttentionKind } from "./gitInsights";+import { plural } from "./gitBadges";++const TONE: Record<AttentionItem["tone"], { icon: LucideIcon; className: string }> = {+ danger: { icon: CircleX, className: "text-destructive" },+ warning: { icon: TriangleAlert, className: "text-warning" },+ neutral: { icon: GitMerge, className: "text-[hsl(var(--gh-merged))]" },+};++/** What the row's click does, named on its right edge. */+const ACTION: Record<AttentionKind, string> = {+ ci_failing: "show",+ default_ci: "view",+ pr_conflicts: "show",+ changes_requested: "show",+ default_behind: "update",+ unpushed: "show",+ behind: "show",+ cleanup: "clean_up",+};++/**+ * What needs a look across the whole repository, worst first: failing checks,+ * conflicts, work that is only on this computer, branches that fell behind,+ * merged branches that can go. One line each; a click goes to the fix.+ */+export function AttentionList({ items, onAct }: { items: AttentionItem[]; onAct: (item: AttentionItem) => void }) {+ const t = useT();+ if (items.length === 0) {+ return (+ <p data-testid="git-all-clear" className="flex items-center gap-1.5 border-b border-border/60 px-3 py-2.5 text-[11.5px] text-muted-foreground">+ <Check className="h-3.5 w-3.5 shrink-0 text-success" aria-hidden />+ {t("ide_side_panel.git.attention.none")}+ </p>+ );+ }+ return (+ <section data-testid="git-attention" aria-label={t("ide_side_panel.git.attention.title")} className="border-b border-border/60 py-1">+ <h3 className="flex h-7 items-center gap-1.5 px-3 text-[10.5px] font-semibold uppercase tracking-wider text-muted-foreground">+ {t("ide_side_panel.git.attention.title")}+ <span className="tabular-nums text-muted-foreground/70">{items.length}</span>+ </h3>+ <ul>+ {items.map((item) => {+ const tone = TONE[item.tone];+ const Icon = tone.icon;+ return (+ <li key={item.kind}>+ <button+ type="button"+ data-testid="git-attention-item"+ data-kind={item.kind}+ onClick={() => onAct(item)}+ className="group/item flex w-full items-start gap-2 px-3 py-1.5 text-left hover:bg-secondary/60 focus-visible:bg-secondary/60 focus-visible:outline-none"+ >+ <Icon className={cn("mt-px h-3.5 w-3.5 shrink-0", tone.className)} aria-hidden />+ <span className="min-w-0 flex-1">+ <span className="block text-[12px] leading-snug text-foreground">{plural(t, `ide_side_panel.git.attention.${item.kind}`, item.count)}</span>+ <span className="block truncate font-mono text-[10.5px] text-muted-foreground">+ {item.names.join(", ")}+ {item.count > item.names.length ? ` +${item.count - item.names.length}` : ""}+ </span>+ </span>+ <span className="shrink-0 pt-px text-[11px] text-accent group-hover/item:underline">+ {t(`ide_side_panel.git.attention.action.${ACTION[item.kind]}`)}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchDetails.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchDetails.tsxnew file mode 100644index 0000000000..2c3886d2c8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchDetails.tsx@@ -0,0 +1,402 @@+import { useEffect, useState, type ReactNode, type SVGProps } from "react";+import {+ ArrowDownToLine,+ ArrowUpFromLine,+ ChevronRight,+ CirclePlay,+ FolderOpen,+ GitBranch,+ GitPullRequestCreate,+ Globe,+ Laptop,+ Loader2,+ SquareTerminal,+ Trash2,+ type LucideIcon,+} from "lucide-react";+import { fill, useT } from "@/i18n";+import { useRunLocale } from "@/components/runs/format";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";+import { QuickTooltip } from "@/components/ui/tooltip";+import { useEventStore } from "@/store/events";+import { branchUrl } from "./BranchMenu";+import { DiffView } from "../explorer/DiffView";+import { commitDateLabel, PR_ICON } from "./gitBadges";+import { isMerged, livePr, needsPull, needsPush, syncOf } from "./gitInsights";+import {+ fetchBranchContents,+ fetchBranchFileDiff,+ openBranchCheckout,+ type BranchContents,+ type BranchEditors,+ type BranchFile,+ type BranchFileDiff,+ type BranchRow,+} from "./gitOverviewApi";+import type { GitActions } from "./useGitActions";++function DetailButton({+ icon: Icon,+ label,+ testId,+ primary,+ danger,+ busy,+ disabled,+ onClick,+}: {+ icon: LucideIcon | ((props: SVGProps<SVGSVGElement>) => ReactNode);+ label: string;+ testId: string;+ primary?: boolean;+ danger?: boolean;+ busy?: boolean;+ disabled?: boolean;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ data-testid={testId}+ disabled={disabled}+ onClick={onClick}+ className={cn(+ "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border px-2 text-[11.5px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ primary+ ? "border-transparent bg-primary text-primary-foreground hover:bg-primary/90"+ : danger+ ? "border-border/70 text-destructive hover:bg-destructive/10"+ : "border-border/70 text-foreground/90 hover:bg-secondary",+ )}+ >+ {busy ? (+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin motion-reduce:animate-none" aria-hidden />+ ) : (+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />+ )}+ <span className="truncate">{label}</span>+ </button>+ );+}++/** A file's change as one coloured letter, like the Explorer's change list. */+const FILE_STATUS: Record<BranchFile["status"], { letter: string; tone: string }> = {+ added: { letter: "A", tone: "text-success" },+ deleted: { letter: "D", tone: "text-destructive" },+ modified: { letter: "M", tone: "text-warning" },+};++function BranchFileRow({+ file,+ workspaceId,+ branch,+ base,+ remote,+}: {+ file: BranchFile;+ workspaceId: string;+ branch: string;+ base: string;+ remote: boolean;+}) {+ const t = useT();+ const [open, setOpen] = useState(false);+ const [diff, setDiff] = useState<BranchFileDiff | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ if (!open || diff) return;+ let alive = true;+ fetchBranchFileDiff(workspaceId, branch, base, remote, file.path)+ .then((answer) => alive && setDiff(answer))+ .catch((err: Error) => alive && setError(err.message));+ return () => {+ alive = false;+ };+ }, [open, diff, workspaceId, branch, base, remote, file.path]);+ const status = FILE_STATUS[file.status];+ const slash = file.path.lastIndexOf("/");+ return (+ <li data-testid="git-branch-file" data-path={file.path}>+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ className="flex w-full min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ChevronRight className={cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")} aria-hidden />+ <span className={cn("w-3 shrink-0 text-center font-mono text-[10.5px] font-semibold", status.tone)}>{status.letter}</span>+ <span className="min-w-0 flex-1 truncate font-mono text-[11px]">+ <span className="text-foreground">{file.path.slice(slash + 1)}</span>+ {slash > 0 && <span className="ml-1.5 text-muted-foreground">{file.path.slice(0, slash)}</span>}+ </span>+ {file.added === null ? (+ <span className="shrink-0 text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.binary")}</span>+ ) : (+ <span className="shrink-0 font-mono text-[10.5px] tabular-nums">+ <span className="text-success">+{file.added}</span> <span className="text-destructive">−{file.removed}</span>+ </span>+ )}+ </button>+ {open && (+ <div data-testid="git-branch-file-diff" className="my-1 max-h-96 overflow-auto rounded-md border border-border/60 bg-background">+ {error ? (+ <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>+ ) : !diff ? (+ <p className="flex items-center gap-1.5 px-3 py-2 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />+ {t("ide_side_panel.git.details.loading")}+ </p>+ ) : diff.binary ? (+ <p className="px-3 py-2 text-[11px] text-muted-foreground">{t("ide_side_panel.git.details.binary")}</p>+ ) : (+ <DiffView hunks={diff.hunks} />+ )}+ </div>+ )}+ </li>+ );+}++function DetailHeading({ children }: { children: ReactNode }) {+ return <h4 className="text-[10.5px] font-semibold uppercase tracking-wide text-muted-foreground">{children}</h4>;+}++/**+ * What a clicked branch row folds open: what can be done with the branch+ * (switch to it, push it, bring it up to date, open its pull request, delete+ * it), where it lives, and the branch itself — its own commits and the files+ * it changes, each file's diff one click away.+ */+export function BranchDetails({+ row,+ repoUrl,+ defaultBranch,+ baseRef,+ githubReady,+ workspaceId,+ editors,+ actions,+}: {+ row: BranchRow;+ repoUrl: string;+ defaultBranch: string;+ baseRef: string;+ githubReady: boolean;+ workspaceId: string;+ editors: BranchEditors | null;+ actions: GitActions;+}) {+ const t = useT();+ const lang = useRunLocale();+ const pushToast = useEventStore((state) => state.pushToast);+ const [contents, setContents] = useState<BranchContents | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ let alive = true;+ fetchBranchContents(workspaceId, row.name, defaultBranch, row.remote_only)+ .then((answer) => alive && setContents(answer))+ .catch((err: Error) => alive && setError(err.message));+ return () => {+ alive = false;+ };+ // Re-read when the branch tip moves, not on every overview poll.+ }, [workspaceId, row.name, row.head, row.remote_only, defaultBranch]);++ const url = branchUrl(repoUrl, row);+ const checkedOut = !row.remote_only && (row.current || Boolean(row.worktree));+ const pr = row.pull_requests[0];+ const canOpen = checkedOut && Boolean(editors?.file_manager);+ const isDefault = row.name === defaultBranch;+ const sync = syncOf(row);+ const idle = actions.busy === "";++ const openLocal = (target: string) => {+ void openBranchCheckout(workspaceId, row.name, target)+ .then((result) => {+ if (!result.opened) pushToast("error", t("ide_side_panel.git.details.open_failed"));+ })+ .catch((err: Error) => pushToast("error", err.message || t("ide_side_panel.git.details.open_failed")));+ };++ const where = row.remote_only+ ? t("ide_side_panel.git.details.local_absent")+ : row.current+ ? t("ide_side_panel.git.current")+ : row.worktree+ ? `${t("ide_side_panel.git.details.local_worktree")} ${row.worktree}`+ : t("ide_side_panel.git.details.local_branch_only");+ const dateOf = (seconds: number) =>+ seconds ? new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" }).format(new Date(seconds * 1000)) : "";+ const showBase = !isDefault && baseRef && row.base_ahead != null && row.base_behind != null;++ return (+ <div data-testid="git-branch-details" className="space-y-3 border-t border-border/50 pb-3 pl-3 pr-3 pt-2.5 text-[11.5px]">+ <div data-testid="git-branch-actions" className="flex flex-wrap gap-1.5">+ {!row.current && !row.worktree && (+ <DetailButton+ icon={GitBranch}+ label={t(row.remote_only ? "ide_side_panel.git.act.check_out" : "ide_side_panel.git.act.switch")}+ testId="git-act-switch"+ busy={actions.busy === `switch:${row.name}`}+ disabled={!idle}+ onClick={() => actions.switchTo(row.name)}+ />+ )}+ {needsPull(row) && row.upstream && !row.upstream_gone && (+ <DetailButton+ icon={ArrowDownToLine}+ label={t(row.unfetched && !row.behind ? "ide_side_panel.git.act.fetch" : "ide_side_panel.git.act.update")}+ testId="git-act-update"+ busy={actions.busy === `update:${row.name}` || actions.busy === "fetch"}+ disabled={!idle}+ onClick={() => (row.unfetched && !row.behind ? void actions.fetch() : actions.update(row.name))}+ />+ )}+ {needsPush(row) && sync !== "diverged" && (+ <DetailButton+ icon={ArrowUpFromLine}+ label={t(sync === "ahead" ? "ide_side_panel.git.act.push" : "ide_side_panel.git.act.publish")}+ testId="git-act-push"+ busy={actions.busy === `push:${row.current ? "" : row.name}`}+ disabled={!idle}+ onClick={() => actions.push(row.current ? "" : row.name)}+ />+ )}+ {githubReady && !row.remote_only && !isDefault && !livePr(row) && !isMerged(row) && (+ <DetailButton+ icon={GitPullRequestCreate}+ label={t("ide_side_panel.git.act.create_pr")}+ testId="git-act-pr"+ busy={actions.busy === `pr:${row.current ? "" : row.name}`}+ disabled={!idle}+ onClick={() => actions.createPullRequest(row.current ? "" : row.name)}+ />+ )}+ {canOpen &&+ editors?.editors.map((editor) => (+ <DetailButton+ key={editor.id}+ icon={SquareTerminal}+ label={fill(t("ide_side_panel.git.details.open_in"), { editor: editor.label })}+ testId={`git-open-${editor.id}`}+ onClick={() => openLocal(editor.id)}+ />+ ))}+ {canOpen && (+ <DetailButton icon={FolderOpen} label={t("ide_side_panel.git.details.open_folder")} testId="git-open-folder" onClick={() => openLocal("folder")} />+ )}+ {url && <DetailButton icon={Globe} label={t("ide_side_panel.git.details.open_github")} testId="git-open-github" onClick={() => void openExternalUrl(url)} />}+ {pr && (+ <DetailButton+ icon={PR_ICON[pr.state]}+ label={fill(t("ide_side_panel.git.menu.open_pr"), { number: pr.number })}+ testId="git-open-pr"+ onClick={() => void openExternalUrl(pr.url)}+ />+ )}+ {row.ci.url && (+ <DetailButton icon={CirclePlay} label={t("ide_side_panel.git.menu.open_ci")} testId="git-open-ci" onClick={() => void openExternalUrl(row.ci.url)} />+ )}+ {!row.remote_only && !row.current && !isDefault && (+ <DetailButton+ icon={Trash2}+ label={t("ide_side_panel.git.act.delete")}+ testId="git-act-delete"+ danger+ busy={actions.busy === `delete:${row.name}`}+ disabled={!idle}+ onClick={() => actions.remove(row)}+ />+ )}+ </div>++ <p className="text-[11px] text-muted-foreground">+ <Laptop className="mr-1 inline h-3 w-3 align-[-2px]" aria-hidden />+ <span className="break-all">{where}</span>+ {row.upstream && (+ <span className="block pl-4">+ {row.upstream_gone+ ? fill(t("ide_side_panel.git.details.upstream_gone"), { upstream: row.upstream })+ : fill(t("ide_side_panel.git.tracks"), { upstream: row.upstream, ahead: row.ahead, behind: row.behind })}+ </span>+ )}+ {showBase && (+ <span data-testid="git-branch-base" className="block pl-4">+ {fill(t("ide_side_panel.git.details.vs_base"), { ahead: row.base_ahead ?? 0, behind: row.base_behind ?? 0, base: baseRef })}+ </span>+ )}+ </p>++ {error ? (+ <p className="text-[11px] text-destructive">{error}</p>+ ) : !contents ? (+ <p data-testid="git-branch-loading" className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />+ {t("ide_side_panel.git.details.loading")}+ </p>+ ) : !contents.available ? (+ <p className="text-[11px] text-muted-foreground">{contents.reason}</p>+ ) : (+ <>+ <section data-testid="git-branch-commits" className="space-y-1">+ <DetailHeading>+ {contents.base+ ? fill(t("ide_side_panel.git.details.commits_vs"), { n: contents.commits.length, base: contents.base })+ : fill(t("ide_side_panel.git.details.commits_latest"), { n: contents.commits.length })}+ </DetailHeading>+ {contents.commits.length === 0 ? (+ <p className="text-[11px] text-muted-foreground">{fill(t("ide_side_panel.git.details.no_commits"), { base: contents.base })}</p>+ ) : (+ <ol className="space-y-0.5">+ {contents.commits.map((commit) => (+ <li key={commit.sha} data-testid="git-branch-commit" data-sha={commit.sha} className="flex min-w-0 items-baseline gap-2">+ {/* Only a commit GitHub has gets a link; one still only here would open a 404. */}+ {repoUrl && commit.on_github ? (+ <button+ type="button"+ data-testid="git-commit-link"+ onClick={() => void openExternalUrl(`${repoUrl}/commit/${encodeURIComponent(commit.sha)}`)}+ className="shrink-0 font-mono text-[10.5px] text-info hover:underline"+ >+ {commit.sha.slice(0, 7)}+ </button>+ ) : commit.on_github === false ? (+ <QuickTooltip content={t("ide_side_panel.git.local_only_tip")} side="bottom" className="inline-flex shrink-0">+ <span data-testid="git-commit-local" className="inline-flex items-center gap-1 font-mono text-[10.5px] text-warning">+ <Laptop className="h-3 w-3" aria-hidden />+ {commit.sha.slice(0, 7)}+ </span>+ </QuickTooltip>+ ) : (+ // An older backend does not say where the commit is: no link, no claim.+ <span className="shrink-0 font-mono text-[10.5px] text-muted-foreground">{commit.sha.slice(0, 7)}</span>+ )}+ <QuickTooltip content={`${commit.subject}\n${commit.author} · ${dateOf(commit.committed_at)}`} side="bottom" className="flex min-w-0 flex-1">+ <span className="truncate text-foreground">{commit.subject}</span>+ </QuickTooltip>+ <span className="shrink-0 text-[10.5px] tabular-nums text-muted-foreground">+ {commit.committed_at ? commitDateLabel(commit.committed_at, lang) : ""}+ </span>+ </li>+ ))}+ </ol>+ )}+ {contents.commits_truncated && <p className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.more_commits")}</p>}+ </section>+ {contents.base && (+ <section data-testid="git-branch-files" className="space-y-1">+ <DetailHeading>{fill(t("ide_side_panel.git.details.files"), { n: contents.files.length })}</DetailHeading>+ <ul>+ {contents.files.map((file) => (+ <BranchFileRow key={file.path} file={file} workspaceId={workspaceId} branch={row.name} base={defaultBranch} remote={row.remote_only} />+ ))}+ </ul>+ {contents.files_truncated && <p className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.more_files")}</p>}+ </section>+ )}+ </>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchList.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchList.tsxnew file mode 100644index 0000000000..515567e6a7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchList.tsx@@ -0,0 +1,351 @@+import { useEffect, useMemo, useState } from "react";+import { ChevronDown, ChevronRight, Ellipsis, FolderGit2, Search, X } from "lucide-react";+import { fill, useT } from "@/i18n";+import { useRunLocale } from "@/components/runs/format";+import { cn } from "@/lib/utils";+import { QuickTooltip } from "@/components/ui/tooltip";+import { BranchDetails } from "./BranchDetails";+import { CiBadge, commitDateLabel, PullRequestBadge } from "./gitBadges";+import { BRANCH_FILTERS, matchesFilter, matchesQuery, syncOf, type BranchFilter } from "./gitInsights";+import type { BranchEditors, BranchRow, RepoOverview } from "./gitOverviewApi";+import { ShowMore } from "./Section";+import type { GitActions } from "./useGitActions";++/** Rows drawn before "show more": a repository can hold hundreds of branches. */+const PAGE = 20;++type Translate = (key: string) => string;++interface Fact {+ id: string;+ text: string;+ tone?: string;+ tip?: string;+}++/** The row's second line: when it last changed and what, if anything, is off. */+function factsOf(t: Translate, row: BranchRow, lang: string): Fact[] {+ const facts: Fact[] = [];+ if (row.committed_at) {+ const full = new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" }).format(new Date(row.committed_at * 1000));+ facts.push({ id: "date", text: commitDateLabel(row.committed_at, lang), tip: fill(t("ide_side_panel.git.last_commit"), { date: full }) });+ }+ const merged = row.merged_into[0];+ if (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 });+ facts.push({ id: "merged", text: fill(t("ide_side_panel.git.merged_short"), { target: merged.target }), tone: "text-[hsl(var(--gh-merged))]", tip });+ }+ const sync = syncOf(row);+ if (row.ahead > 0) {+ facts.push({ id: "push", text: fill(t("ide_side_panel.git.row.to_push"), { n: row.ahead }), tone: "text-warning", tip: t("ide_side_panel.git.row.to_push_tip") });+ }+ if (row.behind > 0) {+ facts.push({ id: "pull", text: fill(t("ide_side_panel.git.row.to_pull"), { n: row.behind }), tone: "text-info", tip: t("ide_side_panel.git.row.to_pull_tip") });+ } else if (row.unfetched) {+ facts.push({ id: "pull", text: t("ide_side_panel.git.row.unfetched"), tone: "text-info", tip: t("ide_side_panel.git.row.unfetched_tip") });+ }+ if (sync === "unpublished" && !merged) {+ facts.push({ id: "local", text: t("ide_side_panel.git.local_only"), tone: "text-warning", tip: t("ide_side_panel.git.local_only_tip") });+ }+ if (sync === "gone" && !merged) {+ facts.push({ id: "gone", text: t("ide_side_panel.git.row.gone"), tip: t("ide_side_panel.git.row.gone_tip") });+ }+ return facts;+}++function BranchLine({+ row,+ overview,+ workspaceId,+ editors,+ actions,+ menuOpen,+ onMenu,+ expanded,+ onToggle,+}: {+ row: BranchRow;+ overview: RepoOverview;+ workspaceId: string;+ editors: BranchEditors | null;+ actions: GitActions;+ menuOpen: boolean;+ onMenu: (row: BranchRow, x: number, y: number) => void;+ expanded: boolean;+ onToggle: () => void;+}) {+ const t = useT();+ const lang = useRunLocale();+ const isDefault = !row.remote_only && row.name === overview.default_branch;+ const facts = factsOf(t, row, lang);+ return (+ <li+ data-testid="git-branch-row"+ data-branch={row.name}+ data-current={row.current || undefined}+ data-expanded={expanded || undefined}+ data-sync={syncOf(row)}+ onContextMenu={(event) => {+ event.preventDefault();+ onMenu(row, event.clientX, event.clientY);+ }}+ className={cn("relative", expanded && "bg-secondary/30")}+ >+ {row.current && <span className="absolute inset-y-0 left-0 w-0.5 bg-accent" aria-hidden />}+ <div className={cn("group/row flex min-h-[38px] items-center gap-0.5 pl-3 pr-1 hover:bg-secondary/40", menuOpen && "bg-secondary/60")}>+ <button+ type="button"+ data-testid="git-branch-toggle"+ aria-expanded={expanded}+ onClick={onToggle}+ className="flex min-w-0 flex-1 flex-col py-1 text-left leading-tight focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ >+ <span className="flex min-w-0 items-center gap-1.5">+ <span className={cn("truncate font-mono text-[12.5px] text-foreground", row.current && "font-semibold")}>{row.name}</span>+ {row.current && (+ <span data-testid="git-current-tag" className="shrink-0 rounded bg-accent/15 px-1 text-[9.5px] font-medium uppercase tracking-wide text-accent">+ {t("ide_side_panel.git.row.current")}+ </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>+ )}+ </span>+ <span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground">+ {facts.map((fact, index) => (+ <QuickTooltip key={fact.id} content={fact.tip ?? fact.text} side="bottom" className="inline-flex min-w-0 shrink-0 items-center gap-1.5 last:shrink">+ {index > 0 && <span className="text-muted-foreground/50" aria-hidden>·</span>}+ <span data-testid={`git-fact-${fact.id}`} className={cn("truncate tabular-nums", fact.tone)}>+ {fact.text}+ </span>+ </QuickTooltip>+ ))}+ {row.worktree && (+ <QuickTooltip content={fill(t("ide_side_panel.git.in_worktree"), { path: row.worktree })} side="bottom" className="inline-flex shrink-0">+ <FolderGit2 data-testid="git-worktree" className="h-3 w-3" aria-label={t("ide_side_panel.git.worktree_badge")} />+ </QuickTooltip>+ )}+ </span>+ </button>+ <PullRequestBadge prs={row.pull_requests} />+ <CiBadge ci={row.ci} stale={row.ci_stale} />+ <QuickTooltip content={t("ide_side_panel.git.more")} side="bottom" className="inline-flex shrink-0">+ <button+ type="button"+ data-testid="git-branch-more"+ data-branch-menu-anchor+ aria-label={fill(t("ide_side_panel.git.menu.aria"), { branch: row.name })}+ aria-haspopup="menu"+ aria-expanded={menuOpen}+ onClick={(event) => {+ const rect = event.currentTarget.getBoundingClientRect();+ onMenu(row, rect.right - 264, rect.bottom + 4);+ }}+ className={cn(+ "inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground opacity-0 hover:bg-secondary hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/row:opacity-100",+ menuOpen && "bg-secondary text-foreground opacity-100",+ )}+ >+ <Ellipsis className="h-4 w-4" aria-hidden />+ </button>+ </QuickTooltip>+ <ChevronDown+ className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground/70 transition-transform motion-reduce:transition-none", expanded && "rotate-180")}+ aria-hidden+ />+ </div>+ {expanded && (+ <BranchDetails+ row={row}+ repoUrl={overview.github.repo_url}+ defaultBranch={overview.default_branch}+ baseRef={overview.base_ref ?? ""}+ githubReady={overview.github.available}+ workspaceId={workspaceId}+ editors={editors}+ actions={actions}+ />+ )}+ </li>+ );+}++/**+ * Every branch, the checked-out one first and the rest by last change: search+ * by name or pull request, narrow to what needs pushing, pulling or fixing.+ * Branches that exist only on GitHub sit in their own folded group.+ */+export function BranchList({+ overview,+ workspaceId,+ editors,+ actions,+ filter,+ onFilter,+ menuBranch,+ onMenu,+}: {+ overview: RepoOverview;+ workspaceId: string;+ editors: BranchEditors | null;+ actions: GitActions;+ filter: BranchFilter;+ onFilter: (value: BranchFilter) => void;+ /** The row whose menu is open ("" when none). */+ menuBranch: string;+ onMenu: (row: BranchRow, x: number, y: number) => void;+}) {+ const t = useT();+ const [query, setQuery] = useState("");+ const [limit, setLimit] = useState(PAGE);+ const [showRemote, setShowRemote] = useState(false);+ const [remoteLimit, setRemoteLimit] = useState(PAGE);+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());+ useEffect(() => {+ setQuery("");+ setExpanded(new Set());+ setShowRemote(false);+ }, [workspaceId]);+ // A new question starts at the top of its answer.+ useEffect(() => {+ setLimit(PAGE);+ setRemoteLimit(PAGE);+ }, [filter, query, workspaceId]);++ const trimmed = query.trim();+ const all = useMemo(() => [...overview.branches, ...overview.remote_branches], [overview]);+ const counts = useMemo(() => {+ const result = {} as Record<BranchFilter, number>;+ for (const value of BRANCH_FILTERS) {+ result[value] = all.filter((row) => matchesFilter(row, value) && matchesQuery(row, trimmed)).length;+ }+ return result;+ }, [all, trimmed]);+ const narrowed = filter !== "all" || trimmed !== "";+ const visible = (rows: BranchRow[]) => rows.filter((row) => matchesFilter(row, filter) && matchesQuery(row, trimmed));+ const local = visible(overview.branches);+ const remote = visible(overview.remote_branches);+ const remoteOpen = showRemote || narrowed;+ const toggle = (key: string) =>+ setExpanded((current) => {+ const next = new Set(current);+ if (!next.delete(key)) next.add(key);+ return next;+ });+ const line = (row: BranchRow, key: string) => (+ <BranchLine+ key={key}+ row={row}+ overview={overview}+ workspaceId={workspaceId}+ editors={editors}+ actions={actions}+ menuOpen={menuBranch === key}+ onMenu={onMenu}+ expanded={expanded.has(key)}+ onToggle={() => toggle(key)}+ />+ );++ return (+ <div data-testid="git-branches">+ <div data-testid="git-filter-bar" className="space-y-1.5 px-3 pb-2">+ <label className="flex h-7 items-center gap-1.5 rounded-md border border-border/70 bg-background px-2 focus-within:ring-2 focus-within:ring-ring">+ <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <input+ data-testid="git-search"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape" && query) {+ event.stopPropagation();+ setQuery("");+ }+ }}+ placeholder={t("ide_side_panel.git.search")}+ aria-label={t("ide_side_panel.git.search")}+ className="min-w-0 flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground"+ />+ {query && (+ <button+ type="button"+ aria-label={t("ide_side_panel.git.search_clear")}+ onClick={() => setQuery("")}+ className="inline-flex h-4 w-4 items-center justify-center rounded text-muted-foreground hover:text-foreground"+ >+ <X className="h-3 w-3" aria-hidden />+ </button>+ )}+ </label>+ <div role="group" aria-label={t("ide_side_panel.git.filter_aria")} className="flex flex-wrap gap-x-3 gap-y-1">+ {BRANCH_FILTERS.filter((value) => value === "all" || value === filter || counts[value] > 0).map((value) => (+ <button+ key={value}+ type="button"+ data-testid={`git-filter-${value}`}+ aria-pressed={filter === value}+ onClick={() => onFilter(value)}+ className={cn(+ "inline-flex h-5 items-center gap-1 border-b-2 text-[11px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ filter === value ? "border-accent text-foreground" : "border-transparent text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`ide_side_panel.git.filter.${value}`)}+ <span className="tabular-nums text-muted-foreground/70">{counts[value]}</span>+ </button>+ ))}+ </div>+ </div>++ <ul aria-label={t("ide_side_panel.git.branches")}>{local.slice(0, limit).map((row) => line(row, row.name))}</ul>+ {local.length > limit && (+ <ShowMore+ testId="git-branches-more"+ label={fill(t("ide_side_panel.git.show_more"), { n: Math.min(PAGE, local.length - limit), left: local.length - limit })}+ onClick={() => setLimit((value) => value + PAGE)}+ />+ )}+ {narrowed && counts[filter] === 0 && (+ <p data-testid="git-filter-empty" className="px-4 py-6 text-center text-xs text-muted-foreground">+ {t("ide_side_panel.git.filter_empty")}+ </p>+ )}+ {overview.truncated && (+ <p className="px-3 py-2 text-[11px] text-muted-foreground">{fill(t("ide_side_panel.git.truncated"), { n: overview.branches.length })}</p>+ )}+ {remote.length > 0 && (+ <div className="border-t border-border/60">+ <button+ type="button"+ data-testid="git-remote-toggle"+ aria-expanded={remoteOpen}+ onClick={() => setShowRemote((value) => !value)}+ className="flex h-8 w-full items-center gap-1 pl-2 text-left text-[10.5px] font-semibold uppercase tracking-wider text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ >+ <ChevronRight className={cn("h-3.5 w-3.5 transition-transform motion-reduce:transition-none", remoteOpen && "rotate-90")} aria-hidden />+ {fill(t("ide_side_panel.git.remote_only"), { n: remote.length })}+ </button>+ {remoteOpen && (+ <>+ <ul aria-label={fill(t("ide_side_panel.git.remote_only"), { n: remote.length })}>+ {remote.slice(0, remoteLimit).map((row) => line(row, `remote:${row.name}`))}+ </ul>+ {remote.length > remoteLimit && (+ <ShowMore+ testId="git-remote-more"+ label={fill(t("ide_side_panel.git.show_more"), { n: Math.min(PAGE, remote.length - remoteLimit), left: remote.length - remoteLimit })}+ onClick={() => setRemoteLimit((value) => value + PAGE)}+ />+ )}+ </>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchMenu.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchMenu.tsxindex 1c68efff87..a64a2363e8 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchMenu.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/BranchMenu.tsx@@ -1,6 +1,8 @@import { useEffect, useLayoutEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from "react";import { createPortal } from "react-dom";import {+ ArrowDownToLine,+ ArrowUpFromLine,Copy,ExternalLink,FolderOpen,@@ -14,13 +16,16 @@ import {Link2,CirclePlay,SquareTerminal,+ Trash2,type LucideIcon,} from "lucide-react";import { fill, useT } from "@/i18n";import { robustCopy } from "@/lib/clipboard";import { openExternalUrl } from "@/lib/openExternal";import { useEventStore } from "@/store/events";+import { needsPull, needsPush, syncOf } from "./gitInsights";import type { BranchRow } from "./gitOverviewApi";+import type { GitActions } from "./useGitActions";const MENU_WIDTH = 264;const MENU_MARGIN = 8;@@ -42,13 +47,15 @@ interface MenuItem {hint?: string;icon: LucideIcon;disabled?: boolean;+ danger?: boolean;onSelect: () => void;}/**- * Everything one branch row offers: its GitHub pages (branch, commits,- * comparison with the default branch, the pull request or a new one, the CI- * run) and the strings people paste elsewhere. Opened by right-click or by+ * Everything one branch row offers: what can be done with the branch (switch,+ * update, push, delete), its GitHub pages (branch, commits, comparison with+ * the default branch, the pull request or a new one, the CI run) and the+ * strings people paste elsewhere. Opened by right-click or by* the row's ⋯ button; portalled so the scrolling list never clips it.*/export function BranchMenu({@@ -57,6 +64,7 @@ export function BranchMenu({defaultBranch,x,y,+ actions,onDismiss,}: {row: BranchRow;@@ -64,6 +72,7 @@ export function BranchMenu({defaultBranch: string;x: number;y: number;+ actions?: GitActions;onDismiss: () => void;}) {const t = useT();@@ -136,6 +145,34 @@ export function BranchMenu({const pr = row.pull_requests[0];const livePr = pr && pr.state !== "merged" && pr.state !== "closed" ? pr : undefined;+ const act = (work: () => void) => () => {+ onDismiss();+ work();+ };+ const does: MenuItem[] = [];+ if (actions && !row.current && !row.worktree) {+ does.push({+ id: "switch",+ label: t(row.remote_only ? "ide_side_panel.git.act.check_out" : "ide_side_panel.git.act.switch"),+ icon: GitBranch,+ onSelect: act(() => actions.switchTo(row.name)),+ });+ }+ if (actions && needsPull(row) && row.behind > 0 && row.upstream && !row.upstream_gone) {+ does.push({ id: "update", label: t("ide_side_panel.git.act.update"), icon: ArrowDownToLine, onSelect: act(() => actions.update(row.name)) });+ }+ if (actions && needsPush(row) && syncOf(row) !== "diverged") {+ does.push({+ id: "push",+ label: t(syncOf(row) === "ahead" ? "ide_side_panel.git.act.push" : "ide_side_panel.git.act.publish"),+ icon: ArrowUpFromLine,+ onSelect: act(() => actions.push(row.current ? "" : row.name)),+ });+ }+ if (actions && !row.remote_only && !row.current && !isDefault) {+ does.push({ id: "delete", label: t("ide_side_panel.git.act.delete"), icon: Trash2, danger: true, onSelect: act(() => actions.remove(row)) });+ }+const github: MenuItem[] = [{id: "branch",@@ -242,7 +279,7 @@ export function BranchMenu({<GitBranch aria-hidden className="h-3 w-3 shrink-0" /><span className="min-w-0 truncate font-mono">{row.name}</span></div>- {[github, copies].map((section, index) => (+ {[does, github, copies].filter((section) => section.length > 0).map((section, index) => (<div key={section[0]?.id ?? index} role="group" className={index > 0 ? "mt-1 border-t border-border/70 pt-1" : ""}>{section.map((item) => {const Icon = item.icon;@@ -254,9 +291,9 @@ export function BranchMenu({data-testid={`git-menu-${item.id}`}disabled={item.disabled}onClick={item.onSelect}- className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] text-foreground transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-45"+ className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] transition-colors hover:bg-muted focus-visible:bg-muted focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-45 ${item.danger ? "text-destructive" : "text-foreground"}`}>- <Icon aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <Icon aria-hidden className={`h-4 w-4 shrink-0 ${item.danger ? "text-destructive" : "text-muted-foreground"}`} /><span className="flex min-w-0 flex-1 flex-col"><span className="truncate">{item.label}</span>{item.hint && <span className="truncate text-[11px] text-muted-foreground">{item.hint}</span>}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/CleanupDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/CleanupDialog.tsxnew file mode 100644index 0000000000..418a14b6a9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/CleanupDialog.tsx@@ -0,0 +1,193 @@+import { useEffect, useRef, useState } from "react";+import { createPortal } from "react-dom";+import { Check, FolderGit2, Loader2 } from "lucide-react";+import { fill, useT } from "@/i18n";+import { deleteBranch } from "@/lib/gitApi";+import { plural } from "./gitBadges";+import type { BranchRow } from "./gitOverviewApi";++interface Kept {+ name: string;+ reason: string;+}++/**+ * Removes merged branches in one go — after showing exactly which, with every+ * one of them unticked-able. Nothing is forced: a branch whose commits exist+ * nowhere else, or whose worktree holds uncommitted changes or an open+ * workspace, is kept and listed with the reason.+ */+export function CleanupDialog({ rows, workspaceId, onClose }: { rows: BranchRow[]; workspaceId: string; onClose: (changed: boolean) => void }) {+ const t = useT();+ const [picked, setPicked] = useState<ReadonlySet<string>>(() => new Set(rows.map((row) => row.name)));+ const [phase, setPhase] = useState<"ask" | "running" | "done">("ask");+ const [progress, setProgress] = useState(0);+ const [removed, setRemoved] = useState(0);+ const [kept, setKept] = useState<Kept[]>([]);+ const stop = useRef(false);+ const cancelButton = useRef<HTMLButtonElement>(null);+ useEffect(() => cancelButton.current?.focus(), []);+ // Closing the dialog mid-run stops before the next branch. Reset on mount:+ // React's development mode runs an effect's cleanup once before the real mount.+ useEffect(() => {+ stop.current = false;+ return () => {+ stop.current = true;+ };+ }, []);++ const chosen = rows.filter((row) => picked.has(row.name));+ const withWorktree = chosen.filter((row) => row.worktree).length;+ const toggle = (name: string) =>+ setPicked((current) => {+ const next = new Set(current);+ if (!next.delete(name)) next.add(name);+ return next;+ });++ const start = async () => {+ setPhase("running");+ let done = 0;+ const left: Kept[] = [];+ for (const [index, row] of chosen.entries()) {+ if (stop.current) break;+ setProgress(index + 1);+ try {+ await deleteBranch(workspaceId, row.name, { withWorktree: Boolean(row.worktree) });+ done += 1;+ } catch (err) {+ left.push({ name: row.name, reason: (err as Error).message });+ }+ }+ setRemoved(done);+ setKept(left);+ setPhase("done");+ };+ const close = () => onClose(phase !== "ask");++ return createPortal(+ <div+ role="presentation"+ className="fixed inset-0 z-[110] flex items-center justify-center bg-background/60 p-4"+ onKeyDown={(event) => {+ if (event.key === "Escape" && phase !== "running") {+ event.stopPropagation();+ close();+ }+ }}+ >+ <section+ role="alertdialog"+ aria-modal="true"+ aria-labelledby="git-cleanup-title"+ data-testid="git-cleanup"+ data-phase={phase}+ className="flex max-h-[80vh] w-full max-w-md flex-col rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-float"+ >+ <h2 id="git-cleanup-title" className="text-sm font-semibold text-foreground">+ {phase === "done"+ ? plural(t, "ide_side_panel.git.cleanup.done_title", removed)+ : plural(t, "ide_side_panel.git.cleanup.title", chosen.length)}+ </h2>++ {phase === "ask" && (+ <>+ <p className="mt-1.5 text-xs leading-relaxed text-muted-foreground">+ {t("ide_side_panel.git.cleanup.body")}+ {withWorktree > 0 && ` ${plural(t, "ide_side_panel.git.cleanup.worktrees", withWorktree)}`}+ </p>+ <ul className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md border border-border/70">+ {rows.map((row) => (+ <li key={row.name}>+ <label className="flex cursor-pointer items-center gap-2 px-2.5 py-1.5 hover:bg-secondary/60">+ <input+ type="checkbox"+ data-testid="git-cleanup-pick"+ data-branch={row.name}+ checked={picked.has(row.name)}+ onChange={() => toggle(row.name)}+ className="h-3.5 w-3.5 shrink-0 accent-[hsl(var(--accent))]"+ />+ <span className="min-w-0 flex-1 truncate font-mono text-[12px] text-foreground">{row.name}</span>+ {row.worktree && <FolderGit2 className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-label={t("ide_side_panel.git.worktree_badge")} />}+ </label>+ </li>+ ))}+ </ul>+ </>+ )}++ {phase === "running" && (+ <div className="mt-3 space-y-2">+ <p data-testid="git-cleanup-progress" className="flex items-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />+ {fill(t("ide_side_panel.git.cleanup.progress"), { done: progress, total: chosen.length })}+ </p>+ <div className="h-1 overflow-hidden rounded-full bg-secondary">+ <div className="h-full bg-accent transition-[width] duration-200" style={{ width: `${(progress / Math.max(1, chosen.length)) * 100}%` }} />+ </div>+ </div>+ )}++ {phase === "done" && (+ <div className="mt-2 min-h-0 flex-1 overflow-y-auto">+ {kept.length === 0 ? (+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Check className="h-3.5 w-3.5 text-success" aria-hidden />+ {t("ide_side_panel.git.cleanup.done_all")}+ </p>+ ) : (+ <>+ <p className="text-xs text-muted-foreground">{plural(t, "ide_side_panel.git.cleanup.kept", kept.length)}</p>+ <ul className="mt-2 space-y-1.5">+ {kept.map((entry) => (+ <li key={entry.name} data-testid="git-cleanup-kept" className="text-[11.5px] leading-snug">+ <span className="font-mono text-foreground">{entry.name}</span>+ <span className="block text-muted-foreground">{entry.reason}</span>+ </li>+ ))}+ </ul>+ </>+ )}+ </div>+ )}++ <div className="mt-4 flex shrink-0 justify-end gap-2">+ {phase === "ask" && (+ <>+ <button+ ref={cancelButton}+ type="button"+ data-testid="git-cleanup-cancel"+ onClick={close}+ className="h-8 rounded-md px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("ide_side_panel.git.confirm.cancel")}+ </button>+ <button+ type="button"+ data-testid="git-cleanup-ok"+ disabled={chosen.length === 0}+ onClick={() => void start()}+ className="h-8 rounded-md bg-destructive px-3 text-xs font-medium text-destructive-foreground hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ {plural(t, "ide_side_panel.git.cleanup.ok", chosen.length)}+ </button>+ </>+ )}+ {phase === "done" && (+ <button+ type="button"+ data-testid="git-cleanup-close"+ onClick={close}+ className="h-8 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("ide_side_panel.git.cleanup.close")}+ </button>+ )}+ </div>+ </section>+ </div>,+ document.body,+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/ConfirmDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/ConfirmDialog.tsxnew file mode 100644index 0000000000..39d7ad12a2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/ConfirmDialog.tsx@@ -0,0 +1,89 @@+import { useEffect, useRef, type ReactNode } from "react";+import { createPortal } from "react-dom";+import { Loader2 } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++/**+ * The question asked before anything that cannot be taken back: deleting a+ * branch, rewriting local commits. Cancel has the focus, so Enter never+ * confirms by accident; Escape and a click outside both cancel.+ */+export function ConfirmDialog({+ title,+ body,+ confirmLabel,+ destructive = true,+ busy = false,+ onConfirm,+ onCancel,+ children,+}: {+ title: string;+ body?: string;+ confirmLabel: string;+ destructive?: boolean;+ busy?: boolean;+ onConfirm: () => void;+ onCancel: () => void;+ children?: ReactNode;+}) {+ const t = useT();+ const cancelButton = useRef<HTMLButtonElement>(null);+ useEffect(() => cancelButton.current?.focus(), []);+ return createPortal(+ <div+ role="presentation"+ className="fixed inset-0 z-[110] flex items-center justify-center bg-background/60 p-4"+ onPointerDown={(event) => {+ if (event.target === event.currentTarget && !busy) onCancel();+ }}+ onKeyDown={(event) => {+ if (event.key === "Escape" && !busy) {+ event.stopPropagation();+ onCancel();+ }+ }}+ >+ <section+ role="alertdialog"+ aria-modal="true"+ aria-labelledby="git-confirm-title"+ data-testid="git-confirm"+ className="w-full max-w-sm rounded-xl border border-border bg-popover p-4 text-popover-foreground shadow-float"+ >+ <h2 id="git-confirm-title" className="break-words text-sm font-semibold text-foreground">+ {title}+ </h2>+ {body && <p className="mt-1.5 whitespace-pre-line break-words text-xs leading-relaxed text-muted-foreground">{body}</p>}+ {children}+ <div className="mt-4 flex justify-end gap-2">+ <button+ ref={cancelButton}+ type="button"+ data-testid="git-confirm-cancel"+ disabled={busy}+ onClick={onCancel}+ className="h-8 rounded-md px-3 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ {t("ide_side_panel.git.confirm.cancel")}+ </button>+ <button+ type="button"+ data-testid="git-confirm-ok"+ disabled={busy}+ onClick={onConfirm}+ className={cn(+ "inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60",+ destructive ? "bg-destructive text-destructive-foreground hover:opacity-90" : "bg-primary text-primary-foreground hover:bg-primary/90",+ )}+ >+ {busy && <Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />}+ {confirmLabel}+ </button>+ </div>+ </section>+ </div>,+ document.body,+ );+}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.tsxindex 0f1b6fb45c..51e08ad9f5 100644--- 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@@ -1,10 +1,12 @@+import { StrictMode } from "react";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 { GitOverviewTab, resetGitOverviewCache } from "./GitOverviewTab";+import type { BranchRow, Checkout, CiStatus, PullRequest, RepoOverview } from "./gitOverviewApi";import { openExternalUrl } from "@/lib/openExternal";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";+import { useIdeSidePanelStore } from "@/store/ideSidePanel";vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn(async () => true) }));@@ -26,11 +28,13 @@ function branch(name: string, extra: Partial<BranchRow> = {}): BranchRow {pull_requests: [],ci: noCi,ci_stale: false,+ base_ahead: 1,+ base_behind: 0,...extra,};}-const pr = (number: number, state: "draft" | "open" | "queued" | "merged" | "closed", ci: CiStatus = noCi) => ({+const pr = (number: number, state: PullRequest["state"], ci: CiStatus = noCi, extra: Partial<PullRequest> = {}): PullRequest => ({number,title: `Change ${number}`,url: `https://github.com/o/r/pull/${number}`,@@ -42,8 +46,28 @@ const pr = (number: number, state: "draft" | "open" | "queued" | "merged" | "cloupdated_at: "",queue_position: state === "queued" ? 2 : null,ci,+ ...extra,});+const CHECKOUT: Checkout = {+ branch: "feature/wip",+ detached: false,+ unborn: false,+ head: "abc123def456",+ upstream: "origin/feature/wip",+ ahead: 2,+ behind: 0,+ files: 0,+ staged: 0,+ unstaged: 0,+ untracked: 0,+ conflicted: 0,+ operation: "",+ stashes: 0,+ last_fetch: Math.floor(Date.now() / 1000) - 120,+ has_remote: true,+};+const OVERVIEW: RepoOverview = {available: true,reason: "",@@ -84,8 +108,16 @@ const OVERVIEW: RepoOverview = {}),],remote_branches: [branch("only-remote", { remote_only: true, upstream: "" })],+ checkout: CHECKOUT,+ base_ref: "origin/main",};+const withCheckout = (extra: Partial<Checkout>, current: Partial<BranchRow> = {}): RepoOverview => ({+ ...OVERVIEW,+ checkout: { ...CHECKOUT, ...extra },+ branches: [{ ...OVERVIEW.branches[0], ...current }, ...OVERVIEW.branches.slice(1)],+});+let answer: unknown = OVERVIEW;let status = 200;/** Holds overview answers back, like a slow GitHub read. */@@ -94,6 +126,10 @@ const calls: string[] = [];const puts: string[] = [];const opens: string[] = [];const diffs: string[] = [];+/** Every action the tab asked the backend for: the route and its JSON body. */+const posts: { path: string; body: Record<string, unknown> }[] = [];+/** Queued failures per action route: `[status, detail]`, used once each. */+const refusals: Record<string, [number, unknown][]> = {};const CONTENTS = {available: true,branch: "feature/wip",@@ -129,6 +165,7 @@ const REPOS = {{ name: "o/r", description: "", private: false, fork: false, url: "", pushed_at: "" },],};+const ACTION = /\/api\/agentic-ide\/git\/(fetch|pull|commit|switch|branch\/push|branch\/pull-request|branch\/update|branch\/delete)$/;beforeEach(() => {answer = OVERVIEW;@@ -138,6 +175,9 @@ beforeEach(() => {puts.length = 0;opens.length = 0;diffs.length = 0;+ posts.length = 0;+ for (const key of Object.keys(refusals)) delete refusals[key];+ resetGitOverviewCache();vi.stubGlobal("fetch",vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {@@ -145,6 +185,13 @@ beforeEach(() => {calls.push(url);const json = (body: unknown, code = 200) =>new Response(JSON.stringify(body), { status: code, headers: { "Content-Type": "application/json" } });+ const action = ACTION.exec(url);+ if (action && init?.method === "POST") {+ posts.push({ path: action[1], body: JSON.parse(String(init.body)) });+ const refusal = refusals[action[1]]?.shift();+ if (refusal) return json({ detail: refusal[1] }, refusal[0]);+ return json({ ok: true, message: "Done.", upstream: "origin/feature/wip", commit: "abc1234", url: "https://github.com/o/r/pull/11" });+ }if (url.includes("/github/repos")) return json(REPOS);if (url.includes("/branch/contents")) return json(CONTENTS);if (url.includes("/branch/diff")) {@@ -176,23 +223,244 @@ afterEach(() => {});const row = (name: string) => screen.getAllByTestId("git-branch-row").find((el) => el.dataset.branch === name)!;+const rowNames = () => screen.getAllByTestId("git-branch-row").map((el) => el.dataset.branch);+const posted = (path: string) => posts.filter((post) => post.path === path).map((post) => post.body);-describe("GitOverviewTab", () => {- it("lists the workspace's branches and marks the checked-out one", async () => {+describe("GitOverviewTab — the checkout at a glance", () => {+ it("says who is ahead and offers the one next step as a button", async () => {+ render(<GitOverviewTab />);+ expect((await screen.findByTestId("git-current-branch")).textContent).toBe("feature/wip");+ expect(screen.getByTestId("git-sync-push").dataset.count).toBe("2");+ expect(screen.getByTestId("git-sync-pull").dataset.count).toBe("0");+ expect(screen.getByTestId("git-sync-sentence").textContent).toBe("This computer is 2 commits ahead of origin/feature/wip.");+ expect(screen.getByTestId("git-working-tree").textContent).toContain("Nothing to commit");+ const next = screen.getByTestId("git-next");+ expect(next.dataset.step).toBe("push");+ expect(next.textContent).toContain("Push 2 commits to origin/feature/wip");+ fireEvent.click(screen.getByTestId("git-next-action"));+ await vi.waitFor(() => expect(posted("branch/push")).toEqual([{ workspace_id: "w1", branch: "" }]));+ // The overview is read again once the action finished.+ await vi.waitFor(() => expect(calls.some((url) => url.includes("refresh=true"))).toBe(true));+ });++ it("commits uncommitted work from an inline message box", async () => {+ answer = withCheckout({ ahead: 0, files: 3, unstaged: 2, untracked: 1 }, { ahead: 0 });+ render(<GitOverviewTab />);+ const tree = await screen.findByTestId("git-working-tree");+ expect(tree.textContent).toContain("3 changed files");+ expect(tree.textContent).toContain("2 modified · 1 new");+ expect(screen.getByTestId("git-next").dataset.step).toBe("commit");+ fireEvent.click(screen.getByTestId("git-next-action"));+ expect(screen.getByTestId("git-commit-form").textContent).toContain("Commits all 3 changed files");+ expect((screen.getByTestId("git-commit-submit") as HTMLButtonElement).disabled).toBe(true);+ fireEvent.change(screen.getByTestId("git-commit-message"), { target: { value: "feat: add the widget" } });+ fireEvent.click(screen.getByTestId("git-commit-submit"));+ await vi.waitFor(() => expect(posted("commit")).toEqual([{ folder: "/code/app", message: "feat: add the widget" }]));+ await vi.waitFor(() => expect(screen.queryByTestId("git-commit-form")).toBeNull());+ });++ it("opens the Changes tab to review what is uncommitted", async () => {+ answer = withCheckout({ files: 1, unstaged: 1 });+ render(<GitOverviewTab />);+ fireEvent.click(await screen.findByTestId("git-review-changes"));+ expect(useIdeSidePanelStore.getState().active).toBe("changes");+ });++ it("pulls with a fast-forward, and rewrites local commits only after a confirmation", async () => {+ answer = withCheckout({ ahead: 0, behind: 3 }, { ahead: 0, behind: 3 });+ refusals.pull = [[422, { message: "Both moved on.", code: "diverged" }]];+ render(<GitOverviewTab />);+ expect((await screen.findByTestId("git-next")).textContent).toContain("Pull 3 commits from origin/feature/wip");+ expect(screen.getByTestId("git-sync-sentence").textContent).toBe("origin/feature/wip is 3 commits ahead of this computer.");+ fireEvent.click(screen.getByTestId("git-next-action"));+ await vi.waitFor(() => expect(posted("pull")).toEqual([{ workspace_id: "w1", rebase: false }]));+ // The branch had diverged: nothing was rewritten, the tab asks first.+ const dialog = await screen.findByTestId("git-confirm");+ expect(dialog.textContent).toContain("Rebase your commits onto the remote ones?");+ fireEvent.click(within(dialog).getByTestId("git-confirm-ok"));+ await vi.waitFor(() => expect(posted("pull")).toEqual([{ workspace_id: "w1", rebase: false }, { workspace_id: "w1", rebase: true }]));+ });++ it("offers a rebase for a diverged branch and does nothing when it is cancelled", async () => {+ answer = withCheckout({ ahead: 2, behind: 1 }, { ahead: 2, behind: 1 });+ render(<GitOverviewTab />);+ expect((await screen.findByTestId("git-next")).dataset.step).toBe("rebase");+ expect(screen.getByTestId("git-sync-sentence").textContent).toContain("Both moved on: 2 only here, 1 only on origin/feature/wip.");+ fireEvent.click(screen.getByTestId("git-next-action"));+ fireEvent.click(within(await screen.findByTestId("git-confirm")).getByTestId("git-confirm-cancel"));+ expect(screen.queryByTestId("git-confirm")).toBeNull();+ expect(posts).toEqual([]);+ });++ it("names a failing pull request's checks as the next thing to fix", async () => {+ const failing = { ...noCi, state: "failure" as const, total: 5, passed: 3, failed: 2, names: ["lint", "tests"], url: "https://github.com/o/r/actions/runs/9" };+ answer = withCheckout({ ahead: 0 }, { ahead: 0, pull_requests: [pr(7, "open", failing)], ci: failing });+ render(<GitOverviewTab />);+ const next = await screen.findByTestId("git-next");+ expect(next.dataset.step).toBe("fix_ci");+ expect(next.textContent).toContain("CI is failing on #7");+ expect(next.textContent).toContain("Failed: lint, tests");+ fireEvent.click(screen.getByTestId("git-next-action"));+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/actions/runs/9");+ });++ it("opens a pull request for a pushed branch that has none", async () => {+ answer = withCheckout({ ahead: 0 }, { ahead: 0, pull_requests: [], ci: noCi });+ render(<GitOverviewTab />);+ expect((await screen.findByTestId("git-next")).dataset.step).toBe("open_pr");+ fireEvent.click(screen.getByTestId("git-next-action"));+ await vi.waitFor(() => expect(posted("branch/pull-request")).toEqual([{ workspace_id: "w1", branch: "", title: "", draft: false }]));+ await vi.waitFor(() => expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/pull/11"));+ });++ it("says so when there is nothing to do", async () => {+ answer = { ...withCheckout({ branch: "main", upstream: "origin/main", ahead: 0 }), branch: "main", branches: [branch("main", { current: true })], remote_branches: [] };+ render(<GitOverviewTab />);+ const next = await screen.findByTestId("git-next");+ expect(next.dataset.step).toBe("done");+ expect(next.textContent).toContain("Everything is up to date");+ expect(screen.queryByTestId("git-next-action")).toBeNull();+ expect(screen.getByTestId("git-sync-sentence").textContent).toBe("In sync with origin/main.");+ expect(screen.getByTestId("git-all-clear")).toBeTruthy();+ });++ it("flags commits on GitHub that were not fetched yet, and fetches them", async () => {+ answer = withCheckout({ ahead: 0 }, { ahead: 0, unfetched: true });+ render(<GitOverviewTab />);+ expect((await screen.findByTestId("git-next")).dataset.step).toBe("fetch");+ expect(screen.getByTestId("git-sync-sentence").textContent).toContain("GitHub has newer commits that are not fetched yet.");+ fireEvent.click(screen.getByTestId("git-next-action"));+ await vi.waitFor(() => expect(posted("fetch")).toEqual([{ folder: "/code/app" }]));+ });++ it("paints the last overview at once when the tab is reopened", async () => {+ const first = render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ first.unmount();+ let release: () => void = () => {};+ gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ render(<GitOverviewTab />);+ // No answer has arrived yet, and the tab is already complete.+ expect(screen.queryByTestId("git-loading")).toBeNull();+ expect(screen.getByTestId("git-current-branch").textContent).toBe("feature/wip");+ expect(rowNames()).toContain("main");+ release();+ });++ it("shows the tab's shape while the very first answer loads", async () => {+ let release: () => void = () => {};+ gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ render(<GitOverviewTab />);+ expect(screen.getByTestId("git-loading")).toBeTruthy();+ release();+ expect(await screen.findByTestId("git-status")).toBeTruthy();+ });++ it("still works against a backend from before the control center", async () => {+ const { checkout: _checkout, base_ref: _base, ...old } = OVERVIEW;+ answer = old;+ render(<GitOverviewTab />);+ expect(await screen.findByTestId("git-older-backend")).toBeTruthy();+ expect(screen.getByTestId("git-sync-push").dataset.count).toBe("2");+ expect(screen.queryByTestId("git-working-tree")).toBeNull();+ expect(rowNames()).toContain("main");+ });+});++describe("GitOverviewTab — what needs attention", () => {+ it("lists problems across the repository, worst first", async () => {+ const failing = { ...noCi, state: "failure" as const, total: 4, passed: 3, failed: 1, names: ["lint"], url: "https://github.com/o/r/actions/runs/3" };+ answer = {+ ...OVERVIEW,+ branches: [...OVERVIEW.branches, branch("wip/local", { upstream: "", on_github: false }), branch("feature/stale", { behind: 4 })],+ pull_requests: [pr(12, "open", failing), pr(13, "open", noCi, { conflicting: true }), pr(7, "open")],+ };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",- "only-remote",+ const items = await screen.findAllByTestId("git-attention-item");+ expect(items.map((el) => el.dataset.kind)).toEqual(["ci_failing", "pr_conflicts", "unpushed", "behind", "cleanup"]);+ expect(items[0].textContent).toContain("CI is failing on 1 pull request");+ expect(items[0].textContent).toContain("#12");+ expect(items[2].textContent).toContain("1 branch has commits only on this computer");+ // "Show" narrows the branch list to what has to be pushed — the checked-out branch included.+ fireEvent.click(items[2]);+ expect(rowNames()).toEqual(["feature/wip", "wip/local"]);+ fireEvent.click(items[3]);+ expect(rowNames()).toEqual(["feature/stale"]);+ });++ it("lists every open pull request with its CI, the broken ones first", async () => {+ const failing = { ...noCi, state: "failure" as const, total: 4, passed: 3, failed: 1, names: ["lint"], url: "https://github.com/o/r/actions/runs/3" };+ answer = {+ ...OVERVIEW,+ pull_requests: [pr(12, "open", failing, { head: "feature/broken", review: "changes_requested" }), pr(7, "open", noCi, { review: "approved" })],+ };+ render(<GitOverviewTab />);+ const rows = await screen.findAllByTestId("git-pr-row");+ expect(rows.map((el) => el.dataset.number)).toEqual(["12", "7"]);+ expect(rows[0].textContent).toContain("feature/broken");+ // Into the default branch is the rule and goes unsaid.+ expect(rows[0].textContent).not.toContain("→ main");+ expect(rows[0].textContent).toContain("changes requested");+ expect(rows[1].textContent).toContain("approved");+ expect(within(rows[0]).getByTestId("git-ci").querySelector("[data-ci-state]")?.getAttribute("data-ci-state")).toBe("failure");+ fireEvent.click(within(rows[0]).getByTestId("git-pr-open"));+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/pull/12");+ });++ it("removes merged branches only after showing which, and reports what was kept", async () => {+ answer = {+ ...OVERVIEW,+ branches: [...OVERVIEW.branches, branch("feature/old", { merged_into: [{ target: "main", via: "git", number: null, url: "" }], worktree: "/code/trees/old" })],+ };+ refusals["branch/delete"] = [[422, { message: "old has 1 uncommitted change. Remove it anyway?", code: "dirty" }]];+ // Strict mode on purpose: its mount, unmount, mount must not leave the run stopped.+ render(+ <StrictMode>+ <GitOverviewTab />+ </StrictMode>,+ );+ const item = (await screen.findAllByTestId("git-attention-item")).find((el) => el.dataset.kind === "cleanup")!;+ expect(item.textContent).toContain("2 merged branches can be removed");+ fireEvent.click(item);+ const dialog = await screen.findByTestId("git-cleanup");+ expect(dialog.textContent).toContain("Remove 2 merged branches?");+ expect(within(dialog).getAllByTestId("git-cleanup-pick").map((el) => el.dataset.branch)).toEqual(["feature/done", "feature/old"]);+ expect(posts).toEqual([]); // nothing happens before the confirmation+ fireEvent.click(within(dialog).getByTestId("git-cleanup-ok"));+ await vi.waitFor(() => expect(screen.getByTestId("git-cleanup").dataset.phase).toBe("done"));+ // Never forced: the worktree with uncommitted work stayed, and the dialog says why.+ expect(posted("branch/delete")).toEqual([+ { workspace_id: "w1", branch: "feature/done", force: false, remote: false, with_worktree: false },+ { workspace_id: "w1", branch: "feature/old", force: false, remote: false, with_worktree: true },]);+ expect(screen.getByTestId("git-cleanup").textContent).toContain("Removed 1 branch");+ expect(screen.getByTestId("git-cleanup-kept").textContent).toContain("uncommitted change");+ });++ it("lets a merged branch be unticked before the cleanup", async () => {+ render(<GitOverviewTab />);+ fireEvent.click((await screen.findAllByTestId("git-attention-item")).find((el) => el.dataset.kind === "cleanup")!);+ const dialog = await screen.findByTestId("git-cleanup");+ fireEvent.click(within(dialog).getByTestId("git-cleanup-pick"));+ expect((within(dialog).getByTestId("git-cleanup-ok") as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(within(dialog).getByTestId("git-cleanup-cancel"));+ expect(screen.queryByTestId("git-cleanup")).toBeNull();+ expect(posts).toEqual([]);+ });+});++describe("GitOverviewTab — branches", () => {+ it("lists the workspace's branches and marks the checked-out one", async () => {+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ expect(rowNames()).toEqual(["feature/wip", "main", "feature/done", "feature/queued", "feature/draft", "feature/dropped"]);expect(row("feature/wip").dataset.current).toBe("true");+ expect(within(row("feature/wip")).getByTestId("git-current-tag")).toBeTruthy();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");});@@ -212,9 +480,9 @@ describe("GitOverviewTab", () => {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-fact-merged").textContent).toBe("merged into 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("main")).queryByTestId("git-fact-merged")).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.@@ -239,92 +507,27 @@ describe("GitOverviewTab", () => {expect(tip.textContent).toContain("lint");});- it("lists GitHub-only branches, folds them on request, and forces a GitHub read on refresh", async () => {- render(<GitOverviewTab />);- await screen.findAllByTestId("git-branch-row");- expect(row("only-remote")).toBeTruthy();- fireEvent.click(screen.getByTestId("git-remote-toggle"));- expect(screen.queryAllByTestId("git-branch-row").some((el) => el.dataset.branch === "only-remote")).toBe(false);- 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");- });-- it("asks once which GitHub repository the folder is, recommending its remote", async () => {- answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };- render(<GitOverviewTab />);- // The recommendation is clickable at once; the rest of the list follows.- await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));- const choices = screen.getAllByTestId("git-repo-choice");- expect(choices.map((el) => el.dataset.repo)).toEqual(["o/r", "octo/other"]);- expect(choices[0].textContent).toContain("Recommended");- expect(screen.getByTestId("git-repo-picker").textContent).toContain("Connect a GitHub repository");- fireEvent.click(choices[0]);- await vi.waitFor(() => expect(puts).toEqual([JSON.stringify({ workspace_id: "w1", repo: "o/r" })]));- expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(7);- expect(screen.queryByTestId("git-repo-picker")).toBeNull();- });-- it("leaves the picker at once after a pick, while GitHub is still being read", async () => {- answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };- render(<GitOverviewTab />);- await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));- let release: () => void = () => {};- gate = new Promise<void>((resolve) => {- release = resolve;- });- fireEvent.click(screen.getAllByTestId("git-repo-choice")[0]);- // The local branches and the choice show before GitHub has answered.- expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(7);- expect(screen.queryByTestId("git-repo-picker")).toBeNull();- const state = screen.getByTestId("git-github-state");- expect(state.textContent).toContain("o/r");- expect(state.textContent).toContain("Reading pull requests and CI from GitHub");- release();- await vi.waitFor(() => expect(screen.getByTestId("git-github-state").textContent).toContain("GitHub status from"));- });-- it("reopens the pick from the repository name to change it", async () => {- render(<GitOverviewTab />);- fireEvent.click(await screen.findByTestId("git-bound-repo"));- await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));- fireEvent.click(screen.getByLabelText("Keep the current repository"));- expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(7);- });-- it("offers to connect GitHub and still lists the local branches", async () => {- answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "not_connected", repo: "" } };- render(<GitOverviewTab />);- expect(await screen.findByTestId("git-connect-github")).toBeTruthy();- expect(screen.getAllByTestId("git-branch-row")).toHaveLength(7);- fireEvent.click(screen.getByText("Connect GitHub"));- expect(useEventStore.getState().activeSection).toBe("plugins");- });-- it("opens a branch on GitHub from its icon, and leaves unpushed branches inert", async () => {- answer = { ...OVERVIEW, branches: [...OVERVIEW.branches, branch("wip/local", { upstream: "", on_github: false })] };- render(<GitOverviewTab />);- await screen.findAllByTestId("git-branch-row");- fireEvent.click(within(row("feature/done")).getByTestId("git-branch-link"));- expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/tree/feature/done");- expect(within(row("wip/local")).getByTestId("git-branch-link").tagName).toBe("SPAN");- });-- it("marks every branch as local only, local and on GitHub, or GitHub only", async () => {- answer = { ...OVERVIEW, branches: [...OVERVIEW.branches, branch("wip/local", { upstream: "", on_github: false })] };+ it("says in words what each branch has to push or pull, and where it lives", async () => {+ answer = {+ ...OVERVIEW,+ branches: [+ ...OVERVIEW.branches,+ branch("wip/local", { upstream: "", on_github: false }),+ branch("feature/both", { ahead: 3, behind: 1, worktree: "/code/trees/both" }),+ branch("feature/gone", { upstream_gone: true }),+ ],+ };render(<GitOverviewTab />);await screen.findAllByTestId("git-branch-row");- const location = (name: string) => within(row(name)).getByTestId("git-location");- expect(location("wip/local").dataset.location).toBe("local");- expect(location("wip/local").textContent).toBe("local only");- expect(location("main").dataset.location).toBe("both");- expect(location("main").textContent).toBe("local + GitHub");- expect(location("only-remote").dataset.location).toBe("github_only");+ expect(within(row("wip/local")).getByTestId("git-fact-local").textContent).toBe("local only");+ expect(row("wip/local").dataset.sync).toBe("unpublished");+ expect(within(row("feature/both")).getByTestId("git-fact-push").textContent).toBe("3 to push");+ expect(within(row("feature/both")).getByTestId("git-fact-pull").textContent).toBe("1 to pull");+ expect(within(row("feature/both")).getByTestId("git-worktree")).toBeTruthy();+ expect(within(row("feature/gone")).getByTestId("git-fact-gone").textContent).toBe("remote deleted");+ // A branch in sync says nothing about syncing at all.+ expect(within(row("main")).queryByTestId("git-fact-push")).toBeNull();+ expect(within(row("main")).queryByTestId("git-fact-local")).toBeNull();});it("shows when each branch last changed", async () => {@@ -339,12 +542,52 @@ describe("GitOverviewTab", () => {};render(<GitOverviewTab />);await screen.findAllByTestId("git-branch-row");- const date = (name: string) => within(row(name)).queryByTestId("git-commit-date")?.textContent;+ const date = (name: string) => within(row(name)).queryByTestId("git-fact-date")?.textContent;expect(date("fresh")).toBe("2 hr. ago");expect(date("old")).toBe("Mar 3, 2024");expect(date("undated")).toBeUndefined();});+ it("draws a long list a page at a time", async () => {+ answer = { ...OVERVIEW, branches: Array.from({ length: 45 }, (_, index) => branch(`feature/n${index}`)), remote_branches: [] };+ render(<GitOverviewTab />);+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(20);+ expect(screen.getByTestId("git-branches-more").textContent).toContain("Show 20 more (25 left)");+ fireEvent.click(screen.getByTestId("git-branches-more"));+ expect(screen.getAllByTestId("git-branch-row")).toHaveLength(40);+ // Searching looks through every branch, not only the ones drawn.+ fireEvent.change(screen.getByTestId("git-search"), { target: { value: "n44" } });+ expect(rowNames()).toEqual(["feature/n44"]);+ });++ it("keeps GitHub-only branches folded until asked, and fetches on refresh", async () => {+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ expect(rowNames()).not.toContain("only-remote");+ fireEvent.click(screen.getByTestId("git-remote-toggle"));+ expect(rowNames()).toContain("only-remote");+ fireEvent.click(screen.getByTestId("git-refresh"));+ await vi.waitFor(() => expect(posted("fetch")).toEqual([{ folder: "/code/app" }]));+ await vi.waitFor(() => expect(calls.some((url) => url.includes("refresh=true"))).toBe(true));+ });++ it("narrows the list by search and by filter", async () => {+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ fireEvent.click(screen.getByTestId("git-filter-failing"));+ expect(rowNames()).toEqual(["feature/dropped"]);+ fireEvent.click(screen.getByTestId("git-filter-merged"));+ expect(rowNames()).toEqual(["feature/done"]);+ fireEvent.click(screen.getByTestId("git-filter-all"));+ fireEvent.change(screen.getByTestId("git-search"), { target: { value: "#9" } });+ expect(rowNames()).toEqual(["feature/draft"]);+ // A search also finds branches that exist only on GitHub.+ fireEvent.change(screen.getByTestId("git-search"), { target: { value: "only-rem" } });+ expect(rowNames()).toEqual(["only-remote"]);+ fireEvent.change(screen.getByTestId("git-search"), { target: { value: "nothing-like-this" } });+ expect(screen.getByTestId("git-filter-empty")).toBeTruthy();+ });+it("folds a clicked branch open with its local folder and its GitHub page", async () => {answer = { ...OVERVIEW, branches: [...OVERVIEW.branches, branch("wip/local", { upstream: "", on_github: false })] };render(<GitOverviewTab />);@@ -363,13 +606,14 @@ describe("GitOverviewTab", () => {expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/tree/feature/wip");fireEvent.click(within(details).getByTestId("git-open-pr"));expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/pull/7");+ expect(within(details).getByTestId("git-branch-base").textContent).toBe("1 ahead of origin/main, 0 behind");- // Not checked out anywhere: nothing local to open, the switch command instead; not on GitHub either.+ // Not checked out anywhere: nothing local to open, a switch instead; not on GitHub either.fireEvent.click(within(row("wip/local")).getByTestId("git-branch-toggle"));const local = within(row("wip/local")).getByTestId("git-branch-details");await within(local).findByTestId("git-branch-commits");expect(within(local).queryByTestId("git-open-folder")).toBeNull();- expect(within(local).getByTestId("git-copy-switch")).toBeTruthy();+ expect(within(local).getByTestId("git-act-switch").textContent).toBe("Switch to it");expect(within(local).queryByTestId("git-open-github")).toBeNull();// The branch is readable in place: its commits and files, each file's diff one click away.@@ -393,6 +637,98 @@ describe("GitOverviewTab", () => {expect(within(row("feature/wip")).queryByTestId("git-branch-details")).toBeNull();});+ it("acts on a branch from its details: switch, publish, update", async () => {+ answer = {+ ...OVERVIEW,+ branches: [...OVERVIEW.branches, branch("wip/local", { upstream: "", on_github: false }), branch("feature/stale", { behind: 4 })],+ };+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ fireEvent.click(within(row("wip/local")).getByTestId("git-branch-toggle"));+ const local = within(row("wip/local")).getByTestId("git-branch-details");+ expect(within(local).getByTestId("git-act-push").textContent).toBe("Publish");+ fireEvent.click(within(local).getByTestId("git-act-push"));+ await vi.waitFor(() => expect(posted("branch/push")).toEqual([{ workspace_id: "w1", branch: "wip/local" }]));+ await vi.waitFor(() => expect((within(local).getByTestId("git-act-switch") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(within(local).getByTestId("git-act-switch"));+ await vi.waitFor(() => expect(posted("switch")).toEqual([{ workspace_id: "w1", branch: "wip/local" }]));++ fireEvent.click(within(row("feature/stale")).getByTestId("git-branch-toggle"));+ const stale = within(row("feature/stale")).getByTestId("git-branch-details");+ await vi.waitFor(() => expect((within(stale).getByTestId("git-act-update") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(within(stale).getByTestId("git-act-update"));+ await vi.waitFor(() => expect(posted("branch/update")).toEqual([{ workspace_id: "w1", branch: "feature/stale" }]));+ // The branch the person is on, and the default branch, cannot be deleted from here.+ fireEvent.click(within(row("main")).getByTestId("git-branch-toggle"));+ expect(within(row("main")).queryByTestId("git-act-delete")).toBeNull();+ });++ it("deletes a branch only after a confirmation, and asks again before losing commits", async () => {+ refusals["branch/delete"] = [[422, { message: "feature/draft has 2 commits that exist nowhere else. Delete it anyway?", code: "unmerged" }]];+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ fireEvent.click(within(row("feature/draft")).getByTestId("git-branch-toggle"));+ fireEvent.click(within(row("feature/draft")).getByTestId("git-act-delete"));+ const first = await screen.findByTestId("git-confirm");+ expect(first.textContent).toContain("Delete feature/draft?");+ expect(posts).toEqual([]); // the click alone deleted nothing+ fireEvent.click(within(first).getByTestId("git-confirm-ok"));+ await vi.waitFor(() =>+ expect(posted("branch/delete")).toEqual([{ workspace_id: "w1", branch: "feature/draft", force: false, remote: false, with_worktree: false }]),+ );+ // The backend found commits that exist nowhere else: a second, explicit question.+ const second = await screen.findByText("feature/draft holds work that exists nowhere else");+ expect(second).toBeTruthy();+ expect(screen.getByTestId("git-confirm").textContent).toContain("Deleting it loses those commits for good.");+ fireEvent.click(screen.getByTestId("git-confirm-ok"));+ await vi.waitFor(() => expect(posted("branch/delete")[1]).toEqual({ workspace_id: "w1", branch: "feature/draft", force: true, remote: false, with_worktree: false }));+ });++ it("can delete the branch on GitHub too, when asked", async () => {+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ fireEvent.click(within(row("feature/queued")).getByTestId("git-branch-more"));+ fireEvent.click(within(await screen.findByTestId("git-branch-menu")).getByTestId("git-menu-delete"));+ const dialog = await screen.findByTestId("git-confirm");+ fireEvent.click(within(dialog).getByTestId("git-confirm-remote"));+ fireEvent.click(within(dialog).getByTestId("git-confirm-ok"));+ await vi.waitFor(() => expect(posted("branch/delete")[0]).toMatchObject({ branch: "feature/queued", remote: true }));+ });++ it("asks about the GitHub copy again, unticked, before deleting work that exists nowhere else", async () => {+ refusals["branch/delete"] = [[422, { message: "feature/queued has 1 commit that exist nowhere else.", code: "unmerged" }]];+ render(<GitOverviewTab />);+ await screen.findAllByTestId("git-branch-row");+ fireEvent.click(within(row("feature/queued")).getByTestId("git-branch-more"));+ fireEvent.click(within(await screen.findByTestId("git-branch-menu")).getByTestId("git-menu-delete"));+ const first = await screen.findByTestId("git-confirm");+ fireEvent.click(within(first).getByTestId("git-confirm-remote"));+ fireEvent.click(within(first).getByTestId("git-confirm-ok"));+ await screen.findByText("feature/queued holds work that exists nowhere else");+ // The earlier tick is not carried over silently: this dialog decides for itself.+ expect((screen.getByTestId("git-confirm-remote") as HTMLInputElement).checked).toBe(false);+ fireEvent.click(screen.getByTestId("git-confirm-ok"));+ await vi.waitFor(() => expect(posted("branch/delete")).toHaveLength(2));+ expect(posted("branch/delete")[0]).toMatchObject({ force: false, remote: true });+ expect(posted("branch/delete")[1]).toMatchObject({ force: true, remote: false });+ });++ it("drops a half-written commit and an open question when another workspace is shown", async () => {+ answer = withCheckout({ ahead: 0, files: 3, unstaged: 2, untracked: 1 }, { ahead: 0 });+ render(<GitOverviewTab />);+ fireEvent.click(await screen.findByTestId("git-next-action"));+ fireEvent.change(screen.getByTestId("git-commit-message"), { target: { value: "meant for the first workspace" } });+ fireEvent.click(within(row("feature/draft")).getByTestId("git-branch-toggle"));+ fireEvent.click(within(row("feature/draft")).getByTestId("git-act-delete"));+ expect(await screen.findByTestId("git-confirm")).toBeTruthy();+ useIdeChatStore.setState({ workspace: { id: "w2", name: "Other", path: "/code/other" }, stagedPane: null });+ answer = { ...withCheckout({ ahead: 0, files: 3, unstaged: 2, untracked: 1 }, { ahead: 0 }), root: "/code/other" };+ await vi.waitFor(() => expect(calls.some((url) => url.includes("workspace_id=w2"))).toBe(true));+ await vi.waitFor(() => expect(screen.queryByTestId("git-confirm")).toBeNull());+ expect(screen.queryByTestId("git-commit-form")).toBeNull();+ expect(posts).toEqual([]);+ });+it("offers GitHub pages and copies from a branch's menu", async () => {render(<GitOverviewTab />);await screen.findAllByTestId("git-branch-row");@@ -410,17 +746,67 @@ describe("GitOverviewTab", () => {fireEvent.click(within(second).getByTestId("git-menu-create-pr"));expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/compare/main...feature/done?expand=1");});+});- it("narrows the list by search and by filter", async () => {+describe("GitOverviewTab — connecting", () => {+ 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 />);- await screen.findAllByTestId("git-branch-row");- fireEvent.click(screen.getByTestId("git-filter-failing"));- expect(screen.getAllByTestId("git-branch-row").map((el) => el.dataset.branch)).toEqual(["feature/dropped"]);- fireEvent.click(screen.getByTestId("git-filter-all"));- fireEvent.change(screen.getByTestId("git-search"), { target: { value: "#9" } });- expect(screen.getAllByTestId("git-branch-row").map((el) => el.dataset.branch)).toEqual(["feature/draft"]);- fireEvent.change(screen.getByTestId("git-search"), { target: { value: "nothing-like-this" } });- expect(screen.getByTestId("git-filter-empty")).toBeTruthy();+ expect((await screen.findByTestId("git-unavailable")).textContent).toContain("not a git repository");+ });++ it("asks once which GitHub repository the folder is, recommending its remote", async () => {+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };+ render(<GitOverviewTab />);+ // The recommendation is clickable at once; the rest of the list follows.+ await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));+ const choices = screen.getAllByTestId("git-repo-choice");+ expect(choices.map((el) => el.dataset.repo)).toEqual(["o/r", "octo/other"]);+ expect(choices[0].textContent).toContain("Recommended");+ expect(screen.getByTestId("git-repo-picker").textContent).toContain("Connect a GitHub repository");+ fireEvent.click(choices[0]);+ await vi.waitFor(() => expect(puts).toEqual([JSON.stringify({ workspace_id: "w1", repo: "o/r" })]));+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);+ expect(screen.queryByTestId("git-repo-picker")).toBeNull();+ });++ it("leaves the picker at once after a pick, while GitHub is still being read", async () => {+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };+ render(<GitOverviewTab />);+ await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));+ let release: () => void = () => {};+ gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ fireEvent.click(screen.getAllByTestId("git-repo-choice")[0]);+ // The local branches and the choice show before GitHub has answered.+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);+ expect(screen.queryByTestId("git-repo-picker")).toBeNull();+ const state = screen.getByTestId("git-github-state");+ expect(state.textContent).toContain("o/r");+ expect(state.textContent).toContain("Reading pull requests and CI from GitHub");+ release();+ await vi.waitFor(() => expect(screen.getByTestId("git-github-state").textContent).toContain("fetched 2 min. ago"));+ });++ it("reopens the pick from the repository name to change it", async () => {+ render(<GitOverviewTab />);+ fireEvent.click(await screen.findByTestId("git-bound-repo"));+ await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));+ fireEvent.click(screen.getByLabelText("Keep the current repository"));+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);+ });++ it("offers to connect GitHub and still shows the local state", async () => {+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "not_connected", repo: "" } };+ render(<GitOverviewTab />);+ expect(await screen.findByTestId("git-connect-github")).toBeTruthy();+ expect(screen.getAllByTestId("git-branch-row")).toHaveLength(6);+ expect(screen.getByTestId("git-sync-push").dataset.count).toBe("2");+ // Pull requests are GitHub's: without a connection there is no such list.+ expect(screen.queryByTestId("git-section-prs")).toBeNull();+ fireEvent.click(screen.getByText("Connect GitHub"));+ expect(useEventStore.getState().activeSection).toBe("plugins");});it("asks for one restart when the running backend does not know the route yet", async () => {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.tsxindex 203a85f95e..5b7a77109d 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx@@ -1,145 +1,69 @@-import { useCallback, useEffect, useMemo, useState, type ReactNode, type SVGProps } from "react";-import {- ChevronDown,- ChevronRight,- CircleCheck,- CircleDashed,- CircleDot,- CircleHelp,- CircleX,- CirclePlay,- Copy,- Ellipsis,- ExternalLink,- FolderGit2,- FolderOpen,- GitBranch,- GitMerge,- GitPullRequest,- GitPullRequestClosed,- GitPullRequestDraft,- Globe,- Laptop,- Loader2,- RefreshCw,- Search,- SquareTerminal,- X,- type LucideIcon,-} from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { ExternalLink, FolderGit2, Loader2, RefreshCw } from "lucide-react";import { fill, useT } from "@/i18n";import { useRunLocale } from "@/components/runs/format";-import { robustCopy } from "@/lib/clipboard";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 { BranchMenu, branchUrl } from "./BranchMenu";-import { DiffView } from "../explorer/DiffView";+import { useIdeSidePanelStore } from "@/store/ideSidePanel";+import { AttentionList } from "./AttentionList";+import { BranchList } from "./BranchList";+import { BranchMenu } from "./BranchMenu";+import { CleanupDialog } from "./CleanupDialog";+import { ConfirmDialog } from "./ConfirmDialog";+import { agoLabel, LinkIcon } from "./gitBadges";import { ConnectGitHubCard, GitHubRepoPicker } from "./GitHubRepoPicker";-import {- fetchBranchEditors,- fetchGitOverview,- GitOverviewError,- openBranchCheckout,- fetchBranchContents,- fetchBranchFileDiff,- type BranchContents,- type BranchEditors,- type BranchFile,- type BranchFileDiff,- type BranchRow,- type CiState,- type CiStatus,- type PullRequest,- type PullRequestState,- type RepoOverview,-} from "./gitOverviewApi";+import { attention, canCleanUp, checkoutOf, openPullRequests, type AttentionItem, type BranchFilter } from "./gitInsights";+import { fetchBranchEditors, fetchGitOverview, GitOverviewError, type BranchEditors, type BranchRow, type RepoOverview } from "./gitOverviewApi";+import { PullRequestList } from "./PullRequestList";+import { Section } from "./Section";+import { StatusPanel } from "./StatusPanel";+import { useGitActions } from "./useGitActions";/**- * 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.+ * An unchanged repository answers a poll with one `git status`; 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;-/** While GitHub's first read is still loading, the local branches are already shown and this re-asks soon. */+/** While GitHub is being read (the first time, or again after an action), the local state is already shown and this re-asks soon. */const POLL_LOADING_MS = 1_500;-// 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",-};+/**+ * The last overview per workspace. Reopening the tab paints it at once and+ * refreshes behind it, instead of starting from a spinner every time.+ */+const LAST_OVERVIEW = new Map<string, RepoOverview>();-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 />;+/** Forget every remembered overview (tests start from an empty tab). */+export function resetGitOverviewCache(): void {+ LAST_OVERVIEW.clear();}function useGitOverview(workspaceId: string | null) {- const [data, setData] = useState<RepoOverview | null>(null);+ const [data, setData] = useState<RepoOverview | null>(() => (workspaceId ? (LAST_OVERVIEW.get(workspaceId) ?? null) : null));const [error, setError] = useState("");const [routeMissing, setRouteMissing] = useState(false);const [loading, setLoading] = useState(false);- const [force, setForce] = useState(0);+ const [round, setRound] = useState(0);+ // Set by refresh(), used up by the next read: a later workspace switch is an ordinary read again.+ const forceNext = useRef(false);+ const shown = useRef(workspaceId);useEffect(() => {- setData(null);+ if (shown.current === workspaceId) return;+ shown.current = workspaceId;+ setData(workspaceId ? (LAST_OVERVIEW.get(workspaceId) ?? null) : null);setError("");}, [workspaceId]);useEffect(() => {if (!workspaceId) return;let alive = true;let timer: number | undefined;- let refresh = force > 0;+ let refresh = forceNext.current;+ forceNext.current = false;let githubLoading = false;const tick = async () => {if (useEventStore.getState().activeSection === "agentic-ide") {@@ -147,7 +71,8 @@ function useGitOverview(workspaceId: string | null) {try {const next = await fetchGitOverview(workspaceId, refresh);refresh = false;- githubLoading = next.github?.code === "loading";+ githubLoading = next.github?.code === "loading" || Boolean(next.github?.refreshing);+ LAST_OVERVIEW.set(workspaceId, next);if (alive) {setData(next);setError("");@@ -171,730 +96,28 @@ function useGitOverview(workspaceId: string | null) {alive = false;window.clearTimeout(timer);};- }, [workspaceId, force]);- return { data, error, routeMissing, 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>- );- })}- </>- );-}--type BranchLocation = "local" | "both" | "github_only";--function branchLocation(row: BranchRow): BranchLocation {- if (row.remote_only) return "github_only";- return row.upstream || row.on_github ? "both" : "local";-}--// Where the branch lives, one icon per place: a laptop for this computer, a-// globe for GitHub. Amber while it is only here — nothing backs it up yet.-const LOCATION_STYLE: Record<BranchLocation, { local: boolean; github: boolean; text: string; chip: string }> = {- local: { local: true, github: false, text: "text-warning", chip: "border-warning/40 bg-warning/10" },- both: { local: true, github: true, text: "text-info", chip: "border-info/35 bg-info/10" },- github_only: { local: false, github: true, text: "text-muted-foreground", chip: "border-border bg-muted/40" },-};--const LOCATION_LABEL: Record<BranchLocation, string> = { local: "local_only", both: "both", github_only: "github_only" };--function LocationChip({ row }: { row: BranchRow }) {- const t = useT();- const location = branchLocation(row);- const style = LOCATION_STYLE[location];- const label = LOCATION_LABEL[location];- return (- <QuickTooltip content={t(`ide_side_panel.git.${label}_tip`)} side="bottom" className="inline-flex shrink-0">- <span- data-testid="git-location"- data-location={location}- className={cn("inline-flex items-center gap-1 rounded-full border px-1.5 py-px text-[10.5px] font-medium leading-none", style.chip, style.text)}- >- {style.local && <Laptop className="h-3 w-3 shrink-0" aria-hidden />}- {style.github && <Globe className="h-3 w-3 shrink-0" aria-hidden />}- {t(`ide_side_panel.git.${label}`)}- </span>- </QuickTooltip>- );-}--/** Today's commits read "3 hours ago"; older ones show the day ("3 Oct", plus the year when it differs). */-function commitDateLabel(seconds: number, lang: string, now = Date.now()): string {- const date = new Date(seconds * 1000);- const elapsed = Math.max(0, now - date.getTime());- if (elapsed < 24 * 3_600_000) {- const relative = new Intl.RelativeTimeFormat(lang, { numeric: "auto", style: "short" });- if (elapsed < 3_600_000) return relative.format(-Math.max(1, Math.round(elapsed / 60_000)), "minute");- return relative.format(-Math.round(elapsed / 3_600_000), "hour");- }- const sameYear = date.getFullYear() === new Date(now).getFullYear();- return new Intl.DateTimeFormat(lang, { day: "numeric", month: "short", ...(sameYear ? {} : { year: "numeric" }) }).format(date);-}--function CommitDate({ seconds }: { seconds: number }) {- const t = useT();- const lang = useRunLocale();- if (!seconds) return null;- const full = new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" }).format(new Date(seconds * 1000));- return (- <QuickTooltip content={fill(t("ide_side_panel.git.last_commit"), { date: full })} side="bottom" className="inline-flex shrink-0">- <span data-testid="git-commit-date" className="tabular-nums">- {commitDateLabel(seconds, lang)}- </span>- </QuickTooltip>- );-}--function DetailButton({- icon: Icon,- label,- testId,- primary,- onClick,-}: {- icon: LucideIcon | ((props: SVGProps<SVGSVGElement>) => ReactNode);- label: string;- testId: string;- primary?: boolean;- onClick: () => void;-}) {- return (- <button- type="button"- data-testid={testId}- onClick={onClick}- className={cn(- "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border px-2 text-[11.5px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- primary- ? "border-primary/40 bg-primary/10 text-foreground hover:bg-primary/15"- : "border-border/70 text-foreground/90 hover:bg-secondary",- )}- >- <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />- <span className="truncate">{label}</span>- </button>- );-}--/** A file's change as one coloured letter, like the Explorer's change list. */-const FILE_STATUS: Record<BranchFile["status"], { letter: string; tone: string }> = {- added: { letter: "A", tone: "text-success" },- deleted: { letter: "D", tone: "text-destructive" },- modified: { letter: "M", tone: "text-warning" },-};--function BranchFileRow({- file,- workspaceId,- branch,- base,- remote,-}: {- file: BranchFile;- workspaceId: string;- branch: string;- base: string;- remote: boolean;-}) {- const t = useT();- const [open, setOpen] = useState(false);- const [diff, setDiff] = useState<BranchFileDiff | null>(null);- const [error, setError] = useState("");- useEffect(() => {- if (!open || diff) return;- let alive = true;- fetchBranchFileDiff(workspaceId, branch, base, remote, file.path)- .then((answer) => alive && setDiff(answer))- .catch((err: Error) => alive && setError(err.message));- return () => {- alive = false;- };- }, [open, diff, workspaceId, branch, base, remote, file.path]);- const status = FILE_STATUS[file.status];- const slash = file.path.lastIndexOf("/");- return (- <li data-testid="git-branch-file" data-path={file.path}>- <button- type="button"- aria-expanded={open}- onClick={() => setOpen((value) => !value)}- className="flex w-full min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <ChevronRight className={cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")} aria-hidden />- <span className={cn("w-3 shrink-0 text-center font-mono text-[10.5px] font-semibold", status.tone)}>{status.letter}</span>- <span className="min-w-0 flex-1 truncate font-mono text-[11px]">- <span className="text-foreground">{file.path.slice(slash + 1)}</span>- {slash > 0 && <span className="ml-1.5 text-muted-foreground">{file.path.slice(0, slash)}</span>}- </span>- {file.added === null ? (- <span className="shrink-0 text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.binary")}</span>- ) : (- <span className="shrink-0 font-mono text-[10.5px] tabular-nums">- <span className="text-success">+{file.added}</span> <span className="text-destructive">−{file.removed}</span>- </span>- )}- </button>- {open && (- <div data-testid="git-branch-file-diff" className="my-1 max-h-96 overflow-auto rounded-md border border-border/60 bg-background">- {error ? (- <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>- ) : !diff ? (- <p className="flex items-center gap-1.5 px-3 py-2 text-[11px] text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />- {t("ide_side_panel.git.details.loading")}- </p>- ) : diff.binary ? (- <p className="px-3 py-2 text-[11px] text-muted-foreground">{t("ide_side_panel.git.details.binary")}</p>- ) : (- <DiffView hunks={diff.hunks} />- )}- </div>- )}- </li>- );-}--function DetailHeading({ children }: { children: ReactNode }) {- return <h4 className="text-[10.5px] font-semibold uppercase tracking-wide text-muted-foreground">{children}</h4>;-}--/**- * What a clicked branch row folds open: the branch itself — its own commits- * and the files it changes, each file's diff one click away — plus one row of- * ways out (an editor, the folder, GitHub, the pull request).- */-function BranchDetails({- row,- repoUrl,- defaultBranch,- workspaceId,- editors,-}: {- row: BranchRow;- repoUrl: string;- defaultBranch: string;- workspaceId: string;- editors: BranchEditors | null;-}) {- const t = useT();- const lang = useRunLocale();- const pushToast = useEventStore((state) => state.pushToast);- const [contents, setContents] = useState<BranchContents | null>(null);- const [error, setError] = useState("");- useEffect(() => {- let alive = true;- fetchBranchContents(workspaceId, row.name, defaultBranch, row.remote_only)- .then((answer) => alive && setContents(answer))- .catch((err: Error) => alive && setError(err.message));- return () => {- alive = false;- };- // Re-read when the branch tip moves, not on every overview poll.- }, [workspaceId, row.name, row.head, row.remote_only, defaultBranch]);-- const url = branchUrl(repoUrl, row);- const checkedOut = !row.remote_only && (row.current || Boolean(row.worktree));- const pr = row.pull_requests[0];- const canOpen = checkedOut && Boolean(editors?.file_manager);-- const openLocal = (target: string) => {- void openBranchCheckout(workspaceId, row.name, target)- .then((result) => {- if (!result.opened) pushToast("error", t("ide_side_panel.git.details.open_failed"));- })- .catch((err: Error) => pushToast("error", err.message || t("ide_side_panel.git.details.open_failed")));- };- const copy = (text: string) => {- void robustCopy(text).then((ok) =>- pushToast(ok ? "success" : "error", ok ? fill(t("ide_side_panel.git.menu.copied"), { text }) : t("ide_side_panel.git.menu.copy_failed")),- );- };-- const where = row.remote_only- ? t("ide_side_panel.git.details.local_absent")- : row.current- ? t("ide_side_panel.git.current")- : row.worktree- ? `${t("ide_side_panel.git.details.local_worktree")} ${row.worktree}`- : t("ide_side_panel.git.details.local_branch_only");- const dateOf = (seconds: number) =>- seconds ? new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" }).format(new Date(seconds * 1000)) : "";-- return (- <div data-testid="git-branch-details" className="space-y-3 border-t border-border/50 pb-3 pl-8 pr-3 pt-2.5 text-[11.5px]">- <div className="flex flex-wrap gap-1.5">- {canOpen &&- editors?.editors.map((editor) => (- <DetailButton- key={editor.id}- icon={SquareTerminal}- label={fill(t("ide_side_panel.git.details.open_in"), { editor: editor.label })}- testId={`git-open-${editor.id}`}- onClick={() => openLocal(editor.id)}- />- ))}- {canOpen && (- <DetailButton icon={FolderOpen} label={t("ide_side_panel.git.details.open_folder")} testId="git-open-folder" onClick={() => openLocal("folder")} />- )}- {!checkedOut && !row.remote_only && (- <DetailButton icon={Copy} label={t("ide_side_panel.git.menu.copy_switch")} testId="git-copy-switch" onClick={() => copy(`git switch ${row.name}`)} />- )}- {url && <DetailButton icon={Globe} label={t("ide_side_panel.git.details.open_github")} testId="git-open-github" onClick={() => void openExternalUrl(url)} />}- {pr && (- <DetailButton- icon={PR_ICON[pr.state]}- label={fill(t("ide_side_panel.git.menu.open_pr"), { number: pr.number })}- testId="git-open-pr"- onClick={() => void openExternalUrl(pr.url)}- />- )}- {row.ci.url && (- <DetailButton icon={CirclePlay} label={t("ide_side_panel.git.menu.open_ci")} testId="git-open-ci" onClick={() => void openExternalUrl(row.ci.url)} />- )}- </div>-- <p className="text-[11px] text-muted-foreground">- <Laptop className="mr-1 inline h-3 w-3 align-[-2px]" aria-hidden />- <span className="break-all">{where}</span>- {row.upstream && (- <span className="block pl-4">{fill(t("ide_side_panel.git.tracks"), { upstream: row.upstream, ahead: row.ahead, behind: row.behind })}</span>- )}- </p>-- {error ? (- <p className="text-[11px] text-destructive">{error}</p>- ) : !contents ? (- <p data-testid="git-branch-loading" className="flex items-center gap-1.5 text-[11px] text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />- {t("ide_side_panel.git.details.loading")}- </p>- ) : !contents.available ? (- <p className="text-[11px] text-muted-foreground">{contents.reason}</p>- ) : (- <>- <section data-testid="git-branch-commits" className="space-y-1">- <DetailHeading>- {contents.base- ? fill(t("ide_side_panel.git.details.commits_vs"), { n: contents.commits.length, base: contents.base })- : fill(t("ide_side_panel.git.details.commits_latest"), { n: contents.commits.length })}- </DetailHeading>- {contents.commits.length === 0 ? (- <p className="text-[11px] text-muted-foreground">{fill(t("ide_side_panel.git.details.no_commits"), { base: contents.base })}</p>- ) : (- <ol className="space-y-0.5">- {contents.commits.map((commit) => (- <li key={commit.sha} data-testid="git-branch-commit" data-sha={commit.sha} className="flex min-w-0 items-baseline gap-2">- {/* Only a commit GitHub has gets a link; one still only here would open a 404. */}- {repoUrl && commit.on_github ? (- <button- type="button"- data-testid="git-commit-link"- onClick={() => void openExternalUrl(`${repoUrl}/commit/${encodeURIComponent(commit.sha)}`)}- className="shrink-0 font-mono text-[10.5px] text-info hover:underline"- >- {commit.sha.slice(0, 7)}- </button>- ) : commit.on_github === false ? (- <QuickTooltip content={t("ide_side_panel.git.local_only_tip")} side="bottom" className="inline-flex shrink-0">- <span data-testid="git-commit-local" className="inline-flex items-center gap-1 font-mono text-[10.5px] text-warning">- <Laptop className="h-3 w-3" aria-hidden />- {commit.sha.slice(0, 7)}- </span>- </QuickTooltip>- ) : (- // An older backend does not say where the commit is: no link, no claim.- <span className="shrink-0 font-mono text-[10.5px] text-muted-foreground">{commit.sha.slice(0, 7)}</span>- )}- <QuickTooltip content={`${commit.subject}\n${commit.author} · ${dateOf(commit.committed_at)}`} side="bottom" className="flex min-w-0 flex-1">- <span className="truncate text-foreground">{commit.subject}</span>- </QuickTooltip>- <span className="shrink-0 text-[10.5px] tabular-nums text-muted-foreground">- {commit.committed_at ? commitDateLabel(commit.committed_at, lang) : ""}- </span>- </li>- ))}- </ol>- )}- {contents.commits_truncated && <p className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.more_commits")}</p>}- </section>- {contents.base && (- <section data-testid="git-branch-files" className="space-y-1">- <DetailHeading>{fill(t("ide_side_panel.git.details.files"), { n: contents.files.length })}</DetailHeading>- <ul>- {contents.files.map((file) => (- <BranchFileRow- key={file.path}- file={file}- workspaceId={workspaceId}- branch={row.name}- base={defaultBranch}- remote={row.remote_only}- />- ))}- </ul>- {contents.files_truncated && <p className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.more_files")}</p>}- </section>- )}- </>- )}- </div>- );+ }, [workspaceId, round]);+ const refresh = useCallback(() => {+ forceNext.current = true;+ setRound((value) => value + 1);+ }, []);+ return { data, error, routeMissing, loading, refresh };}-function BranchLine({- row,- isDefault,- repoUrl,- defaultBranch,- workspaceId,- editors,- menuOpen,- onMenu,- expanded,- onToggle,-}: {- row: BranchRow;- isDefault: boolean;- repoUrl: string;- defaultBranch: string;- workspaceId: string;- editors: BranchEditors | null;- menuOpen: boolean;- onMenu: (row: BranchRow, x: number, y: number) => void;- expanded: boolean;- onToggle: (name: string) => void;-}) {- 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 }));+async function restartApp(pushToast: (kind: "warning" | "error", text: string) => void, t: (key: string) => string): Promise<boolean> {+ try {+ const response = await fetch("/api/settings/restart-app", { method: "POST" });+ if (response.status === 409) {+ pushToast("warning", t("topbar.restart_missions_running"));+ return false;+ }+ if (!response.ok) throw new Error(`restart-failed:${response.status}`);+ // The window closes and relaunches; the button stays busy until then.+ return true;+ } catch {+ pushToast("error", t("permissions.restart_failed"));+ return false;}- 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;- const url = branchUrl(repoUrl, row);- const openTip = fill(t("ide_side_panel.git.open_branch"), { branch: row.name });- return (- <li- data-testid="git-branch-row"- data-branch={row.name}- data-current={row.current || undefined}- data-expanded={expanded || undefined}- onContextMenu={(event) => {- event.preventDefault();- onMenu(row, event.clientX, event.clientY);- }}- className={cn(row.current && "bg-accent/10", expanded && "bg-secondary/30")}- >- <div className={cn("group/row flex min-h-9 items-center gap-1 py-1 pl-2 pr-1", menuOpen && "bg-secondary/60")}>- <LinkIcon url={url} tip={url ? openTip : nameTip} label={url ? openTip : row.name} testId="git-branch-link">- <BranchIcon className={cn("h-4 w-4 shrink-0", row.current ? "text-accent" : "text-muted-foreground")} aria-hidden />- </LinkIcon>- <button- type="button"- data-testid="git-branch-toggle"- aria-expanded={expanded}- onClick={() => onToggle(row.name)}- className="flex min-w-0 flex-1 flex-col rounded-md text-left leading-tight focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <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>- <span className="mt-0.5 flex min-w-0 items-center gap-2 text-[10.5px] text-muted-foreground">- <LocationChip row={row} />- <CommitDate seconds={row.committed_at} />- <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>}- </span>- </button>- <PullRequestBadge prs={row.pull_requests} />- <CiBadge ci={row.ci} stale={row.ci_stale} />- <QuickTooltip content={t("ide_side_panel.git.more")} side="bottom" className="inline-flex shrink-0">- <button- type="button"- data-testid="git-branch-more"- data-branch-menu-anchor- aria-label={fill(t("ide_side_panel.git.menu.aria"), { branch: row.name })}- aria-haspopup="menu"- aria-expanded={menuOpen}- onClick={(event) => {- const rect = event.currentTarget.getBoundingClientRect();- onMenu(row, rect.right - 264, rect.bottom + 4);- }}- className={cn(- "inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground opacity-0 hover:bg-secondary hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/row:opacity-100",- menuOpen && "bg-secondary text-foreground opacity-100",- )}- >- <Ellipsis className="h-4 w-4" aria-hidden />- </button>- </QuickTooltip>- <ChevronDown- className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", expanded && "rotate-180")}- aria-hidden- />- </div>- {expanded && (- <BranchDetails row={row} repoUrl={repoUrl} defaultBranch={defaultBranch} workspaceId={workspaceId} editors={editors} />- )}- </li>- );-}--type BranchFilter = "all" | "pr" | "failing" | "unmerged" | "local";-const BRANCH_FILTERS: BranchFilter[] = ["all", "pr", "failing", "unmerged", "local"];--function matchesFilter(row: BranchRow, filter: BranchFilter): boolean {- if (filter === "pr") return row.pull_requests.some((pr) => pr.state !== "merged" && pr.state !== "closed");- if (filter === "failing") return row.ci.state === "failure";- if (filter === "unmerged") return row.merged_into.length === 0;- if (filter === "local") return !row.remote_only && !row.upstream && !row.on_github;- return true;-}--function matchesQuery(row: BranchRow, query: string): boolean {- if (!query) return true;- const needle = query.toLowerCase().replace(/^#/, "");- return (- row.name.toLowerCase().includes(needle) ||- row.pull_requests.some((pr) => String(pr.number) === needle || pr.title.toLowerCase().includes(needle))- );-}--/** Search by name or pull request, and narrow the list to what needs a look. */-function BranchFilterBar({- query,- onQuery,- filter,- onFilter,- counts,-}: {- query: string;- onQuery: (value: string) => void;- filter: BranchFilter;- onFilter: (value: BranchFilter) => void;- counts: Record<BranchFilter, number>;-}) {- const t = useT();- return (- <div data-testid="git-filter-bar" className="shrink-0 space-y-1.5 border-b border-border/60 px-3 py-2">- <label className="flex h-7 items-center gap-1.5 rounded-md border border-border/70 bg-background px-2 focus-within:ring-2 focus-within:ring-ring">- <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />- <input- data-testid="git-search"- value={query}- onChange={(event) => onQuery(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Escape" && query) {- event.stopPropagation();- onQuery("");- }- }}- placeholder={t("ide_side_panel.git.search")}- aria-label={t("ide_side_panel.git.search")}- className="min-w-0 flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted-foreground"- />- {query && (- <button- type="button"- aria-label={t("ide_side_panel.git.search_clear")}- onClick={() => onQuery("")}- className="inline-flex h-4 w-4 items-center justify-center rounded text-muted-foreground hover:text-foreground"- >- <X className="h-3 w-3" aria-hidden />- </button>- )}- </label>- <div role="group" aria-label={t("ide_side_panel.git.filter_aria")} className="flex flex-wrap gap-1">- {BRANCH_FILTERS.map((value) => (- <button- key={value}- type="button"- data-testid={`git-filter-${value}`}- aria-pressed={filter === value}- onClick={() => onFilter(value)}- className={cn(- "inline-flex h-6 items-center gap-1 rounded-full border px-2 text-[11px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- filter === value- ? "border-primary/40 bg-primary/10 text-foreground"- : "border-border/70 text-muted-foreground hover:bg-secondary hover:text-foreground",- )}- >- {t(`ide_side_panel.git.filter.${value}`)}- <span className="tabular-nums text-muted-foreground">{counts[value]}</span>- </button>- ))}- </div>- </div>- );-}--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>- {(["local", "both", "github_only"] as const).map((location) => (- <li key={location} className="flex items-center gap-1.5">- <span className={cn("inline-flex items-center gap-0.5", LOCATION_STYLE[location].text)}>- {LOCATION_STYLE[location].local && <Laptop className="h-3.5 w-3.5" aria-hidden />}- {LOCATION_STYLE[location].github && <Globe className="h-3.5 w-3.5" aria-hidden />}- </span>- {t(`ide_side_panel.git.${LOCATION_LABEL[location]}_tip`)}- </li>- ))}- </ul>- </div>- );}/**@@ -909,19 +132,7 @@ function RestartToConnectCard() {const restart = async () => {if (restarting) return;setRestarting(true);- try {- const response = await fetch("/api/settings/restart-app", { method: "POST" });- if (response.status === 409) {- pushToast("warning", t("topbar.restart_missions_running"));- setRestarting(false);- return;- }- if (!response.ok) throw new Error(`restart-failed:${response.status}`);- // The window closes and relaunches; the button stays busy until then.- } catch {- pushToast("error", t("permissions.restart_failed"));- setRestarting(false);- }+ if (!(await restartApp(pushToast, t))) setRestarting(false);};return (<div data-testid="git-error" className="mx-3 my-3 space-y-2 rounded-lg border border-border/60 bg-muted/30 p-3">@@ -941,37 +152,70 @@ function RestartToConnectCard() {);}-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 backend answers, but is older than the control center: say so in one line. */+function OlderBackendNote() {+ const t = useT();+ const pushToast = useEventStore((state) => state.pushToast);+ const [restarting, setRestarting] = useState(false);+ return (+ <p data-testid="git-older-backend" className="flex items-center gap-2 border-b border-border/60 px-3 py-2 text-[11px] text-muted-foreground">+ <span className="min-w-0 flex-1">{t("ide_side_panel.git.older_backend")}</span>+ <button+ type="button"+ disabled={restarting}+ onClick={() => {+ setRestarting(true);+ void restartApp(pushToast, t).then((ok) => !ok && setRestarting(false));+ }}+ className="shrink-0 rounded text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ {t("ide_side_panel.git.restart_button")}+ </button>+ </p>+ );+}++/** Quiet placeholder blocks in the shape of the tab, while the first answer loads. */+function LoadingShape() {+ const t = useT();+ const bar = "rounded bg-secondary motion-safe:animate-pulse";+ return (+ <div data-testid="git-loading" role="status" aria-label={t("ide_side_panel.git.loading")} className="space-y-3 px-3 py-3">+ <div className={cn(bar, "h-4 w-40")} />+ <div className={cn(bar, "h-11 w-full")} />+ <div className={cn(bar, "h-12 w-full")} />+ {[0, 1, 2, 3].map((index) => (+ <div key={index} className="space-y-1.5 pt-1">+ <div className={cn(bar, "h-3 w-3/5")} />+ <div className={cn(bar, "h-2.5 w-2/5")} />+ </div>+ ))}+ </div>+ );}/**- * 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.+ * The Git tab: the state of the open workspace's repository at a glance. On+ * top, the checkout the person is in — who is ahead, what is uncommitted, the+ * one next step. Below it what needs a look across the repository, every open+ * pull request with its CI, and every branch. What matters can be done here.*/export function GitOverviewTab() {const t = useT();+ const lang = useRunLocale();const workspace = useIdeChatStore((state) => state.workspace);const workspaceId = workspace?.id ?? null;const { data, error, routeMissing, loading, refresh } = useGitOverview(workspaceId);- // GitHub-only branches show by default; the header still folds them away.- const [showRemote, setShowRemote] = useState(true);- const [showLegend, setShowLegend] = useState(false);- const [query, setQuery] = useState("");+ // Fetch and commit name the workspace's own folder; everything else names the workspace.+ const actions = useGitActions(workspaceId ?? "", workspace?.path ?? "", data?.branch ?? "", refresh);const [filter, setFilter] = useState<BranchFilter>("all");+ const [open, setOpen] = useState({ prs: true, branches: true });const [menu, setMenu] = useState<{ row: BranchRow; x: number; y: number } | null>(null);- const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());+ const [cleaning, setCleaning] = useState<BranchRow[] | null>(null);+ const [alsoRemote, setAlsoRemote] = useState(false);const [editors, setEditors] = useState<BranchEditors | null>(null);- const toggleRow = useCallback((name: string) => {- setExpanded((current) => {- const next = new Set(current);- if (!next.delete(name)) next.add(name);- return next;- });- }, []);+ const prsRef = useRef<HTMLDivElement>(null);+ const branchesRef = useRef<HTMLDivElement>(null);useEffect(() => {let alive = true;fetchBranchEditors()@@ -983,7 +227,7 @@ export function GitOverviewTab() {};}, []);const openMenu = useCallback((row: BranchRow, x: number, y: number) => {- setMenu((current) => (current?.row.name === row.name ? null : { row, x, y }));+ setMenu((current) => (current?.row.name === row.name && current.row.remote_only === row.remote_only ? null : { row, x, y }));}, []);const closeMenu = useCallback(() => setMenu(null), []);// Reopened from the repository chip to change an earlier choice.@@ -996,22 +240,14 @@ export function GitOverviewTab() {useEffect(() => setChanging(false), [workspaceId]);useEffect(() => setPickedRepo(""), [data, workspaceId]);useEffect(() => {- setQuery("");setFilter("all");setMenu(null);- setExpanded(new Set());+ setCleaning(null);}, [workspaceId]);- const allRows = useMemo(() => [...(data?.branches ?? []), ...(data?.remote_branches ?? [])], [data]);- const trimmed = query.trim();- const counts = useMemo(() => {- const result = {} as Record<BranchFilter, number>;- for (const value of BRANCH_FILTERS) {- result[value] = allRows.filter((row) => matchesFilter(row, value) && matchesQuery(row, trimmed)).length;- }- return result;- }, [allRows, trimmed]);- const narrowed = filter !== "all" || trimmed !== "";- const visible = (rows: BranchRow[]) => rows.filter((row) => matchesFilter(row, filter) && matchesQuery(row, trimmed));+ useEffect(() => setAlsoRemote(false), [actions.confirmation]);++ const items = useMemo(() => (data?.available ? attention(data) : []), [data]);+ const prs = useMemo(() => (data?.available ? openPullRequests(data) : []), [data]);if (!workspace) {return <p className="px-4 py-6 text-center text-xs text-muted-foreground">{t("ide_side_panel.git.no_workspace")}</p>;@@ -1022,86 +258,96 @@ export function GitOverviewTab() {);const boundRepo = pickedRepo || github?.repo || "";const repoName = (data?.root || workspace.path).replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? workspace.name;+ const checkout = data?.available ? checkoutOf(data) : null;+ const fetching = actions.busy === "fetch";++ const reveal = (section: "prs" | "branches") => {+ setOpen((current) => ({ ...current, [section]: true }));+ const target = section === "prs" ? prsRef : branchesRef;+ // After the section has opened.+ window.setTimeout(() => target.current?.scrollIntoView?.({ block: "start", behavior: "smooth" }), 0);+ };+ const onAttention = (item: AttentionItem) => {+ if (!data) return;+ const fallback = data.branches.find((row) => row.name === data.default_branch);+ if (item.kind === "cleanup") return setCleaning(data.branches.filter((row) => canCleanUp(row, data.default_branch)));+ if (item.kind === "default_ci") return void (fallback?.ci.url && openExternalUrl(fallback.ci.url));+ if (item.kind === "default_behind") {+ return fallback && fallback.behind > 0 ? actions.update(fallback.name) : void actions.fetch();+ }+ if (item.kind === "unpushed" || item.kind === "behind") {+ setFilter(item.kind);+ return reveal("branches");+ }+ return reveal("prs");+ };+ const syncNow = () => {+ // Fetch first, so "to pull" counts what the remote has now; a repository without a remote just re-reads.+ if (checkout?.has_remote && data?.checkout) void actions.fetch();+ else refresh();+ };+ const fetched = checkout?.last_fetch ? fill(t("ide_side_panel.git.fetched"), { when: agoLabel(checkout.last_fetch, lang, t) }) : "";+ const refreshTip = [+ t("ide_side_panel.git.refresh"),+ github?.available ? fill(t("ide_side_panel.git.github_updated"), { when: agoLabel(github.fetched_at, lang, t) }) : "",+ ]+ .filter(Boolean)+ .join("\n");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="shrink-0 border-b border-border/60 px-3 pb-2 pt-2.5"><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">+ <QuickTooltip content={refreshTip} side="bottom" className="inline-flex"><buttontype="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"+ disabled={actions.busy !== ""}+ onClick={syncNow}+ 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 disabled:opacity-60">- <RefreshCw className={cn("h-3.5 w-3.5", loading && "animate-spin motion-reduce:animate-none")} aria-hidden />+ <RefreshCw className={cn("h-3.5 w-3.5", (loading || fetching || github?.refreshing) && "animate-spin motion-reduce:animate-none")} aria-hidden /></button></QuickTooltip></span></div>- {boundRepo && (+ {(boundRepo || fetched) && (<p data-testid="git-github-state" className="flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground">- <QuickTooltip content={t("ide_side_panel.git.change_repo")} side="bottom" className="inline-flex min-w-0">- <button- type="button"- data-testid="git-bound-repo"- onClick={() => setChanging(true)}- className="inline-flex min-w-0 items-center gap-1 rounded px-0.5 font-mono text-foreground/80 hover:bg-secondary hover:text-foreground"- >- <span className="truncate">{boundRepo}</span>- </button>- </QuickTooltip>- <span aria-hidden>·</span>+ {boundRepo && (+ <QuickTooltip content={t("ide_side_panel.git.change_repo")} side="bottom" className="inline-flex min-w-0">+ <button+ type="button"+ data-testid="git-bound-repo"+ onClick={() => setChanging(true)}+ className="inline-flex min-w-0 items-center gap-1 rounded px-0.5 font-mono text-foreground/80 hover:bg-secondary hover:text-foreground"+ >+ <span className="truncate">{boundRepo}</span>+ </button>+ </QuickTooltip>+ )}+ {boundRepo && <span aria-hidden>·</span>}<span className="min-w-0 truncate">- {pickedRepo- ? t("ide_side_panel.git.github_reading")- : github?.available- ? fill(t("ide_side_panel.git.github_updated"), { when: sinceLabel(t, github.fetched_at) })- : github?.reason}+ {fetching+ ? t("ide_side_panel.git.fetching")+ : pickedRepo || github?.code === "loading"+ ? t("ide_side_panel.git.github_reading")+ : boundRepo && github && !github.available+ ? github.reason+ : fetched || t("ide_side_panel.git.never_fetched")}</span></p>)}</div>- {showLegend && (- <div className="shrink-0 border-b border-border/60 pt-2">- <Legend />- </div>- )}- {!picking && data?.available && allRows.length > 0 && (- <BranchFilterBar query={query} onQuery={setQuery} filter={filter} onFilter={setFilter} counts={counts} />- )}+{picking && data && workspaceId ? (<GitHubRepoPickerkey={workspaceId}@@ -1116,94 +362,68 @@ export function GitOverviewTab() {onCancel={github?.repo ? () => setChanging(false) : undefined}/>) : (- <div className="min-h-0 flex-1 overflow-y-auto py-1">- {github?.code === "not_connected" && <ConnectGitHubCard />}- {!data ? (- error ? (- routeMissing ? (- <RestartToConnectCard />+ <div className="min-h-0 flex-1 overflow-y-auto">+ {!data ? (+ error ? (+ routeMissing ? (+ <RestartToConnectCard />+ ) : (+ <p data-testid="git-error" className="px-4 py-6 text-center text-xs text-destructive">+ {error}+ </p>+ )) : (- <p data-testid="git-error" className="px-4 py-6 text-center text-xs text-destructive">- {error}- </p>+ <LoadingShape />)- ) : (- <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")}+ ) : !data.available ? (+ <p data-testid="git-unavailable" className="px-4 py-6 text-center text-xs text-muted-foreground">+ {data.reason}</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")}>- {visible(data.branches).map((row) => (- <BranchLine- key={row.name}- row={row}- isDefault={row.name === data.default_branch}- repoUrl={github?.repo_url ?? ""}- defaultBranch={data.default_branch}- workspaceId={workspace.id}- editors={editors}- menuOpen={menu?.row.name === row.name}- onMenu={openMenu}- expanded={expanded.has(row.name)}- onToggle={toggleRow}- />- ))}- </ul>- {narrowed && counts[filter] === 0 && (- <p data-testid="git-filter-empty" className="px-4 py-6 text-center text-xs text-muted-foreground">- {t("ide_side_panel.git.filter_empty")}- </p>- )}- {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>- )}- {visible(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 || narrowed}- 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"+ ) : (+ <>+ {!data.checkout && <OlderBackendNote />}+ <StatusPanel key={workspace.id} overview={data} actions={actions} onOpenChanges={() => useIdeSidePanelStore.getState().openTab("changes")} />+ {github?.code === "not_connected" && <ConnectGitHubCard />}+ <AttentionList items={items} onAct={onAttention} />+ {github?.available && (+ <div ref={prsRef}>+ <Section+ id="prs"+ title={t("ide_side_panel.git.prs.title")}+ count={prs.length}+ open={open.prs}+ onToggle={() => setOpen((current) => ({ ...current, prs: !current.prs }))}+ >+ <PullRequestList prs={prs} defaultBranch={data.default_branch} />+ </Section>+ </div>+ )}+ <div ref={branchesRef}>+ <Section+ id="branches"+ title={t("ide_side_panel.git.branches")}+ count={data.branches.length}+ open={open.branches}+ onToggle={() => setOpen((current) => ({ ...current, branches: !current.branches }))}>- <ChevronRight className={cn("h-3.5 w-3.5 transition-transform", (showRemote || narrowed) && "rotate-90")} aria-hidden />- {fill(t("ide_side_panel.git.remote_only"), { n: visible(data.remote_branches).length })}- </button>- {(showRemote || narrowed) && (- <ul aria-label={fill(t("ide_side_panel.git.remote_only"), { n: visible(data.remote_branches).length })}>- {visible(data.remote_branches).map((row) => (- <BranchLine- key={row.name}- row={row}- isDefault={false}- repoUrl={github?.repo_url ?? ""}- defaultBranch={data.default_branch}- workspaceId={workspace.id}- editors={editors}- menuOpen={menu?.row.name === row.name}- onMenu={openMenu}- expanded={expanded.has(`remote:${row.name}`)}- onToggle={() => toggleRow(`remote:${row.name}`)}- />- ))}- </ul>- )}+ <BranchList+ overview={data}+ workspaceId={workspace.id}+ editors={editors}+ actions={actions}+ filter={filter}+ onFilter={setFilter}+ menuBranch={menu ? `${menu.row.remote_only ? "remote:" : ""}${menu.row.name}` : ""}+ onMenu={openMenu}+ />+ </Section></div>- )}- {error && <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>}- </>- )}- </div>+ {error && <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>}+ </>+ )}+ </div>)}+{menu && data && (<BranchMenurow={menu.row}@@ -1211,9 +431,47 @@ export function GitOverviewTab() {defaultBranch={data.default_branch}x={menu.x}y={menu.y}+ actions={data.checkout ? actions : undefined}onDismiss={closeMenu}/>)}+ {actions.confirmation && (+ <ConfirmDialog+ title={actions.confirmation.title}+ body={actions.confirmation.body}+ confirmLabel={actions.confirmation.confirmLabel}+ busy={actions.busy !== ""}+ onCancel={actions.dismiss}+ onConfirm={() => {+ const pending = actions.confirmation;+ actions.dismiss();+ void pending?.run({ remote: alsoRemote });+ }}+ >+ {actions.confirmation.remoteOption && (+ <label className="mt-3 flex cursor-pointer items-center gap-2 text-xs text-foreground">+ <input+ type="checkbox"+ data-testid="git-confirm-remote"+ checked={alsoRemote}+ onChange={(event) => setAlsoRemote(event.target.checked)}+ className="h-3.5 w-3.5 accent-[hsl(var(--accent))]"+ />+ {t("ide_side_panel.git.confirm.delete_remote")}+ </label>+ )}+ </ConfirmDialog>+ )}+ {cleaning && data && (+ <CleanupDialog+ rows={cleaning}+ workspaceId={workspace.id}+ onClose={(changed) => {+ setCleaning(null);+ if (changed) refresh();+ }}+ />+ )}</section>);}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/PullRequestList.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/PullRequestList.tsxnew file mode 100644index 0000000000..65afbc449f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/PullRequestList.tsx@@ -0,0 +1,84 @@+import { useState } from "react";+import { fill, useT } from "@/i18n";+import { useRunLocale } from "@/components/runs/format";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";+import { QuickTooltip } from "@/components/ui/tooltip";+import { agoLabel, CiBadge, PR_ICON, PR_TONE, prStateLabel } from "./gitBadges";+import type { PullRequest } from "./gitOverviewApi";+import { ShowMore } from "./Section";++/** Drawn before "show all": enough to see everything that is broken. */+const FIRST_PAGE = 6;++function updatedSeconds(pr: PullRequest): number {+ const stamp = Date.parse(pr.updated_at);+ return Number.isFinite(stamp) ? Math.floor(stamp / 1000) : 0;+}++function PullRequestRow({ pr, defaultBranch }: { pr: PullRequest; defaultBranch: string }) {+ const t = useT();+ const lang = useRunLocale();+ const Icon = PR_ICON[pr.state];+ // Into the default branch is the rule; only another target is worth the space.+ const facts: { text: string; tone?: string }[] = [{ text: pr.base === defaultBranch ? pr.head : `${pr.head} → ${pr.base}` }];+ if (pr.conflicting) facts.push({ text: t("ide_side_panel.git.prs.conflicts"), tone: "text-destructive" });+ if (pr.review === "changes_requested") facts.push({ text: t("ide_side_panel.git.prs.changes_requested"), tone: "text-destructive" });+ if (pr.review === "approved") facts.push({ text: t("ide_side_panel.git.prs.approved"), tone: "text-success" });+ if (pr.review === "review_required") facts.push({ text: t("ide_side_panel.git.prs.review_required") });+ if (pr.fork && pr.author) facts.push({ text: fill(t("ide_side_panel.git.prs.from_fork"), { author: pr.author }) });+ const updated = updatedSeconds(pr);+ if (updated) facts.push({ text: agoLabel(updated, lang, t) });+ return (+ <li data-testid="git-pr-row" data-number={pr.number} data-state={pr.state} className="flex min-h-[38px] items-center gap-1 pl-3 pr-1 hover:bg-secondary/40">+ <button+ type="button"+ data-testid="git-pr-open"+ onClick={() => void openExternalUrl(pr.url)}+ className="flex min-w-0 flex-1 items-start gap-2 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ >+ <QuickTooltip content={prStateLabel(t, pr)} side="bottom" className="mt-0.5 inline-flex shrink-0">+ <Icon className={cn("h-3.5 w-3.5", PR_TONE[pr.state])} aria-hidden />+ </QuickTooltip>+ <span className="min-w-0 flex-1 leading-tight">+ <span className="flex min-w-0 items-baseline gap-1.5">+ <span className={cn("shrink-0 font-mono text-[11px] tabular-nums", PR_TONE[pr.state])}>#{pr.number}</span>+ <span className="truncate text-[12.5px] text-foreground">{pr.title}</span>+ </span>+ {/* Too narrow for everything: the age at the end is what gets cut. */}+ <span className="mt-0.5 flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap text-[10.5px] text-muted-foreground">+ {facts.map((fact, index) => (+ <span key={fact.text} className={cn(index === 0 ? "min-w-[4rem] truncate font-mono" : "shrink-0", fact.tone)}>+ {index > 0 && <span className="mr-1.5 text-muted-foreground/60" aria-hidden>·</span>}+ {fact.text}+ </span>+ ))}+ </span>+ </span>+ </button>+ <CiBadge ci={pr.ci} />+ </li>+ );+}++/** Every open pull request, what is broken first; a click opens it on GitHub. */+export function PullRequestList({ prs, defaultBranch }: { prs: PullRequest[]; defaultBranch: string }) {+ const t = useT();+ const [all, setAll] = useState(false);+ if (prs.length === 0) {+ return <p data-testid="git-prs-empty" className="px-3 pb-2.5 text-[11.5px] text-muted-foreground">{t("ide_side_panel.git.prs.none")}</p>;+ }+ const shown = all ? prs : prs.slice(0, FIRST_PAGE);+ return (+ <>+ <ul aria-label={t("ide_side_panel.git.prs.title")} className="pb-1">+ {shown.map((pr) => (+ <PullRequestRow key={pr.number} pr={pr} defaultBranch={defaultBranch} />+ ))}+ </ul>+ {prs.length > shown.length && (+ <ShowMore testId="git-prs-more" label={fill(t("ide_side_panel.git.show_all"), { n: prs.length })} onClick={() => setAll(true)} />+ )}+ </>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/Section.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/Section.tsxnew file mode 100644index 0000000000..2758ab7d77--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/Section.tsx@@ -0,0 +1,60 @@+import type { ReactNode } from "react";+import { ChevronRight } from "lucide-react";+import { cn } from "@/lib/utils";++/** One titled block of the Git tab; the heading folds it. */+export function Section({+ id,+ title,+ count,+ open,+ onToggle,+ aside,+ children,+}: {+ id: string;+ title: string;+ count?: number;+ open: boolean;+ onToggle: () => void;+ /** Sits at the heading's right edge (a small action). */+ aside?: ReactNode;+ children: ReactNode;+}) {+ return (+ <section data-testid={`git-section-${id}`} data-open={open || undefined} className="border-b border-border/60">+ <div className="flex h-8 items-center pr-2">+ <button+ type="button"+ data-testid={`git-section-toggle-${id}`}+ aria-expanded={open}+ onClick={onToggle}+ className="flex h-full min-w-0 flex-1 items-center gap-1 pl-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ >+ <ChevronRight+ className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform motion-reduce:transition-none", open && "rotate-90")}+ aria-hidden+ />+ <span className="truncate text-[10.5px] font-semibold uppercase tracking-wider text-muted-foreground">{title}</span>+ {count !== undefined && <span className="shrink-0 text-[10.5px] tabular-nums text-muted-foreground/70">{count}</span>}+ </button>+ {aside}+ </div>+ {open && children}+ </section>+ );+}++/** "Show 20 more" under a list that is longer than it is useful to draw at once. */+export function ShowMore({ label, onClick, testId }: { label: string; onClick: () => void; testId: string }) {+ return (+ <button+ type="button"+ data-testid={testId}+ onClick={onClick}+ className="w-full px-3 py-2 text-left text-[11.5px] text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ >+ {label}+ </button>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/StatusPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/StatusPanel.tsxnew file mode 100644index 0000000000..dba25a7410--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/StatusPanel.tsx@@ -0,0 +1,359 @@+import { useState } from "react";+import { ArrowDown, ArrowUp, Check, CircleAlert, FileDiff, GitBranch, Loader2 } from "lucide-react";+import { fill, useT } from "@/i18n";+import { openExternalUrl } from "@/lib/openExternal";+import { cn } from "@/lib/utils";+import { CiBadge, plural, PullRequestBadge } from "./gitBadges";+import { checkoutOf, nextStep, type NextStep } from "./gitInsights";+import type { RepoOverview } from "./gitOverviewApi";+import type { GitActions } from "./useGitActions";++type Translate = (key: string) => string;++function SyncCell({ direction, count, known }: { direction: "push" | "pull"; count: number; known: boolean }) {+ const t = useT();+ const Icon = direction === "push" ? ArrowUp : ArrowDown;+ const active = known && count > 0;+ return (+ <div data-testid={`git-sync-${direction}`} data-count={known ? count : undefined} className="flex items-center gap-2 bg-background px-2.5 py-2">+ <Icon className={cn("h-4 w-4 shrink-0", active ? (direction === "push" ? "text-warning" : "text-info") : "text-muted-foreground/50")} aria-hidden />+ <span className={cn("text-lg font-semibold leading-none tabular-nums", active ? "text-foreground" : "text-muted-foreground/60")}>+ {known ? count : "–"}+ </span>+ <span className="min-w-0 truncate text-[11px] text-muted-foreground">{t(`ide_side_panel.git.status.to_${direction}`)}</span>+ </div>+ );+}++/** Who is ahead, in one sentence. */+function syncSentence(t: Translate, overview: RepoOverview): string {+ const checkout = checkoutOf(overview);+ const row = overview.branches.find((branch) => branch.current);+ if (checkout.detached || !checkout.branch) return t("ide_side_panel.git.status.detached");+ if (row?.upstream_gone) return t("ide_side_panel.git.status.gone");+ if (!checkout.upstream) return t(checkout.has_remote ? "ide_side_panel.git.status.unpublished" : "ide_side_panel.git.status.no_remote");+ const upstream = checkout.upstream;+ if (checkout.ahead && checkout.behind) {+ return fill(t("ide_side_panel.git.status.diverged"), { ahead: checkout.ahead, behind: checkout.behind, upstream });+ }+ if (checkout.ahead) return fill(plural(t, "ide_side_panel.git.status.ahead", checkout.ahead), { upstream });+ if (checkout.behind) return fill(plural(t, "ide_side_panel.git.status.behind", checkout.behind), { upstream });+ return fill(t("ide_side_panel.git.status.synced"), { upstream });+}++function workingTree(t: Translate, overview: RepoOverview): { clean: boolean; text: string; detail: string } {+ const checkout = checkoutOf(overview);+ if (checkout.files === 0) return { clean: true, text: t("ide_side_panel.git.status.clean"), detail: "" };+ const parts = [+ checkout.conflicted ? fill(t("ide_side_panel.git.status.n_conflicted"), { n: checkout.conflicted }) : "",+ checkout.staged ? fill(t("ide_side_panel.git.status.n_staged"), { n: checkout.staged }) : "",+ checkout.unstaged ? fill(t("ide_side_panel.git.status.n_modified"), { n: checkout.unstaged }) : "",+ checkout.untracked ? fill(t("ide_side_panel.git.status.n_untracked"), { n: checkout.untracked }) : "",+ ].filter(Boolean);+ return { clean: false, text: plural(t, "ide_side_panel.git.status.changed", checkout.files), detail: parts.join(" · ") };+}++interface StepView {+ title: string;+ reason: string;+ /** The button's label; none when there is nothing to click. */+ action: string;+ tone: "action" | "danger" | "wait" | "done";+}++function describe(t: Translate, step: NextStep, overview: RepoOverview): StepView {+ const upstream = checkoutOf(overview).upstream;+ const key = (name: string) => t(`ide_side_panel.git.next.${name}`);+ switch (step.kind) {+ case "resolve":+ return {+ title: step.operation ? fill(key("resolve_operation"), { operation: step.operation }) : key("resolve"),+ reason: step.conflicts ? plural(t, "ide_side_panel.git.next.resolve_reason", step.conflicts) : key("resolve_reason_none"),+ action: key("open_changes"),+ tone: "danger",+ };+ case "detached":+ return { title: key("detached"), reason: key("detached_reason"), action: "", tone: "wait" };+ case "fetch":+ return { title: key("fetch"), reason: key("fetch_reason"), action: key("fetch_action"), tone: "action" };+ case "pull":+ return {+ title: fill(plural(t, "ide_side_panel.git.next.pull", step.count), { upstream }),+ reason: key("pull_reason"),+ action: key("pull_action"),+ tone: "action",+ };+ case "commit":+ return { title: plural(t, "ide_side_panel.git.next.commit", step.count), reason: key("commit_reason"), action: key("commit_action"), tone: "action" };+ case "rebase":+ return {+ title: fill(key("rebase"), { upstream }),+ reason: fill(key("rebase_reason"), { ahead: step.ahead, behind: step.behind }),+ action: key("rebase_action"),+ tone: "action",+ };+ case "publish":+ return { title: key("publish"), reason: key("publish_reason"), action: key("publish_action"), tone: "action" };+ case "push":+ return { title: fill(plural(t, "ide_side_panel.git.next.push", step.count), { upstream }), reason: key("push_reason"), action: key("push_action"), tone: "action" };+ case "open_pr":+ return {+ title: key("open_pr"),+ reason: fill(key("open_pr_reason"), { base: overview.default_branch }),+ action: key("open_pr_action"),+ tone: "action",+ };+ case "fix_ci":+ return {+ title: step.number ? fill(key("fix_ci_pr"), { number: step.number }) : key("fix_ci"),+ reason: step.names.length ? fill(key("fix_ci_reason"), { names: step.names.join(", ") }) : key("fix_ci_reason_none"),+ action: step.url ? key("view_checks") : "",+ tone: "danger",+ };+ case "fix_conflict":+ return { title: fill(key("fix_conflict"), { number: step.pr.number }), reason: fill(key("fix_conflict_reason"), { base: step.pr.base }), action: key("view_pr"), tone: "danger" };+ case "changes_requested":+ return { title: fill(key("changes_requested"), { number: step.pr.number }), reason: key("changes_requested_reason"), action: key("view_pr"), tone: "danger" };+ case "wait_queue":+ return { title: fill(key("wait_queue"), { number: step.pr.number }), reason: key("wait_queue_reason"), action: key("view_pr"), tone: "wait" };+ case "wait_ci":+ return { title: key("wait_ci"), reason: key("wait_ci_reason"), action: step.url ? key("view_checks") : "", tone: "wait" };+ case "ready":+ return { title: fill(key("ready"), { number: step.pr.number }), reason: key("ready_reason"), action: key("view_pr"), tone: "done" };+ default:+ return { title: key("done"), reason: key("done_reason"), action: "", tone: "done" };+ }+}++function busyKey(step: NextStep): string {+ if (step.kind === "pull" || step.kind === "rebase") return "pull";+ if (step.kind === "push" || step.kind === "publish") return "push:";+ if (step.kind === "open_pr") return "pr:";+ return step.kind;+}++/**+ * The top of the Git tab: the checkout the person is in — who is ahead, what+ * is uncommitted, how its pull request and CI stand — and the one next step,+ * as a button.+ */+export function StatusPanel({+ overview,+ actions,+ onOpenChanges,+}: {+ overview: RepoOverview;+ actions: GitActions;+ onOpenChanges: () => void;+}) {+ const t = useT();+ const checkout = checkoutOf(overview);+ const row = overview.branches.find((branch) => branch.current);+ const step = nextStep(overview);+ const view = describe(t, step, overview);+ const tree = workingTree(t, overview);+ const [composing, setComposing] = useState(false);+ const [message, setMessage] = useState("");+ const tracking = Boolean(checkout.upstream) && !row?.upstream_gone && !checkout.detached;+ const working = actions.busy !== "" && actions.busy === busyKey(step);++ const act = () => {+ switch (step.kind) {+ case "resolve":+ return onOpenChanges();+ case "fetch":+ return void actions.fetch();+ case "pull":+ return actions.pull();+ case "rebase":+ return actions.rebase();+ case "commit":+ return setComposing(true);+ case "publish":+ case "push":+ return actions.push();+ case "open_pr":+ return actions.createPullRequest();+ case "fix_ci":+ case "wait_ci":+ return void openExternalUrl(step.url);+ case "fix_conflict":+ case "changes_requested":+ case "wait_queue":+ case "ready":+ return void openExternalUrl(step.pr.url);+ default:+ return undefined;+ }+ };+ // What else is possible right now, beside the one next step.+ const extras: { id: string; label: string; run: () => void }[] = [];+ if (checkout.files > 0 && step.kind !== "commit" && step.kind !== "resolve" && !checkout.detached) {+ extras.push({ id: "commit", label: t("ide_side_panel.git.next.commit_action"), run: () => setComposing(true) });+ }+ if (tracking && checkout.behind > 0 && step.kind !== "pull" && step.kind !== "rebase" && step.kind !== "resolve") {+ extras.push({ id: "pull", label: t("ide_side_panel.git.next.pull_action"), run: actions.pull });+ }+ if (tracking && checkout.ahead > 0 && checkout.behind === 0 && step.kind !== "push" && step.kind !== "resolve") {+ extras.push({ id: "push", label: t("ide_side_panel.git.next.push_action"), run: () => actions.push() });+ }+ const commit = async () => {+ if (!message.trim()) return;+ if (await actions.commit(message.trim())) {+ setMessage("");+ setComposing(false);+ }+ };++ return (+ <section data-testid="git-status" aria-label={t("ide_side_panel.git.status.aria")} className="shrink-0 border-b border-border/60 px-3 pb-3 pt-2.5">+ <div className="flex min-h-6 items-center gap-1.5">+ <GitBranch className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span data-testid="git-current-branch" className="min-w-0 truncate font-mono text-[13px] font-semibold text-foreground">+ {checkout.detached || !checkout.branch ? overview.head.slice(0, 7) : checkout.branch}+ </span>+ {checkout.branch === overview.default_branch && checkout.branch !== "" && (+ <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>+ )}+ <span className="ml-auto flex shrink-0 items-center">+ {row && <PullRequestBadge prs={row.pull_requests} />}+ {row && <CiBadge ci={row.ci} stale={row.ci_stale} />}+ </span>+ </div>++ <div+ data-testid="git-sync"+ className="mt-2 grid grid-cols-2 gap-px overflow-hidden rounded-lg border border-border/70 bg-border/70"+ >+ <SyncCell direction="push" count={checkout.ahead} known={tracking} />+ <SyncCell direction="pull" count={checkout.behind} known={tracking} />+ </div>+ <p data-testid="git-sync-sentence" className="mt-1.5 text-[11.5px] leading-snug text-muted-foreground">+ {syncSentence(t, overview)}+ {row?.unfetched && <span className="text-info"> {t("ide_side_panel.git.status.unfetched")}</span>}+ </p>++ {overview.checkout && (+ <p data-testid="git-working-tree" data-clean={tree.clean || undefined} className="mt-1.5 flex min-w-0 items-center gap-1.5 text-[11.5px]">+ {tree.clean ? (+ <Check className="h-3.5 w-3.5 shrink-0 text-success" aria-hidden />+ ) : (+ <FileDiff className={cn("h-3.5 w-3.5 shrink-0", checkout.conflicted ? "text-destructive" : "text-warning")} aria-hidden />+ )}+ <span className={cn("shrink-0", tree.clean ? "text-muted-foreground" : "text-foreground")}>{tree.text}</span>+ {tree.detail && <span className="min-w-0 truncate text-muted-foreground">{tree.detail}</span>}+ {!tree.clean && (+ <button+ type="button"+ data-testid="git-review-changes"+ onClick={onOpenChanges}+ className="ml-auto shrink-0 rounded px-1 text-[11px] text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("ide_side_panel.git.status.review")}+ </button>+ )}+ </p>+ )}++ {composing ? (+ <div data-testid="git-commit-form" className="mt-2.5 space-y-1.5 rounded-lg border border-border/70 bg-secondary/40 p-2">+ <textarea+ data-testid="git-commit-message"+ autoFocus+ rows={2}+ value={message}+ onChange={(event) => setMessage(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) void commit();+ if (event.key === "Escape") {+ event.stopPropagation();+ setComposing(false);+ }+ }}+ placeholder={t("ide_side_panel.git.commit.placeholder")}+ aria-label={t("ide_side_panel.git.commit.placeholder")}+ className="w-full resize-none rounded-md border border-border/70 bg-background px-2 py-1.5 text-[12px] text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"+ />+ <p className="text-[10.5px] leading-snug text-muted-foreground">{plural(t, "ide_side_panel.git.commit.scope", checkout.files)}</p>+ <div className="flex justify-end gap-1.5">+ <button+ type="button"+ onClick={() => setComposing(false)}+ className="h-7 rounded-md px-2.5 text-[11.5px] text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("ide_side_panel.git.confirm.cancel")}+ </button>+ <button+ type="button"+ data-testid="git-commit-submit"+ disabled={!message.trim() || actions.busy !== ""}+ onClick={() => void commit()}+ className="inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-2.5 text-[11.5px] font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ {actions.busy === "commit" && <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />}+ {t("ide_side_panel.git.commit.submit")}+ </button>+ </div>+ </div>+ ) : (+ <div+ data-testid="git-next"+ data-step={step.kind}+ className={cn(+ "mt-2.5 flex items-center gap-2 rounded-lg border px-2.5 py-2",+ view.tone === "danger" ? "border-destructive/30 bg-destructive/5" : "border-border/70 bg-secondary/40",+ )}+ >+ {view.tone === "done" ? (+ <Check className="h-4 w-4 shrink-0 text-success" aria-hidden />+ ) : view.tone === "danger" ? (+ <CircleAlert className="h-4 w-4 shrink-0 text-destructive" aria-hidden />+ ) : null}+ <div className="min-w-0 flex-1">+ {view.tone !== "done" && (+ <p className="text-[9.5px] font-semibold uppercase tracking-wider text-muted-foreground">{t("ide_side_panel.git.next.label")}</p>+ )}+ <p className="break-words text-[12.5px] font-medium leading-snug text-foreground">{view.title}</p>+ <p className="break-words text-[11px] leading-snug text-muted-foreground">{view.reason}</p>+ </div>+ {view.action && (+ <button+ type="button"+ data-testid="git-next-action"+ disabled={actions.busy !== ""}+ onClick={act}+ className={cn(+ "inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-[11.5px] font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60",+ view.tone === "action"+ ? "bg-primary text-primary-foreground hover:bg-primary/90"+ : "border border-border-strong text-foreground hover:bg-secondary",+ )}+ >+ {working && <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />}+ {view.action}+ </button>+ )}+ </div>+ )}+ {!composing && extras.length > 0 && (+ <div data-testid="git-quick-actions" className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 px-0.5 text-[11px]">+ <span className="text-muted-foreground">{t("ide_side_panel.git.next.also")}</span>+ {extras.map((extra) => (+ <button+ key={extra.id}+ type="button"+ data-testid={`git-quick-${extra.id}`}+ disabled={actions.busy !== ""}+ onClick={extra.run}+ className="rounded text-accent hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ >+ {extra.label}+ </button>+ ))}+ </div>+ )}+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitBadges.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitBadges.tsxnew file mode 100644index 0000000000..140b0461c6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitBadges.tsx@@ -0,0 +1,185 @@+import type { ReactNode, SVGProps } from "react";+import { CircleCheck, CircleDashed, CircleX, GitMerge, GitPullRequest, GitPullRequestClosed, GitPullRequestDraft, Loader2 } 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 type { CiState, CiStatus, PullRequest, PullRequestState } from "./gitOverviewApi";++type Translate = (key: string) => string;++/** "1 commit" / "3 commits": the locale's own one-and-many forms. */+export function plural(t: Translate, key: string, n: number): string {+ return fill(t(`${key}_${n === 1 ? "one" : "other"}`), { n });+}++// 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.+export 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>+ );+}++export 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 the shapes GitHub uses for checks — a circle that is dashed,+// spinning, ticked or crossed — so a green tick can never be read as a merge.+export const CI_TONE: Record<CiState, string> = {+ none: "text-muted-foreground/60",+ pending: "text-warning",+ running: "text-warning",+ success: "text-success",+ failure: "text-destructive",+};++export 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 />;+}++/** An icon that opens a GitHub page; a plain span when there is nowhere to go. */+export 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>+ );+}++export function prStateLabel(t: Translate, 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}`);+}++/** CI in one plain line: "CI failed — 2 of 14 checks: lint, tests". */+export function ciSentence(t: Translate, ci: CiStatus): string {+ const head = t(`ide_side_panel.git.ci.${ci.state}`);+ if (ci.state === "none" || ci.total === 0) return head;+ const count =+ ci.state === "failure"+ ? fill(t("ide_side_panel.git.ci_failed_of"), { failed: ci.failed, total: ci.total })+ : fill(t("ide_side_panel.git.ci_passed_of"), { passed: ci.passed, total: ci.total });+ const names = ci.state === "failure" && ci.names.length > 0 ? `: ${ci.names.join(", ")}` : "";+ return `${head} — ${count}${names}`;+}++export 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-3.5 w-3.5", 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>+ );+}++export function CiBadge({ ci, stale = false }: { ci: CiStatus; stale?: boolean }) {+ const t = useT();+ if (ci.state === "none") return null;+ const lines = [ciSentence(t, ci)];+ if (ci.state !== "failure" && ci.names.length > 0) lines.push(fill(t("ide_side_panel.git.ci_running_names"), { 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>+ );+}++/** Today's commits read "3 hours ago"; older ones show the day ("3 Oct", plus the year when it differs). */+export function commitDateLabel(seconds: number, lang: string, now = Date.now()): string {+ const date = new Date(seconds * 1000);+ const elapsed = Math.max(0, now - date.getTime());+ if (elapsed < 24 * 3_600_000) {+ const relative = new Intl.RelativeTimeFormat(lang, { numeric: "auto", style: "short" });+ if (elapsed < 3_600_000) return relative.format(-Math.max(1, Math.round(elapsed / 60_000)), "minute");+ return relative.format(-Math.round(elapsed / 3_600_000), "hour");+ }+ const sameYear = date.getFullYear() === new Date(now).getFullYear();+ return new Intl.DateTimeFormat(lang, { day: "numeric", month: "short", ...(sameYear ? {} : { year: "numeric" }) }).format(date);+}++/** "just now", "5 min. ago", "3 hr. ago", "2 days ago" — how long ago something was read. */+export function agoLabel(seconds: number, lang: string, t: Translate, now = Date.now()): string {+ const elapsed = Math.max(0, now / 1000 - seconds);+ if (elapsed < 45) return t("ide_side_panel.git.just_now");+ const relative = new Intl.RelativeTimeFormat(lang, { numeric: "always", style: "short" });+ if (elapsed < 3600) return relative.format(-Math.max(1, Math.round(elapsed / 60)), "minute");+ if (elapsed < 86_400) return relative.format(-Math.round(elapsed / 3600), "hour");+ return relative.format(-Math.round(elapsed / 86_400), "day");+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitInsights.test.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitInsights.test.tsnew file mode 100644index 0000000000..69b5741bc8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitInsights.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it } from "vitest";+import { attention, canCleanUp, needsPull, needsPush, nextStep, syncOf } from "./gitInsights";+import type { BranchRow, Checkout, CiStatus, PullRequest, RepoOverview } from "./gitOverviewApi";++const noCi: CiStatus = { state: "none", url: "", total: 0, passed: 0, failed: 0, running: 0, pending: 0, commit: "", names: [] };+const failed: CiStatus = { ...noCi, state: "failure", total: 3, passed: 2, failed: 1, names: ["lint"], url: "https://ci/1" };++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,+ base_ahead: 1,+ base_behind: 0,+ ...extra,+ };+}++function pr(number: number, extra: Partial<PullRequest> = {}): PullRequest {+ return {+ number,+ title: `Change ${number}`,+ url: `https://github.com/o/r/pull/${number}`,+ state: "open",+ base: "main",+ head: "feature/x",+ head_oid: "",+ merged_at: "",+ updated_at: "",+ queue_position: null,+ ci: noCi,+ ...extra,+ };+}++const CLEAN: Checkout = {+ branch: "feature/x",+ detached: false,+ unborn: false,+ head: "abc123def456",+ upstream: "origin/feature/x",+ ahead: 0,+ behind: 0,+ files: 0,+ staged: 0,+ unstaged: 0,+ untracked: 0,+ conflicted: 0,+ operation: "",+ stashes: 0,+ last_fetch: 1,+ has_remote: true,+};++function overview(checkout: Partial<Checkout> = {}, current: Partial<BranchRow> = {}, others: BranchRow[] = []): RepoOverview {+ const state = { ...CLEAN, ...checkout };+ return {+ available: true,+ reason: "",+ root: "/code/app",+ branch: state.branch,+ detached: state.detached,+ head: state.head,+ default_branch: "main",+ truncated: false,+ github: { available: true, reason: "", code: "", repo: "o/r", suggested_repo: "", source: "app", repo_url: "https://github.com/o/r", fetched_at: 1 },+ branches: [+ branch(state.branch || "feature/x", { current: true, upstream: state.upstream, ahead: state.ahead, behind: state.behind, ...current }),+ branch("main"),+ ...others,+ ],+ remote_branches: [],+ checkout: state,+ base_ref: "origin/main",+ };+}++describe("syncOf", () => {+ it("names how a branch stands to its remote", () => {+ expect(syncOf(branch("a"))).toBe("synced");+ expect(syncOf(branch("a", { ahead: 2 }))).toBe("ahead");+ expect(syncOf(branch("a", { behind: 1 }))).toBe("behind");+ expect(syncOf(branch("a", { ahead: 2, behind: 1 }))).toBe("diverged");+ expect(syncOf(branch("a", { upstream: "", on_github: false }))).toBe("unpublished");+ expect(syncOf(branch("a", { upstream_gone: true }))).toBe("gone");+ expect(syncOf(branch("a", { remote_only: true, upstream: "" }))).toBe("remote_only");+ });++ it("counts only work of its own as needing a push", () => {+ expect(needsPush(branch("a", { ahead: 1 }))).toBe(true);+ expect(needsPush(branch("a", { upstream: "", on_github: false }))).toBe(true);+ // Just created from main: nothing of its own to lose.+ expect(needsPush(branch("a", { upstream: "", on_github: false, base_ahead: 0 }))).toBe(false);+ // Merged work is safe in the target, wherever the branch itself is.+ expect(needsPush(branch("a", { upstream_gone: true, merged_into: [{ target: "main", via: "pull_request", number: 3, url: "" }] }))).toBe(false);+ // A deleted remote branch is what a merged pull request leaves behind: no alarm.+ expect(needsPush(branch("a", { upstream_gone: true }))).toBe(false);+ expect(needsPull(branch("a", { unfetched: true }))).toBe(true);+ });+});++describe("nextStep", () => {+ const step = (...args: Parameters<typeof overview>) => nextStep(overview(...args));++ it("finishes what is half-done before anything else", () => {+ expect(step({ operation: "merge", conflicted: 2, files: 2, behind: 3 })).toEqual({ kind: "resolve", operation: "merge", conflicts: 2 });+ expect(step({ detached: true, branch: "" }).kind).toBe("detached");+ });++ it("gets the remote's commits before saving and sharing your own", () => {+ expect(step({}, { unfetched: true }).kind).toBe("fetch");+ // A fast-forward is safe even with uncommitted files, so it comes first.+ expect(step({ behind: 3, files: 2, unstaged: 2 })).toEqual({ kind: "pull", count: 3 });+ expect(step({ files: 4, unstaged: 3, untracked: 1, ahead: 2 })).toEqual({ kind: "commit", count: 4 });+ expect(step({ ahead: 2, behind: 1 })).toEqual({ kind: "rebase", ahead: 2, behind: 1 });+ expect(step({ ahead: 2 })).toEqual({ kind: "push", count: 2 });+ expect(step({ upstream: "" }, { on_github: false }).kind).toBe("publish");+ });++ it("does not suggest committing files git does not track yet", () => {+ expect(step({ files: 5, untracked: 5 }).kind).not.toBe("commit");+ });++ it("looks after the pull request once the branch is shared", () => {+ expect(step().kind).toBe("open_pr");+ expect(step({}, { pull_requests: [pr(4, { ci: failed })] })).toEqual({ kind: "fix_ci", number: 4, names: ["lint"], url: "https://ci/1" });+ expect(step({}, { pull_requests: [pr(4, { conflicting: true })] }).kind).toBe("fix_conflict");+ expect(step({}, { pull_requests: [pr(4, { review: "changes_requested" })] }).kind).toBe("changes_requested");+ expect(step({}, { pull_requests: [pr(4, { state: "queued" })] }).kind).toBe("wait_queue");+ expect(step({}, { pull_requests: [pr(4, { ci: { ...noCi, state: "running", total: 2 } })] }).kind).toBe("wait_ci");+ expect(step({}, { pull_requests: [pr(4, { ci: { ...noCi, state: "success", total: 2, passed: 2 } })] }).kind).toBe("ready");+ });++ it("says so when there is nothing to do", () => {+ expect(step({ branch: "main", upstream: "origin/main" }).kind).toBe("done");+ // A merged branch needs no pull request.+ expect(step({}, { merged_into: [{ target: "main", via: "git", number: null, url: "" }] }).kind).toBe("done");+ });++ it("works from the current branch's row on a backend without checkout state", () => {+ const old = overview({ ahead: 2 });+ delete old.checkout;+ expect(nextStep(old)).toEqual({ kind: "push", count: 2 });+ });+});++describe("attention", () => {+ it("is empty when the repository is in order", () => {+ expect(attention(overview({ branch: "main", upstream: "origin/main" }))).toEqual([]);+ });++ it("lists what is broken first and what can be tidied last", () => {+ const merged = branch("feature/done", { merged_into: [{ target: "main", via: "git", number: null, url: "" }] });+ const data = overview({}, {}, [+ merged,+ branch("feature/local", { upstream: "", on_github: false }),+ branch("feature/stale", { behind: 4 }),+ ]);+ data.pull_requests = [pr(7, { ci: failed }), pr(8, { conflicting: true }), pr(9, { review: "changes_requested" }), pr(10)];+ data.branches[1] = branch("main", { behind: 2 });+ const items = attention(data);+ expect(items.map((item) => [item.kind, item.count])).toEqual([+ ["ci_failing", 1],+ ["pr_conflicts", 1],+ ["changes_requested", 1],+ ["default_behind", 1],+ ["unpushed", 1],+ ["behind", 1],+ ["cleanup", 1],+ ]);+ expect(items[0].names).toEqual(["#7"]);+ expect(canCleanUp(merged, "main")).toBe(true);+ // The branch the person is on is never offered for removal.+ expect(canCleanUp({ ...merged, current: true }, "main")).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitInsights.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitInsights.tsnew file mode 100644index 0000000000..6c28237c80--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitInsights.ts@@ -0,0 +1,237 @@+/**+ * What the Git tab concludes from one overview: how a branch stands to its+ * remote, what needs a look across the repository, and the one next step for+ * the checkout the person is in. Pure functions — the components only render.+ */++import type { BranchRow, Checkout, PullRequest, RepoOverview } from "./gitOverviewApi";++/** How a branch stands to its remote counterpart. */+export type SyncState =+ | "synced"+ | "ahead" // commits to push+ | "behind" // commits to pull+ | "diverged" // both+ | "unpublished" // only on this computer+ | "gone" // its remote branch was deleted+ | "remote_only";++export function syncOf(row: BranchRow): SyncState {+ if (row.remote_only) return "remote_only";+ if (row.upstream_gone) return "gone";+ if (!row.upstream) return row.on_github ? "synced" : "unpublished";+ if (row.ahead && row.behind) return "diverged";+ if (row.ahead) return "ahead";+ return row.behind ? "behind" : "synced";+}++const LIVE = new Set(["queued", "open", "draft"]);++/** The branch's pull request that is still open, if it has one. */+export function livePr(row: BranchRow): PullRequest | undefined {+ return row.pull_requests.find((pr) => LIVE.has(pr.state));+}++export function isMerged(row: BranchRow): boolean {+ return row.merged_into.length > 0;+}++/** Commits that exist only on this computer: pushing is what backs them up. */+export function needsPush(row: BranchRow): boolean {+ if (row.remote_only || isMerged(row)) return false;+ const sync = syncOf(row);+ if (sync === "ahead" || sync === "diverged") return true;+ // Never pushed: only a branch with work of its own counts. A branch whose+ // remote one was deleted is not counted — that is what a merged pull request+ // leaves behind, and calling it unsaved work would cry wolf.+ return sync === "unpublished" && (row.base_ahead ?? 1) > 0;+}++export function needsPull(row: BranchRow): boolean {+ return !row.remote_only && (row.behind > 0 || Boolean(row.unfetched));+}++/** A merged branch that is neither checked out here nor the default one can go. */+export function canCleanUp(row: BranchRow, defaultBranch: string): boolean {+ return !row.remote_only && !row.current && row.name !== defaultBranch && isMerged(row);+}++export type BranchFilter = "all" | "unpushed" | "behind" | "failing" | "pr" | "merged";+export const BRANCH_FILTERS: readonly BranchFilter[] = ["all", "unpushed", "behind", "failing", "pr", "merged"];++export function matchesFilter(row: BranchRow, filter: BranchFilter): boolean {+ if (filter === "unpushed") return needsPush(row);+ if (filter === "behind") return needsPull(row);+ if (filter === "failing") return row.ci.state === "failure";+ if (filter === "pr") return Boolean(livePr(row));+ if (filter === "merged") return isMerged(row);+ return true;+}++export function matchesQuery(row: BranchRow, query: string): boolean {+ if (!query) return true;+ const needle = query.toLowerCase().replace(/^#/, "");+ return (+ row.name.toLowerCase().includes(needle) ||+ row.pull_requests.some((pr) => String(pr.number) === needle || pr.title.toLowerCase().includes(needle))+ );+}++/**+ * The checkout's state. A backend from before the control center sends none;+ * the current branch's row then stands in (no uncommitted-change counts).+ */+export function checkoutOf(overview: RepoOverview): Checkout {+ if (overview.checkout) return overview.checkout;+ const row = overview.branches.find((branch) => branch.current);+ return {+ branch: overview.branch,+ detached: overview.detached,+ unborn: false,+ head: overview.head,+ upstream: row?.upstream ?? "",+ ahead: row?.ahead ?? 0,+ behind: row?.behind ?? 0,+ files: 0,+ staged: 0,+ unstaged: 0,+ untracked: 0,+ conflicted: 0,+ operation: "",+ stashes: 0,+ last_fetch: 0,+ has_remote: true,+ };+}++/** Every pull request that is still open; derived from the branches for an older backend. */+export function openPullRequests(overview: RepoOverview): PullRequest[] {+ if (overview.pull_requests) return overview.pull_requests;+ const seen = new Set<number>();+ const found: PullRequest[] = [];+ for (const row of [...overview.branches, ...overview.remote_branches]) {+ const pr = livePr(row);+ if (pr && !seen.has(pr.number)) {+ seen.add(pr.number);+ found.push(pr);+ }+ }+ return found;+}++// ------------------------------------------------------------------ next step++export type NextStep =+ | { kind: "resolve"; operation: string; conflicts: number }+ | { kind: "detached" }+ | { kind: "fetch" }+ | { kind: "pull"; count: number }+ | { kind: "commit"; count: number }+ | { kind: "rebase"; ahead: number; behind: number }+ | { kind: "publish" }+ | { kind: "push"; count: number }+ | { kind: "open_pr" }+ | { kind: "fix_ci"; number: number | null; names: string[]; url: string }+ | { kind: "fix_conflict"; pr: PullRequest }+ | { kind: "changes_requested"; pr: PullRequest }+ | { kind: "wait_queue"; pr: PullRequest }+ | { kind: "wait_ci"; number: number | null; url: string }+ | { kind: "ready"; pr: PullRequest }+ | { kind: "done" };++/**+ * The one thing to do next in this checkout, in the order a careful developer+ * works: finish what is half-done, get the remote's commits, save your own,+ * share them, then look after the pull request.+ */+export function nextStep(overview: RepoOverview): NextStep {+ const checkout = checkoutOf(overview);+ const row = overview.branches.find((branch) => branch.current);+ if (checkout.operation || checkout.conflicted > 0) {+ return { kind: "resolve", operation: checkout.operation, conflicts: checkout.conflicted };+ }+ if (checkout.detached || !checkout.branch) return { kind: "detached" };+ if (row?.unfetched) return { kind: "fetch" };+ // A fast-forward never touches local commits, so it comes before anything else.+ if (checkout.behind > 0 && checkout.ahead === 0) return { kind: "pull", count: checkout.behind };+ const tracked = checkout.staged + checkout.unstaged;+ if (tracked > 0) return { kind: "commit", count: checkout.files };+ if (checkout.behind > 0 && checkout.ahead > 0) {+ return { kind: "rebase", ahead: checkout.ahead, behind: checkout.behind };+ }+ const isDefault = checkout.branch === overview.default_branch;+ const hasWork = (row?.base_ahead ?? 1) > 0;+ if (!checkout.upstream && checkout.has_remote && (!isDefault || !row?.on_github) && hasWork) {+ return { kind: "publish" };+ }+ if (checkout.ahead > 0) return { kind: "push", count: checkout.ahead };++ const pr = row ? livePr(row) : undefined;+ if (pr) {+ if (pr.ci.state === "failure") return { kind: "fix_ci", number: pr.number, names: pr.ci.names, url: pr.ci.url || pr.url };+ if (pr.conflicting) return { kind: "fix_conflict", pr };+ if (pr.review === "changes_requested") return { kind: "changes_requested", pr };+ if (pr.state === "queued") return { kind: "wait_queue", pr };+ if (pr.ci.state === "running" || pr.ci.state === "pending") return { kind: "wait_ci", number: pr.number, url: pr.ci.url || pr.url };+ if (pr.state === "open" && pr.ci.state === "success") return { kind: "ready", pr };+ return { kind: "done" };+ }+ if (row && !isDefault && row.upstream && !row.upstream_gone && !isMerged(row) && hasWork && overview.github.available) {+ return { kind: "open_pr" };+ }+ if (row && row.ci.state === "failure" && !row.ci_stale) {+ return { kind: "fix_ci", number: null, names: row.ci.names, url: row.ci.url };+ }+ if (row && (row.ci.state === "running" || row.ci.state === "pending") && !row.ci_stale) {+ return { kind: "wait_ci", number: null, url: row.ci.url };+ }+ return { kind: "done" };+}++// ------------------------------------------------------------------ attention++export type AttentionKind =+ | "ci_failing"+ | "default_ci"+ | "pr_conflicts"+ | "changes_requested"+ | "default_behind"+ | "unpushed"+ | "behind"+ | "cleanup";++export interface AttentionItem {+ kind: AttentionKind;+ tone: "danger" | "warning" | "neutral";+ count: number;+ /** A few names for the row's second line (branches, or `#12` for pull requests). */+ names: string[];+}++const MAX_NAMES = 3;++/** What needs a look across the repository, worst first. Empty means all clear. */+export function attention(overview: RepoOverview): AttentionItem[] {+ const items: AttentionItem[] = [];+ const prs = openPullRequests(overview);+ const add = (kind: AttentionKind, tone: AttentionItem["tone"], names: string[]) => {+ if (names.length > 0) items.push({ kind, tone, count: names.length, names: names.slice(0, MAX_NAMES) });+ };+ const number = (pr: PullRequest) => `#${pr.number}`;+ const local = overview.branches;+ const fallback = local.find((row) => row.name === overview.default_branch);++ add("ci_failing", "danger", prs.filter((pr) => pr.ci.state === "failure").map(number));+ if (fallback && fallback.ci.state === "failure") add("default_ci", "danger", fallback.ci.names.length ? fallback.ci.names : [fallback.name]);+ add("pr_conflicts", "danger", prs.filter((pr) => pr.conflicting).map(number));+ add("changes_requested", "warning", prs.filter((pr) => pr.review === "changes_requested").map(number));+ if (fallback && !fallback.current && needsPull(fallback)) add("default_behind", "warning", [fallback.name]);+ add("unpushed", "warning", local.filter((row) => !row.current && needsPush(row)).map((row) => row.name));+ add(+ "behind",+ "warning",+ local.filter((row) => !row.current && row.name !== overview.default_branch && needsPull(row) && !isMerged(row)).map((row) => row.name),+ );+ add("cleanup", "neutral", local.filter((row) => canCleanUp(row, overview.default_branch)).map((row) => row.name));+ return items;+}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.tsindex 7121ef1b18..1bbf99f78e 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts@@ -39,6 +39,13 @@ export interface PullRequest {updated_at: string;queue_position: number | null;ci: CiStatus;+ /** GitHub cannot merge it as it is: it conflicts with its base. */+ conflicting?: boolean;+ /** `approved` | `changes_requested` | `review_required` | "" (no review rule). */+ review?: string;+ author?: string;+ /** Opened from a fork: its branch is not one of this repository's. */+ fork?: boolean;}export interface MergedInto {@@ -67,6 +74,36 @@ export interface BranchRow {ci: CiStatus;/** Local commits CI has not seen yet. */ci_stale: boolean;+ /** The upstream is configured but was deleted on the remote. */+ upstream_gone?: boolean;+ /** GitHub has commits here that were not fetched yet; `behind` undercounts until a fetch. */+ unfetched?: boolean;+ /** Commits it has that the default branch lacks, and the other way round; null when unknown. */+ base_ahead?: number | null;+ base_behind?: number | null;+}++/** The folder's own state: what is uncommitted and how it stands to its remote. */+export interface Checkout {+ branch: string;+ detached: boolean;+ unborn: boolean;+ head: string;+ upstream: string;+ ahead: number;+ behind: number;+ /** Files with any uncommitted change. */+ files: number;+ staged: number;+ unstaged: number;+ untracked: number;+ conflicted: number;+ /** `merge` | `rebase` | `cherry-pick` | `revert` | `bisect` while one is unfinished. */+ operation: string;+ stashes: number;+ /** Epoch seconds of the last fetch; 0 when never. */+ last_fetch: number;+ has_remote: boolean;}export interface GitHubState {@@ -83,6 +120,8 @@ export interface GitHubState {repo_url: string;/** Epoch seconds of the GitHub answer in use. */fetched_at: number;+ /** A newer answer is being read right now; ask again shortly. */+ refreshing?: boolean;}export interface RepoOverview {@@ -97,6 +136,12 @@ export interface RepoOverview {remote_branches: BranchRow[];truncated: boolean;github: GitHubState;+ /** Missing from a backend that predates the control center (until the next app start). */+ checkout?: Checkout;+ /** What `base_ahead` / `base_behind` compare with (`origin/main`). */+ base_ref?: string;+ /** Every open pull request, the ones needing a look first. */+ pull_requests?: PullRequest[];}/** A failed call; `routeMissing` means the running backend predates this tab (restart once). */diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/useGitActions.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/useGitActions.tsnew file mode 100644index 0000000000..6a666d2874--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/useGitActions.ts@@ -0,0 +1,180 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { fill, useT } from "@/i18n";+import {+ commitAll,+ deleteBranch,+ fetchRemotes,+ GitApiError,+ openBranchPullRequest,+ pullBranch,+ pushWorkspaceBranch,+ switchBranch,+ updateBranch,+} from "@/lib/gitApi";+import { openExternalUrl } from "@/lib/openExternal";+import { useEventStore } from "@/store/events";+import type { BranchRow } from "./gitOverviewApi";++/** A question the tab asks before an action that cannot be taken back. */+export interface Confirmation {+ title: string;+ body: string;+ confirmLabel: string;+ /** Offered as a checkbox: also delete the branch on GitHub. */+ remoteOption?: boolean;+ run: (options: { remote: boolean }) => Promise<void>;+}++export interface GitActions {+ /** The action in flight (`pull`, `push:feature/x`, …); "" when idle. */+ busy: string;+ confirmation: Confirmation | null;+ dismiss: () => void;+ fetch: () => Promise<void>;+ pull: () => void;+ rebase: () => void;+ /** Push the current branch, or `branch` without checking it out. */+ push: (branch?: string) => void;+ /** Stage everything and commit; resolves true when the commit was made. */+ commit: (message: string) => Promise<boolean>;+ switchTo: (branch: string) => void;+ update: (branch: string) => void;+ remove: (row: BranchRow) => void;+ createPullRequest: (branch?: string) => void;+}++/**+ * Everything the Git tab can do to the repository. Each action runs once at a+ * time, says what happened in a toast, and re-reads the overview afterwards.+ * The two that cannot be undone — rewriting local commits and deleting a+ * branch — only run from a confirmation.+ */+export function useGitActions(workspaceId: string, folder: string, branch: string, refresh: () => void): GitActions {+ const t = useT();+ const pushToast = useEventStore((state) => state.pushToast);+ const [busy, setBusy] = useState("");+ const [confirmation, setConfirmation] = useState<Confirmation | null>(null);+ const running = useRef(false);+ // A question asked about one repository is void once another one is shown.+ useEffect(() => setConfirmation(null), [workspaceId]);++ /** Runs `work`; a rejection whose code is in `handled` is returned instead of shown. */+ const run = useCallback(+ async (key: string, work: () => Promise<string>, handled: string[] = []): Promise<GitApiError | null | undefined> => {+ if (running.current || !folder || !workspaceId) return undefined;+ running.current = true;+ setBusy(key);+ try {+ const message = await work();+ if (message) pushToast("success", message);+ return null;+ } catch (err) {+ const failure = err instanceof GitApiError ? err : new GitApiError((err as Error).message, "failed");+ if (handled.includes(failure.code)) return failure;+ pushToast("error", failure.message);+ return undefined;+ } finally {+ running.current = false;+ setBusy("");+ refresh();+ }+ },+ [folder, pushToast, refresh, workspaceId],+ );++ return useMemo<GitActions>(() => {+ const rebase = () =>+ setConfirmation({+ title: t("ide_side_panel.git.confirm.rebase_title"),+ body: t("ide_side_panel.git.confirm.rebase_body"),+ confirmLabel: t("ide_side_panel.git.confirm.rebase_ok"),+ run: async () => {+ await run("pull", async () => {+ await pullBranch(workspaceId, true);+ return fill(t("ide_side_panel.git.done.rebased"), { branch });+ });+ },+ });++ const onRemote = (row: BranchRow) => row.on_github && Boolean(row.upstream) && !row.upstream_gone;+ const removeNow = async (row: BranchRow, force: boolean, remote: boolean) => {+ const failure = await run(+ `delete:${row.name}`,+ async () => {+ await deleteBranch(workspaceId, row.name, { force, remote, withWorktree: Boolean(row.worktree) });+ return fill(t("ide_side_panel.git.done.deleted"), { branch: row.name });+ },+ ["unmerged"],+ );+ if (failure) {+ // The backend found commits that exist nowhere else: ask again, explicitly.+ setConfirmation({+ title: fill(t("ide_side_panel.git.confirm.delete_force_title"), { branch: row.name }),+ body: t("ide_side_panel.git.confirm.delete_force_body"),+ confirmLabel: t("ide_side_panel.git.confirm.delete_force_ok"),+ // Asked again, unticked: losing the remote copy too is this dialog's own decision.+ remoteOption: onRemote(row),+ run: ({ remote: again }) => removeNow(row, true, again),+ });+ }+ };++ return {+ busy,+ confirmation,+ dismiss: () => setConfirmation(null),+ fetch: async () => {+ await run("fetch", async () => {+ await fetchRemotes(folder);+ return "";+ });+ },+ pull: () => {+ const pulled = async () => {+ await pullBranch(workspaceId);+ return fill(t("ide_side_panel.git.done.pulled"), { branch });+ };+ void run("pull", pulled, ["diverged"]).then((failure) => {+ if (failure) rebase();+ });+ },+ rebase,+ push: (target = "") => {+ void run(`push:${target}`, async () => fill(t("ide_side_panel.git.done.pushed"), { upstream: (await pushWorkspaceBranch(workspaceId, target)).upstream }));+ },+ commit: async (message) => {+ const failure = await run("commit", async () => fill(t("ide_side_panel.git.done.committed"), { commit: (await commitAll(folder, message)).commit }));+ return failure === null;+ },+ switchTo: (target) => {+ void run(`switch:${target}`, async () => {+ await switchBranch(workspaceId, target);+ return fill(t("ide_side_panel.git.done.switched"), { branch: target });+ });+ },+ update: (target) => {+ void run(`update:${target}`, async () => {+ await updateBranch(workspaceId, target);+ return fill(t("ide_side_panel.git.done.updated"), { branch: target });+ });+ },+ remove: (row) =>+ setConfirmation({+ title: fill(t("ide_side_panel.git.confirm.delete_title"), { branch: row.name }),+ body: row.worktree+ ? fill(t("ide_side_panel.git.confirm.delete_body_worktree"), { path: row.worktree })+ : t("ide_side_panel.git.confirm.delete_body"),+ confirmLabel: t("ide_side_panel.git.confirm.delete_ok"),+ remoteOption: onRemote(row),+ run: ({ remote }) => removeNow(row, false, remote),+ }),+ createPullRequest: (target = "") => {+ void run(`pr:${target}`, async () => {+ const { url } = await openBranchPullRequest(workspaceId, { branch: target });+ if (url) void openExternalUrl(url);+ return t("ide_side_panel.git.done.pr_opened");+ });+ },+ };+ }, [branch, busy, confirmation, folder, run, t, workspaceId]);+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex d67627711e..a33569dc60 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -7630,7 +7630,7 @@}},"git": {- "aria": "Branches, Pull Requests und CI",+ "aria": "Git- und GitHub-Status","needs_restart": "Dodaios braucht dafür einmal einen Neustart. Danach wählst du einmal das Repository für diesen Ordner.","connect_repo_title": "GitHub-Repository verbinden","restart_button": "Dodaios neu starten",@@ -7649,28 +7649,20 @@"pick_cancel": "Aktuelles Repository behalten","change_repo": "Anderes GitHub-Repository für diesen Ordner wählen","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",+ "loading": "Repository wird gelesen …",+ "refresh": "Vom Remote holen und 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",+ "worktree_badge": "hat einen eigenen Worktree","tracks": "Folgt {upstream}: {ahead} voraus, {behind} zurück",- "ahead_behind": "↑{ahead} ↓{behind}","not_pushed": "Noch nicht zu GitHub gepusht","local_only": "nur lokal","local_only_tip": "Nur auf diesem Rechner. Noch nicht zu GitHub gepusht.",- "both": "lokal + GitHub",- "both_tip": "Auf diesem Rechner und auf GitHub.",- "github_only": "nur GitHub",- "github_only_tip": "Nur auf GitHub, nicht auf diesem Rechner.","last_commit": "Letzter Commit: {date}","details": {"local_absent": "Nur auf GitHub, nicht auf diesem Rechner.",@@ -7687,9 +7679,11 @@"no_commits": "Keine Commits über {base} hinaus.","more_commits": "Ältere Commits werden nicht gezeigt.","files": "{n} Dateien geändert",- "more_files": "Es wurden mehr Dateien geändert, als hier stehen."+ "more_files": "Es wurden mehr Dateien geändert, als hier stehen.",+ "upstream_gone": "{upstream} wurde auf dem Remote gelöscht.",+ "vs_base": "{ahead} vor {base}, {behind} dahinter"},- "merged_short": "in {target}",+ "merged_short": "in {target} gemergt","merged_git": "In {target} gemergt: Jeder Commit dieses Branches ist in {target} enthalten.","merged_pr": "Über Pull Request #{number} in {target} gemergt.","pr": {@@ -7708,17 +7702,11 @@"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_reading": "Pull Requests und CI werden von GitHub gelesen…",- "github_off": "Kein GitHub-Status: {reason}",- "seconds_ago": "vor {n} s",- "minutes_ago": "vor {n} min",- "open_branch": "{branch} auf GitHub öffnen","more": "Weitere Optionen","search": "Branches oder #PR suchen…","search_clear": "Suche leeren",@@ -7727,8 +7715,9 @@"all": "Alle","pr": "Offener PR","failing": "CI rot",- "unmerged": "Nicht gemergt",- "local": "Nur lokal"+ "unpushed": "Zu pushen",+ "behind": "Zu holen",+ "merged": "Gemergt"},"filter_empty": "Kein Branch passt.","menu": {@@ -7749,6 +7738,195 @@"copied": "Kopiert: {text}","copy_failed": "Kopieren in die Zwischenablage hat nicht geklappt.","no_repo": "Noch kein GitHub-Repository gewählt"+ },+ "just_now": "gerade eben",+ "fetched": "geholt {when}",+ "fetching": "Hole vom Remote …",+ "never_fetched": "noch nie geholt",+ "older_backend": "Einmal neu starten, dann sind der volle Status und die Aktionen da.",+ "show_all": "Alle {n} anzeigen",+ "show_more": "{n} weitere anzeigen (noch {left})",+ "ci_failed_of": "{failed} von {total} Prüfungen fehlgeschlagen",+ "ci_passed_of": "{passed} von {total} Prüfungen bestanden",+ "status": {+ "aria": "Dieser Checkout",+ "to_push": "zu pushen",+ "to_pull": "zu holen",+ "synced": "Synchron mit {upstream}.",+ "ahead_one": "Dieser Rechner ist {n} Commit vor {upstream}.",+ "ahead_other": "Dieser Rechner ist {n} Commits vor {upstream}.",+ "behind_one": "{upstream} ist {n} Commit vor diesem Rechner.",+ "behind_other": "{upstream} ist {n} Commits vor diesem Rechner.",+ "diverged": "Beide sind weitergelaufen: {ahead} nur hier, {behind} nur auf {upstream}.",+ "unpublished": "Diesen Branch gibt es nur auf diesem Rechner.",+ "no_remote": "Dieses Repository hat noch kein Remote.",+ "gone": "Sein Branch auf dem Remote wurde gelöscht.",+ "detached": "Kein Branch ausgecheckt (losgelöster HEAD).",+ "unfetched": "GitHub hat neuere Commits, die noch nicht geholt sind.",+ "clean": "Nichts zu committen",+ "changed_one": "{n} geänderte Datei",+ "changed_other": "{n} geänderte Dateien",+ "n_conflicted": "{n} im Konflikt",+ "n_staged": "{n} vorgemerkt",+ "n_modified": "{n} geändert",+ "n_untracked": "{n} neu",+ "review": "Ansehen"+ },+ "next": {+ "label": "Nächster Schritt",+ "also": "Außerdem:",+ "resolve": "Konflikte auflösen",+ "resolve_operation": "{operation} abschließen",+ "resolve_reason_one": "{n} Datei ist im Konflikt. Löse ihn auf und mach dann weiter.",+ "resolve_reason_other": "{n} Dateien sind im Konflikt. Löse sie auf und mach dann weiter.",+ "resolve_reason_none": "Der Vorgang wurde begonnen und nicht beendet.",+ "open_changes": "Änderungen öffnen",+ "detached": "Einen Branch auschecken",+ "detached_reason": "Commits von jetzt gehören zu keinem Branch.",+ "fetch": "Neue Commits holen",+ "fetch_reason": "GitHub hat Commits, die dieser Rechner noch nicht kennt.",+ "fetch_action": "Holen",+ "pull_one": "{n} Commit von {upstream} holen",+ "pull_other": "{n} Commits von {upstream} holen",+ "pull_reason": "Ein Fast-Forward: Deine Dateien rücken vor, nichts wird umgeschrieben.",+ "pull_action": "Pull",+ "commit_one": "{n} geänderte Datei committen",+ "commit_other": "{n} geänderte Dateien committen",+ "commit_reason": "Nicht committete Arbeit ist noch nicht in Git gesichert.",+ "commit_action": "Committen …",+ "rebase": "Auf {upstream} rebasen",+ "rebase_reason": "{ahead} hier und {behind} auf dem Remote: Keine Seite kann einfach vorrücken.",+ "rebase_action": "Rebasen …",+ "publish": "Diesen Branch veröffentlichen",+ "publish_reason": "Es gibt ihn nur auf diesem Rechner – noch sichert ihn nichts.",+ "publish_action": "Veröffentlichen",+ "push_one": "{n} Commit zu {upstream} pushen",+ "push_other": "{n} Commits zu {upstream} pushen",+ "push_reason": "Es gibt sie nur auf diesem Rechner.",+ "push_action": "Push",+ "open_pr": "Pull Request öffnen",+ "open_pr_reason": "Der Branch ist gepusht und hat noch keinen Pull Request nach {base}.",+ "open_pr_action": "Pull Request öffnen",+ "fix_ci": "CI schlägt auf diesem Branch fehl",+ "fix_ci_pr": "CI schlägt bei #{number} fehl",+ "fix_ci_reason": "Fehlgeschlagen: {names}",+ "fix_ci_reason_none": "Mindestens eine Prüfung ist fehlgeschlagen.",+ "view_checks": "Prüfungen ansehen",+ "fix_conflict": "#{number} steht im Konflikt mit seinem Ziel",+ "fix_conflict_reason": "GitHub kann ihn erst mergen, wenn er auf dem Stand von {base} ist.",+ "view_pr": "Pull Request öffnen",+ "changes_requested": "Bei #{number} wurden Änderungen verlangt",+ "changes_requested_reason": "Ein Reviewer wartet auf eine Aktualisierung.",+ "wait_queue": "#{number} ist in der Merge-Warteschlange",+ "wait_queue_reason": "Er wird von selbst gemergt, sobald er dran ist und CI grün ist.",+ "wait_ci": "CI läuft",+ "wait_ci_reason": "Nichts zu tun, bis die Prüfungen fertig sind.",+ "ready": "#{number} hat alle Prüfungen bestanden",+ "ready_reason": "Er kann geprüft und gemergt werden.",+ "done": "Alles ist auf dem aktuellen Stand",+ "done_reason": "Nichts zu committen, zu pushen oder zu holen."+ },+ "commit": {+ "placeholder": "Commit-Nachricht",+ "scope_one": "Committet die {n} geänderte Datei, auch eine neue.",+ "scope_other": "Committet alle {n} geänderten Dateien, auch neue.",+ "submit": "Committen"+ },+ "confirm": {+ "cancel": "Abbrechen",+ "rebase_title": "Deine Commits auf die des Remotes rebasen?",+ "rebase_body": "Deine lokalen Commits werden auf den Remote-Branch aufgesetzt und bekommen neue IDs. Gibt es Konflikte, wird der Rebase zurückgenommen und nichts ändert sich.",+ "rebase_ok": "Rebasen",+ "delete_title": "{branch} löschen?",+ "delete_body": "Der Branch wird von diesem Rechner entfernt. Ein Branch, dessen Commits es nirgendwo sonst gibt, wird nicht ohne erneute Nachfrage gelöscht.",+ "delete_body_worktree": "Der Branch und sein Worktree-Ordner werden von diesem Rechner entfernt:\n{path}\nEin Worktree mit nicht committeten Änderungen bleibt erhalten. Dateien, die Git dort ignoriert (Build-Ausgaben, Abhängigkeiten), gehen mit dem Ordner.",+ "delete_ok": "Branch löschen",+ "delete_remote": "Auch auf GitHub löschen",+ "delete_force_title": "{branch} enthält Arbeit, die es nirgendwo sonst gibt",+ "delete_force_body": "Beim Löschen gehen diese Commits endgültig verloren.",+ "delete_force_ok": "Trotzdem löschen"+ },+ "done": {+ "pushed": "Nach {upstream} gepusht.",+ "committed": "{commit} committet.",+ "pr_opened": "Pull Request geöffnet.",+ "pulled": "Geholt: {branch} ist auf dem aktuellen Stand.",+ "rebased": "{branch} auf sein Remote rebased.",+ "switched": "Zu {branch} gewechselt.",+ "updated": "{branch} ist auf dem Stand seines Remotes.",+ "deleted": "{branch} gelöscht."+ },+ "attention": {+ "title": "Braucht Aufmerksamkeit",+ "none": "Nichts braucht Aufmerksamkeit.",+ "ci_failing_one": "CI schlägt bei {n} Pull Request fehl",+ "ci_failing_other": "CI schlägt bei {n} Pull Requests fehl",+ "default_ci_one": "CI schlägt auf dem Standard-Branch fehl",+ "default_ci_other": "CI schlägt auf dem Standard-Branch fehl",+ "pr_conflicts_one": "{n} Pull Request steht im Konflikt mit seinem Ziel",+ "pr_conflicts_other": "{n} Pull Requests stehen im Konflikt mit ihrem Ziel",+ "changes_requested_one": "Bei {n} Pull Request wurden Änderungen verlangt",+ "changes_requested_other": "Bei {n} Pull Requests wurden Änderungen verlangt",+ "default_behind_one": "Der Standard-Branch ist hinter seinem Remote",+ "default_behind_other": "Der Standard-Branch ist hinter seinem Remote",+ "unpushed_one": "{n} Branch hat Commits nur auf diesem Rechner",+ "unpushed_other": "{n} Branches haben Commits nur auf diesem Rechner",+ "behind_one": "{n} Branch ist hinter seinem Remote",+ "behind_other": "{n} Branches sind hinter ihrem Remote",+ "cleanup_one": "{n} gemergter Branch kann entfernt werden",+ "cleanup_other": "{n} gemergte Branches können entfernt werden",+ "action": {+ "show": "Zeigen",+ "view": "Ansehen",+ "update": "Aktualisieren",+ "clean_up": "Aufräumen …"+ }+ },+ "prs": {+ "title": "Offene Pull Requests",+ "none": "Keine offenen Pull Requests.",+ "conflicts": "Konflikte",+ "changes_requested": "Änderungen verlangt",+ "approved": "freigegeben",+ "review_required": "Review nötig",+ "from_fork": "Fork von {author}"+ },+ "cleanup": {+ "title_one": "{n} gemergten Branch entfernen?",+ "title_other": "{n} gemergte Branches entfernen?",+ "body": "Ihre Arbeit ist bereits im Standard-Branch. Nimm den Haken bei allen weg, die du behalten willst. Ein Branch, dessen Commits es nirgendwo sonst gibt, bleibt immer erhalten.",+ "worktrees_one": "{n} davon hat einen Worktree-Ordner; er wird mit entfernt, samt der Dateien, die Git dort ignoriert, außer er enthält nicht committete Änderungen oder einen offenen Workspace.",+ "worktrees_other": "{n} davon haben einen Worktree-Ordner; sie werden mit entfernt, samt der Dateien, die Git dort ignoriert, außer sie enthalten nicht committete Änderungen oder einen offenen Workspace.",+ "ok_one": "{n} Branch entfernen",+ "ok_other": "{n} Branches entfernen",+ "progress": "Entferne {done} von {total} …",+ "done_title_one": "{n} Branch entfernt",+ "done_title_other": "{n} Branches entfernt",+ "done_all": "Alles Ausgewählte wurde entfernt.",+ "kept_one": "{n} blieb erhalten:",+ "kept_other": "{n} blieben erhalten:",+ "close": "Fertig"+ },+ "act": {+ "switch": "Dorthin wechseln",+ "check_out": "Hier auschecken",+ "update": "Aktualisieren",+ "fetch": "Holen",+ "push": "Push",+ "publish": "Veröffentlichen",+ "create_pr": "Pull Request öffnen",+ "delete": "Löschen …"+ },+ "row": {+ "current": "aktuell",+ "to_push": "{n} zu pushen",+ "to_push_tip": "Commits, die es nur auf diesem Rechner gibt.",+ "to_pull": "{n} zu holen",+ "to_pull_tip": "Commits, die das Remote hat und diesem Branch fehlen.",+ "unfetched": "neu auf GitHub",+ "unfetched_tip": "GitHub hat neuere Commits, die noch nicht geholt sind.",+ "gone": "Remote gelöscht",+ "gone_tip": "Sein Branch auf dem Remote wurde gelöscht."}},"skills": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 4170b04648..c5948d4dd2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -7630,7 +7630,7 @@}},"git": {- "aria": "Branches, pull requests and CI",+ "aria": "Git and GitHub status","needs_restart": "Dodaios needs one restart to turn this on. After that you pick this folder's repository once.","connect_repo_title": "Connect a GitHub repository","restart_button": "Restart Dodaios",@@ -7649,28 +7649,20 @@"pick_cancel": "Keep the current repository","change_repo": "Pick a different GitHub repository for this folder","no_workspace": "Select a workspace to see its branches.",- "loading": "Reading branches from git and GitHub…",- "refresh": "Refresh from git and GitHub now",+ "loading": "Reading the repository…",+ "refresh": "Fetch from the remote and refresh","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",+ "worktree_badge": "has its own worktree","tracks": "Tracks {upstream}: {ahead} ahead, {behind} behind",- "ahead_behind": "↑{ahead} ↓{behind}","not_pushed": "Not pushed to GitHub yet","local_only": "local only","local_only_tip": "Only on this computer. Not pushed to GitHub yet.",- "both": "local + GitHub",- "both_tip": "On this computer and on GitHub.",- "github_only": "GitHub only",- "github_only_tip": "Only on GitHub, not on this computer.","last_commit": "Last commit: {date}","details": {"local_absent": "Only on GitHub, not on this computer.",@@ -7687,9 +7679,11 @@"no_commits": "No commits beyond {base}.","more_commits": "Older commits are not listed.","files": "{n} files changed",- "more_files": "More files changed than are listed."+ "more_files": "More files changed than are listed.",+ "upstream_gone": "{upstream} was deleted on the remote.",+ "vs_base": "{ahead} ahead of {base}, {behind} behind"},- "merged_short": "in {target}",+ "merged_short": "merged into {target}","merged_git": "Merged into {target}: every commit of this branch is in {target}.","merged_pr": "Merged into {target} through pull request #{number}.","pr": {@@ -7708,17 +7702,11 @@"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_reading": "Reading pull requests and CI from GitHub…",- "github_off": "No GitHub status: {reason}",- "seconds_ago": "{n} s ago",- "minutes_ago": "{n} min ago",- "open_branch": "Open {branch} on GitHub","more": "More options","search": "Search branches or #PR…","search_clear": "Clear search",@@ -7727,8 +7715,9 @@"all": "All","pr": "Open PR","failing": "CI failed",- "unmerged": "Not merged",- "local": "Local only"+ "unpushed": "To push",+ "behind": "To pull",+ "merged": "Merged"},"filter_empty": "No branch matches.","menu": {@@ -7749,6 +7738,195 @@"copied": "Copied: {text}","copy_failed": "Could not copy to the clipboard.","no_repo": "No GitHub repository picked yet"+ },+ "just_now": "just now",+ "fetched": "fetched {when}",+ "fetching": "Fetching from the remote…",+ "never_fetched": "never fetched",+ "older_backend": "Restart once to turn on the full status and the actions.",+ "show_all": "Show all {n}",+ "show_more": "Show {n} more ({left} left)",+ "ci_failed_of": "{failed} of {total} checks failed",+ "ci_passed_of": "{passed} of {total} checks passed",+ "status": {+ "aria": "This checkout",+ "to_push": "to push",+ "to_pull": "to pull",+ "synced": "In sync with {upstream}.",+ "ahead_one": "This computer is {n} commit ahead of {upstream}.",+ "ahead_other": "This computer is {n} commits ahead of {upstream}.",+ "behind_one": "{upstream} is {n} commit ahead of this computer.",+ "behind_other": "{upstream} is {n} commits ahead of this computer.",+ "diverged": "Both moved on: {ahead} only here, {behind} only on {upstream}.",+ "unpublished": "This branch exists only on this computer.",+ "no_remote": "This repository has no remote yet.",+ "gone": "Its branch on the remote was deleted.",+ "detached": "No branch is checked out (detached HEAD).",+ "unfetched": "GitHub has newer commits that are not fetched yet.",+ "clean": "Nothing to commit",+ "changed_one": "{n} changed file",+ "changed_other": "{n} changed files",+ "n_conflicted": "{n} in conflict",+ "n_staged": "{n} staged",+ "n_modified": "{n} modified",+ "n_untracked": "{n} new",+ "review": "Review"+ },+ "next": {+ "label": "Next step",+ "also": "Also:",+ "resolve": "Resolve the conflicts",+ "resolve_operation": "Finish the {operation}",+ "resolve_reason_one": "{n} file is in conflict. Resolve it, then continue.",+ "resolve_reason_other": "{n} files are in conflict. Resolve them, then continue.",+ "resolve_reason_none": "It was started and not finished.",+ "open_changes": "Open changes",+ "detached": "Check out a branch",+ "detached_reason": "Commits made now belong to no branch.",+ "fetch": "Fetch the new commits",+ "fetch_reason": "GitHub has commits this computer has not seen yet.",+ "fetch_action": "Fetch",+ "pull_one": "Pull {n} commit from {upstream}",+ "pull_other": "Pull {n} commits from {upstream}",+ "pull_reason": "A fast-forward: your files move forward, nothing is rewritten.",+ "pull_action": "Pull",+ "commit_one": "Commit {n} changed file",+ "commit_other": "Commit {n} changed files",+ "commit_reason": "Uncommitted work is not saved in git yet.",+ "commit_action": "Commit…",+ "rebase": "Rebase onto {upstream}",+ "rebase_reason": "{ahead} here and {behind} on the remote: neither side can simply move forward.",+ "rebase_action": "Rebase…",+ "publish": "Publish this branch",+ "publish_reason": "It exists only on this computer — nothing backs it up yet.",+ "publish_action": "Publish",+ "push_one": "Push {n} commit to {upstream}",+ "push_other": "Push {n} commits to {upstream}",+ "push_reason": "They exist only on this computer.",+ "push_action": "Push",+ "open_pr": "Open a pull request",+ "open_pr_reason": "The branch is pushed and has no pull request into {base} yet.",+ "open_pr_action": "Open pull request",+ "fix_ci": "CI is failing on this branch",+ "fix_ci_pr": "CI is failing on #{number}",+ "fix_ci_reason": "Failed: {names}",+ "fix_ci_reason_none": "At least one check failed.",+ "view_checks": "View checks",+ "fix_conflict": "#{number} conflicts with its base",+ "fix_conflict_reason": "GitHub cannot merge it until it is brought up to date with {base}.",+ "view_pr": "Open pull request",+ "changes_requested": "Changes were requested on #{number}",+ "changes_requested_reason": "A reviewer is waiting for an update.",+ "wait_queue": "#{number} is in the merge queue",+ "wait_queue_reason": "It merges on its own once its turn comes and CI passes.",+ "wait_ci": "CI is running",+ "wait_ci_reason": "Nothing to do until the checks finish.",+ "ready": "#{number} passed every check",+ "ready_reason": "It is ready to be reviewed and merged.",+ "done": "Everything is up to date",+ "done_reason": "Nothing to commit, push or pull."+ },+ "commit": {+ "placeholder": "Commit message",+ "scope_one": "Commits the {n} changed file, a new one included.",+ "scope_other": "Commits all {n} changed files, new ones included.",+ "submit": "Commit"+ },+ "confirm": {+ "cancel": "Cancel",+ "rebase_title": "Rebase your commits onto the remote ones?",+ "rebase_body": "Your local commits are replayed on top of the remote branch and get new ids. If they conflict, the rebase is undone and nothing changes.",+ "rebase_ok": "Rebase",+ "delete_title": "Delete {branch}?",+ "delete_body": "The branch is removed from this computer. A branch whose commits exist nowhere else is not deleted without asking again.",+ "delete_body_worktree": "The branch and its worktree folder are removed from this computer:\n{path}\nA worktree with uncommitted changes is kept. Files git ignores there (build output, dependencies) go with the folder.",+ "delete_ok": "Delete branch",+ "delete_remote": "Also delete it on GitHub",+ "delete_force_title": "{branch} holds work that exists nowhere else",+ "delete_force_body": "Deleting it loses those commits for good.",+ "delete_force_ok": "Delete anyway"+ },+ "done": {+ "pushed": "Pushed to {upstream}.",+ "committed": "Committed {commit}.",+ "pr_opened": "Pull request opened.",+ "pulled": "Pulled: {branch} is up to date.",+ "rebased": "Rebased {branch} onto its remote.",+ "switched": "Switched to {branch}.",+ "updated": "{branch} is up to date with its remote.",+ "deleted": "Deleted {branch}."+ },+ "attention": {+ "title": "Needs attention",+ "none": "Nothing needs attention.",+ "ci_failing_one": "CI is failing on {n} pull request",+ "ci_failing_other": "CI is failing on {n} pull requests",+ "default_ci_one": "CI is failing on the default branch",+ "default_ci_other": "CI is failing on the default branch",+ "pr_conflicts_one": "{n} pull request conflicts with its base",+ "pr_conflicts_other": "{n} pull requests conflict with their base",+ "changes_requested_one": "Changes were requested on {n} pull request",+ "changes_requested_other": "Changes were requested on {n} pull requests",+ "default_behind_one": "The default branch is behind its remote",+ "default_behind_other": "The default branch is behind its remote",+ "unpushed_one": "{n} branch has commits only on this computer",+ "unpushed_other": "{n} branches have commits only on this computer",+ "behind_one": "{n} branch is behind its remote",+ "behind_other": "{n} branches are behind their remote",+ "cleanup_one": "{n} merged branch can be removed",+ "cleanup_other": "{n} merged branches can be removed",+ "action": {+ "show": "Show",+ "view": "View",+ "update": "Update",+ "clean_up": "Clean up…"+ }+ },+ "prs": {+ "title": "Open pull requests",+ "none": "No open pull requests.",+ "conflicts": "conflicts",+ "changes_requested": "changes requested",+ "approved": "approved",+ "review_required": "needs review",+ "from_fork": "fork of {author}"+ },+ "cleanup": {+ "title_one": "Remove {n} merged branch?",+ "title_other": "Remove {n} merged branches?",+ "body": "Their work is already in the default branch. Untick any you want to keep. A branch whose commits exist nowhere else is always kept.",+ "worktrees_one": "{n} of them has a worktree folder; it is removed too, with the files git ignores there, unless it holds uncommitted changes or an open workspace.",+ "worktrees_other": "{n} of them have a worktree folder; those are removed too, with the files git ignores there, unless they hold uncommitted changes or an open workspace.",+ "ok_one": "Remove {n} branch",+ "ok_other": "Remove {n} branches",+ "progress": "Removing {done} of {total}…",+ "done_title_one": "Removed {n} branch",+ "done_title_other": "Removed {n} branches",+ "done_all": "Everything selected was removed.",+ "kept_one": "{n} was kept:",+ "kept_other": "{n} were kept:",+ "close": "Done"+ },+ "act": {+ "switch": "Switch to it",+ "check_out": "Check out here",+ "update": "Update",+ "fetch": "Fetch",+ "push": "Push",+ "publish": "Publish",+ "create_pr": "Open pull request",+ "delete": "Delete…"+ },+ "row": {+ "current": "current",+ "to_push": "{n} to push",+ "to_push_tip": "Commits that exist only on this computer.",+ "to_pull": "{n} to pull",+ "to_pull_tip": "Commits the remote has and this branch lacks.",+ "unfetched": "new on GitHub",+ "unfetched_tip": "GitHub has newer commits that are not fetched yet.",+ "gone": "remote deleted",+ "gone_tip": "Its branch on the remote was deleted."}},"skills": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex f373cd482a..8c15427ca7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -7630,7 +7630,7 @@}},"git": {- "aria": "Ramas, pull requests y CI",+ "aria": "Estado de Git y GitHub","needs_restart": "Dodaios necesita reiniciarse una vez para activarlo. Después eliges una sola vez el repositorio de esta carpeta.","connect_repo_title": "Conectar un repositorio de GitHub","restart_button": "Reiniciar Dodaios",@@ -7649,28 +7649,20 @@"pick_cancel": "Mantener el repositorio actual","change_repo": "Elegir otro repositorio de GitHub para esta carpeta","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",+ "loading": "Leyendo el repositorio…",+ "refresh": "Traer del remoto y actualizar","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",+ "worktree_badge": "tiene su propio 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","local_only_tip": "Solo en este ordenador. Aún no se ha subido a GitHub.",- "both": "local + GitHub",- "both_tip": "En este ordenador y en GitHub.",- "github_only": "solo GitHub",- "github_only_tip": "Solo en GitHub, no está en este ordenador.","last_commit": "Último commit: {date}","details": {"local_absent": "Solo en GitHub, no en este ordenador.",@@ -7687,9 +7679,11 @@"no_commits": "Ningún commit más allá de {base}.","more_commits": "Los commits más antiguos no se muestran.","files": "{n} archivos cambiados",- "more_files": "Hay más archivos cambiados de los que se muestran."+ "more_files": "Hay más archivos cambiados de los que se muestran.",+ "upstream_gone": "{upstream} fue eliminada en el remoto.",+ "vs_base": "{ahead} por delante de {base}, {behind} por detrás"},- "merged_short": "en {target}",+ "merged_short": "fusionada 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": {@@ -7708,17 +7702,11 @@"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_reading": "Leyendo pull requests y CI de GitHub…",- "github_off": "Sin estado de GitHub: {reason}",- "seconds_ago": "hace {n} s",- "minutes_ago": "hace {n} min",- "open_branch": "Abrir {branch} en GitHub","more": "Más opciones","search": "Buscar ramas o #PR…","search_clear": "Borrar búsqueda",@@ -7727,8 +7715,9 @@"all": "Todas","pr": "PR abierto","failing": "CI fallido",- "unmerged": "Sin fusionar",- "local": "Solo local"+ "unpushed": "Por subir",+ "behind": "Por traer",+ "merged": "Fusionadas"},"filter_empty": "Ninguna rama coincide.","menu": {@@ -7749,6 +7738,195 @@"copied": "Copiado: {text}","copy_failed": "No se pudo copiar al portapapeles.","no_repo": "Aún no hay repositorio de GitHub elegido"+ },+ "just_now": "ahora mismo",+ "fetched": "traído {when}",+ "fetching": "Trayendo del remoto…",+ "never_fetched": "nunca traído",+ "older_backend": "Reinicia una vez para activar el estado completo y las acciones.",+ "show_all": "Mostrar los {n}",+ "show_more": "Mostrar {n} más (quedan {left})",+ "ci_failed_of": "{failed} de {total} comprobaciones fallaron",+ "ci_passed_of": "{passed} de {total} comprobaciones pasaron",+ "status": {+ "aria": "Este checkout",+ "to_push": "por subir",+ "to_pull": "por traer",+ "synced": "Sincronizado con {upstream}.",+ "ahead_one": "Este equipo va {n} commit por delante de {upstream}.",+ "ahead_other": "Este equipo va {n} commits por delante de {upstream}.",+ "behind_one": "{upstream} va {n} commit por delante de este equipo.",+ "behind_other": "{upstream} va {n} commits por delante de este equipo.",+ "diverged": "Ambos avanzaron: {ahead} solo aquí, {behind} solo en {upstream}.",+ "unpublished": "Esta rama existe solo en este equipo.",+ "no_remote": "Este repositorio aún no tiene remoto.",+ "gone": "Su rama en el remoto fue eliminada.",+ "detached": "No hay ninguna rama activa (HEAD separado).",+ "unfetched": "GitHub tiene commits más nuevos que aún no se han traído.",+ "clean": "Nada que confirmar",+ "changed_one": "{n} archivo modificado",+ "changed_other": "{n} archivos modificados",+ "n_conflicted": "{n} en conflicto",+ "n_staged": "{n} preparados",+ "n_modified": "{n} modificados",+ "n_untracked": "{n} nuevos",+ "review": "Revisar"+ },+ "next": {+ "label": "Siguiente paso",+ "also": "También:",+ "resolve": "Resolver los conflictos",+ "resolve_operation": "Terminar la operación ({operation})",+ "resolve_reason_one": "{n} archivo está en conflicto. Resuélvelo y continúa.",+ "resolve_reason_other": "{n} archivos están en conflicto. Resuélvelos y continúa.",+ "resolve_reason_none": "Se empezó y no se terminó.",+ "open_changes": "Abrir cambios",+ "detached": "Activa una rama",+ "detached_reason": "Los commits de ahora no pertenecen a ninguna rama.",+ "fetch": "Traer los commits nuevos",+ "fetch_reason": "GitHub tiene commits que este equipo aún no ha visto.",+ "fetch_action": "Traer",+ "pull_one": "Traer {n} commit de {upstream}",+ "pull_other": "Traer {n} commits de {upstream}",+ "pull_reason": "Un avance rápido: tus archivos avanzan, nada se reescribe.",+ "pull_action": "Pull",+ "commit_one": "Confirmar {n} archivo modificado",+ "commit_other": "Confirmar {n} archivos modificados",+ "commit_reason": "El trabajo sin confirmar aún no está guardado en git.",+ "commit_action": "Confirmar…",+ "rebase": "Hacer rebase sobre {upstream}",+ "rebase_reason": "{ahead} aquí y {behind} en el remoto: ningún lado puede simplemente avanzar.",+ "rebase_action": "Rebase…",+ "publish": "Publicar esta rama",+ "publish_reason": "Solo existe en este equipo: nada la respalda todavía.",+ "publish_action": "Publicar",+ "push_one": "Subir {n} commit a {upstream}",+ "push_other": "Subir {n} commits a {upstream}",+ "push_reason": "Solo existen en este equipo.",+ "push_action": "Push",+ "open_pr": "Abrir una pull request",+ "open_pr_reason": "La rama está subida y aún no tiene pull request hacia {base}.",+ "open_pr_action": "Abrir pull request",+ "fix_ci": "La CI falla en esta rama",+ "fix_ci_pr": "La CI falla en #{number}",+ "fix_ci_reason": "Fallaron: {names}",+ "fix_ci_reason_none": "Al menos una comprobación falló.",+ "view_checks": "Ver comprobaciones",+ "fix_conflict": "#{number} tiene conflictos con su base",+ "fix_conflict_reason": "GitHub no puede fusionarla hasta que esté al día con {base}.",+ "view_pr": "Abrir pull request",+ "changes_requested": "Se pidieron cambios en #{number}",+ "changes_requested_reason": "Un revisor espera una actualización.",+ "wait_queue": "#{number} está en la cola de fusión",+ "wait_queue_reason": "Se fusiona sola cuando llegue su turno y la CI pase.",+ "wait_ci": "La CI está en marcha",+ "wait_ci_reason": "Nada que hacer hasta que terminen las comprobaciones.",+ "ready": "#{number} pasó todas las comprobaciones",+ "ready_reason": "Está lista para revisarse y fusionarse.",+ "done": "Todo está al día",+ "done_reason": "Nada que confirmar, subir o traer."+ },+ "commit": {+ "placeholder": "Mensaje del commit",+ "scope_one": "Confirma el {n} archivo modificado, también si es nuevo.",+ "scope_other": "Confirma los {n} archivos modificados, también los nuevos.",+ "submit": "Confirmar"+ },+ "confirm": {+ "cancel": "Cancelar",+ "rebase_title": "¿Hacer rebase de tus commits sobre los del remoto?",+ "rebase_body": "Tus commits locales se reaplican sobre la rama remota y reciben identificadores nuevos. Si hay conflictos, el rebase se deshace y nada cambia.",+ "rebase_ok": "Rebase",+ "delete_title": "¿Eliminar {branch}?",+ "delete_body": "La rama se elimina de este equipo. Una rama cuyos commits no existen en ningún otro lugar no se elimina sin volver a preguntar.",+ "delete_body_worktree": "La rama y su carpeta de worktree se eliminan de este equipo:\n{path}\nUn worktree con cambios sin confirmar se conserva. Los archivos que git ignora allí (compilados, dependencias) se van con la carpeta.",+ "delete_ok": "Eliminar rama",+ "delete_remote": "Eliminarla también en GitHub",+ "delete_force_title": "{branch} contiene trabajo que no existe en ningún otro lugar",+ "delete_force_body": "Al eliminarla, esos commits se pierden para siempre.",+ "delete_force_ok": "Eliminar de todos modos"+ },+ "done": {+ "pushed": "Subido a {upstream}.",+ "committed": "Commit {commit} creado.",+ "pr_opened": "Pull request abierta.",+ "pulled": "Traído: {branch} está al día.",+ "rebased": "Rebase de {branch} sobre su remoto hecho.",+ "switched": "Cambiado a {branch}.",+ "updated": "{branch} está al día con su remoto.",+ "deleted": "{branch} eliminada."+ },+ "attention": {+ "title": "Requiere atención",+ "none": "Nada requiere atención.",+ "ci_failing_one": "La CI falla en {n} pull request",+ "ci_failing_other": "La CI falla en {n} pull requests",+ "default_ci_one": "La CI falla en la rama por defecto",+ "default_ci_other": "La CI falla en la rama por defecto",+ "pr_conflicts_one": "{n} pull request tiene conflictos con su base",+ "pr_conflicts_other": "{n} pull requests tienen conflictos con su base",+ "changes_requested_one": "Se pidieron cambios en {n} pull request",+ "changes_requested_other": "Se pidieron cambios en {n} pull requests",+ "default_behind_one": "La rama por defecto va por detrás de su remoto",+ "default_behind_other": "La rama por defecto va por detrás de su remoto",+ "unpushed_one": "{n} rama tiene commits solo en este equipo",+ "unpushed_other": "{n} ramas tienen commits solo en este equipo",+ "behind_one": "{n} rama va por detrás de su remoto",+ "behind_other": "{n} ramas van por detrás de su remoto",+ "cleanup_one": "{n} rama fusionada se puede eliminar",+ "cleanup_other": "{n} ramas fusionadas se pueden eliminar",+ "action": {+ "show": "Mostrar",+ "view": "Ver",+ "update": "Actualizar",+ "clean_up": "Limpiar…"+ }+ },+ "prs": {+ "title": "Pull requests abiertas",+ "none": "No hay pull requests abiertas.",+ "conflicts": "conflictos",+ "changes_requested": "cambios pedidos",+ "approved": "aprobada",+ "review_required": "necesita revisión",+ "from_fork": "fork de {author}"+ },+ "cleanup": {+ "title_one": "¿Eliminar {n} rama fusionada?",+ "title_other": "¿Eliminar {n} ramas fusionadas?",+ "body": "Su trabajo ya está en la rama por defecto. Desmarca las que quieras conservar. Una rama cuyos commits no existen en ningún otro lugar siempre se conserva.",+ "worktrees_one": "{n} de ellas tiene una carpeta de worktree; también se elimina, con los archivos que git ignora allí, salvo que tenga cambios sin confirmar o un workspace abierto.",+ "worktrees_other": "{n} de ellas tienen una carpeta de worktree; también se eliminan, con los archivos que git ignora allí, salvo que tengan cambios sin confirmar o un workspace abierto.",+ "ok_one": "Eliminar {n} rama",+ "ok_other": "Eliminar {n} ramas",+ "progress": "Eliminando {done} de {total}…",+ "done_title_one": "{n} rama eliminada",+ "done_title_other": "{n} ramas eliminadas",+ "done_all": "Se eliminó todo lo seleccionado.",+ "kept_one": "{n} se conservó:",+ "kept_other": "{n} se conservaron:",+ "close": "Listo"+ },+ "act": {+ "switch": "Cambiar a ella",+ "check_out": "Activar aquí",+ "update": "Actualizar",+ "fetch": "Traer",+ "push": "Push",+ "publish": "Publicar",+ "create_pr": "Abrir pull request",+ "delete": "Eliminar…"+ },+ "row": {+ "current": "actual",+ "to_push": "{n} por subir",+ "to_push_tip": "Commits que existen solo en este equipo.",+ "to_pull": "{n} por traer",+ "to_pull_tip": "Commits que el remoto tiene y a esta rama le faltan.",+ "unfetched": "nuevo en GitHub",+ "unfetched_tip": "GitHub tiene commits más nuevos que aún no se han traído.",+ "gone": "remoto eliminado",+ "gone_tip": "Su rama en el remoto fue eliminada."}},"skills": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.jsonindex 0afefc541d..5c8ee4ccca 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json@@ -7630,7 +7630,7 @@}},"git": {- "aria": "Branches, pull requests e CI",+ "aria": "Estado do Git e do GitHub","needs_restart": "O Dodaios precisa de reiniciar uma vez para ativar isto. Depois escolhes o repositório desta pasta uma única vez.","connect_repo_title": "Ligar um repositório GitHub","restart_button": "Reiniciar o Dodaios",@@ -7649,28 +7649,20 @@"pick_cancel": "Manter o repositório atual","change_repo": "Escolher outro repositório GitHub para esta pasta","no_workspace": "Seleciona um workspace para ver os branches.",- "loading": "A ler branches do git e do GitHub…",- "refresh": "Atualizar agora a partir do git e do GitHub",+ "loading": "A ler o repositório…",+ "refresh": "Buscar do remoto e atualizar","branches": "Branches",- "legend": "O que significam os símbolos",- "legend_merged": "Branch integrado num destino","open_repo": "Abrir o repositório no GitHub","remote_only": "Só no GitHub ({n})","truncated": "A mostrar os {n} branches alterados mais recentemente.","current": "Em checkout neste workspace",- "default": "O branch predefinido do repositório","default_badge": "predefinido","in_worktree": "Em checkout noutra worktree: {path}",- "worktree_badge": "outra worktree",+ "worktree_badge": "tem a sua própria worktree","tracks": "Segue {upstream}: {ahead} à frente, {behind} atrás",- "ahead_behind": "↑{ahead} ↓{behind}","not_pushed": "Ainda não enviado para o GitHub","local_only": "só local","local_only_tip": "Só neste computador. Ainda não enviado para o GitHub.",- "both": "local + GitHub",- "both_tip": "Neste computador e no GitHub.",- "github_only": "só GitHub",- "github_only_tip": "Só no GitHub, não neste computador.","last_commit": "Último commit: {date}","details": {"local_absent": "Só no GitHub, não neste computador.",@@ -7687,9 +7679,11 @@"no_commits": "Sem commits além de {base}.","more_commits": "Os commits mais antigos não são listados.","files": "{n} ficheiros alterados",- "more_files": "Foram alterados mais ficheiros do que os listados."+ "more_files": "Foram alterados mais ficheiros do que os listados.",+ "upstream_gone": "{upstream} foi eliminado no remoto.",+ "vs_base": "{ahead} à frente de {base}, {behind} atrás"},- "merged_short": "em {target}",+ "merged_short": "integrado em {target}","merged_git": "Integrado em {target}: todos os commits deste branch estão em {target}.","merged_pr": "Integrado em {target} através do pull request #{number}.","pr": {@@ -7708,17 +7702,11 @@"success": "CI aprovada","failure": "CI falhou"},- "ci_counts": "{passed} de {total} verificações aprovadas · {failed} falharam · {running} em execução · {pending} em espera",- "ci_failed_names": "Falharam: {names}","ci_running_names": "Em execução: {names}","ci_stale": "Estas verificações correram em {commit}; os commits locais mais recentes ainda não foram enviados.","click_ci": "Clica para abrir a execução da CI.","github_updated": "Estado do GitHub de {when}","github_reading": "A ler pull requests e CI do GitHub…",- "github_off": "Sem estado do GitHub: {reason}",- "seconds_ago": "há {n} s",- "minutes_ago": "há {n} min",- "open_branch": "Abrir {branch} no GitHub","more": "Mais opções","search": "Procurar branches ou #PR…","search_clear": "Limpar pesquisa",@@ -7727,8 +7715,9 @@"all": "Todos","pr": "PR aberto","failing": "CI falhou",- "unmerged": "Não integrados",- "local": "Só locais"+ "unpushed": "Por enviar",+ "behind": "Por receber",+ "merged": "Integrados"},"filter_empty": "Nenhum branch corresponde.","menu": {@@ -7749,6 +7738,195 @@"copied": "Copiado: {text}","copy_failed": "Não foi possível copiar para a área de transferência.","no_repo": "Ainda não foi escolhido nenhum repositório GitHub"+ },+ "just_now": "agora mesmo",+ "fetched": "buscado {when}",+ "fetching": "A buscar do remoto…",+ "never_fetched": "nunca buscado",+ "older_backend": "Reinicie uma vez para ativar o estado completo e as ações.",+ "show_all": "Mostrar todos os {n}",+ "show_more": "Mostrar mais {n} (restam {left})",+ "ci_failed_of": "{failed} de {total} verificações falharam",+ "ci_passed_of": "{passed} de {total} verificações passaram",+ "status": {+ "aria": "Este checkout",+ "to_push": "por enviar",+ "to_pull": "por receber",+ "synced": "Sincronizado com {upstream}.",+ "ahead_one": "Este computador está {n} commit à frente de {upstream}.",+ "ahead_other": "Este computador está {n} commits à frente de {upstream}.",+ "behind_one": "{upstream} está {n} commit à frente deste computador.",+ "behind_other": "{upstream} está {n} commits à frente deste computador.",+ "diverged": "Ambos avançaram: {ahead} só aqui, {behind} só em {upstream}.",+ "unpublished": "Este branch existe apenas neste computador.",+ "no_remote": "Este repositório ainda não tem remoto.",+ "gone": "O branch dele no remoto foi eliminado.",+ "detached": "Nenhum branch está ativo (HEAD destacado).",+ "unfetched": "O GitHub tem commits mais recentes que ainda não foram buscados.",+ "clean": "Nada para fazer commit",+ "changed_one": "{n} ficheiro alterado",+ "changed_other": "{n} ficheiros alterados",+ "n_conflicted": "{n} em conflito",+ "n_staged": "{n} preparados",+ "n_modified": "{n} modificados",+ "n_untracked": "{n} novos",+ "review": "Rever"+ },+ "next": {+ "label": "Próximo passo",+ "also": "Também:",+ "resolve": "Resolver os conflitos",+ "resolve_operation": "Concluir a operação ({operation})",+ "resolve_reason_one": "{n} ficheiro está em conflito. Resolva-o e continue.",+ "resolve_reason_other": "{n} ficheiros estão em conflito. Resolva-os e continue.",+ "resolve_reason_none": "Foi iniciada e não foi concluída.",+ "open_changes": "Abrir alterações",+ "detached": "Ative um branch",+ "detached_reason": "Os commits feitos agora não pertencem a nenhum branch.",+ "fetch": "Buscar os commits novos",+ "fetch_reason": "O GitHub tem commits que este computador ainda não viu.",+ "fetch_action": "Buscar",+ "pull_one": "Receber {n} commit de {upstream}",+ "pull_other": "Receber {n} commits de {upstream}",+ "pull_reason": "Um avanço rápido: os seus ficheiros avançam, nada é reescrito.",+ "pull_action": "Pull",+ "commit_one": "Fazer commit de {n} ficheiro alterado",+ "commit_other": "Fazer commit de {n} ficheiros alterados",+ "commit_reason": "O trabalho sem commit ainda não está guardado no git.",+ "commit_action": "Commit…",+ "rebase": "Fazer rebase sobre {upstream}",+ "rebase_reason": "{ahead} aqui e {behind} no remoto: nenhum lado pode simplesmente avançar.",+ "rebase_action": "Rebase…",+ "publish": "Publicar este branch",+ "publish_reason": "Só existe neste computador: nada o protege ainda.",+ "publish_action": "Publicar",+ "push_one": "Enviar {n} commit para {upstream}",+ "push_other": "Enviar {n} commits para {upstream}",+ "push_reason": "Só existem neste computador.",+ "push_action": "Push",+ "open_pr": "Abrir um pull request",+ "open_pr_reason": "O branch foi enviado e ainda não tem pull request para {base}.",+ "open_pr_action": "Abrir pull request",+ "fix_ci": "A CI está a falhar neste branch",+ "fix_ci_pr": "A CI está a falhar em #{number}",+ "fix_ci_reason": "Falharam: {names}",+ "fix_ci_reason_none": "Pelo menos uma verificação falhou.",+ "view_checks": "Ver verificações",+ "fix_conflict": "#{number} tem conflitos com a base",+ "fix_conflict_reason": "O GitHub só o pode integrar quando estiver atualizado com {base}.",+ "view_pr": "Abrir pull request",+ "changes_requested": "Foram pedidas alterações em #{number}",+ "changes_requested_reason": "Um revisor aguarda uma atualização.",+ "wait_queue": "#{number} está na fila de merge",+ "wait_queue_reason": "É integrado sozinho quando chegar a vez dele e a CI passar.",+ "wait_ci": "A CI está a correr",+ "wait_ci_reason": "Nada a fazer até as verificações terminarem.",+ "ready": "#{number} passou em todas as verificações",+ "ready_reason": "Está pronto para ser revisto e integrado.",+ "done": "Está tudo atualizado",+ "done_reason": "Nada para fazer commit, enviar ou receber."+ },+ "commit": {+ "placeholder": "Mensagem do commit",+ "scope_one": "Faz commit do {n} ficheiro alterado, mesmo que seja novo.",+ "scope_other": "Faz commit dos {n} ficheiros alterados, incluindo os novos.",+ "submit": "Commit"+ },+ "confirm": {+ "cancel": "Cancelar",+ "rebase_title": "Fazer rebase dos seus commits sobre os do remoto?",+ "rebase_body": "Os seus commits locais são reaplicados sobre o branch remoto e recebem novos identificadores. Se houver conflitos, o rebase é desfeito e nada muda.",+ "rebase_ok": "Rebase",+ "delete_title": "Eliminar {branch}?",+ "delete_body": "O branch é removido deste computador. Um branch cujos commits não existem em mais lado nenhum não é eliminado sem nova confirmação.",+ "delete_body_worktree": "O branch e a pasta da sua worktree são removidos deste computador:\n{path}\nUma worktree com alterações sem commit é mantida. Os ficheiros que o git ignora ali (compilações, dependências) vão com a pasta.",+ "delete_ok": "Eliminar branch",+ "delete_remote": "Eliminar também no GitHub",+ "delete_force_title": "{branch} contém trabalho que não existe em mais lado nenhum",+ "delete_force_body": "Ao eliminá-lo, esses commits perdem-se de vez.",+ "delete_force_ok": "Eliminar mesmo assim"+ },+ "done": {+ "pushed": "Enviado para {upstream}.",+ "committed": "Commit {commit} criado.",+ "pr_opened": "Pull request aberto.",+ "pulled": "Recebido: {branch} está atualizado.",+ "rebased": "Rebase de {branch} sobre o remoto concluído.",+ "switched": "Mudou para {branch}.",+ "updated": "{branch} está atualizado com o remoto.",+ "deleted": "{branch} eliminado."+ },+ "attention": {+ "title": "Precisa de atenção",+ "none": "Nada precisa de atenção.",+ "ci_failing_one": "A CI está a falhar em {n} pull request",+ "ci_failing_other": "A CI está a falhar em {n} pull requests",+ "default_ci_one": "A CI está a falhar no branch predefinido",+ "default_ci_other": "A CI está a falhar no branch predefinido",+ "pr_conflicts_one": "{n} pull request tem conflitos com a base",+ "pr_conflicts_other": "{n} pull requests têm conflitos com a base",+ "changes_requested_one": "Foram pedidas alterações em {n} pull request",+ "changes_requested_other": "Foram pedidas alterações em {n} pull requests",+ "default_behind_one": "O branch predefinido está atrás do remoto",+ "default_behind_other": "O branch predefinido está atrás do remoto",+ "unpushed_one": "{n} branch tem commits só neste computador",+ "unpushed_other": "{n} branches têm commits só neste computador",+ "behind_one": "{n} branch está atrás do remoto",+ "behind_other": "{n} branches estão atrás do remoto",+ "cleanup_one": "{n} branch integrado pode ser removido",+ "cleanup_other": "{n} branches integrados podem ser removidos",+ "action": {+ "show": "Mostrar",+ "view": "Ver",+ "update": "Atualizar",+ "clean_up": "Limpar…"+ }+ },+ "prs": {+ "title": "Pull requests abertos",+ "none": "Não há pull requests abertos.",+ "conflicts": "conflitos",+ "changes_requested": "alterações pedidas",+ "approved": "aprovado",+ "review_required": "precisa de revisão",+ "from_fork": "fork de {author}"+ },+ "cleanup": {+ "title_one": "Remover {n} branch integrado?",+ "title_other": "Remover {n} branches integrados?",+ "body": "O trabalho deles já está no branch predefinido. Desmarque os que quiser manter. Um branch cujos commits não existem em mais lado nenhum é sempre mantido.",+ "worktrees_one": "{n} deles tem uma pasta de worktree; também é removida, com os ficheiros que o git ignora ali, exceto se tiver alterações sem commit ou um workspace aberto.",+ "worktrees_other": "{n} deles têm uma pasta de worktree; também são removidas, com os ficheiros que o git ignora ali, exceto se tiverem alterações sem commit ou um workspace aberto.",+ "ok_one": "Remover {n} branch",+ "ok_other": "Remover {n} branches",+ "progress": "A remover {done} de {total}…",+ "done_title_one": "{n} branch removido",+ "done_title_other": "{n} branches removidos",+ "done_all": "Tudo o que foi selecionado foi removido.",+ "kept_one": "{n} foi mantido:",+ "kept_other": "{n} foram mantidos:",+ "close": "Concluído"+ },+ "act": {+ "switch": "Mudar para ele",+ "check_out": "Ativar aqui",+ "update": "Atualizar",+ "fetch": "Buscar",+ "push": "Push",+ "publish": "Publicar",+ "create_pr": "Abrir pull request",+ "delete": "Eliminar…"+ },+ "row": {+ "current": "atual",+ "to_push": "{n} por enviar",+ "to_push_tip": "Commits que existem só neste computador.",+ "to_pull": "{n} por receber",+ "to_pull_tip": "Commits que o remoto tem e faltam a este branch.",+ "unfetched": "novo no GitHub",+ "unfetched_tip": "O GitHub tem commits mais recentes que ainda não foram buscados.",+ "gone": "remoto eliminado",+ "gone_tip": "O branch dele no remoto foi eliminado."}},"skills": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex e1ee958dcc..5b7e2a5e07 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -7630,7 +7630,7 @@}},"git": {- "aria": "分支、拉取请求和 CI",+ "aria": "Git 与 GitHub 状态","needs_restart": "需要重启一次 Dodaios 才能开启此功能。之后你只需为这个文件夹选择一次仓库。","connect_repo_title": "连接 GitHub 仓库","restart_button": "重启 Dodaios",@@ -7649,28 +7649,20 @@"pick_cancel": "保留当前仓库","change_repo": "为这个文件夹选择其他 GitHub 仓库","no_workspace": "选择一个工作区以查看其分支。",- "loading": "正在从 git 和 GitHub 读取分支…",- "refresh": "立即从 git 和 GitHub 刷新",+ "loading": "正在读取仓库…",+ "refresh": "从远程获取并刷新","branches": "分支",- "legend": "图标含义",- "legend_merged": "已合并到目标的分支","open_repo": "在 GitHub 上打开仓库","remote_only": "仅在 GitHub 上({n})","truncated": "显示最近修改的 {n} 个分支。","current": "已在此工作区检出",- "default": "仓库的默认分支","default_badge": "默认","in_worktree": "已在另一个工作树中检出:{path}",- "worktree_badge": "其他工作树",+ "worktree_badge": "有独立的工作树","tracks": "跟踪 {upstream}:领先 {ahead},落后 {behind}",- "ahead_behind": "↑{ahead} ↓{behind}","not_pushed": "尚未推送到 GitHub","local_only": "仅本地","local_only_tip": "仅在这台电脑上。尚未推送到 GitHub。",- "both": "本地 + GitHub",- "both_tip": "在这台电脑和 GitHub 上都有。",- "github_only": "仅 GitHub",- "github_only_tip": "仅在 GitHub 上,不在这台电脑上。","last_commit": "最近提交:{date}","details": {"local_absent": "仅在 GitHub 上,不在这台电脑上。",@@ -7687,9 +7679,11 @@"no_commits": "没有超出 {base} 的提交。","more_commits": "更早的提交未列出。","files": "{n} 个文件已更改",- "more_files": "更改的文件比列出的更多。"+ "more_files": "更改的文件比列出的更多。",+ "upstream_gone": "{upstream} 已在远程删除。",+ "vs_base": "比 {base} 领先 {ahead} 个,落后 {behind} 个"},- "merged_short": "已在 {target}",+ "merged_short": "已合并到 {target}","merged_git": "已合并到 {target}:此分支的每个提交都已在 {target} 中。","merged_pr": "已通过拉取请求 #{number} 合并到 {target}。","pr": {@@ -7708,17 +7702,11 @@"success": "CI 已通过","failure": "CI 失败"},- "ci_counts": "{total} 项检查中 {passed} 项通过 · {failed} 项失败 · {running} 项运行中 · {pending} 项等待中",- "ci_failed_names": "失败:{names}","ci_running_names": "运行中:{names}","ci_stale": "这些检查运行于 {commit};较新的本地提交尚未推送。","click_ci": "点击以打开 CI 运行。","github_updated": "GitHub 状态更新于 {when}","github_reading": "正在从 GitHub 读取拉取请求和 CI…",- "github_off": "没有 GitHub 状态:{reason}",- "seconds_ago": "{n} 秒前",- "minutes_ago": "{n} 分钟前",- "open_branch": "在 GitHub 上打开 {branch}","more": "更多选项","search": "搜索分支或 #PR…","search_clear": "清除搜索",@@ -7727,8 +7715,9 @@"all": "全部","pr": "打开的 PR","failing": "CI 失败",- "unmerged": "未合并",- "local": "仅本地"+ "unpushed": "待推送",+ "behind": "待拉取",+ "merged": "已合并"},"filter_empty": "没有匹配的分支。","menu": {@@ -7749,6 +7738,195 @@"copied": "已复制:{text}","copy_failed": "无法复制到剪贴板。","no_repo": "尚未选择 GitHub 仓库"+ },+ "just_now": "刚刚",+ "fetched": "{when}获取",+ "fetching": "正在从远程获取…",+ "never_fetched": "从未获取",+ "older_backend": "重启一次即可启用完整状态和操作。",+ "show_all": "显示全部 {n} 个",+ "show_more": "再显示 {n} 个(剩余 {left} 个)",+ "ci_failed_of": "{total} 项检查中 {failed} 项失败",+ "ci_passed_of": "{total} 项检查中 {passed} 项通过",+ "status": {+ "aria": "当前检出",+ "to_push": "待推送",+ "to_pull": "待拉取",+ "synced": "与 {upstream} 同步。",+ "ahead_one": "本机比 {upstream} 领先 {n} 个提交。",+ "ahead_other": "本机比 {upstream} 领先 {n} 个提交。",+ "behind_one": "{upstream} 比本机领先 {n} 个提交。",+ "behind_other": "{upstream} 比本机领先 {n} 个提交。",+ "diverged": "两边都有新提交:{ahead} 个只在本机,{behind} 个只在 {upstream}。",+ "unpublished": "此分支只存在于本机。",+ "no_remote": "此仓库还没有远程。",+ "gone": "它在远程的分支已被删除。",+ "detached": "未检出任何分支(分离 HEAD)。",+ "unfetched": "GitHub 上有尚未获取的新提交。",+ "clean": "没有需要提交的内容",+ "changed_one": "{n} 个文件有改动",+ "changed_other": "{n} 个文件有改动",+ "n_conflicted": "{n} 个冲突",+ "n_staged": "{n} 个已暂存",+ "n_modified": "{n} 个已修改",+ "n_untracked": "{n} 个新文件",+ "review": "查看"+ },+ "next": {+ "label": "下一步",+ "also": "还可以:",+ "resolve": "解决冲突",+ "resolve_operation": "完成未结束的操作({operation})",+ "resolve_reason_one": "{n} 个文件有冲突。解决后再继续。",+ "resolve_reason_other": "{n} 个文件有冲突。解决后再继续。",+ "resolve_reason_none": "该操作已开始但尚未完成。",+ "open_changes": "打开更改",+ "detached": "检出一个分支",+ "detached_reason": "现在创建的提交不属于任何分支。",+ "fetch": "获取新提交",+ "fetch_reason": "GitHub 上有本机尚未看到的提交。",+ "fetch_action": "获取",+ "pull_one": "从 {upstream} 拉取 {n} 个提交",+ "pull_other": "从 {upstream} 拉取 {n} 个提交",+ "pull_reason": "快进:文件向前推进,不会改写任何内容。",+ "pull_action": "拉取",+ "commit_one": "提交 {n} 个有改动的文件",+ "commit_other": "提交 {n} 个有改动的文件",+ "commit_reason": "未提交的工作尚未保存到 git。",+ "commit_action": "提交…",+ "rebase": "变基到 {upstream}",+ "rebase_reason": "本机有 {ahead} 个、远程有 {behind} 个:两边都无法直接快进。",+ "rebase_action": "变基…",+ "publish": "发布此分支",+ "publish_reason": "它只存在于本机,还没有任何备份。",+ "publish_action": "发布",+ "push_one": "向 {upstream} 推送 {n} 个提交",+ "push_other": "向 {upstream} 推送 {n} 个提交",+ "push_reason": "它们只存在于本机。",+ "push_action": "推送",+ "open_pr": "创建拉取请求",+ "open_pr_reason": "分支已推送,还没有指向 {base} 的拉取请求。",+ "open_pr_action": "创建拉取请求",+ "fix_ci": "此分支的 CI 失败",+ "fix_ci_pr": "#{number} 的 CI 失败",+ "fix_ci_reason": "失败项:{names}",+ "fix_ci_reason_none": "至少有一项检查失败。",+ "view_checks": "查看检查",+ "fix_conflict": "#{number} 与目标分支冲突",+ "fix_conflict_reason": "更新到 {base} 的最新状态后 GitHub 才能合并。",+ "view_pr": "打开拉取请求",+ "changes_requested": "#{number} 被要求修改",+ "changes_requested_reason": "审阅者在等待更新。",+ "wait_queue": "#{number} 在合并队列中",+ "wait_queue_reason": "轮到它且 CI 通过后会自动合并。",+ "wait_ci": "CI 正在运行",+ "wait_ci_reason": "检查完成前无需操作。",+ "ready": "#{number} 已通过全部检查",+ "ready_reason": "可以审阅并合并了。",+ "done": "一切都是最新的",+ "done_reason": "没有需要提交、推送或拉取的内容。"+ },+ "commit": {+ "placeholder": "提交说明",+ "scope_one": "提交这 {n} 个有改动的文件,包括新文件。",+ "scope_other": "提交全部 {n} 个有改动的文件,包括新文件。",+ "submit": "提交"+ },+ "confirm": {+ "cancel": "取消",+ "rebase_title": "把你的提交变基到远程提交之上?",+ "rebase_body": "本地提交会在远程分支之上重新应用,并获得新的 ID。如有冲突,变基会被撤销,不会有任何改变。",+ "rebase_ok": "变基",+ "delete_title": "删除 {branch}?",+ "delete_body": "该分支将从本机移除。如果它的提交在别处不存在,不再次确认就不会删除。",+ "delete_body_worktree": "该分支及其工作树文件夹将从本机移除:\n{path}\n含有未提交更改的工作树会被保留。其中被 git 忽略的文件(构建产物、依赖)会随文件夹一起删除。",+ "delete_ok": "删除分支",+ "delete_remote": "同时在 GitHub 上删除",+ "delete_force_title": "{branch} 含有别处不存在的工作",+ "delete_force_body": "删除后这些提交将永久丢失。",+ "delete_force_ok": "仍然删除"+ },+ "done": {+ "pushed": "已推送到 {upstream}。",+ "committed": "已提交 {commit}。",+ "pr_opened": "拉取请求已创建。",+ "pulled": "已拉取:{branch} 已是最新。",+ "rebased": "已将 {branch} 变基到远程。",+ "switched": "已切换到 {branch}。",+ "updated": "{branch} 已与远程同步。",+ "deleted": "已删除 {branch}。"+ },+ "attention": {+ "title": "需要关注",+ "none": "没有需要关注的事项。",+ "ci_failing_one": "{n} 个拉取请求的 CI 失败",+ "ci_failing_other": "{n} 个拉取请求的 CI 失败",+ "default_ci_one": "默认分支的 CI 失败",+ "default_ci_other": "默认分支的 CI 失败",+ "pr_conflicts_one": "{n} 个拉取请求与目标分支冲突",+ "pr_conflicts_other": "{n} 个拉取请求与目标分支冲突",+ "changes_requested_one": "{n} 个拉取请求被要求修改",+ "changes_requested_other": "{n} 个拉取请求被要求修改",+ "default_behind_one": "默认分支落后于远程",+ "default_behind_other": "默认分支落后于远程",+ "unpushed_one": "{n} 个分支的提交只在本机",+ "unpushed_other": "{n} 个分支的提交只在本机",+ "behind_one": "{n} 个分支落后于远程",+ "behind_other": "{n} 个分支落后于远程",+ "cleanup_one": "{n} 个已合并的分支可以移除",+ "cleanup_other": "{n} 个已合并的分支可以移除",+ "action": {+ "show": "显示",+ "view": "查看",+ "update": "更新",+ "clean_up": "清理…"+ }+ },+ "prs": {+ "title": "未关闭的拉取请求",+ "none": "没有未关闭的拉取请求。",+ "conflicts": "有冲突",+ "changes_requested": "要求修改",+ "approved": "已批准",+ "review_required": "待审阅",+ "from_fork": "来自 {author} 的 fork"+ },+ "cleanup": {+ "title_one": "移除 {n} 个已合并的分支?",+ "title_other": "移除 {n} 个已合并的分支?",+ "body": "它们的工作已在默认分支中。取消勾选想保留的分支。提交在别处不存在的分支始终会被保留。",+ "worktrees_one": "其中 {n} 个有工作树文件夹;它也会连同其中被 git 忽略的文件一起移除,除非含有未提交的更改或有打开的工作区。",+ "worktrees_other": "其中 {n} 个有工作树文件夹;它们也会连同其中被 git 忽略的文件一起移除,除非含有未提交的更改或有打开的工作区。",+ "ok_one": "移除 {n} 个分支",+ "ok_other": "移除 {n} 个分支",+ "progress": "正在移除第 {done} 个,共 {total} 个…",+ "done_title_one": "已移除 {n} 个分支",+ "done_title_other": "已移除 {n} 个分支",+ "done_all": "所选分支已全部移除。",+ "kept_one": "保留了 {n} 个:",+ "kept_other": "保留了 {n} 个:",+ "close": "完成"+ },+ "act": {+ "switch": "切换到它",+ "check_out": "在此检出",+ "update": "更新",+ "fetch": "获取",+ "push": "推送",+ "publish": "发布",+ "create_pr": "创建拉取请求",+ "delete": "删除…"+ },+ "row": {+ "current": "当前",+ "to_push": "{n} 个待推送",+ "to_push_tip": "只存在于本机的提交。",+ "to_pull": "{n} 个待拉取",+ "to_pull_tip": "远程有而此分支没有的提交。",+ "unfetched": "GitHub 上有更新",+ "unfetched_tip": "GitHub 上有尚未获取的新提交。",+ "gone": "远程已删除",+ "gone_tip": "它在远程的分支已被删除。"}},"skills": {diff --git a/jarvis/ui/web/frontend/src/lib/gitApi.ts b/jarvis/ui/web/frontend/src/lib/gitApi.tsindex 66241c7644..6d7649896a 100644--- a/jarvis/ui/web/frontend/src/lib/gitApi.ts+++ b/jarvis/ui/web/frontend/src/lib/gitApi.ts@@ -145,6 +145,49 @@ export function pushBranch(folder: string): Promise<{ upstream: string }> {return post("/push", { folder });}+// The Git tab's actions name the open workspace, never a path: the backend+// takes the folder from the workspace, so they cannot act anywhere else.++/** Push the workspace's current branch, or `branch` without checking it out. */+export function pushWorkspaceBranch(workspaceId: string, branch = ""): Promise<{ upstream: string }> {+ return post("/branch/push", { workspace_id: workspaceId, branch });+}++/** Fast-forward the current branch; `rebase` replays local commits onto the remote ones. */+export function pullBranch(workspaceId: string, rebase = false): Promise<{ message: string }> {+ return post("/pull", { workspace_id: workspaceId, rebase });+}++export function switchBranch(workspaceId: string, branch: string): Promise<{ branch: string; message: string }> {+ return post("/switch", { workspace_id: workspaceId, branch });+}++/** Fast-forward `branch` to its upstream without switching to it. */+export function updateBranch(workspaceId: string, branch: string): Promise<{ message: string }> {+ return post("/branch/update", { workspace_id: workspaceId, branch });+}++/** Delete a local branch; rejects with code `unmerged` until `force` when its commits exist nowhere else. */+export function deleteBranch(+ workspaceId: string,+ branch: string,+ options: { force?: boolean; remote?: boolean; withWorktree?: boolean } = {},+): Promise<{ message: string }> {+ return post("/branch/delete", {+ workspace_id: workspaceId, branch, force: options.force ?? false, remote: options.remote ?? false, with_worktree: options.withWorktree ?? false,+ });+}++/** Open a pull request for the workspace's current branch, or for `branch`. */+export function openBranchPullRequest(+ workspaceId: string,+ options: { title?: string; draft?: boolean; branch?: string } = {},+): Promise<{ url: string }> {+ return post("/branch/pull-request", {+ workspace_id: workspaceId, branch: options.branch ?? "", title: options.title ?? "", draft: options.draft ?? false,+ });+}+export function fetchRemotes(folder: string): Promise<{ ok: boolean }> {return post("/fetch", { folder });}diff --git a/tests/unit/agentic_ide/test_git_control_center.py b/tests/unit/agentic_ide/test_git_control_center.pynew file mode 100644index 0000000000..2e8e0dba49--- /dev/null+++ b/tests/unit/agentic_ide/test_git_control_center.py@@ -0,0 +1,646 @@+"""The Git tab as a control center: the fast local read and the actions it offers."""++from __future__ import annotations++import shutil+import subprocess+from pathlib import Path++import pytest++from jarvis.agentic_ide import git_local, git_ops, git_overview, github_link, github_pulls+from jarvis.agentic_ide.git_ops import GitError+from jarvis.agentic_ide.git_overview import CiStatus, PullRequest++pytestmark = 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, text: str = "") -> str:+ (root / name).write_text(text or name, encoding="utf-8")+ _git(root, "add", name)+ _git(root, "commit", "-q", "-m", f"add {name}")+ return _git(root, "rev-parse", "HEAD")+++def remote(tmp_path: Path) -> Path:+ bare = tmp_path / "remote.git"+ _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare))+ return bare+++def repo(tmp_path: Path, remote: Path) -> Path:+ """A clone on ``main`` with one pushed commit."""+ root = tmp_path / "project"+ root.mkdir()+ _git(root, "init", "-q", "-b", "main")+ _commit(root, "a.txt")+ _git(root, "remote", "add", "origin", str(remote))+ _git(root, "push", "-q", "-u", "origin", "main")+ _git(root, "remote", "set-head", "origin", "main")+ return root+++def other(tmp_path: Path, remote: Path) -> Path:+ """A second clone: someone else pushing to the same remote."""+ clone = tmp_path / "other"+ _git(tmp_path, "clone", "-q", str(remote), str(clone))+ return clone+++# ------------------------------------------------------------------ the local read+++def test_checkout_reports_what_is_uncommitted_and_how_it_stands(repo: Path, other: Path) -> None:+ _commit(other, "theirs.txt")+ _git(other, "push", "-q")+ _git(repo, "fetch", "-q")+ _commit(repo, "mine.txt")+ (repo / "a.txt").write_text("edited", encoding="utf-8")+ (repo / "staged.txt").write_text("s", encoding="utf-8")+ _git(repo, "add", "staged.txt")+ (repo / "new.txt").write_text("n", encoding="utf-8")++ checkout = git_overview.overview(repo, github=False).checkout+ assert (checkout.branch, checkout.upstream) == ("main", "origin/main")+ assert (checkout.ahead, checkout.behind) == (1, 1)+ assert (checkout.staged, checkout.unstaged, checkout.untracked) == (1, 1, 1)+ assert checkout.files == 3 and checkout.conflicted == 0+ assert checkout.has_remote and checkout.last_fetch > 0+ assert checkout.operation == ""+++def test_an_unfinished_merge_is_named(repo: Path) -> None:+ _git(repo, "switch", "-q", "-c", "side")+ _commit(repo, "a.txt", "side")+ _git(repo, "switch", "-q", "main")+ _commit(repo, "a.txt", "main")+ subprocess.run(["git", "merge", "side"], cwd=repo, capture_output=True, check=False)+ checkout = git_overview.overview(repo, github=False).checkout+ assert checkout.operation == "merge" and checkout.conflicted == 1+++def test_branches_say_how_far_they_are_from_the_default_branch(repo: Path) -> None:+ _git(repo, "switch", "-q", "-c", "feature/wip")+ _commit(repo, "b.txt")+ _commit(repo, "c.txt")+ _git(repo, "switch", "-q", "main")+ _commit(repo, "d.txt")+ _git(repo, "push", "-q")+ info = git_overview.overview(repo, github=False)+ assert info.base_ref == "origin/main"+ wip = next(row for row in info.branches if row.name == "feature/wip")+ assert (wip.base_ahead, wip.base_behind) == (2, 1)+ assert wip.merged_into == [] and not wip.upstream_gone+++def test_a_deleted_upstream_is_reported_as_gone(repo: Path) -> None:+ _git(repo, "switch", "-q", "-c", "feature/done")+ _commit(repo, "b.txt")+ _git(repo, "push", "-q", "-u", "origin", "feature/done")+ _git(repo, "switch", "-q", "main")+ _git(repo, "push", "-q", "origin", "--delete", "feature/done")+ rows = git_overview.overview(repo, github=False).branches+ assert next(row for row in rows if row.name == "feature/done").upstream_gone+++def test_the_branch_list_is_reused_until_a_ref_moves(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ reads: list[Path] = []+ real = git_local._read_heads++ def counting(root: Path):+ reads.append(root)+ return real(root)++ monkeypatch.setattr(git_local, "_read_heads", counting)+ git_overview.overview(repo, github=False)+ git_overview.overview(repo, github=False)+ assert len(reads) == 1 # nothing moved: no branch listing ran again+ # An uncommitted edit changes the checkout, never the branch list.+ (repo / "a.txt").write_text("edited", encoding="utf-8")+ assert git_local.read(repo) is not None+ assert len(reads) == 1+ _commit(repo, "b.txt")+ names = [row.name for row in git_overview.overview(repo, github=False).branches]+ assert len(reads) == 2 and names == ["main"]+ _git(repo, "branch", "feature/new")+ names = [row.name for row in git_overview.overview(repo, github=False).branches]+ assert len(reads) == 3 and set(names) == {"main", "feature/new"}+++def test_unfetched_commits_on_github_are_flagged(+ repo: Path, other: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ theirs = _commit(other, "theirs.txt")+ _git(other, "push", "-q")++ def snapshot(repo_name: str, token: str) -> git_overview._GitHubSnapshot:+ snap = git_overview._GitHubSnapshot(ok=True, fetched_at=git_overview.time.time())+ snap.refs["main"] = (theirs[:12], CiStatus())+ return snap++ monkeypatch.setattr(git_overview, "_fetch_github", snapshot)+ monkeypatch.setattr(github_link, "credential", lambda: github_link.Credential("t", "app"))+ monkeypatch.setattr(github_link, "bound_repository", lambda folder: "o/r")+ main = git_overview.overview(repo).branches[0]+ assert main.unfetched and main.behind == 0 # git cannot know yet; GitHub does+ _git(repo, "fetch", "-q")+ main = git_overview.overview(repo).branches[0]+ assert not main.unfetched and main.behind == 1+++def test_open_pull_requests_list_what_is_broken_first() -> None:+ def pr(number: int, **extra: object) -> PullRequest:+ base = {"title": "t", "url": "u", "state": "open", "base": "main", "head": f"b{number}"}+ return PullRequest(number=number, **{**base, **extra}) # type: ignore[arg-type]++ snap = git_overview._GitHubSnapshot(ok=True)+ snap.prs = [+ pr(1, state="draft"),+ pr(2),+ pr(3, ci=CiStatus(state="failure")),+ pr(4, state="queued"),+ pr(5, state="merged"),+ pr(6, conflicting=True),+ pr(7, review="changes_requested"),+ ]+ assert [p.number for p in git_overview._open_pull_requests(snap)] == [3, 6, 7, 4, 2, 1]+++# ------------------------------------------------------------------ pull / update / push+++def test_pull_fast_forwards(repo: Path, other: Path) -> None:+ _commit(other, "theirs.txt")+ _git(other, "push", "-q")+ assert "up to date" in git_ops.pull(repo)+ assert (repo / "theirs.txt").is_file()+++def test_pull_never_rewrites_a_diverged_branch_unasked(repo: Path, other: Path) -> None:+ _commit(other, "theirs.txt")+ _git(other, "push", "-q")+ mine = _commit(repo, "mine.txt")+ with pytest.raises(GitError) as exc:+ git_ops.pull(repo)+ assert exc.value.code == "diverged"+ assert _git(repo, "rev-parse", "HEAD") == mine # untouched+ assert "Rebased" in git_ops.pull(repo, rebase=True)+ assert (repo / "theirs.txt").is_file() and (repo / "mine.txt").is_file()+ assert git_ops.inspect(repo).behind == 0+++def test_a_conflicting_rebase_is_aborted(repo: Path, other: Path) -> None:+ _commit(other, "a.txt", "theirs")+ _git(other, "push", "-q")+ mine = _commit(repo, "a.txt", "mine")+ with pytest.raises(GitError) as exc:+ git_ops.pull(repo, rebase=True)+ assert exc.value.code == "conflict"+ assert _git(repo, "rev-parse", "HEAD") == mine+ assert git_overview.overview(repo, github=False).checkout.operation == ""+++def test_update_branch_moves_a_branch_that_is_not_checked_out(repo: Path, other: Path) -> None:+ _git(repo, "switch", "-q", "-c", "feature/x")+ theirs = _commit(other, "theirs.txt")+ _git(other, "push", "-q")+ git_ops.update_branch(repo, "main")+ assert _git(repo, "rev-parse", "main") == theirs+ assert git_ops.inspect(repo).branch == "feature/x" # never switched+++def test_update_branch_refuses_to_drop_local_commits(repo: Path, other: Path) -> None:+ mine = _commit(repo, "mine.txt")+ _git(repo, "switch", "-q", "-c", "feature/x")+ _commit(other, "theirs.txt")+ _git(other, "push", "-q")+ with pytest.raises(GitError) as exc:+ git_ops.update_branch(repo, "main")+ assert exc.value.code == "diverged"+ assert _git(repo, "rev-parse", "main") == mine+++def test_push_publishes_a_branch_without_switching_to_it(repo: Path, remote: Path) -> None:+ _git(repo, "switch", "-q", "-c", "feature/x")+ tip = _commit(repo, "b.txt")+ _git(repo, "switch", "-q", "main")+ assert git_ops.push(repo, "feature/x") == "origin/feature/x"+ assert _git(remote, "rev-parse", "feature/x") == tip+ assert git_ops.inspect(repo).branch == "main"+++def _open(monkeypatch: pytest.MonkeyPatch, folder: Path) -> None:+ """Make ``folder`` the open workspace ``w1`` — the Git tab's actions act on nothing else."""+ from types import SimpleNamespace++ from jarvis.ui.web import agentic_ide_git_routes as routes++ session = SimpleNamespace(folder=str(folder), terminals=[])+ registry = SimpleNamespace(+ sessions=[session], get=lambda workspace_id: session if workspace_id == "w1" else None+ )+ monkeypatch.setattr(routes, "get_registry", lambda: registry)+++# ------------------------------------------------------------------ delete+++def test_deleting_a_branch_asks_again_when_its_commits_exist_nowhere_else(repo: Path) -> None:+ _git(repo, "switch", "-q", "-c", "feature/x")+ _commit(repo, "b.txt")+ _commit(repo, "c.txt")+ _git(repo, "switch", "-q", "main")+ with pytest.raises(GitError) as exc:+ git_ops.delete_branch(repo, "feature/x")+ assert exc.value.code == "unmerged" and "2 commits" in str(exc.value)+ assert git_ops.branch_tip(repo, "feature/x")+ assert "Deleted feature/x" in git_ops.delete_branch(repo, "feature/x", force=True)+ assert git_ops.branch_tip(repo, "feature/x") == ""+++def test_a_pushed_or_merged_branch_is_deleted_without_a_second_question(+ repo: Path, remote: Path+) -> None:+ _git(repo, "switch", "-q", "-c", "feature/pushed")+ _commit(repo, "b.txt")+ _git(repo, "push", "-q", "-u", "origin", "feature/pushed")+ _git(repo, "switch", "-q", "main")+ # Its work is in main, so both copies of the branch may go.+ _git(repo, "merge", "-q", "--no-ff", "-m", "merge pushed", "feature/pushed")+ summary = git_ops.delete_branch(repo, "feature/pushed", remote=True)+ assert summary == "Deleted feature/pushed here and on origin."+ assert "feature/pushed" not in _git(remote, "branch", "--list")+ # A squash merge leaves commits git cannot find elsewhere; the caller's proof decides.+ _git(repo, "switch", "-q", "-c", "feature/squashed")+ _commit(repo, "c.txt")+ _git(repo, "switch", "-q", "main")+ assert "Deleted" in git_ops.delete_branch(repo, "feature/squashed", merged=True)+++def test_the_current_and_the_default_branch_cannot_be_deleted(repo: Path) -> None:+ _git(repo, "switch", "-q", "-c", "feature/x")+ for name, code in (("feature/x", "current"), ("main", "invalid")):+ with pytest.raises(GitError) as exc:+ git_ops.delete_branch(repo, name, force=True)+ assert exc.value.code == code+++def test_a_branch_in_a_worktree_goes_only_with_a_clean_unused_worktree(repo: Path) -> None:+ made = git_ops.prepare(repo, "new_worktree", branch="agent/one")+ tree = Path(made.folder)+ with pytest.raises(GitError) as exc:+ git_ops.delete_branch(repo, "agent/one")+ assert exc.value.code == "checked_out"+ with pytest.raises(GitError) as exc:+ git_ops.delete_branch(repo, "agent/one", with_worktree=True, open_folders=[str(tree)])+ assert exc.value.code == "in_use"+ (tree / "wip.txt").write_text("unsaved", encoding="utf-8")+ with pytest.raises(GitError) as exc:+ git_ops.delete_branch(repo, "agent/one", with_worktree=True)+ assert exc.value.code == "dirty"+ assert tree.is_dir() and git_ops.branch_tip(repo, "agent/one") # nothing was removed+ (tree / "wip.txt").unlink()+ git_ops.delete_branch(repo, "agent/one", with_worktree=True)+ assert not tree.exists() and git_ops.branch_tip(repo, "agent/one") == ""+++def test_the_delete_route_takes_a_merged_pull_request_as_proof(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from fastapi import HTTPException++ from jarvis.ui.web import agentic_ide_git_routes as routes++ _git(repo, "switch", "-q", "-c", "feature/squashed")+ tip = _commit(repo, "b.txt")+ _git(repo, "switch", "-q", "main")+ _open(monkeypatch, repo)+ request = routes.DeleteBranchRequest(workspace_id="w1", branch="feature/squashed")+ with pytest.raises(HTTPException) as exc:+ routes.delete_branch(request)+ assert exc.value.detail["code"] == "unmerged"++ snap = git_overview._GitHubSnapshot(ok=True, fetched_at=git_overview.time.time())+ snap.prs = [+ PullRequest(+ number=8, title="t", url="u", state="merged", base="main",+ head="feature/squashed", head_oid=tip[:12],+ )+ ] # fmt: skip+ git_overview._CACHE._entries["o/r"] = snap+ monkeypatch.setattr(github_link, "bound_repository", lambda folder: "o/r")+ assert routes.delete_branch(request)["ok"]+ assert git_ops.branch_tip(repo, "feature/squashed") == ""+++# ------------------------------------------------------------------ pull requests+++def test_a_pull_request_is_opened_through_the_github_connection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls: list[dict] = []++ def fake_graphql(token: str, query: str, variables: dict | None = None) -> dict:+ calls.append(variables or {})+ if "createPullRequest" not in query:+ return {"data": {"repository": {"id": "R_1"}}}+ return {+ "data": {"createPullRequest": {"pullRequest": {"number": 12, "url": "https://x/12"}}}+ }++ monkeypatch.setattr(github_link, "graphql", fake_graphql)+ created = github_pulls.create("o/r", "t", head="feature/x", base="main", title="Add x")+ assert (created.number, created.url) == (12, "https://x/12")+ assert calls[1]["input"] == {+ "repositoryId": "R_1",+ "baseRefName": "main",+ "headRefName": "feature/x",+ "title": "Add x",+ "draft": False,+ }+++def test_github_refusing_a_pull_request_is_said_in_its_own_words(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def fake_graphql(token: str, query: str, variables: dict | None = None) -> dict:+ if "createPullRequest" not in query:+ return {"data": {"repository": {"id": "R_1"}}}+ return {+ "data": {"createPullRequest": None},+ "errors": [{"message": "A pull request already exists for o:feature/x."}],+ }++ monkeypatch.setattr(github_link, "graphql", fake_graphql)+ with pytest.raises(github_link.GitHubError) as exc:+ github_pulls.create("o/r", "t", head="feature/x", base="main", title="Add x")+ assert "already exists" in str(exc.value) and exc.value.code == "refused"+++def test_the_pull_request_route_pushes_and_titles_from_the_first_commit(+ repo: Path, remote: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from jarvis.ui.web import agentic_ide_git_routes as routes++ _git(repo, "switch", "-q", "-c", "feature/x")+ _commit(repo, "b.txt")+ tip = _commit(repo, "c.txt")+ seen: dict = {}++ def fake_create(repo_name: str, token: str, **kwargs: object):+ seen.update(kwargs, repo=repo_name)+ return github_pulls.CreatedPullRequest(number=3, url="https://x/3")++ monkeypatch.setattr(github_pulls, "create", fake_create)+ monkeypatch.setattr(github_link, "credential", lambda: github_link.Credential("t", "app"))+ monkeypatch.setattr(github_link, "bound_repository", lambda folder: "o/r")+ _open(monkeypatch, repo)+ answer = routes.open_branch_pull_request(routes.BranchPullRequestRequest(workspace_id="w1"))+ assert answer == {"ok": True, "url": "https://x/3"}+ assert seen == {+ "repo": "o/r", "head": "feature/x", "base": "main", "title": "add b.txt", "draft": False,+ } # fmt: skip+ assert _git(remote, "rev-parse", "feature/x") == tip # pushed first+++# ------------------------------------------------------------------ reading GitHub+++def _repo_payload(**parts: object) -> dict:+ return {"data": {"repository": {"url": "https://github.com/o/r", **parts}}}+++def _pr_node(number: int, head: str, state: str = "OPEN") -> dict:+ return {+ "number": number,+ "title": f"PR {number}",+ "url": f"https://github.com/o/r/pull/{number}",+ "state": state,+ "headRefName": head,+ "baseRefName": "main",+ "mergeable": "CONFLICTING" if number == 2 else "MERGEABLE",+ "reviewDecision": "CHANGES_REQUESTED" if number == 2 else None,+ "author": {"login": "dana"},+ }+++def test_github_is_asked_in_parts_and_a_missing_part_only_costs_its_own_data(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ asked: list[str] = []++ def fake_graphql(token: str, query: str, variables: dict | None = None) -> dict:+ if "pageInfo" in query:+ return _repo_payload(refs={"pageInfo": {"hasNextPage": False}, "nodes": []})+ if "states: OPEN" in query:+ asked.append("open")+ return _repo_payload(pullRequests={"nodes": [_pr_node(1, "a"), _pr_node(2, "b")]})+ if "MERGED" in query:+ asked.append("recent")+ raise github_link.GitHubError("GitHub could not be reached.", code="unreachable")+ asked.append("refs")+ return _repo_payload(refs={"nodes": [{"name": "main", "target": {"oid": "0" * 40}}]})++ monkeypatch.setattr(github_link, "graphql", fake_graphql)+ snap = git_overview._fetch_github("o/r", "t")+ assert sorted(asked) == ["open", "recent", "refs"]+ # Recently merged pull requests are missing this round; everything else landed.+ assert snap.ok and [pr.number for pr in snap.prs] == [1, 2]+ assert (snap.prs[1].conflicting, snap.prs[1].review, snap.prs[1].author) == (+ True,+ "changes_requested",+ "dana",+ )+ assert "main" in snap.refs+++def test_a_refresh_never_makes_the_tab_wait_for_github(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import threading++ release = threading.Event()+ reads: list[float] = []++ def slow_fetch(repo_name: str, token: str) -> git_overview._GitHubSnapshot:+ reads.append(git_overview.time.time())+ if len(reads) > 1:+ release.wait(5)+ snap = git_overview._GitHubSnapshot(ok=True, fetched_at=git_overview.time.time())+ snap.refs["main"] = ("0" * 12, CiStatus(state="success" if len(reads) > 1 else "none"))+ return snap++ monkeypatch.setattr(git_overview, "_fetch_github", slow_fetch)+ monkeypatch.setattr(github_link, "credential", lambda: github_link.Credential("t", "app"))+ monkeypatch.setattr(github_link, "bound_repository", lambda folder: "o/r")+ first = git_overview.overview(repo)+ assert first.github.available and not first.github.refreshing++ # A push makes the answer outdated: it stays on screen while the new one loads.+ git_overview.clear_github(repo)+ started = git_overview.time.time()+ stale = git_overview.overview(repo, refresh=True, wait_for_github=False)+ assert git_overview.time.time() - started < 2+ assert stale.github.available and stale.github.refreshing+ assert stale.branches[0].ci.state == "none"+ release.set()+ deadline = git_overview.time.time() + 5+ while git_overview.time.time() < deadline:+ later = git_overview.overview(repo, wait_for_github=False)+ if not later.github.refreshing:+ break+ git_overview.time.sleep(0.05)+ assert later.branches[0].ci.state == "success" and len(reads) == 2+++# ------------------------------------------------------------------ hardening+++def test_deleting_the_remote_branch_too_never_counts_it_as_a_safe_copy(+ repo: Path, remote: Path+) -> None:+ _git(repo, "switch", "-q", "-c", "feature/open")+ tip = _commit(repo, "b.txt")+ _git(repo, "push", "-q", "-u", "origin", "feature/open")+ _git(repo, "switch", "-q", "main")+ # Pushed but not merged: the remote copy is the only other place the work lives.+ with pytest.raises(GitError) as exc:+ git_ops.delete_branch(repo, "feature/open", remote=True)+ assert exc.value.code == "unmerged"+ assert git_ops.branch_tip(repo, "feature/open") == tip+ assert _git(remote, "rev-parse", "feature/open") == tip+ # Without the remote delete the pushed copy keeps the work, so the local branch may go.+ assert "Deleted feature/open." == git_ops.delete_branch(repo, "feature/open")+ assert _git(remote, "rev-parse", "feature/open") == tip+++def test_a_worktree_an_agent_pane_runs_in_counts_as_open(monkeypatch: pytest.MonkeyPatch) -> None:+ from types import SimpleNamespace++ from jarvis.ui.web import agentic_ide_git_routes as routes++ pane = SimpleNamespace(cwd=lambda workspace: "/code/app/.worktrees/agent-x")+ plain = SimpleNamespace(cwd=lambda workspace: workspace)+ session = SimpleNamespace(folder="/code/app", terminals=[pane, plain])+ monkeypatch.setattr(routes, "get_registry", lambda: SimpleNamespace(sessions=[session]))+ assert routes._open_folders() == ["/code/app", "/code/app/.worktrees/agent-x", "/code/app"]+++def test_a_local_merge_survives_a_rebase(repo: Path, other: Path) -> None:+ _commit(other, "theirs.txt")+ _git(other, "push", "-q")+ _git(repo, "switch", "-q", "-c", "side")+ _commit(repo, "side.txt")+ _git(repo, "switch", "-q", "main")+ _git(repo, "merge", "-q", "--no-ff", "-m", "merge side", "side")+ git_ops.pull(repo, rebase=True)+ assert _git(repo, "log", "-1", "--format=%s") == "merge side"+ assert len(_git(repo, "log", "-1", "--format=%P").split()) == 2 # still a merge+++def test_a_failed_github_read_keeps_the_last_good_answer(monkeypatch: pytest.MonkeyPatch) -> None:+ answers = [+ git_overview._GitHubSnapshot(ok=True, fetched_at=git_overview.time.time() - 500),+ git_overview._GitHubSnapshot(ok=False, code="unreachable", fetched_at=0.0),+ ]+ reads: list[str] = []++ def fetch(repo_name: str, token: str) -> git_overview._GitHubSnapshot:+ reads.append(repo_name)+ return answers[min(len(reads), len(answers)) - 1]++ monkeypatch.setattr(git_overview, "_fetch_github", fetch)+ cache = git_overview._GitHubCache()+ good = cache.get("o/r", "t")+ assert good is answers[0]+ # Stale by now: a forced read fails, and the good answer stays.+ assert cache.get("o/r", "t", force=True) is good+ assert len(reads) == 2+ # ... and the failure is not retried on every poll.+ assert cache.get("o/r", "t", wait=False) is good+ assert not cache.loading("o/r") and len(reads) == 2+++def test_a_git_call_that_fails_is_not_remembered_as_no_branches(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ assert [row.name for row in git_local.read(repo).branches] == ["main"]+ real = git_local.git_out+ broken = {"on": True}++ def flaky(args: list[str], cwd: Path) -> str | None:+ if broken["on"] and args[0] in {"for-each-ref", "status"}:+ return None+ return real(args, cwd)++ monkeypatch.setattr(git_local, "git_out", flaky)+ _git(repo, "branch", "feature/new") # moves a ref: the branch list has to be re-read+ state = git_local.read(repo, fresh=True)+ # Git did not answer: the last known state is shown, not an empty repository.+ assert state is not None and [row.name for row in state.branches] == ["main"]+ assert state.checkout.branch == "main"+ broken["on"] = False+ names = {row.name for row in git_local.read(repo).branches}+ assert names == {"main", "feature/new"}+++def test_the_tab_actions_only_act_on_an_open_workspace(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from fastapi import HTTPException++ from jarvis.ui.web import agentic_ide_git_routes as routes++ _open(monkeypatch, repo)+ for call in (+ lambda: routes.pull_branch(routes.PullBranchRequest(workspace_id="other")),+ lambda: routes.switch_branch(routes.BranchRequest(workspace_id="other", branch="main")),+ lambda: routes.delete_branch(routes.DeleteBranchRequest(workspace_id="other", branch="x")),+ lambda: routes.push_workspace_branch(routes.PushBranchRequest(workspace_id="other")),+ ):+ with pytest.raises(HTTPException) as exc:+ call()+ assert exc.value.status_code == 404+ _git(repo, "branch", "feature/x")+ assert routes.switch_branch(routes.BranchRequest(workspace_id="w1", branch="feature/x"))["ok"]+ assert git_ops.inspect(repo).branch == "feature/x"+++def test_an_open_workspace_is_a_folder_threads_may_read(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from types import SimpleNamespace++ from jarvis.agentic_ide import library, thread_folders+ from jarvis.agentic_ide import session as ide_session++ opened = tmp_path / "opened"+ opened.mkdir()+ registry = SimpleNamespace(sessions=[SimpleNamespace(folder=str(opened))])+ monkeypatch.setattr(ide_session, "get_registry", lambda: registry)+ monkeypatch.setattr(library, "list_projects", lambda include_archived=False: [])+ assert thread_folders.allowed_thread_folder(opened) == opened.resolve()+ assert thread_folders.allowed_thread_folder(tmp_path) is Nonediff --git a/tests/unit/agentic_ide/test_git_overview.py b/tests/unit/agentic_ide/test_git_overview.pyindex a0791c6645..0db2ec7c35 100644--- a/tests/unit/agentic_ide/test_git_overview.py+++ b/tests/unit/agentic_ide/test_git_overview.py@@ -182,8 +182,11 @@ def test_pull_request_states_cover_the_five_github_states() -> None:(3, "queued"),(4, "merged"),(5, "closed"),+ (6, "open"),]assert snap.prs[2].queue_position == 2+ # A fork's pull request is listed, but never attached to a branch of this repository.+ assert [pr.fork for pr in snap.prs] == [False, False, False, False, False, True]assert snap.busy # a queued PR is worth re-reading sooner